automating system administration tasks n.
Skip this Video
Loading SlideShow in 5 Seconds..
Automating System Administration Tasks PowerPoint Presentation
Download Presentation
Automating System Administration Tasks

Loading in 2 Seconds...

play fullscreen
1 / 90

Automating System Administration Tasks - PowerPoint PPT Presentation

  • Uploaded on

Automating System Administration Tasks. Chapter 23. Understand what tasks lend themselves to automation. Understand the tools available to automate system administration tasks. Understand differences between shells, and shell programming languages. Chapter Goals.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

Automating System Administration Tasks

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
chapter goals
Understand what tasks lend themselves to automation.
  • Understand the tools available to automate system administration tasks.
  • Understand differences between shells, and shell programming languages.
Chapter Goals
what to automate
As we have seen, there are several repetitive tasks in system administration:
    • Downloading and installing patches
    • Installing accounts
    • Managing configuration files
    • Managing printers
    • Scanning log files
    • Monitoring security
    • Cleaning out temporary files.
  • These tasks lend themselves to automation using a variety of tools.
What to automate?
what to automate1
    • RedHat up2date
    • Notre Dame’s “nd.installpatch”
  • Installing accounts
    • Acmaint
    • grep user_name /afs/ >>/etc/passwd ; pwconv
  • Managing Configuration Files
    • rdist
    • expect
    • rsync
    • package
What to automate?
what to automate2
Managing printers
    • Write a script to add printers for you
  • Scanning log files and monitoring security
    • Swatch
    • Logwatch
    • Write a script to watch for things of interest to you.
  • Cleaning out temporary files
    • cron
    • find
What to automate?
information distribution
Distributing system information (files) is a problem.
    • Small site --> small problem.
    • Large site --> LARGE problem.
      • Consider: Site with 4 system architectures:
        • Sun (250 hosts)
        • HP (250 hosts)
        • IBM (250 hosts)
        • PC’s with Linux (250 hosts)
      • How would you distribute a new version of sendmail to each host?
Information Distribution
information distribution1
The first problem to tackle is “what should we distribute”?
    • Try to determine which files may be distributed to multiple system architectures (usually text files).
    • Try to determine what binaries are located on the system disks (not on network file systems).
    • Try to determine which files are scripts that would work on multiple architectures.
    • Try to determine which files are common to all hosts of a particular architecture.
Information Distribution
information distribution2
Some typical examples:
    • System Binaries
      • sendmail
      • login – common to a single OS/architecture
      • ftpd
      • tcpd
    • Common configuration files
      • /etc/motd
      • password file
      • shadow file – may not be directly usable
Information Distribution
information distribution3
The next problem to tackle is which hosts you want to distribute files to:
    • All hosts of an architecture? (Sparc, HP)
    • All hosts which are clients of a particular server?
    • All hosts which are null clients of a particular mail server?
    • All hosts in engineering?
  • The more files/architectures you have to distribute information to, the more complex the setup will be for the distribution method (and the more likely you will mess something up).
Information Distribution
information distribution4
There are two methods of distributing system information:
    • The push method - a server pushes the information to the clients.
      • Advantages:
        • It is usually easy to run “unscheduled” push operations.
        • You have some control over when the process runs.
      • Disadvantages:
        • More difficult to update a single client.
        • Tainted files will be distributed just like good files.
      • Setup:
        • Need to build/maintain copies of files to distribute.
        • Need to build/maintain the distribution control file.
Information Distribution
information distribution5
There are two methods of distributing system information:
    • The pull method - a client pulls the information from a server.
      • Advantages:
        • It is easy to run “unscheduled” updates.
        • Systems can be reset to a known state upon reboot.
      • Disadvantages:
        • More difficult to update clients all at once.
        • Administrator has no idea which hosts have updated.
      • Setup:
        • Need to build/maintain copies of files to distribute.
        • Need to build/maintain the distribution control file.
Information Distribution
information distribution6
The push method
    • The rdist program is one example of a “push method” file distribution system.
      • Need to build a distfile
        • tells what systems to distribute the files to
        • tells which files to distribute to the systems
        • allows special operations to be performed
        • allows notification of success/failures
        • allows exceptions to the rules
        • may be run from a cron entry
        • Has a handy “no action” version that allows rules testing.
