Tuesday, 5 February 2013

Fun with Find Command

Find a file and delete it. Replace foo.bar with the file or use wild cards *.bar
  $ find /home -name foo.bar -type f -exec rm -f "{}" ';'

When trying to find large files in / filesytem the find command will return results from other files systems. Try using the -dev option.
  $ find / -dev -size +3000 -exec ls -l {} ;
       
This will not return files in /usr/local file system. This will return files large then 3000 blocks only in the root file system.
  $ find /usr -dev -size +5000 -exec ls -l {} ;

Someone's done a 'cp -r' and filled up the filesystem. Here's a simple way to locate the unwanted files...
  $ find . -ctime -1 -print
   
Find has a partiularly powerful mechanism, -exec, which lets you execute commands on a per-file basis, while being selective about the files you're operating on. Lets say we want to delete all the *.bak or *.backup files which are older than 30 days. Type the following all on 1 line.
  $ find . ( -name '*.bak' -o -name *.backup ) -type f -atime +30 -exec rm '{}' ;

It would be even better if we only deleted the *.bak file if the original file was still available. In this case, we can use csh and test to help. Type the following all on 1 line.
  $ find . ( -name '*.bak' -o -name *.backup ) -type f -atime +30 -exec csh -c 'if ( -f $1:r ) rm $1' '{}' ;

or if you're really paraniod, use 'test -s' to verify that the original file has not been truncated. Type the following all on 1 line.
  $ find . -name '*.bak' -type f -atime +30 -exec csh -c 'test -s $1:r && rm $1' '{}' ;
        
Protecting users from themselves - file permissions
  $ find . -type l -exec gawk 'BEGIN { "ls -lag}' /dev/null ;

Find text in whole directory tree:
  $ find . -type f | xargs grep "text"

Find and Replace in whole directory tree:
  $ find . -type f [-name "..."] -exec perl -pi -e 's|xxx|yyy|g' {} ;
 

Files named filename.suffix
  $ find . -type f -exec grep -ls nohup.out {} \;
 
Greater than or equal to 100KB
  $ find . -size +100k -exec ls -l {} \; | awk '{printf $9, $5}'
 
Greater than or equal to 100KB. Sort the output numerically
  $ find . -size +100k -exec ls -l {} \; | awk '{printf "%40s %10s \n", $9, $5}' | sort -n +1
 
Changed in the last 7 hours
  $ find / -ctime -7 -print

Modified in the last 7 hours
  $ find / -daystart -mtime -7 -print
 
Files of type Directory
  $ find . -type d -print
 
Owned by user username
  $ find / -user jdoe -print 2>/dev/null

Owned by userid number
  $ find / -uid 227 -print 2>/dev/null
 
Prompt user before removing a file
  $ find / -name nohup.out -ok rm {} \;
 
Case insensitive search
  $ find . -iname -print
 
Find files under current directory named string.scr or string.prt
  $ find . \( -name "*.scr" -o -name "*.rpt" \) -print
 
Find core files. Prompt user for deletion
  $ find / -name core -ok rm {} \;

Files that end with 'log'
  $ find / -print 2>/dev/null | grep log\$

Files that start with 'law'
  $ find / -print 2>/dev/null | grep \^law
 
Files changed within the last hour
  $ find . -ctime -1 -exec ls -l {} \; 2>/dev/null
 
Files not changed within the last year. Prompt user for deletion
  $ find . -ctime +$(print $((365*20))) -exec ls -l {} \; -ok rm {} \;
 
Symbolic links
  $ find . -type -l -print
  $ find . -type -l -exec ls -l {} \;
 
Files older than 30 days
  $ cd /var/backup/logs; find . -daystart -mtime +30 -print
 
Files older than 30 days. Remove.
  $ find . -daystart -mtime +30 -print -exec rm {} \;
 
Files older than 30 days. Prompt for removal.
  $ find . -daystart -mtime +30 -print -ok rm {} \;

Edit all files that contain string
  $ vi `find . -name string -print 2>/dev/null`
  $ find . -name "1000318*" | xargs -n 10 rm


