Anda di halaman 1dari 261

1

Table of Contents
Movement Within the Directory System.....................................................3 cd............................................................................................................3 pwd.........................................................................................................4 Managing Files and Text............................................................................5 cp............................................................................................................5 ls.............................................................................................................7 mkdir.......................................................................................................9 mv.........................................................................................................10 rm.........................................................................................................11 cat.........................................................................................................12 sed........................................................................................................12 sed scripts............................................................................................21 cmp.......................................................................................................22 column..................................................................................................23 csplit.....................................................................................................23 cut.........................................................................................................25 diff.........................................................................................................25 egrep....................................................................................................26 elvis......................................................................................................27 emacs...................................................................................................27 expand..................................................................................................27 fgrep.....................................................................................................27 fmt........................................................................................................28 grep......................................................................................................28 head.....................................................................................................28 less.......................................................................................................30 lpq.........................................................................................................33 lpr.........................................................................................................33 lprm......................................................................................................33 more.....................................................................................................34 nl...........................................................................................................34 od.........................................................................................................35 paste.....................................................................................................37 pico.......................................................................................................37

2 sort.......................................................................................................37 pr..........................................................................................................38 split.......................................................................................................39 tac.........................................................................................................40 tail.........................................................................................................40 tee........................................................................................................41 tr...........................................................................................................42 merge...................................................................................................43 rm.........................................................................................................43 rmdir.....................................................................................................44 wc.........................................................................................................44 xargs.....................................................................................................44 Managing System and Program Information...........................................46 cal.........................................................................................................47 date......................................................................................................50 &...........................................................................................................50 bg.........................................................................................................51 fg..........................................................................................................51 jobs.......................................................................................................51 renice....................................................................................................53 Troubleshooting........................................................................................54 fsck - Recovering from a System Crash..............................................55 e2fsck...................................................................................................57 xvidtune................................................................................................58 xwininfo................................................................................................59 xload.....................................................................................................60 Managing Network Connections..............................................................63 chkconfig..............................................................................................63 ping.......................................................................................................64 ftp.........................................................................................................68 host.......................................................................................................68 ifconfig .................................................................................................69 mail ......................................................................................................71 neat......................................................................................................75 netstat..................................................................................................75 route.....................................................................................................77

3 telnet.....................................................................................................79 traceroute.............................................................................................80 Secure Shell - SSH..............................................................................80 Configure the Bridge .........................................................................101 EBTABLES man page...................................................................103 Modify the Script............................................................................115 Managing Drives and Formats...............................................................117 mount.................................................................................................117 umount...............................................................................................118 fdisk....................................................................................................119 dd.......................................................................................................123 df........................................................................................................123 du.......................................................................................................124 mkfs....................................................................................................124 mkdosfs..............................................................................................124 chmod................................................................................................125 chattr..................................................................................................127 Using the su command......................................................................127 umask.................................................................................................129 Package Management .........................................................................131 Introduction to RPMs.........................................................................131 tar.......................................................................................................137 fromdos..............................................................................................139 Debian Package System....................................................................139 Managing Users and Groups.................................................................141 Message of the Day...........................................................................141 mesg n...............................................................................................142 wall.....................................................................................................142 adduser..............................................................................................144 passwd...............................................................................................144 chsh....................................................................................................152 Quotas................................................................................................152 Quota.................................................................................................153 groupadd............................................................................................158 groupmod...........................................................................................158 chgrp..................................................................................................159

4 groupdel.............................................................................................160 newgrp................................................................................................160 chown.................................................................................................160 useradd..............................................................................................161 usermod.............................................................................................161 userdel...............................................................................................161 groupadd............................................................................................162 Managing Backups.................................................................................165 cpio.....................................................................................................165 Hard Drive Backups...........................................................................166 Creating a Backup With Tar..............................................................166 Using tarfiles......................................................................................167 bzip2...................................................................................................169 compress............................................................................................169 gzexe..................................................................................................169 gzip.....................................................................................................170 unzip...................................................................................................170 System Administration Tools.................................................................173 apropos .............................................................................................173 arch....................................................................................................173 at........................................................................................................174 batch...................................................................................................175 bc........................................................................................................175 chroot.................................................................................................175 chkconfig............................................................................................175 cksum.................................................................................................176 cron....................................................................................................176 dumpkeys...........................................................................................179 dmesg.................................................................................................179 expand...............................................................................................186 getkeycodes.......................................................................................187 id.........................................................................................................187 init.......................................................................................................188 kbd_mode..........................................................................................188 kill.......................................................................................................188 killall....................................................................................................189

5 find......................................................................................................189 locate..................................................................................................190 locatedb..............................................................................................191 lsmod..................................................................................................191 lsof......................................................................................................193 makewhatis........................................................................................195 mc.......................................................................................................195 mke2fs................................................................................................195 ntsysv.................................................................................................196 ps........................................................................................................196 printenv...............................................................................................198 pwconv...............................................................................................198 pwunconv ..........................................................................................198 grpunconv..........................................................................................198 script...................................................................................................199 shutdown............................................................................................199 sleep...................................................................................................200 strace..................................................................................................200 strings.................................................................................................201 stty......................................................................................................202 superprobe.........................................................................................202 tcsh.....................................................................................................202 tload....................................................................................................202 unshar................................................................................................203 top......................................................................................................204 uptime................................................................................................204 whatis.................................................................................................204 workbone............................................................................................204 workman.............................................................................................205 x11perf...............................................................................................205 xauth...................................................................................................207 xconsole.............................................................................................208 xev......................................................................................................208 XF86Config........................................................................................208 xload...................................................................................................208 xclock ................................................................................................209

6 oclock.................................................................................................209 rclock..................................................................................................209 which..................................................................................................210 xlock...................................................................................................210 xcalc...................................................................................................210 xclipboard...........................................................................................210 xeyes..................................................................................................210 xpaint..................................................................................................210 xmag...................................................................................................211 xrefresh..............................................................................................211 xspread...............................................................................................212 xterm..................................................................................................212 zsh......................................................................................................212 startx...................................................................................................212 clear....................................................................................................212 Command History ...........................................................................212 audiocompose....................................................................................213 biff.......................................................................................................213 elm......................................................................................................213 fastmail...............................................................................................214 fetchmail.............................................................................................214 pine.....................................................................................................216 tcpdump.............................................................................................216 Vi editor..................................................................................................217 Basic Commands...............................................................................217 Numeric Movement............................................................................219 Retrieving Lost Files...........................................................................220 The Bash Shell.......................................................................................221 Working Directory..............................................................................223 Command-Line Scan.........................................................................224 Creating a Shell Script.......................................................................224 Using Variables..................................................................................225 Wildcards...........................................................................................227 Pipeline..............................................................................................228 Projects...................................................................................................229 Context For Projects......................................................................229

7 Setup for Projects..........................................................................230 Managing Files and Text........................................................................233 Project: Moving Policy Files...........................................................233 Project: Reviewing Log Files for Security Issues..........................233 Project: Find all Files with a Specific Pattern................................236 Managing Users and Groups.................................................................238 Project: Delete User and Manage Files.........................................238 Managing Network Connections............................................................240 Setup Network on a Computer......................................................240 Project: SSH Transfer Policy Files and Directories to New Server.. 248 Managing Drives and Formats...............................................................252 Project: Mounting and Unmounting USB Drives...........................252 Managing Backups.................................................................................253 Project: Back-Up Your Home Directory.........................................253

8 Copyright and Trademark Information The product and material in this manual is protected under International Copyright Laws. All rights are reserved. No part of this manual may be reproduced, transmitted or transcribed without the expressed written permission of Cybermontana Inc. Linux is a registered trademark of Linus Torvalds. Mandrake, Fedora and SuSE are registered trademarks. Windows is a registered trademark of Microsoft Inc. All other brand names and trademarks are properties of their respective owners. The information contained in this manual represents our best efforts at accuracy, but we do not assume liability or responsibility for any errors that may appear in this manual.

December 10, 2006 Cybermontana Inc. Box 1262 Trout Creek, MT 59874

Learning Linux Commands

Learning Linux Commands is a process. As with any process you need to understand that it will not all come together the first day. In fact, employing Linux commands effectively is a process that you will begin to enjoy and find that you will use more once you get over the initial frustrations. The book and CD are designed to help you get over the major initial hurdles quickly. The book and CD are based on three categories of information. First, Factual knowledge. In Factual Knowledge each of the commands will be listed with information regarding the major purpose of the command, available options and an example of how it is used. The second category of the book will be Practical Projects. Many people seem to want to learn commands but it is all too boring and it is difficult to find the right command for the right purpose. The Practical Projects will take a series of commands and illustrate how all of those commands work together to complete a project. An example would be all of the commands needed to setup networking on a computer. The final category is found on the CD that comes with the book. The CD provides Flash Movies with audio to illustrate how the commands work to accomplish the goals that you have at the terminal. This format should provide learning options that anyone could come up to speed with commands.

Movement Within the Directory System

Movement Within the Directory System

cd
Change directory. Examples: cd By simply typing cd it will take you to your home directory. You could also go to your home directory by typing: cd ~ cd /home/fred This command would take you to the directory fred located in the home directory. If you were in the /home/fred directory and knew that there was another directory in /home/fred called work you could enter that directory one of two ways: cd /home/fred/work or

Movement Within the Directory System


cd work Notice that there is no leading /.

Knowing how to change directories is critical to being able to navigate the Linux directory system. One of the reasons it is important to be able to navigate is that all commands are executed based on your preset working directory. For example, if you wanted to list the contents of the /etc directory with the command ls and your present working directory was /home/fred you would have to execute the command: ls /etc However, if your current working directory was /etc the command would be: ls Therefore it is important to clearly understand your present working directory. The pwd command aids in this because it will print the present working directory. If you need to move up the directory tree you can use this command to move up one directory: cd .. For example if you are located in the /usr/share directory and then type: cd.. You will now be located in the /usr directory, you have moved up one level.

pwd
This will print to screen your current working directory. If your present working directory was /home/fred and you executed the pwd command you would get this return: /home/fred If your resent working directory was /usr/share and you executed the pwd command you would get this return: /usr/share

Managing Files and Text

Managing Files and Text

cp
The copy command for Linux is cp. This command is a heavily used command that is simple but allows you to use options that created a very powerful tool. Example: cp /home/fred/text /home/jim/ This command will copy the file text to Jim's home directory. options -a retain archival attributes -b create backup of file instead of overwriting -d maintain symbolic links -f force copy -i interactive mode, prompts before files are overwritten -l creates links between files copied to directories instead of actually copying the file -p preserve existing permissions -r copy entire directory and subdirectories

Managing Files and Text


-R -s -S -u -v -V -x

copy entire directory and subdirectories create symbolic links between file copied to directories instead of actual copy set a suffix to all new files, default is ~ does not copy to newer files verbose mode version-control numbering ignores subdirectories on remote file systems

An often used option with cp is the -R or -r option that allows you to copy not only directories but all of the sub-directories that are contained inside a directory. For example suppose you are in an office and the office maintains a directory system that contains policies and procedures as well as all client files which relate to the running of the business. All of these documents are located in one directory on the file system called /home/office. The directory system has been expanded and a new partition has been created called /off. The /off partition will contain all of the office material that is located in /home/office. Therefore, /home/office needs to be copied to /off. Here is the directory system that must be copied. /home/office /procedures /policies /activities /clients cp -R /home/office /off The command recursively (that means folders and sub-folders) copies all of the material in /home/office to /off. Now an additional problem may arise. In a Linux file system you have the ability to set permissions of read/write/execute on each file individually. Suppose the file system that was created in /home/office has individual permissions set on each file in terms of who may modify each file within the office. You need to then maintain those file permissions when you copy. That may easily be accomplished by using the -p option that will maintain permissions originally set. In this example, the same recursive action is taken by copying all of the files and folders in addition the permissions are maintained. cp -Rp /home/office /off The p option is added with the -R.

Managing Files and Text

ls
This command will list the contents of a directory. Example, this will list contents of current working directory: ls -l Options -l list files one line at a time -A lists all the contents of a directory except for current directory and parent directory -B ignore backups -c sort by change time -d lists file and directory names without contents -e lists all times in full -f lists without sorting -k lists file size in kilobytes -l lists files in long format -L list files by symbolic link -m list files horizontally separated by commas -r sorts files in reverse order -R lists files recursively -S lists files by size, biggest first -u sorts files by the last time they were accessed -x prints in columns, sorted horizontally -X sorts files alphabetically by file extension To list the contents of the present working directory type: ls data Desktop dsl-scripts.sxw focus focus1.png focus2.png focus3.png n1.png n20.png n21.png n2.png n3.png n4.png n7.png sandisk256_mini.jpg sed-scripts.sxw u1.png u2.png u3.png ub1.png ub3.png

Notice you have 3 columns listing files and images. Now try the same thing with the -l option. ls -l

Managing Files and Text

-rw-r--r-- 1 mike mike 1756 2005-07-29 09:22 data drwxr-xr-x 4 mike mike 4096 2005-07-29 05:45 Desktop -rw-r--r-- 1 mike mike 7895 2005-07-29 05:51 dsl-scripts.sxw drwxr-xr-x 2 mike mike 4096 2005-07-31 09:12 focus -rw-r--r-- 1 mike mike 608529 2005-07-04 00:45 focus1.png -rw-r--r-- 1 mike mike 630219 2005-07-04 00:45 focus2.png -rw-r--r-- 1 mike mike 367726 2005-07-04 00:46 focus3.png -rw-r--r-- 1 mike mike 630219 2005-07-04 00:49 focus6.png drwxr-xr-x 7 root root 4096 2005-03-04 06:15 jre1.5.0_02 ---cut--When you list with the -l option you get more information and it is placed on one line. The information you will receive is permissions, owner, group file size, time last modified and file name. If you had a large list of material and you wanted to list it by the time the file was changed you could use the -c option. ls -c focus focus1.png focus2.png focus3.png focus6.png The most recently changed file is first. To list all files and directories without any kind of formating choose the -f option. ls -f . .. .bashrc .bash_profile .Xauthority .xsession-errors .dmrc .gconf focus.png ---cut--Note that the -f will also list the hidden files and directories which start with a period.

Managing Files and Text

List all files horizontally only separated with a comma, ls -m Desktop, dsl-scripts.sxw, focus, focus1.png, focus2.png, focus3.png, focus6.png, jre1.5.0_02, jre-1_5_0_02-linux-i586.bin, jre-1_5_0_02-linux-i586-rpm.bin, n10.png, n12.png, ---cut--List files by size with the biggest first. ls -S jre-1_5_0_02-linux-i586.bin jre-1_5_0_02-linux-i586-rpm.bin ub6.png u3.png up1.png ub1.png ub3.png ---cut--Sort files by the last time they were accessed. Use this command: ls -u Andrew.sxc focus6.png focus3.png focus2.png focus1.png focus Desktop

mkdir
This command will create a directory with read/write/execute rights(0777). Of course it only makes sense that you must have write permissions to the directory in which you will create the new folder. Example: mkdir stuff

Managing Files and Text

10

When you use the command ls -la you see the directory is created with read/write/execute rights. The owner is the user who created the directory. drwxr-xr-x 2 mike mike 4096 2005-08-06 11:05 stuff

The mkdiir command has an option to modify the mode from 777 (read/write/execute permissions) to any mode you would like. That option is -m. mkdir -m 444 stuff dr--r--r-- 2 mike mike 4096 2005-08-06 11:08 stuff

The difference here is that the directory was created as read only (444). This saves the step of modifying the permissions after the directory is created. The other option that is very useful is to create a directory tree of folders in one command, use the -p option for this process. mkdir -p tech/docs/projects mike@ub:~$ ls tech docs mike@ub:~$ ls tech/docs/ projects This shows that the folders were created and are visible with the ls command.

mv
This command moves or renames files. Now it may seem strange that mv would be used to rename files; however, because the process of renaming a file or directory requires the same update for the directory as a move mv was used. Example: mv mytext /home/fred The file mytext is moved to the /home/fred directory and is given the name mytext. Options

Managing Files and Text


-b -f -i -S -u

11

create backup before moving remove existing destination files without asking prompt before overwriting destination files set a new suffix don't move a file to an existing location with same or newer file When you use the -f option you will not have answer any questions when the process begins. The -i option is just the opposite in that it is an interactive option so that you will be asked for each process of moving a file or directory.

rm
This will remove or delete files and directories. You must have permission to write to the directory that contains a file if you want to delete that file. Example: rm mytext -d -i -f -r,-R remove linked directories prompt before removing force delete without any prompting recursive removal, all files, directories and sub-directories

An often used option is the -R or recursive removal. This will remove all directories and the sub contents. You will probably want to use the -f option as well so you do not need to answer yes to each file and directory that is going to be used. This command can be dangerous if you are not careful. rm -fR tech/ Notice two options are used here to force the removal and to remove a directory and its contents. The -i option is a good choice if there is some question concerning if the file should be removed or not because the user will be asked to verify each removal.

Managing Files and Text

12

cat
cat will read a file and print it to standard output, usually the screen. cat is short for catenate. Example: cat mytext This will show the contents of mytext. cat mytext yourtext This will show the content of mytext and then follow it with yourtext. cat mytext yourtext > newtext This will combine the two texts into a new text file in order. Options -A prints nonprinting and control characters -e show a $ at the end of each line

sed
Sed is a stream editor which has the primary function of filtering. The filtering done by sed usually flows from standard input into sed where filtering occurs and then goes to standard output. What that means is that when sed is used to filter information in a file the output goes to the computer screen. sed has the ability to be programed by creating a sed script which allows text or other information to be filtered through the script and then go to standard output, or screen. The advantage of sed is that you can write a script and then use it time after time to filter information through it. Using a script in this fashion is very valuable when you are performing repetitive tasks. The other aspect of sed that is so important is that when it interacts with a file the file remains unchanged; sed does not by default alter any files it just filters information within those files. Sed will process a file one line at a time, As it processes each individual line it will place the output on the screen. When sed is processing a line the line is placed in a buffer that is used for that purpose, which allows sed to release the buffer once the line has been processed. The buffer, called a pattern space, then receives the next line as it is

Managing Files and Text


processed by sed. Using sed The format for using sed is simple: sed command filename

13

An example would be working with the file /etc/group. If you wanted to see a list of every group that started with a text string ct you could use sed like this: sed -n /ct/p /etc/group In the example sed is followed by the option -n which suppresses the printing to the screen of the entire pattern space and the line you are looking for. When you use -n you get the output to the screen of only your solution. Notice that /ct/ is the pattern that you are looking for and the p will print it to the screen. The file that sed will work with is /etc/group. ctools:x:106: There is your one line solution, your system may use different groups so it may be different. With some information you will not want to evaluate all of the data contained in the file that sed is working with so you may choose to use addressing which allows you to specify the lines you want to work with. Addressing uses numbers, which refer to line numbers, regular expressions or a combination of the two to specify data to work with. By default sed will work with every line so if you want to limit sed to only specific lines you must use addressing.

Sed Commands a\ b label c\ d D i\ h H g appends lines to current line of text branch to command with label or if no label branch to end of script change text in line with new text delete line from pattern space in memory delete the first line of the pattern space insert text above current line copy pattern space to a holding buffer append pattern space to holding buffer get holding buffer and copy it into pattern buffer overwriting contents

Managing Files and Text

14

G get holding buffer and copy it into pattern buffer appending contents l list nonprinting characters n read next line and start processing with the next command N append next line to pattern space,insert newline, change line number p print lines of pattern space P print first line in pattern space q exit r filename read from specific filename t label branch on error T label branch on error w filename write and append the pattern space to filename W filename write and append first line of pattern space to filename ! apply commands to all lines except ones selected s/pattern/replacement pattern replace a pattern = print the current line number # text indicates a comment sed Substitution Flags g globally substitutes p print lines w write lines to filename x exchange holding buffer contents with pattern space y translate one character to another sed Options -e command --expression=command -h, --help -n, --quiet, --silent -f filename --file=script file allow multiple commands allow multiple commands help suppress default output must precede a filename script file with sed commands

Examples of Usage A number of examples will help build understanding at this point. In order to create a safe file to work with create a file called data in your home directory that contains a listing of all files and folders in the /etc directory. Call the file data. ls /etc/ > /home/linux/data Usage of ! The usage of the exclamation point negates the current command.

Managing Files and Text


sed -n /a/p data a2ps-site.cfg acpi/ adjtime aliases@ alternatives/ armagetron/ at.deny bash_completion.d/ bashrc bonobo-activation/ bootsplash/ cron.daily/ ----cut---a2ps.cfg

15

The first example is sed used without the exclamation mark. When you use -n you get the output to the screen of only your solution. Without -n sed would print all the data and your solution. This example of sed is looking for all files and directories that have the letter a. Now the same example but with the exclamation point. sed -n /a/!p data

bluetooth/ CORBA/ cron.d/ cron.hourly/ cron.monthly/ cron.weekly/ csh.cshrc csh.login cups/ cvs/ dbus-1/ dev.d/ devfs/ ---cut---

Managing Files and Text

16

Note that A in CORBA is not the same as a, lower case. This output from sed prints every line that does not contain an a. Now create a script that will list all of the files and directories in the data file which have the letter a. Call the script seda.sh. Make sure the script is executable by using: chmod 755 seda.sh ls /etc > data2 sed -n '/a/p' data2

a2ps.cfg a2ps-site.cfg acpi/ adjtime aliases@ alternatives/ armagetron/ at.deny bash_completion.d/ bashrc bonobo-activation/ bootsplash/ ---cut--The outcome is like the first example with sed. This example demonstrates that sed needs to work with a file that contains the directory information, not the directory itself. That is why the first line in the command is ls to create a file with the output. Text strings sed is often used to search for text strings or to filter data that has text strings. Therefore understanding how sed employs text strings is very important. Sed supports a set of special characters to control pattern searching. ^ used to match the beginning of a word

sed -n /^a/p data Here sed is filtering lines in the data file that begin with the letter a. a2ps.cfg

Managing Files and Text


a2ps-site.cfg acpi/ adjtime aliases@ alternatives/ armagetron/ at.deny ---cut--sed -n -e /^a/p data -e /^b/p data

17

Now sed is filtering all words that begin with a and then the ones that begin with b from the same file data. a2ps.cfg a2ps-site.cfg acpi/ adjtime aliases@ alternatives/ armagetron/ at.deny bash_completion.d/ bashrc bluetooth/ bonobo-activation/ bootsplash/ ---cut--$ match words that end with a string

sed -n /conf$/p data This filter will list all lines with the ending of conf form the data file. esd.conf host.conf initlog.conf krb5.conf ld.so.conf lftp.conf

Managing Files and Text


libuser.conf lilo.conf

18

matches one character in line but not newline character

sed -n /d..e/p data sed will filter lines which do not start with d but have the letter d followed by any two letters and then an e. scrollkeeper.conf * matches any number of characters followed by a text strings

sed -n / *cap/p data The line must contain any number of matches followed by the text string cap. printcap termcap [Xx} matches one letter in the set

sed -n /[Xx]/p data This filter will look for lines that have either a capital X or lower case x. exports fax.config lynx-site.cfg mandrakelinux-release pentaxpj.conf postfix/ X11/ xdg/ ---cut---

Delete

Managing Files and Text

19

Often times you will want to print the output but delete one line in the output, then you would use the d command. Here is an example: sed '3d' data This command will print the data file but not line 3. Here is the output: acpi adduser.conf aliases aliases.db alsa alternatives anacrontab apm apt ---cut--sed '5,$d' data This command will print only the first four lines as it requests the deletion of line five to the end of the file. The $ is a symbol used indicate the end of the file. Here is the output: acpi adduser.conf adjtime aliases sed '/^a/d' data This sed command deletes every line that begins with the letter a. Therefore, it prints all lines but those that start with a. bash.bashrc bash_completion bash_completion.d bogofilter.cf bonobo-activation calendar cdrecord ---cut--sed -n '/^a/p' data This sed command will print only the lines that begin with a. This is not a delete command however, this demonstrates that often instead of deleting line that start with b-z it is easier to print the lines that begin with a.

Managing Files and Text


acpi adduser.conf adjtime aliases aliases.db alsa alternatives anacrontab ---cut---

20

Substituion sed is often used for substitution. The s command is used to create the substitution and you will list one string that will replace the second string. Here is an example; sed -n 's/^a/A/gp' data Here sed will print the output of replacing all lines that begin with a lower case a with an upper case A. This will be done globally in the document, that is indicated by the g. Here is the outcome: Acpi Adduser.conf Adjtime Aliases Aliases.db Alsa Alternatives Anacrontab Print Command The print command which is very common with sed is indicated by the letter p. Here is a simple print command. sed -n '/^bash/p' data This command prints all of the lines that begin with the text string bash. bash.bashrc bash_completion bash_completion.d sed -n '/^a/,/^c/p' data This sed command prints all of the lines that start with a to c and are between and c.

Managing Files and Text

21

Note that with this command it will print the first line that starts with c as well. acpi adduser.conf adjtime aliases aliases.db alsa alternatives anacrontab apm apt at.deny bash.bashrc bash_completion bash_completion.d bogofilter.cf bonobo-activation calendar

Multiple Edit Commands sed allows you to use a number of commands or edits in one line by including the -e option. sed -e 's/^bash/Bash/' -n -e '/^Bash/p' data sed will filter the outcome to change all lines that begin with bash to Bash and then print only the lines that begin with Bash. Bash.bashrc Bash_completion Bash_completion.d

sed scripts
If you need to create a script with sed that will allow you to repeat an action on a specific type of text you can create a sed script which will be activated by using the -f after the sed command followed by the filename of the script. sed -f mysedscript

Managing Files and Text

22

It is important not to leave trailing whitespace at the end of your lines in the sed script and it is important to put one sed command per line or terminate each command with a semicolon. Remember, sed will edit your text file one line at a time because that is what is placed in memory. # sed script evaluating the /etc directory /hosts.allow/a\ This file determines which networks and individual\ computers can connect to the daemons on the server /hosts.deny/c\ ***********************************\ This is an important file for security that should\ be to deny all.\ ************************************\ Here is the output of the sed script: sed -f mysdsccript data ---cut--hosts hosts.allow This file determines which networks and individual computers can connect to the daemons on the server *********************************** This is an important file for security that should be to deny all. ************************************ ---cut--In the script that is run on the file data that was created from a list of files and directories in /etc, you can see that the first sed command looks for the line, hosts.allow and then appends several lines of text to hosts.allow. The append is indicated by the a\. The next sed command then looks for the line with hosts.deny and changes the hosts.deny line to the line indicated in the script. The change is created by using the c\ command.

cmp
Compare two files.

Managing Files and Text


cmp go go.c go go.c differ: char1, line 1

23

The outcome above shows the place where these two files are different. Here is another example showing where the two files do differ so you could verify that by looking at line 1. cmp sp1.rtf sp.rtf sp1.rtf sp.rtf differ: byte 1, line 1

column
This command will format input into columns. Example: column -c 2 mytext Users Passwords fred 567kdv mary 90-jdjm tom dksowi Notice the columns are not lined up from the text. However, if you use the table option it is lined up. Options -c num sets the number of columns with num -t formats input as a table Here is an example of creating a table. column -t mytext Users Passwords fred 567kdv mary 90-jdjm tom dksowi

csplit
This command allows you to split a larger file into two smaller ones.

Managing Files and Text


Options -k keeps files even if command line fails csplit -k data 10 {75}

24

This command will create up to 75 files from the file data and split them into files with 10 lines each. The command created these files: xx00 xx01 xx02 xx03 xx04 xx05 xx06 xx07 xx08 xx09 xx10 xx11 xx12 xx13 xx14 xx15 xx16 xx17 xx18 xx19

Here is the output of looking at one of those files using the cat command: cat xx18 terminfo timezone ucf.conf udev updatedb.conf vim vnc.conf w3m

Managing Files and Text


wgetrc X11

25

cut
This command will cut columns or fields from a file and display them or make them available to move to another file. Example: cut -f5,7,8 timecard This example will cut fields 5,7,8 and display them on the screen. cut -c5,6 timecard > newinfo This example will take the columns 5,6 and place them in a new file called newinfo. Options -c list cuts columns -f list cuts fields specified in the list

diff
diff compares two files and returns the lines where there are differences. Example: diff po pi Binary files po and pi differ This gives you a basic understanding that they are different.

Options -a -b -B -c -i

compares all files ignores whitespace ignores blank lines prints 3 lines of context fore each difference ignores case

Managing Files and Text

26

Here is an example of the difference between two files which list the amount of difference and then it shows what things are different. diff data person1.rtf 1,192d0 < acpi < adduser.conf < adjtime < aliases < aliases.db < alsa < alternatives < anacrontab < apm < apt < at.deny ----cut---

egrep
This will search for patterns in multiple files. Example: egrep -wc turkey mytext 3 This returns the information that the whole word turkey is found 3 times in the file mytext. Options -c -C -e pattern -f file -i -l -L number of matches display two lines before and after each match search for pattern uses a pattern from a file ignore case lists files that contain matches lists files that have no matches

Managing Files and Text


-w

27

lists whole words that are matched

elvis
Launch the text editor which is much like vi.

emacs
Launches a powerful text editor.

expand
This command will convert tabs to spaces. Option -i converts only tabs at beginning of lines

fgrep
fgrep will search a file for a text string. This will search for patterns in multiple files. Example: fgrep -wc turkey mytext 3 This returns the information that the whole word turkey is found 3 times in the file mytext. Options -c -C -e pattern -f file -i -l -L -w number of matches display two lines before and after each match search for pattern uses a pattern from a file ignore case lists files that contain matches lists files that have no matches lists whole words that are matched

Managing Files and Text

28

fmt
The fmt command formats files by justifying the text to the right margin and eliminating new lines.

grep
This command searches a file or files for text strings. This will search for patterns in multiple files. Example: grep -wc turkey mytext 3 This returns the information that the whole word turkey is found 3 times in the file mytext. Options -A num -B num -c -C -e pattern -f file -i -l -L -w -x number of lines after the matched pattern number of lines before the matched pattern number of matches display two lines before and after each match search for pattern uses a pattern from a file ignore case lists files that contain matches lists files that have no matches lists whole words that are matched lists only whole lines that are matched

head
This command will display the beginning of a file. The default is 10 lines. Example: head -n50 /var/log/messages This will show the first 50 lines of /var/log/messages

Managing Files and Text


Here is the output of the example: head -n50 /var/log/messages

29

