Linux lvm - Logical Volume Manager

Linux lvm - Logical Volume Manager












This article describes a basic logic behind a Linux logical volume manager by showing real examples of configuration and usage. Although Debian Linux will be used for this tutorial, you can also apply the same command line syntax with other Linux distributions such as Red Hat, Mandriva, SuSe Linux and others.

1. This is what we are going to do

Logical Volume Manager

2. Create Partitions

For this Linux lvm example you need an unpartitioned hard disk /dev/sdb. First you need to create physical volumes. To do this you need partitions or a whole disk. It is possible to run pvcreate command on /dev/sdb, but I prefer to use partitions and from partitions I later create physical volumes.

Logical Volume Manager List Partitions with fdisk
Use your preferred partitioning tool to create partitions. In this example I have used cfdisk.

Create partitions with cfdiskLogical Volume Manager List Partitions with fdisk


Partitions are ready to use.

3. Create physical volumes

Use the pvcreate command to create physical volumes.

# pvcreate /dev/sdb1
# pvcreate /dev/sdb2

The pvdisplay command displays all physical volumes on your system.

# pvdisplay 

Alternatively the following command should be used:

# pvdisplay /dev/sdb1 

Create physical volumes with pvcreate

4. Create Virtual Group

At this stage you need to create a virtual group which will serve as a container for your physical volumes. To create a virtual group with the name "mynew_vg" which will include /dev/sdb1 partition, you can issue the following command:

# vgcreate mynew_vg /dev/sdb1 

To include both partitions at once you can use this command:

# vgcreate mynew_vg /dev/sdb1 /dev/sdb2 

Create Virtual Group

Feel free to add new physical volumes to a virtual group by using the vgextend command.

# vgextend mynew_vg /dev/sdb2 

virtual group extend

5. Create Logical Volumes

From your big cake (virtual group) you can cut pieces (logical volumes) which will be treated as a partitions for your linux system. To create a logical volume, named "vol01", with a size of 400 MB from the virtual group "mynew_vg" use the following command:

  • create a logical volume of size 400 MB -L 400
  • create a logical volume of size 4 GB -L 4G
# lvcreate -L 400 -n vol01 mynew_vg

lvm lvcreate

With a following example you will create a logical volume with a size of 1GB and with the name vol02:

# lvcreate -L 1000 -n vol02 mynew_vg

lvcreate

Note the free size in virtual group.

lvcrete free space

6. Create File system on logical volumes

The logical volume is almost ready to use. All you need to do is to create a filesystem.:

# mkfs.ext3 -m 0 /dev/mynew_vg/vol01 

the -m option specifies the percentage reserved for the super-user, set this to 0 if you wish not to waste any space, the default is 5%. create file system on the logical volumes

7. Edit /etc/fstab

Add an entry for your newly created logical volume into /etc/fstab
edit /etc/fstab to include logical volumes

7.1. Mount logical volumes

Before you mount do not forget to create a mount point.

# mkdir /home/foobar 

mount logical volumes

8. Extend logical volume

The biggest advantage of logical volume manager is that you can extend your logical volumes any time you are running out of the space. To increase the size of a logical volume by another 800 MB you can run this command:

# lvextend -L +800 /dev/mynew_vg/vol01 

Extend logical volume
The command above does not actually increase the physical size of volume, to do that you need to:

# resize2fs  /dev/mynew_vg/vol01 

Look at the figure below to see what problems you may encounter when extending a volume:
Problem with extending a logical volume

9. Remove logical volume

The command lvremove can be used to remove logical volumes. Make sure that before you attempt to remove logical volumes your logical volume does not have any valuable data stored on it, moreover, make sure the volume is unmounted.

# lvdisplay 

display volume group

# lvremove /dev/mynew_vg/vol02 

remove logical volume

Install 64-bit Adobe Flash Player on Ubuntu

FlashNow that there is a java browser plugin and a working wine for 64-bit on the Ubuntu repositories, there is not much holding back 64-bit Linux on the desktop. Maybe the only thing missing is the Adobe Flash player. Most of the time Flash is just annoying, nevertheless sometimes needed. Luckily, there is now a Flash Player release for 64-bit Linux (however, still beta alpha but stable so far) . I am pretty sure the instructions are identical for other Linux distributions.

To install it:

1. Download it from here (now here). The beta has been closed and Adobe plans to release a 64-bit linux version soon. In the meanwhile you can get the latest version here (the md5 checksum is 5aa962abc2e2c85a5efee6a39a6a91a0) and cross your fingers for html5 :) . (NB: The screenshot is from a previous release, however the actual binary *is* the latest. You should consider using flashblock (package xul-ext-flashblock in Debian/Ubuntu) or an other alternative (gnash) until Adobe releases a security fix.)

2. Unpackage it using a terminal (with the assumption your firefox downloads into your Desktop as default):
cd Desktop
tar xvzf
libflashplayer-10.0.32.18.linux-x86_64.so.tar.gz

(The name of the tar.gz file may change when a new version is released, change accordingly).

3. Create a plugin directory in your $HOME (instead of a system directory):

cd
mkdir -p .mozilla/plugins

4. Move the file to the plugin directory:
mv Desktop/libflashplayer.so .mozilla/plugins

5. Restart firefox. Go to about:plugins to see if it’s enabled:
about:plugins
That’s it.

Edit: Alternatively, you can use the graphical approach:

1. go to the download pages and click on “Download 64-bit Plugin for Linux (TAR.GZ, 3.64 MB)”.
2. select “Open with ” in firefox (you have to click on open to enable the ok button) and clck on OK.
3. The archive manager will open and show you the libflashplayer.so file.
4. Click on extra and a save window will open.
5. Type ctrl + h to show hidden files. Go to .mozilla (dubble click).
6. If no “plugins” directory is present, click on “Create Folder” on the top right and type as name “plugins” (without the quotes). Press Ener.
7. Click on Extract.
8. Click on Close on the windows showing the result.
9. Close the archive manager.
10. Restart firefox.

Add a New Hard Disk VMWARE Without Rebooting Guest

It is possible to add or remove a SCSI device explicitly, or to re-scan an entire SCSI bus without rebooting a running Linux VM guest.

1) Add a New Disk To Vm Guest

  • First, you need to add hard disk by visiting vmware hardware settings menu.
    Click on VM > Settings

  • Alternatively you can press CTRL + D to bring settings dialog box.

  • Click on Add+ to add new hardware to guest:


  • Select hardware type Hard disk and click on Next

  • Select create a new virtual disk and click on Next

  • Set virtual disk type to SCSI and click on Next

  • Set maximum disk size as per your requirements and click on Next

  • Finally, set file location and click on Finish.

2) Rescan the SCSI Bus to Add a SCSI Device Without rebooting the VM

A rescan can be issued by typing the following command:

echo "- - -" > /sys/class/scsi_host/host#/scan
fdisk -l
tail -f /var/log/message

Replace host# with actual value such as host0. You can find scsi_host value using the following command:

# ls /sys/class/scsi_host

Output:

host0

Now type the following to send a rescan request:

echo "- - -" > /sys/class/scsi_host/host0/scan
fdisk -l
tail -f /var/log/message

3) Format a New Disk

You can create partition using fdisk and format it using mkfs.ext3 command:

# fdisk /dev/sdc
# mkfs.ext3 /dev/sdc3

4) Create a Mount Point And Update /etc/fstab

# mkdir /disk3

Open /etc/fstab file, enter:

# vi /etc/fstab

Append as follows:

/dev/sdc3 /disk3 ext3 defaults 1 2

Save and close the file.

Love Linux?

Being a Unix Guru

UNIX is an extremely popular platform for deploying server software partly because of its security and stability, but also because it has a rich set of command line and scripting tools. Programmers use these tools for manipulating the file system, processing log files, and generally automating as much as possible.

If you want to be a serious server developer, you will need to have a certain facility with a number of UNIX tools; about 15. You will start to see similarities among them, particularly regular expressions, and soon you will feel very comfortable. Combining the simple commands, you can build very powerful tools very quickly--much faster than you could build the equivalent functionality in C or Java, for example.

This lecture takes you through the basic commands and then shows you how to combine them in simple patterns or idioms to provide sophisticated functionality like histogramming. This lecture assumes you know what a shell is and that you have some basic familiarity with UNIX.

