E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable) [duplicate]

sudo rm /var/cache/debconf/*.dat


A solution to this locking problem is detailed in the wiki:
fuser -v /var/cache/debconf/config.dat
Will show you what process is holding the lock then you simply need to note down the PID and kill it like so:
sudo kill PID
sudo kill -9 PID  # if the first doesn't work

postfix queue file write error message size limit

If you get an error like:
Aug 21 12:41:03 webb4 postfix/sendmail[11234]: fatal: web1_user(12967): queue file write error

in your mail log, then the vale for message_size_limit in postfix main.cf is too low. Edit postfix main.cf:

vi /etc/postfix/main.cf
and set the message size limit to a higher value. E.g.
message_size_limit = 900000000
and restart postfix:

/etc/init.d/postfix restart

If there is no message_size_limit set in main.cf, just add the line.

The configuration option is "message_size_limit" and by default is set to 10240000 bytes which is roughly 10MB. You can see what setting your postfix install is currently using by issuing the following command:

postconf | grep message_size_limit

Just doing "postconf" on its own will show all the options so using grep on "message_size_limit" filters the output to just the setting we want. For the default setting, you'll see this:
message_size_limit = 10240000
To change the setting to some other value, open the main.cf file in your favourite text editor (it's often at a location like /etc/postfix/main.cf) and either edit or add the following line, depending if it's already in the file or not.
message_size_limit = 20480000
In the above example I've changed it to ~20MB.
Then reload postfix like so:
service postfix reload

Recommended:
postconf | grep message_size_limit
postconf -e message_size_limit=20480000             
service postfix reload

Something to note: many emails use base64 (there is 8bitmime but support is far from universal). So the space taken up by the attatchment in the email will be about a third bigger than the total size of the attatchments. Then you have to consider the rest of the mail.
So if you want to receive 20MB files you need to set the message size limit to around 27MB.


lsof command

Who are browsing my home/office web server?
lsof -r 2 -n -P -c nginx -a -i TCP@IPAddress:80

Feel free to replace port 80 with other ports such as 21 (FTP), 22(SSH), 443 (HTTPS) and so on to get the same info. The -c options set the user name (see man page http://www.manpager.com/linux/man8/lsof.8.html for more info on all options) :
lsof -r 2 -n -P -c vsftpd -a -i TCP@IPAddress:21
lsof -r 2 -n -P -c sshd -a -i TCP@IPAddress:22


netstat -punt | grep ":80"

http://www.manpager.com/linux/man8/lsof.8.html

8 Linux TR Command Examples

tr is an UNIX utility for translating, or deleting, or squeezing repeated characters. It will read from STDIN and write to STDOUT.
tr stands for translate.

Syntax

The syntax of tr command is:
$ tr [OPTION] SET1 [SET2]

Translation

If both the SET1 and SET2 are specified and ‘-d’ OPTION is not specified, then tr command will replace each characters in SET1 with each character in same position in SET2.

1. Convert lower case to upper case

The following tr command is used to convert the lower case to upper case
$ tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
thegeekstuff
THEGEEKSTUFF
The following command will also convert lower case to upper case
$ tr [:lower:] [:upper:]
thegeekstuff
THEGEEKSTUFF
You can also use ranges in tr. The following command uses ranges to convert lower to upper case.
$ tr a-z A-Z
thegeekstuff
THEGEEKSTUFF

2. Translate braces into parenthesis

You can also translate from and to a file. In this example we will translate braces in a file with parenthesis.
$ tr '{}' '()' < inputfile > outputfile
The above command will read each character from “inputfile”, translate if it is a brace, and write the output in “outputfile”.

3. Translate white-space to tabs

The following command will translate all the white-space to tabs
$ echo "This is for testing" | tr [:space:] '\t'
This is for testing

4. Squeeze repetition of characters using -s

In Example 3, we see how to translate space with tabs. But if there are two are more spaces present continuously, then the previous command will translate each spaces to a tab as follows.
$ echo "This   is   for testing" | tr [:space:] '\t'
This   is   for testing
We can use -s option to squeeze the repetition of characters.
$ echo "This   is   for testing" | tr -s [:space:] '\t'
This is for testing
Similarly you can convert multiple continuous spaces with a single space
$ echo "This  is  for testing" | tr -s [:space:] ' '
This is for testing

5. Delete specified characters using -d option

tr can also be used to remove particular characters using -d option.
$ echo "the geek stuff" | tr -d 't'
he geek suff
To remove all the digits from the string, use
$ echo "my username is 432234" | tr -d [:digit:]
my username is
Also, if you like to delete lines from file, you can use sed d command.

6. Complement the sets using -c option

You can complement the SET1 using -c option. For example, to remove all characters except digits, you can use the following.
$ echo "my username is 432234" | tr -cd [:digit:]
432234

7. Remove all non-printable character from a file

The following command can be used to remove all non-printable characters from a file.
$ tr -cd [:print:] < file.txt

8. Join all the lines in a file into a single line

The below command will translate all newlines into spaces and make the result as a single line.
$ tr -s '\n' ' ' < file.txt

send mail with python script to notify disk usage part 1

Reference:
http://rajivpandit.wordpress.com/2013/09/19/how-to-send-email-by-python/
https://docs.python.org/2/library/email-examples.html
                                                                                                           

[root@server1 ~]# pwd
/root
[root@server1 ~]# cat disk.txt
Filesystem      Size  Used Avail Use% Mounted on
/dev/simfs      400G  1.4G  399G   1% /
none            4.0G  4.0K  4.0G   1% /dev
none            4.0G   48K  4.0G   1% /dev/shm



[root@server1 ~]# vim mailer.py

#!/usr/bin/python
import os
import smtplib
import email.Utils
# Import the email modules we'll need
from email.mime.text import MIMEText
fp = open('disk.txt', 'rb')
msg = MIMEText(fp.read())
to = "norbuurgen@gmail.com"
FROM = "urgen@localhost.com"
server = smtplib.SMTP('localhost')
server.sendmail(FROM, [to], msg.as_string())
server.quit()


= = = = = = = = = = = ===   = = === =      === = = =   =
Following are the two ways to send email notifications by python

“””
This Script Will Send Email Using Internal Email System
In this no need any authentication or password required to send Email
Python Version 2.6
“””
from email.mime.text import MIMEText
import email.Utils
import smtplib

emailList = ["recepient1@gmail.com", "recepient2@gmail.com"] # this is List of Email Ids

for emailID in emailList:
try:
print “Sending email to … “, emailID

FROM = “email@gmail.com”
TO = emailID
message = “This Email is send by Python\n Python is Great !!!”
msg = MIMEText(message)
msg["Subject"] = “Email Notification by Python”
msg["Message-id"] = email.Utils.make_msgid()
msg["From"] = FROM
msg["To"] = TO
host = “smtp.gmail.com”
server = smtplib.SMTP(host)
server.sendmail(FROM, TO, msg.as_string())
server.quit()
print “Email Send”

except Exception, e:
print e





“””
This Script Will Send Email Using Gmail
This Required Username and password
Python Version 2.6
“””
from email.mime.text import MIMEText
from datetime import date
import smtplib

SMTP_SERVER = “smtp.gmail.com”
SMTP_PORT = 587
SMTP_USERNAME = “email@gmail.com”
SMTP_PASSWORD = “password”

EMAIL_TO = ["recepient1@gmail.com", "recepient2@gmail.com"]
EMAIL_FROM = “email@gmail.com”
EMAIL_SUBJECT = “Demo Email : “

DATE_FORMAT = “%d/%m/%Y”
EMAIL_SPACE = “, “

DATA=’This is the content of the email.’

def send_email():
msg = MIMEText(DATA)
msg['Subject'] = EMAIL_SUBJECT + ” %s” % (date.today().strftime(DATE_FORMAT))
msg['To'] = EMAIL_SPACE.join(EMAIL_TO)
msg['From'] = EMAIL_FROM
mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mail.starttls()
mail.login(SMTP_USERNAME, SMTP_PASSWORD)
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
mail.quit()
print “Email Send”

if __name__==’__main__':
send_email()


# # # # # # Send mysql status report  # # # # # # #
[root@server1 ~]# vim check.py

import smtplib
from email.mime.text import MIMEText
sql_found = False
io_found = False
with open("status.txt") as logfile:
  for line in logfile:
    if not io_found and "kSlave_IO_Running: Yes" in line:
        print "match1",line
        io_found = True
    if not sql_found and "Slave_SQL_Running: Yes" in line:
        print "match2",line
        sql_found = True

if not sql_found or not io_found:
    msg=MIMEText("Warning!! Mysql Replicatoin Stopped")
    fromaddr="root@DBausit.com"
    toaddr="norbuurgen@gmail.com"
    server = smtplib.SMTP('localhost')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, [toaddr], msg.as_string())
    server.quit()
else:
    print "mysql running OK"

Ansible part 1

##############Ansible ###############
play book is composed of 1 or more plays in a list
The goal of a play is to map a group of hosts to some well defined roles, represented by things ansible calls tasks. At a basic level, a task is nothing more than a call to an ansible module, which you should have learned about in earlier chapters.


---
- hosts: webservers
  remote_user: root
  tasks:
  - name: create the new user
    yum: pkg=httpd state=latest
  - name: write the apache config file
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf
    notify:
    - restart apache
  - name: ensure apache is running
    service: name=httpd state=started
  handlers:
    - name: restart apache
      service: name=httpd state=restarted

ansible 192.168.140.20 -a "/usr/bin/yum install libselinux-python"

pip install passlib

python -c "from passlib.hash import sha512_crypt; print sha512_crypt.encrypt('nepal12')"
$6$rounds=100000$KYpBC3u43XAxBJNg$7Gh04HYw3wySag8uYqeRghh0L.MtLhVTzNMEe5vr71CFWLSarvHGwrV4I.vStCXzwdPYScZFOHrfrxvl9wzMK1

copy and paste the result like below
ansible all -m user -a 'name=foo password=$6$rounds=100000$40KA9Y5UUFMh/6xC$/rUKR9Qqu7S56nQm9bV91izUA8ExDIb5rxg73QYeyHO.uGiN/9tgfgfdycsj74F36Lz6E1ZvcZf.Bz4wzwxQk0'


Play book for creating user , group with id 777 , add new user to group , copy file from local ansible server to remote client , add new user to sudoers file , install nrpe in client

---
- name: Hello World!
  gather_facts: False
  hosts: all
  vars:
      password: '$6$rounds=100000$3b69WiNTWemboVhu$IGTjv.FvMEDVzXRHEey9ddmuxKhAFL8BBL8unvCos9fcTPQkxkIEEHs1QWraTejPai5ytcq7Hs3Y3ZJ3qmRHv.'
  user: root
  tasks:
   - action: group name=demogroup1 gid=777 state=present
   - action: user name=nplinkuser1 password={{password}}
   - action: user name=nplinkuser1 groups=demogroup1 append=yes
   - copy: src=/asia dest=/
   - lineinfile: "dest=/etc/sudoers state=present regexp='^nplinkuser1' line='nplinkuser1 ALL=(ALL)  ALL'"
   - yum: name=nrpe state=latest