Linux Help Desk

Linux Help Desk

Sunday, April 12, 2015

How to Configure Zimbra 8 Mail Server in Centos 6







Zimbra Collaboration Suite (ZCS) is a groupware product created by Zimbra, Inc. It is widely used in the world. Users can share folders, contacts, schedules and other things, using a very rich web interface. Currently the latest version of Collaboration Suite is  Zimbra 8.6.0. It brings new features, improvements in Mail server and it provides a better web client experience. Click here to view the new improvements and fixes in Zimbra Collaboration Suite 8.6.0. In this tutorial, I will explain how to install Zimbra 8.6.0 RHEL6 or CentOS 6./ RHEL 7 or CentOS 7.

 Prerequisite                                                                                         
* CentOS 6 or CentOS 7
* server. root access to the server.
* A fully qualified domain name ( FQDN ) for your Zimbra mail server mx record and ensure your domain is configured correctly.

First you need to do some initial setup in the server                                                            
1. Configure /etc/hosts and hostname

2. Allow iptables to by-pass all zimbra ports.

3.  Disabled SELINUX
                                                                                                            

[root@centos6 ~]# vim /etc/sysconfig/selinux

Change enforcing to disabled                                                                                               

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

4. Stop any MTA services installed in the server                                                                

[root@centos6 ~]# systemctl stop postfix
[root@centos6 ~]# systemctl disable postfix
[root@centos6 ~]# systemctl stop sendmail
[root@centos6 ~]# systemctl disable sendmail

5.Update the OS                                                                                                                  


[root@centos6 ~]# yum update -y

6.Install the required packages and libraries by issuing the following command :            

[root@centos6 ~]# yum install perl perl-core ntpl nmap sudo libidn gmp libaio libstdc++ unzip sysstat sqlite -y

Now, the server is ready for install Zimbra 8.6.0.
Download Zimbra Open Source Edition 8.6.0


Issue the following command to download ZCS 8.6.0

wget https://files.zimbra.com/downloads/8.6.0_GA/zcs-8.6.0_GA_1153.RHEL7_64.20141215151110.tgz

Extract the downloaded tar file :                                                                                          

Using the following command you can extract the tar file, We downloaded in previous step

# tar xzf zcs-8.6.0_GA_1153.RHEL7_64.20141215151110.tgz

Go to extracted ZCS Open Source Edition                                                                              

# cd zcs-8.6.0_GA_1153.RHEL7_64.20141215151110

Start the installation with the following command :

Now, we are going to install the ZCS package using the script

# ./install.sh --platform-override

You can see the following screen when starting the script.                                                 

Operations logged to /tmp/install.log.14668
Checking for existing installation...
    zimbra-ldap...NOT FOUND
    zimbra-logger...NOT FOUND
    zimbra-mta...NOT FOUND
    zimbra-dnscache...NOT FOUND
    zimbra-snmp...NOT FOUND
    zimbra-store...NOT FOUND
    zimbra-apache...NOT FOUND
    zimbra-spell...NOT FOUND
    zimbra-convertd...NOT FOUND
    zimbra-memcached...NOT FOUND
    zimbra-proxy...NOT FOUND
    zimbra-archiving...NOT FOUND
    zimbra-core...NOT FOUND

PLEASE READ THIS AGREEMENT CAREFULLY BEFORE USING THE SOFTWARE. ZIMBRA, INC. ("ZIMBRA") WILL ONLY LICENSE THIS SOFTWARE TO YOU IF YOU FIRST ACCEPT THE TERMS OF THIS AGREEMENT. BY DOWNLOADING OR INSTALLING THE SOFTWARE, OR USING THE PRODUCT, YOU ARE CONSENTING TO BE BOUND BYTHIS AGREEMENT. IF YOU DO NOT AGREE TO ALL OF THE TERMS OF THIS AGREEMENT, THEN DO NOT DOWNLOAD, INSTALL OR USE THE PRODUCT.

License Terms for the Zimbra Collaboration Suite :                                                          

http://www.zimbra.com/license/zimbra-public-eula-2-5.html

Do you agree with the terms of the software license agreement? [N] y

Checking for prerequisites...
     FOUND: NPTL
     FOUND: nmap-ncat-6.40-4
     FOUND: sudo-1.8.6p7-11
     FOUND: libidn-1.28-3
     FOUND: gmp-5.1.1-5
     FOUND: libaio-0.3.109-12
     FOUND: libstdc++-4.8.2-16.2
     FOUND: unzip-6.0-13
     FOUND: perl-core-5.16.3-283

Checking for suggested prerequisites...
     FOUND: perl-5.16.3
     FOUND: sysstat
     FOUND: sqlite
Prerequisite check complete.

Checking for installable packages                                                                                        

Found zimbra-core
Found zimbra-ldap
Found zimbra-logger
Found zimbra-mta
Found zimbra-dnscache
Found zimbra-snmp
Found zimbra-store
Found zimbra-apache
Found zimbra-spell
Found zimbra-memcached
Found zimbra-proxy

Select the packages to install                                                                                                

Install zimbra-ldap [Y]

Install zimbra-logger [Y]

Install zimbra-mta [Y]

Install zimbra-dnscache [Y] N

Install zimbra-snmp [Y]

Install zimbra-store [Y]

Install zimbra-apache [Y]

Install zimbra-spell [Y]

Install zimbra-memcached [Y]

Install zimbra-proxy [Y]
Checking required space for zimbra-core
Checking space for zimbra-store
Checking required packages for zimbra-store
zimbra-store package check complete.

Installing:
    zimbra-core
    zimbra-ldap
    zimbra-logger
    zimbra-mta
    zimbra-snmp
    zimbra-store
    zimbra-apache
    zimbra-spell
    zimbra-memcached
    zimbra-proxy

The system will be modified.  Continue? [N] Y                                                                      

Removing /opt/zimbra
Removing zimbra crontab entry...done.
Cleaning up zimbra init scripts...done.
Cleaning up /etc/ld.so.conf...done.
Cleaning up /etc/security/limits.conf...done.

Finished removing Zimbra Collaboration Server.                                                                  

Installing packages

    zimbra-core......zimbra-core-8.6.0_GA_1153.RHEL7_64-20141215151110.x86_64.rpm...done
    zimbra-ldap......zimbra-ldap-8.6.0_GA_1153.RHEL7_64-20141215151110.x86_64.rpm...done
    zimbra-logger......zimbra-logger-8.6.0_GA_1153.RHEL7_64-20141215151110.x86_64.rpm...done
    zimbra-mta......zimbra-mta-8.6.0_GA_1153.RHEL7_64-20141215151110.x86_64.rpm...done
    zimbra-snmp......zimbra-snmp-8.6.0_GA_1153.RHEL7_64-20141215151110.x86_64.rpm...done
    zimbra-store......zimbra-store-8.6.0_GA_1153.RHEL7_64-20141215151110.x86_64.rpm...done
    zimbra-apache......zimbra-apache-8.6.0_GA_1153.RHEL7_64-20141215151110.x86_64.rpm...done
    zimbra-spell......zimbra-spell-8.6.0_GA_1153.RHEL7_64-20141215151110.x86_64.rpm...done
    zimbra-memcached......zimbra-memcached-