[By the way, this page gets a lot of attention on the net and unfortunately I get mail from lots of people that have better solutions or stuff I should add. I'm only showing what I've learned from watching good UNIX people so I am not saying these tips are the optimal solutions. I'd make a pretty ignorant sys admin.]

Everything is a stream

The first thing you need to know is that UNIX is based upon the idea of a stream. Everything is a stream, or appears to be. Device drivers look like streams, terminals look like streams, processes communicate via streams, etc... The input and output of a program are streams that you can redirect into a device, a file, or another program.

Here is an example device, the null device, that lets you throw output away. For example, you might want to run a program but ignore the output.

$ ls > /dev/null # ignore output of ls

where "# ignore output of ls" is a comment.

Most of the commands covered in this lecture process stdin and send results to stdout. In this manner, you can incrementally process a data stream by hooking the output of one tool to the input of another via a pipe. For example, the following piped sequence prints the number of files in the current directory modified in August.

$ ls -l | grep Aug | wc -l

Imagine how long it would take you to write the equivalent C or Java program. You can become an extremely productive UNIX programmer if you learn to combine the simple command-line tools. Even when programming on a PC, I use MKS's UNIX shell and command library to make it look like a UNIX box. Worth the cash.

Getting help

If you need to know about a command, ask for the "man" page. For example, to find out about the ls command, type

$ man ls
LS(1) System General Commands Manual LS(1)

NAME
ls - list directory contents

SYNOPSIS
ls [-ACFLRSTWacdfgiklnoqrstux1] [file ...]

DESCRIPTION
For each operand that names a file of a type other than directory, ls
...

You will get a summary of the command and any arguments.

If you cannot remember the command's name, try using apropos which finds commands and library routines related to that word. For example, to find out how to do checksums, type

$ apropos checksum
cksum(1), sum(1) - display file checksums and block counts
md5(1) - calculate a message-digest fingerprint (checksum) for a file

Special Directories and files

A shortcut for you home directory, /home/username, is ~username. For example, ~parrt is my home directory,/home/parrt.

When you are using the shell, there is the notion of current directory. The dot '.' character is a shorthand for the current directory and '..' is a shorthand for the directory above the current. So to access file test in the current directory, ./test is the same as plain test. If test is a directory above, use ../test.

/ is the root directory; there is no drive specification in UNIX.

The .bash_profile file is very important as it is how your shell session is initialized including your ever-importantCLASSPATH environment variable. Your bash shell initialization file is ~username/.bash_profile and has set up code like the following:

PATH=$PATH:$HOME/bin

Typically, you will go in and set your CLASSPATH so that you don't have to set it all the time.

export CLASSPATH=".:/home/public/cs601/junit.jar"

The export means that the assignment to CLASSPATH is visible to all child processes (that is, visible to all programs you run from the shell).

The basics

cd

Changing a directory is done with cd dir where dir can be "." or ".." to move to current directory (do nothing) or go up a directory.

ls

Display files in a directory with ls. The -l option is used to display details of the files:

total 9592
-rw-r--r-- 1 parrt staff 5600 Aug 19 2005 C-Java-relationship.html
...
drwxr-xr-x 13 parrt staff 442 Oct 19 2005 sessions
-rw-r--r-- 1 parrt staff 2488 Oct 19 2005 sessions.html
...

"staff" is parrt's group.

If you want to see hidden files (those starting with "."), use "-a".

Combinations are possible: use "ls -la" to see details of all files including hidden ones.

displaying files

There are 4 useful ways to display the contents or portions of a file. The first is the very commonly used commandcat. For example, to display my list of object-oriented keywords used in this course, type:

$ cat /home/public/cs601/oo.keywords.txt

If a file is really big, you will probably want to use more, which spits the file out in screen-size chunks.

$ more /var/log/mail.log

If you only want to see the first few lines of a file or the last few lines use head and tail.

$ head /var/log/mail.log
$ tail /var/log/mail.log

You can specify a number as an argument to get a specific number of lines:

$ head -30 /var/log/mail.log

The most useful incantation of tail prints the last few lines of a file and then waits, printing new lines as they are appended to the file. This is great for watching a log file:

$ tail -f /var/log/mail.log

If you need to know how many characters, words, or lines are in a file, use wc:

$ wc /var/log/mail.log
164 2916 37896 /var/log/mail.log

Where the numbers are, in order, lines, words, then characters. For clarity, you can use wc -l to print just the number of lines.

pushd, popd

Instead of cd you can use pushd to save the current dir and then automatically cd to the specified directory. For example,

$ pwd
/Users/parrt
$ pushd /tmp
/tmp ~
$ pwd
/tmp
$ popd
~
$ pwd
/Users/parrt

top

To watch a dynamic display of the processes on your box in action, use top.

ps

To print out (wide display) all processes running on a box, use ps auxwww.

chmod

To change the privileges of a file or directory, use chmod. The privileges are 3 digit octal words with 3 bits per digit: rwxrwxrwx where the first digit is for the file owner, the 2nd for the group, and 3rd for anybody. 644 is a common word value file which means 110100100 or rw-r--r--. When you do ls -l you will see these bits. 755 is a common word value for directories: rwxr-xr-x where directories need to be executable for cd to be able to enter that dir. 755 is a shorthand for the more readable argument u=rwx,go=rx. u is user, g is group, o is other.

Use chmod -R for recursively applying to all the dirs below the argument as well.

Searching streams

One of the most useful tools available on UNIX and the one you may use the most is grep. This tool matches regular expressions (which includes simple words) and prints matching lines to stdout.

The simplest incantation looks for a particular character sequence in a set of files. Here is an example that looks for any reference to System in the java files in the current directory.

grep System *.java

You may find the dot '.' regular expression useful. It matches any single character but is typically combined with the star, which matches zero or more of the preceding item. Be careful to enclose the expression in single quotes so the command-line expansion doesn't modify the argument. The following example, looks for references to any a forum page in a server log file:

$ grep '/forum/.*' /home/public/cs601/unix/access.log

or equivalently:

$ cat /home/public/cs601/unix/access.log | grep '/forum/.*'

The second form is useful when you want to process a collection of files as a single stream as in:

cat /home/public/cs601/unix/access*.log | grep '/forum/.*'

If you need to look for a string at the beginning of a line, use caret '^':

$ grep '^195.77.105.200' /home/public/cs601/unix/access*.log

This finds all lines in all access logs that begin with IP address 195.77.105.200.

If you would like to invert the pattern matching to find lines that do not match a pattern, use -v. Here is an example that finds references to non image GETs in a log file:

$ cat /home/public/cs601/unix/access.log | grep -v '/images'

Now imagine that you have an http log file and you would like to filter out page requests made by nonhuman spiders. If you have a file called spider.IPs, you can find all nonspider page views via:

$ cat /home/public/cs601/unix/access.log | grep -v -f /tmp/spider.IPs

Finally, to ignore the case of the input stream, use -i.

Translating streams

Morphing a text stream is a fundamental UNIX operation. PERL is a good tool for this, but since I don't like PERL I stick with three tools: tr, sed, and awk. PERL and these tools are line-by-line tools in that they operate well only on patterns fully contained within a single line. If you need to process more complicated patterns like XML or you need to parse a programming language, use a context-free grammar tool like ANTLR.

tr

For manipulating whitespace, you will find tr very useful.

If you have columns of data separated by spaces and you would like the columns to collapse so there is a single column of data, tell tr to replace space with newline tr ' ' '\n'. Consider input file /home/public/cs601/unix/names:

jim scott mike
bill randy tom

To get all those names in a column, use

$ cat /home/public/cs601/unix/names | tr ' ' '\n'

If you would like to collapse all sequences of spaces into one single space, use tr -s ' '.

To convert a PC file to UNIX, you have to get rid of the '\r' characters. Use tr -d '\r'.

sed

If dropping or translating single characters is not enough, you can use sed (stream editor) to replace or delete text chunks matched by regular expressions. For example, to delete all references to word scott in the names file from above, use

$ cat /home/public/cs601/unix/names | sed 's/scott//'

which substitutes scott for nothing. If there are multiple references to scott on a single line, use the g suffix to indicate "global" on that line otherwise only the first occurrence will be removed:

$ ... | sed 's/scott//g'

If you would like to replace references to view.jsp with index.jsp, use

$ ... | sed 's/view.jsp/index.jsp/'

If you want any .asp file converted to .jsp, you must match the file name with a regular expression and refer to it via \1:

$ ... | sed 's/\(.*\).asp/\1.jsp/'

The \(...\) grouping collects text that you can refer to with \1.

If you want to kill everything from the ',' character to end of line, use the end-of-line marker $:

$ ... | sed 's/,.*$//' # kill from comma to end of line

awk

When you need to work with columns of data or execute a little bit of code for each line matching a pattern, useawk. awk programs are pattern-action pairs. While some awk programs are complicated enough to require a separate file containing the program, you can do some amazing things using an argument on the command-line.

awk thinks input lines are broken up into fields (i.e., columns) separate by whitespace. Fields are referenced in an action via $1, $2, ... while $0 refers to the entire input line.

A pattern-action pair looks like:

pattern {action}

If you omit the pattern, the action is executed for each input line. Omitting the action means print the line. You can separate the pairs by newline or semicolon.

Consider input

aasghar Asghar, Ali
wchen Chen, Wei
zchen Chen, Zhen-Jian

If you want a list of login names, ask awk to print the first column:

$ cat /home/public/cs601/unix/emails.txt | awk '{print $1;}'

If you want to convert the login names to email addresses, use the printf C-lookalike function:

$ cat /home/public/cs601/unix/emails.txt | awk '{printf("%s@cs.usfca.edu,",$1);}'

Because of the missing \n in the printf string, you'll see the output all on one line ready for pasting into a mail program:

aasghar@cs.usfca.edu,wchen@cs.usfca.edu,zchen@cs.usfca.edu

You might also want to reorder columns of data. To print firstname, lastname, you might try:

$ cat /home/public/cs601/unix/emails.txt | awk '{printf("%s %s\n", $3, $2);}'

but you'll notice that the comma is still there as it is part of the column:

Ali Asghar,
Wei Chen,
Zhen-Jian Chen,

You need to pipe the output thru tr (or sed) to strip the comma:

$ cat /home/public/cs601/unix/emails.txt | \
awk '{printf("%s %s\n", $3, $2);}' | \
tr -d ','

Then you will see:

Ali Asghar
Wei Chen
Zhen-Jian Chen

You can also use awk to examine the value of content. To sum up the first column of the following data (in file/home/public/cs601/unix/coffee):

3 parrt
2 jcoker
8 tombu

use the following simple command:

$ awk '{n+=$1;} ; END {print n;}' < /home/public/cs601/unix/coffee

where END is a special pattern that means "after processing the stream."

If you want to filter or sum all values less than or equal to, say 3, use an if statement:

$ awk '{if ($1<=3) n+=$1;} END {print n;}' < /home/public/cs601/unix/coffee

In this case, you will see output 5 (3+2);

Using awk to grab a particular column is very common when processing log files. Consider a http://www.jguru.compage view log file, /home/public/cs601/unix/pageview-20021022.log, that are of the form:

date-stamp(thread-name): userID-or-IPaddr URL site-section

So, the data looks like this:

20021022_00.00.04(tcpConnection-80-3019):       203.6.152.30    /faq/subtopic.jsp?topicID=472&page=2    FAQs   
20021022_00.00.07(tcpConnection-80-2981): 995134 /index.jsp Home
20021022_00.00.08(tcpConnection-80-2901): 66.67.34.44 /faq/subtopic.jsp?topicID=364 FAQs
20021022_00.00.12(tcpConnection-80-3003): 217.65.96.13 /faq/view.jsp?EID=736437 FAQs
20021022_00.00.13(tcpConnection-80-3019): 203.124.210.98 /faq/topicindex.jsp?topic=JSP FAQs/JSP
20021022_00.00.15(tcpConnection-80-2988): 202.56.231.154 /faq/index.jsp FAQs
20021022_00.00.19(tcpConnection-80-2976): 66.67.34.44 /faq/view.jsp?EID=225150 FAQs
220021022_00.00.21(tcpConnection-80-2974): 143.89.192.5 /forums/most_active.jsp?topic=EJB Forums/EJB
20021022_00.00.21(tcpConnection-80-2996): 193.108.239.34 /guru/edit_account.jsp Guru
20021022_00.00.21(tcpConnection-80-2996): 193.108.239.34 /misc/login.jsp Misc
...

When a user is logged in, the log file has their user ID rather than their IP address.

Here is how you get a list of URLs that people view on say October 22, 2002:

$ awk '{print $3;}' < /home/public/cs601/unix/pageview-20021022.log
/faq/subtopic.jsp?topicID=472&page=2
/index.jsp
/faq/subtopic.jsp?topicID=364
/faq/view.jsp?EID=736437
/faq/topicindex.jsp?topic=JSP
/faq/index.jsp
/faq/view.jsp?EID=225150
/forums/most_active.jsp?topic=EJB
/guru/edit_account.jsp
/misc/login.jsp
...

If you want to count how many page views there were that day that were not processing pages (my processing pages are all of the form process_xxx), pipe the results through grep and wc:

$ awk '{print $3;}' < /home/public/cs601/unix/pageview-20021022.log | \
grep -v process | \
wc -l
67850

If you want a unique list of URLs, you can sort the output and then use uniq:

$ awk '{print $3;}' < /home/public/cs601/unix/pageview-20021022.log | \
sort | \
uniq

uniq just collapses all repeated lines into a single line--that is why you must sort the output first. You'll get output like:

/article/index.jsp
/article/index.jsp?page=1
/article/index.jsp?page=10
/article/index.jsp?page=2
...

Tarballs

Note: The name comes from a similar word, hairball (stuff that cats throw up), I'm pretty sure.

To collect a bunch of files and directories together, use tar. For example, to tar up your entire home directory and put the tarball into /tmp, do this

$ cd ~parrt
$ cd .. # go one dir above dir you want to tar
$ tar cvf /tmp/parrt.backup.tar parrt

By convention, use .tar as the extension. To untar this file use

$ cd /tmp
$ tar xvf parrt.backup.tar

tar untars things in the current directory!

After running the untar, you will find a new directory, /tmp/parrt, that is a copy of your home directory. Note that the way you tar things up dictates the directory structure when untarred. The fact that I mentioned parrt in the tar creation means that I'll have that dir when untarred. In contrast, the following will also make a copy of my home directory, but without having a parrt root dir:

$ cd ~parrt
$ tar cvf /tmp/parrt.backup.tar *

It is a good idea to tar things up with a root directory so that when you untar you don't generate a million files in the current directly. To see what's in a tarball, use

$ tar tvf /tmp/parrt.backup.tar

Most of the time you can save space by using the z argument. The tarball will then be gzip'd and you should use file extension .tar.gz:

$ cd ~parrt
$ cd .. # go one dir above dir you want to tar
$ tar cvfz /tmp/parrt.backup.tar.gz parrt

Unzipping requires the z argument also:

$ cd /tmp
$ tar xvfz parrt.backup.tar.gz

If you have a big file to compress, use gzip:

$ gzip bigfile

After execution, your file will have been renamed bigfile.gz. To uncompress, use

$ gzip -d bigfile.gz

To display a text file that is currently gzip'd, use zcat:

$ zcat bigfile.gz

Moving files between machines

rsync

When you need to have a directory on one machine mirrored on another machine, use rsync. It compares all the files in a directory subtree and copies over any that have changed to the mirrored directory on the other machine. For example, here is how you could "pull" all logs files from livebox.jguru.com to the box from which you execute thersync command:

$ hostname
jazz.jguru.com
$ rsync -rabz -e ssh -v 'parrt@livebox.jguru.com:/var/log/jguru/*' \
/backup/web/logs

rsync will delete or truncate files to ensure the files stay the same. This is bad if you erase a file by mistake--it will wipe out your backup file. Add an argument called --suffix to tell rsync to make a copy of any existing file before it overwrites it:

$ hostname
jazz.jguru.com
$ rsync -rabz -e ssh -v --suffix .rsync_`date '+%Y%m%d'` \
'parrt@livebox.jguru.com:/var/log/jguru/*' /backup/web/logs

where `date '+%Y%m%d'` (in reverse single quotes) means "execute this date command".

To exclude certain patterns from the sync, use --exclude:

$ rsync -rabz --exclude=entitymanager/ --suffix .rsync_`date '+%Y%m%d'` \
-e ssh -v 'parrt@livebox.jguru.com:/var/log/jguru/*' /backup/web/logs

scp

To copy a file or directory manually, use scp:

$ scp lecture.html parrt@nexus.cs.usfca.edu:~parrt/lectures

Just like cp, use -r to copy a directory recursively.

Miscellaneous

find

Most GUIs for Linux or PCs have a search facility, but from the command-line you can use find. To find all files named .p4 starting in directory ~/antlr/depot/projects, use:

$ find  ~/antlr/depot/projects -name '.p4'

The default "action" is to -print.

You can specify a regular expression to match. For example, to look under your home directory for any xml files, use:

$ find ~ -name '*.xml' -print

Note the use of the single quotes to prevent command-line expansion--you want the '*' to go to the findcommand.

You can execute a command for every file or directory found that matches a name. For example, do delete all xml files, do this:

$ find ~ -name '*.xml' -exec rm {} \;

where "{}" stands for "current file that matches". The end of the command must be terminated with ';' but because of the command-line expansion, you'll need to escape the ';'.

You can also specify time information in your query. Here is a shell script that uses find to delete all files older than 14 days.

#!/bin/sh

BACKUP_DIR=/var/data/backup

# number of days to keep backups
AGE=14 # days
AGE_MINS=$[ $AGE * 60 * 24 ]

# delete dirs/files
find $BACKUP_DIR/* -cmin +$AGE_MINS -type d -exec rm -rf {} \;

fuser

If you want to know who is using a port such as HTTP (80), use fuser. You must be root to use this:

$ sudo /sbin/fuser -n tcp 80
80/tcp: 13476 13477 13478 13479 13480
13481 13482 13483 13484 13486 13487 13489 13490 13491
13492 13493 13495 13496 13497 13498 13499 13500 13501 13608

The output indicates the list of processes associated with that port.

whereis

Sometimes you want to use a command but it's not in your PATH and you can't remember where it is. Use whereis to look in standard unix locations for the command.

$ whereis fuser
fuser: /sbin/fuser /usr/man/man1/fuser.1 /usr/man/man1/fuser.1.gz
$ whereis ls
ls: /bin/ls /usr/man/man1/ls.1 /usr/man/man1/ls.1.gz

whereis also shows man pages.

which

Sometimes you might be executing the wrong version of a command and you want to know which version of the command your PATH indicates should be run. Use which to ask:

$ which ls
alias ls='ls --color=tty'
/bin/ls
$ which java
/usr/local/java/bin/java

If nothing is found in your path, you'll see:

$ which fuser
/usr/bin/which: no fuser in (/usr/local/bin:/usr/local/java/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/usr/X11R6/bin:/home/parrt/bin)

kill

To send a signal to a process, use kill. Typically you'll want to just say kill pid where pid can be found from psor top (see below).

Use kill -9 pid when you can't get the process to die; this means kill it with "extreme prejudice".

traceroute

If you are having trouble getting to a site, use traceroute to watch the sequence of hops used to get to a site:

$ /usr/sbin/traceroute www.cnn.com
1 65.219.20.145 (65.219.20.145) 2.348 ms 1.87 ms 1.814 ms
2 loopback0.gw5.sfo4.alter.net (137.39.11.23) 3.667 ms 3.741 ms 3.695 ms
3 160.atm3-0.xr1.sfo4.alter.net (152.63.51.190) 3.855 ms 3.825 ms 3.993 ms
...

What is my IP address?

$ /sbin/ifconfig

Under the eth0 interface, you'll see the inet addr:

eth0      Link encap:Ethernet  HWaddr 00:10:DC:58:B1:F0
inet addr:138.202.170.4 Bcast:138.202.170.255 Mask:255.255.255.0
...

Useful combinations

How to kill a set of processes

If you want to kill all java processes running for parrt, you can either run killall java if you are parrt or generate a "kill" script via:

$ ps auxwww|grep java|grep parrt|awk '{print "kill -9 ",$2;}' > /tmp/killparrt
$ bash /tmp/killparrt # run resulting script

The /tmp/killparrt file would look something like:

kill -9 1021
kill -9 1023
kill -9 1024

Note: you can also do this common task with:

$ killall java

Please be aware that this is linux specific; i'm told that it will kill all processing on UNIXen like Solaris!

How to make a histogram

A histogram is set of count, value pairs indicating how often the value occurs. The basic operation will be to sort, then count how many values occur in a row and then reverse sort so that the value with the highest count is at the top of the report.

$ ... | sort |uniq -c|sort -r -n

Note that sort sorts on the whole line, but the first column is obviously significant just as the first letter in someone's last name significantly positions their name in a sorted list.

uniq -c collapses all repeated sequences of values but prints the number of occurrences in front of the value. Recall the previous sorting:

$ awk '{print $3;}' < /home/public/cs601/unix/pageview-20021022.log | \
sort | \
uniq
/article/index.jsp
/article/index.jsp?page=1
/article/index.jsp?page=10
/article/index.jsp?page=2
...

Now add -c to uniq:

$ awk '{print $3;}' < /home/public/cs601/unix/pageview-20021022.log | \
sort | \
uniq -c
623 /article/index.jsp
6 /article/index.jsp?page=1
10 /article/index.jsp?page=10
109 /article/index.jsp?page=2
...

Now all you have to do is reverse sort the lines according to the first column numerically.

$ awk '{print $3;}' < /home/public/cs601/unix/pageview-20021022.log | \
sort | \
uniq -c | \
sort -r -n
6170 /index.jsp
2916 /search/results.jsp
1397 /faq/index.jsp
1018 /forums/index.jsp
884 /faq/home.jsp?topic=Tomcat
...

In practice, you might want to get a histogram that has been "despidered" and only has faq related views. You can filter out all page view lines associated with spider IPs and filter in only faq lines:

$ grep -v -f /tmp/spider.IPs /home/public/cs601/unix/pageview-20021022.log | \
awk '{print $3;}'| \
grep '/faq' | \
sort | \
uniq -c | \
sort -r -n
1397 /faq/index.jsp
884 /faq/home.jsp?topic=Tomcat
525 /faq/home.jsp?topic=Struts
501 /faq/home.jsp?topic=JSP
423 /faq/home.jsp?topic=EJB
...

If you want to only see despidered faq pages that were referenced more than 500 times, add an awk command to the end.

$ grep -v -f /tmp/spider.IPs /home/public/cs601/unix/pageview-20021022.log | \
awk '{print $3;}'| \
grep '/faq' | \
sort | \
uniq -c | \
sort -r -n | \
awk '{if ($1>500) print $0;}'
1397 /faq/index.jsp
884 /faq/home.jsp?topic=Tomcat
525 /faq/home.jsp?topic=Struts
501 /faq/home.jsp?topic=JSP

Generating Java class hierarchy diagrams

A student asked if I knew of a program that generated class hierarchy diagrams. I said "no", but then realized we don't need one. Here's the one liner to do it:

# pulls out superclass and class as $5 and $3:
# public class A extends B ...
# only works for public classes and usual formatting
cat *.java | grep 'public class' $1 | \
awk 'BEGIN {print "digraph foo {";} {print $5 "->" $3;} END {print "}"}'

It generates DOT format graph files. Try it. It's amazing. Works for most cases. Output looks like:

digraph foo {
antlr.CharScanner->JavaLexer
antlr.LLkParser->Mantra
->TestLexer
}

Generating scripts and programs

I like to automate as much as possible. Sometimes that means writing a program that generates another program or script.

Processing mail files

I wanted to get a sequence of SQL commands that would update our database whenever someone's email bounced. Processing the mail file is pretty easy since you can look for the error code followed by the email address. A bounced email looks like:

From MAILER-DAEMON@localhost.localdomain  Wed Jan  9 17:32:33 2002
Return-Path: <>
Received: from web.jguru.com (web.jguru.com [64.49.216.133])
by localhost.localdomain (8.9.3/8.9.3) with ESMTP id RAA18767
for ; Wed, 9 Jan 2002 17:32:32 -0800
Received: from localhost (localhost)
by web.jguru.com (8.11.6/8.11.6) id g0A1W2o02285;
Wed, 9 Jan 2002 17:32:02 -0800
Date: Wed, 9 Jan 2002 17:32:02 -0800
From: Mail Delivery Subsystem
Message-Id: <200201100132.g0a1w2o02285@web.jguru.com>
To:
MIME-Version: 1.0
Content-Type: multipart/report; report-type=delivery-status;
boundary="g0A1W2o02285.1010626322/web.jguru.com"
Subject: Returned mail: see transcript for details
Auto-Submitted: auto-generated (failure)

This is a MIME-encapsulated message

--g0A1W2o02285.1010626322/web.jguru.com

The original message was received at Wed, 9 Jan 2002 17:32:02 -0800
from localhost [127.0.0.1]

----- The following addresses had permanent fatal errors -----

(reason: 550 Host unknown)

----- Transcript of session follows -----
550 5.1.2 ... Host unknown (Name server: intheneck.com: host not found)
...

Notice the SMTP 550 error message. Look for that at the start of a line then kill the angle brackets, remove the ...and use awk to print out the SQL:

# This script works on one email or a file full of other emails
# since it just looks for the SMTP 550 or 554 results and then
# converts them to SQL commands.
grep -E '^(550|554)' | \
sed 's/[<>]//g' | \
sed 's/\.\.\.//' | \
awk "{printf(\"UPDATE PERSON SET bounce=1 WHERE email='%s';\n\",\$3);}" >> bounces.sql

I have to escape the $3 because it means something to the surround bash shell script and I want awk to see the dollar sign.

Generating getter/setters

#!/bin/bash
# From a type and name (plus firstlettercap version),
# generate a Java getter and setter
#
# Example: getter.setter String name Name
#

TYPE=$1
NAME=$2
UPPER_NAME=$3

echo "public $TYPE get$UPPER_NAME() {"
echo " return $NAME;"
echo "}"
echo
echo "void set$UPPER_NAME($TYPE $NAME) {"
echo " this.$NAME = $NAME;"
echo "}"
echo

Have I been hacked?

Failed logins: /var/log/messages

last, w, uptime

/etc/passwd changed?

fuser for ports

portscans in server report

weird processing hogging CPU?

Redhat configuration (RHEL3, RHEL4, RHEL5)

Redhat configuration : pbraun.nethence.com/doc/sysutils_linux/redhat.html
Daily mail reports with logwatch : pbraun.nethence.com/doc/sysutils/logwatch.html
Log rotation techniques : pbraun.nethence.com/doc/sysutils/log_rotation.html
Redhat/XEN configuration : pbraun.nethence.com/doc/sysutils/xen_redhat.html

Introduction
For RHEL3, RHEL4, RHEL5. We recomment to install a minimal Redhat (only @base) and proceed with other using YUM against a DVD or the network.

Redhat sources : ftp.redhat.com/
CentOS mirrors : mirror-status.centos.org/

Post-install configuration in brief
- disable security level and selinux
- environment
- network configuration
- services
- syslog
- lvm
- additional packages
- sync time
- mail alias
- screen
- file indexation
(-) rhn


Post-install configuration
Disable security level and selinux
On Redhat's first boot,
Security level : disabled
SELinux : disabled
Note. otherwise once system has booted,
system-config-securitylevel-tui

Environment
Remove motd and show hidden files,
cd /etc
cat motd
#mv motd motd.dist
vi bashrc
add,
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:$HOME/bin
LANG=C
export PATH LANG

[[ $USER = root ]] && \
PS1='${HOSTNAME%%.*}# ' \
PS1='${HOSTNAME%%.*}> '

case "$-" in *i*)
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
alias ll='ls -alkF'
alias vi='vim'

who
;;
esac
apply immediately,
source bashrc

No freacking colors,
cd ~/
echo "syn off" >> .vimrc
cat ~/.vimrc

Remove skeletons but bashrc and bash_profile,
cd /etc
mv skel skel.dist
mkdir skel
cp skel.dist/.bashrc skel
cp skel.dist/.bash_profile skel
cp ~/.vimrc skel

Setup default group,
useradd -D -g users
Note. also tweakable in /etc/default/useradd

Network configuration
Configure hostname and gateway,
vi /etc/sysconfig/network
like,
NETWORKING=yes
NETWORKING_IPV6=no
HOSTNAME=host.example.net
GATEWAY=10.1.1.254

Configure IP and netmask,
vi /etc/sysconfig/network-scripts/ifcfg-eth0
like,
DEVICE=eth0
BOOTPROTO=static
IPADDR=10.1.1.1
NETMASK=255.255.255.0
ONBOOT=yes
Note. "BOOTPROTO=static" is checked during Oracle installation
Note. remove HWADDR so you can replace network cards transparently (works best since RHEL5 and maybe on latest RHEL4s, bugs were fixed)
Note. otherwise,
#system-network-config-tui

Apply,
hostname host.example.net
service network restart

Configure file based host name resolution,
vi /etc/hosts
like,
127.0.0.1 localhost.localdomain localhost
#rhel5: ::1 localhost6.localdomain6 localhost6
10.1.1.254 gw.example.net gw
10.1.1.1 host.example.net host

Fix name resolution,
vi /etc/resolv.conf
like,
search example.net
nameserver DNS1_IP
nameserver DNS2_IP


Services
On RHEL3,
service apmd stop
service autofs stop
service cups stop
chkconfig apmd off
chkconfig autofs off
chkconfig cups off

On RHEL4,
service apmd stop
service autofs stop
service cups stop
service acpid stop
service bluetooth stop
service haldaemon stop
service hidd stop
service pcmcia stop

chkconfig apmd off
chkconfig autofs off
chkconfig cups off
chkconfig acpid off
chkconfig bluetooth off
chkconfig haldaemon off
chkconfig hidd off
chkconfig pcmcia off

On RHEL5,
#service acpid stop
service atd stop
service auditd stop
service autofs stop
service avahi-daemon stop
service bluetooth stop
service cups stop
service firstboot stop
#service haldaemon stop
service hidd stop
service pcscd stop
service yum-updatesd stop

#chkconfig acpid off
chkconfig atd off
chkconfig auditd off
chkconfig autofs off
chkconfig avahi-daemon off
chkconfig bluetooth off
chkconfig cups off
chkconfig firstboot off
#chkconfig haldaemon off
chkconfig hidd off
chkconfig pcscd off
chkconfig yum-updatesd off

Note. if xen domU,
#chkconfig microcode_ctl off
Note. if Compaq Smart Array (cciss),
#chkconfig smartd off
Note. if using serial console only, no PC console
#chkconfig gpm off

Syslog
Send all the system logs in one single file,
cd /etc
mv syslog.conf syslog.conf.dist
vi syslog.conf
like,
*.* -/var/log/messages
apply,
service syslog restart

Fix perms,
chown root:wheel /var/log/messages
chmod 640 /var/log/messages

LVM
Exclude CDrom from LVM,
cd /etc/lvm
cp lvm.conf lvm.conf.dist
vi lvm.conf
change the filter directive to,
filter = [ "r/dev/cdrom" ]
Note. if you've got SAN you might aslo want to exclude sd* and let LVM handle only dm-0

Additional packages
Configure your YUM repository and make sure you've got those installed,
rpm -q \
sendmail \
man \
man-pages \
xorg-x11-xauth \
screen \
wget \
lynx \
lftp \
ntp \
vsftpd \
vim-enhanced \
cvs \
grep ^package
#rhel4 & rhel5 : mc
#rhel5 : mlocate
#rhel4 : slocate
#rhel3: XFree86-xauth
eventually,
#rpm-build
#rpm-devel
#gallery2-imagemagick or ImageMagick

Screen
Configure,
cd /etc
mv screenrc screenrc.dist
vi screenrc
like,
startup_message off
caption always "%-Lw%{= BW}%50>%n%f* %t%{-}%+Lw%< %{=b BW} %H %{-} %l %c %d/%m/%Y" bindkey ^[, prev bindkey ^[; next shelltitle "" autodetach on defscrollback 65000 then user specifics, cd ~/ vi .screenrc like, screen -t "log" 0 tail -F /var/log/messages and launch, cd ~/ screen Sync time cd /etc mv ntp.conf ntp.conf.dist #sed '/^#/d; /^$/d;' ntp.conf.dist > ntp.conf
vi ntp.conf
like,
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery
restrict 127.0.0.1
restrict -6 ::1
server ntp.obspm.fr
driftfile /var/lib/ntp/drift
keys /etc/ntp/keys
apply,
service ntpd start
chkconfig ntpd on

Otherwise,
#ntpdate -u ntp.obspm.fr
or even simply,
#date -s 20091020
#date -s 09:24

Mail alias
Configure the root and wheel users aliases,
cd /etc
vi aliases
change,
root: yourmail@example.net
check for MX and apply,
host -t mx example.net
newaliases

File indexation
Update the mlocate database,
updatedb

RHN
Register to the Redhat network,
rhn_register


Advanced configuration
FTP server
Enable vsftpd,
rpm -q vsftpd
service vsftpd start
chkconfig vsftpd on
Note. /etc/skel was configured previously

You can now create FTP users


Miscellaneous
Prevent ctrl-alt-suppr from restarting the box,
vi /etc/inittab
comment that line,
#ca::ctrlaltdel:/sbin/shutdown -t3 -r now

To change language's locale,
vi /etc/sysconfig/i18n

To get everything through serial console, configure GRUB and inittab.
Ref. www.faqs.org/docs/pocket_linux/x1252.html


Advanced network configuration
Check network interfaces negociation & link,
ethtool eth0 grep Link

To force network interface's bandwidth,
ethtool -s eth0 speed 1000 duplex full autoneg off
And apply it permanently,
vi /etc/sysconfig/network-scripts/ifcfg-eth0
for example,
ETHTOOL_OPTS="speed 1000 duplex full autoneg off"

As for static routes,
vi /etc/sysconfig/static-routes
or
vi /etc/sysconfig/network-scripts/route-ethX
e.g.,
GATEWAY0=10.10.0.1
NETMASK0=255.0.0.0
ADDRESS0=10.0.0.0

GATEWAY1=10.2.0.1
NETMASK1=255.255.0.0
ADDRESS1=192.168.0.0

Refs.
web.mit.edu/rhel-doc/5/RHEL-5-manual/Deployment_Guide-en-US/pt-network-related-config.html
kbase.redhat.com/faq/FAQ_79_2561.shtm


RHEL installation numbers
They're supposed to simplify deployments in environments with different subscriptions. However, it's just a pain for non supported Redhats. Here are a few working install numbers as a workaround,
Client,
0000000e0017fc01
Server,
000000e90007fc00
Server with Cluster,
00000065000bfc00
Server with ClusterStorage,
000000ab000ffc00
Server with HPC,
000000e30013fc00
Server with Directory,
000000890017fc00
Server with SMB,
00000052001bfc00
Ref. linuxczar.net/moin/RHEL_Instaltion_Numbers
Ref. www.redhat.com/support/resources/faqs/installation_numbers/


Huge memory
RHEL4 had the hugemem kernel but it wasn't recommended to use it even though you had 64Go+ of RAM. Today RHEL5 is fine with default kernel, althouth HP says it runs with max 64Go in its OS compatibility table.


Comparison & critics
- how to fix it afterwards if a fake/temporary install number has been given during installation ?
- the useless "complete log install.log" warning during install
- initrd shouldn't exist. At least the disk drivers should be included into the bare kernel.
- when updating httpd with "yum update", files that were intentionally removed come back, like,
/etc/httpd/conf.d/welcome.conf
Note. this may unfortunately happen with other updates.
- should be english only, no translations. for example, lynx keyboard interaction stays english while the messages are in french. Spooky.
- logwatch sucks compared to custom scripts
- logrotate sucks compared to newsyslog
- RHEL vs Centos: silly constrain about the CDs


References
www.redhat.com/docs/manuals/enterprise/
web.mit.edu/rhel-doc/5/RHEL-5-manual/Deployment_Guide-en-US/
mirror.centos.org/centos/4/os/i386/NOTES/RELEASE-NOTES-U5-fr.html
Init scripts lock files : www.redhat.com/magazine/008jun05/departments/tips_tricks/

Building Screen GNU in Solaris 10

A slightly cleaner patch would be the following, although I am not sure whether the default for setenv() shouldn't be the version with three arguments.

--- misc.c Fri April 28 18:37:29 2010
***************

      • 613,619 ****

*/
# endif /* NEEDSETENV */
#else /* USESETENV */
! # if defined(linux) || defined(_convex_) || (BSD >= 199103)
setenv(var, value, 1);
# else
setenv(var, value);
--- 613,619 ----
*/
# endif /* NEEDSETENV */
#else /* USESETENV */
! # if defined(linux) || defined(_convex_) || (BSD >= 199103) || defined(_sun_)
setenv(var, value, 1);
# else
setenv(var, value);

screen lets you keep multiple (virtual) terminals open in one terminal window, and keeps them open in local session, even if you log out from your remote-session. (Yes, this sounds incomprehensible, but it is really handy!)

  wget ftp://ftp.sunfreeware.com/pub/freeware/SOURCES/screen-4.0.2.tar.gz
tar zxvf screen-4.0.2.tar.gz
cd screen-4.0.2
./configure --prefix=$PKGROOT/screen/4.0.2 \
--enable-colors256 \
--with-sys-screenrc=$ETCROOT/screenrc
make
make install
cp etc/etcscreenrc $ETCROOT/screenrc
cd $PKGROOT/screen
ln -s 4.0.2/ current
I ignored the final note that make install gave: 'termcap entry (./terminfo/screencap) should be installed manually.'


Setting up cronjobs in Unix and Linux

What is crontab?

cron is a unix, solaris utility that allows tasks to be automatically run in the background at regular intervals by the cron daemon.

linux_crontab_syntax.gif

These tasks are often termed as cron jobs in unix , solaris.
Crontab (CRON TABle) is a file which contains the schedule of cron entries to be run and at specified times.


Crontab Restrictions

You can execute crontab if your name appears in the file /usr/lib/cron/cron.allow. If that file does not exist, you can use
crontab if your name does not appear in the file /usr/lib/cron/cron.deny.
If only cron.deny exists and is empty, all users can use crontab.
If neither file exists, only the root user can use crontab. The allow/deny files consist of one user name per line.

Crontab Location

Where is it stored?

It will be stored /var/spool/cron/ but we only root has permission for those directories

Crontab Commands

export EDITOR=vi ;to specify a editor to open crontab file.

crontab -e Edit your crontab file, or create one if it doesn’t already exist.
crontab -l Display your crontab file.
crontab -r Remove your crontab file.
crontab -v Display the last time you edited your crontab file. (This option is only available on a few systems.)

Crontab file

Crontab syntax :-
A crontab file has five fields for specifying day , date and time followed by the command to be run at that interval.
* * * * * command to be executed
- – – – -
‘ ‘ ‘ ‘ ‘
‘ ‘ ‘ ‘ +—– day of week (0 – 6) (Sunday=0)
‘ ‘ ‘ +——- month (1 – 12)
‘ ‘ +——— day of month (1 – 31)
‘ +———– hour (0 – 23)
+————- min (0 – 59)

* in the value field above means all legal values as in braces for that column.
The value column can have a * or a list of elements separated by commas. An element is either a number in the ranges shown above or two numbers in the range separated by a hyphen (meaning an inclusive range).

Note: The specification of days can be made in two fields: month day and weekday. If both are specified in an entry, they are cumulative meaning both of the entries will get executed .

How to Modify Crontab file?

*

crontab -e

This will open the crontab file and let you edit it. By default this file will be opened with the VI editor and you will need to press the “Insert” key on your keyboard to be able to write in that file.
*

30 13 * * * /home/your_username/run-me.sh >/dev/null 2>&1

The first character you see is “30” this means that crontab will run the script every time the clock hits the 30 minutes mark. Next “13” this means that crontab will run the script when the clock hits 13. The next three * tell crontab to run the script every day, of every month of every weekday. Combining these fields crontab will run the script every day at exactly 13:30. You may notice that we added the “>/dev/null 2>&1” string at the end of the command. The default cron job will always send and e-mail to the root account when ever a command is executed. Now you don’t want to be notified every day that your crontab job has been executed. If you don’t want to receive e-mails every day notifying you about your job’s execution place this “>/dev/null 2>&1” at the end of every instance of every crontab command.

When you are finished adding your commands to the crontab file you need to save and exit. If you are using VI as your editor you need to issue the following commands:

*

Press the Esc (Escape key) on your keyboard to enter the command mode of VI
*

After you pressed Escape then type the following characters :wq! and press Enter. Remember you have to type this characters (remove the quotes): “:wq!”.

linux_crontab_colorful.png

Crontab Example

#A line in crontab file like below removes the tmp files from /home/someuser/tmp each day at 6:30 PM.
30 18 * * * rm /home/someuser/tmp/*
#This runs every fifteen minutes
*/15 * * * * /notesbit/work/scripts/crons/denyhack1 > /dev/null 2>&1
*/20 * * * * /notesbit/work/scripts/crons/denyhack2 > /dev/null 2>&1
#This runs every twenty five minutes
*/25 * * * * /notesbit/work/scripts/crons/denyhack3 > /dev/null 2>&1
*/35 * * * * /notesbit/work/scripts/crons/denyhack4 > /dev/null 2>&1
# This runs every day at 2:14 PM
08 14 * * * /root/work/scripts/crons/stkinc NUAN > /dev/null 2>&1

Crontab Example 1: This crontab example runs updatedb command 35 minutes past every hour.

35 * * * * updatedb

Crontab Example 2: This crontab example runs /usr/local/bin/diskusage.sh every 5 minutes (e.g. 0, 5, 10, 15, …).

*/5 * * * * /usr/local/bin/diskusage.sh

Crontab Example 3: This crontab example runs /usr/local/bin/diskusage.sh at 1:25 AM, 1:50 AM every Tuesday and on 15th of every month.

25,50 1 15 * 2 /usr/local/bin/diskusage.sh

Crontab Example 4: This crontab example runs /usr/local/bin/diskusage.sh at 2:00 PM on 10th of March, June, September and December.

00 14 10 3,6,9,12 * /usr/local/bin/diskusage.sh

Crontab Example 5: This crontab example runs ‘/usr/local/bin/diskusage.sh user@linuxconfig.sh’ at 9.00 PM every Monday, Wednesday, Friday. Note: Using names for the week day and months is extension in some versions of crontab.

00 21 * * Mon,Wed,Fri /usr/local/bin/diskusage.sh user@linuxconfig.sh

Crontab Example 6: This crontab example runs /usr/local/bin/diskusage.sh every 5 minutes during the 5 working days (Monday – Friday), every week and month.

*/5 * * * 1-5 /usr/local/bin/diskusage.sh

Crontab Example 7: This crontab example runs /usr/local/bin/diskusage.sh every minute during the 4-th hour only in Sunday, every week and month. This is every minute from 0:00 till 0:59, then from 4:00 till 4:59, etc.

* */4 * * sun /usr/local/bin/diskusage.sh

3. System wide cron scheduler
As a Linux administrator you can also use predefined cron directories:

/etc/cron.d /etc/cron.daily /etc/cron.hourly /etc/cron.monthly /etc/cron.weekly

If root wishes to run backup.sh script once a week he will place backup.sh script into /etc/cron.weekly directory.
4. Cron Scheduler on user level
Every user can edit, view or remove his own crontab file. If the root user needs to change someone else’s crontab file he must add ‘-u’ option to specify the user name. To edit crontab file for user foobar we can use command:

# crontab -u foobar -e

Remove foobar’s crontab file:

# crontab -u foobar -r

To view foobar’s crontab content:

# crontab -u foobar -l

Crontab Environment

cron invokes the command from the user’s HOME directory with the shell, (/usr/bin/sh).
cron supplies a default environment for every shell, defining:
HOME=user’s-home-directory
LOGNAME=user’s-login-id
PATH=/usr/bin:/usr/sbin:.
SHELL=/usr/bin/sh

Users who desire to have their .profile executed must explicitly do so in the crontab entry or in a script called by the entry

Reference & source: http://www.linuxconfig.org

What is crontab?

cron is a unix, solaris utility that allows tasks to be automatically run in the background at regular intervals by the cron daemon.

linux_crontab_syntax.gif

These tasks are often termed as cron jobs in unix , solaris.
Crontab (CRON TABle) is a file which contains the schedule of cron entries to be run and at specified times.

Crontab Restrictions

You can execute crontab if your name appears in the file /usr/lib/cron/cron.allow. If that file does not exist, you can use
crontab if your name does not appear in the file /usr/lib/cron/cron.deny.
If only cron.deny exists and is empty, all users can use crontab.
If neither file exists, only the root user can use crontab. The allow/deny files consist of one user name per line.

Crontab Location

Where is it stored?

It will be stored /var/spool/cron/ but we only root has permission for those directories

Crontab Commands

export EDITOR=vi ;to specify a editor to open crontab file.

crontab -e Edit your crontab file, or create one if it doesn’t already exist.
crontab -l Display your crontab file.
crontab -r Remove your crontab file.
crontab -v Display the last time you edited your crontab file. (This option is only available on a few systems.)

Crontab file

Crontab syntax :-
A crontab file has five fields for specifying day , date and time followed by the command to be run at that interval.
* * * * * command to be executed
- – – – -
‘ ‘ ‘ ‘ ‘
‘ ‘ ‘ ‘ +—– day of week (0 – 6) (Sunday=0)
‘ ‘ ‘ +——- month (1 – 12)
‘ ‘ +——— day of month (1 – 31)
‘ +———– hour (0 – 23)
+————- min (0 – 59)

* in the value field above means all legal values as in braces for that column.
The value column can have a * or a list of elements separated by commas. An element is either a number in the ranges shown above or two numbers in the range separated by a hyphen (meaning an inclusive range).

Note: The specification of days can be made in two fields: month day and weekday. If both are specified in an entry, they are cumulative meaning both of the entries will get executed .

How to Modify Crontab file?

*

crontab -e

This will open the crontab file and let you edit it. By default this file will be opened with the VI editor and you will need to press the “Insert” key on your keyboard to be able to write in that file.
*

30 13 * * * /home/your_username/run-me.sh >/dev/null 2>&1

The first character you see is “30” this means that crontab will run the script every time the clock hits the 30 minutes mark. Next “13” this means that crontab will run the script when the clock hits 13. The next three * tell crontab to run the script every day, of every month of every weekday. Combining these fields crontab will run the script every day at exactly 13:30. You may notice that we added the “>/dev/null 2>&1” string at the end of the command. The default cron job will always send and e-mail to the root account when ever a command is executed. Now you don’t want to be notified every day that your crontab job has been executed. If you don’t want to receive e-mails every day notifying you about your job’s execution place this “>/dev/null 2>&1” at the end of every instance of every crontab command.

When you are finished adding your commands to the crontab file you need to save and exit. If you are using VI as your editor you need to issue the following commands:

*

Press the Esc (Escape key) on your keyboard to enter the command mode of VI
*

After you pressed Escape then type the following characters :wq! and press Enter. Remember you have to type this characters (remove the quotes): “:wq!”.

linux_crontab_colorful.png

Crontab Example

#A line in crontab file like below removes the tmp files from /home/someuser/tmp each day at 6:30 PM.
30 18 * * * rm /home/someuser/tmp/*
#This runs every fifteen minutes
*/15 * * * * /notesbit/work/scripts/crons/denyhack1 > /dev/null 2>&1
*/20 * * * * /notesbit/work/scripts/crons/denyhack2 > /dev/null 2>&1
#This runs every twenty five minutes
*/25 * * * * /notesbit/work/scripts/crons/denyhack3 > /dev/null 2>&1
*/35 * * * * /notesbit/work/scripts/crons/denyhack4 > /dev/null 2>&1
# This runs every day at 2:14 PM
08 14 * * * /root/work/scripts/crons/stkinc NUAN > /dev/null 2>&1

Crontab Example 1: This crontab example runs updatedb command 35 minutes past every hour.

35 * * * * updatedb

Crontab Example 2: This crontab example runs /usr/local/bin/diskusage.sh every 5 minutes (e.g. 0, 5, 10, 15, …).

*/5 * * * * /usr/local/bin/diskusage.sh

Crontab Example 3: This crontab example runs /usr/local/bin/diskusage.sh at 1:25 AM, 1:50 AM every Tuesday and on 15th of every month.

25,50 1 15 * 2 /usr/local/bin/diskusage.sh

Crontab Example 4: This crontab example runs /usr/local/bin/diskusage.sh at 2:00 PM on 10th of March, June, September and December.

00 14 10 3,6,9,12 * /usr/local/bin/diskusage.sh

Crontab Example 5: This crontab example runs ‘/usr/local/bin/diskusage.sh user@linuxconfig.sh’ at 9.00 PM every Monday, Wednesday, Friday. Note: Using names for the week day and months is extension in some versions of crontab.

00 21 * * Mon,Wed,Fri /usr/local/bin/diskusage.sh user@linuxconfig.sh

Crontab Example 6: This crontab example runs /usr/local/bin/diskusage.sh every 5 minutes during the 5 working days (Monday – Friday), every week and month.

*/5 * * * 1-5 /usr/local/bin/diskusage.sh

Crontab Example 7: This crontab example runs /usr/local/bin/diskusage.sh every minute during the 4-th hour only in Sunday, every week and month. This is every minute from 0:00 till 0:59, then from 4:00 till 4:59, etc.

* */4 * * sun /usr/local/bin/diskusage.sh

3. System wide cron scheduler
As a Linux administrator you can also use predefined cron directories:

/etc/cron.d /etc/cron.daily /etc/cron.hourly /etc/cron.monthly /etc/cron.weekly

If root wishes to run backup.sh script once a week he will place backup.sh script into /etc/cron.weekly directory.
4. Cron Scheduler on user level
Every user can edit, view or remove his own crontab file. If the root user needs to change someone else’s crontab file he must add ‘-u’ option to specify the user name. To edit crontab file for user foobar we can use command:

# crontab -u foobar -e

Remove foobar’s crontab file:

# crontab -u foobar -r

To view foobar’s crontab content:

# crontab -u foobar -l

Crontab Environment

cron invokes the command from the user’s HOME directory with the shell, (/usr/bin/sh).
cron supplies a default environment for every shell, defining:
HOME=user’s-home-directory
LOGNAME=user’s-login-id
PATH=/usr/bin:/usr/sbin:.
SHELL=/usr/bin/sh

Users who desire to have their .profile executed must explicitly do so in the crontab entry or in a script called by the entry

Reference & source: http://www.linuxconfig.org

VMware Unidentified Network Issue FIX

VMware Unidentified Network Issue in Vista and Windows Server 2008 Fix

There is however, a very annoying problem when you install VMware on Vista (and Windows Server 2008). When you install VMware it adds a few virtual network adapters. For various reasons, these adapters are listed in the Network Sharing Center as being on an “Unidentified network (Public network)” and all of the features under Sharing and Discovery are turned off .

Here is the best fix I’ve found thanks to a post by richv in the VMware forum:

  1. Run regedit
  2. Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}
  3. Underneath you should see several keys labeled 0000, 0001, 0002 etc… Look through these and find the VMware adapters. They will probably be near the end of the list if you just installed VMware.
  4. For each of the VWware adapters, add a new DWORD value named “*NdisDeviceType” and set it to 1 (make sure you get the * at the beginning of the name, I missed that the first time).
  5. Disable and Enable each of the network adapters.

