Munin Installation in CentOS

Munin is a monitoring tool for servers. It uses RRDtool to log and graph data from your servers. The plugin API is very easy to grasp. Actually, I haven’t read the API documentation yet. I just looked at the output of the plugins and it looks easy to achieve. The data can be accessed through the web.

Munin works by polling your servers for the data hence two applications, Munin and Munin Node. The former periodically gathers data (cronned) and the latter serves the data to the former. Please refer to the following for our example configuration. You can make up a domain if you want Munin to group your servers similar to the live demo.

Munin “Graph Server” – graph-server.net (10.10.10.1)
A Munin Node – munin-sample.net (100.100.100.2)

1. Installing and Configuring Munin

In this section, we set it up on graph-server.net

Add the RPMforge repository.

#rpm -Uhv http://apt.sw.be/packages/rpmforge-release/rpmforge-release-0.3.6-1.el4.rf.i386.rpm

This step is optional if your Linux distribution has the packages in its default repositories.

Install munin.

#yum -y install munin

Change the ownership of the Munin web docroot to munin.

#chown -R munin:munin /var/www/munin

The default configuration file (in version 1.2.5-1) the value for the web docroot points to the wrong directory. Replace the value of htmldir from /var/www/html/munin to /var/www/munin at /etc/munin/munin.conf (line 7).

Restart Apache and Cron, service httpd restart && service crond restart

