Automating - Delmar

advertisement
Automating System
Administration Tasks
Chapter 23
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.
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?
• Patches
– RedHat up2date
– Notre Dame’s “nd.installpatch”
• Installing accounts
– Acmaint
– grep user_name /afs/nd.edu/common/etc/passwd >>/etc/passwd ; pwconv
• Managing Configuration Files
–
–
–
–
rdist
expect
rsync
package
What to automate?
• 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
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
• 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
• Some typical examples:
– System Binaries
•
•
•
•
sendmail
login – common to a single OS/architecture
ftpd
tcpd
– Common configuration files
•
•
•
•
/etc/motd
sendmail.cf
password file
shadow file – may not be directly usable
Information Distribution
• 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
• 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
• 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
• 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
– Rdist
• 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!
Sample rdist file
#
# distribute something to lab hosts
#
BASE=“/afs/nd.edu/user33/curt”
SOL_CLIENTS=( snowwhite boole branin eckert noyce turing )
#
# Files to distribute
#
lab6:
$BASE/courses/cse444/lab6.init -> ${SOL_CLIENTS}
install /etc/init.d/lab6;
special "chmod 755 /etc/init.d/lab6";
Rdist Example
#
# distribute Solaris sendmail to grumpy, mail.cse), mail clients
# distribute HPUX sendmail to geo
# distribute AIX4 sendmail to yoyo and euclid
BASE=/afs/nd.edu/wsadmin/cse_254
SRC=/afs/nd.edu/user14/csesoft/src
SOL_CLIENTS=( aliens.dcrl atanasoff athena backus bashful berry boole branin)
STANDALONE=( grumpy )
AIX_CLIENTS=(euclid yoyo)
HPUX_CLIENTS=( geo )
SUNS=(${SOL_CLIENTS} ${STANDALONE} ${SERVER})
SERVER=( wizard )
ALL=(${SERVER} ${STANDALONE} ${SOL_CLIENTS} ${AIX_CLIENTS} )
Rdist example
#
# Files to distribute
#
sendmail.cf.solcli:
$BASE/common/etc/mail/sendmail.cf -> ${SOL_CLIENTS}
special "cp /etc/mail/sendmail.cf /etc/mail/sendmail.cf.old";
install /etc/mail/sendmail.cf.new;
special "cp /etc/mail/sendmail.cf.new /etc/mail/sendmail.cf";
special "ln -s /etc/mail/sendmail.cf /etc/sendmail.cf";
special "rm /etc/mail/sendmail.cf.new";
sendmail.cf.server:
$BASE/server/etc/mail/sendmail.cf -> ${SERVER}
special "cp /etc/mail/sendmail.cf /etc/mail/sendmail.cf.old";
install /etc/mail/sendmail.cf.new;
special "cp /etc/mail/sendmail.cf.new /etc/mail/sendmail.cf";
special "ln -s /etc/mail/sendmail.cf /etc/sendmail.cf";
special "rm /etc/mail/sendmail.cf.new";
Rdist example
sendmail.cf.stand:
$BASE/grumpy/etc/mail/sendmail.cf -> ${STANDALONE}
special "cp /etc/mail/sendmail.cf /etc/mail/sendmail.cf.old";
install /etc/mail/sendmail.cf.new;
special "cp /etc/mail/sendmail.cf.new /etc/mail/sendmail.cf";
special "ln -s /etc/mail/sendmail.cf /etc/sendmail.cf";
special "rm /etc/mail/sendmail.cf.new";
sendmail.sun:
$BASE/common/usr/lib/sendmail -> ${SUNS}
special "cp /usr/lib/sendmail /usr/lib/sendmail.old";
install /usr/lib/sendmail.new;
special "chgrp sys /usr/lib/sendmail";
special "chmod 6755 /usr/lib/sendmail";
special "/usr/local/bin/killj sendmail";
special "cp /usr/lib/sendmail.new /usr/lib/sendmail";
special "/usr/lib/sendmail -bd -q1h";
special "rm /usr/lib/sendmail.new";
Rdist example
sendmail.cf.aix:
$SRC/sendmail/cf/cf/nd-csedept-AIX4-hidden.cf -> ${AIX_CLIENTS}
special "cp /etc/mail/sendmail.cf /etc/mail/sendmail.cf.old";
install /etc/mail/sendmail.cf;
special "ln -s /etc/mail/sendmail.cf /etc/sendmail.cf";
sendmail.aix:
$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";
sendmail.cf.hpux:
$SRC/sendmail/cf/cf/nd-csedept-HPUX10-hidden.cf -> ${HPUX_CLIENTS}
special "cp /etc/mail/sendmail.cf /etc/mail/sendmail.cf.old";
install /etc/mail/sendmail.cf;
special "ln -s /etc/mail/sendmail.cf /etc/sendmail.cf";
Rdist example
sendmail.hpux:
$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";
Information Distribution
• 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
Sample expect script
#!/usr/local/src/gnu/bin/expect
spawn /bin/ftp
expect "ftp> " {send "open dopey.cselab.nd.edu\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"}
exit
Information Distribution
– 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.
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
#
# Some necessary links
# Eases installation of new machines
#
LA /usr/include/X11 /afs/nd.edu/sun4x_55/usr/local/src/X11R6/usr/include/X11
LA /usr/lib/X11 /afs/nd.edu/sun4x_55/usr/local/src/X11R6/usr/lib/X11
#
# Particular to this cluster
# Package file, MOTD, and AFS cache size
#
F /etc/motd
/afs/nd.edu/wsadmin/cse_254/211
root sys
#
# For all CSE clients (i.e. non-wizard)
#
F /.rhosts
/afs/nd.edu/wsadmin/cse_254/common
root sys
F /.cshrc
/afs/nd.edu/wsadmin/cse_254/common
root sys
F /.profile
/afs/nd.edu/wsadmin/cse_254/common
root sys
F
/var/spool/cron/crontabs/root
644
444
444
444
/afs/nd.edu/wsadmin/cse_254/common root other 400
Sample package file
# Replace some /etc
F /etc/passwd
/afs/nd.edu/wsadmin/cse_254/211server root other 644
F /etc/resolv.conf
/afs/nd.edu/wsadmin/cse_254/211server root other 644
F /etc/pam.conf
/afs/nd.edu/wsadmin/cse_254/common.26 root other 644
FQ /etc/inet/hosts
/afs/nd.edu/wsadmin/cse_254/211server root other 444
LA /etc/hosts
/etc/inet/hosts
root other 644
F /etc/inet/services
/afs/nd.edu/wsadmin/cse_254/common
root other 644
LA /etc/services
/etc/inet/services
root other 644
F /etc/syslog.conf
/afs/nd.edu/wsadmin/cse_254/common
root other 644
F /etc/init.d/cse_client /afs/nd.edu/wsadmin/cse_254/common
root other 755
LA /etc/rc3.d/S99cse_client
/etc/init.d/cse_client
root other 755
F /usr/etc/ifstatus
/afs/nd.edu/wsadmin/cse_254/common.26 root other 755
F /etc/inet/inetd.conf
/afs/nd.edu/wsadmin/cse_254/common
root sys 444
LA /etc/inetd.conf
/etc/inet/inetd.conf
root other 444
F /usr/sbin/in.ftpd
/afs/nd.edu/wsadmin/cse_254/common.26 bin bin 555
F /etc/ftpaccess
/afs/nd.edu/wsadmin/cse_254/common.26 bin bin 555
F /usr/bin/top
/afs/nd.edu/wsadmin/cse_254/common
bin bin 4755
##
FAQ /usr/lib/sendmail
/afs/nd.edu/wsadmin/cse_254/common/usr/lib/sendmail root
other 4555
F /usr/lib/sendmail.hf
/afs/nd.edu/wsadmin/cse_254/common
root other 555
F /etc/mail/sendmail.cf /afs/nd.edu/wsadmin/cse_254/211
root other 444
LA /etc/sendmail.cf
/etc/mail/sendmail.cf
root other 444
Information Distribution
• 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
Shells
• 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
• Shells
– 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
• Shells
– 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
• Shells
– 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
• 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
• Example Script Invocations
nispopulate -u -F -p /nisstuff/update -d cselab.nd.edu.
/etc/init.d/lab10 start
which talk
cd /tmp
basename /afs/nd.edu/user33/curt
Shell Programming
• 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 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 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
fruit
echo $fruit
apple
echo “User: $USER”
User: curt
Shell Programming
• Shell Variables
– You can also set variables by executing commands:
menu=`cat food`
now=`date`
– 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
• Metacharacters
– 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
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
Back Quotes
$ HN=uname -n
-n: not found
$ HN=`uname -n`
$ echo $HN
grumpy
$ who am i
curt
pts/5
$ 'who am i'
who am i: not found
$ `who am i`
curt: not found
Nov 11 13:47
Shell Programming
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 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
• Test Conditions
– The shells also provides a way to test the external environment:
-r file
-w file
-x file
-e file
-o file
-z file
-f file
-d file
(read permission)
(write permission)
(execute permission)
(file exists)
(user owns file)
(file is empty)
(plain file)
(file is a directory)
if [ -e /usr/lab/tmp/”$AFSID”.start ] ; then
if [ ! -d /usr/lab/tmp/”$AFSID” ] ; then
Shell Programming
• 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 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
• Conditional Processing
– The shells all provide a way to do conditional processing:
if [ condition ] ; then
if ( condition) then
statements
else (or else if)
statements
fi
endif
Shell Programming
• Conditional Processing
for variable in list
# BOURNE SHELL
do
statements
done
foreach i ( list )
statements
end
# CSH
Shell Programming
• Conditional Processing
while condition #BOURNE
while condition # CSH
do
statements
statements
done
until condition
do
statements
done
end
Shell Programming
• Conditional Processing SH
case variable in
pattern 1)
statements
;;
pattern 2)
statements
;;
*) #default case
statements
;;
esac
Shell Programming
• Conditional Processing CSH
switch ( variable )
case pattern 1:
statements
breaksw
pattern 2:
statements
breaksw
default :
statements
breaksw
endsw
Shell Programming
• 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
• 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
• 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
• I/O Redirection
echo $1 $2 $3 > $4
echo $1 $2 $3 >> $4
# overwrite $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.
EOF
Shell Programming
• 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
• 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
• Other Shell Features
– The set command allows you to set $1 through $n to the words
given as its arguments:
who -r
.
run-level
set `who -r`
echo $6
09:13
3
Nov 21 09:13
2
0
S
Shell Programming
• 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
#!/bin/sh
#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 $1 |
/usr/bin/sed -e 's/^ *//' -e 's/ .*//'`
[ "$pid" != "" ] && kill $pid
}
Shell Programming
# Start/stop processes required for client NFS
case "$1" in
'start')
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
fi
# 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 ]
then
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"
fi
fi
Shell Programming
/sbin/mountall -F nfs
/sbin/mountall -F cachefs
/sbin/swapadd
;;
'stop')
killproc lockd
killproc statd
/sbin/umountall -F cachefs
/sbin/umountall -F nfs
;;
*)
echo "Usage: /etc/init.d/nfs.client { start | stop }"
;;
esac
Shell Programming
• 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!
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
• WARNING!!!
• 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
– 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 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 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{} \;
SEE WARNING!!
Find Command
• 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
– 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 {} \;
SEE WARNING!!!
Find Command
• Find
– 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
• Cleanup Tools
– Many places create special scripts to locate
and remove “cruft” from the system.
– Skulker
– SpaceGripe
– DiskClean
• Most are based on find.
AWK
• AWK
– 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
• AWK
– 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
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 :
John
Jeff
Amy
AWK
• 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
Jeff Walker
234 Cushing Hall
Notre Dame, IN 46656
Amy Vanderbilt
876 Hesburgh Library
Notre Dame, IN 46656
AWK
• Awk
– 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
John
AWK
• Awk
– 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 input....you just provide
pattern matching statements.
AWK
• AWK
– 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
• 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.
AWK
• AWK
• 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
• AWK
– 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:
<, >, <=, >=, ==, !=, ~, !~
||, &&
AWK
• AWK
• 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
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
else
{ print $1,$2,$3,$4,$5,$6,$7 }
# Print number of users assimilated
}
END { print nnsh “ users converted from /bin/nsh to /bin/zork” }
}'
AWK
• 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
AWK
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`
ln=`echo $last | cut -b1-7`
f1=C
ln=Freelan
try=curt:x:1234:40:GECOS:/home/curt:/bin/csh
found=`echo $try | cut -d: -f1`
found=curt
Other Useful Tools
• 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
• There are many variants of the grep command. The “fgrep” command
has an interesting flag:
– Consider:
• a password file contains the following entries:
curt:x:1234:40:GECOS:/home/curt:/bin/csh
curt1:x:1235:40:GECOS:/home/curt1:/bin/csh
curt2:x:1236:40:GECOS:/home/curt2:/bin/csh
• 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
• 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
•
•
•
•
•
•
•
•
•
•
•
•
#!/bin/sh
#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
}
Summary
• 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.
Download