8.6.0_GA_1153.RHEL6_64-20141215151110.x86_64.rpm...done                                          
zimbra-proxy......zimbra-proxy-8.6.0_GA_1153.RHEL6_64-20141215151110.x86_64.rpm...done
Operations logged to /tmp/zmsetup01032015-084819.log
Installing LDAP configuration database...done.
Setting defaults...No results returned for A lookup of centos6.example.local
Checked nameservers; 192.168.0.70
No results returned for AAAA lookup of centos6.example.local
Checked nameservers; 192.168.0.70

DNS ERROR resolving centos6.example.local                                                                   
It is suggested that the hostname be resolvable via DNS
Change hostname [Yes]
Please enter the logical hostname for this host [centos6.example.local] mail.example.com
No results returned for A lookup of mail.example.com
Checked nameservers: 192.168.0.70

DNS ERROR resolving mail.example.com                                                                         
It is suggested that the hostname be resolvable via DNS
Re-Enter hostname [Yes]
Please enter the logical hostname for this host [centos6.example.local] mail.example.local

DNS ERROR resolving MX for mail.example.local                                                           
It is suggested that the domain name have an MX record configured in DNS
Change domain name? [Yes]
Create domain: [mail.example.local] example.local
MX: mail.example.local (192.168.0.70)

        Interface: 127.0.0.1
        Interface: ::1
        Interface: 192.168.0.70
done.
Checking for port conflicts

Main menu                                                                                                                         

   1) Common Configuration:
   2) zimbra-ldap:                             Enabled
   3) zimbra-logger:                           Enabled
   4) zimbra-mta:                              Enabled
   5) zimbra-snmp:                             Enabled
   6) zimbra-store:                            Enabled
        +Create Admin User:                    yes
        +Admin user to create:                 admin@example.local
******* +Admin Password                        UNSET
        +Anti-virus quarantine user:           virus-quarantine.fsbv7fj6r0@example.local
        +Enable automated spam training:       yes
        +Spam training user:                   spam.7xlmrmrh3@example.local
        +Non-spam(Ham) training user:          ham.rt_1on1o@example.local
        +SMTP host:                            mail.example.local
        +Web server HTTP port:                 8080
        +Web server HTTPS port:                8443
        +Web server mode:                      https
        +IMAP server port:                     7143
        +IMAP server SSL port:                 7993
        +POP server port:                      7110
        +POP server SSL port:                  7995
        +Use spell check server:               yes
        +Spell server URL:                     http://mail.example.local:7780/aspell.php
        +Enable version update checks:         TRUE
        +Enable version update notifications:  TRUE
        +Version update notification email:    admin@centos6.example.local
        +Version update source email:          admin@centos6.example.local
        +Install mailstore (service webapp):   yes
        +Install UI (zimbra,zimbraAdmin webapps): yes

   7) zimbra-spell:                            Enabled
   8) zimbra-proxy:                            Enabled
   9) Enable VMware HA:                        no
  10) Default Class of Service Configuration:
   s) Save config to file
   x) Expand menu
   q) Quit

Address unconfigured (**) items  (? - help) 6                                                                      

Store configuration

   1) Status:                                           Enabled
   2) Create Admin User:                       yes
   3) Admin user to create:                     admin@example.local
** 4) Admin Password                         UNSET
   5) Anti-virus quarantine user:              virus-quarantine.fsbv7fj6r0@example.local
   6) Enable automated spam training:     yes
   7) Spam training user:                        spam.7xlmrmrh3@example.local
   8) Non-spam(Ham) training user:       ham.rt_1on1o@example.local
   9) SMTP host:                                   mail.example.local
  10) Web server HTTP port:                 8080
  11) Web server HTTPS port:               8443
  12) Web server mode:                         https
  13) IMAP server port:                        7143
  14) IMAP server SSL port:                7993
  15) POP server port:                          7110
  16) POP server SSL port:                   7995
  17) Use spell check server:                  yes
  18) Spell server URL:                          http://mail.example.local:7780/aspell.php
  19) Enable version update checks:            TRUE
  20) Enable version update notifications:     TRUE
  21) Version update notification email:       admin@centos6.example.local
  22) Version update source email:             admin@centos6.example.local
  23) Install mailstore (service webapp):      yes
  24) Install UI (zimbra,zimbraAdmin webapps): yes

Select, or 'r' for previous menu [r] 4                                                                                   

Password for admin@example.local (min 6 characters): [SBmeBXtA] password

Store configuration

   1) Status:                                           Enabled
   2) Create Admin User:                       yes
   3) Admin user to create:                     admin@example.local
   4) Admin Password                           set
   5) Anti-virus quarantine user:              virus-quarantine.fsbv7fj6r0@example.local
   6) Enable automated spam training:    yes
   7) Spam training user:                        spam.7xlmrmrh3@example.local
   8) Non-spam(Ham) training user:       ham.rt_1on1o@example.local
   9) SMTP host:                                  mail.example.local
  10) Web server HTTP port:                8080
  11) Web server HTTPS port:              8443
  12) Web server mode:                        https
  13) IMAP server port:                       7143
  14) IMAP server SSL port:               7993
  15) POP server port:                         7110
  16) POP server SSL port:                 7995
  17) Use spell check server:                 yes
  18) Spell server URL:                        http://mail.example.local:7780/aspell.php
  19) Enable version update checks:            TRUE
  20) Enable version update notifications:     TRUE
  21) Version update notification email:       admin@centos6.example.local
  22) Version update source email:             admin@centos6.example.local
  23) Install mailstore (service webapp):      yes
  24) Install UI (zimbra,zimbraAdmin webapps): yes

Select, or 'r' for previous menu [r] 21                                                                                   

Version update destination address: [admin@centos6.example.local] admin@example.local

Store configuration

   1) Status:                                          Enabled
   2) Create Admin User:                       yes
   3) Admin user to create:                    admin@example.local
   4) Admin Password                           set
   5) Anti-virus quarantine user:              virus-quarantine.fsbv7fj6r0@example.local
   6) Enable automated spam training:          yes
   7) Spam training user:                      spam.7xlmrmrh3@example.local
   8) Non-spam(Ham) training user:             ham.rt_1on1o@example.local
   9) SMTP host:                               mail.example.local
  10) Web server HTTP port:                    8080
  11) Web server HTTPS port:                   8443
  12) Web server mode:                         https
  13) IMAP server port:                        7143
  14) IMAP server SSL port:                    7993
  15) POP server port:                         7110
  16) POP server SSL port:                     7995
  17) Use spell check server:                  yes
  18) Spell server URL:                        http://mail.example.local:7780/aspell.php
  19) Enable version update checks:            TRUE
  20) Enable version update notifications:     TRUE
  21) Version update notification email:       admin@example.local
  22) Version update source email:             admin@centos6.example.local
  23) Install mailstore (service webapp):      yes
  24) Install UI (zimbra,zimbraAdmin webapps): yes