You can check if it’s working through your browser (i.e. http://10.10.10.1/munin/). You will get a 404 (not found) if you don’t supply a trailing slash.

2. Add a Node

In this section, we will configure munin-sample.net.

Add the RPMforge repository (see 1.1).

Install Munin Node.

#yum -y install munin-node

Configure. Edit /etc/munin/munin-node.conf with your favorite text editor.

Allow the graph server (graph-server.net/10.10.10.1) to poll the node.
allow ^192\.168\.1\.1$

If your server doesn’t report the correct hostname, add the following line

host_name munin-sample.net

If your servers have two interfaces and on the same LAN (e.g. one for Internet and another for LAN), you can configure the node to bind and listen on the local interface by changing the value of host (line 13) from * to the local IP of the node.
Start munin-node and set to start on bootup.

#service munin-node start
#chkconfig munin-node on

Edit Munin’s configuration on the graph server (/etc/munin/munin.conf).

[munin-sample.net]
address 100.100.100.2
use_node_name yes

Wait for at least 5 minutes for the new node to appear. You can also install the node on the graph server. The default node configuration will work out of the box.

3. Install/Activate Some Plugins

This section should familiarize you with the plugin installation routine. Plugins are installed in the nodes.

Apache

Create a symbolic link to the Apache plugins (stored in /usr/share/munin/plugins) in the plugin folder.

#ln -s /usr/share/munin/plugins/apache_* /etc/munin/plugins/

Enable server status reports. Add the following to Apache’s configuration file.

ExtendedStatus On
<Location /server-status>
SetHandler server-status
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Location>

Restart Apache and the node

service httpd restart && service munin-node restart

Asterisk
Download the plugins for your Asterisk version from here.
Extract them to /usr/share/munin/plugins.
Make the files executable

#chmod 755 /usr/share/munin/plugins/asterisk_*

Configure Asterisk Manager by adding/changing the following in /etc/asterisk/manager.conf

[general]
enabled = yes
port = 5038
[munin]
secret = somepassword
permit = 127.0.0.1 ;if this doesn't work, use the local IP
write = system,call,log,verbose,command,agent,user

Add the following to the plugin configuration file in /etc/munin/plugin-conf.d/munin-node

[asterisk_*]
env.username munin
env.secret somepassword
Reload Asterisk's configuration and restart the node.
asterisk -rx reload >> /dev/null && service munin-node restart
MySQL

Create a symbolic link to the MySQL plugins (stored in /usr/share/munin/plugins) in the plugin folder.

#ln -s /usr/share/munin/plugins/mysql_* /etc/munin/plugins/

If your root user has a password (or want to use a different user), edit the plugin configuration file in /etc/munin/plugin-conf.d/munin-node and uncomment line 16 by removing the leading hash (#). Then change the parameters that will be used when mysqladmin is run.

Restart the node

#service munin-node restart

MTR

Make sure you have the latest version of MTR.

#yum -y install mtr && yum -y update mtr

Extract to /usr/share/munin/plugins
Make the file executable.

#chmod 755 /usr/share/munin/plugins/mtr100_

Create a symbolic link to the plugin (stored in /usr/share/munin/plugins) in the plugin folder. Append the host that you want to query to the link of the name.

#ln -s /usr/share/munin/plugins/mtr100_ /etc/munin/plugins/mtr100_somehost.com

To add another host to query, just create another symbolic link.

Add the following to the plugin configuration file in /etc/munin/plugin-conf.d/munin-node
[mtr100_*]
timeout 60

Restart the node
#service munin-node restart


Why Email Server in Linux are popular?


Supports POP3, IMAP and Web mail access. These are standard services that ideally should be available in any mail system for flexible email access.

Is extremely fast, reliable and scalable. Linux performs well and its uptime is very, very good.

Does not require expensive hardware. Thanks to its fast and efficient services, expensive high end hardware is not necessary.

Is very secured. The Linux operating system is very difficult to exploit. The National Security Agency even contributed to allow Linux to support even stronger levels of security.

Has a powerful anti-spam filter. SpamAssassin uses a wide variety of local and network tests to identify spam signatures.

Has an effective and regularly updated anti-virus. The open source nature of Clam Antivirus allows it to respond to new viruses even faster than commercial antivirus softwares.

Has small to zero (as in free) software cost depending on your support needs. Depending on your support needs, you have the option of using a community supported Linux or a company supported one.

Works with Microsoft Active Directory. You can integrate Microsoft Active Directory user accounts and distribution list into your Linux mail server to simplify administration.

configure: error: C++ compiler cannot create executables


SOLUTIONS:

If you are getting the following error while running configuration file
configure: error: C++ compiler cannot create executables
It means that you have not installed c++ libraries to fix that please execute the below command.
yum install *gcc-c++*
which will install gcc-c++ libraries which will fix the issue.

Mail Server Setup in details

For deploying a consistent, efficient email server, pay heeds to the following considerations

Linux Distribution


Red Hat Enterprise Linux is a Linux distribution produced by Red Hat and targeted toward the commercial market, including mainframes. Red Hat commits to supporting each version of RHEL for 7 years after its release.

  



CentOS is an Enterprise-class Linux Distribution derived from sources freely provided to the public by Red Hat.



Mail Delivery and Transfer

Postfix is an open source SMTP Server that is fast, easy to administer, flexible while at the same time being sendmail compatible enough to not upset existing users. Written by security expert Wietse Venema, it is built from the ground up to be secure.


Dovecot is an open source IMAP and POP3 server for Linux/UNIX-like systems. It complements Postfix with its high performance, ease of administration and rock solid security.

Web Mail Access



Apache is an open-source HTTP server supporting a wide range of operating systems including UNIX and Windows NT. Apache is a secure, efficient and extensible HTTP server that provides HTTP services in sync with the current HTTP standards.



Squirrelmail is an open source standards-based webmail package written in PHP.



Anti-Spam and Anti-Virus

MailScanner is an open source anti-virus and anti-spam filter for email servers. The anti-virus and anti-spam portion is delegated to third party applications.

ClamAV is an open source (GPL) anti-virus toolkit for UNIX, designed especially for e-mail scanning on mail gateways.


SpamAssassin is a mail filter, written in Perl, that identifies spam using a wide range of heuristic tests on mail headers and body text.





Lightweight Directory Access Protocol (LDAP)

Fedora Directory Server is an enterprise-class Open Source LDAP server for Linux. It is full-featured, supports multi-master replication, and already handles many of the largest LDAP deployments in the world.



OpenLDAP is an open source implementation of the Lightweight Directory Access Protocol.

JXplorer is a standards compliant general purpose open source ldap browser that can be used to read and search any ldap directory, or any X500 directory with an ldap interface.

Active Directory Integration

Samba is an Open Source/Free Software suite that provides seamless file and print services to SMB/CIFS clients.








System Administration


Webmin is a web-based interface for system administration for Unix. Using any modern web browser, you can setup user accounts, Apache, DNS, file sharing and much more.


For more: http://linux-circles.blogspot.com/2012/07/email-server-in-details.html

Configure NTP in linux


Configure NTP in centOS
1. Click System, select Administration and click Date & Time.
2. In the Date/Time Properties window, click the Network Time Protocol tab.
3. Check Enable Network Time Protocol. Next click Show advanced options and check Synchronize system clock before starting service. Finally, click OK.

Configure NTP (Console)

#/usr/sbin/ntpdate pool.ntp.org
immediately synchronizes the system clock. Make sure the ntpd service is not running before using this command.

#/sbin/service ntpd start
starts the ntpd service

#/sbin/service ntpd stop
stops the ntpd service

#/etc/ntp.conf
the above is not a command, it is the location of the ntpd configuration file

find command in details

Sample1: # find all the files in /home with name test.txt. Here –name is used to specify the filename.

# find /home –name test.txt

Sample2: # find the files whose name is test.txt and in present working directory

# find . –name test.txt

Sample3: # find all the files whose name contains both capital letters and small letters in it.

# find /home –iname test.txt

Sample4: Search for only directories whose name is var in / directory

# find / -type d –name var

Sample5: Search for an mp3 files whose name is temp.mp3

# find / -type f –name temp.mp3

Sample6:Search for a file name test.txt and its permissions are 775 in a given box

# find / -perm 775 –name test.txt

Sample7: How about searcing files with SUID bit set and file permissions are 755?

# find / -perm 4755

Sample8:How can i # find SGID bit set files with 644 permissions?

# find / -perm 2644

Sample9: How can i # find Sticky bit set files in my system with permissions 551?

# find / -perm 1551

Sample10:Search for all the files whose SUID bit is set

# find / -perm /u=s

Sample11: Search for all the files whose SGID bit is set

# find / -perm /g+s

Sample12: Search for all the files  whose StickyBit is set

# find / -perm /o=t

Sample13: Search for all the files whose owener permissions is read only.

# find / -perm /u=r

Sample14:Search for all the files which have user, group and others with executable permissions

# find / -perm /a=x

Sample15: Search for all the files with name test.txt and the owner of this file is user

# find / -user user –name test.txt

Sample16: # find all the files whos name is test.txt and owned by a group called redcluster

# find / -group redcluster –name test.txt

Sample17: Search for a file: test.txt whose file status is changed more than 90 days back

# find / -ctime +90 –name test.txt

Sample18: Search for all the files which are modified exactly 90 days back

# find / -mtime 90

Sample19: Search for all the files with name test.txt which is accessed less than 90 days

# find / -atime -90

Sample20: # find all the files which are modified more than 90 days back and less than 180 days

# find / -mtime +90 –mtime -180

Sample21: # find all the files changed less than 30mins

# find / -cmin -30

Sample22: # find all the files modified exactly 30 mins back

# find / -mmin 30

Sample23: # find all the files accessed more than 30 mins back

# find / -amin +30

Sample24: # find all the files which are modified more than 5mins back and less than 25mins

# find / -mmin +5 –mmin -25

Sample25: I have new file called test.txt which is just created, now I want to get all the files which are created later this file creation.

# find / -newer test.txt

Sample26: Search for files whose size is more than 10bytes

# find / -size +10c

Sample27: Search for files which are exactly 10kb in /opt folder

# find /opt –size 10k

Sample28: Search for files which are less than 10MB in /var folder

# find /var –size -10M

Sample29: Search for files which are more than 1GB size in /usr folder

# find /usr –size +1G

Sample30: # find all the empty files in my system

# find / -size 0k

Sample31:# find all the files which are with more than size 100MB and less than 1GB and the owner of the file is xyz and the file name is Adda.txt in /red folder

# find /red –size +100M –size -1G –user xyz –iname adda.txt

Sample32:# find all the files with SGID for the group sales and with size exactly 100MB with file name as pass.txt under /opt

# find /opt –size 100M –group sales –perm g+s –name pass.txt

Sample33: # find all the files which are more than 100MB and less than 1GB in size.

# find / -size +100M –size -1G
or
# find / -size +100M -a -size -1G

Sample34:# find a file with passwd.txt in /var folder and long list this file for checking file properties.

# find /var –iname passwd.txt –exec ls –l {} \;

Sample35: # find all the files with name test.txt in /mnt and change the ownership of the files from user to Narendra

# find /mnt –user user –name test.txt –exec chown narendra: {} \;
-exec command {} \; –for executing a command on # find files -inum -For # finding a file with inode number

Sample36:# find all the files with name test.sh in /abc folder and then grep if for word is there in that file or not

# find /abc –name test.sh –exec grep ‘for’ {} \;
chmod, grep, ls, rm, mv, cp,md5sum

Sample37: # find all the files with name xyz.txt owned by user in /var/ftp/pub and change the permissions to 775 to them.

# find /var/ftp –user user –name xyz.txt –exec chmod 775 {} \;

Sample 38:# find all the files with name temp.txt in /xyz folder and backup then compress them to send it for saving

# find /xyz –name xyz.txt –exec tar xvfz temp.tar.gz {} \;

Sample39:# find files with name abc.txt in /home directory and take backup of each file before modifying it.

# find /home –name abc.txt –exec cp {} {}.bkf \;
This above command will create files with .bkf extension whenever it # finds abc.txt file.

Sample40:# find files which are more than 1GB and not accessed for the past 6 months and delete them.

# find / -size +1G -mtime +180 –exec rm –rf {} \;

Sample41:# find all the files with executable permissions and display their checksum value

# find / -perm /a=x -exec md5sum {} \;

Sample42:# find all the files with name abc.txt and owner as user then move them to /opt folder

# find / -user user -name abc.txt -exec mv {} /opt/ \;

Sample43:# find files with abc.txt name in /opt directory change the owner permissions from user to Narendra and change the permissions to 775

# find /opt –user user –name abc.txt –exec chown Narendra: {} \; -exec chmod 775 {} \;


Sample44: # find all the commands which ends with .sh file extension in /opt folder

# find /opt –name *.sh

Sample45:

# find /opt –name \*.sh
Or
# find /opt –name “*.sh”
Note: These two will work, because you negated your shell parsing * wild character.

Sample46:Search for all the files which start with abc and ends with different extension in /opt folder

# find /opt –name abc.\*

Sample47:Search for files which start with red and ends with many names such as redhat, redtop, redsoap etc.

# find / -name red\*

Sample 48:How about search for files which always end with dump.

# find / -name \*dump

Sample49: # find abc.txt file in /opt and /var folder at a time

# find /opt /var –name abc.txt
The above command will search in only two locations i.e. in /opt and /var Search multiple locations but not in particular location. Sample50:Search in entire system expect /proc folder

# find / -path /proc -prune -name cpuinfo
The -path variable to define the path of a location. And -prune combined with -path will say not to descend in to the mention path /proc

Sample51:Search for abc.txt in /opt and /var expect in /var/tmp folder

# find /opt /var -path /var/tmp -prune -name abc.txt

Sample52:I want to search for abc.txt and hash.c file at a time. This can be achieved by using -o operator

# find / -name abc.txt -o -name hash.c
Here when ever # find command sees -o it just or the options on its left and right hand side.

Sample53:How about i want to # find two directories say opt and var how can i # find them?

# find / -type d \( -name opt -o -name var \)

Sample54: Negation operator is useful for negating a search team. for Sample we want to # find all the files with name abc.txt which don’t have 755 permissions

# find . -type f ! -perm 755 -name abc.txt

Passwordless SSH Authentications


Howto Linux / UNIX setup SSH with DSA public key authentication (password less login)

Q. How do you set-up SSH with DSA public key authentication? I have Linux laptop called tom and remote Linux server called jerry. How do I setup DSA based authentication so I don’t have to type password?

A. DSA public key authentication can only be established on a per system / user basis only i.e. it is not system wide. You will be setting up ssh with DSA public key authentication for SSH version 2 on two machines:

#1 machine : your laptop called tom
#2 machine : your remote server called jerry

Command to type on your laptop/desktop (local computer)

First login to local computer called tom and type the following command.

Step #1: Generate DSA Key Pair

Use ssh-keygen command as follows:
$ ssh-keygen -t dsa

Output:

Enter file in which to save the key (/home/vivek/.ssh/id_dsa):  Press [Enter] key
Enter passphrase (empty for no passphrase): myPassword
Enter same passphrase again: myPassword
Your identification has been saved in /home/vivek/.ssh/id_dsa.
Your public key has been saved in /home/vivek/.ssh/id_dsa.pub.
The key fingerprint is:
04:be:15:ca:1d:0a:1e:e2:a7:e5:de:98:4f:b1:a6:01 vivek@vivek-desktop
Caution: a) Please enter a passphrase different from your account password and confirm the same.
b) The public key is written to /home/you/.ssh/id_dsa.pub.
c) The private key is written to /home/you/.ssh/id_dsa.
d) It is important you never-ever give out your private key.

