sed and awk

Remove multiple spaces
= = = = = = = = = = = = =

Remove leading space and number in history command output
 
history | sed 's/^ *[0-9][0-9]* *//'


root@vm2:~# cat hello 
#ab 12
cd      99
   zz    te
#ef
    test
      #tellso

root@vm2:~# cat hello  | sed 's/^\s\+//g'

#ab 12
cd      99
zz    te
#ef
test
#tellso

Combinig sed expression
root@vm2:~# cat hello  | sed 's/^\s\+//g;s/\s\+/ /g'
#ab 12
cd 99
zz te
#ef
test
#tellso


sed 'p' passwd  #prints file content but double content
sed -n '1p' file.txt  #print 1st line
sed -n  '2p' file.txt  #print 2nd line
sed -n 4,13p file.txt #print 4 to 14 line
sed -n '$p'  file.txt  #print last
sed -n '1!p' file.txt  #print all except line 1
sed -n '1,3!p' file.txt #print all except line 1 to 3


=======================using regular expression=======================
we use '-e' option when we use expression

sed -n -e '/2011/p' file.txt     # print line containing 2011
sed -n -e '/^root/p' passwd      # print lines starting with word 'root'
sed -n -e '/root$/p' passwd      # print lines Ending with word 'root'
sed -n -e '/^harke101$/p' passwd
sed -n -e '/^harke101.*$/p' passwd     # print lines Starting and Ending with word 'root'
sed -n -e '/[0-9]/p' firewall.txt     # print lines containing number 0-9
sed -n -e '/^[0-9][0-9][0-9]$/p'  firewall.txt #print beginning and ending with 3 char number
sed -n -e '/[0-9]\{3\}/p' firewall.txt # print beginning and ending with 3 char number
sed -n -e '/^[0-9]\{3\}$/p' firewall.txt # print beginning and ending with 3 char number



Find sumtotal of column

ps aux | grep apache | awk '{ sum += $6 } END { print sum }'
ls -lh php*; ls -l php* | awk '{ SUM += $5} END { print SUM/1024/1024 }'
===========================================================================



echo 'its a trap' | sed s/ra/zzz/        ##replace the word ra with zzz, matches only first occurance of Reg Ex
its a tzzzp

echo "how now brown cow" | sed s/ow/YY/  
hYY now brown cow

echo "how now brown cow" | sed s/ow/YY/g
hYY nYY brYYn cYY

sed -ie 's/ow/aagh/g' ~/temp.txt   #Make changes to the file itself

sed '11,$ d' ~/temp.txt  #delete line 11 and latter lines of file

sed '/#.*/ d'  file.txt   #delete line starting with '#'

