Tar command

Extract an archive to a directory different from the current, use the -C   or --directory, tar option, as in
 
tar -xf archive.tar -C /target/directory 
 
Tar gzip compression
$ tar cvzf archive_name.tar.gz dirname/

Tar bzipped compression
$ tar cvfj archive_name.tar.bz2 dirname/ 

Adding a file or directory to an existing archive using option -r

$ tar rvf archive_name.tar newdir/
Note: You cannot add file or directory to a compressed archive. 

Estimate the tar archive size

The following command, estimates the tar file size ( in KB ) before you create the tar file.
$ tar -cf - /directory/to/archive/ | wc -c
20480

Listing an archive using tar command

View the tar archive file content without extracting using option tvf

You can view the *.tar file content before extracting as shown below.
$ tar tvf archive_name.tar

View the *.tar.gz file content without extracting using option tvzf

You can view the *.tar.gz file content before extracting as shown below.
$ tar tvfz archive_name.tar.gz

dig DNS

# dig -t ANY  example.com

Query from specific dns server

dig -t ANY @dnsserver/ip  example.com

To check which dns server you are using :

cat /etc/resolv.conf

or(i used wifi so couldnt find in resolv.conf and ran below cmd)

nm-tools | grep DNS
==============================================
Display multiline queries
This +multiline option will show you records like the SOA records in a verbose multi-line format with human-readble comments. Here’s a sample of it.
$ dig  hotmail.com +multiline +noall +answer


root@devopserver:/home# dig +nocmd google.com ANY +multiline +noall +answer

ogi.edu.        14390 IN SOA zeal.admin.ogi.edu. hostmaster.admin.ogi.edu. (
                201301181  ; serial
                600        ; refresh (10 minutes)
                900        ; retry (15 minutes)
                3600000    ; expire (5 weeks 6 days 16 hours)
                600        ; minimum (10 minutes)
                )
ogi.edu.        14390 IN NS fork.admin.ogi.edu.
ogi.edu.        14390 IN NS dns1.ohsu.edu.
ogi.edu.        14390 IN NS zeal.admin.ogi.edu.
ogi.edu.        14390 IN NS cse.ogi.edu.
ogi.edu.        14390 IN A 129.95.20.4
ogi.edu.        14390 IN MX 5 anise.csee.ogi.edu.
ogi.edu.        14390 IN MX 15 hermes.admin.ogi.edu.
ogi.edu.        14390 IN MX 3 castor.bme.ogi.edu.
..............
+nocmd is used to supress display of dig version numbers etc.
---------------------------------------------------------------------------------------------------------------------------------
Reverse lookup example
----------------------------------------------------------------------------------------------------------------------------


root@devops-server:/home/devops1# dig +nocmd -x 8.8.8.8 +noall +answer
#use -short for short answer


------------------------------------------------------------------------------------------------------------------------------------
Other examples
------------------------------------------------------------------------------------------------------------------------------------
Query from file  eg. names.txt
$ dig -f names.txt +noall +answer
redhat.com.             60      IN      A       209.132.183.81
centos.org.             60      IN      A       72.232.194.162


$cat names.txt
redhat.com
centos.org

-------------------------------------------------------

dig +nocomments www.cyberciti.biz
+++++++++++++++++++++++++++++++++++++++++++++++
Custom script
++++++++++++++++++++++++++++++++++++++++++++++
[sshadmin@mx12 ~]$ cat digg.sh 
#!/bin/bash
#echo "Enter the domain name:"
printf "\n"
read -p "Enter the domain name: " fqdn
printf "\n"
echo "------------Query Result for NS ------------------"
printf "\n"
/usr/bin/dig +nocmd $fqdn NS  +noall +answer
printf "\n"
printf "\n"
echo "------------Query Result for A Record---------------"
printf "\n"
/usr/bin/dig +nocmd $fqdn  +noall +answer
printf "\n"
echo "------------MX Query Result------------------"
printf "\n"
printf "please wait for mx " 
sleep 1
printf "."
sleep 1
printf "."
sleep 1
printf "\n"
printf "\n"
/usr/bin/dig +nocmd $fqdn MX +noall +answer
printf "\n"
 
 
#use any for all in one
dig +nocmd google.com ANY +noall +answer 

Remove web search in Ubuntu dash board search

Save and Run below script ============================================================ #!/bin/bash GS="/usr/bin/gsettings" CCUL="com.canonical.Unity.lenses" # Figure out the version of Ubuntu that you're running V=`/usr/bin/lsb_release -rs` # The privacy problems started with 12.10, so earlier versions should do nothing if awk "BEGIN {exit !($V < 12.10 || $V >= 14.10)}"; then echo "Good news! This version of Ubuntu is not known to invade your privacy." else # Check Canonical schema is present. Take first match, ignoring case. SCHEMA="`$GS list-schemas | grep -i $CCUL | head -1`" if [ -z "$SCHEMA" ] then printf "Error: could not find Canonical schema %s.\n" "$CCUL" 1>&2 exit 1 else CCUL="$SCHEMA" fi # Turn off "Remote Search", so search terms in Dash don't get sent to the internet $GS set $CCUL remote-content-search none # If you're using earlier than 13.10, uninstall unity-lens-shopping if [ $V \< 13.10 ]; then sudo apt-get remove -y unity-lens-shopping # If you're using a later version, disable remote scopes else $GS set $CCUL disabled-scopes \ "['more_suggestions-amazon.scope', 'more_suggestions-u1ms.scope', 'more_suggestions-populartracks.scope', 'music-musicstore.scope', 'more_suggestions-ebay.scope', 'more_suggestions-ubuntushop.scope', 'more_suggestions-skimlinks.scope']" fi; # Block connections to Ubuntu's ad server, just in case if ! grep -q "127.0.0.1 productsearch.ubuntu.com" /etc/hosts; then echo -e "\n127.0.0.1 productsearch.ubuntu.com" | sudo tee -a /etc/hosts >/dev/null fi echo "All done. Enjoy your privacy." fi