That should take care of the problem. Setting *NdisDeviceType to 1 causes Windows to ignore the device when it does network identification. Here is an MSDN article with more details.

Top 10 Tips and Tricks for Making Your Stuff  Last Longer

We live in a disposable world, but just because things weren't meant to last doesn't mean you can't make them last. These 10 tips and tricks will help you squeeze more life from your batteries, appliances, flowers, razor blades, and more.

Photo by smplyme84.

10. Get More Life from Your Appliances

Top 10 Tips and Tricks for Making Your Stuff  Last Longer

If you're lucky, a good appliance can last you for years and years. If not, you'll be making those not-so-fun-but-very-expensive purchases way more regularly than you care to. Increase your chances of keeping those appliances around longer by knowing how to properly care for them. We've highlighted tips for proper refrigerator care and vacuum maintenance, and did you know that washing the lint filter in your dryer (not just cleaning it out) will increase its life? Photo by swanksalot. (Original posts: Refrigerator, vacuum cleaner, clothes dryer)

9. Extend the Life of Your Fresh Cut Flowers

Top 10 Tips and Tricks for Making Your Stuff  Last Longer

Fresh flowers are a tough buy: They look great and add all kinds of life to a room, but they can also die extremely quickly. With the right water solution (think parts sugar, bleach, and citrus), your fresh cut flowers can last a lot longer. Photo by amiefedora.

