Monday, May 30, 2011

File Fragmentation checking on Linux

To find file fragmentation information for a specific file,we can use filefrag command.
filefrag reports on how badly fragmented a particular file. It makes allowances for indirect blocks for ext2 and ext3 filesystems, but can be used on files for any filesystem.

syntax:

filefrag -v (filename)

# filefrag -v /home/example/example.txt

-v   => verbose when checking for file fragmentation

ouptput:(for example)

Checking example.txt
Filesystem type is: ef53
Filesystem cylinder groups is approximately 606
Blocksize of file example.txt is 4096
File size of example.txt is 1194 (1 blocks)
First block: 7006588
Last block: 7006588
example.txt: 1 extent found

To Clear Linux Memory Cache

To free pagecache:

# sync; echo 1 > /proc/sys/vm/drop_caches

To free dentries and inodes:

# sync; echo 2 > /proc/sys/vm/drop_caches

To free pagecache, dentries and inodes:

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

==> sync - flush file system buffers

Linux A-Z Commands

A
alias     - Create your own name for a command
arch      - To print machine architecture
ash       - Ash command interpreter (shell)
awk       - Pattern scanning and processing language
ac        - User connection statistics

B
basename  - Remove directory and suffix from a file name
bash      - GNU Bourne-Again Shell
bsh       - Command interpreter (Shell)
bc        - Command line calculator
bunzip2   - Unzip .bz2 files


cat       - Concatenate a file print it to the screen
chgrp     - Change the group designation of a file
chmod     - Change file permissions
chown     - Change the owner of a file
cjpeg     - Compress an image file to a JPEG file
clear     - Clear terminal screen (command line)
comm      - Compare two sorted files
cp        - Copy command
cpio      - Copy files to and from archives
cut       - Print selected parts of lines to standard output


date      - Display date and time
dc        - Command line calculator
df        - Disk space free
diff      - Difference between two files
diff3     - Difference between 3 files
dig       - Interrogate DNS name servers
djpeg     - Decompress a JPEG file to an image file
dmesg     - Print or control the kernel ring buffer (print out bootup messages)
doexec    - Run an executable with an arbitrary argv
domainname- Show or set the system's NIS/YP domain name
dos2unix  - Converts plain text files in DOS/MAC format to UNIX format
du        - Show disk useage
dumpkeys  - Write keyboard driver's translation tables to std output


echo      - Display a line of text
ed        - Line-oriented text editor
egrep     - Print lines matching a pattern
elinks    - A text mode WWW browser
env       - Dislay the path
ex        - Start Vim in ex mode
eject     - Eject media from device


factor    - Display prime factors of a number
false     - Exit with a status code indicating failure
fdisk     - Disk usage
fgrep     - Variant of grep
find      - Find a file
finger    - Displays information about the system users
fixps     - Try to fix common PostScript problems that break postprocessing
free      - Display free memory


grep      - Search for a pattern using regular expression
gtar      - GNU version of the archiving utility tar.
gunzip    - Unzip .gz files
gzip      - Compress files


halt      - Stop the system
hdparm    - Get/set harddisk parameters
head      - Print the first 10 lines of a file to standard output
hostname  - Show or set the system's host name
history   - Display entire command history
HISTSIZE  - Change history size
httpd     - Apache Hypertext Transfer Protocol Server

I  -
identify  - It describes the format and characteristics of image files.
id        - Print information for username, or the current user
ifconfig  - Display network and hardware addresses
igawk     - Gawk with include files
ipcalc    - Calculate IP information for a host


kbd_mode  - Report or set the keyboard mode
kill      - Terminate a process


last      - Show list of last logged in users
lastlog   - reports the log of all users or of a given user
link      - Call the link function to create a link to a file
links     - See elinks
ln        - Create a link to the specified TARGET with optional LINK_NAME
loadkeys  - Load keyboard translation tables
locate    - Displays the location of the file
login     - Sign in
look      - Displays any lines in file which contain "string" as a prefix.
ls        - List directory contents
lsmod     - List loaded kernel modules
lynx      - Command to start the Lynx browser


mac2unix  - Converts plain text files in DOS/MAC format to UNIX format
mail      - A mail processing system, which has a command syntax like ed
man       - Display a particular manual entry
manweb    - Manweb is part of the Netpbm package
mdu       - Display the amount of space occupied by an MSDOS directory
mkdir     - Create a directory
mkfs      - Make a filesystem on a drive
mknod     - Make block or character special files
mktemp    - Make temporary filename (unique)
more      - Page through text one screenful at a time.
mount     - Mount a filesystem/device
mt        - Control magnetic tape drive operation
mv        - Move and / or rename files
         
N
namei     - Follow a pathname until a terminal point is found
nano      - An enhanced free Pico clone
nc        - arbitrary TCP and UDP connections and listens
ncftp     - Browser program for the File Transfer Protocol
nedit-nc  - nedit-nc is the client interface to the NEdit text editor
netstat   - Display verbose info about network processes and ports
nice      - Run a command with modified priority
nslookup  - query internet domain name servers
nisdomainname  - Show or set system's NIS/YP domain name