Remove empty lines and comments {#  and ;}

 cat taste | sed '/^[#;]/d' | sed '/^$/d'      =>[#;] means lines starting with semicolon ";"  or hash " # " 


Tr command in linux
= = = = = = =  = = =  = =

Replace newline[\n]with    '  '  <space>

echo "$string" | tr '\n' ' '

Translate white-space to tabs

$ 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

# Replace multiple newline with single new line


cat -s filename

cat -s 10-master.conf | grep -v "#" | cat -s

# with sed

cat filename | sed '/^$/d'

# with tr to replace multiple newline to one
cat file name | tr -s '\n'

mailscanner clamd spamassassin- Integrating mailscanner part 3

====Integrating MailScannner=====
1. Edit the file /etc/postfix/main.cf and remove the # in front of the line below

header_checks = regexp:/etc/postfix/header_checks

2. Edit the file /etc/postfix/header_checks and add the line below to the bottom of the file

/^Received:/ HOLD

3. MailScanner should now be the one to start the Postfix service. Stop the Postfix service and start the Clamd and MailScanner service in that order. Use the commands below to accomplish these.

chkconfig postfix off
chkconfig clamd on
chkconfig MailScanner on
service postfix stop
service clamd start
service MailScanner start
= = = = = clean mailscanner quarantine emails as the size increase gradually by time = = =
 # cd /etc/cron.daily/
# vim  clean.quarantine
$disabled = 0;    #uncomment
$days_to_keep   = 3;    # set value according to your needs

#./clean.quarantine       ; #to run now by hand


= = = = = clamd  may stop ,, dirty fix by periodically restarting clamd = = = = =  =
[root@mx12 xinetd.d]# crontab -l
*/3 * * * * /opt/checkclam.sh

# cat /opt/checkclam.sh
#!/bin/bash
if ! pgrep clamd > /dev/null;
then
/etc/init.d/clamd restart > /dev/null;
else
echo "OK `date +%T\ %F`" >> /program.log; #'\ ' is for space use %t for tab
fi

 = = = = = = = = = = = = = = =  = = = = = =

Perform header checks  with /etc/postfix/header_checks   file :

/^Received:/ HOLD
#                                                               HEADER_CHECKS
#
/^Subject:.*Info..P..E N I_S..--..E-N-L..A R-G-E M_E..N T-___P_I L..L_S-*/ HOLD
/^Subject:.*skinny/ HOLD
/^Subject:.*      / HOLD
/^Subject:.*Easy*/ HOLD
/^From:.*medch*/ HOLD
/^From: "expediti/ HOLD
/^From:.*newsfilm@ds02.01cloud.com/ HOLD
/^From:.*no-reply@answers.medchrome.com*/ HOLD
/^From:.*expediti/ HOLD
/^From:.*tejecraft.com.np*/ HOLD

[root@mx12 postfix]# cat check_sender
gmail.com   REJECT
hotmail.com    REJECT
yahoo.com      REJECT
medch@ds02.01cloud.com  REJECT
expediti@ds01.01cloud.com REJECT
info@tejecraft.com.np REJECT
newsfilm@ds02.01cloud.com REJECT
no-reply@answers.medchrome.com REJECT
info@wexnepal.com REJECT


[]#postmap check_sender
]#vim main.cf

smtpd_sender_restrictions = check_sender_access hash:/etc/postfix/check_sender

mailscanner clamd spamassassin-- mailscanner.conf configuratoin part 2

yum install spamassassin

Configuring MailScanner
#check below lines match
vim  /etc/MailScanner/virus.scanners.conf
clamav          /usr/lib/MailScanner/clamav-wrapper     /usr/local
clamd           /bin/false                              /usr/sbin



vim /etc/MailScanner/MailScanner.conf
# **** RULE: It must not contain any spaces! ****
%org-name% = mx12  #give your servername
%org-long-name% =          #your organization full name optional
%web-site% =   #optional
Run As User = postfix
Run As Group = postfix
Incoming Queue Dir = /var/spool/postfix/hold
Outgoing Queue Dir = /var/spool/postfix/incoming
Quarantine Dir = /var/spool/MailScanner/quarantine
PID file = /var/run/MailScanner.pid
MTA  = postfix
Incoming Work User =
Incoming Work Group = clam
Incoming Work Permissions = 0640

Virus Scanners = clamd
Clamd Port = 3310
Clamd Lock File =
Clamd Use Threads = no  #just check leave defaults
Clamd Socket = /var/run/clamav/clamd.sock
Use SpamAssassin = yes
SpamAssassin User State Dir = /var/spool/MailScanner/spamassassin


===SETUP NECESSARY DIRECTORIES===
cd /var/spool/MailScanner/
mkdir spamassassin
chown -R postfix.clam *
chmod -R 750 *


[root@mx12 MailScanner]# ls -l
total 12
drwxr-x---  9 postfix clam   4096 Aug 21 02:27 incoming
drwxr-x--- 26 postfix apache 4096 Aug 21 00:01 quarantine
drwxr-x---  2 postfix clam   4096 Aug 21 02:17 spamassassin

mailscanner clamd spamassassin- installing clamd and mailscanner part 1

=====install  clamd and mailscanner=====

 first add epel

 yum install clamd
 3. To test ClamAV AntiVirus, type in the command clamscan in a terminal window.
 4. To update the virus database, type in the command freshclam in a terminal window.
 yum install
perl-Archive-Zip
perl-DBI
perl-DBD-SQLite
perl-Filesys-Df
perl-Net-CIDR
perl-OLE-Storage_Lite
perl-Sys-Hostname-Long
perl-Sys-SigAction
perl-MIME-tools

3. Download the latest stable version of MailScanner for RedHat, Fedora and Mandrake Linux at http://www.mailscanner.info/downloads.html.

4. Extract MailScanner using the command below.

tar -xvzf ~/Desktop/MailScanner*.gz

Replace ~/Desktop with the path of your downloaded file

5. Finally, type in the command below to install MailScanner.

cd MailScanner-4.83.5-1
yum install --nogpgcheck mailscanner* tnef*

Replace MailScanner-4.83.5-1 with the path of the extracted MailScanner archive file.

6. To test MailScanner, use the command below.

MailScanner

Errors related to configuration files are ok. Errors saying “Can’t locate xxx.pm” are perl module dependency problems so repeat step 2.

automysql backup auto mysql backup

################### Shell Bash style NO 1###############################
#!/bin/bash
#Script to make a regular copy of a mysql database and gzip it into the SAVEDIR.

USER="authorized_user"
PASSWORD="the_password"
DATABASE="database_name"
SAVEDIR="/backup"

/usr/bin/nice -n 19 /usr/bin/mysqldump -u $USER --password=$PASSWORD --default-character-set=utf8 $DATABASE -c | /usr/bin/nice -n 19 /bin/gzip -9 > $SAVEDIR/$DATABASE-$(date '+%Y%m%d-%H').sql.gz

################### Shell Bash style NO 2###############################
 #!/bin/bash
mysqldump  -u  root  -pyourP@ssword cloud | gzip > /mysqldump/cloud_db_`date '+%m-%d-%Y'`.sql.gz

##############################################################################
AutoMySQLBackup is a clever script that takes the pain out of setting up automated incremental daily, weekly, and monthly backups of MySQL databases. Its only dependency is the mysqldumpcommand, which comes with mysql-client. AutoMySQLBackup dumps your databases at whatever intervals you desire, and rolls them up into compressed tarballs. Then you can copy the tarballs to other media, and encrypt them if you wish.

Getting AutoMySQLBackup

Download AutoMySQLBackup from Sourceforge, and then unpack the tarball:
$ tar zxvf automysqlbackup-v3.0_rc6.tar.gz
Now you should have the automysqlbackup-v3.0_rc6 directory with six files in it: automysqlbackup, automysqlbackup.conf, CHANGELOG, install.sh, LICENSE, and README.
Next, read the README because it contains installation instructions and other useful information. It may not tell you everything you need to know, so hopefully this article will fill the gaps. Then your next step is to run install.sh, and this requires root privileges. If the installation script fails you can easily install AutoMySQLBackup manually by following these steps. These are run from the directory where you unpacked the tarball:
# chown root:root automysqlbackup
# chmod 0700 automysqlbackup
# cp automysqlbackup /usr/local/bin/
# mkdir /etc/automysqlbackup
# cp automysqlbackup.conf /etc/automysqlbackup/automysqlbackup.conf
# cd /etc/automysqlbackup
# cp automysqlbackup.conf servername.conf
Replace "servername.conf" with whatever you want to name your configuration file. Then you will have a copy of the original for reference, and your working configuration file.

Configuration Options

The configuration file is large and well-commented, and you need to change only a few things to start making and testing your backups. First you need to select a MySQL user that has, at a minimum, SELECT privileges, and then enter that user and user's password:
# Username to access the MySQL server e.g. dbuser
CONFIG_mysql_dump_username='db_user'
# Password to access the MySQL server e.g. password
CONFIG_mysql_dump_password='sekkritpassword'
There is a complication if you are using Parallels Plesk 10.2 or newer on your server, and you want to authenticate with the admin user. It is better to use a different MySQL user, like one you have created with minimal privileges just for AutoMySQLBackup, but if that is not possible then you can't use the plain-text admin password. Starting with version 10.2 the Plesk admin password is encrypted in /etc/psa/.psa.shadow. You can dump this password in plain text with this command if you need to recover it:
# /usr/local/psa/bin/admin --show-password
But you can't use the plain text password in your AutoMySQLBackup configuration. Instead, use the encrypted password:
# Password to access the MySQL server e.g. password
CONFIG_mysql_dump_password=`cat /etc/psa/.psa.shadow`
Your server is localhost, and you need to create or choose a directory to store your backups in:
# Host name (or IP address) of MySQL server e.g localhost
CONFIG_mysql_dump_host='localhost'
# Backup directory location e.g /backups
CONFIG_backup_dir='/home/mysqlbackups'
You have a lot of control over which databases are backed up. If you have a lot of them, then leaving CONFIG_db_names=() empty copies all of them. Then if there are any you want to exclude, just create an exclude list. One of my servers hosts over 150 virtual Web hosts, and each one has its own MySQL database, so this is a huge timesaver for me:
# List of databases for Daily/Weekly Backup e.g. ( 'DB1' 'DB2' 'DB3' ... )
# set to (), i.e. empty, if you want to backup all databases
CONFIG_db_names=()
# List of databases for Monthly Backups.
# set to (), i.e. empty, if you want to backup all databases
CONFIG_db_month_names=()
# List of DBNAMES to EXLUCDE if DBNAMES is empty, i.e. ().
CONFIG_db_exclude=('information_schema' 'test_db' 'demo_db' )
Rotation settings are straightforward. This example performs monthly backups on the 3rd of every month, weekly backups on Saturdays, daily backups are kept for 7 days, weekly backups are kept for 14 days, and monthly backups for 30 days.
# Which day do you want monthly backups? (01 to 31)
# If the chosen day is greater than the last day of the month, it will be done
# on the last day of the month.
# Set to 0 to disable monthly backups.
CONFIG_do_monthly="03"
# Which day do you want weekly backups? (1 to 7 where 1 is Monday)
# Set to 0 to disable weekly backups.
CONFIG_do_weekly="6"
# Set rotation of daily backups. VALUE*24hours
# If you want to keep only today's backups, you could choose 1, i.e. everything older than 24hours will be removed.
CONFIG_rotation_daily=7
# Set rotation for weekly backups. VALUE*24hours
CONFIG_rotation_weekly=14
# Set rotation for monthly backups. VALUE*24hours
CONFIG_rotation_monthly=30
There are two items that control notifications. I like to see the logfiles after every run, as this example shows:
# What would you like to be mailed to you?
# - log   : send only log file
# - files : send log file and sql files as attachments (see docs)
# - stdout : will simply output the log to the screen if run manually.
# - quiet : Only send logs if an error occurs to the MAILADDR.
CONFIG_mailcontent='log'
# Email Address to send mail to? (
 user@domain.com)CONFIG_mail_address='
 carla@tuxcomputing.com'