Aug 30 06:16:07 localhost syslogd 1.4.1#16ubuntu6: restart. Aug 30 06:21:03 localhost kernel: Inbound IN=eth0 OUT= MAC=00:d0:59:9c:3d:fc:00:0e:0c: 2e:db:32:08:00 SRC=192.168.2.63 DST=192.168.2.99 LEN=198 TOS=0x00 PREC=0x00 TTL=64 ID=2462 DF PROTO=UDP SPT=138 DPT=138 LEN=178 Aug 30 06:27:03 localhost kernel: Inbound IN=eth0 OUT= MAC=00:d0:59:9c:3d:fc:00:0e:0c: 2e:db:32:08:00 SRC=192.168.2.63 DST=192.168.2.99 LEN=198 TOS=0x00 PREC=0x00 TTL=64 ID=2473 DF PROTO=UDP SPT=138 DPT=138 LEN=178 Aug 30 06:34:03 localhost kernel: Inbound IN=eth0 OUT= MAC=00:d0:59:9c:3d:fc:00:0e:0c: 2e:db:32:08:00 SRC=192.168.2.63 DST=192.168.2.99 LEN=198 TOS=0x00 PREC=0x00 TTL=64 ID=2484 DF PROTO=UDP SPT=138 DPT=138 LEN=178 Aug 30 06:40:53 localhost kernel: e100: eth0: e100_watchdog: link down Aug 30 06:52:01 localhost kernel: e100: eth0: e100_watchdog: link up, 10Mbps, half-duplex Aug 30 07:01:22 localhost kernel: Inbound IN=eth0 OUT= MAC=00:d0:59:9c:3d:fc:00:0e:0c: 2e:db:32:08:00 SRC=192.168.5.63 DST=192.168.5.99 LEN=198 TOS=0x00 PREC=0x00 TTL=64 ID=2504 DF PROTO=UDP SPT=138 DPT=138 LEN=178 Aug 30 07:12:22 localhost kernel: Inbound IN=eth0 OUT= MAC=00:d0:59:9c:3d:fc:00:0e:0c: 2e:db:32:08:00 SRC=192.168.5.63 DST=192.168.5.99 LEN=198 TOS=0x00 PREC=0x00 TTL=64 ID=2517 DF PROTO=UDP SPT=138 DPT=138 LEN=178 Aug 30 07:24:22 localhost kernel: Inbound IN=eth0 OUT= MAC=00:d0:59:9c:3d:fc:00:0e:0c: 2e:db:32:08:00 SRC=192.168.5.63 DST=192.168.5.99 LEN=198 TOS=0x00 PREC=0x00 TTL=64 ID=2530 DF PROTO=UDP SPT=138 DPT=138 LEN=178 Aug 30 07:35:17 localhost gconfd (mike-7650): Exiting Aug 30 07:35:18 localhost shutdown[5892]: shutting down for system halt Aug 30 07:35:25 localhost kernel: apm: BIOS version 1.2 Flags 0x03 (Driver version 1.16ac) Aug 30 07:35:25 localhost kernel: apm: disabled on user request. Aug 30 07:35:29 localhost kernel: Kernel logging (proc) stopped. Aug 30 07:35:29 localhost kernel: Kernel log daemon terminating. ---cut--Options -c num -c numk -c numm -n num

first num of bytes first num kilobytes of file first num of megabytes of file number of lines

Managing Files and Text

30

less
This command displays parts of a file at request so you can read one screen or one additional at a time instead of the whole file flying by. Also, an advantage of less is that it does not read the whole file before output is placed on the screen. This means that the actual usage of less is faster than more for example. This speed difference is most evident in larger files. Options Space scroll forward one line at a time D scroll forward screen at a time Return scroll forward one line at a time B scroll backward one screen U scroll backward screen at a time Y scroll backward one line g scroll to beginning of text G scroll to the end of text H help :n show next file ;p show last file /textpattern search for a text pattern ?textpattern search backward for a text pattern The file used for an example is called data. The command to use for normal operations is the less command followed by the filename: less data acpi adduser.conf adjtime aliases aliases.db alsa alternatives anacrontab apm apt at.deny bash.bashrc bash_completion bash_completion.d bogofilter.cf

Managing Files and Text


bonobo-activation calendar cdrecord chatscripts console console-tools cron.d cron.daily data

31

The example shows the output of the less command. The output stops at the end of the first page and the word data, shown in the example, has a cursor on it that is blinking. It is waiting for input to go to another screen line, etc. When you enter commands it will take place from this blinking cursor. This is important to consider when you are doing a search because you may want to search either forward or backward. If you wanted to search the document for conf files or the text string conf you would use this command: /conf Here is the output; notice it stops on the first conf file located. adduser.conf adjtime aliases aliases.db alsa alternatives anacrontab apm apt at.deny bash.bashrc bash_completion bash_completion.d bogofilter.cf bonobo-activation calendar cdrecord chatscripts console console-tools

Managing Files and Text


cron.d cron.daily cron.hourly :

32

If you choose the command n at this point you will see all the next conf files highlighted. See the output. Again notice the colon at the end waiting for a command.

debconf.conf debian_version default defoma deluser.conf dev.d devfs dhcp3 dictionaries-common discover.conf discover.conf-2.6 discover.conf.d discover.d dm dpkg emacs environment esound evms.conf fdmount.conf firestarter fonts foomatic :
Another common way of using less, is to pipe a file into less for the same output. cat data | less

Managing Files and Text

33

This command gives you the same output as the first command. The pipe symbol is used to input the data file through less.

lpq
This will check the print spool. It will return information on all jobs in the queue. It will return the user's name, and current rank in the queue. Options -l -Pprinter

prints information about each file in a job entry designates a specific printer

lpr
This command sends files to a print-spool daemon, which allows it to go to the printer when available. Example: lpr mytext

Options -m -Pprinter

send mail when job complete sends output to specific printer

lprm
This will remove print jobs from the printer. Options -Pprinter sends output to specific printer

Managing Files and Text


-user removes jobs owned by a user

34

more
This command will display all or parts of a file. Type q to quit more. Commands b move backwards one screen d scroll 11 lines f forward one screen z display next screen Options +num start display at line number +/pattern search for pattern before file is displayed

nl
The nl command is used to number lines in a text file. The command allows you to add options to create the style of numbering required. Here is an example: nl -b t data 1 acpi 2 adduser.conf 3 adjtime 4 aliases 5 aliases.db 6 alsa 7 alternatives 8 anacrontab 9 apm ---cut--In this example the style to number only lines that have text has been chosen. Options -b set numbering to style chosen, t is the default

Managing Files and Text


-f -h

35

set the footer number style n being the default set the header numbering n being the default

Numbering Styles A set a number for every line even if empty t number only lines with text n do not number lines p textstring search for a specific text string in the file Here is an example of searching for a text string which is searching for the text string vim. nl -b pvim data 1 vim vnc.conf w3m wgetrc X11 xdg xml xpdf

od
The od command will dump a file into a specific format. This command is often used to check on byte codes of binary files. Options The options are available by first using the -t to signify the type of output. A c O x named character ASCII character octal format hexidecimal

example: od -t c data 0000000 0000020 0000040 0000060 0000100 0000120 0000140 a c f \n s \n a \n n a t \n a s p a a a c a h i d l l r t r \n a d d u s e r . c o n j t i m e \n a l i a s e i a s e s . d b \n a l s t e r n a t i v e s \n a o n t a b \n a p m \n a p . d e n y \n b a s h . b c \n b a s h _ c o m p l

Managing Files and Text


0000160 0000200 0000220 0000240 od data e e e i t t r v i i . a o o c t n n f i \n . \n o b a d \n b o n \n s b n c h o o a

36
_ c o m p l g o f i l t b o - a c t l e n d a r

0000000 061541 064560 060412 062144 071565 071145 061456 067157 0000020 005146 062141 072152 066551 005145 066141 060551 062563 0000040 005163 066141 060551 062563 027163 061144 060412 071554 0000060 005141 066141 062564 067162 072141 073151 071545 060412 0000100 060556 071143 067157 060564 005142 070141 005155 070141 0000120 005164 072141 062056 067145 005171 060542 064163 061056 0000140 071541 071150 005143 060542 064163 061537 066557 066160 0000160 072145 067551 005156 060542 064163 061537 066557 066160 0000200 072145 067551 027156 005144 067542 067547 064546 072154 ---cut---

od -t x data 0000000 69706361 6464610a 72657375 6e6f632e 0000020 64610a66 6d69746a 6c610a65 65736169 0000040 6c610a73 65736169 62642e73 736c610a 0000060 6c610a61 6e726574 76697461 610a7365 0000100 7263616e 61746e6f 70610a62 70610a6d 0000120 74610a74 6e65642e 61620a79 622e6873 0000140 72687361 61620a63 635f6873 6c706d6f 0000160 6f697465 61620a6e 635f6873 6c706d6f 0000200 6f697465 0a642e6e 6f676f62 746c6966 0000220 632e7265 6f620a66 6f626f6e 7463612d 0000240 74617669 0a6e6f69 656c6163 7261646e 0000260 7264630a 726f6365 68630a64 63737461 0000300 74706972 6f630a73 6c6f736e 6f630a65 ---cut---

Managing Files and Text

37

paste
This will merge two files placing the text side by side in columns. There are two major options. Options -d'n' this will separate columns with character n -s merge lines from one file to a single line A simple example of paste are two files t1 and t2. t1 has the text 456 and t2 has the text test. When these are put together with paste it looks like this: paste t1 t2 456 test

Another option is to separate the columns using a letter instead of a tab. Here is an example: paste -d'#' t1 t2 456#test

pico
Launches the pico text editor.

sort
This will sort or merge lines of text and write them to screen. Options -o file -m -d -k

writes output to file merge sorted files dictionary sort sort by key

Managing Files and Text

38

Database or file named info which contains three fields with addresses. These can be sorted with the sort command by any of the three fields. mike tom mary Helena Missoula Butte 56 Montana Street 43 South Street 84 Copper Street

Here is an example using sort with the default settings: sort info mary mike tom Butte Helena Missoula 84 Copper Street 56 Montana Street 43 South Street

Here is the same example sorted by the third field: sort -d -k 3 info tom mike mary Missoula Helena Butte 43 South Street 56 Montana Street 84 Copper Street

The -d is for dictionary sort and the -k allows you to chose a field, field 3 which is the actual street addresses is used for the sort.

pr
The pr command converts text files into paginated, columnar output and can include headers and page fills. Options -d -h header -l lines -o width double space include a header set line length, the default is 66 set the left margin to width

Here is an example using a header for the file info: pr -h MyAddresses info

Managing Files and Text


2005-09-04 04:02 mike tom mary Helena Missoula Butte MyAddresses 56 Montana Street 43 South Street 84 Copper Street

39
Page 1

split
If you needed to split a file into smaller sections to manipulate in a program you could use the split command. Options -n line number the default number of lines is 1000 In this example the file data is split into sections having 5 lines each. Also notice that each new file has a prefix datasplit_ added to the command to enable you to differentiate the new files. split -5 data datasplit_ datasplit_aa datasplit_ab datasplit_ac datasplit_ad datasplit_ae datasplit_af datasplit_ag datasplit_ah datasplit_ai datasplit_aj datasplit_ak datasplit_al datasplit_am datasplit_an datasplit_ao datasplit_ap datasplit_aq datasplit_ar ---cut---

Managing Files and Text

40

In the example you can see that the default is to start with a file name of aa and precede onward. Here is a look at the content of datasplit_aa cat datasplit_aa acpi adduser.conf adjtime aliases aliases.db Just as expected each file contains five lines of text.

tac
The tac command is the opposite of cat. cat prints the contents of a file from beginning to end while tac prints the contents of files from end to beginning. See the example of the file below. cat info mike tom mary tac info mary tom mike Butte Missoula Helena 84 Copper Street 43 South Street 56 Montana Street Helena Missoula Butte 56 Montana Street 43 South Street 84 Copper Street

tail
By default it will print the last 10 lines of a file to screen. Example: tail -f /var/log/messages This command will allow you to monitor your screen as the file continues to grow. This is a very handy troubleshooting tool as you are able to see problems develop in the logs.

Managing Files and Text


Options -c num -f -l num

41

display num number of bytes loop forever trying to the file as it grows display num number of lines

Here is an example of the default 10 lines: tail /var/log/messages Sep 4 02:33:47 localhost gconfd (mike-7657): Resolved address "xml:readonly:/etc/gconf/gconf.xml.defaults" to a read-only configuration source at position 2 Sep 4 02:34:01 localhost gconfd (mike-7657): Resolved address "xml:readwrite:/home/mike/.gconf" to a writable configuration source at position 0 Sep 4 02:38:10 localhost exiting on signal 15 Sep 4 02:38:11 localhost syslogd 1.4.1#16ubuntu6: restart. Sep 4 02:58:13 localhost -- MARK -Sep 4 03:18:14 localhost -- MARK -Sep 4 03:38:14 localhost -- MARK -Sep 4 03:58:16 localhost -- MARK -Sep 4 04:18:17 localhost -- MARK -Sep 4 04:38:17 localhost -- MARK --

tee
The output of a command may be sent to two separate files with the tee command. If a file exists, it will overwrite it. Example: mike@ub:~$ ls | tee tee.rtf 1st_file 2nd_file 3com.jpg Andrew.sxc blue alien.jpg cbslinux cbslinux~ data Desktop focus focus1.png

Managing Files and Text


interactive_test.sxw jre1.5.0_02 jre-1_5_0_02-linux-i586.bin jre-1_5_0_02-linux-i586-rpm.bin messages.rtf mysedscript n10.png n12.png n13.png n1.png

42

The example shows the output to the screen and also note that a file called tee.rtf was created with the same content. Options -a appends but does not overwrite -i will ignore interrupt signals The append option allows you to create a file and add to it constantly to create a reference. touch Change the access and /or the modification times on a file. Example: touch -t 200103251635 mytext This command changes the timestamp to March 25,2001 at 4:35 p.m. 2001 Year 03 March 25 Day 1635 Military time Options -a -m -t timestamp

change the access time change the modification time change the timestamp in the form CCYYMMDDhhmm

tr
The tr command will translate the characters from one string to another string of text. The two strings must correspond to one another.

Managing Files and Text

43

Options -d delete characters from string as it goes to output -s squeeze out repeated characters in string In this example the contents of the file info are first viewed with cat and then the letters are all changed to caps, cat info mike tom mary Helena Missoula Butte 56 Montana Street 43 South Street 84 Copper Street

cat info | tr a-z A-Z MIKE TOM MARY HELENA MISSOULA BUTTE 56 MONTANA STREET 43 SOUTH STREET 84 COPPER STREET

merge
This command will merge three files and add all the changes from file2 and file3 into file1. Example; merge text1 text2 text3

rm
This will remove files. Example:

Managing Files and Text


rm mytext -d -i remove linked directories prompt before removing

44

rmdir
Removes empty directories. This command will not remove directories that have files.

wc
wc will provide you with a listing of character count, line count and word count. Options -c print character count -l print line count -w print word count This example shows first the word count on the file data and then the character count. wc -w data 192 data mike@ub:~$ wc -c data 1756 data

xargs
This command will run a command multiple times to make sure the arguments are all executed. Options -n numberarguments limit number additional arguments

In the example the arguments are only run one time. This example is searching for each occurrence of the string vim from the root directory.

Managing Files and Text

45

find / -type f | xargs -n 1 grep vim # vim:ft=sh: complete -f -X '*.@(o|so|so.!(conf)|a|tar?(.@(gz|bz2))|tgz|tbz2|rpm|zip|ZIP|gif|GIF|jp?(e)g| JP?(E)G|mp3|MP3|mp?(e)g|MPG|avi|AVI|asf|ASF|ogg|OGG|class|CLASS)' vi vim gvim rvim view rview rgvim rgview gview grep: /etc/apt/secring.gpg: Permission denied grep: /etc/apt/trustdb.gpg: Permission denied # vim:ts=4:sw=4: # vim:set ai et sts=2 sw=2 tw=0: # vim: syntax=sh # vim: syntax=sh # vim:syntax=sh # vim:set ai et sts=2 sw=2 tw=80: # vim:set ai et sts=2 sw=2 tw=80: # vim:set ai et sts=2 sw=2 tw=80: # vim:set ai et sts=2 sw=2 tw=80: # vim:set ai et sts=2 sw=2 tw=80: ---cut---

Managing Files and Text

46

Managing System and Program Information

Managing System and Program Information

47

cal
If you are looking to see what day your birthday will appear in 237 years, this is the program you need. cal can display any year from 1 to 9999. The simplest way to use cal is to just type cal and you will get the current month and year. cal August 2005 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 If you want a specific month of a year type the month and year: cal september 2005 September 2005 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

Managing System and Program Information


18 19 20 21 22 23 24 25 26 27 28 29 30

48

Do not abbreviate the year by using 05 as you will get the year 05 not 2005.

cal september 05 September 5 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 Options -3 print months before and after selected month -J display Julian Calendar -m print a calendar with Monday as first day of week -w print the number of week below each column -y print present year cal -3 This will print the months before and after present month. July 2005 August 2005 September 2005 Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 2 1 2 3 4 5 6 1 2 3 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10 10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17 17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24 24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30 31 cal -m This command shows the days starting with Monday instead of Sunday. August 2005 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Managing System and Program Information


15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 cal -y This will display the whole year. 2005

49

January February March Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 1 2 3 4 5 1 2 3 4 5 2 3 4 5 6 7 8 6 7 8 9 10 11 12 6 7 8 9 10 11 12 9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19 16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26 23 24 25 26 27 28 29 27 28 27 28 29 30 31 30 31 April May June Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 2 1 2 3 4 5 6 7 1 2 3 4 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11 10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18 17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25 24 25 26 27 28 29 30 29 30 31 26 27 28 29 30 July August September Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 2 1 2 3 4 5 6 1 2 3 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10 10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17 17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24 24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30 31 October November December Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 1 2 3 4 5 1 2 3 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17 16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24 23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31 30 31

Managing System and Program Information

50

date
This command will display the current date and time. Example: date Sun Nov 11 12:35:52 MST 2001 date has a lot of variables that you may change using this format: date +%A Sunday The date command with the + and %A prints the full spelling of the day. Here are more formats: %a abbreviates the day %A spells out the day %b abbreviates the month %B spells out the month %d returns the day in two digits %D returns the date in mm/dd/yy format %e returns the day as a numeral 1-31 %h abbreviates the month %H returns time in a military hour %m returns the month in two numerals %M returns the number of minutes %S returns the number of seconds 0-59 %T returns time in hh:mm:ss format %Z returns a time zone name If you have the rights to change the time this option -s will allow you to set the time. If you were root and wanted to change the date and time to August 8, 2005 at 8:46 AM you could use the following command. date 0708084605 Fri Jul 8 08:46:00 MDT 2005 07 - august 08 - day 0846 - 8:46 AM 05 - 05

&
Use this command to place a command in the background.

Managing System and Program Information

51

bg
This command will allow you to place a command in the background and continue function. In the example you see a series of commands in reference to the command top. First you see top being placed in the background by using the command and &. This lists the job number 1 and the PID 17422. You may also place a command in the background by stopping a program with Ctrl+z and the command bg; which is also shown in the example. The program is brought to the foreground with the fg command and is then seen in the output on the screen as shown. top & [1] 17422 bg [1]+ top & fg top top - 12:59:30 up 10:28, 2 users, load average: 0.14, 0.11, 0.17 Tasks: 78 total, 2 running, 76 sleeping, 0 stopped, 0 zombie Cpu(s): 15.1% us, 1.2% sy, 0.0% ni, 83.6% id, 0.0% wa, 0.1% hi, 0.0% si Mem: 256812k total, 206284k used, 50528k free, 2236k buffers Swap: 514040k total, 114208k used, 399832k free, 66296k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 9273 mike 16 0 38556 9532 7156 R 9.9 3.7 0:17.48 gnome-terminal 6009 root 15 0 84484 35m 4876 S 4.4 14.2 118:55.81 Xorg 9110 mike 15 0 185m 47m 23m S 0.9 18.8 5:23.15 soffice.bin 7703 mike 15 0 12908 6576 5744 S 0.4 2.6 0:13.55 metacity 7722 mike 15 0 18016 8272 7020 S 0.2 3.2 0:12.53 wnck-applet

fg
Use this command to bring a command to the foreground.

jobs
This will list the current jobs in the foreground or background. Options -l list PIDs The example shows the top command placed in the background and then jobs is used to

Managing System and Program Information


show programs in the background. top & [1] 17537 mike@ub:~$ jobs [1]+ Stopped top nice

52

nice works with the scheduling algorithm of the operating system to adjust the priority of individual programs on the system. A Linux system has a scheduling process where the operating system must adjust access to the processor for each program that is running whether it is a background job, a process waiting for a time slice or a program actively using the CPU. The problem is that CPU can only process one program at a time. Therefore to service many processes running on the system the CPU scheduling must allocate a time slice for each process and set priorities for those time slices. This whole process is dynamic and is constantly monitored by the scheduling of the CPU. The value of being dynamic is that any processes that have been waiting for a long period of time will get a elevated priority by the scheduler. The nice command will allow you to set priorities for how commands are executed. The increment must be in the range of 1-19. If the user does not specify a number the number 10 is assumed. Any increment which exceeds 19 will receive the 19 priority. The lower the number, including negative numbers, the higher the priority. This means that the number 5 is a lower priority than the number -4. The lowest priority is 19 and the highest priority is -20. Only root is able to use the negative numbers. The syntax for nice is as follows: nice -n increment command argument Example: nice -n +12 vi project.rtf In this example nice decreases the number by 12 for the command vi. The argument is the file that vi will edit. Here is an example outcome when a normal user tries to increase the priority using negative numbers. mike@ub:~$ nice -n-10 vi test.rtf nice: cannot set priority: Permission denied

Managing System and Program Information

53

renice
renice will allow you to alter the scheduling priority of a process that is viewed as the target, which is usually the PID. Options -u targets interpreted as usernames -p targets interpreted as PIDs This example shows a new instance of top is initiated so that there are two instances of top running. Next the example shows that renice is used to change the priority of top. Remember positive numbers lower the priority and negative numbers will increase the priority. It shows that top is reduced in priority from 0 to 19. top & [2] 17660 [2] Stopped top mike@ub:~$ renice 20 17660 17660: old priority 0, new priority 19 jobs [1]+ Stopped [2] Stopped top top

Managing System and Program Information

54

Troubleshooting

Troubleshooting

55

fsck - Recovering from a System Crash


At some point your system will crash and you need to perform a manual repair of your file system. A typical situation would be power loss while you are working on the system. You reboot and the system stops and indicates you must perform a manual repair of the system using fsck. Hers is a sample of the text you may see: /dev/hda1 not cleanly unmounted, check forced. fsck .........54% inode 1130517 zero dtime ...........Fixed fsck failed. Please repair manually and reboot. Please note that the root file system is currently mounted read-only. To remount it read-write: mount -n -o remount, rw / Control-D will exit from this shell and REBOOT the system.

Troubleshooting

56

O.K. i t looks like a nightmare...but it is not so bad if you do a few basic things. Your file system is installed on a partition on the hard drive and it is that partition that you need to run the manual check on. If you have it on hard drive and it is divided into two partitions, one for swap and one for the file system, then it will look like this: /dev/hda1 /dev/hda2 The dev part of this signifies that it is an attached device. Notice that hd stands for hard drive and the a means that it is the first hard drive or Master on the primary disk controller. Now one of these will be swap space and the other will be your distribution. So you need to run the program fsck on your file system partition. fsck /dev/hda1 This command would start a manual scan of the partition hda1. If you do this and it says it cannot use fsck on swap file then do it on the second one: fsck /dev/hda2 That is all you have to do most of the time as it will be automatically fixed. The actual program that does the fixing is fsck which tries to repair the Linux file system. Often times the fsck will give an exit code which will tell you what has happened when it is done: 0 No errors 1 File system errors corrected 2 System should be rebooted 4 File system errors left uncorrected 8 Operational error 16 Usage or syntax error

You could also use fsck to repair a mount point like /usr fsck /usr When you are done what you will need to do is reboot the machine at the command prompt type: init 6 When the machine reboots it should be OK. If it is not OK...well I hope you have a backup.

57
e2fsck The e2fsck program is much the same as fsck; it is used to check a file system on a partition for consistency. When you format a disk partition in Linux, you set aside part of the disk for storing pointers that are used to locate the actual disk blocks that make up the files; these pointers are called inodes. The inodes and other important information about the files system including: the size of the files system, file system label and the number of inodes is stored in what is called the superblock. The superblock is so important that if it gets corrupted the rest of the files system is unavailable. However, because it is so valuable the superblock is duplicated every 8192 blocks. The first copy is at 8193, the second copy is at 16385. Now, if your first superblock is completely toast, you can still repair the file system by going to the second block. Example: E2fsck -b -y 8193 /dev/hdc5 -b tells the program to use an alternative superblock. -p Automatic repair with no questions. -n Make no changes to the file system -y Answer yes to all questions. -c Check for bad blocks. -f Force checking even if the file system is marked clean. -v Give a lot of information, verbose. fsck The file system in Linux can become corrupted by many things including; turning the power off your computer before you shutdown Linux, a driver error, or even when the electricity goes off. When these things happen, the fsck program reports file inconsistencies. fsck can only repair structural problems of the file system. When the fsck program finds errors it prompts you to repair them. With fsck you have the following options: -p Preen - this performs automatic repairs that do not change the contents of files. Lost files are placed in the lost+found directory, files that are actually zero length are deleted, and missing blocks are placed back on the list of free blocks (blocks that data can be placed on). -n This only lists the problems, and answers no to all prompts. -y This answers yes to all prompts and repairs the damage regardless of severity. -f This forces a file system check.

58
xvidtune This command will allow you to fine-tune your video performance. It would be a good idea to heed the warnings when you start the program.

The warning is something you need to consider when you use the program. However, any misconfiguration of the Xwindow can have the same bad effects.

59

xwininfo
This command will return information on a specified window. Here is an example: xwininfo xwininfo: Please select the window about which you would like information by clicking the mouse in that window. xwininfo: Window id: 0x34006c2 "The GIMP" Absolute upper-left X: 1150 Absolute upper-left Y: 688 Relative upper-left X: 5 Relative upper-left Y: 23 Width: 192 Height: 245

60
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: +1150+688 -58+688 -58-117 +1150-117 -geometry 4x0-53+665

xload xload is a historical graph of your system load. Simple, but helpful. This small graph can be left open to help you evaluate the load on your system while performing other tasks.

61

62

Managing Network Connections

63

Managing Network Connections

chkconfig
This command is used to activate and deactivate services. Example: chkconfig - -list Notice in the list the columns represent run levels that each program is on or off. chkconfig You can change run levels for programs using this command.

64
Example: chkconfig --level 345 msqld off First notice that there are two dashes in front of level. This command turns off mysqld in run levels 3,4 and 5.

ping
Testing Network Connections. Purpose of ping This program will help determine if a computer is online by sending a ICMP ECHO_REQUEST. The expected response is in the form of ICMP ECHO_RESPONSE. In other words, there should be a return response from the machine that was contacted.

Syntax ping [options] destination Example: ping -c 100 192.168.4.35 The -c option provides the ability to set how many pings should occur before the command stops. In this example the destination will be pinged 100 times as the count follows the option.

65

Stopping the ping Command Turn off the pings using ctrl+c

ping Options

Options -c count -s size -I Interface -i interval -f flood

number of packets to send determines the size of the packets to be sent which network card to use time interval continuous stream of packets

Count Option Example: ping -c 100 192.168.4.35 The -c option provides the ability to set how many pings should occur before the command stops. In this example the destination will be pinged 100 times as the count follows the option.

66

Size Option Example: ping -s 100 192.168.4.35 The ICMP header data contains 8 bytes of data and 56 bytes are sent by default so 64 bytes is what is typically sent by ping. The example shows sending 100 bytes and so the added 8 bytes of data will send a total of 108 bytes.

Interface Option Example: ping -I eth1 192.168.4.35

67
The interface option -I allows the user to choose which network card to use. network interfaces start with eth0 and increase. eth1 is the second network interface. Interval Option Example: ping -i .2 192.168.4.35 The -i option allows a time interval change. the default time interval is 1 second. This interval may be dropped to .2. After that root rights must be used to decrease it further. Flood Option Example: ping -f 192.168.4.35 The -f option floods a destination with continuous pings. Users must be root to run this option. Be careful as there may be serious consequences to using this unwisely.

ping is often used to establish that a network connection is actually up. ping 192.168.5.222 PING 192.168.5.222 (192.168.5.222) 56(84) bytes of data. --- 192.168.5.222 ping statistics --18 packets transmitted, 0 received, 100% packet loss, time 16996ms This would suggest that the node or computer on the network does not have a functioning

68
network connection, possibly because of a network configuration issue or the computer is off. Again, another look at this output and you would think the computer is down when in fact the computer is blocking pings from the network. Notice the output is exactly the same as the output if the computer was off. This makes this test a questionable evaluation unless you know for sure the computer is not blocking pings from the network. Keep this in mind when making decisions about your network. ping 192.168.5.222 PING 192.168.5.222 (192.168.5.222) 56(84) bytes of data. --- 192.168.5.222 ping statistics --18 packets transmitted, 0 received, 100% packet loss, time 16996ms

ftp
This will allow you to connect to an ftp server to download or upload text or programs. When you are finished type quit. Example: ftp 192.168.5.45 This will connect you to the ftp server at the IP address. You will need a username and password. ftp rpm.com The same result but using a host name.

host
This command allows you to check the IP address of a host. Example: host abc.com This will return the following:

69
abc.com has address 204.202.136.19 abc.com has address 204.202.136.32

ifconfig
ifconfig is used to configure the network interfaces and parameters.

Syntax ifconfig interface parameters Example: ifconfig eth0 192.168.3.45 netmask 255.255.255.0 If parameters are not given the interface and the configuration for that interface are given. If the interface is not indicated then it will list all available information for active interfaces.

Output With no options this is an example of the output listing the enabled interfaces and loopback, lo

70
eth0 Link encap:Ethernet HWaddr 00:03:0C:11:F6:A4 inet addr:192.168.3.18 Bcast:192.168.5.255 Mask:255.255.255.0 inet6 addr: fe80::203:dff:fe11:f6a9/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:16535 errors:0 dropped:0 overruns:0 frame:0 TX packets:17674 errors:0 dropped:0 overruns:0 carrier:0 collisions:1782 txqueuelen:1000 RX bytes:14901259 (14.2 Mb) TX bytes:2966504 (2.8 Mb) Interrupt:217 Base address:0xe800 Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:199 errors:0 dropped:0 overruns:0 frame:0 TX packets:199 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:122418 (119.5 Kb) TX bytes:122418 (119.5 Kb)

lo

Activating Interfaces ifconfig eth0 up This command will activate the eth0 interface. ifconfig eth0 down This will shut down the eth0 interface. The interface needs to be chosen so that the correct interface is taken up or down.

71
ifconfig ipaddress The ipaddress can be set for a network card using this option. It is important to indicate the network interface that should have the ipaddress. Example: ifconfig eth0 192.168.3.45 netmask 255.255.255.0 The ipaddress 192.168.3.45 and the netmask of 255.255.255.0 are added to the eth0 interface. ifconfig netmask The network mask can be set for a network card using this option. It is important to indicate the network interface that should have the netmask. Example: ifconfig eth0 netmask 255.255.255.0 The netmask of 255.255.255.0 is added to the eth0 interface.

mail
The mail program will list mail that has been sent. Select the last mail which you just sent by typing the number corresponding to the mail. You will see something similar to this: ########################################## From mike@tc.mytestserver.com Mon Mar 28 03:19:17 2005 X-Original-To: mike Delivered-To: mike@tc.mytestcomputer.com Date: Mon, 28 Mar 2005 03:19:17 -0700 (MST) From: mike@tc.mytestcomputer.com (mike) To: undisclosed-recipients:; this is a test of the sendmail program ########################################### The text that you see above your line of text for the mail is called the header. The header