Select, or 'r' for previous menu [r] 22                                                                                

Version update source address: [admin@centos6.example.local] admin@example.local

Store configuration

   1) Status:                                  Enabled
   2) Create Admin User:                       yes
   3) Admin user to create:                    admin@example.local
   4) Admin Password                           set
   5) Anti-virus quarantine user:              virus-quarantine.fsbv7fj6r0@example.local
   6) Enable automated spam training:          yes
   7) Spam training user:                      spam.7xlmrmrh3@example.local
   8) Non-spam(Ham) training user:             ham.rt_1on1o@example.local
   9) SMTP host:                               mail.example.local
  10) Web server HTTP port:                    8080
  11) Web server HTTPS port:                   8443
  12) Web server mode:                         https
  13) IMAP server port:                        7143
  14) IMAP server SSL port:                    7993
  15) POP server port:                         7110
  16) POP server SSL port:                     7995
  17) Use spell check server:                  yes
  18) Spell server URL:                        http://mail.example.local:7780/aspell.php
  19) Enable version update checks:            TRUE
  20) Enable version update notifications:     TRUE
  21) Version update notification email:       admin@example.local
  22) Version update source email:             admin@example.local
  23) Install mailstore (service webapp):      yes
  24) Install UI (zimbra,zimbraAdmin webapps): yes

Select, or 'r' for previous menu [r] r                                                                                     

Main menu

   1) Common Configuration:
   2) zimbra-ldap:                             Enabled
   3) zimbra-logger:                           Enabled
   4) zimbra-mta:                              Enabled
   5) zimbra-snmp:                             Enabled
   6) zimbra-store:                            Enabled
   7) zimbra-spell:                            Enabled
   8) zimbra-proxy:                            Enabled
   9) Enable VMware HA:                        no
  10) Default Class of Service Configuration:
   s) Save config to file
   x) Expand menu
   q) Quit

*** CONFIGURATION COMPLETE - press 'a' to apply                                                    
Select from menu, or press 'a' to apply config (? - help) a
Save configuration data to a file? [Yes]
Save config in file: [/opt/zimbra/config.23920]
Saving config in /opt/zimbra/config.23920...done.
The system will be modified - continue? [No] yes
Operations logged to /tmp/zmsetup01032015-084819.log
Setting local config values...done.
Initializing core config...Setting up CA...done.
Deploying CA to /opt/zimbra/conf/ca ...done.
Creating SSL zimbra-store certificate...done.
Creating new zimbra-ldap SSL certificate...done.
Creating new zimbra-mta SSL certificate...done.
Creating new zimbra-proxy SSL certificate...done.
Installing mailboxd SSL certificates...done.
Installing MTA SSL certificates...done.
Installing LDAP SSL certificate...done.
Installing Proxy SSL certificate...done.
Initializing ldap...done.
Setting replication password...done.
Setting Postfix password...done.
Setting amavis password...done.
Setting nginx password...done.
Setting BES searcher  password...done.
Creating server entry for mail.example.local...done.
Setting Zimbra IP Mode...done.
Saving CA in ldap ...done.
Saving SSL Certificate in ldap ...done.
Setting spell check URL...done.
Setting service ports on mail.example.local...done.
Setting zimbraFeatureTasksEnabled=TRUE...done.
Setting zimbraFeatureBriefcasesEnabled=TRUE...done.
Setting TimeZone Preference...done.
Initializing mta config...done.
Setting services on mail.example.local...done.

Adding mail.example.local to zimbraMailHostPool in default COS...done.                        
Creating domain example.local...done.
Setting default domain name...done.
Creating domain example.local...already exists.
Creating admin account admin@example.local...done.
Creating root alias...done.
Creating postmaster alias...done.
Creating user spam.7xlmrmrh3@example.local...done.
Creating user ham.rt_1on1o@example.local...done.
Creating user virus-quarantine.fsbv7fj6r0@example.local...done.
Setting spam training and Anti-virus quarantine accounts...done.
Initializing store sql database...done.
Setting zimbraSmtpHostname for mail.example.local...done.
Configuring SNMP...done.
Setting up syslog.conf...done.
Starting servers...done.
Installing common zimlets...
        com_zimbra_proxy_config...done.
        com_zimbra_mailarchive...done.
        com_zimbra_attachmail...done.
        com_zimbra_url...done.
        com_zimbra_phone...done.
        com_zimbra_date...done.
        com_zimbra_ymemoticons...done.
        com_zimbra_clientuploader...done.
        com_zimbra_srchhighlighter...done.
        com_zimbra_tooltip...done.
        com_zimbra_webex...done.
        com_zimbra_bulkprovision...done.
        com_zimbra_email...done.
        com_zimbra_adminversioncheck...done.
        com_zimbra_cert_manager...done.
        com_zimbra_viewmail...done.
        com_zimbra_attachcontacts...done.
Finished installing common zimlets.
Restarting mailboxd...done.

Creating galsync account for default domain...done.                                                          

You have the option of notifying Zimbra of your installation.
This helps us to track the uptake of the Zimbra Collaboration Server.
The only information that will be transmitted is:
The VERSION of zcs installed (8.6.0_GA_1153_RHEL6_64)
The ADMIN EMAIL ADDRESS created (admin@example.local)

Notify Zimbra of your installation? [Yes] no
Notification skipped
Setting up zimbra crontab...done.

Moving /tmp/zmsetup01032015-084819.log to /opt/zimbra/log                                           

Configuration complete - press return to exit

Start zimbra services : # su - zimbra
# zmcontrol start

Access admin panel via browser :                                                                                        

https://<your_zimbra_domain.com>:7071

or directly by IP:

https://192.168.0.70:7071

Wednesday, April 8, 2015

How to Configure Postfix,Dovecot with SMTP-AUTH & TLS/SSL in Centos 6.5

How to setup or working a mail server where Postfix is the SMTP service, and Dovecot provides IMAP and POP services. We will configure our mail server to use secure connection only (SMTPS, IMAPS, POP3S). The configuration has been tested and it’s also based on our personal experience so it’s fully functional and operational mail server.

Before we proceed to setup a mail server, the following DNS Records are most important for delivering email to destination so the email originates from your server will not land up on Junk folders in major free email providers.

1. DNS Entry for your mail server with MX record
2. Setup an SPF record (see openspf.org )
3. Reverse IP for your Mail Server


NOTE:
If you are using some firewall don’t forget to make exception on the appropriate ports.
POSTFIX

Postfix is a free open source mail transfer agent (MTA), a computer program for the routing and delivery of email. It is intended as a fast, easy-to-administer, and secure alternative to the widely-used Sendmail MTA which is installed by default with CentOS.

- so first we need to remove the Sendmail MTA                                                                    

yum remove sendmail

Install Postfix

# yum install postfix -y

We have to also setup SASL with our postfix to authenticate our users who want to send email outside of the permitted network. We don’t want our mail server to be open relay and thereby restricting sending mail only to the local users. Without SASL authentication postfix will give relay access denied error if you attempt to send mail outside of the network.

