Friday, December 03, 2004

Automate Backup in Linux

Automated Backup Linux(Source) to Linux (Destination) :
=========================================

Source IP - 67.15.35.18
Destination IP - 192.168.0.17

Scenario:
=======

Here we need to backup data from 67.15.35.18 (/opt/mavb-proxy-recent/src) to 192.168.0.17 (/home/sriram)

Steps :
=====

1) First we need to automate the login process with out initializing the password.
- For that we use ssh-keygen

2) We need a Backup Script that can be run on the Backup Server (192.168.0.17) at the scheduled time.
- This script will connect using ssh, tar the specified directory and scp the directory to Backup Server and delete the tar file from the destination server.
- This can be added to cron job.

How To :
=======

1) Creating SSH-Keygen in 192.168.0.17

#ssh-keygen -t rsa

Ente the Pass Phrase
eg pass

2) Change the directory to cd /root/.ssh/ where the Public key is stored.

3)
Copy your public keys to scp id_rsa.pub 67.15.35.18:/root/.ssh/authorized_keys2

4) Check if the server asks for password

# ssh
67.15.35.18

This should log in with out asking for password.

The script I run to take the backup in 192.168.0.17 (/home/sriram)

#!/bin/sh
today=$(date +%Y%m%d-%H%M%S).tgz --- Variable Defined
ssh 67.15.35.18 "tar -cvf /opt/mavb-proxy-recent/$today /opt/mavb-proxy-recent/src " --- connects and tars(backup)
scp root@67.15.35.18:/opt/mavb-proxy-recent/$today . --- copyies the backup file to the backup server (192.168.0.17)
ssh 67.15.35.18 "rm -rf /opt/mavb-proxy-recent/$today" --- removes the backfile from the server(67.15.35.18)

Saturday, November 20, 2004

Ftp Connections

To allow ftp connections

/sbin/modprobe ip_conntrack_ftp
/sbin/modprobe ip_nat_ftp


Wednesday, November 03, 2004

Check if a Perl Module is Installed

root@web-rshack2 perl5]# perl (do a Enter)
use Image::GD::Thumbnail (In the Blank line type use and whole Perl
module)
do a ctrl - d this shuld not give any error which means perl module is
Insatlled.


[root@web-rshack2 perl5]# perl
use Image::GD::Thumbnail (Ctrl-d)
[root@web-rshack2 perl5]# perl
use tete(ctrl-d)
Can't locate tete.pm in @INC (@INC contains:
/usr/lib/perl5/5.8.0/i386-linux-thread-multi /usr/lib/perl5/5.8.0
/usr/lib/perl5/site_perl/5.8.0/i386-linux-thread-multi
/usr/lib/perl5/site_perl/5.8.0 /usr/lib/perl5/site_perl
/usr/lib/perl5/vendor_perl/5.8.0/i386-linux-thread-multi
/usr/lib/perl5/vendor_perl/5.8.0 /usr/lib/perl5/vendor_perl
/usr/lib/perl5/5.8.0/i386-linux-thread-multi /usr/lib/perl5/5.8.0 .) at
- line 1.
BEGIN failed--compilation aborted at - line 1.

Wednesday, October 20, 2004

Simple For loop

Using For Loop to find a word in list of files/direcories under a directory and move it to another folder 


for file in `ls -1`; do grep "^From: Postmaster@hdfcbank.com" $file; if
[ $? -eq 0 ];then mv $file /root/work; fi; done

Friday, October 01, 2004

Group email Address in google

Many of my friends tell me that they don’t use Gmail because it do not support grouped email addresses like rediff and yahoo. But actually we can create grouped email addresses in Gmail. This is a very simple hack.

Click on Contacts (left-side menu) and choose Add Contact (top right corner). Enter a name for the group in the Name field. Then in the Primary Email field start inputting the addresses of group members. Here is the trick: leave out the first and last brackets. This is how you should do it (substituting the appropriate email addresses):

Then save the address. Once you save it, you can see that GMail puts a bracket around the list of addresses. You can try it out by clicking on Compose. Next time you want to send a note to this group, just start typing in the group name and the address list will come up as an option.

Friday, August 20, 2004

Network Time Protocol

Configuring NTP on Linux Server

Network Time Protocol, NTP is a service that can query other computers over the network
and synchronize the computer's clock to the server's time.

Steps
--------

1) Connect to server using SSH

2) Install NTP. Download rpm from rpmfind.net for the relevant Redhat release.
3) Create the backup of existing /etc/ntp.conf file.
mv /etc/ntp.conf /etc/ntp.conf.bkp

4) Create a new /etc/ntp.conf file with following contents.

--------------------------------

server 127.127.1.0 # local clock
fudge 127.127.1.0 stratum 10