P
paste     - Merge lines of files
pdf2dsc   - Generate a PostScript page list of a PDF document
pdf2ps    - Convert PDF file "input.pdf" to PostScript(tm) in "output.ps"
pdfinfo   - Print contents of the 'Info' dictionary (plus some other useful information) from a PDF file
pdftotext - Convert pdf files to plain text
perl      - Practical Extraction and Report Language
pgawk     - The profiling version of gawk
pico      - Text editor that comes with Pine (from the University of Washington)
pine      - Email program used by The University of Washington
ping6     - Ping
ping      - Send ICMP ECHO_REQUEST to network hosts
pinky     - A lightweight 'finger' program;
pr        - Format for printing
ps        - Processes running
ps2ascii  - Ghostscript translator from PostScript or PDF to ASCII
ps2epsi   - Generate conforming Encapsulated PostScript
ps2frag   - Obsolete shell script for the PSfrag system
ps2pdf12  - Convert PostScript to PDF 1.2 (Acrobat 3 and later compatible) using ghostscript
ps2pdf13  - Convert PostScript to PDF 1.3 (Acrobat 4 and later compatible) using ghostscript
ps2pdf14  - Use ps2pdfwr: Convert PostScript to PDF without specifying Compatibility Level, using ghostscript
ps2pdf    - Convert PostScript to PDF using ghostscript
ps2pdfwr  - Convert PostScript to PDF without specifying Compatibility Level, using ghostscript
ps2pk     - Creates a TeX pkfont from a type1 PostScript font
ps2ps     - ps2ps uses gs to convert PostScript(tm) file "input.ps" to simpler and (usually) faster PostScript in "output.ps"
psbook    - Rearranges pages from a PostScript document into "signatures" for printing books or booklets
pwd       - Print Working Directory

Q
quota     - Display disk usage and limits

R
resize    - Xterm window size
readelf   - Displays information about ELF files
reboot    - Stop the system, poweroff, reboot
red       - red is a restricted ed: it can only edit files in the current directory and cannot execute shell commands
rename    - Rename files
rmdir     - Remove a directory
rm        - Remove files or directories
rpm       - rpm command options
rundig    - Sample script to create a search database for ht://Dig
rview     - The GUI version of Vim in easy mode with restrictions
rvi       - Vi / Vim editor


S
sed       - Stream editor
setfont   - Load EGA/VGA console screen font
sfdisk    - Modified fdisk program
sftp      - Secure file transfer protocol (ftp)
sh        - Shell (BASH)
shred     - Safely remove data from disk drive
sleep     - Delay for a specified amount of time
slocate   - Security Enhanced version of the GNU Locate
sort      - Sort lines of a text file
ssh       - Secure shell connection command
stty        - change and print terminal line settings
su        - switch user
switchdesk- Graphical and text mode interface for choosing desktop environment
sync      - flush the file system buffers
ssh       - Secure shell connection command


tail      - Print the last 10 Lines of a file standard output
tar       - Create an Archive
tcsh      - Enhanced completely compatible version of the Berkeley UNIX C shell, csh
tee       - Copy standard input to each file, and also to standard output
telnet    - User interface to the telnet protocol
time      - Run the specified program command with the given arguments
touch     - Creating empty files
tracepath6- See tracepath
tracepath - Trace path to a network host discovering MTU along this path
traceroute6-See traceroute
traceroute- Print the route packets take to network host
tree      - Display file tree
true      - Exit with a status code indicating success
tty       - Print the current terminal


umask     - File creation mask
umount    - Detache file system(s) mentioned from file hierarchy
uname     - Print system information ( kernel version )
unicode_start- Put keyboard and console into Unicode (UTF-8) mode
unicode_stop - Undo the effect of unicode_start
unlink    - Call the unlink function to remove the specified file
uniq      - Remove duplicate lines from sorted file
updatedb  - Update the slocate database
untar     - Unarchive a file
unzip     - Unzip .zip files
useradd   - Add a new user
users     - Output who is currently logged in according to system records
usleep    - Sleep a given number of microseconds. default is 1


view      - Start vim in read-only mode
vi        - Start the vi editor
vim      - Start the vim editor
vigr      - Edit the password or group files
visudo    - edit the sudoers file

W
w         - who is logged on and what they are doing
wc        - Word count of a file
wget      - Non-interactive download of files from the Web
whatis    - Search the whatis database for complete words (command names)
whereis   - Locate a command or file
which     - Find command path
whoami    - Print effective userid
who       - show who is logged on
whois     - Client for the whois service

X
xinit     - Start Xserver
xpdf      - Portable Document Format (PDF) file viewer for X windows
xwd       - dump an image of an X window
xrandr    - Change resolution running Xwindows ( command line )
Xvfb      - Virtual framebuffer X server for X Version 11
Xorg      - X11R6 X server

Y
ypdomainname - Show or set the system's NIS/YP domain name
yum       - Yellowdog Updater Modified
ypbind    - Nis binding process
ypserv    - Nis Server

Z
zcat      - Compress or expand files
zip       - Compression and file packaging utility
zdump     - Time zone dumper
zenmap    - Graphical Nmap frontend and results viewer
zipinfo   - List detailed information about a ZIP archive

To Find The Details Of The CPU


To Find The Details Of The CPU , Instead Of Opening The File cat /etc/cpuinfo

# dmidecode -t type