Changed in the last 20 hours, greater than 1MB in size, excluding some file systems
  $ find . -ctime -20 -size +1000k -print | grep -v \/usr | grep -v \/var | grep -v \/ora

awk one liner

Print column1, column5 and column7 of a data file or output of any columns list

awk '{print $1, $5, $7}' data_file

cat file_name |awk '{print $1 $5 $7}'

ls –al |awk '{print $1, $5, $7}' -- Prints file_permissions,size and date

List all files names whose file size greater than zero.

ls –al |awk '$5 > 0 {print $9}'

List all files whose file size equal to 512bytes.

ls –al |awk '$5 == 512 {print $9}'

print all lines

awk '{print }' file_name

awk '{print 0}' file_name

Number of lines in a file

awk ' END {print NR}' file_name

Number of columns in each row of a file

awk '{print NF}' file_name

Sort the output of file and eliminate duplicate rows

awk '{print $1, $5, $7}' |sort –u

List all file names whose file size is greater than 512bytes and owner is “oracle”

ls –al |awk '$3 == "oracle" && $5 > 512 {print $9}'

List all file names whose owner could be either “oracle” or “root”

ls –al |awk '$3 == "oracle" || $3 == "root" {print $9}'
Print column1, column5 and column7 of a data file or output of any columns list

awk '{print $1, $5, $7}' data_file

cat file_name |awk '{print $1 $5 $7}'

ls –al |awk '{print $1, $5, $7}' -- Prints file_permissions,size and date

List all files names whose file size greater than zero.

ls –al |awk '$5 > 0 {print $9}'

List all files whose file size equal to 512bytes.

ls –al |awk '$5 == 512 {print $9}'

print all lines

awk '{print }' file_name

awk '{print 0}' file_name

Number of lines in a file

awk ' END {print NR}' file_name

Number of columns in each row of a file

awk '{print NF}' file_name

Sort the output of file and eliminate duplicate rows

list all the files whose owner is not “oracle

ls –al |awk '$3 != "oracle" {print $9}'

List all lines which has at least one or more characters

awk 'NF > 0 {print }' file_name

List all lines longer that 50 characters

awk 'length($0) > 50 {print }' file_name

List first two columns

awk '{print $1, $2}' file_name

Swap first two columns of a file and print

awk '{temp = $1; $1 = $2; $2 = temp; print }' file_name

Replace first column as “ORACLE” in a data file

awk '{$1 = "ORACLE"; print }' data_file

Remove first column values in a data file

awk '{$1 =""; print }' data_file

Calculate total size of a directory in Mb

ls –al |awk '{total +=$5};END {print "Total size: " total/1024/1024 " Mb"}'

Calculate total size of a directory including sub directories in Mb

ls –lR |awk '{total +=$5};END {print "Total size: " total/1024/1024 " Mb"}'

Find largest file in a directory including sub directories

ls –lR |awk '{print $5 "\t" $9}' |sort –n |tail -1
Share this:

    * StumbleUpon
    * Facebook
    * Email
    * Digg
    * Reddit
    * Twitter
*

awk for apache log


One thing I've never seen anyone else do, for reasons that I can't imagine, is to change the Apache log file format to a more easily parseable version with the information that actually matters to you.

For example, we never use HTTP basic auth, so we don't need to log those fields. I am interested in how long each request takes to serve, so we'll add that in. For one project, we also want to know (on our load balancer) if any servers are serving requests slower than others, so we log the name of the server we're proxying back to.

Here's an excerpt from one server's apache config:
# We don't want to log bots, they're our friends
BrowserMatch Pingdom.com robot

# Custom log format, for testing
#
#         date          proto   ipaddr  status  time    req     referer         user-agent
LogFormat "%{%F %T}t    %p      %a      %>s     %D      %r      %{Referer}i     %{User-agent}i" standard
CustomLog /var/log/apache2/access.log standard env=!robot

What you can't really tell from this is that between each field is a literal tab character (\t). This means that if I want to do some analysis in Python, maybe show non-200 statuses for example, I can do this:

for line in file("access.log"):
  line = line.split("\t")
  if line[3] != "200":
    print line