# servers added by Zed www.bldrdoc.gov/timefreq/service/time-servers.html
server 129.6.15.28
server 129.6.15.29
server 63.149.208.50
server 132.163.4.101
server 132.163.4.102
server 132.163.4.103
server 128.138.140.44
server 192.43.244.18
server 131.107.1.10
server 216.200.93.8
server 208.184.49.9
server 207.126.103.204
server 207.200.81.113
server 205.188.185.33

driftfile /etc/ntp/drift
multicastclient # listen on default 224.0.1.1
broadcastdelay 0.008

#
# Authentication delay. If you use, or plan to use someday, the
# authentication facility you should make the programs in the auth_stuff
# directory and figure out what this number should be on your machine.
#
authenticate no

-----------------------------

5) Create the separate ticker file /etc/ntp/step-tickers that contains the list of time servers. Use the following command to create the step-tickers file.
awk '/^server/ {print $2}' /etc/ntp.conf | grep -v '127.127.1.0' > /etc/ntp/step-tickers

6) Change the timezone of the server.

ln -sf /usr/share/zoneinfo/GMT /etc/localtime

7) Edit /etc/sysconfig/clock and make sure it has the below entries. If not change it.

ZONE="GMT"
UTC=true
ARC=false

8) Before starting the service, synchronize your clock using one of the servers with ntpdate command.
ntpdate -u nist1.datum.com

9) Start the NTPD daemon.
/etc/rc.d/init.d/ntpd start

10) Check the configuration using ntpq -p command.

11) Configure your server to start NTPD at startup.
chkconfig --level 345 ntpd on

Wednesday, July 21, 2004

Difference between Unix Flavours

If you look at the history of Unix, you will find that it is strewn with different flavors of Unices, each doing a particular task in its own way, there being no synergy between them. Inspite of all this, some of the Unix flavors have succeeded in surviving the Linux onslaught.
As a Linux user, have you ever wondered what differences each Unix flavour have from each other ? Yes? Then look no further. Bhami.com has compiled an extensive table detailing the differences in commands used for executing a task in various flavors of Unices and Linux which I found really interesting. It is a real eye opener for anyone interested in computing on the Posix platform.

Sunday, June 20, 2004

Sort Difference between 2 files

file1

[root@mybox unix]# cat file1
This is line 1

This is line 2

This is line 3

file2

[root@mybox unix]# cat file2
This is line 1
This is line 3

[root@mybox unix]# diff -by file1 file2
This is line 1 This is line 1
<
This is line 2 <
<
This is line 3 This is line 3
[root@mybox unix]#

Sunday, May 30, 2004

Hardlink and Symlinks

HARDLINKS AND SYMLINKS


Today we will test your virtual imagination capabilities !

The main difference between hardlinks and symlinks ( symbolic or softlinks ) are:
1.) You cannot make a hardlink to a directory.
2.) If you remove the original file of a hardlink the link will still show you the content of the file.
3.) A symlink can link a directory
4.) The symlink is useless as you remove the original file.

All this might seem hard to grasp, but let´s explain:


Hardlinks

A little experiment to show the case.

CODE
$ mkdir Test

( Making a new directory for our test )

CODE
$ cd Test

( Move in the directory )

CODE
$ vi fileA

( Make a file called fileA )

<>
Type in some funny lines of text
<>
<> ( save the file )

So, we made a ¨fileA¨ in a new directory called ¨Test¨ in your /home.

CODE
$ ln fileA fileB

( Making a hardlink )

CODE
$ ls -il fileA fileB

( The ¨i¨ argument will show the inode on the HD )
This is what you get:

QUOTE (Text @ Screen)
1482256 -rw-r--r-- 2 bruno bruno 21 May 5 15:55 fileA
1482256 -rw-r--r-- 2 bruno bruno 21 May 5 15:55 fileB


Here you can see that both fileA and fileB have the same inode number ( 1482256 ), also both files have the same file permissions and the same size, because that ´size´ is on the same inode it does not consume any extra space on your HD !

Now if we would remove the original ¨fileA¨

CODE
$ rm fileA

and have a look at the content of the ¨link¨ fileB

CODE
$ cat fileB

you will still be able to read the funny line of text you typed. ( MAGIC ! )




Symlinks

Staying in the same test directory as above we make a symlink:

CODE
$ ln -s fileB fileC
$ ls -il fileB fileC

This is what you´ll get:

QUOTE (Text @ Screen)
1482256 -rw-r--r-- 1 bruno bruno 21 May 5 15:55 fileB
1482226 lrwxrwxrwx 1 bruno bruno 5 May 5 16:22 fileC -> fileB


You´ll notice the inodes are different and the link got a ¨l¨ before the rwxrwxrwx . The link has different permissions than the original file because it is just a symbolic link, its real content is just a string pointing to the original file. The size of the symlink ( 5 ) is the size of it´s string. ( The "-> fileB" at the end shows you where the link points to )

