Wednesday, July 2, 2014

A bash example of processing both short and long command line arguments without using getopts or getopt

Processing command line arguments from bash getopts is limited to single character flags.  When writing scripts, I find it useful and/or necessary to use longer flag names both with and without arguments.

The external command getopt works, but its got some issues with quoted arguments.  Plus, it creates an external dependency that may or may not be on the system.

The easiest way to process more complex command line arguments from within bash is this way ... read the script comments for more details.  Some test cases and example usage follows.

--cut getops-alternative--
#!/bin/bash

# joseph.tingiris@gmail.com

# The bash built in 'getopts' does not allow the parsing of long command line
# arguments.  However, it is possible to parse and process both short and long
# command line arguments using a for loop combined with shifted case statements
# and contingencies.
#
# This shell script provides a working example of how to use this alternative
# from within bash (sh, or ksh).

# if there are no arguments, echo a usage message and/or exit
if [ $# -eq 0 ]; then echo "usage: $0 [-a <argument>|-b|--a-long <argument>|--b-long]"; exit 1; fi

# because the arguments get shifted each time, make sure to set and use a previously declared variable
declare -i total_arguments=$#

# for each command line argument, evaluate them case by case, process them, and shift to the next
for ((i=1; i <= $total_arguments; i++))
do
 arguments=0
 case "$1" in
 -a)
  # short -a flag, requires an argument
  arguments=1
  A_FLAG=1
  A_FLAG_VALUE="$2"
  if [ "$A_FLAG_VALUE" != "" ] && [ ${A_FLAG_VALUE:0:1} == "-" ]; then 
   echo "warning, argument value looks like a flag!"; 
  fi
  echo "-a flag value = '$A_FLAG_VALUE'"
  shift # do an extra shift for flags with arguments
  ;;
 -b)
  # short -b flag, no argument required
  B_FLAG=1
  echo "-b flag was set"
  ;;
 -a-long | --a-long)
  # long --a-flag, requires an argument
  arguments=1
  A_LONG_FLAG=1
  A_LONG_FLAG_VALUE="$2"
  if [ "$A_LONG_FLAG_VALUE" != "" ] && [ ${A_LONG_FLAG_VALUE:0:1} == "-" ]; then 
   echo "warning, argument value looks like a flag!"; 
  fi
  echo "--a-long value = '$A_LONG_FLAG_VALUE'"
  shift # do an extra shift for flags with arguments
  ;;
 -b-long | --b-long)
  # short --b-flag, no argument required
  B_LONG_FLAG=1
  echo "--b-long was set"
  ;;
 *)
  # unknown flags
  if [ $arguments -eq 0 ] && [ "$1" != "" ]; then
   echo "unknown flag '$1'"
   exit 2 # not absolutely necessary, but does enforce proper usage
  fi
  ;;
 esac
 shift
done

# HTH ... The end.

exit 0
--cut getops-alternative--

Here's my output from the above script ...

No arguments given displays a basic usage banner.  Of course, a more elaborate usage function could be created and called instead.

$ getopts-alternative 
usage: /usr/local/sbin/getopts-alternative [-a <argument>|-b|--a-long <argument>|--b-long]

A flag given that requires an argument, but none is given.

$ getopts-alternative -a
-a flag value = ''

A flag given that requires an arugment, none is given, and another flag is interpreted as its argument.  It's a corner case that may happen in practice and is not completely unavoidable.  So for this example I simply put in a warning message.  Discretionary, safer handling could be performed ...

$ getopts-alternative -a -b
warning, argument value looks like a flag!
-a flag value = '-b'

A valid flag with an argument and a valid flag without an argument.

$ getopts-alternative -a 'hello world' -b
-a flag value = 'hello world'
-b flag was set

Valid flags and an invalid flag.

$ getopts-alternative -a 'hello world' -b -c
-a flag value = 'hello world'
-b flag was set
unknown flag '-c'