First Run

For the first few runs, while you're getting familiar with AutoMySQLBackup, I recommend backing up just one or two small databases. It's safe and can't hurt your databases, but the larger your databases the longer it takes to try different configuration tweaks. Run it from the command line like this:
# automysqlbackup /etc/automysqlbackup/servername.conf
Then you can check your backup directory to see if it worked. It should have created all the necessary directories:
# ls /home/mysqlbackups/
daily/  
fullschema/  
latest/  
monthly/  
status/  
tmp/  
weekly/
And made entries like this, for each database you backed up, in the daily/ directory:
-rw-r--r-- 1 root root 66428 Oct 25 00:12 daily_db_name_2012-10-22_00h05m_Monday.sql.gz
AutoMySQLBackup generates a detailed log file, so there will be no mysteries about what happened if anything goes wrong.
The README offers a simple backup script:
#!/bin/sh
/usr/local/bin/automysqlbackup /etc/automysqlbackup/myserver.conf
chown root.root /var/backup/db* -R
find /var/backup/db* -type f -exec chmod 400 {} \;
find /var/backup/db* -type d -exec chmod 700 {} \;
You'll need to change myserver.conf to your configuration file name, and /var/backup/ to your own backup directory. This script ensures that the backup files owner is root, and that they are read-only, which are simple precautions against accidental changes. Don't forget to make it executable.

Scheduled Backups

Good old cron is still champ for scheduling backups. This example runs the backup script every morning at 12:05AM:
5 0 * * *  /usr/local/bin/backupscript 

Offsite Backups

Now that you have these nice database backups, what do you do with them? I use Horcrux, which we learned about last week, to encrypt and copy them to an offsite backup. So all I have to do to add my database backups to my Horcrux backup is to add this line to my Horcrux configuration:
+ /home/mysqlbackups/
Because these are compressed tarballs, you can manage them like any ordinary files and copy them to whatever backup media you want.
What about restoring from backup? AutoMySQLBackup doesn't offer any special tools for making that any easier, so you'll have to do it manually by first unzipping the backup file, and then using the mysql client to restore your database or databases. The README and forums are helpful, but what will help the most is knowing how to administer MySQL databases.

grep command GREP command

ls -l | grep -i python  # -i  = case insensitive search

ls -l | grep -v "python"   # -v = invert the search , not matching element will be printed

# find . –name "*.mp3" | grep –i JayZ | grep –vi "remix" 

ps -ef | grep -c [h]ttpd  #count number of matching line

cat myfile.txt | grep -n "major12"  # print line number of matching line