CODE
$ cat fileB

and

CODE
$ cat fileC

Will show the same funny text.

Now if we remove the original file:

CODE
$ rm fileB

and check the Test directory

CODE
$ ls

you will see the link fileC is still there, but if we do

CODE
$ cat fileC

it will tel you that there is no such file or directory !! Though

CODE
$ ls -il fileC

will still give you:

QUOTE (Text @ Screen)
1482226 lrwxrwxrwx 1 bruno bruno 5 May 5 16:22 fileC -> fileB

But the link is obsolete ! ( hope you´re still with me )

O.K. The test is over, you can delete the Test directory

CODE
$ cd ..
$ rm -rf Test

( ¨r¨ stands for recursive ¨f¨ is force )


WARNING: "rm -rf" is very powerfull, if ever someone wants to play a trick on you and tells you to do "rm -rf /" as root, you might loose all your files and directories on your / partition !!!

Not dizzy yet ? Wait till next week when we come to the real stuff !


Sriram

Thursday, May 20, 2004

File Permissions

CODE
$ ls -l /etc/gnome/gnomerc


This is what you will get:

QUOTE (Text @ Screen)
-rwxr-xr-x 1 root root 484 Feb 25 14:08 /etc/gnome/gnomerc


This does look a bit complicated but it really isn´t. The first 10 characters are built up like this:

- | rwx | r-x | r-x

The first one tells you whether it is a file ( - ) a directory ( d ) or a link ( l )
The next three are for the "user" 'r'ead 'w'rite and e'x'ecute. The next three for the "group" and the last three for all "others"

The next 1 stands for the number of links to the file. The owner. The group. The size in bytes. The date and time of the last modification to the file. And the name of the file.

Wednesday, April 21, 2004

Sed One Liner ...





Latest version of this file is usually at:
http://sed.sourceforge.net/sed1line.txt
http://www.student.northpark.edu/pemente/sed/sed1line.txt
This file is also available in Portuguese at:
http://www.lrv.ufsc.br/wmaker/sed_ptBR.html

FILE SPACING:

# double space a file
sed G

# double space a file which already has blank lines in it. Output file
# should contain no more than one blank line between lines of text.
sed '/^$/d;G'

# triple space a file
sed 'G;G'

# undo double-spacing (assumes even-numbered lines are always blank)
sed 'n;d'

# insert a blank line above every line which matches "regex"
sed '/regex/{x;p;x;}'

# insert a blank line below every line which matches "regex"
sed '/regex/G'

# insert a blank line above and below every line which matches "regex"
sed '/regex/{x;p;x;G;}'

NUMBERING:

# number each line of a file (simple left alignment). Using a tab (see
# note on '\t' at end of file) instead of space will preserve margins.
sed = filename | sed 'N;s/\n/\t/'

# number each line of a file (number on left, right-aligned)
sed = filename | sed 'N; s/^/ /; s/ *\(.\{6,\}\)\n/\1 /'

# number each line of file, but only print numbers if line is not blank
sed '/./=' filename | sed '/./N; s/\n/ /'

# count lines (emulates "wc -l")
sed -n '$='

TEXT CONVERSION AND SUBSTITUTION:

# IN UNIX ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
sed 's/.$//' # assumes that all lines end with CR/LF
sed 's/^M$//' # in bash/tcsh, press Ctrl-V then Ctrl-M
sed 's/\x0D$//' # gsed 3.02.80, but top script is easier

# IN UNIX ENVIRONMENT: convert Unix newlines (LF) to DOS format
sed "s/$/`echo -e \\\r`/" # command line under ksh
sed 's/$'"/`echo \\\r`/" # command line under bash
sed "s/$/`echo \\\r`/" # command line under zsh
sed 's/$/\r/' # gsed 3.02.80

# IN DOS ENVIRONMENT: convert Unix newlines (LF) to DOS format
sed "s/$//" # method 1
sed -n p # method 2

# IN DOS ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
# Can only be done with UnxUtils sed, version 4.0.7 or higher.
# Cannot be done with other DOS versions of sed. Use "tr" instead.
sed "s/\r//" infile >outfile # UnxUtils sed v4.0.7 or higher
tr -d \r outfile # GNU tr version 1.22 or higher

# delete leading whitespace (spaces, tabs) from front of each line
# aligns all text flush left
sed 's/^[ \t]*//' # see note on '\t' at end of file

# delete trailing whitespace (spaces, tabs) from end of each line
sed 's/[ \t]*$//' # see note on '\t' at end of file

# delete BOTH leading and trailing whitespace from each line
sed 's/^[ \t]*//;s/[ \t]*$//'

# insert 5 blank spaces at beginning of each line (make page offset)
sed 's/^/ /'

# align all text flush right on a 79-column width
sed -e :a -e 's/^.\{1,78\}$/ &/;ta' # set at 78 plus 1 space