Incremental Backup using tar (Tape Archive)

tar --listed-incremental=snapshot1.file -cvzf backup.1.tar.gz /path/to/dir

Check which program using particular port

if port no# is 631 
                                 
sudo lsof –i:631 –n –P  
                                         
 
-n option prevent auto conversion of ip to name .
-P option prevent auto conversion of port number to port name. 
 
COMMAND   PID USER   FD   TYPE  DEVICE  SIZE/OFF  NODE NAME
cupsd         776 root   10u  IPv6   9353       0t0  TCP [::1]:631 (LISTEN)
cupsd         776 root   11u  IPv4   9354       0t0  TCP 127.0.0.1:631 (LISTEN)
cups-brow      953 root    8u  IPv4   9930      0t0  UDP *:631 

If you want a list of all open TCP ports and the programs/processes associated you can type:

$ sudo lsof -i -n -P | grep TCP      
 ~~~~~~~~~~~~~~~~~~~~~~

lsyncd live synchronization

Centos 6.5
yum -y install lua lua-devel pkgconfig gcc asciidoc

Important : Be sure to manually check the destination directory on the slave server. If you have NFS or CloudFuse mounts, these could end up wiped by the lsync process.

Note : Lsyncd version 2.0.4 has a known issue with permissions, see the following bug reports. Always make sure you install either 2.0.7 (stable) or 2.1.4+ (latest)

yum install lsyncd    --as of 2014/june it will install lsyncd 2.1.4

Check SELINUX and set to permissive
+++++++++++++++++++++++++++++++++++++++++++++++++
for yum installed
+++++++++++++++++++++++++++++++++++++++++++++++++++
# cat /etc/sysconfig/lsyncd 
# Keep the space there for systemd. Don't nest variables without
# changing the systemd service file to use: /usr/bin/sh -c 'eval XXXX'

LSYNCD_OPTIONS="-pidfile /var/run/lsyncd.pid /etc/lsyncd.conf"

#LSYNCD_OPTIONS=" "
 
                                                                             
 [root@www ~]#
cp /usr/share/doc/lsyncd-2.1.4/examples/lrsync.lua  /etc/lsyncd.conf

root@web02 [/etc]# cat /etc/lsyncd.conf 
settings = {
 statusFile = "/tmp/lsyncd.stat",
 statusInterval = 1,
}
sync{
 default.rsync,
 source="/home/",
 target="172.69.2.52:/home/",
 excludeFrom="/etc/excludelsync",
 rsync = {
compress = true,
acls = true,
verbose = true,
owner = true,
group = true,
perms = true,
rsh = "/usr/bin/ssh -p 22 -o StrictHostKeyChecking=no"
        }
}
sync{
        default.rsync,
        source="/etc/httpd/",
        target="172.69.2.52:/etc/httpd/",
        excludeFrom="/etc/excludelsync",
        rsync = {
compress = true,
acls = true,
verbose = true,
owner = true,
group = true,
perms = true,
rsh = "/usr/bin/ssh -p 22 -o StrictHostKeyChecking=no"
        }
}
 
cat /etc/excludelsync 
*.log
.cp*
logs
 
                                                                           
 
Ubuntu 
sudo apt-get update
sudo apt-get install lsyncd
 
ls /usr/share/doc/lsyncd/example  ...refer to some files for example
 
use file =>lrsync.lua
 
Local Transfer
 
sudo mkdir /var/log/lsyncd
touch /var/log/lsyncd/lsyncd.{log,status}
 
sudo mkdir /etc/lsyncd
 
sudo nano /etc/lsyncd/lsyncd.conf.lua 

settings = {
 logfile = "/var/log/lsyncd/lsyncd.log",
 statusFile = "/var/log/lsyncd/lsyncd.status"
}
sync {
 default.rsync,
 source = "/source/to/copy",
 target = "/dest",
 ##rsyncOpts = {"rsync option1", "rsync option2", "rsync option3"}
}

For remote(use public key passwordless login for master to slave)
=================
settings = {
        logfile = "/var/log/lsyncd/lsyncd.log",
        statusFile = "/var/log/lsyncd/lsyncd.status"
}

sync {
        default.rsyncssh,
        source = "/source/to/copy",
        host = "remote_mirror_ip_address",
        targetdir = "/remotesync"
}
==========================Example config=================================
settings{
 logfile = "/tmp/lsyncd.log",
 statusFile = "/tmp/lsyncd.stat",
 statusInterval = 2,
}
sync{
 default.rsync,
 source="/home/",
 target="172.69.2.52:/home/",
 rsync = {
binary = "/usr/bin/rsync",
compress = true,
acls = true,
verbose = true,
rsh = "/usr/bin/ssh -p 22 -o StrictHostKeyChecking=no"
        }
}
sync{
        default.rsync,
        source="/etc/httpd/",
        target="172.69.2.52:/etc/httpd/",
        rsync = {
binary = "/usr/bin/rsync",
compress = true,
acls = true,
rsh = "/usr/bin/ssh -p 22 -o StrictHostKeyChecking=no"        
 }
}
sync{
        default.rsync,
        source="/test11/",
        target = "root@172.69.2.52:/test11/",
        rsync = {
binary = "/usr/bin/rsync",
compress = true,
acls = true,
rsh = "/usr/bin/ssh -p 22 -o StrictHostKeyChecking=no"
}
}  

=============lsyncd Error: Terminating since out of inotify watches=============
 