72
is a portion that is added by sendmail. The body, which is separated from the header by a blank line, is the content of your email. The header format is based on a word which is followed by a colon. The word establishes the content of the line that follows. For example, Delivered-To: describes the user the mail was actually delivered to. The Subject: of the header is a optional feature. The Subject: can be added by editing your original file and adding: Subject: Test ########################################### From mike@tc.mytestserver.com Mon Mar 28 04:02:15 2005 X-Original-To: mike Delivered-To: mike@tc.mytestserver.com Subject: test Date: Mon, 28 Mar 2005 04:02:15 -0700 (MST) From: mike@tc.mytestserver.com (mike) To: undisclosed-recipients:; this is a test of the sendmail program ########################################### The Subject: line is now viewable in the header since you manually added it to your file like an email program does. Try to add two Subject: lines...notice the result. ########################################### ...snip Subject: test Subject: new test Date: Mon, 28 Mar 2005 04:12:06 -0700 (MST) ..snip ########################################### Sendmail is looking for a format string, text + : which it determines how it will be used in the header. Try to add a line for FROM: Add this line to your file:

73
From: Aliens ########################################### From mike@tc.mytestserver.com Mon Mar 28 04:02:15 2005 X-Original-To: mike Delivered-To: mike@tc.mytestserver.com Subject: test From: Aliens@tc.mytestserver.com ########################################### Notice that the program interprets the From: Aliens to be a header line even though a line has already been added by sendmail for the real person who sent the message. This gives you some idea about how spammers will manipulate the header to try to fool recipients about the real originator of the message.

Understanding Header Files


Return-Path: <root@ns.bigstrike.org> The Return-Path provides you with the address of the sender so you will be able to return an email. Received: from psmtp.com (exprod5mx120.postini.com [64.18.0.34]) by mail1.example.com (8.12.10/8.12.2) with SMTP id j3UGkfgL028886 for <mike@example.com>; Sat, 30 Apr 2005 10:46:41 -0600 (MDT) The message was received from the psmtp.com server, IP Address is listed. Notice that the mail has traveled between two servers before it was delivered. The psmtp.com server sent the mail to the pop3 server mail1.example.com. The version of sendmail is 8.12.10 and the SMTP is is listed for delivery. Finally the time and date are available for when the mail was accessed. Received: from source ([12.32.36.122]) (using TLSv1) by exprod5mx120.postini.com ([64.18.4.10]) with SMTP; Sat, 30 Apr 2005 09:46:34 PDT The psmtp.com server received the mail from the source or sender who was at 12.32.36.122, date and time are listed. Received: from ns.bigstrike.org (ns.bigstrike.org [127.0.0.1]) by ns.bigstrike.org

74
(8.13.1/8.13.1) with ESMTP id j3UGhuFc016030; Sat, 30 Apr 2005 10:43:56 -0600 The mail was sent from the source of ns.bigstrike.org. Note that ns.bigstrike.org is running a newer version of sendmail. Received: (from root@localhost) by ns.bigstrike.org (8.13.1/8.13.1/Submit) id j3UGhuOk016029; Sat, 30 Apr 2005 10:43:56 -0600 The third Received shows who the sender was, the root user. The next group of information is added by the local machine. Date: Sat, 30 Apr 2005 10:43:56 -0600 This is the date the mail was sent. From: root <root@ns.bigstrike.org> The is the user who sent the mail. Message-Id: <200504301643.j3UGhuOk016029@ns.bigstrike.org> This is the Message-ID the format is year,month,day,time.id To: mike@ns.bigstrike.org This is who the mail is sent to. Subject: Test for Company Subject of the email. Cc:mike@example.com X-pstn-levels: (S:13.87598/99.90000 R:95.9108 P:95.9108 M:97.0232 C:98.7678 ) These are timeout settings. X-pstn-settings: 5 (2.0000:2.0000) s gt3 gt2 gt1 r p m c

X-pstn-addresses: from <root@ns.bigstrike.org> [3075/137] Status: X-Evolution-Source: pop://mike@bigstrike.org Evolution received the mail on the desktop. Mime-Version: 1.0

75
9.6. Mail Delivery Agents

neat
This command will open the Network configuration tool GUI on Fedora and Red Hat distributions.

netstat
Example: netstat -r This will display the routing table for your computer including: Destination, Gateway, Mask, Flags, and Interface. Options -r display routing table -i display interfaces -s display statistics The first example shows the routing table for a networked computer. netstat -r Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface 192.168.2.0 * 255.255.255.0 U 00 0 eth0 default 192.168.2.222 0.0.0.0 UG 00 0 eth0 The next example shows the interfaces. netstat -i Kernel Interface table Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR

76
Flg eth0 1500 0 20034 lo 16436 0 320359 0 0 0 0 0 19150 0 320359 0 0 0 0 0 BMRU 0 LRU

The last example shows statistics that can be handy for troubleshooting. netstat -s Ip: 340684 total packets received 0 forwarded 0 incoming packets discarded 339514 incoming packets delivered 339665 requests sent out Icmp: 0 ICMP messages received 0 input ICMP message failed. ICMP input histogram: 20 ICMP messages sent 0 ICMP messages failed ICMP output histogram: destination unreachable: 20 Tcp: 1121 active connections openings 5 passive connection openings 0 failed connection attempts 228 connection resets received 2 connections established 338456 segments received 338439 segments send out 43 segments retransmited 0 bad segments received. 191 resets sent Udp: 1038 packets received 20 packets to unknown port received. 0 packet receive errors 1215 packets sent TcpExt: 100 TCP sockets finished time wait in fast timer 22904 delayed acks sent 2 delayed acks further delayed because of locked socket Quick ack mode was activated 21 times 134948 packets directly queued to recvmsg prequeue. 9313 of bytes directly received from backlog

77
4577720 of bytes directly received from prequeue 29032 packet headers predicted 118005 packets header predicted and directly queued to user 1955 acknowledgments not containing data received 146656 predicted acknowledgments 0 TCP data loss events 3 timeouts after reno fast retransmit 3 retransmits in slow start 23 other TCP timeouts 38 times receiver scheduled too late for direct processing 19 connections reset due to unexpected data 103 connections reset due to early user close 2 connections aborted due to timeout

route
Purpose of route route provides a command that enables the user to manipulate the routes to and from the computer. route Syntax route options Without options the route command will display the current routing table. route add options target The route add command will add routes, gateways, etc. to the routing table. route del options target The route del command will remove routes, gateways, etc from the routing table.

route Options -net -host -C target is a network target is a single host display kernel routing cache

78
netmask gw default specify the mask to add gateway this is the location of the default gateway

route Output Kernel IP routing table Destination Gateway 192.168.3.0 * link-local * loopback * default 192.168.3.1 Genmask 255.255.255.0 255.255.0.0 255.0.0.0 0.0.0.0 Flags U U U UG Metric 0 0 0 0 Ref Use Iface 0 0 eth0 0 0 eth0 0 0 lo 0 0 eth0

This shows output of route with no options. Notice the default gateway is 192.168.3.1 and there is only one network card, eth0. The U flag indicates that connection is up and the G flag is for gateway. The Metric is the number of hops to that target.

route add default gw Example: route add default gw 192.168.3.1 eth0

79
There is only one default gateway. This is typically the route that a computer must take to access the Internet. It is possible to add an additional gateway but it would not be the default.

telnet
telnet is a client program to connect to a telnet server. Once it is opened you will be asked for a username and password. Example: telnet mysite.com telnet 192.168.4.56 This will allow you to telnet to an IP address. Notice the example is a private IP address. Commands Glossary: user: identifies the username pass: issues the password stat: gets the mailbox statistics list: lists the mails in the mailbox retr x: retrieves mail #x from the list above dele x: marks mail #x from the list top x y: retrieves the first y lines of mail #x (for example top 2 400 will get the first 400 lines of mail #2) rset: reset the mailbox state and undelete any mails that were marked for deletion in the current session noop: this does nothing, just a command usually used to keep the connection alive while you sip your coffee quit: quit the serve Using telnet to Access a Routers Here is an actual example: telnet 192.168.5.79 Trying 192.168.5.79... Connected to 192.168.5.79. Escape character is '^]'.

80
Password: **** At this point the Main Menu is visible and all aspects of the router may be configured. Here is an example of the Main Menu. Copyright (c) 1994 - 2002 ZyXEL Communications Corp. Prestige 643 Main Menu Getting Started 1. General Setup 3. Ethernet Setup 4. Internet Access Setup Advanced Applications 11. Remote Node Setup 12. Static Routing Setup 15. SUA Server Setup Advanced Management 21. Filter Set Configuration 22. SNMP Configuration 23. System Password 24. System Maintenance 25. IP Routing Policy Setup 26. Schedule Setup 99. Exit

traceroute
This will help you find network routing problems. It will display the routes between two hosts. The return will show how many hops (routers/gateways you go through). The fewer the hops the better the connection usually. Each line will list information on a hop.

Secure Shell - SSH


OpenSSH The Secure Shell (SSH) is open source software. It is a viable replacement for telnet, ftp, rsh, rlogin and rcp. Security is incredibly important these days and it is imperative network administrators be able to implement security. OpenSSH supports versions 1.3, 1.5 and 2.

81
The reason that telnet, ftp and others have been replaced with SSH is simply that SSH offers encryption of passwords and data while telnet and ftp still use plain text passwords. Using a packet sniffer, bad guys can intercept your password or your data and compromise your system. The DISPLAY variable is automatically forwarded to the client machine. What this means is if you are using the X Window System, when you log into a remote system, it is displayed on the client machine. Version 3.0 and above eliminate several earlier key options. ~/.ssh/authorized_keys2 ~/.ssh/known_hosts2 ~/.ssh/ssh_known_hosts2 Now SSH Protocol 1 and 2 share the following files: ~/.ssh/authorized_keys ~/.ssh/known_hosts ~/.ssh/ssh_known_hosts When you compile SSH there are several areas to check to make sure you do not give away your security. To create the most secure setup follow these recommendations: - -with-etcdir=... Do not compile SSH and the keep the /etc directory on NFS - -prefix=... SSH executables must not be on NFS mounts - -disable-suid-ssh disable trusted hosts (SSH1) - -disable-suid-ssh-signer disable trusted host (SSH2) - -without-none do not allow anyone to use "none" for cypher, you want encryption - -without-rsh don't use rsh at all - -with-libwrap -with-tcp-wrappers Basic SSH Files System wide configuration files are found in /etc/ssh/ Client: ssh scp sftp Server: (daemon) moduli sshd_config --- initializes SSH connection --- secure copy --- secure ftp

--- contains Diffie-Hellman groups key exchange --- configuration file for sshd

82
ssh_host_dsa_key ssh_host_dsa_key.pub ssh_host_key ssh_host_key.pub ssh_host_rsa_key ssh_key_rsa_key.pub User SSH Files One thing to remember, each user must create and maintain their own SSH files. As a result those files are in your Home directory. The Home directory may be indicated by any of the following: ~ $HOME Examples: ~/.ssh/id_dsa $HOME/.ssh/id_dsa --- notice that the tilde ~ indicates home directory --- home directory --- DSA private key for sshd --- DSA public key used by sshd --- RSA private key sued by sshd --- RSA public key used by sshd --- RSA private key used for sshd protocol 2 --- RSA public key used for sshd protocol 2

Note that /.ssh is a hidden file in the home directory. It is important to turn off other programs that are insecure and that users would use to go around SSH. Several programs will accomplish this. One is from the terminal using chkconfig. Example: Turn off rsh chkconfig - -level 3 rsh off This command will turn rsh off in run level 3. chkconfig - -level 5 rsh off This command will turn off rsh in run level 5, the GUI (graphical user interface). Services that you probably need to turn off in both run levels 3 and 5: telnet, rsh, ftp, rlogin, wu-ftp, vsftpd serviceconf is the GUI program in Red Hat to turn off or on programs in specific run levels. In this example, the run level is 3 (the terminal) and rlogin is not checked so it will

83
not automatically startup. SSH is important to networks because you want to avoid this situation where someone in between two systems intercepts the message and may keep the message or alter it and send it on. SSH will prevent this.

SSH will prevent impersonation of a system. This is where the bad guy pretends to be the intended recipient. Unaware, the sender continues to communicate with the bad guy thinking he is the one that was originally intended.

84

SSH Connection Sequence 1. Secure Transport Layer Connection Established

2. Once the Secure Transport Layer has been established, All Communication is Encrypted

85

3. Client Authentication - Once the secure connection has been verified, the client can authenticate itself to the server in safety.

Once the SSH has established a secure connection, multiple channels can be opened by multiplexing the connection between the two machines. Each channel can handle communication for X11 sessions, terminal sessions or other services. Either the client or the server can initiate a new channel.

Channels will support flow-control allowing them to send and receive information more effectively and increasing the assurance that data will get to where it is supposed to go. The server and client negotiate these channels automatically.

86

Once the client is authenticated and communication is secure, new services may be used in a secure manner, X11 applications and tunneled TCP/IP ports. X11 Forwarding: When you compile SSH by default support for X is included. If you do not use the X Window then you can leave it out and save space. In addition, at compile time you can enable or disable X forwarding. SSH2 Only $ configure...--enable-X11forwarding $ configure...-disable-Z11-forwarding X11 Forwarding allows X applications that are opened on the SSH server to appear on the SSH client display. TCP Port Forwarding enables SSH to encrypt any information that is running through a TCP/IP based program. This feature can be compiled into the program. SSH2 Only $ configure...- -enable-tcp-port-forwarding $ configure...- -disable-tcp-port-forwarding

87

SSH QuickStart If you are like me the last thing you want to do is to have to read 100 pages of information before you can get SSH running. This section is designed to give you the bare requirements to run SSH in 10 minutes. If you have problems refer to the rest of the documentation for a fuller explanation. Step One: Generate Key Pairs This is assuming that OpenSSH is loaded and you are creating a DSA key pair.

1. Open a terminal and type: ssh-keygen -t dsa 2. Accept the default location and type in a passphrase.

OR ......Create a RSA key pair.

1. Open a terminal and type: ssh-keygen -t rsa

88
2. Accept the default location and type in a passphrase. Step Two: chmod ~/.ssh Once you have created your keys you will need to chmod 755 your ssh directory. chmod 755 ~/.ssh You'r done! Now you have a public key, which you will share with computers you want to connect to and a private key which you will not share with anyone, ever. ~/.ssh/id_dsa.pub ---> public key ~/.ssh/id_dsa ---> private key

Both are located in your home directory. Step Three: Share Public Key 1. Move into your ~/.ssh directory cd ~/.ssh 2. View Contents of Directory ls 3. Copy Public Key cp ~/.ssh/id_dsa.pub /mnt/floppy/mykey What we have done here is copied the public key to a floppy so we can share it with another computer. It has been renamed so that we do not get it mixed up with other public keys. 4. Place the Floppy in the Computer You Want to Share With cat /mnt/floppy/mykey >> ~/.ssh/authorized_keys This will add your key to a file of keys that are authorized to access this machine. Step Four: Make Contact

89
Now you have your local machine that has your public key and your private key and you can access the computer you placed your public key on by using this command: ssh 192.168.4.5 This assumes that the IP address of the computer you are making contact with is the IP above; you can also use the domain name, theirserver.com (just for example).

Step 5: Transfer Files Format for scp command scp localfile user@mysever.com:/somewhere/filename Example: (transferring the file test.txt to myserver.com for john) scp test.txt john@myserver.com:/home/john/test.txt

One common mistake: When you log into the remote machine, all commands are issued as if you are local on that machine.

90

Creating a Simple Script for BackUp This example is a backup script that can be used to back up an entire directory to another server. The local machine has a postgres database that you want to preserve on a remote machine (just an example). This script will recursively copy the folders and their contents as well as preserve the permissions on each file to a directory on the remote machine. -r recursive -p permissions Establish a connection with the ssh command and then run this script. scp -rp pgsql/* 192.168.4.3:/pgsql/backup/

The basic command to get going with SSH is the ssh command. It is a secure replacement

91
for rlogin, rsh and telnet. The ssh command will enable you to login to remote machine and execute commands just as if you were on the machine. Here is an example: ssh 192.168.5.1 Of course this IP address is a private IP not public, but you get the idea. The ssh command followed by an IP address. Or you could do this: ssh myserver.net Here you are using the domain name of the server and not the IP address. You will likely get this response: The authenticity of host 'myserver.net' can't be established. DSA key fingerprint is 45:56:3b:2c:cd:f2:5b:34:24:11:2c:45:de:56:26:cb Are you sure you want to continue connecting (yes/no) Type yes to continue and the server will be added to your list of know hosts. scp copies files securely between two machines on a network. The scp command has the following options: -c cipher -i identity_file -P -r -v -B -q -C -F ssh_config -P port select a specific cipher to use for encryption (ssh1) select a file from RSA private key (ssh1) preserve modification times, access times, and modes recursively copy entire directory verbose mode select batch mode disable progress meter enable compression select alternative configuration file for user specify port to connect to on remote host

Once you have made the connection you will be prompted for a password to the remote machine. After you enter the password you will be taken to a command line. When you specify a login password you will become the person on the remote machine that you are on the local machine. Let me say that again, with an example: You are logged in as tom on the client, you will become tom on the server, with all the rights of tom. By using the following command, you can designate who you will be on the remote server:

92

ssh -l username myserver.net Example: ssh -l fred myserver.net Here you are logged in as tom on the client machine and will become fred on the server.

One of the advantages of SSH is that you can generate a key pair so that you do not have to type in your password each time you use ssh. Generating a DSA Key Pair for Version 2 Open a terminal and type: ssh-keygen -t dsa This command will create a DSA key pair that works with version 2 of the SSH Protocol. You will be asked if you want to accept the default location for the file: ~/.ssh/id_dsa

93
Accept the default location and type in a passphrase. A passphrase should be a string of words that you will remember. The phrase makes it more secure than just one word. You can uses spaces and tabs in a passphrase. You will be asked to retype the phrase to confirm it. You best write it down somewhere secure. In this process a public key is also generated at the following location: ~/.ssh/id_dsa.pub Never give out your private key! scp --> transfer local file to remote server scp command will allow you to transfer data over a secure, encrypted connection. Format for scp command scp localfile user@mysever.com:/somewhere/filename Example: (transferring the file test.txt to myserver.com for john) scp text.txt john@myserver.com:/home/john/text.txt

scp to transfer remote file to local machine Format to transfer remote file to local machine scp user@remotehost:/remotefilename /localfilename scp john@myserver.com:/home/john/test.txt /home/john/test.txt

94

scp group transfer If you wanted to transfer the contents of an entire directory, you could follow this procedure: Format for group transfer (local to remote): scp /home/john/groupfiles/* john@myserver.com:/home/john/groupfiles/ Notice the ending / that will indicate a directory.

sftp uses a secure, encrypted connection to establish the ftp transfer. sftp is available for version 2.5.0p1 and higher. sftp john@myserver.com Once in interactive mode sftp will use the following commands: bye quit cd path change remote directory to path (example: cd /tmp) lcd path change local directory to path chgrp grp path change group of file path to grp (numeric number) chmod mode path change permissions of file path chown own path change owner of file, own must be numeric exit quit get remote-path local-path retrieve files help help lmkdir create local directory

95
ln oldpath newpath lpwd ls lumask put local-path remote-path quit rename oldpath newpath rmdir rm path symlink oldpath newpath ! command ! create symbolic link print local working directory display remote directory set local umask to umask exit rename remote path remove remote directory remove remote file create symbolic link execute command in local shell escape to local shell

GENERATE A RSA KEY PAIR Step 1: Generate a RSA key, use the following command: ssh-keygen -t rsa The default location for your keys are: ~ (tilde) is a symbol for your home directory ~/.ssh/id_rsa ~/.ssh/id_rsa.pub Accept the default locations, the first is your private key and the second is the public key. Step 2: Change the directory permissions of your ssh directory: chmod 755 ~/.ssh Step 3: Share keys by copying your public key to another machine. First you probably want to copy your public key to a floppy and then give the floppy to the person who will use your key. Email will work too, but this may be risky if someone intercepts it. cp ~/.ssh/id_rsa.pub /mnt/floppy/mykey Once you get to the machine that will use this key you need to cat the "mykey" into their directory of know servers. cat /mnt/floppy/mykey >> ~/.ssh/authorized_keys

96
Once you have created your keys you will need to chmod 755 your ssh directory. chmod 755 ~/.ssh You'r done! Now you have a public key, which you will share with computers you want to connect to and a private key which you will not share with anyone, ever. ~/.ssh/id_dsa.pub ---> public key ~/.ssh/id_dsa ---> private key

Both are located in your home directory. This means that each user will have to create their own keys! Gnome ssh-agent The purpose of the ssh-agent is to save your passphrase so you do not have to enter it each time you start a ssh or scp connection. You will need to have openssh-askpass-gnome installed. Find out if you have the rpm installed: rpm -q openssh-askpass-gnome You will get a returned statement of the version installed: openssh--askpass-gnome-3.1p1-3 The X Client is the software that will make requests of the X Server and thus send the information requested to be displayed on the screen. This software also is used to switch desktop environments with the command switchdesk. The switchdesk program creates two hidden files in each user's home directory when they use switchdesk. These two files are: ~/.Xclients ~/.Xclients-default If you want to use the ssh-agent with Gnome you will need these files so you will need to switchdesk tops once to create the files.

97
You will need to edit the following line in ~/.Xclients exec $HOME/.Xclients-default Change that line to look like this: exec /usr/bin/ssh-agent $HOME/.Xclients-default In the Startup Programs you need to add the line that you see and set the priority higher than 70 to make sure it has a low priority. The higher the number the lower the priority. Save your work and restart the XWindow. Once you restart Gnome you will be prompted to enter your passphrase. That's it, from now on you should not need to add your password when you use scp or ssh, or sftp. Gnome ssh-agent The purpose of the ssh-agent is to save your passphrase so you do not have to enter it each time you start a ssh or scp connection. At the prompt type: exec /usr/bin/ssh-agent $SHELL Then also type ssh-add You will need to enter your passphrase and then you are done. However..... As soon as you log out your passphrase will be dumped by the system. Each time you log in you will need to execute these two commands in the XTerminal to avoid having to enter your password each command. ssh-add Command will add RSA or DSA identities to the SSH agent. The ssh-agent will locate the necessary files to automatically authenticate. Options for ssh-add

98
-l -L -d -D -x -X -t -s -e list fingerprints of all identities represented by agent list public key parameters of all identities represented by agent remove identity from agent delete all identities from agent lock agent with password unlock agent set maximum lifetime when adding an identity to an agent, usually in seconds add key in smartcard reader remove key in smartcard reader

The OpenSSH Server runs a daemon that listens for connections on port 22. This is the typical situation; however, you may want to start the SSH manually. The server only has one sshd running, if more than one connection is made child processes are started from the one daemon.

To operate SSH, the daemon must be started. Use the following commands at the terminal: /sbin/service sshd start /sbin/service sshd restart /sbin/service sshd stop Notice that this is the daemon sshd, not just ssh. SSH Client is used to access a remote machine to be able to execute command or transfer files. The SSH Client provides a method of logging into a specific machine to which the Client must prove its identity. The identity is provided by encrypted keys. In order for a client to use the SSH Server, the client machine must have SSH loaded and

99
configured. The SSH Client must be authenticated to the machine that it will access. If the SSH is protocol version 1, there are three methods it may use to prove who it is. Two Less Secure Methods Usually Disallowed 1. The remote machine must have the client's machine listed in its /etc/hosts.equiv or /etc/shosts.equiv files and the user name on both machines must be the same, then the user is allowed to login. Or if the remote machine has the user and client machine listed in the .rhosts or .shosts files the user is allowed to login. 2. The login on the remote machine must be permitted by: $HOME/.rhosts, $HOME/.shosts, /etc/hosts.equiv, or /etc/shosts.equiv AND the remote computer must be able to authenticate the client's host key in $HOME/.ssh/known_hosts. This is a security benefit in that it protects against IP spoofing, DNS spoofing and routing spoofing. The third method of authentication is the one preferred in the SSH protocol version 1. 3. RSA Based Authentication - this method uses two separate keys: public/private keys. The server knows the public key located in $HOME/.ssh/authorized_keys while the user or client is the only one that knows the private key located in $HOME/.ssh/identity. When contact is made via SSH the server checks to see if the client is listed in the authorized keys. If it is , it sends a challenge, a random number, which is encrypted by the user's public key. This then can only be decrypted by the private key on the client which will in turn prove who the client is.

100

Authentication with SSH protocol version 2 provides two algorithms that can be used RSA like version 1 and DSA. RSA Keys: $HOME/.ssh/id_rsa $HOME/.ssh/id_rsa.pub DSA Keys $HOME/.ssh/id_dsa $HOME/.ssh/d_dsa.pub same as ~/.ssh/id_rsa

same as

~/.ssh/id_dsa

SSH protocol version 2 also provides for another level of security by encrypting the traffic with 3DES, Blowfish, CAST128 or Arcfour and insuring the integrity with hmac-md5 or hmac-sha1.

101

Configure the Bridge


brctl addbr br0 brctl addif br0 eth0 brctl addif br0 eth1 ifconfig br0 192.168.7.131 netmask 255.255.255.0 up route add default gw 192.168.7.2 dev br0 ifconfig eth0 0.0.0.0 promisc up ifconfig eth1 0.0.0.0 promisch up brctl stp br0 off One router do not need to worry about Spanning Tree Protocol, avoiding a loop. echo "1" > /proc/sys/net/ipv4/ip_forward brctl showmacs br0 This should list all mac addresses that the bridge has located. Bridge Commands # brctl Bridge firewalling registered commands: addbr <bridge> addif <bridge> <device> delbr <bridge> delif <bridge> <device> show showmacs <bridge> showstp <bridge> setageing <bridge> <time> setbridgeprio <bridge> <prio> setfd <bridge> <time> setgcint <bridge> <time> sethello <bridge> <time>

add bridge add interface to bridge delete bridge delete interface from bridge show a list of bridges show a list of mac addrs show bridge stp info set ageing time set bridge priority set bridge forward delay set garbage collection interval set hello time

102
setmaxage <bridge> <time> set max message age setpathcost <bridge> <port> <cost> set path cost setportprio <bridge> <port> <prio> set port priority stp <bridge> <state> turn stp on/off

Show Bridge Interfaces brctl show bridge name bridge id br0 8000.00004c9f0b05 STP enabled no interfaces eth0 eth1

Ebtables tar -zxvf ebtables-v2.0.6.tar.gz cd ebtables-v2.0.6 make install Configuring the Bridging Ebtables Firewall Router is 192.168.7.2 Computer Inside of Bridge 192.168.7.5 ebtables -P FORWARD DROP ebtables -A FORWARD -p 0x806 -j ACCEPT ebtables -A FORWARD -p 0x800 --ip-dst 192.168.7.5 --ip-proto tcp --ip-sport 80 -j ACCEPT ebtables -A FORWARD -p 0x800 --ip-src 192.168.7.5 --ip-proto tcp ip dport 80 -j ACCEPT ebtables -A FORWARD -p 0x800 --ip-src 192.168.7.5 --ip-dst 192.169.7.2 --ip-proto udp -ip-dport 53 -j ACCEPT ebtables -A FORWARD -p 0x800 --ip-src 192.168.7.2 --ip-dst 192.168.7.5 --ip-proto udp -ip-sport 53 -j ACCEPT Only the FOWARD chain needs to be set up because it is a bridge. The default policy is to DROP. The DROP policy means that if a packet does not match any other rule it will be dropped. The 0x806 stands for ARP packages. The protocol is specified in Hex so that ARP packages can pass. Address Resolution Protocol is needed because clients

103
need to find the MAC addresses based on IP Addresses they know. The protocol -p 0x800 is the IP protocol. --ip-scr and --ip-dst give you the source and destination. Stop Spoofed Addresses ebtables -A FORWARD -p IPv4 --ip-src 12.32.36.122 -s ! 00:0e:22:33:44:55 -j DROP This drops all traffic that the source and the mac address do not match the server network card. This will eliminate all traffic that tries to spoof the IP Address of the server.

EBTABLES man page


Edited to Save Space ebtables (v.2.0) - Ethernet bridge frame table administration SYNOPSIS ebtables [-t table] -[ADI] chain rule-specification [match-extensions] [watcher-extensions] TARGET ebtables [-t table] -P chain ACCEPT | DROP | RETURN ebtables [-t table] -F [chain] ebtables [-t table] -Z [chain] ebtables [-t table] -L [-Z] [ chain] [ [ [--Ln] [--Lc] ] | [--Lx] ] [--Lmac2] ebtables [-t table] -N chain ebtables [-t table] -X [chain] ebtables [-t table] -E old-chain-name new-chain-name ebtables [-t table] --init-table ebtables [-t table] [--atomic-file file] --atomic-commit ebtables [-t table] [--atomic-file file] --atomic-init ebtables [-t table] [--atomic-file file] --atomic-save

104
CHAINS There are three Ethernet frame tables with built-in chains in the Linux kernel. The kernel tables are used to divide functionality into different sets of rules. Each set of rules is called a chain. Each chain is an ordered list of rules that can match Ethernet frames. If a rule matches an Ethernet frame, then a processing specification tells what to do with that matching frame. The processing specification is called a 'target'. However, if the frame does not match the current rule in the chain, then the next rule in the chain is examined and so forth. The user can create new (user-defined) chains which can be used as the 'target' of a rule.

TARGETS A firewall rule specifies criteria for an Ethernet frame and a frame processing specification called a target. When a frame matches a rule, then the next action performed by the kernel is specified by the target. The target can be one of these values: ACCEPT, DROP, CONTINUE, RETURN, an 'extension' (see below) or a user-defined chain. ACCEPT means to let the frame through. DROP means the frame has to be dropped. CONTINUE means the next rule has to be checked. This can be handy to know how many frames pass a certain point in the chain or to log those frames. RETURN means stop traversing this chain and resume at the next rule in the previous (calling) chain. For the extension targets please see the TARGET EXTENSIONS section of this man page. Using the Filter Table As stated earlier, there are three Ethernet frame tables in the Linux kernel. The tables are filter, nat and broute. Of these three tables, the filter table is the default table that the ebtables command operates on. If you are working with the filter table, then you can drop the '-t filter' argument to the ebtables command. However, you will need to provide the -t argument for the other two tables. The -t argument must be the first argument on the ebtables command line, if used. -t, --table ebtables -A OUTPUT -p IPv4 -j ACCEPT ebtables -A OUTPUT -p ARP -j ACCEPT filter, is the default table and contains three built-in chains: INPUT (for frames destined for the bridge itself), OUTPUT (for locally-generated frames) and FORWARD (for frames being bridged). nat, is used to change the mac addresses and contains three built-in chains:

105
PREROUTING (for altering frames as soon as they come in), OUTPUT (for altering locally generated frames before they are bridged) and POSTROUTING (for altering frames as they are about to go out). A small note on the naming of chains POSTROUTING and PREROUTING: it would be more accurate to call them PREFORWARDING and POSTFORWARDING, but for all those who come from the iptables world to ebtables it is easier to have the same names. broute, is used to make a brouter, it has one built-in chain: BROUTING. The targets DROP and ACCEPT have special meaning in the broute table. DROP actually means the frame has to be routed, while ACCEPT means the frame has to be bridged. The BROUTING chain is traversed very early. It is only traversed by frames entering on a bridge enslaved NIC that is in forwarding state. Normally those frames would be bridged, but you can decide otherwise here. The redirect target is very handy here. EBTABLES COMMAND LINE ARGUMENTS After the initial ebtables -t, table command line argument, the remaining arguments can be divided into several different groups. These groups are commands, miscellaneous commands, rule-specifications, match-extensions, and watcher-extensions. COMMANDS The ebtables command arguments specify the actions to perform on the table defined with the -t argument. If you do not use the -t argument to name a table, the commands apply to the default filter table. With the exception of both the -Z and --atomic-file commands, only one command may be used on the command line at a time. -A, --append Append a rule to the end of the selected chain. -D, --delete Delete the specified rule from the selected chain. There are two ways to use this command. The first is by specifying an interval of rule numbers to delete, syntax: start_nr[:end_nr]. Using negative numbers is allowed, for more details about using negative numbers, see the -I command. The second usage is by specifying the complete rule as it would have been specified when it was added. -I, --insert Insert the specified rule into the selected chain at the specified rule number. If the current number of rules equals N, then the specified number can be between -N and N+1. For a positive number i, it holds that i and i-N-1 specify the same place in the chain where the rule should be inserted. The number 0 specifies the place past the last rule in the chain and using this number is therefore equivalent with using the -A command. -P, --policy Set the policy for the chain to the given target. The policy can be ACCEPT, DROP or RETURN.

106
-F, --flush Flush the selected chain. If no chain is selected, then every chain will be flushed. Flushing the chain does not change the policy of the chain, however. -Z, --zero Set the counters of the selected chain to zero. If no chain is selected, all the counters are set to zero. The -Z command can be used in conjunction with the -L command. When both the -Z and -L commands are used together in this way, the rule counters are printed on the screen before they are set to zero. -L, --list List all rules in the selected chain. If no chain is selected, all chains are listed. The following three options change the output of the -L list command: --Ln Places the rule number in front of every rule. --Lc Shows the counters at the end of each rule displayed by the -L command. Both a frame counter (pcnt) and a byte counter (bcnt) are displayed. --Lx The output of the --Lx option may be used to create a set of ebtables commands. You may use this set of commands in an ebtables boot or reload script. For example the output could be used at system startup. The --Lx option is incompatible with both of the other --Ln and -Lc chain listing options. --Lmac2 Shows all MAC addresses with the same length, adding leading zeroes if necessary. The default representation omits zeroes in the addresses when they are not needed. All necessary ebtables commands for making the current list of user-defined chains in the kernel and any commands issued by the user to rename the standard ebtables chains will be listed, when no chain name is supplied for the -L command while using the --Lx option. -N, --new-chain Create a new user-defined chain with the given name. The number of user-defined chains is unlimited. A user-defined chain name has maximum length of 31 characters. -X, --delete-chain Delete the specified user-defined chain. There must be no remaining references to the specified chain, otherwise ebtables will refuse to delete it. If no chain is specified, all userdefined chains that aren't referenced will be removed. -E, --rename-chain Rename the specified chain to a new name. Besides renaming a user-defined chain, you may rename a standard chain name to a name that suits your taste. For example, if you like PREBRIDGING more than PREROUTING, then you can use the -E command to rename the PREROUTING chain. If you do rename one of the standard ebtables chain names, please be sure to mention this fact should you post a question on the ebtables mailing lists. It would be wise to use the standard name in your post. Renaming a standard ebtables chain in this fashion has no effect on the structure or function of the ebtables kernel table. --init-table Replace the current table data by the initial table data.

107
--atomic-init Copy the kernel's initial data of the table to the specified file. This can be used as the first action, after which rules are added to the file. The file can be specified using the --atomicfile command or through the EBTABLES_ATOMIC_FILE environment variable. --atomic-save Copy the kernel's current data of the table to the specified file. This can be used as the first action, after which rules are added to the file. The file can be specified using the --atomicfile command or through the EBTABLES_ATOMIC_FILE environment variable. --atomic-commit Replace the kernel table data with the data contained in the specified file. This is a useful command that allows you to load all your rules of a certain table into the kernel at once, saving the kernel a lot of precious time and allowing atomic updates of the tables. The file which contains the table data is constructed by using either the --atomic-init or the --atomicsave command to generate a starting file. After that, using the --atomic-file command when constructing rules or setting the EBTABLES_ATOMIC_FILE environment variable allows you to extend the file and build the complete table before committing it to the kernel. --atomic-file -Z The counters stored in a file with, say, --atomic-init can be optionally zeroed by supplying the -Z command. You may also zero the counters by setting the EBTABLES_ATOMIC_FILE environment variable.

MISCELLANOUS COMMANDS -V, --version Show the version of the ebtables userspace program. -h, --help Give a brief description of the command syntax. Here you can also specify names of extensions and ebtables will try to write help about those extensions. E.g. ebtables -h snat log ip arp. Specify list_extensions to list all extensions supported by the userspace utility. -j, --jump target The target of the rule. This is one of the following values: ACCEPT, DROP, CONTINUE, RETURN, a target extension (see TARGET EXTENSIONS) or a user-defined chain name. --atomic-file file Let the command operate on the specified file. The data of the table to operate on will be extracted from the file and the result of the operation will be saved back into the file. If specified, this option should come before the command specification. An alternative that should be preferred, is setting the EBTABLES_ATOMIC_FILE environment variable. -M, --modprobe program When talking to the kernel, use this program to try to automatically load missing kernel modules.

108

RULE-SPECIFICATIONS The following command line arguments make up a rule specification (as used in the add and delete commands). A "!" option before the specification inverts the test for that specification. Apart from these standard rule specifications there are some other command line arguments of interest. See both the MATCH-EXTENSIONS and the WATCHEREXTENSION(S) below. -p, --protocol [!] protocol The protocol that was responsible for creating the frame. This can be a hexadecimal number, above 0x0600, a name (e.g. ARP ) or LENGTH. The protocol field of the Ethernet frame can be used to denote the length of the header (802.2/802.3 networks). When the value of that field is below (or equals) 0x0600, the value equals the size of the header and shouldn't be used as a protocol number. Instead, all frames where the protocol field is used as the length field are assumed to be of the same 'protocol'. The protocol name used in ebtables for these frames is LENGTH. The file /etc/ethertypes can be used to show readable characters instead of hexadecimal numbers for the protocols. For example, 0x0800 will be represented by IPV4. The use of this file is not case sensitive. See that file for more information. The flag --proto is an alias for this option. -i, --in-interface [!] name The interface via which a frame is received (for the INPUT, FORWARD, PREROUTING and BROUTING chains). The flag --in-if is an alias for this option. --logical-in [!] name The (logical) bridge interface via which a frame is received (for the INPUT, FORWARD, PREROUTING and BROUTING chains). -o, --out-interface [!] name The interface via which a frame is going to be sent (for the OUTPUT, FORWARD and POSTROUTING chains). The flag --out-if is an alias for this option. --logical-out [!] name The (logical) bridge interface via which a frame is going to be sent (for the OUTPUT, FORWARD and POSTROUTING chains). -s, --source [!] address[/mask] The source mac address. Both mask and address are written as 6 hexadecimal numbers separated by colons. Alternatively one can specify Unicast, Multicast, Broadcast or BGAe based filter. I need to prevent ARPs and other Layer2 based packets (DEC diag. packets, netbios, etc.) from a specific MAC-source to cross the bridge, to prevent loops." (Bridge Group Address). Unicast = 00:00:00:00:00:00/01:00:00:00:00:00, Multicast = 01:00:00:00:00:00/01:00:00:00:00:00, Broadcast = ff:ff:ff:ff:ff:ff/ff:ff:ff:ff:ff:ff or BGA = 01:80:c2:00:00:00/ff:ff:ff:ff:ff:ff. Note that a broadcast address will also match the multicast specification. The flag --src is an alias for this option. -d, --destination [!] address[/mask]

109
The destination mac address. See -s (above) for more details. The flag --dst is an alias for this option.

Simple ebtables script #!/bin/bash # Ebtables transparent firewall script # DEFAULT POLICY ebtables -P INPUT DROP ebtables -P OUTPUT DROP ebtables -P FORWARD DROP # FLUSH TABLES ebtables -F FORWARD #ebtables -F NAT #ebtables -F MANGLE # Forward Arp and IPv4 Traffic ebtables -A FORWARD -p IPv4 -j ACCEPT ebtables -A FORWARD -p ARP -j ACCEPT ebtables -A FORWARD --log-level info --log-ip --log-prefix EBFW # Stop Spoofing IP Addresses ebtables -A FORWARD -p IPv4 --ip-src 12.32.36.122 -s ! 00:0E:0C:2E:DB:32 -j DROP # Stop Scanning #ebtables -A FORWARD -p 0x0163 --ip-src 12.32.36.118 --ip-proto icmp --ip-dst 12.32.36.122 -j DROP # Web Server ebtables -A FORWARD -p 0x800 --ip-dst 12.32.36.122 --ip-proto tcp --ip-sport 80 -j DROP ebtables -A FORWARD -p 0x800 --ip-src 12.32.36.122 --ip-proto tcp --ip-dport 80 -j DROP # DNS Server ebtables -A FORWARD -p 0x800 --ip-src 12.32.36.122 --ip-dst 12.32.36.113 --ip-proto udp --ip-dport 53 -j ACCEPT ebtables -A FORWARD -p 0x800 --ip-src 12.32.36.113 --ip-dst 12.32.36.122 --ip-proto udp --ip-sport 53 -j ACCEPT # SMTP/POP3/IMAP SERVER ebtables -A FORWARD -p 0x800 --ip-dst 12.32.36.122 --ip-proto tcp --ip-sport 25 -j ACCEPT ebtables -A FORWARD -p 0x800 --ip-src 12.32.36.122 --ip-proto tcp --ip-dport 25 -j ACCEPT

110
ebtables -A FORWARD -p 0x800 --ip-dst 12.32.36.122 --ip-proto tcp --ip-sport 110 -j ACCEPT ebtables -A FORWARD -p 0x800 --ip-src 12.32.36.122 --ip-proto tcp --ip-sport 110 -j ACCEPT

Configuring the Bridging Iptables Firewall iptables -P FORWARD DROP iptables -A FORWARD -m state --state ESTBLISHED, RELATED -j ACCEPT iptables -A FORWARD -s 192.168.7.5 -m state --state NEW -j ACCEPT

--------- some rules --------------# we take http and https traffic to and from just about anything iptables -A FORWARD -p tcp --destination-port www -j ACCEPT iptables -A FORWARD -p tcp --source-port www -j ACCEPT iptables -A FORWARD -p tcp --destination-port 443 -j ACCEPT iptables -A FORWARD -p tcp --source-port 443 -j ACCEPT # we need to keep that email flowing iptables -A FORWARD -p tcp --destination-port smtp -j ACCEPT iptables -A FORWARD -p tcp --source-port smtp -j ACCEPT # plus POP3! iptables -A FORWARD -p tcp --destination-port pop-3 -j ACCEPT iptables -A FORWARD -p tcp --source-port pop-3 -j ACCEPT # dns is required to work # FIXME : we have well defined DNS servers so requests from # extrenal hosts should be permitted only to those. iptables -A FORWARD -p udp --destination-port 53 -j ACCEPT iptables -A FORWARD -p udp --source-port 53 -j ACCEPT iptables -A FORWARD -p tcp --destination-port 53 -j ACCEPT iptables -A FORWARD -p tcp --source-port 53 -j ACCEPT Basically, everything traverses the FORWARD chain Since the bridge has no length, you don't know which direction a packet is traveling so you do something like this: iptables -A FORWARD -m physdev -s www.wormspreader.com -p tcp --physdev-in eth1 -j DROP

111

Simple iptables script #!/bin/bash # This script comes with no warranty ...use at own risk # br0="192.168.5.10" GATEWAY_IP="192.168.5.2" LAN_NET="192.168.5.0/255.255.255.0" #LAN_BROADCAST="192.168.5.255" CLASS_A="10.0.0.0/8" CLASS_B="172.16.0.0/12" CLASS_C="192.168.0.0/16" CLASS_D_MULTICAST="224.0.0/4" CLASS_E_RESERVED_NET="240.0.0/4" BROADCAST_SRC="O.O.O.0" BROADCAST_DEST="255.255.255.255" WEB1="192.168.5.11" SSH="192.168.5.3" ########################################### # Add protection from the kernel echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts for f in /proc/sys/net/ipv4/conf/*/accept_source_route; do echo 0 > $f done for f in /proc/sys/net/ipv4/conf/*/accept_redirects; do echo 0 > $f done for f in /proc/sys/net/ipv4/conf/*/send_redirects; do echo 0 > $f done for f in /proc/sys/net/ipv4/conf/*/rp_filter; do echo 1 > $f done for f in /proc/sys/net/ipv4/conf/*/log_martians; do echo 1 > $f

