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