Sunday, June 27, 2010

Linux Commands

Basics

Files and directories

ls      # Show current directory contents

ls -l $path # Show details about the file or directory
cd $dir # Change current directory to $dir
cd .. # Change current directory to parent directory
pwd # Show current directory path
mkdir $dir # Create a directory
cp $src(s) $dst # Copy $src file(s) to $dst
cp $src(s) $dir # Copy $src file(s) into the directory $dir
mv $src $dst # Move $src to $dst. Also used to rename files.
mv $src(s) $dir # Move a group of files into a directory
rm $file(s) # Remove (delete) files
rmdir $dir(s) # Delete empty directory(s)
rm -rf $dirs(s) # Delete files and/or directory(s) with their contents
> $file # Erase the contents of a file

Copy a hierarchical directory

cp -a $sourceDir $destDir

Backup a hierarchical directory

rsync -a --delete $sourceDir $destDir

1) Sym links, ownership, permissions and hidden files are copied.
2) A trailing "/" on either dir means "contents of".
3) Only the files that need to be copied get copied.
4) Files in the destDir but not in source are deleted.

Change the owner of a file

chown owner file        # owner only

chown owner.group file # owner & group
chown .group file # group only
chown owner. file # owner & group=owner

Change the permissions of a file

chmod changes fileName

The changes are a comma separated list of expressions.
Each expression is of the form:
users+permissions # Add permissions
users-permissions # Remove permissions
The users can be one or more of the letters:
u User (Oner of the file)
g Group (Group of users)
o Others (Everyone else)
OR:
a All (Same as "ugo", the default)
The permissions can be one or more of the letters:
r Read
w Write
x Execute
The user classes are specified in the order
UserGroupOther, with three bits for each to
enable or disable ReadWriteExecute.
Example:
chmod u+rwx,g+rw,o-rwx aFile
Numerical equivalent:
chmod 760 aFile

Show disk usage of current dir or selected dir

 du -s 

Write to stdout

 echo anything

Write to a file

 echo anything >  

Append to a file

 echo anything >>  

Update the modified time for a file

 touch  

Quickly create an empty file

   >  

Show differences between files

   diff -r leftDir rightDir 

Show files that differ without details

   diff -r -q leftDir rightDir 

Trace execution of a shell script

   sh -x  

Monitor additions to a log file

   tail -f  

Make a symbolic link

   ln -s   

List files in color

   ls --color=tty

(Alias this to ls)

List a single column of names only

        ls -1 

List directories only

find -type d -maxdepth 1

(Alias this to lsd)

List files in order of modification time

        ls -lrt 

List all open files and sockets

        lsof 

Run a shell script so it changes the environment

        source .bash_profile (or whatever script you changed) 

Run a command relative to another root file system

        chroot newroot command 

Execute a shell script and echo the commands for debugging

        sh -x yourScript 

Printing

Print a file on the default printer

        lpr myfile 

Print a file on a selected printer

        lpr -P printer myfile 

Show a list of available printers

        lpstat -p 

Show the default printer

        lpstat -d 

Set the default printer for the user

lpoptions -d LaserJet 

Set the default printer for everyone

        lpadmin -d LaserJet 

Show what's on the print queue

        lpq 

Remove a job from the print queue

        lprm nn 

Remove all jobs queued by the user

        lprm - 

Control the printers (has help for commands)

        lpc 

Web interface for CUPS

        http://localhost:631/ 

Configure a remote Windows printer

        Determine the remote printer name:

smbclient -L hostname -U username
(In this case, the printer was called "Deskjet")
1) Device: Windows Printer via Samba
2) URI: smb//administrator:password@sparksvaio/Deskjet
3) Driver: HP New Deskjet Series Cups v1.1 (en)

Configure a local printer-port printer

        Determine the remote printer name:

smbclient -L hostname -U username
(In this case, the printer was called "Deskjet")
1) Device: Parallel Port #1 (Hewlett-Packard HP LaserJet 4000 Series)
2) Driver: HP LaserJet Series CUPS v1.1 (en)

Configure printers on a Linksys print server

        1) Select LPD/LPR Protocol.

2) Device URIs for each port:
lpd://Sc0405b5/L1
lpd://Sc0405b5/L2
3) Select the drivers
HP New Deskjet Series Cups v1.1 (en)
HP LaserJet 4000 Series PS (en)

CUPS directory for manufacturer's ppd files

        /usr/share/cups/model 

CUPS ppd files added by me

        hp4000.ppd.gz

hp970Cse.ppd
These came from the sourceforge project sponsored by HP.
The hp970Cse.pdd requires foomatic which requires a TON of
perl stuff. If you don't want all this, the cup built-in
"New Deskjet" works fine.

Text

Check spelling of a text file

        ispell myFile.txt 

Check spelling of one word: script version

        echo $1 | ispell -a | sed -n -e '/^\&/p' -e '/^\#/p'

Put this expression in a shell script on your PATH.

Cut out part of lines cols n-m

        cut -c n-m path 

Cut out part of lines n-eol

        cut -c n- path 

File systems

Format a floppy disk

        fdformat /dev/fd0H1440

mkfs -t msdos /dev/fd0H1440 1440
When putting ext2 on a floppy, omit the su reserve:
mkfs -t ext2 -m 0 /dev/fd0H1440 1440
Some-but-not-all floppies can be enlarged:
fdformat /dev/fd0u1722

Mount filesystems

        mount -t iso9660 -ro /dev/hdc /mnt/cdrom

mount -t vfat /dev/hda5 /mnt/dos
mount -t ext2 /dev/sda3 /mnt/jazz
mount -t ntfs /dev/hda1 /mnt/nt
mount -t smbfs //sparks750/c /mnt/sparks750
(See fstab below for more smbfs options)
mount -t hfs /dev/sda /mnt/jazz -o afpd -o uid=500
(Currently, the afpd option hangs up the Mac...)
mount -t nfs mac.sparks.com:/root /mnt/macroot
To support nfs mounts, remote system must have /etc/exports:
/root *.sparks.com(rw)

Make and mount 1Meg file system inside a file

        dd if=/dev/zero of=MyDiskImage.ext2 bs=1k count=1000

mkfs -t ext2 MyDiskImage.ext2
mkdir here
mount -t ext2 -o loop MyDiskImage.ext2 here

Make and format a Macintosh filesystem inside a file

        dd if=/dev/zero of=MacDiskImage.hfs bs=1k count=whatever

hformat -l "HD1" MacDiskImage.hfs

Show free space on all drives

        df 

Show details about a linux file system

        tune2fs -l /dev/hdax 

Create an ext3 file system

        mkfs -t ext2 -j /dev/hdax 

Convert ext2 to ext3

tune2fs -j /dev/hdax 

Resize a file system (offline)

        Revert from ext3 to ext2 if necessary (see below)

I have heard that this step is unnecessary.
unmount /dev/hda1
e2fsck -f /dev/hda1
resize2fs /dev/hda1 newSizeInBlocks
mount /dev/hda1 /mnt/point
If newSize is not specified, the file system will grow to
fill the partition.
After shrinking a file system, you can shrink the partition to match.
After growing a partition, you can grow the file system to match.

Revert an ext3 file system to ext2

        umount /dev/hda1        # Unmount the partition

tune2fs -O ^has_journal /dev/hda1 # Turn off journaling
e2fsk -y /dev/hda1 # Check for errors
mount -t ext2 /dev/hda1 /mnt/point # Remount as ext2
cd /mnt/point # Go to root directory
rm -f .journal # Remove the journal
You must update entry in fstab if this is a permanent change.
Ext3 should be reverted to ext2 before resizing.

Convert an ext2 file system to ext3

        tune2fs -j /dev/hda1

Edit fstab to indicate ext3
If this is the root partition, you need to use an initrd to boot.
See redhat documentation for details.

Create and use an encrypted dm_crypt volume

This is the new and prefered way to handle file system encryption.

See the next section on the older "cryptoloop" method.
You need a device to access a whole drive, a partition, a logical
volume or a loopback file. We will use "myDev" for this example.
A new filesystem will be created in this example.
Create a dm_crypt mapping to the device
cryptsetup create mymap mydev
You will be prompted for the passphrase.
The default cipher is AES 256.
Now you can create and mount any normal filesystem:
mkfs -t ext2 /dev/mapper/mymap
mount -t ext2 /dev/mymap /mnt/mymount
When you are finished using the volume:
umount /mnt/mymount
cryptsetup remove mymap
When mounting a previously-created dm_crypt volume:
cryptsetup create mymap mydev
mount /dev/mapper/mydev /mnt/mymount

Create and use an encrypted cryptoloop volume

        This is the older and depricated method for using an encrypted

loopback filesystem. It depends on patched versions of of losetup
that are not part of recent Linux distributions.
First make a big file of random stuff:
dd if=/dev/urandom of=myfile bs=1M count=50
Load the crypto module group and your selected cypher:
modprobe cryptoloop
modprobe cipher-twofish
Mount the file as an encrypted loopback device:
losetup -e twofish /dev/loop0 myfile
You will need to answer these questions:
Available keysizes (bits): 128 192 256
Keysize: 128
Password :
Now you can create and mount any normal filesystem:
mkfs -t ext2 /dev/loop0
mount -t ext2 /dev/loop0 /mnt/myMount
When you are finished using the volume:
umount /mnt/myMount
losetup -d /dev/loop0
To mount a previously-created cryptoloop volume:
mount -t ext2 -o loop,encryption=twofish myfile /mnt/myMount

Parted

Preparation

        Run parted from a boot floppy if you need to resize root.

Unmount other partitions first.
First use df to see how much space is used if you intend
to shrink a working partition.

Partition types (ptype)

        primary, logical, extended 

File system types (ftype)

        ext2, FAT, hfs, linux-swap, ntfs, reiserfs 

Flags

        boot, root, swap, hidden, raid, lvm, lba 

Show the current layout

print 

Resize a partition

        resize minor start end 

Create an unformatted partition

        mkpart ptype start end 

Create a new primary ext2 partition

        mkpartfs ptype ftype start end 

Remove a partition

        rm pnumber 

Change the partition state flag

        set pnumber flag state 

Perform a simple check

        check pnumber 

Make a new partition table (Destroys the whole disk)

        mklabel type 

Label types

        msdos, bsd, mac, pc98, sun, loop

Note: You can match the decimal sizes of adjacent
partitions. Parted takes care of details.

Logical volumes

Terminology

        Physical Volume - A whole disk or a partition on a disk.

Volume Group - A collection of physical volumes.
Logical volume - A "partition" on a Volume Group.

Getting started

        If LVM has never been used on a system, first run

vgscan to create the /dev directory and other structures.
Each partition must have a partition type of 0x8E. (Use fdisk)
(This does not apply if you are using a whole disk.)

Define each physical volume

pvcreate /dev/hdb       # A whole disk

pvcreate /dev/hda3 # A partition
An error may be reported if you try to create a physical
volume from a whole disk that had partitions defined.
To destroy the partition table for a whole disk:
dd if=/dev/zero of=/dev/hdb bs=1K count=1
blockdev --rereadpt /dev/hdb

Create a volume group using several physical volumes

vgcreate myVG /dev/hdb /dev/hda3