Type Information
----------------------------------------
0 BIOS
1 System
2 Base Board
3 Chassis
4 Processor
5 Memory Controller
6 Memory Module
7 Cache
8 Port Connector
9 System Slots
10 On Board Devices
11 OEM Strings
12 System Configuration Options
13 BIOS Language
14 Group Associations
15 System Event Log
16 Physical Memory Array
17 Memory Device
18 32-bit Memory Error
19 Memory Array Mapped Address
20 Memory Device Mapped Address
21 Built-in Pointing Device
22 Portable Battery
23 System Reset
24 Hardware Security
25 System Power Controls
26 Voltage Probe
27 Cooling Device
28 Temperature Probe
29 Electrical Current Probe
30 Out-of-band Remote Access
31 Boot Integrity Services
32 System Boot
33 64-bit Memory Error
34 Management Device
35 Management Device Component
36 Management Device Threshold Data
37 Memory Channel
38 IPMI Device
39 Power Supply

Monday, May 16, 2011

Dns Configuration

1.Required Packages

*bind
*bind-utils
*bind-devel
*caching-nameserver

bind - Berkeley Internet Name Domain

2. Port Number

*DNS - 53
*RDNS - 993

3.Protocols Required

*UDP - User Datagram Protocol
*TCP - Transmission Control Protocol

4.Services

/etc/init.d/named restart/stop/start/reload/configtest

5.Configuration Files

* /etc/named.caching-nameserver.conf
* /etc/named.rfc1912.zones
* /etc/named

6.Daemon

/usr/sbin/named


[root@192.168.5.50:/var/named/chroot/var/named ]# cat /var/named/chroot/etc/named.caching-nameserver.conf
//
// named.caching-nameserver.conf
//
// Provided by Red Hat caching-nameserver package to configure the
// ISC BIND named(8) DNS server as a caching only nameserver
// (as a localhost DNS resolver only).
//
// See /usr/share/doc/bind*/sample/ for example named configuration files.
//
// DO NOT EDIT THIS FILE - use system-config-bind or an editor
// to create named.conf - edits to this file will be lost on
// caching-nameserver package upgrade.
//
options {
# listen-on port 53 { 127.0.0.1; };
# listen-on-v6 port 53 { ::1; };
directory "/var/named";
dump-file "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
# query-source port 53;
# query-source-v6 port 53;
# allow-query { localhost; };
};
logging {
channel default_debug {
file "data/named.run";
severity dynamic;
};
};
view localhost_resolver {
# match-clients { localhost; };
match-destinations { localhost; };
recursion yes;
include "/etc/named.rfc1912.zones";
};

[root@192.168.5.50:/var/named/chroot/var/named ]# cat /var/named/chroot/etc/named.rfc1912.zones
// named.rfc1912.zones:
//
// Provided by Red Hat caching-nameserver package
//
// ISC BIND named zone configuration for zones recommended by
// RFC 1912 section 4.1 : localhost TLDs and address zones
//
// See /usr/share/doc/bind*/sample/ for example named configuration files.
//
zone "." IN {
type hint;
file "named.ca";
};

zone "localdomain" IN {
type master;
file "localdomain.zone";
allow-update { none; };
};

zone "localhost" IN {
type master;
file "localhost.zone";
allow-update { none; };
};

zone "net50-mail.com" IN {
type master;
file "net50.for";
allow-update { none; };
};

zone "0.0.127.in-addr.arpa" IN {
type master;
file "named.local";
allow-update { none; };
};

zone "5.168.192.in-addr.arpa" IN {
type master;
file "net50.rev";
allow-update { none; };
};

zone "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa" IN {
type master;
file "named.ip6.local";
allow-update { none; };
};

zone "255.in-addr.arpa" IN {
type master;
file "named.broadcast";
allow-update { none; };
};

zone "0.in-addr.arpa" IN {
type master;
file "named.zero";
allow-update { none; };
};

[root@192.168.5.50:/var/named/chroot/var/named ]# cat net50.for
$TTL 86400
@ IN SOA net50-mail.com. root.net50-mail.com. (
1997022700 ; Serial
28800 ; Refresh
14400 ; Retry
3600000 ; Expire
86400 ) ; Minimum
IN NS 192.168.5.50
net50-mail.com. IN A 192.168.5.50
server.net50-mail.com. IN A 192.168.5.50
www CNAME server.net50-mail.com.

$TTL 86400
@ IN SOA net50-mail.com. root.net50-mail.com. (
1997022700 ; Serial
28800 ; Refresh
14400 ; Retry
3600000 ; Expire
86400 ) ; Minimum
IN NS 192.168.5.50
50 IN PTR net50-mail.com.

Linux few crazy commands

1. If we type mistake at the beginning of the command in terminal would require you to use the slow way of punching the right/left arrow keys to travel in the command string.
Try Ctrl+e to move to the end of the command string and Ctrl+a to reach start. It’s the fastest way to edit a Linux command line. To delete a word in the command string, use Ctrl+w.

2. Another wonder of a simple shell variable is !$.

$ mkdir raj
$ mv raj raj1
$ cd raj1

Well, Linux has a shorter and quicker way:

$ mkdir raj
$ mv !$ raj1
$ cd !$

=> here we can use ALT + . or ESC + . Or !$
=> ALT + . and ESC + . print the previous argument
=> !$ points to the last string in the command string