# pwd
/proc/sys/fs/inotify
root@web01 [/proc/sys/fs/inotify]# ls
./  ../  max_queued_events  max_user_instances  max_user_watches 
#bydefault value in max_user_watches is = 8192 
#echo 65535 > /proc/sys/fs/inotify/max_user_watches
# cat /proc/sys/fs/inotify/max_user_watches          
65536 
To make the change permanent, edit the file /etc/sysctl.conf and add this line to the end of the file:
fs.inotify.max_user_watches=65535
If this server is a VPS and it is running in a OpenVZ container then you are NOT allowed to modify any kernel parameter of that container. and you will get below error
root@vps01 [/proc/sys/fs/inotify]# sysctl -w fs.inotify.max_user_watches=65535 
error: permission denied on key 'fs.inotify.max_user_watches'
change it from host

mysql db server replicationmodel ktv proj

Minimal centos6.4 
(First off allow mysql port 3306 via iptables) 

iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT
OR
iptables -A INPUT -p tcp -s 0/0 --sport 1024:65535 -d 202.54.1.20 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s 192.168.213.10(put slave ip for slave) --sport 3306 -d 0/0 --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT
OR
(@Master)
iptables -A INPUT -p tcp -s 192.168.140.11 --sport 1024:65535 -d 192.168.213.10 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s 192.168.213.10 --sport 3306 -d 192.168.213.11 --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT

 
One-server process that runs per slave server connected..shows up as binary log dump process thats usually bin-log dump process.Hence binary logging must be enabled on master server to allow replication.
At slave side.there are two process
  1. I/O Thread(moves data/connects to Master and downloads the updated data to a temp log  file called RELAY LOG file at slave system)
  2. SQL Thread(processes sql statements store in relay log  )
Once replication is up and running
Relay Log contains file
  1. host_name-relay-bin.nnnnn 
  2. host_name-relay-bin.index
 these files are created and removed once updates are commited on slave.
Replication is asynchronous.Good for web apps(read intensive(read are fast than writes))

#yum install mysql-server

----------------------------------------------------------------------------------------------------
vim /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
server-id =10                            ##server-id can be 1 to 2^32 -1
log-bin
                             
##enable binary logging ::to give specific name type log-bin = give-name

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