cat myfile.txt | grep -w "NepalKTM"  #returns only "NepalKTM" match entire word only
 
cat apache.conf | grep -v "^#"  

check process status and start if it is not running using cron bash

[root@mx12 /]# cat /opt/checkclam.sh
#!/bin/bash
if ! pgrep clamd > /dev/null;
then
/etc/init.d/clamd restart > /dev/null;
else
echo "OK `date +%T\ %F`" >> /program.log; #'\ ' is for space use %t for tab
fi


[root@mx12 /]# crontab -l
*/3 * * * * /opt/checkclam.sh 


== == =====  ===== = =  =  === === ====    == =  ========= =
#!/bin/bash

# Check if gedit is running
if ps aux | grep "[h]ttdp" > /dev/null
then
    echo "Running"
else
    echo "Stopped"
fi
 
This script is just checking to see if the program "httpd" is running.
The square brackets are useful to avoid the output of the grep command. Without this the conditional will always return true, because the grep command start a process with the same content of the searched string.
 = = = =  = = = = = = = = =Check SELINUX and turn it to permissive  = = = = = = = = = = = = = =
#!/bin/bash
var1=`getenforce`
if [ "$var1" == "Permissive" ]
then
    :                             # the " : " colon will do nothing or NO operation
else
/usr/sbin/setenforce 0
fi
 
 
============
 
[root@mailvm /]# cat selinuxcheck 
#!/bin/bash
var1=`getenforce`
#if [ "$var1" == "Permissive" ] 
#then  
#    :
#else 
#/usr/sbin/setenforce 0 
#fi
if [ "$var1" == "Enforcing" ]
then
echo "enforced mode"
printf "Now changing to Permissive"
sleep 1
printf "."
sleep 1
printf "."
/usr/sbin/setenforce 0
else
echo "permissive mode [OK]"  
fi
echo
 
============================================================================= 

ICINGA check postfix mailq in icinga part 3

#icinga  #icinga

#vim /etc/nagios/nrpe.cfg

allowed_hosts=198.50.155.195,  127.0.0.1
command[check_users]=/usr/lib/nagios/plugins/check_users -w 5 -c 10
command[check_load]=/usr/lib/nagios/plugins/check_load -w 15,10,5 -c 30,25,20
command[check_hda1]=/usr/lib/nagios/plugins/check_disk -w 20% -c 10% -p /
command[check_zombie_procs]=/usr/lib/nagios/plugins/check_procs -w 5 -c 10 -s Z
command[check_total_procs]=/usr/lib/nagios/plugins/check_procs -w 150 -c 200
command[check_mailq]=/usr/lib/nagios/plugins/check_mailq -w 300 -c 500

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
root@vps:/usr/lib/nagios/plugins# ls -l /usr/lib/nagios/plugins/check_mailq
-rwxr-xr-x 1 root root 916 Aug 15 16:34 /usr/lib/nagios/plugins/check_mailq*


#cat /usr/lib64/nagios/plugins/check_mailq

#!/bin/bash
#
# 19-07-2010
# Author: Cherwin Nooitmeer <cherwin@gmail.com>
#

# exit codes
e_ok=0
e_warning=1
e_critical=2
e_unknown=3



# regular expression that matches queue IDs (e.g. D71EF7AC80F8)
queue_id='^[A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9]'

usage="Invalid command line usage"

if [ -z $1 ]; then
    echo $usage
    exit $e_unknown
fi

while getopts ":w:c:" options
do
    case $options in
        w ) warning=$OPTARG ;;
        c ) critical=$OPTARG ;;
        * ) echo $usage
            exit $e_unknown ;;
    esac
done

# determine queue size
qsize=$(mailq | egrep -c $queue_id)
if [ -z $qsize ]
then
    exit $e_unknown
fi

if [ $qsize -ge $critical ]; then
    retval=$e_critical
elif [ $qsize -ge $warning ]; then
    retval=$e_warning
elif [ $qsize -lt $warning ]; then
    retval=$e_ok
fi

echo "$qsize mail(s) in queue | mail_queue=$qsize"
exit $retval




===========@ In ICINGA server -===============
#no need to add nrpe user in sudoer file

# /usr/local/icinga/libexec/check_nrpe -H 5.9.240.227 -c check_mailq
 358 mail(s) in queue | mail_queue=358

ICINGA EXIM mailq script for icinga part 2

========================================================================
check mailq EXIM
 ========================================================================
At client side:-
#rpm -qf utils.pm                                  //tofind the package name of file
#yum install nagios-plugins-perl
do this if you face the"utils.sh not found error". make dir's as needed
#ln -s /usr/lib64/nagios/plugins/utils.sh  /usr/local/nagios/libexec/utils.sh
#visudo
   Comment out    

#Defaults    requiretty             <<<= = =

#add nrpe user like below line
root    ALL=(ALL)       ALL
nrpe ALL=NOPASSWD:/usr/sbin/exim                             
Save/exit
 ***************************************
copybelow script in file name  "check_eximmailqueue"
#ls -l  /usr/lib64/nagios/plugins/check_eximmailqueue
-rwxr-xr-x 1 root root   3285 Jul 27 06:25 check_eximmailqueue*
-rwxr-xr-x 1 root root 172880 Oct 17  2013 check_http*
-rwxr-xr-x 1 root root  40944 Oct 17  2013 check_load*
-rwxr-xr-x 1 root root  22256 Apr 30 21:28 check_nrpe*
-rwxr-xr-x 1 root root  36080 Oct 17  2013 check_users*
-rwxr-xr-x 1 root root  38696 Oct 17  2013 negate*
-rwxr-xr-x 1 root root  36104 Oct 17  2013 urlize*
-rw-r--r-- 1 root root   2091 Oct 17  2013 utils.pm
-rwxr-xr-x 1 root root   2728 Oct 17  2013 utils.sh*
cat /usr/lib64/nagios/plugins/check_eximmailqueue
#!/bin/sh
###############################################
#
# Nagios script to check Exim mail queue status
#
# Copyright 2007, 2008 Ian Yates
#
# NOTE: Depending on your config, the nagios user will probably be
#       needed to be added to the exim group for this script to function correctly
#
# See usage for command line switches
#