112
done ########################################### # Remove existing rules iptables --flush iptables -t nat --flush iptables -t mangle --flush # Unlimited loopback traffic iptables -A INPUT -i lo -j ACCEPT iptables -A OUTPUT -o lo -j ACCEPT # Set Policies to drop iptables --policy INPUT DROP iptables --policy OUTPUT DROP iptables --policy FORWARD DROP # Remove pre-existing user defined iptables --delete-chain iptables -t nat --delete-chain iptables -t mangle --delete-chain ############################################# # Stop Stealth Scans and TCP State Flags iptables -A FORWARD -p tcp --tcp-flags ALL NONE -j DROP iptables -A FORWARD -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP iptables -A FORWARD -p tcp --tcp-flags SYN,RST SYN,RST -j DROP iptables -A FORWARD -p tcp --tcp-flags FIN,RST FIN,RST -j DROP iptables -A FORWARD -p tcp --tcp-flags ACK,FIN FIN -j DROP iptables -A FORWARD -p tcp --tcp-flags ACK,PSH PSH -j DROP iptables -A FORWARD -p tcp --tcp-flags ACK,URG URG -j DROP ############################################ # Connection State to By-Pass Rule Checking iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT iptables -A INPUT -m state --state INVALID -j DROP iptables -A OUTPUT -m state --state INVALID -j DROP iptables -A FORWARD -m state --state INVALID -j DROP ##################################################### # SPECIAL ##################################################### # No Matter What I Want to Block These Ports iptables -A FORWARD -p tcp --dport 4444 -j DROP iptables -A FORWARD -p tcp --dport 135 -j DROP iptables -A FORWARD -p tcp --dport 21 -j DROP

113
# Don't forward limited broadcast either way iptables -A FORWARD -d $BROADCAST_DEST -j DROP iptables -A FORWARD -p ! udp -d $CLASS_D_MULTICAST -j DROP ######################################################### # ICMP control and status messages # Log and drop initial ICMP fragments iptables -A INPUT --fragment -p icmp -j DROP iptables -A OUTPUT --fragment -p icmp -j DROP iptables -A FORWARD --fragment -p icmp -j DROP # Flow Control - Mostly Used on LANs iptables -A FORWARD -p icmp --icmp-type source-quench -j ACCEPT # Unexpected Data in Header or Checksum Error iptables -A FORWARD -p icmp --icmp-type parameter-problem -j ACCEPT # STOP NMAP SCANS iptables -A FORWARD -p icmp --icmp-type destination-unreachable -j DROP # Disable Traceroute iptables -A FORWARD -p icmp --icmp-type time-exceeded -j DROP # Disable Ping iptables -A FORWARD -p icmp --icmp-type echo-request -j DROP ############################################# # Web iptables -A FORWARD -p tcp -d $WEB1 --dport 80 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --src $WEB1 -m state --state NEW -j ACCEPT ############################################### # SSH to WEBSERVER iptables -A FORWARD -p tcp --src $SSH --dport 22 -m state --state NEW -j ACCEPT ############################################# # DNS includes settings for Client and Zone Transfers iptables -A FORWARD -p udp --sport 1024:65535 -d $WEB1 --dport 53 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --sport 53 -d $WEB1 --dport 1024:65535 -m state --state NEW -j ACCEPT iptables -A FORWARD -p udp --sport 53 -d $WEB1 --dport 53 -m state --state NEW -j ACCEPT iptables -A FORWARD -p udp --src $WEB1 --sport 1024:65535 --dport 53 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --src $WEB1 --sport 1024:65535 --dport 53 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --src $WEB1 --sport 53 --dport 1024:65535 -m state --state NEW -j ACCEPT iptables -A FORWARD -p udp --src $WEB1 --sport 53 --dport 53 -m state --state NEW -j ACCEPT ################################## # MAIL SERVER AND CLIENTS FOR POP3 AND IMAP

114
# MAIL SERVER SMTP iptables -A FORWARD -p tcp --sport 25 -d $WEB1 --dport 1024:65535 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --src $WEB1 --sport 1024:65535 --dport 25 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --sport 1024:65535 -d $WEB1 --dport 25 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --src $WEB1 --sport 25 --dport 1024:65535 -m state --state NEW -j ACCEPT # POP3 iptables -A FORWARD -p tcp --src $WEB1 --sport 1024:65535 --dport 110 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --sport 110 -d $WEB1 --dport 1024:65535 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --sport 1024:65535 -d $WEB1 --dport 110 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --src $WEB1 --sport 110 --dport 1024:65535 -m state --state NEW -j ACCEPT # IMAP iptables -A FORWARD -p tcp --src $WEB1 --sport 1024:65535 --dport 143 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --sport 143 -d $WEB1 --dport 1024:65535 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --sport 1024:65535 -d $WEB1 --dport 143 -m state --state NEW -j ACCEPT iptables -A FORWARD -p tcp --src $WEB1 --sport 143 --dport 1024:65535 -m state --state NEW -j ACCEPT ################################## # LOGS iptables -A FORWARD -j LOG ########################################## exit 0

Once you verify that the script works correctly, you can save it so it will run the next startup by issuing the command: /etc/init.d/iptables save This will save it into /etc/sysconfig/iptables.

115
Modify the Script
There may be times when you want to modify the firewall script. If you make modifications be sure to create a backup first as your firewall is critical to having everything work correctly. One example when you might want to modify the script is when a new worm attacks and you have done the research to know that the work uses a specific port. Using the firewall script you will be able to completely block the port against the worm. One current worm uses port 31337 so you need to block that port. iptables -A FORWARD -p tcp - -dport 31337 - -sport 31337 -j DROP Microsoft machines are susceptible to port 5000 attacks so block that port as well. iptables -A FORWARD -p tcp - -dport 5000 - -sport 5000 -j DROP Once you have added necessary changes, save the script and then run the script. sh /etc/rc.d/rc.firewall Now save it to the system so the changes will run at boot. service iptables save

116

Managing Drives and Formats

117

Managing Drives and Formats

mount
The mount command will allow you to mount a drive for use. Example: mount /dev/cdrom /cdrom This command tells the system to mount the CDROM and where to mount it. Another more common example would be mounting the cdrom off of the media directory. mount /media/cdrom Options -a mounts all partitions in the /etc/fstab file -h help -r mounts as read only -w mounts as read/write Below is a typical /etc/fstab which shows all of the mount points on the system. If you use

Managing Drives and Formats

118

the -a option it will try to mount all the points that are listed here. # /etc/fstab: static file system information. # # <file system> <mount point> <type> <options> <dump> <pass> proc /proc proc defaults 0 0 /dev/hda1 / ext3 defaults,errors=remount-ro 0 1/dev/hda5 swap sw 0 0 /dev/hdb /media/cdrom0 udf,iso9660 ro,user,noauto 0 0 /dev/fd0 /media/floppy0 auto rw,user,noauto 0 0

none

The option to mount a directory as read only using the -r option may be useful in mounting a directory that provides information to users but should not be modified. You can also mount a directory as read/write with the -w option. mount -r /media/floppy This mounts the floppy drive as read only. mount -w /media/usbdisk This will mount the usb drive as read and write.

umount
This will unmount a drive. This command may be used to unmount a floppy, CDROM, or usb disk. It may also be used to unmount partitions as well. Example: umount /media/cdrom This will unmount the CDROM. Often new Linux distributions may call your CDROM a CDRECORDER or DVDRECORDER if they can burn CDs or DVDs. If you needed to unmount a partition it would be the same process. For example if your partition was a backup partition called /bk you could unmount that partition with this command: umount /bk

Managing Drives and Formats

119

fdisk
fdisk in Linux is a tool to partition hard drives. The ability to modify the physical disk partition is a tool that will be valuable in any Linux situation. Do not mistake this fdisk for the DOS version; they are not the same. Partioning Using fdisk Start fdisk - When you want to start fdisk it is important that you know what disk on your computer you would like to partition. This is especially important if you have multiple disks because you may end up partitioning the wrong drive. When you are at the command prompt, type: fdisk You will see the following: Usage: fdisk [-l] [-b SSZ] [-u] device E.g.: fdisk /dev/hda : fdisk /dev/hdb : fdisk /dev/sdc etc. If you are partitioning the first hard drive on the primary controller it is /dev/hda. The second drive on the primary controller is /dev/hdb and so on. Basic fdisk Commands a b c d l m n 0 p s t u v w toggle a bootable flag edit bsd disklabel toggle the dos compatibility flag delete a partition list known partition types print this menu add a new partition create a new empty DOS partition table print the partition table create a new empty Sun disklabel change a partition's system id change display/entry units verify the partition table write table to disk and exit

Managing Drives and Formats


x extra functionality (experts only)

120

These are the commands you will need to know and will benefit you when you actually begin to use fdisk. option p (print) the current partition table entries A good place to start once you have entered fdisk is to view what the current partition table is by using the p option: This example is a good example of the print option. Notice that this hard drive had one drive on the primary controller, hda, and that drive is partitioned three times, one being a Linux swap. Creating a Partition in fdisk Summary Step #1: Print the partition entries - see what is there before you begin the process. It is always a good idea to verify that what you are about to destroy is what you want to destroy. No doubt about it, if you partition it all information will be gone. Step #2: Delete unwanted partitions. Once you have verified that you want to get rid of the existing partitions, use the d option to delete them. Step #3: Create new partitions. Before you create new partitions it is important you ask yourself what you want to do on the drive, is it a workstation or server, each will have different needs. Use the n option to create the new partitions. Step #4: Verify partition types. View the partition types that you may need with the l option and then check that each of your partitions are the correct type. Step #5: Write the information to disk. Nothing has changed on the drive until you use the w option, then all the information you have created will be written to the drive. Step #1 Detail: By using the command fdisk -l you will be able to see what partitions are actually on the hard drives. The command p once you enter fdisk will provide the same information. Once you view the partitions that exist on the hard drives, you will need to make some

Managing Drives and Formats

121

decisions about which partitions you would like to keep and which ones you would like to delete. This may be especially important if you are going to dual boot your computer and you need to keep your Windows partitions. Step 2: Delete Unwanted Partitions The command for deleteing a partition is d. You can see in the example you will use the d command and then you will need to choose which partition you want to delete. In this example there are only 3 partitions; however, you see that partition numbers 1-4 are listed. If you would try to delete 4 it would return that this is an "empty partition", in other words it doesn't exist. Once you have deleted your partitions you will need to write the partition table for it to become active. If you quit before you write to the table nothing will happen. Write to the partition table with w. Step 3: Create New Partitions You need to figure out what you would like to do with your partitions before you start randomly creating partitions. The workstation example gives you a basic idea of what you might do with a 5 GB hard drive for a workstation and a 6 GB drive for a server(basic). Workstation: / 256M /boot 256M /home 1000M /usr 3000M /tmp 100M /var 100M swap 2x the RAM on the machine The Server installation may require a larger /var for logs and a larger /home for users. This is just a basic example. Server: / /boot /home /usr /tmp /var swap 256M 256M 2000M 3000M 300M 1000M 2x the RAM on the machine

Managing Drives and Formats

122

Once you have decided what partitions you would like to create you are ready to create new partitions. Use the n command in fdisk for a new partition. Once you have done this you will need to decide if it is an extended partition you will create or a primary partition. Let's assume this drive has no partitions at all. You will start with 3 primary partitions first and then the 4th primary partition will actually be an extended partition if you would like to create more than 4 partitions, which you would if you are following our previous examples.. Server: / /boot /home /usr /tmp /var swap 256M 256M 2000M 3000M 300M 1000M 2x the RAM on the machine

Workstation: / 256M /boot 256M /home 1000M /usr 3000M /tmp 100M /var 100M swap 2x the RAM on the machine Both of these examples will create 7 partitions: 3 primary (/ /boot and /home) and 4 extended (/usr /tmp /var swap). Actually the first extended partition will be a partition that encompasses all of the drive space after the first 3 primary partitions. This is because you will need to slice up the extended partition into all of the smaller extended partitions. The first thing you need to do to create a partition is decide on the size of the partition and what that partition will become. If you have decided that the first partition will be /boot and it will be 256M then you would follow this procedure. Create a new partition by choosing n. Choose primary partition by choosing p and the number 1 when asked because it will be the first partition. The example is creating the 4 partition so you would need to place a 1 instead of a 4.You will be asked which cylinder you would like to start your partition on, choose the default by hitting return. Now you will need to choose the last cylinder, this specifies the size of your partition. Notice in the example that +250M is used. This will create a partition size of 256 Megabytes. If you want 250 M you would enter +250M. Create all of your partitions and then write the partition table with the w command.

Managing Drives and Formats

123

Once your partitions are created you are still not done. You need to make sure they are the correct type. You can view the type options by entering fdisk and using the l command to view the types of partitions. You will need to use type 83 for Linux and type 82 for Linux swap. As you look at your partitions you will find that they are already type 83, so you will need to change your swap partition to 82. This is easily accomplished by using the t command which will allow you to change types. Once you issue the t command you will need to choose which partition you want to make the swap partition. Then you can change it by entering the code, see the example. Make sure you write this information to the partition table with the w command. Your partitions should now be complete.

dd
This command will copy a file and perform a file conversion if specified. Example: dd if=/some/boot.img conv=lcase of=/dev/fd0 obs=16k This command will write a boot image to a floppy disk in lower case letters. It will write at 16k at a time. Options if=file of=file conv=lcase conv=ucase obs=bytes read from file instead of standard input writes to file instead of standard output converts file to all lower case converts file to all upper case writes bytes at a time

df
Shows how much free space on directories. Options -m will show results in megabytes -h human readout, easier to understand

Managing Drives and Formats

124

du
The du command displays the estimated amount of space being used by files in a directory.

mkfs
You can build a file system with this command, usually on a hard-disk partition. The filesystem can be a mount point or a device name. Example: mkfs /dev/hda8 Options -l filename -v -t fstype -v

read bad blocks verbose type of system to build provides information about each step to produce a file system

mkdosfs
This command will allow you to create a DOS file system on your Linux machine. Usually the DOS file system is placed on a partition. Options -c -f fats -F fatsize -i volume -s sectors

check partition for bad blocks specifies number of File Allocation Tables in the files system, normally 2 12,16,32bit sets volume ID sets the number of disk sectors per cluster

Managing Drives and Formats

125

Managing Rights to Files and Directories

chmod
This command will change the permissions that are associated with a file or directory. x = execute r = read w = write These are basic rights to files for User(usually creator of the file), Group and Others. u = user g = group o = others

Managing Drives and Formats


all = user, group, others chmod u+x /home/fred/text

126

This command would give all users on the system the execute right for the file /home/fred/text. FILE PERMISSIONS Octal Value Special 4 set-UID 2 set-GID 1 sticky-bit

User r w x

Group r w x

r w x

Others

Octal system uses 8 values 0-7 as opposed to the decimal which uses 10. Examples: Let's say you have a file named text. If you created the file text, you are the User and would have all rights to the file read/write/execute. If you look above, you see that r,w,x under User will mean all rights. Then if you add the numbers in the left hand column, 4,2,1 you get 7. chmod 700 text This command would mean all rights for User (rwx,421=7), no rights for group (0) and no rights for others (0), that's where the 700 comes from. chmod 755 text This command gives all rights to the User (rwx,421=7), read and execute rights to Group and Others (rx, 4 +1 =5). set-UID when this value is used (ex: 4755) it gives the file the same rights as root when it is run set-GID when this value is used (ex: 2755) it gives the file the same rights as the group of the file sticky-bit this tells the OS to keep an executable program's image in memory to reduce the start time of a large program (used infrequently, ex: 1755) chmod Exercise Create a directory called /home/username/info mkdir /home/ username/info Now that you have a directory called /home/info, let's check the permissions on that directory. ls lF /home You will see something like below drwxr-xr-x 2 root root 4096 Oct 23 05:57 info/ Permissions drwxr-xr-x Links Owner Group Size 2 root root Last Modified Time 4096 Oct 23 05:57 File info/

Managing Drives and Formats

127

The owner root has read/write/execute privileges (group = rx, other=rx) Let's change the rights so that group and other can only read. Now use gedit to create a file test and save it in /home/ username/info chmod 0744 /home/ username/info/test Now when you check permissions (ls lF /home/ username/info/test) you will see the following drwxr.r chmod 0724 /home/ username/info/test Now what do you get?

chattr
chattr +i filename This command creates an immutable flag that means that the file cannot be deleted, renamed; no link can be created to the file and no data can be written to the file. Only root will be able to modify it once this is set. Example: chattr -i data

Using the su command


su This important command will run a shell of another user while you are logged in as yourself. The classic example of this command is when you are logged in as a normal user but you need root privileges to complete one action, like install a program. Example: su root Then you would be asked for a password of root. Once you had completed the action necessary you could return to the normal user with the exit command: exit Options

Managing Drives and Formats

128

-l login shell -c command this will pass the command to the shell instead of starting an interactive shell -m leaves the HOME< USER, LOGNAME AND SHELL as they are -s SHELL this runs SHELL instead of the user's shell - - help help su root -c command This will allow you to become root for the command that is needed. Here is an example: su root -c mount /mnt/floppy Whenever you use this command you will be required to put in the root user password, this protects users from making modifications to the system. This also provides you as the administrator the opportunity to run the system as a normal user but still make changes if necessary. Example: su root -c eject /cdrom This will eject the cdrom, which requires root access. Using the sudo Command sudo looks at a file to determine who can use the command. The file is /etc/sudoers. The default sudoers file in DSL looks like this: #sudoers file root knoppix dsl ALL=(ALL) ALL ALL=NOPASSWD: ALL ALL=NOPASSWD: ALL

This file allows root, of course but it also allows the users knoppix and dsl to become root without a password. This may not be such a bid problem with a home system but if you use this as a firewall or server you should certainly change it. Here is how to correct the

Managing Drives and Formats


problem. Become the root user by using sudo su or the su

129

Once you are root edit the /etc/sudoers file with vi and place a # mark in front of the two users that you would like to eliminate for sudoers. The example shows both users have been eliminated from the sudoers now. The only way to obtain root privileges is to use the su command and enter the root password. #sudoers file root ALL=(ALL) ALL ALL=NOPASSWD: ALL ALL=NOPASSWD: ALL