#service mysqld restart
-------------------------------------------------------------------------------------------------------
#mysql -p
<password>
NOTE:  i had some problems with syncing the msyqld-bin .xxx and index number so make sure of those with command show master status like below; ( use  command :  reset master ;  //to reset indexes)

mysql> show master status;
+-------------------+----------+--------------+------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+-------------------+----------+--------------+------------------+
| mysqld-bin.000002 |      106 |              |                  |
+-------------------+----------+--------------+------------------+

[root@master ~]# ls /var/lib/mysql/
ibdata1      ib_logfile1        master-bin.000002  mysql              mysqld-bin.000002  mysql.sock
ib_logfile0  master-bin.000001  master-bin.index   mysqld-bin.000001  mysqld-bin.index
---------------------------------------------------------------------------------------------------
mysql> create database contact;
Query OK, 1 row affected (0.00 sec)

mysql> use contact;
Database changed
mysql> create table person(id int NOT NULL AUTO_INCREMENT,name varchar(55),phone int,PRIMARY KEY (id));
Query OK, 0 rows affected (0.01 sec)

mysql> insert into person values (null,'ramesh','9851888899');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> insert into person values (null,'suresh','9841888899');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> select * from person;
+----+--------+------------+
| id | name   | phone      |
+----+--------+------------+
|  1 | ramesh | 2147483647 |
|  2 | suresh | 2147483647 |
+----+--------+------------+
2 rows in set (0.00 sec)
---------------------------------------------------------------------------------------------------
Create Replication account :
GRANT REPLICATION SLAVE ON   *.*  TO 'user1'@'%' IDENTIFIED by 'p@ssword123';
[[% means user1 can be at any host]]
#for replicating particular db eg. contactdb  use contact.*  instead of  -->*.*  (i,e all db's)

 To make 'user1' load data/table(optional)

GRANT SELECT,SUPER,RELOAD ON *.*  TO 'user1'@'%' IDENTIFIED by 'p@ssword123';
 Check:
mysql> show grants for user1;+-----------------------------------------------------------------------------------------------------------------------------------------+
| Grants for user1@%                                                                                                                      |
+-----------------------------------------------------------------------------------------------------------------------------------------+
| GRANT SELECT, RELOAD, SUPER, REPLICATION SLAVE ON *.* TO 'user1'@'%' IDENTIFIED BY PASSWORD '*45DE09574DD7395CB49B9E7AE24CC93A18AED04D' |
+-----------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

Flush tables and block all writes during replication configuratoin:
mysql> FLUSH TABLES WITH READ LOCK;
Query OK, 0 rows affected (0.00 sec)
//Assuming connections are still open to db :
making  a binary backup of database directory;
[root@master ~]# tar -cvf contact.tar /var/lib/mysql/contact





Now copy copy the backup file contact.tar to slave servers:
[root@master ~]# scp contact.tar root@slave1:/var/lib/mysql/
root@slave1's password:*********
contact.tar

At slave1:  untar the contact.tar file located at /var/lib/mysql/contact.tar  
# tar -xvf contact.tar  


Record the master server binary logfile name and offset
 mysql> show master status;
+-------------------+----------+--------------+------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+-------------------+----------+--------------+------------------+
| mysqld-bin.000002 |      968 |              |                  |
+-------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

#file name= mysqld-bin.000002
#offset = 968 
mysql>unlock tables;

#service mysqld restart

At slave1
vim /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
server-id =100   #should be unique

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

#service mysqld start

in mysql command at slave 1
mysql>CHANGE MASTER TO MASTER_HOST='192.168.213.10',MASTER_USER='user1',MASTER_PASSWORD='p@ssword123',MASTER_LOG_FILE='mysqld-bin.000002',MASTER_LOG_POS=968;

mysql>start slave;
mysql>show slave status;  or show slave status \G;
>show processlist;
Confirm the existence of 'Relay log and index files in data directory :
#ls -ltr /var/lib/mysql/
[root@slave1 ~]# ls -ltr /var/lib/mysql/
total 20512
drwx------. 2 mysql mysql     4096 Apr  9 04:11 mysql
-rw-rw----. 1 mysql mysql  5242880 Apr  9 04:11 ib_logfile1
drwx------. 2 mysql mysql     4096 Apr  9 05:16 contact
-rw-rw----. 1 mysql mysql 10485760 Apr  9 05:47 ibdata1
drwxr-xr-x. 3 root  root      4096 Apr  9 05:48 var
-rw-rw----. 1 mysql mysql  5242880 Apr  9 06:11 ib_logfile0
srwxrwxrwx. 1 mysql mysql        0 Apr  9 06:11 mysql.sock
-rw-rw----. 1 mysql mysql      156 Apr  9 06:25 mysqld-relay-bin.000001
-rw-rw----. 1 mysql mysql       52 Apr  9 06:25 mysqld-relay-bin.index
-rw-rw----. 1 mysql mysql      252 Apr  9 06:25 mysqld-relay-bin.000002
-rw-rw----. 1 mysql mysql       75 Apr  9 06:25 master.info
-rw-rw----. 1 mysql mysql       52 Apr  9 06:25 relay-log.info
mysql-relay-bin.index tells mysql which mysqld-relay-bin-XXX(which accepts updates from master server) is current file..
[root@slave1 mysql]# cat master.info
15
mysqld-bin.000003                    #name of bin file currently in use
246                                          #offset
192.168.213.10    #name of server
user1                   #account
p@ssword123    #password
3306                  #port used
60                  #retrieval interval
0
0
similar info is with relay log ..used in situation like poweroutage etc .. ..
------------------------------------------------------------------------------
When outof sync problem occur to change logfile posiiton or name
--------------------------------------------------------------------------------
mysql> STOP SLAVE; 
Query OK, 0 rows affected (0.00 sec) 

mysql> FLUSH TABLES WITH READ LOCK; 
Query OK, 0 rows affected (0.00 sec) 

mysql> UNLOCK TABLES; 
Query OK, 0 rows affected (0.00 sec) 

mysql> CHANGE MASTER TO MASTER_LOG_FILE='mysqld-bin.000001'; 
Query OK, 0 rows affected (0.00 sec) 

mysql> CHANGE MASTER TO MASTER_LOG_POS=98; 
Query OK, 0 rows affected (0.00 sec) 

mysql> start slave; 
Query OK, 0 rows affected (0.00 sec)





yum lock error ::

    Existing lock /var/run/yum.pid: another copy is running as pid [pid number].
    Another app is currently holding the yum lock; waiting for it to exit...
    
Example :
    [root@server /]# yum install [service name]
    Loaded plugins: fastestmirror
    Existing lock /var/run/yum.pid: another copy is running as pid 20360.
    Another app is currently holding the yum lock; waiting for it to exit...
      The other application is: yum
        Memory :  19 M RSS (396 MB VSZ)
        Started: Sun Mar  6 21:06:51 2011 - 00:29 ago
        State  : Traced/Stopped, pid: 20360
    
Please hit ctrl-c; that’s the key combination to kill any currently running process in a bash shell or terminal.
    Exiting on user cancel.
    
Solution 1:
To remove the pid, please run command rm -f and follow with yum.pid path and [pid number]
    [root@server /]# rm -f /var/run/yum.pid 20360
    
Solution 2:
Find out what is the locking up yum by running:
    [root@server /]# ps aux | grep yum
    
Please take note on the [pid number] of the process and run this command to kill the process:
    [root@server /]# kill -9 [insert pid]

postfix

# Virtual Users And Domains With Postfix, Courier, MySQL And SquirrelMail
___________________________________________________________

A mail server is the computerized equivalent of your friendly neighbourhood mailman. Every email that is sent passes through a series of mail servers along its way to its intended recipient. Although it may seem like a message is sent instantly - zipping from one PC to another in the blink of an eye - the reality is that a complex series of transfers takes place. Without this series of mail servers, you would only be able to send emails to people whose email address domains matched your own - i.e., you could only send messages from one example.com account to another example.com account.
Throughout this document we will be using a number of acronyms to describe things. It will help you (if you've never heard of these before) to know them in advance. Here is the short list with their associated definitions:
MTA - Mail Transfer Agent. We are using Postfix for MTA.
MDA - Mail Delivery Agent. Accepts inbound mail from an MTA and delivers it to the appropriate user on the local machine & we are using Courier as a MDA.
MUA - Mail User Agent. Software used by humans to download mail, upload to an MTA, create, and read mail. Squirrel mail agent will be our MUA.
POP3 - Post Office Protocol. This protocol POP3 allows a client computer to retrieve electronic mail from a POP3 server via a (temporary) TCP/IP or other connection.
IMAP - Internet Message Access Protocol. A protocol allowing a client to access and manipulate electronic mail messages on a server. It permits manipulation of remote message folders (mailboxes), in a way that is functionally equivalent to local mailboxes.
SMTP - Simple Mail Transport Protocol. A server to server protocol, so other protocols (POP3, IMAP etc.) are used to access the messages. The SMTP dialog usually happens in the background under the control of the message transport system, e.g. postfix but it is possible to interact with an SMTP server using telnet to connect to the normal SMTP port, 25. E.g.

Configuration Steps:

Before we start the installation we should make sure that the firewall (iptables) is off (at least for now) and that SELinux is disabled (this is important!).
Remove Iptables (firewall) and disable selinux
[root@mail ~]# iptables –F
[root@mail ~]# service iptables save
[root@mail ~]# chkconfigip tables off
[root@mail ~]# vi /etc/sysconfig/selinux

SELINUX=disabled

[root@mail ~]# reboot
Remove Some old Software (if installed)
[root@mail ~]# yum remove postfix dovecot

Install Apache, MySQL, phpMyAdmin&mailx

[root@mail ~]# yum install -y ntp httpd mysql* php* php-mysql gcc openssl* cyrus-sasl* pkgconfigzlib-devel phpMyAdmin pcre-devel openldap-devel postgresql-devel expect libtool-ltdl-devel openldap-servers libtool gdbm-devel pam-devel gamin-devel libidn-devel db4-devel mod_ssl telnet sqlite-devel mail

Install postfix, courier, maildrop

[root@mail ~]# cd /rpm-folder
[root@mail ~]# rpm -ivh courier-authlib-0.65.0-1.el6.x86_64.rpm courier-authlib-mysql-0.65.0-1.el6.x86_64.rpm courier-authlib-devel-0.65.0-1.el6.x86_64.rpm courier-imap-4.12.0-1.x86_64.rpm maildrop-2.6.0-1.x86_64.rpm epel* postfix-2.6.6-2.2.el6.x86_64.rpm

Set MySQL Passwords And Configure phpMyAdmin

[root@mail ~]# chkconfig --levels 235 mysqld on
[root@mail ~]# servicemysqld start
[root@mail ~]# mysql_secure_installation

In order to log into MySQL to secure it, we'll need the currentpassword for the root user. If you've just installed MySQL, and you haven't set the root password yet, the password will be blank, So you should just press the Enter here.

Enter current password for root (enter for none): <-- ENTERPassword
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.

Set root password? [Y/n] <-- y
New password: <-- yourrootsqlpassword
Re-enter new password: <-- yourrootsqlpassword
Password updated successfully!
Reloading privilege tables..
... Success!

By default, a MySQL installation has an anonymous user, allowing anyoneto log into MySQL without having to have a user account created forthem. This is intended only for testing, and to make the installationgo a bit smoother. You should remove them before moving into production environment.

Remove anonymous users? [Y/n] <-- n
... Success!

Normally, root should only be allowed to connect from 'localhost'. This ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] <-- n
... Success!

By default, MySQL comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] <-- y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] <-- y
... Success!

