Académique Documents
Professionnel Documents
Culture Documents
com)
Copyright (C) 2004 (GNU Free Documentation License)
Last Updated: Sun Aug 8 19:49:25 EDT 2010
**Note, if you want email notification after every 50 new tips have
been
added, then, click on the following link:
https://sourceforge.net/project/filemodule_monitor.php?
filemodule_id=120838
TIP 1:
Is NTP Working?
$ ntpq -pn
$ cat /etc/ntp.conf
$ cat /etc/ntp/step-tickers
timeserver1.upenn.edu
tock.usno.navy.mil
128.4.40.12
/usr/sbin/ntpdate -s -b -p 8 timeserver1.upenn.edu
Why? Because if the time is off ntpd will not start. The
command above set the
clock. If System Time deviates from true time by more than
1000 seconds, then,
the ntpd daemon will enter panic mode and exit.
/etc/init.d/ntpd restart
ntpq -pn
SPECIAL NOTE:
$ export TZ=EST
$ date
Mon Aug 2 10:34:04 EST 2004
$ export TZ=NET
$ date
Mon Aug 2 15:34:18 NET 2004
DST timezone
$ export TZ=EST+5EDT,M4.1.0/2,M10.5.0/2
Take a look at the last line "M10.5.0/2". What does it mean? Here
is the
documentation
October
Su Mo Tu We Th Fr Sa
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Prove it. Take the following program sunrise, which can calcuates
sunrise
and sunset for an latitude and longitude. This program can be
downloaded
from the following location:
http://sourceforge.net/direct-
dl/mchirico/souptonuts/working_with_time.tar.gz
Below is a bash script that will run the program for the next 100
days.
#!/bin/bash
# program: next100days Mike Chirico
# download:
# http://sourceforge.net/direct-
dl/mchirico/souptonuts/working_with_time.tar.gz
#
# This will calculate the sunrise and sunset for
# latitude 39.95 Note must convert to degrees
# longitude 75.15 Note must convert to degrees
lat=39.95
long=75.15
for (( i=0; i <= 100; i++))
do
sunrise `date -d "+$i day" "+%Y %m %d"` $lat $long
done
$ export TZ=EST+5EDT,M4.1.0/2,M10.5.0/2
$ ./next100days
$ ls /usr/share/zoneinfo
$ export TZ=:/usr/share/zoneinfo/posix/America/Aruba
$ export TZ=:/usr/share/zoneinfo/Egypt
Reference:
http://prdownloads.sourceforge.net/cpearls/date_calc.tar.gz?
download
TIP 2:
mkdir -p ../dir1
mkdir -p ../dir2
cp /etc/*.conf ../dir1/.
cp /etc/*.cnf ../dir2/.
Using append
$ cpio -i -F test.tar
TIP 3:
STEP 5 (ENCRYPTION)
$ mke2fs -q
yes, you can even use reiser, but you'll need to create a
bigger
disk image. Something like "dd if=/dev/zero of=/tmp/disk-image
count=50480".
$ mkdir /virtual-fs
$ mount -o loop=/dev/loop0 /tmp/disk-image /virtual-fs
$ umount /virtual-fs
SPECIAL NOTE: If you are using Fedora core 2, in the /etc/fstab you
can take
advantage of acl properties for this mount. Note the acl
next to the
rw entry. This is shown here with ext3.
Also, if you are using Fedora core 2 and above, you can
mount the file
on a cryptoloop.
$ modprobe loop
$ modprobe cryptoloop
$ modprobe aes
If you do not have Fedora core 2, then, you can build the
kernel from source
with some of the following options (not complete, yet)
reference:
http://cvs.sourceforge.net/viewcvs.py/cpearls/cpearls/src/posted_on_sf/a
cl/ehd.pdf?rev=1.1&view=log
$ cat /etc/mtab
TIP 5:
$ cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
BOOTPROTO=static
BROADCAST=192.168.99.255
IPADDR=192.168.1.155
NETMASK=255.255.252.0
NETWORK=192.168.1.0
ONBOOT=yes
$ cat /etc/sysconfig/network-scripts/ifcfg-eth0:1
DEVICE=eth0:1
BOOTPROTO=static
BROADCAST=192.168.99.255
IPADDR=192.168.1.182
NETMASK=255.255.252.0
NETWORK=192.168.1.0
ONBOOT=yes
TIP 6:
$ /usr/sbin/groupadd share
$ chown -R root.share /home/share
$ /usr/bin/gpasswd -a <username> share
$ chmod 2775 /home/share
$ ls -ld /home/share
drwxrwsr-x 2 root share 4096 Nov 8 16:19
/home/share
^---------- Note the s bit, which was set with the
chmod 2775
$ cat /etc/group
...
share:x:502:chirico,donkey,zoe
... ^------- users are added to this group.
The user may need to login again to get access. Or, if the user is
currently
logged in, they can run the following command:
$ su - <username>
Note: SUID, SGID, Sticky bit. Only the left most octet is examined,
and "chmod 755" is used
as an example of the full command. But, anything else could be
used as well. Normally
you'd want executable permissions.
Sticky bit:
$ chmod 1770 dirA
Below files created within the directory have the group ID of the
directory, rather than that
of the default group setting for the user who created the file.
TIP 7:
'q' exits.
'u' moves up to the table of contents of the current section.
'n' moves to the next chapter.
'p' moves to the previous chapter.
'space' goes into the selected section.
$ info coreutils
$ whatis open
open (2) - open and possibly create a file or device
open (3) - perl pragma to set default PerlIO layers for input
and output
open (3pm) - perl pragma to set default PerlIO layers for
input and output
open (n) - Open a file-based or command pipeline channel
$ man 2 open
$ man -k selinux
$ man 8 ping
1 General Commands
2 System Calls and Error Numbers
3 C Libraries
3p perl
4 Devices and device drivers
5 File Formats and config files
6 Game instructions
7 Miscellaneous information
8 System maintenance
9 Kernel internals
$ whereis -m ls
ls: /usr/share/man/man1/ls.1.gz /usr/share/man/man1/ls.1
/usr/share/man/man1p/ls.1p
$ man /usr/share/man/man1/ls.1.gz
$ manpath
/usr/share/man:/usr/X11R6/man:/usr/local/share/man:/usr/local/pgsql/man:
/usr/man:/usr/local/man
TIP 8:
The "jobs -p" gives the process number of each job, and the
kill -9 kills everything. Yes, sometimes "kill -9" is excessive
and you should issue a "kill -15" that allows jobs to clean-up.
However, for exacs session, I prefer "kill -9" and haven't had
a problem.
$ jobs -l
$ jobs -pl
[1]+ 29388 Running nice -n +15 find . -ctime 2 -exec
ls -l {} \; >mout &
19 was the lowest priority for this job. You cannot increase
the priority unless you are root.
TIP 9:
Need to Delete a File for Good -- not even GOD can recover.
TIP 10:
Who and What is doing What on Your System - finding open sockets,
files etc.
$ lsof
or as root
$ watch lsof -i
$ lsof -i -U
You can also get very specific about ports. Do this as root for low
ports.
$ lsof -i TCP:3306
$ lsof -i UDP:1812
Also try fuser. Suppose you have a mounted file-system, and you
need
to umount it. To list the users on the file-system /work
$ fuser -u /work
To kill all processes accessing the file system /work in any way.
If you need IO load information about your system, you can execute
iostat. But note, the very first iostat gives a snapshot since
the last boot. You typically want the following command, which
gives
you 3 outputs every 5 seconds.
$ iostat -xtc 5 3
Linux 2.6.12-1.1376_FC3smp (squeezel.squeezel.com)
10/05/2005
Time: 07:05:04 PM
avg-cpu: %user %nice %system %iowait %idle
0.97 0.06 1.94 0.62 96.41
Time: 07:05:09 PM
avg-cpu: %user %nice %system %iowait %idle
0.60 0.00 1.70 0.00 97.70
Time: 07:05:14 PM
avg-cpu: %user %nice %system %iowait %idle
1.00 0.00 1.60 0.00 97.39
vmstat reports memory statistics. See tip 241 for vmstat for
I/O subsystem total statistics.
$ vmstat
$ ifconfig
$ cat /proc/sys/vm/.. (entries under here)
Also
$ cat /proc/meminfo
$ cat /proc/stat
$ cat /proc/uptime
1078623.55 1048008.34 First number is the number of seconds
since boot.
The second number is the number of
idle seconds.
$ cat /proc/loadavg
0.25 0.14 0.10 1/166 7778 This shows load at 1,5, and 15
minutes,
a total of 1 current running process
out
from a total of 166. The 7778 is the
last
process id used.
Ref:
http://www.teamquest.com/resources/gunther/ldavg1.shtml
$ ls -l /proc/self/fd/0
lrwx------ 1 chirico chirico 64 Jun 29 13:17 0 ->
/dev/pts/51
lrwx------ 1 chirico chirico 64 Jun 29 13:17 1 ->
/dev/pts/51
lrwx------ 1 chirico chirico 64 Jun 29 13:17 2 ->
/dev/pts/51
lr-x------ 1 chirico chirico 64 Jun 29 13:17 3 ->
/proc/26667/fd
$ tree /proc/self
/proc/self
|-- auxv
|-- cmdline
|-- cwd -> /work/souptonuts/documentation/theBook
|-- environ
|-- exe -> /usr/bin/tree
|-- fd
| |-- 0 -> /dev/pts/51
| |-- 1 -> /dev/pts/51
| |-- 2 -> /dev/pts/51
| `-- 3 -> /proc/26668/fd
|-- maps
|-- mem
|-- mounts
|-- root -> /
|-- stat
|-- statm
|-- status
|-- task
| `-- 26668
| |-- auxv
| |-- cmdline
| |-- cwd -> /work/souptonuts/documentation/theBook
| |-- environ
| |-- exe -> /usr/bin/tree
| |-- fd
| | |-- 0 -> /dev/pts/51
| | |-- 1 -> /dev/pts/51
| | |-- 2 -> /dev/pts/51
| | `-- 3 -> /proc/26668/task/26668/fd
| |-- maps
| |-- mem
| |-- mounts
| |-- root -> /
| |-- stat
| |-- statm
| |-- status
| `-- wchan
`-- wchan
10 directories, 28 files
$ sysctl -a
$ ipcs
$ ipcs -l "This gives limits"
TIP 11:
As root:
$ chattr +i filename
$ chattr -i filename
List attributes
$ lsattr filename
TIP 12:
$ ssh-agent $SHELL
$ ssh-add
The "ssh-add" will allow you to enter the passphrase and it will
save it for the current login session.
TIP 13:
Securing the System: Don't allow root to login remotely. Instead,
the admin could login as another account, then, "su -". However,
root can still login "from the local terminal".
Protocol 2
PermitRootLogin no
PermitEmptyPasswords no
/etc/init.d/sshd restart
Why would you want to do this? It's not possible for anyone to
guess
or keep trying the root account. This is especially good for
computers
on the Internet. So, even if the "root" passwords is known, they
can't
get access to the system remotely. Only from the terminal, which
is locked
in your computer room. However, if anyone has a account on the
server,
then, they can login under their account then "su -".
TIP 14:
Normally logs rotate monthly, over writing all the old data.
Here's a
sample "/etc/logrotate.conf" that will keep 12 months of backup
compressing the logfiles
$ cat /etc/logrotate.conf
TIP 15:
$ netstat -tanup
$ netstat -tanp
or
$ netstat -s -u
or TCP
$ netstat -s -t
or summary of everything
$ netstat -s
$ netstat -i
Listening interfaces?
$ netstat -l
TIP 16:
AuthUserFile /usr/local/apache/htdocs/chirico/alpha/.htpasswd
AuthGroupFile /dev/null
AuthName "Your Name and regular password required"
AuthType Basic
#
<Directory /usr/local/apache/htdocs/chirico/alpha>
AllowOverride FileInfo AuthConfig Limit
Options MultiViews Indexes SymLinksIfOwnerMatch
IncludesNoExec
<Limit GET POST OPTIONS PROPFIND>
Order allow,deny
Allow from all
</Limit>
<LimitExcept GET POST OPTIONS PROPFIND>
Order deny,allow
Deny from all
</LimitExcept>
</Directory>
TIP 17:
# mt -f /dev/nst0 rewind
# mt -f /dev/nst0 tell
At block 0.
# mt -f /dev/nst0 tell
# mt -f /dev/nst0 rewind
# cd junk
# mt -f /dev/nst0 rewind
# mt -f /dev/nst0 tell
At block 0.
# tar -xzf /dev/nst0 one
STEP 8 (Next, take a look to see what block the tape is at)
# mt -f /dev/nst0 tell
At block 2.
STEP 9 (Now backup directories three and four)
# mt -f /dev/nst0 tell
At block 4.
At block 1:
one/
one/test
two/
At block 2:
three/
three/samplehere
four/
At block 4:
(* This is empty *)
A few notes. You can set the blocking factor and a label
with tar. For example:
But note if you try to read it with the default, incorrect blocking
factor, then, you will get the following error:
$ tar -t --file=/dev/nst0
tar: /dev/nst0: Cannot read: Cannot allocate memory
tar: At beginning of tape, quitting now
tar: Error is not recoverable: exiting now
$ mt -f /dev/nst0 rewind
$ tar -t --blocking-factor=128 --file=/dev/nst0
temp label
Notes
$ MYCOMMENTS="Big_important_tape"
$ tar --label="$(date +%F)"+"${MYCOMMENTS}"
Getting data off of tape with dd command with odd blocking factor.
Just set ibs very high
$ mt -f /dev/nst0 rewind
$ tar --label="Contenets of Notes" --create --blocking-
factor=128 --file=/dev/nst0 Notes
$ mt -f /dev/nst0 rewind
$ dd ibs=1048576 if=/dev/st0 of=notes.tar
TIP 18:
TIP 19:
$ mkdir /iso0
$ mount -o loop -t iso9660 /FC2-i386-DVD.iso /iso0
Reference:
http://umn.dl.sourceforge.net/sourceforge/souptonuts/README_fedora.txt
TIP 20:
Getting Information about the Hard drive and list all PCI devices.
$ hdparm /dev/hda
/dev/hda:
multcount = 16 (on)
IO_support = 0 (default 16-bit)
unmaskirq = 0 (off)
using_dma = 1 (on)
keepsettings = 0 (off)
readonly = 0 (off)
readahead = 256 (on)
geometry = 16383/255/63, sectors = 234375000,
start = 0
or for SCSI
$ hdparm /dev/sda
$ hdparm -i /dev/hda
/dev/hda:
Model=IC35L120AVV207-1, FwRev=V24OA66A,
SerialNo=VNVD09G4CZ6E0T
Config={ HardSect NotMFM HdSw>15uSec Fixed DTR>10Mbs }
RawCHS=16383/16/63, TrkSize=0, SectSize=0, ECCbytes=52
BuffType=DualPortCache, BuffSize=7965kB, MaxMultSect=16,
MultSect=16
CurCHS=16383/16/63, CurSects=16514064, LBA=yes,
LBAsects=234375000
IORDY=on/off, tPIO={min:240,w/IORDY:120},
tDMA={min:120,rec:120}
PIO modes: pio0 pio1 pio2 pio3 pio4
DMA modes: mdma0 mdma1 mdma2
UDMA modes: udma0 udma1 udma2 udma3 udma4 *udma5
AdvancedPM=yes: disabled (255) WriteCache=enabled
Drive conforms to: ATA/ATAPI-6 T13 1410D revision 3a: 2
3 4 5 6
/dev/hda:
Timing buffer-cache reads: 128 MB in 0.41 seconds
=315.32 MB/sec
Timing buffered disk reads: 64 MB in 1.19 seconds =
53.65 MB/sec
$ lspci -v
TIP 21:
If you want to use the emacs editor for editing cron jobs, then,
set the following in your "/home/user/.bash_profile"
EDITOR=emacs
$ crontab -e
The sample "commented out command" will run at 10:14 and 10:15
every Sunday. There will
be no "mail" sent to the user because of the ">/dev/null 2>&1"
entry.
$ crontab -l
$ crontab -l -u <username>
$ crontab -e -u <username>
/etc/cron.hourly/
/etc/cron.daily/
/etc/cron.weekly/
/etc/cron.monthly/
$ cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly
TIP 22:
TIP 23:
$ look stuff
stuff
stuffage
stuffata
stuffed
stuffender
stuffer
stuffers
stuffgownsman
stuffier
stuffiest
stuffily
stuffiness
stuffinesses
stuffiness's
stuffing
stuffings
stuffing's
stuffless
stuffs
stuffy
http://prdownloads.sourceforge.net/souptonuts/linuxwords.1.tar.gz?
download
Note: vim users can setup the .vimrc file with the following. Now
when you type
CTL-X CTL-T in insert mode, you'll get a thesaurus lookup.
set dictionary+=/usr/share/dict/words
set thesaurus+=/usr/share/dict/words
Or, you can call aspell with the F6 command after putting the
folling entry in your
.vimrc file
Now, hit F6 when you're in vim, and you'll get a spell checker.
$ gnome-dictionary
TIP 24:
Example:
$ type -all ls
ls is aliased to `ls --color=tty'
ls is /bin/ls
TIP 25:
function calc
{
echo "${1}"|bc -l;
}
$ calc 3+45
48
$ calc "s(.4)"
.38941834230865049166
TIP 26:
#!/bin/bash
# This program will kill all processes from a
# user. The user name is read from the command line.
#
# This program also demonstrates reading a bash variable
# into an awk script.
#
# Usage: kill9user <user>
#
kill -9 `ps aux|awk -v var=$1 '$1==var { print $2 }'`
Check their cron jobs and "at" jobs, if you have a security issue.
$ crontab -u <user> -e
Lock the account:
$ passwd -l <user>
$ rm /home/user/.shosts
$ rm /home/user/.rhosts
$ rm -rf /home/user/.ssh
$ rm /home/user/.forward
or consider
$ mv /home/user /home/safeuser
Do an inventory
To see all users, except the current user. Do not use the
dash "ps -aux" is wrong but the following is correct:
For BSD formats and when the stat keyword is used, additional
characters may be displayed:
TIP 27:
$ date "+%m%d%Y"
06172004
See TIP 87 when working with large delta time changes -40 years,
or -200 years ago, or even
1,000,000 days into the future.
TIP 28:
For example, take a look at the following two lines. The first line
prints a "}" caused
by the extra D in \x027D. The the line immediately below does not
work as expected.
The following date can be used in awk because the single quotes are
enclosed within the
double quotes.
date '+%m%d%Y.%H%M%S.%N%z'
But it's also possible to replace "+" with \x2B, "%" with \x25,
and "d" with \x64 as follows:
07062004.113820.346033000-0400 bob 71
07062004.113820.346033000-0400 tom 43
07062004.113820.346033000-0400 sal 34
07062004.113820.346033000-0400 bob 89
07062004.113820.346033000-0400 tom 66
07062004.113820.346033000-0400 sal 99
For this example it's not needed because single quotes are used
inside of double quotes; however, there may be times when
hex replacement is easier.
$ man ascii
TIP 29:
Need a WWW Browser for the Terminal Session? Try lynx or elinks.
$ lynx
$ lynx
http://umn.dl.sourceforge.net/sourceforge/souptonuts/How_to_Linux_and_Op
en_Source.txt
$ elinks http://somepage.
http://elinks.or.cz/
TIP 30:
$ s
If you're using the not using the alias command above,
substitute
CTL-a for CTL-p below. :
$ man screen
TIP 31:
$ factor 2345678992
2345678992: 2 2 2 2 6581 22277
$ factor 7867
7867: 7867
TIP 32:
For large "ls" listings try the followin, then, use the arrow key
to move up and down the list.
$ ls /some_large_dir/ | less
or
or
$ less some_large_file
TIP 33:
TIP 34:
$ cat ~/.netrc
machine upload.sourceforge.net login anonymous password
m@temp.com
default login anonymous password user@site
#!/bin/bash
#
# Sample ftp automated script to download
# file to ${dwnld}
#
dwnld="/work/faq/unix-faq"
cd ${dwnld}
ftp << FTPSTRING
prompt off
open rtfm.mit.edu
cd /pub/usenet-by-group/news.answers/unix-faq/faq
mget contents
mget diff
mget part*
bye
FTPSTRING
#!/bin/bash
# ftp sourceforge auto upload ftpup.sh
# Usage: ./ftpup.sh <filename>
#
# machine upload.sourceforge.net user anonymous m@aol.com
ftp -n -u << FTPSTRING
open upload.sourceforge.net
user anonymous m@aol.com
binary
cd incoming
put ${1}
bye
FTPSTRING
TIP 35:
$ echo f{ee,ie,oe,um}
fee fie foe fum
$ mkdir -p /work/junk/{one,two,three,four}
TIP 36:
TIP 37:
Try typing a long command say, then, type "fc" for an easy way
to edit the command.
"fc" will bring the last command typed into an editor, "emacs" if
that's the default editor. Type "fc -l" to list last few commands.
To seach for a command, try typing "CTL-r" at the shell prompt for
searching. "CTL-t" to transpose, say "sl" was typed by you want
"ls".
TIP 38:
$ pushd /etc
$ pushd /usr/local
$ dirs -v
0 /usr/local
1 /etc
2 /work/souptonuts/documentation/theBook
$ pwd
/usr/local
$ pushd +1
$ pwd
/etc
$ dirs -v
0 /etc
1 /work/souptonuts/documentation/theBook
2 /usr/local
TIP 39:
$echo ${UID}_
Compare to
$echo $UID_
TIP 40:
$ r="this is stuff"
$ echo ${r:3}
$ echo ${r:5:2}
Note, ${varname:offset:length}
$ r="new stuff"
$ echo ${r:? "that's r for you"}
new stuff
$ unset r
$ echo ${r:? "that's r for you"}
bash: r: that's r for you
$ unset p
$ p=(one two three)
$ echo -e "${p[@]}"
one two three
or
$ echo -e "${p[*]}"
one two three
$ echo -e "${#p[@]}"
3
$ echo -e "${p[0]}"
one
$ echo -e "${p[1]}"
two
TIP 41:
Loops in Bash
$ path=$PATH:
$ while [ $path ]; do echo " ${path%%:*} "; path=${path#*:};
done
$IFS=:
$ for dir in $PATH
> do
> ls -ld $dir
> done
drwxr-xr-x 2 root root 4096 Jun 10 20:16
/usr/local/bin
drwxr-xr-x 2 root root 4096 Jun 13 23:12
/bin
drwxr-xr-x 3 root root 40960 Jun 12 08:00
/usr/bin
drwxr-xr-x 2 root root 4096 Feb 14 03:12
/usr/X11R6/bin
drwxrwxr-x 2 chirico chirico 4096 Jun 6 13:06
/home/chirico/bin
$ declare -i i
$ i=5;
$ while (( $i > 1 )); do
> i=i-1
> echo $i
> done
4
3
2
$ declare -i
$ while read filename; do echo "- $filename "; done < test |nl
-w1
declare -a Array
Array[0]="zero"
Array[1]="one"
Array[2]="two"
for i in `seq ${#Array[@]}`
do
echo $Array[$i-1]
done
TIP 42:
You have created a program "prog.c", saved as this name and also
copied
to "prog.c.old". You post "prog.c" to users. Next, you make
changes
to prog.c
$ cp /etc/fstab{,.bak}
TIP 43:
$ cat file_of_files
file1
file2
$ cat file1
This is the data in file1
$ cat file 2
This is the data in file2
TIP 44:
$ cat data
1 2 3
4 5
6 7 8 9 10
11 12
13 14
Three columns?
or
$ tr ' ' '\n' < data |xargs -l3|tr ' ' '+'|bc
"Note that tr, sed, and awk mail fail on files containing '\0'
sed and awk have unspecified behaviors if the input
doesn't end in a '\n' (or to sum up, cat works for
binary and text files, text utilities such as sed or awk
work only for text files).
TIP 45:
$ shopt -s cdspell
$ cd /usk/local
^-------- still gets you to --
|
/usr/local
What other options can you set? The following will list
all the options:
$ shopt -p
TIP 46:
$ script -a <filename>
$ script installation
$ (command)
$ (result)
$ ...
$ ...
$ (command)
$ (result)
$ exit
The whole session log is in the installation file that you can
later
read and/or cleanup and add to a documentation.
This command can also be used to redirect the contents to another
user,
but you must be root to do this.
$ w
Step 2 - Run script on that pts. After running this command below
everything you type will appear on their screen.
$ script /dev/pts/4
TIP 47:
Or to filter out port 123 as well getting the full length of the
packet
(-s 0), use the following:
$ tcpdump -i eth0 -nN -vvv -xX -s 0 port not 22 and port not
123
If you're looking for sign of DOS attacks, the following show just
the SYN
packets on all interfaces:
TIP 48:
http://en.tldp.org/
http://www.redhat.com/docs/manuals/enterprise/
TIP 49:
/etc/ld.so.conf
$ ldconfig
TIP 50:
$ cat ./src/test.c
int test(int t)
{
printf("%d\n",t);
return t;
}
$ cat ./src/prog1.c
/*
program: prog1.c
dependences: test.c
$ cat ./include/libpersonal.h
$ cd src
$ gcc -o prog test.c prog1.c -I../include
However, if you want to create your own static library, then, run
the following:
$ mkdir -p ../lib
$ gcc -c test.c -o ../lib/test.o
$ cd ../lib
$ ar r libpersonal.a test.o
$ ranlib libpersonal.a
$ ar rs libpersonal.a test.o
$ cd ../src
$ gcc -I../include -L../lib -o prog1 prog1.c -lpersonal
$ cd ..
$ tree src lib include
src
|-- prog
|-- prog1
|-- prog1.c
`-- test.c
lib
|-- libpersonal.a
`-- test.o
include
`-- libpersonal.h
This was a STATIC library. Often times you will want to use a
SHARED
or dynamic library.
SHARED LIBRARY:
$ cd ../lib
$ gcc -c -fpic ../src/test.c -o test.o
$ cd ../src
$ gcc -Wl,-R../lib -L../lib -I../include -o prog2 prog1.c
-lpersonal
This should work fine. But, take a look at prog2 using the ldd
command.
$ ldd prog2
To fix this, you should specify the direct path to the library. And
in my
case it is rather long
TIP 51:
$ tail -f stuff | \
awk ' /now/ { system("mail -s \"This is working\"
mikechirico@hotmail.com < msg") }'
Or, you can run a program, say get headings on slashdot from the
program "getslash.php" which
runs on "192.168.1.155" with account "chirico". Assuming you have
ssh keys setup, then, the following
will send mail from the output:
See (TIP 80) for scraping the headings on slash dot and how to get
a copy of "getslash.php". If you still
want to use awk:
Note the "\x27" is a quote. Maybe you only want articles dealing
with "Linux":
For $60, you can get a numeric display from "delcom engineering"
that you can send messages and
data to. I get weather information off the internet and send it to
this device.
http://sourceforge.net/projects/delcom/
TIP 52:
To Encrypt:
To Decrypt
$ openssl des3 -d -salt -in file.des3 -out file.txt -k
mypassword
Need to encrypt what you type? Enter the following, then start
typing
and ^D to end.
TIP 53:
Check that a File has Not Been Tampered With: Use Cryptographic
Hashing Function.
$ md5sum file
TIP 54:
When you do the above command you get two certificates. If you copy
past both certificates by taking the following contents include the
begin and end show below:
-----BEGIN CERTIFICATE-----
....
-----END CERTIFICATE-----
#
#
# Sample .fetchmailrc file for Comcast
#
# Check mail every 90 seconds
set daemon 90
set syslog
set postmaster donkey
#set bouncemail
#
# Comcast email is zdonkey but computer account is just donkey
#
poll mail.comcast.net with proto POP3 and options no dns
user 'zdonkey' with pass "somethin35" is 'donkey' here
options ssl sslcertck sslcertpath '/home/donkey/.certs'
smtphost comcast.net
# currently not used
mda '/usr/bin/procmail -d %T'
REFERENCE: http://www.openssl.org/
http://www.catb.org/~esr/fetchmail/fetchmail-
6.2.5.tar.gz
http://www.madboa.com/geek/openssl/
TIP 55:
.
|-- a
| `-- b
| |-- c
| | `-- d
| | |-- file1
| | `-- file2
| `-- x
| `-- y
| `-- file3
`-- newdir
.
|-- a
| `-- b
| |-- c
| | `-- d
| | |-- file1
| | `-- file2
| `-- x
| `-- y
| `-- file3
`-- newdir
`-- a
`-- b
`-- c
`-- d
|-- file1
`-- file2
Note that you can't do this with "cp -r" because you'd pickup
the x directory and its contents.
You probably want to use the "cp --parents" command for directory
surgery, which you need to be very specific on what you cut and
copy.
TIP 56:
$ locate document|xargs ls -l
The "locate" database may only get updated every 24 hours. For
more recent finds,
use the "find" command.
TIP 57:
List only directories, max 2 nodes down that have "net" in the name
Find all, but skip what's in "/CVS" and "/junk". Start from "/work"
Note -regex and -iregex work on the directory as well, which means
you must consider the "./" that comes before all listings.
Here is another example. Find all files except what is under the
CVS, including
CVS listings. Also exclude "#" and "~".
Looking for files changed in the last 24 hours? Make sure you add
the
minus sign "-1", otherwise, you will only find files changed
exactly
24 hours from now. With the "-1" you get files changed from now to
24
hours.
NOTE: if you don't use -type f, you make get "." returned,
which
when run through ls "ls ." may list more than what you
want.
Also you may only want the current directory
http://sourceforge.net/project/showfiles.php?
group_id=79320&package_id=80711
See "TIP 71" for examples of find using the inode feature. " $ find
. -inum <inode> -exec rm -- '{}' \; "
TIP 58:
How do you remove a file that has the name "-". For instance, if
you run the command
"$ cat > - " and type some text followed by ^d, how does the "-"
file get deleted?
$ rm -- -
$ rm -rf ./one
TIP 59:
Giving ownership.
How do you give the user "donkey" ownership to all directories and
files under
"./fordonkey" ?
Only Permit root login -- give others a message when they try to
login.
TIP 61:
Limits: file size, open files, pipe size, stack size, max memory
size
cpu time, plus others.
$ ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
file size (blocks, -f) unlimited
max locked memory (kbytes, -l) unlimited
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 8179
virtual memory (kbytes, -v) unlimited
$ ulimit -f 10
Now try
bozo - maxlogins 1
$ ulimit -Ha
To list soft limits:
$ ulimit -Sa
TIP 62:
If you have multiple blank lines that you want to squeeze down to
one line, then, try the following:
$ cat -s <file>
$ cat -n <file>
$ cat -t <file>
$ cat -e <file>
/* ctlgen.c
Program to generate ctl characters.
Compile:
Run:
cat -v mout
*/
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i;
return 0;
}
TIP 63:
TIP 64:
$ source .bash_profile
With the above command, the user does not have to logout.
TIP 65:
$ [[ -f /etc/passwd ]]
$ echo $?
0
And the following is false, which returns a 1.
$ [[ -f /etc/passwdjabberwisnohere ]]
$ echo $?
1
Sample program "mdo" to show the difference between "$@" and "$*"
#!/bin/bash
function myarg
{
echo "$# in myarg function"
}
echo -e "$# parameters on the cmd line\n"
echo -e "calling: myarg \"\$@\" and myarg \"\$*\"\n"
myarg "$@"
myarg "$*"
echo -e "\ncalling: myarg \$@ and myarg \$* without quotes\n"
myarg $@
myarg $*
The result of running "./mdo one two". Note that when quoted,
myarg "$*",
returns 1 ... all parameters are smushed together as one word.
2 in myarg function
1 in myarg function
2 in myarg function
2 in myarg function
#!/bin/bash
IFS=|
echo -e "$*\n"
IFS=,
echo -e "$*\n"
IFS=\;
echo -e "$*\n"
IFS=$1
echo -e "$*\n"
one,two,three,four,five
one;two;three;four;five
oneotwoothreeofourofive
TIP 66:
Replace all "x" with "y" and all "y" with "x" in file data.
$ cata data
x y
y x
TIP 67:
How does one send and receive Comcast email from a home Linux
box,
which uses Comcast as the ISP, if the local account on the
Linux
box is different from the Comcast email. For instance, the
account on the Linux box is "chirico@third-fl-71" and the
Comcast
email account is "mchirico@comcast.net". Note both the
hostname and
username are different.
So, the user "chirico" using "mutt", "elm" or any email program
would
like to send out email to say "donkey@comcast.net"; yet, donkey
would
see the email from "mchirico@comcast.net" and not
"chirico@third-fl-71"
but chirico@third-fl-71 would get the replies.
http://prdownloads.sourceforge.net/souptonuts/README_COMCAST_EMAIL.txt?
download
TIP 69:
How do you remove just the last 2 lines from a file and save the
result?
Or, as Amos Shapira pointed out, it's much easier with the head
command.
$ head -2 file
How do you remove blank lines, or lines with just spaces and tabs,
saving the origional file as file.backup?
Or, you may want to remove empty spaces and tabs at the end of a
line
Or, you may want to converts dates of the format 01/23/2007 to the
format 2007-01-23. This is MySQL's common date format.
TIP 70:
TIP 71:
$ ls -libt *
Or to check contents
$ find . -inum <inode> -exec cat '{}' \;
Reference:
http://www.faqs.org/ftp/usenet/news.answers/unix-faq/faq/part2
TIP 72:
Reference:
http://www.shelldorado.com/articles/mailattachments.html
TIP 73:
$ strace <program>
$ strace ./topen
TIP 74:
Or, to get the file listing from a package that is not installed
use the
"-p" option.
Note, you can also get specific listing. For example, suppose you
want to view the changelog
$ rpm -K /iso0/Fedora/RPMS/libpcap-0.8.3-7.i386.rpm
/iso0/Fedora/RPMS/libpcap-0.8.3-7.i386.rpm: (sha1) dsa
sha1 md5 gpg OK
$ rpm -qa
To uninstall a package
$ rpm -e
$ rpm -K *.rpm
TIP 75:
#!/bin/bash
set -x
ls
date
+ ls
ChangeLog CVS data test
+ date
Thu Jul 1 20:41:04 EDT 2004
TIP 76:
Using wget.
Grap a webpage and pipe it to less. For example suppose you wanted
to pipe the
contents of all these tips, directly from the web.
$ wget -O -
http://prdownloads.sourceforge.net/souptonuts/How_to_Linux_and_Open_Sour
ce.txt?download|less
TIP 77:
$ /sbin/ifconfig
$ dos2unix file.txt
$ unix2dos unixfile
NOTE: If you're working file DOS files, you'll probably want to use
"zip" instead of "gzip" so users on Windows can unzip them.
TIP 79:
This simple example waits for the input "hi", in some form before
returning, immediately, "hello there!". Otherwise, it will wait for
60 seconds, then, return "hello there!".
#!/usr/bin/expect
set timeout 60
expect "hi\n"
send "hello there!\n"
Reference:
http://www.oreilly.com/catalog/expect/chapter/ch03.html
http://www.cotse.com/dlf/man/expect/bulletproof1.htm
TIP 80:
#!/usr/bin/php -q
<?php
$fileName = "http://slashdot.org/slashdot.xml";
$rss = file($fileName) or die ("Cannot open file $fileName\n");
for ($index=0; $index < count($rss); $index++)
{
echo $rss[$index];
}
?>
http://prdownloads.sourceforge.net/souptonuts/php_scripts.tar.gz?
download
TIP 81:
TIP 82:
http://sourceforge.net/project/showfiles.php?group_id=13897
$ ./configure
$ make
$ make install
http://www.gnu.org/software/mdk/manual/
TIP 83:
Gnuplot [ http://sourceforge.net/projects/gnuplot/ ].
$ gnuplot file
# File /home/chirico/data
#
2005-07-26 1 2.3 3
2005-07-27 2 3.4 5
2005-07-28 3 4 6.6
2005-07-29 4 6 2.5
You can now get a graph of this data running the following:
$ gnuplot file
TIP 84:
$ cat /proc/cpuinfo
processor : 0
vendor_id : GenuineIntel
cpu family : 15
model : 2
model name : Intel(R) Pentium(R) 4 CPU 2.20GHz
stepping : 9
cpu MHz : 2193.221
cache size : 512 KB
fdiv_bug : no
hlt_bug : no
f00f_bug : no
coma_bug : no
fpu : yes
fpu_exception : yes
cpuid level : 2
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic
sep mtrr
bogomips : 4325.37
TIP 85:
#include "colors.inc"
#include "finish.inc"
#include "metals.inc"
#include "textures.inc"
#include "stones.inc"
#include "skies.inc"
camera {
location < 2, 3, -8 >
look_at < 0, 0, 0 >
focal_point <0, 0, 0>
blur_samples 20
}
light_source {
< 0, 10, 0>
color White
area_light <2,0,0>,<0,0,2>, 2, 2
adaptive 1
fade_distance 8
fade_power 1
}
sky_sphere {
S_Cloud3
}
#declare ball1=
sphere {
<3, 2, 0>, 0.5
texture {
T_Silver_1E
pigment {Blue}
}
}
#declare ball2=
sphere {
<3, 1, 0>, 1
texture {
T_Silver_1E
pigment {Green}
}
}
Output_File_Type=P
Width=320
Height=240
Initial_Frame=1
Final_Frame=10
Antialias=true
Subset_Start_Frame=1
Subset_End_Frame=10
Cyclic_Animation=on
TIP 86:
GPG -- GnuPG
Reference: http://www.gnupg.org/documentation/faqs.html
http://codesorcery.net/mutt/mutt-gnupg-howto
http://www.gnupg.org/(en)/download/index.html
(SCRIPT 4) on following link:
http://prdownloads.sourceforge.net/souptonuts/README_common_script_comma
nds.html?download
Generage key:
$ gpg --gen-key
$ gpg --fingerprint
$ gpg --list-keys
Encrypt
$ gpg -r Mike --encrypt sample.txt
$ gpg --list-keys
/home/chirico/.gnupg/pubring.gpg
v------------------ Use this with "0x"
in front -------
pub 1024D/A11C1499 2004-07-15 Mike Chirico
<mchirico@comcast.net> |
sub 1024g/E1A3C2B3 2004-07-15
|
v----------------------------------------------------
$ gpg --send-keys 0xA11C1499
Receving keys:
Special Note: If you get the following error "GPG: Warning: Using
Insecure Memory" , then,
" chmod 4755 /path/to/gpg" to setuid(root)
permissioins on the gpg binary.
NOTE: If using mutt, just before sending with the "y" option, hit
"p" to sign or encrypt.
It's possible to create a gpg/pgp email from the command line. For
a tutorial on this,
reference (SCRIPT 4) at the following link:
http://prdownloads.sourceforge.net/souptonuts/README_common_script_comma
nds.html?download
TIP 87:
Working with Dates: Steffen Beyer has developed a Perl and C module
for working with dates
$ wget http://www.engelschall.com/u/sb/download/pkg/Date-Calc-
5.3.tar.gz
$ tar -xzvf Date-Calc-5.3.tar.gz
$ cd Date-Calc-5.3
$ cp ./examples/cal.c .
$ gcc cal.c DateCalc.c -o mcal
TIP 88:
TIP 89:
ps command in detail
Here are the possible codes when using state "$ ps -e -o state,cmd"
For instance:
$ ps -e -o pid,state,start,time,etime,cmd
...
9946 S 15:40:45 00:00:00 02:23:29 /bin/bash -i
9985 T 15:41:24 00:00:01 02:22:50 emacs mout2
10003 T 15:43:59 00:00:00 02:20:15 emacs NOTES
10320 T 17:38:42 00:00:00 25:32 emacs stuff.c
...
You may want to command below, without the -e, which will give the
process only under the current terminal.
$ ps -o pid,state,start,time,etime,cmd
$ ps -e -o %cpu,pid,state,start,time,etime,%cpu,%mem,cmd|sort
-rn|less
$ ps aux
$ ps aeux
...
chirico 2735 0.0 0.1 4400 1492 pts/0 S Aug04
0:00 -bash USER=chirico LOGNAME=chirico HOME=/home/chirico PATH=/usr/
chirico 2771 0.0 0.0 4328 924 pts/0 S Aug04
0:00 screen -e^Pa -D -R HOSTNAME=third-fl-71.localdomain TERM=xterm S
chirico 2772 0.0 0.6 9476 6352 ? S Aug04
0:54 SCREEN -e^Pa -D -R HOSTNAME=third-fl-71.localdomain TERM=xterm S
chirico 2773 0.0 0.1 4432 1548 pts/1 S Aug04
0:10 /bin/bash STY=2772.pts-0.third-fl-71 TERM=screen TERMCAP=SC|scre
chirico 2797 0.0 0.1 4416 1496 pts/2 S Aug04
0:00 /bin/bash STY=2772.pts-0.third-fl-71 TERM=screen TERMCAP=SC|scre
root 2821 0.0 0.0 4100 952 pts/2 S Aug04
0:00 su -
root 2822 0.0 0.1 4384 1480 pts/2 S Aug04
0:00 -bash
chirico 2862 0.0 0.1 4428 1524 pts/3 S Aug04
0:00 /bin/bash STY=2772.pts-0.third-fl-71 TERM=screen TERMCAP=SC|scre
sporkey 2946 0.0 0.2 6836 2960 ? S Aug04
0:15 fetchmail
chirico 2952 0.0 0.1 4436 1552 pts/5 S Aug04
0:00 /bin/bash STY=2772.pts-0.third-fl-71 TERM=screen TERMCAP=SC|scre
chirico 3880 0.0 0.1 4416 1496 pts/6 S Aug05
0:00 /bin/bash STY=2772.pts-0.third-fl-71 TERM=screen TERMCAP=SC|scre
root 3904 0.0 0.0 4100 956 pts/6 S Aug05
0:00 su - donkey
donkey 3905 0.0 0.1 4336 1452 pts/6 S Aug05
0:00 -bash
donkey 3938 0.0 0.2 6732 2856 ? S Aug05
0:14 fetchmail
chirico 3944 0.0 0.1 4416 1496 pts/7 S Aug05
0:00 /bin/bash STY=2772.pts-0.third-fl-71 TERM=screen TERMCAP=SC|scre
...
$ ps aeuxwwf
The ww option above gives a wide format with all variables. Use the
above command if you plan
to parse through a Perl script. Otherwise, it may be easier to do a
quick read using the command
below, without "ww".
$ ps aeuxf
...
root 2339 0.0 0.1 3512 1444 ? S Dec01
0:00 /usr/sbin/sshd
root 25651 0.0 0.1 6764 1980 ? S Dec23
0:00 \_ /usr/sbin/sshd
chirico 25653 0.0 0.2 6840 2236 ? S Dec23
0:14 \_ /usr/sbin/sshd
chirico 25654 0.0 0.1 4364 1440 pts/4 S Dec23
0:00 \_ -bash USER=chirico LOGNAME=chirico HOME=/home/chirico
chirico 25690 0.0 0.0 4328 920 pts/4 S Dec23
0:00 \_ screen -e^Pa -D -R HOSTNAME=third-fl-71.localdomain
TERM=xterm
root 2355 0.0 0.0 2068 904 ? S Dec01
0:00 xinetd -stayalive -pidfile /var/run/xinetd.pid
...
$ ps -fC emacs
UID PID PPID C STIME TTY TIME CMD
chirico 5049 5020 0 May11 pts/13 00:00:00 emacs -nw Notes
chirico 12368 5104 0 May12 pts/18 00:00:00 emacs -nw
dnotify.c
chirico 19792 18028 0 May13 pts/20 00:00:00 emacs -nw hello.c
chirico 14034 27367 0 18:52 pts/8 00:00:00 emacs -nw
How_to_Linux_and_Open_Source.txt
You may also want to consider using top in batch mode. Here the "-n
1" means refresh once,
and the "b" is for batch. The "fmt -s" is to put it in a more
readable format.
TIP 90:
Learning Assembly.
Once you have written the source, assuming the file is "exit.s", it
can be compiled as follows:
$ as exit.s -o exit.o
$ ld exit.o -o exit
#
#INPUT: none
#
#OUTPUT: returns a status code. This can be viewed
# by typing
#
# echo $?
#
# after running the program
#
#VARIABLES:
# %eax holds the system call number
# (this is always the case)
#
# %ebx holds the return status
#
.section .data
.section .text
.globl _start
_start:
movl $1, %eax # this is the linux kernel command
# number (system call) for exiting
# a program
movl $0, %ebx # this is the status number we will
# return to the operating system.
# Change this around and it will
# return different things to
# echo $?
int $0x80 # this wakes up the kernel to run
# the exit command
After running this program, you can get the exit code.
$ echo $?
0
That is about all it does; but, get the book for more details. The
book is free.
http://savannah.nongnu.org/download/pgubook/
TIP 91:
Creating a sandbox for reiserfstune,debugreiserfs and ACL. Also
see TIP 4.
Assume you have a reisers files system created from a disk file,
which
means you have done something like the following:
Now, you can run reiserfstune. But, first you will need to umount
fs2
# umount /fs2
# reiserfstune ./disk-rfs
# debugreiserfs -J ./disk-rfs
You can recreate the file and delete the loop device.
Now, try working with some of the ACL options - you can only do
this
with the latest kernel and tools -- Fedora Core 2 will work.
Assume you have 3 users, donkey, chirico and bozo2. You can give
everyone rights to this file system as follows:
# setfacl -R -m
d:u:donkey:rwx,d:u:chirico:rwx,d:u:bozo2:rwx /fs2
TIP 92:
SpamAssassin - Setup.
Step 1.
$ su -
Once you have root privileges invoke cpan.
cpan>
Step 2.
Configuration.
$ cat /etc/mail/spamassassin/local.cf
########################################################################
###
#
# rewrite_subject 0
# report_safe 1
# trusted_networks 212.17.35.
#
Step 3.
Update .procmail.
$ cat /home/chirico/.procmailrc
PATH=/bin:/usr/bin:/usr/local/bin
MAILDIR=/var/spool/mail
DEFAULT=/var/spool/mail/chirico
LOGFILE=/home/chirico/MailBAG
MYHOME=/home/chirico
# Must have folder MailTRASH
TRASH=/home/chirico/MailTRASH
# Spamassassin
:0fw
* <300000
|/usr/local/bin/spamassassin
Reference:
http://pm-doc.sourceforge.net/
TIP 93:
$ cat dotfile
digraph g
{
node [shape = record];
TIP 94:
$ cat Makefile
# Compiler flags
sqliteLIB := $(shell ls /usr/local/lib/libsqlite.so)
sqlite3LIB := $(shell ls /usr/local/lib/libsqlite3.so)
# all assumes sqlite and sqlite3 are installed
#
test:
ifeq ("$(sqlite3LIB)","/usr/local/lib/libsqlite3.so")
@echo -e "True -- we found the file"
else
@echo "False -- we did not find the file"
endif
So, if I run make I will get the following output.
$ make
True -- we found the file
TIP 95:
if [ -e /etc/ntp.conf ]
then
echo "You have the ntp config file"
else
echo "You do not have the ntp config file"
fi
Now using an AND condition inside the [ ]. By the way, above, you
can put the "then" on the same line as the if "if [ -e
/etc/ntp.conf ]; then"
as long as you use the ";".
if [ \( -e /etc/ntp.conf \) -a \( -e /etc/ntp/ntpservers \) ]
then
echo "You have ntp config and ntpservers"
elif [ -e /etc/ntp.conf ]; then
echo " You just have ntp.conf "
elif [ -e /etc/ntp/ntpservers ]; then
echo " You just have ntpservers "
else
echo " you have neither ntp.conf or ntpservers"
fi
Example usage.
#!/bin/bash
{
while read num value; do
if [ $num -gt 2 ]; then
echo $value
fi
done
} < somefile
TIP 96:
INITIAL REPOSITORY:
$ mkdir sqlite_examples
$ mkdir sqlite_examples/man
$ mkdir sqlite_examples/testing
$ cd <directory>
$ cvs -d repository_root_directory import -m "Created
directory structure" yoyodyne/dir yoyo start
$ cd sqlite_examples
$ cvs -d /work/cvsREPOSITORY/ import -m 'test SQlite'
sqlite_examples sqlite_examples start
COOL TOOLS:
1. cvsps
2. cvsreport
$ cvsps -f README_sqlite_tutorial.html
TIP 97:
dd delete
u undelete
y yank (copy to buffer)
p/P p before cursor/P after cursor
/stuff/ search
n repeat in same direction
N repeat in opposite direction
/return repeat seach forward
?return repeat seach backward
vim
:split
:split <filename>
:sp <filename>
:split new
set dictionary+=/usr/share/dict/words
set thesaurus+=/usr/share/dict/words
butter<ctl-x><ctl-k><ctl-n>
Contents of script
%s/one/two/g|x
TIP 98:
Using apt-get
$ apt-get update
$ apt-get -s install <pkage> <---- if everything is ok,
then, remove the s
$ dpkg-reconfigure exim4-config
TIP 99:
$ mkdir -p /cdrom
$ mount /dev/cd0a /cdrom
$ cd /cdrom
To add packages
$ pkg_add -v <directory>
$ mkdir -p /home/chirico/cdrom
$ mount /dev/cdrom /home/chirico/cdrom
TIP 100:
References:
http://www.knoppix.net/docs/index.php/BootFloppyHowTo
TIP 101:
$ diction mytext|less
$ diction
This is more text to read and you can do with it
what you want.
(stdin):1: This is more text to read and you [can -> (do not
confuse with "may")] do with it what you want.
DESCRIPTION
Diction finds all sentences in a document, that contain phrases
from a
database of frequently misused, bad or wordy diction. It
further
checks for double words. If no files are given, the document is
read
from standard input. Each found phrase is enclosed in [ ]
(brackets).
Suggestions and advice, if any, are printed headed by a right
arrow ->.
A sentence is a sequence of words, that starts with a
capitalised word
and ends with a full stop, double colon, question mark or
exclaimation
mark. A single letter followed by a dot is considered an
abbreviation,
so it does not terminate a sentence. Various multi-letter
abbrevia-
tions are recognized, they do not terminate a sentence as well.
TIP 102:
/etc/aliases
root: root@main.com
$ newaliases
TIP 103:
Reference: http://go.to/chrony
In the file "/etc/chrony/chrony.conf" add/replace the following
server 146.186.218.60
server 128.118.25.3
server 128.2.129.21
$ /etc/init.d/chrony restart
Shell command:
# chronyc
chronyc> sourcestats
210 Number of sources = 3
Name/IP Address NP NR Span Frequency Freq Skew
Std Dev
========================================================================
b50.cede.psu.edu 2 0 64 0.000 2000.000
4000ms
otc2.psu.edu 2 0 66 0.000 2000.000
4000ms
FS3.ECE.CMU.EDU 2 0 64 0.000 2000.000
4000ms
chronyc>
ZONE="Etc/GMT"
ZONE="America/New York"
Normally the system keep accurate time with the software clock.
TIP 104:
NFS mount
SERVER (192.168.1.182)
$ /etc/init.d/nfs restart
$ cat /etc/exports
/home 192.168.1.171(rw)
/home 192.168.1.71(rw)
/home 192.168.1.0/255.255.252.0(rw)
$ exportfs -rv
If the above does not work or you are not using lokkit
IPTABLES (values in /etc/sysconfig/iptables on SERVER )
# NFS Need to accept fragmented packets and may not have header
# so you will not know where they are coming from
-A INPUT -f -j ACCEPT
-A INPUT -p tcp -m tcp -s 192.168.1.171 -m multiport --dports
111,683,686,685,1026,2049,2219 -j ACCEPT
-A INPUT -p tcp -s 192.168.1.171 -d 0/0 --dport 32765:32768 -j
ACCEPT
-A INPUT -p udp -m udp -s 192.168.1.171 -m multiport --dports
111,683,686,685,1026,2049,2219 -j ACCEPT
-A INPUT -p udp -s 192.168.1.171 -d 0/0 --dport 32765:32768 -j
ACCEPT
-A INPUT -f -j ACCEPT
-A INPUT -p tcp -m tcp -s 192.168.1.71 -m multiport --dports
111,683,686,685,1026,2049,2219 -j ACCEPT
-A INPUT -p tcp -s 192.168.1.71 -d 0/0 --dport 32765:32768 -j
ACCEPT
-A INPUT -p udp -m udp -s 192.168.1.71 -m multiport --dports
111,683,686,685,1026,2049,2219 -j ACCEPT
-A INPUT -p udp -s 192.168.1.71 -d 0/0 --dport 32765:32768 -j
ACCEPT
(Reference: http://nfs.sourceforge.net/nfs-howto/server.html)
and
(Reference: http://nfs.sourceforge.net/nfs-howto/security.html)
CLIENT1 (192.168.1.171)
$ mkdir -p /home2
$ cat /etc/fstab
192.168.1.182:/home /home2 nfs rw 0 0
$ mount -a -t nfs
Reference:
http://nfs.sourceforge.net/nfs-howto/index.html
MONITOR NFS:
$ nfsstat -c
$ nfsstat -s
The following "cat" command is done on the NFS server, and shows
which
clients are mounting. This does not go with examples above. By
the way,
"root_squash" is the default, and means that root access on the
clients is
denied. So, how does the client root get access to these
filesystems? You have
to "su - <someuser>".
$ cat /proc/fs/nfs/exports
# Version 1.1
# Path Client(Flags) # IPs
/home 192.168.1.102(rw,root_squash,sync,wdelay)
/home squeezel.squeezel.com(rw,root_squash,sync,wdelay)
/home 192.168.1.106(rw,root_squash,sync,wdelay)
/home
livingroom.squeezel.com(rw,root_squash,sync,wdelay)
/home 10.8.0.1(rw,root_squash,sync,wdelay)
/home closet.squeezel.com(rw,root_squash,sync,wdelay)
(Reference: http://www.vanemery.com/Linux/NFSv4/NFSv4-no-
rpcsec.html#automount )
TIP 105:
http://www.microsoft.com/canada/smallbiz/sgc/articles/ref_net_ports_ms_p
rod.mspx?pf=true
Firewalling?
http://www.microsoft.com/technet/prodtechnol/windowsserver2003/library/S
erverHelp/428c1bbf-2ceb-4f76-a1ef-0219982eca10.mspx
TIP 106:
Man pages: If man pages are formatting incorrectly with PuTTY, try
editing
the "/etc/man.config" file with the following changes:
TIP 107:
This is how you can run it on the program "a.out" for valgrind
version 2.2.0
With C++ programs with gcc 3.4 and later that use STL, export
GLIBCXX_FORCE_NEW
only when testing to disable memory caching. Remember to enable
for production
as this will have a performance penalty. Reference
http://valgrind.org/docs/FAQ/
TIP 108:
Runlevel Configuring.
The program ntsysv, run as root, gives you a ncurses GUI to what
will
run on your system on boot. The chkconfig program (man chkconfig)
has
the ability to list which programs are set to start on the chosen
run level.
# ntsysv
# chkconfig
# /sbin/service --status-all
Note, you can also set these manually. For example, normally you
will
have files in "/etc/init.d/" that will take parameters like
"start","stop"
"restart".
$ ls /etc/rc3.d/*mysql
/etc/rc3.d/K85mysql
/etc/rc3.d/S85mysql
# cd /etc/rc3.d
# ln -s ../init.d/mysql S85mysql
# ln -s ../init.d/mysql K85mysql
# cd /etc/rc5.d
# ln -s ../init.d/mysql S85mysql
# ln -s ../init.d/mysql K85mysql
Above you can see it's on. Here's how we would have turned this
on with chkconfig.
Reference:
http://www-128.ibm.com/developerworks/linux/library/l-
boot.html?ca=dgr-lnxw99-obg-BootFast
TIP 109:
Reference:
http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?
db=man&fname=/usr/share/catman/p_man/cat3x/fam.z
http://www.devchannel.org/devtoolschannel/04/05/13/2146252.shtml
TIP 110:
http://www.gnu.org/software/libc/manual/html_mono/libc.html
#include <stdio.h>
#include <gnu/libc-version.h>
int main (void)
{
puts (gnu_get_libc_version ());
return 0;
}
TIP 111:
Name: chirico.org
Address: 66.35.250.210
>
$ nslookup - dilbert
>
dig:
dig gives you more information. You should probably use dig
instead
of nslookup.
;; QUESTION SECTION:
;chirico.org. IN A
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 55908
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 2,
ADDITIONAL: 2
;; QUESTION SECTION:
;chirico.org. IN A
;; ANSWER SECTION:
chirico.org. 5538 IN A 66.35.250.210
;; AUTHORITY SECTION:
chirico.org. 30599 IN NS
ns78.worldnic.com.
chirico.org. 30599 IN NS
ns77.worldnic.com.
;; ADDITIONAL SECTION:
ns78.worldnic.com. 16022 IN A 216.168.225.218
ns77.worldnic.com. 7 IN A 216.168.228.41
It's also possible to get all the zone information. The following
command
queries my local dns 192.168.1.71 for the squeezel.com. zone
information.
Reference ( http://www.tldp.org/HOWTO/DNS-HOWTO-5.html )
Also see TIP 223.
TIP 112:
http://prdownloads.sourceforge.net/cpearls/autotools.tar.gz?download
A "Makefile.am" is required:
bin_PROGRAMS = sprog
sprog_SOURCES = sqlite3api.cc
sprog_LDADD = @INCLUDES@ @SQLIBOBJS@
$ aclocal
$ autoconf
$ touch NEWS README AUTHORS ChangeLog
$ automake --add-missing
$ make dist
Note: did you ever want to save all the output from a
./configure? Well, it
is automatically saved in the "config.log" file. In fact,
this file may
contain a lot more than what you saw on the screen.
Also, you may need to rerun ./configure. But before you
do, delete
the "config.cache" file to get a clean build.
TIP 113:
M is the ESC
C or c is the Ctl
Note: if the shell prompt does not show up correctly, then, you
may want to creat a ".emacs_bash"
file with the following contents:
PS1="emacs:\W \$ "
R rename
v view
Z compress the file
+ create directory
c-x l list the line you are on, and how many lines in
the document.
You will get something like: Page has 4881
lines (4440 + 442),
which means you are on the 4440 line.
c-x rb notes
c-x rb emacs
rectangle
---------
C-SPC
goto the next region
C-x
C-x
then, C-x r r "name of register"
macros:
-------
c-x ( start macro
c-x ) end macro
c-x e execute macro
mail:
-----
c-x m mail
c-c c-s send
C-x C-e
(insert "\n\nExtra Line of text")
</body>
</html>")
)
Backspace issues when using "emacs -nw"? They putting the following
in your "~/.emacs" file
TIP 114:
$ ncftpget ftp://ftp.gnu.org/pub/gnu/gcc/gcc-3.2.3/gcc-
3.2.3.tar.gz
$ ncftpget
ftp://ftp.linux.ncsu.edu/pub/fedora/linux/core/3/i386/iso/FC3*
TIP 115:
$ expr 6 + 4
10
$ expr 6+4
6+4
$ expr 10 \* 10
100
$ var1=34
$ expr $var1 + 3
37
or
$ var1=2
$ var1=`expr $var1 \* 2`
$ echo $var1
4
$ mstr="12345"
$ expr length $mstr
5
Regular expressions
$ myexpr="[a-z][1-9]"
$ echo $myexpr
[a-z][1-9]
This may not be the best way to find out if it is Friday, but
it seems to work. It's more of an exercise in xargs.
$ date
Fri Dec 31 16:44:47 EST 2004
$ date|xargs -i expr {} : "[Fri]"
1
TIP 116:
eval
$ mypipe="|"
$ eval ls $mypipe wc
6 6 129
Did you catch that? The above statement is the same as
$ ls | wc
TIP 117:
Note before going through all this trouble, you may find what
you're looking for at the following site:
http://lxr.linux.no/
$ export SRCDIR=/home/src
$ cd $SRCDIR
$ wget http://www.csn.ul.ie/~mel/projects/patchset/patchset-
0.5.tar.gz
$ export PATH=$PATH:$SRCDIR/patchset-0.5/bin
export WWW_USER=nobody
Getting kernel source. The last step builds and asks a lot of
questions. Enter
yes to things that interest you, since this is what you will
see in the source
code. It is not going to build for booting. The "downlaod -p"
is for downloading
a patch.
$ download 2.6.10
$ createset 2.6.10
$ make-kernel -b 2.6.10
$ mkdir -p /home/src/glimpse
$ cd /home/src/glimpse
$ wget http://webglimpse.net/trial/glimpse-latest.tar.gz
$ tar -xzf glimpse-latest.tar.gz
$ cd glimpse-4.18.0
$ ./configure; make
$ make install
$ make -p /home/src/lxr
$ cd /home/src/lxr
$ wget http://heanet.dl.sourceforge.net/sourceforge/lxr/lxr-
0.3.1.tar.gz
$ cd lxr-0.3
$ make install
Apache changes
<Files ~ (search|source|ident|diff|find)>
SetHandler cgi-script
</Files>
</Directory>
# Configuration file.
Now you should be ready to run "make-lxr". Make sure the path
is setup to patchset,
which is repeated here. The last step take awhile.
$ export SRCDIR=/home/src
$ cd $SRCDIR
$ export PATH=$PATH:$SRCDIR/patchset-0.5/bin
$ make-lxr 2.6.10
Now you need to index the source. Below the ./glimpse_* file
will be put in
root. Checkout the -H option if you do not want them here on a
temporary
bases of if you run out of room.
$ mv /root/.glimps_* /var/www/lxr/source/2.6.10/.
$ chown -R nobody.nobody ./.glimpse_*
TIP 118:
exec - you can change standard output and input without starting
a new
process.
$ exec 3>output3
$ ls >& 3
$ exec 3<output3
$ cat <&3
ChangeLog
CVS
How_to_Linux_and_Open_Source.txt
How_to_Linux_and_Open_Source.txt.~1.193.~
mfile
mfile2
mfile3
mftp
output3
$ exec 3>output3
$ exec 4>output4
$ exec 5>output5
$ >&3-
Closing the "input" file descriptor
$ 3<&-
$ lsof -a -p $$ -d 0-10
#!/bin/bash
sleep 1
declare -x n
let n=${n:=0}+1
[ $n -le 5 ] && echo "$n" && exec $0
#!/bin/bash
declare -x N
declare -x n
N=${N:=$(od -vAn -N1 -tu4 < /dev/urandom)}
let n=${n:=0}+1
[ $(($n%2)) -eq 0 ] && echo "She Loves Me!" || echo "She
Loves Me NOT!"
[ $n -lt $N ] && exec $0
TIP 119:
$ who -r
run-level 3 Dec 31 19:02 last=S
$ arch
i686
TIP 120:
$ atq
or
$ at -l
TIP 121:
Creating a Manpage
$ man soup
$ gzip /usr/local/man/man1/soup.1
For plenty of examples look at the other man pages. Also the
following
is helpful. The last one is a tutorial "man 7 mdoc"
$ man manpath
$ man groff
$ man 7 mdoc
TIP 122:
TIP 123:
news.announce.newusers:
comp.lang.c++.moderated! 1-500
comp.unix.programmer! 1-500
comp.unix.shell! 1-500
gnu.emacs.gnus! 1-500
(defun my-message-mode-setup ()
(setq fill-column 72)
(turn-on-auto-fill))
(add-hook 'message-mode-hook 'my-message-mode-setup)
E-x gnus
p previous article
del scroll up
m new mail
a new posting
c Catchup
T T toggle threading
TIP 124:
Note, if you are on the computer you can sometime use the
local loopback.
In fact, sometimes you can only use the local loop back
127.0.0.1 in
place of "bozo.company.com"
TIP 125:
IP forwarding, IP Masquerade
TIP 126:
DESKTOP="KDE"
DISPLAYMANAGER="KDE"
TIP 127:
Have a file and you do not know whay type it is (tar, gz, ASCII,
binary) ?
Use the file command. Below it is used on the file "mftp"
$ file mftp
mftp: Bourne-Again shell script text executable
TIP 128:
http://www.tldp.org/HOWTO/Software-RAID-HOWTO-1.html
http://lists.us.dell.com/pipermail/linux-poweredge/2003-
July/014331.html
Note, you must setup grub for each RAID 1 device. Suppose you
have
2 SCSI drives (sda and sdb). By default grub is setup on sda;
but, you
need to enable it for sdb (/dev/hdb for ide) as follows:
grub>
grub>quit
$ cat /proc/mdstat
$ sfdisk -d /dev/sdb
$ sfdisk -d /dev/sda
$ fdisk -l /dev/sda "This will give general information"
$ fdisk -l "General information for all drives"
Adding raid (assume you want to add the first drive "sda1", or
if it is the second
drive then substitute "sda2" below )
$ cat /proc/mdstat
Personalities : [raid1]
read_ahead 1024 sectors
Event: 12
md0 : active raid1 sda1[0] sdb1[1]
104320 blocks [2/2] [UU]
$ cat /proc/mdstat
Personalities : [raid1]
read_ahead 1024 sectors
Event: 9
md0 : active raid1 sda1[0] sdb1[1]
104320 blocks [2/2] [UU]
$ cat /etc/raidtab
TIP 129:
1. Press 'e'
2. Press 'e' again
3. Append 'single' to the kernel version listing
See
http://linuxgazette.net/107/tomar.html
TIP 130:
TIP 131:
$ chfn
TIP 132:
$ chsh -l
/bin/sh
/bin/bash
/sbin/nologin
/bin/ash
/bin/bsh
/bin/ksh
/usr/bin/ksh
/usr/bin/pdksh
/bin/tcsh
/bin/csh
/bin/zsh
TIP 133:
$ declare -i n
$ n=3#22
$ echo $n
8
Base 16 (hex)
$ declare -i n2
$ n2=16#a
$ echo $n2
10
Base 8 (octal)
$ declare -i n3
$ n3=8#11
$ echo $n3
9 Note 8+1=9
TIP 134:
TIP 135:
TIP 136:
$ mkdir 1
$ dd if=/dev/zero of=disk-image count=40960
40960+0 records in
40960+0 records out
$ cd ..
Step 2: tar the directory and contents to tape. First rewind the
tape. These examples
use /dev/nst0 as the location of the tape. Make sure to
substitute your values
if needed.
$ mt -f /dev/nst0 rewind
$ tar --label="Test 1" --create --blocking-factor=128
--file=/dev/nst0 1
Step 3: Read data from the tape using a block size of 128k. If
you get an I/O error, which
could happend if you used a different blocking factor
above, then, you may need
to increase the bs to 256, or 512 etc. as needed.
$ mt -f /dev/nst0 rewind
$ dd if=/dev/nst0 bs=128k of=testblocksz count=1
0+1 records in
0+1 records out
$ ls -l testblocksz
-rw-r--r-- 1 root root 65536 Feb 9 10:41
testblocksz
$ ls -lh testblocksz
-rw-r--r-- 1 root root 64k Feb 9 10:41
testblocksz
Note above that the size 65536 is equal to 64k. That "h"
switch in "ls" is for
human readable.
Step 5: So what does this tell you? You can now use these numbers
to "dd" files
to tape. But, first tar will be used to create the file
locally.
$ mt -f /dev/nst0 rewind
$ dd if=test.tar bs=64k of=/dev/nst0
Step 7: Now test that it can be read with tar command using
blocking-factor=128.
Note the "t" command in tar is for tell. It will not write
data.
$ mt -f /dev/nst0 rewind
$ tar -tvf /dev/nst0 --blocking-factor=128
V--------- 0/0 0 2005-02-09 10:38:20 Test
1--Volume Header--
drwxr-xr-x root/root 0 2005-02-09 10:34:10 1/
-rw-r--r-- root/root 20971520 2005-02-09 10:34:11
1/disk-image
Step 8: Reading tape data with dd. Most of the time a high "ibs"
input block size
$ mt -f /dev/nst0 rewind
$ dd if=/dev/nst0 of=outfromdd.tar ibs=64k
321+0 records in
41088+0 records out
Go to end of data
$ mt -f /dev/nst0 eod
Previous record
$ mt -f /dev/nst0 bsfm 1
Forward record
$ mt -f /dev/nst0 fsf 1
Rewind
$ mt -f /dev/nst0 rewind
Tell
$ mt -f /dev/nst0 tell
#!/bin/bash
# Program to backup server remotely
# Assume remote server is nis, you are on squeezel
#
# Recover from tape
#
# dd if=/dev/nst0 of=test.tar.gz bs=64k
#
filename="support1.$(date "+%m%d%y%H%M").tar.gz"
DIRTOBACKUP=/var/www
#tar cvzf - $DIRTOBACKUP | ssh root@nis '(mt -f
/dev/nst0 rewind; dd of=/dev/nst0 bs=64k )'
tar cvzf - $DIRTOBACKUP | ssh support1@hamlet "dd
of=/home/support1/backups/${filename} "
#!/bin/bash
# Program to push files to tape
#
#
# Notes on recovering from tape
#
# dd if=/dev/nst0 of=test.tar.gz ibs=64k
# or
# $ ssh root@tapeserver "mt -f /dev/nst0 rewind"
# $ ssh root@tapeserver "dd if=/dev/nst0 ibs=64k"|dd
of=cvs1.tar.gz
#
#
#
# First rewind tape
ssh root@tapeserver 'mt -f /dev/nst0 rewind'
#
# Grab only the last file
file=$(find /home/cvs -iname 'cvs*.tar.gz'|sort|tail -n
1)
dd if=${file}|ssh root@tapeserver 'dd of=/dev/nst0
bs=64k'
TIP 137:
RedirectMatch (.*)\.gif$
http://www.anotherserver.com$1.jpg
If more than one DNS record points to the server, then, it's
possible to redirect based upon which DNS entry was used in
the web query.
dev.mchirico.org
notes.mchirico.org
TIP 138:
STEP 1:
$ mkdir -p /samba/share
STEP 2:
STEP 3:
umount /samba/sales
/bin/mount -t smbfs -o
username=donkey,workgroup=donkeydomain,
password=passw0rk1,port=139,dmask=770,fmask=660,
netbiosname=homecpu //localhost/share /samba/share
TIP 139:
Music on Fedora Core -- How to play music on
http://magnatune.com with "xmms".
$ lspci|grep -i audio
STEP 1:
$ alsamixer
STEP 2:
$ aplay /usr/lib/python2.3/test/audiotest.au
STEP 3:
http://rpmseek.com/rpm-pl/xmms-mp3.html
STEP 4:
TIP 140:
Routing -- getting access to a network 1 hop away. You are
currently on the 192 network
and you want access to the 172.21.0.0 network that
has a computer straddling
the two, with /proc/sys/net/ipv4/ip_forward set to 1.
To undo:
$ netstat -r
References:
http://lartc.org/lartc.html
TIP 141:
TIP 142:
http://prdownloads.sourceforge.net/souptonuts/instructions_boot_system.t
xt
TIP 143:
TIP 144:
$ mount -o remount /
TIP 145:
By the way, with nmap you can specify multiple ports. Below
is an example of multiple ports; but, use the commands above
for Microsoft VPN services.
TIP 146:
Perl and ssh - monitoring systems. The output from ssh can be
parsed. Below is
a simple procedure to just to read the ssh ouput into perl.
#!/usr/bin/perl
#
$pid = open $readme, "ssh root\@hamlet df -lh|" or die "Could
not ssh\n";
while(<$readme>) {
print $_
}
close $readme
#!/usr/bin/perl
#
$pid = open $readme, "ssh root\@hamlet df -lh 2>/dev/null|" or
die "Could not ssh\n";
while(<$readme>) {
print $_
}
close $readme
# Cannot do this!
$pid = open $readme, "|ssh root\@hamlet df -lh 2>/dev/null|"
or die "Could not ssh\n";
#!/usr/bin/perl
@ArrayOfArray = (
[ "ant", "bee" ],
[ "mouse", "mole", "rat" ],
[ "duck", "goose", "flamingo" ],
[ "rose","carnation","sunflower"],
);
for $i ( 0 .. $#ArrayOfArray ) {
for $j ( 0 .. $#{$ArrayOfArray[$i]} ) {
print "Element $i $j is $ArrayOfArray[$i][$j]\n";
}
}
#!/usr/bin/perl
# ./program < /etc/passwd
while(<>){
next unless s/^(.*?):\s*//;
$HoA{$1} = [ split(/:/) ];
}
for $i (keys %HoA ) {
print "$i: @{ $HoA{$i} } \n";
}
http://www.unix.org.ua/orelly/perl/prog3/ch09_01.htm
also
http://www.stonehenge.com/merlyn/UnixReview/
For a quick example on using Perl with SQLite, see the following
links:
http://prdownloads.sourceforge.net/souptonuts/README_sqlite_tutorial.htm
l?download
or
http://freshmeat.net/articles/view/1428/
or
http://www.perl.com/pub/a/1999/09/refererents.html
Standard input for files. This example will read from stdin, or
open a file if given as
an argument, and convert all "<" to "<" and ">" to ">",
which can be handy when
converting text files to html files. Note the "while(<>)" will
take multiple file names
on the command line.
#!/usr/bin/perl
while(<>) {
s/&/&amp;/g;
s/</&lt;/g;
s/>/&gt;/g;
s/</</g;
s/>/>/g;
print;
}
Perl Debugger is very useful for testing commands and works like
an interpreter, just
like python. So to get into the Perl Debugger execute the command
below, "q" to quit.
$ perl -de 0
Shutdown
TIP 148:
$ ac -dyp
TIP 149:
http://smartmontools.sourceforge.net/
$ smartctl -i /dev/hda
$ smartctl -A /dev/hda
TIP 150:
$ wget
http://voxel.dl.sourceforge.net/sourceforge/mavetju/dhcpdump-1.5.tar.gz
$ ./configure
$ make && make install
Once it's installed, you can monitor all dhcp traffic as follows,
if done with root.
The above assumes you are using eth0 (ethernet port 0).
TIP 151:
A sample .ssh/config file (note this must have chmod 600 rights)
## Server1 ##
Host 130.21.19.227
LocalForward 20000 192.168.0.66:80
LocalForward 22000 192.168.0.66:22
HostKeyAlias localhostKey227
TIP 152:
Renaming files - suppose you want to rename all the ".htm" files
to ".html"
The above command will give you "file.1", "file.2" ... "file.6"
TIP 153:
#!/usr/bin/perl
# rename - change filenames
$op = shift;
for (@ARGV) {
$was = $_;
eval $op;
die if $@;
# next line calls built-in function, not the script
rename($was,$_) unless $was eq $_;
}
Also reference:
http://www.unix.org.ua/orelly/perl/prog3/
TIP 154:
R project (http://www.r-project.org)
To start R, just type "R" at the command prompt and "q()" to quit.
Below
2 is raised to powers 0 through 6 and thrown into an array.
$ R
> N <- 2^(0:6)
> N
[1] 1 2 4 8 16 32 64
>
> summary(N)
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.00 3.00 8.00 18.14 24.00 64.00
> N[1:3]
[1] 1 2 4
TIP 155:
ls - listing files by size, with the biggest file listed last
$ ls --sort=size -lhr
TIP 156:
#!/usr/bin/perl
# Copyright (c) GPL 2005 Mike Chirico
# This program deletes old files from several directories
# and within each directory there must be x number of copies
# each y number of bytes
#
sub delete_old_ones {
$directory_and_file=$_[0];
$save_count=$_[1];
$bytes_in_file=$_[2];
# Don't change setting here of '-lt'
$pid = open $readme, "ls -lt $directory_and_file|" or die
"Could not execute\n";
while(<$readme>) {
my @fields = split;
# Make sure we have $save_count good ones with data
if ($fields[4] > $bytes_in_file && $save_count > 0) {
$save_count--;
print "Kept files: $fields[4] $fields[8]\n";
}
# delete the old ones
if ($save_count <= 0 )
{
print "Deleted files: $fields[4] $fields[8]\n";
unlink $fields[8];
}
}
close $readme;
}
@AofA = (
[ "/home/cvs/backups/*.gz", "6",196621 ],
[ "/home/mail/backups/*.gz","5",34 ],
[ "/home/snort/backups/*.gz","2",34 ],
[ "/home/server1/backups/*.gz","2",34 ],
[ "/home/actserver/backups/*.gz","2",34 ],
[ "/home/server2/backups/*.gz","2",34 ],
);
foreach( @AofA ) {
&delete_old_ones($_->[0],$_->[1],$_->[2]);
}
TIP 157:
TIP 158:
Keeping files in sync going both ways. Unlike rsync, this is not a
one way mirror
option.
$ wget http://caml.inria.fr/pub/distrib/ocaml-3.08/ocaml-
3.08.3.tar.gz
$ tar -xzf ocaml-3.08.3.tar.gz
$ cd ocaml-3.08.3
$ ./configure
$ make world
$ make opt
$ make install
$ wget
http://www.cis.upenn.edu/~bcpierce/unison/download/stable/latest/unison-
2.10.2.tar.gz
$ tar -xzf unison-2.10.2.tar.gz
$ cd unison-2.10.2
$ make UISTYLE=text
$ su
# cp unison /usr/local/bin/.
TIP 159:
Dump ext2/ext3 filesystem information with "dumpe2fs". Perform the
mount command
and query away.
$ dumpe2fs /dev/sda1
TIP 160:
$ /usr/sbin/sysreport
$ mkdir -p /root/sos
$ TMPDIR='/root/sos' sosreport -a --batch --no-progressbar
TIP 161:
Key Bindings Using bind. You can bind, say, ctl-t to a command.
"\C-t": ls -l
$ bind -f .inputrc
To unbind use the "-r" option. Single quotes are not needed.
$ bind -r "\C-t"
Getting a list of all bindings can be done as follows, and not this
can be redirected
to the ".inputrc" file for further editing.
TIP 162:
Find device names "sd" or with major number 4 and device name
"tty". Print the
record number NR, plus the major number and minor number.
TIP 163:
Firewall - allow UDP port 514 on the main server that will
receive the logs.
SYSLOGD_OPTIONS="-r -m -0"
Note, the "-r" is to allow remote logging and "-m 0" specifies
that that the syslog process should
not write regular timestamps. I prefer to only write timestamps
for the clients.
*.* @192.168.1.81
RSYSLOG: Are you using rsyslog? If so, the instructions are a big
different. You'll edit /etc/rsyslog.conf
$ModLoad imudp.so
$UDPServerRun 514
TIP 164:
$ kudzu -p
/etc/sysconfig/hwconf
$ lspci
TIP 165:
$ ncftpget ftp://ftp.iu.hio.no/pub/cfengine/cfengine-
2.1.15.tar.gz
$ md5sum cfengine-2.1.15.tar.gz
f03de82709f84c3d6d916b6e557321f9 cfengine-2.1.15.tar.gz
$ ./configure --with-berkeleydb=/usr/local/BerkeleyDB.4.3/lib
$ make
$ make install
$ mkdir -p /var/cfengine/bin
$ mkdir -p /var/cfengine/inputs
$ cp /usr/local/sbin/cf* /var/cfengine/bin
$ cfkey
The command above will write the public and private keys in
"/var/cfengine/ppkeys".
# Lines in /etc/rc.local
/usr/local/sbin/cfexecd
/usr/local/sbin/cfservd
/usr/local/sbin/cfenvd
$ scp /var/cfengine/ppkeys/localhost.pub
root@squeezel.squeezel.com:/var/cfengine/ppkeys/root-
tape.squeezel.com.pub
$ scp
root@squeezel.squeezel.com:/var/cfengine/ppkeys/localhost.pub
/var/cfengine/ppkeys/root-squeezel.squeezel.com.pub
closet.squeezel.com
tape.squeezel.com
$ cfrun squeezel.squeezel.com -v
TIP 166:
# /var/cfengine/inputs/cfagent.conf
#
# You run this with the following:
# cfagent -vK
control:
actionsequence = ( files tidy editfiles )
ChecksumDatabase = ( /var/cfengine/cache.db )
# Below, true to update md5
ChecksumUpdates = ( true )
files:
/home/chirico/deleteme/tripwire checksum=md5
recurse=inf
/home/chirico/deleteme/tripwire/moredata checksum=md5
recurse=inf
#/home/chirico/deleteme/tripwire/compress recurse=inf
include=*.txt acti on=compress
# If the database isn't secure, nothing is secure...
/var/cfengine/cache.db mode=600 owner=root
action=fixall
tidy:
/home/chirico/deleteme/tripwire pattern=*~ recurse=inf
age=0
# You must put an age. 0 runs now.
editfiles:
{ /tmp/testdir/stuff
HashCommentLinesContaining "finger"
AppendIfNoSuchLine "# Edit Change with cfengine "
}
To run the example, execute the following command. The "-K" causes
the lock file to be ignored.
$ cfagent -vK
TIP 167:
Next, create 20M file. Since I have many of these files, I created
a special directory "/usr/disk-img"
# mkdir -p /usr/disk-img
# dd if=/dev/zero of=/usr/disk-img/disk-quota.ext3
count=40960
# mount /quota
# ls -l /quota
lost+found
You'll get errors the first time this is run, because you have no
quota files.
But, run it a second time and you'll see something similiar to the
following:
# ls -l /quota
total 26
-rw------- 1 root root 6144 Jun 14 12:23 aquota.group
-rw------- 1 root root 6144 Jun 14 12:23 aquota.user
drwx------ 2 root root 12288 Jun 14 12:18 lost+found
$ quotaon /quota
If you need to turn off quotas, the command is "quotaoff -a" for
all filesystems. You'll run into
errors if you try to run quotacheck, say "quotacheck -avug" because
this tries to unmount and mount
the filesystem. You need to turn off quotas first "quotaoff
/quota". Note you only need to run
quotacheck once, or when doing maintenance after a system crash.
$ repquota /quota
*** Report for user quotas on device /dev/loop0
Block grace time: 7days; Inode grace time: 7days
Block limits File
limits
User used soft hard grace used soft
hard grace
----------------------------------------------------------------------
root -- 1189 0 0 2 0
0
chirico -+ 93 0 0 4 2
5 6days
Note above that user "chirico" has used 4 on the file limits. This
user has a hard
limit of 5. So when this user tries to create 2 more files (bring
this over the limit of 5)
then he will get the following error as demonstrated below.
$ repquota /quota
*** Report for user quotas on device /dev/loop0
Block grace time: 7days; Inode grace time: 7days
Block limits File
limits
User used soft hard grace used soft
hard grace
----------------------------------------------------------------------
root -- 1189 0 0 2 0
0
chirico -+ 94 0 0 5 2
5 6days
Note the "+" sign above. User "chirico" is above the File soft
limits, and in this case
above the hard limits.
$ cat /etc/quotatab
#
# This is sample quotatab (/etc/quotatab)
# Here you can specify description of each device for user
#
# Comments begin with hash in the beginning of the line
# Example of description
/dev/loop0: This is loopback device
$ warnquota
By the way, if you want to change the grace period, it can only be
done on a filesystem
basis. Not per user.
$ edquota -t
Step 1:
$ whereis quota
whereis quota
quota: /usr/bin/quota /usr/share/man/man1/quota.1.gz
$ rpm -q quota
quota-3.12-5
Step 2:
/dev/VolGroup00/LogVol00 / ext3
defaults,usrquota,grpquota 1 1
LABEL=/boot /boot ext3
defaults 1 2
none /dev/pts devpts
gid=5,mode=620 0 0
none /dev/shm tmpfs
defaults 0 0
none /proc proc
defaults 0 0
none /sys sysfs
defaults 0 0
/dev/VolGroup00/LogVol01 swap swap
defaults 0 0
Step 3:
$ mount -o remount /
Step 4:
$ quotacheck -cugm /
Step 5:
$ quotacheck -avumg
Step 6:
$ edquota -f / chirico
$ edquota -g share
You can see the status of the group quota with the following
command:
$ quota -g share
Step 7:
Step 8:
$ mount
/dev/mapper/VolGroup00-LogVol00 on / type ext3
(rw,usrquota,grpquota)
Step 9:
$ warnquota
Step 10:
#!/bin/sh
# Place this file in /etc/cron.daily
# with rights 0755
/usr/sbin/warnquota
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
/usr/bin/logger -t warnquota "ALERT exited abnormally
with [$EXITVALUE]"
fi
exit 0
References:
http://www.redhat.com/docs/manuals/enterprise/RHEL-4-
Manual/sysadmin-guide/ch-disk-quotas.html
(TIP 6, TIP 186, and TIP 205)
TIP 168:
rdist - remote file distribution client program. You can use this
program in combination with
ssh. This program does more than just copy files. Once a file has
been copied, you can dictate
other actions to be performed. Or you can hold off copying all
together if the destination is
running low on inodes, or disk space.
For the purpose of this example, all commands will been run on
"squeezel.squeezel.com", and the
computers that will be updated are "tape.squeezel.com" and
"closet.squeezel.com". Obviously, you
would substitute your computer names.
# Contents of myDistfile
HOSTS = ( chirico@tape.squeezel.com closet.squeezel.com
)
TIP 169:
TIP 170:
Perl map function. Try the following to get a quick take on this
function,
which increments each value in the array a;
#!/usr/bin/perl
@a = (1,2,3);
map {$_++} @a;
map { print "$_\n" } @a;
or
#!/usr/bin/perl
@a = (1,2,3);
map { print "$_\n"} map {++$_} @a;
And you can easily make modifications, like reversing the order
#!/usr/bin/perl
@a = (1,2,3);
map { print "$_\n"} reverse map {++$_} @a;
#!/usr/bin/perl
@a = (1,2,3);
map { print "$_\n"} reverse grep{ $_ > 3} map {++$_} @a;
#!/usr/bin/perl
@a = (1,2,3);
map { print "$_\n"} reverse grep{ !($_ % 2)} map {++$_} @a;
Reference: http://www-128.ibm.com/developerworks/linux/library/l-
road4.html
TIP 171:
#!/usr/bin/perl
sub test {
local $mval;
while( $mval = shift ) {
print " $mval\n";
}
}
test("one","two","three");
TIP 172:
sshd: 192.168.1.171
TIP 173:
To quick find all instances of ssh running, for user root, execute
the following
command:
Another command command is "pidof" that can tell you how many
processes are running.
This can be useful for detecting DOS attacks.
$ pidof sshd
4783 4781 30008 30006 29888 29886 2246
Crack
http://www.crypticide.com/users/alecm/
Slurpie
http://www.ussrback.com/distributed.htm
TIP 175:
$ chage -M 90 <username>
TIP 176:
$ cat /proc/sys/vm/overcommit_memory
0
page-cluster:
The Linux VM subsystem avoids excessive disk seeks by
reading
multiple pages on a page fault. The number of pages it reads
is dependent on the amount of memory in your machine.
$ cat /proc/sys/vm/page-cluster
3
min_free_kbytes:
This is used to force the Linux VM to keep a minimum number
of kilobytes free. The VM uses this number to compute a
pages_min
value for each lowmem zone in the system. Each lowmem zone
gets
a number of reserved free pages based proportionally on its
size.
$ cat /proc/sys/vm/min_free_kbytes
3831
max_map_count:
This file contains the maximum number of memory map areas a
process
may have. Memory map areas are used as a side-effect of
calling
malloc, directly by mmap and mprotect, and also when loading
shared
libraries.
$ cat /proc/sys/vm/max_map_count
65536
TIP 177:
$ ls /sys/block/hda/queue/iosched
back_seek_max back_seek_penalty clear_elapsed
fifo_batch_expire fifo_expire_async
fifo_expire_sync find_best_crq key_type quantum queued
References: http://lwn.net/Articles/102505/
http://bhhdoa.org.au/pipermail/ck/2004-
September/000961.html
TIP 178:
$ wget http://www.iozone.org/src/current/iozone3_242.tar
$ tar -xf iozone3_242.tar
$ cd iozone3_242/src/current
$ make linux
$ iozone -a
$ ./iozone -a -s 10000 -O
TIP 179:
$ HISTTIMEFORMAT="%y/%m/%d %T "
Defining the environment variable above give you the date/time info
when you
execute history:
$ history
...
175 05/06/30 12:51:46 grep '141.162.' mout > mout2
176 05/06/30 12:51:48 e mout2
177 05/06/30 12:56:59 ls
178 05/06/30 12:57:02 ls
179 05/06/30 12:57:39 ls
180 05/06/30 12:57:49 ls -l
181 05/06/30 13:01:10 history
182 05/06/30 13:01:20 HISTTIMEFORMAT="%y/%m/%d %T "
183 05/06/30 13:01:23 history
...
TIP 180:
$ ls "/lib/modules/$(uname -r)/build/.config"
TIP 181:
$ stty -a
speed 38400 baud; rows 0; columns 0; line = 0;
intr = ^C; quit = ^\; erase = <undef>; kill = <undef>; eof =
^D; eol = <undef>; eol2 = <undef>; start = ^Q;
stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V;
flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr
icrnl ixon -ixoff -iuclc -ixany -imaxbel
opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0
cr0 tab0 bs0 vt0 ff0
isig icanon iexten -echo echoe echok -echonl -noflsh -xcase
-tostop -echoprt echoctl echoke
TIP 182:
Above the web client is on "192.168.1.102". You can see that the
1st server "192.168.1.71" then goes out to
the 2nd server "192.168.1.81" on the second line. The third line
shows the 2nd server "192.168.1.81" responding to
the 1st server, and the forth line passes this data back to the web
client "192.168.1.102".
Note: You can save your current iptables setting with the following
command:
The big advantage is that you can store the counters as well.
TIP 183:
=====================================================================
T 1 2K 1 2K 0 0
0
C 1 0 0
TIP 184:
/* Program p1.c */
#include <stdio.h>
#include <stdlib.h>
t1(int i)
{
printf("t1:%d\n", i);
}
t2(int j)
{
printf("t2:%d\n", j);
}
int main(void)
{
int i, j;
$ gprof -p -b p1
Flat profile:
TIP 185:
/home/chirico/stuff
|-- dirA
`-- dirB
CDPATH=/home/chirico/stuff
Now, no matter what directory you are in if you use the cd command
below
you will automatically move to "/home/chirico/stuff/dirA".
$ cd dirA
CDPATH=/work/cpearls/src/posted_on_sf/:/work/souptonuts/documentation/:/
home/chirico/deleteme/
export PATH CVS_RSH EDITOR JAVA_HOME CDPATH
TIP 186:
Groups - add groups and users to groups. The following shows how to
create the group "share"
and add the user "chirico" to this group. The following
should be done as root, and
assumes the account "chirico" already exits.
$ groupadd share
$ usermod -G share chirico
$ newgrp share
TIP 187:
Step 1:
$ uname -a
Linux closet.squeezel.com 2.6.12-1.1398_FC4 #1 Fri Jul 15
00:52:32 EDT 2005 i686 i686 i386 GNU/Linux
Step 2:
$ wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-
2.6.12.3.tar.gz
$ wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-
2.6.12.3.tar.gz.sign
Step 4:
$ cp "/lib/modules/$(uname -r)/build/.config" .
Step 5:
$ make oldconfig
$ make bzImage
$ make modules
$ make modules_install
$ make install
Step 6:
default=0
timeout=5
splashimage=(hd0,2)/grub/splash.xpm.gz
hiddenmenu
title Fedora Core (2.6.12.3)
root (hd0,2)
kernel /vmlinuz-2.6.12.3 ro
root=/dev/VolGroup00/LogVol00 rhgb quiet
initrd /initrd-2.6.12.3.img
title Fedora Core (2.6.12-1.1398_FC4)
root (hd0,2)
kernel /vmlinuz-2.6.12-1.1398_FC4 ro
root=/dev/VolGroup00/LogVol00 rhgb quiet
initrd /initrd-2.6.12-1.1398_FC4.img
title Fedora Core (2.6.11-1.1369_FC4)
root (hd0,2)
kernel /vmlinuz-2.6.11-1.1369_FC4 ro
root=/dev/VolGroup00/LogVol00 rhgb quiet
initrd /initrd-2.6.11-1.1369_FC4.img
title Other
rootnoverify (hd0,1)
chainloader +1
Step 7:
$ shutdown -r now
Step 8:
$ opcontrol --vmlinux=/home/kernel/linux-2.6.12.3/vmlinux
Now start.
$ opcontrol --start
Using 2.6+ OProfile kernel interface.
Reading module info.
Using log file /var/lib/oprofile/oprofiled.log
Daemon started.
Profiler running.
Shutdown opcontrol.
$ opcontrol --shutdown
Run report.
$ opreport
TIP 188:
Step 1:
Step 2:
Edit /etc/imapd.conf
configdirectory: /var/lib/imap
partition-default: /var/spool/imap
admins: cyrus
sievedir: /var/lib/imap/sieve
sendmail: /usr/sbin/sendmail
hashimapspool: true
# Chirico Commented the below line
# sasl_pwcheck_method: saslauthd
# Because using sasldb
sasl_pwcheck_method: auxprop
sasl_auxprop_plugin: sasldb
# Chirico end change
sasl_mech_list: PLAIN
tls_cert_file: /usr/share/ssl/certs/cyrus-imapd.pem
tls_key_file: /usr/share/ssl/certs/cyrus-imapd.pem
tls_ca_file: /usr/share/ssl/certs/ca-bundle.crt
Step 3:
$ ls -l /etc/sasldb2
-rw-r----- 1 root root 12288 Jul 31 09:50 /etc/sasldb2
Step 4:
Step 5:
mailbox_transport =
lmtp:unix:/var/lib/imap/socket/lmtp
mailbox_transport = cyrus
Restart postfix.
/etc/init.d/postfix restart
Step 6:
$ /etc/init.d/cyrus-imapd restart
Shutting down cyrus-imapd:
[ OK ]
Starting cyrus-imapd: preparing databases... done.
[ OK ]
$ ls -l /var/lib/imap/socket/lmtp
srwxrwxrwx 1 root root 0 Jul 31 10:04
/var/lib/imap/socket/lmtp
Step 7:
Add users. Note, you may have to go back to step 3 to add
them to /etc/sasldb2
as well.
$ su - cyrus
$ cyradm tape.squeezel.com
tape.squeezel.com> cm user.chirico
tape.squeezel.com> quit
Now got back as root, and check that everything was created
correctly.
$ ls /var/spool/imap/c/user/
total 8
drwx------ 2 cyrus mail 4096 Jul 31 10:21 chirico
Step 8:
$ tail /var/log/maillog
$ ls -l /usr/lib/cyrus-imapd/deliver
-rwxr-xr-x 1 root root 846228 Apr 4 18:59
/usr/lib/cyrus-imapd/deliver
So I need to change my /etc/postfix/master.cf as follows:
$ /etc/init.d/postfix restart
$ ls -l /var/spool/imap/c/user/chirico/
total 40
-rw------- 1 cyrus mail 545 Jul 31 10:44 1.
-rw------- 1 cyrus mail 547 Jul 31 10:45 2.
-rw------- 1 cyrus mail 1276 Jul 31 10:45 cyrus.cache
-rw------- 1 cyrus mail 153 Jul 31 10:21 cyrus.header
-rw------- 1 cyrus mail 196 Jul 31 10:45 cyrus.index
Step 9:
Local firewall.
# imap
iptables -A INPUT -p udp -s 192.168.1.0/24 --dport 143
-j ACCEPT
iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 143
-j ACCEPT
Step 10:
HINTS -
"|exec /usr/bin/procmail"
to=<chirico@squeezel.squeezel.com>, relay=cyrus,
delay=0,
status=sent (squeezel.squeezel.com)
TIP 189:
TIP 190:
mutt with imap - assume you have setup imap (see tip 188). Now how
do you configure
your ".muttrc" file to automatically connect,
securely to the IMAP server?
$ cat .muttrc
set spoolfile =
"imaps://chirico:S0m3paSSw0r9@squeezel.squeezel.com/
set imap_force_ssl=yes
set certificate_file=~/.mutt/certificates/72d31154.0
http://souptonuts.sourceforge.net/postfix_tutorial.html
Apache - CGI scripts. There are two ways to enable CGI scripts.
The second method is the
prefered method.
First way, the easy way. Look for the "http.conf" file. On
Fedora Core, this file can be
found under "/etc/httpd/conf/httpd.conf". Edit this file as
follows to make
"http://squeezel.squeezel.com/chirico-cgi/" execute scripts.
Second way, the better way. Instead of doing the above, make
the following change in
"/etc/httpd/conf/httpd.conf".
<Directory /home/chirico/cgi-bin>
Options +ExecCGI
SetHandler chirico-cgi
</Directory>
Running a test script. Now copy the following test script into
the directory "/home/chirico/cgi-bin"
and change the rights to execute for the user running this.
#!/bin/sh
# Save as test.cgi
# chown apache.apache test.cgi
# chmod 700 test.cgi
echo "Content-Type: text/html"
echo
echo "Hello world from user <b>`whoami`</b>! "
TIP 192:
#!/bin/bash
while getopts "ab:cd:" Option
# b and d take arguments
#
do
case $Option in
a) echo -e "a = $OPTIND";;
b) echo -e "b = $OPTIND $OPTARG";;
c) echo -e "c = $OPTIND";;
d) echo -e "d = $OPTIND $OPTARG";;
esac
done
shift $(($OPTIND - 1))
TIP 193:
The following sieve script put all jefferson.edu mail into the
folder jefferson. This assumes that I have already created the IMP
directory, or mail box (INBOX.jefferson), which can be done in mutt
with the "C" command. Below is an example of finding
"jefferson.edu"
anywhere in the header.
Now, from the command propt execute "sieveshell" with the hostname
of the
imap server. My server is squeezel.squeezel.com, so I would execute
the
following:
$ sieveshell squeezel.squeezel.com
connecting to squeezel.squeezel.com
Please enter your password:****
> put jefferson.siv
> activate jefferson.siv
> list
jefferson.siv <- active script
> quit
Note the put brings in the script. And you need to activiate it.
You can activate a sieve script for any user on your system if you
are
root. This is an example of activating a script for user chirico.
Assume
below the root prompt is "#".
You can also automate everything from a bash script. But note after
the -e the commands, and not a file with the commands, follows
within
quotes. This is the script I use for my home system.
#!/bin/bash
sieveshell -a chirico -u chirico -e 'deactivate
delete chirico.siv
put chirico.siv
activate chirico.siv
list
' squeezel.squeezel.com
References:
http://wiki.fastmail.fm/index.php/SieveRecipes
http://www.cyrusoft.com/sieve/#documents
TIP 194:
emacs - editing files remotely with tramp. Tramp comes with the
latest version of emacs.
That means if you're using Fedora core 4, with emacs, you
have tramp. This is
ideal for editing files on remote computers that do not use
emacs.
(require 'tramp)
(setq tramp-default-method "scp")
Find file:/chirico@tape.squeezel.com:test.txt
References:
http://savannah.gnu.org/projects/tramp/
TIP 195:
trusted X11 forwarding - running gnome and KDE both on one screen,
at the same
time securely. The following assumes gnome is running on
the current
computer and "closet.squeezel.com" has KDE
$ ssh -Y closet.squeezel.com
$ startkde
$ ssh -Y closet.squeezel.com
$ gnome-session
First you must allow magic cookies for each server connection.
$ MCOOKIE=$(mcookie)
$ xauth add $(hostname)/unix:1 MIT-MAGIC-COOKIE-1 $MCOOKIE
$ xauth add localhost/unix:1 MIT-MAGIC-COOKIE-1 $MCOOKIE
Again, note that you have to add this for EACH connection. So
if you wanted 2 as well
$ MCOOKIE=$(mcookie)
$ xauth add $(hostname)/unix:2 MIT-MAGIC-COOKIE-1 $MCOOKIE
$ xauth add localhost/unix:2 MIT-MAGIC-COOKIE-1 $MCOOKIE
$ xinit -- :1 vt12
Note, if you do not add the above cookies, you will get the
follow error:
$ ssh -Y closet.squeezel.com
$ gnome-session
Yes, you will get errors about sound and some custom drivers
is the remove
computer has different hardware. After is loads, you can
switch back and
forth between session with (ctl-alt-F12) and (ctl-alt-F7)
TIP 196:
Suspend ssh session - you have just sshed into a computer "ssh -l
user example.com", and you
want to get back to the terminal prompt of the computer you
started with. Escapte, by
default with ssh is "~", so enter "~" followed by "ctl-z" to
suspend.
TIP 197:
TIP 198:
size - determining the size of the text segment, data segment, and
"bss" or uninitialized data segment.
$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Jan 14 2005 /bin/sh -> bash
char s[10];
TIP 199:
Using the at command.
$ cat ./job1
#!/bin/bash
date >> /tmp/job1
The at command is listed below. For queue "-q" names you can only
specify one letter. Here we're using x. The letter determines the
priority with "a" the highest.
$ at -q x -f ./job1 -m 11:54am
job 3 at 2005-10-04 11:54
Now, if you execute the atq command, you'll get the following.
$ atq
3 2005-10-04 11:54 x chirico
$ at -q x -m 12:08pm
at> ls -l
at> who
at> date
at> ^D
$ /etc/init.d/atd status
TIP 200:
lsusb - command will display all USB buses and all devices
connected.
$ lsusb
Bus 005 Device 003: ID 413c:2010 Dell Computer Corp.
Bus 005 Device 002: ID 413c:1003 Dell Computer Corp.
Bus 005 Device 001: ID 0000:0000
Bus 004 Device 001: ID 0000:0000
Bus 003 Device 003: ID 0fc5:1227 Delcom Engineering
Bus 003 Device 002: ID 046d:c016 Logitech, Inc. Optical Mouse
Bus 003 Device 001: ID 0000:0000
Bus 002 Device 001: ID 0000:0000
Bus 001 Device 001: ID 0000:0000
TIP 201:
$ cat /proc/buddyinfo
Node 0, zone DMA 541 218 42 2 0 0
0 1 1 1 0
Node 0, zone Normal 2508 2614 52 1 5 5
0 1 1 1 0
Node 0, zone HighMem 0 1 3 0 1 0
0 0 0 0 0
TIP 202:
arp - Linux ARP kernel moduel. This command implements the Address
Resolution Protocol.
$ arp
Address HWtype HWaddress Flags Mask
Iface
tape.squeezel.com ether 00:50:DA:60:5B:AD C
eth0
squeezel.squeezel.com ether 00:11:11:8A:BE:3F C
eth0
gw.squeezel.com ether 00:0F:66:47:15:73 C
eth0
TIP 203:
So, how does your system react when the load average is above 600.
Have you even seen a
computer with a load average of 600? Well, this could be your
chance.
Reference: http://freshmeat.net/projects/dbench/
$ dbench 34
TIP 204:
TIP 206:
$ accton -h
Usage: accton [-hV] [file]
[--help] [--version]
$ accton /var/account/pacct
Now take a look at this file. It will grow. To see command that
are executed, use the lastcomm command.
$ lastcomm
The above command gives output for all users. To get the data
for user "chirico" execute the following command:
[chirico@big ~]$ sa
30 5.23re 0.00cp 10185k
11 4.83re 0.00cp 8961k ***other
8 0.13re 0.00cp 19744k nagios*
4 0.00re 0.00cp 2542k automount*
3 0.00re 0.00cp 680k sa
2 0.13re 0.00cp 17424k check_ping
2 0.13re 0.00cp 978k ping
TIP 207:
$ cat /proc/acpi/thermal_zone/THM/temperature
temperature: 58 C
TIP 208:
script -f with mkfifo to allow another user to view what you type
in real-time.
Step 1. Create a fifo (first in first out) file that the other
user can view. For this example create the file
/tmp/scriptout
Step 2. Have the second user, voyeur user, cat this file.
Output will block
for them until you complete step 3. The other user, voyer,
is executing the command below.
TIP 209:
$ cd /
$ touch forcefsck
Now reboot the system, and when it comes up fsck will be
forced on the system.
$ shutdown -r now
TIP 210:
Reference: http://sourceforge.net/direct-
dl/mchirico/cpearls/simple_but_common.tar.gz (rand.c)
TIP 211:
Want to find out the speed of your NIC? (Full Duplex or Half),
then use ethtool.
TIP 212:
rpm install hang? You might need to delete the lock state
information.
$ rm -f /var/lib/rpm/__db*
Because sometimes you will run "rpm -ivh somerpm" and it will just
sit
there.
TIP 213:
10.0.0.0/255.0.0.0
10.0.0.0/8
10
<Directory /var/www/html/chirico/>
Order allow,deny
Allow from 10.0.0.0/8 # All 10.
Allow from 192.168.0.0/16 # All 192.168
Allow from 127 # All 127.
</Directory>
Here's an example that only allows access to .html files
and nothing else for a particular directory.
<Directory "/var/www/html/chirico/protected">
Satisfy All
Order allow,deny
Deny from all
<Files *.html>
Order deny,allow
Allow from all
Satisfy Any
</Files>
</Directory>
$ /etc/init.d/httpd reload
TIP 214:
$ cat /proc/sys/fs/file-nr
2030 263 104851
| | \- maximum open file descriptors
| |
| \- total free allocated file descriptors
|
(Total allocated file descriptors since boot)
$ cat /proc/sys/fs/file-max
104851
To change this
(Reference http://www.netadmintools.com/art295.html
and also see the man page for this: man 5 proc )
TIP 215:
Ctrl-Alt-Del will cause an immediate reboot, without syncing dirty
buffers by
setting the value > 0 in /proc/sys/kernel/ctrl-alt-del.
TIP 216:
Redefining keys in X using xev and xmodmap. The program xev, used
in an X window
terminal screen will display information on mouse movements, keys
pressed and
released.
$ xev
Now type shift-4 and you'll notice the event details below:
To get the key back to the dollar, issue the following command.
By the way it's possible to define multiple key codes for a sigle
key. You'll need
to have a key defined as the Mode_switch. Perhaps you'd like to use
the Windows key,
or the key with the Microsoft logo on it, since you're using Linux.
This key is
keycode 115
$ xmodmap -e 'keycode 115 = Mode_switch'
Now you could define 3 values to the shift-4. For this example use
ld, Yen and dollar.
TIP 217:
$ getconf GNU_LIBPTHREAD_VERSION
NPTL 2.3.90
http://en.wikipedia.org/wiki/NPTL
By the way, you can query all system settings with the
following command:
$ getconf -a
TIP 218:
$ import screen.png
KDE has the ability to take screenshots with the command below.
$ ksnapshot
$ xwininfo
Absolute upper-left X: 4
Absolute upper-left Y: 21
Relative upper-left X: 0
Relative upper-left Y: 0
Width: 880
Height: 510
Depth: 24
Visual Class: TrueColor
Border width: 0
Class: InputOutput
Colormap: 0x20 (installed)
Bit Gravity State: NorthWestGravity
Window Gravity State: NorthWestGravity
Backing Store State: NotUseful
Save Under State: no
Map State: IsViewable
Override Redirect State: no
Corners: +4+21 -396+21 -396-493 +4-493
-geometry 880x510+0+0
Now use the import command with the Window id. My example is
shown below.
And to quickly display this image that you just saved, use the
display command.
$ display id.miff
TIP 219:
The following works with Fedora Core 5. Only the users added to the
fuse group can mout
external drives. Below the user chirico is being added to the group
fuse.
$ shutdown -r now
$ mkdir v0
$ sshfs root@v0.squeezel.com:/ v0
$ cd v0
$ ls -l
bin dev home lost+found media mnt opt q
sbin srv tmp var
boot etc lib master_backup misc net proc root
selinux sys usr
$ fusermount -u /home/chirico/v0
Yes, you can mount the filesystem on boot. Below shows an example
entry for /etc/fstab, but
this only allows user on the current system to view what is is
/mnt/v0.
sshfs#root@v0.squeezel.com:/var/log /mnt/v0
fuse defaults 0 0
References:
(http://fuse.sourceforge.net/sshfs.html)
TIP 220:
Note - make sure you have commented out the following line
in /etc/sysconfig/iptables
Or
$ openvpn --remote big.squeezel.com --dev tun1
--ifconfig 10.4.0.2 10.4.0.1
TIP 221:
Reference (http://www.madboa.com/geek/openssl/)
TIP 222:
Above I'm typing m() then hitting return. Note the echo on the next
line followed
by the prompt >. I then enter {.
TIP 223:
Stats on DNS Server. You can get stats on your DNS server.
$ rndc stats
TIP 224:
rocommunity pA33worD
$ /etc/init.d/snmpd restart
Or
$ snmpgetnext -v 1 -c pA33worD localhost sysUpTime
DISMAN-EVENT-MIB::sysUpTimeInstance = Timeticks:
(26452) 0:04:24.52
Reference( TIP 225 shows how to use MRTG for gathering snmp
stats).
http://www.net-snmp.org/tutorial/tutorial-
5/commands/snmpv3.html
TIP 225:
$ cfgmaker --output=/etc/mrtg/v5.squeezel.com \
ifref=ip --global
"workdir:/var/www/html/mrtg/stats"\
pA33worD@v5.squeezel.com
Reference:
http://www.chinalinuxpub.com/doc/www.siliconvalleyccie.com/linux-
hn/mrtg.htm
TIP 226:
Step 1.
Step 2.
Alt-ScrollLock
Ctl-ScrollLock
TIP 227:
$ mount
$ e2fsck -D -f /dev/sda1
TIP 228:
Step 1.
$ cat /etc/sysconfig/network-scripts/ifcfg-bond0
DEVICE=bond0
IPADDR=192.168.1.12
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
USERCTL=no
BOOTPROTO=none
ONBOOT=yes
Step 2.
Modify eth0, eth1 and eth2. Shown below are each one of my
files. Note that
you must comment out, or remove the ip address, netmask,
gateway and hardware
address from each one of these files, since settings should
only come from
the ifcfg-bond0 file above. I've chosen to comment out the
lines, instead of
removing, should I decide to unbond my NICS sometime in the
future.
$ cat /etc/sysconfig/network-scripts/ifcfg-eth0
$ cat /etc/sysconfig/network-scripts/ifcfg-eth1
$ cat /etc/sysconfig/network-scripts/ifcfg-eth2
Step 3.
# bonding commands
alias bond0 bonding
options bond0 mode=balance-alb miimon=100
Step 4.
$ modprobe bonding
Step 5.
$ cat /proc/net/bonding/bond0
Ethernet Channel Bonding Driver: v3.0.3 (March 23,
2006)
References:
http://www.cyberciti.biz/nixcraft/vivek/blogger/2006/04/linux-
bond-or-team-multiple-network.php
Good, well written article describing the steps above.
http://sourceforge.net/project/showfiles.php?
group_id=24692&package_id=146474
Documentation for bonding that can also be found in the kernel
./Documentation/networking/bonding.txt
TIP 229:
TIP 230:
Correct settings for EDT are shown above. Note, the months Mar and
Nov.
You can also run the same command by location.
$ man zic
Reference:
http://www-1.ibm.com/support/docview.wss?
rs=0&q1=T1010301&uid=isg3T1010301&loc=en_US&cs=utf-8&cc=us&lang=en
TIP 231:
Step 1 - Download Qt 4.
$ mkdir -p /home/src/qt
$ wget ftp://ftp.trolltech.com/qt/source/qt-x11-
opensource-src-4.2.2.tar.gz
$ cd /home/src/qt
$ tar -xzf qt-x11-opensource-src-4.2.2.tar.gz
Note, make sure you get the latest version of Qt. When I'm
wrote this it
was 4.2.2. Check for updates.
$ cd /home/src/qt/qt-x11-opensource-src-4.2.2
$ ./configure -static -prefix /home/src/qt/qt-x11-
opensource-src-4.2.2
$ make sub-src
$ PATH=/home/src/qt/qt-x11-opensource-src-4.2.2/bin:$PATH
$ export PATH
$ cd /home/chirico/widgetpaint
$ qmake -project
$ qmake -config release
$ make
TIP 232:
$ ssh -Y user@servertofix
$ system-config-securitylevel
TIP 233:
If you want to tag multiple messages with mutt, use the capital
T, when
in mutt.
T
~A (To tag all messages. Note, enter the tilda "~"
without quotes)
;s (After entering ;s, you'll be asked where to save the
message)
From here you can create a new fold. If you're using IMAP mail
boxes, then
use C to create a mailbox.
(Reference: http://www.mutt.org/doc/manual/manual-4.html )
TIP 234:
Note, the first line will color blue all indexes with
the word Poker. The second operates on the body of the
message.
TIP 235:
TIP 236:
$ biosdecode
SYSID present.
Revision: 0
Structure Table Address: 0x000F0411
Number Of Structures: 1
SMBIOS 2.3 present.
Structure Table Length: 2570 bytes
TIP 237:
TIP 238:
$ cp moduleName.pp /usr/share/selinux/targeted/.
$ cd /usr/share/selinux/targeted/
$ semodule -i moduleName.pp
$ semodule -l
Reference:
http://fedorasolved.org/security-solutions/selinux-module-
building/
If you really get stuck, you may need to relabel all files on
your system.
First edit /etc/selinux/config and set to permissive mode. Next
run the following
command.
$ touch /.autorelabel
TIP 239:
Yum Database Fix-up - you may have done a yum update, then,
inadvertently
killed it. It maybe necessary to rebuild the database.
$ rm /var/lib/rpm/__db*
$ rpm --rebuilddb
$ yum clean all
Note, you may also run into the situation where you need to
reinstall a package
directly. The following example shows how to reinstall the sysstat
package on
fedora 8.
$ wget
http://download.fedora.redhat.com/pub/fedora/linux/releases/8/Everything
/i386/os/Packages/sysstat-7.0.4-3.fc8.i386.rpm
$ rpm -ivh --replacepkgs sysstat-7.0.4-3.fc8.i386.rpm
TIP 240:
Convert Epoch Seconds to the Current Time. Note, some programs like
Nagios list
epoch seconds. Here's a way to do the conversion.
TIP 241:
vmstat - For disk IO subsystem total statistics since last boot use
the -D option
$ vmstat -D
27 disks
2 partitions
2766536 total reads
526906 merged reads
61184034 read sectors
21233780 milli reading
8849711 writes
3719803 merged writes
100480938 written sectors
181253052 milli writing
0 inprogress IO
12854 milli spent IO
The last stat shows 12854 ms spent reading from the disk.
Merged reads and merged writes happen when the kernel tries to
combine requests for contiguous regions on the disk for a
performance
increase.
TIP 242:
TIP 243:
$ ls -d .*
. .bash_logout .config .eggcups .qt .redhat .sqlite_history
.. .bash_history .bashrc .eclipse .emacs
TIP 244:
Summary Report
======================
Range of time in logs: 10/12/2007 10:09:05.572 - 10/24/2007
14:20:01.242
Selected time for report: 10/24/2007 00:00:01 - 10/24/2007
14:20:01.242
Number of changes in configuration: 0
Number of changes to accounts, groups, or roles: 0
Number of logins: 0
Number of failed logins: 0
Number of authentications: 1
Number of failed authentications: 0
Number of users: 1
Number of terminals: 2
Number of host names: 1
Number of executables: 3
Number of files: 0
Number of AVC's: 0
Number of MAC events: 0
Number of failed syscalls: 0
Number of anomaly events: 0
Number of responses to anomaly events: 0
Number of crypto events: 0
Number of process IDs: 105
Number of events: 111
TIP 245:
Postfix - Sender Dependent Relay Host Maps. You would use this
type of setup with Google Apps, where you're supporting
local Linux email accounts with your domain MX record
pointing to Google.
/etc/postfix/main.cf:
sender_dependent_relayhost_maps =
hash:/etc/postfix/sender_relayhost
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_sender_dependent_authentication = yes
/etc/postfix/sender_relayhost:
#format: sender-address relayhost
mchirico@cwxstat.org [cwxstat.org]
zchirico@cwxstat.org [cwxstat.org]
achirico@cwxstat.org [cwxstat.org]
lchirico@cwxstat.org [cwxstat.org]
root@cwxstat.org [cwxstat.org]
/etc/postfix/sasl_passwd:
#email email:password
mchirico@cwxstat.org mchirico@cwxstat.org:89mbup
zchirico@cwxstat.org zchirico@cwxstat.org:PAss8orD
achirico@cwxstat.org achirico@cwxstat.org:P33key
lchirico@cwxstat.org lchirico@cwxstat.org:Dunkin34
root@cwxstat.org zchirico@cwxstat.org:P4rple
References:
http://souptonuts.sourceforge.net/postfix_tutorial.html
http://groups.google.com/group/list.postfix.users/browse_thread/thread/a
4f5ca7e3137b6c3/9d1db8686b1e3ffe?
lnk=st&q=sender_dependent_relayhost_maps#9d1db8686b1e3ffe
TIP 246:
Finding the source from an rpm file, using the audit package as an
example.
$ cat /etc/redhat-release
Fedora release 7 (Moonshine)
#baseurl=http://download.fedora.redhat.com/pub/fedora/linux/updates/
$releasever/SRPMS/
$ wget
http://download.fedora.redhat.com/pub/fedora/linux/updates/7/SRPMS/audit
-1.5.6-2.fc7.src.rpm
You may also want to check for source packages in the following
directory:
/usr/src/redhat/SOURCES
TIP 247:
$ git clone
git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git
linux-2.6
TIP 248:
$ man syscalls
(Reference: http://www.ibm.com/developerworks/linux/library/l-
system-calls/)
TIP 249:
http://rute.2038bug.com/index.html.gz
TIP 250:
$ dmidecode
(Reference: http://www.nongnu.org/dmidecode/)
TIP 251:
$ whatmask 192.168.1.0/25
-----------------------------------------------
TCP/IP NETWORK INFORMATION
------------------------------------------------
IP Entered = ..................: 192.168.1.0
CIDR = ........................: /25
Netmask = .....................: 255.255.255.128
Netmask (hex) = ...............: 0xffffff80
Wildcard Bits = ...............: 0.0.0.127
------------------------------------------------
Network Address = .............: 192.168.1.0
Broadcast Address = ...........: 192.168.1.127
Usable IP Addresses = .........: 126
First Usable IP Address = .....: 192.168.1.1
Last Usable IP Address = ......: 192.168.1.126
$ whatmask 192.168.1.128/25
------------------------------------------------
TCP/IP NETWORK INFORMATION
------------------------------------------------
IP Entered = ..................: 192.168.1.128
CIDR = ........................: /25
Netmask = .....................: 255.255.255.128
Netmask (hex) = ...............: 0xffffff80
Wildcard Bits = ...............: 0.0.0.127
------------------------------------------------
Network Address = .............: 192.168.1.128
Broadcast Address = ...........: 192.168.1.255
Usable IP Addresses = .........: 126
First Usable IP Address = .....: 192.168.1.129
Last Usable IP Address = ......: 192.168.1.254
TIP 252:
TIP 253:
$ cp /usr/share/zoneinfo/US/Eastern /etc/localtime
TIP 254:
You use putty from Windows; but, when you try to run tools like
lokkit, mc, or any Nurses menu on your Linux box the display is
hard to read. To fix this, from Putty, select the following
options (Window/Translation). Now under the box titled "Received
data assumed to be in which character set: choose UTF-8.
TIP 255:
eth0, eth1, or eth10? If you stuck and cannot figure out what
device
your NIC is registering under, perhaps the kernel has loaded from
boot,
then take a look under the following:
Okay, but you want to start at eth0. If fact you can control which
NIC
starts at which device. Here's how.
$ udevinfo -a -p /sys/class/net/eth10
...
looking at device '/class/net/eth10':
KERNEL=="eth10"
SUBSYSTEM=="net"
DRIVER==""
ATTR{addr_len}=="6"
ATTR{iflink}=="8"
ATTR{ifindex}=="8"
ATTR{features}=="0x0"
ATTR{type}=="1"
ATTR{link_mode}=="0"
ATTR{address}=="00:00:24:ca:0a:c2"
ATTR{broadcast}=="ff:ff:ff:ff:ff:ff"
ATTR{carrier}=="1"
...
Take the following information above and create the following file
/etc/udev/rules.d/11-local.rules
KERNEL=="eth*",ATTR{address}=="00:00:24:ca:0a:c2",NAME="eth0"
TIP 256:
Note, even when filling in the .config parameters, you need to use
the ARCH command above if you're compiling on a 64 bit computer
for a 32 bit system.
TIP 257:
TIP 258:
uuidgen
c0bcfac5-286b-4f76-b3a0-bd45adfd65ca
TIP 259:
http://www.pathname.com/fhs/
TIP 260:
Emacs - you have a file where you want to replace the returns
hidden in the document with some other combination.
This is a sample
sentance.
This is a sample\
sentance.
TIP 261:
Step 1:
Step 2:
TIP 262:
Step 1:
Step 2:
$ mkswap /swapfile0
Step 3:
$ swapon /swapfile0
Step 4:
Step 5:
Check that the swap file is working the the free command.
Also,
reboot too to make sure the swap file works on restart and
that
/etc/fstab was correctly configured.
TIP 263:
$ ifconfig br0 up
$ netstat -i
Kernel Interface table
Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK
TX-ERR TX-DRP TX-OVR Flg
br0 1500 0 105139 0 0 0 78613
0 0 0 BMRU
eth0 1500 0 923738 13 370 13 737339
3 0 3 BMRU
eth1 1500 0 143691 0 0 0 166542
4 0 4 BMRU
eth2 1500 0 134115 0 0 0 220353
4 0 4 BMRU
$ iptables -F
$ iptables -A INPUT -i br0 -p tcp --dport 111 -d
192.168.1.120 -m physdev --physdev-is-in -j DROP
$ iptables -A INPUT -i br0 -p udp --dport 111 -d
192.168.1.120 -m physdev --physdev-is-in -j DROP
Now you may want to block certain traffic going through this
router. The example below prevents the device attached on eth2
from sending packets to eth1 on port 111.
Okay, so the above command blocks port 111 from eth2 to eth1. If
you want to block all traffic from a device attached to this
router, you may want to consider using ebtables, which is a layer
2 protocol (operating at a lower level than iptables).
TIP 264:
$ ping soekris10
PING soekris10.squeezel.com (192.168.1.153) 56(84) bytes of data.
64 bytes from soekris10.squeezel.com (192.168.1.153): icmp_seq=1
ttl=64 time=1.89 ms
64 bytes from soekris10.squeezel.com (192.168.1.153): icmp_seq=2
ttl=64 time=0.445 ms
64 bytes from soekris10.squeezel.com (192.168.1.153): icmp_seq=3
ttl=64 time=0.479 ms
64 bytes from soekris10.squeezel.com (192.168.1.153): icmp_seq=4
ttl=64 time=0.458 ms
$ ping soekris10
PING soekris10.squeezel.com (192.168.1.153) 56(84) bytes of data.
64 bytes from soekris10.squeezel.com (192.168.1.153): icmp_seq=1
ttl=64 time=203 ms
64 bytes from soekris10.squeezel.com (192.168.1.153): icmp_seq=2
ttl=64 time=101 ms
64 bytes from soekris10.squeezel.com (192.168.1.153): icmp_seq=3
ttl=64 time=101 ms
You may want to change this setting back to what is was, which
can be done with the following command:
Reference:
http://devresources.linux-
foundation.org/shemminger/netem/example.html
TIP 265:
Consolidate duplicate files via hardlinks. This is a package
that automatically walks through files, on the same filesystem,
looking for duplicates. When a duplicate is found, one file is
chosen as the master and the other duplicate matches link to this
master.
$ mkdir 1
$ mkdir 2
$ echo "stuff here" >1/file1
$ cp 1/file1 2/.
Now, you have two files that are the same; however, the timestamp
does
differ. To see what hard link finds, use the -ncv option. Note (-n)
option
prevents changes from being made.
$ hardlink -ncvv .
Directories 3
Objects 5
IFREG 2
Mmaps 1
Comparisons 1
Would link 1
Would save 4096
Again, no changes have actually been made yet. We can verify this
by looking at
the inodes for the file.
$ ls -i 1 2
1:
12738583 file1
2:
12738584 file1
Okay, let's run the program for real, by taking out the -n
option.
$ hardlink -cvv .
Linked ./1/file1 to ./2/file1, saved 11
Directories 3
Objects 5
IFREG 2
Mmaps 1
Comparisons 1
Linked 1
saved 4096
Now that shows that it ran, and to really confirm, let's look at
the inodes.
$ ls -i 1 2
1:
12738583 file1
2:
12738583 file1
Okay. They are the same. Now if were a very large file, you'd see
a decrease in disk space, since you're only pointing to the
contents
of one file.
Interesting note, if you edit the file with emacs, it will not
save changes in both places. Because the default settings of
emacs save the contents into a new file, you'll only get the
changes made in the file you're editing.
If you had made a soft link (ln -s file1a file2a), then, changing
one file with emacs will change the other ... just an important
point
to note.
TIP 266:
http://dag.wieers.com/home-made/dstat/
TIP 267:
The example above links the regex libary. There are over 70 such
libraries. They can be linked using -lboost_libname, where
libname is the name of the libarary.
TIP 268:
Hardening Red Hat Enterprise Linux 5. The following is a good talk
by Steve Grubb.
http://www.redhat.com/promo/summit/2008/downloads/pdf/hardening-
rhel5.pdf
If that link does not exist, I have a copy of the pdf at the
following:
http://chirico.googlecode.com/svn/trunk/security/hardening-
rhel5.pdf
Also checkout some of the other presentations in the 2008 Red Hat
Summit.
http://www.redhat.com/promo/summit/2008/downloads/
TIP 269:
http://freshmeat.net/projects/iotop/
TIP 270:
$ cat a
1
4
3
$ cat b
4
6
5
TIP 271:
The following is done with the real project banssh on Google Code.
2. Revert back to version N (save version 334). You can pick and
choose
and valid version numbers.
$ svn update
4. This requires write access, but suppose you want to add a tag
for your
release. This example will add release banssh-0.0.3
$ svn list H*
10. To list the log of commits. You may want to pipe the
result to a file.
$ svn log
$ svn info
Path: .
URL: https://banssh.googlecode.com/svn/trunk
Repository Root: https://banssh.googlecode.com/svn
Repository UUID: 554197c9-0241-0830-1070-ccc24ce314de
Revision: 427
Node Kind: directory
Schedule: normal
Last Changed Author: mchirico
Last Changed Rev: 426
Last Changed Date: 2009-02-03 19:48:24 -0500 (Tue, 03 Feb 2009)
$ svn help
TIP 272:
Of course, it's very likely that command from .bashrc will also
get executed on
login, since often .bashrc is called within .bash_profile. Look
for the following
command:
TIP 273:
Port forwarding with ssh and scp. Note the lowercase "p" for ssh
and the
uppercase "P" for scp.
Step 1.
Step 2.
Step 3.
TIP 274:
server001
server002
...
server999
And you need a quick way of generating the list of names, with
numbers below 100 preceded with one or two zeros. Do worry, there
is a one liner to do this.
TIP 275:
Explanation:
$ ionice <PID>
TIP 276:
TIP 277:
TIP 278:
You may have a problem getting you're wireless card working with
Linux. It's
possible you may need to download and compile the driver.
http://www.broadcom.com/support/802.11/linux_sta.php
wget http://www.broadcom.com/docs/linux_sta/hybrid-portsrc-
x86_64-v5_10_91_9.tar.gz
tar -xzf hybrid-portsrc-x86_64-v5_10_91_9.tar.gz
make -C /lib/modules/$(uname -r)/build M=`pwd`
sudo cp wl.ko /lib/$(uname -r)/.
sudo depmod
sudo modprobe wl
TIP 279:
TIP 280:
ctl-shft-backspace
TIP 281:
Error in logs:
##########################################################
Generated by certwatch(1)
Step 1:
Generate new certificate. This will be for 3600 days (about 10
years).
Step 2:
Edit the apache ssl.conf file /etc/httpd/conf.d/ssl.conf
# Server Certificate:
# Point SSLCertificateFile at a PEM encoded certificate. If
# the certificate is encrypted, then you will be prompted for a
# pass phrase. Note that a kill -HUP will prompt again. A new
# certificate can be generated using the genkey(1) command.
#SSLCertificateFile /etc/pki/tls/certs/localhost.crt
SSLCertificateFile /etc/pki/tls/certs/squeel.org.crt
Step 3:
Restart apache
You can still remove both packages using the --allmatches option
TIP 283
Keeping an ssh session alive from the client. Normally you would
need only one of these options.
PROGRAMMING TIP 1:
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int
main (void)
{
int fp,error;
char buf[BUFLEN+1];
return 0;
}
/* end of open.c */
PROGRAMMING TIP 2:
/* start of code
gcc uid_open.c -o uid_open
su
chown root.chirico uid_open
chmod u+s uid_open
exit
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main()
{
int fd;
/* end of code */
PROGRAMMING TIP 3:
PROGRAMMING TIP 4:
http://sourceforge.net/project/showfiles.php?group_id=79066
PROGRAMMING TIP 5:
$ ls -libt *
or
or
Compile:
Reference:
http://prdownloads.sourceforge.net/cpearls/simple_but_common_0.0.14.tar.
gz?download
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int
main (void)
{
int fp,error;
char buf[BUFLEN+1];
if ((fp = open ("\n\n\n\n\n\n\n\n\n", O_RDWR | O_CREAT,
0600)) == -1)
{
fprintf (stderr, "Can't open data: %s\n", strerror
(errno));
return 1;
}
return 0;
**Note, if you want email notification after every 50 new tips have
been
added, then, click on the following link:
https://sourceforge.net/project/filemodule_monitor.php?
filemodule_id=120838
PROGRAMMING TIP 6:
http://prdownloads.sourceforge.net/souptonuts/lemon_examples.tar.gz?
download
PROGRAMMING TIP 7:
#include <iostream>
#include <list>
#include <vector>
#include <iterator>
v.push_back(1);
v.push_back(2);
copy(v.begin(),v.end(),ostream_iterator<int>(cout,"\n"));
l.push_back(23);
l.push_back(12);
copy(l.begin(),l.end(),ostream_iterator<int>(cout,"\n"));
PROGRAMMING TIP 8:
Compile:
g++ -o virtualfunc -Wall -W -O2 -s -pipe virtual_function.cc
Download:
http://prdownloads.sourceforge.net/cpearls/simple_but_common_cpp.tar.gz?
download
*/
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
#include <iterator>
#include <functional>
class Employee {
string first,last;
public:
Employee(const string& fn="John",const string& ln="Smith"):
first(fn),last(ln) {}
virtual void print() const {
cout << "First name: " << first << ", Last name: " << last << endl;
}
virtual ~Employee() {}
};
for_each(subordinates.begin(),subordinates.end(),mem_fun(&Employee::prin
t));
cout << endl << endl;
}
void addstaff(Employee& staff){
subordinates.push_front(&staff);
}
void addstaff(Employee* staff){
subordinates.push_front(staff);
}
};
int main()
{
Employee p0("Lisa","Payne");
Manager m0;
return 0;
}
PROGRAMMING TIP 9:
*/
#include <iostream>
#include <cmath>
using namespace std;
class Point {
public:
static Point rectangular(float x, float y);
static Point polar(float radius, float angle);
float get_x() { return x_; }
float get_y() { return y_; }
private:
Point(float x, float y);
float x_, y_;
};
int main(void)
{
Point p1 = Point::rectangular(5.7,1.2);
Point p2 = Point::polar(5.7,1.2);
cout << "(" << p1.get_x() << ", " << p1.get_y() << ")" << endl;
cout << "(" << p2.get_x() << ", " << p2.get_y() << ")" << endl;
}
/* Copy_constructor_assignment.cc
Copyright (c) 2004 GPL Mike Chirico, mchirico@comcast.net or
mchirico@users.sourceforge.net
Download:
http://prdownloads.sourceforge.net/cpearls/simple_but_common.tar.gz?
download
*/
#include <iostream>
class Name {
public:
char* s;
};
class Table {
Name *p;
size_t sz;
public:
Table(size_t s=15) {
p = new Name[sz=s];
for(size_t i=0; i< sz; ++i) p[i].s="****";
}
Table(const Table &t);
Table& operator=(const Table&);
int prt();
void asgn(char* ts,size_t index);
~Table(){ delete[] p; }
};
int Table::prt()
{
for(size_t i=0; i< sz; ++i) std::cout << p[i].s << " ";
std::cout << std::endl;
return 0;
}
/*
asgn will increase the array of strings, if needed
to size index+1, and add the string ts to position
index.
*/
void Table::asgn(char* ts,size_t index)
{
if(index < sz ) {
p[index].s=ts;
}else if ( index >= sz ){
Name *tp;
tp=p;
p = new Name[index+1];
p[index].s=ts;
sz=index+1;
}
}
int main(void)
{
Table t1;
Table t2(5);
t1=t2;
t1.prt();
t2.prt();
}
/* vector.c --
* Copyright 2009 cwxstat LLC., Elkins Park, Pennsylvania.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
*
* Authors:
* Mike Chirico <mchirico@gmail.com>
*
*/
/*
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
typedef struct
{
char **key;
char **val;
int argc;
} Key_val;
typedef struct
{
char **key;
Key_val **val;
int argc;
} Vec;
Vec *
vecAdd(Vec * c, const char *key, Key_val * val)
{
char *s = NULL;
Key_val *v = NULL;
char **t = NULL;
Key_val **tC = NULL;
v = val;
strcpy(s, key);
if (c == NULL) {
c = (Vec *) malloc(sizeof(Vec));
if (c == NULL)
return NULL;
c->key = NULL;
c->val = NULL;
c->argc = 0;
}
c->argc = c->argc + 1;
t = (char **) realloc(c->key,sizeof(char *) * (long unsigned
int)c->argc);
if (t == NULL)
return NULL;
t[c->argc - 1] = s;
c->key = t;
return c;
}
Key_val *
keyAdd(Key_val * c, const char *key, const char *val)
{
char *s = NULL;
char *v = NULL;
char **t = NULL;
strcpy(s, key);
strcpy(v, val);
if (c == NULL) {
c = (Key_val *) malloc(sizeof(Key_val));
if (c == NULL)
return NULL;
c->key = NULL;
c->val = NULL;
c->argc = 0;
}
c->argc = c->argc + 1;
t = realloc(c->key, sizeof(char *) * (long unsigned int) c-
>argc);
if (t == NULL)
return NULL;
t[c->argc - 1] = s;
c->key = t;
return c;
}
void
pr(Key_val * c)
{
int i;
if (c == NULL)
return;
for (i = 0; i < c->argc; ++i)
printf("%s->%s\n", c->key[i], c->val[i]);
return;
}
void
prV(Vec * c)
{
int i;
if (c == NULL)
return;
for (i = 0; i < c->argc; ++i) {
printf("[%s]=>\n", c->key[i]);
pr(c->val[i]);
printf("\n\n");
return;
}
void
myfree(Key_val * c)
{
if (c == NULL)
return;
int i;
for (i = 0; i < c->argc; ++i) {
free(c->key[i]);
free(c->val[i]);
}
free(c->key);
free(c->val);
free(c);
void
myfreeV(Vec * c)
{
if (c == NULL)
return;
int i;
for (i = 0; i < c->argc; ++i) {
free(c->key[i]);
myfree(c->val[i]);
}
free(c->key);
free(c->val);
free(c);
char *
find(Key_val * c,const char *s)
{
int i;
for (i = 0; i < c->argc; ++i)
if (strcmp(c->key[i], s) == 0)
return c->val[i];
return NULL;
}
/*
Find a particular key_val in a vector given
a vector key.
*/
Key_val *
findK(Vec * c, const char *s)
{
int i;
for (i = 0; i < c->argc; ++i)
if (strcmp(c->key[i], s) == 0)
return c->val[i];
return NULL;
}
int
main(void)
{
Key_val *k = NULL;
Vec *v = NULL;
char *s;
k = NULL;
k = keyAdd(k, "twenty one", "21");
k = keyAdd(k, "twenty two", "22");
k = keyAdd(k, "twenty three", "23");
k = keyAdd(k, "twenty four", "24");
v = vecAdd(v, "TWO", k);
prV(v);
myfreeV(v);
return 0;
}
REFERENCES:
(1) http://www.tldp.org/LDP/abs/html/index.html
(2) http://www.shelldorado.com/ (3)
http://www.faqs.org/ftp/usenet/news.answers/unix-faq/faq/part1
(4) http://www-106.ibm.com/developerworks/library/l-rpm1/
(5) http://www-136.ibm.com/developerworks/linux/ (6)
http://www.gnu.org/manual/manual.html (7) http://fedora.redhat.com/
(8) http://souptonuts.sourceforge.net/chirico/index.php (9)
http://www.faqs.org/faqs/
(10) http://www.faqs.org/docs/linux_network/ (11)
http://www.tml.hut.fi/~viu/linux/sag/sag-0.6.2.html/index.html (12)
http://www.yolinux.com/TUTORIALS/LinuxTutorialSysAdmin.html (13)
http://sed.sourceforge.net/grabbag/scripts/
SUMMARY:
(1)(2)(3) Excellent resource for bash scripts.
(4) rpm resource
(6) GNU Manuals Online
(7)Fedora
(8) Authors Website
(11)(12) System Admin
(13) Excellent source of sed scripts
RECOMMENDED BOOKS:
RECOMMENDED HOWTOS:
CORRECTIONS:
http://www.pixelbeat.org/cmdline.html
http://www.pixelbeat.org/rotagator/linux.tips/rotagator.fortune
http://www.pixelbeat.org/scripts/
ADDITIONAL TUTORIALS
Linux Quota Tutorial This tutorial walks you through implementing disk quotas for
both users and groups on Linux, using a virtual filesystem, which is a filesystem created
from a disk file. Since quotas work on a per-filesystem basis, this is a way to implement
quotas on a sub-section, or even multiple subsections of your drive, without reformatting.
This tutorial also covers quotactl, or quota's C interface, by way of an example program
that can store disk usage in a SQLite database for monitoring data usage over time.
Gmail on Home Linux Box using Postfix and Fetchmail If you have a Google Gmail
account, you can relay mail from your home linux system. It's a good exercise in
configuring Postfix with TLS and SASL. Plus, you will learn how to bring down the mail
safely, using fetchmail with the "sslcertck" option.
Create your own custom Live Linux CD These steps will show you how to create a
functioning Linux system, with the latest 2.6 kernel compiled from source, and how to
integrate the BusyBox utilities including the installation of DHCP. Plus, how to compile
in the OpenSSH package on this CD based system. On system boot-up a filesystem will
be created and the contents from the CD will be uncompressed and completely loaded
into RAM -- the CD could be removed at this point for boot-up on a second computer.
The remaining functioning system will have full ssh capabilities. You can take over any
PC assuming, of course, you have configured the kernel with the appropriate drivers and
the PC can boot from a CD.
SQLite Tutorial This article explores the power and simplicity of sqlite3, first by
starting with common commands and triggers, then the attach statement with the union
operation is introduced in a way that allows multiple tables, in separate databases, to be
combined as one virtual table, without the overhead of copying or moving data. Next, the
simple sign function and the amazingly powerful trick of using this function in SQL
select statements to solve complex queries with a single pass through the data is
demonstrated, after making a brief mathematical case for how the sign function defines
the absolute value and IF conditions.
Lemon Parser Tutorial Lemon is a compact, thread safe, well-tested parser generator
written by D. Richard Hipp. Using a parser generator, along with a scanner like flex, can
be advantageous because there is less code to write. You just write the grammar for the
parser. This article is an introduction to the Lemon Parser, complete with examples.