Information Distribution
information distribution7
    • Need to create a repository of files to distribute.
      • Good idea to use RCS/SCCS/CVS to keep track of versions, and changes.
      • Good idea to keep the repository “read only” so that bad versions of files do not get distributed.
      • Special caveat:
        • Rdist distributes the files with the ownership of the user who ran the rdist command.
        • This can be a major problem if not handled by the settings in the distfile!
Information Distribution
sample rdist file

# distribute something to lab hosts



SOL_CLIENTS=( snowwhite boole branin eckert noyce turing )


# Files to distribute



$BASE/courses/cse444/lab6.init -> ${SOL_CLIENTS}

install /etc/init.d/lab6;

special "chmod 755 /etc/init.d/lab6";

Sample rdist file
rdist example

# distribute Solaris sendmail to grumpy, mail.cse), mail clients

# distribute HPUX sendmail to geo

# distribute AIX4 sendmail to yoyo and euclid



SOL_CLIENTS=( aliens.dcrl atanasoff athena backus bashful berry boole branin)

STANDALONE=( grumpy )

AIX_CLIENTS=(euclid yoyo)



SERVER=( wizard )


Rdist Example
rdist example1

# Files to distribute


$BASE/common/etc/mail/ -> ${SOL_CLIENTS}

special "cp /etc/mail/ /etc/mail/";

install /etc/mail/;

special "cp /etc/mail/ /etc/mail/";

special "ln -s /etc/mail/ /etc/";

special "rm /etc/mail/";

$BASE/server/etc/mail/ -> ${SERVER}

special "cp /etc/mail/ /etc/mail/";

install /etc/mail/;

special "cp /etc/mail/ /etc/mail/";

special "ln -s /etc/mail/ /etc/";

special "rm /etc/mail/";

Rdist example
rdist example2

$BASE/grumpy/etc/mail/ -> ${STANDALONE}

special "cp /etc/mail/ /etc/mail/";

install /etc/mail/;

special "cp /etc/mail/ /etc/mail/";

special "ln -s /etc/mail/ /etc/";

special "rm /etc/mail/";


$BASE/common/usr/lib/sendmail -> ${SUNS}

special "cp /usr/lib/sendmail /usr/lib/sendmail.old";

install /usr/lib/;

special "chgrp sys /usr/lib/sendmail";

special "chmod 6755 /usr/lib/sendmail";

special "/usr/local/bin/killj sendmail";

special "cp /usr/lib/ /usr/lib/sendmail";

special "/usr/lib/sendmail -bd -q1h";

special "rm /usr/lib/";

Rdist example
rdist example3

$SRC/sendmail/cf/cf/ -> ${AIX_CLIENTS}

special "cp /etc/mail/ /etc/mail/";

install /etc/mail/;

special "ln -s /etc/mail/ /etc/";


$SRC/sendmail/src/obj.AIX.4.000044673500/sendmail -> ${AIX_CLIENTS}

special "cp /usr/lib/sendmail /usr/lib/sendmail.old";

install /usr/lib/sendmail;

special "/usr/local/bin/killj sendmail";

special "/usr/lib/sendmail -bd -q1h";

$SRC/sendmail/cf/cf/ -> ${HPUX_CLIENTS}

special "cp /etc/mail/ /etc/mail/";

install /etc/mail/;

special "ln -s /etc/mail/ /etc/";

Rdist example
rdist example4

$SRC/sendmail/src/obj.HP-UX.10.2/sendmail -> ${HPUX_CLIENTS}

special "cp /usr/lib/sendmail /usr/lib/sendmail.old";

install /usr/lib/sendmail;

special "/usr/local/bin/killj sendmail";

special "/usr/lib/sendmail -bd -q1h";

Rdist example
information distribution8
The pull method
    • There are two common “pull” packages:
      • expect
        • expect uses ftp to copy files to the client
        • expect provides some directives to manage the ftp session.
        • can be run from a bootup script
        • can be run from a cron entry
Information Distribution
sample expect script

spawn /bin/ftp

expect "ftp> " {send "open\r"}

expect "): " {send "gorp\r"}

expect "Password:" {send "c@Ntheh@\r"}

expect "ftp> " {send "bin\r"}

expect "ftp> " {send "get np.tar /dev/null\r"}

expect "ftp> " {send "quit\r"}


