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 {} \;

Postfix Useful Commands

To Check Postfix Queue
#mailq

To Check Sasl Auth
#tail -f /var/log/messages|grep sasl

To Check Posfix Logs
#tail -f /var/log/maillog|grep postfix

List of domains that are being deferred
#qshape-maia -s  deferred

Checking Specific Mail From Queue
---------------------------------------
To view the full mails
#postcat -q D5EB71AEA45
If you an error postcat: fatal: open queue file D5EB71AEA45: No such file or directory, Then it means mail has been delivered or removed using postsuper

If you want to remove specific mail from queue
#postsuper -d  D5EB71AEA45

Sorting Queued Mails By From Address:
# mailq | awk '/^[0-9,A-F]/ {print $7}' | sort | uniq -c | sort -n

Removing Mails Based On Sender Address
# mailq| grep '^[A-Z0-9]'|grep peggysj@msn.com|cut -f1 -d' ' |tr -d \*|postsuper -d -

or, if you have put the queue on hold, use
# mailq | awk '/^[0-9,A-F].*capitalone@mailade.com/ {print $1}' | cut -d '!' -f 1 | postsuper -d -
to remove all mails being sent using the From address “capitalone@mailade.com”.


if you want to remove all mails sent by the domain msn.com from the queue
#mailq| grep '^[A-Z0-9]'|grep @msn.com|cut -f1 -d' ' |tr -d \*|postsuper -d -

Memory Flushing Commands+PageCaches




To free dentries and inodes:
#echo 1 > /proc/sys/vm/drop_caches

To free pagecache, dentries and inodes:
#echo 2 > /proc/sys/vm/drop_caches

#echo 3 > /proc/sys/vm/drop_caches

Exim mail commands, frozen emails

To know the number of frozen mails in the mail queue, you can use the following command

#exim -bpr | grep frozen | wc -l

In order to remove all frozen mails from the Exim mail  queue, use the following command

#exim -bpr | grep frozen | awk {'print $3'} | xargs exim -Mrm

You can also use the command given below to delete all frozen mails

#exiqgrep -z -i | xargs exim -Mrm

If you want to only delete frozen messages older than a day, you can try the following

#exiqgrep -zi -o 86400

where you can change the value 86400 depending on the time frame you want to keep (1 day = 86400 seconds).

Test SMTP operations using Telnet


How to test SMTP operations using Telnet

1. Telnet into Exchange server hosting IMS service using TCP port 25.
Command is telnet <servername> 25

2. Turn on local echo on your telnet client so that you can see what you are typing.
On Win 9x and NT 3.5/4.0 Telnet client this done by selecting the "preferences" from the "terminal" pull down menu, and checking the local echo radio button.  For Windows 2000 telnet client, issue command "set local_echo", from the telnet command prompt.

3. Issue the following smtp command sequence

helo <your domain name><enter>                
response should be as follows
250 OK

mail from: <your Email Address><enter>
response should be as follows
250 OK - mail from <your Email address>

rcpt to: <recipient address><enter>
response should be as follows
250 OK - Recipient <recipient address>

data<enter>
response should be as follows
354 Send data.  End with CRLF.CRLF

To: <recipient's display name><enter>
From: <your display name><enter>
Subject: <Subject field of Email message><enter>
<Enter you body text><enter><enter> . <enter>
response should be as follows
250 OK

quit<enter>


######################################################

telnet: > telnet pop.example.com pop3
telnet: Trying 192.0.2.2...
telnet: Connected to pop.example.com.
telnet: Escape character is '^]'.
server: +OK InterMail POP3 server ready.
client: USER MyUsername
server: +OK please send PASS command
client: PASS MyPassword
server: +OK MyUsername is welcome here
client: LIST
server: +OK 1 messages
server: 1 1801
server: .
client: RETR 1
server: +OK 1801 octets
server: Return-Path: sender@example.com
server: Received: from client.example.com ([192.0.2.1])
server:        by mx1.example.com with ESMTP
server:        id <20040120203404.CCCC18555.mx1.example.com@client.example.com>
server:        for <recipient@example.com>; Tue, 20 Jan 2004 22:34:24 +0200
server: From: sender@example.com
server: Subject: Test message
server: To: recipient@example.com
server: Message-Id: <20040120203404.CCCC18555.mx1.example.com@client.example.com>
server:
server: This is a test message.
server: .
client: DELE 1
server: +OK
client: quit
server: +OK MyUsername InterMail POP3 server signing off.

crontab examples


# run this command every minute of every day to check apache
* * * * * /var/www/devdaily.com/bin/check-apache.sh

# this command will run at 12:05, 1:05, etc.
5 * * * * /usr/bin/wget -O - -q -t 1 http://localhost/cron.php

# run the backup scripts at 4:30am
30 4 * * * /var/www/devdaily.com/bin/create-all-backups.sh


// every 5 minutes
0,5,10,15,20,25,30,35,40,45,50,55  * * * * /var/www/devdaily.com/bin/do-update.sh

# run this crontab entry every 5 minutes
*/5 * * * * /var/www/devdaily.com/bin/do-update.sh

  string   meaning
  ------   -------
  @reboot   Run once, at startup.
  @yearly   Run once a year, "0 0 1 1 *".
  @annually   (sames as @yearly)
  @monthly   Run once a month, "0 0 1 * *".
  @weekly   Run once a week, "0 0 * * 0".
  @daily   Run once a day, "0 0 * * *".
  @midnight   (same as @daily)
  @hourly   Run once an hour, "0 * * * *".

min    hour    mday   month   wday   Execution time
30       0           1           1,6,12      *           00:30 Hrs on 1st of Jan, June & Dec.
0         20        *           10         1-5           8.00 PM every weekday (Mon-Fri) only in Oct.
0         0          1,10       *              *            midnight on 1st & 10th  of month
5,10    0          10          *             1             At 12.05,12.10 every Monday & on 10th of every month

Useful FreeBSD/UNIX commands

Useful FreeBSD/UNIX commands:

#pwd                Present Working Directory
#uptime             Server UpTime stats & operation                
#df                    Disk Free space
#w                   Who is logged on & server info
#who                WHO is logged on and IP address
#last                 LAST users logged on and statuses
#ac                 ACcounting of total time logged on
#top                TOP processes currently executing listed per CPU time
#ps aux
#ps ax
#uname -a
#env                Shows current environment variables, including user & path
#set
#netstat
#trafshow
#cd                 Change the Directory that you are working in
#man                Show the MANual pages for a program
#tail -300 maillog  Show the TAILend of the 'maillog' file -- last 300 lines
#kill -9 PID        KILLs a specific process # (PID), non-catchable, non-ignorable (-9)
#shutdown -r now    ShutDown the computer, then reboot, immediately
#id
#hostname
#vmstat -w 5
#vmstat boot
#more               Display a file, showing a page at a time. Show MORE by hitting 'space'.
#head
#tail
#ls -lt             LiSt (-l with L_ots of info) (-t sort by time)
#ls -laTFWi         LisT all info
#pwd
#users              Shows which users are logged on using shell / command line
pkg_info           List the packages installed                
pkg_add            Add a package
ftp ftp.gnu.org    connects to ftp site ftp.gnu.org
Ctrl-C              Cancel operation
Ctrl-S               Pause operation
Alt-F1              Alternate to the 1st terminal window when using 'shell'
Alt-F2              Alternate to the 2nd terminal window when using 'shell'

FIND (starting in root dir) "nameoffile" or anything begining with that
#find / -name "name_of_file*"
       
FIND files modified within last day:
#find / -mtime -1 -print

FIND files modified over 5 days ago:
#find / -mtime +5 -print

Compress a log file, then mail as an attachment
#gzip -c access_log.processed -v > access_log.processed.gz; ls -lt        
#uuencode access_log.processed.gz DOMAIN.com.log.gz | mail -s "DOMAIN.com Log File" SomeEmail@xyz.com        
Or inline:

#mail -s "Some Text File" email@domain.com < file.log

LiSt files with all info R = recurse subdirs.  Takes 3 hours!
#ls -laTFWiR

Change the owner to 'userowner' of directory 'somedirectory'
#chown userowner somedirectory

Show brief statistics about qmail
#/usr/local/psa/qmail/bin/qmail-qstat

Show the summary info for EACH email in qmail queue
#/usr/local/psa/qmail/bin/qmail-qread

Email Server in details


What you Need
- Linux Server with Centos 4/5 (VPS or Dedicated)
- Apache 2 with PHP4 or later
- Postfix (SMTP server or MTA)
- Dovecot ( IMAP/POP3 server)
- Squirrelmail (A free Webmail)

What you should know?
1. DNS Entry for your mail server with MX record
2. Setup an SPF record (see openspf.org
)
3. Setup Domain Name Keys
4 . Reverse IP for your Mail Server

Install Postfix (SMTP Server/MTA)

#yum remove sendmail
#yum install postfix

#vi /etc/postfix/main.cf
myhost= mail.example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = all
mydestination = $myhostname, $mydomain

NOTE: Make sure you uncomment inet_interfaces = localhost

Setting up SASL + TLS
We have to also setup SASL with our postfix to authenticate our users who want to send email outside of the permitted network.

#vi /etc/postfix/main.cf

add the following lines

smtpd_sasl_auth_enable = yes
smtpd_recipient_restrictions = permit_mynetworks,permit_sasl_authenticated,reject_unauth_destina tion
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth

Install Dovecot (POP3/IMAP Server)
Dovecot is a very popular POP3/IMAP server. The main difference between POP3 and IMAP is while accessing the your email with  outlook if you use POP3 the mail is downloaded to your computer and deleted from the server. With IMAP the mail is retained in the server. IF any problem occurs while downloading the emails are lost with POP3. The configuration file is located at

#vi /etc/dovecot.conf

#yum install dovecot
#vi /etc/dovecot.conf
protocols = imap imaps pop3 pop3s
Look for the line auth default and make these changes
auth default {
mechanisms = plain login
passdb pam {
}
userdb passwd {
}
socket listen {
client {
path = /var/spool/postfix/private/auth
mode = 0660
user = postfix
group = postfix
}
}
}

Install Squirrelmail

#yum install squirrelmail

To setup the squirrelmail under apache, open  /etc/httpd/conf/httpd.conf and insert the following lines

Alias /squirrelmail /usr/local/squirrelmail/www
<Directory /usr/local/squirrelmail/www>
Options Indexes
AllowOverride none
DirectoryIndex index.php
Order allow,deny
allow from all
</Directory>

The squirrelmail configuration utility is located in /usr/share/squirrelmail/config/conf.pl. Run the configuration utility and set the server settings to SMTP and change your domain name to example.com

/usr/share/squirrelmail/config/conf.pl

Before you access squirrelmail or mail restart all the services

#/etc/init.d/postfix start
#/etc/init.d/dovecot start
#/etc/init.d/saslauthd start
#service httpd restart

To access squirrelmail point your browser to
http://www.domain.com/webmail

Create Local Users
#adduser john
#passwd john

Using Outlook Express
Email: john@domain.com

Incoming POP3 settings: mail.domain.com
Outgoing POP3 settings: mail.domain.com
UserName: john
Password: xxxx

NOTE: Before sending any outgoing email with outlook, make sure you tick the My server requires authentication under server settings.


How do i test whether mail server is working or not?

The simplest way to check for your mail server working is enter your domain in pingability.com or dnsstuff.com and check for the errors. You may also want to find if it is not open relay. Check your log file /var/log/maillog for any errors as well.

Another way to test your mail server is using telnet. You will get output like the one below.
> telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 mail.simplegerman.com ESMTP Postfix
ehlo simplegerman.com
250-mail.simplegerman.com
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-AUTH PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN

NOTE: If you are using firewall make sure you dont block mail server ports

How to install ftp server?



FTP is used to transfer the file from the source machine to any machine on any location, this is one of the original software or a protocol of TCP/IP protocol suit. It works on server client mode, it was developed for centralizing the data so that client can download their required things wherever whenever they want.
Port number of FTP is 20,21. It listens the request on port 20 and makes the connection on port 21.

Here we are using VSFTPD(Very secure FTP Demon): It is one of the original software included with red hat provides the more security then other protocol.

How to install ftp server?
#yum insall vsftpd
You can use rpm or yum to install vsftpd.

Now your server is installed, make the changes according to your need in the configuration file /etc/vsftpd/vsftpd.conf

Some Important tips for FTP Server