# center all text in the middle of 79-column width. In method 1,
# spaces at the beginning of the line are significant, and trailing
# spaces are appended at the end of the line. In method 2, spaces at
# the beginning of the line are discarded in centering the line, and
# no trailing spaces appear at the end of lines.
sed -e :a -e 's/^.\{1,77\}$/ & /;ta' # method 1
sed -e :a -e 's/^.\{1,77\}$/ &/;ta' -e 's/\( *\)\1/\1/' # method 2

# substitute (find and replace) "foo" with "bar" on each line
sed 's/foo/bar/' # replaces only 1st instance in a line
sed 's/foo/bar/4' # replaces only 4th instance in a line
sed 's/foo/bar/g' # replaces ALL instances in a line
sed 's/\(.*\)foo\(.*foo\)/\1bar\2/' # replace the next-to-last case
sed 's/\(.*\)foo/\1bar/' # replace only the last case

# substitute "foo" with "bar" ONLY for lines which contain "baz"
sed '/baz/s/foo/bar/g'

# substitute "foo" with "bar" EXCEPT for lines which contain "baz"
sed '/baz/!s/foo/bar/g'

# change "scarlet" or "ruby" or "puce" to "red"
sed 's/scarlet/red/g;s/ruby/red/g;s/puce/red/g' # most seds
gsed 's/scarlet\|ruby\|puce/red/g' # GNU sed only

# reverse order of lines (emulates "tac")
# bug/feature in HHsed v1.5 causes blank lines to be deleted
sed '1!G;h;$!d' # method 1
sed -n '1!G;h;$p' # method 2

# reverse each character on the line (emulates "rev")
sed '/\n/!G;s/\(.\)\(.*\n\)/&\2\1/;//D;s/.//'

# join pairs of lines side-by-side (like "paste")
sed '$!N;s/\n/ /'

# if a line ends with a backslash, append the next line to it
sed -e :a -e '/\\$/N; s/\\\n//; ta'

# if a line begins with an equal sign, append it to the previous line
# and replace the "=" with a single space
sed -e :a -e '$!N;s/\n=/ /;ta' -e 'P;D'

# add commas to numeric strings, changing "1234567" to "1,234,567"
gsed ':a;s/\B[0-9]\{3\}\>/,&/;ta' # GNU sed
sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta' # other seds

# add commas to numbers with decimal points and minus signs (GNU sed)
gsed ':a;s/\(^\|[^0-9.]\)\([0-9]\+\)\([0-9]\{3\}\)/\1\2,\3/g;ta'

# add a blank line every 5 lines (after lines 5, 10, 15, 20, etc.)
gsed '0~5G' # GNU sed only
sed 'n;n;n;n;G;' # other seds

SELECTIVE PRINTING OF CERTAIN LINES:

# print first 10 lines of file (emulates behavior of "head")
sed 10q

# print first line of file (emulates "head -1")
sed q

# print the last 10 lines of a file (emulates "tail")
sed -e :a -e '$q;N;11,$D;ba'

# print the last 2 lines of a file (emulates "tail -2")
sed '$!N;$!D'

# print the last line of a file (emulates "tail -1")
sed '$!d' # method 1
sed -n '$p' # method 2

# print only lines which match regular expression (emulates "grep")
sed -n '/regexp/p' # method 1
sed '/regexp/!d' # method 2

# print only lines which do NOT match regexp (emulates "grep -v")
sed -n '/regexp/!p' # method 1, corresponds to above
sed '/regexp/d' # method 2, simpler syntax

# print the line immediately before a regexp, but not the line
# containing the regexp
sed -n '/regexp/{g;1!p;};h'

# print the line immediately after a regexp, but not the line
# containing the regexp
sed -n '/regexp/{n;p;}'

# print 1 line of context before and after regexp, with line number
# indicating where the regexp occurred (similar to "grep -A1 -B1")
sed -n -e '/regexp/{=;x;1!p;g;$!N;p;D;}' -e h

# grep for AAA and BBB and CCC (in any order)
sed '/AAA/!d; /BBB/!d; /CCC/!d'

# grep for AAA and BBB and CCC (in that order)
sed '/AAA.*BBB.*CCC/!d'

# grep for AAA or BBB or CCC (emulates "egrep")
sed -e '/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d # most seds
gsed '/AAA\|BBB\|CCC/!d' # GNU sed only

# print paragraph if it contains AAA (blank lines separate paragraphs)
# HHsed v1.5 must insert a 'G;' after 'x;' in the next 3 scripts below
sed -e '/./{H;$!d;}' -e 'x;/AAA/!d;'

# print paragraph if it contains AAA and BBB and CCC (in any order)
sed -e '/./{H;$!d;}' -e 'x;/AAA/!d;/BBB/!d;/CCC/!d'