Sample expect script
information distribution9
Another pull technology is the “package” command used with AFS.
    • package requires the administrator to set up a control file which contains a list of files which will be distributed.
    • package allows a noaction mode to test rules.
    • package could be run from cron (dangerous?).
    • package is usually run at system reboot.
Information Distribution
sample package file

# CSE supplemental package file

# Need these directories defined so that we can get to other entries


D / root root 755

D /afs root root 2755

D /etc root staff 755

D /etc/mail sys mail 755

D /etc/init.d root sys 775

D /etc/inet root sys 755

D /etc/rc3.d root sys 775

D /etc/rc2.d root sys 775

DR /var/tmp bin sys 1777

DR /tmp bin sys 1777

D /usr root sys 775

D /usr/bin root bin 775

D /usr/sbin root bin 775

D /usr/include root sys 775

D /usr/vice root other 755

D /usr/vice/etc root other 755

D /var root sys 755

D /var/spool root bin 755

D /var/spool/cron root sys 755

D /var/spool/cron/crontabs root sys 755

Sample package file
sample package file1

# Some necessary links

# Eases installation of new machines


LA /usr/include/X11 /afs/

LA /usr/lib/X11 /afs/


# Particular to this cluster

# Package file, MOTD, and AFS cache size


F /etc/motd /afs/ root sys 644


# For all CSE clients (i.e. non-wizard)


F /.rhosts /afs/ root sys 444

F /.cshrc /afs/ root sys 444

F /.profile /afs/ root sys 444

F /var/spool/cron/crontabs/root /afs/ root other 400

Sample package file
sample package file2
# Replace some /etc

F /etc/passwd /afs/ root other 644

F /etc/resolv.conf /afs/ root other 644

F /etc/pam.conf /afs/ root other 644

FQ /etc/inet/hosts /afs/ root other 444

LA /etc/hosts /etc/inet/hosts root other 644

F /etc/inet/services /afs/ root other 644

LA /etc/services /etc/inet/services root other 644

F /etc/syslog.conf /afs/ root other 644

F /etc/init.d/cse_client /afs/ root other 755

LA /etc/rc3.d/S99cse_client /etc/init.d/cse_client root other 755

F /usr/etc/ifstatus /afs/ root other 755

F /etc/inet/inetd.conf /afs/ root sys 444

LA /etc/inetd.conf /etc/inet/inetd.conf root other 444

F /usr/sbin/in.ftpd /afs/ bin bin 555

F /etc/ftpaccess /afs/ bin bin 555

F /usr/bin/top /afs/ bin bin 4755


FAQ /usr/lib/sendmail /afs/ root other 4555

F /usr/lib/sendmail.hf /afs/ root other 555

F /etc/mail/ /afs/ root other 444

LA /etc/ /etc/mail/ root other 444

Sample package file
information distribution10
Other distribution methods
    • NIS - centralized database, not really a way to “distribute” files. The files are available to other hosts, but they are located on a (few) server(s).
    • MIT’s Hesoid - never caught on, difficult to build configuration files. Uses DNS to provide information from a central server.
    • Netinfo - NeXT computer’s version of NIS.
    • Rsync
    • Cfengine
Information Distribution
Many automation tasks are handled using shell (or other) scripts.
  • Shell scripts are generally portable across multiple versions of operating systems.
  • Other scripting languages, such as Python, or Perl are much more powerful, but not always installed on systems by default.
shell programming
    • UNIX provides several shell programs for the users.
      • These programs are the user’s interface with the system software.
      • The shell programs read commands from the user terminal and interpret or execute them as required.
      • Some of the more popular shells available are:
        • sh - the original Bourne shell
        • csh - the Berkeley C shell
        • bash - the Bourne Again SHell (an updated sh)
        • ksh - the Korn shell
        • tcsh - an updated version of the C shell.
Shell Programming
shell programming1
    • Shell selection is a highly subjective user decision.
    • While the shells are primarily a command interpreter, they also provide an interpreted programming language which users can employ to make their lives easier.
    • Different shells implement different programming languages.
    • Unfortunately, system administrators have to be proficient with several shell languages in order to manage the system.
    • Over the next few lectures we will look at the “sh” and “csh” shells. In particular we will look at using these shells to write shell scripts which will assist us with our system administration tasks.