anonymous_enable=yes: It is a global user, through which anybody can access it. Change it to NO to disable anonymous access.
local_enable=yes: It allows the system users to access the FTP.
local_root=/var/ftp: Add this to assign home directory to all ftp users, by default this line is not in the configuration file and the ftp's home directory is the home directory of the user itself.
chroot_local_user=yes: Add this line to enable the chroot in FTP. Using this, user can not change their home directory. TO make your FTP server secure enable this feature with anonymous_enable=no.
/etc/vsftpd/userlist: It allows the user to connecct with ftp server.
/etc/vsftpd/ftpusers: It denies the suers to access ftp.
/var/log/xferlog: This file contain the logs of ftp server.

Restart the service now:
#service vsftpd restart
#chkconfig vsftpd on

If SELinux is enabled on the server, then it may create problem in making connection from the client side. Use this to allow ftp connection.
#setsebool -P ftpd_disable_trans=1

On Client's side:

GUI: Open the browser and open the URL ftp://serverIP

CLI: #ftp serverIP

Useful commands:
ls: To list the file and folders.
get filename: To download the file.
mget filename*: To download the multiple files.
put filename: To upload the file.
mput filename: To upload multiple files.

How to install MySQL


How to install MySQL

Install MySQL

#yum install mysql-server mysql php-mysql

How to configure MySQL

Set the MySQL service to start on boot

#chkconfig --levels 235 mysqld on

Start the MySQL service

#service mysqld start

Log into MySQL

#mysql -u root

Set the root user password for all local domains
#SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new-password');
#SET PASSWORD FOR 'root'@'localhost.localdomain' = PASSWORD('new-password');
#SET PASSWORD FOR 'root'@'127.0.0.1' = PASSWORD('new-password');


Drop the Any user
#DROP USER ''@'localhost';
#DROP USER ''@'localhost.localdomain';

Exit MySQL
exit


Forgotten MySQL Root Password

Stop the mysql daemon
#mysqld_safe --skip-grant-tables
#mysql --user=root mysql
>update user set Password=PASSWORD('new-password') where user='root';
>flush privileges;
>exit;

Sending SMS Notifications From Nagios


Sending SMS Notifications From Nagios
In my last article I have discuses how to install Gnokii for sending/receiving SMS from your computer. Today I'll explain how we are using Gnokii + Nagios for sending SMS notifications to our cell phones. Its a great way to get notify of the problems while on road.

I assume that you have working Nagios and its monitoring the devices in your infrastructure and sending notifications via Email and you are looking how to get these problem notifications on your phones.

Gnokii is also working and you can send SMS from CLI.

Lets cut it short and back to actual business.

In my setup we have Nagios and Gnokii install on same host running Centos 5.4, but it can easily be followed for any other Linux distro or even with setup where Gnokii is install on separate host.

1. Make sure you can send SMS from CLI with "gnokii --sendsms +92xxxxx" using root or the user under which Nagios process is running normally its 'nagios' user, sending under nagios user requires to add nagios to groups which have permission to access the device files.

a) So add nagios to 'uucp' group (you can do this with usermod command)

Gnokii also acquire a lock under /var/lock

b) So add nagios user to 'lock' group also.

su to nagios user and send sms from CLI using gnokii --sendsms, when it works move forward for defining commands.

2. Define command for send notification via SMS in commands.cfg

# 'notify-service-by-sms' command definition
define command{
command_name notify-service-by-sms
command_line /usr/bin/printf "%.120s" "*** Nagios Alert*** $HOSTALIAS$/$SERVICEDESC$ is $SERVICESTATE$" | /usr/local/bin/gnokii --sendsms $CONTACTPAGER$
}

# 'notify-host-by-sms' command definition
define command{
command_name notify-host-by-sms
command_line /usr/bin/printf "%.120s" "*** Nagios Alert*** $NOTIFICATIONTYPE$ : Host $HOSTALIAS$ is $HOSTSTATE$" | /usr/local/bin/gnokii --sendsms $CONTACTPAGER$
}

3. Modify contacts.cfg and add or modify a contact by calling new commands

define contact{
contact_name askarali
use generic-contact
alias Askar Ali Khan
email emailaddress
pager +92xxxxxx
service_notification_commands notify-service-by-email,notify-service-by-sms
host_notification_commands notify-host-by-email,notify-host-by-sms
}

The key in the contact detail is the service/host notifications commands

service_notification_commands notify-service-by-email,notify-service-by-sms
host_notification_commands notify-host-by-email,notify-host-by-sms

I have configured a contact so that he can receive notifications via Email 'notify-service-by-email' as well as via SMS 'notify-service-by-sms'


That's all, finally reload nagios, before reload better to run syntax check

'nagios -v PathTo nagios.cfg'

and then reload

/etc/init.d/nagios reload

Now Nagios will send SMS notifications on your phone whenever there is problem with any host/service which being monitor with Nagios.

I hope this could help.

Webmin in Details


To install webmin, follow the following steps.
1. Download the tarball, webmin.x.x.x.tar.gz
2. unzip it, tar -zxvf webmin.x.x.x.tar.gz
3. cd webmin.x.x.x
4. Run the following command and provide necessary informations

./setup.sh /usr/local/webmin

If you want to uninstall, then...

/etc/webmin/uninstall.sh

Thats all. Enjoy

Installing webmin in freeBSD
To install webmin, update your ports, enter:
# portsnap fetch update

Install webmin from /usr/ports/sysutils/webmin, enter:
# cd /usr/ports/sysutils/webmin
# make install clean

Configure webmin
Now, webmin is installed. Start webmin on startup, enter:
# vi /etc/rc.conf
Append following line:
webmin_enable="YES"

You need to run /usr/local/lib/webmin/setup.sh script in order to setup the various config
files, enter:
# /usr/local/lib/webmin/setup.sh

https://your-domain.com:10000/

Changing your webmin passwords

It’s not unusual that, as your FreeBSD server is so stable, you end not knowing what your password was.
Under other systems the location of webmin is clear and most of the documentation will point you to /usr/libexec/webmin or something like that, in FreeBSD, by default (and after some updates) webmin is installed under
/usr/local/lib/webmin-1.300
Where 1.300 is the running version
And it’s configuration file is located at:
/usr/local/etc/webmin
So, to change the password of let’s say user foo to bar you’ll have to type:
/usr/local/lib/webmin-1.300/changepass.pl /usr/local/etc/webmin foo bar

Script for daily SARG reports


SARG is Squid Analysis Report Generator is a tool that allow you to view "where" your users are going to on the Internet. http://sarg.sourceforge.net/