Similar to the first case, but with a valid long flag that requires an argument (that isn't given).  It also contains an unknown flag (and the unknown flag case had the exit commented out).

$ getopts-alternative -a 'hello world' -b -c --a-long
-a flag value = 'hello world'
-b flag was set
unknown flag '-c'
--a-long value = ''

Again, a long flag is given that requires an argument that also isn't given.  So, the next flag is interpreted as an argument and a warning is produced.

$ getopts-alternative -a 'hello world' -b -c --a-long --b-long
-a flag value = 'hello world'
-b flag was set
unknown flag '-c'
warning, argument value looks like a flag!
--a-long value = '--b-long'

The only thing 'wrong' here is that an unknown flag was given and it didn't exit.

$ getopts-alternative -a 'hello world' -b -c --a-long 'never forget' --b-long
-a flag value = 'hello world'
-b flag was set
unknown flag '-c'
--a-long value = 'never forget'
--b-long was set

Multiple unknown flags, exit commented out.

$ getopts-alternative -a 'hello world' -b -c --a-long 'never forget' --b-long -d
-a flag value = 'hello world'
-b flag was set
unknown flag '-c'
--a-long value = 'never forget'
--b-long was set
unknown flag '-d'

A minor change, testing '-a-long' instead of '--a-long' to ensure multiple names can be used for the same case.

$ getopts-alternative -a 'hello world' -b -c -a-long 'never forget' --b-long -d
-a flag value = 'hello world'
-b flag was set
unknown flag '-c'
--a-long value = 'never forget'
--b-long was set
unknown flag '-d'

Various flags given out of order.

$ getopts-alternative -b -c -a-long 'hello world' -a 'never forget' 
-b flag was set
unknown flag '-c'
--a-long value = 'hello world'
-a flag value = 'never forget'

Saturday, June 21, 2014

Basic guide for setting up virtual machines using QEMU/KVM on Fedora 20

The purpose of this guide is simply to get started using QEMU/KVM with Fedora 20. There is no need to install and boot from a special kernel. Fedora has KVM support built in which makes it rather easy. However, the tools required to install and maintain virtual machines are *not* installed by default. There are quite a few other prerequisites and post installation details that are outside the scope of this article, too.

For now, I think it's enough to say that my host machine is a quad-core x64 system with 16G of RAM and a few hundred gigs of local storage.  It doesn't take much, so let's begin!

While this step isn't required, my opinion is that it's best to begin with the most up-to-date Fedora base packages ...

sudo yum update

 ... and a reboot.

sudo init 6

To begin using the QEMU/KVM support built into the kernel (via libvirtd), I've chosen the following packages as the starting point ...

qemu-kvm
qemu-kvm-tools
virt-dmesg
virt-install
virt-manager
virt-top
virt-v2v
virt-viewer
virt-what
virt-who

The packages are all available from the fedora repository and can be installed with yum. It will determine all of the dependencies (about 135M) ...

sudo yum install qemu-kvm qemu-kvm-tools virt-dmesg virt-install virt-manager virt-top virt-v2v virt-viewer virt-what virt-who 

It's not a bad idea to verify the the packages were actually installed ...

rpm -q qemu-kvm qemu-kvm-tools virt-dmesg virt-install virt-manager virt-top virt-v2v virt-viewer virt-what virt-who 

--begin rpm -q output--
qemu-kvm-1.6.2-6.fc20.x86_64
qemu-kvm-tools-1.6.2-6.fc20.x86_64
virt-dmesg-0.3.0-10.fc20.x86_64
virt-install-1.0.1-3.fc20.noarch
virt-manager-1.0.1-3.fc20.noarch
virt-top-1.0.8-7.fc20.x86_64
virt-v2v-0.9.0-5.fc20.x86_64
virt-viewer-0.6.0-1.fc20.x86_64
virt-what-1.13-2.fc20.x86_64
virt-who-0.8-9.fc20.noarch
--end rpm -q output--

Another reboot (is not necessarily required, but it can't hurt either) ...

init 6

... and the system should be ready to create virtual machines!

The virt-manager (GUI) and virt-install (CLI) are the utilities used to install VMs. By default, everything ends up in /var/lib/libvirt but I find it's easier to have a symlink such as ...

ln -s /var/lib/libvirt /vm

... but that's not required, either, and ultimately your choice.

The virt-manager (GUI) is fairly self explanatory, I think. It provides many options to choose from when creating VMs. It's also possible to modify existing VMs.  Typically, I use the virt-manager wizard to create the first virtual machine, point it at an ISO image to install the OS, and then go from there.

A graphical (or text based) console window to the VM can be opened via virt-manager.  Or, if the VM is already created then the virt-viewer utility can also be used to connect to the virtual machine's (graphical) console.  For example ...

virt-viewer centos6-1

... will connect to the VM named 'centos6-1' (if it exists).  The primary advantage is that virt-viewer isn't as resource intensive as virt-manager and it still provides the necessities such as buttons to turn the VM on/off and/or pause it (etc).

After you've been around the block with virt-manager a few times, I highly recommend learning to use virt-install instead.  It's the equivalent command line utility and significantly more capable once you get the hang of things. 
 
Other utilities that are useful ...

virt-clone
virt-convert
virt-dmesg
virt-host-validate
virt-image
virt-manager
virt-p2v-server
virt-pki-validate
virt-top
virt-uname
virt-viewer
virt-what
virt-who
virt-xml
virt-xml-validate


... and fun!

Wednesday, July 3, 2013

logging new connections with iptables

INSTALL METHOD #1 - iptables is already started & running (live update)

1) Backup existing /etc/sysconfig/iptables

cp /etc/sysconfig/iptables /etc/sysconfig/iptables.pre-LOGNEW-start

2) Save running iptables config

service iptables save

3) Backup running /etc/sysconfig/iptables

cp /etc/sysconfig/iptables /etc/sysconfig/iptables.pre-LOGNEW-running

4) Create a new iptables chain called 'LOGNEW'

iptables -N LOGNEW
iptables -I LOGNEW 1 -m limit --limit 2/min -j LOG --log-prefix "iptables-new: "
#iptables -I LOGNEW 1 -m iprange --src-range 127.0.0.1-127.0.0.255 -j RETURN # disables logging loopbacks
#iptables -I LOGNEW 1 -m iprange --dst-range 223.0.0.1-223.0.0.255 -j RETURN # disables logging multicasts
#iptables -I LOGNEW 1 -m iprange --dst-range 224.0.0.1-224.0.0.255 -j RETURN # disables logging multicasts