4. What if you want to create a chain of directories and sub-directories, something like /tmp/our/your/mine?


$ mkdir -p /tmp/our/your/mine

P - parent directory

5. One very interesting way to combine some related commands is with &&.

$ cd dir_name && ls -alr && cd ..

6. Have you ever tried checking the vulnerability of your Linux system? Try a fork-bomb to evaluate this:

$ :(){ :|: & };:

It’s actually a shell function; look closely and it’s an unnamed function :() with the body enclosed in {}. The statement ‘:|:’ makes a call to the function itself and pipes the output to another function call—thus we are calling the function twice. & puts all processes in the background and hence you can’t kill any process. Finally ‘;’ completes the function definition and the last ‘:’ initiates a call to this unnamed function. So it recursively creates processes and eventually your system will hang. This is one of the most dangerous Linux commands and may cause your computer to crash!

How to avoid a fork bomb? Of course, by limiting the process limit; you need to edit /etc/security/limits.conf. Edit the variable nproc to user_name hard nproc 100. You require root privileges to modify this file.

7. One more dirty way to hack into the system is through continuous reboots, resulting in the total breakdown of a Linux machine. Here’s an option that you need root access for. Edit the file /etc/inittab and modify the line id:5:initdefault: to id:6:initdefault:. That’s all! Linux specifies various user modes and 6 is intended for reboot. Hence, your machine keeps on rebooting every time it checks for the default user mode.
check - Modify your Grub configuration (the Linux bootloader) and boot in single user mode. Edit the file /etc/inittab and change the default user level to 5.

Ten Linux Commands you Don’t Use most

1.Quickly Find a PID with pgrep

pgrep looks through the currently running processes and lists the process IDs which matches the selection criteria.

pgrep ssh

This will list all PIDs associated with the ssh process.

2.Execute The Last Executed Command

!!

This will execute the last command you used on the command line.

3.Execute The Last Command Starting With s

If you want to execute a command a command from history starting with the letter S you can use the following:

!s

This will execute the last command used on the command line that started with s.

4.Run a Command Repeatedly and Display the Output

watch runs command repeatedly, This allows you to watch the program output change over time. By default, the program is run every 2 seconds. watch is very similar to tail.

watch -d ls -l

This will watch the current directory for any file changes and highlight the change when it occurs.

5.Save Quickly in VI/VIM

If you’re in a hurry, you can save and quit the file you’re editing in vi by exiting insert mode, holding shift, and hitting z twice.

6.Quickly Log Out of a Terminal

You can quickly log out of a terminal session by using: CTRL+D

7.Navigate to the Last Directory You Were In

cd - will take you to the last directory you were in.

8.Make Parent Directories the Smart Way

mkdir -p /home/adam/make/all/of/these/directories/ will create all directories as needed even if they do not exist.

9.Delete the Entire Line

delete the entire line in teminal by using: CTRL+U.

10.Set the Time stamp of a File

touch -c -t 0801010800 .c will show the time stamp as 2008-01-01 8:00. The format is (YYMMDDhhmm).

Crontab - 15 Cron Job Examples

An experienced Linux sysadmin knows the importance of running the routine maintenance jobs in the background automatically.

Linux Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format
MIN HOUR DOM MON DOW CMD
Table: Crontab Fields and Allowed Ranges (Linux Crontab Syntax)Field Description Allowed Value
MIN Minute field 0 to 59
HOUR Hour field 0 to 23
DOM Day of Month 1-31
MON Month field 1-12
DOW Day Of Week 0-6
CMD Command Any command to be executed.

1. Scheduling a Job For a Specific Time Every Day

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.
30 08 10 06 * /home/raj/full-backup
30 – 30th Minute
08 – 08 AM
10 – 10th Day
06 – 6th Month (June)
* – Every day of the week
2. Schedule a Job For More Than One Instance (e.g. Twice a Day)

The following script take a incremental backup twice a day every day.

This example executes the specified incremental backup shell script (incremental-backup) at 11:00 and 16:00 on every day. The comma separated value in a field specifies that the command needs to be executed in all the mentioned time.
00 11,16 * * * /home/raj/bin/incremental-backup
00 – 0th Minute (Top of the hour)
11,16 – 11 AM and 4 PM
* – Every day
* – Every month
* – Every day of the week
3. Schedule a Job for Specific Range of Time (e.g. Only on Weekdays)

If you wanted a job to be scheduled for every hour with in a specific range of time then use the following.
Cron Job everyday during working hours

This example checks the status of the database everyday (including weekends) during the working hours 9 a.m – 6 p.m
00 09-18 * * * /home/raj/bin/checkdatabase
00 – 0th Minute (Top of the hour)
09-18 – 9 am, 10 am,11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm
* – Every day
* – Every month
* – Every day of the week
Cron Job every weekday during working hours

This example checks the status of the database every weekday (i.e excluding Sat and Sun) during the working hours 9 a.m – 6 p.m.

4. How to View Crontab Entries?
View Current Logged-In User’s Crontab entries

To view your crontab entries type crontab -l from your unix account as shown below.

raj@mail$ crontab -l
0-55/5 * * * * /usr/sbin/vnstat.cron

[Note: This displays crontab of the current logged in user]
View Root Crontab entries