. /usr/local/nagios/libexec/utils.sh


VERSION="1.3"

EXIM=$(which exim)
SUDO=/usr/bin/sudo

FLAG_VERBOSE=FALSE
LEVEL_WARN=""
LEVEL_CRIT=""
RESULT=""
EXIT_STATUS=$STATE_OK


###############################################
#
## FUNCTIONS
#

## Print usage
usage() {
    echo " check_eximailqueue $VERSION - Nagios Exim mail queue check script"
    echo ""
    echo " Usage: check_eximailqueue -w <warning queue size> -c <critical queue size> [ -v ] [ -h ]"
    echo ""
    echo "         -w  Queue size at which a warning is triggered"
    echo "         -c  Queue size at which a critical is triggered"
    echo "         -v  Verbose output (ignored for now)"
    echo "         -h  Show this page"
    echo ""
}

## Process command line options
doopts() {
    if ( `test 0 -lt $#` )
    then
        while getopts w:c:vh myarg "$@"
        do
            case $myarg in
                h|\?)
                    usage
                    exit;;
                w)
                    LEVEL_WARN=$OPTARG;;
                c)
                    LEVEL_CRIT=$OPTARG;;
                v)
                    FLAG_VERBOSE=TRUE;;
                *)    # Default
                    usage
                    exit;;
            esac
        done
    else
        usage
        exit
    fi
}


# Write output and return result
theend() {
    echo $RESULT
    exit $EXIT_STATUS
}


#
## END FUNCTIONS
#

#############################################
#
## MAIN
#


# Handle command line options
doopts $@

# Do the do
OUTPUT=`$SUDO -u root $EXIM -bpc`
if test -z "$OUTPUT" ; then
    RESULT="Mailqueue WARNING - query returned no output!"
    EXIT_STATUS=$STATE_WARNING
else
    if test "$OUTPUT" -lt "$LEVEL_WARN" ; then
        RESULT="Mailqueue OK - $OUTPUT messages on queue"
        EXIT_STATUS=$STATE_OK
    else
        if test "$OUTPUT" -ge "$LEVEL_CRIT" ; then
            RESULT="Mailqueue CRITICAL - $OUTPUT messages on queue"
            EXIT_STATUS=$STATE_CRITICAL
        else
            if test "$OUTPUT" -ge "$LEVEL_WARN" ; then
                RESULT="Mailqueue WARNING - $OUTPUT messages on queue"
                EXIT_STATUS=$STATE_WARNING
            fi
        fi
    fi
fi

# Quit and return information and exit status
theend

delete file with inode

ls -il   #list file inode


stat  filename  

SYNTAX-  find . -inum [inode-number] -exec rm -i {} \;

Example:-
 
find . -inum 782263 -exec rm -i {} \;

(a) Create a hard to delete file name:
$ cd /tmp
$ touch "\+Xy \+\8"
$ ls

(b) Try to remove this file with rm command:
$ rm \+Xy \+\8

(c) Remove file by an inode number, but first find out the file inode number:
$ ls -ilOutput:
781956 drwx------  3 viv viv 4096 2006-01-27 15:05 gconfd-viv
781964 drwx------  2 viv viv 4096 2006-01-27 15:05 keyring-pKracm
782049 srwxr-xr-x  1 viv viv    0 2006-01-27 15:05 mapping-viv
781939 drwx------  2 viv viv 4096 2006-01-27 15:31 orbit-viv
781922 drwx------  2 viv viv 4096 2006-01-27 15:05 ssh-cnaOtj4013
781882 drwx------  2 viv viv 4096 2006-01-27 15:05 ssh-SsCkUW4013
782263 -rw-r--r--  1 viv viv    0 2006-01-27 15:49 \+Xy \+\8
Note: 782263 is inode number.
(d) Use find command to delete file by inode:
Find and remove file using find command, type the command as follows:
$ find . -inum 782263 -exec rm -i {} \;

python 2.6.6 mysqldb connect centos 6.3

yum groupinstall 'Development tools'
yum install python-setuptools
yum install unzip
yum install wget
yum install python-devel mysql-devel zlib-devel openssl-devel
wget --no-check-certificate https://pypi.python.org/packages/source/M/MySQL-python/MySQL-python-1.2.5.zip

unzip MySQL-python-1.2.5.zip

cd MySQL-python-1.2.5

[root@mail MySQL-python-1.2.5]# python setup.py build
running build
running build_py
copying MySQLdb/release.py -> build/lib.linux-i686-2.6/MySQLdb
running build_ext
[root@mail MySQL-python-1.2.5]# echo $?

[root@mail MySQL-python-1.2.5]# python setup.py install

.
.
.
Adding MySQL-python 1.2.5 to easy-install.pth file

Installed /usr/lib/python2.6/site-packages/MySQL_python-1.2.5-py2.6-linux-i686.egg
Processing dependencies for MySQL-python==1.2.5
Finished processing dependencies for MySQL-python==1.2.5

#echo $?
0

nmap command

#2: Scan multiple IP address or subnet (IPv4)

nmap 192.168.1.1 192.168.1.2 192.168.1.3
## works with same subnet i.e. 192.168.1.0/24
nmap 192.168.1.1,2,3
You can scan a range of IP address too:
nmap 192.168.1.1-20
You can scan a range of IP address using a wildcard:
nmap 192.168.1.*
Finally, you scan an entire subnet:
nmap 192.168.1.0/24
 