Installation Of Required Packages for SMTP AUTH                                                            


# yum install cyrus-sasl cyrus-sasl-devel cyrus-sasl-gssapi cyrus-sasl-md5 cyrus-sasl-plain -y

Postfix configuration files are stored in /etc/postfix. The two main postfix configuration files are master.cf and main.cf. First we are going to make some additions or changes to the main.cf configuration file as below

# vim /etc/postfix/main.cf

myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
home_mailbox = Maildir/
mailbox_command =
mynetworks = 127.0.0.0/8
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
relay_domains =
local_recipient_maps =

NOTE:
Make sure you uncomment inet_interfaces = all if you are enabling all option. It’s often made mistake leaving both uncommented!

Next we configure SMTP-AUTH

For this edit /etc/postfix/main.cf and make changes as given below                                    

# vim /etc/postfix/main.cf
smtpd_sasl_local_domain =
smtpd_sasl_auth_enable = yes
smtpd_sasl_type = cyrus
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtpd_sasl_authenticated_header = yes
smtpd_recipient_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination

Then edit /etc/postfix/master.cf and paste this under SMTP                                                 
#  vim /etc/postfix/master.cf
    smtps   inet n   -   n   - - smtpd
      -o smtpd_sasl_auth_enable=yes
      -o smtpd_reject_unlisted_sender=yes
      -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
      -o broken_sasl_auth_clients=yes

We must edit /usr/lib/sasl2/smtpd.conf so that Postfix allows PLAIN and LOGIN logins. On a 64Bit CentOS you must edit the file /usr/lib64/sasl2/smtpd.conf instead. It should look like this:


pwcheck_method: saslauthd
mech_list: plain login

Afterwards we create the certificates for TLS                                                                      


# mkdir /etc/postfix/ssl
# cd /etc/postfix/ssl/
# openssl genrsa -des3 -rand /etc/hosts -out smtpd.key 2048
# chmod 600 smtpd.key
# openssl req -new -key smtpd.key -out smtpd.csr
# openssl x509 -req -days 3650 -in smtpd.csr -signkey smtpd.key -out smtpd.crt
# openssl rsa -in smtpd.key -out smtpd.key.unencrypted
# mv -f smtpd.key.unencrypted smtpd.key
# openssl req -new -x509 -extensions v3_ca -keyout cakey.pem -out cacert.pem -days 3650

Next we configure Postfix for TLS:                                                                                        

The following lines should be added, edited or uncommented in main.cf file
# vim /etc/postfix/main.cf
smtpd_tls_auth_only = no
smtp_use_tls = yes
smtpd_use_tls = yes
smtp_tls_note_starttls_offer = yes
smtpd_tls_key_file = /etc/postfix/ssl/smtpd.key
smtpd_tls_cert_file = /etc/postfix/ssl/smtpd.crt
smtpd_tls_CAfile = /etc/postfix/ssl/cacert.pem
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom

#  service saslauthd start
# chkconfig saslauthd on

DOVECOT                                                                                              

It’s an open source IMAP and POP3 server for Linux/UNIX-like systems, written primarily with security in mind.

Install Dovecot (POP3S/IMAPS Server)

# yum install dovecot -y

Open the dovecot config file /etc/dovecot.conf and make the following changes. You may need to comment or uncomment certain lines, we intend to use secure connection only so we remove IMAP and POP3; if you want to use them please configure Dovecot to do so.

# vim /etc/dovecot/dovecot.conf

Uncomment the following line:                                                                                                

## Line 20 - umcomment ##
protocols = imap pop3 lmtp

Edit file /etc/dovecot/conf.d/10-mail.conf file

# vim /etc/dovecot/conf.d/10-mail.conf

Make the changes as shown below:                                                                                        

## Line 24 - uncomment ##
mail_location = maildir:~/Maildir

Edit /etc/dovecot/conf.d/10-auth.conf
# vim /etc/dovecot/conf.d/10-auth.conf

And make the changes as shown below:

## line 9 - uncomment##
disable_plaintext_auth = yes

 Line 97 - Add a letter "login"
auth_mechanisms = plain login

Edit file /etc/dovecot/conf.d/10-master.conf,
# vim /etc/dovecot/conf.d/10-master.conf

Make changes as shown below:                                                                                             

 Line 83, 84 - Uncomment and add "postfix"

  #mode = 0600
   user = postfix
   group = postfix

Start Dovecot service:

# service dovecot start
# chkconfig dovecot on

CREATE LOCAL USERS/MAILDIR                                                                                  

1. Create a localuser with adduser
# adduser milon

2. Update the password of ‘milon’ using
# passwd milon

chkconfig postfix on
chkconfig dovecot on

OR type ntsysv for GUI tool                                                                                                  

- to start run

/etc/init.d/postfix start
/etc/init.d/dovecot start

Test:

1. Check if the mail server is listening on the apriopriate ports (SMTP:25, SMTPS:465, IMAPS:993, POP3S:995)

netstat -ntpl

To see if SMTP-AUTH and TLS work properly now run the following command (you can also run the telnet command on the other ports to test if TLS and AUTH is working)

# telnet localhost 25                                                                                                               

To test further, set up an account in Evolution / Thunderbird / Outlook and test the SMTP with the username and password you set up earlier.

Remember that because you are using a self signed certificate, your email client will prompt you each time about an untrusted certificate so you can use the client certificate you created to suppress these warnings.

NOTE: If you encounter any problems, check the log file at /var/log/maillog.
FINAL NOTE:

Postfix is an extremely powerful and versatile mail transport agent. In this tutorial we have seen how to implement email server using postfix and dovecot for a single domain based on system user accounts.

How to set up MailScanner, Clam Antivirus and SpamAssassin in CentOS 6.5

In the world of mail servers, MailScanner is one of the best open source software for virus scanning and spam detection. MailScanner relies on pre-installed anti-virus and anti-spam software to check incoming and outgoing emails for malicious content or patterns of spamming. This makes sure that the mail server does not participate in the distribution of malware and unsolicited spam emails. It also helps preventing the mail server IP from becoming blacklisted, keeping the mail server records clean.

Preparing the System

Before we start doing anything, it should be mentioned that SELinux is disabled on CentOS. It is also necessary to add Repoforge repository on CentOS

Install EPEL Repository:We will use Squirrelmail for webmail client. Squirrelmail will not be found on CentOS official repositories, so let us enable EPEL repository. Follow the below link to install and enable EPEL repository.

## RHEL/CentOS 6 32-Bit ##
# wget http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
# rpm -ivh epel-release-6-8.noarch.rpm

## RHEL/CentOS 6 64-Bit ##
# wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
# rpm -ivh epel-release-6-8.noarch.rpm

Installing Dependencies

yum is used to install packages that are required for MailScanner. The list is long, but fortunately yum can resolve all the dependencies.

# yum install gcc cpp perl bzip2 zip unrar make patch automake rpm-build perl-DBI perl-MIME-tools perl-DBD-SQLite binutils glibc-devel perl-Filesys-Df zlib zlib-devel -y

