Some Shell Scripts

Shell Script to add zone to DNS server.

NS1 =
NS2 =

# check to see if the script is being run as root or not
grep=`which grep`
rndc=`which rndc`
if [ "$(id -u)" != "0" ]; then
echo "You must be root in order to run this script. You are `whoami`."
exit 1
# if this is a cPanel server, exit the script as a DNS zone can be created from WHM
if [ -d "/usr/local/cpanel" ]; then
echo "This is a cPanel box. You can create the DNS zone from WHM."
exit 1;
# if this is a Plesk server, exit the script as the DNS zone can be created from Plesk itself
elif [ -d "/usr/local/psa" ]; then
echo "This is a Plesk box. You can create the DNS zone from the Plesk Control Panel."
exit 1;
echo "Please enter the domain name"
read domain
echo "Please enter the IP address for the domain"
read ip
test=`echo "${ip}." | $grep -E "([0-9]{1,3}\.){4}"`
if [ "$test" ]
echo "$ip" | nawk -F. '{
if ( (($1>=0) && ($1<=255)) &&    (($2>=0) && ($2<=255)) &&    (($3>=0) && ($3<=255)) &&    (($4>=0) && ($4<=255)) ) { print($0 " is a valid IP address. Using this IP." ); } else { print($0 ": Please specify a correct IP address." ); exit 1; } }' else echo "${ip} is not a valid IP address, exiting script!" exit 1; fi fi //echo "The zone file for the domain $domain will be created using $ip." //admin=$3 //echo "Please enter the administrator for this domain's DNS in a form" //read admin //ns1=$4 //echo "Please enter the primary nameserver for $domain" //read ns1 //ns2=$5 //echo "Please enter the secondary nameserver for $domain" //read ns2 # ok, so enough with the chit-chat, let's move on to the DNS stuff serial=`date +%Y%m%d00` folder=`echo $domain|cut -c1` mkdir /var/named/$folder touch /var/named/$folder/$ echo -e "\$ORIGIN ." >> /var/named/$
echo -e "\$TTL 600     ; 10 minutes" >> /var/named/$folder/$
echo "$domain   IN     SOA    ns1.$domain. (" >> /var/named/$folder/$
echo "               $serial    ; serial, todays date + todays serial" >> /var/named/$folder/$
echo "               7200           ; refresh, seconds" >> /var/named/$folder/$
echo "               3600            ; retry, seconds" >> /var/named/$folder/$
echo "               43200         ; expire, seconds" >> /var/named/$folder/$
echo "               3600 )            ; minimum, seconds" >> /var/named/$folder/$
echo "                  IN       A    $ip" >> /var/named/$folder/$
echo "                  IN       NS" >> /var/named/$folder/$
echo "                  IN       NS" >> /var/named/$folder/$
echo "                  IN       MX    5 mail.$domain." >> /var/named/$folder/$
echo -e "\$ORIGIN $domain." >> /var/named/$folder/$
echo "mail.$domain. IN     A     $ip" >> /var/named/$folder/$
echo "www           IN     CNAME $domain." >> /var/named/$folder/$
echo "ftp           IN     A     $ip" >> /var/named/$folder/$
echo "sql           IN     A     $ip" >> /var/named/$folder/$
echo "ns1           IN     A     $ip" >> /var/named/$folder/$
echo "ns2           IN     A     $ip" >> /var/named/$folder/$
echo "Done creating DNS zone, adding the zone to named.conf in file"
echo "zone \"$domain\" IN {" >> /etc/named/
echo "     type master;" >> /etc/named/
echo "     file \"/var/named/$folder/$\";" >> /etc/named/
echo "     allow-transfer {" >> /etc/named/
echo ";" >> /etc/named/
echo "     };" >> /etc/named/
echo "};" >> /etc/named/
echo "Zone addded to named.conf. Restarting rndc & named"
sleep 2
$rndc reload
/etc/init.d/named restart
echo "All done"

Script to check if IP is blacklisted

# -- $Id: blcheck.xml,v 1.8 2007/06/17 23:38:00 j65nko Exp $ --

#*/15 * * * * sh /root/|mail -s "Spam Report in 15 Min"
#*/15 * * * * sh /root/|mail -s "Spam Report in 15 Min"