#3: Read list of hosts/networks from a file (IPv4)

nmap -iL /tmp/test.txt
 
cat > /tmp/test.txt
 
server1.cyberciti.biz
192.168.1.0/24
192.168.1.1/24
10.1.2.3
localhost
 

#4: Excluding hosts/networks (IPv4)

When scanning a large number of hosts/networks you can exclude hosts from a scan:
nmap 192.168.1.0/24 --exclude 192.168.1.5
nmap 192.168.1.0/24 --exclude 192.168.1.5,192.168.1.254

OR exclude list from a file called /tmp/exclude.txt
 
nmap -iL /tmp/scanlist.txt --excludefile /tmp/exclude.txt
 

#5: Turn on OS and version detection scanning script (IPv4)

nmap -A 192.168.1.254 nmap -v -A 192.168.1.1 nmap -A -iL /tmp/scanlist.txt

#6: Find out if a host/network is protected by a firewall

nmap -sA 192.168.1.254 nmap -sA server1.cyberciti.biz

#7: Scan a host when protected by the firewall

nmap -PN 192.168.1.1 nmap -PN server1.cyberciti.biz

#8: Scan an IPv6 host/address

The -6 option enable IPv6 scanning. The syntax is:
nmap -6 IPv6-Address-Here nmap -6 server1.cyberciti.biz nmap -6 2607:f0d0:1002:51::4 nmap -v A -6 2607:f0d0:1002:51::4

#9: Scan a network and find out which servers and devices are up and running

This is known as host discovery or    ping scan:      
nmap -sP 192.168.1.0/24

#10: How do I perform a fast scan?

nmap -F 192.168.1.1

#11: Display the reason a port is in a particular state

nmap --reason 192.168.1.1
nmap --reason server1.cyberciti.biz

#12: Only show open (or possibly open) ports

nmap --open 192.168.1.1
nmap --open server1.cyberciti.biz

#13: Show all packets sent and received

nmap --packet-trace 192.168.1.1
nmap --packet-trace server1.cyberciti.biz
 

#12: Only show open (or possibly open) ports

nmap --open 192.168.1.1 nmap --open server1.cyberciti.biz

#13: Show all packets sent and received

nmap --packet-trace 192.168.1.1
nmap --packet-trace server1.cyberciti.biz
 

14#: Show host interfaces and routes

This is useful for debugging (ip command or route command or netstat command like output using nmap)
nmap --iflist

#15: scan specific ports?

## Scan port 80
nmap -p 80 192.168.1.1
 
## Scan TCP port 80
nmap -p T:80 192.168.1.1
 
## Scan UDP port 53
nmap -p U:53 192.168.1.1
 
## Scan two ports ##
nmap -p 80,443 192.168.1.1
 
## Scan port ranges ##
nmap -p 80-200 192.168.1.1
 
## Combine all options ##
nmap -p U:53,111,137,T:21-25,80,139,8080 192.168.1.1
nmap -p U:53,111,137,T:21-25,80,139,8080 server1.cyberciti.biz
nmap -v -sU -sT -p U:53,111,137,T:21-25,80,139,8080 192.168.1.254
 
## Scan all ports with * wildcard ##
nmap -p "*" 192.168.1.1
 
## Scan top ports i.e. scan $number most common ports ##
nmap --top-ports 5 192.168.1.1
nmap --top-ports 10 192.168.1.1
 

#16: The fastest way to scan all your devices/computers for open ports ever

nmap -T5 192.168.1.0/24

#17: How do I detect remote operating system?

You can identify a remote host apps and OS using the -O option:
 
nmap -O 192.168.1.1
nmap -O  --osscan-guess 192.168.1.1
nmap -v -O --osscan-guess 192.168.1.1
 

#18: How do I detect remote services (server / daemon) version numbers?

nmap -sV 192.168.1.1

#19: Scan a host using TCP ACK (PA) and TCP Syn (PS) ping

If firewall is blocking standard ICMP pings, try the following host discovery methods:
nmap -PS 192.168.1.1
nmap -PS 80,21,443 192.168.1.1
nmap -PA 192.168.1.1
nmap -PA 80,21,200-512 192.168.1.1
 

#20: Scan a host using IP protocol ping

nmap -PO 192.168.1.1

#21: Scan a host using UDP ping

This scan bypasses firewalls and filters that only screen TCP:
nmap -PU 192.168.1.1 nmap -PU 2000.2001 192.168.1.1

#22: Find out the most commonly used TCP ports using TCP SYN Scan

  ### Stealthy scan ### nmap -sS 192.168.1.1   ### Find out the most commonly used TCP ports using TCP connect scan (warning: no stealth scan) ### OS Fingerprinting ### nmap -sT 192.168.1.1   ### Find out the most commonly used TCP ports using TCP ACK scan nmap -sA 192.168.1.1   ### Find out the most commonly used TCP ports using TCP Window scan nmap -sW 192.168.1.1   ### Find out the most commonly used TCP ports using TCP Maimon scan nmap -sM 192.168.1.1 
 

#23: Scan a host for UDP services (UDP scan)

Most popular services on the Internet run over the TCP protocol. DNS, SNMP, and DHCP are three of the most common UDP services. Use the following syntax to find out UDP services:
nmap -sU nas03
nmap -sU 192.168.1.1

#24: Scan for IP protocol

This type of scan allows you to determine which IP protocols (TCP, ICMP, IGMP, etc.) are supported by target machines:
nmap -sO 192.168.1.1

#25: Scan a firewall for security weakness

The following scan types exploit a subtle loophole in the TCP and good for testing security of common attacks:
 
## TCP Null Scan to fool a firewall to generate a response ##
## Does not set any bits (TCP flag header is 0) ##
nmap -sN 192.168.1.254
 
## TCP Fin scan to check firewall ##
## Sets just the TCP FIN bit ##
nmap -sF 192.168.1.254
 