8. Make Your Clothes Last Longer

Top 10 Tips and Tricks for Making Your Stuff  Last Longer

Your clothes are way too expensive to be disposable, and besides—that favorite t-shirt isn't going to keep holes out of itself after its thousandth wash. Personal finance blog Wisebread rounds up a ton of tips for making your clothes last longer, including washing everything in cold water. In addition to your clothes lasting longer, you'll also save a ton on your energy bills. Photo by jon_a_ross. (Original post)

7. Keep Food Better for Longer

Top 10 Tips and Tricks for Making Your Stuff  Last Longer

Good food, by its very nature, expires, but with a few smart tricks you can help it last a good deal longer. Apart from obvious stuff, like storing food in air-tight containers or refrigerating it when applicable, you can also keep certain foods better for longer with clever tricks. For example, apples can extend the shelf life of cake, herbs last longer if you treat them like flowers, and hard cheese lasts longer if wrapped loosely in parchment paper. (Original posts: Cake, herbs, cheese)

6. Stretch the Life of Your Laptop Battery

Top 10 Tips and Tricks for Making Your Stuff  Last Longer

If you're not looking to entirely resurrect your batteries but just want to improve how long your laptop lasts between charges, you've got all kinds of options. Windows 7 users can try previously mentioned Aerofoil to disable Aero graphics and other battery-sucking features when you unplug, and you can always stick the the simple tried-and-true methods like powering down your display's brightness, turning off unused devices (like BlueTooth), and disabling all those startup items. It's also a good idea to occasionally calibrate your battery, and if you're unsure whether or not it's better for your battery to keep your laptop plugged in, just remember: When in doubt, unplug your laptop regularly. Photo by candescent.