Or if I wanted to do 'who is hotlinking images?' it would be

if line[6] in ("","-") and "/images" in line[5]:

For IP counts in an access log, the previous example:

cat log | grep -o "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" | sort -n | uniq -c | sort -n

becomes something like this:

cat log | cut -d '\t' -f 3 | uniq -c | sort -n

Easier to read and understand, and far less computationally expensive (no regex) which, on 9 GB logs, makes a huge difference in how long it takes. When this gets REALLY neat is if you want to do the same thing for User-agents. If your logs are space-delimited, you have to do some regular expression matching or string searching by hand. With this format, it's simple:

cat log | cut -d '\t' -f 8 | uniq -c | sort -n

Exactly the same as the above. In fact, any summary you want to do is essentially exactly the same.

Why on earth would I spend my system's CPU on awk and grep when cut will do exactly what I want orders of magnitude faster?


How do I use awk pattern scanning and processing language under bash scripts? Can you provide a few examples?

One thing I've never seen anyone else do, for reasons that I can't imagine, is to change the Apache log file format to a more easily parseable version with the information that actually matters to you.

For example, we never use HTTP basic auth, so we don't need to log those fields. I am interested in how long each request takes to serve, so we'll add that in. For one project, we also want to know (on our load balancer) if any servers are serving requests slower than others, so we log the name of the server we're proxying back to.

Here's an excerpt from one server's apache config:
# We don't want to log bots, they're our friends
BrowserMatch Pingdom.com robot

# Custom log format, for testing
#
#         date          proto   ipaddr  status  time    req     referer         user-agent
LogFormat "%{%F %T}t    %p      %a      %>s     %D      %r      %{Referer}i     %{User-agent}i" standard
CustomLog /var/log/apache2/access.log standard env=!robot

What you can't really tell from this is that between each field is a literal tab character (\t). This means that if I want to do some analysis in Python, maybe show non-200 statuses for example, I can do this:

for line in file("access.log"):
  line = line.split("\t")
  if line[3] != "200":
    print line

Or if I wanted to do 'who is hotlinking images?' it would be

if line[6] in ("","-") and "/images" in line[5]:

For IP counts in an access log, the previous example:

cat log | grep -o "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" | sort -n | uniq -c | sort -n

becomes something like this:

cat log | cut -d '\t' -f 3 | uniq -c | sort -n

Easier to read and understand, and far less computationally expensive (no regex) which, on 9 GB logs, makes a huge difference in how long it takes. When this gets REALLY neat is if you want to do the same thin
Awk is an excellent tool for building UNIX/Linux shell scripts. AWK is a programming language that is designed for processing text-based data, either in files or data streams, or using shell pipes. In other words you can combine awk with shell scripts or directly use at a shell prompt.
Print a Text File

awk '{ print }' /etc/passwd
OR
awk '{ print $0 }' /etc/passwd
Print Specific Field

Use : as the input field separator and print first field only i.e. usernames (will print the the first field. all other fields are ignored):
awk -F':' '{ print $1 }' /etc/passwd
Send output to sort command using a shell pipe:
awk -F':' '{ print $1 }' /etc/passwd | sort
Pattern Matching

You can only print line of the file if pattern matched. For e.g. display all lines from Apache log file if HTTP error code is 500 (9th field logs status error code for each http request):
awk '$9 == 500 { print $0}' /var/log/httpd/access.log
The part outside the curly braces is called the "pattern", and the part inside is the "action". The comparison operators include the ones from C:

== != < > <= >= ?:

If no pattern is given, then the action applies to all lines. If no action is given, then the entire line is printed. If "print" is used all by itself, the entire line is printed. Thus, the following are equivalent:
awk '$9 == 500 ' /var/log/httpd/access.log
awk '$9 == 500 {print} ' /var/log/httpd/access.log
awk '$9 == 500 {print $0} ' /var/log/httpd/access.log
Print Lines Containing tom, jerry AND vivek

Print pattern possibly on separate lines:
awk '/tom|jerry|vivek/' /etc/passwd
Print 1st Line From File