Installing ClamAV and SpamAssassin

yum can be used to install ClamAV and SpamAssassin as well. The following few steps cover how to install and prepare them.
# yum install clamav spamassassin

Update ClamAV.
# freshclam -v

Update and start SpamAssassin.

# sa-update

# service spamassassin start
# chkconfig spamassassin on

# service clamd start
# chkconfig clamd on


Fix a path to MailScanner by creating a symbolic link.
# ln -s /usr/bin/freshclam /usr/local/bin/freshclam

Configuring Postfix

Postfix header_checks is used to hold any incoming email that Postfix receives. MailScanner performs checks on the emails held in a queue.
# vim /etc/postfix/main.cf

## This line is added ##
header_checks = regexp:/etc/postfix/header_checks

# vim /etc/postfix/header_checks

## This line is added ##
/^Received:/ HOLD

Preparing MailScanner

MailScanner is not yet available in CentOS or Repoforge repositories. We will download packages from the official MailScanner site and install it.

# wget https://s3.amazonaws.com/mailscanner/release/v4/rpm/MailScanner-4.85.2-1.rpm.tar.gz

Now we will extract and install the packages. The installation will take some time, so you can take a break if you want.

# tar zxvf MailScanner-4.85.2-1.rpm.tar.gz
# cd MailScanner-4.85.2-1
# ./install

After installation, the directories necessary for SpamAssassin are created and permissions are modified.

Next, the configuration file for MailScanner is backed up and then modified.
# vim /etc/MailScanner/MailScanner.conf

%org-name% = test
Run As User = postfix
Run As Group = postfix
Incoming Queue Dir = /var/spool/postfix/hold
Outgoing Queue Dir = /var/spool/postfix/incoming
MTA = postfix
Incoming Work Group = clam
Incoming Work Permissions = 0640
Virus Scanners = clamd
Clamd Socket = /var/run/clamav/clamd.sock
SpamAssassin User State Dir = /var/spool/MailScanner/
spamassassin
High Scoring Spam Actions = deliver

## please check /etc/MailScanner/spam.lists.conf for more details ##
Spam List = SBL+XBL


# vi /etc/MailScanner/virus.scanners.conf
clamd /bin/false /usr
# vi /etc/MailScanner/spam.assassin.prefs.conf
bayes_ignore_header X-test-MailScanner
bayes_ignore_header X-test-MailScanner-SpamCheck
bayes_ignore_header X-test-MailScanner-SpamScore
bayes_ignore_header X-test-MailScanner-Information
envelope_sender_header X-test-MailScanner-From
#use_auto_whitelist 0
# cd /var/spool/MailScanner
# mkdir spamassassin
# chown -R postfix:clam *
# chmod -R 750 *

Debug MailScanner stats before firing up.
# MailScanner -lint

# service MailScanner start
# chkconfig MailScanner on

Verifying MailScanner Operation

After MailScanner has been deployed, the events that take place behind the scenes can be viewed in /var/log/maillog. The following log snippet shows the sample activities while a mail is processed by Postfix.

# tailf /var/log/maillog

On a finishing note, MailScanner is a very powerful tool for providing necessary security to a mail server. It can protect the mail server from malware for both incoming and outgoing mails. It is a must for any email server deployed in production environment.

Monday, April 6, 2015

Linux - Centos 7 Directory Structure

Each of the above directory (which is a file, at the first place) contains important information, required for booting to device drivers, configuration files, etc. Describing briefly the purpose of each directory, we are starting hierarchically.


/bin : All the executable binary programs (file) required during booting, repairing, files required to run into single-user-mode, and other important, basic commands viz., cat, du, df, tar, rpm, wc, history, etc.
/boot : Holds important files during boot-up process, including Linux Kernel.
/dev : Contains device files for all the hardware devices on the machine e.g., cdrom, cpu, etc
/etc :  Contains Application’s configuration files, startup, shutdown, start, stop script for every individual program.
/home : Home directory of the users. Every time a new user is created, a directory in the name of user is created within home directory which contains other directories like Desktop, Downloads, Documents, etc.
/lib : The Lib directory contains kernel modules and shared library images required to boot the system and run commands in root file system.
/lost+found : This Directory is installed during installation of Linux, useful for recovering files which may be broken due to unexpected shut-down.
/media : Temporary mount directory is created for removable devices viz., media/cdrom.
/mnt : Temporary mount directory for mounting file system.
/opt : Optional is abbreviated as opt. Contains third party application software. Viz., Java, etc.
/proc : A virtual and pseudo file-system which contains information about running process with a particular Process-id aka pid.
/root : This is the home directory of root user and should never be confused with ‘/‘ 
/run : This directory is the only clean solution for early-runtime-dir problem.
/sbin : Contains binary executable programs, required by System Administrator, for Maintenance. Viz., iptables, fdisk, ifconfig, swapon, reboot, etc.
/srv : Service is abbreviated as ‘srv‘. This directory contains server specific and service related files.
/sys : Modern Linux distributions include a /sys directory as a virtual filesystem, which stores and allows modification of the devices connected to the system.
/tmp :System’s Temporary Directory, Accessible by users and root. Stores temporary files for user and system, till next boot.
/usr : Contains executable binaries, documentation, source code, libraries for second level program.
/var : Stands for variable. The contents of this file is expected to grow. This directory contains log, lock, spool, mail and temp files.

 
Exploring Important file, their location and their Usability

Linux is a complex system which requires a more complex and efficient way to start, stop, maintain and reboot a system unlike Windows. There is a well defined configuration files, binaries, man pages, info files, etc. for every process in Linux.

    /boot/vmlinuz : The Linux Kernel file.
    /dev/hda : Device file for the first IDE HDD (Hard Disk Drive)
    /dev/hdc : Device file for the IDE Cdrom, commonly
    /dev/null : A pseudo device, that don’t exist. Sometime garbage output is 
                     redirected to /dev/null, so that it gets lost, forever.
    /etc/bashrc  : Contains system defaults and aliases used by bash shell.
    /etc/crontab: A shell script to run specified commands on a predefined 
                         time Interval.
    /etc/exports : Information of the file system available on network.
    /etc/fstab : Information of Disk Drive and their mount point.
    /etc/group : Information of Security Group.
    /etc/grub.conf : grub bootloader configuration file.
    /etc/init.d : Service startup Script.
    /etc/lilo.conf : lilo bootloader configuration file.
    /etc/hosts : Information of Ip addresses and corresponding host names.
    /etc/hosts.allow : List of hosts allowed to access services on the local 
                               machine.
    /etc/host.deny : List of hosts denied to access services on the local  
                             machine.
    /etc/inittab : INIT process and their interaction at various run level.
    /etc/issue : Allows to edit the pre-login message.
    /etc/modules.conf : Configuration files for system modules.
    /etc/motd : motd stands for Message Of The Day, The Message users 
                      gets upon login.
    /etc/mtab : Currently mounted blocks information.
    /etc/passwd : Contains password of system users in a shadow file, a 
                         security implementation.
    /etc/printcap : Printer Information
    /etc/profile : Bash shell defaults
    /etc/profile.d : Application script, executed after login.
    /etc/rc.d : Information about run level specific script.
    /etc/rc.d/init.d : Run Level Initialisation Script.
    /etc/resolv.conf : Domain Name Servers (DNS) being used by System.
    /etc/securetty : Terminal List, where root login is possible.
    /etc/skel : Script that populates new user home directory.
    /etc/termcap : An ASCII file that defines the behaviour of Terminal, 
                          console and printers.
    /etc/X11 : Configuration files of X-window System.
    /usr/bin : Normal user executable commands.
    /usr/bin/X11 : Binaries of X windows System.
    /usr/include : Contains include files used by ‘c‘ program.
    /usr/share : Shared directories of man files, info files, etc.
    /usr/lib : Library files which are required during program compilation.
    /usr/sbin : Commands for Super User, for System Administration.
    /proc/cpuinfo : CPU Information
    /proc/filesystems : File-system Information being used currently.
    /proc/interrupts : Information about the current interrupts being utilized 
                              currently.
    /proc/ioports : Contains all the Input/Output addresses used by devices 
                           on the server.
    /proc/meminfo : Memory Usages Information.
    /proc/modules : Currently using kernel module.
    /proc/mount : Mounted File-system Information.
    /proc/stat : Detailed Statistics of the current System.
    /proc/swaps : Swap File Information.
    /version : Linux Version Information.
    /var/log/lastlog : log of last boot process.
    /var/log/messages : log of messages produced by syslog daemon at
                                    boot.
    /var/log/wtmp : list login time and duration of each user on the system 
                              currently.