Step #2: Set directory permission

Next make sure you have correct permission on .ssh directory:
$ cd
$ chmod 755 .ssh

Step #3: Copy public key

Now copy file ~/.ssh/id_dsa.pub on Machine #1 (tom) to remote server jerry as ~/.ssh/authorized_keys:
$ scp ~/.ssh/id_dsa.pub user@jerry:.ssh/authorized_keys

Command to type on your remote server called jerry

Login to your remote server and make sure permissions are set correct:
$ chmod 600 ~/.ssh/authorized_keys

Linux Configure Netconsole To Log Messages Over UDP Network


Linux Configure Netconsole To Log Messages Over UDP Network

Linux can be configured to log dmesg output to another system via network using syslog. It is done using kernel level networking stuff ia UDP port 514. There is module called netconsole which logs kernel printk messages over udp allowing debugging of problem where disk logging fails and serial consoles are impractical. Most modern distro has this netconsole as a built-in module. netconsole initializes immediately after NIC cards. There are two steps to configure netconsole:

Syslogd server - Let us assume 192.168.1.100 IP having FQDN - syslogd.nixcraft.in. Please note that the remote host can run either 'netcat -u -l -p <port>' or syslogd.
All other systems running netconsole module in kernel

Step # 1: Configure Centralized syslogd

Login to syslogd.nixcraft.in server. Open syslogd configuration file. Different UNIX / Linux variant have different configuration files

Red Hat / CentOS / Fedora Linux Configuration

If you are using Red Hat / CentOS / Fedora Linux open /etc/sysconfig/syslog file and set SYSLOGD_OPTIONS option for udp logging.

# vi /etc/sysconfig/syslog

Configure syslogd option as follows:
SYSLOGD_OPTIONS="-m 0 -r -x"

Save and close the file. Restart syslogd, enter:
# service syslog restart

Debian / Ubuntu Linux Configuration

If you are using Debian / Ubuntu Linux open file /etc/default/syslogd set SYSLOGD option for udp logging.
# vi /etc/default/syslogd

Configure syslogd option as follows:
SYSLOGD_OPTIONS="-r"

# /etc/init.d/sysklogd restart

FreeBSD configuration

If you are using FreeBSD open /etc/rc.conf and set syslogd_flags option option for udp logging. Please note that FreeBSD by default accepts network connections. Please refer to syslogd man page for more information.

Firewall configuration

You may need to open UDP port 514 to allow network login. Sample iptables rules to open UDP port 514:
MYNET="192.168.1.0/24"
SLSERVER="192.168.1.100"
iptables -A INPUT -p udp -s $MYNET --sport 1024:65535 -d $SLSERVER --dport 514 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p udp -s $SLSERVER --sport 514 -d $MYNET --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT

Step # 2: Configure Linux Netconsole

You need to configure netconsole service. Once this service started, you are allowed a remote syslog daemon to record console output from local system. The local port number that the netconsole module will use 6666 (default). You need to set the IP address of the remote syslog server to send messages.

Open /etc/sysconfig/netconsole file under CentOS / RHEL / Fedora Linux, enter:
# vi /etc/sysconfig/netconsole

Set SYSLOGADDR to 192.168.1.100 (IP address of remote syslog server)
SYSLOGADDR=192.168.0.1

Save and close the file. Restart netconsole service, enter:
# /etc/init.d/netconsole restart

A note about Debian / Ubuntu Linux

Red Hat has netconsole init script. However, under Debian / Ubuntu Linux, you need to manually configure netconsole. Type the following command to start netconsole by loading kernel netconsole module, enter:
# modprobe netconsole 6666@192.168.1.5/eth0,514@192.168.1.100/00:19:D1:2A:BA:A8

Where,

6666 - Local port
192.168.1.5 - Local system IP
eth0 - Local system interface
514 - Remote syslogd udp port
192.168.1.100 - Remote syslogd IP
00:19:D1:2A:BA:A8 - Remote syslogd Mac
You can add above modprobe line to /etc/rc.local to load module automatically. Another recommend option is create /etc/modprobe.d/netconsole file and append following text:
# echo 'options netconsole netconsole=6666@192.168.1.5/eth0,514@192.168.1.100/00:19:D1:2A:BA:A8 '> /etc/modprobe.d/netconsole

How do I verify netconsole is logging messages over UDP network?

Login to remote syslog udp server (i.e. 192.168.1.100 our sample syslogd system), enter:
# tail -f /var/log/messages

/var/log/messages is default log file under many distributions to log messages. Refer to /etc/syslog.conf for exact location of your file.

How do I use nc / netcat instead of messing with syslogd?

This is called one minute configuration. You can easily get output on 192.168.1.100 without using syslogd. All you have to do is run netcat (nc) command, on 192.168.1.100:
$ nc -l -p 30000 -u

Login to any other box, enter command:
# modprobe netconsole 6666@192.168.1.5/eth0,30000@192.168.1.100/00:19:D1:2A:BA:A8

Output should start to appear on 192.168.1.100 from 192.168.1.5 without configuring syslogd or anything else.

How to install PHPmyAdmin in Linux


Before installing make sure you have php install on your webserver.

yum install php php-* php-mysql

Step: 1

mkdir /download
Step: 2

cd /download
Step: 3

wget http://sourceforge.net/projects/phpmyadmin/files/phpMyAdmin/3.5.1/phpMyAdmin

Step: 4