Login as root user (su – root) and do crontab -l as shown below.
root@mail# crontab -l
no crontab for root
Crontab HowTo: View Other Linux User’s Crontabs entries

To view crontab entries of other Linux users, login to root and use -u {username} -l as shown below.
root@mail# crontab -u raj -l

00 09-18 * * * /home/raj/checkdatabase
5. How to Edit Crontab Entries?
Edit Current Logged-In User’s Crontab entries

To edit a crontab entries, use crontab -e as shown below. By default this will edit the current logged-in users crontab.
raj@mail$ crontab -e

*/10 * * * * /home/raj/debian/bin/check-disk-space
~
"/tmp/crontab.XXXXyjWkHw" 2L, 83C

[Note: This will open the crontab file in Vim editor for editing.
Please note cron created a temporary /tmp/crontab.XX... ]

When you save the above temporary file with :wq, it will save the crontab and display the following message indicating the crontab is successfully modified.
~
"crontab.XXXXyjWkHw" 2L, 83C written
crontab: installing new crontab
Edit Root Crontab entries

Login as root user (su – root) and do crontab -e as shown below.
root@mail# crontab -e
Edit Other Linux User’s Crontab File entries

To edit crontab entries of other Linux users, login to root and use -u {username} -e as shown below.
root@mail# crontab -u raj -e

00 09-18 * * * /home/raj/ubuntu/bin/check-db-status
~
~
~
"/tmp/crontab.XXXXyjWkHw" 2L, 83C
6. Schedule a Job for Every Minute Using Cron.

Ideally you may not have a requirement to schedule a job every minute. But understanding this example will will help you understand the other examples mentioned below in this article.
* * * * * CMD

The * means all the possible unit — i.e every minute of every hour through out the year. More than using this * directly, you will find it very useful in the following cases.
When you specify */5 in minute field means every 5 minutes.
When you specify 0-10/2 in minute field mean every 2 minutes in the first 10 minute.
Thus the above convention can be used for all the other 4 fields.
7. Schedule a Background Cron Job For Every 10 Minutes.

Use the following, if you want to check the disk space every 10 minutes.
*/10 * * * * /home/raj/check-disk-space

It executes the specified command check-disk-space every 10 minutes through out the year. But you may have a requirement of executing the command only during office hours or vice versa. The above examples shows how to do those things.

Instead of specifying values in the 5 fields, we can specify it using a single keyword as mentioned below.

There are special cases in which instead of the above 5 fields you can use @ followed by a keyword — such as reboot, midnight, yearly, hourly.
Table: Cron special keywords and its meaningKeyword Equivalent
@yearly 0 0 1 1 *
@daily 0 0 * * *
@hourly 0 * * * *
@reboot Run at startup.

8. Schedule a Job For First Minute of Every Year using @yearly

If you want a job to be executed on the first minute of every year, then you can use the @yearly cron keyword as shown below.

This will execute the system annual maintenance using annual-maintenance shell script at 00:00 on Jan 1st for every year.
@yearly /home/raj/red-hat/bin/annual-maintenance
9. Schedule a Cron Job Beginning of Every Month using @monthly

It is as similar as the @yearly as above. But executes the command monthly once using @monthly cron keyword.

This will execute the shell script tape-backup at 00:00 on 1st of every month.
@monthly /home/raj/suse/bin/tape-backup
10. Schedule a Background Job Every Day using @daily

Using the @daily cron keyword, this will do a daily log file cleanup using cleanup-logs shell scriptat 00:00 on every day.
@daily /home/raj/arch-linux/bin/cleanup-logs "day started"
11. How to Execute a Linux Command After Every Reboot using @reboot?

Using the @reboot cron keyword, this will execute the specified command once after the machine got booted every time.
@reboot CMD
12. How to Disable/Redirect the Crontab Mail Output using MAIL keyword?

By default crontab sends the job output to the user who scheduled the job. If you want to redirect the output to a specific user, add or update the MAIL variable in the crontab as shown below.
raj@mail$ crontab -l
MAIL="raj"

@yearly /home/raj/annual-maintenance
*/10 * * * * /home/raj/check-disk-space

[Note: Crontab of the current logged in user with MAIL variable]


If you wanted the mail not to be sent to anywhere, i.e to stop the crontab output to be emailed, add or update the MAIL variable in the crontab as shown below.
MAIL=""
13. How to Execute a Linux Cron Jobs Every Second Using Crontab.

You cannot schedule a every-second cronjob. Because in cron the minimum unit you can specify is minute. In a typical scenario, there is no reason for most of us to run any job every second in the system.
14. Specify PATH Variable in the Crontab

All the above examples we specified absolute path of the Linux command or the shell-script that needs to be executed.

For example, instead of specifying /home/raj/tape-backup, if you want to just specify tape-backup, then add the path /home/raj to the PATH variable in the crontab as shown below.
raj@mail$ crontab -l

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/home/raj

@yearly annual-maintenance
*/10 * * * * check-disk-space

[Note: Crontab of the current logged in user with PATH variable]
15. Installing Crontab From a Cron File

Instead of directly editing the crontab file, you can also add all the entries to a cron-file first. Once you have all thoese entries in the file, you can upload or install them to the cron as shown below.
raj@mail$ crontab -l
no crontab for ramesh