# knoppix # dsl

Example on becoming root after the change: su root

umask
When a user creates a file, umask sets the permissions of that file. Each file has permissions based on numeric values. These numeric values are represented by the octal system. FILE PERMISSIONS Octal Value Special 4 set-UID 2 set-GID 1 sticky-bit User r w x Group r w x Others

r w x

Octal system uses 8 values 0-7 as opposed to the decimal which uses 10. Examples:

Managing Drives and Formats

130

Let's say you have a file named text. If you created the file text, you are the User and would have all rights to the file read/write/execute. If you look above, you see that r,w,x under User will mean all rights. Then if you add the numbers in the left hand column, 4,2,1 you get 7. chmod 700 text This command would mean all rights for User (rwx,421=7), no rights for group (0) and no rights for others (0), that's where the 700 comes from. chmod 755 text This command gives all rights to the User (rwx,421=7), read and execute rights to Group and Others (rx, 4 +1 =5). umask determines what the octal values or permissions of each created file will be. You can determine what the values will be by subtracting the umask form 777, which would be full read/write/execute rights for everyone. You can see the default umask by typing the command umask. umask 0022 At this time the 0 is not used but may be in the future. The 022 Example: 777-0022 = 644 which is read/write for the user and read for others and the group. Note that currently files are not created with the executable bit as a security measure. That is why you will see it really functions like this: 666 022 = 644

Package Management

131

Package Management

Introduction to RPMs
No matter how you will use Linux, personal desktop or server, you will need to know how to manage software. One very important tool in software management is RPMs. The RPM Package Manager, RPM, was designed to make software management easier. It is an open packaging system that will work on Linux and Unix systems. An RPM is a package of files that are needed to add or upgrade software. When a RPM is installed it will not overwrite older files but will back them up so that you have less problems in package installation and so you can remove the RPM if you want to go back. A package is really just a container with files that are needed to install a software application. These packages will include binaries, configuration files and documentation files. Because RPMs management requires changes to your system you will have to be logged in

132
as root. The current release of RPM is 4.1-1.06. If you are using RPM management which is newer or older you may find differing functionality. RPM Package Information The RPM usually will include the version, release and the computer architecture for the system it was designed for. Each of these queries (rpm -q rpmname) will result in the version and release. If the rpm is cpu sensitive, you will also see the architecture as well. You can look in /proc/cpuinfo to find out if your computer architecture is i386,i586 or i686. Here are a few examples: rpm -q gimp gimp-1.2.3-9 rpm -q httpd httpd-2.0.40-11 rpm -q kernel kernel-2.4.18-14 kernel-2.4.18-19.8.0 Security and the RPM It seems nothing is secure these days. Therefore it is important to validate the RPM that you are installing on your system. There are two basic methods for validating your RPM: 1. MD5 Validation - This method verifies that the package data was not corrupted and is intact. 2. GPG Validation - This method verifies the authenticity of the file and will make sure that the file is a Red Hat RPM for example. In order for this to take place Red Hat provides their public key on the installation CD located in the RPM-GPG-KEY file. If you want to authenticate your RPMS using the GPG validation you wil need to import the key. If you are using the CDROM location the command would be as follows: rpm - -import /mnt/cdrom/RPM-GPG-KEY Once the public key is imported you can authenticate a RPM on the CD with this command: rpm - -checksig /mnt/cdrom/RedHat/RPMS/packagename.rpm Verifying an Installed Package:

133
Once you have installed a package and you need to verify the integrity of the package, you can verify it against the RPM database that is on the system or against a RPM on the CD. Verify will check the size, MD5 checksum, permissions, type, owner, and group of the package. Verify all packages against the RPM database: rpm - -verify a This may take some time. Verify Against an RPM on a CD: rpm - -verify -p /mnt/cdrom/RedHat/RPMS/packagename.rpm Verify Against RPM Mounted by NFS: rpm - -verify -p /home/RPMS/packagename.rpm Verify File Associated With a Package: rpm - -verify - -file /bin/tar If there is not a problem you will get nothing in return. Failure of a Verify of a File Associated With a Package: As stated previously if you check a file associated with a package and there is no problem, there will be no output. However, if there is a problem the output will indicate where the problem is. The output is a string of characters 8 long. Each character indicates a test that was performed. If the test passes you will see only a ".", but if the test fails you will see one of the characters indicated below: 5 S L T D U G M MD5 checksum file size symbolic link file modification time device user group mode

Example: rpm - -verify --file /bin/tar 5....... This indicated the MD5 checksum failed, all others passed.

134
Query Mode: Query Mode will provide information about the RPMs on your system. The format for Query Mode is: rpm -q <options> 1. Query all packages on the system (list all RPMs) rpm -qa 2. Query the package owning a particular file rpm -qf /etc/mail system will return the RPM that owns this file --> sendmail-8.12.5-7 3. Query packages that provide this capability rpm -q - -whatprovides /etc/passwd system will return the RPM that owns this file --> setup-2.5.20-1 4. Query packages that require this capability rpm -q - -whatrequires gimp system will return the RPM that owns this file --> sane-frontends Also listed will be version, release date, size,group, license, summary and a description. Query Mode: The basic function of query mode is to make a request for information represented by this command: rpm -q packagename Options (for package selection): -a all RPMs - -whatrequires find RPMs that require a specific rpm - -whatprovides find RPMs that provide a capacity for a needed rpm -f file find what RPM owns that file (use full path) -g group list packages in that particular RPM -p package query an uninstalled RPM named package Options (for package information): -i show information about package -R list the RPMs that this package depends on - -provides list the capabilities that this package provides - -changelog show change information on the RPM -l list files in the RPM

135
-s -d -c - -dump permissions, - -last -querytags -q formatstring list the state of the files (normal, not installed, replaced) list documentation files list configuration files display path, size, modification time, MD5, checksum, owner, group (used with -l,-c or -d) show installation date, time (most recent first) print tags, used with -qf customized output format for information

Formatting the Output of a Query: You have several optional components such as literal text, directives, character sequences, modifiers and interators. Type this command to see the query tags (over 100) rpm - -querytags Installing RPMs The basic format for installing RPMs is: rpm -i packagename Options: - -force - -h - -nodeps - -test -v install no regardless if it is installed, newer, etc. print up to 50 hash marks do not perform the dependency check (only disables checks) do not install, just display dependencies and conflicts verbose mode

Upgrading RPMs: The rpm -U packagename will upgrade the existing package or install the package even if a previous one was not installed. The command, rpm -F packagename will only freshen the package if it has been previously installed. rpm -U packagename rpm -F packagename If another version was previously installed, when you upgrade you may see this message: saving /etc/somerpmpackage.conf as /etc/somerpmpackage.conf.rpmsave Notice the "rpmsave" that will be attached to the previous configuration files. This will allow you a method to go back to the RPM you were using before install and not lose configuration files. Removing RPMs: The removal of RPMs is done with the -e option.

136
rpm -e packagename When the removal is successful there will be no output. If you try to uninstall and get an error message that another RPM requires the file you are about to uninstall, it is a bad idea to ignore it. These dependencies are critical to maintaining stability of your system. However, if you know what you are doing you can use the - -nodeps option to force the uninstall. Red Hat RPM Management Red Hat has tried to create a system that is easy for the Linux user to add and subtract RPMs. They have created a Graphical User Interface (GUI) that is accessible from System Settings / Packages. The Package Management Tool is available at installation as well. When you choose the package Management Tool it first builds the database and checks the system packages that are currently installed.

The Package Management Tool is also available using the terminal and using this command: redhat-config-packages Once the package Managment Tool is open you are able to add or remove packages. Notice the format provides a description of a group of packages that are related, such as " X Windows System", and it lists the number of packages that are in that grouping. By choosing "Details" you are able to specifically choose which package you would like to install or uninstall. The "Details" section lists both the Standard Packages, the packages most commonly installed with this grouping and also Extra Packages which you can select or unselect to make additional choices. Once you have made your selections, the Package Management Tool will inform you concerning the amount of disk space this installation will take. If you choose Show Details the packages selected and the disk space will be shown.

137
When you click "Continue" the system will show you a progress bar so you can determine how much longer it will take to install the packages you selected. Once you have made your choices you will be informed of whch CD is needed to install the requested packages.

You may either place the correct CD in the computer or click Cancel to try again.

tar
The easiest method for installing programs in Linux is the RPM. However, there will be times when building an application from the source cd will be better. The source code may be a better choice because it may take time before the source file is converted into an RPM. Thus by using the source code you get a newer version. Here is an example on how to unpackage a tar file. Step 1: UnPack The Source Package Move to a temporary folder and create another folder to place your package into. Use the gzip -d command to decompress the program. Step 2: Use Tar Command to UnPack tar -xvf package.tar When this is done it will usually create a directory with the package name, move into this directory. To see this new directory name use the command ls to list the files in the current folder. ls cd /package.folder Step 3: Configure The goal here is to create a Makefile which will be used to build your software. ./configure - -prefix=/tmp/program/newprogam You will see lots of files created. Notice that the - -prefix= will allow you to direct the program to install where you want it. Otherwise the default is /usr/local.

138
Step 4: Build the Software In order to build the software you need to issue the make command. make Again, a lot of files will be created. Step 5: Install The final step is installation. make install That's it, the program should run. The easiest way to uninstall a tar file is to go back to your original folder where you issued the make command and type: make uninstall The second method would be to simply delete the folder that the program is in currently. The third method, if the others are not great options, is to run ./configure again so you have a Makefile for the uninstall option above.

tar backup tar can be used for simple backups of your data. When you tar a file, it is written to the location in a tar format which will preserve directory,pathname,inode, user, group, permissions and creation, modification times. Example: cd /home/mike tar cvf /dev/ftape Restore a Directory: cd /tmp

139
tar xvf /dev/ftape This will extract all of the files from /home/mike to the /tmp directory.

fromdos
This command will convert a DOS txt file to UNIX by replacing the carriage-return/linefeed sequence at the end of the DOS txt files of the UNIX linefeed usage. gunzip The gunzip file is used to unzip compressed files.

Options -c standard output without changing files -N keeps timestamp and original name -q quiet mode, no status information -t tests for integrity -v verbose mode

Debian Package System


Debian, Corel and Storm Linux are distributions that use dpkg commands. Install: dpkg -i package.deb Remove: dpkg -r package.deb

140

Managing Users and Groups

141

Managing Users and Groups

Message of the Day


With multiple users logging in you can communicate with those users by writing a message to users they can see when they log in. edit /etc/motd Save your message and you are done. Welcome to the Network! Please note that we will have a system upgrade later this evening from 6 PM to 8 PM. Be sure to have adequate backups of all important data. Admin

Managing Users and Groups

142

Be aware that users who log in using the graphical interface may not notice the motd while those who login using the terminal will not be able to miss it. /etc/issue This message is displayed immediately before the login prompt on unused terminals. You can edit this file to communicate with users. Here is an example of the etc/issue message from Ubuntu. Ubuntu 5.04 "Hoary Hedgehog" \n \l mesg n This command will turn off write and talk so that users are not bothered by multitudes of messages. However, root will override this attempt to turn off incoming messages. Example: mesg n

wall This command is used to communicate with all users. It stands for "write all". The command can be used by issuing the wall command followed by the message and concluded with Ctrl+D. Example: wall Please observe all security regulations. Ctrl+D The message will be broadcast to all users online. Here is an example from a user using wall. First you type the command wall and then follow it with the message for all users. The broadcast will indicate which user sent the message. mike@ub:~$ wall hello

Managing Users and Groups


Broadcast Message from mike@ub (/dev/pts/0) at 5:12 ... hello You can check to see if wall is installed with: rpm -q wall

143

wall has a security history so many admins do not install it. who - Active Users The who command lists the users currently logged into the system. The information for who is kept in /var/run/utmp. A history of logins is kept in /var/log/wtmp. Example: who root tty1 Mar 7 07:05 root pts/0 Mar 7 07:05 mike tty2 Mar 7 07:05 write If you wanted to communicate with a specific user while they were on the system you could use the write command. write username --> hit enter message --> hit enter for new line Ctrl_D Example: write fred Be sure to log out when you are done! Ctrl_D fred will receive the message in this form: Message from root@top on pts/0 at 18:29 Be sure to log out when you are done! EOF

Managing Users and Groups

144

adduser
Creating Users Exercise: Example: adduser john Create a password for john. passwd john smith14 (Unix will return warning if the word is a dictionary word) Create a directory for john mkdir /home/john You will find that the directory is already created by default. Let's create a new user called john.

passwd
The passwd command will prompt you to change your own password if the command is typed alone. Your password should not be a dictionary word and it should be at least 6 letters. If you wanted to change the password of another user and you were logged in as root you would type the user's name and then the command. User Summary In order to provide access to server resources all users need to have an account set up for them. The administrator sets up an account using the useradd command and creating a password with the passwd command. The passwords are kept in the /etc/shadow file to make sure they cannot be viewed. The specifics of the user's environment will be provided in the /etc/skel file which will determine what shell the user will access as well as other

Managing Users and Groups

145

specifics provided. Whenever a user is created the user is placed in a group that will allow the administrator to manage groups of users with similar needs. The /etc/motd file provides a method that the administrator can communicate a "message of the day" to users for information. This section will provide interactive lessons of managing these aspects of administration. Create User Creating a user in Linux is simple. Type.. useradd Joe This creates a user named Joe. However, this does not create a password nor any other options that you would like. Here are several options: -u uid user ID specified -g group specify a group for the user -G lists groups the user is in -c comment describe user -d dir home directory -m make home directory if it does not exist -k skel_dir skeleton home directory -s shell login program, the default is /bin/bash -e YYYY-MM-DD expiration date account disabled -p password create password at time of creating user adduser command The previous example used useradd instead of adduser. Either command may be used to create new users with the same options. The rest of this CD will use useradd instead of adduser. -u uid user ID specified -g group specify a group for the user -G lists groups the user is in -c comment describe user -d dir home directory -m make home directory if it does not exist -k skel_dir skeleton home directory -s shell login program, the default is /bin/bash -e YYYY-MM-DD expiration date account disabled -p password create password at time of creating user Why Use useradd? One of the advantages of this command is that it will automatically run chown and chgrp commands to make sure the permissions are set correctly for the user. If you don't use

Managing Users and Groups


useradd you must set these permissions manually.

146

Another advantage of useradd is that it is a command that can be used on all Linux systems to add users. Often the GUI (graphical user interface) made for Gnome or KDE will be different than what you are familiar with or the GUI may crash. Files When a User is Created There are five major files that are employed when the administrator creates a user. /etc/passwd - contains user account information /etc/shadow - secure user password stored here, only root can read it /etc/group - group information for user /etc/default/useradd - default information for adding all users /etc/login.defs - system default login in settings User Passwords Passwords are kept in /etc/passwd Example Entry: mike - username x - encrypted password 500 - user ID 500 - Group ID Mike - information about user /home/mike - user's home directory /bin/bash - user's login shell mike:x:500:500:Mike :/home/mike:/bin/bash Creating a Password If you would like to create a new password for a user you will use two commands. The first will indicate the user you want to make the change for and the second will be the password. The command is passwd username. Example: passwd john Then you would be asked to enter the new password two times.

Managing Users and Groups


Password Control

147

The command usermod can be used to create several password aging attributes. Here are several options: -c comment -d home_dir -e expire_date -f inactivity -g group -G grouplist -l login_name -m -s shell -u user_id description of the user change the home directory assign an expiration date in the MM/DD/YYYY format number of days before account disabled change primary group set the list of groups that the user is in change login name for user used only with -d option, home contents copied to new home directory indicate a new shell change user ID

Reset a Password Users forget their passwords. Often the administrator will be expected to reset those passwords. Looking up passwords is not a possibility because they are encrypted in storage. A new password must be created with the passwd command. To reset the password for user John: passwd John Then you will be prompted to enter a password twice. chage Check Password The command chage -l can be used to show the status of a user's password protection. Let's say you wanted to check the status of diane's password. chage -l diane Minimum: 0 Maximum: 20 Warning: 7 Inactive: -1 Last Change: Password Expires: Password Inactive: Account Expires:

May, 01, 2002 May 21, 2002 Never May 30, 2002

Managing Users and Groups

148

Modify Users Modify Password of User Mike passwd mike Enter new password. Assign a Group useradd mike -G 505 This assigns mike to the 505 group, this should be an existing group. Assign a ID # useradd mike -u 509 This assigns mike the ID of 509. Assign a Shell useradd mike -s /bin/ash Assigns a specific shell to the user Shadow Passwords User and group passwords are encrypted in /etc/shadow and /etc/gshadow. This removes the passwords from the publicly accessible /etc/passwd file. Only the root user is able to access these two files. The result is that users will not be able to attempt to crack other user passwords. Note, activating shadow passwords is an option during installation. pwconv - converts the existing /etc/passwd file to shadow passwords. pwunconv - returns the passwords to the former state grpconv - converts group file grpunconv - returns group file to former state User ID (UID)

Managing Users and Groups

149

Typically user IDs are unique and will begin with the number 500. Administration IDs are usually less than 100. The administration IDs should not be modified as it may impact the system. The UID of 0 is the superuser or root. Often administrators simply allow the system to assign UIDs. One tool sometimes used to change UIDs is usermod, though this is not recommended as it will probably have negative effects. The Graphical User Interface is usually an option with all major operating systems. When you create a new user you may enter a name, the real name and password. The Login Shell may be selected from those available. You also choose the location for the home directory. The home directory is usually located in the /home directory with the user name as the new directory. example: /home/salley. Disable Accounts Existing Account mike:x:500:500:Mike :/home/mike:/bin/bash Disable Account with * in second column mike:*:500:500:Mike :/home/mike:/bin/bash Expire User Accounts Using the expire option will allow the administrator to lock down an account without destroying the data so that it may be available for a short time. Example: chage -E /06/08/03 mike This option is valuable for temporary accounts as well. A directory could be created to hold the user's files for a time. Example: mkdir /mikeold: chmod 000 /mikeold This will protect the data from being changed.

Managing Users and Groups


Delete Users

150

Example: The -r takes all associated files and directories in the home directory. It will not delete files owned by the user in another directory besides home. userdel -r mike If you only wanted to delete the the user account and login you would use: userdel mike Delete All User Files As explained earlier, when you use userdel to delete a user account the command will not delete files owned by the user, but outside the user's home directory. You will need to search those out: find / -user mike -print This command will search for all files owned by the user mike starting with / and print the filenames to the screen. Change File Ownership There may be a time when you need to delete a user and replace that user with another user who will need access to the former user's files. For this you want to change ownership of the needed files. Do a search and change the files. find / -user mike -exec chown joe ; Place brackets after joe so that the output can be placed in them. All of the files will be searched out for mike and ownership changed to joe.

Managing Users and Groups

151

/etc/profile When the bash shell begins, this file is one of the ones it will look for. The commands listed in this file will be executed and set up information that will impact the global configuration for all bash users. This file will not contain the aliases, these will instead be located in the bashrc file because /etc/profile is only executed on the first login while the aliases may be needed for various shells. Skeleton Directory The skeleton directory allows you to configure a template directory that can be used for new users. When you create a new user and use the -k option, you can specify that the skeleton directory be used. In fact, you could create several skeleton directories that you could use for different kinds of users, setting permissions and giving access to resources that the users may need. /etc/skel The default files for creating new user accounts is /etc/skel. Example: ../ .bash_logout .bash_profile .bashrc .emacs .gtkrc .screenrc All users will get the same settings. These skeleton user files are used to populate newly created user accounts with standard, commonly used files.

User Default Environment When you use useradd the defaults are supplied by the /etc/login.defs file. If you want to

Managing Users and Groups

152

modify these defaults it can be done manually or by using useradd with the -D option and then changing one of the additional options. -b -e -f -g -s default_home default_expiration date default_inactive default_group default_shell

Example: useradd -D -b /home/finance -s /bin/bash This will change the default values.

chsh
The chsh command is used to change shells. This will only change the shell. chsh -s /bin/ash -s shell -l -v -u -help csh csh changes the shell to the C shell. login shell show available shells version information usage message

Quotas
Disk quotas allow the administrator to limit the disk space used by users and groups. The quota command can be used to create quotas for users stored in /etc/passwd and for groups in /etc/group. Usually the restrictions are placed on the directories that users have in /home but they can be applied to the filesystem in /etc/fstab. Some Linux systems do not support quotas.

Managing Users and Groups

153

Quota limits are of five types: 1. Per-User Hard Limit - once limit is achieved the user will not be able to write to the disk 2. Per-User Soft Limit - once the user reaches the limit a warning is given and the user has time to finish the write but the warning remains on the terminal until it is cleaned up 3. Per-Group Hard Limit - once limit is achieved the group, including all individual users will not be able to write to the disk 4. Per-Group Soft Limit - once the group reaches the limit a warning is given and all the users have time to finish the write but the warning remains on the terminals until it is cleaned up 5. Grace Period - once the soft limit is reached a Grace Period is initiated, and the user/users have a set number of hours, days, etc. until it turns into a hard limit

Quota

Installation of Quotas The kernel must be able to support quotas. By default quotas are setup on most systems, this is an example of a Enterprise Server found in /boot/config-2.4.*** The config file (kernel) name will be different on each system. Please note that if the config file does not have quota enabled it may have to be changed in the kernel. # File systems # CONFIG_FS_POSIX_ACL=y CONFIG_QUOTA=y Check to see if the quota rpm is installed rpm -qi quota Find a list of tools that are associated with quota rpm -ql quota /sbin/quotaon /fs This command will enable quotas for the filesystem. /sbin/quotaoff /fs This command will disable quotas for the filesystem. /usr/sbin/edquota username Edit the quotas for a specific user. /usr/bin/quota Users can review the quotas set for them. /usr/sbin/repquota Generates a report of disk usage by users.

Managing Users and Groups


/sbin/quotacheck Checks for quota usage

154

Setting Up Quotas When the computer starts there is a script that will check to see if /etc/fstab has been modified to provide quotas. This script will run the two commands needed to enable quotas; quotacheck and quotaon. The script is found at /etc/rc.sysinit if you would like to view it. Edit /etc/fstab In order for a directory to use quotas it must be set up in the /etc/fstab file. Be careful, make a backup of /etc/fstab before making modifications. In the example below the upper line shows the default, the lower line shows the modifications to begin the process of setting up quotas. The second line sets up user quotas, the third line sets up user quotas and group quotas. /dev/hda7 /home ext3 defaults 12 ##################################### /dev/hda7 /home ext3 exec,dev,suid,rw,usrquota 12 ##################################### /dev/hda7 /home ext3 exec,dev,suid,rw,usrquota,grpquota

12

Once the changes have been made, (you made a backup right?), then restart the system to remount the quotas after being set up. Starting the Quota System The following options can be employed with the command quotacheck to gain information for managing the server, run only when the filesystem is unmounted in most cases. -a -v -u -g -m scan for quotas by checking the /etc/mtab file verbose scan scan for user quotas scan for group quotas remounts a scanned filesystem

If you run a command like this (only run it on an umounted system), it will check all the above: quotacheck -avugm This command will check the /etc/mtab. If the quotas were set up correctly there should be a aquota file in the directory that the

Managing Users and Groups

155

quotas were setup on. Try this command for quotas on the /home directory, assuming /home is on a separate partition. ls -la /home/aquota.* You should see the output that the file exists. Set Up User Quotas The edquota command is what you will use to edit a users quota. This command actually edits the aquota.user file if you are editing for users and the aquota.group file if you will be setting limits on groups. edquota -u fred This command will open up fred quota file which has seven columns. The top of the file will list the user name and UID. The first column will list the directory filesystem. This is usually in the format of the partition that the quotas are on. An example: /dev/hda6 The second column lists the number of blocks that are currently used by the user. These are 1KB blocks. An example: 4485296 This is almost 4.5 GB. The next two columns represent the soft and hard limits for the users. 0 means that the user has no limits. 4000000 in the soft limit means that when the user reaches 4 GB they will activate a message that they are in violation of their quota. The grace period set in days gives this user the opportunity to make changes to move under the soft limit. Once the grace period is over, the user will be forced to make the necessary changes. The hard limit represents a boundary that the user will not be able to cross no matter what. Administrators do not need to set hard limits unless the grace period is used. If an administrator does not use the grace period the result will be that the soft limit will be the boundary for users. Typically, users appreciate a reasonable boundary with a warning system so that in the middle of an important project they are not forced with deleting data before they can save. Of course there are always the users that will push it to the limit. Creating a Profile:

Managing Users and Groups

156

One advantage of the edquota command is that an administrator is able to create one quota for a user and then use that user as a template or profile for other users. Create a profile for a user, save and test the quota to be sure it is correct. Then use the edquota command to roll out that profile to other users. Here is an example. Disk quotas for user fred (uid 505): Filesystem blocks soft hard /dev/sdc1 34000 35000 40000 inodes soft hard 234 0 0

Here fred represents the profile so that once fred quota file is saved it may be used to create other user quotas. Use this command to create similar quotas for harry and mary. edquota -up fred harry mary The edquota command may also be used to create group limits on space used. The -g option will provide this feature. edquota -g office The first thing to do is to make sure the group has been created. In the example, office group is used to create a limit for the whole of office users. Note this is a SCSI drive in the example not a IDE drive. Disk quotas for user office (gid 509): Filesystem blocks soft hard /dev/sdc1 34000 35000 40000

inodes soft hard 234 0 0

The quotacheck command must be run on a regular basis to maintain the quotas that have been set. Quota Options: quotacheck The purpose of this command is to scan the filesystem for disk usage, create, check and repair quota files. The quotacheck command should be run when the system boots and when it mounts nonvalid filesystems. This command should only be run when the quotas are turned off as it can cause damage to data in quota files. -a check for quotas in /etc/mstab

Managing Users and Groups

157

-v verbose -u check for user quotas -g check for group quotas -m remount the directory that scanned for quotas -d debugging mode -f forces checking and writing of new quota files when the quotas are enabled....not recommended to use! quota This command checks the disk usage and the limits of users and groups. -u check for user quotas -g check for group quotas -q show filesystems where the user is over the limit repquota This command creates a summary of quotas on a filesystem. -u -a -v -g report on quotas for a user report on quotas for entire filesystem report all quotas even if no usage report quotas fro groups

edquota This provides a way to edit quotas for users. -u edit user -g edit group -t edit soft limit time

View Quotas
The quota command displays the quota limits on users or groups. quota -u quota -g Example: user quota followed by username group quota followed by group name

Managing Users and Groups


quota -u mike Returned info: Disk quotas for user mike (uid 500): none

158

Groups Every user will be created and added to a group. Groups are an effective method of managing users with similar needs. The command to create a group is groupadd. There are a number of options that can be used with the groupadd command. If you wanted to add a new group called sales you would use the following command:

groupadd
groupadd sales -g gid -r -f -o -help group number, 0-499 are usually for system accounts the group added will be a system account this option will not allow you to exit if a group with the same name exists this will allow you to use an existing gid if used with the -g option

group Files When a group is created, or another user is added to a group, several files will be changed. /etc/group - contains group information /etc/gshadow - contains the secure account information

groupmod
The groupmod command is used to create, modify, or delete groups. If you needed to change the group sales to a new group called marketing, you would type this command:

Managing Users and Groups


groupmod sales -n marketing

159

This will change the group account sales to marketing. -g gid -n change group id numbers, must be unique change the name of a group

chgrp
This command will change group assignments which are associated with a file or directory. Options -c print changes -f ignore information about files that can not be changed -v verbose information on changes -R changes occur recursively, all subdirectories are also changed Example: chgrp admin fred.info This will change the group assigned to this file from fred to the admin which could be a more restricted group. The Graphical User Interface provides a visual method of creating groups. The program lists the users and groups that are available with ID numbers. To create a new group you will have to select a name and a GID (group identification number). You can manually select the number you want or allow the program to select the next available number. Here is a list of groups and GIDs as well as the list of the users in each group. When you choose group properties you can select what users you want to place in your group simply by placing a check mark next to their name. Here you can see three members have been added to the TechSupport group. If you had a large number of users and groups you may want to filter how you view your information. By choosing the filter "TechSupport" you will see the TechSupport group as well as the members of that group.

Managing Users and Groups

160

groupdel
The groupdel command is used to delete a group. This will remove the group from the server. Files will have to be checked to verify that there are no existing files with the group ID. Also, if the group is a primary group it cannot be deleted until all the users have been removed. groupdel sales

newgrp
This command will change your group permissions after logging in.

chown
This command changes the ownership of a file or directory. Example: Let's say Fred has created a file called text and it is stored in Fred's home directory. What you want to do is change the ownership from Fred (who created the file) to Jim. chown jim /home/fred/text Now Jim is the owner of this file.

Managing Users and Groups

161

useradd
This command enables the administrator to create new user accounts. Options -c add a comment -d create a home directory, the default is /home/username -D list and change system defaults -m create and populate home directory -s define specific shell for user

usermod
At times you will need to modify user accounts which may be done with this command. Options -L lock a password -U unlock a password This command will enable you to use many of the same commands as those found in useradd. For example you may use this command to add a comment to a username. usermod -c "Tech Guy" joe If you had created a user password and wanted to lock it you could use this command: usermod -L joe

userdel
This command allows you to delete a user's account. Options -r recursive removal of home directory If you wanted to remove joe and all of the files in the home directory you would use this command. userdel -r joe Note that the removal of a user and their home directory does not remove files and directories owned by that user on the system, so keep that in mind as those remaining files and directories will need to have the ownership changed.

Managing Users and Groups

162

groupadd
When you would like to add a group this is the command to use. Here is an example: groupadd tech gpasswd Use this command to add a password to a specific group. This may be handy when you have a group that will share a directory. groupmod Options -n name modify the name of a group In the example a group is added called tech but then modified to technology. groupadd tech groupmod -n technology tech groupdel Deleting a group can be performed with this command. groupdel tech passwd This command provides an interactive interface to create passwords for users. Options for root Only -l lock account A user may change their own account password by typing the command. The user must supply their current password to make the change. passwd Changing password for joe (current) UNIX password: Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully Some password management is done to encourage good passwords, see the example. passwd Changing password for joe (current) UNIX password: Enter new UNIX password: Retype new UNIX password:

Managing Users and Groups


Bad: new and old password are too similar

163

As root the superuser may change any user by using the passwd command and then entering the username. The example shows the changing of the password for joe. passwd joe Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully chage The chage command modifies the aging properties of a password. This command allows you to set the time a password expires for example. Options -E expirationdate set date for expiration MM/DD/YY or MM/DD/YYYY -l list user password settings The example lists the settings for joe. chage -l joe Minimum: 0 Maximum: 99999 Warning: 7 Inactive: -1 Last Change: Sep 05, 2005 Password Expires: Never Password Inactive: Never Account Expires: Never The next example shows changing joe's password expiration date and then the out put of listing his settings after it was changed. Note that it shows the date it was changed on. chage -E 08/12/06 joe root@ub:/home/mike # chage -l joe Minimum: 0 Maximum: 99999 Warning: 7 Inactive: -1 Last Change: Sep 05, 2005 Password Expires: Never Password Inactive: Never Account Expires: Aug 12, 2006

Managing Users and Groups

164