how to configure vsftpd (ftp) Service in CentOS 6.5

How to setup vsftpd service on CentOS 6.5

vsftpd is a free FTP service for UNIX and linux systems. It is very stable, fast and secure ftp server. In this post, i will share how to setup sftpd Service on CentOS 6.5. The steps has been tested working fine with other version of CentOS 6.

1. Install vsftpd ftp service :

[root@server ~]# yum install vsftpd -y

2. Install ftp client on linux :

[root@server ~]# yum install ftp -y

3. Create local admin user to access ftp service.

[root@server ~]# useradd admin
[root@server ~]# passwd admin

Changing password for user admin.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

4. Add admin user into vsftpd userlist as below :


[root@server ~]# vi /etc/vsftpd/user_list
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
news
uucp
operator
games
nobody
admin

5. Disabled anonymous access:


anonymous_enable=YES

to below :

anonymous_enable=NO

6. Add the following to bottom of the config file. If userlist_deny=NO, only allow users in this file :

userlist_deny=NO

7. Update the following banner :


ftpd_banner=Welcome to yourdomianFTP service.

8. Start vsftpd service :

[root@server ~]# service vsftpd start

Starting vsftpd for vsftpd:                                [  OK  ]

9. Configure vsftpd daemon start automatically on booting :

[root@server ~]# chkconfig vsftpd on

10. Test ftp service connection from windows client using user1 :


C:\>ftp 192.168.0.5
Connected to 192.168.0.5.
220 Welcome to yourdomian FTP service.
User (192.168.0.5:(none)): admin
331 Please specify the password.
Password:
230 Login successful.
ftp> bye
221 Goodbye.

11. Test ftp service connection from linux client using user1 :

[root@server-05 ~]# ftp 192.168.0.5
Connected to 192.168.0.5 (192.168.0.5).
220 Welcome to yourdomain FTP service.
Name (192.168.0.5:root): admin
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> exit
221 Goodbye.

Friday, April 3, 2015

Linux Top Basic Shell Command

1. Basic Server Service Status:
# uptime - Displays the server uptime 
# last - Last login users of the system
# date - Show system clock   
# hostame - Displays the hostname and/or FQDN of the system
# uname -a - Displays the hostname and detailed kernel version
# cat /etc/redhat-release - Displays the version of Linux installed Example:
# cat /proc/cpuinfo - Displays information about the CPU(s)
# df -h - Displays the partitions, their sizes details, and mount points
# free - Displays detail about the system memory and usage
# lsof - Displays all open files
# lsof -nPi:22- Displays any open files which use port 22
# locate httpd.conf- Displays the full path to any file named httpd.conf
# updatedb - Rebuilds index of files for search using the locate utility
2. File Copy, Move, Delete:
# cp file1.txt file2.txt - Copies file1.txt to file2.txt
# mv old.txt new.txt - Renames a file called old.txt to new.txt
# rm file1.txt - Deletes file1.txt
# mkdir httpds- Creates a new directory called httpds
# cp -R httpd httpds - Recursively copies all files from directory httpd to httpds
# cp -PR httpd httpds - Recursively copies all files from directory httpd to httpds and retains all permission settings
# rm -rf httpd- Recursively deletes folder httpd and all contents
# chkconfig --list - Displays all services and their state (start or stop) at each
runlevel
# chkconfig --level 35 httpd on - Sets httpd to start on runlevels 35 when machine is booted
# service httpd start - Immediately starts Apache
3. File Attributes

#chown apache virtualhosts.txt- Changes ownership of the virtualhosts.txt file to user apache
#chgrp apache virtualhosts.txt- Changes membership of the virtualhosts.txt file to group apache
#chmod a+x sniffer.pl- Allows the sniffer.pl file to be executed 
4. File Permissoin (Chmod)

7 rwx read, write, execute 6 rw- read, write 5 r-x read, execute 4 r-- read 3 -wx write, execute 2 -w- write 1 --x execute 0 --- no permissions

# chmod 777 passwords.txt- Allows read, write, and execute on the file passwords.txt to anyone
# chmod 000 passwords.txt- Blocks read, write, and execute on the file passwords.txt to anyone 
5. Yum repository update 
# yum update -y - Updates all packages without prompting
# yum install iptraf- Installs a package named iptraf
# yum whatprovides */iostat - Searches all repositories and returns RPMs that provide the program iostat
# yum update samba- updates a package named samba 
RPM Finding:
# rpm -q http- Displays the version of daemon http (apache)
#rpm -qa | grep bind- Displays all packages installed with the word bind. Example:
#rpm -qa | grep bind

 
bind-chroot-9.3.6-16.P1.el5
system-config-bind-4.0.3-4.el5.centos
bind-utils-9.3.6-16.P1.el5
bind-9.3.6-16.P1.el5
bind-libs-9.3.6-16.P1.el5
ypbind-1.19-12.el5