## TCP Xmas scan to check firewall ##
## Sets the FIN, PSH, and URG flags, lighting the packet up like a Christmas tree ##
nmap -sX 192.168.1.254

 

#26: Scan a firewall for packets fragments

The -f option causes the requested scan (including ping scans) to use tiny fragmented IP packets. The idea is to split up the TCP header over
several packets to make it harder for packet filters, intrusion detection systems, and other annoyances to detect what you are doing.
nmap -f 192.168.1.1
nmap -f fw2.nixcraft.net.in
nmap -f 15 fw2.nixcraft.net.in
## Set your own offset size with the --mtu option ##
nmap --mtu 32 192.168.1.1

#27: Cloak a scan with decoys

The -D option it appear to the remote host that the host(s) you specify as decoys are scanning the target network too. Thus their IDS might report 5-10 port scans from unique IP addresses, but they won't know which IP was scanning them and which were innocent decoys:
nmap -n -Ddecoy-ip1,decoy-ip2,your-own-ip,decoy-ip3,decoy-ip4 remote-host-ip nmap -n -D192.168.1.5,10.5.1.2,172.1.2.4,3.4.2.1 192.168.1.5

#28: Scan a firewall for MAC address spoofing

  ### Spoof your MAC address ## nmap --spoof-mac MAC-ADDRESS-HERE 192.168.1.1   ### Add other options ### nmap -v -sT -PN --spoof-mac MAC-ADDRESS-HERE 192.168.1.1     ### Use a random MAC address ### ### The number 0, means nmap chooses a completely random MAC address ### nmap -v -sT -PN --spoof-mac 0 192.168.1.1  

#29: How do I save output to a text file?

The syntax is:
nmap 192.168.1.1 > output.txt nmap -oN /path/to/filename 192.168.1.1 nmap -oN output.txt 192.168.1.1

setup spamassassin centos 6 for zpanel

First we need to install postgrey daemon.
Open a terminal window and enter:


Code:
yum install postgrey

OK. Service installed!

Now open /etc/init.d/postgrey with your favorite editor and find this line:

Code:
vi /etc/init.d/postgrey

# search for this line
Code:
options="--unix=/var/spool/postfix/postgrey/socket"

It means that process "postgrey" is using socket instead of tcp connection. Socket path is cruical for postfix to communicate with postgrey. CTRL (CMD) + C this path for later use!

We need to start the service and make sure, that the service will start automatically after reboot!

Code:
service post grey start
chkconfig postgrey on

The postfix config part…
With your favourite editor open /etc/postfix/main.cf

Code:
vi /etc/postfix/main.cf

… and find the

Code:
smtpd_recipient_restrictions =

it should look something like this:

Code:
smtpd_recipient_restrictions =
   permit_mynetworks,
   permit_sasl_authenticated,
   check_policy_service unix:/var/spool/postfix/postgrey/socket, ### Add this line. Double check the socket path!!!

Mine smtpd_recipient_restrictions block looks like this:

Code:
smtpd_recipient_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        check_policy_service unix:/var/spool/postfix/postgrey/socket,
        reject_invalid_hostname,
        reject_unauth_destination,
        reject_non_fqdn_sender,
        reject_non_fqdn_recipient,
        reject_unknown_recipient_domain,
        reject_unauth_pipelining,
        reject_unknown_sender_domain,
        reject_unknown_recipient_domain,

# SPAM/black list checks

        reject_rbl_client sbl-xbl.spamhaus.org,
#       reject_rbl_client multi.uribl.com, ### Too many requests - payable service
        reject_rbl_client dsn.rfc-ignorant.org,
        reject_rbl_client dul.dnsbl.sorbs.net,
        reject_rbl_client dnsbl.njabl.org,
        reject_rbl_client bl.spamcop.net,
#       reject_rbl_client dnsbl.sorbs.net, ### This one is blocking emails from yahoo
        reject_rbl_client cbl.abuseat.org,
        reject_rbl_client ix.dnsbl.manitu.net,
        reject_rbl_client combined.rbl.msrbl.net,
        reject_rbl_client rabl.nuclearelephant.com,
        permit

If you want to whitelist some clients/recipients open this two files with your editor of choice:

Code:
vi /etc/postfix/postgrey_whitelist_clients
vi /etc/postfix/postgrey_whitelist_recipients

For the last step all we have to do is to reload the Postfix configuration with:

Code:
service postfix reload

Just to be sure that Postfix and Postgrey are working together check the maillog with:

Code:
tail -f /var/log/maillog

… and find this line

Code:
Aug 28 17:33:59 hostname postgrey[20092]: action=greylist, reason=new, client_name=remote.mail.server, client_address=<remote IP address>, sender=<email@address>, recipient=<email@address>

Well done. You've just dramatically reduced the number of SPAM messages.

If you want to read more about Postgrey service, here is the link: http://projects.puremagic.com/greylisting/

Enjoy!
=================================================================
 SCRIPT TO INSTALL IN CENTOS