Managing Backups

165

Managing Backups

Backing up data is a critical aspect of all computer use. Linux provides many easy methods for backing up data. The user should consider backing up all data that cannot be easily recovered quickly. That includes the /home directory which is the location of user data. You may also want to back up the /etc directory as this is where the majority of configuration files are located.

cpio
cpio can be used for system backups. The cpio format will preserve directory, pathname, inode, user, group, permissions and creation, modification times. Options: -v verbose mode -B use large blocks -Cn use blocks of n bytes -c use ASCII headers

166

Hard Drive Backups


The cost of hard drives continues to drop and so they make great backup options. The key to backing up to a hard drive is to have two hard drives. It is not too productive to backup on the same hard drive as your data because if that drive fails you will lose it all. One way to use a second hard drive is to create a separate partition on the second drive for backups called /bk for instance. Then either drag and-drop data to the second drive or use the cp command. Here is an example with two hard drives where the second hard drive is one partition /bk. This is a quick command: cp -R /home /bk Notice that the copy command, cp is used with the recursive option -R which copies over all the subdirectories as well.

Creating a Backup With Tar


The tar program is on all Linux systems and provides a way to create a backup of a directory quickly. The format for tar is: tar options destination source It is easy to get the destination and source confused so double check it. If the user mary wanted to back up her home directory to a backup partition called /bk this would be the command: tar cvf /bk/mary_bk.tar /home/mary Notice the options are: c create an archive v verbose and list all the activity f place the archive in a file Now if there were a system crash and mary needed to retrieve that tar file and expand it here is the command to do that: tar xvf /bk/mary_bk.tar / The options are: x extract the files v verbose

167
f w z N read from the file interactive mode enable compression in the tar file, gzip is used only save files newer than the date listed

Notice that if mary lost her directory the whole thing could be restored by indicating where to restore it and that is why the / is important because it would recreate /home/mary from the / directory. If you wanted to list the contents of the tar file to see if a specific file was located in the tar file you would use this command: tar -tvf mike_bk.tar drwxr-xr-x mike/mike drwxr-xr-x mike/mike -rwxr-xr-x mike/mike -rwxr-xr-x mike/mike drwxr-xr-x mike/mike -rwxr-xr-x mike/mike ---cut--0 2005-09-11 07:40:31 home/mike/Desktop/ 0 1969-12-31 17:00:00 home/mike/Desktop/book/ 54307 2003-12-30 12:40:52 home/mike/Desktop/book/00p.png 5782 2004-01-08 08:09:55 home/mike/Desktop/book/Book.stw 0 1969-12-31 17:00:00 home/mike/Desktop/book/Calc/ 27990 2003-08-10 23:18:57 home/mike/Desktop/book/Calc/calc.sxc

Using tarfiles
Some distributions like Slackware use tarfiles to install and update programs. However, all Linux distributions can use tarfiles from the terminal. A tarball is a compressed file containing a program's directory contents which includes source code, a Makefile and documentation. This file is compressed with gzip and created as a file with tar. When both of these programs are used it creates a file extension tar.gz. Because both tar and gzip are common programs on Linux this method of distribution has become not only popular but practical. When you want to use a file that has been compressed and was created with tar you will need to perform two steps to use the program. First you will need to decompress the file, which can be done with this command: gzip -d tarfilename.tar.gz Next you will need to extract the tar file with this command: tar xvf tarfilename.tar Notice that since the file was decompressed the .gz extension was removed. Once this file is extracted into a directory you will need to compile it usually to make it functional. The directory that was created when the file was extracted will contain a README file that will

168
give you complete instructions on what needs to be done to get the program to work but typically it will follow this pattern: 1. Run the configure file that is located in the directory by placing a ./ in front of configure so that it looks like this in a terminal ./configure and then hit Enter. This will make sure that you have the proper compiler and check for dependencies. 2. Use the make command to compile the source code, which creates a binary format. This command is just the word make in the terminal and then choose Enter. 3. The next command is make install in a terminal which installs the binary program in the correct location. Here is what the series of commands will look like: ./configure make make install That process will then install the program that you are interested in using. Here is an example of installing two programs using tar. First, chkrootkit, which is an administrative tool to check for root kits on the system and the second is firefox. The files can be downloaded as tar.gz files. chkrootkit.tar.gz firefox-1.0.installer.tar.gz Copy these two files to the hard drive into the appropriate folder, where you want these in the file system. Both of these files are tar files and are compressed so that to use them you must uncompress, extract and install the files. You can use one tar command to uncompress and extract: tar -zxvf chkrootkit.tar.gz Once this file is extracted then move into the directory with the cd command: cd chkrootkit-0.43 Now as root run the program as root with this command: ./chkrootkit The Firefox browser may be installed by a user with this command: tar -zxvf firefox-1.0.installer.tar.gz Once this file is extracted then move into the directory with the cd command: cd firefox-installer Now run the command: ./firefox-installer If all the necessary dependencies are correct the program will be installed. You may find dependencies that must be fixed before a program can be installed.

169

bzip2
This command will compress a file with the Burrows-Wheeler block-sorting textcompression algorithm. It works much like gzip but with smaller archives. Options -d --decompress -z --compress -t --test -k --keep -s --small decompress decompress compress compress test compression without creating a compressed file test compression without creating a compressed file keep input files keep input files reduce memory usage reduce memory usage

Notice that there are two dashes in front of the options that are words!

compress
This command will compress a file using the Lempe-Ziv coding. Compressed files will replace the original and must be compressed one at a time. Uncompression can be done with the uncompress command. Example: compress mytext uncompress mytext

gzexe
This command will compress executable files to save space on your hard drive. The consequences of compression are that it takes a little longer to execute.

170
Option -d decompress the compressed executable

gzip
This command will compress files using the Lempel-Ziv coding. When the file is compressed it is named file.gz and the original is deleted. Example: gzip mytext Result - mytext.gz Options -c standard output without changing original files -d decompress files -f force compression -N keep original name and timestamp -q quiet mode -r recursive mode -S add a specified suffix instead of .gz -t test for integrity -v verbose mode

unzip
This will unzip a compressed file using the PKZip or Winzip format. example: unzip myfilename.zip That will unzip the file.

171
If you wanted to only unzip one file (ReadMe.txt) from the zipped file you could use: unzip myfilename.zip ReadMe.txt

172

System Administration Tools

173

System Administration Tools

apropos
This command will give you a short definition of a topic. Example: apropos rxvt rxvt (ouR XVT) [rxvt] (1) - a VT102 emulator for the X window system

arch
If you are wanting to know what kind of computer architecture you have on your PC you can

System Administration Tools


find out with this command. arch i686

174

This tells you that your computer is a modern Pentium computer. Several other outputs are possible such as i386, i486, i586.

at
The at command will run a script at a specified time. The command is used by typing at and then the time you want the activity to occur. This will create the at> prompt enabling you to enter the commands you desire to run. When you are done press Control+D. Example: at 5:32am at> echo "Time to get started" at> Contol+D Unlike cron, these jobs will only run once. The time format is hh:mm Options -l list jobs -d jobnumber delete a job This example shows that the user root has two jobs waiting. at -l 2 2005-09-11 09:07 a root at -d job1 This will delete job1.

System Administration Tools

175

batch
batch is much like at except that batch runs when the load average falls below a certain level. The default load average is 0.8.

bc
This command comes from an engineering tool. bc uses common operators as well as more complex operators. Common Operators: + addition subtraction / division * multiplication % remainder ^ exponential sqrt(n) square root It is important to note that the bc command needs to be stopped with the command: quit

chroot
This command changes the root directory to a specified path. Example: If you wanted to change the root directory to /home/software you would type the following command: chroot /home/software

chkconfig
This command is used to activate and deactivate services. Example:

System Administration Tools

176

chkconfig - -list Notice in the list the columns represent run levels that each program is on or off. chkconfig You can change run levels for programs using this command. Example: chkconfig --level 345 msqld off First notice that there are two dashes in front of level. This command turns of mysqld in run levels 3,4 and 5.

cksum
If you want to check to see if you file is corrupt you can use this command: cksum filename

cron
cron is designed to help the administrator run commands on a regular basis unattended. In order to protect cron, two files are used to limit access to the program. /etc/cron.allow /etc/cron.deny If both of these files are empty, all users will have the ability to run cron files. Submitting a cron job: /var/spool/cron/username /etc/crontab /etc/cron.d /etc/cron.hourly /etc/cron.daily /etc/cron.weekly /etc/cron.monthly - individual cron jobs - root user for the system cron jobs - root user for the system cron jobs - each has a shell script that runs

System Administration Tools

177

Here is an example of /etc/cron.daily If you wanted to add a program into this file, edit it as root and on one line include the command you need to run. " Press ? for keyboard shortcuts " Sorted by name (.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.b"= /etc/cron.daily/ ../ .placeholder 0anacron apt bsdmainutils find.notslocate logrotate man-db netkit-inetd samba slocate standard sysklogd Here is an example of /etc/cron.weekly " Press ? for keyboard shortcuts " Sorted by name (.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.b"= /etc/cron.weekly/ ../ .placeholder 0anacron man-db popularity-contest sysklogd Here is an example of /etc/cron.monthly " Press ? for keyboard shortcuts " Sorted by name (.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.b"= /etc/cron.monthly/ ../ .placeholder 0anacron scrollkeeper standard

System Administration Tools

178

cron Format There are seven fields that must be used. field 1 - minute 0-59, a - between numbers means a range 1-30 a comma between numbers means individual 1,5,8 2 hour 0-23 3 day of month 0-31 4 month 0-12 5 day of week 0-7 (both and 7 are Sunday) 6 user 7 command Example: 7 0 * * 1 /home/mike/bk.sh This will run the backup script in /home/mike at 12:07 Mondays. The asterisk in a field indicates that all possible values are run for that field. Create a cron Job Three commands are important for creating cron jobs. crontab -l crontab -r crontab -e list all the current cron jobs for user remove cron jobs edit cron jobs

When crontab -e is run the vi editor opens and the user is allowed to edit the file. It is imperative that the user be familiar with vi so that the file can be edited and saved. Example: crontab -e (this opens crontab file) click i (edit mode in vi) 10 * * * * /home/mike/bk (runs backup script at 10 after the hour) esc (exits edit mode in vi, now in command mode) shift: w! (writes the file that you have created) shift: q (quits vi editor)

System Administration Tools

179

dumpkeys
The purpose of this command is to provide information on your current keyboard driver.

dmesg
This command provides the information that flashed across the screen during startup. Example: dmesg | less This command will help you go through one page at a time so you can read it. Here is an example; Linux version 2.6.10-5-386 (buildd@vernadsky) (gcc version 3.3.5 (Debian 1:3.3.5-8ubuntu2)) #1 Fri Jun 24 16:53:01 UTC 2005 BIOS-provided physical RAM map: BIOS-e820: 0000000000000000 - 000000000009fc00 (usable) BIOS-e820: 000000000009fc00 - 00000000000a0000 (reserved) BIOS-e820: 00000000000f0000 - 0000000000100000 (reserved) BIOS-e820: 0000000000100000 - 000000000fff0000 (usable) BIOS-e820: 000000000fff0000 - 000000000fff3800 (reserved) BIOS-e820: 000000000fff3800 - 0000000010000000 (ACPI NVS) 255MB LOWMEM available. On node 0 totalpages: 65520 DMA zone: 4096 pages, LIFO batch:1 Normal zone: 61424 pages, LIFO batch:14 HighMem zone: 0 pages, LIFO batch:1 DMI 2.3 present. ACPI: RSDP (v000 COMPAQ ) @ 0x000f9970 ACPI: RSDT (v001 COMPAQ RSDTBL 0x00000001 CPQ 0x00000001) @ 0x0fff476d ACPI: FADT (v001 COMPAQ CPQB151 0x20020315 CPQ 0x00000001) @ 0x0fff4828 ACPI: SSDT (v001 COMPAQ CPQGysr 0x00001001 MSFT 0x0100000c) @ 0x0fff4799 ACPI: DSDT (v001 COMPAQ ARMADAE7 0x00010000 MSFT 0x0100000c) @

System Administration Tools

180

0x00000000 ACPI: PM-Timer IO Port: 0x5008 Built 1 zonelists Kernel command line: root=/dev/hda1 ro quiet splash Local APIC disabled by BIOS -- you can enable it with "lapic" mapped APIC to ffffd000 (01203000) Initializing CPU#0 PID hash table entries: 1024 (order: 10, 16384 bytes) Detected 995.720 MHz processor. Using pmtmr for high-res timesource Console: colour VGA+ 80x25 Dentry cache hash table entries: 65536 (order: 6, 262144 bytes) Inode-cache hash table entries: 32768 (order: 5, 131072 bytes) Memory: 252060k/262080k available (1436k kernel code, 9404k reserved, 754k data, 224k init, 0k highmem) Checking if this processor honours the WP bit even in supervisor mode... Ok. Calibrating delay loop... 1974.27 BogoMIPS (lpj=987136) Security Framework v1.0.0 initialized SELinux: Disabled at boot. Mount-cache hash table entries: 512 (order: 0, 4096 bytes) CPU: After generic identify, caps: 0383f9ff 00000000 00000000 00000000 00000000 00000000 CPU: After vendor identify, caps: 0383f9ff 00000000 00000000 00000000 00000000 00000000 CPU: L1 I cache: 16K, L1 D cache: 16K CPU: L2 cache: 256K CPU: After all inits, caps: 0383f9ff 00000000 00000000 00000040 00000000 00000000 CPU: Intel Pentium III (Coppermine) stepping 0a Enabling fast FPU save and restore... done. Enabling unmasked SIMD FPU exception support... done. Checking 'hlt' instruction... OK. Checking for popad bug... OK. ACPI: Looking for DSDT in initrd... not found! ACPI: setting ELCR to 0200 (from 0800) checking if image is initramfs...it isn't (bad gzip magic numbers); looks like an initrd Freeing initrd memory: 4300k freed NET: Registered protocol family 16 EISA bus registered PCI: PCI BIOS revision 2.10 entry at 0xf0478, last bus=1 PCI: Using configuration type 1 mtrr: v2.0 (20020519) ACPI: Subsystem revision 20050211 ACPI: Interpreter enabled ACPI: Using PIC for interrupt routing

System Administration Tools

181

ACPI: PCI Root Bridge [C005] (00:00) PCI: Probing PCI hardware (bus 00) ACPI: PCI Interrupt Routing Table [\_SB_.C005._PRT] ACPI: Power Resource [C129] (on) ACPI: Power Resource [C0DB] (on) ACPI: PCI Interrupt Link [C142] (IRQs *11) ACPI: PCI Interrupt Link [C148] (IRQs 11) *0, disabled. ACPI: PCI Interrupt Link [C149] (IRQs *11) ACPI: PCI Interrupt Link [C14A] (IRQs *11) ACPI: Power Resource [C15F] (off) ACPI: Power Resource [C161] (off) ACPI: Power Resource [C163] (off) Linux Plug and Play Support v0.97 (c) Adam Belay pnp: PnP ACPI init pnp: PnP ACPI: found 15 devices PnPBIOS: Disabled by ACPI PNP PCI: Using ACPI for IRQ routing ** PCI interrupts are no longer routed automatically. If this ** causes a device to stop working, it is probably because the ** driver failed to call pci_enable_device(). As a temporary ** workaround, the "pci=routeirq" argument restores the old ** behavior. If this argument makes the device work again, ** please email the output of "lspci" to bjorn.helgaas@hp.com ** so I can fix the driver. PCI: Cannot allocate resource region 4 of device 0000:00:07.1 pnp: 00:0c: ioport range 0x4d0-0x4d1 has been reserved pnp: 00:0c: ioport range 0x800-0x87f has been reserved pnp: 00:0c: ioport range 0x4000-0x400f has been reserved pnp: 00:0c: ioport range 0x5000-0x5063 could not be reserved pnp: 00:0c: ioport range 0x6004-0x6005 could not be reserved pnp: 00:0c: ioport range 0xf000-0xf0cf has been reserved audit: initializing netlink socket (disabled) audit(1124158427.917:0): initialized VFS: Disk quotas dquot_6.5.1 Dquot-cache hash table entries: 1024 (order 0, 4096 bytes) devfs: 2004-01-31 Richard Gooch (rgooch@atnf.csiro.au) devfs: boot_options: 0x0 Initializing Cryptographic API Limiting direct PCI/PCI transfers. isapnp: Scanning for PnP cards... isapnp: No Plug & Play device found i8042.c: Detected active multiplexing controller, rev 1.0. serio: i8042 AUX0 port at 0x60,0x64 irq 12 serio: i8042 AUX1 port at 0x60,0x64 irq 12

System Administration Tools

182

serio: i8042 AUX2 port at 0x60,0x64 irq 12 serio: i8042 AUX3 port at 0x60,0x64 irq 12 serio: i8042 KBD port at 0x60,0x64 irq 1 Serial: 8250/16550 driver $Revision: 1.90 $ 54 ports, IRQ sharing enabled ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A ttyS2 at I/O 0x3e8 (irq = 4) is a 16550A ACPI: PCI Interrupt Link [C149] enabled at IRQ 11 PCI: setting IRQ 11 as level-triggered ACPI: PCI interrupt 0000:00:09.1[A] -> GSI 11 (level, low) -> IRQ 11 ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A io scheduler noop registered io scheduler anticipatory registered io scheduler deadline registered io scheduler cfq registered RAMDISK driver initialized: 16 RAM disks of 8192K size 1024 blocksize input: AT Translated Set 2 keyboard on isa0060/serio0 EISA: Probing bus 0 at eisa0 Cannot allocate resource for EISA slot 1 Cannot allocate resource for EISA slot 3 Cannot allocate resource for EISA slot 4 Cannot allocate resource for EISA slot 5 Cannot allocate resource for EISA slot 6 EISA: Detected 0 cards. NET: Registered protocol family 2 IP: routing cache hash table of 2048 buckets, 16Kbytes TCP: Hash tables configured (established 16384 bind 32768) NET: Registered protocol family 8 NET: Registered protocol family 20 Restarting tasks...<6> Strange, kswapd0 not stopped Strange, kseriod not stopped done ACPI wakeup devices: C005 C0AE C14B C057 C16B ACPI: (supports S0 S1 S3 S4 S4bios S5) RAMDISK: cramfs filesystem found at block 0 RAMDISK: Loading 4300KiB [1 disk] into ram disk... done. VFS: Mounted root (cramfs filesystem) readonly. Freeing unused kernel memory: 224k freed ACPI: Fan [C15D] (off) ACPI: Fan [C160] (off) ACPI: Fan [C162] (off) ACPI: CPU0 (power states: C1[C1] C2[C2]) ACPI: Processor [C0B4] (supports 8 throttling states) ACPI: Thermal Zone [C15E] (42 C)

System Administration Tools

183

NET: Registered protocol family 1 Uniform Multi-Platform E-IDE driver Revision: 7.00alpha2 ide: Assuming 33MHz system bus speed for PIO modes; override with idebus=xx PIIX4: IDE controller at PCI slot 0000:00:07.1 PIIX4: chipset revision 1 PIIX4: not 100% native mode: will probe irqs later ide0: BM-DMA at 0x1000-0x1007, BIOS settings: hda:DMA, hdb:DMA Probing IDE interface ide0... hda: TOSHIBA MK1516GAP, ATA DISK drive hdb: Compaq CRN-8241B, ATAPI CD/DVD-ROM drive elevator: using anticipatory as default io scheduleride0 at 0x1f0-0x1f7,0x3f6 on irq 14 hda: max request size: 128KiB hda: 23579136 sectors (12072 MB), CHS=23392/16/63, UDMA(33) hda: cache flushes not supported /dev/ide/host0/bus0/target0/lun0: p1 p2 < p5 > Probing IDE interface ide1... ide2: I/O resource 0x3EE-0x3EE not free. ide2: ports already in use, skipping probe Probing IDE interface ide3... Probing IDE interface ide4... Probing IDE interface ide5... Stopping tasks: ==| Freeing memory... done (458 pages freed) Restarting tasks... done EXT3-fs: mounted filesystem with ordered data mode. kjournald starting. Commit interval 5 seconds Adding 514040k swap on /dev/hda5. Priority:-1 extents:1 EXT3 FS on hda1, internal journal hdb: ATAPI 24X CD-ROM drive, 128kB Cache Uniform CD-ROM driver Revision: 3.20 parport: PnPBIOS parport detected. parport0: PC-style at 0x378, irq 7 [PCSPP,TRISTATE,EPP] lp0: using parport0 (interrupt-driven). mice: PS/2 mouse device common for all mice Synaptics Touchpad, model: 1 Firmware: 5.6 Sensor: 22 new absolute packet format Touchpad has extended capability bits -> multifinger detection -> palm detection input: SynPS/2 Synaptics TouchPad on isa0060/serio4 ts: Compaq touchscreen protocol output Capability LSM initialized

System Administration Tools

184

device-mapper: 4.3.0-ioctl (2004-09-30) initialised: dm-devel@redhat.com md: md driver 0.90.1 MAX_MD_DEVS=256, MD_SB_DISKS=27hdb: packet command error: status=0x51 { DriveReady SeekComplete Error } hdb: packet command error: error=0x54 ide: failed opcode was 100 cdrom: open failed. inserting floppy driver for 2.6.10-5-386 Floppy drive(s): fd0 is 1.44M FDC 0 is a post-1991 82077 irda_init() NET: Registered protocol family 23 input: PC Speaker Real Time Clock Driver v1.12 Linux agpgart interface v0.100 (c) Dave Jones agpgart: Detected an Intel 440BX Chipset. agpgart: Maximum main memory to use for agp memory: 203M agpgart: AGP aperture is 64M @ 0x50000000 cpci_hotplug: CompactPCI Hot Plug Core version: 0.2 pci_hotplug: PCI Hot Plug PCI Core version: 0.5 shpchp: acpi_shpchprm:\_SB_.C005 evaluate _BBN fail=0x5 shpchp: acpi_shpchprm:get_device PCI ROOT HID fail=0x5 pciehp: acpi_pciehprm:\_SB_.C005 evaluate _BBN fail=0x5 pciehp: acpi_pciehprm:get_device PCI ROOT HID fail=0x5 Linux Kernel Card Services options: [pci] [cardbus] [pm] ACPI: PCI Interrupt Link [C142] enabled at IRQ 11 ACPI: PCI interrupt 0000:00:04.0[A] -> GSI 11 (level, low) -> IRQ 11 Yenta: CardBus bridge found at 0000:00:04.0 [0e11:b121] Yenta: Enabling burst memory read transactions Yenta: Using CSCINT to route CSC interrupts to PCI Yenta: Routing CardBus interrupts to PCI Yenta TI: socket 0000:00:04.0, mfunc 0x01001c72, devctl 0x64 Yenta: ISA IRQ mask 0x0438, PCI irq 11 Socket status: 30000006 ACPI: PCI interrupt 0000:00:04.1[A] -> GSI 11 (level, low) -> IRQ 11 Yenta: CardBus bridge found at 0000:00:04.1 [0e11:b121] Yenta: Using CSCINT to route CSC interrupts to PCI Yenta: Routing CardBus interrupts to PCI Yenta TI: socket 0000:00:04.1, mfunc 0x01001c72, devctl 0x64 Yenta: ISA IRQ mask 0x0438, PCI irq 11 Socket status: 30000006 usbcore: registered new driver usbfs usbcore: registered new driver hub USB Universal Host Controller Interface driver v2.2

System Administration Tools

185

ACPI: PCI Interrupt Link [C14A] enabled at IRQ 11 ACPI: PCI interrupt 0000:00:07.2[D] -> GSI 11 (level, low) -> IRQ 11 uhci_hcd 0000:00:07.2: Intel Corp. 82371AB/EB/MB PIIX4 USB uhci_hcd 0000:00:07.2: irq 11, io base 0x4020 uhci_hcd 0000:00:07.2: new USB bus registered, assigned bus number 1 hub 1-0:1.0: USB hub found hub 1-0:1.0: 2 ports detected usb 1-1: new low speed USB device using uhci_hcd and address 2 piix4_smbus 0000:00:07.3: Found 0000:00:07.3 device usbcore: registered new driver hiddev input: USB HID v1.10 Mouse [Logitech USB Receiver] on usb-0000:00:07.2-1 usbcore: registered new driver usbhid drivers/usb/input/hid-core.c: v2.0:USB HID core driver ACPI: PCI interrupt 0000:00:08.0[A] -> GSI 11 (level, low) -> IRQ 11 es1968: clocking to 48000 e100: Intel(R) PRO/100 Network Driver, 3.2.3-k2-NAPIe100: Copyright(c) 1999-2004 Intel Corporation ACPI: PCI interrupt 0000:00:09.0[A] -> GSI 11 (level, low) -> IRQ 11 e100: eth0: e100_probe: addr 0x41280000, irq 11, MAC addr 00:D0:59:9C:3D:FC e100: eth0: e100_watchdog: link up, 10Mbps, half-duplex NET: Registered protocol family 17 NET: Registered protocol family 10 Disabled Privacy Extensions on device c02f0500(lo) IPv6 over IPv4 tunneling driver ACPI: AC Adapter [C0F6] (on-line) ACPI: Battery Slot [C0FE] (battery present) ACPI: Battery Slot [C0FF] (battery absent) ACPI: Battery Slot [C100] (battery absent) ACPI: Power Button (FF) [PWRF] ACPI: Sleep Button (CM) [C057] ACPI: Lid Switch [C16B] ibm_acpi: ec object not found apm: BIOS version 1.2 Flags 0x03 (Driver version 1.16ac) apm: overridden by ACPI. mtrr: 0x40000000,0x800000 overlaps existing 0x40000000,0x400000 mtrr: 0x40000000,0x800000 overlaps existing 0x40000000,0x400000 ip_tables: (C) 2000-2002 Netfilter core team ip_conntrack version 2.1 (2047 buckets, 16376 max) - 336 bytes per conntrack eth0: no IPv6 routers present cs: IO port probe 0x0100-0x04ff: excluding 0x100-0x107 cs: IO port probe 0x0800-0x08ff: clean. cs: IO port probe 0x0c00-0x0cff: clean. cs: IO port probe 0x0a00-0x0aff: clean. e100: eth0: e100_watchdog: link down

System Administration Tools

186

e100: eth0: e100_watchdog: link up, 10Mbps, half-duplex As you review the example you can see it would be a great aid in troubleshooting problems because it shows the hardware status of the machine and how it is interacting with the software and kernel. Notice the important role that ACPI plays in managing both power and hardware.

expand
When you would like to convert tabs to spaces you may use expand. By default this command will convert the standard tab to 8 spaces. you may also specify the tab stops. Options -t tab stops, default i s8 spaces -i convert only the first tab

fmt The fmt command allows you to format text to a specific width. Options -u uniform spacing -w width, default is 75 characters join This command may be used to join data from two separate files. It can be used as a simple database configuration method. Here is the first file, d1. 1 mike 2 fred 3 tom 4 mary Here is the second file. 1 87jKl45F 2 ho7%kd9 3 hom873J 4 modj8#

System Administration Tools

187

Here the two files are joined and a third file is created (d3) with the completed process. Note the numbering of the lines. join -j 1 d1 d2 > d3 cat d3 1 mike 87jKl45F 2 fred ho7%kd9 3 tom hom873J 4 mary modj8#

getkeycodes This command will return the scancode-to-keycode mapping from the kernel.

id This command returns information about users and groups. Here is an example of the user mike using the command id. mike@ub:~$ id uid=1000(mike) gid=1000(mike) groups=4(adm),20(dialout),24(cdrom),25(floppy), 29(audio),30(dip),44(video),46(plugdev),107(lpadmin),108(scanner),109(admin), 1000(mike) Several Options: -g returns only group info -G supplementary group info -n returns names -r returns the real user ID and group ID, not the effective IDs -u returns user ID only info This is a method of gaining information on topics of interest. Example: info gimp Options: -f file this will use a file instead of a standard info file - -help

System Administration Tools

188

-o file sends information to a file instead of standard output - - version Close the info program with q. init init is the command that starts and loads drivers for the kernel. It uses 6 different run levels to provide options. 0 1 2 3 4 5 6 halt single user mode, used for emergency recovery multiuser, command line, not network multiuser, command line with network not used Graphical User Interface, multiuser reboot

Example: init 0 This will halt the system. init 6 This will reboot the system.

kbd_mode
This command returns the current mode or it will change modes.

kill
This command will end a process ID or PID. Either you must be root or own the PID to use this command. Example: The first thing you might do is list the PIDs with: kill -l

System Administration Tools


Then you may kill a PID with the format:

189
kill -signal#

killall
killall will kill all processes by name. Notice the killall -l will list PIDs by name. Options: -e performs exact matches on the process name -g this will kill the process group -w waits for specified process to die -l list all valid signals -v verbose mode login The login command is used to log into Linux. Login will ask for a name and a password. Options: -h hostname This will send the login to a remote machine.

find
Use this to find a file. Example: find / -atime -5 This command will find all files and directories changed less than 5 days ago. Options -amin min

-atime days

replace min with the following +min more than m minutes ago m exactly m minutes ago -m less than m minutes ago replace days with the following +d more than d days ago

System Administration Tools


d exactly d days ago -d less than d days ago find a file named file files which are owned by a user

190

-name file -user user

The find command will allow you to search through directories to locate files. The example below shows that the find command is used to search a specific directory, /home/mike for the file named sp.rtf, notice that it is in quotes. find /home/mike -name "sp.rtf" /home/mike/sp.rtf

locate
This command will locate a pattern in a database of filenames and will return the filenames that match. Example: locate .html The return would be all files with .html in the name. Here is an example with results when trying to locate all files with an .sh extension. mike@ub:~$ locate .sh /etc/default/initrd-tools.sh /etc/init.d/procps.sh /etc/init.d/checkroot.sh /etc/init.d/checkfs.sh /etc/init.d/mountnfs.sh /etc/init.d/mountall.sh ---cut--/var/lib/dpkg/info/e2fslibs.shlibs /var/lib/dpkg/info/libcomerr2.shlibs /var/lib/dpkg/info/libss2.shlibs /var/lib/dpkg/info/libuuid1.shlibs /var/lib/dpkg/info/libcap1.shlibs /var/lib/dpkg/info/libdb1-compat.shlibs /var/lib/dpkg/info/libdb3.shlibs /var/lib/dpkg/info/libncurses5.shlibs ---cut---

System Administration Tools

191

Notice in the above example that the return includes files that have .shlibs.

locatedb
This command will locate a pattern in a database of filenames and will return the filenames that match. Example: locatedb .html The return would be all files with .html in the name. lsmod lsmod command lists the currently loaded modules. Here is an example of modules loaded on a laptop. mike@ub:~$ lsmod Module Size Used by speedstep_smi 5520 0 speedstep_lib 4228 1 speedstep_smi proc_intf 4100 0 freq_table 4100 1 speedstep_smi cpufreq_userspace 4572 1 cpufreq_ondemand 6172 0 cpufreq_powersave 1920 0 pcmcia 21380 4 ipt_limit 2688 5 iptable_mangle 2944 0 ipt_LOG 6656 7 ipt_MASQUERADE 3584 0 iptable_nat 24648 1 ipt_MASQUERADE ipt_TOS 2560 0 ipt_REJECT 6528 0 ip_conntrack_irc 71856 0 ip_conntrack_ftp 72624 0 ipt_state 2048 4 ip_conntrack 43668 5 ipt_MASQUERADE,iptable_nat,ip_conntrack_irc,ip_conntrack_ftp,ipt_state iptable_filter 3840 1

System Administration Tools

192

ip_tables 17408 9 ipt_limit,iptable_mangle,ipt_LOG,ipt_MASQUERADE,iptable_nat,ipt_TOS,ipt_REJECT,ipt_ state,iptable_filter video 16260 0 sony_acpi 6280 0 pcc_acpi 11264 0 button 6800 0 battery 10244 0 container 4608 0 ac 4996 0 ipv6 229504 9 af_packet 20744 0 e100 32384 0 mii 4736 1 e100 snd_es1968 27648 2 snd_ac97_codec 64608 1 snd_es1968 snd_pcm_oss 47652 1 snd_mixer_oss 16768 2 snd_pcm_oss snd_pcm 84872 3 snd_es1968,snd_ac97_codec,snd_pcm_oss snd_timer 23300 1 snd_pcm snd_page_alloc 9604 2 snd_es1968,snd_pcm gameport 4608 1 snd_es1968 snd_mpu401_uart 7168 1 snd_es1968 snd_rawmidi 22944 1 snd_mpu401_uart snd_seq_device 8332 1 snd_rawmidi snd 50276 9 snd_es1968,snd_ac97_codec,snd_pcm_oss,snd_mixer_oss,snd_pcm,snd_timer,snd_mpu 401_uart,snd_rawmidi,snd_seq_device soundcore 9824 3 snd usbhid 29376 0 i2c_piix4 8592 0 i2c_core 21264 1 i2c_piix4 uhci_hcd 30224 0 usbcore 107384 3 usbhid,uhci_hcd yenta_socket 19584 0 pcmcia_core 53568 2 pcmcia,yenta_socket pci_hotplug 30512 0 intel_agp 20636 1 agpgart 31784 1 intel_agp rtc 12216 0 pcspkr 3816 0 irtty_sir 7936 0 sir_dev 18092 1 irtty_sir irda 168000 2 irtty_sir,sir_dev

System Administration Tools


crc_ccitt floppy md dm_mod capability commoncap joydev tsdev evdev psmouse mousedev parport_pc lp parport ide_cd cdrom ext3 jbd ide_generic piix ide_disk ide_core unix thermal processor fan fbcon font bitblit vesafb cfbcopyarea cfbimgblt cfbfillrect

193

2176 1 irda 54864 0 43856 0 53116 1 5000 0 7808 1 capability 9408 0 7488 0 9088 1 19336 0 11160 1 34372 1 10792 0 33480 2 parport_pc,lp 38532 0 36508 1 ide_cd 120968 1 54168 1 ext3 1664 0 9988 1 18176 3 118988 4 ide_cd,ide_generic,piix,ide_disk 26164 818 13576 0 22708 1 thermal 4612 0 34048 0 8448 1 fbcon 5120 1 fbcon 6948 0 3968 1 vesafb 3072 1 vesafb 3584 1 vesafb

lsof The lsof command shows you the files that are opened by a command. Here all of the processes associated with /dev/tty1 are listed.

System Administration Tools

194

gam_serve 7668 mike 56r DIR 3,1 4096 213306 /var/lib/updatenotifier/user.d gam_serve 7668 mike 57r DIR 3,1 4096 229378 /var/lib/dpkg gam_serve 7668 mike 58r DIR 3,1 4096 229723 /var/cache/apt/archives/partial gam_serve 7668 mike 59r DIR 3,1 40960 213002 /var/cache/apt/archives gam_serve 7668 mike 60r DIR 3,1 4096 229729 /var/lib/apt/lists/partial gam_serve 7668 mike 61u unix 0xc1ea06e0 16121 socket gam_serve 7668 mike 62r DIR 3,1 4096 164297 /home/mike/Desktop/book gam_serve 7668 mike 63r DIR 3,1 4096 164312 /home/mike/Desktop/book/Commands xscreensa 7676 mike cwd DIR 3,1 4096 2/ xscreensa 7676 mike rtd DIR 3,1 4096 2/ xscreensa 7676 mike txt REG 3,1 218264 1245493 /usr/bin/xscreensaver xscreensa 7676 mike mem REG 3,1 58716 836298 /usr/share/fonts/truetype/ttf-bitstream-vera/VeraBd.ttf xscreensa 7676 mike mem REG 3,1 605432 836325 /usr/share/fonts/truetype/freefont/FreeSerif.ttf xscreensa 7676 mike mem REG 3,1 65932 836296 /usr/share/fonts/truetype/ttf-bitstream-vera/Vera.ttf xscreensa 7676 mike mem REG 3,1 31972 745625 /usr/lib/libXcursor.so. 1.0.2 xscreensa 7676 mike mem REG 3,1 34516 753716 /lib/tls/i686/cmov/libnss_files-2.3.2.so xscreensa 7676 mike mem REG 3,1 32348 753721 /lib/tls/i686/cmov/libnss_nis-2.3.2.so xscreensa 7676 mike mem REG 3,1 73304 753713 /lib/tls/i686/cmov/libnsl-2.3.2.so xscreensa 7676 mike mem REG 3,1 28420 753714 /lib/tls/i686/cmov/libnss_compat-2.3.2.so xscreensa 7676 mike mem REG 3,1 129972 745570 /usr/lib/libexpat.so. 1.0.0 xscreensa 7676 mike mem REG 3,1 65256 737904 /usr/lib/libz.so.1.2.2 xscreensa 7676 mike mem REG 3,1 447212 743696 /usr/lib/libfreetype.so. 6.3.5 xscreensa 7676 mike mem REG 3,1 154916 745604 /usr/lib/libfontconfig.so.1.0.4 xscreensa 7676 mike mem REG 3,1 1222116 753708 /lib/tls/i686/cmov/libc-2.3.2.so xscreensa 7676 mike mem REG 3,1 18300 753709 /lib/tls/i686/cmov/libcrypt-2.3.2.so xscreensa 7676 mike mem REG 3,1 9152 753710 /lib/tls/i686/cmov/libdl-2.3.2.so

System Administration Tools


xscreensa 7676 mike mem REG xscreensa 7676 mike mem REG xscreensa 7676 mike mem REG 820968 /usr/X11R6/lib/libXext.so.6.4 xscreensa 7676 mike mem REG 820962 /usr/X11R6/lib/libX11.so.6.2 xscreensa 7676 mike mem REG 820981 /usr/X11R6/lib/libXt.so.6.0 xscreensa 7676 mike mem REG 820483 /usr/X11R6/lib/libICE.so.6.3 xscreensa 7676 mike mem REG 3,1 3,1 3,1

195
30360 68884 51760 753690 /lib/libpam.so.0.76 745615 /usr/lib/libXft.so.2.1.1

3,1 802576 3,1 316976 3,1 3,1 85680 31804 820485 /usr/X11R6/

makewhatis This command will build and update the whatis database that is used by whatis and apropos.

mc
Launch the directory browser midnight commander which does not require the X Window. As you can see you will be able to use the menu at the bottom to perform many tasks. mke2fs This command create an ext2 file system on a device. Example: /sbin/mke2fs /dev/fd0 This will create an ext2 file system on the floppy. Options -c check for bad blocks

System Administration Tools

196

pathchk This command checks to validate if the filename is valid and it will also check to see if the file meets length requirements. Example: pathchk /home/fred/work One option is available. -p this will check for POSIX portability

ntsysv
This is a text based program to configure which services are started at boot time for each run level. ping This program will help determine if a computer is up by sending a ICMP echo request. Turn off the pings using ctrl+c. ping -c 100 192.168.5.44 This will send 100 pings to the IP address listed. Options -c count number of packets to send -s size determines the size of the packets to be sent -I Interface which network card to use ps ps lists the currently running processes on the system. Each time a program runs on the system a number of processes are started and run to make a program work. These processes or tasks can be listed with the ps command. ps will list processes connected with your account ps aux will show all processes on the machine

System Administration Tools


-a -f -l -u -w -x -C -U

197

current user's processes shown display process family trees, all of the processes related to a daemon for example long format user format with names and start times wide output format, easier to read see processed not started with terminal, usually a daemon display processes used with a command display processes associated with a user

ps -U mike The example shows each process that the user owns mike@ub:~$ ps -U mike PID TTY TIME CMD 7596 ? 00:00:00 x-session-manag 7641 ? 00:00:00 ssh-agent 7644 ? 00:00:00 dbus-launch 7645 ? 00:00:00 dbus-daemon-1 7647 ? 00:00:01 gconfd-2 7650 ? 00:00:00 gnome-keyring-d 7652 ? 00:00:00 esd 7654 ? 00:00:00 bonobo-activati 7656 ? 00:00:01 gnome-settings7659 ? 00:00:04 gam_server 7667 ? 00:00:00 xscreensaver 7691 ? 00:00:00 gnome-smproxy 7693 ? 00:00:05 metacity 7701 ? 00:00:03 gnome-panel 7703 ? 00:00:12 nautilus 7705 ? 00:00:00 gnome-volume-ma 7711 ? 00:00:00 update-notifier 7713 ? 00:00:01 gnome-cups-icon 7718 ? 00:00:04 wnck-applet 7720 ? 00:00:00 trashapplet 7723 ? 00:00:00 gnome-vfs-daemo 7731 ? 00:00:00 mapping-daemon 7736 ? 00:00:00 clock-applet 7738 ? 00:00:00 notification-ar 7740 ? 00:00:00 gnome-netstatus 7742 ? 00:00:01 battstat-applet 7744 ? 00:00:00 mixer_applet2 7747 ? 00:04:17 firefox-bin 8394 ? 00:00:44 soffice.bin 9399 ? 00:00:00 gksudo 10141 ? 00:00:00 gnome-terminal

System Administration Tools


10143 ? 00:00:00 gnome-pty-helpe 10144 pts/0 00:00:00 bash 10160 pts/0 00:00:00 ps

198

Often you may want to only look at the processes for one command: ps -aux | grep sendmail This example looks at the processes run by sendmail.

printenv
The printenv command shows the environmental variables of a user. The command returns all variables unless one is specified.

pwconv
Converts the existing /etc/passwd file to shadow passwords.

pwunconv
returns the passwords to the former state grpconv - converts group file

grpunconv
returns group file to former state reset The reset command is able to reset the terminal. Example: reset

System Administration Tools

199

script
This command will save each character from a terminal session to a specified file. If you do not specify a file it will save it to typescript. Option -a file this will append keystrokes to an existing filename If you would want to record your interaction with the shell you could use this command. Start a script by using the command and a file which will record all of the terminal session information. script test.rtf Script started on Sun 21 Aug 2005 06:31:39 AM MDT ---cut--8 ./.gconf/desktop/gnome/url-handlers/https 8 ./.gconf/desktop/gnome/url-handlers/http 44 ./.gconf/desktop/gnome/url-handlers 8 ./.gconf/desktop/gnome/background 120 ./.gconf/desktop/gnome 124 ./.gconf/desktop ---cut--exit Script done on Sun 21 Aug 2005 06:31:57 AM MDT This example demonstrates the process. The script will record the command and the output as well. To stop the script type exit.

shutdown
/sbin/shutdown -h now /sbin/shutdown -r now /sbin/shutdown -h +5 halt poweroff reboot shutdown now restart now 5 minute delay before shutdown shutdown now shutdown now restart now

System Administration Tools

200

sleep
This command will pause your system for a specified time. sleep Options numbers numberm numberh numberd Example: sleep 5h your system will pause for 5 hours seconds minutes hours days

strace
The strace command will trace system calls and signals. strace df Here we are using strace to follow the command df. mike@ub:~$ strace df execve("/bin/df", ["df"], [/* 30 vars */]) = 0 uname({sys="Linux", node="ub", ...}) = 0 brk(0) = 0x8051000 access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory) old_mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE| MAP_ANONYMOUS, -1, 0) = 0xb7fe9000 open("/etc/ld.so.preload", O_RDONLY) = -1 ENOENT (No such file or directory) open("/etc/ld.so.cache", O_RDONLY) =3 fstat64(3, {st_mode=S_IFREG|0644, st_size=37030, ...}) = 0 old_mmap(NULL, 37030, PROT_READ, MAP_PRIVATE, 3, 0) = 0xb7fdf000 close(3) =0 access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory) open("/lib/tls/i686/cmov/libc.so.6", O_RDONLY) = 3 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\215Y\1"..., 512) = 512