If you want to generate daily reports from Squid proxy server logs, create script:

#!/bin/bash

#Get current date
TODAY=$(date +%d/%m/%Y)

#Get yesterday's date
YESTERDAY=$(date --date yesterday +%d/%m/%Y)

/usr/bin/sarg -z -d $YESTERDAY-$TODAY > /dev/null 2>&1

exit 0

And add it to cron jobs:

55 23 * * * /scripts/sarg_daily_report

And restart cron

Postfix - Blocking spam before it enters the server


Postfix - blocking spam before it enters the server

Posted in DNSBL E-mail E-mail spam Extended SMTP Mail transfer agents Postfix Spam filtering
When i first setup the server part 1 and part 2 i used the basic setting for postfix but soon found that i could reduce the amount of spam and load on the server by rejecting it before accepting it, i will do this by forcing mail servers that wanna deliver mail to me to be configured correctly and by using a few RBL (Real-time Blacklists).

Since i use Webmin i just navigate to "servers", "Posfix Mail server" then click "Edit Config Files" or manually edit "/etc/postfix/main.cf"

Below is my new config file - obviously change the IP's to your IP's and the domains to yours.

########################################################
inet_protocols = all
inet_interfaces = 127.0.0.1, 192.168.0.200, [2001:470:1f09:d2b::220], [::1]
smtp_bind_address = 192.168.0.200
smtp_bind_address6 = [2001:470:1f09:d2b::220]
myorigin = $mydomain
mynetworks = 127.0.0.0/8, 192.168.0.200, [2001:470:1f09:d2b::/64], [::1/128]
myhostname = mail.example.com
mydomain = example.com
mydestination = $myhostname, $mydomain, localhost.$mydomain, localhost

virtual_alias_domains = example.co.uk, example2.com, example3.com, example2.co.uk
virtual_alias_maps = hash:/etc/postfix/virtual

smtpd_delay_reject = yes
smtpd_helo_required = yes
smtpd_helo_restrictions = permit_mynetworks, reject_non_fqdn_hostname, reject_invalid_hostname, permit

smtpd_sender_restrictions =permit_sasl_authenticated, permit_mynetworks, reject_non_fqdn_sender, reject_unknown_sender_domain, permit

smtpd_recipient_restrictions = permit_mynetworks, permit_inet_interfaces, permit_sasl_authenticated, reject_unauth_pipelining, reject_invalid_hostname, reject_non_fqdn_hostname, reject_unknown_recipient_domain, reject_unauth_destination, reject_rbl_client dnsbl.sorbs.net, reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net, permit

policyd-spf_time_limit = 3600
smtpd_client_restrictions = permit_tls_all_clientcerts, reject_unauth_pipelining

2bounce_notice_recipient = webmaster@example.com
error_notice_recipient = webmaster@example.com
bounce_notice_recipient = webmaster@example.com

smtpd_sasl_local_domain =
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_sasl_authenticated_header = yes
smtpd_tls_key_file = /etc/postfix/ssl/key.pem
smtpd_tls_cert_file = /etc/postfix/ssl/mail.example.com.pem
smtpd_tls_CAfile = /etc/postfix/ssl/sub.class1.server.ca.pem
smtpd_error_sleep_time = 5s

smtp_use_tls = yes
smtpd_tls_auth_only = no
smtp_tls_note_starttls_offer = yes
smtpd_use_tls = yes
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s

tls_random_source = dev:/dev/urandom
disable_vrfy_command = yes
unknown_client_reject_code = 550
unknown_hostname_reject_code = 550
unknown_address_reject_code = 550

some people might say this is quite restrictive as it will block any mail server that is mis-configured or using a dynamic ip, or been blocked for sending spam but i have found it blocks 95% of the spam i was receiving beforehand without using a spam filter (thus reducing the load on the server) and i haven't seen any downsides as all legit mail is getting through fine.

I'll try and explain what the main changes are. There are 3 main sections I changed "smtpd_helo_restrictions", "smtpd_sender_restrictions" and "smtpd_recipient_restrictions"

smtpd_sender_restrictions =permit_sasl_authenticated, permit_mynetworks, reject_non_fqdn_sender, reject_unknown_sender_domain, permit
This allows my networks and users that have authenticated themselves to connect but blocks any servers that haven't configured a valid hostname for there mail server (should always use a proper domain name i.e. myhostname = mail.example.com) and also stops people trying to relay mail through my server.

smtpd_helo_restrictions = permit_mynetworks, reject_non_fqdn_hostname, reject_invalid_hostname, permit
When mail servers communicate with each other they say hello and identify themselves, this setting allows my networks to connect but blocks any servers that haven't configured a valid hostname for there mail server (should always use a proper domain name i.e. myhostname = mail.example.com)

smtpd_recipient_restrictions = permit_mynetworks, permit_inet_interfaces, permit_sasl_authenticated, reject_unauth_pipelining, reject_non_fqdn_hostname, reject_unknown_recipient_domain, reject_unauth_destination, reject_invalid_hostname, reject_rbl_client dnsbl.sorbs.net, reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net, permit
This setting does the same as the above commands except it rejects mail servers that have been listed on RBL (Real-time Blacklists) you can google for more RBL lists but these do just fine for me.
I use dnsbl.sorbs.net, zen.spamhaus.org and bl.spamcop.net

If you want a more detailed explanation of what each option does have a read of Postfix Configuration Parameters it lists every option going.

I have also setup SPF checking and a white-list just in-case a valid email server gets on the RBL list. SPF can be studied in previous article.

Postfix - whitelisting and spf filtering



Postfix - whitelisting and spf filtering

The whitelist will allow me to manually allow any mail servers to bypass the spf filtering and RBL(Real-time Blacklists) lists.

What does SPF filtering do? Suppose a spammer forges a Hotmail.com address and tries to spam you. They connect from somewhere other than Hotmail. When his message is sent, you see MAIL FROM: , but you don't have to take his word for it. You can ask Hotmail if the IP address comes from their network.
(In this example) Hotmail publishes an SPF record. That record tells you how to find out if the sending machine is allowed to send mail from Hotmail. If Hotmail says they recognize the sending machine, it passes, and you can assume the sender is who they say they are. If the message fails SPF tests, it's a forgery. That's how you can tell it's probably a spammer.