$ cat cron-file.txt
@yearly /home/raj/annual-maintenance
*/10 * * * * /home/ramej/check-disk-space

raj@mail$ crontab cron-file.txt

raj@mail$ crontab -l
@yearly /home/raj/annual-maintenance
*/10 * * * * /home/raj/check-disk-space

Note: This will install the cron-file.txt to your crontab, which will also remove your old cron entries. So, please be careful while uploading cron entries from a cron-file.txt.

Linux Command For Gmail inbox checking

To check the gmail,u can access ur  gmail inbox from command prompt.

#curl -u username:password --silent "https://mail.google.com/mail/feed/atom" | perl -ne 'print "\t" if //; print "$2\n" if /<(title|name)>(.*)<\/\1>/;'

To find IP address & To watch Linux Memory usage

Find out your router’s external IP address using the Linux command line

To Find Router external IP.Using the following commands we can see our router external IP address

without curl

#wget -O - -q icanhazip.com

with curl

#curl ifconfig.me
 
#curl icanhazip.com

#curl -s 'http://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9\.]*\).*/\1/g'



TO see Linux memory usage in real-time

If you want to display your memory usage in real-time, do a

#watch -d "free -mt"

It will display used and free memory every two seconds.

To watch SSH users actions

To view your ssh user activities

#cat /dev/vcs1

this will show you what happens in first console. to check other consoles  /dev/vcs1 or vcs2 or vcs3.

Man Command Utilities

Man pages(short for manual pages)are the documentation that comes preinstalled with almost all Unix and Unix-like operating systems. The linux command used to display them is man. Each page is a self-contained document.

The following section numbers of the manual followed by the types of pages they contain.

1   Executable programs or shell commands (or) User-level commands
2   System calls (functions provided by the kernel)
3   Library calls (functions within program libraries)
4   Special files (or) Devices and device drivers
5   File formats and conventions e.x:-/etc/passwd
6   Games
7   Miscellaneous (or) Various miscellaneous stuff - macro packages etc.(including macro packages &conventions), e.x:-man(7)
8   System administration commands (or) System maintenance and operation commands(usually only for root)
9   Kernel routines [Non standard]

To Create a PDF document for man page

syntax :-

man -t (command) | ps2pdf -> (command).pdf
ex:-
man -t man -t mkdir | ps2pdf -> mkdir.pdf

To Enable Query Cache in Mysql

Query caching is a way to increase the mysql performance by caching database queries.
to enable just edit one file, in redhat it’s called /etc/my.cnf

Add the following lines in the mysqld section

[mysqld]
query_cache_limit = 16M
query_cache_size = 256M
query_cache_type = 1

restart the mysql daemon

# /etc/init.d/mysql restart

To verify the cache is enabled

# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 36074287
Server version: 5.0.92-community-log MySQL Community Edition (GPL)

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

mysql> SHOW VARIABLES LIKE '%query_cache%';


+------------------------------+----------+
| Variable_name                | Value    |
+------------------------------+----------+
| have_query_cache             | YES      |
| query_cache_limit            | 16777216 |
| query_cache_min_res_unit     | 4096     |
| query_cache_size             | 268435456|
| query_cache_type             | ON       |
| query_cache_wlock_invalidate | OFF      |
+------------------------------+----------+

Strange Linux Commands Stands

awk = "Aho Weinberger and Kernighan"
            This language was named by its authors, Al Aho, Peter Weinberger and Brian Kernighan.

cat = "CATenate"
The cat command is a standard Unix program used to concatenate and display files. The name is from catenate, a synonym of concatenate.

grep = "Global Regular Expression Print"
    grep comes from the ed command to print all lines matching a certain pattern g/re/p where re is a regular expression.

    fgrep = "Fixed GREP"
    fgrep searches for fixed strings only. The "f" does not stand for "fast" - in fact, "fgrep foobar *.c" is usually slower than "egrep foobar *.c"
   
    egrep = "Extended GREP"
   