5. Run Windows 7 Longer Without Activation

Top 10 Tips and Tricks for Making Your Stuff  Last Longer

Windows 7 is already insanely popular considering how new it is and how slow users were to upgrade to Vista, but if you're taking Windows 7 for a test spin and aren't quite sure you're ready to pony up for a license, you can extend Windows 7's activation period by 120 days (that's four whole months) using the same rearm code that worked with Vista. (Original post)

4. Extend the Usefulness of Your Old MP3 Player

Top 10 Tips and Tricks for Making Your Stuff  Last Longer

Face facts: That old MP3 player served you really well, but time is a bitter mistress, and it's not looking quite as shiny as it once did. If it's an iPod, take a look at our top 10 ways to repurpose your old iPod. My favorite hack, whether it's an iPod or not: Breathe new life into your aging MP3 player with the open-source MP3 player firmware, Rockbox.

3. Revive Dead Batteries, Hard Drives in Freezer

Top 10 Tips and Tricks for Making Your Stuff  Last Longer

Batteries increasingly power our portable gadgets, and while many these days are rechargeable, disposable batteries can cost a pretty penny over time. Storing the right kinds of batteries in the freezer can make them last longer, and even if your laptop battery goes completely dead, a little time in the freezer can revive it for at least a little bit. In fact, you can revive a dead hard drive in the freezer. Photo by scalespeeder. (Original posts: Batteries in the freezer, Revive dead laptop battery)

2. Seriously Extend the Life of Your Razor Blades

Disposable razor blades represents every business person's dream business model: The razor itself sells for cheap, but the blades—which you need to regularly refill—cost an arm and a leg. Turns out, however, that you can do a whole lot to make those blades last longer. Next time your blade's getting dull, try rubbing it backwards across your skin or a pair of jeans, and for regular upkeep, remember to keep it dry or store it in mineral oil. Our own Jason Fitzpatrick had all kinds of luck with mineral oil and wet shaving. (Original posts: Dry blades, Mineral oil)

1. Keep Your Cellphone Battery Trucking All Day Long and Then Some

Top 10 Tips and Tricks for Making Your Stuff  Last Longer

You rely on your cellphone to stay connected no matter where you are, but if the battery dies, it's not really doing its job. Our exhaustive guide to saving your smartphone's battery life will get you started with tons of methods for making your cellphone battery last longer between charges—like keeping your cellphone outside your pocket and away from extra heat. If you're really serious about getting a cellphone that lasts longer, you may even want to consider changing networks. Photo by [177]. (Original posts: Belt-clip cellphone, Choose the right network)

top