tar -xvf phpMyAdmin-3.5.1-english.tar.gz
Step: 5

mv phpMyAdmin-3.5.1-english /var/www/html/phpmyadmin
Step: 6

cd /var/www/html/phpmyadmin/
Step: 7

cp config.sample.inc.php config.inc.php
Step: 8

vi config.inc.php
Step: 9
cahnge Authentication type from cookie to http

save & exit
Step: 10

service httpd restart

time to test phpmyadmin on webserver

http://192.168.2.10/phpmyadmin

Postfix Block or Reject address

This summary is not available. Please click here to view the post.

Install linux RKHunter in linux


wget http://downloads.rootkit.nl/rkhunter-1.2.7.tar.gz

tar -zxvf rkhunter-1.2.7.tar.gz

cd rkhunter-1.2.7

./installer.sh

Now you can run a test scan with the following command:

/usr/local/bin/rkhunter -c

How to setup a daily scan report?

vi /etc/cron.daily/rkhunter.sh

#!/bin/bash
(/usr/local/bin/rkhunter -c --cronjob 2>&1 | mail -s "Daily Rkhunter Scan
Report" email@domain.com)

chmod  x /e
chmod  x /etc/cron.daily/rkhunter.sh

rkhunter --update

Install MRTG in centOS




Centos Install and Configure MRTG

The Multi Router Traffic Grapher (MRTG) is a tool to monitor the traffic load on network-links.

MRTG generates HTML pages containing PNG images which provide a LIVE visual representation of this traffic. You need the following packages:

mrtg : Multi Router Traffic Grapher
net-snmp and net-snmp-utils : SNMP (Simple Network Management Protocol) is a protocol used for network management. The NET-SNMP project includes various SNMP tools. net-snmp package contains the snmpd and snmptrapd daemons, documentation, etc. You also want to install the net-snmp-utils package, which contains NET-SNMP utilities.
This FAQ works with RHEL / CentOS and Fedora Linux.

Step # 1: Install MRTG

Type the following command to install packages using yum command under CentOS / Fedora Linux:
# yum install mrtg net-snmp net-snmp-utils

Step # 2: Configure snmpd

If you need to monitor localhost including interface and other stuff such as CPU, memory etc, configure snmpd. Open /etc/snmp/snmpd.conf, enter:
# vi /etc/snmp/snmpd.conf

Update it as follows to only allow access from localhost:

com2sec local     localhost           public
group MyRWGroup v1         local
group MyRWGroup v2c        local
group MyRWGroup usm        local
view all    included  .1                               80
access MyRWGroup ""      any       noauth    exact  all    all    none
syslocation VSNL, India
syscontact Root <vivek@nixcraft.tld>
Save and close the file. Restart snmpd:
# chkconfig snmpd on
# service snmpd restart

Make sure you see interface IP, by running the following command:
# snmpwalk -v 1 -c public localhost IP-MIB::ipAdEntIfIndex

Sample Outputs:
IP-MIB::ipAdEntIfIndex.123.xx.yy.zzz = INTEGER: 2
IP-MIB::ipAdEntIfIndex.127.0.0.1 = INTEGER: 1
Step # 3: Configure MRTG

Use cfgmaker command to creates /etc/mrtg/mrtg.cfg file, enter:
# cfgmaker --global 'WorkDir: /var/www/mrtg' --output /etc/mrtg/mrtg.cfg public@localhost

--global 'WorkDir: /var/www/mrtg' : add global config entries i.e. set workdir to store MRTG graphs.
--output /etc/mrtg/mrtg.cfg: configr output filename
public@localhost : public is the community name of the device you want to create a configuration for. If you are using the wrong community name you will get no response from the device. localhost is the DNS name or the IP number of an SNMP-managable device i.e. our local server.
Finally, run indexmaker to create web pages which display the status of an array of mrtg interface status pages:
# indexmaker --output=/var/www/mrtg/index.html /etc/mrtg/mrtg.cfg

Step # 4: Verify Cron Job

/etc/cron.d/mrtg runs mrtg command to monitor the traffic load on network links:
# cat /etc/cron.d/mrtg

Sample Output:

*/5 * * * * root LANG=C LC_ALL=C /usr/bin/mrtg /etc/mrtg/mrtg.cfg --lock-file /var/lock/mrtg/mrtg_l --confcache-file /var/lib/mrtg/mrtg.ok
Just make sure crond is running and you are done with configuration:
# chkconfig --list crond

If it is off in run level # 3, just run the following to turn on crond service:
# chkconfig crond on
# service crond on

How do I view mrtg graphs?
You need Apache web server to view graphs, simply type the following to install httpd:
# yum install httpd
# chkconfig httpd on
# service httpd on

Fire a webbrowser and type the url:
http://your-ip.add.ress/mrtg/

http://192.168.1.5/mrtg/


How Do I Create MRTG For My Router at 192.168.1.254?

Run cfgmaker as follows (there is no need to configure snmp for router, as most router and switches comes pre configured with their own SNMPD):
# cfgmaker --global 'WorkDir: /var/www/mrtg' --output /etc/mrtg/mrtg.cfg public@router
OR
# cfgmaker --global 'WorkDir: /var/www/mrtg' --output /etc/mrtg/mrtg.cfg public@192.168.1.254


Hardening CentOS 5


Hardening CentOS 5

Configure user account. logout and relogin as user. su wherever required.
            useradd <username>
eg.        useradd myodduser

        passwd myodduser <new password>

 Configure Default runlevel to runlevel 3
        Use your favorite text editor to edit /etc/inittab
        Find a line  that is similar to the following:
       id:3:initdefault:

Verify the no. after “id:” id-colon  is 3. If it is not make it three.

To restrict virtual terminals to two:
Find out following stanza to enable only two virtual terminals available:

# Run gettys in standard runlevels
1:2345:respawn:/sbin/mingetty tty1
2:2345:respawn:/sbin/mingetty tty2
3:2345:respawn:/sbin/mingetty tty3
4:2345:respawn:/sbin/mingetty tty4
5:2345:respawn:/sbin/mingetty tty5
6:2345:respawn:/sbin/mingetty tty6

Make it to:

# Run gettys in standard runlevels
1:2345:respawn:/sbin/mingetty tty1
2:2345:respawn:/sbin/mingetty tty2
#3:2345:respawn:/sbin/mingetty tty3
#4:2345:respawn:/sbin/mingetty tty4
#5:2345:respawn:/sbin/mingetty tty5
#6:2345:respawn:/sbin/mingetty tty6

Save /etc/inittab and exit

Edit /etc/fstab . For the file systems /tmp, /var, and /home replace the "defaults" with "noexec,nodev,nosuid"

noexec    : Binaries are not allowed to be executed. NEVER use this option for your root file system!
nosuid :  Blocks the operation of suid, and sgid bits.
nodev  : Prevent any user to mount the file system.

Disable unused services in order to save on resources and minimize potential security holes.
These Services that are to be stopped are mentioned here, check appendix A in case of custom requirements.

NetworkManager
NetworkManagerDispatacpid
apmd
autofs
avahi-daemon
avahi-dnsconfd
bluetooth
conman
cpuspeed
cups
dc_client
dc_server
dhcdbd
dund
firstboot
gpm
haldaemon
hidd
ibmasm
ip6tables
ipmi
irda
irqbalance
kdump
kudzu
mcstrans
mdmonitor
mdmpd
microcode_ctl
netfs
netplugd
nfs
nfslock
nscd
oddjobd
pand
pcscd
portmap
rdisc
restorecond
rpcgssd
rpcidmapd
rpcsvcgssd
saslauthd
setroubleshoot
smartd
smb
squid
tux
winbind
wpa_supplicant
xfs
ypbind
yum-updatesd

With following command format:

chkconfig –level 12345 <servicename_to_be_disabled> off

To stop if any of the service is running:
service  <servicename_to_be_stopped> stop

check  /etc/hosts
It must be in the format. (See the 127.0.0.1 line)
127.0.0.1 localhost.localdomain localhost
IP.AD.DR.ESS machine.domain.name machine

Edit  /etc/host.conf
order bind,hosts
multi on
nospoof on

Edit /etc/sysctl.conf - tighten
1. net.ipv4.tcp_syncookies = 1          # Enable TCP SYN Cookie Protection
2. net.ipv4.conf.all.accept_source_route = 0    # Disables IP source routing
3. net.ipv4.conf.all.accept_redirects = 0     # Disable ICMP Redirect Acceptance
4. net.ipv4.conf.all.rp_filter = 1        # Enable IP spoofing protection, turn on source route verification  
5. net.ipv4.icmp_echo_ignore_broadcasts = 1 # Enable ignoring broadcasts request
6. net.ipv4.icmp_ignore_bogus_error_responses = 1 # Enable bad error message Protection
7 net.ipv4.conf.all.log_martians = 1         # Log Spoofed Packets, Source Routed Packets, Redirect Packets

Edit /etc/hosts.deny
portmap: ALL

Edit /etc/hosts.allow
portmap: localhost
portmap: 127.0.0.1

SSH:
Disable RootLogin, force protocol 2, (explore restricting SSH to users/groups )
Protocol 2
HostbasedAuthentication no
PermitRootLogin no
PermitEmptyPasswords no
UsePrivilegeSeparation yes
AllowTcpForwarding no
X11Forwarding no
StrictModes yes
AllowUsers admin user1 user2 user3 (put actual users here in place of userN)

Stripping It Down
Following rpms are to be removed (You may add or remove some packages from this list in order to satisfy your environment.)

xkeyboard-config-0.8-7.fc6
dosfstools-2.11-6.2.el5
finger-0.17-32.2.1.1
dos2unix-3.1-27.1
esound-0.2.36-3
system-config-securitylevel-1.6.29.1-1.el5
NetworkManager-0.6.4-6.el5
OpenIPMI-2.0.6-5.el5.3
apmd-3.2.2-5
acpid-1.0.4-5
system-config-network-1.3.99-1.el5
gnome-python2-gtkhtml2-2.14.2-4.fc6
gnome-python2-bonobo-2.16.0-1.fc6
xorg-x11-drv-mouse-1.1.1-1.1
system-config-display-1.0.48-2.el5
xorg-x11-server-Xorg-1.1.1-48.13.0.1.el5
xorg-x11-server-Xvfb-1.1.1-48.13.0.1.el5
gnome-mime-data-2.4.2-3.1
centos-release-notes-5.0.0-2
xorg-x11-filesystem-7.1-2.fc6
xorg-x11-xauth-1.0.1-2.1
xorg-x11-xkb-utils-1.0.2-2.1
talk-0.17-29.2.2
cpuspeed-1.2.1-1.45.el5
hicolor-icon-theme-0.9-2.1
alsa-lib-1.0.12-3.el5
GConf2-2.14.0-9.el5
xorg-x11-utils-7.1-2.fc6
bluez-gnome-0.5-5.fc6
xorg-x11-xinit-1.0.2-13.el5
ypbind-1.19-7.el5
firstboot-tui-1.4.27.2-1.el5.centos.1
system-config-soundcard-2.0.6-1.el5
yp-tools-2.9-0.1
system-config-samba-1.2.39-1.el5
system-config-kdump-1.0.9-3.el5
tux-3.2.18-9.fc6
xorg-x11-fonts-base-7.1-2.1.el5
gnome-python2-canvas-2.16.0-1.fc6
gnome-mount-0.5-3.el5
xorg-x11-drv-vesa-1.2.1-5.2.el5
xorg-x11-drv-keyboard-1.1.0-2.1
xorg-x11-drv-evdev-1.0.0.5-2.el5
samba-common-3.0.23c-2.el5.2.0.2
xorg-x11-xfs-1.0.2-4
samba-client-3.0.23c-2.el5.2.0.2
xorg-x11-server-Xnest-1.1.1-48.13.0.1.el5
samba-3.0.23c-2.el5.2.0.2
gpm-1.20.1-74.1
xorg-x11-server-utils-7.1-4.fc6
redhat-menus-6.7.8-1.el5
metacity-2.16.0-8.el5
alsa-utils-1.0.12-3.fc6
OpenIPMI-libs-2.0.6-5.el5.3
portmap-4.0-65.2.2.1
nfs-utils-1.0.9-16.el5
system-config-nfs-1.3.23-1.el5
subversion-1.4.2-2.el5
gnome-python2-gconf-2.16.0-1.fc6
gnome-python2-extras-2.14.2-4.fc6
gnome-python2-gnomevfs-2.16.0-1.fc6
xorg-x11-drv-void-1.1.0-3.1

Security and management tool installations and fine tuning:
Security Tools Download, install and run:
a. chkrootkit - http://www.chkrootkit.org/download/
Download to /usr/local/src
Extract using "tar -zxf"
Compile & Install using "make sense"
Run chkrootkit

b. rkhunter - http://www.rootkit.nl/projects/rootkit_hunter.html
Download to /usr/local/src
Extract using "tar -zxf"
Install using ./install.sh
./installer.sh --layout /usr/local –install
rkhunter --update
Run "rkhunter -c --createlogfile"

Management Tool:. Download, install, configure: Webmin with SSL
Package Dependencies
Ensure openssl and openssl-devel are installed
rpm -q openssl
rpm -q openssl-devel
If they are not installed, install them using:
yum install openssl openssl-devel -y
(Mention ONLY those packages that need to be installed).

Download the Webmin RPM - http://www.webmin.com/
Download the RPM to /usr/local/src
Install using rpm -Uvh
Go to https://IP.AD.DR.ESS:10000 to configure. Login with user root, and password
1. Under Webmin -> Users -> Edit the root user. Rename root user to "admin"
2. Under Logging ensure all events by all users are logged
3. Change the port from 10000 to a suitable one above 50000 (and below 60000).
4. Under Authntication - set the idle time-out to 5 minutes.

d. Perl Libraries

Net::SSLeay - http://www.cpan.org/modules/by-module/Net/Net_SSLeay.pm-1.30.tar.gz
Download to /usr/local/src/
Extract with tar -xzf
Prepare with "perl Makefile.PL"
Compile & Install with "make install"
Test installation with "perl -e 'use Net::SSLeay'". You should be returned to the prompt. If you get errors, the installation did not succeed.

e. Portsentry -ftp://194.199.20.114/linux/freshrpms/fedora/linux/1/portsentry/portsentry-1.1-11.fr.i386.rpm
Download the RPM to /usr/local/src
Install using rpm -Uvh
Edit /etc/portsentry/portsentry.conf
Edit /etc/portsentry/portsentry.modes
Edit /etc/portsentry/portsentry.ignore
Start portsentry.

f. Checksuite - http://checksuite.sourceforge.net/
Download the RPM to /usr/local/src
Install using rpm -Uvh

g. Fine Tuning IPTABLES:
edit /etc/sysconfig/iptables

Insert rules for trusted ip addresses only which should access ssh port.

-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -s <trusted ip address>  -j ACCEPT

These rules are to be added before following rule:
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited

Also you will have to make sure other ports are kept open (Those considered under Pre-Installation preparation)

Turning off un-wanted services on linux machines


chkconfig atd  off
chkconfig auditd  off
chkconfig avahi-daemon  off
chkconfig bluetooth  off
chkconfig cgconfig  off
chkconfig cgred  off
chkconfig cups  off
chkconfig dc_client  off
chkconfig dc_server  off
chkconfig dnsmasq  off
chkconfig ebtables  off
chkconfig firstboot  off
chkconfig gpsd  off
chkconfig haldaemon  off
chkconfig ip6tables  off
chkconfig iptables   off
chkconfig irda  off
chkconfig iscsi  off
chkconfig iscsid  off
chkconfig ksm  off
chkconfig ksmtuned  off
chkconfig libvirt-guests  off
chkconfig libvirtd  off
chkconfig lvm2-monitor  off
chkconfig mdmonitor  off
chkconfig NetworkManager  off
chkconfig netconsole  off
chkconfig netfs  off
chkconfig nfs  off
chkconfig nfslock  off
chkconfig nmb  off
chkconfig ntpd  off
chkconfig ntpdate  off
chkconfig openct  off
chkconfig openvpn  off
chkconfig pcscd  off
chkconfig portreserve  off
chkconfig psacct  off
chkconfig rdisc  off
chkconfig restorecond  off
chkconfig rpcbind  off
chkconfig rpcgssd  off
chkconfig rpcidmapd  off
chkconfig rpcsvcgssd  off
chkconfig rsyslog  off
chkconfig saslauthd  off
chkconfig sendmail  off
chkconfig smb  off
chkconfig smolt  off
chkconfig snmpd  off
chkconfig speech-dispatcherd  off
chkconfig snmptrapd  off
chkconfig squid  off
chkconfig svnserve  off
chkconfig vboxdrv  off
chkconfig vboxweb-service  off
chkconfig wicd  off
chkconfig wpa_supplicant  off
chkconfig ypbind off
===========================================================

Following services for Apache and Mysql running on the same server.
chkconfig abrtd  on
chkconfig httpd  on
chkconfig network  on
chkconfig mysqld  on
chkconfig sshd  on
chkconfig udev-post  on
chkconfig xinetd on

VI commands in Details

General Startup
To use vi: vi filename
To exit vi and save changes: ZZ   or  :wq
To exit vi without saving changes: :q!
To enter vi command mode: [esc]

Cursor Movement
h      move left (backspace)
j       move down
k      move up
l       move right (spacebar)
[return]   move to the beginning of the next line
$       last column on the current line
0       move cursor to the first column on the current line
^       move cursor to first nonblank column on the current line
w      move to the beginning of the next word or punctuation mark
W     move past the next space
b       move to the beginning of the previous word or punctuation mark
B       move to the beginning of the previous word, ignores punctuation
 e       end of next word or punctuation mark
 E       end of next word, ignoring punctuation
 H       move cursor to the top of the screen
 M       move cursor to the middle of the screen
 L        move cursor to the bottom of the screen

Screen Movement
       G       move to the last line in the file
       xG     move to line x
       z+      move current line to top of screen
       z        move current line to the middle of screen
       z-      move current line to the bottom of screen
       ^F      move forward one screen
       ^B      move backward one line
       ^D      move forward one half screen
       ^U      move backward one half screen
       ^R      redraw screen
       ^L      redraw screen

Inserting
       r       replace character under cursor with next character typed
       R      keep replacing character until [esc] is hit
       i        insert before cursor
       a       append after cursor
       A      append at end of line
       O      open line above cursor and enter append mode

Deleting
x       delete character under cursor
dd     delete line under cursor
 dw    delete word under cursor
 db     delete word before cursor

Copying Code
        yy      (yank)'copies' line which may then be put by the p(put) command. Precede with a count for multiple lines.

Put Command brings back previous deletion or yank of lines, words, or characters
        P       bring back before cursor
        p       bring back after cursor

Find Commands
?       finds a word going backwards
/       finds a word going forwards
 f       finds a character on the line under the cursor going forward
 F      finds a character on the line under the cursor going backwards
 t       find a character on the current line going forward and stop one character before it
T      find a character on the current line going backward and stop one character before it
; repeat last f, F, t, T

Miscellaneous Commands
. -----> repeat last command
u -----> undoes last command issued
U -----> undoes all commands on one line
xp -----> deletes first character and inserts after second (swap)
J -----> join current line with the next line
^G -----> display current line number
% -----> if at one parenthesis, will jump to its mate mx mark current line with character x
'x -----> find line marked with character x

Line Editor Mode
Any commands form the line editor ex can be issued upon entering line mode.

To enter: type ':'
To exit: press[return] or [esc]

READING FILES
copies (reads) filename after cursor in file currently editing
:r filename

WRITE FILE
:w saves the current file without quitting

MOVING
:# move to line #
:$ move to last line of file
:^ move to the begining of a line

SHELL ESCAPE
executes 'cmd' as a shell command.
:!'cmd'

Account Expiry Notifications in linux

#! /usr/bin/perl
####################################################################
# Description:
# This script emails a user when their:
# - password is within 14 days of expiring.
# - password is expired
#
# This script requires the following to work:
# - Each user needs a $HOME/.forward file that contains a valid
#   email address.
# - The $HOME/.forward file must be owned by the user account
#####################################################################
$HOST=`uname -n`;  chomp($HOST);
$UNIXSUPPORT="some_email@domain.com";
$epoch = int(time/(60*60*24));

open(SHADOW, "< /etc/shadow");
while (<SHADOW>) {
  ($USER, $encr_pass, $created, undef, $exp_days, undef, undef, undef)=split(/:/, $_);
  chomp($shel = `egrep "^$USER:" /etc/passwd | cut -d: -f6`);
  next if $shel =~ m(/sbin/nologin);  # we don't care about accounts w/ nologin shell
  $PASS_AGE = ($exp_days-($epoch-$created));

  if ($encr_pass =~ m{^\!\!$} || $encr_pass =~ m{^\*$}){
          $Nothing = 0; # Account is locked/password not set - skip this condition
          next;


  }elsif ($encr_pass =~ m{^\!.*$})  {
          $Nothing = 0;  # Account is administratively locked - skip this condition
          next;


  } elsif ($created eq "0" || $exp_days eq "99999")  {
          # Password aging is disabled for the account - Set the correct policy for the user
          `passwd -x 90 -w 14 $USER`;                     # password expires in 90 days/Warning 14
          `chage -d 0 $USER`;                             # Force password change on next login
           next;


  } elsif ($PASS_AGE >= 0 && $PASS_AGE <= 14)  {
          # password expires within 14 days - notify user

          $SUBJECT = "Password expiration notification for $USER from $HOST";
          &SendMail("$USER", "$SUBJECT", "

Notice:  The user account $USER will expire in $PASS_AGE days on $HOST.
Login and change the password before the expiration date or the account may be locked.

Your new password must conform to the following policies:
 - Minimum of 8 characters in length
 - Contains at least 1 special character within the first 8 characters
 - Contains at least 1 numeric character within the first 8 characters


Contact the Support Team for any further assistance.
");

         next;

  } elsif ($PASS_AGE < 0 && $PASS_AGE > -90) {
          # password is expired - notify user

          $SUBJECT = "Password expiration notification for $USER from $HOST";
          &SendMail("$USER", "$SUBJECT", "

Notice:  The user account $USER expired $PASS_AGE days ago on $HOST.
Login and change the password or the account may be locked or removed.

Your new password must conform to the following policies:
 - Minimum of 8 characters in length
 - Contains at least 1 special character within the first 8 characters
 - Contains at least 1 numeric character within the first 8 characters

Contact the Support Team for any further assistance.
");

       next;

  } elsif ($PASS_AGE < -90 ) {
          # Password has been expired for more than 90 days - lock and notify support for deletion
          `passwd -l $USER`;                             # Lock the account
          `/usr/sbin/usermod -s /sbin/nologin $USER`;    # Set a nologin shell

          $SUBJECT = "User account $USER has been expired for 90 days or more";
          &SendMail("root", "$SUBJECT", "

Notice:  The user account $USER expired $PASS_AGE days ago on $HOST.
Since the user has not changed the password, consider removing the account.
");
          next;

  }

}
close(SHADOW);
#############################################################################
### Define the subroutines below
#############################################################################

###
#1# Send a message to the user
###
sub SendMail {
  my ($to, $subject, $message) = @_;
  my $sendmail = '/usr/sbin/sendmail';
  open(MAIL, "|$sendmail -oi -t");
  print MAIL "From: $UNIXSUPPORT\n";
  print MAIL "To: $to\n";
  print MAIL "Subject: $subject\n\n";
  print MAIL "$message\n";
  close(MAIL);
}

Most useful Linux Commands

ls     ------------------------------ List all files and directories
ls -l  ------------------------------ List all files and directories with some extra information
dir  ------------------------------  Display directories
mkdir <name> ------------------------------ Create a directory
mkidr -p <dir_name1>/<dir_name2>------------------------------Create multiple directories
rmdir <dir_name>------------------------------Remove an empty directory
rm <file_name>------------------------------Remove a file/directory with confirmation
rm -rf <file/dir_name>------------------------------Remove file/directory without confirmation
cat <file_name>------------------------------View a file
cat > <file_name>------------------------------Create a new file and edit it
touch <file_name>------------------------------Create a file
vi <file_name>------------------------------File editor
vim <file_name>------------------------------File editor
command >file_name------------------------------Write output of the command into the file
cd      ------------------------------Change directory
cd ..   ------------------------------Move one directory back
cd -    ------------------------------Move to previous directory
cd ~    ------------------------------Move to current user’s home directory
cd /home/me ------------------------------Move to /home/me directory
shutdown -h now ------------------------------Shuts the system down to halt immediately.
shutdown -r now ------------------------------Shuts the system down immediately and the system reboots.
mv -i myfile yourfile ------------------------------Move the file from “myfile” to “yourfile”. This effectively changes the name of “myfile” to “yourfile”.
mv -i /data/myfile .  ------------------------------Move the file from “myfile” from the directory “/data” to the current working directory.
echo <text>  ------------------------------Display the text
find              ------------------------------Search for files in a directory hierarchy
locate           ------------------------------Search for files in a directory hierarchy
grep             ------------------------------Depth Search
wc               ------------------------------Word count
kill               ------------------------------To kill a process
reboot         ------------------------------Reboot the system
poweroff     ------------------------------poweroff the system
mount          ------------------------------mount a partition
umount        ------------------------------unmount a partition
fdisk -l        ------------------------------Partition manipulator

System Informations
pwd  ------------------------------Prints present working directory
hostname ------------------------------Prints hostname
uname    ------------------------------ prints the name of OS
whoami  ------------------------------ Prints your login name
date       ------------------------------ Prints system date
cal <year> ------------------------------Prints calendar of the year
who          ------------------------------ Determine the users logged on the machine
w             ------------------------------  Determine who is logged on the system
rwho -a   ------------------------------   Determine the remote users
finger <user_name>  ------------------------------System info about user
last     ------------------------------Show list of users last logged-in on your system
lastb   ------------------------------Show last unsuccessful login attempts on your system
history  ------------------------------Show the used commands
history -c ------------------------------Clears all history
comman    ------------------------------Run the most recent command from the bash history commands that start with the string “ comman “
uptime  ------------------------------Display the system uptime
ps    ------------------------------Process status
ps -aux | more ------------------------------ List all the currently running process
top        ------------------------------ List the currently running process, sorted by CPU usage
gtop, ktop, htop   ------------------------------ GUI choice for top
arch       ------------------------------ Display the system architecture
Xorg -version    ------------------------------ Show the version of X windows I have on my system
cat /etc/issue ------------------------------ Check what distribution you are using
free -m    ------------------------------ Check your usage, free memory of primary memory
df -h   ------------------------------ Disk free information in human readable form
du / -bh | more   ------------------------------ Print detailed disk usage for each sub-directory starting at the “/” (root) directory
cat /proc/cpuinfo ------------------------------ Displays cpu information
cat /etc/interrupts ------------------------------ List the interrupts in use
cat /proc/version ------------------------------ Linux version and other info
cat /proc/filesystems ------------------------------ Show the type of filesystem currently in use
cat /etc/printcap | less ------------------------------ Show the setup of printers
lsmod   ------------------------------ Show the currently loaded kernel modules
set | more ------------------------------ Show the current user environment
env | more ------------------------------ Show environment variables
dmesg | less ------------------------------ Print kernel messages
chage -l <user_login_name>  ------------------------------See my password expiry information
chage username   ------------------------------ Change User's Expiry
quota    ------------------------------ Display my disk quota
sysctl -a | more ------------------------------ Display  all the configurable Linux kernel parameters
runlevel    ------------------------------ Print the previous and current runlevel

IP tables
iptables –L ------------------------------ Lists the current filter rules
iptables –F ------------------------------ Flush the rules temporarily / Disable the rules temporarily
iptables –h ------------------------------ Prints help information

Networking
ifconfig ------------------------------ Displays all the interface information
ifstat ------------------------------ Check the current network usage
iptraf  ------------------------------ A network utility allows you check the network activities
ifup ------------------------------ Bring a network interface up
ifdown  ------------------------------ Bring a network interface down

Help
man <command_name> ------------------------------ Display man pages of the command
<command_name> –help ------------------------------ Command help
info <command_name> ------------------------------ Helping command
whatis <command_name> ------------------------------ Display man pages description

Compress and decompress
tar –cvf <file_name.tar> <file_name_1> <file_name_2> . .   ------------------------------ Compress files
tar –xvf <file_name.tar>     ------------------------------ Decompress the compressed file
tar –xvf <file_name.tar> – C <location>   ------------------------------ Decompress files to desired location
tar –zcvf <file_name.tar.gz> <file_name_1> <file_name_2>  ------------------------------ Compress files with gz
tar –zxvf <file_name.tar.gz> ------------------------------ Decompress the compressed gz files
tar –zxvf <file_name.tar.gz> -C <location> ------------------------------ Decompress files to desired location

apt-get commands
apt-get install <package_name> ------------------------------ Installing package(s)
apt-get remove <package_name>  ------------------------------ Removing package(s)
apt-get update  ------------------------------ Update the repository
apt-cdrom add  ------------------------------ Add CD ROM archives to repository
apt-cdrom ident ------------------------------ Identify CD-ROM disk
apt-get  -d install <package_name> ------------------------------ Download packages, no installation or unpacking
apt-get –purge remove <package_name>--------- Remove all traces of a package, incl. Configuration files etc.,
apt-get –u update ------------------- Upgrades all installed packages, but does not remove any packages to resolve dependencies
apt-get –u dist-upgrade -------------- Upgrades all the installed packages, removes or installs packages as needed to satisfy all dependencies
apt-cache search <package_name> -------------------- Search package in the cache
apt-get check ------------------------------ Check broken dependencies
apt-cache autoclean ------------------------------ Remove cached packages that are no longer needed
apt-cache clean  ------------------------------ Remove all cached packages
apt-get help ------------------------------ Help

dpkg commands
dpkg –l ------------------------------ List all the installed packages
dpkg –L  <package_name>------------------------------ List files belonging to a package
dpkg –S <file_name> ------------------------------ To See which package a file belongs to
dpkg –s <package_name>------------------------------ To show complete package information
dpkg –yet-to-unpack  ------------------------------ To look for downloaded, uninstalled packages
dpkg –audit ------------------------------ Show partially installed packages
dpkg -i <package> ------------------------------ Install a new package
dpkg -r <package> ------------------------------ Remove a package

Yum Commands
yum list [available|installed|extras|updates|obsoletes|all|recent] [pkgspec]
yum list ------------------------------ List packages enabled in the repository
yum list all ------------------------------ List packages enabled in the repository
yum list available ----Lists all the packages available to be installed in any enabled repository on your system
yum list installed -------------------------- Lists all the packages installed on the system
yum list extras -------- Lists any installed package which no longer appears in any of your enabled repositories
yum list obsoletes ------Lists any obsoleting relationships between any available package and any installed package
yum list updates -----Lists any package in an enabled repository which is an update for any installed package
yum list recent -----------------Lists any package added to any enabled repository in the last seven(7) days
yum list pkgspec ---------------------Refine your listing for particular packages
yum check-update -----------------------It returns an exit code of 100 if there are any updates available
yum info -----------------------------Displays information about any package installed or available
yum search ------------------------------ Search and list the packages
yum provides/yum whatprovides Searches for which packages provide the requested dependency of file and also takes wildcards for files
yum clean  ------------------------- Clean up the cache of metadata and packages
yum clean packages ----------Cleans up any cached packages in any enabled repository cache directory
yum clean metadata -------Cleans up any xml metadata that may have been cached from any enabled repository
yum clean dbcache ---------------- Clean up the cached copies of those from any enabled repository cache
yum clean all ------------------------------ Clean all cached files from any enabled repository
yum shell  /  yum makecache ------------------------------These two commands are used to download and make usable all the metadata for the currently enabled yum repos

RPM Commands
rpm –ivh <package_name>--------------------- Install a new package
rpm –Uvh <package_name>------------------- Update an already installed package
rpm –e<package_name> -------------------------- Remove a package
rpm –aq ------------------------------  To list all rpm packages installed on your system
rpm –F <package_name> ------------------------------ Freshening up the already installed package
rpm –version ------------------------------  Prints rpm version

Send emails to everyone of your linux machine

# vi /etc/alias  <---- edit alias file

add the following line at the bottom of the page
allusers:  user1,user2

update the alias database
# newaliases

Using the above concept you can mail to all users of your office with following line in your
/etc/alias file:

When there are unlimited users
allusers:  user1,user2,user3............. user500

But thats not a smart solution. Each time a new email user created and quit , you need to keep the /etc/alias database update.

1.Mail Forwarding with sendmail

To make your task easy, create an alais entry
# vi /etc/alias
allusers:        :include:/etc/mail/allusers

# newaliases
# touch /etc/mail/allusers

Now each time before sending mail to  alluser@yourdomain.com run the following command in your terminal

# awk -F: '$3 > 100 { print $1 }' /etc/passwd > /etc/mail/allusers

If you dont want to remember this long line you can make a binary file with this command and execute the file before sending mail to  allusers@yourcompany.com

# vi /usr/bin/nameofusers
awk -F: '$3 > 100 { print $1 }' /etc/passwd > /etc/mail/allusers

2. Mail Forwarding with sendmail

# chmod 755 /usr/bin/nameofusers
Now each time before sending mail to  alluser@yourdomain.com run the following command in your terminal

#/usr/bin/nameofusers
It'll send email to those users who are currently listed in /etc/passwd file.

Shutdown linux machine by non root user


Shutdown/ Reboot linux machine by non root user
 
01. Create a group testgroup and a user test under this group
#  groupadd testgroup
# adduser -G testgroup test

02. Temporarily change permissions of /etc/sudoers, so you have write permission on this file:
# chmod u+w /etc/sudoers

03. Give the the Group and its users permission to execute the shutdown command by editing
/etc/sudors

# vi /etc/sudoers
Add the following Line:
%testgroup ALL= NOPASSWD: /sbin/shutdown

04. Remove the write persmission on /etc/sudoers file
 1 / 2Shutdown by Non-Root User
 
# chmod u-w /etc/sudoers
04. Any user of Group "testgroup" (i.e user test) can shutdown the Linux box by executing
following command
# sudo shutdown -h now

Perform command at time


Uses of "at" command to do job at specific time:
 
01. For example,  your office declared the internet connection will be off after 8 pm, but you've to leave office now. don't worry ! just issue the following command and get out of your office. If you use squid type the following command:

# at 20:00
at> service squid start
(Press CTRL+D to save)

If you use your linux box as router:
# at 20:00
at> echo 1 > /proc/sys/net/ipv4/ip_forward

02. When I take exam in my class, the questions and answer sheet is available in my webserver. If the exam starts from 10.00 am and ends at 11.00 am.
# at 10:00
 1 / 5Perform a command at specific time
 
at> service httpd start
CTRL+D

# at 11:00
at> service httpd stop
CTRL+D

03. When the last date of submission a project through ftp is 06:00 pm, 11th June, 2011
# at 18:00 06/11/2011
at> service vsftpd stop
CTRL+D
Two more "at" related utilities
atq : show the current pending jobs
 2 / 5Perform a command at specific time

atrm: remove any pending job
While "at" command is used for performing a command (or run a script) once at a specific time,"cron" is used to perform the job repeatably at a specific time. For example, If your office decided to keep your internet from 08.00 am to 6.00 pm everyday, you need to do the
followings:
 
01. Create two executable scripts which will be used to stop squid and start squid
# vi /usr/sbin/stopsquid
------------------------------------------
#! /bin/bash
service squid stop
------------------------------------------
# chmod 755 /usr/sbin/stopsquid
 3 / 5Perform a command at specific time

# vi /usr/sbin/startsquid
 
------------------------------------------
#! /bin/bash
service squid start
------------------------------------------
# chmod 755 /usr/sbin/startsquid
02. run the corn at 08 hours and 18 hours

# crontab -e

00 18 * * * /usr/sbin/stopsquid
00 08 * * * /usr/sbin/startsquid

# service crond restart
 4 / 5Perform a command at specific time

For more information about corn: manpage of crontab, crond

Searching and File Operations in linux

TOP 10 largest file
# find /var -type f -ls | sort -k 7 -r -n | head -10

FIND FILES MORE THAN 5Gb
# find /var/log/ -type f -size +5120M -exec ls -lh {} \;

Find all temp files older than a month and delete:
# find /usr/home/admin/Maildir/new -mtime +30-type f | xargs /bin/rm -f

# find /usr/local/apache -mtime +30-type f | xargs /bin/rm -f

# find /usr/home/admin/Maildir/new -mtime +30-type f | xargs /bin/rm -f

# find /usr/local/apache* -type f -mtime +30 -exec rm '{}' '+'

# find /home/ksucre/Maildir/new/ -mtime +50-type f | xargs /bin/rm -f

# find /usr -size +5000M

To find files older than, for example, 10 days.
# find /home/user1/Maildir/new -mtime +10

Find files older than, say, 30 minutes:
# find /tmp -mmin +30

Remove files older than x days like this
# find /path/* -mtime +x -exec rm {} \;