5) For all INPUT packets, forward 'NEW' connections to the 'LOGNEW' chain

iptables -I INPUT 1 -m state --state NEW -j LOGNEW

6) Save running iptables config

service iptables save

7) Validate running iptable config

service iptables restart
iptables -S

Verify the following lines exist in the output of iptables -S:

...
-N LOGNEW
-A INPUT -m state --state NEW -j LOGNEW
...
-A LOGNEW -m limit --limit 2/min -j LOG --log-prefix "iptables-new: "


Check the output of /var/log/messages

grep iptables-new: /var/log/messages

-------------------------------------------------------------------------------------------------------------------------------------------------------


INSTALL METHOD #2 - manually modify /etc/sysconfig/iptables

1) Backup existing /etc/sysconfig/iptables

cp /etc/sysconfig/iptables /etc/sysconfig/iptables.pre-LOGNEW-start

2) Edit /etc/sysconfig/iptables

vi /etc/sysconfig/iptables

Below the line starts with ":OUTPUT ACCEPT *", add the following line
:LOGNEW - [0:0]

As the very first statement to the INPUT filter (lines beginning with "-A INPUT ..."), add the following line
-A INPUT -m state --state NEW -j LOGNEW

Above the line begins with "COMMIT", or below the very last statement to the FORWARD filters (lines beginning with "-A FORWARD"), add the following line
# to filter noise, add RETURN (don't log) statements prior to -j LOG
-A LOGNEW -m limit --limit 2/min -j LOG --log-prefix "iptables-new: "

REMOVAL METHOD #1 - with iptables running (live update)

1) Remove the INPUT rule

iptables -D INPUT -m state --state NEW -j LOGNEW

2) Remove the LOGNEW links

while `iptables -D LOGNEW 1`; do iptables -D LOGNEW 1; done

3) Remove the LOGNEW chain

iptables -X LOGNEW

Tuesday, July 2, 2013

unixtime.bash

The Solaris version of /bin/date does not support the '+%s' argument whereas GNU's date does.

According to (GNU) man date, it provides the following:

       %s     seconds since 1970-01-01 00:00:00 UTC

Of course, this is also known as UNIXTIME or Epoch Time and is very useful for determining the difference between two dates. 

Necessity being the mother of invention, I developed the following bash script to provide a common mechanism for both Solaris (10+) and Linux (RHEL 5+) to calculate an epoch time based on the input given.  It is also compatible with anything else that can run the bash shell and has 'cut' somewhere in the path (e.g. CentOS, Debian, Ubuntu, BSD, Cygwin, etc.).

So now it's possible to write a single script that works on multiple UNIX variants without installing additional binaries.

Here it is ...

--cut--
#!/bin/bash -r

# Script to calculate an accurate UNIX/Epoch time with the only external dependency being 'cut'.

# 20130702, Joseph Tingiris (joseph.tingiris@gmail.com)