Cleaning up...

All done! If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!

Configure phpMyAdmin

(We have to configure this to manage the database through GUI)

[root@mail ~]# vi /etc/httpd/conf.d/phpmyadmin.php

#<Directory /usr/share/phpMyAdmin/>
# <IfModulemod_authz_core.c>
# # Apache 2.4
# <RequireAny>
# Requireip 127.0.0.1
# Require ip ::1
# </RequireAny>
# </IfModule>
# <IfModule !mod_authz_core.c>
# Apache 2.2
# Order Deny,Allow
# Deny from All
# Allow from 127.0.0.1
# Allow from ::1
# </IfModule>
#</Directory>

[root@mail ~]# chkconfig --levels 235 httpd on
[root@mail ~]# service httpd restart

Create the MySQL Database for Postfix /courier

[root@mail ~]# mysqladmin -u root –p
password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.1.71 Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help.Type '\c' to clear the current input statement.

mysql> create database mail;
mysql>GRANT SELECT, INSERT, UPDATE, DELETE ON mail.* TO 'mail_admin'@'localhost' IDENTIFIED BY 'mailadmin';
mysql>GRANT SELECT, INSERT, UPDATE, DELETE ON mail.* TO 'mail_admin'@'localhost.localdomain' IDENTIFIED BY mailadmin ';
mysql>FLUSH PRIVILEGES;

mysql> USE mail;
mysql> CREATE TABLE domains (
domain varchar(50) NOT NULL,
PRIMARY KEY (domain) )
ENGINE=MyISAM;
mysql> CREATE TABLE forwardings (
source varchar(80) NOT NULL,
destination TEXT NOT NULL,
PRIMARY KEY (source) )
ENGINE=MyISAM;

mysql> CREATE TABLE users (
email varchar(80) NOT NULL,
password varchar(20) NOT NULL,
quota bigint(20) DEFAULT '10485760',
PRIMARY KEY (email)
) ENGINE=MyISAM;

mysql> CREATE TABLE transport (
domain varchar(128) NOT NULL default '',
transport varchar(128) NOT NULL default '',
UNIQUE KEY domain (domain)
) ENGINE=MyISAM;

mysql> quit;

Here we are defining the Database structure for mail server
The domains table will store each virtual domain that Postfix should receive emails for (e.g. 16c.com).
domain
16c.com
The forwardings table is for aliasing one email address to another, e.g. forward emails for info@16c.com to sales@16c.com.
source destination
info@16c.com sales@16c.com
The users table stores all virtual users (i.e. email addresses, because theemail address and user name is the same) and passwords (in encrypted form!) and a quota value for each mail box (in this installation the default value is 209715200 bytes which means 200MB).
email password Quota
sales@16c.com No9.E4skNvGa. ("secret" in encrypted form) 209715200
The transport table is optional, it is for advanced users. It allows to forward mails for single users, whole domains or all mails to another server. For example,
domain transport
16c.com smtp:[1.2.3.4]
would forward all emails for 16c.com via the smtp protocol to the server with the IP address 1.2.3.4 (the square brackets [] mean "do not make a lookup of the MX DNS record" (which makes sense for IP addresses...). If you use a fully qualified domain name (FQDN) instead you would not use the square brackets.).
Configure Postfix & define virtual maps
[root@mail ~]# vi /etc/postfix/mysql-virtual_domains.cf

user = mail_admin
password = mailadmin
dbname = mail
query = SELECT domain AS virtual FROM domains WHERE domain='%s'
hosts = 127.0.0.1

[root@mail ~]# vi /etc/postfix/mysql-virtual_forwardings.cf

user = mail_admin
password = mailadmin
dbname = mail
query = SELECT destination FROM forwardings WHERE source='%s'
hosts = 127.0.0.1