# print paragraph if it contains AAA or BBB or CCC
sed -e '/./{H;$!d;}' -e 'x;/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d
gsed '/./{H;$!d;};x;/AAA\|BBB\|CCC/b;d' # GNU sed only

# print only lines of 65 characters or longer
sed -n '/^.\{65\}/p'

# print only lines of less than 65 characters
sed -n '/^.\{65\}/!p' # method 1, corresponds to above
sed '/^.\{65\}/d' # method 2, simpler syntax

# print section of file from regular expression to end of file
sed -n '/regexp/,$p'

# print section of file based on line numbers (lines 8-12, inclusive)
sed -n '8,12p' # method 1
sed '8,12!d' # method 2

# print line number 52
sed -n '52p' # method 1
sed '52!d' # method 2
sed '52q;d' # method 3, efficient on large files

# beginning at line 3, print every 7th line
gsed -n '3~7p' # GNU sed only
sed -n '3,${p;n;n;n;n;n;n;}' # other seds

# print section of file between two regular expressions (inclusive)
sed -n '/Iowa/,/Montana/p' # case sensitive

SELECTIVE DELETION OF CERTAIN LINES:

# print all of file EXCEPT section between 2 regular expressions
sed '/Iowa/,/Montana/d'

# delete duplicate, consecutive lines from a file (emulates "uniq").
# First line in a set of duplicate lines is kept, rest are deleted.
sed '$!N; /^\(.*\)\n\1$/!P; D'

# delete duplicate, nonconsecutive lines from a file. Beware not to
# overflow the buffer size of the hold space, or else use GNU sed.
sed -n 'G; s/\n/&&/; /^\([ -~]*\n\).*\n\1/d; s/\n//; h; P'

# delete all lines except duplicate lines (emulates "uniq -d").
sed '$!N; s/^\(.*\)\n\1$/\1/; t; D'

# delete the first 10 lines of a file
sed '1,10d'

# delete the last line of a file
sed '$d'

# delete the last 2 lines of a file
sed 'N;$!P;$!D;$d'

# delete the last 10 lines of a file
sed -e :a -e '$d;N;2,10ba' -e 'P;D' # method 1
sed -n -e :a -e '1,10!{P;N;D;};N;ba' # method 2

# delete every 8th line
gsed '0~8d' # GNU sed only
sed 'n;n;n;n;n;n;n;d;' # other seds

# delete ALL blank lines from a file (same as "grep '.' ")
sed '/^$/d' # method 1
sed '/./!d' # method 2

# delete all CONSECUTIVE blank lines from file except the first; also
# deletes all blank lines from top and end of file (emulates "cat -s")
sed '/./,/^$/!d' # method 1, allows 0 blanks at top, 1 at EOF
sed '/^$/N;/\n$/D' # method 2, allows 1 blank at top, 0 at EOF

# delete all CONSECUTIVE blank lines from file except the first 2:
sed '/^$/N;/\n$/N;//D'

# delete all leading blank lines at top of file
sed '/./,$!d'

# delete all trailing blank lines at end of file
sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' # works on all seds
sed -e :a -e '/^\n*$/N;/\n$/ba' # ditto, except for gsed 3.02*

# delete the last line of each paragraph
sed -n '/^$/{p;h;};/./{x;/./p;}'

SPECIAL APPLICATIONS:

# remove nroff overstrikes (char, backspace) from man pages. The 'echo'
# command may need an -e switch if you use Unix System V or bash shell.
sed "s/.`echo \\\b`//g" # double quotes required for Unix environment
sed 's/.^H//g' # in bash/tcsh, press Ctrl-V and then Ctrl-H
sed 's/.\x08//g' # hex expression for sed v1.5

# get Usenet/e-mail message header
sed '/^$/q' # deletes everything after first blank line

# get Usenet/e-mail message body
sed '1,/^$/d' # deletes everything up to first blank line

# get Subject header, but remove initial "Subject: " portion
sed '/^Subject: */!d; s///;q'

# get return address header
sed '/^Reply-To:/q; /^From:/h; /./d;g;q'

# parse out the address proper. Pulls out the e-mail address by itself
# from the 1-line return address header (see preceding script)
sed 's/ *(.*)//; s/>.*//; s/.*[:<] *//'

# add a leading angle bracket and space to each line (quote a message)
sed 's/^/> /'

# delete leading angle bracket & space from each line (unquote a message)
sed 's/^> //'

# remove most HTML tags (accommodates multiple-line tags)
sed -e :a -e 's/<[^>]*>//g;/
# extract multi-part uuencoded binaries, removing extraneous header
# info, so that only the uuencoded portion remains. Files passed to
# sed must be passed in the proper order. Version 1 can be entered
# from the command line; version 2 can be made into an executable
# Unix shell script. (Modified from a script by Rahul Dhesi.)
sed '/^end/,/^begin/d' file1 file2 ... fileX | uudecode # vers. 1
sed '/^end/,/^begin/d' "$@" | uudecode # vers. 2