System Administration Tools

201

fstat64(3, {st_mode=S_IFREG|0644, st_size=1222116, ...}) = 0 old_mmap(NULL, 1232428, PROT_READ|PROT_EXEC, MAP_PRIVATE, 3, 0) = 0xb7eb2000 old_mmap(0xb7fd4000, 36864, PROT_READ|PROT_WRITE, MAP_PRIVATE| MAP_FIXED, 3, 0x121000) = 0xb7fd4000 old_mmap(0xb7fdd000, 7724, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED| MAP_ANONYMOUS, -1, 0) = 0xb7fdd000 close(3) =0 old_mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE| MAP_ANONYMOUS, -1, 0) = 0xb7eb1000 set_thread_area({entry_number:-1 -> 6, base_addr:0xb7eb1080, limit:1048575, seg_32bit: 1, contents:0, read_exec_only:0, limit_in_pages:1, seg_not_present:0, useable:1}) = 0 ---cut---

strings
This command is used to find printable text strings, usually within binary files. A string is by default 4 characters. Example: strings filename Options -a search the whole object -f this will print the name of the file in addition to the string -n num changes the default 4 letters in a string to whatever you want -o prints the decimal offset of the string strings-gnu This command is used to find printable text strings, usually within binary files. A string is by default 4 characters. Example: strings-gnu filename Options -a search the whole object -f this will print the name of the file in addition to the string

System Administration Tools

202

-n num changes the default 4 letters in a string to whatever you want -o prints the decimal offset of the string

stty
The stty command by itself will return the current settings of the terminal (baud rate,line discipline number, line settings) . Example: mike@ub:~$ stty speed 38400 baud; line = 0; eol = M-^?; eol2 = M-^?; ixany

superprobe
This command will check your system for the graphics server and chipset. This information then can be used in the xf68config that you can create. Note the Warning when you run the program!

tcsh
This command will start a C shell.

tload
This command will show system load in a graph form.

System Administration Tools

203

unshar
This command unpacks a shar file. unshar options filename Options -c overwrite existing file, same as force -f -d directory change to the directory listed

System Administration Tools

204

top
This command will list processes on the system, the processes using the most CPU resources. Stop top with ctrl+c.

uptime
This command will tell you how long your system has been operating. It will also list the current time, users and load average for 1,5 and 15 minutes.

whatis
The whatis command is useful in finding out info on a subject. Example: whatis gimp gimp (1) - an image manipulation and paint program

whoami A command to remind you who you are logged in as.

workbone
This command will allow you to play audio CDs. The program only displays the current track number and the time that has elapsed. The numeric keypad is used for control. Options 9 play 8 pause / resume 7 stop 6 play next track 5 replay previous track 4 go to previous track

System Administration Tools


3 forward 15 seconds 2 stop music and end program 1 go back 15 seconds 0 exit program

205

workman
Under the X window this command plays audio CDs. It will allow you to use programmable play lists, time elapsed/remaining, and create a database.

x11perf
This command will give you a set of tests on an X server and reports on the performance. This command provides a set of benchmarks to evaluate X server performance. In the example below all tests are performed. You can see the benchmarks are listed for each test. This will give you valuable information for comparing standards on your system. Notice that this command is available for Xfree86 and X.Org. x11perf -all mike@ub:~$ x11perf -all x11perf - X11 performance program, version 1.5 The X.Org Foundation server version 60802000 on :0.0 from ub Sat Aug 27 05:03:58 2005 Sync time adjustment is 0.0731 msecs. 40000000 reps @ 0.0002 msec (6480000.0/sec): Dot 40000000 reps @ 0.0002 msec (6230000.0/sec): Dot 40000000 reps @ 0.0002 msec (6200000.0/sec): Dot mike@ub:~$ x11perf -all x11perf - X11 performance program, version 1.5 The X.Org Foundation server version 60802000 on :0.0 from ub Sat Aug 27 05:07:10 2005 Sync time adjustment is 0.0751 msecs. 40000000 reps @ 0.0002 msec (5960000.0/sec): Dot 40000000 reps @ 0.0002 msec (4890000.0/sec): Dot

System Administration Tools


40000000 reps @ 40000000 reps @ 40000000 reps @ 200000000 trep @ 20000000 reps @ 20000000 reps @ 20000000 reps @ 20000000 reps @ 20000000 reps @ 100000000 trep @ 3000000 reps @ 3000000 reps @ 3000000 reps @ 3000000 reps @ 3000000 reps @ 15000000 trep @

206

0.0002 msec (6240000.0/sec): Dot 0.0002 msec (5690000.0/sec): Dot 0.0002 msec (6410000.0/sec): Dot 0.0002 msec (5790000.0/sec): Dot 0.0004 msec (2800000.0/sec): 1x1 rectangle 0.0004 msec (2330000.0/sec): 1x1 rectangle 0.0004 msec (2720000.0/sec): 1x1 rectangle 0.0003 msec (3160000.0/sec): 1x1 rectangle 0.0003 msec (3200000.0/sec): 1x1 rectangle 0.0004 msec (2810000.0/sec): 1x1 rectangle

0.0028 msec (358000.0/sec): 10x10 rectangle 0.0022 msec (451000.0/sec): 10x10 rectangle 0.0028 msec (355000.0/sec): 10x10 rectangle 0.0022 msec (447000.0/sec): 10x10 rectangle 0.0025 msec (400000.0/sec): 10x10 rectangle 0.0025 msec (398000.0/sec): 10x10 rectangle

72000 reps @ 0.1792 msec ( 5580.0/sec): 100x100 rectangle 72000 reps @ 0.1508 msec ( 6630.0/sec): 100x100 rectangle 72000 reps @ 0.1308 msec ( 7640.0/sec): 100x100 rectangle

Here is an example of what you may see as x11perf is running.

207

xauth
If you are using the X server, this command will display and edit the authorization information. If you use the list option you will be able to view the current magic cookie. The significance of the magic cookie is that it will be needed as a security measure to view your X Window remotely. There are two magic cookies that are viewed with this command. The first is the inet domain and the second is the unix domain. mike@ub:~$ xauth list ub/unix:0 MIT-MAGIC-COOKIE-1 951bd6024bb75bfb5ecfc413e3f613c2 localhost.localdomain/unix:0 MIT-MAGIC-COOKIE-1 951bd6024bb75bfb5ecfc413e3f613c2 Now if you copy the inet domain magic cookie and then log into a remote machine you need to: set env DISPLAY local.machine:0 Then insert the magic cookie with this command: xauth add <paste in the magic cookie> Now you should have remote access to the Xwindow. Seeing how easy this may be done gives you good reason to block ports 6000-6007 which are used by the Xwindow.

Xconfigurator is a stand alone program that you can run at any time to configure the XWindow. It is important to know how to run this program because it allows you to alter your video settings. Many times when you first load a distro by default it uses the highest resolution available, creating a screen that is difficult to read. Xconfigurator allows you to change that to the setting you choose.

Be warned that Xconfigurator may freeze your system. When you run it this warning will be listed. Then the next window that appears has a brief detailed description of the Xconfigurator program. Click "Ok" to start the program. You will then view several windows contain monitor, video, and clockchip options in step to setting your screen resolution. Finally, you are allowed to choose your video resolution.

208

xconsole
This command displays messages on a screen that usually go to /dev/console

xev
This command prints any events that occur on the box that it opens.

XF86Config
Located in /etc/X11/XF86Config this file holds the configuration for the XWindow, including settings for mouse, keyboard, monitor, graphics card, and screen sizes. With this command you can use information gained from the SuperProbe command to set up your X Window.

xload
xload is a historical graph of your system load. Simple, but helpful. This small graph can be left open to help you evaluate the load o your system while performing other tasks.

209

xclock
xclock gives you a simple clock which will provide the time.

oclock
This command creates a round clock that by default is pictured in your left upper screen. This clock has a number of simple changes that can be made by typing options. Example oclock -fg red -fg color -bg color -jewel color -minute color -hour color -bd color -bw color -transparent color of hands background color jewel color color of minute hand color of hour hand border color width of border makes the clock transparent

Clicking X will shut the clock down.

rclock
This command creates a clock that by default is pictured in your left upper screen. This clock has a number of simple changes that can be made by typing options. Example rclock -fg red -fg color -bg color -fn fontname -iconic color of foreground background color sets fonts starts iconified

210
-adjust ddhhmm days,hours, minutes adjustment -update n how often to update clock face, default 30 seconds -mail n how often new mail is checked Clicking X will shut the clock down.

which
which is a command that will provide the location of a program in the directory system. For example if you need to know where the who program was you could type : which who /usr/bin/who

xlock
In order to lock your screen, you may use xlock. It will require a password to open up again. It will turn off all connections, the screen saver, mouse, and screen go blank.

xcalc
This command provides a scientific calculator.

xclipboard
This command will allow you to see the files that are currently in the clipboard.

xeyes
xeyes creates a pair of eyes that follow the movement of the cursor.

xpaint
This command launches the xpaint program. xlogo

211

Displays a huge red x.

xmag
This command will display a portion of your screen magnified. First it lets you select the area to be magnified. The example shows magnified text from the console.

xrefresh
Repaints all or part of your screen.

212

xspread
xspread is a sophisticated spreadsheet program.

xterm
xterm will start a terminal.

zsh
Launches the Z shell.

startx
The startx command will launch an X Window session. This is an important command to know if you start your system at the terminal.

clear
Often the terminal window gets filled with stuff...using the clear command will remove everything but the prompt.

Command History
If you are using the terminal, using the command history is a must. The terminal keeps a

213
record of all of the commands you use during your sessions. The total history of the commands can be seen by typing: history The history command will listed up to 500 commands. You may only want to see a partial list so you could type: history 35 That will list the last 35 commands.

audiocompose
You can record audio and send it via email with this command. Example: audiocompose mymusic

biff
biff will notify you if you have received mail. Options n turn off y turn on

elm
This is an interactive mail system. You can even use elm to send a message via the command line. Options -a arrow cursor -f folder reads mail from a folder -i file include file in outgoing mail

214

fastmail
This command is designed to send batches of mail to a large group of people. Options -b bcc-list -c cc-list -f from -s subject

sends bind carbon copies to the list sends carbon copies to list sets the from sets the subject

fetchmail
This command will retrieve mail from a remote server and forward it to your local system. lynx lynx is a text based web browser. messages This command will let you know how many messages are in a folder. Example: messages There are 78 messages in your incoming mailbox. SETTING UP YOUR MODEM IN LINUX So naturally, you want to get your Linux machine online. This process is actually easier than it looks! At this point, I am hoping you have all the necessary information from your ISP about your DNS, dialup number you will use and what kind of modem you are using. 1. GET YOUR ISP INFORMATION

ISP INFORMATION EXAMPLE ACTUAL DNS NAMESERVER IP 12.32.34.32 DOMAIN Blackfoot.net

215
Account Name myaccount Password ********** Dial-Up Number 888-4701 COMPUTER INFORMATION Device /dev/ttyS0 COM Port COM1 2. OPEN A TERMINAL AS ROOT First, login to your machine using your root account. If you started Xwindows, open a terminal. Type the command statserial (give details on the serial port pins and which device), you will see at the top of the page device :/dev/ttyS0 3. SELECT COM PORT At a terminal type modemtool (connects modem to serial port) and you will see the four Com port options (see figure 1.1). Highlight the option that you found in step two, click OK. 4. OPEN NETWORK CONFIGURATION Choose the Gnome foot, select Programs / System / Network Configuration / Names. Once you have selected the Names Tab, enter your domain (supplied by your ISP) and you will see your computer name or Host name. 5. ADD A PPP INTERFACE Select Programs / Internet / Dialup Configuration and choose Add on the Accounts Tab. Now simply supply answers to questions asked by the program. 6. CONFIGURE YOUR MODEM Select the Modems Tab (see figure 1.4), highlight your modem and choose edit. Now configure the modem to the desired specifications 7. LOGIN TO YOUR ISP Select Programs / Internet / RH PPP Dialer and choose your current account to activate dialing. See Figure 1.6. That's it; you should be online!

216

pine
This command will allow you to open a full screen Internet News and Email program. Example: pine This will open an interactive program.

tcpdump
This is a useful debugging tool. Example: tcpdump host somesite.com and anothersite.com This will return output communication between the two domains. tcpdump port ftp This will show problems you may be having connecting to a ftp server. You may have to use port ftp-data for the data transfer as well. tcpdump port 80 This will allow you to see the http communications.

Vi editor

217

Vi editor
The vi editor is a character cell editor that can be used to modify system files or create a script. You can start vi by opening a terminal and typing vi. There are two modes for vi, command mode and insert mode. If you want to write text into the file you will need to click on i to enter text mode. Write your text and then to save click esc to enter command mode and then :w filename to save. When you want to exit type :q and enter.

Basic Commands
Commands :vi vi filename i :q :q! :x :w :w filename :w! esc Shift : Arrow keys h j k l Command Mode Enter the command mode with Esc. The basic things you want to do in command mode are: 1. View the document 2. Save the document - use Shift: w filename 3. Exit - use Shift: q Description Invoke the editor Open a file in vi Enter edit mode Quit Quit without saving Write the file if modified and quit Write the file Writes to a filename Write the file overriding protection Stop edit mode Command mode Movement move left one character move down one character move up one character move right one character

Vi editor

218

Example: Save your document as myfile. Shift: w myfile (then click Enter) Shift: q This will exit the program. Insert Mode Insert Mode is required to make any changes to the document that you are viewing or will create. vi /etc/hosts.allow This is a typical command to open and edit the /etc/hosts.allow file. # # ALL: 192.168.6.3 The listing above shows what a /etc/hosts.allow may look like. You want to enter into edit mode so click the letter i (notice it is lower case). Immediately at the bottom of the page you will see this - - INSERT- - This means that you can now edit the file. When you are done with your edit enter command mode by clicking Esc. Edit Mode allows you to edit the file much like a normal document. Basic Modes of vi Command Mode: default mode when vi opens In command mode every keystroke is associated with a command. Insert Mode: enter insert mode by clicking the letter "i" (lower case) In insert mode keystrokes are converted into text. Use the Esc key to exit insert mode and return to command mode. Save a file - :w Save a file to a location - :w /directory/your_choice Save and exit - :wq! quit - :q

Vi editor
h - left one space j - down one line k - up one line l - right one line

219

Numeric Movement
Numeric Movement by adding a number before each letter w - forward one word b - backward one word Numeric arguments may be used by adding a number to the letter vi can be used to open files in read only mode. This is valuable for opening configuration files that do not need changing but offer information that is needed. The example file can be opened in read only using this command: vi -R example Another way to open a read only file is to use the view command: view example Once the file is open it can be changed and written to by using the ! w! example Global Replacement Using Global Replacement in vi can be a very handy tool. The idea with replacement is to choose a word that you need to replace either in one line or through the whole document. Then issue a command that replaces each instance of the word. Suppose the document has been completed and then the word "Company" needs to be replaced with "MyCompany". Here is the command to replace one line: :s/Company/MyCompany/ The substitution is made on one line. Now the whole document: :%s/Company/MyCompany/g This will globally (g) substitute Company with MyCompany.

Vi editor

220

Retrieving Lost Files


There may be times when a project is in the works and the system loses power. The file that was open was actually in a buffer and may be able to be retrieved. Of course, don't count on it ...save often. Anyway, here is a method of retrieving the information that was in the buffer. Use one of these commands to check for any buffer files that were saved by the system: ex -r vi -r

The Bash Shell

221

The Bash Shell


What is a shell? A shell is a program that acts as an intermediary between the user and the Linux kernel. The shell receives commands from the user through typed words and passes them into the kernel for processing. The kernel has the ability to communicate with hardware and gather resources like files and memory. The most common shell is bash. History of Shells The first shell was created by Steven Bourne in 1979 and was a part of UNIX version 7. C shell was developed as an alternative by Bill Joy of the University of California at Berkley. This shell was part of the Berkley Software Foundation Distribution (BSD), which is still popular today. The C shell functions much like C programming so users who have a background in C tend to gravitate in this direction. The Korn shell is based on a combination of the Bourne and C shells. Each of these shells have advantages and are popular in use. The GNU project created a completely free shell called the Bash shell. It received the name from Bourne Again shell since it was based on the Bourne shell. The bash shell was written originally by Brian Fox in 1988. Bash has become the standard shell for Linux and is the default of most Linux distributions. You can access the shell from a terminal. Open a terminal and type: echo $SHELL This should show you which shell you are using, like so. /bin/bash The terminal is pictured below. This is Konsole from the KDE Desktop but many consoles are possible and they all run bash.

The Bash Shell

222

The procedure for interacting with bash is: command arguments Here is an example of listing the contents of a home directory: ls /home/mike The command is ls and that command acts upon the directory /home/mike. Here is another example: touch text In this example the command touch, which create an empty file, interacts with the system by creating the file text. In addition to commands and arguments there are also options that are available to commands. Here is an example of the ls command with the -a option which lists all files even the hidden ones.

The Bash Shell


ls -a /home/mike

223

Options usually require the before the option and the option is typically one letter. Users may use multiple options in the same command. Here is an example using ls and two options -a for all files and -l for long listing of the output. ls -la /home/mike You do not need to add a for each option, one for the entire list of options is OK.

Working Directory
The Working Directory is the location of the directory that you re currently in. For example if you log into the system, it is designed so that you will begin in your home directory. If your username was tom then your home directory by default would be /home/tom. When tom logs into the system it places him in the /home/tom directory, which is the current working directory. So if tom issues the command ls, then it will list the contents of /home/tom. If tom moves to the /usr directory by using the command cd /usr (which means change directories to /usr) then the current working directory is /usr Current working directory is the current directory that a command will interact with. Now, that does not mean that you have to be located in a directory to issue a command in the shell. Regardless of your current working directory you can use a command that interacts with any directory by using a path. For example, if you were located in the /home/tom directory you could list the contents of the /usr/share directory by using the path of that directory so the command would look like this: ls /usr/share One command that will verify your working directory is the command pwd, which stands for print working directory. Moving Around in Directories The cd command is the basic way to move around in the directory system. Cd followed by the directory location will move the user's current working directory. For example, cd /home This command moves a user to the /home directory where all user directories are located. If the user fred wanted to move to their /home directory they would use: cd /home/fred There is a shortcut to moving to your home directory. The ~ is equivalent to the home directory. As a result fred can move to his home directory with this command:

The Bash Shell


cd ~

224

This makes it easier than typing the full path.

Command-Line Scan
When you type a command at the shell prompt, you can continue until you type a carriage-return character. When the shell receives the carriage-return it parses the whole line left to right. Until you choose the carriage-return character the line can go on for a very long time. Once the shell receives the carriage-return it will parse the entire line. When the shell parses the line it looks for special characters that it must interpret. Open a terminal and look at the prompt, it should look something like this: mike@wk:~> It will list the user's name and the machine that they are on. It is ready to accept commands and pass them to the kernel.