[root@mail ~]# vi /etc/postfix/mysql-virtual_mailboxes.cf

user = mail_admin
password = mailadmin
dbname = mail
query = SELECT CONCAT(SUBSTRING_INDEX(email,'@',-1),'/',SUBSTRING_INDEX(email,'@',1),'/') FROM users WHERE email='%s'
hosts = 127.0.0.1

[root@mail ~]# vi /etc/postfix/mysql-virtual_email2email.cf

user = mail_admin
password = mailadmin
dbname = mail
query = SELECT email FROM users WHERE email='%s'
hosts = 127.0.0.1

[root@mail ~]# vi /etc/postfix/mysql-virtual_transports.cf

user = mail_admin
password = mailadmin
dbname = mail
query = SELECT transport FROM transport WHERE domain='%s'
hosts = 127.0.0.1

[root@mail ~]# vi /etc/postfix/mysql-virtual_mailbox_limit_maps.cf

user = mail_admin
password = mailadmin
dbname = mail
query = SELECT quota FROM users WHERE email='%s'
hosts = 127.0.0.1

[root@mail ~]# chmod o= /etc/postfix/mysql-virtual_*.cf
[root@mail ~]# chgrp postfix /etc/postfix/mysql-virtual_*.cf

[root@mail ~]# groupadd -g 5000 vmail
[root@mail ~]# useradd –r -g vmail -u 5000 vmail -d /storage_drive/vmail –m

Next we do some Postfix configuration in main.cf

[root@mail ~]# cp /etc/postfix/main.cf{,.bak}

[root@mail ~]# postconf -e 'myhostname = mail.16c.com'

[root@mail ~]# postconf -e 'mydestination = mail.16c.com, localhost, localhost.localdomain'

[root@mail ~]# postconf -e 'mynetworks = 127.0.0.0/8'

[root@mail ~]# postconf -e 'virtual_alias_domains ='

[root@mail ~]# postconf -e ' virtual_alias_maps = proxy:mysql:/etc/postfix/mysql-virtual_forwardings.cf, mysql:/etc/postfix/mysql-virtual_email2email.cf'

[root@mail ~]# postconf -e 'virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql-virtual_domains.cf'

[root@mail ~]# postconf -e 'virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailboxes.cf'

[root@mail ~]# postconf -e 'virtual_mailbox_base = /storage_Drive/vmail’

[root@mail ~]# postconf -e 'virtual_uid_maps = static:5000'

[root@mail ~]# postconf -e 'virtual_gid_maps = static:5000'

[root@mail ~]# postconf -e 'smtpd_sasl_auth_enable = yes'

[root@mail ~]# postconf -e 'broken_sasl_auth_clients = yes'

[root@mail ~]# postconf -e 'smtpd_sasl_authenticated_header = yes'

[root@mail ~]# postconf -e 'smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination'

[root@mail ~]# postconf -e 'smtpd_use_tls = yes'

[root@mail ~]# postconf -e 'smtpd_tls_cert_file = /etc/postfix/smtpd.cert'

[root@mail ~]# postconf -e 'smtpd_tls_key_file = /etc/postfix/smtpd.key'

[root@mail ~]# postconf -e 'transport_maps = proxy:mysql:/etc/postfix/mysql-virtual_transports.cf'

[root@mail ~]# postconf -e 'virtual_create_maildirsize = yes'

[root@mail ~]# postconf -e 'virtual_maildir_extended = yes'

[root@mail ~]# postconf -e 'virtual_mailbox_limit_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailbox_limit_maps.cf'

[root@mail ~]# postconf -e 'virtual_mailbox_limit_override = yes'

[root@mail ~]# postconf -e 'virtual_maildir_limit_message = "The user you are trying to reach is over quota."'

[root@mail ~]# postconf -e 'virtual_overquota_bounce = yes'

[root@mail ~]# postconf -e 'proxy_read_maps = $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks $virtual_mailbox_limit_maps'

[root@mail ~]# postconf -e 'inet_interfaces = all'

Afterwards we create the SSL certificate that is needed for TLS:

[root@mail ~]# cd /etc/postfix

[root@mail ~]# opensslreq -new -outform PEM -out smtpd.cert -newkey rsa:2048 -nodes -keyoutsmtpd.key -keyform PEM -days 365 -x509