Now time to start setting everything, for the spf filtering we need to install a few packages so start with

yum --enable epel install python-dns python-pydns

we also need "pyspf". check for any updates from here
Then install it, you need to be the root user (change the version numbers if theirs an update)

#wget http://sourceforge.net/projects/pymilter/files/pyspf/pyspf-2.0.5/pyspf-2.0.5.tar.gz/download
#tar xvfz pyspf-2.0.5.tar.gz
#cd pyspf-2.0.5/
#python setup.py build
#python setup.py install

Finally we need "pypolicyd-spf". check for any updates from here
Then install it, you need to be the root user (change the version numbers if theirs an update)

#wget http://launchpad.net/pypolicyd-spf/0.8/0.8.0/+download/pypolicyd-spf-0.8.0.tar.gz
#tar xvfz pypolicyd-spf-0.8.0.tar.gz
#cd pypolicyd-spf-0.8.0/
#python setup.py build
#python setup.py install

Now everything is install I need to tell postfix to use it. Since i use Webmin i just navigate to "servers", "Posfix Mail server" then click "Edit Config Files" or manually edit "/etc/postfix/main.cf"

Now find "smtpd_recipient_restrictions = ", and add "check_client_access hash:/etc/postfix/rbl_override_whitelist, check_policy_service unix:private/policyd-spf," after "reject_unauth_destination,"
It is important that you add it AFTER reject_unauth_destination or else your system can become an open relay!
It should look like this.

smtpd_recipient_restrictions = permit_mynetworks, permit_inet_interfaces, permit_sasl_authenticated, reject_unauth_pipelining, reject_invalid_hostname, reject_non_fqdn_hostname, reject_unknown_recipient_domain, reject_unauth_destination, check_client_access hash:/etc/postfix/rbl_override_whitelist, check_policy_service unix:private/policyd-spf, reject_rbl_client dnsbl.sorbs.net, reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net, permit

Now I need to edit "/etc/postfix/master.cf". Since i use Webmin i just navigate to "servers", "Posfix Mail server" then click "Edit Config Files" and select "master.cf" from the drop box at the top.

Now i add at the end

policyd-spf  unix  -       n       n       -       0       spawn
                   user=nobody argv=/usr/bin/policyd-spf

The leading spaces before user=nobody are important so Postfix knows this line belongs to the previous one.

The last thing i need to do is create the whitelist file, so login as root

#cd /etc/postfix
#vi /etc/postfix/rbl_override_whitelist

Then add all ip addresses or hostname that you want whitelisted (one per line only)
here what it should look like

1.2.3.4 OK
mail.example.net OK

After you create/modify the file you need to run

#postmap /etc/postfix/rbl_override_whitelist

Finally restart postfix

#/etc/init.d/postfix restart

Now send a test message from an external email account to test, if the email doesn't arrive check the logs for any errors (something you should do regularly anyway).

Hopefully everything is working fine and you should start seeing a drop in forged emails, don't forget to create a spf record for your domain so other servers can check your emails. There is a easy to use wizard to help create the record for you.
This is what my record looks like

v=spf1 a ip4:195.242.236.240 ip4:85.234.148.232/30 ip4:85.234.148.236 ip6:2001:470:1f09:d2b::/64 ip6:2001:470:1f09:81e::/64 -all

It basically lists all the ip address that are allowed to send email for my domain and says reject everything else.
If you wanna check if a particulate site has an spf record or you want to check if its working correctly, you can check from http://www.kitterman.com/spf/validate.html

Sendmail and Dovecot Configurations


Install Sendmail and Dovecot

Code:
[root@sendmail ~]# yum install sendmail*
[root@sendmail mail]# yum install dovecot


Verify the installation and compilation options

Code:
[root@sendmail ~]# rpm -qa|grep sendmail
sendmail-8.13.8-2.el5
sendmail-cf-8.13.8-2.el5
sendmail-doc-8.13.8-2.el5
sendmail-devel-8.13.8-2.el5


Code:
[root@sendmail ~]# sendmail -d0.1 -bv
Version 8.13.8
 Compiled with: DNSMAP HESIOD HES_GETMAILHOST LDAPMAP LOG MAP_REGEX
                MATCHGECOS MILTER MIME7TO8 MIME8TO7 NAMED_BIND NETINET NETINET6
                NETUNIX NEWDB NIS PIPELINING SASLv2 SCANF SOCKETMAP STARTTLS
                TCPWRAPPERS USERDB USE_LDAP_INIT

============ SYSTEM IDENTITY (after readcf) ============
      (short domain name) $w = sendmail
  (canonical domain name) $j = sendmail.example.com
         (subdomain name) $m = example.com
              (node name) $k = sendmail.example.com
========================================================

This command will show the compiled options of sendmail.


Configuration

Code:
[root@sendmail mail]# cd /etc/mail/

[root@sendmail mail]# vi local-host-names


this file will contain the domain names for which the send mail server is going to serve

Code:
# local-host-names - include all aliases for your machine here.
example.com

Edit the mc file

Code:
[root@sendmail mail]# vi sendmail.mc

Code:
dnl # Following line is optional. If you want ot relay the mails through another server, use the next line