Note: If you are using devfs, you must use the whole physical name
not just the symbolic link in /dev. For example:
/dev/ide/host0/bus0/target0/lun0/part1

Extend a volume group by adding another physical volume

        vgextend /dev/myVG /dev/hda5 

Reduce a volume group by removing a physical volume

        vgreduce /dev/myVG /dev/hda3

This can be done live, but you have to make sure all
the extents in use on the physical volume are moved
to another volume. To do this before executing the
command shown above, you would use:
pvmove /dev/hda3

Create a logical volume

        lvcreate --size 200M --name myVol myVG

You can now use this logical volume like a normal partition
mkfs -t ext2 /dev/myVG/myVol
mount -t ext2 /dev/myVG/myVol /mnt/myMP

Extend a logical volume to a specific size

        lvextend --size 12G /dev/myVG/myVol

Does NOT extend the size of the file system!

Extend a logical volume by adding a specific size

        lvextend --size +1G /dev/myVG/myVol

Does NOT extend the size of the file system!

Extend the file system and logical volume at the same time

        e2fsadm --size +2G /dev/myVG/myVol

Sadly, there is no e2fsadm for LVM version 2...

Extend the file system and logical volume (the old way)

        You have to unmount first

umount /mnt/myMP
Grow the volume
lvextend --size +40G /dev/myVG/myVol
Check the filesystem (It makes you do this before the resize)
e2fsck -f /dev/myFG/myVol
Resize the file system to take up all the available space
resize2fs /dev/myVG/myVol

Reduce a file system and logical volume at the same time

        e2fsadm --size -200M /dev/myVG/myVol 

Activate all volume groups at boot time

vgscan

vgchange --available y

Remove a logical volume

        umount /mnt/myMP

lvchange --available n /dev/myVG/myVol
lvremove /dev/myVG/myVol

Remove a volume group

        Make sure all the logical volumes are unmounted!

vgchange --available n /dev/myVG
vgremove /dev/myVG

Snapshots

        A snapshot lets you do a backup of the instantanious state of

a logical volume. You create a snapshot, back it up, and then
delete the snapshot. The state of the snapshot volume is frozen
while you're making the backup, while the original volume keeps
changing.
lvcreate --size 200M --snapshot --name snapVol /dev/myVG/myVol
mount -t ext2 /dev/myVG/snapVol /mnt/snap
rsync -a --delete /mnt/snap/ /mnt/backups/myVol
umount /mnt/snap
lvremove /dev/myVG/snapVol

Diagnostics

        pvscan  # Display all physcial volumes

lvscan # Display all logical volumes
pvdisplay /dev/hda4 # Display the state of a physical volume
vgdisplay /dev/myVG # Display the state of a volume group
lvdisplay /dev/vg1/archVol # Display the state of a logical volume

My server layout

        vgscan

pvcreate /dev/hdb
vgcreate vg1 /dev/hdb
lvcreate --size 30G --name backVol vg1
lvcreate --size 40G --name archVol vg1
lvcreate --size 4G --name tempVol vg1
mkfs -t ext2 -j /dev/vg1/backVol
mkfs -t ext2 -j /dev/vg1/archVol
mkfs -t ext2 /dev/vg1/tempVol
pvcreate /dev/hda4
vgcreate vg2 /dev/hda4
lvcreate --size 5G --name homeVol vg2
lvcreate --size 9G --name wwwVol vg2
lvcreate --size 1G --name spoolVol vg2
lvcreate --size 3G --name tempVol vg2
mkfs -t ext2 -j /dev/vg2/homeVol
mkfs -t ext2 -j /dev/vg2/wwwVol
mkfs -t ext2 -j /dev/vg2/spoolVol
mkfs -t ext2 /dev/vg2/tempVol

Disk drives

Basic hdparm syntax

        hdparm options /dev/hda 

Options

        -c 1    I/O support mode 1 (32 bit)

-c 2 I/O support mode 2 (16 bit)
-c 3 I/O support mode 3 (32 bit & sync)
-m 16 Multi sector count 16 on
-A 1 Enable drive read-ahead
-a 8 Drive read-ahead count
-d 1 DMA On
-u 1 Enable interruptable driver (dangerous)
-X 66 Ultra DMA mode 2 (dangerous, unnecessary)
-X 34 Multiword DMA mode 2 (dangerout, unnecessary)
-S n Spindown time in 5sec tics (0 <= n <= 240)
-t Perform & display drive test results
-T Perform & display Linux disk cache test

Example tuning for my computer

The big Maxtor on the HP has these settings.

I think the PIO mode works best.
hdparm -A 1 -a 8 -m 16 -d 1 -c 2

Boot time settings for hdparm

        /etc/sysconfig/harddisks 

Users

Prompt for new password

passwd 

Change your login shell program

        chsh 

Shut down and reboot or halt

        shutdown -r now

shutdown -h now

Adding or removing users

        useradd userName

userdel name
In Redhat Land, useradd also creates and adds the
new user to a new unique group with the same name.

Adding or removing groups

        groupadd name

groupdel name

Changing passwords

        passwd

passwd user

Adding or removing users from a group

        gpasswd -a user group

gpasswd -d user group

Change all sorts of stuff at once

        usermod loginName \

-g newLoginGroup
-G newGroup1,...,newGroupN
-l newLoginName
-d newHomeDirectory
-u newUID
Using -G, the user will be removed from any group not listed.
Using -l, the user still has their old home directory.
You can't change the login name of a user who is currently logged in.
See man page for more options.

Log into a remote system with no password

        rlogin remoteIP

The .rhosts file must be in the remote login directory.
It contains the ipNames of allowed users.
You can add a local username if not the same as remote.
The .rhosts file must have read privilages only for owner.
/etc/xinetd.d/rlogin must not be disabled.
If you want to rlogin from a root account
/etc/securetty must have an entry for "rlogin".

Processes

Show the current process list

        ps ax 

Kill a process by name

        killall name 

Kill a process by id number

        kill pid 

Kill a process that is being difficult

        kill -s 9 pid 

Run a command in the background

        command & 

Put an active command into the background

        First break with control Z, then

bg

List all the jobs you have running

        jobs 

Bring a job back to the forground

        fg 

Stop a background job

        kill 

Suspend a backgroud job

        stop 

Fix terminal that has fonts garbled by a binary dump

        Just type: V O 

Searching

Find path to an executable file

        which command 

Find and print file names

find adirectoryPath/ -name  

Find and apply a command to each file found

        find path/ -name  | xargs  

Find and apply a command (old way)

        find path -name  -exec  {} \; 

Find a pattern with recursive search and show file names

        find path -name "" -exec grep -l  {} \; 

Find a pattern in any and all files with recursive search

        find path | grep  

Find and and confirm before doing a command

        find path/ -name  -ok  {} \; 

Find a pattern in files

        grep   

Find a pattern in files with recursive search (new way)

        grep -rl   

Time

Update the clock from a time server (Three steps)

        rdate -u -p -s ns.scruz.net # This gets the time and sets system time

hwclock --systohc # Write system time to cmos
hwclock --adjust # Apply a rate adjustment
# The startup scripts normally take care of this:
hwclock --hctosys # Read system time from cmos
The may be --localtime or --utc. For localtime, you
need to have an /etc/localtime file which can be a copy or
link to zoneinfo file. (These are in /usr/share/zoneinfo)

Schedule a command for later execution

        Specific time

at 10:25pm
Relative time
at now + 1 minute
at 4pm + 3 days
A prompt will appear for you to enter commands.
Finish with EOF (control D)
Show your pending jobs:
atq
Remove a job:
atrm

Start a timed server as the master clock (put in rc.local)

        timed -M -F localhost 

Start a timed client

        timed 

Use cron for periodic script execution

        Use a bash script in one of these directories:

cron.daily
cron.hourly
cron.monthly
cron.weekly

Using 'at' from inside a bash script

        at 3am <<-EOF

service tomcat restart
EOF

Audio

Play samples from a file

        play test.wav 

Use 'play' on systems with artsd (such as kde)

        On these systems, /dev/dsp is always tied up by artsd.

Use the artsdsp command to run any program that would
normally access /dev/dsp directly:
artsdsp play test.wav

Record samples to a wav file

        Record a "normal" stereo wav file:

rec -c 2 -f U -r 44100 -s w -v 8.0 test.wav
Options:
-c 2 Two channels (stereo)
-r 44100 Sample rate
-f Sample encoding:
s Signed linear (2's compliment)
u Unsigned linear
U U-law (logarithmic) U.S. standard
A A-law (logarithmic) EU. standard
a ADPCM (Adaptive Differential Pulse-Code Modulation)
i IMA_ADPCM
g GSM
-s Sample size:
b 8 bit bytes
w 16 bit words
l 32 bit long words
f 32 bit floats
d 64 bit floats
D 80 bit IEEE floats
-t File format:
au Sun
cdr CD track
gsm GSM 06.10 Lossy Speech Compression
wav Windows RIFF (Header contains all params)
-v Set the volume
1.0 No change
2.0 Linear increase by 2.0
0.5 Linear decrease by 2.0
8.0 About right to balance with other .wavs
The file format can be specified by giving the file
a matching extension.
ADPCM, IMA_ADPCM & GSM are intended for speech compression.
U-law would be appropriate for music.

Play sounds concurrently

        esdplay

(Some people make this an alias for 'play')

Reroute microphone through esd

        esdrec | esdcat 

Play an mp3 file

        mpg123 yourfile.mp3 

Convert an mp3 file to a wav

        mpg123 -s yourfile.mpg > yourfile.raw

The above command will display the bit rate and the sample rate.
The output is 16 bit, signed pcm, little endian. No header.
sox -c 2 -w -s -r xxx yourfile.raw yourfile.wav
The xxx value must be the sample rate displayed by mpg123.
You can pipeline mpg123 into sox. Use a - for the sox input.
An easier way to do both steps:
lame --decode yourfile.mp3 yourfile.wav

Use sox to play (almost) any sound file

sox inputOptions inputFile outputOptions outputFile

Do a "man soxexam" to see many examples.
Format options
Channels
-c n Where n = 1,2 or 4
Sample rate
-r rate Where rate is in Hertz
Sample size
-b 8 bits
-w 16 bits
-l 32 bits
Encoding
-s Signed linear
-u Unsigned linear
-U U-law (U.S. logarithmic)
-A A-law (Euro logarithmic)
-a ADPCM (Adaptive pulse-code modulation)
-i IMA_ADPCM
-g GSM
-f Floating point
Input file format is controled by the file extension:
.wav (You don't need to specify other options)
.au (Options may or may not be needed)

Convert a wav to an mp3

        lame [-b bitrate] infile.wav outfile.mp3 

CDs

Using cdrecord with non-scsi drives

        The primary tool described in the following sections is "cdrecord".

The most current versions of this program accept normal Linux
CD device names, e.g. "/dev/cdrom" and support both SCSI and
ATAPI drives.
Earlier versions of cdrecord only worked with SCSI drives and
required the bizarre "x,y,z" drive name notation.

Create a data CDR readable by Linux (-r) or Windows (-J)

        nice --18 mkisofs -l -J -r -V MyVolumeName sourceDirectory/ \

| cdrecord speed=x dev=/dev/cdrom -data -
To make a CDRW, add blank=fast to cdrecord options.
Speed should be 8 for CDRs and 4 for CDRW on my HP 9200.

Create an ISO image file from a directory of files

        mkisofs -l -r -J -V MyVolumeName -o myISOfile.iso.bin sourceDirectory/ 

Copy a raw DATA CD at the sector level. Source is on /dev/cdrom

        cdrecord -v dev=/dev/cdrom speed=2 -isosize /dev/cdrom 

Make a normal audio cd with tracks taken from mp3 files

        mpg123 -s file1.mp3 \

| cdrecord speed=x dev=/dev/cdrom -audio -pad -swab -nofix -

Fixate the CD

cdrecord dev=/dev/cdrom -fix 

Rip a music CD track

        cdparanoia [-d device] trackRange result.wav 

Rip all the tracks on an audio cd to a set of wav files

        One wav per track:

cdparanoia 1- -B

Rip and convert one track to one mp3

        cdparanoia trackNumber - | lame -b 160 - result.mp3 

Record an audio cd from a directory full of wav files

        One wav per track:

cdrecord speed=s dev=/dev/cdrom -audio *.wav

Track range examples

        1-      # Entire CD

-- -3 # Beginning through track 3
2-4 # Tracks 2 through 4

Create a CDR from an ISO image

        cdrecord speed=4 dev=/dev/cdrom -data imageFile.iso.bin

For cdrw, add: blank=fast

Create an ISO image file from a CD

        readcd dev=/dev/cdrom f=myImageFile.iso.bin 

Dealing with older versions of cdrecord

        Older versions of cdrecord require scsi drivers or

scsi emulation with atapi drives. The following sections
show how to deal with this situation.

Make your ide cdrom look like a scsi device

The cdrecord program wants to see scsi devices:

The cdrom module must be loaded first, but it will
normally be loaded if it was operating in ide mode.
Otherwise, do an "insmod cdrom" first.
rmmod ide-cd
insmod cdrom
insmod sr_mod
insmod ide-scsi
The scsi-mod will be loaded if you have
a real scsi interface in your machine.
Otherwise, # it must be loaded before sr_mod.

Restore the cd to normal (IDE) operation

        rmmod sr_mod ide-scsi

insmod ide-cd

Make atapi cd drives look like scsi at boot time

        For this example, assume you have two ide drives:

hdc and hdd.
Method 1: Add this line in lilo.conf to the kernel section:
append="hdc=ide-scsi hdd=ide-scsi"
Method 2: Add these lines to /etc/modules.conf:
options ide-cd ignore=hdc
options ide-cd ignore=hdd
pre-install sg modprobe ide-scsi
pre-install sr_mod modprobe ide-scsi
pre-install ide-scsi modprobe ide-cd

Devices for the cd drives in scsi mode

/dev/scd0       cdram

/dev/scd1 cdrom
/dev/scd1 dvd

Device names for cd drives in ide mode

        /dev/hdc        cdram

/dev/hdd cdrom
/dev/hdd dvd

List all SCSI devices visible to cdrecord in x,y,z format

        The cdrecord program will use "dev=x,y,z" notation where x,y,z are

shown by the command:
cdrecord -scanbus

Firewire

Load the firewire packet module

        modprobe ieee1394 

Load the firewire card controller

        modprobe ohci1394

The ohci module will recognize your disk as a SCSI device
and automatically load the serial bus protocol (sbp2) module.
If you need to see what's going on for debugging, do a
tail -f /var/log/messages in another shell window before
you load the module.

Scan the bus for the SCSI address

        cdrecord --scanbus

Mine was at SCSI addresss 2,0,0 so it is /dev/sdb.
If the result had been 1,x,y it would be on /dev/sda.

Use fdisk to find the partition name

        fdisk /dev/sdb

I found the DOS partition on the ipod at /dev/sdb2

Create a mount point

        mkdir /mnt/ipod 

Mount the device by hand

        mount -t vfat /dev/sb2 /mnt/ipod 

Example fstab entry

        /dev/sb2 /mnt/ipod vfat noauto 0 0 

Mount the device when an fstab entry exists

        mount /mnt/ipod 

Before you remove the device!

        umount /mnt/ipod

rmmod sbp2
After the rmmod, the iPod will tell you that
it's ok to disconnect. This precaution should
be observed before unplugging any firewire disk.

Remounting (With firewire and ohci already loaded)

        modprobe sbp2

mount /mnt/ipod

Wine

Changes in /etc/wine/wine.conf

        [Drive C]

"Path" = "/mnt/win"
[wine]
# In this section, change all the paths: substituting
# winnt for windows if that applies to your windows
# installation mounted at /mnt/win
# iPod support for EphPod
[Drive G]
"Path" = "/mnt/ipod"
"Type" = "hd"
"Label" = "iPod Drive"
"Filesystem" = "win95"
# To share EphPod config file with windows
# Drive E is where Windows sees the server
[Drive H]
"Path" = "/mnt/server"
"Type" = "network"
"Label" = "Server"
"Filesystem" = "win95"

Security

Use RPM to verify all packages

        rpm -Va

The code letters:
S file Size differs
M Mode differs (includes permissions and file type)
5 MD5 sum differs
D Device major/minor number mis-match
L readLink(2) path mis-match
U User ownership differs
G Group ownership differs
T mTime differs
c A configuration file
A streamlined report that ignores date-only changes:
rpm -Va | grep -v ".......T"
To make this a cron job that mails the result:
rpm -Va | grep -v ".......T" | mail myself@mydomain
To skim off acceptable changes
rpm -Va | grep -v ".......T" | grep -vf rpmChanges | \
mail myself@mydomain
Append any new acceptable changes to the rpmChanges file.

Services

Control individual services

        service  

Typical selectors are: start, stop, restart, status.
If you run the command without a selector, it will display
a list of possible selectors.

Standard run levels identify groups of system services

        0       Halt

1 Single user
2 Multiuser, no networking, local additions
3 Multiuser, networking, local additions
4 Multiuser, networking, no local additions
5 Same as 3 plus X Windows Login
6 Reboot

Change the run level of the system immediately

        telinit newLevelNumber

Each runlevel has an associated list of services that should
be stopped or started. These services are configured using
the chkconfig command described below.

Change the run level the system will use after reboot

        This is done by editing the file:

/etc/inittab
Inside, you will find an expression that looks like this:
id:3:initdefault::
In the example shown above, "3" is the run level used at boot time.
If you wanted to have an X-Windows splash screen with a login dialog,
you would change this number to "5".

Configuring runlevels

        For each runlevel, we need to specify which services start and which

services should shut down. We also need to specify the order in which
services start or shut down to allow for interdependencies.
A collection of directories and symbolic links are used to perform
these functions. A directory exists for each run level X:
/etc/rc.d/rcX.d
Each run level directory contains symbolic links. The links all
point to the service control files found in:
/etc/rc.d/init.d
The name of the link begins with the letter "S" if the service
should start. The name of the link begins with "K" if the service
should be stopped (Killed.)
The link names also determine order of starting or stopping:
Following the S or K is a two-character integer that determines
the order of execution relative to the other links in the directory.
Higher numbers make the service start later.
After the ordering digits, the service name appears. For example,
the following link will start networking at relative step 10 of
runlevel 3:
/etc/rc.d/rc3.d/S10network
Networking gets turned off in runlevel 1, so we find this link:
/etc/rc.d/rc1.d/K90network
The Linux boot process uses these links to start or stop the
appropriate services at boot time or when you explicitly switch
the run level using the telinit command.
You can maintain all these links by hand: The important idea is to keep
them complimentary: If you create start links on levels 2 and 5,
you should have kill links on 0,1,3,4, and 6.
The chkconfig command is supposed to help you maintain these links.
It doesn't start or stop a service, it only creates or deletes the
symbolic links.
The chkconfig command obtains run level and starting order information
from a special comment found inside each service control file.
A typical comment in a service control file looks like this:
# chkconfig: 2345 90 60
This was extracted from my /etc/rc.d/init.d/crond control file.
The comment suggests that the crond service should start on
runlevels 2345 at relative position 90. By the complimentary
priciple, it should have kill links on levels 0, 1 and 6 at relative
position 60.
Install both start and kill links for a newly installed service:
chkconfig --add serviceName
Remove all start and kill links for a service at all run levels.
chkconfig --del serviceName
Some service control files will have a minus character for the list
of run levels. For example, my Samba control file (smb) contains:
# chkconfig - 91 35
To install a new service like this you first use:
chkconfig --add serviceName
This will put kill links on every level.
Then you specify the levels where you want the service to run:
Add start links and remove kill links from specified levels:
chkconfig --level levelString serviceName on
Add kill links and remove start links from specified levels:
chkconfig --level levelString serviceName off
If you don't use the "--level levelString" option, the default
levels 2345 will be used.
Example to start Samba at runlevels 345:
chkconfig --level 345 smb on
It often happens that people try to maintain the links
by hand and get everything messed up. To clean house when you
are uncertain about a service configuration, first get rid of all
the links using:
chkconfig --del serviceName

Kernel

View the startup messages

        dmesg 

Slow down the boot process so you can see what happens

        Add 'confirm' (no quotes) to the lilo command line:

Example, At the lilo promp:
LILO: vmLinuz confirm

Display all system version information

        uname -a 

Display only the kernel version string

        uname -r 

Specify the root device on a boot floppy

        rdev /dev/fd0 /dev/hda7 

Show the root device for an image file

        rdev anImageFile 

Set the root device for an image file

        rdev anImageFile /dev/hda7 

Add a device entry

        mknod /dev/name type major minor

Where type is p b c or u

Make a ramdisk root file system image with support for PCMCIA

        pcinitrd --all myInitrdFile 

Mount a RAM disk root file system image so you can poke around inside

        mount -t ext2 -o loop myInitrdFile /mnt/initrd

(You have to gunzip compressed images first)

Core dump file size

        ulimit -c 

You can disable core dumps by putting "ulimit -c 0" in
/etc/profile

Controlling PCMCIA slots

        cardctl { suspend, resume, status, eject, insert } slot#

cardinfo # X interface for cardctl

Copy raw kernel image to floppy device (obscure way)

        dd if=/boot/vmlinuz of=/dev/fd0 bs=8192 

DOS command to boot with a commpressed RAM disk root file system

        loadlin vmlinuz initrd=myGZippedFileSystemImage 

Change a dynamic kernel parameter (example)

        echo anInteger > /proc/sys/kernel/file_max 

Update module dependancies after editing /etc/modules.conf

        depmod -a 

Tell lilo you have edited lilo.conf

        lilo 

Tell the kernel to flush the write-behind cache

        sync 

Write something in the system log (Great for system script debugging)

        logger -t MyProgram "This is a message"

Also see "man initlog" for debugging init.d scripts.

Building a new kernel

        Update /usr/src/linux symbolic link to point at sources.

Go into /usr/src/linux
Backup .config to a safe place if you want to keep a copy.
make mrproper (Will delete old .config)
make xconfig (Fill in the blanks and write the .config file)
OR Copy in an old .config file and do:
make oldconfig
Edit the Makefile to bump the version number!
make dep clean bzImage install ;
make modules modules_install
If your root device has a modular driver
you will need an initial ram disk at boot time.
For kernel/module version set xx.yy.zz use:
mkinitrd /boot/initrd-xx.yy.zz xx.yy.zz
This will build a ramdisk file system image that contains
all the loadable modules for block devices described in your
/etc/conf.modules file. See also pcinitrd for PCMCIA boot
devices.
Add another entry for your old kernel to lilo.conf & run lilo.
Move any modules you don't build (like dpc)
Some versions of gcc are not compatible with some kernels.
Redhat supplies a "kgcc" for these systems.

Update PCMCIA

        OBSOLETE: This is part of the kernel make process now!

Preserve the Redhat-modified /etc/pcmcia/network script.
In the pcmcia-cs source directory:
make clean config
Answer the questions: Symbols from the source tree and
don't say yes to the plug & play bios question.
make all install
Restore the redhat version of /etc/pcmcia/network

Patch a kernel

        Put the patch file in /usr/src (above 'linux') and cd there.

Then:
patch -s -p0 <>

Test a patch before you apply

        Add the --dry-run option 

Copy raw kernel image to make a bootable floppy device

        cp zImage /dev/fd0 

Cross compiling a kernel

        Build cross versions of binutils and gcc:

Define the appropriate CROSS_COMPILE prefix and
use ./config & make as usual.
Make a separate copy of kernel sources.
Don't update the /usr/src/linux symbolic link.
The /usr/src/linux must point to your host kernel source.
Edit the Linux Makefile in the new kernel sources.
The CROSS_COMPILE must match the one used for the
binutils & gcc. Example:
ARCH := ppc
CROSS_COMPILE =powerpc-linux-
Proceed as usual.

Re-lilo a linux boot partition that is not the running system

The need for this arrises when you forget to lilo a new kernel.

Boot from a CD or floppy, mount the target Linux partition. Then:
chroot linuxPartition lilo

Patch

Create a patch file

        oldVersion      # Path to the unmodified files

newVersion # Path to the modified files
diff -rN oldVersion newVersion > patchFile
-r Perform diff recursively
-N Support creating new files

Apply a patch file

        You should be in the directory above oldVersion:

patch -u -s -p0 <>
-s Silent
-p0 Don't modify file path names in the patch
-pN Remove first N components of file path names
-d p Switch to the directory named by p

RPM

Install or remove a package

        rpm -i package.rpm      # Install a package

rpm -U package.rpm # Update an installed package
rpm -F package.rpm # Freshen (Update only if installed)
rpm -e packageName # Remove a package

Queries

        rpm -qip package.rpm    # Describe a non-installed package

rpm -qlp package.rpm # List files in a non-installed package
rpm -qa # List all installed packages
rpm -qf afile # See which package installed a file
rpm -qR package # Find out what a package needs
rpm -qa | grep # See which packages have pat in name

List packages by the source Linux distribution

        rpm -qai | grep Dist | awk -F': ' '{print $3}' | sort | uniq -c 

Build a binary rpm using a source rpm

        rpmbuild --rebuild your.src.rpm

The result is in /usr/src/redhat/RPMS/i386

Build a new source rpm from an installed source rpm

        rpm -i xxxx.src.rpm

You can now tamper with the tgz in /usr/src/redhat/SOURCES
rpmbuild -bs /usr/src/redhat/SPECS/xxxx.spec
The result is in /usr/src/redhat/SRPMS

Create a binary rpm from a tar.gz that contains a .spec

        rpmbuild -tb yourpackage.tar.gz 

Obtain a set of updates from Redhat

        up2date -u -d

The downloaded files are in /var/spool/up2date

Install rpm on an empty linux partition mounted on 'mp'

        rpm --root mp --initdb 

Create a cpio archive from an rpm and write to an archiveFile

        rpm2cpio rpmFile > archive.cpio 

Expand a cpio archive

        cpio -mid <>

Unpack an rpm on one step

        rpm2cpio rpmFile | cpio -mid 

Use query formats

        The whole format is one "string"

Each tag specification looks like this: %{NAME}
You usually want a newline at the end:
rpm -q xmms --qf "%{SIZE}\n"
Between the "%" and the opening brace "{" you can
specify field sizes, or any other C printf formatting chars.
Positive integers select right alignment in the field.
Negative integers select left alignment in the field:
rpm -qa --qf "%-30{NAME} %10{SIZE}\n"
Some header tags select arrays of values.
Use square brackets to iterate over the set.
You can specify more than one array tag inside the query:
rpm -q xmms --qf "[%-50{FILENAMES} %10{FILESIZES}\n]"
Normally, all tags inside square brackets must be array tags.
If you want to print a fixed tag as a label on each line, add
an "=" char to the fixed-tag name:
rpm -q xmms -qf "[%{=NAME} %{FILENAMES}\n]"
Display a list of all rpms sorted by size:
rpm -qa --qf "%-50{NAME} %10{SIZE}\n" | sort -nk 2,2
Display a list of all "devel" packages sorted by size:
rpm -qa | grep devel | \
xargs rpm -q --qf "%-50{NAME} %10{SIZE}\n" | \
sort -nk 2,2

List all the available header tags for query formats

        rpm --querytags 

Show the value of a header element

        rpm -q packageName --qf "%{SIZE}\n" 

List the sizes of selected packages

        rpm -qa | grep devel | xargs rpm -q --qf "%{NAME} %{SIZE}\n" 

Fix a hoarked rpm database

        Symptom: All rpm commands "hang up"

Find and kill all processes running rpm or up2date:
ps ax | grep rpm
ps ax | grep up2date
(Kill them by hand)
Remove all rpm database lock files:
rm -f /var/lib/rpm/__db*
This usually gets things going. If not:
First make a backup of the database:
cp -r /var/lib/rpm /var/lib/rpm.copy
Then rebuild the database
rpm --rebuilddb
This takes some time, but if it hangs forever, repeat
the "Find and kill rpm" step and proceed with:
cd /var/lib/rpm
db_verify Packages
(You may need to install db4-utils)
If db_verify reports errors, try:
cp Packages Packages.backup
db_dump Packages.backup | db_load Packages
rpm --rebuilddb
If all these steps fail, you are in big do-do.

Signature verification errors

        Recent versions of Redhat require signature verification

when processing packages. If you havn't imported the
Redhat GPG signature, you will get errors of the form:
warning: ... V3 DSA signature: NOKEY, key ID ...
To fix this, first obtain a copy of the file RPM-GPG-KEY.
If you are creating your own rpm-based distribution, the
file is widely available on the web.
On a Redhat system, it can be found using:
find /usr -name RPM-GPG-KEY
When you have the file, execute the following expression:
rpm --import RPM-GPG-KEY

Perl

Building and installing a package

        perl Makefile.PL;

make
make test
su
make install

Archives

Tar commands

        tar czf arch.tgz path   # Make an archive (Add v for verbose)

tar xzf arch.tgz # Restore an archive (Add v for verbose)
tar tf arch.tar # List an archive (must not be gziped)
Other tar options
-C directory # Change to this directory first
-T fileList # Use this list of file names
--same-owner # Keep original ower when extracting
--same-permissions # Keep original permissions when extracting
--absolute-paths # Don't strip leading /
--directory dirPath # Change to this directory first
--files-from=fileList # Get file names from another file

Gzip a file or directory

gzip file

gunzip file.gz

Zip a file or directory

        zip -r archive.zip files...

unzip archive.zip

Backup using rsych

        Normal unix-to-unix with locally mounted paths:

rsync -a --delete sourceDir/ destDir
Backup to a vfat or smb filesystem using only time attribute:
rsync -rt --delete --exclude="System Volume Information"* \
sourceDir/ destDir
The trailing / on the sourceDir is important:
It means copy the contents of sourceDir into destDir.

Cpio options

        Mode of operation is one of "pio":

p Pass files through without using an archive file
i Extract from an archive
o Create an archive
Other common options:
t List the contents of the archive
m Preserve modification times
d Create directories as needed
u Overwrite files without warnings

Extract files from a cpio archive, create directories as needed

        cpio -mid <>

Check for absolute file names in cpio archives

List the archive to see if it has absolute names.

Use --no-absolute-filenames if necessary.
This doesn't happen very often, but if it does and
you are root a Bad Thing (tm) can happen.

List a cpio archive

        cpio -t <>

Use cpio to copy everyting in current dir to targetDir

        Includes invisible dot files. Preserves all dates.

find . | cpio -pudm targetDir
On modern Linux systems "cp -a" will do the same thing.

Create a cpio archive from a list of files in current directory

        find . | cpio -o > archiveFile 

Keyboard

Redefine the backspace/delete key

        Used when telneting to unusual systems

stty erase

Show the keycodes as you press keys

        showkey 

Turn on autorepeat (Sometimes it goes away...)

        xset r 

Restore default backspace key operation

        xmodmap -e "keycode 22 = BackSpace" 

Restore default delete key operation

        xmodmap -e "keycode 107 = Delete" 

X Windows

Start X windows and specify bits per pixel

        startx -- -bpp 24 

Start X windows and specify a layout

        startx -- -layout myLayout

Layouts are defined in /etc/X11/XF86Config

Start X with a specific monitor dots-per-inch setting

        startx -- -dpi 80       # My Hitachi monitor

startx -- -dpi 95 # My Tecra flat panel
You can do this with a config file .xserverrc in home dir:
exec X -dpi 80
Then just "startx" as usual.

Start X and record the messages so you can see what happened

        startx > myXDebug.txt 2>&1 

Display info about the active X display

xdpyinfo 

Show properties of an X window

        xwininfo

xprop

Send X output of one program to another machine

         -display :0 

Send all X output to another machine

        export DISPLAY=targetIPnameOrNumber:0.0 

Set the default cursor

        xsetroot -cursor_name left_ptr

Others: draped_box, hand1, hand2, iron_cross,
plus, top_left_arrow, watch

Show X events (including keys)

        xev 

Show X user prefs settings

        xset -q 

Allow some other machine to draw on your x display

        xhost +

Put this command in your .xinitrc to make it permanent

Run xterm on another machine & exec a command

        xterm -display :0 -e  

Make XF86Config use the xfs font server

        Use FontPath "unix/:-1" (Redhat 6.x)

Update: "unix/:7100" (Redhat 7.x and other Linux systems)

Add a TrueType font directory (Requires FreeType package)

        cd theFontDirectory

ttmkfdir > fonts.scale
mkfontdir
chkfontpath --add `pwd`
service xfs reload
Note: Redhat runs ttmkfdir and mkfontdir on
every directory known to xfs in the xfs
startup script. These fonts become known
when you run chkfontpath.

Add a font to the Redhat anti-aliasing system

        Put the new font file in: /usr/share/fonts

Or in the per-user directory: ~/.fonts
Then run:
fc-cache

List the fonts X knows about

        xlsfonts 

Show local font server info

        fsinfo -server unix/:-1 

Example /etc/X11/xdm/Xservers for a one-display system

        :0 local /usr/X11R6/bin/X 

Show the status of X video support

        xvinfo 

Install the NVIDIA binary drivers

        rpm --rebuild NVIDIA_kernel-1.0-2314.src.rpm

rpm -i /usr/src/redhat/RPMS/i386/NVIDIA_kernel-1.0-2314.i386.rpm
rpm -i NVIDIA_GLX-1.0-2313.i386.rpm
# Now edit your XF86Config-4:
Remove Device section line:
Driver "nv"
Add Device section line:
Driver "nvidia"
Add Module section line: (it is normally present)
Load "glx"
Remove from Module section:
Load "dri"
Load "GLcore"

Use kdm to support remote X terminals (or Cygwin)

        You need to edit a bunch of files on the server:

File: /etc/X11/xdm/kdmrc
Make sure access is enabled as shown:
Enable=true
File: /etc/X11/xdm/Xaccess
Comment out the line:
* CHOOSER BROADCAST #any indirect host can get a chooser
Add lines to the end of the file with the ip name or number of
each client:
192.168.1.1
myclient.my.domain.com
etc.
File: /etc/X11/xdm/Xservers
If-and-only-if your server runs headless, comment out this line:
:0 local /usr/X11R6/bin/X
File: /etc/inittab
If you want automatic startup of kdm or xdm, on the server,
change the default runlevel:
id:5:initdefault:
File: /etc/rc.d/rc.local
If you don't start kdm using inittab, add this entry to rc.local:
/usr/bin/kdm
File: /etc/sysconfig/desktop
If you have more than one desktop system installed, this
entry selects the one that will be used for remote and local
logins: (Use KDM for kde or GDM for Gnome.)
DISPLAYMANAGER=KDM
In your iptables firewall setup script you must allow xdmcp:
iptables -A udpChain -p udp --dport xdmcp -j ACCEPT

Remote access with SSH RSA security

Newer linux distributions are configured to require SSH authorization for remote X clients. In this document, see "SSH access with RSA keys" for details about creating and using keys.

When using RSA, you still need the ip name or number of each client machine in the server's Xaccess file.

The X server has a file that contains the SSH public keys of each user and/or entire client machines that are allowed to connect:

        /usr/share/config/kdm/kdmkeys 

If you create this file, you must set the permissions:

        chmod u+rw,g-rwx,o-rwx /usr/share/config/kdm/kdmkeys 

You don't need to authorize the whole client if you only want to allow selected users on that client.

Public keys are copied or mailed from the client machines. A special public and private key set may be created for the whole host. It is kept in:

        /etc/ssh/ssh_host_rsa_key.pub 

You append the contents of this file to the server's kdmkeys file to authorized everybody on the whole client.

Public key files for individual users are found in:

        /home/someuser/.ssh/id_rsa.pub 

Simply append the contents of this file to the server's kdmkeys file to authorize this user.

SSH

The concept

Secure Shell (ssh) lets you connect to a remote host and start a shell session just like Telnet.
Unlike Telnet, ssh uses cryptography to log in and protect the data flow between you and the remote host.

Setting up ssh access is conceptually involved, but once this is done, ssh is very easy to use. For example: To start a shell session on a remote host you simply type:

        Login using your current user name:

ssh remoteHostIpName
Specify the remote user name:
ssh -l userName remoteHostIpName
Or using 'email' notation:
ssh userName@remoteHostIpName

SSH can perform many other marvels such as port forwarding: This lets you channel tcp/ip traffic between any selected client and server port through the secure connection. A common use of this feature is to run remote X-Windows programs and have them display on the client automatically. (If you have the superb Cygwin rootless X-client configured on you Windows box, this makes a shocking demonstration to the unwashed Windows user.)

The following sections deal with understanding and configuring ssh access.

RSA cryptography

SSH supports several encryption mechanisms, but one of the best is based on the RSA public key system.

To use RSA, you need a pair of numerical keys. One key is public: You can pass it out to your friends or publish it in a public directory. The other key is private and must be keep secret.

RSA is a Good Thing™ because it works without ever exchanging private keys over an insecure communication channel, e.g. the internet. It also supports signatures: A person who recieves a message can verify that only you could have sent the message.

Creating your own set of RSA keys

Individual users will need to run ssh-keygen to create their own public/private key files.

        ssh-keygen -t rsa -C "A comment" 

The program will propose this private key filename, which you normally accept:

        /home/someuser/.ssh/id_rsa 

The program will also create the public key file:

        /home/someuser/.ssh/id_rsa.pub 

You will also be asked for a passphrase. If you specify a passphrase, you will need to enter it whenever ssh or other programs want to use your private key.

The comment parameter is optional. If you don't supply a comment using "-C", the default is a string derived from you login name and the name of your host formatted like an email address:

        yourName@yourMachine.yourDomain 

The comment appears as plain text in your public key string. When examining an authorization file on a remote server, this text helps you remember who is authorized.

Once you have a key set, you can freely distribute copies of your id_rsa.pub file to anyone who wants to send you secure messages.

The file permissions for private key files must be set correctly or the ssh program will not work. The ssh-keygen program will do this properly, but to set them by hand you would use, for example:

        chmod u+rw,g-rwx,o-rwx id_rsa 

The individual user's hidden .ssh directory must also have the proper permissions:

        chmod u+rwx,g-rwx,o-rwx .ssh 

Enable ssh access to a remote account

You must setup your client ssh keys as decribed above. They will be in the hidden .ssh directory in your home directory on the client machine.

Email, ftp or otherwise copy your id_rsa.pub file to your home directory on the remote machine. To avoid confusion, we rename the file "client_rsa.pub". You must append the contents of this file to the authorized_keys file in the .ssh directory at the top-level of your remote home directory.

To do this, you need to log into your remote account by some other means or ask someone who has access to do this for you. This command will append your key to the authorized_keys file:

        cat client_rsa.pub >> .ssh/authorized_keys 

If you're creating a new .ssh/authorized_keys file, you must set the permissions or remote access will be denied:

        chmod u+rw,g-rwx,o-rwx .ssh/authorized_keys 

If some other user such as "root" does this for you, they also need to make sure that you own the file:

        chown yourUserName:yourGroupName .ssh/authorized_keys 

Similarly, the remote .ssh directory must have the correct permissions and owner:

        chmod u+rwx,g-rwx,o-rwx .ssh

chown yourUserName:yourGroupName .ssh

Creating a host key set

An entire host machine may have a key set. The public part of this key is kept on remote servers to authorize access by the entire machine. Many services can be configured to use host-level authorization.

Host keys should be located in:

        /etc/ssh/ssh_host_rsa_key

/etc/ssh/ssh_host_rsa_key.pub

The automatic installers for many Linux distributions create the host key files in /etc/ssh automatically.

To create them by hand, run ssh-keygen and specify the path names shown above. Passphrases are not normally used with host keys.

Images

Resize a directory full of images

        mogrify -format jpg -resize 400 *.jpg

Convert all gifs to jpgs

        mogrify -format jpg *.gif

Programming

Compile and link a C program

        cc file1.c file2.c file3.c -o program

Compile for subsequent linking

        cc -c file.c # Produces file.o by default 

Link compiled modules

        ld file1.o file2.o file3.o -o result 

Create a dynamically linkable library

        This library can be used with dlopen, dlclose, dlsym:

cc -rdynamic -c test.c -o test.o
ld -shared test.o -o test.so

Debug with gdb on a terminal

        list      # List source starting at line

list # No continues listing
break # Set breakpoint
clear # Clear breakpoint
run p1 p2 ... # Start program with parameters
step # Step into
next # Step over
quit # Exit debugger
continue # Continue from break
print expr # Show value of expression
display expr # Print value at each break
backtrace # Show the calling stack

Show the libraries used by a program

        ldd  

List all the symbols defined by an object file

        nm  

Ask dynamic linker to scan for new libraries

        ldconfig 

Check out a module with CVS

        export CVSROOT=":pserver:anonymous@cvs.computer.com:/var/cvsroot"

cvs login
Answer the password prompt.
Then cd to the local diretory where you want the source.
Check out the files:
cvs -z3 checkout name

Scanner

Find the scsi device that controls your scanner

        sane-find-scanner

(For this example, we will assume that /dev/sg0 is the result)

Make a new user & group for the scanner

        useradd saned 

Give this group access to the scanner device

        chown root:saned /dev/sg0

chmod g+rw /dev/sg1

Add an entry to /etc/services

        sane 6566/tcp saned # SANE network scanner daemon 

Add an entry to /etc/xinet.d

        service sane

{
socket_type = stream
server = /usr/sbin/saned
protocol = tcp
user = saned
group = saned
wait = no
disable = no
}
You will need to verify the location of the saned program
on your system. Use "which saned" and modify the xinet.d
file shown above appropriately.

Specify allowed hosts

        Edit:

/etc/sane.d/saned.conf
Append your allowed hosts (names, ip numbers, or subnets)
Example for a local subnet:
192.168.1.0/24

Eliminate unused backends

        This is not strictly necessary, but it may prevent some

module loading errors. Edit:
/etc/sane.d/dll.conf
Remove everything but the entry for your scanner type and "net."
The "v41", for example, causes the char-major-81 error.
UPDATE: None of this section applies to Fedora core II.

Tell xinetd to reload the configuration files

        service xinetd restart 

Networking

Start/stop a network device

        ifup 

ifdown
These commands are scripts that automatically set up all
the ip parameters and take care of special cases
such as PPP, PPPoE, DHCP, firewalls and others.
At least in Redhat, the implicit parameters go in:
/etc/sysconfig/network
/etc/sysconfig/network-scripts/ifcfg-

Show or configure interface parameters

        ifconfig        # Show params for active interfaces

ifconfig -a # Show params including inactive interfaces
ifconfig # Show params for a specific interface
ifconfig \ # Set params and start the interface
address \
netmask \
broadcast
\
metric
The ifconfig command directly configures and starts the interface.
It is up to you to take care of routing and other issues.

Show and modify routing tables

        route -n        # List numbers, not names

route add default # Add a default route
route delete # Remove a route

Export NFS files systems after editing /etc/exports

        exportfs -r 

Show what's going through a network interface

        tcpdump -i  

Restart xinetd after you edit /etc/xinetd.d files

        killall -HUP xinetd 

Configure a tftp directory path

        Add the path as a parameter to the tftp daemon in inetd.conf 

Run a command on another computer

        rsh ipName command parameters

See discussion of rlogin above for required preconditions.
The /etc/xinetd.d/rsh must be enabled.
The /etc/securetty must have an entry for rsh.

Return the ip information about a host

        host hostName

dig hostName
nslookup hostName
ping hostName
ping ipAddress

Show all connections

        netstat -vat 

Show processes and programs listening for connections

        netstat -lp 

Obtain and install network configuration from a DHCP server

        dhclient -nw 

Firewall

Overview

        Incoming and outgoing IP packets pass through chains.

A chain is a list of rules.
A rule specifies a pattern to match in the IP packet.
If the rule does not match, the packet is passed on
to the next rule in the chain.
If the rule matches, the packet is passed to the target.
The target of a rule can be another chain or the special
targets: ACCEPT, DROP, QUEUE or RETURN.
ACCEPT - Let the packet through
DROP - Throw the packet away
RETURN - Leave this chain and let caller decide.
If packet 'runs off' the end of a chain, RETURN is the default
target. RETURN from inside a built-in chain will execute the
the default chain policy.
There are two commonly used tables, "filter" and "nat":
The "filter" table contains chains for normal packets.
Built-in chains for "filter":
INPUT where packets arrive from outside the machine.
OUTPUT where packets are sent out from the machine.
FORWARD where packets go that are being routed.
The "nat" table contains chains for packets that create connections.
Built-in chains for "nat":
PREROUTING Alters input packets before routing.
OUTPUT Alters locally-generated packets before routing.
POSTROUTING Alter packets after routing before they go out.

Flags for parameters used with iptables

        -A Chain name to append new rule

-t tableName (default is filter)
-s Source IP address
-d Destination IP address
-i Input interface
-o Output interface
-p IP protocol (tcp, udp, icmp)
-j Target
--dport Desination port (tcp, smtp, ftp, etc.)
--sport Source port (tcp, smtp, ftp, etc.)

All the available services (named ports) are listed in

        /etc/services 

Commonly used ip protocols

        tcp, udp, icmp 

Commonly used tcp ports

        telnet, ftp, imap, smtp,

ssh, http, domain,
netbios-ssn (samba)

Remove all rules on a chain or on all chains (--flush)

        iptables -F optionalChainName 

Delete a chain or all chains (--delete-chain)

        iptables -X optionalChainName 

Zero packet & byte counters in all chains (--zero)

        iptables -Z optionalChainName 

Create new chain (--new-chain)

        iptables -N newChainName 

Apply a default policy (--policy)

        Only valid for built-in chains (INPUT, OUTPUT, etc.)

The policy target cannot be another chain.
iptables -P chainName target

List the rules in a chain

        iptables -L optionalChainName 

Rules to reset (eliminate) a firewall

 iptables -t filter -F

iptables -t filter -X
iptables -t filter -Z
iptables -t nat -F
iptables -t nat -X
iptables -t nat -Z
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT

Enable forwarding NAT

        echo 1 > /proc/sys/net/ipv4/ip_forward

iptables -t nat -A POSTROUTING -o $inetDev -j SNAT --to-source $inetIP
iptables -A FORWARD -i $lanDev -j ACCEPT

Target for logging a rule (must go before the planned action)

        -j LOG --log-prefix "Firewall: My rule fired" 

Recommended kernel settings for a firewall

        These can be entered into /etc/sysctl.conf where they

will be copied to /proc/sys at boot time.
echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
echo "1" > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses
echo "1" > /proc/sys/net/ipv4/conf/all/rp_filter
echo "0" > /proc/sys/net/ipv4/conf/all/accept_source_route
echo "0" > /proc/sys/net/ipv4/conf/all/accept_redirects

Support Masquerade when you have a dynamic IP (PPP, SLIP, etc)

        echo "1" > /proc/sys/net/ipv4/ip_dynaddr 

Rules for a simple-minded firewall

        TBD 

Automatic iptables using the redhat init script

        Make a firewall using your script or command from the console.

Save the results in /etc/sysconfig/iptables using iptables-save.
At boot time, these values will be restored.
iptables-save > /etc/sysconfig/iptables
Enable the script at boot time using
chkconfig --add iptables
Other init script operations:
service iptables start # Apply /etc/sysconfig/iptables
service iptables stop # Admit all packets (remove firewall)
service iptables panic # Stop all incomming packets
service iptables restart # Reload the tables
service iptables save # Does iptables-save for you
rervice iptables status # Display the tables
The firewall /proc settings should be configured in /etc/sysctl.conf:
net.ipv4.ip_forward = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.accept_redirects = 0
At boot time, sysctl.conf is loaded by /etc/rc.d/rc.sysinit

Email

Send a file to another user with sendmail

        sendmail  <  

Send a typed message to another user

        mail 

Type your message here
and end with a d

Send mail with a binary attachment

        cat afile.bin | uuencode temp.txt | mail -s "This is a test" userid 

Talk to sendmail directly (for debugging)

        telnet  25

ehlo
mail from:
rcpt to:
data
Type your message here and end with a dot:
.
quit

Talk to a POP server directly for debugging

        telnet  110

USER
PASS

Configure sendmail

        Enable the sendmail daemon via rc scripts

You only do this if the machine is a server.
chkconfig --add sendmail
service sendmail start
Changes for sendmail.mc
/etc/mail/sendmail.mc: (Changes only)
dnl DAEMON_OPTIONS(Port=smtp,Addr=127.0.0.1, Name=MTA)dnl
dnl FEATURE(accept_unresolvable_domains)dnl
FEATURE(`masquerade_entire_domain')dnl
FEATURE(`masquerade_envelope')dnl
FEATURE(`allmasquerade')dnl
MASQUERADE_AS(`csparks.com')dnl
MASQUERADE_DOMAIN(`csparks.com')dnl
If you run an mail server behind NAT,
sendmail may try to use the envelope sender "localhost.localdomain".
This upsets a lot of remote MTAs and they may bounce your email.
To fix this, add this line to sendmail.mc:
define(`confDOMAIN_NAME', `server.csparks.com')dnl
Whatever name you use should resolve externally to your server.
After changing /etc/mail/sendmail.mc you must run:
m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf
service sendmail restart
Allow all local hosts on your domain to relay:
/etc/mail/access:
csparks.com RELAY
makemap hash /etc/mail/access < /etc/mail/access
On the server, populate local-host-names with machine names that
have local accounts. When mail arrives for any of these machines,
the user name is presumed to match that of a local user.
csparks.com
mail.csparks.com
People who have identical user names on other machines must be
sorted out with distinct local accounts:
virtusertable:
user@machine1 localUserName1
user@machine2 localUserName2
makemap hash /etc/mail/virtusertable < /etc/mail/virtusertable
In client /etc/hosts file, add "doted" entries for the server:
Not required if you run a real DNS with bind.
192.168.0.2 mail.csparks.com mail.csparks.com.
Restart sendmail after reconfiguring
kill -HUP `head -1 /var/run/sendmail.pid`

Configure the IMAP server

        Entry for /etc/xinetd.d

service imap
{ socket_type = stream
wait = no
user = root
server = /usr/sbin/imapd
disable = no
}
Create an md5 password file owned by root:
touch /etc/cram-md5.pwd
Add one line for each imap user of this form:
usernamepassword
Both pop & imap will use this file to avoid
transmitting clear-text passwords.
After editing, the file permissions should be changed:
chmod a-rwx,o+r /etc/cram-md5.pwd

Spam

SpamBouncer

In the good old days, a simple procmail script could get rid of most email spam. Those days are long gone.

SpamBouncer is a huge procmail filter that does an excellent job of filtering spam. Unlike many other spam filters, it also helps you fight back by automatically harassing and complaining to the spammer's ISP.

SpamBouncer was invented by Katherine Hampton, a famous anti-spam fanatic. She maintains the program with uncompromising zeal. Updates are issued very frequently and are required if you want to counter the lastest spammer strategies.

My simple-minded settings (shown below) will get you started, but configuring SpamBouncer can be a Big Deal™. You should probably study theSpamBouncer website before attempting to use this program.

Installing and configuring SpamBouncer

Unpack the distribution into a directory "spamBouncer". Inside, you will find a sample configuration file: "procmail.rc". Copy this to your home directory and rename it ".procmailrc".

You must edit .procmailrc to make your personal settings. Rather than editing the file here and there, it is easier to put all your changes right before the actual SpamBouncer code is called. Search for the comment "BEGIN RECIPIES" and put your changes right before that section. Your new definitions will replace the default set earlier in the file.

My additions to .procmail.rc

        # BEGIN My Spambouncer settings

DOMAIN=csparks.com
ALTFROM=hsparks@visi.com
BULKFOLDER=${DEFAULT}
BLOCKFOLDER=${MAILDIR}/Blocked
SPAMFOLDER=/dev/null
ALWAYSBLOCK=${HOME}/.alwaysblock
FORMAIL=/usr/bin/formail
SBDIR=${HOME}/spamBouncer
NSLOOKUP="nslookup -sil -timeout=5 -retry=2"
BLOCKLEVEL=4
SPAMLEVEL=8
NUKEBOUNCES=yes
BLOCKREPLY=NOTIFY
BYPASSWD=mxyzptlk
PATTERNMATCHING=SILENT
VIRUSFOLDER=/dev/null
# Special services
FTSGWEBFORMCHECK=yes
NJABLPROXYCHECK=yes
ORDBCHECK=yes
OSOOLCHECK=yes
RFCABUSECHECK=yes
RFCDNSCHECK=yes
RFCIPWHOISCHECK=yes
RFCPOSTMASTERCHECK=yes
RFCWHOISCHECK=yes
SPAMCOPCHECK=yes
CBLCHECK=yes
# END My SpamBouncer settings
# BEGIN Recipies
...

Other SpamBouncer configurations files

        .myemail

Every email address that is "you" on this account.
.nobounce
Domains or addresses not to be bounced.
.legitlists
Mailing list senders you want to keep.
.alwaysblock
People or domains that aways get blocked.
This feature must be enabled.
No blank lines should be in any of these files or
Very Bad Things will happen.

Apache

Create and configure virtual hosts

        In /etc/httpd/conf/httpd.conf

NameVirtualHost *
For each host:

ServerName myHost.myDomain.com
DocumentRoot /var/www/html/myDirectory

You must have a CNAME entry for myHost in your
zone file or a definition for myHost.myDomain.com
in your /etc/hosts file.
# BEGIN HVS Support for virtual hosts
NameVirtualHost *

ServerName www.csparks.com
DocumentRoot /var/www/html


ServerName hardinge.csparks.com
DocumentRoot /var/www/html/hardinge


ServerName watchmaking.csparks.com
DocumentRoot /var/www/html/watchmaking


ServerName ipchange.csparks.com
DocumentRoot /var/www/html/ipchange

# END HVS Support for virtual hosts

Configure Apache for XML

        Netscape won't display xml documents unless the associated xsl file

is served with the appropriate mime type (text/xml or application/xml)
This can be set in Apache by editing /etc/httpd/conf/srm.conf and
adding two AddType directives:
AddType application/xml .xml
AddType application/xml .xsl

Typical changes to the httpd.conf file

        ServerName www.csparks.com

ServerAdmin hugh@csparks.com

Access control

        To password protect a sub-directory on your website,

create the file .htaccess that contains:
AuthName "Banner message for password dialog"
AuthType Basic
AuthUserFile /var/www/.htpasswd
require valid-user
Set the permissions:
chmod u+rw,u-x,go-rwx .htaccess
chown apache:apache .htaccess
Create the password file:
htpasswd -c /var/www/.htpasswd aUserName
The program will prompt for the password.
The password file SHOULD NOT be located under your
visible web hierarchy, e.g. /var/www/html/...
Set the permissions:
chmod u+rw,u-x,go-rwx .htaccess
chown apache:apache .htaccess
Add a user to the password file:
htpasswd /var/www/.htpasswd aUserName
The program will prompt for the password.
Delete a user from the password file:
htpasswd -D /var/www/.htpasswd aUserName
Allowing specific users
If you have a site with many users that have various
access permisions, they can all go into the same .htpasswd
file, but you can restrict access to selected users of
selected sub-directories. In the .htaccess, change the
"require" line to read (for example)
require user bill mark jane
The same result could be obtained by haveing many different
.htpasswd files, but this method is easier to administer.
Using groups
Groups allow you to define abstract sets of users and
keep the actual user names out of the .htaccess file.
Change the .htaccess "require" line to read, for example:
require group chessplayers
Add this line to .htaccess:
AuthGroupFile /var/www/htgroups
The file htgroups contains lines like these:
chessplayers: bill mark jane
goplayers: judy steve
Password protect a single file by adding this section:
allow from all

require valid-user

To completly block web access to a file:
allow from all

deny from all

Exclude only selected ip addresses or subnets:
order allow,deny
deny from 192.168.1.12
deny from 148.150.0.0/255.255.0.0
allow from all
Allow only selected ip addresses or subnets
order deny,allow
deny from all
allow from 148.150.62.151
allow from 192.168.1.0/255.255.255.0
All of the directives described above may be placed in
a Directory element in your central httpd.conf file
instead of using the .htaccess file in the protected directory.
For example:

AllowOverride None
order deny,allow
deny from all
allow from 192.168.1.0/255.255.255.0

To diagnose access problems:
tail -f /var/log/httpd/error_log

Prevent recursion in rewrite rules

        In this example, files that end with ".xml" or ".mml"

are rewritten to find them in the "mxyzptlk" directory:
RewriteEngine on
RewriteCond %{REQUEST_URI} !(^/mxyzptlk/.*)
RewriteRule (.*)\.(xml|mml)$ mxyzptlk$1.$2 [P]
Using these rules, the client browser will show the orignal
URL in the address display, not the rewritten version.

Test the validity of the httpd.conf file

        apachectl configtest 

MySQL

Installation

        Install the server and client rpms.

Edit the /etc/rc.d/init.d/mysqld to add runlevels 2345
chkconfig --del mysqld # To clean up
chkconfig --add mysqld # Add to the runlevels
service mysqld start # Start the service
Setting the root password for the first time
mysqladmin password firstPassword
Changing the root password
mysqladmin --password=oldPassword password newPassword
The examples above assume you are logged in as
root. Otherwise add the key --user=root
Key concept: mysql usernames and passwords have
nothing to do with Linux usernames and passwords:
You must explicitly authorize all mysql users.
(See the GRANT command below.)

Login to the command line interface

        mysql --user=myName --password=xxxyyy

If you don't specify the username, it
will be taken to match your login name.

Show all existing databases

        show databases ; 

Create a new database

        create database databaseName ; 

Delete a database

        drop database databaseName ;

1) You can't drop a database that some program is using.
2) On some versions of MySQL, deleting a database is more
involved. When you try to drop a database, the "show databases"
command will show that the database is still there. This occurs
because some files are left in the top-level database directory.
On Redhat/Fedora installations, the top-level database directories
are located in /var/lib/mysql. After the first "drop database"
fails, delete all the debris in the top-level database directory.
A second "drop database" command will now succeed.

Add a user

        grant all privileges

on databaseName.tableName
to username@localhost
identified by 'aPassword' ;
The wild card * can be used for the databaseName and/or
tableName.
Without the *'s, a single name is the name of table in
the context db. (See "use db" below)
Use "grant" multiple times to grant access to the same
user from different (selected) hosts.

Remove a user

        revoke all privileges on *.* from username@localhost

delete from mysql.user where user='username' and host='hostname' ;
flush privileges ;

Run a script to configure a database

        mysql --password=xxxyyy dataBaseName <>

Select a database to use

        use dataBaseName ; 

Show the tables defined in the database

        show tables ; 

Describe a table (Show the field names and types)

        describe tableName ;

show columns from tableName ;

Create a new table in the current database

        create table pet

( name VARCHAR(20),
owner VARCHAR(20),
species VARCHAR(20),
sex CHAR(1),
birth DATE,
death DATE
) ;

Common data types

        char(size)

Fixed-length character string.
Size is specified in parenthesis.
Unused positions are padded with spaces.
varchar(size)
Variable-length character string.
Max size is specified in parenthesis.
int
Signed integer value.
real
Signed floating point value
date
Date value
time
Time value

Constraints

        Each column is defined by a name, data type and optional constraint.

Example constraints:
unique
not null
primary key

Adding records to a table from a text file

        load data local infile "pet.txt" into table pet ; 

Table text file format has tab delimited fields

        # Note the use of \N for null values.

Fido Mary dog \N 1997-12-09 \N

Adding records to a table from the command line

Note the use of NUL and quotes around string values.

insert into pet values
( 'Puffball',
'Diane',
'hamster',
'f',
'1999-03-30',
NULL
) ;

Inserting only selected column values

        insert into pet (name, owner) values ('Goober', 'George') ; 

Deleting a record

        delete from pet where name = 'Puffball' ; 

Delete all records

        delete from pet 

Deleting a table and all the data

        drop table tableName 

Looking things up in the database

        select  from  where 

a list of columns or * for all columns
select * from pet

Fixing a record

        update pet set birth = "1989-08-31" where name = "Bowser"; 

Reload the whole table from a text file

        set autocommit=1; # Used for quick re-create of the table

delete from pet;
load data local infile "pet.txt" into table pet ;

Selections

        select * from pet where name = "Bowser" ;

select * from pet where birth >= "1998-1-1" ;
select * from pet where species = "dog" and sex = "f" ;
select name, birth from pet;
select owner from pet ;
select name, owner from pet where species in ('dog', 'cat') ;
select distinct owner from pet ;
select name, birth from pet order by birth ;
select name, birth from pet order by birth desc ;
select name, species, birth from pet order by species, birth desc ;
select pet.name, pet.age, employee.salary, employee.title
from pet, employee where pet.name = "Bugsy";

Setup for Bookmarks4u

Fix import timeout by editing libimport.php :

After:
$fp = fopen($userfile, "r");
Add:
set_time_limit(360) ;

Weirdness with localhost

        After performing a grant to someuser@localhost, you may

find that an external application configured to access the
database will not be able to connect.
Many Linux distributions will have an /etc/hosts file like this:
127.0.0.1 myname.mydomain myalias localhost.localdomain localhost
When DNS (named) is not configured and running, the /etc/hosts file
is used for forward and reverse lookups. It appears that many
programs do some sort of security checking before connecting to MySQL
by looking up "localhost" and then doing a reverse lookup on the
result. The reverse lookup on "127.0.0.1" using the /etc/hosts file
shown above will yield: "myname.mydomain.com". This string gets
used when connecting to MySQL, which fails because it doesn't match
the string "localhost".
To fix this (only for machines without DNS), I suggest that
/etc/hosts contain:
127.0.0.1 localhost myalias
In other words, forget about pretending you have a domain when you don't.

DNS

Using DNS behind NAT

I have a small LAN behind an ADSL modem. The company where I registered my domain name lets me set up any number of aliases to my site, which has only one IP number. My Linux server runs DNS only for the local LAN. I find that "things go better" with a lot of programs (MySQL, sendmail, DSPAM) when I run this internal DNS instead of relying on /etc/hosts.

The following sections show all the DND configuration files for my site.

/etc/hosts

        I keep this file empty. 

/etc/host.conf

        order bind,hosts 

/etc/resolv.conf

        domain csparks.com

nameserver 192.168.1.2

/etc/sysconfig/network

        NETWORKING=yes

HOSTNAME=server
GATEWAY=192.168.0.254

/etc/named.conf

        options {

directory "/var/named";
forward first;
forwarders {
66.133.191.35;
170.215.255.114;
};
};
logging {
category lame-servers { null; } ;
};
zone "0.0.127.in-addr.arpa" IN {
type master;
file "localhost.rev";
allow-update { none; };
};
zone "csparks.com" {
type master;
allow-update { none; };
file "csparks.zone";
};
zone "1.168.192.in-addr.arpa" {
type master;
allow-update { none; };
file "csparks.rev";
};

/var/named/localhost.rev

        $TTL 3D

@ IN SOA dns.csparks.com. hugh.csparks.com. (
2001100710 ; Serial
8H ; Refresh
2H ; Retry
4W ; Expire
1D ) ; Minimum
IN NS dns.csparks.com.
1 IN PTR localhost.

/var/named/csparks.zone

        ; csparks.zone - Zone file for csparks.com

$TTL 3D
@ IN SOA server.csparks.com. postmaster.csparks.com. (
20040807 ; serial: todays date + todays serial
8H ; refresh, seconds
2H ; retry, seconds
4W ; expire, seconds
1D ) ; minimum, seconds
NS server
MX 10 mail.csparks.com.
localhost A 127.0.0.1
server A 192.168.1.2
router A 192.168.0.254
hp A 192.168.1.1
sparks750 A 192.168.1.3
mac A 192.168.1.5
sparksVaio A 192.168.1.7
sparks9k A 192.168.1.9
cyndi81 A 192.168.1.10
guest A 192.168.1.11
sparks730 A 192.168.1.23
wireless A 192.168.1.99
mail CNAME server
ftp CNAME server
www CNAME server
shell CNAME server
hardinge CNAME server
watchmaking CNAME server
ipchange CNAME server
dspam CNAME server

/var/named/csparks.rev

        $TTL 3D

@ IN SOA dns.csparks.com. postmaster.csparks.com. (
20040312 ; Serial, todays date + todays serial
8H ; Refresh
2H ; Retry
4W ; Expire
1D) ; Minimum TTL
NS dns.csparks.com.
1 PTR hp.csparks.com.
2 PTR server.csparks.com.
3 PTR sparks750.csparks.com.
5 PTR mac.csparks.com.
7 PTR sparksVaio.csparks.com.
9 PTR sparks9k.csparks.com.
10 PTR cyndi81.csparks.com.
11 PTR guest.csparks.com.
23 PTR sparks730.csparks.com.
99 PTR wireless.csparks.com.
254 PTR router.csparks.com.

Router

Router model

        3Com OfficeConnect Remote 812 ADSL Router 

Router URL

        http://router.csparks.com:8080 

Global settings

        Enable IP Routing 

Local LAN configuration

        IP Address & DHCP:

IP: 192.168.0.254
Mask: 255.255.255.0
Rip: None
Use this network as DHCP: No
DNS: Disable
I tried this. I made my named.conf forward
requests to the router instead of the known
Citizens name server addresses. It worked
very slowly.
IP Static Routes: None.
IPX Address:
IPX Static Services:
IPX Static Routes: Turn all this stuff off.

Remote site profile

        This is the main setup for the ADSL connection.

I have one remote site profile called "Citizens".
Enable Remote Site: yes
PPP over ATM (PPPoA): yes
User Name: hugh_sparks@citlink.net
Password: xxxxx
VPI: 0
VCI: 35
Quality of Service: Unspecified Bit Rate
Enable IP Routing: Yes
Use this connection as default gateway: yes
RIP: None
DNS: Pass DNS requests to...: No.
Security:
Verify packets can be routed back: Yes
Enable protect files and printers: Yes
IPX Stuff:
Turn all this off.
Address Translation: NAT
Default Workstation: 0.0.0.0 (None)
Accessible LAN Servers:
Set table below.

Port forwarding setup for TCP only. UDP map is empty.

        ftp-data        20      192.168.0.2:20

ftp 21 192.168.0.2:21
telnet 23 192.168.0.2:23
smtp 25 192.168.0.2:25
domain 53 192.168.0.2:53
http 80 192.168.0.2:80
pop2 109 192.168.0.2:109
pop3 110 192.168.0.2:110
auth 113 192.168.0.2:113
imap 143 192.168.0.2:143
When I switched to a firewall machine, I still had to
configure the individual ports as above. I tried to
leave them blank and set the default workstation to the
firewall, but it didn't work. Outsiders could not connect
to the servers for some reason.

Bash

Some built-in Commands

        . includeFileName

source fileName
alias name='expression'
unalias name
var=value
unset var
exit value
export var=value,...

File predicates

        if [ -e  ] ; then

# Do this if file exists
fi
Not operator: !
Other boolean operators: &&, ||

File predicates

        -d Is a directory

-e Exists
-f Is a regular file
-h Is a symbolic link
-r Is readable
-s Size is > 0
-w Is writable
-x Is executable

String predicates

        -z     # Length of string is zero

-n # Lenght of string is non-zero

Infix predicates

        if [  -nt  ] ; then

Do this if file1 is newer than file2 (or file2 does not exist)
fi

Infix file predicates

        -nt Newer than. Or file1 exists and file2 does not.

-ot Older than. Or file2 exists and file1 does not.

String infix operators

        ==, !=, <, > 

Numerical infix operators

        -eq, -ne, -lt, -le, -gt, -ge 

Script parameter names

        $1,...,$n

The script name is in $0

Using command results as a parameter

        Enclose the command in back-quotes:

Example: getting the size of a directory
dirSize=`du -s myDirectory | awk '{print $1}'`

Generating files from a script

        cat > myFile <<-'EOF'

These lines go into myFile.
This is the last line.
EOF

Picking out the nth element of a string

        The string should be pipelined to this command:

awk '{print $n}'

Picking out the nTh element from multi-line text

        This example returns the memory size of the machine.

Note the escapes required on nested quotes:
memSize=`sh -c 'echo $7' \`cat /proc/meminfo\` `

Devices

Examples from my workstation

        mouse -> /dev/input/mice

modem -> /dev/ttyS0
cdrom -> /dev/hdc
cdrom1 -> /dev/hdd

DHCP

Part of my basement LAN configuration

        # /etc/rc.d/init.d/dhcpd

ddns-update-style ad-hoc;
option domain-name "csparks.com";
option domain-name-servers 192.168.1.2;
subnet 192.168.1.0 netmask 255.255.255.0
{ option routers 192.168.1.2;
option subnet-mask 255.255.255.0;
option broadcast-address 192.168.1.255;
}
subnet 192.168.0.0 netmask 255.255.255.0 {}
host hp
{ hardware ethernet 00:20:78:12:16:89;
fixed-address 192.168.1.1;
option host-name "hp";
}
host sparks750
{ hardware ethernet 00:60:08:8a:b9:ce;
fixed-address 192.168.1.3;
option host-name "sparks750";
}

Configuration

File locations and descriptions

        /etc/hosts      # Known IP number/name bindings

/etc/fstab # Define mount points & filesystems
/etc/smb.conf # Config Samba server
/etc/exports # List of nfs exported directories
/etc/cram-md5.pwd # Imap & pop3 access: username password
/etc/dhcpd.conf # Configure dhcpd server (bootp)
/etc/inetd.conf # Configure servers (telnet, tftp, etc)
/etc/bashrc # Global functions and aliases
/etc/lilo.conf # Edit for boot setup, then run lilo
/etc/localtime # Link into a /usr/share/zoneinfo file
/etc/named.conf # Configuation for named DNS (bind)
/etc/resolv.conf # IP names and config for DNS
/etc/securetty # Terminals that are allowed to be root
/etc/DIR_COLORS # Colors used by color ls
/etc/modprobe.conf # Configure module loader
/etc/printcap # One entry per printer
/etc/profile # Global environment and startup
/etc/profile.d/*.sh # Modular global environ additions
/etc/ppp/options # Contains lock for ppp (Remove lock!)
/etc/ppp/ip-up.local # Things to do after connecting
/etc/ppp/pap-secrets # Username-password entries
/etc/ppp/resolv.conf # Created by ppp with usepeerdns option
/etc/pcmcia/config.opts # Used to exclude IRQ 12 for PS/2 mouse
/etc/pcmcia/network.opts # Configure and start pcmcia ethernet
/etc/securetty # List terminals allowed to login as root
/etc/sysconfig/pcmcia # Use this to turn on pcmcia
/etc/sysconfig/network # Start networking, set def gateway
/etc/sysconfig/network-scripts # ifcfg-xxx files for each interface
/etc/sysconfig/clock # Vars used in rc.sysinit to set the clock
/etc/sysctl.conf # Kernel settings for /proc/sys boot
/etc/rc.d/init.d # Start/stop scripts for system services
/etc/rc.d/rc.sysinit # Boot time configuration script
/etc/X11/XF86Config # Configuration for XFree86
/etc/X11/XF86Config-4 # New Configuration for XFree86 4.x
/etc/X11/fs/config # Configuration for xfs font server
/etc/X11/xdm/Xservers # List of servers and displays for xdm

Other interesting files

        /boot/vmlinuz   # Conventional symbolic link to kernel image

/var/log/dmesg # Startup messages
/var/log/messages # Main system message log
/var/log/maillog # Log for mail i/o
/var/log/httpd # Apache web server log files
/var/named/ # Location of zone files for named
/var/spool/mail # Each user's mbox file for new mail
/var/spool/lpd/xxx # One xxx directory per printer
/var/spool/lpd/xxx/.config # Hidden access info for printer
/var/spool/mqueue # Directory for queued outgoing mail
/usr/X11R6/lib/X11/rgb.txt # Names for all the X colors
/usr/X11R6/lib/X11/ # X configuration stuff
/dev/sndstat # Shows the sound configuration
/lib/modules # Path to system modules
/usr/share/zoneinfo # Subdirectories contain time zone files
/usr/src/linux/.config # Hidden kernel config file
/usr/src/redhat/... # RPM source and build directories

Example /etc/fstab

        # Root and swap volumes

/dev/hda1 / ext3 defaults 1 1
/dev/hda3 swap swap defaults 0 0
# Special device mounts
none /proc proc defaults 0 0
none /dev/pts devpts gid=5,mode=620 0 0
none /dev/shm tmpfs defaults 0 0
# Removable media
/dev/fd0 /mnt/floppy auto noauto,owner,kudzu 0 0
/dev/cdrom /mnt/cdrom iso9660 noauto,owner,kudzu,ro 0 0
# Logical volumes on the boot device
/dev/vg2/spoolVol /var/spool ext2 defaults 0 0
/dev/vg2/homeVol /home ext2 defaults 0 0
/dev/vg2/wwwVol /var/www ext2 defaults 0 0
# Logical volumes on the backup device
/dev/vg1/backVol /mnt/back ext3 defaults 0 0
/dev/vg1/archVol /mnt/dos ext3 defaults 0 0
# Samba network
//hp/dos /mnt/hpDos smbfs noauto,username=administrator 0 0
//hp/c /mnt/hpWin smbfs noauto,username=administrator 0 0
//sparksVaio/C$ /mnt/vaio smbfs noauto,username=administrator 0 0
//sparks9k/Main /mnt/9kWin smbfs noauto,username=administrator 0 0
# NFS network
# hp:/mnt/c /mnt/dummy1 nfs noauto,_netdev 0 0
# Loop mount example
# /mnt/Mac.hfs /mnt/mac hfs noauto,loop 0 0

Example /etc/exports

Note: "sync" is the default, but if it is not specified, the

log gets complaints.
/mnt/back *.csparks.com(rw,no_root_squash,sync)
/mnt/dos *.csparks.com(rw,no_root_squash,sync)
/var/www/html *.csparks.com(rw,no_root_squash,sync)

Example /etc/lilo.conf

        boot=/dev/hda

root=/dev/hda6
map=/boot/map
message=/boot/message
install=/boot/boot.b
prompt
timeout=50
default=linux
# Enable boot partition beyond cylinder 1024:
lba32
image=/boot/vmlinuz
label=linux
root=/dev/hda6
read-only
image=/boot/oldlinuz
label=oldlinux
root=/dev/hda6
read-only
other=/dev/hda1
label=win

Example /etc/grub.conf

        #boot=/dev/hda

default=0
timeout=10
splashimage=(hd0,0)/boot/grub/splash.xpm.gz
title Fedora Core (2.6.6-1.435.2.3)
root (hd0,0)
kernel /boot/vmlinuz-2.6.6-1.435.2.3 ro root=/dev/hda1 rhgb quiet
initrd /boot/initrd-2.6.6-1.435.2.3.img

Example /etc/sysconfig/static-routes

When a device is started, the static-routes file

is read by the script ifup-routes. For each line
that matches the device in the first parameter it
reads the line:
read device args
The routes are added by a script that performs "route add"
(Note the minus character before $args)
route add -$args $device
For example: (This is used to route back to basilisk)
eth0 host 192.168.2.3 gw 192.168.0.1

Example /etc/modules.conf

        # OBSOLETE: Now using /etc/modprobe.conf

alias eth0 tulip
alias tap0 ethertap
alias scsi_hostadapter aic7xxx
alias parport_lowlevel parport_pc
alias sound-slot-0 es1371
alias sound-service-0-0 es1371
alias sound-service-0-3 es1371
alias sound-service-0-4 es1371
post-install sound-slot-0 /bin/aumix-minimal \
-f /etc/.aumixrc -L >/dev/null 2>&1 || :
pre-remove sound-slot-0 /bin/aumix-minimal \
-f /etc/.aumixrc -S >/dev/null 2>&1 || :
alias usb-controller usb-uhci
alias char-major-180 usbcore
alias cdrom sr_mod
alias cdram sr_mod
above sr_mod ide-scsi
alias char-major-195 NVdriver
alias net-pf-1 unix
alias net-pf-17 af_packet

Example /etc/modprobe.conf

        alias eth0 8139too

alias eth1 tulip
alias scsi_hostadapter fdomain
alias snd-card-0 snd-intel8x0
install snd-intel8x0 /sbin/modprobe --ignore-install snd-intel8x0 && /usr/sbin/alsactl restore >/dev/null 2>&1 || :
remove snd-intel8x0 { /usr/sbin/alsactl store >/dev/null 2>&1 || : ; }; /sbin/modprobe -r --ignore-remove snd-intel8x0
alias usb-controller ohci-hcd
alias char-major-195* nvidia

Regular expressions

Anchors

        ^       Beginning of the line

$ End of the line
<>
> Right word boundary

Quantifiers

        .       Any single character except eol

x* Zero or more x's (maximal)
x+ One or more x's (maximal)
x? Zero or one x's (maximal)
x*? Zero or more (minimal)
x+? One or more (minimal)
x?? Zero or one (minimal)

Character classes

        [abcdef]        Any of the enclosed characters

[a-z] Any in the range of characters
[^a-e] Any char except a-e
[^abcdef] Not any of the characters

Expressions

(expression)    Grouping an expression

\c Escape a meta character c like *+. etc.
exp1|exp2 Matches expression1 or expression 2.