Country Name (2 letter code) [XX]:<-- Enter your Country Name (e.g., "DE").
State or Province Name (full name) []:<-- Enter your State or Province Name.
Locality Name (eg, city) [Default City]:<-- Enter your City.
Organization Name (eg, company) [Default Company Ltd]:<-- Enter your Organization Name (e.g., the name of your company).
Organizational Unit Name (eg, section) []:<-- Enter your Organizational Unit Name (e.g. "IT Department").
Common Name (eg, your name or your server's hostname) []:<-- Enter the Fully Qualified Domain Name of the system (e.g. "server1.example.com").
Email Address []:<-- Enter your Email Address.

Then change the permissions of the smtpd.key:

[root@mail ~]# chmod o= /etc/postfix/smtpd.key
Configure Saslauthd (this configuration required for SSL/TLS Authentication)
[root@mail ~]# vi /etc/sasl2/smtpd.conf

#pwcheck_method: saslauthd
#mech_list: plain login
pwcheck_method: authdaemond
log_level: 3
mech_list: PLAIN LOGIN
authdaemond_path:/var/spool/authdaemon/socket

Then start Postfix, saslauthd, and courier-authlib:

[root@mail ~]# chmod 755 /var/spool/authdaemon
[root@mail ~]# chkconfig --levels 235 courier-authlib on
[root@mail ~]# service courier-authlib restart

[root@mail ~]# chkconfig --levels 235 postfix on
[root@mail ~]# chkconfig --levels 235 saslauthd on
[root@mail ~]# service postfix restart
[root@mail ~]# service saslauthd restart
[root@mail ~]# chkconfig –levels 235 sendmail off

Configure Courier
Now we have to tell Courier that it should authenticate against our MySQL database. First, edit /etc/authlib/authdaemonrc and change the value of authmodulelistso that it reads.

[root@mail ~]# vi /etc/authlib/authdaemonrc

authmodulelist="authmysql" ( add this line )

#authmodulelist="authuserdbauthpamauthpgsqlauthldapauthmysqlauthcustomauthpipe" ( add # or comment this line)

Then edit /etc/authlib/authmysqlrc. It should look exactly like this (again, make sure to fill in the correct database details):

[root@mail ~]# cp /etc/authlib/authmysqlrc /etc/authlib/authmysqlrc_orig
[root@mail ~]# cat /dev/null > /etc/authlib/authmysqlrc
[root@mail ~]# vi /etc/authlib/authmysqlrc

MYSQL_SERVER localhost
MYSQL_USERNAME mail_admin
MYSQL_PASSWORD mailadmin
MYSQL_PORT 0
MYSQL_DATABASE mail
MYSQL_USER_TABLE users
MYSQL_CRYPT_PWFIELD password
#MYSQL_CLEAR_PWFIELD password
MYSQL_UID_FIELD 5000
MYSQL_GID_FIELD 5000
MYSQL_LOGIN_FIELD email
MYSQL_HOME_FIELD "/storage_drive/vmail"
MYSQL_MAILDIR_FIELD CONCAT(SUBSTRING_INDEX(email,'@',-1),'/',SUBSTRING_INDEX(email,'@',1),'/')
#MYSQL_NAME_FIELD
MYSQL_QUOTA_FIELD quota

Then restart Courier:

[root@mail ~]# chkconfig --levels 235 courier-imap on
[root@mail ~]# service courier-authlib restart
[root@mail ~]# service courier-imap restart

delete old certificates and generatenewfileand replaced the CN and emailaddress

[root@mail ~]# cd /usr/lib/courier-imap/share
[root@mail ~]# rm -f imapd.pem
[root@mail ~]# rm -f pop3d.pem

[root@mail ~]# vi /usr/lib/courier-imap/etc/imapd.cnf

CN=mail.16c.com
emailAddress=postmaster@16c.com

[root@mail ~]# vi /usr/lib/courier-imap/etc/pop3d.cnf

CN=mail.16c.com
emailAddress=postmaster@16c.com

[root@mail ~]# ./mkimapdcert
[root@mail ~]# ./mkpop3dcert
[root@mail ~]# service courier-authlib restart
[root@mail ~]# service courier-imap restart

Test pop3 by telnet

[root@mail ~]# telnet localhost pop3
Trying ::1...
Connected to localhost.
Escape character is '^]'.
+OK Hello there.
<-- quit (enter quit)
+OK Better luck next time.
Connection closed by foreign host.
Modify /etc/aliases (it is required to create alias for root)
[root@mail ~]# vi /etc/aliases
postmaster: root
root: postmaster@16c.com

[root@mail ~]# newaliases
[root@mail ~]# service postfix restart
Test Postfix
If you see the lines 250-STARTTLS and 250-AUTH PLAIN LOGIN everything is fine.
[root@mail ~]#telnetlocalhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 server1.example.com ESMTP Postfix
<-- ehlo localhost (enter ehlo localhost)
250-server1.example.com
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-AUTH PLAIN LOGIN
250-AUTH=PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
<-- quit (enter quit)
221 2.0.0 Bye
Connection closed by foreign host.

Populate The Database And Test (add domains, users, aliases )
[root@mail ~]# mysql -u root –p
Password: enter password

Mysql> USE mail;

If you want to make entries in the table domains or add domains, that would look like this:

Mysql> INSERT INTO `domains` (`domain`) VALUES ('16c.com');

If you want to make entries in the table users or add users, that would look like this:

Mysql> INSERT INTO `users` (`email`, `password`, `quota`) VALUES ('admin@16c.com', ENCRYPT('adminpassword'),‘10485760’);

If you want to make entries in the table forwardings or forward email, that would look like this:

Mysql> INSERT INTO `forwardings` (`source`, `destination`) VALUES ('info@16c.com', 'sales@16c.com');

Mysql> quit;

Reload postfix service every time when add user or changing in database :-

[root@mail ~]# service postfix reload

Send a Welcome Email For Creating Maildir
[root@mail ~]# mail admin@16c.com
Subject: Welcome<-- ENTER
Welcome! Have fun with your new mail account.<-- ENTER
<-- CTRL+D
EOT
[root@mail ~]#

Installing SquirrelMail
[root@mail ~]# yum install squirrelmail php-pear-DB
[root@mail ~]# service httpd restart

Change SQL Password plugin which we can install manually:

[root@mail ~]# cd /usr/share/squirrelmail/plugins
[root@mail ~]# wget http://www.squirrelmail.org/plugins/change_sqlpass-3.3-1.2.tar.gz
[root@mail ~]# tar – xvfz change_sqlpass-3.3-1.2.tar.gz
[root@mail ~]# cd change_sqlpass
[root@mail ~]# cp config.php.sample config.php

Now we must edit config.php and adjust it to our setup

[root@mail ~]# cd /usr/share/squirrelmail/plugins/change_sqlpass/
[root@mail ~]# vi config.php

[...]
$csp_dsn = 'mysql://mail_admin:mail_admin_password@localhost/mail';
[...]
$lookup_password_query = 'SELECT count(*) FROM users WHERE email = "%1" AND password = %4';
[...]
$password_update_queries = array('UPDATE users SET password = %4 WHERE email = "%1"');
[...]
$password_encryption = 'MYSQLENCRYPT';
[...]
$csp_salt_static = 'LEFT(password, 2)';
[...]
//$csp_salt_query = 'SELECT salt FROM users WHERE username = "%1"';
[...]
$csp_delimiter = '@';
[...]

The Change SQL Password plugin also depends on the Compatibility plugin which we install as follows:
[root@mail ~]# cd /usr/share/squirrelmail/plugins
[root@mail~]# wget http://www.squirrelmail.org/countdl.php?fileurl=http%3A%2F%2Fwww.squirrelmail.org%2Fplugins%2Fcompatibility-2.0.16-1.0.tar.gz

{Note: above command wget should be type with below link with space}
[root@mail ~]# tar -xvzf compatibility-2.0.16-1.0.tar.gz

Now we must go into the SquirrelMail configuration and tell SquirrelMail that we use Courier as our POP3 and IMAP server and enable the Change SQL Password and the Compatibility plugins:

[root@mail ~]# cd /usr/share/squirrelmail/config/
[root@mail ~]# ./conf.pl

You'll see the following menu. Navigate through it as indicated:
SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Main Menu --
1. Organization Preferences
2. Server Settings
3. Folder Defaults
4. General Options
5. Themes
6. Address Books
7. Message of the Day (MOTD)
8. Plugins
9. Database
10. Languages
D. Set pre-defined settings for specific IMAP servers
C Turn color off
S Save data
Q Quit

Command >> <-- D

SquirrelMail Configuration : Read: config.php
---------------------------------------------------------
While we have been building SquirrelMail, we have discovered some
preferences that work better with some servers that don't work so
well with others. If you select your IMAP server, this option will
set some pre-defined settings for that server.

Please note that you will still need to go through and make sure
everything is correct. This does not change everything. There are
only a few settings that this will change.

Please select your IMAP server:
bincimap = Binc IMAP server
courier = Courier IMAP server
cyrus = Cyrus IMAP server
dovecot = Dovecot Secure IMAP server
exchange = Microsoft Exchange IMAP server
hmailserver = hMailServer
macosx = Mac OS X Mailserver
mercury32 = Mercury/32
uw = University of Washington's IMAP server
gmail = IMAP access to Google mail (Gmail) accounts

quit = Do not change anything
Command >> <-- courier

imap_server_type = courier
default_folder_prefix = INBOX.
trash_folder = Trash
sent_folder = Sent
draft_folder = Drafts
show_prefix_option = false
default_sub_of_inbox = false
show_contain_subfolders_option = false
optional_delimiter = .
delete_folder = true

Press enter to continue... <-- ENTER

SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Main Menu --
1. Organization Preferences
2. Server Settings
3. Folder Defaults
4. General Options
5. Themes
6. Address Books
7. Message of the Day (MOTD)
8. Plugins
9. Database
10. Languages

D. Set pre-defined settings for specific IMAP servers

C Turn color off
S Save data
Q Quit

Command >> <-- 8

SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Plugins
Installed Plugins
1. delete_move_next
2. squirrelspell
3. newmail

Available Plugins:
4. administrator
5. bug_report
6. calendar
7. change_sqlpass
8. compatibility
9. filters
10. fortune
11. info
12. listcommands
13. mail_fetch
14. message_details
15. sent_subfolders
16. spamcop
17. test
18. translate

R Return to Main Menu
C Turn color off
S Save data
Q Quit

Command >> <-- 8 (or whatever number the compatibility plugin has - it's needed by the change_sqlpass plugin)

SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Plugins
Installed Plugins
1. delete_move_next
2. squirrelspell
3. newmail
4. compatibility

Available Plugins:
5. administrator
6. bug_report
7. calendar
8. change_sqlpass
9. filters
10. fortune
11. info
12. listcommands
13. mail_fetch
14. message_details
15. sent_subfolders
16. spamcop
17. test
18. translate

R Return to Main Menu
C Turn color off
S Save data
Q Quit

Command >> <-- 8 (the number of the change_sqlpass plugin)

SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Plugins
Installed Plugins
1. delete_move_next
2. squirrelspell
3. newmail
4. compatibility
5. change_sqlpass

Available Plugins:
6. administrator
7. bug_report
8. calendar
9. filters
10. fortune
11. info
12. listcommands
13. mail_fetch
14. message_details
15. sent_subfolders
16. spamcop
17. test
18. translate

R Return to Main Menu
C Turn color off
S Save data
Q Quit

Command >> S

Data saved in config.php
Press enter to continue... <-- ENTER

SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Plugins
Installed Plugins
1. delete_move_next
2. squirrelspell
3. newmail
4. compatibility
5. change_sqlpass

Available Plugins:
6. administrator
7. bug_report
8. calendar
9. filters
10. fortune
11. info
12. listcommands
13. mail_fetch
14. message_details
15. sent_subfolders
16. spamcop
17. test
18. translate

R Return to Main Menu
C Turn color off
S Save data
Q Quit

Command >> <-- Q
Change defaults sub folder setting :-

[root@mail ~]# vi /usr/share/squirrelmail/config/config.php

line no. 56 $default_sub_of_inbox = false;

One last thing we need to do is modify the file /etc/squirrelmail/config_local.php and comment out the $default_folder_prefix variable - if you don't do this, you will see the following error message in SquirrelMail after you've logged in: Query: CREATE "Sent" Reason Given: Invalid mailbox name.

[root@mail ~]# vi /etc/squirrelmail/config_local.php

<?php

/**
* Local config overrides.
*
* You can override the config.php settings here.
* Don't do it unless you know what you're doing.
* Use standard PHP syntax, see config.php for examples.
*
* @copyright &copy; 2002-2006 The SquirrelMail Project Team
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @version $Id$
* @package squirrelmail
* @subpackageconfig
*/

//$default_folder_prefix = '';
?>

[root@mail ~]# service httpd restart

Now all configurations are done & our mail Server is ready to use.

For access mail server type http://mail-server-ip/webmail