Shell Programming
shell programming2
    • Most of you use a variant of the Cshell (csh or tcsh).
      • The Cshell provides some job control, and command line editing options not available under the Bourne shell (sh).
      • Tcsh provides more advanced command line editing and parsing than csh...but tcsh is not a standard shell on all versions of Unix.
    • Under Solaris the root account uses the bourne shell located in /sbin/sh.
      • The bourne shell is not my favorite shell, but the examples I give will be sh based.
      • If you are serious about system administration, I suggest you become familiar with both sh and csh environments.
Shell Programming
shell programming3
Common Shell Features
    • All shells have some common features:
      • Shells allow interactive or background processing.
      • Shells allow input/output redirection.
      • Shells allow “pipes” between commands.
      • Shells allow wildcard matching.
      • Shells assign special meaning to some characters.
      • Shells use variables to store values.
    • The common invocation of a shell command is:
      • command[options] arguments
Shell Programming
shell programming4
Example Script Invocations

nispopulate -u -F -p /nisstuff/update -d

/etc/init.d/lab10 start

which talk

cd /tmp

basename /afs/

Shell Programming
shell programming5
Built-in Shell Operations
    • Shells all have some built-in commands which we can use when writing shell scripts:
      • echo - write a message on standard output (CSH).
        • Been hit by root kit? Use echo!
      • read - read something from standard input
      • test - test various conditions
      • expr - evaluate an expression
      • true - return a true value
      • false - return a false value
      • wait - wait for something (good) to happen
      • sleep - stop for some period of time
Shell Programming
shell programming6
Shell Variables (Built-in)
    • All shells have some built-in variables (reserved names) which can be useful when we write shell scripts:
      • PATH - The system search path
      • LOGNAME - The users login name
      • TERM - The kind of terminal the user is at
      • HOME - The users home directory
      • MAIL - The location of the users mailbox
      • PS1 - The primary prompt string for the user
      • LD_LIBRARY_PATH - The path to system libraries.
Shell Programming
shell programming7
Shell Variables (user assigned)
    • To assign a values to a variables:
      • variable=value (set variable=value for CSH)
        • for example fruit=apple, or i=1, set name=$USER
    • To access the value of the variable, prepend a “$” :

echo fruit


echo $fruit


echo “User: $USER”

User: curt

Shell Programming
shell programming8
Shell Variables
    • You can also set variables by executing commands:

menu=`cat food`


    • It is also possible to assign string values to variables:

PS1=“`uname -n` - Yes Master: “

echo $PS1

grumpy - Yes Master:

        • Must place multi-word strings in double quotes
Shell Programming
shell programming9
    • All shells treat certain characters as special.
      • $ ^ ; & { } [ ] ‘ ` * ( ) | < > newline space tab
      • To use these characters in scripts they must be quoted or escaped.
        • escape a character by placing a backslash in front of it.
        • single quotes protect text from any substitutions.
        • back quotes cause the shell to perform command substitution
        • double quotes protect against wildcard substitution
Shell Programming
shell programming10
Escaping Characters:

$ ( )

syntax error: `)' unexpected

$ \(\)

(): not found

Single Quotes

$ it's $cmd

> '

its $cmd^J: not found

$ it\'s $cmd

it's: not found

Shell Programming
shell programming11
Back Quotes

$ HN=uname -n

-n: not found

$ HN=`uname -n`

$ echo $HN


$ who am i

curt pts/5 Nov 11 13:47

$ 'who am i'

who am i: not found

$ `who am i`

curt: not found

Shell Programming
shell programming12
Double Quotes

$ grep Things to do todolist

grep: can't open to

grep: can't open do

todolist:Things to do:

$ grep "Things to do" todolist

Things to do:

Shell Programming
shell programming13
Shell test features
    • All shells provide test mechanisms:
      • This feature allows us to do conditional processing within shell scripts.
    • In sh we can test for:
      • numeric values:

if [ $# -eq 0 ] ; then if ( $# = 0 ) then (CSH version)

general form: N <primitive> M

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

= != > < >= <=

-o (or) -a (and)

Shell Programming
shell programming14
Test Conditions
    • The shells also provides a way to test the external environment:

-r file (read permission)

-w file (write permission)

-x file (execute permission)

-e file (file exists)

-o file (user owns file)

-z file (file is empty)

-f file (plain file)

-d file (file is a directory)

if [ -e /usr/lab/tmp/”$AFSID”.start ] ; then

if [ ! -d /usr/lab/tmp/”$AFSID” ] ; then

Shell Programming
shell programming15
Shell test features
      • string equality

if [ $LOGNAME = “root” ] ; then

general form: S <primitive> R ; or <primitive> S

primitives: =, !=

-z - is string zero length

-n - is string non zero length

      • Testing strings can produce “odd” results:
      • number=1
      • nombre=‘ 1’

test $number = $nombre evaluates true (spaces eaten)

test “$number” = “$nombre” evaluates false

Shell Programming
shell programming16
Shell Math
    • The shell also allows mathematical operations on variables:
      • The expr command evaluates it’s arguments.
        • General form: expr variable operation variable
        • operations: +, -, *, /, % (remainder)
        • sum=`expr $1 + $2`
Shell Programming
shell programming17
Conditional Processing
    • The shells all provide a way to do conditional processing:

if [ condition ] ; then if ( condition) then


else (or else if)


fi endif

Shell Programming
shell programming18
Conditional Processing

for variable in list # BOURNE SHELL




foreach i( list ) # CSH



Shell Programming
shell programming19
Conditional Processing

while condition #BOURNE while condition # CSH

do statements


done end

until condition




Shell Programming
shell programming20
Conditional Processing SH

case variable in

pattern 1)



pattern 2)



*) #default case




Shell Programming
shell programming21
Conditional Processing CSH

switch ( variable )

case pattern 1:



pattern 2:



default :




Shell Programming
shell programming22
Argument Handling
    • The shell defines a method of handling arguments:
      • $$ is the process id of the shell program
      • The name of the shell program itself is $0
      • Argument variables are numbered in the order passed:
        • $1 $2 $3 $4 ...
      • $* and $@ access all variables
        • $* lumps all variables into a single string
        • $@ keeps variables as separate entities
      • $# is set to the argument count
Shell Programming
shell programming23
Argument Handling
    • When you pass an argument to a shell script how do you access it? For example :
      • /etc/init.d/lab8 start
    • In the example above we can test $1 to see if it is “start” or “stop” and continue accordingly.
Shell Programming
shell programming24
I/O Redirection
    • Input

< file -- causes shell to read from file

<&n -- causes shell to read from file descriptor n

<&- -- causes shell to close standard input

<tag -- causes shell to read up to tag

<~tag -- same as <tag, but discard white space

    • Output

> file -- causes shell to write to file

>>file -- causes shell to append to file

>&n -- causes shell to write to file descriptor n

>&- -- causes shell to close standard output

| -- pipe the output of command and feed it to next command

Shell Programming
shell programming25
I/O Redirection

echo $1 $2 $3 > $4 # overwrite $4

echo $1 $2 $3 >> $4 # append to $4

10 03 * * * cd /tmp ; find . ! -name . -type d -mtime +1 -exec rmdir {} \; >/dev/null 2>&1

ps -ef | grep curt

read answer </dev/tty

cat < EOF

FATAL ERROR: $SPOOL/etc/setup.cache is missing!

The file $SPOOL/etc/setup.cache is not present. This

probably means the machine has not been setup using the faxsetup(1M)

command. Read the documentation on setting up HylaFAX before you

startup a server system.


Shell Programming
shell programming26
Other Shell Features
    • The : command is a null command.
    • Shells allow I/O operations:

echo “Enter your afsid: “

read AFSID </dev/tty

cat file.dat | while read x y z

>do echo $x $y $z ; done

Shell Programming
shell programming27
Other Shell Features
    • All shells provide a means of assigning temporary filenames for their use:
      • sort -u +1 -2 $* |tr -d 0-9 >/tmp/$0$$
    • All shells provide a means of catching interrupts for cleanup processing:
      • trap ‘command arguments’ signal
    • All shells provide a means of debugging shell programs (-x).
    • All shells allow for those dreaded comments:
      • # rest of line is a comment
Shell Programming
shell programming28
Other Shell Features
    • The set command allows you to set $1 through $n to the words given as its arguments:

who -r

. run-level 3 Nov 21 09:13 2 0 S

set `who -r`

echo $6


Shell Programming
shell programming29
Other Shell features
    • The shells also provide a utility to execute arguments.
    • The eval command executes commands generated by multiple levels of indirection:

$ a=c ; b=m ; c=d ; cmd=date