#rpm -ivh proftpd- Interactively installs proftpd
#rpm -Uvh proftpd- Interactive upgrades named proftpd
#rpm -e proftpd- Removes package proftpd
#rpm --rebuilddb - Rebuilds a corrupt RPM database 
6. Compressed files
#unzip package.zip- Unzips the file package.zip
#tar -zvxf stunnel.tar.gz- Decompressed a gzip file named stunnel.tar.gz 
7. LAN Configure (Networking):
#ifup eth0- Enables network interface eth0
#ifdown eth0- Disables network interface eth0
# vi /etc/sysconfig/network-scripts/ifcfg-eth0- Uses vi to edit network settings on eth0
8. IPtables Configure:
# service iptables status - Displays status of iptables (running or not)
# iptables -L - Displays ruleset of iptables
# iptables -I INPUT -p tcp -m tcp -s 192.168.15.254/26 --dport 22 -j ACCEPT - Accepts incoming SSH connections from IP range 192.168.15.254/26
# iptables -I INPUT -p tcp -m tcp -s 0.0.0.0/0 --dport 22 -j DROP - Blocks SSH connections from everywhere else
# iptables -I INPUT -s "192.168.10.121"-j DROP - Drops all traffic from IP 192.168.10.121
# iptables -D INPUT -s "192.168.10.121"-j DROP - Removes previously allied drop all from IP 192.168.10.121
# iptables -I INPUT -s "192.168.10.0/24"-j DROP - Drops all traffic from IP range 192.168.10.0/24
# iptables -A INPUT -p tcp --dport 25 -j DROP - Blocks all traffic to TCP port 25
# iptables -A INPUT -p tcp --dport 25 -j ACCEPT - Allows all traffic to TCP port 25
# iptables -A INPUT -p udp --dport 53 -j DROP - Blocks all traffic to UDP port 53
# /etc/init.d/iptables save - Saves all IPtables rules and re-applies them after a reboot
# /etc/init.d/iptables restart


9. Server Processes & Logs

# ps ax - Displays all running processes
# ps aux - Displays all running processes including CPU and memory usage of each
# ps ax | wc -l - Displays the total number of processes
# top - Interactive process manager which allows sorting by criteria

Logs Files:

# tail -f /var/log/messages - Displays the most current entries to the messages log in real-time
# tail -50 /var/log/messages - Displays the last 50 lines of the messages log
# head -50 /var/log/messages - Displays the first 50 lines of the messages log
# cat /var/log/messages - Displays the entire messages log
# cat /var/log/messages | grep "FTP session opened" - Displays any entries in the messages log that contain the ext FTP session opened
# cat /var/log/messages | grep "FTP session opened" > log2.txt- Writes any entries in the messages log that contain the ext FTP session opened to a file named log2.txt

10. Network IP Masks:
Short Form
Full Form
No. Machines usable IP
Comment
/8
255.0.0.0
16,777,214
Used to be called an `A-class'
/16
255.255.0.0
65,534
Used to be called an `B-class'
/17
255.255.128.0
32,766

/18
255.255.192.0
16,382

/19
255.255.224.0
8,190

/20
255.255.240.0
4,094

/21
255.255.248.0
2,047

/22
255.255.252.0
1,022

/23
255.255.254.0
510