# Check if an IP address is listed on one of the following blacklists
# The format is chosen to make it easy to add or delete
# The shell will strip multiple whitespace


# simple shell function to show an error message and exit
#  $0  : the name of shell script, $1 is the string passed as argument
# >&2  : redirect/send the message to stderr

  echo $0 ERROR: $1 >&2
  exit 2

# -- Sanity check on parameters
[ $# -ne 1 ] && ERROR 'Please specify a single IP address'

# -- if the address consists of 4 groups of minimal 1, maximal digits, separated by '.'
# -- reverse the order
# -- if the address does not match these criteria the variable 'reverse will be empty'

reverse=$(echo $1 |
  sed -ne "s~^\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\)$~\4.\3.\2.\1~p")

if [ "x${reverse}" = "x" ] ; then
      ERROR  "IMHO '$1' doesn't look like a valid IP address"
      exit 1

# Assuming an IP address of as parameter or argument

# If the IP address in $0 passes our crude regular expression check,
# the variable  ${reverse} will contain
# In this case the test will be:
#   [ "x44.33.22.11" = "x" ]
# This test will fail and the program will continue

# An empty '${reverse}' means that shell argument $1 doesn't pass our simple IP address check
# In that case the test will be:
#   [ "x" = "x" ]
# This evaluates to true, so the script will call the ERROR function and quit

# -- do a reverse ( address -> name) DNS lookup
REVERSE_DNS=$(dig +short -x $1)

echo IP $1 NAME ${REVERSE_DNS:----}

# -- cycle through all the blacklists
for BL in ${BLISTS} ; do

    # print the UTC date (without linefeed)
    printf $(env TZ=UTC date "+%Y-%m-%d_%H:%M:%S_%Z")

    # show the reversed IP and append the name of the blacklist
    printf "%-40s" " ${reverse}.${BL}."

    # use dig to lookup the name in the blacklist
    #echo "$(dig +short -t a ${reverse}.${BL}. |  tr '\n' ' ')"
    LISTED="$(dig +short -t a ${reverse}.${BL}.)"
    echo ${LISTED:----}


# --- EOT ------

Posted in Linux, Shell Script | Leave a comment

Monitor linux services using bash script

# Vi

run=`ps ax | grep /usr/local/apache/bin/httpd | grep -v grep | cut -c1-5 | paste -s -`
if [ “$run” ];
echo “apache is running” > /home/admin/check_httpd.log
/usr/local/apache/bin/apachectl -k restart
mail -s “Apache server restarted by check-httpd script ” admin [at]adminlogs[dot]info < /usr/local/apache/logs/error.log

Or ( only for apache )

# Vi

cd /tmp
if [ $? -gt 0 ]; then
/usr/local/apache/bin/apachectl -k restart
mail -s “Apache server restarted by check-httpd script ” admin [at]adminlogs[dot]info < /usr/local/apache/logs/error.log

$? contains the return code of the last executed process. -gt means greater than. Usually programs return zero on success or something else on failure

Add the script to crontab ( It will check the status in every 5 minutes )

*/5 * * * * /bin/bash

Its worked fine and now I have no worry about that website and getting good sleep :)

Posted in Apache, Linux, Optimize, Shell Script | Leave a comment

CentOs Fix for Bash Bug ( CVE-2014-6271 & CVE-2014-7169 )

Bash, aka the Bourne-Again Shell, has a newly discovered security hole which has been officially documented as CVE-2014-6271 & CVE-2014-7169. And, for many Unix or Linux Web servers, it’s a major problem.

The flaw involves how Bash evaluates environment variables. With specifically crafted variables, a hacker could use this hole to execute shell commands. This, in turn, could render a server vulnerable to ever greater assaults.


After couple of days trouble today we got a fix from Centos for the so famous bash security issue ( For known loop holes

CVE-2014-6271 & CVE-2014-7169 )

CentOS 5 Fix :-

* i386:

( sha256sum ) 9755e86ad8536c908f95340be308190b52989bfa0d9268a461c40a3f0d493bc7 : bash-3.2-33.el5_10.4.i386.rpm

* x86_64:

( sha256sum) b1e14edd0d675c6fb0be64cb875fbd9fac208a58e427ea32f373c9359b35642c : bash-3.2-33.el5_10.4.x86_64.rpm

CentOS 6 Fix: -

* x86_64:

* i386:

Test Output : -

[root@ ~]# rpm -qa | grep bash


[root@ ~]# env X='() { (a)= >\’ bash -c “echo date”;

bash: X: line 0: syntax error near unexpected token `=’

bash: X: line 0: `X () { (a)= >\’

bash: error importing function definition for `X’


[root@ ~]#

* After updating to latest bash rpm.

[root@ ~]# rpm -qa | grep bash


[root@ ~]#

[root@ ~]# env X='() { (a)= >\’ bash -c “echo date”;


[root@ ~]#


Posted in Linux | Leave a comment

shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

Today I saw an interesting error ,while restarting apache
]# /etc/init.d/httpd restart
shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
Stopping httpd: [ OK ]
Starting httpd: shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
[ OK ]
may be you also face this or already faced.
Don’t surprise …Just do a  ” cd  / ”   , or  cd  to any direcotry ..  it will fix the error !!

This happen as the current working directory from which the command was fired does not exits on the server.

Posted in Linux | Leave a comment

Heart Bleeding

One of the Google Security Engineer ( Thanks for Neel Mehta of Google Security and team of security engineers (Riku, Antti and Matti) at Codenomicon for discovering the bug)  reported a serious bug with current openssl  on 3rd of April 2014 . ( TLS heartbeat read overrun (CVE-2014-0160) )

As per openssl , Only 1.0.1 and 1.0.2-beta releases of OpenSSL are affected including 1.0.1f and 1.0.2-beta1. And its advised to upgrade to OpenSSL 1.0.1g ( )  to fix this issue or recompile affected versions with the option -DOPENSSL_NO_HEARTBEATS.

You may need to recompile other services which are associated with openssl like Apache , nginx , php etc . Also its better to renew your ssl cert’s to make sure everything is safe/fine.

How to Check Whether your server/website is affected or not ?

Posted in Linux | Leave a comment

POODLE: SSLv3.0 vulnerability

What is POODLE ?

POODLE stands for Padding Oracle On Downgraded Legacy Encryption. This vulnerability allows a man-in-the-middle attacker to decrypt ciphertext using a padding oracle side-channel attack.

How to Fix ?

At present there is no working patch for this bug . So that Admin needs to manually disable SSLv3 on their servers .

Disable SSLv3 – Apache

1) Add ” SSLProtocol All -SSLv2 -SSLv3 ” to httpd.conf

2) Restart apache service .

Disable SSLv3 – Nginx

1) Add ” ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ” to nginx.conf under ssl section .

2) Restart nginx service .

Disable SSLv3 – PostFix

1) change smtpd_tls_mandatory_protocols to ” smtpd_tls_mandatory_protocols =!SSLv2,!SSLv3 ”

2) Restart postfix server .

Disable SSLv3 - Weblogic

Start weblogic with the following JVM option ” ”

How to Diagnose ?

# openssl s_client -connect localhost:443 -ssl3

==> If you have already disabled sslv3 , then the output will be as follows


20888:error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure:s3_pkt.c:1053:SSL alert number 40

20888:error:1409E0E5:SSL routines:SSL3_WRITE_BYTES:ssl handshake failure:s3_pkt.c:530:

==> If you are not disabled the sslv3 and you are getting the following output , then your server is vulnerable to POODLE !!.


depth=0 /C=SomeCountry/ST=SomeState/L=Some Place/O=Example Pte Ltd/OU=Systems/CN=453232-example/

verify error:num=18:self signed certificate

verify return:1

depth=0 /C=SomeCountry/ST=SomeState/L=Some Place/O=Example Pte Ltd/OU=Systems/CN=453232-example/

verify return:1

Certificate chain

0 s:/C=SomeCountry/ST=SomeState/L=Some Place/O=Example Pte Ltd/OU=Systems/CN=453232-example/

i:/C=SomeCountry/ST=SomeState/L=Some Place/O=Example Pte Ltd/OU=Systems/CN=453232-example/


If you manage an entire data center or a corporate intranet, the problem is a little harder to solve than disabling SSL 3.0 in a browser. Regardless of the mitigation strategy you choose, you need to know which of your servers are currently running SSL 3.0. To that end, here a couple of quick scripts based on open source tools that will help you take control of the situation.

The first script,, checks a single target for the presence of SSL 3.0 ciphers. The results will be similar to the following:

# 443

Testing for support of SSL3.0 ciphers…

NULL-MD5…NO (ssl handshake failure)

NULL-SHA…NO (ssl handshake failure)

EXP-RC4-MD5…NO (ssl handshake failure)

RC4-MD5…NO (ssl handshake failure)

RC4-SHA…NO (ssl handshake failure)

EXP-RC2-CBC-MD5…NO (ssl handshake failure)

IDEA-CBC-SHA…NO (no cipher match)

EXP-DES-CBC-SHA…NO (ssl handshake failure)

DES-CBC-SHA…NO (ssl handshake failure)

DES-CBC3-SHA…YES – SSL 3.0 cipher detected

EXP-DH-DSS-DES-CBC-SHA…NO (no cipher match)

DH-DSS-DES-CBC-SHA…NO (no cipher match)

DH-DSS-DES-CBC3-SHA…NO (no cipher match)

EXP-DH-RSA-DES-CBC-SHA…NO (no cipher match)

DH-RSA-DES-CBC-SHA…NO (no cipher match)

DH-RSA-DES-CBC3-SHA…NO (no cipher match)

EXP-DHE-DSS-DES-CBC-SHA…NO (no cipher match)

DHE-DSS-CBC-SHA…NO (no cipher match)

DHE-DSS-DES-CBC3-SHA…NO (no cipher match)

EXP-DHE-RSA-DES-CBC-SHA…NO (no cipher match)

DHE-RSA-DES-CBC-SHA…NO (no cipher match)

DHE-RSA-DES-CBC3-SHA…NO (no cipher match)

EXP-ADH-RC4-MD5…NO (ssl handshake failure)

ADH-RC4-MD5…NO (ssl handshake failure)

EXP-ADH-DES-CBC-SHA…NO (ssl handshake failure)

ADH-DES-CBC-SHA…NO (ssl handshake failure)

ADH-DES-CBC3-SHA…NO (ssl handshake failure)

SSL3 ciphers were detected on server

The second script,, allows you to test an entire network range. Using a network range specified in CIDR notation or a format compatible with nmap, the script detects and checks the standard and alternate ports commonly used for HTTPS on all hosts in the network range. Results will be similar to the following:

# ./

Beginning test… please be patient… – SSL3.0 ciphers NOT supported – SSL3.0 ciphers NOT supported – SSL3.0 ciphers NOT supported – SSL3.0 ciphers supported – SSL3.0 ciphers supported

How you decide to mitigate the risk is a decision you will have to make.

Posted in Linux | Leave a comment

Setup mysql master slave replication over ssl

Master Server :

Slave Server :

Confirm your mysql server is compiled/enabled to support ssl connections using the following command

# mysql -u root -p

mysql > show variables like ‘%ssl%’ ;

If you are getting an output some thing like as follows then you can confirm mysql is compiled to support ssl connections

mysql> show variables like ‘%ssl%’;

| have_openssl | DISABLED |

| have_ssl | DISABLED |

The above shows that mysql is compiled with ssl support but it not enabled in the configuration .

Create Certificates

# cd /var/lib/mysql

# mkdir ssl

>>> Create CA Certificate

# openssl genrsa 2048 > ca-key.pem
# openssl req -new -x509 -nodes -days 1000 -key ca-key.pem > ca-cert.pem

>>> Create Server Certificate

# openssl req -newkey rsa:2048 -days 1000 -nodes -keyout server-key.pem > server-req.pem
# openssl x509 -req -in server-req.pem -days 1000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 > server-cert.pem

>>> Create Client Sertificate .

# openssl req -newkey rsa:2048 -days 1000 -nodes -keyout client-key.pem > client-req.pem
# openssl x509 -req -in client-req.pem -days 1000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 > client-cert.pem

Copy the keys to Slave server

# scp ca-cert.pem client-cert.pem client-key.pem root@

Master Side configuration

# vi /etc/my.cnf

#bind-address =






server-id = 1

log_bin = /var/lib/mysql/mysql-bin.log

Note that server id should be unique here for master its 1.

Restart mysql and confirm now ssl values are showing properly in ” mysql > show variables like ‘%ssl%’ ; ”

# mysql –u root –p

GRANT all privileges ON *.* TO replication@'' IDENTIFIED BY 'password' REQUIRE SSL;

Slave Side Configuration

# vi /etc/my.cnf

bind-address =









check master status on the master node

mysql > show master status ;

| File | Position | Binlog_do_db | Binlog_ignore_db | +

| mysql-bin.002 | 80600 | mydatabase | | +


Update the log location and Position on Slave

Msql > slave stop;

Mysql > CHANGE MASTER TO MASTER_HOST='', MASTER_USER='replication', MASTER_PASSWORD='password', MASTER_LOG_FILE=' mysql-bin.002', MASTER_LOG_POS=80600, MASTER_SSL=1, MASTER_SSL_CA = '/var/opt/mysql/ssl/ca-cert.pem', MASTER_SSL_CERT = '/var/opt/mysql/ssl/client-cert.pem', MASTER_SSL_KEY = '/var/opt/mysql/ssl/client-key.pem';

Mysql > slave start ;

Mysql > show slave status \G ;

*************************** 1. row ***************************

Slave_IO_State: Waiting for master to send event


Master_User: replication

Master_Port: 3306

Connect_Retry: 60

Master_Log_File: mysql-bin.000003

Read_Master_Log_Pos: 12345100

Relay_Log_File: mysql-relay-bin.000002

Relay_Log_Pos: 11381900

Relay_Master_Log_File: mysql-bin.000003

Slave_IO_Running: Yes

Slave_SQL_Running: Yes

Replicate_Do_DB: mydatabase


The above lines which are marked in green shows that replication is working fine from master to slave.

Posted in Linux, MySQL | Leave a comment

SPAM Whitelisting

Whitelisting can help you to get your emails reach inbox instead of spam folder,

i will teach you now how to whitelist your self on some spam filter systems and some email providers.

First of all you must have a domain which have valid rDNS with your server, and you must have a web site on your domain. This may takes you some time, but i highly recommend you to make a fake marketing agency web site, i know this may sounds unethical and, maybe even, illegal ( okay, it’s hard to believe it could illegal since there is tons of hosting companies, web design agency and so on, which are not registered anywhere ), and you can make some simple looking web site explaining that you are providing email marketing services to your clients. Make sure you make it clear that you have a ZERO tolerance to spam and that all emails you have in your lists are generated by you, bla bla, opt in, bla bla, cpan spam, bla bla, just google some email marketing agency and see what they say :-). This will helps you A LOT to get whitelisted almost anywere.

Deciphering SMTP Errors

The SMTP errors that Gmail provides are key to mapping your path to getting off of Gmail’s blacklist.

For email delivery, the two main error codes are 421 and 550 errors.

421 Errors

421 errors are often temporary blocks. Most email servers will attempt to resend the email if they get a 421 error. If you quickly correct a spam or email flood issue, these blocks may resolve automatically. Left unchecked, Google may decide to block your email entirely.

550 Errors

550 errors are permanent failures. If you scan your logs for 550 errors from Gmail, they will often include links and additional information.

If you have 550 errors, you will likely need to take action before Gmail will remove your server IP address.

Requesting Blacklist Removal

If you do not fix the problem first, your removal request will likely be ignored. You don’t want to give the Gmail team any reason not to approve your request. So make sure everything is in order.

Just so you know …  Google does not want you to contact them.

Their forms are buried behind a series our questions that typically lead nowhere. Most of the time you will start with Gmail’s “My domain is having delivery problems with Gmail” form. As you answer the questions, you will typically end up in a dead-end.

However, with the right sequence of answers, you can eventually wind your way to:

Report a delivery problem between your domain and Gmail.

This is where the action happens.   Complete the form in detail but do not be overly verbose.

Once submitted, you can expect it to take 3-7 days to process. Often, you will not hear back from Gmail. Your email will simply start flowing again – provided you fixed the reason you were blacklisted in the first place.

Bulk Senders

Sometimes you have a lot of email – legitimate email – to send. Google does not clearly define what is bulk email. Typically, you will see an SMTP error code in the 400 series, such as:

421, "4.7.0", Our system has detected an unusual rate of unsolicited mail originating from your IP address. 

To protect our users from spam, mail sent from your IP address has been temporarily blocked. 

Review our Bulk Email Senders Guidelines.


If you receive this message, be sure to review Google’s Bulk Sender Guidelines and then complete the Bulk Sender Contact Form.


URL :…

It’s very easy to get on their whitelist, but if they get tons of spam complains about your message, you will be removed to blacklist list very fast ^^


URL :…er/bulkv2.html

It’s hard to get whitelisted on Yahoo, but give it a try.


URL :…rpp&ct=eformts

SPAM FILTERS WHERE YOU CAN ASK FOR WHITELISTENING – only with invite, so it’s almost impossible to get there, but it’s worth if you can

Basically here is the list of, almost, all spam filter systems, so Google their unblacklistening or whitelistening pages :


Tricks to Getting Removed

We work on email delivery issues nearly daily. In our experience, if you do not fix these issues, your chances of getting removed from Gmail or any other blacklist is minimal.

  • Reverse DNS Must Resolve to a Valid Hostname
  • Your Server’s Hostname Must Have a DNS ‘A’ Record
  • Do not blindly forward email to Gmail
  • Make Sure DKIM/SPF are correct
  • Stop the spamming!

You must make sure that whatever triggered the listing in the first place is stopped. If you  do not, you will simply be re-listed.

Posted in Exim, Mail server, Postfix | Leave a comment

How To Rotate IP Address Pool In Linux (Redhat / Centos / Ubuntu / Debian)

You can rotate your Server IP address pool in Linux server by using iptable NAT Postrouting.

I assume you have 8 public IP addresses (x.x.x.1 TO x.x.x.8) configure on Linux postfix server.

Now we rotate only SMPT (port no. 25) traffic, every time SMTP services use different IP address. All 8 IP rotate automatically when your mail server send mail to other user, Every time Linux mail server generate different source address.


# iptables -t nat -I POSTROUTING -m state --state NEW -p tcp --dport 25 -o eth0 -m statistic --mode nth --every 8 --packet 0 -j SNAT --to-source  x.x.x.1

# iptables -t nat -I POSTROUTING -m state –state NEW -p tcp –dport 25 -o eth0 -m statistic –mode nth –every 8 –packet 0 -j SNAT –to-source x.x.x.2

# iptables -t nat -I POSTROUTING -m state –state NEW -p tcp –dport 25 -o eth0 -m statistic –mode nth –every 8 –packet 0 -j SNAT –to-source x.x.x.3

# iptables -t nat -I POSTROUTING -m state –state NEW -p tcp –dport 25 -o eth0 -m statistic –mode nth –every 8 –packet 0 -j SNAT –to-source x.x.x.4

# iptables -t nat -I POSTROUTING -m state –state NEW -p tcp –dport 25 -o eth0 -m statistic –mode nth –every 8 –packet 0 -j SNAT –to-source x.x.x.5

# iptables -t nat -I POSTROUTING -m state –state NEW -p tcp –dport 25 -o eth0 -m statistic –mode nth –every 8 –packet 0 -j SNAT –to-source x.x.x.6

# iptables -t nat -I POSTROUTING -m state –state NEW -p tcp –dport 25 -o eth0 -m statistic –mode nth –every 8 –packet 0 -j SNAT –to-source x.x.x.7

# iptables -t nat -I POSTROUTING -m state –state NEW -p tcp –dport 25 -o eth0 -m statistic –mode nth –every 8 –packet 0 -j SNAT –to-source x.x.x.8

So as per requirement of services you can rotate your whole IP address pool or multiple ip address with different different service port number.

Now if you send 8 mail then all 8 mail have different source address and then it roll over again in the sequence of 1 to 8.


Posted in Exim, Linux, Mail server, Plesk, Postfix | Leave a comment