# This function uses strict input definitions and doesn't do much in the way of validating them.  The function will fail if
# the inputs are not integers (except for INPUT_TIMEZONE).  It will *not* fail if the integers are out of range.
#
# i.e. unixtime 1970 01 01 00 00 00 -0000
# or   unixtime 2013 07 02 13 35 33 -0400
function unixtime() {
    if [ "$1" == "" ]
    then
        # no arguments returns current unixtime (i.e. now)
        INPUT_YEAR=`date +%Y`
        INPUT_MONTH=`date +%m`
        INPUT_DAY=`date +%d`
        INPUT_HOUR=`date +%H`
        INPUT_MINUTE=`date +%M`
        INPUT_SECOND=`date +%S`
        INPUT_TIMEZONE=`date +%z`
    else
        INPUT_YEAR=$1
        INPUT_MONTH=$2
        INPUT_DAY=$3
        INPUT_HOUR=$4
        INPUT_MINUTE=$5
        INPUT_SECOND=$6
        INPUT_TIMEZONE=$7
    fi

    INPUT_YEAR=$((10#$INPUT_YEAR)) # force decimal (base 10)
    INPUT_MONTH=$((10#$INPUT_MONTH)) # force decimal (base 10)
    INPUT_DAY=$((10#$INPUT_DAY)) # force decimal (base 10)
    INPUT_HOUR=$((10#$INPUT_HOUR)) # force decimal (base 10)
    INPUT_MINUTE=$((10#$INPUT_MINUTE)) # force decimal (base 10)
    INPUT_SECOND=$((10#$INPUT_SECOND)) # force decimal (base 10)
        # basic input validation
    if [ "$INPUT_YEAR" == "" ]; then return 9; fi
    if [ "$INPUT_MONTH" == "" ] || [ $INPUT_MONTH -lt 1 ] || [ $INPUT_MONTH -gt 12 ]; then return 9; fi
    if [ "$INPUT_DAY" == "" ] || [ $INPUT_DAY -lt 1 ] || [ $INPUT_DAY -gt 31 ]; then return 9; fi
    if [ "$INPUT_HOUR" == "" ] || [ $INPUT_HOUR -gt 23 ] ; then return 9; fi
    if [ "$INPUT_MINUTE" == "" ] || [ $INPUT_MINUTE -gt 60 ]; then return 9; fi
    if [ "$INPUT_SECOND" == "" ] || [ $INPUT_SECOND -gt 60 ]; then return 9; fi
    if [ "$INPUT_TIMEZONE" == "" ]; then INPUT_TIMEZONE="-0000"; fi # If not set, set the default timezone to UTC (-0000)


    # 1 Determine the number of years since 1970 and multiply that by the number of seconds in a standard year (31536000 seconds).
    #
    YEARS_SINCE_1970=$(($INPUT_YEAR-1970))
    SECONDS_SINCE_1970=$(($YEARS_SINCE_1970*31536000))
    TIME_A=$SECONDS_SINCE_1970
    #echo "YEARS_SINCE_1970          : $YEARS_SINCE_1970"
    #echo "SECONDS_SINCE_1970        : $SECONDS_SINCE_1970"
   
   
    # 2 Determine the number of days and seconds that separate the input date and January 1st.
    #
    MONTH=0
    DAYS_SINCE_JAN1=0
    MONTHS_DAYS="31 28 31 30 31 30 31 31 30 31 30 31"
    for MONTH_DAYS in $MONTHS_DAYS
    do
        MONTH=$(($MONTH+1))
        if [ $MONTH -eq $INPUT_MONTH ]
        then
            #echo "MONTH: $MONTH [$MONTH_DAYS] *"
            DAYS_SINCE_JAN1=$(($DAYS_SINCE_JAN1+$INPUT_DAY-1))
            break
        else
            #echo "MONTH: $MONTH [$MONTH_DAYS]"
            DAYS_SINCE_JAN1=$(($DAYS_SINCE_JAN1+$MONTH_DAYS))
        fi
    done
    SECONDS_SINCE_JAN1=$(($DAYS_SINCE_JAN1*86400))
    TIME_B=$SECONDS_SINCE_JAN1
    #echo "DAYS_SINCE_JAN1           : $DAYS_SINCE_JAN1"
    #echo "SECONDS_SINCE_JAN1        : $SECONDS_SINCE_JAN1"

    # 3 Determine the time difference between the input time and midnight (00:00), in seconds.
    #
    SECONDS_SINCE_MIDNIGHT=$((($INPUT_HOUR*3600)+($INPUT_MINUTE*60)+$INPUT_SECOND))
    TIME_C=$SECONDS_SINCE_MIDNIGHT
    #echo "SECONDS_SINCE_MIDNIGHT    : $SECONDS_SINCE_MIDNIGHT"

    # 4 Find the number of leap years that have elapsed since 1970, and multiply that number by the number of seconds in a day (86400).
    #
    LEAP_YEARS_BEFORE_1970=$(((1970/4)-(1970/100)+(1970/400)))
    LEAP_YEARS_BEFORE_INPUT=$((($INPUT_YEAR/4)-($INPUT_YEAR/100)+($INPUT_YEAR/400)))
    LEAP_YEARS_SINCE_1970=$(($LEAP_YEARS_BEFORE_INPUT-$LEAP_YEARS_BEFORE_1970))
    LEAP_SECONDS_SINCE_1970=$(($LEAP_YEARS_SINCE_1970*86400))
    TIME_D=$LEAP_SECONDS_SINCE_1970
    #echo "LEAP_YEARS_BEFORE_1970    : $LEAP_YEARS_BEFORE_1970"
    #echo "LEAP_YEARS_BEFORE_INPUT   : $LEAP_YEARS_BEFORE_INPUT"
    #echo "LEAP_YEARS_SINCE_1970     : $LEAP_YEARS_SINCE_1970"
    #echo "LEAP_SECONDS_SINCE_1970   : $LEAP_SECONDS_SINCE_1970"

    # 5 Calculate the timezone offset, in seconds.
    #
    TZ_PLUS_MINUS=`echo $INPUT_TIMEZONE | cut -c 1-1`
    TZ_HOUR=`echo $INPUT_TIMEZONE | cut -c 2-3`
    TZ_MINUTE=`echo $INPUT_TIMEZONE | cut -c 4-`
    TZ_SECONDS=$((($TZ_HOUR*3600)+($TZ_MINUTE*60)))
    #echo "TZ_PLUS_MINUS             : $TZ_PLUS_MINUS"
    #echo "TZ_HOUR                   : $TZ_HOUR"
    #echo "TZ_MINUTE                 : $TZ_MINUTE"
    #echo "TZ_SECONDS                : $TZ_SECONDS"

    # 6 Determine the sum of times A, B, C and D, and add or subtract the timezone offset.
    #
    if [ "$TZ_PLUS_MINUS" == "-" ]
    then
        UNIXTIME=$((($TIME_A+$TIME_B+$TIME_C+$TIME_D)+$TZ_SECONDS))
    else
        UNIXTIME=$((($TIME_A+$TIME_B+$TIME_C+$TIME_D)-$TZ_SECONDS))
    fi

    echo "$UNIXTIME"

    # These will work to validate the UNIXTIME variable is correct, if 'date' supports the +%s flag (e.g. GNU/Linux but not Solaris).
    #INPUT_DATE="$INPUT_YEAR-$INPUT_MONTH-$INPUT_DAY $INPUT_HOUR:$INPUT_MINUTE:$INPUT_SECOND $INPUT_TIMEZONE"
    #echo "INPUT_DATE                : $INPUT_DATE"
    #echo "UNIXTIME                  : $UNIXTIME (`date -d @$UNIXTIME`)"
    #UNIXTIME_DATE=`date --date="$INPUT_DATE" +%s`
    #echo "UNIXTIME (date)           : $UNIXTIME_DATE (`date -d @$UNIXTIME_DATE`)"

}

unixtime $1 $2 $3 $4 $5 $6 $7
--cut--

Friday, June 21, 2013

afkd

aWAY fROM kEYBOARD dAEMON
[a]way [f]rom [k]eyboard [d]aemon

A daemon process to determine and control unix processes based on the time of the last key pressed to a given terminal.

With Linux or Solaris, a user can potentially log in via a variety of mechanisms.  There are multiple protocols and associated daemons that use terminals from difference sources.  Terminals are devices that provide enhanced input/output capabilities beyond what could be achieved with only regular files, pipes, and sockets.   For example, physically attached devices such as a keyboard and/or display will get allocated a tty when logging into the kernel via login(1).

ll terminals have a control process such as an associated shell (e.g. bash, csh, etc.).  Individual shells may provide an 'idle timeout', but these are not always effective (i.e. bash's TMOUT doesn't work if another process is controlling both stdin and stdou, such as vi, top, and a large number of other utilities). 

There is a need, regardless of the shell or any other running process (grouped by the same terminal), to ensure idle users who have been away from the keyboard for a specified number of minutes are indeed logged out.  Throughout the years there haven't been many programs written specifically for this function.  Yet, idle terminals are a clear security risk for most systems.  This is especially important for root and console sessions that have been left unattended.


Tuesday, November 13, 2012

CentOS 6 Anaconda / Kickstart PXE Boot & Install Server HOWTO


This page describes how to configure CentOS 6.3 as an Anaconda & Kickstart PXE boot and install server.   The following guide outlines the details for setting up both CentOS 6.3 x86_64 and CentOS 6.3 i386 on the same server.  With a bit more effort, it is also possible to install other Enterprise Linux versions using the same install server (e.g. CentOS 5.8 or any version of Red Hat Enterprise Linux).

Step 1)  Download the CentOS DVD ISOs


o   Keep these available, you'll need them again later in this process.

# 64-bit
wget http://www.gtlib.gatech.edu/pub/centos/6.3/isos/x86_64/CentOS-6.3-x86_64-bin-DVD1.iso
# 32-bit
wget http://www.gtlib.gatech.edu/pub/centos/6.3/isos/i386/CentOS-6.3-i386-bin-DVD1.iso

Step 2) Install CentOS 6.3


o   This will be the anaconda / kickstart server.
o   Start with a 'minimal' install.
o   Make sure to have at least 40GB of free space on / or mounted as /export.
o   This guide uses yum to install the required additional packages.
o   Internet (or a Satellite Server) access isn't necessarily required, but it does make it easier.
o   In lieu of Internet/Satellite access, you could use rpm to install the required packages, but it's more difficult and you will have to install all dependent packages manually.

Step 3) Configure the network interface(s)


o   Don't use dhcp for the anaconda / kickstart server's network interface.
o   Configure /etc/resolv.conf and /etc/nsswitch.conf appropriately for your environment.
o   Remember to check that Internet (or Satellite Server) access works (e.g. yum makecache)

vi /etc/sysconfig/network-scripts/ifcfg-eth1:

-- begin example /etc/sysconfig/network-scripts/ifcfg-eth1--
DEVICE="eth1"
BOOTPROTO="none"
NM_CONTROLLED="no"
ONBOOT="yes"
TYPE="Ethernet"
IPADDR=192.168.111.1
MASK=255.255.255.0
-- end example /etc/sysconfig/network-scripts/ifcfg-eth0--

Step 4) Disable iptables


o   This isn’t absolutely necessary, it’s just easier.

chkconfig iptables off
service iptables stop

Step 5) Disable selinux


·         Again, not necessary but easier.

vi /etc/selinux/config

-- begin example /etc/selinux/config--
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted
-- end example /etc/selinux/config--

Step 6) Install required packages


yum -y install wget syslinux syslinux-tftpboot xinetd tftp-server tftp dhcp httpd openssh-clients

Step 7) Create the anaconda directory structure


mkdir -p /export/anaconda/iso/CentOS
mkdir -p /export/anaconda/media
mkdir -p /export/anaconda/media/CentOS-6.3-x86_64
mkdir -p /export/anaconda/media/CentOS-6.3-i386
mkdir -p /export/anaconda/tftpboot
mkdir -p /export/anaconda/tftpboot/pxelinux.cfg
mkdir -p /export/anaconda/tftpboot/CentOS-6.3-x86_64
mkdir -p /export/anaconda/tftpboot/CentOS-6.3-i386
mkdir -p /export/anaconda/postinstall/
mkdir -p /export/anaconda/cfg/
ln -s /export/anaconda /anaconda

Step 8) Enable anaconda tftp boot via xinetd


vi /etc/xinetd.d/tftp

-- begin example /etc/xinetd.d/tftp--
# default: on
# description: The tftp server serves files using the trivial file transfer \
#       protocol.  The tftp protocol is often used to boot diskless \
#       workstations, download configuration files to network-aware printers, \
#       and to start the installation process for some operating systems.
service tftp
{
        socket_type             = dgram
        protocol                = udp
        wait                    = yes
        user                    = root
        server                  = /usr/sbin/in.tftpd
        server_args             = -s /export/anaconda/tftpboot
        disable                 = no
        per_source              = 11
        cps                     = 100 2
        flags                   = IPv4
}
-- end example /etc/xinetd.d/tftp--
  

Step 9) Configure the DHCP server


o   Note that the example dhcpd.conf below is not authoritative. 
o   For PXE boot to work, you must enter the correct hardware ethernet (MAC) address for each of the clients you want to kickstart.
o   This could be changed to authoritative for a given subnet, but it's safer to prevent *any* client from obtaining an IP address from this dhcp server.
o   Once a client is installed via kickstart, be sure to remove (or change) the MAC address in dhcpd.conf so it doesn't accidentally get re-installed.
o   Preventing fully automatic installs is generally a good practice.

vi /etc/dhcp/dhcpd.conf

-- begin example /etc/dhcp/dhcpd.conf--
ddns-update-style ad-hoc;

not authoritative;

option domain-name              "defaultdomain";

deny unknown-clients;
allow booting;
allow bootp;

option ip-forwarding    false;
option mask-supplier    false;

subnet 192.168.111.0 netmask 255.255.255.0 {
      option routers                  192.168.111.1;
      option domain-name-servers      192.168.111.1;
      option subnet-mask              255.255.255.0;
}

group {
      next-server                     192.168.111.1;
      filename                        "pxelinux.0";
      max-lease-time                  86400;
      default-lease-time              43200;
      min-lease-time                  43200;

      host anaconda-dhcp-200 {
              hardware ethernet 00:0c:29:1b:f7:84; # red
              fixed-address 192.168.111.200;
      }

      host anaconda-dhcp-201 {
              hardware ethernet 00:0c:29:fa:74:e5; # orange
              fixed-address 192.168.111.201;
      }

}
-- end example /etc/dhcp/dhcpd.conf--

Step 10) Copy the CentOS DVD media


o   Use the ISOs downloaded earlier.  Or, download them again.
o   (somehow) Copy them to /export/anaconda/iso/CentOS, e.g.

scp CentOS-6.3-x86_64-bin-DVD1.iso root@192.168.111.1:/export/anaconda/iso/CentOS
scp CentOS-6.3-i386-bin-DVD1.iso root@192.168.111.1:/export/anaconda/iso/CentOS

Or ...

cd /export/anaconda/iso/CentOS
# 64-bit
wget http://www.gtlib.gatech.edu/pub/centos/6.3/isos/x86_64/CentOS-6.3-x86_64-bin-DVD1.iso
# 32-bit
wget http://www.gtlib.gatech.edu/pub/centos/6.3/isos/i386/CentOS-6.3-i386-bin-DVD1.iso

Once the ISOs exist in /export/anaconda/iso/CentOS on the server ...

# 64-bit
cd /export/anaconda/media/CentOS-6.3-x86_64/
mount -o loop /export/anaconda/iso/CentOS/CentOS-6.3-x86_64-bin-DVD1.iso /mnt
cp -rp /mnt/* .
umount /mnt
# 32-bit
cd /export/anaconda/media/CentOS-6.3-i386/
mount -o loop /export/anaconda/iso/CentOS/CentOS-6.3-i386-bin-DVD1.iso /mnt
cp -rp /mnt/* .
umount /mnt

Step 11) Configure default boot menu


o   Adding the default option to boot to rescue mode can avoid fully automatic (accidental) installs.
o   Manual selection of the correct installation / kickstart configuration profile is my best practice.

vi /export/anaconda/tftpboot/pxelinux.cfg/default

-- begin example /export/anaconda/tftpboot/pxelinux.cfg/default--
timeout 3600
default menu.c32

menu title Automatic Anaconda / Kickstart Boot Menu

label 1
    menu label ^ 1) CentOS-6.3-x86_64 (64-bit)
    kernel CentOS-6.3-x86_64/vmlinuz
    append initrd=CentOS-6.3-x86_64/initrd.img ramdisk_size=15491 ip=dhcp ksdevice=bootif ks=http://192.168.111.1/anaconda/cfg/CentOS-6.3-x86_64-ks.cfg
    IPAPPEND 2

label 2
    menu label ^ 2) CentOS-6.3-i386 (32-bit)
    kernel CentOS-6.3-i386/vmlinuz
    append initrd=CentOS-6.3-i386/initrd.img ramdisk_size=15491 ip=dhcp ksdevice=bootif ks=http://192.168.111.1/anaconda/cfg/CentOS-6.3-i386-ks.cfg
    IPAPPEND 2

label 3
    menu label ^ 3) Rescue CentOS-6.3-x86_64 (64-bit)
    kernel CentOS-6.3-x86_64/vmlinuz
    append initrd=CentOS-6.3-x86_64/initrd.img ramdisk_size=15491 ip=dhcp repo=http://192.168.111.1/anaconda/CentOS-6.3-x86_64 lang=en_US.UTF-8 keymap=us rescue

label 4
    menu label ^ 4) Rescue CentOS-6.3-i386 (32-bit)
    menu default
    kernel CentOS-6.3-i386/vmlinuz
    append initrd=CentOS-6.3-i386/initrd.img ramdisk_size=15491 ip=dhcp repo=http://192.168.111.1/anaconda/CentOS-6.3-i386 lang=en_US.UTF-8 keymap=us rescue
-- end example /export/anaconda/tftpboot/pxelinux.cfg/default--

Step 12) Configure /etc/httpd/conf.d/anaconda.conf


vi /etc/httpd/conf.d/anaconda.conf

-- begin example /etc/httpd/conf.d/anaconda.conf--
# anaconda/kickstart
#

Alias /anaconda/cfg /export/anaconda/cfg
<Directory /export/anaconda/cfg/>
    Options Indexes FollowSymLinks
    Allow from All
</Directory>

Alias /anaconda/postinstall /export/anaconda/postinstall
<Directory /export/anaconda/postinstall/>
    Options Indexes FollowSymLinks
    Allow from All
</Directory>

Alias /anaconda /export/anaconda/media
<Directory /export/anaconda/media/>
    Options Indexes FollowSymLinks
    Allow from All
</Directory>
-- end example /etc/httpd/conf.d/anaconda.conf--

Step 13) Customize kickstart configuration files


o   These are working examples, but you should tailor them to your individual needs.

# 64-bit
vi /export/anaconda/cfg/CentOS-6.3-x86_64-ks.cfg

-- begin example /export/anaconda/cfg/CentOS-6.3-x86_64-ks.cfg--
# Example kickstart configuration file for a RHEL 6.3 x86_64 (64-bit) standard install.
#

install

# Specifies the language
lang en_US.UTF-8

# Specifies the keyboard layout
keyboard us

# Skip Red Hat subscriber key input
key --skip

# Forces the text installer to be used (saves time)
text

# Forces the cmdline installer to be used (debugging)
#cmdline

# Skips the display of any GUI during install (saves time)
skipx

# Used with an HTTP install to specify where the install files are located
url --url http://192.168.111.1/anaconda/CentOS-6.3-x86_64

# Assign a static IP address upon first boot & set the hostname
network --onboot yes --bootproto dhcp --hostname rhel63

# Give the second interface a DHCP address (if you are not using a second interface comment this line out)
#network --device eth1 --bootproto=dhcp

# Set the root password
rootpw r00tp@55w0rd

# Enable the firewall and open port 22 for SSH remote administration
firewall --enabled --port=22:tcp

# Setup security and SELinux levels
#authconfig --enableshadow --enablemd5
authconfig --enableshadow --passalgo=sha512

selinux --disabled

# Set the timezone
timezone --utc Etc/UTC

# Create the bootloader in the MBR with drive sda being the drive to install it on
bootloader --location=mbr --driveorder=sda,sdb --append=audit=1

# Wipe all partitions and build them with the info below
clearpart --all --initlabel

#Disk partitioning information
zerombr

# Create primary partitions
part /boot --fstype ext4 --size=500 --asprimary --ondisk=sda
part swap --size=4096 --asprimary --ondisk=sda
part pv.01 --size=100 --grow --asprimary --ondisk=sda
# use the entire second disk for swap
#part swap --size=100 --grow --ondisk=sdb

# Create LVM logical volumes
volgroup system --pesize=32768 pv.01
logvol  /var  --vgname=system  --size=8196  --name=var_vol
logvol  /tmp  --vgname=system  --size=2048  --name=tmp_vol
logvol  /  --vgname=system  --size=100  --grow  --name=root_vol

# reboot when installation completes
reboot

# Install the Core software packages, aka "minimal", plus a couple extras
%packages
# minimal
@core
@server-policy
#@base
#@network-file-system-client
#@server-policy
%end

%pre
# redirect debugging output to tty3
#exec < /dev/tty3 > /dev/tty3
#chvt 3

%post --log=/var/tmp/install.log
# redirect debugging output to tty3
#exec < /dev/tty3 > /dev/tty3
#chvt 3

echo "Creating CentOS-6.3-x86_64 post installation directory ..."
mkdir -p /opt/postinstall

echo "Downloading CentOS-6.3-x86_64 post installation files ..."
cd /opt/postinstall
wget http://192.168.111.1/kickstart/postinstall/CentOS-6.3-x86_64-postinstall.tgz
tar zxf CentOS-6.3-x86_64-postinstall.tgz
rm CentOS-6.3-x86_64-postinstall.tgz > /dev/null 2>&1

echo "Executing CentOS-6.3-x86_64 post installation script ..."
./CentOS-6.3-x86_64-postinstall >> CentOS-6.3-x86_64-postinstall.out 2>&1
echo "Done."
-- end example /export/anaconda/cfg/CentOS-6.3-x86_64-ks.cfg--

# 32-bit
vi /export/anaconda/cfg/CentOS-6.3-i386-ks.cfg

-- begin example /export/anaconda/cfg/CentOS-6.3-i386-ks.cfg--
# Example kickstart configuration file for a RHEL 6.3 i386 (32-bit) standard install.
#

install

# Specifies the language
lang en_US.UTF-8

# Specifies the keyboard layout
keyboard us

# Skip Red Hat subscriber key input
key --skip

# Forces the text installer to be used (saves time)
text

# Forces the cmdline installer to be used (debugging)
#cmdline

# Skips the display of any GUI during install (saves time)
skipx

# Used with an HTTP install to specify where the install files are located
url --url http://192.168.111.1/anaconda/CentOS-6.3-i386

# Assign a static IP address upon first boot & set the hostname
network --onboot yes --bootproto dhcp --hostname rhel63

# Give the second interface a DHCP address (if you are not using a second interface comment this line out)
#network --device eth1 --bootproto=dhcp

# Set the root password
rootpw r00tp@55w0rd

# Enable the firewall and open port 22 for SSH remote administration
firewall --enabled --port=22:tcp

# Setup security and SELinux levels
#authconfig --enableshadow --enablemd5
authconfig --enableshadow --passalgo=sha512

selinux --disabled

# Set the timezone
timezone --utc Etc/UTC

# Create the bootloader in the MBR with drive sda being the drive to install it on
bootloader --location=mbr --driveorder=sda,sdb --append=audit=1

# Wipe all partitions and build them with the info below
clearpart --all --initlabel

#Disk partitioning information
zerombr

# Create primary partitions
part /boot --fstype ext4 --size=500 --asprimary --ondisk=sda
part swap --size=4096 --asprimary --ondisk=sda
part pv.01 --size=100 --grow --asprimary --ondisk=sda
# use the entire second disk for swap
#part swap --size=100 --grow --ondisk=sdb

# Create LVM logical volumes
volgroup system --pesize=32768 pv.01
logvol  /var  --vgname=system  --size=8196  --name=var_vol
logvol  /tmp  --vgname=system  --size=2048  --name=tmp_vol
logvol  /  --vgname=system  --size=100  --grow  --name=root_vol

# reboot when installation completes
reboot

# Install the Core software packages, aka "minimal", plus a couple extras
%packages
# minimal
@core
@server-policy
#@base
#@network-file-system-client
#@server-policy
%end

%pre
# redirect debugging output to tty3
#exec < /dev/tty3 > /dev/tty3
#chvt 3

%post --log=/var/tmp/install.log
# redirect debugging output to tty3
#exec < /dev/tty3 > /dev/tty3
#chvt 3

echo "Creating CentOS-6.3-i386 post installation directory ..."
mkdir -p /opt/postinstall


echo "Downloading CentOS-6.3-i386 post installation files ..."
cd /opt/postinstall
wget http://192.168.111.1/kickstart/postinstall/CentOS-6.3-i386-postinstall.tgz
tar zxf CentOS-6.3-i386-postinstall.tgz
rm CentOS-6.3-i386-postinstall.tgz > /dev/null 2>&1

echo "Executing CentOS-6.3-i386 post installation script ..."
./CentOS-6.3-i386-postinstall >> CentOS-6.3-i386-postinstall.out 2>&1
echo "Done."
-- end example /export/anaconda/cfg/CentOS-6.3-i386-ks.cfg--

Step 15) Finish configuring the PXE boot environment


cp /usr/share/syslinux/pxelinux.0 /export/anaconda/tftpboot/
cp /usr/share/syslinux/menu.c32 /export/anaconda/tftpboot/
# 64-bit
cd /export/anaconda/tftpboot/CentOS-6.3-x86_64/
cp /export/anaconda/media/CentOS-6.3-x86_64/images/pxeboot/* .
# 32-bit
cd /export/anaconda/tftpboot/CentOS-6.3-i386/
cp /export/anaconda/media/CentOS-6.3-i386/images/pxeboot/* .

Step 16) Enable services


chkconfig dhcpd on
chkconfig httpd on
chkconfig xinetd on
service dhcpd restart
service httpd restart
service xinetd restart
reboot

Step 17) PXE Boot the install clients


o   Different hardware manufacturers have different methods for invoking PXE network booting.
o   Make sure to verify the client’s MAC address is in /etc/dhcp/dhcpd.conf and that you’ve restarted dhcpd (e.g. service dhcpd restart).
o   If everything’s correct then you should see screens similar to the following screen shots.