$ eval $`echo $a$b$c`

Fri Nov 21 09:18:45 EST 1997

$ $cmd

Fri Nov 21 09:18:49 EST 1997

Shell Programming
shell programming30

#ident "@(#)nfs.client 1.8 93/07/07 SMI"

if [ ! -d /usr/bin ]

then # /usr not mounted



killproc() { # kill the named process(es)

pid=`/usr/bin/ps -e |

/usr/bin/grep $1 |

/usr/bin/sed -e 's/^ *//' -e 's/ .*//'`

[ "$pid" != "" ] && kill $pid


Shell Programming
shell programming31
# Start/stop processes required for client NFS

case "$1" in


if [ -x /usr/lib/nfs/statd -a -x /usr/lib/nfs/lockd ]then

/usr/lib/nfs/statd > /dev/console 2>&1

/usr/lib/nfs/lockd > /dev/console 2>&1


# obtain kerberos ticket before attempting kerberos NFS mounts

/usr/bin/sed -e 's/#.*//' /etc/vfstab | \

/usr/bin/grep kerberos >/dev/null 2>&1

if [ $? = 0 -a -x /usr/bin/ksrvtgt -a -x /usr/bin/uname ]


HNAME=`/usr/bin/uname -n`

WARN=`/usr/bin/ksrvtgt root $HNAME 2>&1`

if [ $? != 0 ]then

echo "Warning: cannot get kerb ticket for root.$HNAME"

echo " ksrvtgt error: $WARN"



Shell Programming
shell programming32
/sbin/mountall -F nfs

/sbin/mountall -F cachefs




killproc lockd

killproc statd

/sbin/umountall -F cachefs

/sbin/umountall -F nfs



echo "Usage: /etc/init.d/nfs.client { start | stop }"



Shell Programming
shell programming33
Shell Programming
    • All shells provide us with programming constructs (variables, flow control, conditional tests, ...). with these facilities we can write programs to make our lives easier.
    • When writing shell programs we also have easy access to all of the system utilities.
    • By combining shell code and utility calls it is easy to write very powerful tools!
Shell Programming
find command
Cleanup Tools
    • Find
      • The find command can be a very useful tool for administrators to police disk usage.
        • You can find and remove cruft from system directories (core files, a.out, .o files, junk in /tmp).
        • You can locate files owned by a particular user.
        • You can locate files with particular permissions.
        • You can locate files containing a specific string.
        • You can locate files which have been modified since a particular date.
        • You can locate files of a particular size.
Find Command
find command1
  • Removing files from a users directory may be illegal!
    • Files in a user’s account are considered property of the user unless otherwise stated in site policies.
    • User must be informed that files in their account are not personal/private.
  • Files in /tmp are exempt from this, as /tmp is a Public file system. Other public file systems (/scratch, /usr/tmp, /var/tmp, /pub) are also typically considered exempt.
Find Command
find command2
    • The generic invocation of find is:

find pathlist expression

      • The pathlist is a directory [or list of directories and/or files] you wish to search.
      • The expression is a directive which tells find what to look for, and what to do when it finds what it is looking for.
Find Command
find command3
Find pathlist expression
    • Some of the more useful expressions for the find command include:
      • name - search for files called name
      • atime n - search for files which were accessed n days ago.
      • ls - print the current path and related statistics
      • mtime n - search for files which were modified n days ago.
      • exec command - execute command when the file is found.
      • print - causes the filename to be printed when found.
      • type c - search for files of type “c” (file, directory, link, device files, fifo, socket)
      • fstype type - search for filesystems of type
Find Command
find command4
Find examples
    • Suppose you want to make a tape of your files before you leave Notre Dame. You want to keep your source code, your mail addresses, and other files, but you do not want to carry along your a.out’s, any of the .o files, or any netscape cache files.

find $HOME \(-name a.out -o -name ‘*.o’ -o -name ‘cache*’\) -exec rm{} ;

    • If you were a system administrator who wanted to remove the same files from all directories on the system you could modify the command a little:

find / \(-name a.out -o -name ‘*.o’ -o -name ‘cache*’\) -exec rm{} \;


Find Command
find command5
Find examples
    • Suppose you had a series of users complain that their .login files had been modified yesterday by someone other than themselves. If you wanted to find all instances of modified .login files you could use:
      • find /home -name .login -mtime +1 -print
    • Similarly, suppose you knew that someone had compromised your system and replaced the shell program with their own version. You found the string “floobydust” in their version of the shell program, so you want to look and find out if they left other copies of their program on the system:
      • find / -type f -exec grep -l “floobydust” {} \;
Find Command
find command6
    • How do the security tools we discussed (SATAN, COPS) find suid programs?
      • find / (-perm 4755 -o -perm 2755 -o -perm 1755) -print
    • Suppose an employee (UID 666) leaves the company and another employee (UID 999) takes over the code managed by the old employee. You have been asked to make sure the new employee has full permissions on the files the old employee owned:
      • find / -user 666 -exec chown 999 {} \;


Find Command
find command7
    • Find can also be a useful tool for forgetful users (or professors) who want to find where they left something.
      • find $HOME -name homework6 -print
      • find $HOME -exec grep -l “lab combination” {} \;
    • As a system administrator you need to think about a couple of questions:
      • How often should these housekeeping functions be performed?
      • Is there a method that will automate these functions without requiring my intervention.
Find Command
find command8
Cleanup Tools
    • Many places create special scripts to locate and remove “cruft” from the system.
    • Skulker
    • SpaceGripe
    • DiskClean
      • Most are based on find.
Find Command
    • AWK is a powerful pattern matching and scanning tool used by system administrators.
      • AWK is typically used to scan an input string, grab certain portions of the string, then output the information in another format.
    • AWK was developed by Alfred Aho, Peter Weinberger, and Brian Kernighan (hence the name AWK).
    • There are several variants of awk: standard awk (awk), Gnu awk (gawk), and new awk (nawk) are the most common.
    • Awk allows us to:
      • view a text file as if it were made up of records and fields in a textual database
      • Use variables to manipulate the database
      • Use loops and conditional processing
      • Generate formatted reports
    • Nawk adds several capabilities:
      • Define functions
      • Execute UNIX commands
      • Process the results of UNIX commands
      • Better command line argument processing
      • Work with multiple input streams
Generic invocations:

awk ‘instructions’ files

awk -f ‘script’ files

  • If you have a file (filename list) with the following entries:
    • John Doe, 999 Sorin Hall
    • Jeff Walker, 234 Cushing Hall
    • Amy Vanderbilt, 876 Hesburgh Library

awk ‘{print $1}’ list

    • will output :




If you wanted to make mail labels from the file “list” you could do:

awk -F, ‘{print $1 print $2 print “Notre Dame, IN 46656”}’

    • The output would be:

John Doe

999 Sorin Hall

Notre Dame, IN 46656


234 Cushing Hall

Notre Dame, IN 46656


876 Hesburgh Library

Notre Dame, IN 46656

    • You can set shell variables with the output of the awk command.
      • input: name address phone

John Doe, 123 Sorin Hall, 634-4444

name=`awk ‘{print $1}’ input`

echo $name


    • Awk does a lot of the “programming” for you.
    • An AWK program has three parts:
      • An optional “begin” routine which is executed once before the main loop.
      • The main loop.
      • An optional “end” routine that is executed after all of the main loop code is done.
    • AWK provides the main loop. When you call AWK is goes into a loop reading input and providing it to your code.
      • You do not have to write code to read the just provide pattern matching statements.
    • AWK acts on patterns..
      • Your code is a series of patterns and actions.
      • When AWK detects the pattern, it executes the action.
      • For example:

awk ‘{print $1}’ file

          • tells awk to print the first field of the input line.
          • $1 is the pattern
          • print $1 is the action
AWK Regular Expressions

/^$/ {print “Input is a blank line” }

/[0-9]+$/ {print “Input is an integer” }

/[A-z]+/ {print “Input is a string” }

      • AWK works with internal variables much like the Bourne shell does:

x = 1 assigns the value 1 to x

z = “Hello” assigns the string “Hello” to z

w = $1 assigns the value of the first field of the input to the variable w.

      • If we want to perform mathematical operations on the variables in an AWK script, the following operators are available:

+, -, *, /, %, ^

      • AWK also has a group of assignment operators:

+=, ++, --, -=, *=, /=, %=

        • A simple script to count blank lines in a file:

awk ‘/^$/ { ++x} END { print x }’ file

        • AWK has some handy built-in variables:
          • FS is the input field separator. (Default space or tab)
          • OFS is the output field separator
          • RS is the input record separator (Default newline)
          • FILENAME is the name of the input file
          • NR is the number of input records read
        • AWK has relational operators and Boolean operators:

<, >, <=, >=, ==, !=, ~, !~

||, &&

      • So what is all of this useful for (besides lab9)?
        • Suppose your site has a shell called the new shell (nsh). You are discontinuing support for this shell because it is very similar to the zork shell. You need to scan the password file, convert all accounts with nsh to use zork, and you need to keep track of how many users you convert over to the zork shell.
        • The password file consists of 7 colon separated fields.
        • The users shell is held in the 7th field of the input.
awk '{

# Set delimiters

BEGIN { FS=":" ; OFS=":" }

# if shell ($7) is /bin/nsh convert it to /bin/zork

{ if ( $7 == "/bin/nsh" ) {

nnsh++ ; print $1,$2,$3,$4,$5,$6,"/bin/zork" }

# Otherwise don’t change the line


{ print $1,$2,$3,$4,$5,$6,$7 }

# Print number of users assimilated


END { print nnsh “ users converted from /bin/nsh to /bin/zork” }


Another stupid example:
    • You work for a Veterinarian. The Dr. wants to send a postcard to the owners of all dogs informing them of a new parvo-virus immunization law. The information format in the Dr’s database is:
      • Species,Owner Name, Address, City, State, Zip, Phone, Animal’s Name, Animals Age, Immunized,Last Visit, Notes
nawk -F, '{

# If canine and not immunized, print postcard, else ignore the line

if ( $1 == "Canine" && $10 == "No" )

{print $2 ; print $3 ; print $4 ", " $5 " " $6

print ""

print "Dear " $2 ","

print "A recently enacted state law requires that all dog" ;

print "owners get their animals immunized for parvo-virus " ;

print "as soon as possible. Our records indicate that " $8

print "needs to be immunized. Please call our office to " ;

print "make an appointment as soon as possible."

print ""

print ""



other useful tools
Some other tools you might want to experiment with:
    • cut - cut bytes from the input.

first=Curt last=Freeland

f1=`echo $first | cut -b1`f1=C

ln=`echo $last | cut -b1-7`ln=Freelan


found=`echo $try | cut -d: -f1`found=curt

Other Useful Tools
other useful tools1
It’s pretty easy to convert strings from upper to lower case in C. How would you do the same thing in shell scripts?
    • The tr command translates (or transforms) characters on the input stream into different characters on the output stream.

echo $f1$ln

      • CFreelan

lname=`echo $f1$ln | tr “[:upper:]” “[:lower:]”`

echo $lname

      • cfreelan
Other Useful Tools
other useful tools2
There are many variants of the grep command. The “fgrep” command has an interesting flag:
    • Consider:
      • a password file contains the following entries:




      • grep curt /etc/passwd will return all three lines!
      • fgrep -x curt /etc/passwd
        • returns nothing! The -x flag tells grep that it has to match the entire input string exactly.
        • awk -F: ‘{print $1}’ /etc/passwd | fgrep -x curt
Other Useful Tools
other useful tools3
The Streams editor (sed) is a very handy tool. sed uses regular expression matching to convert the input stream to a new output stream one line at a time.
    • SED works on a temporary buffer called the pattern space - it does not change the original input file.
    • SED uses the same commands as the ex and vi editor (when run in line mode).

sed ‘1,3d’ file

        • Deletes lines 1-3 from file and displays result on screen.

sed ‘[Jj]ohn/p’ datafile

        • Prints any lines from the input file that contain John or john
Other Useful Tools
other useful tools4
  • #ident "@(#)nfs.client 1.8 93/07/07 SMI"
  • if [ ! -d /usr/bin ]
  • then # /usr not mounted
  • exit
  • fi
  • killproc() { # kill the named process(es)
  • pid=`/usr/bin/ps -e |
  • /usr/bin/grep -w $1 |
  • /usr/bin/sed -e 's/^ *//' -e 's/ .*//'`
  • [ "$pid" != "" ] && kill $pid
  • }
Other Useful Tools
Automating repetitive tasks allows the administrator time to get other things done.
  • The administrator needs to understand what can be automated, and what cannot be automated.
  • The administrator should understand how to write shell scripts using the command line utilities used to perform daily tasks.