define(`SMART_HOST', `relayserver.example.com')dnl

dnl #
dnl # The following allows relaying if the user authenticates, and disallows
dnl # plaintext authentication (PLAIN/LOGIN) on non-TLS links
dnl #
dnl define(`confAUTH_OPTIONS', `A p')dnl
dnl #
dnl # PLAIN is the preferred plaintext authentication method and used by
dnl # Mozilla Mail and Evolution, though Outlook Express and other MUAs do
dnl # use LOGIN. Other mechanisms should be used if the connection is not
dnl # guaranteed secure.
dnl # Please remember that saslauthd needs to be running for AUTH.
dnl #
TRUST_AUTH_MECH(`EXTERNAL DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl

dnl # The following causes sendmail to only listen on the IPv4 loopback address
dnl # 127.0.0.1 and not on any other network devices. Remove the loopback
dnl # address restriction to accept email from the internet or intranet.
dnl #
dnl # DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')dnl

This step is also optional. If relay server need an authentication provide the credantials here

Code:
[root@sendmail mail]# vi access


Code:
AuthInfo:relay.dnsexit.com "U:USERNAME" "P:PASSWORD" "M:PLAIN"

Add a user and set password

Code:
[root@sendmail mail]# useradd -s /sbin/nologin senthil
[root@sendmail mail]# passwd senthil
Changing password for user senthil.
New UNIX password:
BAD PASSWORD: it is too short
Retype new UNIX password:
passwd: all authentication tokens updated successfully.

Map the mails for users. This will be required when more number of users and more domains are hosted in the same server

[CODE]
Code:
[root@sendmail mail]# vi virtusertable
Code:
senthil@example.com     senthil

Configure Dovecot

Code:
[root@sendmail mail]# vi /etc/dovecot.conf

Code:
protocols = imap pop3

create the sendmail cf file with mc file

Code:
[root@sendmail mail]# m4 sendmail.mc > sendmail.cf
[root@sendmail mail]# make

Start the services

Code:
[root@sendmail mail]# /etc/init.d/sendmail start
[root@sendmail mail]# /etc/init.d/saslauthd start
[root@sendmail mail]# /etc/init.d/dovecot start

Make required services permanent (after a reboot they start automatically)

Code:
[root@sendmail mail]# chkconfig sendmail on
[root@sendmail mail]# chkconfig dovecot on
[root@sendmail mail]# chkconfig saslauthd on

As of now the sendmail server is ready. The server can be accessed by outlook or any mail client.

It will be very nice if are having a imap webmail client. I prefer Roundcube. The previous version of Roundcube was having some security holes(Before 2 years). But the current stable version seems to be secured.

Round cube requires mysql support and php greater than 5.2.0.

The current version of Php is 5.1.6 so have to update php version.

Updating PHP

Code:
[root@sendmail round]# php -v


Code:
PHP 5.1.6 (cli) (built: Mar 14 2007 18:56:07)
Copyright (c) 1997-2006 The PHP Group
Zend Engine v2.1.0, Copyright (c) 1998-2006 Zend Technologies
Code:
[root@sendmail ~]# cd /etc/yum.repos.d

Code:
[root@sendmail ~]# wget dev.centos.org/centos/5/CentOS-Testing.repo

Code:

[root@sendmail ~]# yum --disablerepo=* --enablerepo=c5-testing update php  php-xml php-mysql

Code:
[root@sendmail round]# php -v

Code:
PHP 5.2.10 (cli) (built: Nov 13 2009 11:24:03)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2009 Zend Technologies
Install Mysql And set root password

Code:
yum install mysql mysql-server

/usr/bin/mysqladmin -u root password 'mysqlrootpassword'

Download Round cube Stable version and extract it

Code:
[root@sendmail ~]# cd /tmp/
[root@sendmail ~]# wget nchc.dl.sourceforge.net/project/roundcubemail/roundcubemail/0.3.1/roundcubemail-0.3.1.tar.gz
[root@sendmail ~]# tar -zxvf roundcubemail-0.3.1.tar.gz
[root@sendmail ~]# mv roundcube /usr/share/
[root@sendmail ~]# vi /etc/httpd/conf/roundcube.conf

Inside this file add as follows,

Code:
<IfModule mod_alias.c>
Alias /rcm /usr/share/roundcube
</IfModule>
<Directory /usr/share/roundcube>
   Options None
   Order allow,deny
   allow from all
</Directory>

Code:
[root@sendmail ~]# vi /etc/httpd/conf/httpd.conf

add the following line,

Code:
Include /etc/httpd/conf/roundcube.conf

Set Some permissions

Code:
[root@sendmail ~]# chown -R root:apache /usr/share/roundcube/
[root@sendmail ~]# cd /usr/share/roundcube/
[root@sendmail ~]# chmod g+w temp/
[root@sendmail ~]# chmod g+w logs/

Create Database for Round cube in Mysql

Code:
[root@sendmail ~]# mysql -u root -p

Code:
mysql> create database roundcube;
mysql> show databases;
mysql> create user roundcube;
mysql> GRANT ALL PRIVILEGES ON roundcube.* TO roundcube@localhost IDENTIFIED BY 'roundcube';
mysql> FLUSH PRIVILEGES;
mysql> quit;

restart http

Code:
[root@sendmail ~]# /etc/init.d/httpd restart

In the browser,

Code:
yourserverip/rcm/installer/

Click the "START INSTALLATION" button
These are all very simple forms in the browser. I cant enter all the options because the limited characters. Please contact me if there is any difficulties in filling those options.

General configuration, Database setup, IMAP Settings, SMTP Settings

Then click next

The installer will generate two configuration files for you,

Copy these contents (files) in side the /usr/share/roundcube/config

Code:
[root@sendmail ~]# vi main.inc.php
[root@sendmail ~]# vi db.inc.php

The installer directory should be moved to some other path.
Code:
[root@sendmail ~]# mv installer/ /tmp/

IPTABLES Examples


1. Delete Existing Rules

Before you start building new set of rules, you might want to clean-up all the default rules, and existing rules. Use the iptables flush command as shown below to do this.

iptables -F
(or)
iptables --flush

2. Set Default Chain Policies

The default chain policy is ACCEPT. Change this to DROP for all INPUT, FORWARD, and OUTPUT chains as shown below.

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
When you make both INPUT, and OUTPUT chain’s default policy as DROP, for every firewall rule requirement you have, you should define two rules. i.e one for incoming and one for outgoing.

In all our examples below, we have two rules for each scenario, as we’ve set DROP as default policy for both INPUT and OUTPUT chain.

If you trust your internal users, you can omit the last line above. i.e Do not DROP all outgoing packets by default. In that case, for every firewall rule requirement you have, you just have to define only one rule. i.e define rule only for incoming, as the outgoing is ACCEPT for all packets.

Note: If you don’t know what a chain means, you should first familiarize yourself with the IPTables fundamentals.

3. Block a Specific ip-address

Before we proceed further will other examples, if you want to block a specific ip-address, you should do that first as shown below. Change the “x.x.x.x” in the following example to the specific ip-address that you like to block.

BLOCK_THIS_IP="x.x.x.x"
iptables -A INPUT -s "$BLOCK_THIS_IP" -j DROP
This is helpful when you find some strange activities from a specific ip-address in your log files, and you want to temporarily block that ip-address while you do further research.

You can also use one of the following variations, which blocks only TCP traffic on eth0 connection for this ip-address.

iptables -A INPUT -i eth0 -s "$BLOCK_THIS_IP" -j DROP
iptables -A INPUT -i eth0 -p tcp -s "$BLOCK_THIS_IP" -j DROP

4. Allow ALL Incoming SSH

The following rules allow ALL incoming ssh connections on eth0 interface.

iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
Note: If you like to understand exactly what each and every one of the arguments means, you should read How to Add IPTables Firewall Rules

5. Allow Incoming SSH only from a Sepcific Network

The following rules allow incoming ssh connections only from 192.168.100.X network.

iptables -A INPUT -i eth0 -p tcp -s 192.168.100.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
In the above example, instead of /24, you can also use the full subnet mask. i.e “192.168.100.0/255.255.255.0″.

6. Allow Incoming HTTP and HTTPS

The following rules allow all incoming web traffic. i.e HTTP traffic to port 80.

iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT
The following rules allow all incoming secure web traffic. i.e HTTPS traffic to port 443.

iptables -A INPUT -i eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT

7. Combine Multiple Rules Together using MultiPorts

When you are allowing incoming connections from outside world to multiple ports, instead of writing individual rules for each and every port, you can combine them together using the multiport extension as shown below.

The following example allows all incoming SSH, HTTP and HTTPS traffic.

iptables -A INPUT -i eth0 -p tcp -m multiport --dports 22,80,443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp -m multiport --sports 22,80,443 -m state --state ESTABLISHED -j ACCEPT

8. Allow Outgoing SSH

The following rules allow outgoing ssh connection. i.e When you ssh from inside to an outside server.

iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

Please note that this is slightly different than the incoming rule. i.e We allow both the NEW and ESTABLISHED state on the OUTPUT chain, and only ESTABLISHED state on the INPUT chain. For the incoming rule, it is vice versa.

9. Allow Outgoing SSH only to a Specific Network

The following rules allow outgoing ssh connection only to a specific network. i.e You an ssh only to 192.168.100.0/24 network from the inside.

iptables -A OUTPUT -o eth0 -p tcp -d 192.168.100.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

10. Allow Outgoing HTTPS

The following rules allow outgoing secure web traffic. This is helpful when you want to allow internet traffic for your users. On servers, these rules are also helpful when you want to use wget to download some files from outside.

iptables -A OUTPUT -o eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT

Note: For outgoing HTTP web traffic, add two additional rules like the above, and change 443 to 80.

11. Load Balance Incoming Web Traffic

You can also load balance your incoming web traffic using iptables firewall rules.

This uses the iptables nth extension. The following example load balances the HTTPS traffic to three different ip-address. For every 3th packet, it is load balanced to the appropriate server (using the counter 0).

iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 0 -j DNAT --to-destination 192.168.1.101:443
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 1 -j DNAT --to-destination 192.168.1.102:443
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 2 -j DNAT --to-destination 192.168.1.103:443

12. Allow Ping from Outside to Inside

The following rules allow outside users to be able to ping your servers.

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT

13. Allow Ping from Inside to Outside

The following rules allow you to ping from inside to any of the outside servers.

iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT

14. Allow Loopback Access

You should allow full loopback access on your servers. i.e access using 127.0.0.1

iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

15. Allow Internal Network to External network.

On the firewall server where one ethernet card is connected to the external, and another ethernet card connected to the internal servers, use the following rules to allow internal network talk to external network.

In this example, eth1 is connected to external network (internet), and eth0 is connected to internal network (For example: 192.168.1.x).

iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT

16. Allow outbound DNS

The following rules allow outgoing DNS connections.

iptables -A OUTPUT -p udp -o eth0 --dport 53 -j ACCEPT
iptables -A INPUT -p udp -i eth0 --sport 53 -j ACCEPT

17. Allow NIS Connections

If you are running NIS to manage your user accounts, you should allow the NIS connections. Even when the SSH connection is allowed, if you don’t allow the NIS related ypbind connections, users will not be able to login.

The NIS ports are dynamic. i.e When the ypbind starts it allocates the ports.

First do a rpcinfo -p as shown below and get the port numbers. In this example, it was using port 853 and 850.

rpcinfo -p | grep ypbind
Now allow incoming connection to the port 111, and the ports that were used by ypbind.

iptables -A INPUT -p tcp --dport 111 -j ACCEPT
iptables -A INPUT -p udp --dport 111 -j ACCEPT
iptables -A INPUT -p tcp --dport 853 -j ACCEPT
iptables -A INPUT -p udp --dport 853 -j ACCEPT
iptables -A INPUT -p tcp --dport 850 -j ACCEPT
iptables -A INPUT -p udp --dport 850 -j ACCEPT
The above will not work when you restart the ypbind, as it will have different port numbers that time.

There are two solutions to this: 1) Use static ip-address for your NIS, or 2) Use some clever shell scripting techniques to automatically grab the dynamic port number from the “rpcinfo -p” command output, and use those in the above iptables rules.

18. Allow Rsync From a Specific Network

The following rules allows rsync only from a specific network.

iptables -A INPUT -i eth0 -p tcp -s 192.168.101.0/24 --dport 873 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 873 -m state --state ESTABLISHED -j ACCEPT

19. Allow MySQL connection only from a specific network

If you are running MySQL, typically you don’t want to allow direct connection from outside. In most cases, you might have web server running on the same server where the MySQL database runs.

However DBA and developers might need to login directly to the MySQL from their laptop and desktop using MySQL client. In those case, you might want to allow your internal network to talk to the MySQL directly as shown below.

iptables -A INPUT -i eth0 -p tcp -s 192.168.100.0/24 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 3306 -m state --state ESTABLISHED -j ACCEPT

20. Allow Sendmail or Postfix Traffic

The following rules allow mail traffic. It may be sendmail or postfix.

iptables -A INPUT -i eth0 -p tcp --dport 25 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 25 -m state --state ESTABLISHED -j ACCEPT

21. Allow IMAP and IMAPS

The following rules allow IMAP/IMAP2 traffic.

iptables -A INPUT -i eth0 -p tcp --dport 143 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 143 -m state --state ESTABLISHED -j ACCEPT
The following rules allow IMAPS traffic.

iptables -A INPUT -i eth0 -p tcp --dport 993 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 993 -m state --state ESTABLISHED -j ACCEPT

22. Allow POP3 and POP3S

The following rules allow POP3 access.

iptables -A INPUT -i eth0 -p tcp --dport 110 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 110 -m state --state ESTABLISHED -j ACCEPT
The following rules allow POP3S access.

iptables -A INPUT -i eth0 -p tcp --dport 995 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 995 -m state --state ESTABLISHED -j ACCEPT

23. Prevent DoS Attack

The following iptables rule will help you prevent the Denial of Service (DoS) attack on your webserver.

iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT

In the above example:

-m limit: This uses the limit iptables extension
–limit 25/minute: This limits only maximum of 25 connection per minute. Change this value based on your specific requirement
–limit-burst 100: This value indicates that the limit/minute will be enforced only after the total number of connection have reached the limit-burst level.

24. Port Forwarding

The following example routes all traffic that comes to the port 442 to 22. This means that the incoming ssh connection can come from both port 22 and 422.

iptables -t nat -A PREROUTING -p tcp -d 192.168.102.37 --dport 422 -j DNAT --to 192.168.102.37:22
If you do the above, you also need to explicitly allow incoming connection on the port 422.

iptables -A INPUT -i eth0 -p tcp --dport 422 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 422 -m state --state ESTABLISHED -j ACCEPT

25. Log Dropped Packets

You might also want to log all the dropped packets. These rules should be at the bottom.

First, create a new chain called LOGGING.

iptables -N LOGGING
Next, make sure all the remaining incoming connections jump to the LOGGING chain as shown below.

iptables -A INPUT -j LOGGING
Next, log these packets by specifying a custom “log-prefix”.

iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables Packet Dropped: " --log-level 7

Finally, drop these packets.

iptables -A LOGGING -j DROP

Linux OID's for CPU,Memory and Disk Statistics


SNMP Basics

SNMP stands for Simple Network Management Protocol and consists of three key components: managed devices, agents, and network-management systems (NMSs). A managed device is a node that has an SNMP agent and resides on a managed network. These devices can be routers and access server, switches and bridges, hubs, computer hosts, or printers. An agent is a software module residing within a device. This agent translates information into a compatible format with SNMP. An NMS runs monitoring applications. They provide the bulk of processing and memory resources required for network management.

MIBs, OIDs Overview

MIB stands for Management Information Base and is a collection of information organized hierarchically. These are accessed using a protocol such as SNMP. There are two types of MIBs: scalar and tabular. Scalar objects define a single object instance whereas tabular objects define multiple related object instances grouped in MIB tables.

OIDs or Object Identifiers uniquely identify manged objects in a MIB hierarchy. This can be depicted as a tree, the levels of which are assigned by different organizations. Top level MIB object IDs (OIDs) belong to different standard organizations. Vendors define private branches including managed objects for their own products.

Here is a sample structure of an OID

Iso (1).org(3).dod(6).internet(1).private(4).transition(868).products(2).chassis(4).card(1).slotCps(2)­
.­cpsSlotSummary(1).cpsModuleTable(1).cpsModuleEntry(1).cpsModuleModel(3).3562.3

Most of the people may be looking for OID's for Linux OID's for CPU,Memory and Disk Statistics for this first you need to install SNMP server and clients. If you want to install SNMP server and client installation in linux check here

 CPU  Statistics

        Load
               1 minute Load: .1.3.6.1.4.1.2021.10.1.3.1
               5 minute Load: .1.3.6.1.4.1.2021.10.1.3.2
               15 minute Load: .1.3.6.1.4.1.2021.10.1.3.3

       CPU
               percentage of user CPU time:    .1.3.6.1.4.1.2021.11.9.0
               raw user cpu time:                  .1.3.6.1.4.1.2021.11.50.0
               percentages of system CPU time: .1.3.6.1.4.1.2021.11.10.0
               raw system cpu time:              .1.3.6.1.4.1.2021.11.52.0
               percentages of idle CPU time:   .1.3.6.1.4.1.2021.11.11.0
               raw idle cpu time:                   .1.3.6.1.4.1.2021.11.53.0
               raw nice cpu time:                  .1.3.6.1.4.1.2021.11.51.0

Memory Statistics

               Total Swap Size:                .1.3.6.1.4.1.2021.4.3.0
               Available Swap Space:         .1.3.6.1.4.1.2021.4.4.0
               Total RAM in machine:          .1.3.6.1.4.1.2021.4.5.0
               Total RAM used:                  .1.3.6.1.4.1.2021.4.6.0
               Total RAM Free:                   .1.3.6.1.4.1.2021.4.11.0
               Total RAM Shared:                .1.3.6.1.4.1.2021.4.13.0
               Total RAM Buffered:              .1.3.6.1.4.1.2021.4.14.0
               Total Cached Memory:           .1.3.6.1.4.1.2021.4.15.0

Disk Statistics

       The snmpd.conf needs to be edited. Add the following (assuming a machine with a single '/' partition):

                               disk    /       100000  (or)

                               includeAllDisks 10% for all partitions and disks

       The OIDs are as follows

               Path where the disk is mounted:                 .1.3.6.1.4.1.2021.9.1.2.1
               Path of the device for the partition:            .1.3.6.1.4.1.2021.9.1.3.1
               Total size of the disk/partion (kBytes):        .1.3.6.1.4.1.2021.9.1.6.1
               Available space on the disk:                      .1.3.6.1.4.1.2021.9.1.7.1
               Used space on the disk:                           .1.3.6.1.4.1.2021.9.1.8.1
               Percentage of space used on disk:             .1.3.6.1.4.1.2021.9.1.9.1
               Percentage of inodes used on disk:            .1.3.6.1.4.1.2021.9.1.10.1

Examples

These Commands you need to run on the SNMP server

Get available disk space for / on the target host

#snmpget -v 1 -c "community" target_name_or_ip .1.3.6.1.4.1.2021.9.1.7.1

this will return available disk space for the first entry in the 'disk' section of snmpd.conf; replace 1 with n for the nth entry

Get the 1-minute system load on the target host

#snmpget -v 1 -c "community" target_name_or_ip .1.3.6.1.4.1.2021.10.1.3.1

Get the 5-minute system load on the target host

#snmpget -v 1 -c "community" target_name_or_ip .1.3.6.1.4.1.2021.10.1.3.2

Get the 15-minute system load on the target host

#snmpget -v 1 -c "community" target_name_or_ip .1.3.6.1.4.1.2021.10.1.3.3

Get amount of available swap space on the target host

#snmpget -v 1 -c "community" target_name_or_ip .1.3.6.1.4.1.2021.4.4.0


Linux OID's for CPU,Memory and Disk Statistics