/24
255.255.255.0
254
Used to be called a `C-class'
/25
255.255.255.128
126

/26
255.255.255.192
62

/27
255.255.255.224
30

/28
255.255.255.240
14

/29
255.255.255.248
6

/30
255.255.255.252
2


11. vi /vim Editor:

vi Replace

cw – Vi replace a single word from the current cursor position. To replace a whole word, you put the cursor on the the first character of the word.
c$ – replace the current line but doesn’t extend to change the rest of a wrapped sentence on the screen
r – Vi Replace the character under the cursor
R – Replaced the text on the same line until Esc is pressed, but it doesn’t change text on the next line. Instead, it pushes to ahead of the current changes.

vi Delete

x – Deletes a single character under the cursor
X – Deletes a single character before the cursor
dw – Deletes a single word that’s currently under the cursor, from the cursor position onward.

vi Delete Line

dd – Vi delete line, regardless of the cursors position on the line
D – Deletes all text from the cursor position to the end of the line
dL – Deletes all text from the cursor position to the end of the screen
dG – Deletes all text from the cursor to the EOF
d^ – Deletes all text from the beginning of the line to the cursor

vi Copy & Paste

Commands for Vi copy & paste:
yy – Vi copy line – copies a line of text to the unnamed buffer
3yy – Copies 3 lines of text to the unnamed buffer
yw – Copies a word (under the cursor) to the unnamed buffer
3yw – Copies 3 words to the unnamed buffer
P – Pastes the contents 0f the unnamed buffer to the right of the cursor
p – Pastes the contents of the unnamed buffer to the left of the cursor

vi Page Down

Ctrl+F – Vi page down – Moves forward a page
Ctrl+D – Moves forward half a page

vi Page Up

Ctrl+B – Vi page up – Moves back a page
Ctrl+U – Moves backward a half-page

vi Save & Exit

 :q – Vi exit – this will close Vi
:wq – Vi save & exit
:w – Vi Save, write the file out to disk
: x – Vi exit, and prompts it you want to save on exit.
Shift+ZZ - Alternative way to save and exit Vi
:q! – Exits vi and discards and changes you made
:wq! – Vi Save and exit if you are root and do not have the write bit set for the file you are attempting to write.

12. MySQL Commands - Cheat Sheet

New Installation - tighten up security
Change root password to something!

shell> mysql -u root mysql
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');
mysql> SET PASSWORD FOR 'root'@'host_name' = PASSWORD('new_password');

Remove annonymous accounts
shell> mysql -u root -p mysql
mysql> SELECT Host, User FROM user; -show us where they live
mysql> DELETE FROM user WHERE User = '';
mysql> FLUSH PRIVILEGES;
Also, don't forget about the .mysql_history file that gets created in your home directory!

Databases
Make new Database:
mysql> CREATE DATABASE reports;
Make sure it got created properly:
mysql>SELECT DATABASE();
View Databases:
mysql>SHOW DATABASES;
Remove a Databse:
mysql>DROP DATABASE oldatabase;
Change working database:
mysql> USE newdatabase;

Users
Add a user with full super user privileges who can connect from anywhere:
mysql>GRANT ALL PRIVILEGES ON *.* TO king@'%' IDENTIFIED BY 'some_pass' WITH GRANT OPTION;
mysql>GRANT ALL PRIVILEGES ON *.* TO king@localhost IDENTIFIED BY 'some_pass' WITH GRANT OPTION;
Add a local user to manage the reports database:
mysql> GRANT ALL ON reports.* TO reports@localhost IDENTIFIED BY 'new_password';
mysql> GRANT ALL ON reports.* TO reports@jane.plumblossom.orgIDENTIFIED BY 'new_password';

Make sure the user is setup:
mysql> SELECT * FROM user; OR
mysql> SELECT Host, User FROM user;
When connecting an older client to MySQL server version 4.1 or greater you will need to set the password to the 'Old Style' due to the change in the authentication protocol. Macintosh 10.4 server ships with PHP 4 which cannot connect to the newer MySQL server that comes installed. I wonder whose bright idea that was.
mysql> SET PASSWORD FOR 'reports'@'localhost' = OLD_PASSWORD('new_password');
Flush Privileges to activate changes:
mysql> flush privileges;

Tables
Add a Table:
mysql> CREATE TABLE test_table(id MEDIUMINT PRIMARY KEY, name VARCHAR(20));
mysql> SHOW TABLES;
Remove Table:
mysql> DROP TABLE course;
Change Fieldname or Type:
mysql> ALTER TABLE courses MODIFY course_name VARCHAR(20);
mysql> ALTER TABLE tablename CHANGE field_name new_field_name datatype;
Update a single field:
mysql> UPDATE courses SET year = '2003' WHERE course_id = '1';
mysql> UPDATE tablename SET fieldname = value WHERE fieldname = criteria;
Delete a Row:
mysql> DELETE FROM courses WHERE course_id = 0;
Delete a column:
mysql> ALTER TABLE courses DROP COLUMN course_id;
Add a new column:
mysql> ALTER TABLE tablename ADD COLUMN column-name datatype(value) AFTER existing_field;
Insert Data (row)
mysql>INSERT INTO courses VALUES('','Technology','bschonhorst','Brad','Simpson','Fall','2003',NULL,'0','0','0','0','0');

Searching
Wildcards: Use the % Symbol to find alex alexa alexia alexis
mysql> SELECT * FROM users WHERE name LIKE '%alex%';
Select some info:
mysql> SELECT course_id, rteacher FROM courses;
Get the last insert ID:
mysql> SELECT LAST_INSERT_ID();
Basic Backups
mysqldump  --opt database > backup-file.sql -u reports -p
Then to import after upgrade
mysql -u user -p  dbname < dbname-backup-file.sql
See also, Flush and Lock table before doing on a server

13. Packing, unpacking, and installing files:
gzip compress:
#gzip <filename.ext>
gzip extract:
#gunzip <filename.ext>
gzip retrieve information about file:
#gzip -l <filename.ext>
tar archive:
#tar cfv <archive name.ext> <file/folder to archive>
tar extract:
#tar xvf <filename.ext>
tar retrieve information about file:
#tar tvf <filename.tar>
gzip and tar compress in one command:
#tar cvzf <archive name.tar.gz> <file/folder to archive>
gzip and tar extract in one command:
#tar xvzf <filename.tar.gz>
 
14. install rpm files Manually:
 
#rpm -ivh <rpm file name>

install rpm package even if already installed:
#rpm -ivh --replacepkgs <rpm file name>

uninstall rpm packages:
#rpm -e <rpm package name>

After uninstalling an rpm package, you will find that it still has config files and other bits strewn about. The rm -rf and rm -f commands are VERYpowerful and can easily render your linux installation unusable. Be very careful. A 'reasonably safe' way (provided you pay attention and are careful) to clean the files up is:

1) Do a find / -name "<filename>*" | more
2) Check the output and make SURE it only includes the files you want to remove.
3) Do a find / -name "<filename>*" | xargs rm -f


tar basic functions and options:

function:

c To create a new archive
x To extract files from an archive
t To list the contents of an archive
r To append files to the end of an archive
u To update files that are newer than those in the archive
d To compare files in the archive to those in the filesystem

options:
f <filename> To specify that the tar file to be read or written is named <filename>
k To keep any existing files when extracting, i.e. don't delete the origional files
v To make tar show the files it is archiving or restoring (don't use in shell scripts)
z To specify that the data to be written to the tar file should be gzipped



15. Miscellaneous commands:

To download a web page(s):
#wget -m -r -l5Checking open network ports:
#netstat -apn | more
Show file attributes and permissions:
#llShow all files in a directory (including hidden .<name> files
#
ls -A
Show information about mounted volumes:
#df -h
Turn off all power management:
#xset -dpms
Load StartX setup routine:
#X86configDisplay log file starting at the end:
#tail -f <file name>

Samba commands:
Add user/change password (user must have a unix account first):
#smbpasswd -a <username>



Apache commands:
.htpasswd file creation for Apache Directory security use:

To create a new .htpasswd file and add a user (will prompt for password):
#htpasswd -c /etc/httpd/conf/.htpasswd <name>
To create a new user in an existing .htpasswd file (will prompt for password):
#htpasswd /etc/httpd/conf/.htpasswd <name>

<Directory> security examples in httpd.conf (which use the .htpasswd file):

<Directory "/var/www/html/<directory>">
AuthType Basic
AuthName "Restricted Uploads"
AuthUserFile /etc/httpd/conf/.htpasswd
Require valid-user
(means anyone in the .htpasswd file can access)
</Directory>

**and**

<Directory "/var/www/html/<directory>">
AuthType Basic
AuthName "Restricted file access"
AuthUserFile /etc/httpd/conf/.htpasswd
Require jjones
(only jjones in the .htpasswd file has access)
</Directory>


RedHat/Fedora account creation:
To create a new user account:
#useradd <name>
To add/change a password:
#passwd <name> (will prompt for password twice)
To add a user to a group:
#usermod -G <groupname> <username>


Set owner of a file/folder:
#chown <user.group> <file/folder name>
#chown -R >user.group> <file/folder name> for recursive, i.e. apply changes to subfolders

Set permissions on a file/folder:
#chmod 777 <file/folder name> for full rights (dangerous!)
#chmod 775 <file/folder name> for full rights for user/group but no write/execute for 'other'
#chmod 765 <file/folder name> for full user rights, no write for 'group', and no write/execute for 'other'
Add -R for recursive, i.e. chmod -R 775 <file/folder name> to apply rights to subfolders

File permissions take the form of:
User
Group
Other
-RWX
RWX
RWX


The leading dash in the above table is for the type of data, d would be a directory and - indicates a file.

File permissions can be set using bits, as referenced above:
User
Group
Other
read
write
execute
read
write
execute
read
write
execute
400
200
100
40
20
10
4
2
1

Another way to look at it would be to visualize -r--r--r-- and calculate it as:
400
40
4
= 444

~examples~
File permissions of -rwxrwxr-x would be:
400+200+100 plus 40+20+10 plus 4+1 (no write for Other) which equals 775
File permissions of -rwxr-xr-x would be:
400+200+100 plus 40+10 plus 4+1 (no write for Group or Other) which equals 755

So, chmod -R 775 /var/www/html means /html and subfolders have -rwxrwxr-x or full rights except 'Other', which doesn't have write permissions.


Making symbolic links:
#
ln -s <location/filename> <name of symbolic link>

Example: ln -s /var/www/html/homesite homesite would create a link named homesite to /var/www/html/homesite which is a folder.


Sending Root system messages and logs to an email address:
Edit /etc/aliases
Un-remark (remove # symbol) from 'root:' and add the email address of the recipient.
Save file.
At the command prompt, type newaliases to update the database.



Enable daily yum updates:
Pre-FC6 setup:
# chkconfig yum on
# service yum start
Should see "Enabling nightly yum update: [OK]"
FC6 and later setup (yum-cron is a seperate package):
# yum install yum-cron
# chkconfig yum-cron on
# service yum-cron start
Should see "Enabling nightly yum update: [OK]"
Other yum features:List all available software:
#yum list

See if there are updated packages available:
#yum check-update

Update all installed packages that have a newer version available:
#yum update

Install specific package(s) (and its dependencies, if missing any):
#yum install <packagename>
Search all known packages entries (descriptions etc) for <word>
#yum search
<word>
Show basic information about a package
#yum info <packagename>