awk "NR==1{print;exit}" /etc/resolv.conf
awk "NR==$line{print;exit}" /etc/resolv.conf
Simply Arithmetic

You get the sum of all the numbers in a column:
awk '{total += $1} END {print total}' earnings.txt
Shell cannot calculate with floating point numbers, but awk can:
awk 'BEGIN {printf "%.3f\n", 2005.50 / 3}'
Call AWK From Shell Script

A shell script to list all IP addresses that accessing your website. This script use awk for processing log file and verification is done using shell script commands.

#!/bin/bash
d=$1
OUT=/tmp/spam.ip.$$
HTTPDLOG="/www/$d/var/log/httpd/access.log"
[ $# -eq 0 ] && { echo "Usage: $0 domain-name"; exit 999; }
if [ -f $HTTPDLOG ];
then
    awk '{print}' $HTTPDLOG >$OUT
    awk '{ print $1}' $OUT  |  sort -n | uniq -c | sort -n
else
    echo "$HTTPDLOG not found. Make sure domain exists and setup correctly."
fi
/bin/rm -f $OUT

AWK and Shell Functions

Here is another example. chrootCpSupportFiles() find out the shared libraries required by each program (such as perl / php-cgi) or shared library specified on the command line and copy them to destination. This code calls awk to print selected fields from the ldd output:


chrootCpSupportFiles() {
# Set CHROOT directory name
local BASE="$1"         # JAIL ROOT
local pFILE="$2"        # copy bin file libs

[ ! -d $BASE ] && mkdir -p $BASE || :

FILES="$(ldd $pFILE | awk '{ print $3 }' |egrep -v ^'\(')"
for i in $FILES
do
  dcc="$(dirname $i)"
  [ ! -d $BASE$dcc ] && mkdir -p $BASE$dcc || :
  /bin/cp $i $BASE$dcc
done

sldl="$(ldd $pFILE | grep 'ld-linux' | awk '{ print $1}')"
sldlsubdir="$(dirname $sldl)"
if [ ! -f $BASE$sldl ];
then
        /bin/cp $sldl $BASE$sldlsubdir
else
        :
fi
}

This function can be called as follows:
chrootCpSupportFiles /lighttpd-jail /usr/local/bin/php-cgi
AWK and Shell Pipes

List your top 10 favorite commands:
history | awk '{print $2}' | sort | uniq -c | sort -rn | head
Sample Output:

   172 ls
    144 cd
     69 vi
     62 grep
     41 dsu
     36 yum
     29 tail
     28 netstat
     21 mysql
     20 cat

whois cyberciti.com | awk '/Domain Expiration Date:/ { print $6"-"$5"-"$9 }'
Awk Program File

You can put all awk commands in a file and call the same from a shell script using the following syntax:
awk -f mypgoram.awk input.txt
Awk in Shell Scripts - Passing Shell Variables TO Awk

You can pass shell variables to awk using the -v option:


n1=5
n2=10
echo | awk -v x=$n1 -v y=$n2 -f program.awk

Assign the value n1 to the variable x, before execution of the program begins. Such variable values are available to the BEGIN block of an AWK program:

BEGIN{ans=x+y}
{print ans}
END{}

remove duplicate files from dir and subdir - python script

#! /usr/bin/python

import os
import sys
import stat
import md5

filesBySize = {}

def walker(arg, dirname, fnames):
    d = os.getcwd()
    os.chdir(dirname)
    try:
        fnames.remove('Thumbs')
    except ValueError:
        pass       
    for f in fnames:
        if not os.path.isfile(f):
            continue
        size = os.stat(f)[stat.ST_SIZE]
        if size < 100:
            continue
        if filesBySize.has_key(size):
            a = filesBySize[size]
        else:
            a = []
            filesBySize[size] = a
        a.append(os.path.join(dirname, f))
    os.chdir(d)

for x in sys.argv[1:]:
    print 'Scanning directory "%s"....' % x
    os.path.walk(x, walker, filesBySize)   

print 'Finding potential dupes...'
potentialDupes = []
potentialCount = 0
trueType = type(True)
sizes = filesBySize.keys()
sizes.sort()
for k in sizes:
    inFiles = filesBySize[k]
    outFiles = []
    hashes = {}
    if len(inFiles) is 1: continue
    print 'Testing %d files of size %d...' % (len(inFiles), k)
    for fileName in inFiles:
        if not os.path.isfile(fileName):
            continue
        aFile = file(fileName, 'r')
        hasher = md5.new(aFile.read(1024))
        hashValue = hasher.digest()
        if hashes.has_key(hashValue):
            x = hashes[hashValue]
            if type(x) is not trueType:
                outFiles.append(hashes[hashValue])
                hashes[hashValue] = True
            outFiles.append(fileName)
        else:
            hashes[hashValue] = fileName
        aFile.close()
    if len(outFiles):
        potentialDupes.append(outFiles)
        potentialCount = potentialCount + len(outFiles)
del filesBySize

print 'Found %d sets of potential dupes...' % potentialCount
print 'Scanning for real dupes...'

dupes = []
for aSet in potentialDupes:
    outFiles = []
    hashes = {}
    for fileName in aSet:
        print 'Scanning file "%s"...' % fileName
        aFile = file(fileName, 'r')
        hasher = md5.new()
        while True:
            r = aFile.read(4096)
            if not len(r):
                break
            hasher.update(r)
        aFile.close()
        hashValue = hasher.digest()
        if hashes.has_key(hashValue):
            if not len(outFiles):
                outFiles.append(hashes[hashValue])
            outFiles.append(fileName)
        else:
            hashes[hashValue] = fileName
    if len(outFiles):
        dupes.append(outFiles)

i = 0
for d in dupes:
    print 'Original is %s' % d[0]
    for f in d[1:]:
        i = i + 1
        print 'Deleting %s' % f
        os.remove(f)
    print

Thursday, 31 January 2013

Howto Bonding

http://www.cyberciti.biz/tips/linux-bond-or-team-multiple-network-interfaces-nic-into-single-interface.html
http://www.cyberciti.biz/howto/question/static/linux-ethernet-bonding-driver-howto.php


For Bonding 
Install ifenslave Control Utility

By default it is installed as Module - /sbin/ifenslave

now create the following file 

vi /etc/sysconfig/network-scripts/ifcfg-bond0
DEVICE=bond0
IPADDR=192.168.92.80
NETWORK=192.168.92.1
NETMASK=255.255.254.0
USERCTL=no
BOOTPROTO=none
ONBOOT=yes

vi /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
USERCTL=no
ONBOOT=yes
MASTER=bond0
SLAVE=yes
BOOTPROTO=none

vi /etc/sysconfig/network-scripts/ifcfg-eth1
DEVICE=eth1
USERCTL=no
ONBOOT=yes
MASTER=bond0
SLAVE=yes
BOOTPROTO=none

Load bond Module driver

vi /etc/modprobe.conf
alias bond0 bonding
options bond0 mode=balance-alb miimon=100

Now Test The config:

modprobe bonding

service network restart

verify everything is working

less /proc/net/bonding/bond0  ---- output will be like below
Bonding Mode: load balancing (round-robin)
MII Status: up
MII Polling Interval (ms): 0
Up Delay (ms): 0
Down Delay (ms): 0

Slave Interface: eth0
MII Status: up
Link Failure Count: 0
Permanent HW addr: 00:0c:29:c6:be:59

Slave Interface: eth1
MII Status: up
Link Failure Count: 0
Permanent HW addr: 00:0c:29:c6:be:63


ifconfig -====

bond0     Link encap:Ethernet  HWaddr 00:0C:29:C6:BE:59
 inet addr:192.168.1.20  Bcast:192.168.1.255  Mask:255.255.255.0
 inet6 addr: fe80::200:ff:fe00:0/64 Scope:Link
 UP BROADCAST RUNNING MASTER MULTICAST  MTU:1500  Metric:1
 RX packets:2804 errors:0 dropped:0 overruns:0 frame:0
 TX packets:1879 errors:0 dropped:0 overruns:0 carrier:0
 collisions:0 txqueuelen:0
 RX bytes:250825 (244.9 KiB)  TX bytes:244683 (238.9 KiB)

eth0      Link encap:Ethernet  HWaddr 00:0C:29:C6:BE:59
 inet addr:192.168.1.20  Bcast:192.168.1.255  Mask:255.255.255.0
 inet6 addr: fe80::20c:29ff:fec6:be59/64 Scope:Link
 UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
 RX packets:2809 errors:0 dropped:0 overruns:0 frame:0
 TX packets:1390 errors:0 dropped:0 overruns:0 carrier:0
 collisions:0 txqueuelen:1000
 RX bytes:251161 (245.2 KiB)  TX bytes:180289 (176.0 KiB)
 Interrupt:11 Base address:0x1400

eth1      Link encap:Ethernet  HWaddr 00:0C:29:C6:BE:59
 inet addr:192.168.1.20  Bcast:192.168.1.255  Mask:255.255.255.0
 inet6 addr: fe80::20c:29ff:fec6:be59/64 Scope:Link
 UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
 RX packets:4 errors:0 dropped:0 overruns:0 frame:0
 TX packets:502 errors:0 dropped:0 overruns:0 carrier:0
 collisions:0 txqueuelen:1000
 RX bytes:258 (258.0 b)  TX bytes:66516 (64.9 KiB)
 Interrupt:10 Base address:0x1480

VI Editor shortcut Keys

keys:
:help index - it will show all command
h -left
j -down
k -up
l -right
x -delete a single caractor
u -undo
ctrl-R -redo
ZZ -save and exit
:q! -exit without saving
:wq -save and exit
dd -delete line
yy -copy line
p -paste line
o -open new line
w -moving forword one word
b -moving backword one word
$ -end of line
5$ -end of 5th line
# -put your cursor in word and search that word in all file
^ -begining of line
:set number -numburing turn on
:set nonumber -turn off numburing
ctrl-u -scrolling up
ctrl-d -scrolling down
dw -delete word
d$ -delete till end of line
cw -delete word and insert mode
. -repeats loast delete or changes
J -caps j joins two lines
) -move next sentences
( -move previous sentences
} -move next paragraph
{ -move previous para
gg -1st line of doc
G -shift g end of doc
d) -delete sentenses
d} -delete para
r -replace caractor
~ -change case uppercase to lower case vice versa
:set hlsearch -set highlight search
:set nohlsearch -unset highlight search
:nohlsearch -clear highlights
n -next search
N -previous search
!! -type command and output will be in your file  
:wnext -save cuurunt filr and go to next file
:next! -dont save currunt file and go to next file
:set autowrite -to save automatically
:args -which file am i on
:previous -same as next
:rewind -shift to fist file
:first -shift to first file
:last -shift to last file
ctrl^ -shifting in two files
v -to select lines visual mode - start visual mode
d -delete
y -copy
ctrl-v -to select block
!Gsort -sort the docs by alphabetics
x   :delete character under the cursor (short for "dl")
X   :delete character before the cursor (short for "dh")
D   :delete from cursor to end of line (short for "d$")
dw  :delete from cursor to next start of word
db  :delete from cursor to previous start of word
diw :dearzoo.com
to add start of line
:%s/^/abcd
add abcd every start of line
search www and delete
:%s/www/
find abcd and replace @arzoo.com
:%s/abcd/@arzoo.com/glete word under the cursor (excluding white space)
daw :delete word under the cursor (including white space)
dG  :delete until the end of the file
dgg :delete until the start of the file
If you use "c" instead of "d" they become change commands. And with "y" you
yank the text. And so forth.
To add @arzoo.com to every end of line
:%s/$/@arzoo.com
to add start of line
:%s/^/abcd
add abcd every start of line
search www and delete
:%s/www/
find abcd and replace @arzoo.com
:%s/abcd/@arzoo.com/g

rubygem tips

example :
install rubygem RMagick

start irb
run following commands in irb

require 'rubygems'
true
require 'RMagick'
true

True means installed both

to see installed gems with version

command is   gem list