Creating a Shell Script


Open vi and type these lines: ################### #!/bin/bash # this is a small script echo -e Hello My Good Friend Fred ################### Now save it as fred. Make the fred file executable by doing this command: chmod u+x fred or chmod 755 fred Now execute the file by typing the command: bash fred

The Bash Shell

225

You should see this output: Hello My Good Friend Fred Take a look at the script. The first line of the script is the complete path to the bash shell. #!/bin/bash This line tells the operating system that the file is to be executed by /bin/bash. The #! is a special directive for the bash shell and must be in the first line. # Any line that begins with # is a comment and is not interpreted. The command that was executed was: echo -e Hello My Good Friend Fred This illustrates how the shell interacts with the commands entered by the user and can be a powerful tool in getting things done.

Using Variables
Variables provide access to memory that can be used to assign values and then read or manipulate those values. Variables are created by using the variable followed by an equal sign. Here is an example: MESSAGE=Hello Fred, you are still my friend, even a good friend. The variable is written in caps followed by=(notice no spaces) and then it contains the value or contents written in quotes. When the variable is called it will display the contents. ################################### #!/bin/bash # MESSAGE=Hello Fred, you are still my friend, even a good friend. echo $MESSAGE ################################### Notice that the the echo command will produce the variable when it is preceded with a $ and in caps. You can even create a variable from input given by the user. In this script the user will input their name and address into the variable. ################################# #!/bin/bash #

The Bash Shell

226

echo please enter your full name. read NAME echo Now enter you address on one line. read ADDRESS echo Hi $NAME How are your today? echo We will ship your package to $ADDRESS ##################################

Here is another example of a more complicated script that clears problems with user account applications. #!/bin/bash ################################################################# # # Main() # VALID=0 # VALID = FALSE while [ ${VALID} = 0 ] ; do clear echo "PLEASE USE CAUTION!!!" echo "######################" echo " KILL PROCESS MENU 1) --- DANGER!! --> Kill User PID 2) --- List User PIDs 3) --- View All PIDs q) --- quit Please type in the choice: " read ACTION case ${ACTION} in 1) echo " Enter User Name for PID Kill" read NAME kill -9 `ps -u $NAME` | less ;;

The Bash Shell


2) echo " View User PIDs " read NAME ps -u $NAME | less ;;

227

3) echo " Press <Enter> to View All Processes" read NAME ps auxw | less ;; [q/Q]) echo "Be Careful !!!!!" VALID=1 exit ;; *) echo "Invalid option, press <Enter> and try again ! " echo "\c"; read zz ;; esac done exit This script allows you to set up a large number of users quickly. Create a document called users with the user name you want to use and the password for that user in two columns. #!/bin/bash ################################################################# # cat users | while read login code do useradd $login echo $code | passwd --stdin $login done

Wildcards
Wildcards in the bash shell provide a way to use one command on a number of files will similar characteristics. There are several kinds of wildcards listed here:

The Bash Shell


Wildcard ? * [set] [!set]

228

Matches any single character any string of characters any character in the set any character not in the set

When you use wildcards to locate matching expressions it is called globbing. Here are some examples. If you had a directory that had these files in it: truck, car, boat, canoe, sled, ski, bike here is how the wildcard would help. Expression * t* s* *e *k* Result truck, car, boat, canoe, sled, ski, bike truck sled, ski canoe, bike ski, bike

Set Construct wildcards use letters, numbers, symbols in brackets. Expression [abcd] [a-d] [a-z] [!0-9] [a-zA-Z] Result a,b,c, or d a,b,c, or d any lower case letter everything but digits all lower and upper case letters

Pipeline
A pipeline is where the standard output of one program is directed into the standard input of another program. For example the following command pipes the standard output of ls into the standard input of less so the results are more readable. ls /etc | less Notice the | or pipe symbol is used to create this connection. Any command line that contains two or more commands connected using a pipe is known as a pipeline.

Projects

229

Projects
Context For Projects

BigStrike Gold Mining Co. http://bigstrike.org

This company is designed to provide context for Linux understanding on how to use Linux commands effectively. Projects are used to create context and clarify understanding. Each project will illustrate important skills or provide insights into the use of commands. The projects are created in group contexts so that you can work on skills for a particular aspect of commands. The numbers coincide with the chapters in the book. BigStrike Gold Company is not a real company and any resemblance to any existing company is purely an accident.

BigStrike Gold Company is a small company with a big future. BigStrike is built around a new technology that allows miners to extract valuable minerals using laser technology without disturbing the surface of the ground. This extraction technique is not only environmentally acceptable but extremely profitable because of the lack of environmental damage. BigStrike has established headquarters in a remote location in Montana and is preparing to begin the first significant test of extracting gold from a secret location as a demonstration of

Projects

230

the value of this technology. There are currently five employees of BigStrike. Each employee has specific assignments and will be in charge of divisions of the company when it lands the first real exploratory mining project. Here are the employees and their divisions: Mary Johnson Finance Jim George - IT Technology Dan Ott Research and Development Slim Peters Mining Debbie French Promotion/Advertising The owner and major financial developer is John Smith. John has designated Jim to put in place the necessary computers and operating systems they need to make this company successful. Jim did extensive research on the available technology and operating systems and has chosen to place Linux desktops on all the company computers. The choice for Linux was based on several important factors that the company needed. First, the company needed an operating system that allowed the company to make modifications the the actual code of the operating system to meet the special needs of the company. Jim was able to access the source code of their Linux distribution because it was open source. Second, the company desktops had to be stable. The company required desktops that would not crash as developers were building technology that was extremely time consuming and expensive. Next, the company demanded security. The company must have access to Internet resources for research and communication but because of the extreme value of the company technology, security was a high priority. Jim found that Linux provided extensive firewall options, quick patches to security issues and a diminished virus problem. Fourth, the company was going to grow rapidly and so the operating system must be flexible and allow for rapid expansion. Linux was extremely flexible in that computers were multiuser and could function as a server/workstation at the same time. In addition, there was no problem in expanding the network or individual computers to deal with growth. Finally, Jim determined that the desktop for the company must have a graphical interface as the intuitive nature of a graphical interface was important for employee productivity. Jim as IT manager needs to be efficient at the command line because the command line is a faster way of getting things done as well as a standard for accomplishing the same tasks on any Linux operating system. These two factors helped Jim become a better manager of his time and resources.

Setup for Projects


####################################################### Before you start working on projects it is important to understand these projects often need to be performed as root and therefore should only be performed on a test machine in case

Projects

231

you make mistakes!!!! ################################################################### In preparation for the projects listed in the book it will save you time if you create the structure for the company BigStrike.org before you move on. That way you can move right into each project without having to create the users, folders and files needed in the projects.

Create These Users Mary Johnson johnsonm Jim George - georgej Dan Ott ottd Slim Peters peterss Debbie French frenchd As root create these users using the useradd command. Notice the user name follows the real name and is lower case with the format last name/first initial. Example: useradd johnsonm Create the following groups: finance tech rad mining promo The groups are important as later each group will have a number of users included in it. The groups are again lower case and short, for an easy to type group name. Use the groupadd command to create each group. Example: groupadd finance Create these directories in the home directory. finance tech rad mining promo

Projects

232

The /home directory should look like this: /home /finance /tech /rad /mining /promo /johnsonm /georgej /ottd /peterss /frenchd

This shows the group folders which will be shared by the members of each group and individual private directories for users. The next thing is to change permissions on each group directory. In the example the owner is changed to the head of each division i the company so they have complete control of the content and usage of the directory. The group is then added so all members of the group may access the contents of the directory. This is just one way to share directories for users so they can collaborate on projects. Example: chown johnsonm:finance /home/finance Do this with each division head for the company. Mary Johnson Finance Jim George - IT Technology Dan Ott Research and Development Slim Peters Mining Debbie French Promotion/Advertising

Managing Files and Text

233

Managing Files and Text


Project: Moving Policy Files
One of the challenges in system administration that is common is the necessity of moving files from one user to another and changing the permissions so the second user can modify the files. In this project Jim, the IT guy, needs to move three policy files from the /home/promo directory to the /home/peterss directory as Slim Peters will now be in charge of these three policy files: NetworkPolicy.pdf SecurityPoilicy.pdf LaptopPolicy.pdf Commands that will be used in this project: cp, touch, chmod, mkdir, useradd, ls, cd Project must be done as root (practice on a test machine). Step 1: Create the Policy Files touch /home/promo/NetworkPolicy.pdf touch /home/promo/SecurityPolicy.pdf touch /home/promo/LaptopPolicy.pdf Touch creates empty files but that is all that is needed for the exercise. Verify they exist and the file attributes with this command: ls -la /home/promo Step 2: Move Files to /home/perterss mv /home/promo/*.pdf /home/peterss Notice the wildcard * which will move all .pdf files Step 3: Change File Permissions of the 3 PDF Files chown perterss:peterss /home/peterss/*.pdf This will change ownership to the user perterss and the group peterss. The colon in the command separates the user and group. Make the files writable for the user with this command. chmod 755 /home/peterss/*.pdf

Project: Reviewing Log Files for Security Issues


Jim George the IT guy has discovered that there have been numerous attempts to login as root from remote sources. The company's concern is that these attempts could lead to a

Managing Files and Text

234

compromise of the system. Jim has asked you to find a command you can use to scan system logs whenever necessary to check for these attempts to login. These must be done on a daily basis so that security measures may be taken to prevent these attacks. Commands that will be used in this project: cat, egrep, cron Project must be done as root (practice on a test machine). The first thing to review is that the system logs are located in the /var/log directory. The system logs most activity in the /var/log/messages file. Most Linux operating systems will also use the /var/log/secure or /var/log/auth.log file for specific security issues. You must be aware of each and check both for any indication of attack. Both of these files are automatically rotated after a period of time. For example the /var/log/messages file is rotated to the /var/log/messages.1 file automatically. Then it is rotated to the /var/log/messages.2, etc. until it is erased from the system. Some operating systems ,like Ubuntu, will rotate these logs to messages.0 and then begin to compress them as well so messages.0 would be rotated to messages.1.gz, etc. You will just need to take a look in /var/log/ to verify the specific settings from your operating system. The next thing you need to decide is which Linux command to use when you are checking logs. As you have reviewed grep, egrep and sed you decide to use egrep as a tool to check logs. So your goal is to design a command that can be used to review logs daily and send Jim a report via mail so that it is totally automated and makes your life more secure and also easier. You discover that the authentications for your operating system are recorded in the /var/log/auth.log file. This is the file that you will then need to review with your egrep command. You decide to use cat and then pipe the output of the cat command into egrep to find a match. Something like this: cat auth.log | egrep failure Here is an actual example that discovers that indeed there are individuals trying to log in as root. mike@ub:/var/log$ cat auth.log | egrep failure Oct 20 07:02:44 localhost su[10004]: (pam_unix) authentication failure; logname=mike uid=1000 euid=0 tty=pts/0 ruser=mike rhost= user=root Oct 20 07:02:45 localhost su[10004]: pam_authenticate: Authentication failure Now you can get the information Jim wants as it provides a date and time of the attempt. The next thing that you need to do is automate this process so that Jim knows it is done

Managing Files and Text

235

each day. For this you decide to use the cron tool. Each user on the system can create cron jobs which will automate tasks that you need to perform on a regular basis. However, to evaluate the /var/log/auth.log file you need root access, which Jim has given you. In order to pen the cron file for root you must use this command as root: contab -e This gives you the ability to edit the cron file for root. You will edit this file using the vi program. There are seven fields that must be used. field 1 - minute 0-59, a - between numbers means a range 1-30 a comma between numbers means individual 1,5,8 2 hour 0-23 3 day of month 0-31 4 month 0-12 5 day of week 0-7 (both and 7 are Sunday) 6 user 7 command Example: 7 0 * * 1 /home/mike/bk.sh This will run the backup script in /home/mike at 12:07 Mondays. The asterisk in a field indicates that all possible values are run for that field. When crontab -e is run the vi editor opens and the users are allowed to edit the file. It is imperative that the user be familiar with vi so that the file can be edited and saved. Example: crontab -e (this opens crontab file) click i (edit mode in vi) 10 * * * * /home/mike/bk (runs backup script at 10 after the hour) esc (exits edit mode in vi, now in command mode) shift: w! (writes the file that you have created) shift: q (quits vi editor) Here is the information that you enter into the cron file for the root user:

Managing Files and Text


04 6 * * * cat /var/log/auth.log | egrep failure

236

This will run the command every morning at 6:04 AM just before Jim gets to the office so he will have the latest information. The next thing you need to input is a command that will send this information to Jim via email so you do not have to do anything. Add this to the script: 04 6 * * * cat /var/log/auth.log | egrep failure | mail -s Security jim@bigstrike.org This will send him the output each morning. The -s sets a heading Security for the email that arrives in Jim's mailbox so he knows exactly what to look for if he wants to filter it into a special mail folder.

Project: Find all Files with a Specific Pattern Debbie French in Advertising wants to convert all OpenOffice documents that were in the OpenOffice 1 format with the .sxw extension into .pdf files. The reason for this is that it will provide a unified format for the business documents so that the company may easily share documents with clients online or in printed form. Commands that will be used in this project: locate (practice on a test machine). Debbie has asked you to provide a list of all .sxw files that are on the server. You will need to use the locate command to find these files and then you will need to export this list into a file format that you can send to Debbie. An easy way to make this happen is to send the output of the command into a file so that it is all done in one command. locate .sxw > FilesToConvert.rtf Often the .rtf format extension is used since it is universally recognized by OpenOffice, vi or Word. Here is an example of the file created. /home/mike/Desktop/book/Commands/commands.sxw /home/mike/Desktop/book/Commands/rpm.sxw /home/mike/Desktop/book/Commands/rpm1.sxw /home/mike/Desktop/book/Commands/rpmd.sxw /home/mike/Desktop/book/Dia/dia.sxw /home/mike/Desktop/book/Dia/title.sxw

Managing Files and Text

237

/home/mike/Desktop/book/dsl/DSL.sxw /home/mike/Desktop/book/dsl/Dsl.sxw /home/mike/Desktop/book/dsl/dsl.sxw /home/mike/Desktop/book/dsl/dsl_bk.sxw /home/mike/Desktop/book/Fedora_1/Fadmin_contents.sxw /home/mike/Desktop/book/Fedora_1/Fadmin_contents1.sxw /home/mike/Desktop/book/Fedora_1/Fadmin_title.sxw /home/mike/Desktop/book/Fedora_1/FedoraAdmin.sxw /home/mike/Desktop/book/Fedora_1/pics/menus.sxw /home/mike/Desktop/book/Flash/Creating Animation.sxw ---cut--When sending the output to a file notice that one > is used. If you wanted to append that file you would use two arrows >> like this: locate .odt >> FilesToConvert.rtf me/mike/Desktop/book/Open/Open_2.odt /home/mike/Desktop/Outline.odt /home/mike/Desktop/BlockCountries.odt /home/mike/.Trash/CCNABook-1.odt /home/mike/.Trash/CCNABook.odt ---cut--Here you see the appended info to the bottom of the list.

Managing Users and Groups

238

Managing Users and Groups


Project: Delete User and Manage Files
In every organization, people leave to move on to new locations. When they leave their accounts need to be managed as well as the files that they have created need to be moved to the user who will take their place. Commands that will be used in this project: rm, touch, chmod, useradd, ls, userdel Project must be done as root (practice on a test machine). Step 1: Add New Users There are several things to keep in mind when adding a new user. Possibly the most important is whether the Linux operating system you are using automatically creates private groups for each user or not. Red Hat for example creates a user and group with the same name when the user is created. This means that no other user on the system, except root, may view the contents of another user. This is called a private group. SuSE on the other hand will create a user and then place all users in the user,s group. This is a significant difference because all users by default may view the contents of all other users' home directories by default. As an administrator do not make the mistake of thinking files are confidential when all users actually can view them! Create a User for Practice in Deleting useradd tom This will create a /home/tom directory. This directory will be set up automatically for rights so that tom may use the directory and programs. Now create file in the directory as root so that this file will represent the files that you will move to another user's directory. touch personal1.rtf personal2.rtf doc1.pdf doc2.pdf /home/tom This command creates multiple files at the same time. These are empty files but will serve as an example in the project. Change the rights so that tom owns all files. Both the user and group will be changed to tom so that it will illustrate the private group setting. chown tom:tom /home/tom/*.rtf chown tom:tom /home/tom/*.pdf Now all files are owned by tom that are in the /home/tom directory. The next step is to create the user who will replace tom. useradd mary Now at the least you should have a /home directory with mary and tom. When a user leaves, their account should be deleted for security reasons, their personal files should be deleted but company files need to be transferred to the user who replaces them.

Managing Users and Groups

239

Step 2: Transfer Files to the New User These files will be treated as if they are company files that need to have rights transferred to the next user. cp /home/tom/*.pdf /home/mary Notice the cp command is used instead of the move command, mv. If these are important company files you may want to verify that the files are actually in place before they are deleted. If you made a terrible mistake in the mv command the files could be destroyed, though the mv command is usually a safe command. chown mary:mary /home/mary/*.pdf This command now changes the rights to the correct user. You can verify the rights by using this command: ls -la /home/mary/*.pdf Step 3: Delete the Old User and Files Often when you use the userdel command the user is deleted and you will be asked if you want to delete the user's home directory as well. If you say yes you are then finished. userdel tom

Managing Network Connections

240

Managing Network Connections


Setup Network on a Computer
Jim has asked you to set up an office computer so that it will connect to the network. This computer does not have the Graphical Interface so you must set it all up using the command line. Commands that will be used in this project: ifconfig,route,ping, Project must be done as root (practice on a test machine).

Step One Network Design The computer has one network card and you will need to use a static IP Address on the computer. You will need to enter a gateway and the DNS that you will be using. You will also need to completely test this machine to verify that it is working perfectly. Here are the settings you need to modify: IP Address: 192.168.3.5 Gateway: 192.168.3.1 DNS: 100.53.26.111 Here is a basic design for the network. The Firewall/Gateway is 192.168.3.1 and the computer you are setting up on the network is 192.168.3.5. You have a hub between your computer and the Firewall/Gateway.

241
Step Two Setup Network Card IP ifconfig is used to configure the network interfaces and parameters. This is the most important tool for setting up your network. This tool must be used as root. The basic syntax is ifconfig interface parameters Here is the command to set up your network card which will be eth0 as it is the first card detected. ifconfig eth0 192.168.3.5 netmask 255.255.255.0 Check the configuration by using the ifconfig command which should have the following output if your setup was correct. ifconfig eth0 Link encap:Ethernet HWaddr 00:03:0C:11:F6:A4 inet addr:192.168.3.5 Bcast:192.168.5.255 Mask:255.255.255.0 inet6 addr: fe80::203:dff:fe11:f6a9/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:16535 errors:0 dropped:0 overruns:0 frame:0 TX packets:17674 errors:0 dropped:0 overruns:0 carrier:0 collisions:1782 txqueuelen:1000 RX bytes:14901259 (14.2 Mb) TX bytes:2966504 (2.8 Mb) Interrupt:217 Base address:0xe800 Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:199 errors:0 dropped:0 overruns:0 frame:0 TX packets:199 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:122418 (119.5 Kb) TX bytes:122418 (119.5 Kb)

lo

If that is all correct then activate the network card. It seems strange that the card will not be immediately available but in the network interfaces must be restarted for them to recognize the new settings. Activating the eth0 interface with this command:

242
ifconfig eth0 up ifconfig eth0 down This will shut down the eth0 interface. The interface needs to be chosen so that the correct interface is taken up or down.

Step Three Configure the route The importance of the route is that your machine needs to understand where to go in order to access the Internet or at least access another network. Gateways connect to networks that are on different networking schemes. For example the network that the computer is on is 192.168.3.0 with a netmask of 255.255.255.0 which makes 253 IP Addresses on that network. Well, there are millions of networks that are tied to the Internet. The only way to talk to those networks outside of yours is to go through a Gateway which has the capacity to connect two networks. The route command is used to tell your computer about the Gateway. route Syntax is simply route followed by options. route add options target The route add command will add routes, gateways, etc. to the routing table. route del options target The route del command will remove routes, gateways, etc from the routing table. route Options

243
-net -host -C netmask gw default target is a network target is a single host display kernel routing cache specify the mask to add gateway this is the location of the default gateway

route add default gw Example: route add default gw 192.168.3.1 eth0 There is only one default gateway. This is typically the route that a computer must take to access the Internet. It is possible to add an additional gateway but it would not be the default. Verify your route configuration. The route command by itself will help you view the current network configurations and Gateway. route Kernel IP routing table Destination Gateway 192.168.3.0 * link-local * loopback * default 192.168.3.1 Genmask 255.255.255.0 255.255.0.0 255.0.0.0 0.0.0.0 Flags U U U UG Metric 0 0 0 0 Ref Use Iface 0 0 eth0 0 0 eth0 0 0 lo 0 0 eth0

This shows output of route with no options. Notice the default gateway is 192.168.3.1 and there is only one network card, eth0. The U flag indicates that connection is up and the G flag is for gateway. The Metric is the number of hops to that target. Step Four Setup DNS To set up your DNS you will need to modify the file /etc/resolv.conf as root. If this is a new machine this file may be empty. So you will use vi to create it. vi /etc/resolv.conf

244
The vi editor is a character cell editor that can be used to modify system files or create a script. You can start vi by opening a terminal and typing vi. There are two modes for vi, command mode and insert mode. If you want to write text into the file you will need to click on i to enter text mode. Write your text and then to save click esc to enter command mode and then :w filename to save. When you want to exit type :q and enter. Basic Commands of vi Commands :vi vi filename i :q :q! :x :w :w filename :w! esc Shift : Arrow keys h j k l Command Mode Enter the command mode with Esc. The basic things you want to do in command mode are: 1. View the document 2. Save the document - use Shift: w filename 3. Exit - use Shift: q Description Invoke the editor Open a file in vi Enter edit mode Quit Quit without saving Write the file if modified and quit Write the file Writes to a filename Write the file overriding protection Stop edit mode Command mode Movement move left one character move down one character move up one character move right one character

Example: Save your document as /etc/resolv.conf Shift: w /etc/resolv.conf (then click Enter)

245
Shift: q This will exit the program. Insert Mode Insert Mode is required to make any changes to the document that you are viewing or will create. vi /etc/resolv.conf You will need to place this text in your /etc/resolv.conf file: nameserver 100.53.26.111 You want to enter into edit mode so click the letter i (notice it is small case). Immediately at the bottom of the page you will see this - - INSERT- - This means that you can now edit the file. When you are done with your edit enter command mode by clicking Esc. Now save your /etc/resolv.conf with :w! Save a file - :w Save a file to a location - :w /directory/your_choice Save and exit - :wq! quit - :q Step Five Make Network Changes Permanent In order for your network changes to be permanent you will need to save them in /etc/sysconfig/network-scripts/ifcfg-eth0 Open this file with vi. vi /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE=eth0 BOOTPROTO=static IPADDR=192.168.3.5 NETMASK=255.255.255.0 NETWORK=192.168.3.0

246
BROADCAST=192.168.3.255 ONBOOT=yes Save this file if it is not already configured. This will provide for the setup of your eth0 network interface with a static IP Address of 192.168.3.5 on the network 192.168.3.0. It will also have it setup on boot of the machine.

Step 6 Test Your Setup use ping to verify your connections. First make sure that all of your cabling is correct and connected. Testing Network Connections. Purpose of ping This program will help determine if a computer is online by sending a ICMP ECHO_REQUEST. The expected response is in the form of ICMP ECHO_RESPONSE. In other words, there should be a return response from the machine that was contacted.

Syntax ping [options] destination Test by pinging the Gateway. ping -c 192.168.3.1 The -c option provides the ability to set how many pings should occur before the command stops. In this example the destination will be pinged 100 times as the count follows the option.

247

Stopping the ping Command Turn off the pings using ctrl+c

ping Options

Options -c count -s size -I Interface -i interval -f flood

number of packets to send determines the size of the packets to be sent which network card to use time interval continuous stream of packets

ping is often used to establish that a network connection is actually up. Ping 192.168.3.1 PING 192.168.3.1 (192.168.3.5) 56(84) bytes of data. --- 192.168.3.5 ping statistics --18 packets transmitted, 0 received, 100% packet loss, time 16996ms

248
This would suggest that the node or computer on the network does not have a functioning network connection, possibly because of a network configuration issue or the computer is off. Again, another look at this output and you would think the computer is down when in fact the computer is blocking pings from the network. Notice the output is exactly the same as the output if the computer were off. This makes this test a questionable evaluation unless you know for sure the computer is not blocking pings from the network. Keep this in mind when making decisions about your network. Ping 192.168.3.1 PING 192.168.3.1 (192.168.3.5) 56(84) bytes of data. --- 192.168.3.1 ping statistics --18 packets transmitted, 100% received, 0 packet loss, time .01ms This indicates then that you have a network connection which is working. Be careful if your Gateway blocks pings because if it does it will look like it is not functioning. At that point you will probably just have to see if a browser can connect to the Internet.

Project: SSH Transfer Policy Files and Directories to New Server


Bigstrike Gold Mining Company is a fast moving company and is now expanding by adding a new server to the company. Jim George the IT guy has built a new server Pluto in a new location in New York in order to handle more of the financial issues because of the company's rapid growth. Jim has asked you (Mary Johnson) to securely move the company Policy files and directories to the new server in New York. His emphasis is security as Bigstrike has created a few powerful enemies. Commands that will be used in this project: ls,cat.scp Project must be done as root (practice on a test machine).

Here is the information that Jim has given you for the process:

249
Pluto IP Address 192.168.3.34 Place Policies in the /Financial partition. Jim has created ssh keys and has given you a USB disk with the SSH key from the Pluto server to place on the server that currently hosts the Policies folders. You will move the necessary files and folders onto the server with the officedir user name because you need the rights to modify the /Financial partition. Jim gives you the officedir password as: OF34_NY52*567

The server that hosts the Policy files and folders is Mars at an IP Address of 192.168.1.2 and the necessary files and folders are located in the Office partition. /Office /Policies /StaffPolicies /CompanyPolicies /Security

You have given the SSH key to Jim for the Mars server which he has placed on the Pluto server. Here are your tasks you will need to perform in order. 1. Log in to the mars Server 2. Add the SSH key to your account Mary Johnson (user name johnsonm) 3. Transfer file and folders with permissions set to the new server Pluto in the /Finance partition

When you created your SSH key you had this output: Your identification has been saved in /home/mike/.ssh/id_dsa. Your public key has been saved in /home/mike/.ssh/id_dsa.pub. The key fingerprint is: 05:9f:44:8a:78:2f:08:b2:37:ef:34:97:8a:25:ee:4d johnsonm@mars First login to the server you will transfer the files from and view your account for SSH. Remember that each user must configure the SSH settings for themselves as they are for

250
individuals, not server wide. View your SSH directory which is hidden with this command: ls .ssh johnsonm@mars:~$ ls .ssh id_dsa id_dsa.pub known_hosts authorized_hosts Notice that the hidden directory has a . in front of ssh. Now when you view the contents of this file you see three files: id_dsa id_dsa.pub known_hosts authorized_keys id_dsa is the private key that was generated from when you, johnsonm created a SSH key. The command is: ssh-keygen -t dsa When you create the Key Pairs using dsa both the private and public keys will have the das signature. OK, so id_dsa is your private key that you never give to anyone...never. This stays in your SSH folder and will help authenticate users who attempt to attach to your account with SSH. The id_dsa.pub is your public key which Jim took and placed on the server Pluto so that when you connect to the Pluto server account officedir it can be authenticated. NOTE, your public SSH key (id_dsa.pub) was given to Jim to place in the officedir hidden .ssh directory so you could connect to that specific account. Complicated, but very secure. Again, then your public key must be placed in the account that you will connect with using SSH. Now you need to copy the public key from the Pluto server into your SSH directory in a specific file. Jim has renamed the Pluto public key file as pluto_pub. It is important to rename these files because you will often have a number of them and you can easily overwrite keys when they have the same name. Now use this command to copy the file into your .ssh directory: cat pluto_pub >> ~/.ssh/authorized_keys The authorized_keys then will authorize connections only from those public keys listed in this file. Now transfer the Policy Files and Folders with permissions set to the new Pluto server in

251
the /Finance partition. scp -rp /Office/Policies officedir@192.168.3.34:/Finance You will see the Polices folder and sub-folders move onto the Pluto server.

Managing Drives and Formats

252

Managing Drives and Formats

Project: Mounting and Unmounting USB Drives


Due to security concerns for the company Research and Development, Dan Ott has requested that all users remove certain data from their local computers every night onto a USB drive. The servers are secure but this concern is the local workstations. So it is important to know how to mount and unmount USB drives quickly and effectively, without mistakes so data i s not lost. Commands that will be used in this project: mount.umount Project must be done as root (practice on a test machine). In mounting drives it is imperative you know something about the file system that you are using. Most Linux files systems will mount USB drives, in a specific location in the file system. This is either in the /mnt directory or in the /media directory. Also when the USB drive is mounted it is either /sda1 or possible /usbdisk. Each distribution is a little different so you will need to pay attention to those differences. Another thing to remember when mounting USB drives is that they are usually mounted as SCSI drives instead of IDE. The significance of this is that instead of having a /hda designation it is a /sda designation. The /hda is reserved for IDE drives and the /sda for SCSI drives. Ubuntu will mount the USB drive as /media/usbdisk. You will also notice that most Linux distributions now mount drives automatically which is very convenient. However, you will still need the skills to mount drives for some situations. In order to mount a drive, open a terminal after the USB drive is attached to issue this command: mount /media/usbdisk Once the drive is available you will be able to browse the drive and save information to the drive. To unmount the drive you will use the reverse command and issue this command: umount /media/usbdisk

Managing Drives and Formats

253

Managing Backups

Project: Back-Up Your Home Directory Research and Development is possibly the most important aspect of Bigstrike Mining Company. Jim has asked you, Dan Ott (ottd) to make sure that your home directory is backed up each night, every night, always. Jim wants an automated back-up with a date on each back-up. The back-up should be sent to the /bk partition which is on a separate drive from your home directory. This is done so that if you lose a drive, the other will still have all of the necessary information. Commands that will be used in this project: tar, Project must be done as root (practice on a test machine). Jim has set the standard for date formats as: month day year all using two digits each. For example September 10, 2005 would be: 091005 The first thing you want to do is try a back-up with a date so that you know your command works before you try to automate the back-ups. Here is a command to back-up using tar: tar cvf /bk/ottd_101505.tar /home/ottd This command creates an archive, with verbose messages so you can see what happens and place it in the file you have designated with a date. Be sure that you have a date format that everyone agrees on. Now that you see that works fine you need a back-up each night after you are done with work. You will need to use the cron tool. Remember that each user on the system can set up their own cron jobs so Jim expects that you know how to use this tool effectively. You decide that you leave work about 6 PM each night so you would like to do your back-up at 7:15 PM each night, 7 days a week.

Anda mungkin juga menyukai