nroff = "New ROFF"
troff = "Typesetter new ROFF"
    These are descendants of "roff", which was a re-implementation of the Multics "runoff" program (a program that you'd use to "run off" a good copy of a document)

tee = T
    From plumbing terminology for a T-shaped pipe splitter.

Perl = "Practical Extraction and Report Language"
Perl = "Pathologically Eclectic Rubbish Lister"
    The Perl language is Larry Wall's highly popular freely-available completely portable text, process, and file manipulation tool that bridges the gap between shell and C programming.

Command to check UUID

In your /etc/fstab file, you have have seen an entry that looks UUID=c81355eb-96d2-458a-8ce0-3fa12a04cb8e instead of a more familiar disk drive designation, such as /dev/hda1. Such entries are called universally unique identifiers (UUID). You can use these 128-bit numbers to make hard disk management easier.

This following command is used to print the UUID for a device. This may be used with UUID= in /etc/fstab to name devices that works even if disks are added and removed. redhat uses this in /etc/fstab file.

Print UUID to a selected  partition /dev/sda1

#blkid -o value -s UUID /dev/sda1

Print all UUIDs

#blkid -o value -s UUID

Basic Monitoring tools

The following monitoring tools can be used to get information about system activities. use these tools to find the performance problem. some of basic monitoring commands

1.top -Process Activity Command

When you need to see the running processes on your Linux in real time, you have top as your tool for that. top also displays other info besides the running processes, like free memory both physical and swap and updates the list every five seconds.,

2.vmstat - Report virtual memory statistics

The command vmstat reports information about processes, memory, paging, block IO, traps, and cpu activity.

3.w - Who Is Logged on And What They Are Doing

w displays the information about users currently on machine, and their processes,the current time,how long the system running, how many users are currently logged on, and the system load average for the past 1, 5, and 15 minutes

4.uptime - How Long The System is Running

The uptime command can be used to check how long the server has been running.

5.ps - process status

The command should be used to display the currently running processes on our systems

6.free - Information about free and used memory on the system

The command free displays the total amount of free and used physical and swap memory in the system, as well as the buffers used by the kernel.

7.iostat - Average CPU Load, Disk Activity

The command iostat report CPU statistics and input/output statistics for devices, partitions and network filesystems (NFS).

8.sar - Store Address Register

The sar command is used to collect, report, and save system activity information it reports every 10min system activity

9.mpstat - Multiprocessor Usage

The mpstat command displays activities for each available processor, reports global and per-processor statistics

10.pmap - Process Memory Usage

pmap displays the memory map of a process for the specified pid

11.netstat - network statistics

The command netstat displays network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.

12.ss - Stack Segment

ss command is used to dump socket statistics. It allows showing information similar to netstat.

13.iptraf - Real-time Network Statistics

The iptraf command is interactive colorful IP LAN monitor. It is an ncurses-based IP LAN monitor that generates various network statistics including TCP info, UDP counts, ICMP and OSPF information, Ethernet load info, node stats, IP checksum errors, and others.

14.tcpdump - Detailed Network Traffic Analysis

The tcpdump is simple command that dump traffic on a network. However, you need good understanding of TCP/IP protocol to utilize this tool. For.e.g to display traffic info about DNS.

15.strace - trace system calls and signals

Trace system calls and signals. This is useful for debugging webserver and other server problems.

16./Proc file system - Various Kernel Statistics

/proc file system provides detailed information about various hardware devices and other Linux kernel information.

How to Encrypt a file in Linux

root@user:~# vim test.txt (write something here)

This is a Test file

:wq
=====Now see the Content of the file using cat command=====

#root@user:~# cat test.txt
This is Test file

=====Now we are going to Encrypt the file with gpg======

root@user:~# gpg -c test.txt

Enter Pass-phrase : <YOUR-PASSWORD>

Repeat Pass-phrase : <YOUR-PASSWORD>

====You can see one more file create.=====

root@user:~# ls -l test*

-rw-rr 1 root root 59 2011-03-02 17:20 test.txt
-rw-rr 1 root root 97 2011-03-02 17:23 test.txt.gpg

=====Lets try to see encrypt file with cat command=====

root@user:~# cat test.txt.gpg

i+`P$@CoEkW%>o
8*zbB`EA9{7
IW

=====Delete original File=====

root@user:~# rm test.txt

=====Now we are going to decrypt the encrypted file=====

root@user:~# gpg test.txt.gpg

Enter Pass-phrase : <YOUR-PASSWORD>


=====See decrypted file content=====

root@user:~# cat test.txt
This is a Test file

A-Z Linux Terminal Shortcuts


Ctl-A       Moves cursor to beginning of line of text (on the command-line).
Ctl-B       Backspace (nondestructive).
Ctl-C       Break. Terminate a foreground job.
Ctl-D       Log out from a shell (similar to exit).
Ctl-E       Moves cursor to end of line of text (on the command-line).
Ctl-F       Moves cursor forward one character position (on the command-line).
Ctl-G       BEL. On some old-time teletype terminals, this would actually ring a bell.In an xterm it might beep.
Ctl-H       Rubout (destructive backspace). Erases characters the cursor backs over while  backspacing.
Ctl-I        Horizontal tab.
Ctl-J        Newline (line feed). In a script, may also be expressed in octal notation -- '\012' or in   hexadecimal -- '\x0a'.
Ctl-K       Vertical tab.  When typing text on the console or in an xterm window, Ctl-K erases  from the character under the cursor to end of line. Within a script, Ctl-K may behave  differently, as in Lee Lee Maschmeyer's example, below
Ctl-L       Formfeed (clear the terminal screen). In a terminal, this has the same effect as the  clear  command. When sent to a printer, a Ctl-L causes an advance to end of the paper sheet.
Ctl-N       Erases a line of text recalled from history buffer [20] (on the command-line).
Ctl-O       Issues a newline (on the command-line).
Ctl-P       Recalls last command from history buffer (on the command-line).
Ctl-Q       Resume (XON). This resumes stdin in a terminal.
Ctl-R       Backwards search for text in history buffer (on the command-line).
Ctl-S       Suspend (XOFF). This freezes stdin in a terminal. (Use Ctl-Q to restore input.)
Ctl-T       Reverses the position of the character the cursor is on with the previous character  (on the      command-line).
Ctl-U       Erase a line of input, from the cursor backward to beginning of line. In some settings, Ctl-U     erases the entire line of input, regardless of cursor position.
Ctl-X       In certain word processing programs, Cuts highlighted text and copies to clipboard.
Ctl-Y       Pastes back text previously erased (with Ctl-U or Ctl-W).
Ctl-Z       Pauses a foreground job.

Ways to Installing CHKROOTKIT on Linux server

 CHKROOTKIT
chkrootkit (Check Rootkit) is a common Unix-based program intended to help system administrators check their system for known rootkits. It is a shell script using common UNIX/Linux tools like the strings.

Environments for chkrootkit:
chkrootkit is tested on: Linux 2.0.x, 2.2.x, 2.4.x and 2.6.x,
FreeBSD 2.2.x, 3.x, 4.x and 5.x, OpenBSD 2.x, 3.x and 4.x., NetBSD
1.6.x, Solaris 2.5.1, 2.6, 8.0 and 9.0, HP-UX 11, Tru64, BSDI and Mac
OS X.


1. Login to your server as root. (SSH)

2. Down load the chkrootkit.
Type: wget ftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz

3. Unpack the chkrootkit you just downloaded.
Type: tar xvzf chkrootkit.tar.gz

4. Change to new directory
Type: cd chkrootkit*

5. Compile chkrootkit
Type: make sense

6. Run chkrootkit
Type: ./chkrootkit

what the chkrootkit will do

1. It checks for signs of rootkits - chkrootkit, ifpromisc.c, chklastlog.c, chkwtmp.c, check_wtmpx.c, chkproc.c, chkdirs.c, strings.c, chkutmp.c; chkrootkit is the main module which controls all other modules.

2.chkrootkit checks system binaries for modifications. eg: find, grep, cron, crontab, echo, env, su, ifconfig, init, sendmail ...).

3.Next, it finds default files and directories of many rootkits (sniffer's logs, HiDrootkit's default dir, tOrn's default files and dirs...).

4.After that, it continues to look for default files and directories of known rootkits.


If it says "Checking `bindshell'... INFECTED (PORTS: 465)"
This is normal and it is NOT really a virus.

The following tests are made:

aliens asp bindshell lkm rexedcs sniffer wted w55808 scalper slapper z2 amd basename biff chfn chsh cron date du dirname echo egrep env find fingerd gpm grep hdparm su ifconfig inetd inetdconf init identd killall ldsopreload login ls lsof mail mingetty netstat named passwd pidof pop2 pop3 ps pstree rpcinfo rlogind rshd slogin sendmail sshd syslogd tar tcpd tcpdump top telnetd timed traceroute vdir w write.

Clamav Installion And Uses On Linux

Clam Antivirus (ClamAV) is a free, cross-platform antivirus software tool-kit able to detect many types of malicious software, including viruses.There is a common talk that there are no viruses on the Linux platform - which to a large extent is true. But when you get a mail attachment from windows machine may be the machine is full of virus. That virus no affect our linux server.But it will affect the windows users whom using our websites.

Download ClamAV from http://sourceforge.net/projects/clamav/files/clamav/0.97/clamav-0.97.tar.gz/download

Extract
# tar zxvf clamav-0.95.1.tar.gz

# cd clamav-0.95.1

# ./configure

# make all

# make install

Once after installation you need to modify two configuration files to get ClamAV running & for definition updates.

1. vim /etc/clamd.conf
   Comment on example:line number 8
2.vim /etc/freshclam.conf
   Comment on example:line number 8


ClamAV installation in Cpanel


#Main >> cPanel >> Manage Plugins

#Name: clamavconnector
      Author: cPanel Inc.
      and select the Install and keep updated tick box

    and finally save

    after completing in WHM.

You can install it from backend. Follow the steps
    
#Go terminal window
      
#login as root

#For 32 bit installations:
    cd /usr/local/cpanel/modules-install/clamavconnector-Linux-i686

#For 64 bit:
    cd /usr/local/cpanel/modules-install/clamavconnector-Linux-x86_64

#Run on screen ./install


update your virus definitions

freshclam

check files in your home directory:

clamscan

check files in the entire home directory:

clamscan -r /home

check files on the entire drive (displaying everything):

clamscan -r /

check files on the entire drive but only display infected files and ring a bell when found:

clamscan -r --bell --mbox -i /

scan and mail report

clamscan --remove -r --bell -i /home/example/mail/ |  mail -s 'clam' 123@example.com

examples of scanned virus

/home/example/mail/new/1301578754.H708604P328.server.test.com,S=42794: Trojan.Spy.Zbot-464 FOUND
/home/example/mail/new/1301578754.H708604P328.server.test.com,S=42794: Removed.
/home/example/mail/new/1301455585.H960996P15497.server.test.com,S=10619: Trojan.Downloader.Agent-1452 FOUND
/home/example/mail/new/1301455585.H960996P15497.server.test.com,S=10619: Removed.

File Fragmentation checking on Linux

    To find file fragmentation information for a specific file,we can use filefrag command.
filefrag reports on how badly fragmented a particular file. It makes allowances for indirect blocks for ext2 and ext3 filesystems, but can be used on files for any filesystem.

syntax:

filefrag -v (filename)

# filefrag -v /home/example/example.txt

-v => verbose when checking for file fragmentation

ouptput:(for example)

Checking example.txt
Filesystem type is: ef53
Filesystem cylinder groups is approximately 606
Blocksize of file example.txt is 4096
File size of example.txt is 1194 (1 blocks)
First block: 7006588
Last block: 7006588
example.txt: 1 extent found