Transcript Unix Linux Administration II
Unix Linux Administration II
Class 6: Scripting arithmetic, quoting and arguments. DNS slave servers. Scripting conditionals
Agenda
discuss Homework.
Unit 1: Scripting arithmetic, quoting and arguments
Unit 2: DNS slave servers
Unit 3:
Scripting conditionals
Homework review
Self signed certificate creating the cert, openssl req –x509 ….
review contents of cert, openssl x509 –in … confirm key, openssl rsa –in ….
Configure server to use new certificate.
locate your ssl.conf file Copy key and certificate Update SSLCertificateFile and SSLCertificateKeyFile directives.
Homework review
Firewall rule updates service iptables status add rule for tcp/udp over port 443 (ssl).
Add CNAME for: WWW.
user info script script template accept single argument, userid Error checking for if user exists?
User details.
Review: web servers
You can compile your webservers from source.
“groupinstall” will provide a standard yum managed webserver.
Related files can be found under: /etc/httpd/, /etc/httpd/conf.d/ /var/www/.
/var/log/httpd
Review:
Script templates - :r template.sh
Variables start with _ or alphabetic character Variables assignment var1=value Re-assign var2=$var1 Rename var3=${var2}.bk
Order of operations; variable substitution, file substitution, parse command line.
Review: self signed certificates
Public certificate and Private key For self-signed certificates you need: private key private.key
certificate signing request (csr) request.csr
public certificate which is based on the newly created csr which is related to the private key.
public.crt
Web server ssl configurations: /etc/httpd/conf.d/
Class 6, Unit 1
What we are going to cover: Scripting; arithmetic, quoting and arguments.
What you should leave this session with: Ability to complete basic math in your shell.
Knowledge of your quoting options.
How to pass and shift arguments.
Script bin
It may be helpful to create a script directory in your home directory with a
bin
sub directory. Using this design you can place your scripts into this directory and then add this to your PATH variable.
~
Random script tips
Whitespace is ignored on the first line.
#! /bin/sh, #!/bin/sh or #! /bin/sh You can set shell options on the first line such as debug #! /bin/sh –x Sometimes you may find scripts with just a dash and no option. This tells the shell that there are no more options. This can prevent some types of spoofing attacks.
#! /bin/sh -
Arithmetic in the shell
The Portable Operating System Interface (POSIX) standards define a set of Application Programming Interfaces (API), shell, and utility interfaces for UNIX systems.
POSIX allows for some basic arithmetic expansion and functions.
Including + - * / < > || && etc.
Standard syntax is
$((expression))
e.g. echo $((2*4))
Shell math cont.
Multiple parenthesis can exist within the basic syntax. They expressions are executed in the order you might remember from high school algebra, *pemdas… echo $(( i = ( i + 10 ) * 2 ) Try this in your shell.
Now run it again did the value change? If so why?
*Please Excuse My Dear Aunt Sally
Shell math cont.
Leading and trailing whitespace is valid.
echo $((i=(i + 10)*2)) Or echo $(( i= ( i + 10 ) * 2)) The exit status ($?) is true (0) so long as the last expression is a non zero value. Otherwise the exit status is false (1).
Quotes, single, double and on…
There are four recognized quotes in shell \ back slash ‘ single quote “ double quote ` back quote
Back slash \
The backslash can remove the special meaning of the character directly adjacent.
echo “The \$PATH value is $PATH”
Shell treats a backslash at the end of a line as an argument delimiter.
ps –ef \ | wc –l
This is often used to break up commands that require multiple lines.
Single Quotes
Single quotes tell the shell not to interpolate anything within the quotes. It is like saying set the value to exactly this regardless of the special characters you might see.
echo '$HOME \\ \$PATH'
Double quotes
Double quotes are the opposite of single quotes in that you want the shell to interpolate the contents within the shell [angus@ulc-180 ~]$ echo "$HOME \\ \$PATH" /home/angus \ $PATH
Back quote and command substitution
The back quote is used to capture command output like date, ls, ps etc.
today=`date` echo $today This can also be done as follows today=$(date) Either is acceptable.
*Solaris may need use the latter syntax
More on command substitution
You can use cat to store file contents in variables.
filecontent=$(cat
Enter argument.
To argue with a script is not a bad thing. This means to provide a value defined at runtime as a variable for your script.
[angus@localhost scripts]$ ./script.sh help
Passing arguments around
When passing in arguments to a script the order of the arguments defines the variable ./myscript name1 name2 name3 name4 Within the script $1 = name1 $2 = name2 …
Positional parameters.
The shell automatically stores the first argument and subsequent arguments starting at $0 through $9 You can leverage these arguments in your script for the duration of the process.
[angus@ulc-231 scripts]$ ./script.sh mon tue What do you think the value of $0 is?
$# what the shell
Every time a shell script is run the $# records the number of variable passed to the script. This can be a good way to determine if the script received the expected input.
$* what the shell is this?
The $* variable replaces all the arguments passed to the shell.
On.sh bob john tom echo $* echo “script only run with first user provided” who | grep $1
Shift my shell variable
Shift values off the stack per se’. Here is a simple example using shift, $#, $* and debug [angus@ulc-188 shell]$ ./shifting.sh a b c d + echo 4 a b c d 4 a b c d + shift + echo 3 b c d 3 b c d
Review:
basic math syntax $((expression)) most common functions available including bitwise and logcal White space is optional.
non-zero final expression return true.
Quoting ', ", ` and \ command subsitution user=$(grep -i $name /etc/passwd)
Review: cont.
Positional parameters are provided by the shell environment and automatically assign variables to values passed into the script. who who | grep root on.sh root who | grep $1 $# = number of arguments passed to the script.
$* = reference all arguments passed to the script $? = Stores the exit value of the script
In class lab 6a
Lab notes for this session can be found here: http://www.ulcert.uw.edu
-> Class Content -> InClass labs ->
Class 6, Unit 2
What we are going to cover: DNS slaves What you should leave this session with: How to configure your DNS slaves Resolving issues with slave and master servers.
DNS redundancy
Typically you want at least two name servers available for any domain in order to avoid problems if one is taken off line. Best practice would suggest that these two servers exist in different in different networks and in different physical locations if possible. It is a fairly simple task to switch a name server from master to slave or vice-versa. How does the named process know if it is the master or slave for a given domain? it is defined in the named.conf file on a zone by zone basis.
Slave vs Master DNS server
The primary difference between a slave and master server is where the data comes from. A slave name server gets the data from a network resource and a master name server reads it directly from zone files.
Slave servers can be configured to pull data from other slave servers if required.
When the slave poll
Slave servers poll the master name server based on the values defined in the SOA block of the zone data.
@ IN SOA ns1.ulcert.uw.edu. Info.ulcert.uw.edu ( 1 ; serial version of the file (usually a date) 3600 ; refresh, slaves refresh after one hour 3600 ; retry after one hour 86400 ; Expire after one day 7200 ; Minimum negative TTL );
When will the slave update?
The slave server will update when polling the master and finding the serial value to have changed. Updates occur over port 53. Full zone transfers (AXFR) are in fact just another query type supported by the named process.
An alternate zone transfer type is the incremental or IXFR query which will return if possible a subset of the zone data based on just the changes.
Dynamic updates are also supported and can occur if the master server is configured to notify the slave servers when changes have occurred.
Setting up your slave
To setup your name server install bind either from source or using a yum package. When complete you could copy over your named.conf from the master server and just make a couple minor updates. First you will want to find the block related to your zone and change the type to slave from master. Next you will want to add a directive for masters {
file "zone.data.txt"
Named.conf update
zone "books.ulcert.uw.edu" IN { type master; file "/var/named/books.txt"; }; zone "books.ulcert.uw.edu" IN { type slave; file "/var/named/books-copy.txt"; masters { 140.142.159.197; }; };
Backing up your zone data
The
file
directive tells your slave server to keep a backup copy of the zone data. By default the slave will attempt to communicate with the master soon after starting up. After which it will continue to poll the master as directed in the SOA stanza. However, if there is a backup file available the slave will read this at startup and update the data as soon as it receives an update from the master. In situation where the master is not immediately available this can be very helpful.
Review:
Slave servers provide redundancy and high availability when designed appropriately form your domain.
The changes between slave and master are fairly simple.
Slave poll masters by default but master can be configured to notify slaves when updates occur.
Slaves can be configured to store zone data locally for backup.
In class lab 6b
Lab notes for this session can be found here: http://www.ulcert.uw.edu
-> Class Content -> InClass labs ->
Class 6, Unit 3
What we are going to cover: Scripting and conditionals What you should leave this session with: How to add decision points to your scripts.
How to enable debug in your scripts.
Indenting
Tabs or Spaces Be consistent! (possible vimrc setting?).
Helps with legibility Most languages ignore white space Good or Bad?
” …code is read much more often than it is written ” Python - http://www.python.org/dev/peps/pep-0008/#indentation
Exit status
Every time you run a script it produces an exit status. Zero is successful anything else indicates failure.
Failures can be caused for lots of reasons. The exit value is stored in $?
echo $?
What are some ways to create a failed exit status?
The "if" construct
"if" is one of the first conditional statements you will probably encounter.
You can think of this as "if X then do Y and finish". The if statement must start with "if" and end with "fi". We will see similar constructs in other conditionals later.
for example: if [ -f /etc/hosts ]; then echo "a host file exists" fi
How to test string values.
You can test an expression for a true or false value using the expression "test".
user=$1 if test “$user” == angus; then echo “$user found on system” fi Many test operators are available such as ==, !=, -z string (string is null) –n string (string is NOT null), string (is defined)
Test cont.
You can also test for integer values with Returns true (0) if: int1 -eq int2 int1 ge int2 “great than or equal to” int1 gt int2 “greater than” int1 le int2 “less than or equal to” int1 lt int2 “less than” int1 ne int2 “not equal to” [ “$value” -eq 0 ]
File tests
The file tests expect a single argument, the filename.
-d file -e file -f file -r file -s file -w file -x file -L file file is a directory file exists file is an ordinary file file is read only file has nonzero length file is writable by process file is executable file is a symbolic link [ -f /etc/passwd ] is this an ordinary file [ -r /etc/passwd ] Is file readable by process.
Logical operators available.
! Used to negate the value [ ! –r /etc/shadow ] is the file not readable -a performs logical AND of two expressions.
[ -f /etc/passwd –a –r /etc/passwd ] BOTH must be true.
-o performs logical OR of two expressions.
[ -f /etc/passwd –o –r /etc/shadow ] true if EITHER are successful
Parentheses
You can use parentheses in a test to alter the order of evaluations however the parentheses must be escaped [ \ ( “$value” –ge 0 \) –a \( $value –lt 10 \) ]
The else conditional
The else statement can expand the if statement. If the first condition is true the second one is skipped.
if cmd; then command1 command2 else command1 command2 fi
else example
# value passed in from cmd line.
user=$1
if
who | grep "^$user " > /dev/null;
then
echo "$user is logged on"
else
echo "$user is NOT logged on"
fi
Exit command
Exit allows you to immediately terminate a script. You can pass exit a numeric value also if you want, this become the status code stored by $?
if
...
else
echo "$user is NOT logged on“ exit 2
fi
Syntax for else/if = elif
If you find a need for nested if statements this can resolved with elif statements.
If cmd ; then cmd elif cmd ; then cmd else cmd fi
The case statement
Case statements let you compare a value against multiple values and execute one when a match is found. Case statements can be very efficient.
case value in pattern) cmd cmd;; pattern) cmd cmd pattern) cmd;; cmd cmd;; esac
Sample case statement
# script expects a single variable.
case "$1” in 0) echo zero;; 1) echo one;; 2) echo two;; 3) echo three;; *) echo "out of expected range";; esac Result, user enters 1 script echoes “one”
Talk about nothing, no operator
The shell representation for no operator is : This can be used in a script when you what to check for a value but do nothing if it is defined but return a message if it does not exist. If grep “userid /etc/passwd” > /dev/null; then : else echo “user is not defined to system” fi
Debug your scripts
One way to debug your scripts is to start them with the –x option like this: /bin/sh –x number.sh
/bin/sh -x number.sh 2 + case "$1" in + echo two Two The set –x option will display command and their arguments as they are executed.
Debug cont.
You can extend the output using –v Enabling –v will display the shell input lines as they are read.
Both can be enabled at the same time.
#!/bin/sh –vx Or within the script using something like set –v on set –x on Disable using +v or +x
Shell logical OR and logical AND
Logical OR = || cmd1 || cmd2 cmd2 is ONLY executed if cmd1 fails.
Logical AND = && cmd1 && cmd2 ONLY if cmd1 succeeds will cmd2 run.
Review: conditionals
Exit status, 0 = success, !0 = fail.
if test "$user" == “
[ -e /etc/nsswitch.conf ] logical operators -a -o || && You can use parentheses to alter the order of evaluations.
if cmd; then do; else do; fi if [ "$HOME" ]; then echo "Found home!"; else echo "shucks we are homeless!"; fi
In class lab 6c
Lab notes for this session can be found here: http://www.ulcert.uw.edu
-> Class Content -> InClass labs ->
Homework
homework for this week posted later tonight.