# zip up each .TXT file individually, deleting the source file and
# setting the name of each .ZIP file to the basename of the .TXT file
# (under DOS: the "dir /b" switch returns bare filenames in all caps).
echo @echo off >zipup.bat
dir /b *.txt | sed "s/^\(.*\)\.TXT/pkzip -mo \1 \1.TXT/" >>zipup.bat

TYPICAL USE: Sed takes one or more editing commands and applies all of
them, in sequence, to each line of input. After all the commands have
been applied to the first input line, that line is output and a second
input line is taken for processing, and the cycle repeats. The
preceding examples assume that input comes from the standard input
device (i.e, the console, normally this will be piped input). One or
more filenames can be appended to the command line if the input does
not come from stdin. Output is sent to stdout (the screen). Thus:

cat filename | sed '10q' # uses piped input
sed '10q' filename # same effect, avoids a useless "cat"
sed '10q' filename > newfile # redirects output to disk

For additional syntax instructions, including the way to apply editing
commands from a disk file instead of the command line, consult "sed &
awk, 2nd Edition," by Dale Dougherty and Arnold Robbins (O'Reilly,
1997; http://www.ora.com), "UNIX Text Processing," by Dale Dougherty
and Tim O'Reilly (Hayden Books, 1987) or the tutorials by Mike Arst
distributed in U-SEDIT2.ZIP (many sites). To fully exploit the power
of sed, one must understand "regular expressions." For this, see
"Mastering Regular Expressions" by Jeffrey Friedl (O'Reilly, 1997).
The manual ("man") pages on Unix systems may be helpful (try "man
sed", "man regexp", or the subsection on regular expressions in "man
ed"), but man pages are notoriously difficult. They are not written to
teach sed use or regexps to first-time users, but as a reference text
for those already acquainted with these tools.

QUOTING SYNTAX: The preceding examples use single quotes ('...')
instead of double quotes ("...") to enclose editing commands, since
sed is typically used on a Unix platform. Single quotes prevent the
Unix shell from intrepreting the dollar sign ($) and backquotes
(`...`), which are expanded by the shell if they are enclosed in
double quotes. Users of the "csh" shell and derivatives will also need
to quote the exclamation mark (!) with the backslash (i.e., \!) to
properly run the examples listed above, even within single quotes.
Versions of sed written for DOS invariably require double quotes
("...") instead of single quotes to enclose editing commands.

USE OF '\t' IN SED SCRIPTS: For clarity in documentation, we have used
the expression '\t' to indicate a tab character (0x09) in the scripts.
However, most versions of sed do not recognize the '\t' abbreviation,
so when typing these scripts from the command line, you should press
the TAB key instead. '\t' is supported as a regular expression
metacharacter in awk, perl, and HHsed, sedmod, and GNU sed v3.02.80.

VERSIONS OF SED: Versions of sed do differ, and some slight syntax
variation is to be expected. In particular, most do not support the
use of labels (:name) or branch instructions (b,t) within editing
commands, except at the end of those commands. We have used the syntax
which will be portable to most users of sed, even though the popular
GNU versions of sed allow a more succinct syntax. When the reader sees
a fairly long command such as this:

sed -e '/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d

it is heartening to know that GNU sed will let you reduce it to:

sed '/AAA/b;/BBB/b;/CCC/b;d' # or even
sed '/AAA\|BBB\|CCC/b;d'

In addition, remember that while many versions of sed accept a command
like "/one/ s/RE1/RE2/", some do NOT allow "/one/! s/RE1/RE2/", which
contains space before the 's'. Omit the space when typing the command.

OPTIMIZING FOR SPEED: If execution speed needs to be increased (due to
large input files or slow processors or hard disks), substitution will
be executed more quickly if the "find" expression is specified before
giving the "s/.../.../" instruction. Thus:

sed 's/foo/bar/g' filename # standard replace command
sed '/foo/ s/foo/bar/g' filename # executes more quickly
sed '/foo/ s//bar/g' filename # shorthand sed syntax

On line selection or deletion in which you only need to output lines
from the first part of the file, a "quit" command (q) in the script
will drastically reduce processing time for large files. Thus:

sed -n '45,50p' filename # print line nos. 45-50 of a file
sed -n '51q;45,50p' filename # same, but executes much faster

Thursday, March 18, 2004

CHANGING FILE PERMISSIONS


Changing the permissions can be done with names and numbers, I like the numbers:
( do you remember the chmod 755 command from a few posts ago ? )

CODE
# chmod 754 tessst.txt

( Will put the file tessst.txt to rwx r-x r-- )

Here is why:
4=read 2=write 1=execute.
The three numbers in the chmod above are for the "user" ( the first number ), "group" ( the second number ) and "others" ( the third number )

So if I want to give the user all permissions: 4+2+1=7
and i give the group read an execute permissions: 4+1=5
and all others only read permission 4=4



Chown and chgrp are two commands also related to permissions:

CODE
# chown

( Changes the owner of the file. )

CODE
# chown anna tessst.txt

( Changes the owner of the file tessst.txt from bruno to anna )



CODE
# chgrp

( Changes the group the file belongs to - if you did change the user and the user belongs to another group )



CODE
# chown -R anna:anna docs

( Changes the user and group ownership of the "docs" directory and all the files in it because of the -R argument ).

QUOTE chmod takes either the decimal representation of the permissions or a symbolic representation. The symbolic representation is [ugoa][+-][rwx]. This is one of the letters u (user=file owner), g (group), o(others), a(all=u and g and o) followed by + or - to add or remove permissions and then the symbolic representation of the permissions in the form of r(read) w(write) x(execute). To make the file "file.txt" writable for all you type: "chmod a+w file.txt"

Thursday, February 19, 2004

Of bash colors, ls colors

The colors that you see when you type "ls" in bash come from an environment variable called LS_COLORS. The LS_COLORS variable can be set from a configuration file using the command called dircolors and the actual file is called dir_colors.

I dug around a bit in man and info pages for ls, dircolors and dir_colors, and the most useful information seems to be the man page for dir_colors. You can access this page by typing man dir_colors at the console, or, you can click man dir_colors

Tuesday, February 03, 2004

Defining Quota in Linux ... ... ...

List of Quota Commands

# quota - display disk usage and limits
# rquota - implement quotas on remote machines
# fstab - static information about the filesystems
# edquota - edit user quotas
# setquota - set disk quotas (Command line editor)
# quotacheck - scan a filesystem for disk usage, create, check and repair quota files
# quotaon - turn filesystem quotas on
# quotaoff - turn filesystem quotas off
# repquota - produce a summary of quota information for a file system
# convertquota - convert quota from old file format to new one. Convert quota.user to aquota.user
# quotactl - manipulate disk quotas (C programmer interface)

The default Red Hat/Fedora Core Linux kernel is shipped quota ready. If you have streamlined your kernel by rebuilding it with fewer options, make sure it has been configured with quotas support. When using the tools xconfig or menuconfig be sure to reply y to:
Quota support (CONFIG_QUOTA) [n] y

Configuration of disk usage quotas on Linux - Perform the following as root:

  1. Edit file /etc/fstab to add qualifier "usrquota" or "grpquota" to the partition. The following file system mounting options can be specified in /etc/fstab: grpquota, noquota, quota and usrquota. (These options are also accepted by the mount command but ignored.) The filesystem when mounted will show up in the file /etc/mtab, the list of all currently mounted filesystems.)

    • To enable user quota support on a file system, add "usrquota" to the fourth field containing the word "defaults".
      ...
      /dev/hda2 /home ext3 defaults,usrquota 1 1
      ...
    • Replace "usrquota" with "grpquota", should you need group quota support on a file system.
      ...
      /dev/hda2 /home ext3 defaults,grpquota 1 1
      ...
    • Need both user quota and group quota support on a file system?
      ...
      /dev/hda2 /home ext3 defaults,usrquota,grpquota 1 1
      ...
      This enables user and group quotas support on the /home file system.

  2. touch /partition/aquota.user
    where the partition might be /home or some partition defined in /etc/fstab.
    then
    chmod 600 /partition/aquota.user

    The file should be owned by root. Quotas may also be set for groups by using the file aquota.group

    Quota file names:

    • Quota Version 2 (Linux 2.4/2.6 kernel: Red Hat 7.1+/8/9,FC 1-3): aquota.user, aquota.group
    • Quota Version 1 (Linux 2.2 kernel: Red Hat 6, 7.0): quota.user, quota.group
    The files can be converted/upgraded using the convertquota command.
  3. Re-boot or re-mount file partition with quotas.
    • Re-boot: shutdown -r now
    • Re-mount partition: mount -o remount /partition

    After re-booting or re-mounting the file system, the partition will show up in the list of mounted filesystems as having quotas. Check /etc/mtab:
    ...
    /dev/hda5 / ext3 rw,usrquota 0 0
    ...

  4. quotacheck -vgum /partition
    or
    quotacheck -vguma
    • For example (Linux kernel 2.4+: Red Hat 7.1+, Fedora): quotacheck -vguma
      quotacheck: WARNING -  Quotafile //aquota.user was probably truncated. ...
      quotacheck: Scanning /dev/hda5 [/] done
      quotacheck: Checked 9998 directories and 179487 files

    • For example (Linux kernel 2.2: Red Hat 6/7.0): quotacheck -v /dev/hda6
      System response:
            Scanning /dev/hda6 [/home] done
      Checked 444 directories and 3136 files
      Using quotafile /home/quota.user

    Quotacheck is used to scan a file system for disk usages, and updates the quota record file "quota.user/aquota.user" to the most recent state. It is recommended thet quotacheck be run at bootup (part of Redhat default installation)

    Man page: quotacheck - scan a filesystem for disk usage, create, check and repair quota files

  5. quotaon -av
    System Response: /dev/hda6: user quotas turned on

    quotaon - enable disk quotas on a file system.
    quotaoff - turn off disk quotas for a file system.

    Man page: quotaon - turn filesystem quotas on and off

  6. edquota -u user_id
    Edit directly using vi editor commands. (See below for more info.)
    For example: edquota -u user1
    • System Response (RH 7+):
      Disk quotas for user user1 (uid 501):
      Filesystem blocks soft hard inodes soft hard
      /dev/hda5 1944 0 0 120 0 0
      • blocks: 1k blocks
      • inodes: Number of entries in directory file
      • soft: Max number of blocks/inodes user may have on partition before warning is issued and grace persiod countdown begins.
        If set to "0" (zero) then no limit is enforced.
      • hard: Max number of blocks/inodes user may have on partition.
        If set to "0" (zero) then no limit is enforced.

    • System Response (RH 6):
                 Quotas for user user1:
      /dev/sdb6: blocks in use: 56, limits (soft = 0, hard = 0)
      inodes in use: 50, limits (soft = 0, hard = 0)
      Something failed if you get the response:
                 /dev/sdb6: blocks in use: 0, limits (soft = 0, hard = 0)
      inodes in use: 0, limits (soft = 0, hard = 0)

      Edit limits:
                 Quotas for user user1:
      /dev/hda6: blocks in use: 992, limits (soft = 50000, hard = 55000)
      inodes in use: 71, limits (soft = 10000, hard = 11000)

    If editing group quotas: edquota -g group_name

    Man page: edquota - edit user quotas

  7. List quotas:
    quota -u user_id

    For example: quota -u user1
    System response:

    Disk quotas for user user1 (uid 501):
    Filesystem blocks quota limit grace files quota limit grace
    /dev/hda6 992 50000 55000 71 10000 11000
    If this does not respond similar to the above, then restart the computer: shutdown -r now

  • Report on all users over quota limits: quota -q
  • Quota summary report: repquota -a
    *** Report for user quotas on device /dev/hda5 Block grace time: 7days; Inode grace time: 7days                         Block limits                File limits User            used    soft    hard  grace    used  soft  hard  grace ---------------------------------------------------------------------- root      -- 4335200       0       0         181502     0     0 bin       --   15644       0       0            101     0     0 ... user1     --    1944       0       0            120     0     0     
    No limits shown with this user as limits are set to 0.

  • One more way to set quota

    setquota -g $group $blocks $blocks 0 0 -a
    setquota -u $username $blocks $blocks 0 0 -a


    Replace $group, $username and $blocks. Note: $blocks is the quota size in MB * 1024! To deactivate quotas for a user or group, run these commands and set $blocks to 0.

    Monday, January 19, 2004

    Scan Linux Systems For worms Torjans...

    Either with ckrootkit or with rkhunter.

    chkrootkit:

    Either install the package that comes with your distribution (on Debian you would run

    apt-get install chkrootkit

    ), or download the sources from www.chkrootkit.org and install manually:

    wget --passive-ftp ftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz

    tar xvfz chkrootkit.tar.gz

    cd chkrootkit-/

    make sense

    Afterwards, you can move the chkrootkit directory somewhere else, e.g. /usr/local/chkrootkit:

    cd ..

    mv chkrootkit-/ /usr/local/chkrootkit

    Now you can run chkrootkit manually:

    cd /usr/local/chkrootkit

    ./chkrootkit

    (if you installed a chkrootkit package coming with your distribution, your chkrootkit might be somewhere else).

    You can even run chkrootkit by a cron job and get the results emailed to you:

    Run

    crontab -e

    to create a cron job like this:

    0 3 * * * (cd /usr/local/chkrootkit-; ./chkrootkit 2>&1 | mail -s "chkrootkit output my server" you@yourdomain.com)

    That would run chkrootkit every night a 3.00h.

    rkhunter:

    Download the latest rkhunter sources from www.rootkit.nl:

    wget http://downloads.rootkit.nl/rkhunter-1.2.7.tar.gz

    tar xvfz rkhunter-1.2.7.tar.gz

    cd rkhunter/

    ./installer.sh

    This will install rkhunter to the directory /usr/local/rkhunter. Now run

    rkhunter --update

    to download the latest chkrootkit/trojan/worm signatures (you should do this regularly).

    Now you can scan your system for malware by running

    rkhunter -c