#!/bin/sh
#
# Script to install postgrey and spamassassin, tested on Centos 6.4 and ZPanel 10.1.0
#
if which postgrey >/dev/null; then
echo "postgrey already exist"
else
echo "Installing postgrey"
yum -y install postgrey
sed -i '/^smtpd_recipient_restrictions =/ s/$/ check_policy_service inet:127.0.0.1:60000,/' /etc/zpanel/configs/postfix/main.cf
sed -i 's/options=\"--unix=\/var\/spool\/postfix\/postgrey\/socket\"/options=\"--inet=127.0.0.1:60000 --delay=150\"/g' /etc/init.d/postgrey
service postgrey start
service postfix reload
chkconfig postgrey on
echo "postgrey installed"
fi
#
if which spamassassin >/dev/null; then
echo "spamassassin already exist"
else
echo "Installing spamassassin"
yum -y install spamassassin
echo -e "\n" > /etc/mail/spamassassin/local.cf
sed -i '1s/^/required_hits 5.0\n/' /etc/mail/spamassassin/local.cf
sed -i '2s/^/report_safe 0\n/' /etc/mail/spamassassin/local.cf
sed -i '3s/^/required_score 5\n/' /etc/mail/spamassassin/local.cf
sed -i '4s/^/rewrite_header Subject ***SPAM***\n/' /etc/mail/spamassassin/local.cf
groupadd spamd
useradd -g spamd -s /bin/false -d /var/log/spamassassin spamd
chown spamd:spamd /var/log/spamassassin
sed -i '/^smtp        inet/ s/$/ -o content_filter=spamassassin/' /etc/zpanel/configs/postfix/master.cf
sed -i '/^smtp      inet/ s/$/ -o content_filter=spamassassin/' /etc/zpanel/configs/postfix/master.cf
sed -i '/^smtp    inet/ s/$/ -o content_filter=spamassassin/' /etc/zpanel/configs/postfix/master.cf
sed -i '/^smtp  inet/ s/$/ -o content_filter=spamassassin/' /etc/zpanel/configs/postfix/master.cf
echo -e "\nspamassassin unix - n n - - pipe flags=R user=spamd argv=/usr/bin/spamc -e /usr/sbin/sendmail.postfix -oi -f \${sender} \${recipient}\n" >> /etc/zpanel/configs/postfix/master.cf
/etc/init.d/postfix restart
/etc/init.d/spamassassin restart
echo "SpamAssassin installed, to test it send a mail from outside with the subject: XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X"
echo "Your first email will take about 150 seconds to arrive"
fi

setup spamassassin ubuntu 12.04 for zpanel

 http://forums.sentora.io/showthread.php?tid=22
Ubuntu :How to setup Spamassassin
How to setup Spamassassin

1: Use apt-get to install Spamassassin and spamc.
Code: (Select All)
apt-get install spamassassin spamc
Add Spamassassin user

2: First add the group spams:
Code: (Select All)
groupadd spamd

3: Then add the user spamd with the home irectory /var/log/spamassassin:
Code: (Select All)
useradd -g spamd -s /bin/false -d /var/log/spamassassin spamd

4: then create the directory /var/log/spamassassin and change the ownership:
Code: (Select All)
mkdir /var/log/spamassassin
chown spamd:spamd /var/log/spamassassin

Setting Up Spamassassin
5: Open the spamassassin config file using:
Code: (Select All)
nano /etc/default/spamassassin

6: Setting up spamassassin
Code: (Select All)
Find ENABLED=0 and change to ENABLED=1
Find CRON=0 and change to CRON=1
Find OPTIONS and change the line to
OPTIONS="--create-prefs --max-children 2 --username spamd \ -H ${SAHOME} -s ${SAHOME}spamd.log"
save and exit

7: Now create a variable named SAHOME with the Spamassassin home directory:
Code: (Select All)
SAHOME="/var/log/spamassassin/"

8: start spamassassin
Code: (Select All)
service spamassassin start

Configuring Postfix

9: Open Postfix config file using:
Code: (Select All)
nano /etc/postfix/master.cf

10: Find the the line
Code: (Select All)
smtp    inet n     -     -     -     -     smtpd
add "-o content_filter=spamassassin" after smtpd

11 End of the file add:
Code: (Select All)
spamassassin unix - n n - - pipe user=spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f ${sender} ${recipient}

12: restart postfix
Code: (Select All)
service postfix restart

Configuring Spamassassin

13: Open the Spamassassin default rules file using:
Code: (Select All)
nano /etc/spamassassin/local.cf

14 : make rules
Code: (Select All)
change
#rewrite_header
Subject ***** SPAM ***** to
rewrite_header Subject [*** SPAM ***]
change required_score 5.0 to required_score 3.0
use_bayes from 0 to 1
bayes_auto_learn from 0 to 1

15: now restart spamassassin
Code: (Select All)
service spamassassin restart

Hardening wordpress website

Hardening WordPress Website
==================================================================
Vulnerabilities in WordPress
Like many modern software packages, WordPress is updated regularly to address new security issues that may arise. Improving software security is always an ongoing concern, and to that end you should always keep up to date with the latest version of WordPress. Older versions of WordPress are not maintained with security updates.

Passwords
Many potential vulnerabilities can be avoided with good security habits. A strong password is an important aspect of this.

The goal with your password is to make it hard for other people to guess and hard for a brute force attack to succeed. Many automatic password generators are available that can be used to create secure passwords.

Securing wp-admin
Adding server-side password protection (such as BasicAuth) to /wp-admin/ adds a second layer of protection around your blog's admin area, the login screen, and your files. This forces an attacker or bot to attack this second layer of protection instead of your actual admin files. Many WordPress attacks are carried out autonomously by malicious software bots. One of the application you can use is latch. For more information on this application you can visit https://latch.elevenpaths.com/, its not only for your WordPress website but can also be used for others too.

Make use of following plugins:
Bulletproof security --> to create strong .htaccess file
Anti-Malware --> to scan the malicious files in the domain
ip blacklist --> to blacklist the ip which tries to do brute force attack


Generate the salt from following link and paste it in wp-config.php file
http://api.wordpress.org/secret-key/1.1/salt/


Summarizing:
1. Making sure your WordPress installation has the latest updates
2. Minimizing the number of plugins you use (and deleting the ones you don’t)
3. Choosing passwords that are difficult to crack
4. Performing regular data backups
5. Protecting your WordPress using .htaccess


For more information please visit following links
http://codex.wordpress.org/Hardening_WordPress
http://www.firedaemon.com/blog/wordpress-hardening-guide
http://thematosoup.com/wordpress-security-htaccess/