Linux Fun: Complete.

Paul Cobbaut

Linux Fun: Complete. by Paul Cobbaut Published 2007/09/10 12:01:42 Copyright © 2007 Paul Cobbaut (paul@cobbaut.be). When I think the book is ready for publishing, I for one will welcome the GNU FDL Overlords.

This book is meant to be used in an instructor-led training. For self-study, the idea is to read this book next to a working Linux computer so you can immediately do every subject, even every command. This book is aimed towards novice linux system administrators (and might be interesting and useful for home users that want to know a bit more about their linux system). However, this book is not meant as an introduction to linux desktop applications like text editors, browsers, mail clients, multimedia or office applications. More information and free .pdf available at http://cobbaut.be/lt/

Table of Contents
1. Introduction to Unix and Linux .................................................................................................... 1 1.1. Operating Systems History .................................................................................................. 1 1.1.1. AT & T Bell Labs .................................................................................................... 1 1.1.2. University of California, Berkeley .......................................................................... 1 1.1.3. GNU’s not Unix....................................................................................................... 1 1.1.4. Linux........................................................................................................................ 1 1.2. Licensing .............................................................................................................................. 2 1.2.1. Proprietary ............................................................................................................... 2 1.2.2. BSD ......................................................................................................................... 2 1.2.3. GNU General Public License (GPL)....................................................................... 2 1.2.4. Others... ................................................................................................................... 2 1.3. Current Distributions............................................................................................................ 2 1.3.1. About ....................................................................................................................... 3 1.3.2. Major Vendors of Unix............................................................................................ 3 1.3.3. Some BSD Distributions ......................................................................................... 3 1.3.3.1. FreeBSD...................................................................................................... 3 1.3.3.2. NetBSD ....................................................................................................... 3 1.3.3.3. OpenBSD .................................................................................................... 3 1.3.4. Linux Distributions.................................................................................................. 4 1.3.4.1. Red Hat ....................................................................................................... 4 1.3.4.1.1. Red Hat Linux ................................................................................ 4 1.3.4.1.2. Fedora Core .................................................................................... 4 1.3.4.1.3. Red Hat Enterprise Linux............................................................... 4 1.3.4.1.4. Differences 4.1 4.2 4.3 and 4.4....................................................... 4 1.3.4.1.5. Red Hat Enterprise Linux 5............................................................ 5 1.3.4.1.6. CentOS and Unbreakable Linux .................................................... 6 1.3.4.2. Ubuntu......................................................................................................... 6 1.3.4.3. Novell Suse ................................................................................................. 6 1.3.4.4. Debian ......................................................................................................... 6 1.3.4.5. Mandriva ..................................................................................................... 6 1.3.5. Solaris ...................................................................................................................... 6 1.3.5.1. Solaris 8 and Solaris 9................................................................................. 7 1.3.5.2. Solaris 10 .................................................................................................... 7 1.3.5.3. Nevada and Solaris Express ........................................................................ 7 1.3.5.4. OpenSolaris, Belenix and Nexenta ............................................................. 7 1.4. Certification.......................................................................................................................... 7 1.4.1. LPI: Linux Professional Institute............................................................................. 7 1.4.1.1. LPIC Level 1............................................................................................... 7 1.4.1.2. LPIC Level 2............................................................................................... 7 1.4.1.3. LPIC Level 3............................................................................................... 8 1.4.1.4. Ubuntu......................................................................................................... 8 1.4.2. Red Hat Certified Engineer ..................................................................................... 8 1.4.3. MySQL .................................................................................................................... 8 1.4.4. Novell CLP/CLE ..................................................................................................... 8 1.4.5. Sun Solaris............................................................................................................... 8 1.4.6. Other certifications .................................................................................................. 8

iii

2. Technical Introduction to Unix and Linux ................................................................................. 10 2.1. How an Operating System works....................................................................................... 10 2.2. Where to find help ? ........................................................................................................... 10 2.2.1. Manual Pages......................................................................................................... 10 2.2.2. Red Hat Manuals online ........................................................................................ 11 2.2.3. Searching the internet with Google ....................................................................... 11 2.2.4. Wikipedia............................................................................................................... 12 2.2.5. The Linux Documentation Project ........................................................................ 12 2.3. Discovering the classroom ................................................................................................. 12 3. The Linux File System Tree ......................................................................................................... 13 3.1. Unix is case sensitive ......................................................................................................... 13 3.2. The linux file system tree ................................................................................................... 13 3.2.1. Filesystem Hierarchy............................................................................................. 13 3.2.2. Filesystem Hierarchy Standard.............................................................................. 13 3.2.3. /bin binaries ........................................................................................................... 13 3.2.4. /boot static files to boot the system........................................................................ 14 3.2.5. /dev device files ..................................................................................................... 14 3.2.5.1. Common physical devices ........................................................................ 14 3.2.5.2. /dev/tty and /dev/pts .................................................................................. 15 3.2.5.3. /dev/null .................................................................................................... 15 3.2.5.4. /dev/zero.................................................................................................... 15 3.2.5.5. /dev/random .............................................................................................. 15 3.2.6. /etc Configuration Files ......................................................................................... 15 3.2.6.1. /etc/X11/.................................................................................................... 16 3.2.6.2. /etc/filesystems.......................................................................................... 16 3.2.6.3. /etc/redhat-release ..................................................................................... 16 3.2.6.4. /etc/skel/ .................................................................................................... 16 3.2.6.5. /etc/sysconfig/ ........................................................................................... 16 3.2.7. /home sweet home ................................................................................................. 17 3.2.8. /initrd ..................................................................................................................... 18 3.2.9. /lib shared libraries ................................................................................................ 18 3.2.9.1. /lib/modules .............................................................................................. 18 3.2.9.2. /lib32 and /lib64 ........................................................................................ 18 3.2.10. /media for Removable Media .............................................................................. 19 3.2.11. /mnt standard mount point................................................................................... 19 3.2.12. /opt Optional software ......................................................................................... 19 3.2.13. /proc conversation with the kernel....................................................................... 19 3.2.13.1. /proc/cmdline .......................................................................................... 22 3.2.13.2. /proc/filesystems ..................................................................................... 22 3.2.13.3. /proc/interrupts........................................................................................ 22 3.2.13.4. /proc/kcore .............................................................................................. 23 3.2.13.5. /proc/mdstat............................................................................................. 24 3.2.13.6. /proc/meminfo......................................................................................... 24 3.2.13.7. /proc/modules.......................................................................................... 25 3.2.13.8. /proc/mounts ........................................................................................... 25 3.2.13.9. /proc/partitions ........................................................................................ 26 3.2.13.10. /proc/swaps ........................................................................................... 26 3.2.14. /root the superuser’s home................................................................................... 27 3.2.15. /sbin system binaries............................................................................................ 27 3.2.16. /srv served by your system .................................................................................. 27 3.2.17. /sys Linux 2.6 hot plugging ................................................................................. 27

iv

3.2.18. /tmp for temporary files ....................................................................................... 28 3.2.19. /usr Unix System Resources................................................................................ 28 3.2.20. /var variable data.................................................................................................. 28 3.2.20.1. /var/lib/rpm ............................................................................................. 28 3.2.20.2. /var/spool/up2date................................................................................... 28 3.3. Working with directories.................................................................................................... 28 3.3.1. pwd ........................................................................................................................ 29 3.3.2. cd ........................................................................................................................... 29 3.3.3. ls ............................................................................................................................ 31 3.3.4. mkdir...................................................................................................................... 32 3.3.5. rmdir ...................................................................................................................... 33 3.3.6. pushd and popd...................................................................................................... 33 3.3.7. Practice: Working with directories ........................................................................ 34 3.4. Working with files .............................................................................................................. 35 3.4.1. file .......................................................................................................................... 35 3.4.2. touch ...................................................................................................................... 35 3.4.3. rm........................................................................................................................... 36 3.4.4. cp ........................................................................................................................... 37 3.4.5. mv .......................................................................................................................... 37 3.4.6. Practice: Working with files .................................................................................. 38 3.5. File contents ....................................................................................................................... 39 3.5.1. head........................................................................................................................ 39 3.5.2. tail .......................................................................................................................... 40 3.5.3. cat .......................................................................................................................... 40 3.5.4. tac .......................................................................................................................... 41 3.5.5. more and less ......................................................................................................... 42 3.5.6. strings .................................................................................................................... 42 3.5.7. split ........................................................................................................................ 42 3.5.8. Practice: File contents............................................................................................ 43 3.5.9. Solution.................................................................................................................. 43 4. Bash, the default Red Hat shell ................................................................................................... 45 4.1. Shell Expansion.................................................................................................................. 45 4.1.1. Control Operators .................................................................................................. 45 4.1.2. Comment ............................................................................................................... 47 4.1.3. White space squeezing .......................................................................................... 47 4.1.4. File globbing.......................................................................................................... 48 4.1.5. Shell variables........................................................................................................ 50 4.1.6. set, unset and env................................................................................................... 51 4.1.7. Bash shell options.................................................................................................. 52 4.1.8. Exporting variables................................................................................................ 52 4.1.9. Delineate variables ................................................................................................ 53 4.1.10. Escaping .............................................................................................................. 53 4.1.11. Shell embedding .................................................................................................. 54 4.1.12. Shell alias............................................................................................................. 55 4.1.13. Displaying shell expansion.................................................................................. 55 4.2. Practice: Discover Bash ..................................................................................................... 56 4.3. bash shell history................................................................................................................ 59

v

........................................................ 62 5..................1.............. sudo ......................................................2.................................... Searching (/ ?) ....................2.................................... /usr/bin/passwd .......................................................................................................... usermod ................................................................................................. Setting octal permissions ..........................................6............$ s/foo/bar/g ).....................3...........................................................................................5........................... 68 6...................................................................................................................................... /etc/skel/ ................................................ 77 7......................................... Setting permissions ........ /etc/login...... vim (vi improved)...........................13.............................................................................................................. 63 5...1. 62 5...................... 67 6................. 63 5..9....... The sticky bit......................... 62 5..................................... 77 7...... chsh .....11.......... gpasswd ...................................2............. Setting options.............................. 69 6....................... who and whoami ................................ Cut... Undo and repeat(u ................................. Reading permissions .. copy and paste lines (3dd 2yy) ...............5. 75 7.........6........... 62 5................................................... 67 6..............................8....................5....................1....................................................................................................................................1.............................. Users and groups.....................3.................................................................11.............................................................................. 61 5..................2............................................................ 80 vi ...................... su .........................3...........................................................................................................................................15............ Cut...........................................................................7.............................. 67 6.................. 63 5.............1.......................................................................................................................12................................. Practice: Users and groups ...... Practice.................................................... usermod ............. 72 6................. Replace all ( :1................... 67 6.............................................. /etc/passwd ..... 68 6.......7........... id....................... 68 6.....................13................... 70 6........................... SetGID on directories...............defs ...................................... Reading files (:r :r !cmd) ......................................................................... 72 7...5............................................................................. 62 5................................. encryption with crypt........ 79 7.......................1...................... Users.......................3................................................................................................................. Practice: Advanced File Permissions ......................... 61 5...................... 75 7..........................................................................................3.......... 62 5.....3....................................... SetGID and SetUID on regular files......................10.................................................2........................6... vipw....................................................................................16........................................... Practice: File Permissions .........4...............................................4........... chage ...... password encryption............ 66 6......................................................................1.............................................2.............................2...............8....3.............................................................................................................. 61 5.......................10..........................................2.. Groups ............ 65 6............... copy and paste a line (dd yy p P).................... 71 6.. Save (or not) and exit (:w :q :q! ) .......................................................15...................................................................................... 64 6............................ 69 6.......................................................7......................... useradd.................................. File Permissions ........................................................................... umask .... 79 7...................... Solutions to the Practice..........14..................)............................................................................................ 78 7........... 66 6.. 71 6...................... 70 6................................................................................. 63 5....8.................................................................................................... 61 5.... 65 6........................................................... encryption with passwd . Start and end of a line (0 or ^ and $)....................... Words (w b)...............................................12................ 61 5........................... 77 7........ 65 6................................................................................................................1.....................................................................3................................................14.................................. 66 6........ Replace and delete a character (r x) ..................................... Start typing (a A i I o O) ............................. 61 5.... encryption with openssl..................................................................1........................ 75 7....................................... command mode and insert mode ..............9..................................................................9........................................................ 65 6.............................4...... Join two lines (J) ............................................ 72 6......... 70 6..................................................... Passwords ..................................................................

....................................................................... append.......................... Confusing I/O redirection .......................5............................................................................ 93 9.............................................................................................. Hello World ............. Introduction to scripting ........................ 99 10........................................................ 84 8..........3.....5... 100 10.... 88 8.................................8...............................................1........................................................................................ 107 11..................................................................................................... 103 11........................................ 81 8................................................6...........................................3...................3.......6.............................. here document ....................... case....................................... output redirection................ 95 9................................................................................................. 109 11.......................................................... top.......................... 87 8....................2................................. signals................................................ error redirection .............. 86 8...... Pipes and filters .... Solutions to the Practice...................................... 83 8........................................................... Process Management ................................................................ grep.................................. More Bash................................3....... Practice................................................6....................................................................................... then then.............................................................................3...................................3...................................................................... ps ... priority and nice values .................................................................. if if................. 83 8................ 110 11.......5........ 109 11..........................................................2........................................................................................................................ Solutions............... let......................................... 94 9............................. 92 9............................................................................................................................... while loop.....................9.................................................................................................................................................................................................................... sourcing a config file ................................................................................. until loop .....................................................................................3.......9.............................. input redirection.........1............................................... 88 8............................................14............................................11.......................... Practice: more bash ....... 86 8................................................................ wc ....................................... Practice : scripts ..............3.................................. 105 11............ 104 11.... locate ............................................................. 83 8....3.........4................ 81 8.....................7.................. find ......3............................................................................................................. shopt ........................1................11..............................................2...............................1........................................................... 99 10................................................2...2.......................................... Variables....... 89 9..................... sort........ 101 10................................................................................... test [ ] ..................................................... 104 11...... tr ..............................7....... 106 11........... 82 8.........................4....16....... 91 9..................... or else ......................................................... jobs ......................................................................................................................... parameters ........................................................6......................................................8........................................ path...4............................................. noclobber ............... 108 11...............................................................................................................................7.................................................... 96 10.................................. tee ............................................15....................................... 85 8......... diff ........................................................ Shell ........ 98 10........................ Shell I/O redirection............. 99 10.......................................................................... 98 10...................... bash shell environment........ 103 11.. 101 10........... cut.................10...............................................5.. 91 9.... 100 10............... 110 vii ................................5........................................................................................................................................................... 95 9.........................................3...........10.13............................................................................................................................................... 101 10.....................................................................8..4................................................................ 93 9......... 98 10......................................................1................... for loop ........................................ runtime input ....................................................... 86 8.................................................... About processes ..................12........................................................................................8................ 82 8............................................................................................... uniq.............................................................................. 81 8.................................. 102 11... pipes ...............................................................................................................4.............

4..................................................................................... Checking a file system . IDE or SCSI ... swap .................. About file systems .......................................................................................................................................4........................... File Systems .. 111 11......................................7............. LPI 101 stuff.................... 113 11................5...........................................................................................6....................................... Hard disk devices ...................................... 112 11.......................................... other tools and filters........ 127 15.................... 123 14.... others..... Practice tools and filters ............................................................................ IO Ports....................................................................................3................... /proc/scsi/scsi ..........................................2............................................................................................................................................ 122 13... 115 12................................... Buses........................3............ 123 14. UDF ..................... 114 12.....9.......................................................................................................................2. Interrupts................. 118 13......................... 127 15...........1..............3.................... Practice File Systems ......16..........................2.................................. 116 13................................ Partition naming ......................................15........................................11.............................................................................................................1.4....... 120 13.................... Configure Fundamental BIOS Settings (LPI 1.............1) ............ other tools......7.........................................................2...........................................................................5............................................................................ fdisk......... 128 15..................... vfat . 115 12................ 127 15..4........... Partitioning new disks .........2.................................. DMA.......... Partitions ...................... 119 13.. hdparm ...................................................................1............................................................................6................................... 118 13............................................................................ ext2 and ext3....................10........................ 129 15............................................................................................................ 129 15..................................................................................................2...........................5...................................... ................................................................................................... Terminology ...................... 124 14..................................................1...............................11..................................2.......................... Disk Usage ........................ comm................... Practice Partitions.........................................................................................2..........................1..... 124 14.................... 128 15.............1..12... df .......... 115 12.............................8..... Tuning a file system .......................... dmesg ....................................................................................................................... 122 14............................................................................................. 123 14................................................................................ 116 12.............. 115 12.................... Erasing a hard disk ...........14...................................................................................................................... 121 13.............................17........................................................................1.................. 119 13.................................................2.................................1........ Solutions: tools and filters........ 127 15.... 123 14............. 131 viii ........................................................ Common file systems ....... Practice hard disk devices ............ fdisk -l .................... 127 15........................13...... Putting a file system on a partition. lsscsi . 127 15........................................................................................................................................ compress............................ 123 14............................................................................................ 121 13......................... 126 15................................................................................................................................... Device Naming........................................... 118 13.....7......... scsi_info ....................................... About Partitions ....1............................................1.......................................................................6................................... 112 11....................... ISO 9660.. od........................3....................... 113 11...............................................101.....................................2............................................. 130 15...........4...................................................................................................................5................................................................. 128 15............................... 118 13...................................................................................................... 120 13..................2........................................6..........3..................................................................... 128 15......

..4.............1.............................................................................1............................... 146 19........ 141 18..................................................... 137 18................................................ crontab........................................................................................... About syslog.4................................................................. Watching logs............................5.. About inodes ..................... Practice Scheduling................................................1...................................... Practice File Systems ...................... 150 19......... 133 17...... /var/log/btmp (lastb) ....... 147 19................................... /etc/inittab ..................................................................................1... Hard links ............... 150 19............................................1................................................................ 143 18......1............................... 146 19..2................................................. 138 18............3..4..... 135 17.. Changing the runlevel ..........................................................6......... 136 17..............................8..................................................... 132 16.....................3...........................................2.... /var/run/utmp (who)................................3........................................ 149 19...........7................3.......................................................................................................................................................................................................... su and ssh logins.................................................................7........................................................................................................................................... Practice..3..............3...5..................................................................................... Booting...................... getty ...................... Init ................................... Mounting local disks .... 135 17..............................................................2..............................2...............2......................................2............................................2.................................................................... 132 16.......................................... 150 19......................................................................................................................................................................................... rc scripts.......................2.................................................................................................. Scheduling . sysinit... System init ................................................................................... Facilities ..... Starting and stopping daemons ............................................................................................................................................................................. Runlevel. Login logging ..........................................3..............................2.. Levels.2................................................................................................................................................................................................. 153 ix ................................2..............................................................4..................... /var/log/lastlog (lastlog)......................3. /var/log/messages....................................................................................................................................... 140 18................................................. /var/log/wtmp (last) .................................3......................... Practice Links............................................................................... /var/log........................ Daemons.................................. 144 18. 141 18................ 151 20.........................................................4.. 144 19....... 148 19...................3....................................................6.................................................................... 139 18.....................................................5..................... 146 19....... 138 18........................1......................................1.1...............................1............................ 136 17................ 139 18......................................................1.. 153 20........................ 152 20. 146 19.................... 135 17...................... Syslogd daemon ...........3........2....................... 138 18..................2..................... 138 18....................... 144 18.......3................................ 146 19..................... 142 18........................ Logging .............. Displaying mounted file systems ................................3................................................................................................. Symbolic links......................................... File Links .................4........................................5................ 149 19................................................................ 132 16........................................... 143 18.................. Display the runlevel .......5........................................................ logger .. 140 18................... 147 19.................3..........3....... 146 19........................................................................ Configuration....................... Permanent mounts........ Practice Logging .............................................................................3..........................4.................................................................... 152 20........................... Mounting ........................16............................ 133 16.........3............. 139 18.......................................................................... 138 18.............................................6. Power and Ctrl-Alt-Del ......................................... About directories..........................2..... at...................................................................... 142 18.................................... more info ............ Rotating logs ........................ About logging ....................5........................3........................................................... 142 18................................3............ Actions......................

......................................... Ubuntu........................................................ Backup Types .........3.........................1..... 159 22..........7........................................... 155 21................................ 168 26....... Building a software RAID array ....................................................... 165 24.................. RAID levels.................................. Creating a swap file .................. 159 22................................................... 163 23............................................................................................................. 168 26................................................................2.....................................................3..... RAID 2..................................................... Swap space in /etc/fstab.1..................... backup devices .................... 163 23.... 166 25... Access Control Lists ......................5......................................................................................2.......................................... 162 23.......................1.........6..................................................... 159 22........... 159 22..................................................... 170 27..................................................... ... RAID ................... Practice RAID ...................................... 169 26........... An example of LVM......... Practice Installing software .............. 165 24....... Suse............2..............................................................................10......................................................................21............ 158 22............................................................2.......................................................................2.................... 174 27.......5............................ Hardware or software ............................................ Practice Disk quotas..... RAID 1+0 ............. Practice Memory ................1.................................................................... 158 22........... 173 27........2.... Practice LVM ................................................ RAID 5 ........................................... Installing Software.............. Disk quotas ...............................2....................1.......................................1................. RAID 0+1 ......................................................... 166 26......3................................................... 169 27.................................. 158 22................................. 175 27...7............................1...........4................................. many others ..................... 156 21.....................9......................... IDE tapes .............2.......................... dump and restore ........... dpkg and Aptitude (Debian............................................................................................................................................... 156 22....................1.................................................. 158 22.. 170 27...................................................................................................................... About lvm .............................................................1.......................................................................... Swap space ................................6..... 159 22...........................................................................................................................5............................ 171 27.................. Disk Quotas.................................................... tar ........................ Compression..........6.8..................................................................... 155 21.........................2. 3 and 4 ?................................................................................. Downloading software . Yum (Fedora) .. Compiling software...........................................................................................................................................................................1...... 170 27.................... 163 23............ 156 21..............2....................................... Logical Volume Management (LVM).... Memory..........................1......).......................... 171 27..................................................................................1.........................2............................. RPM (Red Hat.............. RAID 1 .......... JBOD .......................................8.. SCSI tapes ..........................4....................................................................................................................... 167 26.................3.................................4............................................ 170 27..............3........ About swap space ............................................................2.................. Backup .......... cpio........................................................................ Creating a swap partition................... RAID 6 ........ 158 22............................................................................... 164 24.......................................................1...........2.................................................................................. 155 21..............................................................2..... 158 22............ mt .1..2............ RAID 50 ................................................................... 158 22....................................... 155 21.......................... 167 26......................................2...........................................................4...2........................................ 159 22................ 167 26.....2......1.................................................................1............ 165 25.......)..........................................................2.............................................................................................................. ............ 158 22.... 170 27...................................................................................................................................... 176 x ................ Access Control Lists .................................4.......................................... dd..........................................................3....... RAID 0 ................................................

.................................6...4.... 192 30.......................3...4..................................................................................................................................1............ Command line tools for CUPS.................................................................................................4..2..27............ 180 28..................................................................................................................... many protocols ........................ /etc/sysconfig/network .......................... 186 29.................................. 180 28................................5.................................................................4............................................ mpstat ...........................3.................................4..........................................................5.....3...........................2.........................................................1........................ booting the system ... 197 31................................................4................................................................................................................................ 178 28................................................................. modprobe..................1.........................................5................................... 193 30......... preparing for a rescue boot.....4....2..................... 183 29....................................................... 181 28.........................................................................4. compiling a kernel....................2....................... 181 29..................................................1....................... 200 32...................... /etc/init....d/network(ing)..................................................................................................................................................................4............. 197 31.......................................................... 187 29................ kernel module management ........2................................................................. Normal kernel compilation............... 187 29........................................................................1.....................................................................................................................4.............3................................ CUPS............................. watch .......................................................................................... accept and reject ....................................5..........................4................................................................................... ntop.......... 187 29...............9............1......... lpstat and lpc.................... to GUI or not to GUI.....3... top............................... Practice TCP/IP.........................................3.................................................. 200 32................ 195 30.. /etc/sysconfig/network-scripts ......... Server performance monitoring ..................... Overview kernel compile ..........................................................................................1................... iostat ...... vanilla ....................... 193 30.................................. Internet and routers .................................... 179 28............ 188 29........................................7................................................................................3........................... 194 30............... Red Hat Enterprise Linux 4 specific... 181 28.................. 178 28..................................................................... lpr................ lpq .......................................4. 186 29...... 192 30.................. 197 31.....................4............ enable and disable............................ 193 30....................................... 194 30......... 202 xi ............. About CUPS.....................7............................................4....... /sbin/ifup and /sbin/ifdown .................................... 199 32. CUPS Administration ....................... 178 28.........................................4.......................................................... Practice backup .................. lpmove ........................................................................................................................................ vmstat ............................................................................................... 197 32...................3................................... /sbin/dhclient ...................................................... 195 30.................................................................................... free ...................................................................................... 183 29.............................................6...............................................................................................4..................... 193 30................................................................................ 199 32......................................................................2.................................... lsmod ......................................................................................6............. Compiling one module........................... 201 32........................................ 200 32.................... 189 30..........4... sadc and sar ........... lprm and cancel...................................................... IP address configuration ..................................... Overview of tcp/ip v4.. 176 28... 192 30.................................. TCP/IP .................................................................................. 197 31.8.................................... lpoptions .4........................................................................ 186 29............................................................... /sbin/ifconfig ...1..4.............................. 202 32......................................................2...........9... 183 29...................................................... 199 32..................................... iftop .............................................................8.1...........2............................ /etc/sysconfig................. Kernel Compilation ..........................6.............. CUPS Administration Access ..................... 188 29.............. 195 31....2................... 192 30..... 179 28.............................................3................

.....................10........................................................................................................................................................................................3.................................................................................................1.................................................2................................ Network Attached Storage (NAS)..............................32................2........................................................................ arp.6...................... /etc/hosts.............................. Mounting NAS .......................... 221 39........................................................................... 217 37................................ Practice IP Configuration .... 212 35....................................................... 214 36.............. 220 38................... 205 33..............................................................................................................7................. /sbin/route........ Practive VNC .............................................................................................................................................................. 211 35.......................4................................................................................... 214 36..3............................................................ VNC...................................... NFS: the Network File System ........................................... Binding multiple ip-addresses............. 224 40......9................................................................. 211 35.....................................................1............................. 205 33........................................................................ 223 40....................................4....................................................................................... About VNC .............. 211 35............................ 218 37....................................................................... client configuration................. Backup network configuration ... 222 39.................................................... Introduction to iptables ............ Practice SSH . VNC Client ........................................................................2.......................................3....................5.........1...... server configuration .... xinetd and inetd........................... VNC Server................ Troubleshooting ssh .....2...3. 219 38....................... Practice hostname resolution ............................................................................... Red Hat network settings backup........ 208 34.................2................................................................................................1..............2...................................2................................. Bonding two network cards ................................................................ 216 37......conf.............2..3.............. 224 xii ...............4........ NAS and NFS .............................................................2..3................2..................................4..................... Enabling extra ip-addresses.................................2... 217 37..................................................................................................................................... Practice NFS .......... 208 34......................................................................................................... 206 33... Setting the hostname ..............................3....... Practice........conf ......................... Name Resolution .............................................................................................. 217 37....... 217 37..........................................4...................... 210 35...... /etc/resolv.............................. The superdaemon xinetd .. 222 39....................................................... multihomed hosts .................................... 208 34................. protocol versions .......................... 206 33. Practice multihomed hosts ................... 222 39.................. 204 33......................................................... SSH Protocol versions..................... Practice iptables ....................................... 219 37... Introducing iptables............. 222 39................................................................................................................. 209 34........................1..... Secure Shell........................ 213 36........................................... 220 38.................................................................................................... 209 34..................... 218 37........... The superdaemon inetd ................................................................................. 214 36............... 207 34...........................................................................1.. OpenSSH ..........................5............................................................... inetd or xinetd ........................................ 204 32................. Passwordless ssh .............................................................1................................................................. X forwarding via SSH....................................................................... /etc/nsswitch.................................................................................................1................................................................ 214 36........................................... 205 33..........................................2......... ping............................4........ 209 34........................... 203 32.................................1..................8................... 203 32................................................................................................................................................

........................................................................................1................................... 249 45............................................................................................................ 236 43........................................ valid users ................................................................2.7..............................8........................................................3.. DHCP Server....... 241 44........................................... 225 41..................................................................... 247 45................................... 248 45....................2......................................................... 227 42.......................... Writable File Server .....................................................................2.... 231 43.................................... 238 43.....................1.......... Starting dhcpd ........................... 230 43...............4..... Installing Samba..... Samba Web Administration Tool (SWAT) ...........................................2................................................ NetBIOS name resolving .................... Authenticated User Access ........7................................................................ Introduction to Samba .. 230 42.........................................................6............................................. Practice........................41....... Is DHCP installed ?............ 250 45..................................... 227 41................. Caching only Name Server .................3.......................... 234 43.................................... 225 41.. 231 43...............8................................................. 251 45............................................................ 250 45.................3...........1.................................................. 231 43....... 231 43............................... 226 41....................................................... Starting the name server................. hide unreadable...........................................1......... Example subnet ...................................................................................................... 246 44.............................................................................................................5................................................................................................ Forcing a User Owner ..............5.. More about smbclient........................2........................................................................................... 228 42...2............................7................................................. named ..................3.........2.................. 251 xiii ..........................5............................... address leases .............. Practice..................................3................................................................6......................10............... 233 43................ testparm ..................................................................................................................................... read list ..........................................................................5................................................. smbclient .............. 239 44............................................4..... 251 45.................................1........................... 247 44.. 243 44......... invalid users ...........................................................................2...................... 225 41.............................................................. 243 44.............................................. Practice.................................................................................................. 235 43................................ Practice DNS............. Our first zone.............................9..... About dhcpd ............. bind. 226 41....................6.................................................. 228 42........................................................................ Verify installed version ....... 249 45.....................................................................................................2............. Domain Name System ........................................................ DNS server option....................................................................... About DHCP ... Practice dhcpd ..7................................................................ hosts allow .............................. 225 41.. 228 42......................................................................conf ............................................................ Introduction to BIND ...............6........... 245 44........................................................................ 228 42........................................................................................................... Example router ................... 250 45.4............................................... Frequently used share settings ....................... Practice.............................. Read Only File Server......................... hosts deny .................................................................... Host reservation .5...................................................... 225 41.......................... smbtree .............4..................................................................4......... 229 42..............10.......................................................6....... Documentation ....................... 227 41................................................................................................2.. 228 42...............................................................3.................... Samba daemons......................9................................ Simple Samba File Servers .............................................................. 251 45........................... Samba Servers with authentication and restrictions.......................2........................... create mask and inherit permissions..........................................1......................................................... 248 45.................................................................. 232 43................... 241 44................................7..................................................................... 226 41...................................2.... smb..2.................................................

........................................................................................................................................... Samba 4 ...................... 256 47........... Samba Print Servers..3.................................................................................................. 276 50............. Creating a table ................ more on ...........................................3........................ Samba Prining tips ..........................6................................htaccess .... Apache configuration .......................................................................................... 253 46............................................. Simple Unix SysV Print Server.............cnf .......................... 256 47...................... smb................................. 271 49............................... MySQL...................7.1................ 254 46....... Populating a table..................... 255 47......................................my..................................................5...........................................3...................................... 253 46....................... About......................................................... 281 xiv ..................................................................................................... 260 48...........2.................................... About Computer Accounts. 280 C............5......................................... 256 47....................................................................... About Domain Controllers......... 259 47........................................................................................6.....conf ...................... Practice..... Groups in NTFS acls.......... 272 50........ Samba Domain Member Server ............... 273 50.........................................................................................46......... Practice............ Securing directories with htpasswd and .................................................................. 278 B......................8.................................. Virtual hosts ....................................................................................................................................................... logon scripts .................... Shell shoveling wth netcat ..........................................................10............................2.................................................1.............. ~/........................... 265 48.......................................... Aliases and redirects .......................................................... Serving a BSD-style printer ......................................6.................................... Simple CUPS Print Server ............................... Users and Groups ............................................................... 267 49..... 264 48..................................... 271 49.................................................................................................................................conf .............htaccess ...................................8..................... 267 49..................... 275 50.. 256 47............................................................................1.. 253 46... Simple BSD Print Server ........................... 269 49...1........................................... 268 49............................................5....................................................2.......4................................................ Samba Domain Controller ....................................................... Samba 3 ........ 273 50.. 277 A......................... 262 48.........................3............................... MySQL users and Groups...........8............................................................................... 258 47...................................................... nsswitch...............................................4........ Apache.......... 258 47................................................................................5............................... 272 50............................ 253 46........................... Roaming Profiles.................. 273 50....... 274 50............................................................................................. Joining the Active Directory Domain .......................... Traffic ................................................................. 269 49................................... 257 47..........................3.......................... 256 47.............5................................................................................................................................................................................................................................................................................................................. 268 49......................................................7............ 272 50........................................ 260 47...................9...........1...................4.1.2...............3.............. 271 50................... Looking at databases and tables................................................................................................................................ The net share command ..... smb..................... 265 49............................... Creating a MySQL root user ..................................................................1.................. About password backends ..... Scripting mysql in bash....... 262 48...... Backup and restore of MySQL database.............................................2.......... Mediawiki backup and restore .......1.................................................................................................................4.................................................. Practice..................conf.......................... 272 50......................................................1................................. 263 48................................................................................ Practice........................... About MySQL..................2....................... winbindd.............4........... 256 47..........7......................

GNU’s not Unix Largely because of unhappiness with the restrictive licensing on existing Unix implementations.2. they rewrote all the Unix tools. This meant that every C programmer could make changes. Linux Where GNU/Hurd failed. they are not all volunteers. the Linux kernel succeeded! In 1991 a Finnish student named Linus Torvalds started writing his own operating system for his intel 80386 computer. but you can hardly call that kernel a finished product. aiming to create a complete Unix-like branch.4. until they had a complete Unix-like operating system. By 1978 about 600 computers were running Unix. FreeBSD and OpenBSD are three current Unix-like operating systems derived from the 1991 BSD Net/2 codebase. IBM. to make it portable to other computers. The GNU project aims to create free software. Sony. University of California. seperate from the two other (BSD and Bell Labs). the BSD (Berkeley Software Distribution) branch of Unix was completely separate from the Bell Labs Unix. Unix was made available to universities. Novell. Thanks to this.Chapter 1. Together with Douglas McIlroy they are seen as the creators of Unix. 1. In 1973 they decided to write Unix in C (instead of assembler).1. In January 2007 an estimated seventy million websites are running on a Unix-like web server. Unics (later renamed to Unix) was written for mini computers like the DEC PDP-series.1. thousands of developers are now working on the Linux kernel. but were not so happy with the restrictive licensing. Introduction to Unix and Linux 1. NetBSD. In January 1992. By 1991.1.1. Contrary to popular believe. Development of the GNU operating system started.3.1. 1.1. Microsoft Windows and Apple MacOSX all use source code from BSD. So during the eighties. Sun Solaris. Red Hat. including the full source code. The name Unix is a play on the Multics Operating System for large mainframe computers. Unix was open source software. Operating Systems History 1. Today big companies like Sun. Berkeley Students of Berkeley were happy to join in the development of Bell Labs Unix. Richard Stallman initiated the GNU Project in 1983. but it still required purchase of a license. Mister Torvalds is still the only one to decide what code gets accepted into the kernel. HP and others are actively paying developers to work on the Linux kernel. AT & T Bell Labs In 1969 Dennis Ritchie and Ken Thompson wrote UNICS (Uniplexed Information and Computing System) at Bell Labs. Today the GNU compiler gcc and most other GNU utilities (like bash) are among the most popular on many Unix-like systems. companies and the US government. Linus decided to release Linux under the GNU GPL. 1 . The official kernel of this project is GNU/Hurd. 1.

but you have to leave the copyright notice that refers to BSD.. and the GPL grants you the right to read and change the source code. and you are not authorized to look at or change the closed source code of the operating system. They essentially state that you can copy the software. The goal of the GPL is to guarantee that free software stays free. patents and extensive software licensing. like HP-UX.2.3. in other languages free software translates to vrije software (Dutch) or Logiciel Libre (French). even in court. or even better. the GPL allows you to distribute (sell or give away) that software. Whereas the free from free beer translates to gratis. But the person receiving or buying the software from you has the same rights. This software is usually protected by copyright.2. You can actually call the GPL a viral license because it spreads like a virus. Licensing 1. 2 . The GPL can protect software. In other words. Free as in freedom of speech.2.2.. You should read and understand them before using any software. You are not authorized to install or use these without paying a license to the owner. 1. And also. GNU General Public License (GPL) More and more software is being released under the GPL (in 2006 Java was released under the GPL). not to be confused with free as in not having to pay for your free beer. knowing that the software will be freely available to everyone.Chapter 1. There are many other licenses on software. then you are obligated to put the same license on the modifications (and provide the source code of your modifications). Everyone can work together on GPL software.1. Proprietary Some flavors of Unix.4. You are not authorized to distribute these copies to other people. IBM AIX and Sun Solaris 9 are delivered after purchase in binary form. This license gives a lot of freedom. 1.2. the GPL allows you to copy software. Briefly explained. should you decide to distribute modified versions of GPL software. but offers few protection to someone copying and selling your work.2. Introduction to Unix and Linux 1. 1. Others. BSD BSD style licenses are close to the public domain.

org and (until last year) ftp. usually called distributions. distributed on CD. Some BSD Distributions 1. FreeBSD FreeBSD is a complete operating system. Many distro’s have a central repository of approved software. Major Vendors of Unix We should at least mention IBM’s AIX. netcraft.Chapter 1. Installing software from outside the distro can sometimes be cumbersome and may void your warranty on the system.org/cartoons/?id=19990301&mode=classic here. About Unix comes in many flavors. only two vulnerabilities were found in the default install of OpenBSD. HP’s Tru64 (originally from DEC) and Apple’s MacOSX are more derived from the BSD branch.3. but the copyright owners did not approve the inclusion of this image in this course.com. Sun’s SunOS.1.2.3. Introduction to Unix and Linux 1. and is managed by an integrated package manager.userfriendly.net. 1. Typical among geeks are all the flame wars over which is the best distribution. Millions of websites are running on FreeBSD. including some big like yahoo.3.3.3.cdrom.3. A distribution (or in short distro) is a collection of software packages. OpenBSD Co-founder Theo De Raadt from NetBSD founded the OpenBSD project in 1994. I had this very funny image copied from http://ars.2.3. All the software in a distribution is supposedly thoroughly tested and integrates nicely into a whole. all are based on the original Unix from Bell Labs (Unix System V). online or pre-installed on computers. 1. NetBSD runs on many architectures and is often used in embedded devices. FreeBSD runs on many architectures and is considered to be reliable and robust. freebsd.3. The past ten years. Software is maintained (patched) by the distributor. php. NetBSD NetBSD development started around the same time (1993) as FreeBSD.3. But most Unixes today contain source code and implementations from both original Unix-branches.1. Current Distributions 1. 1.3. OpenBSD runs on 3 .3. Sun’s Solaris and Hewlett-Packards HP-UX. The kernel and all of the utilities are held in the same source code tree. OpenBSD is by far the most secure operating system in the world. 1.3. All source code is thoroughly checked.

Fedora Core Fedora is sponsored by Red Hat. Red Hat contributes a lot to the linux kernel and other free software projects.3. just take a look at the distrowatch. The company Red Hat. The company makes a profit of around one hundred million dollars a year.1. Red Hat Enterprise Linux Since 2005 Red Hat distributes four different RHEL variants. Fedora is a very popular and user friendly Linux-based distro. There is no official support from Red Hat.4.1. Entry-level Server and Workstation. 4 . Red Hat Redhat exists as a company since 1993.3.4. Fedora Core 7 was released May 2007. aimed towards home users. 1.4. 1. RHEL AS is for mission-critical computer systems. Red Hat does not give an explanation for the meaning of AS.3. Inc.1. For many years. It was one of the oldest common Linux distributions.com website.1.1 4. 1.4. but can nevertheless be influential. About every six months there is a new version of Fedora. Suse and Mandrake were considered the big three for end users. ES and WS.4. RHEL WS is for technical power user desktops and critical design. Today.4. Red Hat. you can see some differences (kernel and parted) between RHELv4 updates 2. Red Hat Desktop is for multiple deployments of single user desktops.3. 1.Chapter 1. decided to split Red Hat Linux into Fedora Core and Red Hat Enterprise Linux. The OpenBSD people also bring us OpenSSH. Fedora usually has more recent versions of kernel and applications than RHEL. They distribute Red Hat Enterprise Linux (RHEL) to companies and manage the Fedora project. Red Hat Linux Red Hat Linux was distributed from 1994 until 2003.2.1. Red Hat is still the biggest commercial linux vendor.3.3. RHEL ES is for small to mid-range servers. 1. 3 and 4. Red Hat Linux was the first distro to use the rpm package format. and is aimed toward home users. In the next three screenshots. Linux Distributions There are hundreds of linux distributions.1. 1. the most popular linux distro is Ubuntu.4. but it might be Advanced Server.3.2 4. Differences 4. RHEL is probably the most popular Linux-based distro on servers. Introduction to Unix and Linux sixteen different architectures and is commonly used for firewalls and IDS. Many other distro’s are originally derived from Red Hat Linux.3 and 4. selling support contracts.4 The differences between the RHEL 4 updates are minimal.

txt paul@RHELv4u3:~$ rpm -qa | sort > AllAppsRHELv4u3ES. The first is done on RHELv4u2.9-42.Chapter 1.6. Introduction to Unix and Linux paul@RHELv4u2:~$ cat /etc/redhat-release Red Hat Enterprise Linux ES release 4 (Nahant Update 2) paul@RHELv4u2:~$ uname -r 2.19-1.EL paul@RHELv4u2:~$ [paul@RHELv4u3 ~]$ cat /etc/redhat-release Red Hat Enterprise Linux ES release 4 (Nahant Update 3) [paul@RHELv4u3 ~]$ uname -r 2. Xen is a free virtual machine application that allows modified NetBSD and Linux to serve as host for a number of unmodified guest OS’ses. and then compared with comm.5. network storage and smartcard integration.EL paul@RHELv4u4:~$ rpm -qa | grep ^parted parted-1.EL paul@RHELv4u4:~$ The following screenshot shows a procedure to find all application versions.4.txt AllAppsRHELv4u3ES.9-22. RHEL 5 will also have better SELinux support.0.txt paul@laika:~$ scp RHELv4u2:~/All* .EL paul@RHELv4u2:~$ rpm -qa | grep ^parted parted-1. paul@RHELv4u2:~$ rpm -qa | sort > AllAppsRHELv4u2ES.6.6.txt -3 > diff_u2_u3.6. Beyond just virtualization.19-1.19-4. and lists all installed applications in alphabetical order.EL [paul@RHELv4u3 ~]$ paul@RHELv4u4:~$ cat /etc/redhat-release Red Hat Enterprise Linux AS release 4 (Nahant Update 4) paul@RHELv4u4:~$ uname -r 2.txt 100% 30KB 30.1.3.6.9-34. paul@rhelv4u3’s password: AllAppsRHELv4u3ES.9KB/s 00:00 paul@laika:~$ comm AllAppsRHELv4u2ES.6.3.19-1. One of the notable new features is the inclusion of Xen. Both results are saved in a file. The same is done on RHELv4u3.6.EL parted-devel-1.EL [paul@RHELv4u3 ~]$ rpm -qa | grep ^parted parted-1.txt 100% 31KB 30. 5 . clustering.3KB/s 00:00 paul@laika:~$ scp RHELv4u3:~/All* . Red Hat Enterprise Linux 5 Red Hat Enterprise Linux version 5 is available since March 2007. paul@rhelv4u2’s password: AllAppsRHELv4u2ES.EL parted-devel-1.txt paul@laika:~$ 1. and a way to compare any two installed RHEL servers.6.19-1.

based on debian and funded by South African developer and billionaire astronaut Mark Shuttleworth.4. Novell has signed a very controversial deal with Microsoft..6. and many people from the open source community are actively advocating to abandon Novell completely. . Debian Debian is one of the most secure linux distro’s.4. They are seen as the main competitor to Red Hat with their SLES (Suse Linux Enterprise Server) and SLED (Suse Linux Enterprise Desktop) versions of Suse Linux.3. Mandriva Mandriva is the unification of the Brazilian distro Connectiva with the French distro Mandrake. But Debian is also known to be a linux for advanced users.3.Chapter 1. CentOS and Unbreakable Linux Both CentOS and Oracle’s Unbreakable Linux are directly derived from RHEL. 1.4. let’s wait and see how many organizations will buy a complete solution from Oracle.) are derived from the Debian codebase. Red Hat is not really worried about this.. Ubuntu is probably the most popular Unix-like distribution on personal desktops. and thus can offer much better support.1. they aim to make a profit of selling support soon. but all references to Red Hat trademarks are removed. which is considered the best package management system. Some high profile open source developers have left the company because of this agreement.5. with support from the French government. Novell bought the German company Suse. not for beginners. since they develop a lot on Linux. Linux for Human Beings.4. 1. The company behind Ubuntu is Canonical. Ubuntu is giving away free (as in beer and speech) CD’s with Ubuntu.3. Many people consider Ubuntu to be the most user friendly Linux distribution. A lot of distributions (Ubuntu.3. It is known to be stable and reliable. Novell Suse A couple of years ago. Debian has aptitude.2. Unfortunately they seem slow at getting their act together. Companies are allowed to do this (GPL). Introduction to Unix and Linux 1. Similar to Fedora.4. The Oracle offer however is still very recent. Novell hosts the OpenSUSE project as a testbed for upcoming SLED and SLES releases. They are considered a user friendly distro. 6 .3. and are hoping to make a profit selling support (without having the cost to maintain and develop their own distribution). Knoppix. 1.4.3. 1. Ubuntu Ubuntu is a rather new distribution.

1. Nexenta (www. installation. Sun released the Solaris kernel under the CDDL.3. hoping this will happen.Chapter 1. 1. Future versions of the Solaris operating system are based on this source code. Introduction to Unix and Linux 1. Certification 1. just like IBM AIX and HP-UX. The goal of this GNU/Solaris project is to have the best linux desktop (Ubuntu) including the aptitude package manager running on a Sun Solaris kernel.4.gnusolaris. Solaris Express Community Edition is an official free binary release including open source OpenSolaris and some closed source technologies.org) looks like Ubuntu and feels like Debian. To pass level one. Solaris 1. Solaris Express Developer Edition is the same.5.5. a license similar to the GPL. 1. Belenix and Nexenta OpenSolaris is een open source development project (yes. OpenSolaris. thorough testing before release.4.4.4. Solaris 10 Solaris 10 is the officialy supported Sun distribution.5. LPIC Level 1 This is the junior level certification. Nevada and Solaris Express Nevada is the codename for the next release of Solaris (Solaris 11).5. Solaris 8 and Solaris 9 All Sun Solaris releases before Solaris 10 are proprietary binary only.5.3. updated twice a month without any support from Sun.1. it is only source code). You need to pass exams 101 and 102 to achieve LPIC 1 certification. 7 .1.3.3. networking and basic system administration skills. Another famous opensolaris based distro is Nexenta. you will need linux command line. and released twice a year. It is a free (as in beer) download.3.1.3. Sun releases binary patches and updates. but with some support.2. LPI: Linux Professional Institute 1. The Belenix LiveCD is based on OpenSolaris. Sun would like a community built around the solaris kernel. 1. user management. similar to the linux community.1. It is currently under development by Sun and is based on the OpenSolaris code. backup and restore.

firewall.org.2.4. 1.0 DBA (CMDBA). samba.4.lpi. To pass level two. 1. First they have to troubleshoot and maintain an existing but broken setup (scoring at least 80 percent).4.). web and ftp servers. including Samba. Ubuntu When you are LPIC Level 1 certified. you have to take a live practicum. You need to be LPIC 1 certified and pass exams 201 and 202 to achieve LPIC 2 certification. proxy. Introduction to Unix and Linux 1. The CMDEV is focused at database application developers..4.1.1.4. 1.0 Developer (CMDEV) and Certified MySQL 5. you can take a LPI Ubuntu exam (199) and become Ubuntu certified.Chapter 1. LPIC Level 2 This is the advanced level certification. mail. you will need to be able to administer medium sized linux networks. Both tracks require two exams each.4. news. MySQL There are two tracks for MySQL certification.3.3. LPIC Level 3 This is the senior level certification. You have to perform several tasks and are free to choose your method (commandline or YaST or . perl and others. Passing two exams for an operating system gets you the Solaris Certified Administrator for Solaris X title. No multiple choice involved.2.4. the CMDBA is for database administrators. Certified MySQL 5. To achieve this level you also need LPIC Level 2 and pass a specialty exam. 1. second they have to install and configure a machine (scoring at least 70 percent). 8 .4. Sun Solaris Sun uses the classical formula of multiple choice exams for certification. This is a VNC session to a set of real SLES servers. It contains one core exam (301) which tests advanced skills including ldap. 1. Novell CLP/CLE To become a Novell Certified Linux Professional. More info on www.5.4. 1. Red Hat Certified Engineers have taken a live exam consisting of two parts. The MySQL cluster DBA certification requires CMDBA certification and passing the CMCDBA exam.1. pam.. Red Hat Certified Engineer The big difference with most certs is that there are no multiple choice questions for RHCE.

6. CompTIA’s linux+ and Sair’s Linux GNU.4.Chapter 1. 9 . Introduction to Unix and Linux 1. Other certifications There are many other less known certs like EC council’s Certified Ethical Hacker.

1. so they don’t interfere with other applications. An operating system may start paging. Ah.. RAM modules and hard disks. A computer’s memory comes in different speeds and prices. Ordered from fastest to slowest we have: registers inside the CPU. using a part of the hard disk as memory storage.1. the faster. and giving control to the next process. paul@laika:~$ Manpages can be useful when you are switching a lot between different flavors of unix. processes and applications. Applications receive a vast amount of virtual address space from the operating system. applications seem to run at the same time.conf Reformatting syslog. to find those little differences in commands. before interrupting it. the operating system can support multiprocessing. How an Operating System works The tasks of an operating system include management of hardware. the more expensive. When more than one CPU is present in the system. Very often manpages also describe configuration files and daemons. memory. Where to find help ? 2. Manual Pages Most Unix tools and commands have pretty good man pages. 10 .. A process is compiled source code that is currently running on the computer. the operating system uses interrupts and device drivers. please wait. paul@laika:~$ man whois Reformatting whois(1). To manage the hardware. Type man followed by a command (for which you want help) and start reading. An operating system consists of a software kernel and a number of tools.Chapter 2.. paul@laika:~$ man syslog.2. This really enables applications to run simultaneously. For us humans. and can be considered a platform for applications. The operating system will provide multitasking features by giving every process a small amount of time (about 50ms max) to run on the CPU. 2.. and press q to quit the manpage. Technical Introduction to Unix and Linux 2. A monolithic kernel like Linux can dynamically load these in memory as modules. please wait. Only one process at a time can run on a CPU or processor. cache on the CPU.conf(5).2.

Searching the internet with Google Google is a powerful tool to find help about Unix. or anything else.redhat..conf (5) . Unfortunately. Here are some tricks. 2.Linux system logging utilities. Red Hat Manuals online Red Hat has a lot of info online at http://www. If you want to know more. please wait.2. paul@laika:~$ man -k syslog lm-syslog-setup (8) . Technical Introduction to Unix and Linux paul@laika:~$ man syslogd Reformatting syslogd(8). manual pages do not have the answer to everyhting.list system logfiles paul@laika:~$ By now you will have noticed the numbers between the round brackets. the information there is not always up to date. Search only pages from Belgium (or substitute .Setup and remove LOCALx facility for sysklogd syslog. man man will explain to you that these are section numbers. The man -k command (same as apropos) will show you a list of manpages containing your searchstring. syslogd-listfiles (8) .. Search for pages inside one domain 11 .com/docs/manuals/ in both pdf and html format.configure laptop mode to switch syslog. paul@laika:~$ man woman No manual entry for woman 2.. Look for phrases instead of single words.syslogd(8) configuration file syslogd (8) .Chapter 2. Unfortunately.2. RTFM (Read The Fantastic Manual).be for any other Top Level Domain).2..a shell command interface to the syslog(3) system log module syslog-facility (8) .3.conf based on power state logger (1) .

2.Chapter 2.4. free-content encyclopedia.3.2.wikipedia. The Linux Documentation Project On www. 12 . You have a good chance of finding a clear explanation by typing your search term behind http://en. Wikipedia Wikipedia is a web-based. faqs. 2.org/wiki/ like this example shows. howtos and man pages about Linux and many other programs running on Linux.org you will find a lot of documentation. Students should be able to log on to one or more (virtual) Linux computers and test connectivity to each other and to the internet. Its growth the past two years has been astonishing. 2.tldp. 2. Discovering the classroom It is time now to take a look at what we have in this classroom. Technical Introduction to Unix and Linux Search for pages not containing some words.5.

enter man hier to find information about the file system hierarchy. The linux file system tree All Unix systems have a directory structure that starts at the root directory. According to the FHS /bin/date should exist. In the screenshot below you see a lot of common unix commands like cat. it is primarily intended to be a reference and is not a tutorial on how to manage a Unix filesystem or directory hierarchy. Red Hat. 3. The root directory is represented by a slash. like this: / . cpio. For help about your machine. Filesystem Hierarchy There are some differences between the flavors of Unix. /bin binaries The /bin directory contains binaries for use by all users. date.2.-) 3.1.com/fhs/ we read "The filesystem hierarchy standard has been designed to be used by Unix distribution developers. [paul@RHELv4u3 ~]$ ls / bin dev home lib boot etc initrd lost+found [paul@RHELv4u3 ~]$ media misc mnt opt proc root sbin selinux srv sys tftpboot tmp usr var 3. cp. The Linux File System Tree 3.2. Everything that exists on your linux system can be found below this root directory. package developers. and /etc/hosts is different from /etc/Hosts (the latter one does not exist on a typical Unix). and /bin should contain /bin/cat.2. you’ll have to check with every developer and system administrator in the world .3. dd. You will find a bin subdirectory in many other directories.2. Let’s take a brief look at the contents of the root directory. Let’s take a look at the FHS. Unix is case sensitive Unix is case sensitive. Filesystem Hierarchy Standard On http://www.1. Maybe the FHS will make more Unix file systems unite in the future. A lot of these will be covered in this book." Below we will discuss a couple of root directories. and system implementors.pathname. grep and so on. Novell Suse. paul@laika:~$ ls /bin arch debconf-get loadkeys pidof sysfs 13 . 3. For a complete reference. Binaries are sometimes called executables. However. this means that FILE1 is different from file1. even Sun’s Solaris all aim to follow the Filesystem Hierarchy Standard (FHS).2. echo.Chapter 3.

Instead they are an interface for a device driver toward a (physical or special) device.) # # SATA or SCSI # paul@laika:~$ ls /dev/sd* /dev/sda /dev/sda1 /dev/sda2 # /dev/sda3 /dev/sdb /dev/sdb1 /dev/sdb2 14 . Below a screenshot of SATA device files on a laptop and then IDE attached drives on a desktop. On Linux systems you typically find the /boot/grub directory here. These files don’t change very often.1. The Linux File System Tree archdetect autopartition bash bunzip2 bzcat bzcmp bzdiff bzegrep bzexe bzfgrep bzgrep bzip2 bzip2recover bzless bzmore cat chgrp chmod chown cp cpio dash date dd df dir dmesg dnsdomainname echo ed egrep false fgconsole fgrep fuser get_mountoptions grep gunzip gzexe gzip hostname hw-detect ip kbd_mode kill ld_static list-devices ln login log-output ls lsmod lspci mapdevfs mkdir mknod mktemp more mount mountpoint mt mt-gnu mv nano nc netcat netstat parted_devices parted_server partman partman-commit perform_recipe ping ping6 ps pwd rbash readlink register-module rm rmdir rnano run-parts search-path sed select_mountopt select_mountpoint setpci setupcon sh sh.2.5. 3. (The detailed meaning of these devices will be discussed later.lst (the grub configuration file). but are not located on the harddisk. which defines the bootmenu that is being displayed before the kernel starts. /boot static files to boot the system The /boot directory contains all files needed to boot the computer. /dev device files Device files in /dev appear to be ordinary files.2.2. Common physical devices Common hardware such as hard disk devices are represented by device files in /dev.4. 3. This /boot/grub contains /boot/grub/menu.Chapter 3.distrib sleep stralign stty su sync tar tempfile touch true umount uname uncompress update-dev user-params vdir which xbrlapi zcat zcmp zdiff zegrep zfgrep zforce zgrep zless zmore znew 3.5.

2.conf /etc/ddclient. 3. /dev/tty and /dev/pts For example /dev/tty1 represents a terminal or console attached to the system. then your terminal will be represented as /dev/pts/1 (1 can be another number). /dev/null is not a good location to store all your backups .) When typing commands in a terminal that is part of a graphical interface like Gnome or KDE.conf /etc/ucf. paul@laika:~$ ls /etc/*.conf /etc/brltty. but you can read zeroes from it. (Don’t break your head on the exact terminology of ’terminal’ or ’console’. what we mean here is a commandline interface.2.conf /etc/libao.5. /dev/zero Another Linux special device is /dev/zero. These special devices can be very useful.5.conf /etc/scrollkeeper.4. The Linux File System Tree # IDE or ATAPI # paul@barry:~$ ls /dev/hd* /dev/hda /dev/hda1 /dev/hda2 /dev/hdb /dev/hdb1 /dev/hdb2 /dev/hdc Besides representing physical hardware.conf added as an extension.conf /etc/lftp. But there is much more to be found in /etc. Many times the name of a configuration files is the same as the application or daemon or protocol with .conf /etc/syslog. You cannot sent something to /dev/zero.5.2. /etc Configuration Files All of the machine-specific configuration files should be located in /etc. Technically speaking.2.5.2.conf /etc/ccertificates. which can be considered a source of zeroes. 3.6.conf /etc/ld. 3. 3. but nothing can be retrieved from it.so.conf /etc/uniconf. it has unlimited storage.-). /dev/null can be useful to discard unwanted output from commands. some device files are special. anything given to /dev/null will be discarded. /dev/null On Linux you will find special devices like /dev/null which can be considered a black hole. 3.3.conf 15 .2.conf /etc/cvs-cron.Chapter 3.conf /etc/ltrace.conf /etc/sysctl.conf /etc/logrotate.conf /etc/adduser. /dev/random This device acts as a random number generator on any Unix machine.5.

paul@RHELv4u4:~$ cat /etc/filesystems ext3 ext2 nodev proc nodev devpts iso9660 vfat hfs paul@RHELv4u4:~$ 3.conf /etc/hdparm.conf /etc/wvdial.conf paul@laika:~$ /etc/mke2fs.conf /etc/pnm2ppa.conf /etc/fdmount.1. then mount will first probe /etc/filesystems.conf /etc/updatedb.conf /etc/wodim. /etc/redhat-release This file contains the Red Hat version on most of the Red Hat and Red Hat derived systems.conf /etc/vnc. then mount will continue probing /proc/filesystems. /etc/filesystems When mounting a file system without specifying explicitly the file system.2. Mount will skip lines with the nodev directive.conf /etc/resolv. The Linux File System Tree /etc/debconf.conf /etc/netscsid.6.2.2.org foundation.6. paul@RHELv4u4:~$ cat /etc/redhat-release Red Hat Enterprise Linux AS release 4 (Nahant Update 4) paul@RHELv4u4:~$ 3.conf /etc/popularity-contest. /etc/X11/ The graphical display (aka X Window System or just X) is driven by software from the X.2.Chapter 3.conf.2. /etc/skel/ The skeleton directory /etc/skel is copied to the home directory of a newly created user.6.3.conf 3.conf /etc/nsswitch.conf /etc/usplash.conf /etc/inetd. The configuration file for your graphical display is /etc/X11/xorg. and should this file end with a single * on the last line. 3.conf /etc/uswsusp.conf /etc/host.4.conf /etc/kernel-img. 16 .conf /etc/deluser.conf /etc/pam.6.

Chapter 3.conf pand pcmcia pgsql prelink rawdevices rhn samba saslauthd selinux sendmail spamassassin squid syslog system-config-sec system-config-users system-logviewer tux vncservers xinetd The file /etc/sysconfig/firstboot tells the Red Hat Setup Agent to not run at boot time. For more console keyboard information. You can see hardware detected by kudzu in /etc/sysconfig/hwconf. The keyboard type and table are set in the /etc/sysconfig/keyboard file.p paul@RHELv4u4:~$ network networking network-scripts ntpd openib.B crond installinfo named desktop ipmi netdump diskdump iptables netdump_id_dsa dund iptables-cfg netdump_id_dsa. then simply remove this file. join the Red Hat Network and more. The Linux File System Tree 3.6. It will then create the /etc/sysconfig/firstboot file again. Kudzu is software from Red Hat for automatic discovery and configuration of hardware. We will discuss some of them in greater detail. root@RHELv4u4:/etc/sysconfig# cat keyboard KEYBOARDTYPE="pc" KEYTABLE="us" We will discuss the networking files in this directory in the networking chapter.5. which is not mentioned in the FHS. If you want to run the Red Hat Setup Agent at the next reboot. /etc/sysconfig/ This directory. loadkeys(1) and the directory /lib/kbd/keymaps/. paul@RHELv4u4:~$ cat /etc/sysconfig/firstboot RUN_FIRSTBOOT=NO The file /etc/sysconfig/harddisks contains some parameters to tune the hard disks. dumpkeys(1).2. create a user account. 17 . paul@RHELv4u4:~$ ls /etc/sysconfig/ apmd firstboot irda apm-scripts grub irqbalance auditd harddisks kernel authconfig hidd keyboard autofs httpd kudzu bluetooth hwconf lm_sensors clock i18n mouse console init mouse. and run chkconfig --level 5 firstboot on. The Red Hat Setup Agent allows you to install the latest updates. The file explains itself. check the manual pages of keymaps(5). The screenshot below is the /etc/sysconfig from RHELv4u4 with everything installed. contains a lot of Red Hat Enterprise Linux configuration files.

2.0. paul@pasha:~$ ls -d /home/paul/. So you might encounter directories named /lib32 and /lib64.0 /lib/libcap.Chapter 3.1. 3.so.so 3.so. the home directory of a user also serves as a location to store the user profile.so. It is common practice (but not mandatory) to name the users home directory after their username in the format /home/$USERNAME.9. like those found in /bin. 3.bash_history /home/paul/.2.so.9.so. /lib/modules Typically.2. Like in this example: paul@pasha:~$ ls /home geert guillaume maria paul tom Besides giving every user (or every project or group) a location to store personal files.* /home/paul/.lesshst /home/paul/. often use shared libraries located in /lib.0.so.bashrc /home/paul/..1 /lib/libcfont. The Linux File System Tree 3.ssh /home/paul/.10 /lib/libcidn.1 /lib/libcidn-2.9.Xauthority 3.5. /home/paul/.2. A typical Unix user profile contains a bunch of hidden files (files who’s filename starts with a dot).2.so.1 /lib/libconsole. /lib32 and /lib64 We are now (the year 2007) in a transition between 32-bit and 64-bit systems. /lib shared libraries Binaries.viminfo /home/paul/. /home/paul/.0 /lib/libcrypt-2. to clarify the register size used at compilation time of 18 .0 /lib/libcom_err.5.so /lib/libcap. Removing it causes a kernel panic during the next boot. Below a partial screenshot of the contents of /lib.2.so. The hidden files of the Unix user profile contain settings specific for that user.8. /home sweet home You will find a lot of locations with an extensive hierarchy of personal or project data under /home.bash_profile /home/paul/.0 /lib/libconsole.1.5. /initrd This empty directory is used as a mount point by Red Hat Enterprise Linux during boot time.2.0. paul@laika:~$ ls /lib/libc* /lib/libc-2.2 /lib/libcom_err.so.0. the kernel loads kernel modules from /lib/modules.7.so /lib/libcfont.

3.0. then it installs in /opt/wp.1. My current 64-bit laptop has some older 32-bit binaries and libraries for compatibility with legacy applications. but you might find some systems with add-on software installed in /opt.12.Chapter 3. If that is the case. etc subdirectories in /opt/$packagename/. /opt Optional software Most of my systems today have an empty /opt directory. It is actually a view on the kernel.10: ELF 64-bit LSB shared object. and a means to talk to the kernel 19 . but not taking up diskspace.10 /lib64/libcap. According to the FHS. will not be installed in /opt.2. paul@laika:~$ file /lib32/libc-2.10.so. \ version 1 (SYSV).5. stripped paul@laika:~$ file /lib64/libcap.so. stripped The ELF Executable and Linkable Format is used in almost every Unix-like operating system since System V.2. Solaris 9 does not have it. /media for Removable Media The /media directory serves as a mount point for removable media. for GNU/Linux 2. Solaris 10 does. /proc conversation with the kernel /proc is another special directory. \ version 1 (SYSV).13. lib. putting binaries in /opt/wp/bin and manpages in /opt/wp/man.11. digital cameras and various usb-attached devices. you could very well encounter systems running without this directory. 3. Intel 80386.1. Since /media is rather new in the Unix world. /mnt should only be used to temporarily mount something. AMD x86-64.2.5. or better on what the kernel sees. appearing to be ordinary files. /mnt standard mount point Older Unixes (and Linuxes) used to mount all kind of stuff under /mnt/something/. 3. The Linux File System Tree the libraries.so: ELF 32-bit LSB shared object.so /lib32/libc-2. If for example the package is called wp. meaning devices such as CD-ROM’s.6. Most of the default software which comes along with the distribution. the package should install all its files in the typical bin. paul@laika:~$ ls /media/ cdrom cdrom0 usbdisk 3.2. But you will most likely witness a lot of systems with more than one directory underneath /mnt used as a mountpoint for various local and remote filesystems. It is considered outdated. The screenshot uses the file utility to point out the difference.

.. The Linux File System Tree directly..1 root root 0 Jan 29 18:06 /proc/cpuinfo paul@RHELv4u4:~$ paul@RHELv4u4:~$ .time passes. paul@RHELv4u4:~$ mount -t proc none on /proc type proc (rw) When listing the /proc directory. meaning the files are constantly updated (A view on the kernel). You can see this by executing cat on files like /proc/cpuinfo.Chapter 3. you will see a lot of numbers (on any Unix). which contains information on the CPU. paul@RHELv4u4:~$ date Mon Jan 29 18:06:32 EST 2007 paul@RHELv4u4:~$ ls -al /proc/cpuinfo -r--r--r-. and some interesting files (on Linux) paul@laika:~$ ls /proc 1 2086 4548 5124 10 2096 4550 5142 11 2097 4553 5143 13830 2123 4554 5159 13844 2260 4555 5172 13845 2261 4853 5173 13870 2546 4954 5231 13891 2746 5 5232 153 3 5008 5237 17178 35 5010 5242 17361 36 5035 5356 183 37 5051 5386 184 3754 5052 5442 185 3757 5058 5484 186 38 5059 5485 187 3990 5066 5571 2 4 5079 5599 2061 4025 5084 5600 2084 4325 5091 5621 2085 4547 5109 5665 5692 5727 5741 5808 5822 5827 5852 5945 5946 5947 5948 5949 5982 5984 6 6003 6004 6005 6045 6048 6049 6051 6054 6056 6063 6064 6068 6071 6077 6080 6082 6085 6086 6090 6092 6093 6094 6111 6118 6125 6128 6198 6208 6243 6247 6251 6359 6362 6363 6476 7 7068 7148 7151 7156 7159 7161 7168 8 818 8199 8286 8747 8753 8848 9 acpi asound buddyinfo bus cmdline cpuinfo crypto devices diskstats dma driver execdomains fb filesystems fs ide interrupts iomem ioports irq kallsyms kcore key-users kmsg loadavg locks meminfo misc modules mounts mtrr net partitions scsi self slabinfo stat swaps sys sysrq-trigger sysvipc tty uptime version version_sig vmcore vmnet vmstat zoneinfo Let’s investigate the file properties inside /proc.. paul@RHELv4u4:~$ file /proc/cpuinfo /proc/cpuinfo: empty paul@RHELv4u4:~$ cat /proc/cpuinfo 20 . paul@RHELv4u4:~$ paul@RHELv4u4:~$ date Mon Jan 29 18:10:00 EST 2007 paul@RHELv4u4:~$ ls -al /proc/cpuinfo -r--r--r-.1 root root 0 Jan 29 18:10 /proc/cpuinfo Most files in /proc are 0 bytes. /proc is a proc filesystem. yet they contain data. sometimes a lot of data. Looking at the date and time will display the current date and time.

and on a Sony Playstation 3.000000MHz revision : 5.. here is /proc/cpuinfo on a Sun Sunblade 1000.000000MHz 5.. altivec supported 3192.54 Just for fun. [root@ps3 tmp]# uname -a Linux ps3 2. paul@pasha:~$ cat /proc/cpuinfo cpu : TI UltraSparc III (Cheetah) fpu : UltraSparc III integrated FPU promlib : Version 3 Revision 2 prom : 4. The Linux File System Tree processor vendor_id cpu family model model name stepping cpu MHz cache size fdiv_bug hlt_bug f00f_bug coma_bug fpu fpu_exception cpuid level wp flags bogomips : : : : : : : : : : : : : : : : : : 0 AuthenticAMD 15 43 AMD Athlon(tm) 64 X2 Dual Core Processor 4600+ 1 2398..628 512 KB no no no no yes yes 1 yes fpu vme de pse tsc msr pae mce cx8 apic mtrr pge mca cmov pat 4803.68 Cpu0ClkTck : 000000002cb41780 Cpu1Bogo : 498..20-rc5-dirty #58 SMP Thu Jan 18 13:35:01 CET 2007 ppc64 ppc64 ppc64 GNU/Linux [root@ps3 tmp]# cat /proc/cpuinfo processor : 0 cpu : Cell Broadband Engine.1 (pvr 0070 0501) processor cpu clock revision : : : : 1 Cell Broadband Engine.1 (pvr 0070 0501) 21 .2. altivec supported clock : 3192.6.2 type : sun4u ncpus probed : 2 ncpus active : 2 Cpu0Bogo : 498.Chapter 3.68 Cpu1ClkTck : 000000002cb41780 MMU Type : Cheetah State: CPU0: online CPU1: online .

then mount will first try to probe /etc/filesystems and then probe /proc/filesystems for all the filesystems in there without the nodev label. a lot of files in /proc/sys are writable. /proc/cmdline The parameters that were passed to the kernel at boot time are in /proc/cmdline. then both files are probed. some require root privileges. But some files are writable. paul@RHELv4u4:~$ cat /proc/filesystems nodev sysfs nodev rootfs nodev bdev nodev proc nodev sockfs nodev binfmt_misc nodev usbfs nodev usbdevfs nodev futexfs nodev tmpfs nodev pipefs nodev eventpollfs nodev devpts ext2 nodev ramfs nodev hugetlbfs iso9660 nodev relayfs nodev mqueue nodev selinuxfs ext3 nodev rpc_pipefs nodev vmware-hgfs nodev autofs paul@RHELv4u4:~$ 22 . 3.2. Let’s discuss some of the files in /proc.13. /proc/filesystems The /proc/filesystems file displays a list of supported file systems.13. paul@RHELv4u4:~$ cat /proc/cmdline ro root=/dev/VolGroup00/LogVol00 rhgb quiet 3.1. The Linux File System Tree timebase platform machine : 79800000 : PS3 : PS3 Most of the files in /proc are read only.2. If /etc/filesystems ends with a line containing nothing but a *. When you mount a file system without explicitly defining one.Chapter 3.2.

Chapter 3.2. /proc/kcore The physical memory is represented in /proc/kcore. paul@laika:~$ cat /proc/interrupts CPU0 CPU1 0: 860013 0 IO-APIC-edge 1: 4533 0 IO-APIC-edge 7: 0 0 IO-APIC-edge 8: 6588227 0 IO-APIC-edge 10: 2314 0 IO-APIC-fasteoi 12: 133 0 IO-APIC-edge 14: 0 0 IO-APIC-edge 15: 72269 0 IO-APIC-edge 18: 1 0 IO-APIC-fasteoi 19: 115036 0 IO-APIC-fasteoi 20: 126871 0 IO-APIC-fasteoi 21: 30204 0 IO-APIC-fasteoi 22: 1334 0 IO-APIC-fasteoi 24: 234739 0 IO-APIC-fasteoi NMI: 72 42 LOC: 860000 859994 ERR: 0 paul@laika:~$ timer i8042 parport0 rtc acpi i8042 libata libata yenta eth0 libata. Do not try to cat this file. /proc/interrupts On the x86 architecture.0G 2007-01-30 08:57 /proc/kcore 23 . ohci1394 ehci_hcd:usb1.13.2.13. saa7133[0] nvidia 3.3. this file displays the interrupts.4. The size of /proc/kcore is the same as your physical memory. uhci_hcd:usb2 saa7133[0]. plus four bytes.1 root root 2. the file looks like this. paul@laika:~$ ls -lh /proc/kcore -r-------. The Linux File System Tree 3. instead use a debugger. paul@RHELv4u4:~$ cat /proc/interrupts CPU0 0: 13876877 IO-APIC-edge timer 1: 15 IO-APIC-edge i8042 8: 1 IO-APIC-edge rtc 9: 0 IO-APIC-level acpi 12: 67 IO-APIC-edge i8042 14: 128 IO-APIC-edge ide0 15: 124320 IO-APIC-edge ide1 169: 111993 IO-APIC-level ioc0 177: 2428 IO-APIC-level eth0 NMI: 0 LOC: 13878037 ERR: 0 MIS: 0 paul@RHELv4u4:~$ On a machine with two CPU’s.

The Linux File System Tree paul@laika:~$ 3. With a RAID configured.Chapter 3. paul@RHELv4u4:~$ cat /proc/mdstat Personalities : unused devices: <none> paul@RHELv4u4:~$ 3.5.2. 64k chunk. the following is displayed.2.6. paul@RHELv4u4:~$ cat /proc/meminfo MemTotal: 255864 kB MemFree: 5336 kB Buffers: 42396 kB Cached: 159912 kB SwapCached: 0 kB Active: 104184 kB Inactive: 119724 kB HighTotal: 0 kB HighFree: 0 kB LowTotal: 255864 kB LowFree: 5336 kB SwapTotal: 1048568 kB SwapFree: 1048568 kB Dirty: 40 kB Writeback: 0 kB Mapped: 33644 kB Slab: 21956 kB CommitLimit: 1176500 kB Committed_AS: 82984 kB PageTables: 960 kB VmallocTotal: 761848 kB 24 ... /proc/meminfo You will rarely want to look at /proc/meminfo. algorithm 2 [3/3] [UUU] unused devices: <none> paul@RHELv4u2:~$ When there is no RAID present.13.13. paul@RHELv4u2:~$ cat /proc/mdstat Personalities : [raid5] md0 : active raid5 sdd1[2] sdc1[1] sdb1[0] 2088192 blocks level 5. it looks like this. /proc/mdstat You can obtain RAID information from the kernel by displaying /proc/mdstat.

The Linux File System Tree VmallocUsed: 2588 kB VmallocChunk: 759096 kB HugePages_Total: 0 HugePages_Free: 0 Hugepagesize: 4096 kB .Live 0xffffffff88a40000 exportfs 7808 1 nfsd.Live 0xffffffff88b21000 (P) vmmon 194540 0 . lockd and sunrpc.Live 0xffffffff88af0000 (P) paul@laika:~$ lsmod | grep vm vmnet 36896 13 vmmon 194540 0 paul@laika:~$ Some modules depend on others. In the following example. Live 0xffffffff88a2a000 sunrpc 185032 12 nfs. /proc/modules /proc/modules lists all modules loaded by the kernel.. You can display the same information with lsmod. The output would be too long to display here.lockd. so lets grep for a few.nfsd.2.nfsd. paul@RHELv4u4:~$ free -om total used Mem: 249 244 Swap: 1023 0 paul@RHELv4u4:~$ free 5 1023 shared 0 buffers 41 cached 156 3.nfsd sunrpc 185032 12 nfs..nfsd.since the free command displays the same information in a more user friendly output. paul@laika:~$ cat /proc/modules | grep vm vmnet 36896 13 .Chapter 3.lockd paul@laika:~$ 25 . paul@laika:~$ cat /proc/modules | grep nfsd nfsd 267432 17 . which tells us that vmmon and vmnet are both loaded.13.7. you can see that the nfsd module is used by exportfs. First vm (from Vmware). Live 0xffffffff889fb000 paul@laika:~$ lsmod | grep nfsd nfsd 267432 17 exportfs 7808 1 nfsd lockd 73520 3 nfs. Live 0xffffffff88a3d000 lockd 73520 3 nfs.

2. file system.nodiratime 0 0 /proc/bus/usb /proc/bus/usb usbfs rw 0 0 /sys /sys sysfs rw 0 0 none /dev/pts devpts rw 0 0 /dev/sda1 /boot ext3 rw 0 0 none /dev/shm tmpfs rw 0 0 none /proc/sys/fs/binfmt_misc binfmt_misc rw 0 0 sunrpc /var/lib/nfs/rpc_pipefs rpc_pipefs rw 0 0 paul@RHELv4u4:~$ 3. Verify with /proc/devices to link the major number to the proper device. You see the device.9. so it is always up to date and correct. But /proc/mounts displays what the kernel sees. read-only or read-write and two zero’s. /proc/mounts lists all the mounted file systems.2. /proc/swaps You can find information about swap partition(s) in /proc/swaps. The Linux File System Tree 3.nodiratime 0 0 none /dev tmpfs rw 0 0 /dev/root / ext3 rw 0 0 none /dev tmpfs rw 0 0 none /selinux selinuxfs rw 0 0 /proc /proc proc rw. /proc/mounts Like the mount command and the /etc/mtab file.10.2.13.Chapter 3.13. paul@RHELv4u4:~$ cat /proc/mounts rootfs / rootfs rw 0 0 /proc /proc proc rw. paul@RHELv4u4:~$ cat /proc/partitions major minor #blocks name 3 0 524288 3 64 734003 8 0 8388608 8 1 104391 8 2 8281507 8 16 1048576 8 32 1048576 8 48 1048576 253 0 7176192 253 1 1048576 paul@RHELv4u4:~$ hda hdb sda sda1 sda2 sdb sdc sdd dm-0 dm-1 3. mount point. their number of blocks and the device name in /dev. paul@RHELv4u4:~$ cat /proc/swaps 26 . /proc/partitions The /proc/partitions file contains a table with major and minor number of partitioned devices.13.8.

2. 3.Chapter 3. You will also find a /sbin subdirectory in other directories. If it does not exist by default. ftp and www data to this location. Red Hat plans to move some data that is currently located in /var to /srv. /root is the default location for the root user’s personal data and profile. The FHS suggests locating cvs. A lot of the system binaries will require root privileges for certain tasks. Linux uses sysfs to support usb and IEEE 1394 (aka FireWire) hot plug devices.2.6 kernel. /root the superuser’s home On many systems.6 hot plugging The /sys directory is created for the Linux 2.2.15. paul@RHELv4u4:~$ ls /sys/* /sys/block: dm-0 fd0 hdb md0 ram1 dm-1 hda hdc ram0 ram10 /sys/bus: i2c ide pci ram11 ram12 ram13 ram14 ram15 ram2 ram3 ram4 ram5 ram6 ram7 ram8 ram9 sda sdb sdc platform pnp scsi serio usb /sys/class: firmware i2c-adapter graphics i2c-dev /sys/devices: pci0000:00 platform /sys/firmware: acpi input mem misc net netlink pci_bus printer raw scsi_device scsi_host tty usb usb_host vc system 27 . /srv served by your system You may find /srv to be empty on many systems.net/ ).2. like /srv/project55/ftp and /srv/sales/www. Since 2. 3. then some administrators create it. but mainly for booting and for tools to configure the system.sourceforge. /sys Linux 2. The Linux File System Tree Filename /dev/mapper/VolGroup00-LogVol01 paul@RHELv4u4:~$ Type partition Size Used 1048568 0 Priority -1 3. The FHS also approves administrative naming in /srv. 3. but not for long. rsync.17.14. See the manual pages of udev(8) (the successor of devfs) and hotplug(8) for more info (Or visit http://linux-hotplug.16. /sbin system binaries Similar to /bin.6.

/usr Unix System Resources Although /usr is pronounced like user. print spool directories (/var/spool) and various caches (/var/cache) should be located in /var.20. The /usr hierarchy should contain sharable.1. 3. This location is also used when files are downloaded from the Red Hat Network. then again. /tmp might take up diskspace.2. or from a read only NFS share.20.Chapter 3. /tmp for temporary files When applications (or Users) need to store temporary data. There will be more examples of /var usage further in this book. it might also not (as in being mounted inside RAM memory). 28 . But /var is much more than that. Some people even choose to mount /usr as read only. In any case. /var/lib/rpm Red Hat Enterprise Linux keeps files pertaining to RPM in /var/lib/rpm/.2. The Linux File System Tree /sys/module: ac dm_mirror autofs4 dm_mod battery dm_snapshot button dm_zero /sys/power: state paul@RHELv4u4:~$ ext3 floppy i2c_core i2c_dev ip_conntrack iptable_filter ip_tables ipt_REJECT ipt_state ipv6 jbd lp md5 mii mptbase mptfc mptsas mptscsi mptscsih mptspi 3. Never use /tmp to store data that you want to archive. files in /tmp can be cleared by the operating system. read only data.2. 3. /var/spool/up2date The Red Hat Update Agent uses files in /var/spool/up2date. they should use /tmp.19. 3. 3. it contains Process ID files in /var/run and temporary files that survive a reboot in /var/tmp.2. /var variable data Data that is unpredictable in size. such as log files (/var/log).2.18.2. never forget that it stands for Unix System Resources. This can be done from its own partition.20.

pwd The you are here sign can be displayed with the pwd command (Print Working Directory). available on any Unix or Linux system.1.3.Chapter 3. To explore the filesystem.2. Typing cd ~ has the same effect. paul@laika$ paul@laika$ /etc paul@laika$ paul@laika$ /bin paul@laika$ paul@laika$ /boot/grub paul@laika$ paul@laika$ /home/paul cd /etc pwd cd /bin pwd cd /boot/grub pwd cd /home/paul/ pwd You can pull off a trick with cd. Working with directories It is one thing to know the structure of the Unix filetree. Just typing cd without a target directory. Go ahead.3. will put you in your home directory. paul@laika:~$ pwd /home/paul 3. cd You can change your current directory with the cd command (Change Directory). Here’s a small overview of the most common commands.3. The Linux File System Tree 3. you will need some tools. paul@laika$ paul@laika$ /etc paul@laika$ paul@laika$ /home/paul paul@laika$ paul@laika$ /home/paul cd /etc pwd cd pwd cd ~ pwd 29 . try it: open a commandline interface (like gnome-terminal or an xterm) and type pwd. it is another to walk around in it. 3. The tool displays your current directory.

you have to type cd paul instead of cd /paul to enter the subdirectory paul of the current directory /home.to go to the previous directory. When inside /home.. If you don’t start your path with a slash. then the current directory is the assumed starting point. From within this directory. . The Linux File System Tree To go to the parent directory (the one just above your current directory in the directory tree). . To stay in the current directory.-) paul@laika:/usr/share/games/wesnoth$ pwd /usr/share/games/wesnoth paul@laika:/usr/share/games/wesnoth$ cd .. paul@laika:/usr/share$ cd .. you have to type cd /home instead of cd home to go to the /home directory. type cd . When you type a path starting with a slash.Chapter 3. paul@laika$ pwd /home/paul paul@laika$ cd home bash: cd: home: No such file or directory paul@laika$ cd /home paul@laika$ pwd /home paul@laika$ cd /paul bash: cd: /paul: No such file or directory paul@laika$ cd paul paul@laika$ pwd /home/paul paul@laika$ 30 . paul@laika:/$ pwd / paul@laika:/$ Another useful shortcut with cd is to just type cd . then the root of the filetree is assumed. paul@laika:/usr$ cd ... paul@laika:~$ pwd /home/paul paul@laika:~$ cd /etc paul@laika:/etc$ pwd /etc paul@laika:/etc$ cd /home/paul paul@laika:~$ cd /etc paul@laika:/etc$ cd /home/paul paul@laika:~$ You should be aware of absolute and relative paths in the filetree. paul@laika:/usr/share/games$ pwd /usr/share/games paul@laika:/usr/share/games$ cd . type cd . The screenshot below first shows the current directory (/home/paul).

From now on.bashrc httpd. and it doesn’t show up in regular file listings. ls You can list the contents of a directory with ls. paul@pasha:~$ ls allfiles.conf stuff paul@pasha:~$ ls -l total 23992 -rw-r--r-. paul@pasha:~$ ls allfiles.1 paul paul 0 2006-03-30 summer.txt . or to display different parts of the directory.bash_history .lesshst . it is considered a hidden file.txt . Many times you will be using options with ls to display the contents of the directory in different formats.txt dmesg.Xauthority 31 . the current directory will always be displayed in the prompt. paul@laika$ paul@laika$ / paul@laika$ paul@laika$ /home paul@laika$ paul@laika$ / paul@laika$ paul@laika$ /home cd / pwd cd home pwd cd / pwd cd /home pwd This was the last screenshot with pwd statements.txt .txt dmesg.conf stuff summer.conf stuff summer.txt dmesg. .3.txt 22:53 11:45 14:01 12:22 22:45 allfiles. Just typing ls gives you a list of files in the directory. how the shell variable $PS1 can be configured to do this.txt httpd. 3. not the number 1) gives you a long listing (more information on the contents).txt httpd.txt paul@pasha:~$ ls -a . When a filename on a Unix file system starts with a dot. We will explain later in this book. The Linux File System Tree In case your current directory is the root directory.1 paul paul 24506857 2006-03-30 -rw-r--r-.1 paul paul 14744 2006-09-27 -rw-r--r-.bash_profile dmesg.ssh paul@pasha:~$ stuff summer. All files means including the hidden files.Chapter 3.1 paul paul 8189 2006-03-31 drwxr-xr-x 2 paul paul 4096 2007-01-08 -rw-r--r-.conf . allfiles.txt A frequently used option with ls is -a to show all files.viminfo .3. then both cd /home and cd home will get you in the /home directory.Typing ls -l (that is a letter L..txt httpd.

conf stuff summer.1 paul paul -rw-r--r-.0K 4.1 paul paul drwxr-xr-x 2 paul paul -rw-r--r-.0K 0 2006-03-30 2006-09-27 2006-03-31 2007-01-08 2006-03-30 22:53 11:45 14:01 12:22 22:45 allfiles.0K 0 2006-03-30 2006-09-27 2006-03-31 2007-01-08 2006-03-30 22:53 11:45 14:01 12:22 22:45 allfiles.1 paul paul drwxr-xr-x 2 paul paul -rw-r--r-.txt dmesg.1 paul paul -rw-r--r-. paul@laika:~$ mkdir MyDir paul@laika:~$ cd MyDir paul@laika:~/MyDir$ ls -al total 8 drwxr-xr-x 2 paul paul 4096 2007-01-10 21:13 . It shows the numbers (file sizes) in a more human readable format.txt httpd. Also shown below is some variation in the way you can give the options to ls.0K 4.0K 4.txt 3.txt dmesg.conf stuff summer.0K 0 2006-03-30 2006-09-27 2006-03-31 2007-01-08 2006-03-30 22:53 11:45 14:01 12:22 22:45 allfiles.txt 24M 15K 8.1 paul paul -rw-r--r-.1 paul paul 24M 15K 8.1 paul paul -rw-r--r-. paul@laika:~/MyDir$ mkdir stuff paul@laika:~/MyDir$ mkdir otherstuff paul@laika:~/MyDir$ ls -l total 8 drwxr-xr-x 2 paul paul 4096 2007-01-10 21:14 otherstuff drwxr-xr-x 2 paul paul 4096 2007-01-10 21:14 stuff paul@laika:~/MyDir$ 32 . Think before you type a leading / .1 paul paul -rw-r--r-.1 paul paul paul@pasha:~$ ls -hl total 24M -rw-r--r-.txt 24M 15K 8.0K 0 2006-03-30 2006-09-27 2006-03-31 2007-01-08 2006-03-30 22:53 11:45 14:01 12:22 22:45 allfiles. mkdir Walking around the Unix filetree is fun.1 paul paul -rw-r--r-.3. drwxr-xr-x 39 paul paul 4096 2007-01-10 21:13 .1 paul paul drwxr-xr-x 2 paul paul -rw-r--r-. We will explain the details of the output later in this book! paul@pasha:~$ ls -l -h total 24M -rw-r--r-.txt httpd.4.txt httpd. the name of the new directory to be created.txt dmesg.txt httpd.txt dmesg. You have to give at least one parameter to mkdir.1 paul paul -rw-r--r-..txt 24M 15K 8.Chapter 3. but it is even more fun to create your own directories with mkdir. The Linux File System Tree Another frequently used ls option is -h.1 paul paul paul@pasha:~$ ls -lh total 24M -rw-r--r-.1 paul paul drwxr-xr-x 2 paul paul -rw-r--r-.1 paul paul -rw-r--r-.1 paul paul paul@pasha:~$ ls -h -l total 24M -rw-r--r-.0K 4.conf stuff summer.conf stuff summer.

Pushd adds a directory to the stack and changes to a new current directory.Chapter 3. you can also use rmdir to recursively remove directories. paul@laika:/etc$ cd /bin paul@laika:/bin$ pushd /lib /lib /bin paul@laika:/lib$ pushd /proc /proc /lib /bin paul@laika:/proc$ paul@laika:/proc$ popd /lib /bin paul@laika:/lib$ paul@laika:/lib$ 33 . then you are allowed to forget about these two. pushd and popd These two commands are not essential. then mkdir will create parent directories as needed. rmdir When a directory is empty. paul@laika:~$ rmdir MyDir rmdir: MyDir/: Directory not empty paul@laika:~$ rmdir MyDir/stuff paul@laika:~$ rmdir MyDir And similar to the mkdir -p option. Both commands work with a common stack of previous directories. paul@laika:~$ mkdir -p dir/subdir/subdir2 paul@laika:~$ rmdir -p dir/subdir/subdir2 paul@laika:~$ 3..3. if you think there are too many commands to remember.3. you can use rmdir to remove the directory. The Linux File System Tree When given the option -p.6. paul@laika:~$ paul@laika:~$ MySubdir2 paul@laika:~$ ThreeDeep paul@laika:~$ mkdir -p MyDir2/MySubdir2/ThreeDeep ls MyDir2 ls MyDir2/MySubdir2 ls MyDir2/MySubdir2/ThreeDeep/ 3.5. paul@laika:~/MyDir$ rmdir otherstuff paul@laika:~/MyDir$ ls stuff paul@laika:~/MyDir$ cd . popd removes a directory from the stack and sets the current directory. Some administrators find it useful to work with pushd and popd.

List the contents of the root directory. The Linux File System Tree paul@laika:/lib$ popd /bin paul@laika:/bin$ 3. 2. Go to the root directory. Change to the /etc directory. and dir2 is a subdirectory from dir1 ).Chapter 3. List the files in /boot in a human readable format. 15. 12. and list the contents of ~.3. Create a directory testdir in your homedirectory. 6. Now change to your home directory using only three key presses. Stay where you are. Practice: Working with directories 1. Change to the /etc directory. Remove the directory testdir. Display your current directory. Stay where you are. 34 . 13. Stay where you are. and list the contents of /etc. 9. and list the contents of /bin and /sbin. 16. 4. Change to the /boot/grub directory using only eleven key presses. 10.7. List a long listing of the root directory. stay here and create a directory newdir in your homedirectory. Go to the parent directory of the current directory. 17. 8. 11. List all the files (including hidden files) in your homedirectory. Create in one command the directories ~/dir1/dir2/dir3 (dir3 is a subdirectory from dir2. 3. 5. 7. 14.

4.4.TXT or .0. version 1 (SYSV). # Solaris 9 on Intel bash-2. AMD x86-64. AMD x86-64. It shows the different type of binaries on different architectures. popd and dirs. As a system administrator. dynamically linked (uses shared libs).DOC. use and understand pushd and popd.c: ASCII C program text Here’s another example of the file utility.4\ . dynamically linked.png Desktop/Screenshot. Your editor does not care whether a file ends in . version 1 (SYSV). for GNU/Linux\ 2. s\ tripped # Ubuntu Linux on AMD64 paul@laika:~$ file /bin/date /bin/date: ELF 64-bit LSB executable. file The file utility determines the file type. Use the man page of bash to find information about pushd. for GNU/Linu\ x 2.Chapter 3. you should use the file command to determine the file type. for GNU/Linux 2. for GNU/Linux 2.0. Unlike some other desktop operating system.6.png: PNG image data.6. First some examples on a typical Linux system. stripped # Debian Sarge on SPARC paul@pasha:~$ file /bin/date /bin/date: ELF 32-bit MSB executable.0. for GNU/Linux 2. The Linux File System Tree 18. SPARC. 8-bit/color RGBA. Working with files 3.6.6. Unix does not use extensions to determine the file type.1. for GNU/Linux 2.4. 3.c HelloWorld. dynamically linked (uses shared libs). stripped 35 . If time permits (or if you are waiting for other students to finish this practice). stripped paul@laika:~$ file /etc/passwd /etc/passwd: ASCII text paul@laika:~$ file HelloWorld.1. paul@laika:~$ file Desktop/Screenshot.0. non-inter\ laced paul@laika:~$ file /bin/cat /bin/cat: ELF 64-bit LSB executable. version 1 (SYSV).05$ file /bin/date /bin/date: ELF 32-bit LSB executable 80386 Version 1.1. dynamically linked (uses shared libs). 3840 x 1200.

1 paul paul 0 -t 200505050000 SinkoDeMayo -t 130207111630 BigBattle 1302-07-11 16:30 BigBattle 2005-05-05 00:00 SinkoDeMayo 3.3. the command line in general does not have a waste bin or trashcan to recover files. paul@laika:~$ ls test SinkoDeMayo paul@laika:~$ rm test 36 .Chapter 3. Can you find out what by looking at the next screenshot ? If not. rm When you no longer need a file. When you are logged on as root. However rm accepts several options that will allow you to remove any directory.4. touch One easy way to create a file is with touch. touch can do more than just create files. The Linux File System Tree 3. rm will not remove non-empty directories. use rm to remove it.2. paul@laika:~/test$ touch paul@laika:~/test$ touch paul@laika:~/test$ ls -l total 0 -rw-r--r-.1 paul paul 0 -rw-r--r-. check the manual of touch.1 paul paul 0 paul@laika:~/test$ touch paul@laika:~/test$ touch paul@laika:~/test$ ls -l total 0 -rw-r--r-.4. so you can literally erase your entire system by accident. (We will see many other creative avenues for spawning files later in this book. be very careful with rm -rf. So be careful before removing files! paul@laika:~/test$ ls BigBattle SinkoDeMayo paul@laika:~/test$ rm BigBattle paul@laika:~/test$ ls SinkoDeMayo By default.1 paul paul 0 -rw-r--r-. Unlike some graphical user interfaces. The rm -rf statement is famous because it will erase anything (providing that you have the permissions to do so).) paul@laika:~/test$ touch paul@laika:~/test$ ls -l total 0 -rw-r--r-.1 paul paul 0 -rw-r--r-. because being root implies that permissions don’t apply to you. the file is gone.1 paul paul 0 file1 2007-01-10 21:40 file1 file2 file555 2007-01-10 21:40 file1 2007-01-10 21:40 file2 2007-01-10 21:40 file555 Of course. When you use rm to remove a file.

paul@laika:~/test$ touch FileA paul@laika:~/test$ ls FileA paul@laika:~/test$ cp FileA FileB paul@laika:~/test$ ls FileA FileB paul@laika:~/test$ mkdir MyDir paul@laika:~/test$ ls FileA FileB MyDir paul@laika:~/test$ cp FileA MyDir/ paul@laika:~/test$ ls MyDir/ FileA To copy complete directories. then the sourcefiles are copied in that target directory. In that case. The Linux File System Tree rm: cannot remove ‘test’: Is a directory paul@laika:~$ rm -rf test paul@laika:~$ ls test ls: test: No such file or directory 3. If the target is a directory. paul@laika:~/test$ ls FileA FileB MyDir paul@laika:~/test$ ls MyDir/ FileA paul@laika:~/test$ cp -r MyDir MyDirB paul@laika:~/test$ ls FileA FileB MyDir MyDirB paul@laika:~/test$ ls MyDirB FileA You can also use cp to copy multiple file into a directory.4.4. use cp -r.Chapter 3. use cp with a source and a target argument. use the -i (for interacgtive) option. the last argument (aka the target) must be a directory. paul@laika:~/test$ cp fire water paul@laika:~/test$ cp -i fire water cp: overwrite ‘water’? no paul@laika:~/test$ cp file1 file2 dir1/file3 dir1/file55 dir2 To prevent cp from overwriting existing files. cp To copy a file. 37 .

bak two. Display the type of file of /bin/cat.4. or to move the file to another directory.png .png paul@laika:~/test$ paul@laika:~/test$ 123.txt ls The rename command can also be used. but it has a more complex syntax to enable renaming of many files at once.bak two. the syntax of rename is a bit different. paul@laika:~/test$ paul@laika:~/test$ file100 paul@laika:~/test$ paul@laika:~/test$ ABC. The second example renames all(*) files. paul@laika:~/test$ 123.4. replace any occurrence of conf with bak.txt paul@laika:~/test$ paul@laika:~/test$ 123. Below two examples.5.png ABC. the first switches all occurrences of txt in png for all filenames ending in . The following syntax will work on debian and ubuntu.txt paul@laika:~/test$ touch file100 ls mv file100 ABC. mv Use mv to rename a file.png ls On Red Hat Enterprise Linux. The second example switches all occurrences of uppercase ABC in lowercase abc for all filenames ending in .6. replacing one with ONE.txt ABC.bak [paul@RHEL4a test]$ [paul@RHEL4a test]$ ONE.Chapter 3.conf [paul@RHEL4a test]$ [paul@RHEL4a test]$ one. Practice: Working with files 1.txt ls rename ’s/ABC/abc/’ *. List the files in the /bin directory 2.conf two.png abc.bak [paul@RHEL4a test]$ ls rename conf bak *.png paul@laika:~/test$ ls rename ’s/txt/png/’ *.conf ls rename one ONE * ls 3.conf files. [paul@RHEL4a test]$ one. The first example below renames all *. 38 . /etc/passwd and /usr/bin/passwd. The Linux File System Tree 3.txt.

Did you include all subdirectories of /etc ? 12. try it on both!) 3. 10. Display the type of file of wolf.5.yesterday. head You can use head to display the first ten lines of a file. Display the type of file of wolf.txt and yesterday.txt to copy.5.pdf 3d.1. paul@laika:~$ head /etc/passwd root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh 39 . Create the files today.jpg 3c. Create a directory ~/etcbackup and copy all *. 5.be/wolf.Chapter 3. Download wolf.txt in touched.yesterday.jpg) 3b. Rename copy.txt to kim 9.BAK files to *.txt to match yesterday’s date.conf files from /etc in it.pdf 4. Create a directory ~/touched and enter it. Use one command to remove the directory ~/testbackup and all files in it. Rename the file to wolf. 6. Create a directory called ~/testbackup and copy all files from ~/touched in it.jpg from http://cobbaut. Use rename to rename all *.be (wget http://cobbaut. 11. 7. File contents 3. (if you have a debian and red hat derived distro available.txt 8. Copy yesterday. Change the date on yesterday. The Linux File System Tree 3a.BACKUP.

2. the tail command will display the last ten lines of a file. paul@laika:~$ head -4 /etc/passwd root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh Head can also display the first n bytes. it will scroll by until the end. The Linux File System Tree sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh lp:x:7:7:lp:/var/spool/lpd:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh paul@laika:~$ The head command has some options for displaying the first n lines of a file. Some examples will give a glimpse of the possibilities. The first example is simple. tail Similar to head. 3.Chapter 3. All it does is copying standard input to standard output. we will use some of them during this course. paul@laika:~$ tail /etc/services vboxd 20012/udp binkp 24554/tcp asp 27374/tcp asp 27374/udp csync2 30865/tcp dircproxy 57000/tcp tfido 60177/tcp fido 60179/tcp # Local services paul@laika:~$ # binkp fidonet protocol # Address Search Protocol # # # # cluster synchronization tool Detachable IRC Proxy fidonet EMSI over telnet fidonet EMSI over TCP The tail command has many options.3. this can be very powerful and diverse. but in combination with the shell. If the file is longer than the screen. 40 .5. you can use cat to display a file on the screen. cat The cat command is one of the most universal tools. paul@laika:~$ head -c4 /etc/passwd rootpaul@laika:~$ 3.5.

txt It is very cold today! paul@laika:~/test$ cat winter. Then type one or more lines.5. paul@laika:~/test$ cat > winter. paul@laika:~/test$ cat winter.conf nameserver 194.4 paul@laika:~$ You can use cat to create files with one or more lines of text.Chapter 3.txt It is very cold today! paul@laika:~/test$ cat winter. finish each line with the enter key. paul@laika:~/test$ cat > hot. tac Just one example will show you the purpose of tac (as the opposite of cat).txt <<stop > It is hot today! > Yes it is summer. paul@laika:~/test$ In the third example you will see that cat can be used to copy files. paul@laika:~/test$ cat count one two three four paul@laika:~/test$ tac count four three 41 .txt It is hot today! Yes it is summer. type and hold the Control (Ctrl) key and press d.1. The Ctrl d key combination will send an EOF (End of File) to the running process.4.txt It is very cold today! paul@laika:~/test$ You can actually choose this end marker for cat with << as is shown in this screenshot.txt It is very cold today! paul@laika:~/test$ 3. > stop paul@laika:~/test$ cat hot.7. this will end the cat command.txt > cold. The Linux File System Tree paul@laika:~$ cat /etc/resolv. Just type the command as is shown in the screenshot below.txt paul@laika:~/test$ cat cold. After the last line. We will explain in detail what happens here in the bash shell chapter.

ab splitfile. 42 . a file of size 5000 bytes is split into three smaller files.aa splitfile.5. paul@laika:~$ which ls /bin/ls paul@laika:~$ strings /bin/ls /lib/ld-linux. more and less The more command is useful for displaying files that take up more than one screen.5.1 __gmon_start__ _Jv_RegisterClasses clock_gettime libacl.. This example locates the ls binary. 3.5. Some people prefere the less command instead of more.ac In a similar example below the file is split into max 800 bytes parts.so. This can be useful to fit the file onto multiple instances of a medium too small to contain the complete file. and then displays readable strings in the binary file (output is truncated).so.1 paul paul 2000 -rw-r--r-. 3.5.Chapter 3.1 paul paul 5000 paul@laika:~/test$ split -b paul@laika:~/test$ ls -l total 20 -rw-r--r-. paul@laika:~/test$ ls -l total 8 -rw-r--r-. strings With the strings command you can display readable ascii strings found in (binary) files.1 . More will allow you to see the contents of the file page by page.2 librt. You can use the spacebar to see the next page.1 paul paul 1000 2007-09-09 20:46 bigfile1 2000 bigfile1 splitfile. 2007-09-09 2007-09-09 2007-09-09 2007-09-09 20:46 20:47 20:47 20:47 bigfile1 splitfile..so. The Linux File System Tree two one paul@laika:~/test$ 3.6.7. In the example below.1 paul paul 2000 -rw-r--r-. or q to quit more. split The split command is useful to split files into smaller file. with maximum 2000 bytes each.1 paul paul 5000 -rw-r--r-.

but with all lines in reverse order (the last line first).aa size800.ae size800.1 paul paul 800 -rw-r--r-.ac 3. Use cat to create a file named count.conf. 9. Display the last line of /etc/passwd. The Linux File System Tree paul@laika:~/test$ split -b paul@laika:~/test$ ls -l total 48 -rw-r--r-.8.ab size800. Then split this file in smaller 200 bytes parts. Display the readable character strings from the passwd command. Use cat to make a backup of this file to catcnt.1 paul paul 800 -rw-r--r-.1 paul paul 800 -rw-r--r-. Use ls to find the biggest file in /etc. 7. Display the first 12 lines of /etc/X11/xorg. 43 . 5.txt. Use more to display /var/log/messages.1 paul paul 800 -rw-r--r-.aa splitfile.txt.ad size800.1 paul paul 2000 -rw-r--r-.1 paul paul 2000 -rw-r--r-. Copy this biggest file to your ~/testsplit and name it biggest. 3.txt that looks like this: One Two Three Four Five 4.ag splitfile. Display catcnt.af size800.txt 6.1 paul paul 800 -rw-r--r-.ab splitfile.1 paul paul 200 -rw-r--r-. Make a testsplit directory in your home directory.Chapter 3. 2. 8.1 paul paul 5000 -rw-r--r-.5.1 paul paul 1000 paul@laika:~/test$ 800 bigfile1 size800.1 paul paul 800 -rw-r--r-. 2007-09-09 2007-09-09 2007-09-09 2007-09-09 2007-09-09 2007-09-09 2007-09-09 2007-09-09 2007-09-09 2007-09-09 2007-09-09 20:46 20:48 20:48 20:48 20:48 20:48 20:48 20:48 20:47 20:47 20:47 bigfile1 size800.ac size800. Practice: File contents 1. Use cp to make a backup of this file to cnt.

The Linux File System Tree 3. ls -lrS /etc mkdir ~/testsplit cp /etc/bash_completion ~/testsplit/biggest split -b 200 biggest parts 44 . Solution 9.9.Chapter 3.5.

. Shell Expansion One of the primary features of a shell is to perform a command line scan.. which stands for Bourne again shell. Bash. csh (the C shell) and ksh (the Korn shell). Bash incorporates features from sh (the original Bourne shell). In the screenshot below. white space removal. the line will be executed. it looks like cd is built-in. The manual page of bash contains more than one hundred pages.1.Chapter 4. use the (external) which command. and the lines will be executed sequentially. escaping. then the shell will start scanning that line. 4.echo World ~]$ 45 . [paul@RHELv4u3 Hello [paul@RHELv4u3 World [paul@RHELv4u3 Hello World [paul@RHELv4u3 ~]$ echo Hello ~]$ echo World ~]$ echo Hello. because every command on your linux system is processed by bash after you type it. When you enter a command on the shell’s command prompt. the default Red Hat shell The command line interface used on most Linux systems is bash. and press the enter key.1. Shell expansion is influenced by the following topics (more will follow later) : control operators. /bin/mkdir /bin/pwd /usr/bin/file /usr/bin/rename /usr/bin/which [root@RHEL4b ~]# 4. Bash is important.. Not all commands are external to the shell. and ls cp rm mv mkdir pwd file and rename are external. embedding and shell aliases. some are built-in. Control Operators You can put two or more commands on the same line. The scan will then go until each semicolon. filename generation. variables. before it is executed. [root@RHEL4b ~]# which ls cp rm mv cd mkdir pwd file rename which /bin/cp /bin/ls /bin/mv /bin/rm /usr/bin/which: no cd in (/usr/kerberos/sbin:/usr/kerberos/bin:. separated by a semicolon . To find out whether a command given to the shell will be executed as an external shell command or as a shell built-in command. After the shell has finished scanning that line.1. with the shell waiting for each command to end before starting the next one.

You will get a message when it has finished executing in background. the default Red Hat shell When on the other hand you end a line with an ampersand &.Chapter 4. Meaning the second command is only executed when the first command fails (or in other words: returns a non-zero exit status). paul@barry:~$ echo first && echo second . echo third first third paul@barry:~$ zecho first || echo second . paul@barry:~$ echo first || echo second . echo third -bash: zecho: command not found second third paul@barry:~$ Another example of the same bash logical OR principle. Bash. [paul@RHELv4u3 ~]$ cd gen && ls file1 file3 File55 fileab FileAB fileabc file2 File4 FileA Fileab fileab2 [paul@RHELv4u3 gen]$ cd gen && ls -bash: cd: gen: No such file or directory [paul@RHELv4u3 gen]$ The reverse is true for || . echo third -bash: zecho: command not found third paul@barry:~$ Another example of the same bash logical AND principle. With && the second command is only executed when the first one succeeds (returns a zero exit status). and the command is executed in background. echo third first second third paul@barry:~$ zecho first && echo second . then the shell will not wait for the command to finish. [paul@RHELv4u3 ~]$ cd gen || ls [paul@RHELv4u3 gen]$ cd gen || ls 46 . You will get your shell prompt back. [paul@RHELv4u3 [1] 7925 [paul@RHELv4u3 [paul@RHELv4u3 [paul@RHELv4u3 [1]+ Done [paul@RHELv4u3 ~]$ sleep 20 & ~]$ ~]$ ~]$ sleep 20 ~]$ You can control execution of commands with && denoting a logical AND and || denoting a logical OR.

Chapter 4. Bash. paul@barry:~$ mkdir test paul@barry:~$ cd test paul@barry:~/test$ ls paul@barry:~/test$ # we create a directory #### we enter the directory # is it empty ? 4. The shell will wait with executing the command line until a return without backslash is encountered.3. Comment Inserting bash comments has no influence on the command. That is why the following four different command lines are the same after shell expansion. paul@laika:~/test$ rm file1 && echo It worked! || echo It failed! It worked! paul@laika:~/test$ rm file1 && echo It worked! || echo It failed! rm: cannot remove ‘file1’: No such file or directory It failed! paul@laika:~/test$ Lines ending in a backslash are continued on the next line. [paul@RHEL4b ~]$ echo This command line \ > is split in three \ > parts This command line is split in three parts [paul@RHEL4b ~]$ 4.1. White space squeezing Multiple consecutive white spaces on the command line will be reduced to one white space. the default Red Hat shell -bash: cd: gen: No such file or directory file1 file3 File55 fileab FileAB fileabc file2 File4 FileA Fileab fileab2 [paul@RHELv4u3 gen]$ You can use the logical AND and OR to echo whether a command worked or not.1.2. Comments start with a # (pound sign). [paul@RHELv4u3 Hello World [paul@RHELv4u3 Hello World [paul@RHELv4u3 Hello World [paul@RHELv4u3 Hello World [paul@RHELv4u3 ~]$ echo Hello World ~]$ echo Hello ~]$ echo ~]$ ~]$ echo Hello World World Hello World 47 .

matching the asterisk to any combination of characters (even none). the default Red Hat shell You can prevent the squeezing of white spaces to a single white space character by quoting the spaces. See the man page of glob(7) for more information. Bash. File globbing The shell is also responsible for file globbing (or dynamic filename generation). When no path is given.3.4.Chapter 4.103. (This is part of LPI topic 1. [paul@RHEL4b ~]$ echo "A line with A line with double quotes [paul@RHEL4b ~]$ echo ’A line with A line with single quotes [paul@RHEL4b ~]$ double single quotes" quotes’ Quoted lines can include special escaped charachters recognized by echo (when using echo -e). the shell will use filenames in the current directory. The asterisk * is interpreted by the shell as a sign to generate filenames. 4.) [paul@RHELv4u3 gen]$ file1 file2 file3 [paul@RHELv4u3 gen]$ File4 File55 FileA [paul@RHELv4u3 gen]$ file1 file2 file3 [paul@RHELv4u3 gen]$ File55 [paul@RHELv4u3 gen]$ File55 [paul@RHELv4u3 gen]$ File55 [paul@RHELv4u3 gen]$ ls File4 File55 FileA ls File* Fileab FileAB ls file* fileab fileabc ls *ile55 ls F*ile55 ls F*55 fileab Fileab FileAB fileabc 48 . More information about quoting and escaping later in this chapter. The screenshot below shows how to use escaped n for a newline and escaped t for a tab (usually eight white spaces). check the man page.1. tabs and newlines . [paul@RHEL4b A line with a newline [paul@RHEL4b A line with a newline [paul@RHEL4b A line with [paul@RHEL4b A line with [paul@RHEL4b ~]$ echo -e "A line with \na newline" ~]$ echo -e ’A line with \na newline’ ~]$ echo -e "A line with \ta tab" a tab ~]$ echo -e ’A line with \ta tab’ a tab ~]$ The echo command can generate more than white spaces.

Chapter 4. The order in this list between the brackets is not important. matching the question mark with exactly one character. [paul@RHELv4u3 gen]$ ls file1 file2 file3 File4 File55 [paul@RHELv4u3 gen]$ ls File? File4 FileA [paul@RHELv4u3 gen]$ ls Fil?4 File4 [paul@RHELv4u3 gen]$ ls Fil?? File4 FileA [paul@RHELv4u3 gen]$ ls File?? File55 Fileab FileAB [paul@RHELv4u3 gen]$ FileA fileab Fileab FileAB fileabc The square bracket [ is interpreted by the shell as a sign to generate filenames. 49 . [paul@RHELv4u3 gen]$ file1 file2 file3 [paul@RHELv4u3 gen]$ fileab [paul@RHELv4u3 gen]$ file1 file2 file3 [paul@RHELv4u3 gen]$ fileab [paul@RHELv4u3 gen]$ ls File4 File55 FileA ls file[a5][!Z] ls file[!5]* fileab fileabc ls file[!5]? fileab Fileab FileAB fileabc The bash shell will also understand ranges of characters between brackets. Each pair of brackets is replaced by exactly one character. [paul@RHELv4u3 gen]$ ls file1 file2 file3 File4 File55 FileA fileab Fileab FileAB [paul@RHELv4u3 gen]$ ls File[5A] FileA [paul@RHELv4u3 gen]$ ls File[A5] FileA [paul@RHELv4u3 gen]$ ls File[A5][5b] File55 [paul@RHELv4u3 gen]$ ls File[a5][5b] File55 Fileab [paul@RHELv4u3 gen]$ ls File[a5][5b][abcdefghijklm] ls: File[a5][5b][abcdefghijklm]: No such file or directory [paul@RHELv4u3 gen]$ ls file[a5][5b][abcdefghijklm] fileabc [paul@RHELv4u3 gen]$ fileabc You can also exclude characters from a list between square brackets with the exclamation mark !. Bash. And you are allowed to make combinations of these wild cards. the default Red Hat shell Similar to the asterisk. the question mark ? is interpreted by the shell as a sign to generate filenames. matching any of the characters between [ and the first subsequent ].

UTF-8 paul@RHELv4u4:~/test$ LANG=C paul@RHELv4u4:~/test$ echo $LANG C paul@RHELv4u4:~/test$ ls [a-z]ile? file1 file2 file3 paul@RHELv4u4:~/test$ ls [A-Z]ile? File4 paul@RHELv4u4:~/test$ 4.5. don’t forget the influence of the LANG variable. his homedir is /home/paul [paul@RHELv4u3 gen]$ The exit code of the previous command is stored in the shell variable $?. Actually $? is a shell parameter and not a variable. his homedir is $HOME the userid of paul is 500. Shell variables Another important character interpreted by the shell is the dollar sign $. paul@RHELv4u4:~/test$ ls [A-Z]ile? file1 file2 file3 File4 paul@RHELv4u4:~/test$ ls [a-z]ile? file1 file2 file3 File4 paul@RHELv4u4:~/test$ echo $LANG en_US. Bash. Some languages include lowercase letters in an uppercase range (and vice versa). The shell will look for an environment variable named like the string behind the dollar sign and replace it with the value of the variable (or with nothing if the variable does not exist). 50 . the default Red Hat shell [paul@RHELv4u3 gen]$ ls file1 file3 File55 fileab FileAB fileabc file2 File4 FileA Fileab fileab2 [paul@RHELv4u3 gen]$ ls file[a-z]* fileab fileab2 fileabc [paul@RHELv4u3 gen]$ ls file[0-9] file1 file2 file3 [paul@RHELv4u3 gen]$ ls file[a-z][a-z][0-9]* fileab2 [paul@RHELv4u3 gen]$ But.localdomain [paul@RHELv4u3 gen]$ echo the userid of $USER is $UID.1.Chapter 4. [paul@RHELv4u3 gen]$ echo Hello $USER Hello paul [paul@RHELv4u3 gen]$ echo Hello $user Hello [paul@RHELv4u3 gen]$ echo This is the $SHELL shell This is the /bin/bash shell [paul@RHELv4u3 gen]$ echo This is the $SHELL shell on computer $HOSTNAME This is the /bin/bash shell on computer RHELv4u3. you cannot assign a value to $?.

6.UTF-8 bash -c ’ls File[a-z]’ Filea FileA Fileb FileB [paul@RHEL4b test]$ Use the unset command to remove a variable from your shell environment. use set | more to see the variables then. [paul@RHEL4b test]$ env LANG=C bash -c ’ls File[a-z]’ Filea Fileb [paul@RHEL4b test]$ env LANG=en_US. The env command can also be useful for other neat things. [paul@RHELv4u3 gen]$ echo $MyVar [paul@RHELv4u3 gen]$ MyVar=555 [paul@RHELv4u3 gen]$ echo $MyVar 555 [paul@RHELv4u3 gen]$ 4. unset and env You can use the set and env commands to display a list of environment variables. Notice that bash will set the $SHELL variable on startup. The example below uses this to show the influence of the LANG variable on file globbing.Chapter 4. On Ubuntu and Debian systems. like starting a clean shell (a shell without any inherited environment). set. Bash. echo $? 0 paul@laika:~/test$ rm file1 .1. echo $? rm: cannot remove ‘file1’: No such file or directory 1 paul@laika:~/test$ Bash will let you create your own variables. the set command will end the list of shell variables with a list of shell functions. echo $? 0 paul@laika:~/test$ rm file1 . The env -i command clears the environment for the subshell. [paul@RHEL4b ~]$ MyVar=8472 51 . [paul@RHEL4b ~]$ bash -c ’echo $SHELL $HOME $USER’ /bin/bash /home/paul paul [paul@RHEL4b ~]$ env -i bash -c ’echo $SHELL $HOME $USER’ /bin/bash [paul@RHEL4b ~]$ You can also use the env tool to set the LANG variable (or any other) for an instance of bash with one command. the default Red Hat shell paul@laika:~/test$ touch file1 .

not to the parent shell. The next example will clarify this. Exporting variables You can export shell variables to other shells with the export command. [paul@RHEL4b [paul@RHEL4b [paul@RHEL4b [paul@RHEL4b three four [paul@RHEL4b [paul@RHEL4b ~]$ ~]$ ~]$ ~]$ var3=three var4=four export var4 echo $var3 $var4 ~]$ bash ~]$ echo $var3 $var4 52 . use echo $-. [paul@RHEL4b ~]$ echo $var123 [paul@RHEL4b ~]$ set -u [paul@RHEL4b ~]$ echo $var123 -bash: var123: unbound variable [paul@RHEL4b ~]$ set +u [paul@RHEL4b ~]$ echo $var123 [paul@RHEL4b ~]$ To list all the set options for your Bash shell.1. Bash shell options Both set and unset are built-in shell commands.Chapter 4. [paul@RHEL4b himBH [paul@RHEL4b [paul@RHEL4b himuBCH [paul@RHEL4b [paul@RHEL4b himBH [paul@RHEL4b ~]$ echo $~]$ set -C . set +u ~]$ echo $~]$ 4. Bash.8. set -u ~]$ echo $~]$ set +C . the shell will treat unset variables as a variable having no value. By default. By setting the -u option.unset MyVar. They can be used to set options of the bash shell itself. the shell will treat any reference to unset variables as an error. See the man page of bash for more information.7.1. the default Red Hat shell [paul@RHEL4b ~]$ echo $MyVar. The noclobber option will be explained later in this book (in the I/O redirection chapter).echo $MyVar 8472 [paul@RHEL4b ~]$ 4. This will export the variable to child shells.

1.1. whereas single quotes prevent this.9. Delineate variables Until now. this can be a problem. [paul@RHEL4b ~]$ prefix=Super [paul@RHEL4b ~]$ echo Hello $prefixman and $prefixgirl Hello and [paul@RHEL4b ~]$ echo Hello ${prefix}man and ${prefix}girl Hello Superman and Supergirl [paul@RHEL4b ~]$ 4. [paul@RHELv4u3 hello world [paul@RHELv4u3 hello world [paul@RHELv4u3 escaping \ ? * [paul@RHELv4u3 escaping \?*"’ ~]$ echo hello world ~]$ echo hello\ \ \ world ~]$ echo escaping \\\ \?\ \*\ \"\ \’ " ’ ~]$ echo escaping \\\?\*\"\’ Notice however that double quotes still allow the parsing of variables. Bash. [paul@RHELv4u3 [paul@RHELv4u3 555 [paul@RHELv4u3 555 [paul@RHELv4u3 $MyVar ~]$ MyVar=555 ~]$ echo $MyVar ~]$ echo "$MyVar" ~]$ echo ’$MyVar’ 53 .Chapter 4. we have seen that bash interpretes a variable starting from a dollar sign. This issue can be resolved with curly braces like in this example. In some situations. Escaping When you want to use one of these characters that are automatically interpreted by the shell. the default Red Hat shell four [paul@RHEL4b [paul@RHEL4b four five [paul@RHEL4b exit [paul@RHEL4b three four [paul@RHEL4b ~]$ export var5=five ~]$ echo $var3 $var4 $var5 ~]$ exit ~]$ echo $var3 $var4 $var5 ~]$ 4. until the first occurence of a non-alphanumerical character that is not an underscore.10. you can escape them with a backslash \ (or with quotes as seen earlier).

this is called nested embedding of bash. [paul@RHELv4u3 ~]$ echo ‘cd /etc.echo $P$C$G .echo $var1 [paul@RHELv4u3 gen]$ 54 . You can use variables to prove that new shells are created.echo $(G=Grand.echo $var1) 5 [paul@RHELv4u3 gen]$ echo $var1 [paul@RHELv4u3 gen]$ You can embed a shell in an embedded shell. Shell embedding Shells can be embedded on the command line.ParentChild .echo $var1’ var1=5. But be careful.ParentChildGrand Single embedding can be useful to avoid changing your current directory.11. or in other words the command line scan can spawn new processes. [paul@RHELv4u3 gen]$ echo ‘var1=5. the default Red Hat shell The bash shell will replace variables with their value in double quoted lines. ls -d * | grep pass‘ passwd passwd. [paul@RHEL4b ~]$ P=Parent. [paul@RHEL4b ~]$ echo $P$C$G .$(C=Child.. The screenshot below uses back ticks instead of dollar-bracket to embed. [paul@RHELv4u3 gen]$ echo $var1 [paul@RHELv4u3 gen]$ echo $(var1=5.Chapter 4.passwd.echo $var1‘ 5 [paul@RHELv4u3 gen]$ echo ’var1=5.OLD [paul@RHELv4u3 ~]$ Placing the embedding between back ticks has the same meaning. but not in single quoted lines. [[paul@RHEL4b ~]$ echo "$var3 $SHELL" three /bin/bash paul@RHEL4b ~]$ echo ’$var3 $SHELL’ $var3 $SHELL 4. In the screenshot below (which uses POSIX compliant embedding). Bash. The technical difference between ’ and ‘ is significant! You can not use back ticks to nest embedded shells. the variable $var1 only exists in the (temporary) sub shell. back ticks are often confused with single quotes.1.echo $P$C$G)) Parent . containing a fork of the current shell.

txt file ‘winter. the default Red Hat shell 4.txt three two one [paul@RHELv4u3 ~]$ Aliases can be used to supply some commands with default options.12.txt: No [paul@RHELv4u3 ~]$ [paul@RHELv4u3 ~]$ [paul@RHELv4u3 ~]$ rm: remove regular [paul@RHELv4u3 ~]$ rm -i winter. This can be useful to abbreviate commands.txt empty file ‘winter.txt alias rm=’rm -i’ rm winter.txt -bash: dog: command not found [paul@RHELv4u3 ~]$ alias dog=tac [paul@RHELv4u3 ~]$ dog count. Bash.txt’? no You can undo an alias with the unalias command.txt three two one [paul@RHELv4u3 ~]$ dog count.txt such file or directory touch winter. Shell alias The shell will allow you to create aliases. [paul@RHELv4u3 ~]$ cat count.txt one two three [paul@RHELv4u3 ~]$ tac count.txt’? no rm winter.txt ls winter. [paul@RHELv4u3 ~]$ rm: remove regular [paul@RHELv4u3 ~]$ [paul@RHELv4u3 ~]$ ls: winter.1. [paul@RHEL4b ~]$ /bin/rm [paul@RHEL4b ~]$ [paul@RHEL4b ~]$ alias rm=’rm -i’ /bin/rm [paul@RHEL4b ~]$ [paul@RHEL4b ~]$ /bin/rm [paul@RHEL4b ~]$ which rm alias rm=’rm -i’ which rm unalias rm which rm 55 .Chapter 4.

What kind of file is that ? 3." (including all quotes) 56 . [paul@RHELv4u3 ~]$ set -x ++ echo -ne ’\033]0. but only if cd etc fails. 5. (use a bash variable!) 9. Execute sleep 10. 8.2. and stop displaying it with set +x. Execute ls after cd /etc. which file is executed ? 2. You might want to use this further on in this course.Chapter 4. 6. Execute the pwd command twice. Execute cd /etc after cd etc.paul@RHELv4u3:~\007’ [paul@RHELv4u3 ~]$ set +x + set +x [paul@RHELv4u3 ~]$ echo \$USER $USER [paul@RHELv4u3 ~]$ 4. Displaying shell expansion You can display the shell expansion with set -x.) 4.paul@RHELv4u3:~\007’ [paul@RHELv4u3 ~]$ echo \$USER + echo ’$USER’ $USER ++ echo -ne ’\033]0. or when in doubt about what exactly the shell is doing with your command. what is this command doing ? 7. All these questions can be answered by one command line!! 1. Practice: Discover Bash 0.1. but only if cd /etc did not error. When you type ’passwd’. Use echo to display "Hello World with strange’ characters \ * [ } ~ \\ . Execute sleep 200 in background (do not wait for it to finish). Bash. Use echo to display Hello followed by your username. (remember 0. the default Red Hat shell 4.13.paul@RHELv4u3:~\007’ [paul@RHELv4u3 ~]$ echo $USER + echo paul paul ++ echo -ne ’\033]0.

28. Write a command line that executes ’rm file55’. 12. Show the influence of $LANG in listing A-Z or a-z ranges. 19. List (with ls) all files starting with file and ending with a letter 17.Chapter 4. List (with ls) all files starting with File. the default Red Hat shell 10. 26. List (with ls) all files starting with File and having a digit as fifth character. 27. Create a testdir and enter it. Create files file1 file10 file11 file2 File2 File3 file33 fileAB filea fileA fileAAA file( file 2 (the last one has 6 characters including a space) 13. List (with ls) all files that start with f have i or R as second character and end in a number. Your command line should print ’success’ if file55 is removed. 24. List (with ls) all files that have exactly five characters. List (with ls) all files starting with file and ending in a number. 23. Copy the value of $LANG to $MyLANG. List (with ls) all files starting with a letter and ending in a number. 21. Do the env and set commands display your variable ? 57 . 15. Use one echo command to display three words on three lines. List (with ls) all files starting with file. 16. 14. List all current shell variables. 11. List (with ls) all files starting with File and having a digit as fifth character and nothing else. 29. Create a variable MyVar with a value of 1201. List (with ls) all files that start with f or F and end with 3 or A. Bash. List all files that do not start with the letter F. 20. 18. and print ’failed’ if there was a problem. 25. 22.

echo Middle. add exactly four characters to that command line so that the total output is FirstMiddleLast. Use your alias to echo echo. echo Last 43. Find the list of shell options in the man page of bash. Create a variable. You know that the echo command is safe to use. Can echo replace ls ? How can you list the files in the current directory with echo ? 58 . make sure you understand the -i option of rm. Create two variables. 32b. Display the exported variable in an interactive child shell. List all current aliases. create another variable with value ’do’. Read the man page of rm. the cracker probably replaced the ls commnand. Bash. "_+ 35. You receive information that one of your servers was cracked. Does this work as expected ? 41.i’ . 39. [paul@RHEL4b ~]$ echo First Middle Last [paul@RHEL4b ~]$ First. and export one of them. 38. 32c. 37. Explain what "set -x" does. Given the following screenshot. 36. Destroy your variable. Execute: alias rm=’rm . Use echo and the two variables to echo Dumbledore. Test yourself that you understand it! 40. Display the exported variable in an embedded child shell. 33.Chapter 4. 34. give it the value ’Dumb’. Use echo to display the following exactly: ""\\‘. What is the difference between "set -u" and "set -o nounset" ? 32a. Create an alias for echo. 31. Can this be useful ? 42. the default Red Hat shell 30. Remove your alias for echo.

48.9-34..Chapter 4. Then come back to finish this lab. Some variables are defining this process: $HISTFILE points to the location of the history file. Issue the cal command. [paul@RHELv4u3 ~]$ history 2 cat /etc/redhat-release 3 uname -r 4 rpm -qa | grep ^parted . The cd command is also compromised. Open more than one console (press Ctrl-shift-t in gnome terminal) with the same user account. use history to display your history and type ! followed by a number.. [paul@RHELv4u3 ~]$ echo $HISTFILE /home/paul/. the default Red Hat shell 44. Your shell session history is written to the file when exiting the shell.6. To repeat older commands. Bash. 47. Display a calendar of 1582 and 1752. Issue the date command. 45. Notice anything special ? 4. This is pronounced as bash bash. [paul@RHELv4u3 ~]$ !3 uname -r 2. $HISTFILESIZE is the truncate limit for the number of commands in the history file.3. Now display the date in YYYY/MM/DD format. 50. When is command history written to the history file ? 49. can echo be used to list files in other directories ? Explain how this works (list the contents of /etc and /bin without ls). Read and understand the next section about bash history. $HISTSIZE will tell you how many commands will be remembered in your current shell session.EL 59 . so you can easily repeat previous commands. The shell will echo the command and execute it. Make sure bash remembers the last 5000 commands you typed. Is there another command besides cd to change directories ? 46. type !!. bash shell history The bash shell will remember the commands you type.bash_history [paul@RHELv4u3 ~]$ echo $HISTFILESIZE 1000 [paul@RHELv4u3 ~]$ echo $HISTSIZE 1000 [paul@RHELv4u3 ~]$ To repeat the last command.

you have to be sure about the last command in your current shell history that starts with those characters! You can also use a colon followed by a regular expression to manipulate the previous command. But this can be very very dangerous. the shell will then repeat the last command that started with those characters. the default Red Hat shell [paul@RHELv4u3 ~]$ You can also use the bash with one or more characters. [paul@RHEL4b ~]$ file4 [paul@RHEL4b ~]$ ls file4 file4 [paul@RHEL4b ~]$ ls file5 file5 [paul@RHEL4b ~]$ 422 ls file4 423 ls file4 424 ls file5 425 history 4 [paul@RHEL4b ~]$ ls file4 !ls !ls:s/4/5 history 4 60 . Bash.Chapter 4.

o will put you in a new line after the current line and O will put you in a new line before the current line. The escape key will bring you back to command mode. In command mode. You can do your mistakes twice with . The r key will bring you in insert mode for just one key press.2. The choice of favorite editor is often a cause for flame wars or polls.4. i will insert before the current character and I will insert at the beginning of the line. you can type text. The commands a A i I o O will bring you into insert mode. When in insert mode. 5. joe or other editors installed. Replace and delete a character (r x) When in command mode (it doensn’t hurt to hit the escape key more than once) you can use the x key to delete the current character. you can type commands. 5. vim (vi improved) The editor vi is installed on almost every Unix system in the world. Some basic commands are a A i I o O r x G ’n G’ b w dw dd d0 d$ yw yy y0 y$ 3dd p P u U :w :q :w! :q! :wq ZZ :r :!cmd ’:r !cmd’ ddp yyp /pattern. vi will display -. Start typing (a A i I o O) The difference between a A i I o and O is the location where you can start typing.Chapter 5. will repeat your last command). you can undo your mistakes with u. Undo and repeat(u . 5. command mode and insert mode The vi editor starts in command mode. but once you get to know it. vi becomes a very powerful application.) When in command mode. pico.1. In insert mode.INSERT -. a will append after the current character and A will append at the end of the line. The vi editor is not intuitive to novices. nano. but improved. Linux will very often install vim which is very similar. Also when in command mode.3. 61 .in the bottom left corner. because it is often an easy tool to solve problems. 5. and will return you immediately to command mode. Big X key (or shift x) will delete the character left of the cursor. you can use the r key to replace one single character. Every Linux system administrator should know vi (or rather vim). (in other words the . Feel free to use any of the alternatives to vi(m). Many unixes and linuxes will also have emacs. Most Linux distributions will include the vimtutor which is a 45 minute lesson in vi.

dd will cut the current line. whereas the $ will put the cursor at the end of the current line. Join two lines (J) When in command mode. You can add 0 and $ to the d command. w will jump you to the next word. :q! will quit vi discarding changes. Similarly y0 and y$ will yank till start and end of the current line.11. :wq will save and quit and is the same as typing ZZ in command mode.5. Typing /foo will do a forward search for the string foo.10. Thus. pressing J will append the next line to the current line. 5. copy and paste lines (3dd 2yy) When in command mode. Save (or not) and exit (:w :q :q! ) Pressing the colon : will allow you to give instructions to vi. d0 will delete every character between the current character and the start of the line. typing ?bar will do a backward 62 . copy and paste a line (dd yy p P) When in command mode. Start and end of a line (0 or ^ and $) When in command mode. and b will get you to the previous word. Searching (/ ?) When in command mode typing / will allow you to search in vi for strings (can be a regular expression). You can paste the last copied or cut line after (p) or before (P) the current line. 5. 5. That last one will be noted by vi in the bottom left corner as "4 line yanked". :w will write (save) the file. :q will quit un unchanged file without saving. 5dd will cut 5 lines and 4yy will copy (yank) 4 lines.8.6.9.Chapter 5. before typing dd or yy. 5. vim (vi improved) 5. Cut. yy will copy the current line. you can type a number to repeat the command a number of times. w and b can also be combined with d and y to copy and cut words (dw db yw yb).7. Cut. Likewise d$ will delete everything from the current character till the end of the line. 5. 5. Words (w b) When in command mode. the 0 and the caret ^ will bring you to the start of the current line.

$ s/foo/bar/g ) To replace all occurences of the string foo in bar.5 to only process the first five lines.Chapter 5. The result will be put at the current location. 2. What 3 key combination in command mode will duplicate the current line. The s/foo/bar/g will replace all occurences of foo with bar. 5. Thus :r !ls will put a listing of the current directory in your textfile.15. 5. vim (vi improved) search for bar. :set number ( also try :se nu ) :set nonumber :syntax on :syntax off :set all (list all options) :set tabstop=8 :set tx (CR/LF style endings) :set notx You can set these options (and much more) in ~/. Then tell vi which lines to use.vimrc set number paul@barry:~$ 5.12. Replace all ( :1. You can write 1.$ will do the replace all from the first to the last line. 63 . for example 1. :r foo will read the file named foo. :r !foo will execute the command foo. Practice 1. 5. first switch to ex mode with : . What 3 key combination in command mode will switch two lines’ place (line five becomes line six and line six becomes line five).14. Setting options Some options that you can set in vim. Start the vimtutor and do some or all of the exercises.13. Reading files (:r :r !cmd) When in command mode. 3.vimrc paul@barry:~$ cat ~/.

5. 6. Try this example: i 1 ’Escape Key’ qa yyp ’Ctrl a’ q 5@a (Ctrl a will increase the number with one).Chapter 5. Solutions to the Practice 2. Open the last one in vi and press Ctrl v. 64 . Use the arrow keys to select a Visual Block. 7. What 2 key combination in command mode will switch a character’s place with the next one. Pressing q again will end the recording. Copy /etc/passwd to your ~/passwd. Try pasting it. xp 7. You can recall the macro with @ followed by the name of the macro.16. vim (vi improved) 4. A macro can be recorded with q followed by the name of the macro. So qa will record the macro named a. you can copy this with y or delete it with d. dwwP can switch the current word with the next word. What does dwwP do when you are at the beginning of a word in a sentence ? 5. ddp 4. yyp 3. vi can understand macro’s.

[paul@RHEL4b ~]$ tail /etc/passwd paul:x:500:500:Paul Cobbaut:/home/paul:/bin/bash Jef:x:501:501::/home/Jef:/bin/bash Martina:x:505:505:Martina Hingis:/home/Martina:/bin/bash Venus:x:507:511:Venus Williams:/home/Venus:/bin/bash Serena:x:508:512:Serena Williams:/home/Serena:/bin/bash Kim:x:509:513:Kim Clijsters:/home/Kim:/bin/bash Figo:x:510:514::/home/Figo:/bin/bash Pfaff:x:511:515::/home/Pfaff:/bin/bash Harry:x:516:520:Potter Harry:/home/Harry:/bin/bash Hermione:x:517:521:Hermione Granger:/home/Hermione:/bin/bash [paul@RHEL4b ~]$ 6. [root@RHEL4b ~]# useradd -m Harry [root@RHEL4b ~]# tail -1 /etc/passwd Harry:x:516:520::/home/Harry:/bin/bash [root@RHEL4b ~]# ls -ld /home/Harry/ drwx-----. /etc/passwd All users on a linux system are listed in /etc/passwd.1.4 Harry Harry 4096 Jul 23 12:35 /home/Harry/ [root@RHEL4b ~]# The user named Harry has userid 516 and primary group id 520. Users and groups In general. His default shell is /bin/bash.1.2.1. then use the graphical tool that is provided by your linux distro.Chapter 6. This will make sure that you do not run into problems. whereas really advanced administrators will use vi (or vipw) to edit the proper files directly.1. userdel. groupadd and so on. useradd You can add users with the useradd command as shown in this example. if you are a novice linux user and you need to manage users and groups on your home system. his home directory is /home/Harry and it is created by default (because of the -m option). You can see the default options with useradd -D. Do not attempt the latter as a novice on production systems. Server administrators will use command line tools like useradd. [root@RHEL4b ~]# useradd -D GROUP=100 HOME=/home 65 . He does not have a description. 6. Users 6.

/usr/bin/passwd Passwords of users can be set with the /usr/bin/passwd command.Chapter 6.1. The -r option of userdel will also remove the home directory.First we will delete the user Harry with userdel. For now. [root@RHEL4b ~]# tail -1 /etc/passwd Harry:x:516:520:Harry Potter:/home/Harry:/bin/bash [root@RHEL4b ~]# usermod -c ’Potter Harry’ Harry [root@RHEL4b ~]# tail -1 /etc/passwd Harry:x:516:520:Potter Harry:/home/Harry:/bin/bash [root@RHEL4b ~]# 6.2. usermod You can modify a user with the usermod command. Changing password for Harry (current) UNIX password: New UNIX password: BAD PASSWORD: it’s WAY too short New UNIX password: 66 . [Harry@RHEL4b ~]$ passwd Changing password for user Harry. and can only be read by root. Passwords 6. The /etc/shadow file is read only. Users will have to provide their old password before entering the new one twice.3. Harry’s password will be set later with the passwd command. [root@RHEL4b ~]# userdel -r Harry [root@RHEL4b ~]# useradd -m -s /bin/bash -c ’Harry Potter’ Harry [root@RHEL4b ~]# tail -1 /etc/passwd Harry:x:516:520:Harry Potter:/home/Harry:/bin/bash [root@RHEL4b ~]# 6. then recreate him with proper options. We will see in the file permissions section how it is possible for users to change their password. User passwords are encrypted and kept in /etc/shadow. Users and groups INACTIVE=-1 EXPIRE= SHELL=/bin/bash SKEL=/etc/skel [root@RHEL4b ~]# You can also explicitly supply these options with the useradd command. you will have to know that users can change their password with the passwd command.1.2.

Users and groups Retype new UNIX password: passwd: all authentication tokens updated successfully.1.3. password encryption 6. This encryption is done by the crypt function. and then set the user’s password with passwd user. The root user (and users with sudo rights on su) will still be able to su to Harry (because the password is not needed here).2. [root@RHEL4b ~]# useradd -m xavier [root@RHEL4b ~]# passwd xavier Changing password for user xavier. New UNIX password: Retype new UNIX password: passwd: all authentication tokens updated successfully. The root user also does not need to provide the old password before entering the new password twice. usermod You can also lock (or suspend) and unlock a user account with usermod. The first line in the next screenshot will disable the user Harry by adding a ! in front of his password. The root user does not have to follow these rules (there will be a warning though). making it impossible for Harry to authenticate.Chapter 6.2.3. 67 . 6.2.3. [root@RHEL4b ~]# usermod -L Harry [root@RHEL4b ~]# tail -1 /etc/shadow Harry:!$1$143TO9IZ$RLm/FpQkpDrV4/Tkhku5e1:13717:0:99999:7::: [root@RHEL4b ~]# su . The easiest (and recommended) way to add a user with a password to the system is to add the user with the useradd -m user command. [Harry@RHEL4b ~]$ As you can see. [root@RHEL4b ~]# 6.Harry [Harry@RHEL4b ~]$ 6. the passwd tool will do some basic verification to prevent users from using too simple passwords. encryption with openssl Another way to create users with a password is to use the -p option of useradd. encryption with passwd Passwords are stored in an encrypted format. but that option requires an encrypted password. You can unlock the account again with usermod -U. You can generate this encrypted password with the openssl passwd command.

c -o MyCrypt -lcrypt [root@RHEL4b ~]# .3.Chapter 6. With who am i you can see which of the who list is yourself.h> #include <unistd.4.3.h> int main(int argc. who and whoami The who command will give you information about who is logged on to the system. } [root@RHEL4b ~]# g++ MyCrypt.Y 6.c #include <stdio./MyCrypt stargate 01Y. [paul@RHEL4b ~]$ whoami paul [paul@RHEL4b ~]$ who am i paul pts/0 Jul 24 05:02 (laika) [paul@RHEL4b ~]$ who paul pts/0 Jul 24 05:02 (laika) Harry pts/1 Jul 24 05:04 (laika) [paul@RHEL4b ~]$ 68 . and compile this into a command. encryption with crypt A third option is to create your own c program using the crypt function. "01")). The whoami command exists to tell you your username. char** argv) { printf("%s\n". Users and groups [root@RHEL4b ~]# openssl passwd stargate ZZNX16QZVgUQg [root@RHEL4b ~]# useradd -m -p ZZNX16QZVgUQg mohamed [root@RHEL4b ~]# 6. [root@RHEL4b ~]# cat MyCrypt. return 0.yPnlQ6R. crypt(argv[1].

7.defs The /etc/login. [Serena@RHEL4b ~]$ id uid=508(Serena) gid=512(Serena) groups=512(Serena).defs # Password aging controls: # PASS_MAX_DAYS Maximum number of days a password may be used.5. # PASS_WARN_AGE Number of days warning given before a password expires.Venus [root@RHEL4b ~]# groupmod -n sports tennis [root@RHEL4b ~]# tail -1 /etc/group sports:x:522:Serena. [root@RHEL4b ~]# groupadd tennis [root@RHEL4b ~]# tail -1 /etc/group tennis:x:522: [root@RHEL4b ~]# usermod -G tennis Serena [root@RHEL4b ~]# usermod -G tennis Venus [root@RHEL4b ~]# tail -1 /etc/group tennis:x:522:Serena. Groups can be created with the groupadd command.522(sports) [Serena@RHEL4b ~]$ 6. [root@RHEL4b ~]# grep -i pass /etc/login. You will find password aging and length settings. # PASS_MIN_LEN Minimum acceptable password length. Group membership can be modified with the useradd or usermod command. You can change the group name with the groupmod command. you can display uid. id using the id command. Users and groups 6. Groups Users can be a member of several groups.Venus [root@RHEL4b ~]# A user can type the groups command to see a list of groups where the user belongs to. PASS_MAX_DAYS 99999 PASS_MIN_DAYS 0 69 . the numerical limits of user id’s and group id’s and whether or not a home directory should be created by default. # PASS_MIN_DAYS Minimum number of days allowed between password changes.Chapter 6. Group membership is contained in the /etc/group file. gid and group information about yourself.6.defs file contains some default settings for users. /etc/login. [Harry@RHEL4b ~]$ groups Harry sports [Harry@RHEL4b ~]$ 6.

[paul@RHEL4b ~]$ su Harry Password: [Harry@RHEL4b paul]$ su root Password: [root@RHEL4b paul]# su Serena [Serena@RHEL4b paul]$ By default.Harry Password: [Harry@RHEL4b ~]$ su Password: [root@RHEL4b ~]# 6. This means that it is impossible to logon as root (extra security). To perform tasks as root. Users and groups PASS_MIN_LEN 5 PASS_WARN_AGE 7 [root@RHEL4b ~]# 6. unless you are root. users can be given sudo rights via the /etc/sudoers file to run a command as another user. su The su command allows a user to run a shell as another user.9. issue the su . The sudo command does require you to enter your own password. The end result of this is that the user can type sudo su and become root without having to entering the root password. sudo On linux systems like Ubuntu. Running a shell as another user requires that you know the password of the other user. not for su. To become another user and also get the target user’s environment. On Ubuntu the first user created will get sudo rights to run the su command as root. Thus the password prompt in the screenshot below is for sudo.Chapter 6. the su command keeps the same shell environment. When no username is provided to su or su . Check the man page of visudo before playing with the /etc/sudoers file. the root user does not have a password set. paul@laika:~$ sudo su Password: root@laika:~# 70 .8.then the command will assume root is the target.command followed by the target username. The root user can become any other user without knowing the user’s password. [paul@RHEL4b ~]$ su .

2007 Password Expires: Never Password Inactive: Never Account Expires: Never [root@RHEL4b ~]# 6.12. and set the number of warning days before the password expiration date. [Harry@RHEL4b ~]$ chsh -l /bin/sh /bin/bash /sbin/nologin /bin/ash /bin/bsh /bin/ksh /usr/bin/ksh /usr/bin/pdksh /bin/tcsh /bin/csh /bin/zsh [Harry@RHEL4b ~]$ chsh -s /bin/ksh Changing shell for Harry. At the next login.10.11.Chapter 6. chsh Users can change their own login shell with the chsh command. a password expiration date. The -l option of chage will list these settings for a user. In the example below we delegate permissions to add and remove group members to the sports group to Serena. [Harry@RHEL4b ~]$ 6. Harry will default into ksh instead of bash. Harry here is first obtaining a list of available shells ( the user could have done a cat /etc/shells ) and then changes his login shell to the Korn shell (/bin/ksh). chage The chage command can be used to set an expiration date for a user account (-E). [root@RHEL4b ~]# chage -l Harry Minimum: 0 Maximum: 99999 Warning: 7 Inactive: -1 Last Change: Jul 23. set a mimimum (-m) and maximum (-M) password age. Then we su to Serena and add Harry to the sports group. gpasswd You can delegate control of group membership to another user with the gpasswd command. A lot of this functionality is also available via the passwd command. Password: Shell changed. Users and groups 6. 71 .

Practice: Users and groups 1.14. vipw If after knowing all these commands for user and group management you still want to edit the /etc/passwd. and their full name in the comment. all of them with password set to stargate. Create the users Serena Williams. Users and groups [root@RHEL4b ~]# gpasswd -A Serena sports [root@RHEL4b ~]# su .522(sports) [Serena@RHEL4b ~]$ tail -1 /etc/group sports:x:522:Serena. this does not influence their ability to add or remove members.Harry [root@RHEL4b ~]# 6.Venus. The vipw tool will do proper locking of the file. [root@RHEL4b ~]# tail -1 /etc/gshadow sports:!:Serena:Venus.13.Harry [Serena@RHEL4b ~]$ Group administrators do not need to be a member of the group. with username as their first name. /etc/shadow and /etc/gshadow manually. Verify that the users and their home directory are properly created.15. then use vipw instead of vim directly. 6. The /etc/skel/ directory contains some (usually hidden) files that contain profile settings and default values for applications. 6. 72 . In this way /etc/skel/ serves as a default home directory and as a default user profile.Serena [Serena@RHEL4b ~]$ id Harry uid=516(Harry) gid=520(Harry) groups=520(Harry) [Serena@RHEL4b ~]$ gpasswd -a Harry sports Adding user Harry to group sports [Serena@RHEL4b ~]$ id Harry uid=516(Harry) gid=520(Harry) groups=520(Harry). /etc/skel/ The /etc/skel/ directory is copied to a newly created user’s home directory. Venus Williams and Justine Henin.Chapter 6. [Serena@RHEL4b ~]$ gpasswd -d Serena sports Removing user Serena from group sports [Serena@RHEL4b ~]$ exit Information about group administrators is kept in the /etc/gshadow file. /etc/group. They can even remove themselves from the group.

5a. 12. Use the id command to verify that Serena is a member of tennis. make Venus a member of tennis and sports. Create a user named Einstime without home directory. What happens when you log on with this user ? Can you think of a useful real world example for changing a user’s login shell to an application ? 4. In one command. 7. whoami. Use vi to add Serena to the tennis group. Set the password of two seperate users to stargate. Use vi to copy an encrypted stargate to another user. give him the Korn shell (/bin/ksh) as his default shell. w. Create a user called kornuser. What is the difference between locking a user account and disabling a user account’s password ? 6. 9. 5c. Make sure every new user needs to change his password every 10 days. football and sports. 5b. Set the warning number of days to four for the kornuser. Lock the Venus user account with usermod. 10. 16a. Now try changing the password of Serena to Serena as Serena. Log on with this user (on a command line or in a tty). Use passwd -d to disable the Serena password. Make someone responsible for managing group membership of foot and sports. Users and groups 2. 15. Create the groups tennis. Try the commands who. Can this other user now log on with stargate as a password ? 73 . 13. 14. Look at the encrypted stargate’s in /etc/shadow and explain. 16b. who am i. echo $USER $UID . As root change the password of Einstime to stargate. give him /bin/date as his default logon shell. 8. id. Test that it works. Rename the football group to foot. Take a backup as root of /etc/shadow.Chapter 6. 11. 3.

Use chsh to list all shells. If time permits (or if you are waiting for other students to finish this practice). Now change back to bash. and compare to cat /etc/shells. log out and back in. Users and groups 17.Chapter 6. read the man page of /etc/sudoers and give Serena the sudo right to su. Change your login shell to the Korn shell. Put a file in the skeleton directory and check whether it is copied to user’s home directory. Test that it works (and make sure Serena and root have different passwords). Which useradd option allows you to name a home directory ? 20. 20. When is the skeleton directory copied ? 18. Why use vipw instead of vi ? What could be the problem when using vi or vim ? 19. 74 .

7.2.txt -rwxrwx--.1 paul paul 106 -rw-rw-r-. character devices a c.1 root root 0 paul@RHELv4u4:~/test$ Feb Feb Feb Feb 7 5 5 7 11:53 17:04 15:38 16:07 file1 file2 data. After that.txt 75 . as can be seen in the following screenshot. LDAP or Samba domain.1 paul proj 984 -rw-r--r-. containing r for read access. Setting permissions Permissions can be changed with chmod.2 paul paul 4.txt drwxrwx--. owners can be changed with chown and chgrp.1 paul paul 17 -rw-rw-r-. directories get a d. The first character tells us the type of file. and the third triplet is all the other users that are not the user owner and are not a member of the group owner. pipes get a p. and you need the w permission to create files in or remove files from a directory. as does the group root. every file has a user owner and a group owner. The root user owns the file stuff. two of those are also owned by the group paul.txt User paul owns three files. data.0K 2007-02-07 22:25 UserEnterOnly paul@laika:~/perms$ It is important to know that the first triplet represents the user owner. Actually. Before the user and group owner.1 paul paul 0 2007-02-07 22:22 DefaultPermissions.Chapter 7. you can see ten characters.odt is owned by the group proj.2 paul paul 4.odt stuff.txt -rwxrwxrwx 1 paul paul 0 2007-02-07 22:21 EveryoneFullControl. or they can be in a NIS.1 paul paul 0 2007-02-07 22:21 OnlyOwnerRead.0K 2007-02-07 22:26 AllEnter_UserCreateDelete -rw-r--r-. block devices a b and sockets an s.0K 2007-02-07 22:25 UserAndGroupEnter drwx-----. You need the r permission to list (ls) the contents of a directory and x permission to enter (cd) a directory. you get the permissions in three triplets.txt -r--r----. Reading permissions The users and groups of a system can be locally managed in /etc/passwd and /etc/group. symbolic links are shown with an l.1. paul@RHELv4u4:~/test$ ls -l total 24 -rw-rw-r-. Some examples below. These users and groups can own files.txt. paul@laika:~/perms$ ll total 12K drwxr-xr-x 2 paul paul 4. Regular files get a -. The first example gives the user owner execute permissions. w for write access and x for execute permissions. paul@laika:~/perms$ ls -l permissions.1 paul paul 0 2007-02-07 22:21 OwnerAll_Restnothing. the second is the group owner. File Permissions 7.

txt -rwx-----.1 paul paul 0 2007-02-07 22:34 permissions. paul@laika:~/perms$ chmod a+w permissions. paul@laika:~/perms$ chmod u=rw.txt This example removes the others read permission.txt -rw--wx-wx 1 paul paul 0 2007-02-07 22:34 permissions.1 paul paul 0 2007-02-07 22:34 permissions.txt Feel free to make any kind of combinations.o=r permissions.txt -rwx-w--w.Chapter 7.1 paul paul 0 2007-02-07 22:34 permissions.txt -rwx-wx-wx 1 paul paul 0 2007-02-07 22:34 permissions.txt paul@laika:~/perms$ ls -l permissions.1 paul paul 0 2007-02-07 22:34 permissions.ug+rw.txt -rwxrw-r-.txt 76 .txt You can also set explicit permissions.txt You don’t even have to type the a.txt paul@laika:~/perms$ ls -l permissions.txt paul@laika:~/perms$ ls -l permissions.txt -rw-rw-r-.txt paul@laika:~/perms$ ls -l permissions.txt paul@laika:~/perms$ ls -l permissions.o=r permissions. paul@laika:~/perms$ chmod g-r permissions.txt -rwxr--r-.txt paul@laika:~/perms$ ls -l permissions. File Permissions -rw-r--r-.txt paul@laika:~/perms$ chmod u+x permissions. paul@laika:~/perms$ chmod u=rw permissions.txt This example removes the group owners read permission. paul@laika:~/perms$ chmod +x permissions.txt paul@laika:~/perms$ ls -l permissions.txt paul@laika:~/perms$ ls -l permissions.txt This example gives all of them the write permission.1 paul paul 0 2007-02-07 22:34 permissions.1 paul paul 0 2007-02-07 22:34 permissions.txt -rwx---r-. paul@laika:~/perms$ chmod u=rwx.g=rw. paul@laika:~/perms$ chmod o-r permissions.1 paul paul 0 2007-02-07 22:34 permissions.txt Even the fishy combinations are accepted by chmod.

1 [Harry@RHEL4b ~]$ umask ~]$ touch test ~]$ ls -l test Harry Harry 0 Jul 24 06:03 test ~]$ As you can see. Copy a file owned by root from /etc/ to your permissions dir. 7. the file is also not executable by default. create a directory ~/permissions. Practice: File Permissions 1. Look at the triplet bitwise. Create a file owned by yourself in there. This makes 777 equal to rwxrwxrwx and by the same logic has 654 mean rw-r-xr-.txt paul@laika:~/perms$ ls -l permissions. a set of default permissions are applied.txt paul@laika:~/perms$ ls -l permissions.. who owns this file now ? 77 .txt -rwxrwxrwx 1 paul paul 0 2007-02-07 22:34 permissions. You can display the umask with the umask command. w to 2 and x to 1. [Harry@RHEL4b 0002 [Harry@RHEL4b [Harry@RHEL4b -rw-rw-r-.txt 7. This is a general security feature among Unixes. equaling r to 4.3. You have to explicitely do a chmod +x to make a file executable. paul@laika:~/perms$ chmod 777 permissions. newly created files are never executable by default.txt paul@laika:~/perms$ ls -l permissions.4.txt -rwxr-x--.1 paul paul 0 2007-02-07 22:34 permissions.5. This also means that the 1 bit in the umask has no meaning. The chmod command will accept these numbers.Chapter 7. As normal user.txt -rw-rw-r-. Setting octal permissions Most Unix administrators will use the old school octal system to talk about and set permissions. umask When creating a file or directory. a umask of 0022 is the same as 0033. These default permissions are determined by the umask. File Permissions 7. The umask specifies permissions that you do not want set by default.1 paul paul 0 2007-02-07 22:34 permissions.txt paul@laika:~/perms$ chmod 750 permissions.txt paul@laika:~/perms$ chmod 664 permissions. 2.

is 734 the same as rwxr-xr-. Create a directory that belongs to a group. Display the umask in octal and in symbolic form. As root. Make sure that people can only delete their own files. is 770 the same as rwxrwx--. root@RHELv4u4:~# mkdir /project55 root@RHELv4u4:~# ls -ld /project55 drwxr-xr-x 2 root root 4096 Feb 7 17:38 /project55 78 . give only read to others. 6. Set the umask to 077. 5.? 10. Can a normal user read this file ? Test writing to this file with vi. 13a. look at who owns this file created by root. 11b. Can another normal user read this file ? Test writing to this file with vi.? 9. Can root read this file ? Can root write to this file with vi ? 14. where every member of that group can read and write to files. 7. The sticky bit You can set the sticky bit on a directory to prevent users from removing files that they do not own as a user owner. is 400 the same as r-------. The sticky bit is displayed at the same location as the x permission for others. 7. File Permissions 3. The sticky bit is represented by a t (meaning x is also there) or a T (when there is no x for others). but use the symbolic format to set it. Change the ownership of all files in ~/permissions to yourself.Chapter 7.6. Create a file as root. and create files. 13b. 12. With chmod. With chmod. Make sure you have all rights to these files. create a file in the users ~/permissions directory. With chmod. is 664 the same as r-xr-xr-. As normal user.? 8. 4. Create a file as normal user. With chmod. give only read to others. and others can only read.? 11a. Verify that this works.

even though root does not belong to the group proj55. This means that if any user starts a program that belongs to the root user. root@RHELv4u4:~# groupadd proj55 root@RHELv4u4:~# chown root:proj55 /project55/ root@RHELv4u4:~# chmod 3775 /project55/ root@RHELv4u4:~# touch /project55/fromroot.7. The SetGID bit is represented by an s (meaning x is also there) or a S (when there is no x for the group owner). root@RHELv4u4:~# chmod 1775 /project55/ root@RHELv4u4:~# ls -ld /project55 drwxrwxr-t 2 root root 4096 Feb 7 17:38 /project55 root@RHELv4u4:~# 7. SetGID and SetUID on regular files These two permissions make for the executable file to be executed with the permissions of the file owner(s) instead of the executing owner.) root@RHELv4u4:~# ls -l /etc/shadow -r-------. and the setuid bit is set on that program. File Permissions root@RHELv4u4:~# chmod +t /project55/ root@RHELv4u4:~# ls -ld /project55 drwxr-xr-t 2 root root 4096 Feb 7 17:38 /project55 root@RHELv4u4:~# The sticky bit can also be set with octal permissions. Can be dangerous.txt root@RHELv4u4:~# 7. then the program runs as root. they are stored in /etc/shadow which is only readable by root.8.1 root proj55 0 Feb 7 17:45 fromroot. it is binary 1 in the first of four triplets. (The root user never needs permissions anyway. but sometimes this is good for security. Take the example of passwords. The SetGID bit is displayed at the same location as the x permission for group owner. Like this example shows.Chapter 7. the files created by root in /project55 will belong to proj55 when the SetGID is set. SetGID on directories The SetGID can be used on directories to make sure that all files inside the directory are group owned by the group owner of the directory.txt root@RHELv4u4:~# ls -ld /project55/ drwxrwsr-t 2 root proj55 4096 Feb 7 17:45 /project55/ root@RHELv4u4:~# ls -l /project55/ total 4 -rw-r--r-.1 root root 1260 Jan 21 07:49 /etc/shadow 79 .

you are running that program with root credentials.9. 4. 5. All files created in this directory should be group-owned by the sports group. Practice: Advanced File Permissions 1. Set up a directory. so how can normal non-root users do this ? Let’s take a look at the permissions on the /usr/bin/passwd. root@RHELv4u4:~# ls -l /usr/bin/passwd -r-s--x--x 1 root root 21200 Jun 17 2005 /usr/bin/passwd So essentially. File Permissions Changing your password requires an update of this file. 2. Users should be able to delete only their own user-owned files. 7. when starting the passwd program. owned by the group sports. read about file attributes in the man page of chattr and lsattr. 3.Chapter 7. Test that this works! 6. Members of the sports group should be able to create files in this directory. 80 . Try setting the i attribute on a file and test that it works. If time permits (or if you are waiting for other students to finish this practice).

8. Introduction to scripting Bash has support for programming constructs that can be saved as scripts.Chapter 8. upgraded. Hello World Just like in every programming course. [paul@RHEL4a ~]$ chmod +x hello_world [paul@RHEL4a ~]$ . 81 . [paul@RHEL4a ~]$ echo $var1 [paul@RHEL4a ~]$ . #!/bin/bash # Hello World Script echo Hello World After creating this simple script in vi. we start with a simple Hello World script. And unless you add the scripts directory to your path. updated. you’ll have to chmod +x the script to make it executable. maintained. Variables #!/bin/bash var1=4 echo var1 = $var1 Scripts can contain variables. this is called sourcing a script. a lot of linux commands are scripts.1. configured and removed. The following script will output Hello World. This means that system administrators also need a basic knowledge of scripting to understand how their servers and their applications are started. but since scripts are run in their own shell.2. patched. These scripts in turn then become more bash commands./vars var1 = 4 [paul@RHEL4a ~]$ echo $var1 [paul@RHEL4a ~]$ Luckily you can force a script to run in the same shell. In fact. you’ll have to type the path to the script for the shell to be able to find it. the variables do not survive the end of the script./hello_world Hello World [paul@RHEL4a ~]$ 8.

To instruct a shell to run your script in a certain shell. Shell You can never be sure which shell a user is running.3. #!/bin/ksh echo -n hello echo a Korn subshell ‘echo -n hello‘ 8. This script will run in a bash shell. The /etc/shells file contains a list of shells on your system. for loop The example below shows the syntax of a classical for loop in bash./vars var1 = 4 [paul@RHEL4a ~]$ echo $var1 4 [paul@RHEL4a ~]$ 8. for i in 1 2 4 do echo $i done An example of a for loop combined with an embedded shell to generate the list.Chapter 8. 82 . you can start your script with a shebang #! followed by the shell it is supposed to run in./vars var1 = 4 [paul@RHEL4a ~]$ echo $var1 4 [paul@RHEL4a ~]$ The above is identical to the below. Introduction to scripting [paul@RHEL4a ~]$ source . . A script that works flawlessly in bash. [paul@RHEL4a ~]$ .4. might not work in ksh or csh or dash. #!/bin/bash echo -n hello echo A bash subshell ‘echo -n hello‘ This script will run in a Korn shell (unless /bin/ksh is a link to /bin/bash).

bak echo Backup of $file put in $file. done 8.5. while [ $i -ge 0 ] .bak done 8. until loop Below a simple example of an until loop. from 100 to 1. let i--. now at $i. let i=100. while loop Below a simple example of a while loop. from 100 to 0.Chapter 8. Introduction to scripting for file in ‘ls *. You also have special parameters for the number of parameters. do echo Counting down. The man page of bash has a full list. #!/bin/bash echo The first argument is $1 echo The second argument is $2 echo The third argument is $3 echo echo echo echo \$ \# \? \* $$ $# $? $* PID of the script count arguments last error code all the arguments 83 . done 8. a string of all of them. until [ $i -le 0 ] . parameters A bash shell script can have parameters. The numbering you see in the script below continues if you have more parameters.6.txt‘ do cp $file $file. do echo Counting down. let i--. and also the process id and the last error code. now at $i. let i=100.7.

/pars one two three The first argument is one The second argument is two The third argument is three $ 5610 PID of the script # 3 count arguments ? 0 last error code * one two three all the arguments [paul@RHEL4a scripts]$ . echo $? 1 [paul@RHEL4b ~]$ The test command returns 1 if the test fails. test [ ] The test command can test whether something is true or false. echo $? 0 [paul@RHEL4b ~]$ If you prefer true and false. Introduction to scripting Below is the output of the script above in action.8.Chapter 8. [paul@RHEL4b ~]$ test 56 -gt 55 && echo true || echo false true [paul@RHEL4b ~]$ test 6 -gt 55 && echo true || echo false 84 . Let’s start by testing whether 10 is greater than 55./pars 1 2 The first argument is 1 The second argument is 2 The third argument is $ 5612 PID of the script # 2 count arguments ? 0 last error code * 1 2 all the arguments [paul@RHEL4a scripts]$ 8. [paul@RHEL4b ~]$ test 10 -gt 55 . And as you see in the next screenshot. [paul@RHEL4a scripts]$ . [paul@RHEL4b ~]$ test 56 -gt 55 . then write the test like this./pars a b c The first argument is a The second argument is b The third argument is c $ 5611 PID of the script # 3 count arguments ? 0 last error code * a b c all the arguments [paul@RHEL4a scripts]$ . test returns 0 when a test succeeds.

txt ] then echo isit. Introduction to scripting false The test command can also be written as square brackets.Chapter 8. else execute something else.9. 85 . #!/bin/bash if [ -f isit. the screenshot below is identical to the one above. The example below tests whether a file exists. then then. then it executes like this.txt exists! else echo isit. Take a look at man test to see more options for tests. [ [ [ [ [ [ [ [ [ [ -d foo ] ’/etc’ = $PWD ] $1 != ’secret’ ] 55 -lt $bar ] $foo -ge 1000 ] "abc" < $bar ] -f foo ] -r bar ] foo -nt bar ] -o nounset ] Does the directory foo exist ? Is the string /etc equal to the variable $PWD ? Is the first parameter different from the string secret ? Is 55 less than the value of $bar ? Is the value of $foo greater than or equal to 1000 ? Does the string abc sort before the value of $bar ? Is foo a regular file ? Is bar a readable file ? Is file foo newer than file bar ? Is the shell option nounset set ? Tests can be combined with logical AND and OR. If a certain condition is met. if if. if the file exists then a proper message is echoed. then execute something.txt not found! fi If we name the above script ’choice’. [paul@RHEL4b ~]$ [ 56 -gt 55 ] && echo true || echo false true [paul@RHEL4b ~]$ [ 6 -gt 55 ] && echo true || echo false false Below are some example tests. or else The if then else construction is about choice. [paul@RHEL4b ~]$ [ 66 -gt 55 -a 66 -lt 500 ] && echo true || echo false true [paul@RHEL4b ~]$ [ 66 -gt 55 -a 660 -lt 500 ] && echo true || echo false false [paul@RHEL4b ~]$ [ 66 -gt 55 -o 660 -lt 500 ] && echo true || echo false true 8.

txt exists! [paul@RHEL4a scripts]$ 8.Chapter 8.txt [paul@RHEL4a scripts]$ .10./choice isit. [paul@RHEL4b 255 [paul@RHEL4b 192 [paul@RHEL4b 168 [paul@RHEL4b 56 [paul@RHEL4b 63 [paul@RHEL4b 192 ~]$ let x="0xFF" . Introduction to scripting [paul@RHEL4a scripts]$ .11. echo $x ~]$ let x="8#70" . echo $x 8. echo $x ~]$ let x="8#77" ./choice isit. echo $x ~]$ let x="0xC0" . echo $x ~]$ let x="16#c0" . echo $x ~]$ let x="10 + 100/10" .txt not found! [paul@RHEL4a scripts]$ touch isit. echo $x ~]$ let x="10*2+100/10" . echo $x The let command can also convert between different bases. #!/bin/bash echo -n Enter a number: read number 86 . [paul@RHEL4b 7 [paul@RHEL4b 20 [paul@RHEL4b 18 [paul@RHEL4b 30 ~]$ let x="3 + 4" . echo $x ~]$ let x="0xA8" . runtime input You can ask the user for input with the read command in a script. echo $x ~]$ let x="10-2+100/10" . let The let command allows for evalutation of arithmetic expressions.

"chicken" | "goose" | "duck" ) 87 . [paul@RHEL4b ~]$ cat help #!/bin/bash # # Wild Animals Helpdesk Advice # echo -n "What animal did you see ? " read animal case $animal in "lion" | "tiger") echo "You better start running fast!" . give it a cookie." ./help What animal did you see ? dog Don’t worry.. .Chapter 8. [paul@RHEL4b ~]$ ...13. "cat") echo "Let that mouse go. case You can sometimes simplify nested if statements with a case construct.. sourcing a config file [paul@RHEL4a scripts]$ cat myApp.bash There are 5 quines [paul@RHEL4a scripts]$ 8. give it a cookie.12. Introduction to scripting 8.bash #!/bin/bash # # Welcome to the myApp application # .conf # The config file of myApp # Enter the path here myAppPath=/var/myApp # Enter the number of quines here quines=5 [paul@RHEL4a scripts]$ cat myApp.conf echo There are $quines quines [paul@RHEL4a scripts]$ ./help What animal did you see ? lion You better start running fast! [paul@RHEL4b ~]$ ./myApp./myApp.." . "dog") echo "Don’t worry.

and outputs the sum and product (as shown here). it is not." "Did it fall out your ear ?" "You discovered an unknown animal. echo $? 1 paul@laika:~$ shopt -s cdspell paul@laika:~$ shopt -q cdspell . Enter a number: 5 Enter another number: 2 88 . "babelfish") echo .txt in the current directory. Write a script that receives two parameters (two filenames) and outputs whether those files exist.. and the third shopt command verifies that the option really is set.14. name it!" 8.. The next shopt command sets the value. paul@laika:~$ shopt -q cdspell . Practice : scripts 0. *) echo . Write a script that counts the number of files ending in ... You can now use minor spelling mistakes in the cd command. echo $? 0 paul@laika:~$ cd /Etc /etc paul@laika:/etc$ 8.15. shopt You can toggle the values of variables controlling optional shell behavior with the shopt built-in shell command. The example below first verifies whether the cdspell option is set. 2. Write a script that asks for two numbers. Write a script that receives four parameters.. keep them for later! 1.’. Give each script a different name. 3. 4. Introduction to scripting echo . esac [paul@RHEL4b ~]$ "Eggs for breakfast!" "Approach and say ’Ah you big fluffy kitty. The man page of bash has a complete list of options. and outputs them in reverse order.Chapter 8. "liger") echo ..

to complain if it does not receive exactly two parameters. then nocase=yes. else nocase=no. 11. logging means writing detailed output of everything the script does to a log file in /tmp. Solutions 11.d and /etc/rc. using the shopt nocasematch option. Write a script that counts from 3 to 7 and then from 7 to 3.16. take a look at linux system scripts in /etc/init. 89 . 8. exit with an error if necessary. but try to find it yourself. Use shopt (with the correct toggled option) for this. Improve the script from question 2. and whether it is writable. Make the case statement in "Wild Animals Helpdesk Advice" case insensitive. #!/bin/bash # # Wild Animals Case Insensitive Helpdesk Advice # if shopt -q nocasematch. Put a logging switch in the config file. Improve the previous script to test that the numbers are between 1 and 100. shopt -s nocasematch. (A solution is available in appendix 1.Chapter 8. A script with a case insensitive case statement.d and try to understand them. but reset the value back to it’s original after the end of the case statement. Show the teacher that it works! 9. once with a for loop. then make it writable.d/samba ? There are also some hidden scripts in ~. The nocasematch option is reset to the value it had before the scripts started. Where does execution of a script start in /etc/init. 8.) 12. 7. Introduction to scripting Sum: Product: 5 + 2 = 7 5 x 2 = 10 5. If not. we will discuss them later. once with a while loop and once with a until loop. If time permits (or if you are waiting for other students to finish this practice). 10. Write a script that asks for a filename. Improve the previous script to congratulate the user if the sum equals the product. Verify existance of the file. 6. Make a configuration file for the previous script. then verify that you own the file. and all this three times.

Chapter 8. Introduction to scripting
fi echo -n "What animal did you see ? " read animal case $animal in "lion" | "tiger") echo "You better start running fast!" ;; "cat") echo "Let that mouse go..." ;; "dog") echo "Don’t worry, give it a cookie." ;; "chicken" | "goose" | "duck" ) echo "Eggs for breakfast!" ;; "liger") echo "Approach and say ’Ah you big fluffy kitty.’" ;; "babelfish") echo "Did it fall out your ear ?" ;; *) echo "You discovered an unknown animal, name it!" ;; esac if [ nocase = yes ] ; then shopt -s nocasematch; else shopt -u nocasematch; fi

90

Chapter 9. Process Management
9.1. About processes
A process is compiled source code that is currently running on the system. All processes have a process ID or PID, and a parent process (with a PPID). The child process is often started by the parent process. The init process always has process ID 1, and does not have a parent. But init serves as a foster parent for orphaned processes. When a process stops running, the process dies, when you want a process to die, you kill it. Processes that start at system startup and keep running forever are called daemon processes. Daemons never die. When a process is killed, but it still shows up on the system, then the process is referred to as zombie. You cannot kill zombies, because they are already dead. Some shell environment variables contain information about processes. The $$ variable will hold your current process ID (PID), and $PPID contains the parent PID. Actually $$ is a shell parameter and not a variable, you cannot assign a value to $$.
[paul@RHEL4b 4224 4223 [paul@RHEL4b [paul@RHEL4b 4812 4224 [paul@RHEL4b [paul@RHEL4b 4830 4812 [paul@RHEL4b exit [paul@RHEL4b 4812 4224 [paul@RHEL4b exit [paul@RHEL4b 4224 4223 [paul@RHEL4b ~]$ echo $$ $PPID ~]$ bash ~]$ echo $$ $PPID ~]$ bash ~]$ echo $$ $PPID ~]$ exit ~]$ echo $$ $PPID ~]$ exit ~]$ echo $$ $PPID ~]$

A process starts another process in two fases. First the process creates a fork of itself, an identical copy. Then the forked process executes an exec to replace the forked process with the target child process.
[paul@RHEL4b 4224 [paul@RHEL4b [paul@RHEL4b 5310 4224 [paul@RHEL4b ~]$ echo $$ ~]$ bash ~]$ echo $$ $PPID ~]$

With the exec command, you can execute a process without forking a new process. In the following screenshot i start a Korn shell (ksh) and replace it with a bash shell using the exec command. The

91

Chapter 9. Process Management PID of the bash shell is the same as the PID of the Korn shell. Exiting the child bash shell will get me back to the parent bash, not to the Korn (which does not exist anymore).
[paul@RHEL4b ~]$ 4224 [paul@RHEL4b ~]$ $ echo $$ $PPID 5343 4224 $ exec bash [paul@RHEL4b ~]$ 5343 4224 [paul@RHEL4b ~]$ exit [paul@RHEL4b ~]$ 4224 echo $$ ksh

echo $$ $PPID exit echo $$

9.2. ps
One of the most common tools on Unix to look at processes is ps. The following screenshot shows the parent child relationship between three bash processes.
[paul@RHEL4b 4224 4223 [paul@RHEL4b [paul@RHEL4b 4866 4224 [paul@RHEL4b [paul@RHEL4b 4884 4866 [paul@RHEL4b PID TTY 4223 ? 4224 pts/0 4866 pts/0 4884 pts/0 4902 pts/0 [paul@RHEL4b exit [paul@RHEL4b PID TTY 4223 ? 4224 pts/0 4866 pts/0 4903 pts/0 [paul@RHEL4b exit [paul@RHEL4b PID TTY 4223 ? 4224 pts/0 4904 pts/0 [paul@RHEL4b ~]$ echo $$ $PPID ~]$ bash ~]$ echo $$ $PPID ~]$ bash ~]$ echo $$ $PPID ~]$ ps fx STAT TIME COMMAND S 0:01 sshd: paul@pts/0 Ss 0:00 \_ -bash S 0:00 \_ bash S 0:00 \_ bash R+ 0:00 \_ ps fx ~]$ exit ~]$ ps fx STAT TIME COMMAND S 0:01 sshd: paul@pts/0 Ss 0:00 \_ -bash S 0:00 \_ bash R+ 0:00 \_ ps fx ~]$ exit ~]$ ps fx STAT TIME COMMAND S 0:01 sshd: paul@pts/0 Ss 0:00 \_ -bash R+ 0:00 \_ ps fx ~]$

92

Chapter 9. Process Management On Linux, ps fax is often used. On Solaris ps -ef is common. Here is a partial output from ps fax.
[paul@RHEL4a ~]$ ps fax PID TTY STAT TIME COMMAND 1 ? S 0:00 init [5] ... 3713 5042 5044 5045 5077 ? ? ? pts/1 pts/1 Ss Ss S Ss R+ 0:00 /usr/sbin/sshd 0:00 \_ sshd: paul [priv] 0:00 \_ sshd: paul@pts/1 0:00 \_ -bash 0:00 \_ ps fax

9.3. top
Another popular tool on Linux is top. The top tool can order processes according to CPU usage or other properties. You can also kill processes from within top. In case of trouble, top is often the first tool to fire up, since it also provides you memory and swap space information.

9.4. priority and nice values
All processes have a certain priority and a nice value. Higher priority processes will get more CPU time than low priority processes. You can influence this with the nice and renice commands. The top screenshot below shows four processes, all of then using approximately 25 percent of the CPU. PID 5087 and 5088 are catting the letter x to each other, PID 5090 and 5091 do the same with the letter z.
PID USER 5088 paul 5091 paul 5090 paul 5087 paul PR NI VIRT RES SHR S %CPU %MEM 25 0 4128 404 348 R 25.6 0.2 25 0 3628 400 348 R 25.6 0.2 15 0 4484 404 348 S 24.6 0.2 15 0 3932 400 348 S 24.3 0.2 TIME+ COMMAND 0:13.99 cat 0:07.99 cat 0:07.78 cat 0:14.16 cat

Since the processes are already running, we need to use the renice command to change their nice value. The nice command can only be used when starting a process. The screenshot below shows how to make two running processes nice.
[paul@RHEL4a ~]$ renice +5 5090 5090: old priority 0, new priority 5 [paul@RHEL4a ~]$ renice +5 5091 5091: old priority 0, new priority 5

93

Chapter 9. Process Management Two processes (5090 and 5091) are playing nice now, they allow other processes to use more CPU time.
PID USER 5087 paul 5088 paul 5090 paul 5091 paul PR NI VIRT RES SHR S %CPU %MEM 15 0 3932 400 348 S 37.3 0.2 25 0 4128 404 348 R 36.6 0.2 21 5 4484 404 348 S 13.7 0.2 29 5 3628 400 348 R 12.7 0.2 TIME+ COMMAND 1:19.97 cat 1:19.20 cat 1:10.64 cat 1:10.64 cat

Be careful when playing with negative nice values (the range is from -20 to 19), the responsiveness of your system can be affected. Luckily only root can issue negative nice values, in other words, you can only lower the priority of your running processes.

9.5. signals
Running processes can receive signals from each other, or from the users. You can have a list of signals by typing kill -l, that is a letter l, not the number 1.
[paul@RHEL4a ~]$ kill -l 1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1 64) SIGRTMAX [paul@RHEL4a ~]$

It is common on Linux to use the first signal SIGHUP (or HUP or 1) to tell a process that it should re-read its configuration file. Thus, the kill -1 1 command forces the init process to re-read its configuration file. It is up to the developer of the process to decide whether the process can do this running, or whether it needs to stop and start. The killall command will also default to sending a signal 15 to the processes. The SIGTERM (15) is used to ask a process to stop running, normally the process should die. If it refuses to die, then you can issue the kill -9 command (aka the sure kill). The SIGKILL (9) signal is the only one that a developer cannot intercept. The signal goes directly to the kernel, which will stop the running process (without giving it a chance to save data). When using the kill command without specifying a signal, it defaults to SIGTERM (15).

94

Process Management [paul@RHEL4a ~]$ ps fax | grep cat 5087 pts/1 S 10:04 \_ 5088 pts/1 R 10:06 \_ 5090 pts/1 SN 4:26 \_ 5091 pts/1 RN 4:28 \_ 5220 pts/1 S+ 0:00 \_ [paul@RHEL4a ~]$ kill 5087 [1] Terminated echo -n x | [paul@RHEL4a ~]$ cat . Processes started with an ampersand (&) at the end of the command line can also be seen with jobs.txt 2>/dev/null & [paul@RHEL4a ~]$ Running the fg 5 command would bring the background job with number 5 to the foreground.pipe3 cat grep cat cat .txt [5]+ Stopped vim procdemo.txt 2> /dev/null & [6] 5230 [paul@RHEL4a ~]$ jobs [5]+ Stopped vim procdemo.txt [6]. [paul@RHEL4a ~]$ vi procdemo. jobs Some processes can be frozen with the Ctrl-Z key combination. [paul@RHEL4b [1] 4902 [paul@RHEL4b [2] 4903 [paul@RHEL4b 4902 4903 [paul@RHEL4b PID TTY 4902 pts/0 4903 pts/0 [paul@RHEL4b ~]$ sleep 500 & ~]$ sleep 400 & ~]$ jobs -p ~]$ ps ‘jobs -p‘ STAT TIME COMMAND S 0:00 sleep 500 S 0:00 sleep 400 ~]$ 95 .pipe1 >pipe2 9.Running find / >allfiles. This sends a SIGSTOP to the process. An interesting option is jobs -p to see the PID of background jobs. and can be seen with the jobs command.txt [paul@RHEL4a ~]$ find / > allfiles.pipe1 cat cat .Chapter 9. the vi goes to the background.txt [paul@RHEL4a ~]$ jobs [5]+ Stopped vim procdemo.6. When doing this in vi.

Kill your script with the kill command. List your background jobs. 9. Find your script with ps. Process Management 9. Explain in detail where the numbers come from in the next screenshot. 6. 4. List the background jobs. Same for the copy script. Write a script with a ’while true’ loop that does some calculation. 5. Start editing the while script. Practice 1. organise all processes by memory usage. 12. Use top. 96 . Read the man page of ps and find your script by name with ps. 11.7. Write a script that echoes its process ID and then sleeps for an hour. now use top to display only your script and the init process. When are the variables replaced by their value ? By which shell ? [paul@RHEL4b ~]$ echo $$ $PPID 4224 4223 [paul@RHEL4b ~]$ bash -c "echo $$ $PPID" 4224 4223 [paul@RHEL4b ~]$ bash -c ’echo $$ $PPID’ 5059 4224 2. Use top to kill your script. Copy this script. Run your script again. Start the sleep script in background. 8.Chapter 9. put it in background. Do you see the difference with top ? with ps ? 10. Start the while script. Activate the copy script to foreground. 3. Kill all your running scripts. 7. Start the copy of it in a nice way.

[paul@RHEL4b ~]$ bash -c ’echo $$ $PPID’ 5059 4224 97 . The current bash shell will not replace the $$ and the $PPID.8. [paul@RHEL4b ~]$ bash -c "echo $$ $PPID" 4224 4223 The variables are now single quoted. The current bash shell will replace the $$ and $PPID while scanning the line. Process Management 9. and before executing the echo command. Solutions to the Practice 1. and before executing the bach -c command. The bash -c command will be executed before the variables replaced with their value. This latter bash is the one replacing the $$ and $PPID with their value. but the current bash shell will replace $$ and $PPID while scanning the line.Chapter 9. [paul@RHEL4b ~]$ echo $$ $PPID 4224 4223 The variables are now double quoted.

Bash first reads and executes /etc/profile.bashrc # .bashrc # User specific aliases and functions # Source global definitions if [ -f /etc/bashrc ]. In the case of Red Hat. The shell will not look in the current directory for commands to execute! (Looking for executables in the current directory provided an easy way to crack DOS computers). If you want the shell to look in the current directory.Chapter 10.bashrc file will source /etc/bashrc. Then bash searches for .bashrc.bash_profile | grep PATH PATH=$PATH:$HOME/bin export PATH [paul@RHELv4u3 ~]$ If this is an interactive shell. Bash will execute the first of these three that it finds. A similar system exists for the Korn shell with . /etc/bashrc fi [paul@RHELv4u3 ~]$ When you exit the shell. [[paul@RHEL4b ~]$ echo $PATH /usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/paul/bin [paul@RHEL4b ~]$ PATH=$PATH:. [paul@RHEL4b ~]$ echo $PATH /usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/paul/bin:. [paul@RHELv4u3 ~]$ cat .profile in the home directory. but where do they all come from ? Bash has a number of startup files that are checked (and executed) whenever bash is invoked. then .bash_login and . bash shell environment It is nice to have all these preset and custom aliases and variables.kshrc and other files. path The $PATH variable is very important. then ~/. Typically these files will expand your $PATH environment variable. More Bash 10.2. 98 . . [paul@RHELv4u3 ~]$ cat . it determines where the shell is looking for commands to execute (unless the command is built-in). then add a . to your path. Actually a similar system exists for almost all shells.bash_logout is executed. then bash will also execute .1.bash_profile. 10. the .

1.txt -bash: zcho: command not found [paul@RHELv4u3 ~]$ cat winter. Shell I/O redirection The shell (and almost every other Linux command) takes input from stdin and sends output to stdout and error messages to stderr.Chapter 10. stdout and stderr are the screen. [paul@RHELv4u3 ~]$ echo It is cold today! It is cold today! [paul@RHELv4u3 ~]$ echo It is cold today! > winter. [paul@RHEL3 ~]$ su Password: [root@RHEL3 paul]# echo $PATH /usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin [root@RHEL3 paul]# exit [paul@RHEL3 ~]$ su Password: [root@RHEL3 ~]# echo $PATH /usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin [root@RHEL3 ~]# 10. The root user will have some sbin directories added to the PATH variable. Stdin is usually the keyboard.txt [paul@RHELv4u3 ~]$ 99 . The shell allows you to redirect these streams.because the latter will take on the environment of the target user.3. the file will be cleared! [paul@RHELv4u3 ~]$ cat winter. More Bash [paul@RHEL4b ~]$ Your path might be different when using su instead of su .txt [paul@RHELv4u3 ~]$ cat winter. 10. output redirection Stdout can be redirected with a greater than sign. the shell will see the > sign and will clear the file! This means that even when the command fails.3.txt It is cold today! [paul@RHELv4u3 ~]$ zcho It is cold today! > winter. the shell will see the > sign and will clear the file.txt It is cold today! [paul@RHELv4u3 ~]$ Let me repeat myself here: While scanning the line. While scanning the line.

3.2.txt cannot overwrite existing file set +o noclobber The noclobber can be overruled with >|. noclobber This can be prevented by setting the noclobber option. [paul@RHELv4u3 ~]$ set -o noclobber [paul@RHELv4u3 ~]$ echo It is cold today! > winter.txt It is very cold today! [paul@RHELv4u3 ~]$ 10.3.txt: [paul@RHELv4u3 ~]$ [paul@RHELv4u3 ~]$ cat winter. [paul@RHELv4u3 ~]$ echo It is cold today! > winter. and stderr to /dev/null.txt [paul@RHELv4u3 ~]$ cat winter. 100 . This can be very useful to prevent error messages from cluttering your screen.4.txt [paul@RHELv4u3 ~]$ cat winter. [paul@RHELv4u3 ~]$ find / > allfiles.txt It is cold today! Where is the summer ? [paul@RHELv4u3 ~]$ 10.txt [paul@RHELv4u3 ~]$ cat winter.3.txt -bash: winter.Chapter 10.txt 2> /dev/null [paul@RHELv4u3 ~]$ To redirect both stdout and stderr to the same file. More Bash 10.txt It is cold today! [paul@RHELv4u3 ~]$ echo Where is the summer ? >> winter. error redirection Redirecting stderr is done with 2>. Writing 1> is the same as >. [paul@RHELv4u3 ~]$ It is cold today! [paul@RHELv4u3 ~]$ [paul@RHELv4u3 ~]$ -bash: winter.txt: cannot overwrite existing file [paul@RHELv4u3 ~]$ echo It is very cold today! >| winter.3.txt set -o noclobber echo It is cold today! > winter. append You can always use >> to append output to a file. use 2>&1. The screenshot below shows redirection of stdout to a file.

3. cat winter.txt one two [paul@RHEL4b ~]$ tr ’onetw’ ’ONEZZ’ < text.txt ~]$ cat <<brol > text.txt 2> errors. Confusing I/O redirection The shell will scan the whole line before applying redirection.txt > snow.txt But this one is also correct. The EOF marker can be typed literally or can be called with Ctrl-D. input redirection Redirecting stdin is done with < .4.txt ~]$ cat text. More Bash [paul@RHELv4u3 ~]$ find / > allfiles_and_errors.txt 2>&1 [paul@RHELv4u3 ~]$ 10.txt ONE ZZO [paul@RHEL4b ~]$ 10.6. but less readable.Chapter 10. 101 .txt ~]$ cat text. [paul@RHEL4b > one > two > EOF [paul@RHEL4b one two [paul@RHEL4b > brel > brol [paul@RHEL4b brel [paul@RHEL4b ~]$ cat <<EOF > text.txt ~]$ 10. The following command line is very readable and is correct.5. here document The here document (sometimes called here-is-document) is a way to append input until a certain sequence (usually EOF) is encountered.3. [paul@RHEL4b ~]$ cat < text.

and verify the values of the variables you set in questions 2 and 3. and so on) 4. Does it matter on which line we set our variables in . 2.bash_profile (put them in ~/profilebackups). Where is the command history stored ? And what about command history for Korn users ? 7. the value is the name of the script (profwinner=etc_bashrc in /etc/bashrc. profwinner=dot_profile in ~/.5. Practice: more bash 1.profile.txt Even this will be understood perfectly by the shell.Chapter 10.txt > snow.bashrc ? 6.profile. Log on to a tty and to a gnome-terminal.txt > snow.txt cat So what is the quickest way to clear a file ? >foo 10. More Bash 2> errors. Define an alias ’dog’ for the tac command in one of your profile scripts.bash_profile and .bashrc ~/. Set a unique variable in all these scripts (etc_bashrun=yes in /etc/bashrc. Take a backup copy of /etc/bashrc /etc/profile ~/.profile ~/. Which script did you choose and why ? 102 . Set and export a variable named profwinner in all these scripts. Which of the scripts were executed ? Which not ? Which was executed last ? 5. dot_profilerun=yes in ~/.txt 2> errors. < winter.txt cat winter. and so on) 3.

and the ability of almost any program to be used in a pipe.Chapter 11. Pipes and filters 11.1. [paul@RHEL4b pipes]$ cat count. Below a very simple pipe. A pipe takes stdout from the previous command and sends it as stdin to the next command in the pipe.txt five four three two one [paul@RHEL4b pipes]$ A pipe is represented by a vertical bar | in between two commands. as in this example. [paul@RHEL4b pipes]$ cat count. You still remember cat and tac right ? [paul@RHEL4b pipes]$ cat count. These can be used as building blocks for more complex applications and solutions.txt | tac five four three two one [paul@RHEL4b pipes]$ But pipes can be longer. pipes One of the most powerful advantages of unix is the use of pipes.txt one two three four five [paul@RHEL4b pipes]$ tac count.txt | tac | tac one two three four five [paul@RHEL4b pipes]$ 103 . and all commands in a pipe can be running simultaneously. Pipes can have many commands. What follows after the introduction to pipes is a number of small unix tools that do one specific task very well.

tee outputs both to a file and to stdout. USA [paul@RHEL4b pipes]$ 104 . Pipes and filters Remember that I told you in the beginning of this book that the cat command is actually doing nothing ? [paul@RHEL4b pipes]$ tac count.txt Amelie Mauresmo.Chapter 11. [paul@RHEL4b pipes]$ tac count. BEL Justine Henin.txt | cat | cat | cat | cat | cat five four three two one [paul@RHEL4b pipes]$ 11. usa Venus Williams. [paul@RHEL4b pipes]$ cat tennis. With all the uses of grep you can probably fill a book. grep Time for the real tools now.2.txt five four three two one [paul@RHEL4b pipes]$ 11. usa Venus Williams.txt | tac one two three four five [paul@RHEL4b pipes]$ cat temp. Bel Serena Williams. The most common use of grep is to filter results on keywords. but sometimes you might want intermediate results. tee Writing long pipes in unix is fun.3.txt | grep Williams Serena Williams. This is were tee comes in handy. Fra Kim Clijsters.txt | tee temp. So tee is almost the same as cat. except that it has two identical outputs. USA [paul@RHEL4b pipes]$ cat tennis.

It uses the colon as a delimiter. USA [paul@RHEL4b pipes]$ And of course. USA [paul@RHEL4b pipes]$ One of the most useful options of grep is grep -i which filters in a case insensitive way. and select fields 1 and 3. usa Venus Williams. Bel [paul@RHEL4b pipes]$ 11.txt Serena Williams. BEL Justine Henin. BEL Justine Henin. Pipes and filters You can write this without the cat. [[paul@RHEL4b pipes]$ cut -d: -f1.4. Bel Serena Williams. cut With cut you can select columns from files.txt Kim Clijsters.3 /etc/passwd | tail -4 Figo:510 Pfaff:511 Harry:516 Hermione:517 [paul@RHEL4b pipes]$ 105 . The screenshot below uses cut to filter for the username and userid in the /etc/passwd file. [paul@RHEL4b pipes]$ grep -vi usa tennis.txt Amelie Mauresmo. Fra Kim Clijsters. Bel [paul@RHEL4b pipes]$ grep -i Bel tennis. [paul@RHEL4b pipes]$ grep Williams tennis. usa Venus Williams. depending on a delimiter or a count of bytes. [paul@RHEL4b pipes]$ grep Bel tennis.Chapter 11.txt Kim Clijsters. both options can be combined.txt Justine Henin. BEL Justine Henin. Bel [paul@RHEL4b pipes]$ Another very useful option is grep -v which outputs lines not matching the string. [paul@RHEL4b pipes]$ grep -v Fra tennis.

usa Venus Williams. BEL SERENA WILLIAMS. Fra Kim ClijstErs.Chapter 11. Pipes and filters When using a space as the delimiter for cut. Fra Kim Clijsters. Bel Serena Williams.txt | tr ’e’ ’E’ AmEliE MaurEsmo. USA [paul@RHEL4b pipes]$ cat tennis. FRA KIM CLIJSTERS. USA VENUS WILLIAMS.5. cutting the second to the seventh character of /etc/passwd. usa VEnus Williams. [paul@RHEL4b pipes]$ cat tennis.txt Amelie Mauresmo. [paul@RHEL4b pipes]$ cut -c2-7 /etc/passwd | tail -4 igo:x: faff:x arry:x ermion [paul@RHEL4b pipes]$ 11. 106 . BEl SErEna Williams. BEL JUSTINE HENIN. BEL Justine Henin. tr You can translate characters with tr. USA [paul@RHEL4b pipes]$ Here we translate all newlines to spaces.txt Amelie Kim Justine Serena Venus [paul@RHEL4b pipes]$ One last example. [paul@RHEL4b pipes]$ cat tennis.txt | tr ’a-z’ ’A-Z’ AMELIE MAURESMO. [paul@RHEL4b pipes]$ cut -d" " -f1 tennis. The screenshot translates all occurences of e to E. BEL JustinE HEnin. USA [paul@RHEL4b pipes]$ Here we set all letters to uppercase by defining two ranges. you have to quote the space.

txt [paul@RHEL4b pipes]$ tennis.txt 107 . [paul@RHEL4b pipes]$ wc 5 15 100 tennis.txt [paul@RHEL4b pipes]$ wc 100 tennis.txt -w tennis.txt | tr ’a-z’ ’nopqrstuvwxyzabcdefghijklm’ bar gjb guerr sbhe svir [paul@RHEL4b pipes]$ cat count.txt -c tennis.6. Pipes and filters [paul@RHEL4b pipes]$ cat count. wc Counting words.txt | tr -s ’ ’ one two three four five six [paul@RHEL4b pipes]$ You can also use tr to ’encrypt’ texts with rot13.txt | tr ’\n’ ’ ’ one two three four five [paul@RHEL4b pipes]$ The tr filter can also be used to squeeze multiple occurences of a character to one.txt one two three four five six [paul@RHEL4b pipes]$ cat spaces.txt [paul@RHEL4b pipes]$ wc 15 tennis.txt one two three four five [paul@RHEL4b pipes]$ cat count.txt -l tennis. [paul@RHEL4b pipes]$ cat spaces.txt | tr ’a-z’ ’n-za-m’ bar gjb guerr sbhe svir [paul@RHEL4b pipes]$ 11.Chapter 11. lines and characters is easy with wc.txt [paul@RHEL4b pipes]$ wc 5 tennis. [paul@RHEL4b pipes]$ cat count.

How about a sorted list of logged on users.7. 50 France. 10 France. Rome. 60 Germany. Pipes and filters How many users are logged on to this system ? [paul@RHEL4b pipes]$ who root tty1 Jul 25 10:50 paul pts/0 Jul 25 09:29 (laika) Harry pts/1 Jul 25 12:26 (barry) paul pts/2 Jul 25 12:26 (pasha) [paul@RHEL4b pipes]$ who | wc -l 4 [paul@RHEL4b pipes]$ 11. 10 France. 60 Italy. Rome. Paris. Teheran. Berlin. 70 [paul@RHEL4b pipes]$ sort -n -k3 country. Brussels.txt Belgium. 50 Iran.txt Germany. 10 Germany. 50 [paul@RHEL4b pipes]$ sort -k2 country. sort Sorting is always useful. [paul@RHEL4b pipes]$ sort -k3 country. Brussels. 70 [paul@RHEL4b pipes]$ The screenshot below shows the difference between an alfabetical sort and a numerical sort (both on the third column).txt 108 . Teheran. Brussels.Chapter 11.txt Belgium. 60 Iran. 100 Italy. 100 Belgium. Teheran. Paris. [paul@RHEL4b pipes]$ who | cut -d’ ’ -f1 | sort Harry paul paul root [paul@RHEL4b pipes]$ Sorting on column 1 or column 2. Paris. 70 Italy. [paul@RHEL4b pipes]$ sort -k1 country. Berlin. Berlin. 100 Iran. Rome. The sort filter has a lot of options.

conf.conf" Find files of type file (so not directory or pipe. find . 10 Italy. Brussels.conf" 109 . Berlin. you will want to add 2>/dev/null to the command lines to avoid cluttering your screen with error messages. Rome. -type f -name "*. -name "*. 50 France. Pipes and filters Belgium.) that end in .Chapter 11. Paris. 60 Iran. Teheran. first with and then without duplicates.. 70 Germany.txt Find files that end in .9. 100 [paul@RHEL4b pipes]$ 11. Here are some examples. Here’s a sorted list of logged on users. Find all files in /etc and put the list in etcfiles. In real life. find . uniq With uniq you can remove duplicates from a sorted list.txt find /etc > etcfiles. to search for files.txt Find all files of the entire system and put the list in allfiles. Find is useful at the start of a pipe.txt find / > allfiles..conf in the current directory (and all subdirs). find The find tool is used very often in linux. [paul@RHEL4b pipes]$ who | cut -d’ ’ -f1 | sort Harry paul paul root [paul@RHEL4b pipes]$ who | cut -d’ ’ -f1 | sort | uniq Harry paul root [paul@RHEL4b pipes]$ 11.8.

odf files if you approve of it for every file found. 11.txt Find can also execute another command on every file found.bak.11.10.odf files and copy them to /backup/.db: No such file or di warning: You need to run the ’updatedb’ command (as root) to create the database.bak" Find files that are newer than file44. Please have a look at /etc/updatedb. This is a lot faster than traversing all the directories. This example will look for *.odf" -exec cp {} /backup/ \. use diff -i. Pipes and filters Find files of type directory that end in . use diff -b. after your confirmation. In this examples diff tells you 2c2 the second line in file one was changed with the second line in file two.Chapter 11. The find tool can do much more. but it also means that it is always outdated. you can use diff.conf to enable the daily cron job. locate The locate tool is very different from find in that it uses an index to locate files. another command on every file found. find /data -type d -name "*. 110 . find "/data/*. [paul@RHEL4b ~]$ updatedb fatal error: updatedb: You are not authorized to create a default slocate database! [paul@RHEL4b ~]$ su Password: [root@RHEL4b ~]# updatedb [root@RHEL4b ~]# 11. This example will remove *. then you have to create it (as root on Red Hat Enterprise Linux) with the updatedb command. -newer fil44. and to ignore case. [paul@RHEL4b ~]$ locate Samba warning: locate: could not open database: /var/lib/slocate/slocate. If the index does not exist yet.odf" -ok rm {} \.txt find . see the man page. Find can also execute. To ignore blanks. find "/data/*. diff To compare two files line by line.

txt Abba Cure Queen Turner 111 .txt test]$ diff count. comm You can use comm to quickly compare two sorted files.txt test]$ 11. Pipes and filters [paul@RHEL4b one two three four [paul@RHEL4b one Two three four [paul@RHEL4b 2c2 < two --> Two [paul@RHEL4b test]$ cat > count.12. a line was added as line 3 (2a3) to the second file. [paul@RHEL4b one two four [paul@RHEL4b one two three four [paul@RHEL4b 2a3 > three [paul@RHEL4b test]$ cat > count. Cure and Queen are in both lists. By default comm will output three columns.txt count2.txt test]$ diff count.txt test]$ cat > count2.txt test]$ Another example of diff.txt count2. [paul@RHEL4b test]$ cat > list1.txt Abba Bowie Cure Queen Sweet [paul@RHEL4b test]$ cat > list2. Abba. In this example. Turner is only in the second.txt test]$ cat > count2. After line 2. Bowie and Sweet are only in the first file. The second file now has one more line than the first file.Chapter 11.

1 paul paul 19M Jul 26 04:21 allfiles. od European humans like to work with ascii characters.txt 0000000 141 142 143 144 145 146 147 012 061 062 063 064 065 066 067 012 0000020 paul@laika:~/test$ od -c text.2M -rw-rw-r-.Z [paul@RHEL4b test]$ uncompress allfiles. gunzip. The compress command can make files take up less space.txt [paul@RHEL4b test]$ ls -lh total 3. Pipes and filters [paul@RHEL4b test]$ comm list1.13. You can get the original back with uncompress.1 paul paul 19M Jul 26 04:21 allfiles. paul@laika:~/test$ cat > text.txt 0000000 61 62 63 64 65 66 67 0a 31 32 33 34 35 36 37 0a 0000020 paul@laika:~/test$ od -b text.txt [paul@RHEL4b test]$ compress allfiles. and then uses od to show the contents of the file in hexadecimal bytes. in octal bytes and in ascii (or backslashed) characters.txt [paul@RHEL4b test]$ ls -lh total 19M -rw-rw-r-.1 paul paul 3.2M Jul 26 04:21 allfiles. [paul@RHEL4b test]$ ls -lh total 19M -rw-rw-r-.txt. The example below creates a simple file. In the backup chapter we will also discuss gzip.txt abcdefg 1234567 paul@laika:~/test$ od -t x1 text.txt list2.txt 0000000 a b c d e f g \n 1 2 3 4 5 6 7 \n 0000020 paul@laika:~/test$ 112 . but computers store files in bytes.14.txt Abba Bowie Cure Queen Sweet Turner [paul@RHEL4b test]$ 11. bzip2 and bunzip2. so compression comes in handy.txt [paul@RHEL4b test]$ 11.Chapter 11. compress Users never have enough space.

odf" > data_odf. Explain the difference between these two commands.. Pipes and filters 11. . with their username. 7.txt.txt 3. cp -r /data/*.txt find /data/*. Practice tools and filters 1. pr. nl. Two commands that do the same thing: copy *. Will they both work when there are 200 .conf files in /etc and all its subdirs. 9. paste. Explain the difference between these two statements.info. Write a find command that finds all files created after january 30th this year. Put a sorted list of all bash users in bashusers. userid and home directory in bashusers. 11.15. -name *. 5. Make a list of all files (not directories) in /etc/ that contain the string smb. 11. then look back at the bash chapters. This question is very important.odf files in /data/ ? How about when there are 2 million . 12. 8. Write a find command that finds all *. sed. this is an important question.odf files to /backup/ .txt" find . 4. nmb or samba.odf files created in september last year.. Make a list of all non-bash and non-korn users. What would be a reason to replace the first command with the second ? Again.odf files ? find /data -name "*. awk. other tools and filters You might want to look at expand. unexpand.odf" -exec cp {} /backup/ \. find . 113 . If you don’t know the answer.txt 2. Look at the output of /sbin/ifconfig. Put a sorted list of all bash users. Make a command abc that removes all non-letters from a file (and replaces them with spaces). Count the number of *.odf > data_odf. -name "*.Chapter 11. fmt. Make an ipconfig command that shows only the nic name (eth0). join. the ip address and the subnet mask.16. 6.odf /backup/ find /data -name "*. 10.

Solutions: tools and filters 1. Now create a spell checker that uses those two files and outputs the misspelled words (in this case that would be ’zun’).txt because it is between double quotes.htm files to . 17. Pipes and filters 13.txt | tr ’A-Z ’ ’a-z\n’ | sort | uniq | comm -2 -3 . List all files in the current directory of size between 10 and 20 bytes.txt 14. one word on each line. the second file is a dictionary.txt. Create a file DICT that contains the words "is shining sun the today". Find the hexadecimal byte value for ascii characters : " ’space’ ’tab’ A and a . The find tool will look in the current directory for all files ending in . Create a file called loctest.html.txt. 15. The shell will not touch the *.txt that contains this sentence: The zun is shining today. Create a file named text. Use find and -exec to rename all . The first file is a text.txt to all files in the current directory that end in .txt [paul@RHEL4b]$ cat > DICT is shining sun the today [paul@RHEL4b]$ cat text.txt. find . Can you find this file with locate ? Why not ? How do you make locate find this file ? 14. -name "*. 11.txt" The shell will expand the *. -name *. Then find will give you a syntax error.DICT zun [paul@RHEL4b]$ 114 . find . The one line spell checker. [paul@RHEL4b]$ echo "The zun is shining today" > text. 16.Chapter 11.17.

.11g Cardbus/mini-PCI (rev 01) 00:0f. AGP. VT82xxxxx UHCI USB 1.Chapter 12.. Coolpix 7900 (storage) root@shaka:~# To get a list of all pci devices connected. .. 00:06. RTL-8169 Gigabit Et.0 RAID bus controller: VIA Technologies. Inc.. Inc. VT82xxxxx UHCI USB 1. you could take a look at /proc/pci or run lspci (partial output below).1 Controller. 115 . Inc. paul@laika:~$ lspci .04 and RHEL4u4 below).0 Multimedia controller: Philips Semiconductors SAA7133/SAA7135 Video Broa.0 Network controller: RaLink RT2500 802.0 FireWire (IEEE 1394): Texas Instruments TSB43AB22/A IEEE-1394a-2000 Cont. Configure Fundamental BIOS Settings (LPI 1. you could read the contents of /proc/bus/usb/devices or you could use the more readable output of lsusb.1 USB Controller: VIA Technologies. 00:10...1) The booting or bootstrapping of a computer is the process of reprogramming a pile of hardware components.. PCI-Express and PCMCIA aka PC Card.1. Inc. 3-button Mouse Bus 001 Device 003: ID 0430:0005 Sun Microsystems. root@laika:~# ls /proc/bus/ input pccard pci usb [root@RHEL4b ~]# ls /proc/bus/ input pci usb To list all the usb devices connected to your system. root@shaka:~# lsusb Bus 001 Device 002: ID 0430:0100 Sun Microsystems.. look at the contents of the /proc/bus/ directory (screenshot from Ubuntu 7. Ltd. VIA VT6420 SATA RAID Control.0 USB Controller: VIA Technologies.0 Ethernet controller: Realtek Semiconductor Co..101. PCI.1.. 00:0f... Buses Hardware components communicate with the Central Processing Unit or CPU over a bus. Inc.. 12.. VT82C586A/B/VT82C686/A/B/VT823x/A/.. Type 6 Keyboard Bus 001 Device 001: ID 04b0:0136 Nikon Corp. To list the buses recognized by your kernel on your computer. Inc. The most common buses today are USB...1 IDE interface: VIA Technologies. which is executed here on a SPARC system with Ubuntu. 00:08.. 00:10.1 Controller. 00:0a.. LPI 101 stuff 12. 00:09.1.

The CPU writes data or control codes to the IO port of the device..1. IO Ports Communication in the other direction.. But this is not only a one way communication. ohci1394 eth0 uhci_hcd:usb1. LPI 101 stuff 12.. Since the introduction of pci. 116 .Chapter 12. Unlike interrupts.1. You can see a listing of interrupts on your system in /proc/interrupts. VIA8237 12. happens through IO ports. the CPU can also use a device’s IO port to read status information about the device. ports cannot be shared! [root@RHEL4b ~]# cat /proc/ioports 0000-001f : dma1 0020-0021 : pic1 0040-0043 : timer0 0050-0053 : timer1 0060-006f : keyboard 0070-0077 : rtc 0080-008f : dma page reg 00a0-00a1 : pic2 00c0-00df : dma2 00f0-00ff : fpu 0170-0177 : ide1 02f8-02ff : serial . A devices raises an interrupt when it requires the attention of the CPU (could be because the device has data ready to be read by the CPU).3. irq’s can be shared among devices.. from CPU to device.2. Interrupts An interrupt request or IRQ is a request from a device to the CPU. ra0 nvidia VIA82XX-MODEM. paul@laika:~$ cat /proc/interrupts CPU0 CPU1 0: 1320048 555 IO-APIC-edge 1: 10224 7 IO-APIC-edge 7: 0 0 IO-APIC-edge 8: 2 1 IO-APIC-edge 10: 3062 21 IO-APIC-fasteoi 12: 131 2 IO-APIC-edge 15: 47073 0 IO-APIC-edge 18: 0 1 IO-APIC-fasteoi 19: 31056 1 IO-APIC-fasteoi 20: 19042 1 IO-APIC-fasteoi 21: 44052 1 IO-APIC-fasteoi 22: 188352 1 IO-APIC-fasteoi 23: 632444 1 IO-APIC-fasteoi 24: 1585 1 IO-APIC-fasteoi timer i8042 parport0 rtc acpi i8042 ide1 yenta libata. . uhci_hcd:usb2.

since it only contains currently assigned DMA channels for ISA devices.1. irq 3 . root@laika:~# cat /proc/dma 1: parport0 4: cascade PCI devices that are using dma are not listed in /proc/dma. With DMA or Direct Memory Access a device can gain (temporary) access to a specific range of the RAM memory. LPI 101 stuff 12.4. dma 1 [PCSPP.576000] parport: PnPBIOS parport detected. dma 3.580000] parport0: PC-style at 0x378 (0x778).204000] nsc_ircc_pnp_probe() : From PnP. found firbase 0x2F8 .E [ 20. The screenshot below shows that during boot the parallel port received dma channel 1.Chapter 12. in this case dmesg can be useful.204000] pnp: Device 00:0b activated. DMA A device that needs a lot of data. [ 20. interrupts and ports can pose a heavy load on the CPU.COMPAT. [ 21. [ 21. Looking at /proc/dma might not give you the information that you want. root@laika:~# dmesg | egrep -C 1 ’dma 1|dma 3’ [ 20.204000] nsc-ircc. chip->init root@laika:~# 117 . irq 7. and the Infrared port received dma channel 3.TRISTATE.764000] irda_init() -[ 21.

each device gets a unique SCSI ID. 118 . When the bus speeds was doubled to 10Mhz. ATA allows two devices per bus. since IDE is an ATA-compatible device. You can recognize a block device by the letter b as first character of ls -l. one master and one slave. without touching it! The heads are mounted on an arm (sometimes called a comb). Random access hard disk devices have an abstraction layer called block device to enable formatting in fixed-size (usually 512 bytes) blocks. with more unused space (gap) between the sectors on the outside of the platter. The platters are rotated (at high speeds). Hard disk devices 13. the original ATA was renamed to Parallel ATA. hence the set of tracks accessible at a certain position of the comb forms a cylinder. When you break down the advertised access time of a hard drive. IDE or SCSI Actually.1 root disk 8. whereas 16-bit is wide. [root@RHEL4b ~]# ls -l /dev/sda* brw-rw---. Optical drives often use atapi. Take a look at http://en.1.1 root disk 8. The time it takes to position the head over a certain track is called the seek time. Older 8-bit SCSI is now called narrow. Data is written in concentric circles or tracks. which are very close to the surface of the platter. Terminology Data is commonly stored on magnetic or optical disk platters. you have to set this manually with jumpers.1 root disk 8. 1 Aug brw-rw---. Blocks can be accessed independent of access to other blocks.Chapter 13. Doubling to 20Mhz made it ultra SCSI. With the introduction of SATA (Serial ATA). 0 Aug brw-rw---. Most desktops use ATA devices. this was known as fast SCSI. Unless your controller and devices support cable select.org/wiki/SCSI for more SCSI-standards. the title should be ATA or SCSI.2. which is an ATA interface using the SCSI communication protocol. The SCSI controller also needs a SCSI ID. Track zero is (usually ?) on the inside. Often the platters are stacked on top of each other.wikipedia. 2 Aug [root@RHEL4b ~]# 4 22:55 /dev/sda 4 22:55 /dev/sda1 4 22:55 /dev/sda2 13. do not use this ID for a SCSI-attached device. When using the Small Computer System Interface. you will notice that most of that time is taken by movement of the heads (about 65%) and rotational latency (about 30%). Data is read by heads. Tracks are divided into 512 byte sectors.

with two ATA-IDE disks present. (We will see later on that LVM volumes are commonly seen as /dev/md0. By simply repartitioning or even after a new mkfs command. it can take a long time! root@RHELv4u2:~# badblocks -ws /dev/sdb Testing with pattern 0xaa: done Reading and comparing: done Testing with pattern 0x55: done Reading and comparing: done Testing with pattern 0xff: done Reading and comparing: done Testing with pattern 0x00: done Reading and comparing: done 13. fdisk You can start by using fdisk to find out what kind of disks are seen by the kernel. Since this is really writing to every sector of the disk. Although technically the badblocks tool is meant to look for bad blocks. the slave is /dev/hdb. Erasing a hard disk Before selling your old hard disk on the internet.9 GB.3.0 GB. it might be a good idea to really erase it. Hard disk devices 13. Device Naming All ATA drives on your system will start with /dev/hd followed by a unit letter. some people will still be able to read most of the data on the disk. 60022480896 bytes Disk /dev/hdb: 81. /dev/md1 etc) 13. For the second controller. Below the result on Debian. root@laika:~# fdisk -l | grep Disk Disk /dev/sda: 100.0 GB. 81964302336 bytes And here an example of SATA disks on a laptop with Ubuntu.0 GB. 100030242816 bytes Disk /dev/sdb: 100. but all start with /dev/sd.4. root@barry:~# fdisk -l | grep Disk Disk /dev/hda: 60. The master hdd on the first ATA controller is /dev/hda.Chapter 13. you can continue with /dev/sdaa and /dev/sdab and so on. 100030242816 bytes 119 . SATA hard disks are presented to you with the SCSI /dev/sdx notation. you can use it to erase a disk.5. the names of the devices are /dev/hdc and /dev/hdd. When you run out of letters (after /dev/sdz). SCSI drives follow a similar scheme.

0 GB. 499036192768 bytes Disk /dev/md0: 271 MB.0 GB. root@laika:~# hdparm /dev/sdb /dev/sdb: IO_support readonly readahead geometry = 0 (default 16-bit) = 0 (off) = 256 (on) = 12161/255/63. 499036192768 bytes Disk /dev/sdd: 499. 1566 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sda1 * /dev/sda2 Start 1 14 End 13 1566 Blocks 104391 12474472+ Id 83 8e System Linux Linux LVM Later we will use fdisk to do dangerous stuff like creating and deleting partitions. hdparm To obtain (or set) information and parameters about an ATA (or SATA) hard disk device.4 GB. sectors = 195371568.Chapter 13. 63 sectors/track. This server is attached to a NAS with four NAS disks of half a terabyte. [root@tsvtl1 ~]# fdisk -l | grep Disk Disk /dev/sda: 73.4 GB. four LVM software RAID devices are configured. On the NAS disks. The -i and -I options will give you even more information about the physical properties of the device. Hard disk devices And last but not least. you can use hdparm.0 GB.4 GB. 73407488000 bytes Disk /dev/sdc: 499. 271319040 bytes Disk /dev/md2: 21. start = 0 120 . 73407488000 bytes Disk /dev/sdb: 73. [root@rhel4 ~]# fdisk -l /dev/sda Disk /dev/sda: 12. 499036192768 bytes Disk /dev/sdf: 499. 21476081664 bytes You can also use fdisk to obtain information about one specific hard disk device. 13. 21467889664 bytes Disk /dev/md1: 21. 21476081664 bytes Disk /dev/md3: 21.0 GB. 499036192768 bytes Disk /dev/sde: 499.6. 12884901888 bytes 255 heads. an overview of disks on a RHEL4u3 server with two real 72GB SCSI disks.8 GB.4 GB.4 GB.

UDMA(33) .Chapter 13. hdb:DMA ide1: BM-DMA at 0xfc08-0xfc0f. you can also use dmesg to find information. BIOS settings: hdc:DMA. CHS=65535/16/63. BIOS settings: hda:DMA. 8192kB Cache. scsi_info You can also use scsi_info. Since hard disk devices are detected by the kernel during boot. ATAPI CD/DVD-ROM drive hdd: SONY DVD RW DRU-810A.0 ANSI SCSI revision: 02 Rev: 0438 ANSI SCSI revision: 03 13. root@shaka:~# cat /proc/scsi/scsi Attached devices: Host: scsi0 Channel: 00 Id: 00 Lun: 00 Vendor: Adaptec Model: RAID5 Type: Direct-Access Host: scsi1 Channel: 00 Id: 00 Lun: 00 Vendor: SEAGATE Model: ST336605FSUN36G Type: Direct-Access root@shaka:~# Rev: V1.0. dmesg Kernel boot messages can be seen after boot with dmesg.0" HOST="1" MODEL="SEAGATE ST336605FSUN36G" FW_REV="0438" root@shaka:~# 121 .. ATA DISK drive hdc: SONY DVD RW DRU-510A. /proc/scsi/scsi You can also look at the contents of /proc/scsi/scsi.7. UDMA(33) hdd: ATAPI 40X DVD-ROM DVD-R CD-R/RW drive.9. Hard disk devices 13. UDMA(100) hda: hda1 hda2 hdb: max request size: 128KiB hdb: 160086528 sectors (81964 MB) w/2048KiB Cache. hdd:DMA hda: ST360021A. 2048kB Cache. CHS=65535/16/63. root@shaka:~# scsi_info /dev/sdb SCSI_ID="0. 13.8. ATA DISK drive hdb: Maxtor 6Y080L0. root@barry:~# dmesg | grep "[hs]d[a-z]" Kernel command line: root=/dev/hda1 ro ide0: BM-DMA at 0xfc00-0xfc07. ATAPI CD/DVD-ROM drive hda: max request size: 128KiB hda: 117231408 sectors (60022 MB) w/2048KiB Cache. UDMA(100) hdb: hdb1 hdb2 hdc: ATAPI 32X DVD-ROM DVD-R CD-R/RW drive..

add a virtual 10 gigabyte SCSI hard disk and a virtual 100 megabyte SCSI hard disk. 2. 4.10.0 0438 /dev/sda /dev/sdb 13. Use badblocks to completely erase the 100 mb hard disk. 3. Use dmesg to make a list of hard disk devices (ide. Hard disk devices 13.ata. lsscsi And even lsscsi if it is installed. Practice hard disk devices 1. 5. 122 . 6. Look at /proc/scsi/scsi.11.sata.Chapter 13. Use fdisk to find the total size of all hard disk devices on your system.scsi) detected at bootup. root@shaka:~# lsscsi [0:0:0:0] disk Adaptec [1:0:0:0] disk SEAGATE root@shaka:~# RAID5 ST336605FSUN36G V1. Use dmesg and fdisk (with grep) to display some information about the new disks. Stop a virtual machine.

root@laika:~# fdisk -l /dev/sdb Disk /dev/sdb: 100.Chapter 14. and /dev/hdb5 is the first logical partition on the second ATA hard disk device.1. 63 sectors/track. 14. Each partition has a type field that contains a code. extended (maximum one) or logical (contained within the extended partition). Partitions can be of type primary (maximum four). Logical partition counting always starts at 5. fdisk -l In the fdisk -l example below you can see that two partitions exist on /dev/sdb2. 14. starting the count at 1. Although partitions reside on the same hard disk device. 12161 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sdb1 /dev/sdb2 root@laika:~# Start 1 32 End 31 12161 Blocks 248976 97434225 Id 82 83 System Linux swap / Solaris Linux 123 . Partition naming We saw before that hard disk devices are named /dev/hdx or /dev/sdx with x depending on the hardware configuration. The second partition is much bigger. Next is the partition number. A partition’s geometry and size is usually defined by a starting and ending cylinder (sometimes by head or even sector).3. This determines the computers operating system or the partitions file system. /dev/sdb3 is the third partition on the second SCSI disk. 100030242816 bytes 255 heads. you can (almost) see them as independent of each other. Partitions 14.2. SAme for SCSI. Thus /dev/hda2 is the second partition on the first ATA hard disk device. Please don’t break your head on the difference between a partition and a slice. Different tools have different interpretations of which is which. About Partitions Linux requires you to create one or more partitions aka slices. The first partition spans 31 cylinders and contains a Linux swap partition. Hence the four (possible) primary partitions are numbered 1 to 4.0 GB.

This example uses fdisk. but it does not have any partitions yet. df In the df -h example below you can see the size.Chapter 14. we bought a new disk for our system.8 GB. the new disk is seen as /dev/sdb. but there is nothing wrong with using parted. 124 . 63 sectors/track. you can use fdisk and parted to create the necessary partition(s). sfdisk and gparted. we check with fdisk -l whether Linux can see the new disk. 63 sectors/track.6. Yes it does.5. used gigabytes and percentage and mount point of a partition.4. 1073741824 bytes 255 heads. 14. 1566 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sda1 * /dev/sda2 Start 1 14 End 13 1566 Blocks Id System 104391 83 Linux 12474472+ 8e Linux LVM Disk /dev/sdb: 1073 MB. root@RHELv4u2:~# fdisk -l Disk /dev/sda: 12. 12884901888 bytes 255 heads. Partitions 14. Partitioning new disks In the example below. 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Disk /dev/sdb doesn’t contain a valid partition table Then we create a partition with fdisk on /dev/sdb. nor Sun. First. Changes will remain in memory only. After the new hardware is properly attached.6G 91% /media/sdb2 root@laika:~# 14. free space. root@laika:~# df -h | egrep -e "(sdb2|File)" Filesystem Size Used Avail Use% Mounted on /dev/sdb2 92G 83G 8. other tools You might be interested in more GUI-oriented alternatives to fdisk and parted like cfdisk. Be very very careful not to partition the wrong disk!! root@RHELv4u2:~# fdisk /dev/sdb Device contains neither a valid DOS partition table. SGI or OSF disklabel Building a new DOS disklabel. First we start the fdisk tool with /dev/sdb as argument.

130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot Start End Blocks Id System No partitions exist yet. but they are not yet written to disk. the previous content won’t be recoverable. We choose p for primary. Partitions until you decide to write them. of course. default 1): Using default value 1 Last cylinder or +size or +sizeM or +sizeK (1-130. Command (m for help): p Disk /dev/sdb: 1073 MB. we can issue the p command to see the current disks partition table. 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sdb1 Start 1 End 14 Blocks Id System 112423+ 83 Linux Command (m for help): w The partition table has been altered! Calling ioctl() to re-read partition table. 1 for the start cylinder and 14 for the end cylinder. 63 sectors/track. so we issue n to create a new partition. 1073741824 bytes 255 heads. After that. and then quit the fdisk tool. so we use w to write the changes to disk. 1 for the partition number. Command (m for help): p Disk /dev/sdb: 1073 MB. 1073741824 bytes 255 heads. Syncing disks. Command (m for help): n Command action e extended p primary partition (1-4) p Partition number (1-4): 1 First cylinder (1-130. 63 sectors/track. default 130): 14 We can now issue p again to verify our changes. This means we can still cancel this operation! But it looks good. Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite) Inside the fdisk tool. root@RHELv4u2:~# 125 .Chapter 14.

Practice Partitions 1. Create four logical drives of one gigabyte each.7. Indeed. 1566 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sda1 * /dev/sda2 Start 1 14 End 13 1566 Blocks Id System 104391 83 Linux 12474472+ 8e Linux LVM Disk /dev/sdb: 1073 MB. 2. 5. Create a 50 MB partition on the small SCSI disk. Compare the output of the two commands. 12884901888 bytes 255 heads. Partitions Let’s verify again with fdisk -l to make sure reality fits our dreams.Chapter 14. 3. 126 . 1073741824 bytes 255 heads. 4. 63 sectors/track.8 GB. the screenshot below now shows a partition on /dev/sdb. Use df and fdisk -l to verify your work. Use fdisk and df to display existing partitions and sizes. Create a primary partition of four gigabyte on the big disk. root@RHELv4u2:~# fdisk -l Disk /dev/sda: 12. 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot Start /dev/sdb1 root@RHELv4u2:~# End 1 14 Blocks Id System 112423+ 83 Linux 14. 63 sectors/track.

. About file systems After you are finished partitioning the hard disk. The properties (length. so you don’t need a file system check after an unclean shutdown or power failure. USB sticks and to exchange data between different OS’ses on a home user’s computer. Journaling means that changes are first written to a journal on the disk.Chapter 15. except for the journaling which is only present in ext3. The journal is flushed regularly. FAT16 on DOS. but vfat lacks a lot of features like security and links.2. file systems usually include directories and access control. 15. Common file systems 15. and FAT32 for larger disks. Besides file-based storage.1. FAT disks can be read by every operating system. you can put a file system on each partition. You can convert an ext2 to ext3 with tune2fs -j. but then you lose the journaling.1.2.2. They are essentially the same. Use mke2fs -j to create an ext3 file system. you will have to learn how this is implemented! Access control in file systems is tracked by user ownership (and group owner. and are used a lot for digital cameras. You can mount an ext3 file system as ext2. A disadvantage is that file system checks on ext2 can take a long time. File Systems 15. Directories are usually implemented as files. character set. You will see that ext2 is being replaced by ext3 on most Linux machines. modification times and file ownership. 15. writing the changes in the file system.. vfat The vfat file system exists in a couple of forms : FAT12 for floppy disks.) of filenames are determined by the file system you choose. and contain meta information about files like access times.and membership) in combination with one or more access control lists. Journaling keeps the file system in a consistent state. 127 . You can create these file systems with the /sbin/mkfs or /sbin/mke2fs commands. Do not forget to run mkinitrd if you are booting from this device..2. A file system is a way of organizing files on your partition. ext2 and ext3 Once the most common Linux file systems is the ext2 (the second extended) file system. The Linux VFAT implementation supports all of these.

3.3 format.ISO extension). You might encounter reiserfs on Linux systems. which allows for filenames up to 255 characters and Unix-style file-modes. but it is not common on Red Hat. Putting a file system on a partition We now have a fresh partition. swap is not a file system.ext3 /sbin/mkdosfs /sbin/mkfs.2. File Systems 15. Chances are you will encounter this file system also on your harddisk in the form of images of CD-ROM’s (often with the . The El Torito standard extends ISO 9660 to be able to boot from CD-ROM’s. others.ext2 /sbin/mkfs.msdos /sbin/mkfs.2. 15. 15. which adds 64 unicode characters to the filename.2. 15. ownership and symbolic links. The system binaries to make file systems can be found with ls. Maybe you will see a zfs. 15.cramfs /sbin/mkswap /sbin/mkfs /sbin/mkbootdisk 128 .vfat /sbin/mkinitrd /sbin/mkzonedb /sbin/mkfs. UDF Most optical media today (including CD’s and DVD’s) use UDF.4. the Universal Disk Format. Another extensions to ISO 9660 is Joliet. or one of the dozen other file systems available. [root@RHEL4b ~]# ls -lS -rwxr-xr-x 3 root root -rwxr-xr-x 3 root root -rwxr-xr-x 3 root root -rwxr-xr-x 3 root root -rwxr-xr-x 3 root root -rwxr-xr-x 3 root root -rwxr-xr-x 1 root root -rwxr-x--.2. swap All things considered. But to use a partition as a swap partition it must be formatted as swap space.3. The ISO 9660 standard limits filenames to the 8.5.1 root root -rwxr-xr-x 1 root root -rwxr-xr-x 1 root root -rwxr-xr-x 1 root root -rwxr-xr-x 1 root root [root@RHEL4b ~]# /sbin/mk* 34832 Apr 34832 Apr 34832 Apr 28484 Oct 28484 Oct 28484 Oct 20313 Apr 15444 Oct 15300 May 13036 May 6912 May 5905 Aug 24 24 24 13 13 13 10 5 24 24 24 3 2006 2006 2006 2004 2004 2004 2006 2004 2006 2006 2006 2004 /sbin/mke2fs /sbin/mkfs.. and thus added the Rock Ridge extensions.6.Chapter 15. The Unix world didn’t like this.. ISO 9660 ISO 9660 is the standard format for CD-ROM’s.

Use tune2fs -c or -i to override. The first screenshot lists the reserved space for root (which is set at five percent).Chapter 15.35 (28-Feb-2004) Setting reserved blocks percentage to 10 (10430 blocks) [root@rhel4 ~]# tune2fs -l /dev/sda1 | grep -i "block count" Block count: 104388 Reserved block count: 10430 [root@rhel4 ~]# 129 . even if it is the root file system (as in this example). 73729 Writing inode tables: done Writing superblocks and filesystem accounting information: done This filesystem will be automatically checked every 37 mounts or 180 days. 57345. 15. whichever comes first. Tuning a file system You can use tune2fs to list and set file system settings.00%) reserved for the super user First data block=1 Maximum filesystem blocks=67371008 14 block groups 8192 blocks per group. In real life. 24577. root@RHELv4u2:~# mke2fs /dev/sdb1 mke2fs 1. you might want to use options like -m0 and -j. 8192 fragments per group 2008 inodes per group Superblock backups stored on blocks: 8193. 40961. File Systems It is time for you to read the manual pages of mkfs and mke2fs. You can use tune2fs while the file system is active. you see the creation of an ext2 file system on /dev/sdb1. In the example below. [root@rhel4 ~]# tune2fs -m10 /dev/sda1 tune2fs 1. 112420 blocks 5621 blocks (5.4.35 (28-Feb-2004) Filesystem label= OS type: Linux Block size=1024 (log=0) Fragment size=1024 (log=0) 28112 inodes. [root@rhel4 ~]# tune2fs -l /dev/sda1 | grep -i "block count" Block count: 104388 Reserved block count: 5219 [root@rhel4 ~]# This example changes this value to ten percent.

Disk Usage The du command can summarize disk usage for files and directories.35 (28-Feb-2004) e2fsck 1. [root@RHEL4b ~]# But after unmounting fsck and e2fsck can be used to check an ext2 file system.6. root@pasha:~# du -sh /home/reet 881G /home/reet 15. [paul@RHEL4b ~]$ grep ext /etc/fstab /dev/VolGroup00/LogVol00 / LABEL=/boot /boot [paul@RHEL4b ~]$ ext3 ext3 defaults defaults 1 1 1 2 Manually checking a mounted file system results in a warning from fsck. [root@RHEL4b ~]# ls /sbin/*fsck* /sbin/dosfsck /sbin/fsck /sbin/e2fsck /sbin/fsck. WARNING!!! Running e2fsck on a mounted filesystem may cause SEVERE filesystem damage. Checking a file system The fsck command is a front end tool used to check a file system for errors.vfat The last column in /etc/fstab is used to determine whether a file system should be checked at bootup.cramfs [root@RHEL4b ~]# /sbin/fsck.msdos /sbin/fsck. This option is often used together with -h. so du -sh on a mount point gives the total amount used in that partition.ext2 /sbin/fsck. Do you really want to continue (y/n)? no check aborted.35 (28-Feb-2004) /dev/sda1 is mounted. [root@RHEL4b ~]# fsck /boot fsck 1. File Systems 15. [root@RHEL4b ~]# fsck /boot fsck 1. 17598/104388 blocks [root@RHEL4b ~]# fsck -p /boot 130 .Chapter 15. 44/26104 files.5.35 (28-Feb-2004) /boot: clean.ext3 /sbin/fsck.35 (28-Feb-2004) e2fsck 1. Preventing du to go into subdirectories with the -s option will give you a total for that directory.

7. 3.Chapter 15. Practice File Systems 1. 5. 17598/104388 blocks [root@RHEL4b ~]# 15. 44/26104 files. Create an ext3 filesystem on the 4GB primary and one of the 1GB logical drives. 17598/104388 blocks [root@RHEL4b ~]# e2fsck -p /dev/sda1 /boot: clean. Verify your work with the usual commands. 131 .35 (28-Feb-2004) /boot: clean. 44/26104 files. File Systems fsck 1. 2. 6. Set the reserved space for root on the logical drive to 0 percent. List the filesystems that are known by your system. 4. Create an ext2 filesystem on the 50MB partition. Put a reiserfs on one of the logical drives.

root@RHELv4u2:~# mkdir /home/project55 root@RHELv4u2:~# mount -t ext2 /dev/sdb1 /home/project55/ root@RHELv4u2:~# ls /home/project55/ lost+found root@RHELv4u2:~# Actually the explicit -t ext2 option to set the file system is not always necesarry. The kernel provides the info in /proc/mount in file form. Displaying mounted file systems To view all mounted file systems. Looking at /proc/mount is the best way to be sure. usually as a directory. 16. and the mounting of an ext2 partition on a newly added SCSI disk. the new file system is accessible to users. Once mounted.Chapter 16. The mount command is able to automatically detect a lot of file systems on partitions. root@RHELv4u2:~# cat /proc/mounts | grep /dev/sdb /dev/sdb1 /home/project55 ext2 rw 0 0 root@RHELv4u2:~# cat /etc/mtab | grep /dev/sdb /dev/sdb1 /home/project55 ext2 rw 0 0 root@RHELv4u2:~# mount | grep /dev/sdb /dev/sdb1 on /home/project55 type ext2 (rw) A more user friendly way to look at mounted hard disks is df. The /etc/mtab file on the other hand is updated by the mount command. df supports the -h switch to make the output more human readable.1. look at the files /proc/mounts or /etc/mtab. The df(diskfree) command has the added benefit of showing you the free space on each mounted disk. When adding a file system to your computer. you need to make it available somewhere in the file tree. you need to know the full path starting from the root directory. every file and every directory is part of one big file tree. We say mounting a file system instead of mounting a partition because we will see later that we can also mount file systems that do not exists on partitions. 132 . Do not edit /etc/mtab manually! Another way to view all mounts is by issuing the mount command without any arguments. Like a lot of Linux commands. Mounting a file system makes it available for use. you can mount it. The screenshot below pipes the output of these three through grep. since the information comes directly from the kernel. Mounting Once you’ve put a file system on a partition. 16. Mounting local disks On all Unix systems. To access a file. but /proc/mount does not exist as a file on any hard disk.2. The screenshot below shows the creation of a mount point. to only show our added SCSI disk. The directory where you make a file system available is called a mount point.

Practice File Systems 1. the copy some files to it (everything in /etc). 3. root@RHELv4u2:~# cat /etc/fstab /dev/VolGroup00/LogVol00 / LABEL=/boot /boot none /dev/pts none /dev/shm none /proc none /sys /dev/VolGroup00/LogVol01 swap ext3 ext3 devpts tmpfs proc sysfs swap defaults defaults gid=5. until the next reboot.3.1M 85M 10% /boot none 125M 0 125M 0% /dev/shm /dev/sdb1 107M 1. The first line is for our freshly added SCSI disk. Permanent mounts Until now. Mount the small 50MB partition on /home/project22. Also look in /etc and /proc to interesting files.6M 100M 2% /home/project55 16. This is done using the file system table located in the /etc/fstab file. 2. we can automate the mounting of these file systems. we performed all mounts manually. Verify your work with fdisk. Luckily there is a way to tell your computer to automatically mount certain file systems during boot. /dev/sdb1 server12:/mnt/data/iso /home/project55 /home/iso ext2 nfs defaults defaults 0 0 0 0 16. Below is a sample /etc/fstab file.Chapter 16. the second line mounts an NFS share. mount.4. Then mount the partition as read only on /srv/nfs/salesnumbers. Mount the big primary partition on /mnt. 133 . df.1G 4.mode=620 defaults defaults defaults defaults 1 1 0 0 0 0 0 1 2 0 0 0 0 0 By adding the following two lines. Mounting root@RHELv4u2:~# df Filesystem 1K-blocks Used Available Use% Mounted on /dev/mapper/VolGroup00-LogVol00 11707972 6366996 4746240 58% / /dev/sda1 101086 9300 86567 10% /boot none 127988 0 127988 0% /dev/shm /dev/sdb1 108865 1550 101694 2% /home/project55 root@RHELv4u2:~# df -h Filesystem Size Used Avail Use% Mounted on /dev/mapper/VolGroup00-LogVol00 12G 6.6G 58% / /dev/sda1 99M 9. This works nice.

5. Perform a file system check on the partition mounted at /srv/nfs/salesnumbers. test that it works.Chapter 16. apropos and which. Mounting 4. whereis. Make both mounts permanent. 8. 134 . What happens when you mount a partition on a directory that contains some files ? 6. locate. Describe the difference between these file searching commands: find. What happens when you mount two partitions on the same mountpoint ? 7. updatedb.

paul@RHELv4u4:~/test$ ls -li total 16 817266 -rw-rw-r-. Let’s put some data in one of the files.Chapter 17.1 paul paul 92 Feb 817268 -rw-rw-r-.1 paul paul 0 Feb 817267 -rw-rw-r-.1 paul paul 0 Feb 817268 -rw-rw-r-. Looking at our current directory with ls -ali will display the contents of the directory file.1 paul paul 0 Feb paul@RHELv4u4:~/test$ cat file2 It is winter now and it is very cold.1. but also some extra properties like the name of the file. paul@RHELv4u4:~/test$ touch file1 paul@RHELv4u4:~/test$ touch file2 paul@RHELv4u4:~/test$ touch file3 paul@RHELv4u4:~/test$ ls -li total 12 817266 -rw-rw-r-.2.. When the file system stores a new file on the hard disk. Most of them are unused and empty. but somewhere else on the disk. 135 . You can see the inode numbers with the ls -li command. the permissions. It contains a table mapping filenames to inodes. The data that is displayed by the cat commend is not in the inode. About directories A directory is a special kind of file. We do not like the cold. you first have to understand what an inode is. each inode has a unique number (the inode number). we prefer hot paul@RHELv4u4:~/test$ 5 15:38 file1 5 15:42 file2 5 15:38 file3 summer nights. About inodes To understand links in a file system. File Links 17. All the information you see with this ls command resides in the inode. All this information (except the name of the file and the data) is stored in the inode of the file.1 paul paul 0 Feb paul@RHELv4u4:~/test$ 5 15:38 file1 5 15:38 file2 5 15:38 file3 Three files created one after the other get three different inodes (the first column). it stores not only the contents (data) of the file. the owner of the file. All the inodes are created when you create the file system (with mkfs). 17. and more. except for the filename (which is contained in the directory).1 paul paul 0 Feb 817270 -rw-rw-r-. But the inode contains a pointer to the data.. the creation date.

2 paul paul 92 Feb 5 15:42 file2 817268 -rw-rw-r-.1 paul paul 0 Feb 5 15:38 file3 817270 -rw-rw-r-.4. the hardlinked file will remain. 136 . paul@RHELv4u4:~/test$ ln file2 hardlink_to_file2 paul@RHELv4u4:~/test$ ls -li total 24 817266 -rw-rw-r-. Symbolic links Symbolic links (sometimes called soft links) do not link to inodes. is a mapping to itself. meaning you can safely remove the original file. and the mapping to their five inodes. file1 file2 file3 You can see five names. but create a name to name mapping. both files are equal now. The three others are mappings to files. The dot . then the inode is emptied.. When the counter drops to zero. the symbolic link gets an inode of its own. 17. The screenshot below proves that / and /boot are different partitions. As you can see below. is a mapping to the parent directory. You can use the find command to look for files with a certain inode.Chapter 17. counting the number of hard links to itself. .2 paul paul 92 Feb 5 15:42 hardlink_to_file2 paul@RHELv4u4:~/test$ Both files have the same inode. and the dotdot . And they will both have the same content.. Hard links When we create a hard link to a file. File Links paul@RHELv4u4:~/test$ total 32 817262 drwxrwxr-x 2 800768 drwx-----. so they will always have the same permissions and the same owner. paul@RHELv4u4:~/test$ find / -inum 2 2> /dev/null / /boot /var/lib/nfs/rpc_pipefs/lockd /proc/self paul@RHELv4u4:~/test$ 17. since every inode number is unique to the partition. The inode contains a counter.1 paul paul 0 Feb 5 15:38 file1 817270 -rw-rw-r-.16 817266 -rw-rw-r-1 817270 -rw-rw-r-1 817268 -rw-rw-r-1 paul@RHELv4u4:~/test$ ls -ali paul paul paul paul paul paul 4096 Feb paul 4096 Feb paul 0 Feb paul 92 Feb paul 0 Feb 5 5 5 5 5 15:42 15:42 15:38 15:42 15:38 . Actually.3. then an extra entry is added in the directory. A new file name is mapped to an existing inode.

137 .2 paul paul 106 Feb 817268 -rw-rw-r-.Chapter 17. Create a symbolic link to summer. Display the inode numbers of these three files. since the permissions of the target apply. except two things : name them! 6.d/ /etc/rc. put some text in them...txt. Hard links are limited to their own partition (because they point to an inode). 7. Create two files named winter. do you see the links ? 9. Look in /lib with ls -l.txt named hlwinter.d/ .txt. 2. Everything about a file is in the inode.. Find all files with inode number 2. Create a hard link to winter. even networked).1 paul paul 13 Feb 817270 -rw-rw-r-.2 paul paul 106 Feb 817267 lrwxrwxrwx 1 paul paul 5 Feb paul@RHELv4u4:~/test$ 5 5 5 5 5 17:06 17:04 15:38 17:04 16:55 file1 file2 file3 hardlink_to_file2 symlink_to_file2 -> file2 Permissions on a symbolic link have no meaning.txt. symbolic links can link anywhere (other file systems. Look at the directories /etc/init. 3..5. 17. Practice Links 1. Use the find command to list the two hardlinked files 5. What does this information tell you ? 8.txt and summer. 4.1 paul paul 0 Feb 817270 -rw-rw-r-. the hard links should have the same inode.txt called slsummer. File Links paul@RHELv4u4:~/test$ ls -li total 32 817273 -rw-rw-r-.d/ /etc/rc3.

1 boot.3 cron.log.Chapter 18.log lastlog news mail pgsql maillog ppp maillog.1 prelink.0.syslog anaconda.log.1.0.xlog audit boot.2 spooler.1 rpmpkgs.2 rpmpkgs. /var/log The location for log files according to the FHS is /var/log.4 sa samba scrollkeeper.2.1.3 maillog.1.4 squid uucp vbox vmware-tools-guestd wtmp wtmp.log quagga radius rpmpkgs rpmpkgs.log.2 maillog.log secure secure.4 canna cron cron.2 secure.1 gdm messages.log.log Xorg.4 spooler spooler.3 secure. You will find a lot of log files and directories for common applications in /var/log.4 cups mailman dmesg messages exim messages. [root@RHEL4b ~]# tail /var/log/messages Jul 30 05:13:56 localhost anacron: anacron startup succeeded Jul 30 05:13:56 localhost atd: atd startup succeeded Jul 30 05:13:57 localhost messagebus: messagebus startup succeeded Jul 30 05:13:57 localhost cups-config-daemon: cups-config-daemon startup succeeded Jul 30 05:13:58 localhost haldaemon: haldaemon startup succeeded Jul 30 05:14:00 localhost fstab-sync[3560]: removed all generated mount points Jul 30 05:14:01 localhost fstab-sync[3628]: added mount point /media/cdrom for /dev/hdc Jul 30 05:14:01 localhost fstab-sync[3646]: added mount point /media/floppy for /dev/fd0 Jul 30 05:16:46 localhost sshd(pam_unix)[3662]: session opened for user paul by (uid=0) Jul 30 06:06:37 localhost su(pam_unix)[3904]: session opened for user root by paul(uid=50 [root@RHEL4b ~]# 138 .3 rpmpkgs. About logging 18.log.1 secure. By default this file will contain information on what just happened to the system.2 cron.3 boot. Logging 18.1 spooler.old 18.3 spooler.1 [paul@RHEL4b ~]$ ls /var/log cron.log anaconda.1 Xorg.4 maillog.2 httpd messages. /var/log/messages A typical first file to check when troubleshooting is the /var/log/messages file.4 iptraf mysqld.1. [paul@RHEL4b ~]$ acpid amanda anaconda.3 iiim messages.2 boot.log boot.

/var/run/utmp (who) Use the who command to see the /var/run/utmp file.ELs Wed Feb 14 18:21 (01:15) pc-dss.11:36 (00:01) pc-dss.1.telematic Wed Feb 14 10:03 .2.12:40 (00:12) pc-nae.2.telematic Wed Feb 14 11:34 .1.45 Wed Feb 14 18:39 still logged in 2. /var/log/wtmp (last) The /var/log/wtmp file is updated by the login program.6.telematic Wed Feb 14 07:16 .3.12:31 (02:28) pc-nae.168.6.telematic Wed Feb 14 11:36 .8.telematic Wed Feb 14 12:28 . /var/run/utmp and /var/log/lastlog files. /var/log/lastlog (lastlog) Use lastlog to see the /var/log/lastlog file.9-42.11:34 (01:48) rhel4 Wed Feb 14 07:57 .Chapter 18.08:38 (00:40) pc-sde.12:21 (00:45) pc-nae.122 rm pts/6 rhel4 Tue Feb 13 09:36:54 +0100 2007 Tue Feb 13 10:06:56 +0100 2007 139 .telematic Wed Feb 14 12:32 . [root@rhel4a ~]# lastlog | tail tim pts/5 10. [root@rhel4a ~]# last paul pts/1 reboot system boot nicolas pts/5 stefaan pts/3 nicolas pts/3 nicolas pts/3 dirk pts/5 nicolas pts/3 dimitri pts/5 stefaan pts/4 [root@rhel4a ~]# | head 192. [paul@rekkie ~]$ last reboot reboot system boot 2.13:06 (00:33) pc-sde.0.2. 18. Linux can maintain the /var/log/wtmp.168.telematic Wed Feb 14 09:45 .1. Login logging To keep track of who is logging into the system. /var/log/btmp. Logging 18.170.45) 18. [root@rhel4a ~]# who paul pts/1 Feb 14 18:39 (192. Use last to see the /var/run/wtmp file.16-rekkie wtmp begins Tue May 30 23:11:45 2006 [paul@rekkie ~]$ Mon Jul 30 05:13 (370+08:42) 18.2.1.2.down (05:50) The last command can also be used to get a list of last reboots.

rlogin or su are not registered in /var/log/btmp. Failed logins via tty are.telematic Wed Feb 14 12:28:38 +0100 2007 pc-dss. Doing a chmod o-r /var/log/btmp improves security.telematic Wed Feb 14 10:03:11 +0100 2007 **Never logged in** pc-dss. Logging henk stefaan dirk arsene nicolas dimitri bashuserrm kornuserrm [root@rhel4a ~]# **Never logged in** pc-sde.4. so it contains failed login attempts.2.07:09 Mon Jul 30 07:09 . [root@RHEL4b ~]# lastb lastb: /var/log/btmp: No such file or directory Perhaps this file was removed by the operator to prevent logging lastb info. [root@RHEL4b ~]# The reason given for this is that users sometimes type their password by mistake instead of their login.Chapter 18. [root@RHEL4b ~]# touch /var/log/btmp [root@RHEL4b ~]# ll /var/log/btmp -rw-r--r-. This file is updated by the login program when entering the wrong password.07:10 Mon Jul 30 07:09 . /var/log/btmp (lastb) There is also the lastb command to display the /var/log/btmp file. You can enable bad login logging by simply creating the file.telematic Wed Feb 14 12:32:18 +0100 2007 rhel4 Wed Feb 14 07:57:19 +0100 2007 rhel4 Tue Feb 13 10:35:40 +0100 2007 rhel4 Tue Feb 13 10:06:17 +0100 2007 pts/3 pts/5 pts/5 pts/5 pts/7 pts/5 18. Many computers will not have this file. resulting in no logging of failed login attempts. [root@RHEL4b ~]# lastb HalvarFl tty3 Maria tty1 Roberto tty1 btmp begins Mon Jul 30 07:09:32 2007 [root@RHEL4b ~]# Mon Jul 30 07:10 .1 root root 0 Jul 30 06:12 /var/log/btmp [root@RHEL4b ~]# chmod o-r /var/log/btmp [root@RHEL4b ~]# lastb btmp begins Mon Jul 30 06:12:19 2007 [root@RHEL4b ~]# Failed logins via ssh. so this world readable file poses a security risk.07:09 (00:00) (00:00) (00:00) 140 .

52 port 38752 ssh2 Jul 30 08:27:33 localhost sshd[5018]: Invalid user roberto from ::ffff:192.1.1.168.52 port 41064 ssh2 Jul 30 08:27:36 localhost sshd[5018]: Failed password for invalid user roberto f\ rom ::ffff:192.1.168.168.1. About syslog The standard method of logging on Linux is through the syslogd daemon.1.1.5.3.1.* /var/log/customsec.2.log. Some distributions put this in /var/log/auth.1.52 port 38752 ssh2 Jul 30 05:22:30 localhost sshd[4656]: Failed password for Hermione from ::ffff:1\ 92.1.168.168. The syslog daemon can receive messages on udp port 514 from many applications (and appliances). Syslogd daemon 18. Logging 18.*.52 port 38752 ssh2 Jul 30 07:22:33 localhost sshd[4655]: Failed password for Hermione from ::ffff:1\ 92. with a custom logfile by adding the following line tot syslog.52 port 38752 ssh2 Jul 30 05:22:27 localhost sshd[4656]: Failed password for Hermione from ::ffff:1\ 92.168.168.1.log 18.168.1. verify the syslog configuration.52 port 41064 ssh2 Jul 30 06:27:36 localhost sshd[5019]: Failed password for invalid user roberto f\ rom ::ffff:192. and can append to logfiles.168. auth.1.168. [root@RHEL4b ~]# cat /var/log/secure Jul 30 07:09:03 localhost sshd[4387]: Accepted publickey for paul from ::ffff:19\ 2.52 port 33188 ssh2 Jul 30 07:22:27 localhost sshd[4655]: Failed password for Hermione from ::ffff:1\ 92.52 port 41064 ssh2 Jul 30 06:27:33 localhost sshd[5019]: Failed publickey for invalid user roberto \ from ::ffff:192.168. but quickly became a standard among many Unix applications and was much later written as rfc 3164.52 port 38752 ssh2 Jul 30 05:22:33 localhost sshd[4656]: Failed password for Hermione from ::ffff:1\ 92. Syslog was developed by Eric Allman for sendmail.168.conf. This log will include su and/or ssh failed login attempts.1\ .Chapter 18. you may also have the /var/log/secure file being filled with messages from the auth and/or authpriv syslog facilities.1.52 port 33188 ssh2 Jul 30 05:09:03 localhost sshd[4388]: Accepted publickey for paul from ::ffff:19\ 2.168.52 port 38752 ssh2 Jul 30 07:22:30 localhost sshd[4655]: Failed password for Hermione from ::ffff:1\ 92.3. display messages on terminals 141 .52 Jul 30 06:27:33 localhost sshd[5019]: input_userauth_request: invalid user rober\ to Jul 30 06:27:33 localhost sshd[5019]: Failed none for invalid user roberto from \ ::ffff:192. print.authpriv. su and ssh logins Depending on the distribution.52 port 41064 ssh2 [root@RHEL4b ~]# You can enable this yourself.

Levels The worst severity a message can have is emerg followed by alert and crit. Facilities The man syslog. Logging and forward logs to other syslogd daemons on other machines. lpr. debug info notice warning (warn) err (error) crit alert emerg (panic) 142 . The syslogd daemon is configured in /etc/syslog.conf version 1. 18. auth (security) authpriv cron daemon ftp kern lpr mail mark (internal use only) news syslog user uucp local0-7 18. and an action to decide on what to do with the message.3.none to prevent a specific action from any message from a certain facility. The local0 to local7 facility can be used for appliances (or any networked device that supports syslog). such as mail. You can also specify .conf. Here is a list of all facilities for syslog. news and kern(el) messages. Here is a list of all levels.3. It also contains a level for the severity of the message. Lowest priority should go to info and debug messages.conf will explain the different default facilities for certain daemons.3. The keywords warn.Chapter 18. Specifying a severity will also log all messages with a higher severity. You can prefix the severity with = to obtain only messages that match that severity. The security keyword is deprecated. error and panic are deprecated. in ascending order. Each line in the configuration file uses a facility to determine where the message is coming from.3.2.

=crit local4. Configuration Below a sample configuration of custom local4 messages in /etc/syslog.5.3. seperated by comma’s message to all logged on users file (can be a printer. You can aslo use it in scripts. but also a printer or terminal). 18.4.emerg "l4 emerg" ~]# 143 .3. An example of testing syslogd with the logger tool. Here is a list of all possible actions. Logging 18..* /var/log/critandabove /var/log/onlycrit /var/log/alllocal4 Don’t forget to restart the server.4.Chapter 18. root.conf. local4.) file. The @ sign prefix will send the message on to another syslog server.crit local4. When the action is prefixed with a / then syslog will send the message to the file (which can be a regular file. you can prefix actions with a . Actions The default action is to send a message to the username listed as action. a tty. but don’t sync after every write named pipe other syslog hostname In addition.user1 * / -/ | @ list of users.d/syslog restart Shutting down kernel logger: Shutting down system logger: Starting system logger: Starting kernel logger: [root@rhel4a ~]# [ [ [ [ OK OK OK OK ] ] ] ] 18.. a console. [root@rhel4a [root@rhel4a [root@rhel4a [root@rhel4a ~]# logger -p local4. [root@rhel4a ~]# /etc/init.crit "l4 crit" ~]# logger -p local4. .debug "l4 debug" ~]# logger -p local4. logger The logger command can be used to generate syslog test messages.to omit syncing the file after every logging.

5. [root@rhel4a ~]# cat /var/log/critandabove Feb 14 19:55:19 rhel4a paul: l4 crit Feb 14 19:55:28 rhel4a paul: l4 emerg [root@rhel4a ~]# cat /var/log/onlycrit Feb 14 19:55:19 rhel4a paul: l4 crit [root@rhel4a ~]# cat /var/log/alllocal4 Feb 14 19:55:11 rhel4a paul: l4 debug Feb 14 19:55:19 rhel4a paul: l4 crit Feb 14 19:55:28 rhel4a paul: l4 emerg [root@rhel4a ~]# 18. Watching logs You might want to use the tail -f command to look at the last lines of a log file.Chapter 18. Test that it works! 7. 18. Rotating logs A lot of log files are always growing in size.info only . 144 . You can do the same for the login logfiles with the watch command. Configure /var/log/Mysu.7. understand the difference. 4. remove and mail logfiles. 18. compress. Use the lastlog and lastb commands. Practice Logging 1.log. you might want to use logrotate to rotate. 2.error and above messages in /var/log/l4e.log. Display the /var/run/utmp file. 5. To keep this within bounds. all the su to root messages should go in that log. The -f option will dynamically display lines that are appended to the log. Test that it works. Display the /var/log/wtmp file. More info on the logrotate command in the scheduling chapter. 3. Test that it works with the logger tool! 6.info in /var/log/l4i. Examine syslog to find the location of the log file continaing ssh failed logins.6. Send the local5 messages to the syslog server of your neighbour. Configure syslog to put local4.log and local4. Logging The results of the tests with logger.

Chapter 18. Use tail -f and watch on your local4 log files. 145 . Logging 8. Write a script that executes logger to local4 every 5 seconds (different message).

.1. and although slow booting is not a problem on servers where uptime is measured in years. 19. the recent uptake of linux on the desktop results in user complaints.. 19. There is also an ongoing effort to create initng (init next generation). /etc/inittab After the kernel. implying some kind of satanic connection between UNIX and the underworld. "Daemon" is actually a much older form of "demon". In more recent technical writings.Chapter 19. Unix daemons are not to be confused with demons. The init daemon has PID 1. Booting The details on what happens between ’power on’ and ’kernel loading’ are discussed later in the booting Linux chapter.3. but rather serve to help define a person’s character or personality. Daemons A daemon is a process that runs in background. This is an egregious misunderstanding.2. Init will read its configuration file /etc/inittab. Both systems are asynchronous and can replace the SysV init scripts. System init 19. and stay alive until the system shuts down. Evi Nemeth. it starts the init daemon. In that file. /sbin/init is started with PID 1.3. To improve linux (and Solaris) startup speed. Many unix and linux systems use(d) init scripts to start daemons in the System V release 4 style (explained in detail below).. Daemons are usually started at system boot. Canonical has developed upstart (first used in Ubuntu) and Sun has developed Service Management Facility for Solaris 10.1. [paul@rhel4 ~]$ grep ^id /etc/inittab id:3:initdefault: 146 . Init 19. daemons have no particular bias towards good or evil. But this synchronous (one after the other) method of starting daemons is slow. daemons are often refered to as services. The ancient Greeks’ concept of a "personal daemon" was similar to the modern concept of a "guardian angel" . When the kernel is loaded. it will look for the value of initdefault (3 in the screenshot below). without a link to a GUI or terminal. co-author of the UNIX System Administration Handbook has the following to say about daemons: Many people equate the word "daemon" with the word "demon".

like here on Red Hat Enterprise Linux 4. Some Debian and derived linux systems have full network and GUI logon on runlevels 2 to 5. Besides runlevels 0. Runlevel This number indicates the default runlevel. [paul@rhel4 ~]$ egrep -e"^# Ini" -e"^# Sta" -e"^# Che" /etc/rc. 1 and 6.reboot (Do NOT set initdefault to this) # Runlevel 0 means the system is shutting down. 19. [paul@rhel4 ~]$ That egrep command could also have been written with grep like this : grep "^# \(Ini\|Sta\|Che\)".X11 # 6 .Full multiuser mode # 4 . whereas runlevel 5 is typical for desktops (graphical logon).sysinit script (/etc/init. init will run the /etc/rc. l0:0:wait:/etc/init. mounting file systems. Runlevel 1 is used for troubleshooting.d/rc. starting swap and more.sysinit # Check SELinux status # Initialize hardware # Start the graphical boot. sysinit Independent of the runlevel.4.2. # Check to see if SELinux requires a relabel # Initialize pseudo-random number generator # Start up swapping.Multiuser.d/rc 1 147 . only the root user can log on. Some linuxes have a brief description of runlevels in /etc/inittab. # Default runlevel.3. and only at the console. So always verify the proper meaning of runlevels on your system. rc scripts Init will continue to read /etc/inittab and meets this section on debian linux. so we # Initialiaze ACPI bits # Check filesystems # Start the graphical boot. if you do not have networking) # 3 .3. populating /etc/mtab. without NFS (The same as 3. the use may vary depending on the distribution.Chapter 19. if necessary.d/rc 0 l1:1:wait:/etc/init.d/rc.Single user mode # 2 . if necessary and not done yet.3. /usr may not be mounted yet. Runlevel 3 is typical for servers.halt (Do NOT set initdefault to this) # 1 .unused # 5 . # Initialize the serial ports. The runlevels used by RHS are: # 0 . 19.3. System init 19. This script does a lot of things : setting environment.d/rcS on debian).

d/rc l1:1:wait:/etc/rc.d/rc l6:6:wait:/etc/init.d/rc l3:3:wait:/etc/init.d.3. scripts with uppercase S are started in alphabetical order with "start" as the only parameter. So in both cases. the same happens for scripts starting with K.d is rc.d/rc 0 1 2 3 4 5 6 In both cases. init will continue to read /etc/inittab. 19.d/rc l4:4:wait:/etc/init.d/rc l5:5:wait:/etc/rc.d/rc l5:5:wait:/etc/init.d/rc l3:3:wait:/etc/rc. The second field determines the runlevel in which this line should be executed. The init process never stops keeping an eye on power failures and that triple key combo. When you take a look in the relevant /etc/rc3. System Shutting Down" pr:12345:powerokwait:/sbin/shutdown -c "Power Restored. this means that init will start the rc script with as only parameter the runlevel.d/rc3. powerok and Ctrl-Alt-Delete.d on Red Hat. only one line of the seven will be executed. depending on the runlevel set by initdefault. When entering a runlevel. Power and Ctrl-Alt-Del When rc is finished starting all those scripts. When leaving a runlevel.d/rc l4:4:wait:/etc/rc.d/rc l2:2:wait:/etc/rc.d/rc l6:6:wait:/etc/rc.Chapter 19.d/powerfail start pn::powerfailnow:/etc/init. Actually /etc/inittab has fields seperated by colons. paul@barry:~$ grep "\(^c\|^p\)" /etc/inittab ca:12345:ctrlaltdel:/sbin/shutdown -t1 -a -r now pf::powerwait:/etc/init.d/powerfail stop 148 . System init l2:2:wait:/etc/init. then you will see a lot of (links to) scripts who’s name start with either uppercase K or uppercase S.d/rc 2 3 4 5 6 (on Red Hat Enterprise Linux it is identical except init.d/powerfail now po::powerokwait:/etc/init.d directory. l0:0:wait:/etc/rc. All this is done by the rc script. The relevant part on Red Hat Enterprise Linux.5. [paul@RHEL4b ~]$ grep "\(^c\|^p\)" /etc/inittab ca::ctrlaltdel:/sbin/shutdown -t3 -r now pf::powerfail:/sbin/shutdown -f -h +2 "Power Failure. Shutdown Cancelled" And very similar on Debian Etch. It will read commands on what to execute in case of powerfailure. which is real on debian and a symbolic link to /etc/rc.

Don’t forget to tell init about the change of its configuration file with kill -1 1. getty Almost at the end of /etc/inittab. the init daemon will respawn a new mingetty. When this happens. and watched until they die (user exit’s the shell and is logged out). they will be reborn automatically. there is a section to start and respawn several mingetty’s. [root@RHEL4b 3038 tty1 3039 tty2 3040 tty3 3041 tty4 3042 tty5 3043 tty6 [root@RHEL4b [root@RHEL4b 4774 tty1 4884 tty2 4974 tty3 5026 tty4 5073 tty5 5098 tty6 [root@RHEL4b ~]# ps fax |grep mingetty Ss+ 0:00 /sbin/mingetty Ss+ 0:00 /sbin/mingetty Ss+ 0:00 /sbin/mingetty Ss+ 0:00 /sbin/mingetty Ss+ 0:00 /sbin/mingetty Ss+ 0:00 /sbin/mingetty ~]# kill 3038 3039 3040 3041 ~]# ps fax |grep mingetty Ss+ 0:00 /sbin/mingetty Ss+ 0:00 /sbin/mingetty Ss+ 0:00 /sbin/mingetty Ss+ 0:00 /sbin/mingetty Ss+ 0:00 /sbin/mingetty Ss+ 0:00 /sbin/mingetty ~]# tty1 tty2 tty3 tty4 tty5 tty6 3042 3043 tty1 tty2 tty3 tty4 tty5 tty6 You can disable a mingetty for a certain tty by removing the runlevel from the second field in its line in /etc/inittab. login passes control to the shell listed in /etc/passwd. The login program will verify whether that user exists in /etc/passwd and prompt for (and verify) a password. System init 19.3. [root@RHEL4b ~]# grep getty /etc/inittab # Run gettys in standard runlevels 1:2345:respawn:/sbin/mingetty tty1 2:2345:respawn:/sbin/mingetty tty2 3:2345:respawn:/sbin/mingetty tty3 4:2345:respawn:/sbin/mingetty tty4 5:2345:respawn:/sbin/mingetty tty5 6:2345:respawn:/sbin/mingetty tty6 [root@RHEL4b ~]# A mingetty will display a message on a virtual console and allow you to type a userid and sends that info to the login program.Chapter 19. 149 .6. So the getty’s are started by init. If the password is correct. So even if you kill the mingetty’s.

6. The runlevel command is typical linux and will output the previous and the current runlevel. These can also be used when the system is running to start and stop daemons (or services).5. then it will mark it with the letter N. [root@RHEL4b ~]# service smb restart Shutting down SMB services: Shutting down NMB services: Starting SMB services: Starting NMB services: [root@RHEL4b ~]# [ [ [ [ OK OK OK OK ] ] ] ] 19. Changing the runlevel You can switch to another runlevel with the telinit command.d. and it still works on linux.. status. root@laika:~# [ OK ] [ OK ] You can achieve the same result on Red Hat and derived linuxes with the service command.. System init 19. root@laika:~# /etc/init. Display the runlevel You can see your current runlevel with the runlevel or who -r commands.d/init.d/samba restart * Stopping Samba daemons..4. * Starting Samba daemons. restart. If there was no previous runlevel. stop. On Linux /sbin/telinit is usually a hard link to /sbin/init. [root@RHEL4b ~]# runlevel N 3 The history of who -r dates back to older unixes. Starting and stopping daemons The K and S scripts usually are links to the real scripts in /etc/init. 150 .. Most of them accept the following parameters: start.d or /etc/rc.Chapter 19. [root@RHEL4b ~]# who -r run-level 3 Jul 28 09:15 last=S 19.

Chapter 19. System init

19.7. more info
You might also want to take a look at chkconfig, update-rc.d, shutdown, poweroff and passing init=/bin/bash to the kernel.

19.8. Practice
1. Change /etc/inittab so that only two mingetty’s are respawned. Kill the other mingetty’s and verify that they don’t come back. 2. Use the Red Hat Enterprise Linux 4 virtual machine. Go to runlevel 5, display the current and previous runlevel, then go back to runlevel 3. 3. Is the sysinit script on your computers setting or changing the PATH environment variable ? 4. Write a script that acts like a daemon script in /etc/init.d/. It should have a case statement to act on start/stop/restart and status. Test the script! 5. Have your script started automatically in runlevel 3, test that it works. If it works, also try stopping it in a runlevel. 6. If time permits, use chkconfig to setup your script in runlevels 2 and 3.

151

Chapter 20. Scheduling
20.1. at
Simple scheduling can be done with the at command. This screenshot shows the scheduling of the date command at 22:01 and the sleep command at 22:03. In real life you will hopefully be scheduling more useful commands.
root@laika:~# at 22:01 at> date at> <EOT> job 1 at Wed Aug 1 22:01:00 2007 root@laika:~# at 22:03 at> sleep 10 at> <EOT> job 2 at Wed Aug 1 22:03:00 2007 root@laika:~#

It is easy to check what is scheduled with the atq or at -l commands.
root@laika:~# atq 1 Wed Aug 1 22:01:00 2 Wed Aug 1 22:03:00 root@laika:~# at -l 1 Wed Aug 1 22:01:00 2 Wed Aug 1 22:03:00 root@laika:~#

2007 a root 2007 a root 2007 a root 2007 a root

The at command understands English words like tomorrow and teatime.
root@laika:~# at 10:05 tomorrow at> sleep 100 at> <EOT> job 5 at Thu Aug 2 10:05:00 2007 root@laika:~# at teatime tomorrow at> tea at> <EOT> job 6 at Thu Aug 2 16:00:00 2007 root@laika:~# atq 6 Thu Aug 2 16:00:00 2007 a root 5 Thu Aug 2 10:05:00 2007 a root root@laika:~#

Jobs in the at queue can be removed with atrm.
root@laika:~# atq 6 Thu Aug 2 16:00:00 2007 a root 5 Thu Aug 2 10:05:00 2007 a root

152

Chapter 20. Scheduling
root@laika:~# atrm 5 root@laika:~# atq 6 Thu Aug 2 16:00:00 2007 a root root@laika:~#

For more information, check the man page of at for the significance of /etc/at.allow and /etc/at.deny and at output redirection.

20.2. crontab
The crontab(1) command can be used to maintain the crontab(5) file. Each user can have their own crontab file to schedule jobs at a specific time. This time can be specified with five fields in this order: minute, hour, day of the month, month and day of the week. If a field contains an asterisk (*), then this means all values of that field. The following example means : run script42 eight minutes after two, every day of the month, every month and every day of the week.
8 14 * * * script42

Run script8472 every month on the first of the month at 25 past midnight.
25 0 1 * * script8472

Run this script33 every two minutes on sunday (both 0 and 7 refer to sunday).
*/2 * * * 0

Instead of these five fields, you can also type one of these: @reboot, @yearly or @annually, @monthly, @weekly, @daily or @midnight, and @hourly. Users should not edit the crontab file directly, instead they should type crontab -e which will use the editor defined in the EDITOR or VISUAL environment variable. Users can display their cron table with crontab -l. The cron daemon is reading the cron tables, taking into account the /etc/cron.allow and /etc/cron.deny files.

20.3. Practice Scheduling
1. Schedule two jobs with at, display the at queue and remove a job. 2. As normal user, use crontab -e to schedule a script to run every two minutes. 3. As root, display the crontab file of your normal user.

153

Chapter 20. Scheduling 4. Take a look at the cron files and directories in /etc and understand them. What is the run-parts command doing ?

154

Chapter 21. Memory
You can display information about RAM memory with free -om, top and cat /proc/meminfo. You should understand terms like swapping, paging and virtual memory.

21.1. Swap space
21.1.1. About swap space
When the operating system needs more memory than physically present in RAM, it will use swap space. Swap space is located on slower but cheaper memory. Notice that, although hard disks are commonly used for swap space, their access times are one hundred thousand times slower. The swap space can be a file, a partition, or a combination of files and partitions. You can see the swap space with the free command, or with cat /proc/swaps.
paul@RHELv4u4:~$ free -om total used free shared buffers Mem: 249 245 4 0 Swap: 1023 0 1023 paul@RHELv4u4:~$ cat /proc/swaps Filename Type /dev/mapper/VolGroup00-LogVol01 partition paul@RHELv4u4:~$

cached 125

55

Size Used 1048568 0

Priority -1

The amount of swap space that you need depends heavily on the services that the computer provides.

21.1.2. Creating a swap partition
You can activate or deactivate swap space with the swapon an swapoff commands. New swap space can be created with the mkswap command. The screenshot below shows the creation and activation of a swap partition.
root@RHELv4u4:~# fdisk -l 2> /dev/null | grep hda Disk /dev/hda: 536 MB, 536870912 bytes /dev/hda1 1 1040 524128+ root@RHELv4u4:~# mkswap /dev/hda1 Setting up swapspace version 1, size = 536702 kB root@RHELv4u4:~# swapon /dev/hda1

83

Linux

Now you can see that /proc/swaps displays all swap spaces separately, whereas the free -om command only makes a human readable summary.
root@RHELv4u4:~# cat /proc/swaps

155

root@RHELv4u4:~# dd if=/dev/zero of=/smallswapfile bs=1024 count=4096 4096+0 records in 4096+0 records out root@RHELv4u4:~# mkswap /smallswapfile Setting up swapspace version 1.1. Practice Memory 1. On Solaris you can use mkfile instead of dd. then don’t forget to add them to /etc/fstab. Creating a swap file Here is one more example showing you how to create a swap file. Use dmesg to find the total amount of memory in your computer.1. 156 .4. Memory Filename Type /dev/mapper/VolGroup00-LogVol01 partition /dev/hda1 partition root@RHELv4u4:~# free -om total used free shared buffers Mem: 249 245 4 0 Swap: 1535 0 1535 root@RHELv4u4:~# Size Used 1048568 0 524120 0 cached 125 Priority -1 -2 54 21. size = 4190 kB root@RHELv4u4:~# swapon /smallswapfile root@RHELv4u4:~# cat /proc/swaps Filename Type Size Used /dev/mapper/VolGroup00-LogVol01 partition 1048568 0 /dev/hda1 partition 524120 0 /smallswapfile file 4088 0 root@RHELv4u4:~# Priority -1 -2 -3 21. Swap space in /etc/fstab If you like these swaps to be permanent.Chapter 21. Use free to display memory usage in kilobytes (then in megabytes). /dev/hda1 /smallswapfile swap swap swap swap defaults defaults 0 0 0 0 21. The lines in /etc/fstab will be similar to the following. 2.3.2.

Memory 3. Use free again to verify that it works. On the Red Hat. Put all swap spaces in /etc/fstab and activate them. 157 . create a swap partition on one of your new disks. 4. and a swap file on the other new disk.Chapter 21.

The main disadvantage is that you lose at least half of your available disk space (in other words..2. but offers better performance. and RAID 4 is the same as RAID 5. 22.2. Hardware or software Redundant Array of Independent Disks or RAID can be set up using hardware or software.4. and is often called mirroring (or mirror set. until it is full. RAID 22. Software RAID is cheaper and easier to manage. The main advantage of RAID 0 is that you can create larger drives.2.2. those chunks are evenly spread across every disk in the array. and is often called concatenating (spanning. RAID levels 22. RAID 1 RAID 1 uses exactly two disks.2. because every write would have to write parity to this one (bottleneck) disk. RAID 0 is the only RAID without redundancy.1. or striped volume). or spanned volume). Data is written to the first disk. JBOD offers no redundancy.3. 3 and 4 ? RAID 2 uses bit level striping. or mirrored volume). you at least double the cost). and is often called striping (or stripe set.. spanned set. RAID 0 RAID 0 uses two or more disks. but with a dedicated parity disk. This is actually slower than RAID 5. 158 . 22. but it uses your CPU and your memory. It is unlikely that you will ever see these RAID levels in production. Data is divided in chunks. RAID 2. The main advantage of RAID 1 is redundancy. RAID 3 byte level.1. 22.2. Hardware RAID is more expensive. The main advantage of JBOD (Just a Bunch of Disks) is that you can create larger drives.Chapter 22. Then data is written to the second disk. 22. JBOD JBOD uses two or more disks. All data written to the array is written on each disk.

. RAID 6 RAID 6 is very similar to RAID 5.7. the parity chunk will alternate between all disks.8. Building a software RAID array You can do this during the installation with Disk Druid (easy).2. This means you first create two RAID 0 stripe sets. 22.2. RAID 0+1 will survive one disk failure. 100. this makes 300GB total. as long as not all disks in the same mirror fail.9. Combined in a mirror. 150. when you have six 100GB disks. 22. when you have six 100GB disks. then the stripe sets are each 300GB. You can then combine them into one large stripe set. like RAID 30. RAID 0+1 RAID 0+1 is a mirror(1) of stripes(0). many others There are many other nested RAID combinations. Every time chunks are written to the array. or afterwards using the commandline (not so easy). For example. but uses two parity chunks.3. each divided into chunks. It will only survive the second disk failure if this disk is in the same stripe set as the previous failed disk. 51. RAID 5 RAID 5 uses three or more disks. You then stripe them together into a 300GB drive. RAID 22. RAID 50 RAID 5+0 is a stripe(0) of RAID 5 arrays. 22. and then you set them up as a mirror set.6. For example. 159 .2. then you first create three mirrors of 100GB each. Unlike RAID 4. Suppose you have nine disks of 100GB. 22.2. one of the disks will receive a parity chunk.5. 60. 22. The main advantage of this is that RAID 5 will allow for full data recovery in case of one hard disk failure.2.Chapter 22. RAID 1+0 RAID 1+0 is a stripe(0) of mirrors(1). In this example. . 22. RAID 6 protects against two hard disk failures.10. it can survive up to three hard disk failures. then you can create three RAID 5 arrays of 200GB each..2.

12884901888 bytes 255 heads. 1566 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sda1 * /dev/sda2 Start 1 14 End 13 1566 Blocks Id System 104391 83 Linux 12474472+ 8e Linux LVM Disk /dev/sdb: 1073 MB. default 1): Using default value 1 Last cylinder or +size or +sizeM or +sizeK (1-130. three brand new disks of one gigabyte each are added. In this scenario. Like this screenshot shows. nor Sun. 1073741824 bytes 255 heads. of course. 63 sectors/track. until you decide to write them. root@RHELv4u2:~# fdisk -l Disk /dev/sda: 12.Chapter 22. 63 sectors/track. default 130): Using default value 130 Command (m for help): t Selected partition 1 160 . 1073741824 bytes 255 heads. you have to attach some disks to your computer. 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Disk /dev/sdd doesn’t contain a valid partition table So far so good! Next step is to create a partition of type fd on every disk. root@RHELv4u2:~# fdisk /dev/sdc Device contains neither a valid DOS partition table. After that.8 GB. 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Disk /dev/sdb doesn’t contain a valid partition table Disk /dev/sdc: 1073 MB. 63 sectors/track. the previous content won’t be recoverable. RAID First. 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Disk /dev/sdc doesn’t contain a valid partition table Disk /dev/sdd: 1073 MB. 63 sectors/track. Check with fdisk -l that they are connected. Changes will remain in memory only. Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite) Command (m for help): n Command action e extended p primary partition (1-4) p Partition number (1-4): 1 First cylinder (1-130. 1073741824 bytes 255 heads. The fd type is to set the partition as Linux RAID auto. SGI or OSF disklabel Building a new DOS disklabel.

63 sectors/track.Chapter 22. Syncing disks. 1073741824 bytes 255 heads. 1073741824 bytes 255 heads. 1566 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sda1 * /dev/sda2 Start 1 14 End 13 1566 Blocks Id System 104391 83 Linux 12474472+ 8e Linux LVM Disk /dev/sdb: 1073 MB. 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sdd1 Start 1 End 130 Blocks Id System 1044193+ fd Linux raid autodetect 161 . so we have to tell the system what to do with these disks. 63 sectors/track. 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sdb1 Start 1 End 130 Blocks Id System 1044193+ fd Linux raid autodetect Disk /dev/sdc: 1073 MB. 1073741824 bytes 255 heads. RAID Hex code (type L to list codes): fd Changed system type of partition 1 to fd (Linux raid autodetect) Command (m for help): p Disk /dev/sdc: 1073 MB. 63 sectors/track. 63 sectors/track. 12884901888 bytes 255 heads. root@RHELv4u2:~# Now all three disks are ready for RAID. 1073741824 bytes 255 heads. 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sdc1 Start 1 End 130 Blocks Id System 1044193+ fd Linux raid autodetect Disk /dev/sdd: 1073 MB.8 GB. 63 sectors/track. 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sdc1 Start 1 End 130 Blocks Id System 1044193+ fd Linux raid autodetect Command (m for help): w The partition table has been altered! Calling ioctl() to re-read partition table. root@RHELv4u2:~# fdisk -l Disk /dev/sda: 12.

Nowadays. 2138308608 bytes 2 heads. 4 sectors/track. Create a software RAID 5 on the three disks. Practice RAID 1. Below a partial screenshot how fdisk -l sees the RAID5 root@RHELv4u2:~# fdisk -l <cut> Disk /dev/md0: 2138 MB.Chapter 22. 2. (It is not necessary to put a filesystem on it) 3. Add three virtual disks of 200MB each to the virtual Red Hat machine. but you should type it on one line. Verify with fdisk and in /proc/ that the RAID exists. RAID The next step used to be create the RAID table in /etc/raidtab. The command below is split on two lines to fit this print. you can just issue the command mdadm with the correct parameters. 162 . 522048 cylinders Units = cylinders of 8 * 512 = 4096 bytes Disk /dev/md0 doesn’t contain a valid partition table We will use this software RAID 5 array in the next topic. without the backslash (\). root@RHELv4u2:~# mdadm --create /dev/md0 --chunk=64 --level=5 --raid-devices=3\ /dev/sdb1 /dev/sdc1 /dev/sdd1 mdadm: array /dev/md0 started. 22. LVM.4.

An example of LVM First thing to do. Additionally. sometimes even without any downtime. logical volume resizing and data migration. hard disks or even single partitions can be added at a later time. root@RHELv4u2:~# mke2fs -m0 -j /dev/vg/lvol0 mke2fs 1. Below we present our software RAID 5 to LVM. is create physical volumes that can join the volume group with pvcreate. which we can use as any other disk. The last step lvcreate creates a logical volume. 23. The total size of the group is the limit. LVM does not replace hardware RAID yet. 512000 blocks 0 blocks (0. Then vgcreate creates a volume group using one device. Logical Volume Management (LVM) 23. Note that more devices could be added to the volume group. Physical storage grouping is a fancy name for grouping multiple physical devices (hard disks) into a logical mass storage device. you can migrate data away from a failing hard disk device.Chapter 23. One of the nicest features of LVM is the logical volume resizing.35 (28-Feb-2004) Filesystem label= OS type: Linux Block size=1024 (log=0) Fragment size=1024 (log=0) 128016 inodes.1. LVM and RAID are often used together. You can increase the size of an LVM volume. About lvm Most LVM implementations support physical storage grouping.2.00%) reserved for the super user 163 . To enlarge this physical group. and mounted for normal use. root@RHELv4u2:~# pvcreate /dev/md0 Physical volume "/dev/md0" successfully created root@RHELv4u2:~# vgcreate vg /dev/md0 Volume group "vg" successfully created root@RHELv4u2:~# lvcreate --size 500m vg /dev/cdrom: open failed: Read-only file system Logical volume "lvol0" created The logical volume /dev/vg/lvol0 can now be formatted with ext2. The size of LVM volumes on this physical group is independent of the individual size of the components.

Logical Volume Management (LVM) First data block=1 Maximum filesystem blocks=67633152 63 block groups 8192 blocks per group. 5. whichever comes first. Format them wih ext2. 40961. 24577. pv* or lv*.Chapter 23. 164 . 3. 73729. Create two logical volumes a small one and a bigger one. 401409 Writing inode tables: done Creating journal (8192 blocks): done Writing superblocks and filesystem accounting information: done This filesystem will be automatically checked every 37 mounts or 180 days. Create a volume group that contains a software RAID5. Practice LVM 1. Verify usage with fdisk and df. 221185. a complete disk and a partition on another disk. 8192 fragments per group 2032 inodes per group Superblock backups stored on blocks: 8193. 204801. Use tune2fs -c or -i to override. Take a look at other commands that start with vg* . root@RHELv4u2:~# mkdir /home/project10 root@RHELv4u2:~# mount /dev/vg/lvol0 /home/project10/ root@RHELv4u2:~# df -h | grep proj /dev/mapper/vg-lvol0 485M 11M 474M 3% /home/project10 23.3. Enlarge the small logical volume by 50 percent. mount them and copy some files to them. 4. 2. 57345.

Implement disk quotas on one of your new partitions. root@RHELv4u4:~# quotacheck -cug /home root@RHELv4u4:~# quotacheck -avug The -c is for create. a for checking all quota enabled file systems in /etc/fstab and v for verbose information.user and/or quota. The next step is to edit individual user quotas with edquota or set a general quota on the file system with edquota -t. u for user quota. This requires adding usrquota and/or grpquota to one or more of the file systems in /etc/fstab. root@RHELv4u4:~# cat /etc/fstab | grep usrquota /dev/VolGroup00/LogVol02 /home ext3 usrquota. you can set up disk quotas. The quota command will verify that quota for a user is set.grpquota 0 0 Next you need to remount the file system. You can have a nice overview with repquota. 2. Test that they work by copying many files to the quota’d partition.1.group files. root@RHELv4u4:~# mount -o remount /home The next step is to build the quota. root@RHELv4u4:~# quotaon -vaug Issue the following command to stop all complaints. These files (called the quota files) contain the table of the disk usage on that file system.2. Disk Quotas To limit the disk space used by user.Chapter 24. The final step (before your users start complaining about lack of disk space) is to enable quotas. Use the quotacheck command to accomplish this. Disk quotas 24. 165 . g for group. root@RHELv4u4:~# quotaoff -vaug 24. Practice Disk quotas 1. Limit one of your users to 10 megabyte. The tool will enable you to put hard (this is the real limit) and soft (allows a grace period) limits on blocks and inodes.

166 . you can mount a partition with acl support. Access Control Lists 25. and use setfacl and getfacl to set and get Access Control Lists on your files. Access Control Lists When standard Unix permissions are insufficient.Chapter 25.1.

6-3 To remove a package.1. . Installing this software is very easy. RPM (Red Hat. use -q.. use the rpm -qa command.6-3 167 . More advanced people tend to use the command line (rpm. dpkg.. Beginners should use the graphical software installation tool that is provided by the distribution (Synaptic on Debian. Add/Remove Software on Ubuntu. . The problem begins when you need software from outside of the central repository. yum.Chapter 26.). root@RHELv4u4:~# rpm -q gcc gcc-3. aptitude).rpm . but is in general managed in a central distributed repository. Installing Software Software for your Linux distribution is not scattered all over the place like some other OS’ses.4.3 root@RHELv4u4:~# rpm -q --redhatprovides gcc gcc-3.. To obtain a list of all installed software. Software distributed in the rpm format will be named foo-version. Suse.. A third option is to download vanilla source code and compile the software yourself. To check whether a package is provided by Red Hat. root@RHELv4u4:~# rpm -q --redhatprovides bash bash-3.6-3 root@RHELv4u4:~# rpm -q laika package laika is not installed root@RHELv4u4:~# To install or upgrade a package. providing the application is open source.platform. Type rpm --help to see some of the options.4. use the --redhatprovides option. use the -Uvh switches.0-19. Yast on Suse. You can install software from the repository on Linux in different ways.6-3 root@RHELv4u4:~# rpm -q --redhatprovides laika no package provides laika root@RHELv4u4:~# To verify whether a package is installed.4. 26.) The RPM Package Manager can be used on the command line with rpm or in a graphical way going to Applications--System Settings--Add/Remove Applications. rpm -e gcc-3. rpm -Uvh gcc-3.4. use the -e switch. This means that applications in the repository are tested for your distribution.

yum install $appName To upgrade all applications. aptitude update To patch and upgrade all software to the latest version. aptitude remove $appName 168 . It is installed by default on Fedora. The big advantage of aptitude is it’s ease of use and it’s power to handle dependencies. aptitude search $string To remove an application and all unused files. managed by dpkg. yum search $string 26. dpkg and Aptitude (Debian.. . Installing Software 26. Issue this to see a list of available packages. Yum (Fedora) Yum is an easier way to work with rpm packages..2. or more commonly today by aptitude. aptitude install $appName To search the repositories for applications that contain a certain string in their name or description..) Debian uses . To synchronize with the repositories.deb packages. Ubuntu. yum update To search for a package containing a certain string in the description or name. aptitude upgrade To install an application with all dependencies.Chapter 26.3. yum list available To install an application.

gzip and bzip2 commands are explained in detail later. Search the internet for ’webmin’ and install it. The tar.bz2. Read the documentation. 2.gz or a . If you download a .rpm’s can be installed with the rpm command./configure followed by make (which is the actual compiling) and then by make install to copy the files to their proper location.tgz file. 169 .Chapter 26. Compiling software First and most important.deb file. Sometimes people use the alien command to convert between package formats. Downloading software First and most important.3 tar xzf $applicationName. You can use the following to find out where the package wants to install.5. You will probably receive a .tgz Replace the z with a j when the file ends in . Installing Software 26. Use aptitude to install the ’dict’ application.6. 26. then put the compressed file in a directory. . uninstall Samba from the ubuntu machine.org and install it.4. 3.2.tar. whenever you download software. start by reading the README file! Usually the steps are always the same three : running . then you’ll have to use dpkg to install it. download the latest version from samba.tgz You unpack them like with tar xzf. start by reading the README file! Normally the readme will explain what to do after download. Find the GUI app on all computers to add and remove applications./configure make make install 26. 4. .tar. whenever you download source code for installation. Practice Installing software 1. tar tvzpf $downloadedFile. it will create a directory called applicationName-1. If time permits.

IDE tape devices are located underneath /dev/ht and are numbered starting with 0 for the first tape device.1.lanana.org/docs/device-list/) we find the names for SCSI tapes (major 9 char). prefix them with the letter n.2. SCSI tape devices are located underneath /dev/st and are numbered starting with 0 for the first tape device. SCSI tapes on linux will use the highest hardware compression that is supported by the tape device.1. No rewind and compression is similar to SCSI tapes.org/docs/device-list/) we find the names for IDE tapes (major 37 char). /dev/st0 /dev/st1 /dev/st2 First tape device Second tape device Third tape device To prevent automatic rewinding of tapes.1. m (medium) or a (auto) to the tape name. /dev/ht0 /dev/nht0 /dev/ht0m First IDE tape device Second no rewind IDE tape device First medium compression IDE tape device 170 . To lower the compression level. IDE tapes On the official Linux device list (http://www. 27. SCSI tapes On the official Linux device list (http://www. backup devices Don’t forget that the name of a device strictly speaking has no meaning since the kernel will use the major and minor number to find the hardware! See the man page of mknod and the devices.1.txt file in the linux kernel source for more info. Backup 27.Chapter 27. append one of the letters l (low). /dev/st0l /dev/st0m /dev/nst2m First low compression tape device First medium compression tape device Third no rewind medium compression tape device 27. /dev/nst0 /dev/nst1 /dev/nst2 First no rewind tape device Second no rewind tape device Third no rewind tape device By default.lanana.

tx* -rw-rw-r-. A level 3 backup on Thursday will contain all changes since Wednesday (the last level 3-1).076s paul@RHELv4u4:~/test$ ls -l ?llfiles.041s sys 0m0.050s user 0m0.txt.gz extension to the file. A higher level x backup will include all changes since the last level x-1 backup. Compression It can be beneficial to compress files before backup.1 paul paul 8813553 Feb 27 05:38 allfiles.txt real 0m0. then the Tuesday backup will contain all changes since Monday.2.bz2 paul@RHELv4u4:~/test$ 171 .794s sys 0m0. paul@RHELv4u4:~/test$ ls -l allfiles. Backup Types Linux uses multilevel incremental backups using distinct levels.gz paul@RHELv4u4:~/test$ ls -l allfiles.tx* -rw-rw-r-. Suppose you take a full backup on Monday (level 0) and a level 1 backup on Tuesday. but the latter one compresses a lot better.txt paul@RHELv4u4:~/test$ In general. Taking a level 2 on Wednesday will contain all changes since Tuesday (the last level 2-1).txt.txt real 0m5.tx* -rw-rw-r-. A full backup is a backup at level 0.txt.txt.txt paul@RHELv4u4:~/test$ ls -l allfiles.1 paul paul 931863 Feb 27 05:38 allfiles.1 paul paul 708871 May 12 10:52 bllfiles. The two most popular tools for compression of regular files on linux are gzip/gunzip and bzip2/bunzip2.Chapter 27. Let us compare the two. paul@RHELv4u4:~/test$ cp allfiles.txt paul@RHELv4u4:~/test$ time gzip allfiles.txt paul@RHELv4u4:~/test$ gzip allfiles. Another level 3 on Friday will also contain all changes since Wednesday.tx* -rw-rw-r-.3.968s user 0m5.1 paul paul 931863 Feb 27 05:38 allfiles.009s paul@RHELv4u4:~/test$ time bzip2 bllfiles. Below you can see gzip in action.gz -rw-rw-r-. gzip is much faster than bzip2.gz paul@RHELv4u4:~/test$ gunzip allfiles. Backup 27. A level 2 backup on Saturday would take all changes since the last level 1 from Tuesday. notice that it adds the .txt bllfiles. 27.1 paul paul 8813553 Feb 27 05:38 allfiles.

conf root@RHELv4u4:~# ls -l etc/resolv.tar. root@RHELv4u4:~# tar tvf /backup/etc.tar.tar -rw-r--r-. and the j flag to compress with bzip2..tar etc/resolv.1 root root 47800320 May 12 11:47 /backup/etc.root/root 2657 2004-09-27 -rw-r--r-.tar .conf root@RHELv4u4:~# Use the x flag to restore a tar archive. Verbose mode is enabled with v (also useful when you want to see the files being archived during archiving).Chapter 27.tar root@RHELv4u4:~# Compression can be achieved without pipes since tar uses the z flag to compress with gzip.tar.ta* -rw-r--r-.root/root 13136 2006-11-03 drwxr-xr-x root/root 0 2004-11-03 .tar /etc root@RHELv4u4:~# ls -l /backup/etc. The c option is used to create a tar archive (or tarfile). or a single file from the archive.conf root@RHELv4u4:~# 172 . added with the filename (without leading /).gz root@RHELv4u4:~# The t option is used to list the contents of a tar file.conf root@RHELv4u4:~# ls -l /etc/resolv.tar. Remember that by default tar will restore the file in the current directory.tar etc/resolv. tar The tar utility gets its name from Tape ARchive. use the t option.conf -rw-r--r-. 09:38:21 10:15:03 17:34:50 13:35:50 etc/ etc/warnquota. This tool will receive and send files to a destination (typically a tape or a regular file).2 root root 40 May 12 12:05 /etc/resolv.conf -rw-r--r-. Backup 27. root@RHELv4u4:~# tar czf /backup/etc. root@RHELv4u4:~# tar xvf /backup/etc.1 root root 8496607 May 12 11:47 /backup/etc. root@RHELv4u4:~# tar tvf /backup/etc.. root@RHELv4u4:~# tar cf /backup/etc.gz /etc root@RHELv4u4:~# tar cjf /backup/etc. the f option to name/create the tarfile.bz2 -rw-r--r-.types etc/sound/ To list a specific file in a tar archive. The example below takes a backup of /etc into the file /backup/etc.1 root root 6077340 May 12 11:48 /backup/etc.conf -rw-r--r-.1 root root 77 May 12 08:31 etc/resolv.tar -rw-r--r-.1 root root 47800320 May 12 11:47 /backup/etc.conf etc/resolv.conf etc/mime.tar drwxr-xr-x root/root 0 2007-05-12 -rw-r--r-.4.root/root 77 2007-05-12 08:31:32 etc/resolv.bz2 /etc root@RHELv4u4:~# ls -l /backup/etc.

) | (cd /backup/copy_of_etc/. tar tar can be used together with gzip and copy a file to a remote server through ssh cat backup.. ) | (ssh user@server ’cd /backup/copy_of_etc/.tar | ssh -C bashuser@192.tar" 173 .tar | gzip | ssh bashuser@192. And you can exclude directories or file with --exclude. this is more efficient than using cp -r.pdf >> files_to_archive.tgz -rw-r--r-.Chapter 27.> backup. tar -cf .txt root@RHELv4u4:~# tar cpzf /backup/backup.tgz root@RHELv4u4:~# You can also create a text file with names of files and directories to archive. this copies a directory securely over the network.168.tgz" Compress the tar backup when it is on the network. root@RHELv4u4:~# tar cpzf /backup/etc_with_perms.1.105 "gunzip | cat . root@RHELv4u4:~# find /etc -type f -name "*. Backup You can preserve file permissions with the p flag.> backup. cat backup.168. but leave it uncompressed at the destination.tar | gzip | ssh bashuser@192. and then supply this file to tar with the -T flag.tar.conf > files_to_archive.> backup. root@RHELv4u4:~# (cd /etc.1 root root 8496591 May 12 12:48 /backup/etc_with_perms.txt root@RHELv4u4:~# echo /home -iname *.168.) Another example of tar.tgz /etc root@RHELv4u4:~# tar cpzf /backup/etc_no_sysconf.tgz -T files_to_archive. root@RHELv4u4:~# find /etc -name *. root@RHELv4u4:~# (cd /etc.105 "cat .conf" | xargs tar czf /backup/confs..1.1 root root 8434293 May 12 12:48 /backup/etc_no_sysconf.105 "cat . tar -xpf . with the help of xargs.gz You can also use tar to copy a directory. tar -cf .1. but let ssh handle the compression cat backup.txt The tar utility can receive filenames from the find command.tar" Same as the previous.tgz /etc --exclude /etc/sysconfig root@RHELv4u4:~# ls -l /backup/etc_* -rw-r--r-.

use the -r option. cpio Different from tar and dump is cpio (Copy Input and Output). This makes it an easy companion with find! Some examples below. mke2fs /dev/hda3 mount /dev/hda3 /mnt/data cd /mnt/data restore rf /dev/nst0 To extract only one file or directory from a dump. even during a full backup. find sends filenames to cpio. In case the target is not big enough to hold the dump (end-of-media). it is also very different because it looks at the file system. dump 0f /dev/nst0 /boot dump 0f /dev/nst0 / Listing files in a dump archive is done with dump -t. restore -xf /dev/st0 /etc 27. You can omit files from a dump by changing the dump attribute with the chattr command. Backup 27.Chapter 27. The d attribute on ext will tell dump to skip the file. and you can compare files with dump -C. Like this example shows. but copies the actual files. Where tar receives a lists of files to backup. which puts the files in an archive. it is broken into multiple volumes. The no rewind is mandatory to put the volumes behind each other on the tape. use the -x option. dump will find files to backup by itself by examining ext2.5.cpio 174 . find /etc -depth -print | cpio -oaV -O archive. chattr +d /etc/hosts To restore the complete file system with restore. In the example below we take a full level 0 backup of two partitions to a SCSI tape. Restoring files that were backed up with dump is done with the restore command. Files found by dump will be copied to a tape or regular file.6. /etc/hosts is excluded from dump archives. dump and restore While dump is similar to tar. It can be used to receive filenames. You should have a clean file system mounted and cd’d into it. This can be useful to change the size or block size of a file system. In the following example.

txt of=~/copy_of_summer. dd Some people use dd to create backups.txt .gz Now pipe it through ssh (backup files to a compressed file on another machine) find /etc -depth -print | cpio -oaV | gzip -c | ssh user@host "cat . Some examples.ISO A little outdated maybe.7. dd if=/dev/hdb2 of=/image_of_hdb2.gz 175 . but compressed with gzip find /etc -depth -print | cpio -oaV | gzip -c > archive. Any good tool can burn a copy of the CD with this . and count contains the number of blocks to copy. but dd backups can only be restored to very similar partitions or devices. There are however a lot of useful things possible with dd.ISO file from any CD. dd if=~/summer.cpio.> backup. but just in case : make an image file from a 1.44MB floppy. The easiest way to create a .IMG dd if=/dev/hdb2 | gzip > /image_of_hdb2.Chapter 27. Copy the file summer.cpio. The if switch means Input File.ISO file.IMG.img bs=1024 count=1440 Use dd to copy the MBR (Master Boot Record) of hard disk /dev/hda to a file. of is the Output File. Blocksize is defined by bs. This can be very powerful. Backup The same. dd if=/dev/cdrom of=/path/to/cdrom.gz" find sends filenames to cpio | cpio sends files to ssh | ssh sends files to cpio ’cpio extracts files’ find /etc -depth -print | cpio -oaV | ssh user@host ’cpio -imVd’ the same but reversed: copy a dir from the remote host to the local machine ssh user@host "find path -depth -print | cpio -oaV" | cpio -imVd 27. dd if=/dev/floppy of=/path/to/floppy.img bs=512 count=1 This example shows how dd can copy files. dd if=/dev/hda of=/MBR.txt And who needs ghost when dd can create a (compressed) image of a partition.txt to copy_of_summer.

mt -f /dev/st0 status To rewind a tape. 3a. use mt (Magnetic Tape). Create a backup directory for your neighbour. To receive information about the status of the tape.bz2" 27. Choose a file in /etc and /bin and verify with tar that the file is indeed backed up. mt To manage your tapes. Create a directory (or partition if you like) for backups. Practice backup !! Careful with tar options and the position of the backup file. the backup must be bzip2’d... Backup And there are of course endless combinations with ssh and bzip2. make it accessible under /mnt/neighbourName 176 . This example puts a bzip2 backup of a cdrom on a remote server. the backup must be gzipped.iso.. Extract those two files to your home directory. Use tar to backup /etc in /mnt/backup/etc_date. dd if=/dev/cdrom | bzip2 | ssh user@host "cat .> /backups/cd/cdrom.. mistakes can destroy your system!! 1..8..9. mt -f /dev/st0 rewind To rewind and eject a tape.tgz. mt -f /dev/st0 erase 27.tgz. Link (or mount) it under /mnt/backup. 2a. 2d.Chapter 27. mt -f /dev/st0 eject To erase a tape. Use tar to backup /bin to /mnt/backup/bin_date. Some examples. (Replace date with the current date) 2b. 2c.

Combine find and cpio to create a cpio archive of /etc. 177 . (On the real computer) Create and mount an ISO image of the ubuntu cdrom. Use dd and ssh to put a backup of the master boot record on your neighbours computer. Backup 3b. 7. 5. Combine dd and gzip to create a ’ghost’ image of one of your partitions on another partition. 6. Choose a file in /etc and restore it from the cpio archive into your home directory. 4b. Combine ssh and tar to put a backup of your /boot on your neighbours computer in /mnt/YourName 4a.Chapter 27.

0 0.0 0. load Tasks: 61 total.2% wa. fdisk -l and du -sh.Chapter 28.00 0:00. You should start monitoring your system as soon as possible. 0. Make sure that you get to know your system. lspci. [paul@RHELv4u3 gen]$ free -om -s 10 total used free shared buffers cached 178 . just give your computer a girls name and get to know her.0 0. Boys. top .0 0.0 0.0% si free. you can use top. The baseline is important. to be able to create a baseline. 0.12:23:16 up 2 days.0% ni. CPU and running processes. 2 users.91 0:00.. It will allow you to plan for scaling up or scaling out. You can use free to display information every x seconds. 1 running.0 0. or to display only the processes that you find interesting. but the output is not ideal.9% id.1. like k to kill processes. 60 sleeping.01 0:00. 112356k cached TIME+ 0:00. or t and m to toggle displaying task and memory information.00 0:00.57 0:00.0 0.0 0.0 average: 0.86 COMMAND init ksoftirqd/0 events/0 khelper kacpid kblockd/0 pdflush You can customize top to display the columns of your choice.. 15020k Swap: 524280k total. Mem: 255972k total. 0 zombie 0.0 0. [paul@RHELv4u3 ~]$ top p 3456 p 8732 p 9654 28.5% sy. 4:01.3% us.00.00.2. 0. Top will automatically refresh. Inside top you can use many commands. Let us look at some tools that go beyond ps fax. 0 Cpu(s): 0. 28. 0. 59024k buffers free. or one summary line for all cpu’s.0% hi.0 0. Server performance monitoring Monitoring means obtaining information about the utilization of memory. 240952k used. 98. it allows you to see a steady growth in CPU utilization or a steady decline in free disk space. free The free command is common on Linux to monitor free memory. CPU power. 0.08 0:02.2 0. 144k used. top To start monitoring.00 stopped. or the number 1 to have one line per cpu. 0. This tool will monitor Memory. PR NI VIRT RES SHR S 16 0 2816 560 480 S 34 19 0 0 0 S 5 -10 0 0 0 S 5 -10 0 0 0 S 15 -10 0 0 0 S 5 -10 0 0 0 S 15 0 0 0 0 S %CPU 0. df -h. 524136k PID USER 1 root 2 root 3 root 4 root 5 root 16 root 26 root .0 0. bandwidth and storage.0 %MEM 0.

The screenshot below shows vmstat running every two seconds 100 times (or until the Ctrl-C). Every 3.Chapter 28. vmstat To monitor CPU. and can highlight changes (with the -d switch).0s: free -om total Mem: Swap: used 249 511 free 230 0 shared 19 511 buffers 0 Sat Jan 27 12:13:03 2007 cached 56 109 intro sysadmin ch2 3 4. watch It might be more interesting to combine free with the watch program.-----io---. This program can also run commands with a delay.. Server performance monitoring Mem: Swap: total Mem: Swap: 249 511 used 249 511 222 0 free 222 0 27 511 shared 27 511 buffers 0 0 50 109 cached 50 109 [paul@RHELv4u3 gen]$ 28.---swap-.7MB to 12.--system-. disk and memory statistics in one line there is vmstat.----cpu---r b swpd free buff cache si so bi bo in cs us sy id wa 0 0 144 16708 58212 111612 0 0 3 4 75 62 0 1 99 0 0 0 144 16708 58212 111612 0 0 0 0 976 22 0 0 100 0 0 0 144 16708 58212 111612 0 0 0 0 958 14 0 1 99 0 1 0 144 16528 58212 111612 0 0 0 18 1432 7417 1 32 66 0 1 0 144 16468 58212 111612 0 0 0 0 2910 20048 4 95 1 0 1 0 144 16408 58212 111612 0 0 0 0 3210 19509 4 97 0 0 1 0 144 15568 58816 111612 0 0 300 1632 2423 10189 2 62 0 36 0 1 144 13648 60324 111612 0 0 754 0 1910 2843 1 27 0 72 0 0 144 12928 60948 111612 0 0 312 418 1346 1258 0 14 57 29 0 0 144 12928 60948 111612 0 0 0 0 977 19 0 0 100 0 0 0 144 12988 60948 111612 0 0 0 0 977 15 0 0 100 0 0 0 144 12988 60948 111612 0 0 0 0 978 18 0 0 100 0 [paul@RHELv4u3 ~]$ 179 . Below the r. en sysadmin deel VI 28.9MB. sleeping processes go below b. Swap usage (swpd) stayed constant at 144 kilobytes. free memory dropped from 16.4.3. [paul@RHELv4u3 ~]$ watch -d -n 3 free -om . you see the number of processes waiting for the CPU. See man vmstat for the rest [paul@RHELv4u3 ~]$ vmstat 2 100 procs -----------memory---------..

13 0.00 0. The first block displays statistics since the last reboot.20 0.00 36.00 0. [paul@RHELv4u3 ~]$ iostat -c 5 500 Linux 2.62 0.00 0.00 0.9-34.63 0.00 Blk_wrtn/s 0.00 dm-1 0.32 0.00 7.13 1.00 01/27/2007 Blk_read 1080 941798 968 939862 939034 360 Blk_read 0 0 0 0 0 0 Blk_wrtn 0 1445148 4 1445144 1444856 288 Blk_wrtn 0 0 0 0 0 0 Blk_wrtn/s 0.00 0.42 avg-cpu: %user %nice %sys %iowait 0.77 0.EL (RHELv4u3.localdomain) Device: hdc sda sda1 sda2 dm-0 dm-1 tps 0.00 0.localdomain) avg-cpu: %user %nice %sys %iowait 0.20 99.00 sda2 0.00 dm-0 0.00 1.00 sda 0.00 36.16 47.92 avg-cpu: %user %nice %sys %iowait 0. The -d switch below makes iostat only display disk information (500 times every two seconds). [paul@RHELv4u3 ~]$ You can have more statistics using iostat -d -x.05 0.00 0.78 7.00 7.23 98.95 60.52 0.00 avg-cpu: %user %nice %sys %iowait 2.92 0.01 5.13 0.02 0.00 Blk_read/s 0.00 Blk_read/s 0.52 0.78 0.00 .5.6. [paul@RHELv4u3 ~]$ iostat -d 2 500 Linux 2..00 0.07 0.59 [paul@RHELv4u3 ~]$ %idle 01/27/2007 %idle %idle %idle %idle 180 .00 0.00 52.01 5.9-34..00 avg-cpu: %user %nice %sys %iowait 0.23 0.63 62.6.00 0. Server performance monitoring 28.06 5.00 0.00 0.00 0.00 Device: tps hdc 0.00 sda1 0.Chapter 28.EL (RHELv4u3.31 0. iostat The iostat tool can display disk and cpu statistics. or display only cpu statistics with iostat -c.

03 1.13 %irq 0.27 0.00 %steal 0. or for a selected cpu. sadc and sar The sadc tool writes system utilization data to /var/log/sa/sa??.64 0.04 0. paul@laika:~$ mpstat -P ALL Linux 2.84 98.02 0.01 01/27/2007 %system 0.48 0. like sar -I PROC to display interrupt activity per interrupt and per CPU.60 0. Just before midnight every day.9 0.00 %soft 0.08 0. or sar -r for memory related statistics.00 %idle 95. Server performance monitoring 28.49 0.07 0.93 1. mpstat On multi-processor machines.10 0. These sar reports contain a lot of statistics.40 94.60 0.03 0.06 0.EL (RHELv4u3.01 0.01 0.7.86 98.01 0.localdomain) 12:00:01 AM CPU 12:10:01 AM all 12:20:01 AM all 12:30:01 AM all 12:40:02 AM all 12:50:01 AM all 01:00:01 AM all 01:10:01 AM all [paul@RHELv4u3 sa]$ %user 0.03 02/09/2007 %sys %iowait 1.02 0. Once run.60 0. Like this example for cpu statistics.47 1.Chapter 28. cron runs the sa2 script. which in turn invokes sar.62 0.78 There are other useful sar options.39 0. You can also use sar to display a portion of the statistics that were gathered.01 0.20-3-generic (laika) 08:20:02 PM CPU 08:20:02 PM all 08:20:02 PM 0 08:20:02 PM 1 paul@laika:~$ %user 1.00 0.42 0. 28.00 0.77 1.01 0.08 %idle 98. The sar tool will read the daily data generated by sadc and put it in /var/log/sa/sar??. mpstat can display statistics for all.04 96. the sal script runs sadc for one second.44 0.25 0. 181 .6.01 0. ntop The ntop tool is not present in default Red Hat installs. [paul@RHELv4u3 sa]$ sar -u | head Linux 2.87 98. cron runs the sal script every 10 minutes.68 %iowait 0.37 1. it will generate a very extensive analysis of network traffic in html on http://localhost:3000 .65 0.76 intr/ 1304.47 0.9-34.77 0.9 1304.6. Check the manual page of sar for more.04 0.6. where ?? is replaced with the current day of the month.8.49 0.87 98.45 %nice 0.0 28.73 1.81 %nice 0. By default.80 98.62 98.

Not available on default Red Hat servers. screenshot maken (to do) 182 . Server performance monitoring 28.9.Chapter 28. iftop The iftop tool will display bandwidth by socket statistics for a specific network device.

Itanium systems can use ELILO.gz hiddenmenu 183 . We will focus on grub. eg.img #boot=/dev/sda default=0 timeout=5 splashimage=(hd0. One way to boot an unbootable system is by using the official Red Hat Enterprise Linux CD 1. root@RHELv4u4:~# mkbootdisk ‘uname -r‘ Insert a disk in /dev/fd0. Kernel Compilation 29. type linux rescue.yU3889/initrd. When installing Linux on SPARC architecture. That is.lst (used to be grub. booting the system There are a variety of boot loaders available. Press <Enter> to continue or ^C to abort: cp: writing ‘/tmp/mkbootdisk. which is replacing Lilo in many places.44M floppy these days. most common on intel architecture is GRUB. if you still can.conf).1. and an attempt will be made to rescue your system. # root (hd0.img’: No space left on device cat: write error: No space left on device cat: write error: No space left on device 20+0 records in 20+0 records out root@RHELv4u4:~# 29. So before we start playing with the kernel. This means that # all kernel and initrd paths are relative to /boot/. Any information on the disk will be lost. since most kernels are too big to fit on a 1. you can choose Silo. At the boot prompt of this CD.conf generated by anaconda # # Note that you do not have to rerun grub after making changes to this file # NOTICE: You have a /boot partition. IBM S/390 and zSeries use z/IPL and PowerPC architectures use YABOOT (which means Yet Another boot loader). The grub configuration file is located in /boot/grub/ and is now called menu.2.Chapter 29.0)/grub/splash.xpm.yU3889/vmlinuz’: No space left on device cp: writing ‘/tmp/mkbootdisk. let’s make sure we have a backup boot method.lst # grub. the others work in a similar way. preparing for a rescue boot Modifying the boot process of your system may render it unbootable.0) # kernel /vmlinuz-version ro root=/dev/VolGroup00/LogVol00 # initrd /initrd-version. Another way is to create a bootable floppy for your system with the mkbootdisk command. root@RHELv4u4:~# cat /boot/grub/menu.

9-42.9-42.6.EL ro root=/dev/VolGroup00/LogVol00 rhgb quiet initrd /initrd-2.6.9-42.map-2. to be able to select it from the boot menu.6.6.img TMPinitrd. The kernel uses initrd (an initial RAM disk) at boot time.3.6. It is a compressed cpio archive.EL.EL config-2.6.img title Red Hat Enterprise Linux AS (2.9-42.1 root root drwx-----.0.6. root@RHELv4u4:/boot# ls total 6897 -rw-r--r-.3. so you can look at the contents in this way.paul The vmlinux file is the compressed kernel.9-42.6.gz root@RHELv4u4:/boot# gunzip TMPinitrd.EL. you’ll have to add your own stanza.9-42.6. and can contain additional drivers and modules.6.1 root root -rw-r--r-.Chapter 29.0.6. Once you compiled a kernel.EL vmlinuz-2.1 root root -rw-r--r-.1 root root -rw-r--r-.9-42.img 12288 Nov 3 09:21 lost+found 23108 Aug 3 2005 message 21282 Aug 3 2005 message.0.EL.0.paul.3.lst file.0.map-2.6.ja 749489 Sep 25 17:23 System.img 1170764 Nov 3 14:29 initrd-2. Kernel Compilation title Red Hat Enterprise Linux AS (2.9-42.EL 1504432 Sep 25 17:23 vmlinuz-2.paul config-2.EL) root (hd0.6.img System. First.9-42.3.6.paul initrd-2. root@RHELv4u4:/boot# mkdir /mnt/initrd root@RHELv4u4:/boot# cp initrd-2.1 root root -rw-r--r-.3.img root@RHELv4u4:~# At the bottom of the screenshot above.0.EL.6. The initrd is mounted before the kernel loads.EL.6.6.0.9-42.0. and adding this to the menu.3.3.1 root root -rw-r--r-.EL) root (hd0.2 root root -rw-r--r-.6.0) kernel /vmlinuz-2.9-42.0.9-42.EL 1024 Nov 3 15:58 grub 1170657 Nov 3 15:58 initrd-2.0.EL 749462 Jul 12 2006 System.9-42.0.0) kernel /vmlinuz-2.EL.9-42.map-2.1 root root root@RHELv4u4:/boot# cp root@RHELv4u4:/boot# cp root@RHELv4u4:/boot# cp root@RHELv4u4:/boot# cp -l 50337 Sep 25 17:23 config-2.9-42.9-42.3.0.3.EL.0.EL 50333 Jul 12 2006 config-2.1 root root -rw-r--r-.6.3.EL.EL vmlinuz-2.9-42. You can test adding your stanza by copying an existing kernel.6. let’s copy some files.3.3.0.1 root root -rw-r--r-.3.6.EL.3.EL ro root=/dev/VolGroup00/LogVol00 rhgb quiet initrd /initrd-2.9-42.6.3.9-42. you can see two stanzas starting with the title directive.9-42.1 root root drwxr-xr-x 2 root root -rw-r--r-.3.EL 1504146 Jul 12 2006 vmlinuz-2.9-42.gz root@RHELv4u4:/boot# file TMPinitrd TMPinitrd: ASCII cpio archive (SVR4 with no CRC) root@RHELv4u4:/boot# cd /mnt/initrd/ root@RHELv4u4:/mnt/initrd# cpio -i | /boot/TMPinitrd 4985 blocks root@RHELv4u4:/mnt/initrd# ls -l total 76 drwxr-xr-x 2 root root 4096 Feb 5 08:36 bin drwxr-xr-x 2 root root 4096 Feb 5 08:36 dev drwxr-xr-x 4 root root 4096 Feb 5 08:36 etc 184 .EL System.img initrd-2.0.9-42.9-42.0.EL.map-2.6.

9-42.6. Kernel Compilation -rwxr-xr-x 1 root root 1607 drwxr-xr-x 2 root root 4096 drwxr-xr-x 2 root root 4096 drwxr-xr-x 2 root root 4096 lrwxrwxrwx 1 root root 3 drwxr-xr-x 2 root root 4096 drwxr-xr-x 2 root root 4096 root@RHELv4u4:/mnt/initrd# Feb Feb Feb Feb Feb Feb Feb 5 5 5 5 5 5 5 08:36 08:36 08:36 08:36 08:36 08:36 08:36 init lib loopfs proc sbin -> bin sys sysroot The System.3.img title Red Hat Enterprise Linux AS (2.lst kernel /vmlinuz-2.9-42.3.0. and reboot the machine with it.map contains the symbol table and changes with every kernel compile.EL) root (hd0.paul ro root=/dev/VolGroup00/LogVol00 rhgb quiet initrd /initrd-2.EL ro root=/dev/VolGroup00/LogVol00 rhgb quiet initrd /initrd-2.lst root@RHELv4u4:/boot/grub# tail menu.9-42.6.EL ro root=/dev/VolGroup00/LogVol00 rhgb quiet initrd /initrd-2.paul.img title Red Hat Enterprise Linux AS Paul (2. So we are now ready to create a new stanza.9-42.6.0.6.EL. starting from the same configuration as an existing working one.6.EL. The symbol table is also present in /proc/kallsyms (pre 2.EL.6.Chapter 29.img 185 .6.6.9-42. It allows you to recompile a kernel. root@RHELv4u4:/boot# head System.EL.9-42.0) kernel /vmlinuz-2.0. root@RHELv4u4:/boot/grub# vi menu.3.3.9-42. but it is common practice to put a copy there.EL.3.0.0) kernel /vmlinuz-2.9-42.0.map-‘uname -r‘ 00000400 A __kernel_vsyscall 0000041a A SYSENTER_RETURN_OFFSET 00000420 A __kernel_sigreturn 00000440 A __kernel_rt_sigreturn c0100000 A _text c0100000 T startup_32 c01000c6 t checkCPUtype c0100147 t is486 c010014e t is386 c010019f t L6 root@RHELv4u4:/boot# head /proc/kallsyms c0100228 t _stext c0100228 t calibrate_delay_direct c0100228 t stext c0100337 t calibrate_delay c01004db t rest_init c0100580 t do_pre_smp_initcalls c0100585 t run_init_process c01005ac t init c0100789 t early_param_test c01007ad t early_setup_test root@RHELv4u4:/boot# The last file copied is the kernel configuration used for compilation.6 kernels name this file /proc/ksyms). This file is not necessary in the /boot directory.paul) root (hd0.

3. the size. The next step is to really create those four files ourselves. and the names of other modules using this one. [root@RHELv4u3 ~]# lsmod Module Size iptable_filter 2753 ip_tables 16705 nls_utf8 2113 parport_pc 24577 lp 12077 parport 37129 autofs4 24773 i2c_dev 11329 . and might also put an alias for the hardware in /etc/modprobe. use lsmod. 29. you can now select your own stanza. whereas insmod requires manual loading of depedencies. The same information is present in /proc/modules.Chapter 29.conf. [root@RHELv4u3 ~]# modprobe isdn [root@RHELv4u3 ~]# rmmod slhc 186 . You see the name of each loaded module. Used by 0 1 iptable_filter 0 1 0 2 parport_pc.3. [root@RHELv4u3 ~]# modprobe isdn [root@RHELv4u3 ~]# lsmod | grep isdn isdn 133537 0 slhc 7233 1 isdn [root@RHELv4u3 ~]# Same as insmod.3.1. Normally the kudzu program will detect and configure hardware on Red Hat Enterprise Linux. the rmmod tool is rarely used anymore.lp 0 0 29. Kernel Compilation root@RHELv4u4:/boot/grub# At the boot menu (after the reboot). kernel module management The system must be configured to load the proper kernel module for each piece of hardware.2. lsmod To see a list of currently loaded modules... 29. the use count. modprobe The advantage of modprobe over insmod is that modprobe will load all necessary modules.

The file is called kernel-2.spec.rpm for RHELv4u4.kernel. [root@RHELv4u3 ~]# cat /etc/rc.4.src. Kernel Compilation ERROR: Module slhc [root@RHELv4u3 ~]# [root@RHELv4u3 ~]# [root@RHELv4u3 ~]# [root@RHELv4u3 ~]# is in rmmod rmmod lsmod use by isdn isdn slhc | grep isdn Contrary to rmmod.EL.4.local).modules [root@RHELv4u3 ~]# chmod +x /etc/rc.6.EL. Issue the rpm -i -vv kernel-2.9-42. But getting this one to work perfectly with your Red Hat distribution will be tricky.Chapter 29.modules (which is loaded before /etc/rc.6. which is located on the fourth source cdrom.modules: No such file or directory [root@RHELv4u3 ~]# echo modprobe isdn > /etc/rc.9-42.modules [root@RHELv4u3 ~]# 29.4.modules cat: /etc/rc. put the modprobe command in /etc/rc. vanilla To compile a kernel. you need to get the source code first.2.1. compiling a kernel 29. 187 . 29.src. The vanilla kernel is downloadable from ftp.org. It will put a lot of files in /usr/src/redhat/BUILD. issue rpmbuild -bp -vv --target=i686 /usr/src/redhat/SPECS/kernel-2.rpm command to install this Red Hat package. modprobe will remove unneeded modules. [root@RHELv4u3 [root@RHELv4u3 isdn slhc [root@RHELv4u3 [root@RHELv4u3 [root@RHELv4u3 [root@RHELv4u3 ~]# modprobe isdn ~]# lsmod | grep isdn 133537 0 7233 1 isdn ~]# modprobe -r isdn ~]# lsmod | grep isdn ~]# lsmod | grep slhc ~]# To force the loading of a module at boot (normally you will never have to do this manually). Red Hat Enterprise Linux 4 specific It will be safer to start with the Red Hat kernel source.6.

You might also need mkinitrd when booting from SCSI.Chapter 29.conf.config to /boot. Overview kernel compile An overview of the steps executed to compile the kernel (first attempt.6. screenshot make menuconfig maken !! (to do) Next. no network connection but otherwise functioning kernel).9-34. Now run make modules (took me 22 minutes) and make modules install (20 seconds). or not at all (smaller kernel size).EL-i686]# Issue a make clean to prepare the kernel for compile.4. 29. Normal kernel compilation Now clean up the source from any previous installs with make mrproper.EL-i686]# clean [root@RHELv4u3 2. sit back and relax while the kernel compiles. 188 . Kernel Compilation Now go into /usr/src/redhat/BUILD/kernel-2.6.map.9/linux-2.EL-i686]# head -5 Makefile -34.5. And then run make bzImage. This tool allows you to select whether to compile stuff as a module (m). change the extraversion in the Makefile. You can use time make bzImage to know how long it takes to compile. If you remove to much. this will help you in the next compile to start from a known good configuration. Now copy a working . Also copy the System.6.9-34.6. 29. then this is not needed.EL-i686]# time make bzImage You can already copy this image to /boot with cp arch/i386/boot/bzImage /boot. Compilation is now finished. It is common to copy your . Now run the make menuconfig (or in GUI make xconfig).6. so next time you can go for a short walk (it took six minutes in vmware). don’t forget to create an additional stanza in grub.6.EL-i686]# vi Makefile 2.9-34.paul 2.9-34.9/ .6. to give your compiled kernel a unique name. as part of the kernel (*).config from /boot to our kernel directory.3.9-34. your kernel will not work. [root@RHELv4u3 [root@RHELv4u3 VERSION = 2 PATCHLEVEL = 6 SUBLEVEL = 9 EXTRAVERSION = NAME=AC 1 [root@RHELv4u3 2.EL. If this is your first after downloading the source code. [root@RHELv4u3 2.

img ll /boot vi /boot/grub/menu..9-paul-2 mkinitrd /boot/initrd-2.1.8.6.config /boot/config-2.0. rpm -i -vv kernel-2.6.config vi Makefile time make bzImage modules modules_install cp System.6.map /boot/System.src.6. cd /usr/src/redhat/BUILD/kernel-2.EL. paul@laika:~$ ssh 192.Chapter 29.6.44’s password: Last login: Thu Feb 15 18:29:48 2007 from 192..6.9-paul cp System.9-paul time make modules time make modules_install ls -l /lib/modules/ cp .6.44 paul@192.ELsmp .9/linux-2.config /boot/config-2.6.6./BUILD/kernel-2.img /boot/initrd-2.src.6./.6.9-paul-2 [paul@rhel4a ~]$ 189 .9/linux-2.9-paul-2.map-2.9-42.9-42.6..9-42.6.rpm cd /usr/src/redhat/SPECS/ rpmbuild -bp -vv --target=i686 kernel-2.map-2.9-paul-2 cp arch/i386/boot/bzImage /boot/vmlinuz-2.everything seems to work now.1. Kernel Compilation mkdir kernelcompile cd kernelcompile/ mv /home/paul/kernel-2.9-paul) cp /boot/initrd-2.6.6..9-paul.6.168.6.168.img 2.9-paul.8.9-42.0.9-paul-2 ll /boot vi /boot/grub/menu.6.ELsmp..lst .6.6.img 2.EL.168.9/ make mrproper vi Makefile make menuconfig time make bzImage cp arch/i386/boot/bzImage /boot/vmlinuz-2.1.6.map /boot/System.9/ make mrproper uname -a cp /boot/config-2.spec cd .9-paul (mkinitrd /boot/initrd-2.9-paul-2 cp .rpm .lst reboot The second attempt.45 [paul@rhel4a ~]$ uname -r 2.

ko make[1]: Leaving directory ‘/usr/src/redhat/BUILD/kernel-2. MODPOST CC /home/paul/kernel_module/hello. [root@rhel4a kernel_module]# cat hello.6.9/linux-2.9/linux-2.1 paul paul 153 Feb 15 19:15 Makefile The running of the make command. } void cleanup_module(void) { printk(KERN_INFO "End Hello World.o Building modules. 190 .. return 0. [root@rhel4a kernel_module]# make make -C /lib/modules/2.6. [root@rhel4a kernel_module]# cat Makefile obj-m += hello.mod.6.6.Chapter 29..o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean These are the only two files needed.6. \n").c -rw-rw-r-.c #include <linux/module. stage 2.. [root@rhel4a kernel_module]# ll total 16 -rw-rw-r-. Compiling one module A little C program that will be our module.9’ [root@rhel4a kernel_module]# Now we have more files.9-paul-2/build M=/home/paul/kernel_module modules make[1]: Entering directory ‘/usr/src/redhat/BUILD/kernel-2.9’ CC [M] /home/paul/kernel_module/hello. } The make file for this module.6. Kernel Compilation 29.1 paul paul 250 Feb 15 19:14 hello.\n")..h> #include <section> int init_module(void) { printk(KERN_INFO "Start Hello World.o LD [M] /home/paul/kernel_module/hello.

ko hello.1 root root 37036 Feb -rw-r--r-...1 paul paul 250 Feb -rw-r--r-. Kernel Compilation [root@rhel4a kernel_module]# ll total 172 -rw-rw-r-.6.9-paul-2 SMP 686 REGPARM 4KSTACKS gcc-3.1 root root 632 Feb -rw-r--r-. Feb 15 19:16:35 rhel4a kernel: End Hello World.1 root root 64475 Feb -rw-r--r-. [root@rhel4a kernel_module]# 191 .c hello.1 root root 28396 Feb -rw-rw-r-...Chapter 29.. [root@rhel4a kernel_module]# modinfo hello..o hello.c hello.4 depends: [root@rhel4a kernel_module]# Good.ko [root@rhel4a kernel_module]# lsmod | grep hello hello 5504 0 [root@rhel4a kernel_module]# tail -1 /var/log/messages Feb 15 19:16:07 rhel4a kernel: Start Hello World.o Makefile Use modinfo to verify that it is really a module. [root@rhel4a kernel_module]# rmmod hello [root@rhel4a kernel_module]# Finally /var/log/messages has a little surprise.mod.mod.1 paul paul 153 Feb [root@rhel4a kernel_module]# 15 15 15 15 15 15 19:14 19:15 19:15 19:15 19:15 19:15 hello.ko vermagic: 2. [root@rhel4a kernel_module]# lsmod | grep hello [root@rhel4a kernel_module]# insmod . [root@rhel4a kernel_module]# tail -2 /var/log/messages Feb 15 19:16:07 rhel4a kernel: Start Hello World. so now we can load our hello module.ko filename: hello./hello.

But you can easily add ip-addresses to the list of allowed hosts for administration of CUPS.1 Allow From 10.org website).3.77 Allow From 10.org/en/OpenPrinting (the former linuxprinting.10.linux-foundation.conf # Printer configuration file for CUPS v1.0.Chapter 30. [root@RHELv4u3 ~]# cat /etc/cups/printers.10.10. 30. In the rare case where you do not have a web browser available. the /etc/cups/printers.conf file is updated.41:9100 State Idle Accepting Yes JobSheets none none QuotaPeriod 0 PageLimit 0 KLimit 0 </Printer> [root@RHELv4u3 ~]# 30.0. With IPP print servers and clients use the HTTP protocol to communicate.10. <Location /> Order Deny. Drivers and howtos for all existing printers can be found on http://www.1.conf file to the localhost.1. the Internet Printing Protocol.1. The configuration will be stored in the /etc/cups/ directory. cups web administration is limited in the /etc/cups/cupsd. About CUPS The standard for printing on Linux is CUPS or Common Unix Printing Service.75 </Location> 192 . CUPS is based on IPP. After adding a printer with the web interface.Allow Deny From All Allow From 127. you can use the lpadmin command to manage printers.168. CUPS Administration Access By default. CUPS 30. CUPS Administration You can use the web-based administration of cups for most tasks.2.22rc1 # Written by cupsd on Thu 08 Feb 2007 11:05:52 PM CET <DefaultPrinter HPLaserjet4Si> Info Dit is de snelle printer met wit papier Location aan het raam DeviceURI socket://192. just go to http://localhost:631 on the print server.

lpstat and lpc You can see the status of printers with lpstat and lpc.4.2. [root@RHELv4u3 ~]# lp /etc/passwd request id is HPLaserjet4Si-1 (1 file(s)) [root@RHELv4u3 ~]# lpq HPLaserjet4Si is ready and printing Rank Owner Job File(s) active root 1 passwd [root@RHELv4u3 ~]# lpr /etc/hosts Total Size 3072 bytes 193 . CUPS And make sure cups also listens on other ip-addresses besides 127.0.conf | tail -1 Listen *:631 [root@rhel4 ~]# 30.4.1. [root@RHELv4u3 ~]# lpstat -a HPLaserjet4Si accepting requests since Jan 01 00:00 [root@RHELv4u3 ~]# [root@RHELv4u3 ~]# lpc status HPLaserjet4Si: printer is on device ’socket’ speed -1 queuing is enabled printing is enabled 2 entries daemon present [root@RHELv4u3 ~]# 30. lpr You can now use lp and lpr to print documents to your printer. [root@RHELv4u3 ~]# lpq HPLaserjet4Si is ready no entries [root@RHELv4u3 ~]# 30. lpq You can use lpq to look at the queue.3.4.0. Command line tools for CUPS 30.Chapter 30.1 [root@rhel4 ~]# grep -i listen /etc/cups/cupsd.4.

Chapter 30. lprm and cancel You can use lprm to remove print jobs from the queue. to remove all print jobs from user paul from the system. [root@RHELv4u3 ~]# lpq HPLaserjet4Si is ready and printing Rank Owner Job File(s) active root 1 passwd [root@RHELv4u3 ~]# cancel 1 [root@RHELv4u3 ~]# lpq HPLaserjet4Si is ready no entries [root@RHELv4u3 ~]# Total Size 3072 bytes 30. you can use lprm paul.4. [root@RHELv4u3 ~]# lpoptions -l ColorModel/Output Mode: *Gray Black Resolution/Resolution: 150dpi *300dpi 600dpi PageSize/Media Size: *Letter Legal Executive Statement A4 C5 C6 DL COM10 Monarch InputSlot/Media Source: *Standard Manual MultiPurpose Upper Lower LargeCapacity Auto PageRegion/PageRegion: Letter Legal Executive Statement A4 C5 C6 DL COM10 Monarch .5.4.4. 194 .. [root@RHELv4u3 ~]# lpq HPLaserjet4Si is ready and printing Rank Owner Job File(s) active root 1 passwd 1st root 2 hosts [root@RHELv4u3 ~]# lprm 2 [root@RHELv4u3 ~]# lpq HPLaserjet4Si is ready and printing Rank Owner Job File(s) active root 1 passwd [root@RHELv4u3 ~]# Total Size 3072 bytes 1024 bytes Total Size 3072 bytes You can also use cancel for this. You can remove jobs by job number. lpoptions You can use lpoptions to display or set options like page size or color mode for the printer.. When you are root. CUPS [root@RHELv4u3 ~]# lpq HPLaserjet4Si is ready and printing Rank Owner Job File(s) active root 1 passwd 1st root 2 hosts [root@RHELv4u3 ~]# Total Size 3072 bytes 1024 bytes 30. Just typing lpoptions -l will list all the options for the (default) printer.

6. [paul@laika ~]# lp -o"ColorModel=Gray" plan. lpmove Jobs can be move to another printer with the lpmove command. since enable is also a bash built-in command. In the screenshot below a color document is printed in grayscale on a color printer.4. [root@RHELv4u3 ~]# lpq HPLaserjet4Si is ready and printing Rank Owner Job File(s) active root 3 hosts 1st root 5 passwd 2nd root 6 passwd 3rd root 7 passwd [root@RHELv4u3 ~]# lpmove 6 HPDJ500 [root@RHELv4u3 ~]# lpq -P HPDJ500 HPDJ500 is ready and printing Rank Owner Job File(s) active root 6 passwd [root@RHELv4u3 ~]# Total Size 1024 bytes 3072 bytes 3072 bytes 3072 bytes Total Size 3072 bytes 30.pdf 30.4. you have to give the full path /usr/bin/enable to use the CUPS enable command. [root@RHELv4u3 ~]# lpq -P HPDJ500 HPDJ500 is ready no entries [root@RHELv4u3 ~]# disable HPDJ500 [root@RHELv4u3 ~]# lpq -P HPDJ500 HPDJ500 is not ready no entries [root@RHELv4u3 ~]# /usr/bin/enable HPDJ500 [root@RHELv4u3 ~]# lpq -P HPDJ500 HPDJ500 is ready no entries [root@RHELv4u3 ~]# 195 .7.Chapter 30. enable and disable Printers can be stopped and started with the disable and enable commands. CUPS You can override default options explicitly with the lp -o command. Be careful in /bin/bash. You can access the man page of CUPS enable with man 8 enable.

4. Printers will start accepting jobs again after the accept command.8.Chapter 30. CUPS 30. [root@RHELv4u3 ~]# lpstat -a HPDJ500 accepting requests since Jan 01 00:00 HPLaserjet4Si accepting requests since Jan 01 00:00 [root@RHELv4u3 ~]# reject HPDJ500 [root@RHELv4u3 ~]# lpstat -a HPDJ500 not accepting requests since Jan 01 00:00 Rejecting Jobs HPLaserjet4Si accepting requests since Jan 01 00:00 [root@RHELv4u3 ~]# accept HPDJ500 [root@RHELv4u3 ~]# lpstat -a HPDJ500 accepting requests since Jan 01 00:00 HPLaserjet4Si accepting requests since Jan 01 00:00 [root@RHELv4u3 ~]# 196 . accept and reject Printers can be prevented from accepting jobs with the reject command.

whereas udp is connectionless but faster. telnet and FTP have fixed port numbers. usually placed in a DNS name space forming the FQDN or Fully Qualified Domain Name. and are listed in the /etc/protocols file.1. The icmp error messages are used by ping. Routers are layer 3 devices. paul@laika:~$ grep tftp /etc/services tftp 69/udp paul@laika:~$ 197 . that is what people say since 1995. TCP/IP 31.D or E).3. layer 2 contains bridges and switches.Chapter 31. To find a port number.C. Today we work with CIDR notation to determine network id and host id. Internet and routers The internet is a collection of routers that act as gateways between different segments. SSH. layer 1 is cabling with repeaters and hubs. 31. HTTP. Those subnets used to be classful (A.. this is either static or received from a DHCP server. you use tcp. multicast groups are managed by igmp and the ip to mac resolution is done by the broadcast protocol arp.2. but this wasted a lot of address space.. 31. paul@laika:~$ grep tcp /etc/protocols tcp 6 TCP # transmission control protocol paul@laika:~$ Every host receives a hostname. Overview of tcp/ip v4 The unicast Internet Protocol is one of the oldest network protocols. Internet networks contain several subnets. commonly used today for LAN and WAN networks. Common application level protocols like SMTP. In a couple of years we will all be using IPv6! At least. These protocols are visible in the protocol field of the ip header. Routers use their routing table to determine the route of tcp/ip packets. Every host gets a unique 32-bit ip-address. look in /etc/services.B. Layer 2 devices know your 48-bit unique in the world MAC address. many protocols For reliable connections.

Practice TCP/IP 1. whereas internet streaming radio and live broadcasts are using udp.Chapter 31. ssh.4. pop3. TCP/IP 31. Which ports are used by http. 198 . telnet. Explain why e-mail and websites are sent over tcp. nntp and ftp ? 2.

this is the Network Administration Tool.1. 32. or until reboot.199 [root@RHEL4b ~]# The ip address change will be valid until the next change.0 root@laika:~# 199 . Avoid mixed use of the GUI tool with command line or direct editing of network configuration files. Also. or set the ip address.168.0 KiB) TX bytes:8895 (8. In the case of RHEL. setup your tcp/ip configuration at install time. Normal users cannot use it to disable or enable interfaces. let’s take a look at the files and script that configure your network. The first ethernet network card on linux is eth0. Every user has access to /sbin/ifconfig.255. or enable it with ifconfig eth0 up.255. because many GUI tools will override your manually edited settings.2.168. You can also supply the subnet mask with ifconfig.6 KiB) Interrupt:185 Base address:0x1400 [root@RHEL4b ~]# You can also disable a network interface with ifconfig eth0 down. otherwise use the graphical tool from your distribution. on Red Hat Servers avoid editing the files in /etc/sysconfig/networking manually! Now that we settled this.1. /sbin/ifconfig You can use the ifconfig command to see the tcp/ip configuration of a network interface.255.Chapter 32.168.255 Mask:255.1. IP address configuration 32. [root@RHEL4b ~]# ifconfig eth0 eth0 Link encap:Ethernet HWaddr 00:0C:29:3B:15:80 inet addr:192. providing the path is set.255. [root@RHEL4b ~]# ifconfig eth0 192. Novell and OpenSUSE users can use YaST.191 Bcast:192.1.1. You should choose only one method to manage these files. root@laika:~# ifconfig eth0 192.40 netmask 255.0 inet6 addr: fe80::20c:29ff:fe3b:1580/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:84 errors:0 dropped:0 overruns:0 frame:0 TX packets:80 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:9216 (9. to GUI or not to GUI If you can.168.

removed PID file Internet Systems Consortium DHCP Client V3. if you try this via an ssh connection. Below an example.1. The script stops and starts the interfaces. and leaving the default hostname of localhost. For info.168.pid with pid 134993416 Internet Systems Consortium DHCP Client V3.4.d/network(ing) If you have a problem with network interfaces. you can try to restart the network init script.1. There is already a pid file /var/run/dhclient. please visit http://www. root@laika:~# /etc/init. setting 192.168.255.pid with pid 14570 killed old client process. root@laika:~# 32. /etc/sysconfig/network Routing and host information for all network interfaces is specified in the /etc/sysconfig/network file.0.d/networking restart * Reconfiguring network interfaces.3.1. 32.isc.eth0. then you might lose your ssh connection.4.255.1 as the router (default gateway). IP address configuration Careful.04. as shown here on Ubuntu 7.0. Debian derived systems do not have this directory.org/sw/dhcp/ Listening on LPF/eth0/00:90:f5:4e:ae:17 Sending on LPF/eth0/00:90:f5:4e:ae:17 Sending on Socket/fallback DHCPRELEASE on eth0 to 192.1 bound to 192.4 Copyright 2004-2006 Internet Systems Consortium.255 port 67 DHCPACK from 192.1.4 Copyright 2004-2006 Internet Systems Consortium.1 port 67 There is already a pid file /var/run/dhclient. please visit http://www. and renews an ip configuration with the DHCP server. All rights reserved. 32.isc. All rights reserved.168.org/sw/dhcp/ Listening on LPF/eth0/00:90:f5:4e:ae:17 Sending on LPF/eth0/00:90:f5:4e:ae:17 Sending on Socket/fallback DHCPDISCOVER on eth0 to 255. For info..255 port 67 interval 5 DHCPOFFER from 192. Common options not shown in this screenshot are 200 . /etc/sysconfig Red Hat derived Linux systems store their network configuration files in the /etc/sysconfig/ directory.localdomain.255.40 -.1.renewal in 249143 seconds.168.255.1.1 DHCPREQUEST on eth0 to 255..Chapter 32.eth0. /etc/init.168.

4.168. both meaning there should be no protocol used at boottime to set the interface values. The BROADCAST variable is no longer needed.168. The first ethernet NIC will get ifcfg-eth0.1. paul@RHELv4u2:~$ cat /etc/sysconfig/network NETWORKING=yes HOSTNAME=localhost.localdomain GATEWAY=192.1 The same file. then this is the ifcfg-eth1. it will be calculated. Below is an example. Be careful when editing these files. but here the hostname of the machine is not set to the default as above.255. /etc/sysconfig/network-scripts For every network card in your computer.1.2. until you start the system-config-network (might soon be renamed to redhat-config-network) tool. the next one ifcfg-eth1 and so on.1. paul@RHELv4u2:~$ cat /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE=eth1 BOOTPROTO=dhcp HWADDR=00:0C:29:6A:34:D8 ONBOOT=yes TYPE=Ethernet Besides dhcp and bootp the BOOTPROTO variable can be static or none.0 NETWORK=192.Chapter 32. 201 .168.255.1. [paul@RHEL4b ~]$ cat /etc/sysconfig/network NETWORKING=yes HOSTNAME=RHEL4b [paul@RHEL4b ~]$ 32. and NISDOMAIN to specify the NIS domain name.255 HWADDR=00:0C:29:5A:86:D7 IPADDR=192. you should have an interface configuration file named /etc/sysconfig/network-scripts/ifcfg-$IFNAME.0 ONBOOT=yes TYPE=Ethernet When the second nic is configured for dhcp. paul@RHELv4u2:~$ cat /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE=eth0 BOOTPROTO=static BROADCAST=192. This tool can and will overwrite your manual edits. IP address configuration GATEWAYDEV to set one of your network cards as the gateway device. your edits will work.168.222 NETMASK=255.

org/sw/dhcp/ Listening on LPF/eth0/00:90:f5:4e:ae:17 Sending on LPF/eth0/00:90:f5:4e:ae:17 Sending on Socket/fallback DHCPDISCOVER on eth0 to 255. 32.168.isc.pid with pid 14925 killed old client process. root@laika:~# 202 .1.Chapter 32.0.255. For info.isc. root@laika:~# ifup eth0 There is already a pid file /var/run/dhclient.4 Copyright 2004-2006 Internet Systems Consortium.40 -.1 bound to 192.pid with pid 134993416 Internet Systems Consortium DHCP Client V3. please visit http://www. Because the /etc/network/interfaces file says eth0 uses DHCP.5. All rights reserved.4 Copyright 2004-2006 Internet Systems Consortium.0.1 port 67 On debian derived systems. All rights reserved.255.1.renewal in 231552 seconds.255 port 67 DHCPACK from 192. In the screenshot below ifup is used to bring up the eth0 interface.1 DHCPREQUEST on eth0 to 255.168. the ifup tool will (try to) start the dhclient daemon.255.255. you need to specify the MACADDR variable. Do not use HWADDR and MACADDR in the same ifcfg file. root@laika:~# ifdown eth0 There is already a pid file /var/run/dhclient.1.168.files. For this.eth0.eth0. It can not be used to set the MAC address of a nic. these commands will look at /etc/network/interfaces.1.255 port 67 interval 8 DHCPOFFER from 192. /sbin/ifup and /sbin/ifdown The ifup and ifdown commands take an interface as argument and bring it up or down. The screenshot below deactivates the eth0 network interface.168. please visit http://www. IP address configuration The HWADDR can be used to make sure that the nic’s get the correct name when multiple nic’s are present in the computer. For info. removed PID file Internet Systems Consortium DHCP Client V3. whereas on Red Hat derived systems they will look at /etc/sysconfig/network-scripts/ifcfg.org/sw/dhcp/ Listening on LPF/eth0/00:90:f5:4e:ae:17 Sending on LPF/eth0/00:90:f5:4e:ae:17 Sending on Socket/fallback DHCPRELEASE on eth0 to 192.

72) at 00:03:BA:09:7C:F9 [ether] on eth1 root@barry:~# 203 .0 Flags U MSS Window 0 0 irtt Iface 0 eth0 Genmask 255.0 * [root@RHEL4b ~]# Genmask 255.168.1. When your adapter is configured for DHCP or BOOTP.73) at 00:03:BA:09:7F:D2 [ether] on eth1 anya (192.168.255.1. root@RHEL4b ~]# netstat -r Kernel IP routing table Destination Gateway 192. The arp table can be displayed with the arp tool.8.168.Chapter 32.1.1.168. 32.71) at 00:03:BA:02:C3:82 [ether] on eth1 shaka (192. /sbin/route You can see the computer’s local routing table with the route command (and also with netstat -r ).1 [root@RHEL4b ~]# route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref 192.168. so we use route add default gw to add a default gateway.1.255.168.0.1.1) at 00:12:01:E2:87:FB [ether] on eth1 faith (192.0 * [root@RHEL4b ~]# route Kernel IP routing table Destination Gateway 192.168.1.168.0.255.1 0. root@barry:~# arp -a ? (192.0 U 0 0 * default 192.41) at 00:0E:7F:41:0D:EB [ether] on eth1 kiss (192.49) at 00:D0:E0:91:79:95 [ether] on eth1 laika (192.1.1. /sbin/dhclient Home and client Linux desktops often have dhclient running. then /sbin/ifup will start the dhclient daemon.40) at 00:90:F5:4E:AE:17 [ether] on eth1 pasha (192.255.168.168.1. This is a daemon that enables a network interface to lease an ip configuration from a DHCP server.1.191) at 00:0C:29:3B:15:80 [ether] on eth1 agapi (192.0 Flags Metric Ref U 0 0 Use Iface 0 eth0 It appears this computer does not have a gateway configured.6.255.255.7.1. arp Mac to IP resolution is handled by the arp protocol.168.0 255.0 UG 0 0 [root@RHEL4b ~]# Use Iface 0 eth0 0 eth0 32. IP address configuration 32.1.168. [root@RHEL4b ~]# route add default gw 192.168.

Chapter 32. Use ifconfig to list all your network interfaces and their ip-addresses. 4.419 ms --. Verify with ifconfig and ping to a neighbour that it works. Is the dhclient daemon running ? 7.168. Ping the default gateway. IP address configuration Anya is a Cisco Firewall.1.168.5: icmp_seq=3 bytes of data.168. laika is a Clevo laptop and Agapi.168.9. then ip is configured. Use ifdown or ifconfig to disable your eth0 network card. 3.574/1004.1. Verify that you have a default gateway. Use the GUI tool to enable dhcp again (and verify the changes in the config files). Write down your ip-address and subnet mask. 204 .1. 4 received.419/251.5: icmp_seq=2 64 bytes from 192. pipe 2 [root@RHEL4b ~]# 32.10.5 (192.186/434. Practice IP Configuration 1.1.5: icmp_seq=1 64 bytes from 192.1. Also look at the configuration files in /etc/network or /etc/sysconfig to see how the GUI tool sets a fixed address. ping If you can ping to another host. [root@RHEL4b ~]# ping 192.19 ms ttl=64 time=0.520 ms. then look at the MAC address of the default gateway. time 3009ms rtt min/avg/max/mdev = 0.5) 56(84) 64 bytes from 192. Use the GUI tool of your distro to set a fix ip address (use the same address as the one you got from dhcp). ttl=64 time=1004 ms ttl=64 time=1.1. 8.5: icmp_seq=0 64 bytes from 192.192.168. Kiss is a Kiss DP600. 5.5 PING 192.168.1. The question mark is a Red Hat Enterprise Linux server running in vmware.494 ms ttl=64 time=0. Faith is an HP Color printer. Shaka and Pasha are SPARC servers. 6.1.168. 0% packet loss. Restart networking to enable your network card again. 2.168.5 ping statistics --4 packets transmitted. 32.

1 localhost 127. 127.1.200 server1 >> /etc/hosts root@RHELv4u4:~# cat /etc/hosts # Do not remove the following line. paul@RHELv4u2:~$ cat /etc/hosts # Do not remove the following line.168.168.1. Name Resolution 33.5 barry # appliances 192.168.0.103 Sol9b 205 .localdomain localhost 192.0.1. Below is the default /etc/hosts file on Red Hat Enterprise Linux.168.168.0.72 shaka 192.0.168.41 faith 192.localdomain localhost paul@RHELv4u2:~$ The message inside the hosts file is clear.1. do not remove the loopback address from /etc/hosts.0. the hosts file can be used to name servers.localdomain localhost root@RHELv4u4:~# echo 192. or various programs # that require network functionality will fail. This file contains a static table to link ip-addresses to hostnames.0.168.1.168. /etc/hosts Let’s start with the /etc/hosts file. or various programs # that require network functionality will fail.103 Sol9a 192.71 pasha 192.138 xander # virtual machines 192. or various programs # that require network functionality will fail. root@RHELv4u4:~# cat /etc/hosts # Do not remove the following line. paul@laika:~$ cat /etc/hosts 127. 127.1 localhost.Chapter 33. Like this example shows. 127.0.1.1.200 server1 root@RHELv4u4:~# In small networks.0.0. But you are allowed to add some entries to the hosts file.1.1 localhost.1. One easy way to add a name to ip relation is using the echo command.1.168.1 laika # servers 192.0.1.0.1 localhost.1 anya 10.

/etc/nsswitch. there is no guarantee that your ssh session will always survive a restart of network services.conf file. adjust the HOSTNAME directive in the /etc/sysconfig/network or /etc/network/interfaces file. root@RHELv4u4:~# vi /etc/sysconfig/network root@RHELv4u4:~# echo RHELv4u4 > /etc/HOSTNAME root@RHELv4u4:~# hostname localhost. Setting the hostname You can use the hostname tool to display or to set the machines hostname.0.138 Big networks should use Domain Name System or DNS instead of the hosts file. /etc/resolv. Changing the hostname requires a restart of the network services.4.Chapter 33.localdomain root@RHELv4u4:~# service network restart Shutting down interface eth0: [ OK ] 206 . paul@RHELv4u2:~$ cat /etc/resolv.2. One of those is the order between the /etc/hosts file and DNS. it is best to set up DNS instead of relying on the hosts file. Name Resolution 33. Setting dns before files will give dns priority over the hosts file.conf can decide on the order of things to process. It is a good idea to also put the hostname in /etc/HOSTNAME and /etc/hosts since applications sometimes expect it to be there. The new hostname then stays valid until the next reboot.3.0. Your computer can locate its DNS server using the /etc/resolv. root@RHELv4u4:~# grep host /etc/nsswitch.conf. But what happens when a hostname exists in /etc/hosts and in the DNS database ? 33. The following screenshot shows the relevant part of nsswitch.localdomain root@RHELv4u2:~# hostname Borg root@RHELv4u2:~# hostname Borg root@RHELv4u2:~# To change a machines hostname permanently.conf #hosts: db files ldap nis dns hosts: files dns 33. root@RHELv4u2:~# hostname localhost.conf The Name Service Switch file nsswitch.conf nameserver 10. This screenshot was taken via ssh.conf In larger networks.

1 localhost. Use echo or vi to add an entry for Antwerp (10. or various programs # that require network functionality will fail. Does it take priority to the name server ? Give the name server priority to the /etc/hosts file in /etc/nsswitch. Ping your neighbour using this name.com.localdomain localhost 192.168.Chapter 33. Practice hostname resolution 1. 2. Ping Antwerp.conf.localdomain paul@RHELv4u2:~$ cat /etc/sysconfig/network NETWORKING=yes HOSTNAME=RHELv4u2.conf ? Test that it workd by pinging google. Change your hostname with the hostname command. Verify what the GUI tool did in /etc/hosts.5. 207 . You can also use the nslookup or dig commands. 127. write it down here. 7.localdomain paul@RHELv4u2:~$ 33. 3.0. Does it work ? How long will this hostname be valid ? 4.222 RHELv4u2 RHELv4u2.com in /etc/hosts.7) in the hosts file. Display your hostname. Add an entry for google. Use the GUI tool to change your hostname.1.0.localdomain root@RHELv4u4:~# [ [ [ [ OK OK OK OK ] ] ] ] Below an example of a properly configured hostname paul@RHELv4u2:~$ cat /etc/HOSTNAME RHELv4u2 paul@RHELv4u2:~$ cat /etc/hosts # Do not remove the following line. Do you need to put the real hostname of your neighbour in your /etc/hosts ? 6.5. Is there a name server listed in /etc/resolv. Name Resolution Shutting down loopback interface: Setting network parameters: Bringing up loopback interface: Bringing up interface eth0: root@RHELv4u4:~# hostname RHELv4u4.6. Add an entry for your neighbour’s computer in your /etc/hosts file. 5.

Another popular feature of ssh is called X11 forwarding and is implemented with ssh -X.1. In other words. which means your user id and password can be sniffed by tools like ethereal aka wireshark. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added ’192. An ssh connection always starts with a cryptographic handshake.220 The authenticity of host ’192. Then authentication takes place (using user id/password or public/private keys) and communication can take place over the encrypted connection.220’s password: Last login: Sun Jan 21 07:16:26 2007 from 192.168.1.161’ to the list o Password: 208 . X forwarding via SSH The ssh protocol will remember the servers it connected to (and warn you in case something suspicious happened).168.222 paul@RHELv4u4:~$ 34.168.org -p 55555 Warning: Permanently added the RSA host key for IP address ’81.174.1.1.168.220 (192.1.220 paul@192.1. To securely connect to your servers. The OpenSSH package is maintained by the OpenBSD people and is distributed with a lot of operating systems (it may even be the most popular package in the world).168. paul@RHELv4u2:~$ ssh 192.220’ (RSA) to the list of known hosts.2. paul@192. Below sample use of ssh to connect from one server (RHELv4u2) to another one (RHELv4u4). use OpenSSH.168. followed by encryption of the transport layer using a symmetric cypher.168. These older protocols do not encrypt the login session.168. Although the application will run on the remote computer from greet. rlogin and rsh to remotely connect to your servers.Chapter 34. paul@RHELv4u2:~$ ssh 192. paul@laika:~/PDF$ ssh -X greet@greet. Secure Shell Avoid using telnet.240.220’s password: Last login: Sun Jan 21 08:49:19 2007 from 192.220)’ can’t be established. RSA key fingerprint is c4:3c:52:e6:d8:8b:ce:17:8b:c9:78:5a:f3:51:06:4f.168.ssh/known_hosts file. the tunnel is encrypted before you start typing anything.dyndns. OpenSSH 34.1.40 paul@RHELv4u4:~$ The second time ssh remembers the connection. Below an example of X11 forwarding: user paul logs in as user greet on her computer to start the graphical application mozilla-thunderbird.1. It added an entry to the ~/.1.1. it will be displayed on the screen attached locally to paul’s computer. and will use strong 128-bit encryption.

Avoid using version 1 anywhere. and then copy your public key to the destination server. root@laika:/etc/ssh# grep Protocol ssh_config # Protocol 2.1.Chapter 34.220 "ls -l" total 8 drwxr-xr-x 2 paul paul 4096 Jan 16 12:22 Desktop paul@RHELv4u2:~$ 34. OpenSSH Linux raika 2. since it contains some known vulnerabilities.168.5. Troubleshooting ssh Use ssh -v to get debug information about the ssh connection attempt. use ssh-keygen to generate a key pair without a passphrase.ssh/authorized_keys You can now use ssh to connect passwordless to another computer.6. ssh-keygen -t rsa scp . In combination with ssh’s capability to execute commands on the remote host.4.ssh/id_rsa. paul@RHELv4u2:~$ ssh 192. SSH Protocol versions The ssh protocol has two versions (1 and 2). Passwordless ssh To set up passwordless ssh authentication through public/private keys.105:~/.1. You can control the protocol version via /etc/ssh/ssh_config for the client side and /etc/ssh/sshd_config for the openssh-server daemon. this can be useful in pipes across different machines.3. 209 .pub otheruser@192.1 root@laika:/etc/ssh# grep Protocol sshd_config Protocol 2 root@laika:/etc/ssh# Configuration of ssh is done in the /etc/ssh directory and is pretty straightforward.168.8-2-686 #1 Tue Aug 16 13:22:48 UTC 2005 i686 GNU/Linux Last login: Thu Jan 18 12:35:56 2007 greet@raika:~$ ps fax | grep thun greet@raika:~$ mozilla-thunderbird & [1] 30336 34. 34.

9p1 debug1: match: OpenSSH_3. Practice SSH 1.168.. OpenSSH paul@laika:~$ ssh -v bert@192. (or between the ubuntu and the Red Hat) 210 .) 2.192 OpenSSH_4.ssh/id_dsa type -1 debug1: Remote protocol version 1. OpenSSL 0. Use ssh-keygen to create a keypait without passphrase.1.192] port 22. 34.* debug1: Enabling compatibility mode for protocol 2.ssh/id_rsa type 1 debug1: identity file /home/paul/. (You might need to install the openssh-server with aptitude.168. but on your neighbour’s computer.6. then test ssh to your neighbour (by ip-address or by hostname).1. Create a user for your neighbour.8c 05 Sep 2006 debug1: Reading configuration data /home/paul/.ssh/identity type -1 debug1: identity file /home/paul/. then close your firefox! Use ssh -X to run firefox on your screen..168. remote software version OpenSSH_3.99.Chapter 34.1. debug1: Connection established. Verify in the ssh configuration files that only protocol version 2 is allowed.9.3p2 Debian-8ubuntu1.192 [192.9p1 pat OpenSSH_3.ssh/config debug1: Reading configuration data /etc/ssh/ssh_config debug1: Applying options for * debug1: Connecting to 192.0 . debug1: identity file /home/paul/. Setup passwordless ssh between you and your neighbour. Do you see your neighbour’s bookmark ? 3. Create a bookmark in Firefox. 4.

The superdaemon xinetd The xinetd daemon is often called a superdaemon because it listens to a lot of incoming connections.2. inetd or xinetd First veroify whether your computer is running inetd or xinetd.conf and the files in the directory /etc/xinetd. When a connection request is received.Chapter 35. This Debian 4.deny) and then give control of the connection to the other daemon. but they have different configuration files. starting other daemons when they are needed).d paul@RHELv4u2:~$ = = = = = 60 SYSLOG authpriv HOST PID HOST 25 30 211 . [root@RHEL4b ~]# ps fax | grep inet 3003 ? Ss 0:00 xinetd -stayalive -pidfile /var/run/xinetd. paul@RHELv4u2:~$ cat /etc/xinetd. xinetd will first check TCP wrappers (/etc/hosts. and starts other daemons when they are needed.pid Both daemons have the same functionality (listening to many ports. Let’s first take a look at /etc/xinetd. and include /etc/xinetd.0 Etch is running inetd. This superdaemon is configured through /etc/xinetd.d/ defaults { instances log_type log_on_success log_on_failure cps } includedir /etc/xinetd.conf.allow and /etc/hosts.d.1. 35.conf # # Simple configuration file for xinetd # # Some defaults. xinetd and inetd 35. root@barry:~# ps fax | grep inet 3870 ? Ss 0:00 /usr/sbin/inetd This Red Hat Enterprise Linux 4 update 4 is running xinetd.

The socket_type should be set to stream for tcp services (and to dgram for udp). The superdaemon inetd This superdaemon has only one configuration file /etc/inetd. Every protocol or daemon that it is listening for. To use SWAT. gets one line in this file.conf tftp dgram udp wait root@barry:~# nobody /usr/sbin/tcpd /usr/sbin/in. 35.d/swat # default: off # description: SWAT is the Samba Web Admin Tool.d contains more specific configuration files. Setting this to no means the service is enabled! Check the xinetd and xinetd. The last setting disable can be set to yes or no. Let’s also take a look at one of them. service swat { port = 901 socket_type = stream wait = no only_from = 127. paul@RHELv4u2:~$ ls /etc/xinetd. xinetd and inetd According to the settings in this file. Use swat \ # to configure your Samba server. The directory /etc/xinetd.conf. The log_on_failure += concats the userid to the log message formatted in /etc/xinetd.conf manual pages for many more configuration options. and must be the same as the port specified in /etc/services.Chapter 35. Port determines the service port. It uses the authpriv facility to log the host ip-address and pid of successful daemon spawns.1 user = root server = /usr/sbin/swat log_on_failure += USERID disable = yes } paul@RHELv4u2:~$ The services should be listed in the /etc/services file. When a service (aka protocol linked to daemon) gets more than 25 cps (connections per second). it holds subsequent requests for 30 seconds.d amanda chargen-udp echo klogin rexec talk amandaidx cups-lpd echo-udp krb5-telnet rlogin telnet amidxtape daytime eklogin kshell rsh tftp auth daytime-udp finger ktalk rsync time chargen dbskkd-cdb gssftp ntalk swat time-udp paul@RHELv4u2:~$ cat /etc/xinetd.conf.0. root@barry:~# grep ftp /etc/inetd.tftpd /boot/ 212 . \ # connect to port 901 with your favorite web browser. xinetd can handle 60 client requests at once.3.0.

213 .conf #902 stream tcp nowait root /usr/sbin/vmware-authd vmware-authd 35. Practice 1. Here an example of the disabled vmware web interface (listening on tcp port 902). Disable swat.conf above by putting a # at the start of that line. Verify on all systems whether they are using xinetd or inetd. xinetd and inetd You can disable a service in inetd. paul@laika:~$ grep vmware /etc/inetd. (If telnet is installable. Enable swat. Is swat enabled or disabled ? 4. Look at the configuration files.4. 2. test it. then replace swat in these questions with telnet) Is swat installed ? If not. then install swat and look at the changes in the (x)inetd configuration. 3.Chapter 35. test it.

1.168. You can do this manually with modprobe. you have to load the kernel module for bonding. Binding multiple ip-addresses To bind more than one ip-addres to the same interface. multihomed hosts 36. Bonding two network cards You can combine two physical network interfaces as one logical interface.conf (used to be called /etc/modules.232 36.1. use ifup. root@RHELv4u2:/etc/sysconfig/network-scripts# alias bond0 bonding >> /etc/modprobe. use service network stop|start|restart.1. to deactivate it.conf).255 214 .168.conf You need two network cards to enable bonding. Only two directives are required in the file.3. use ifcfg-eth0:0. root@RHELv4u2:~# ifdown eth0:0 root@RHELv4u2:~# ifup eth0:0 To stop. Enabling extra ip-addresses To activate a virtual network interface.Chapter 36. root@RHELv4u2:~# cat /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE=eth0 BROADCAST=192. use ifdown. Do not stop the network when connected through ssh. configured like this. and add the MASTER and SLAVE variables. root@RHELv4u2:/etc/sysconfig/network-scripts# modprobe bonding root@RHELv4u2:/etc/sysconfig/network-scripts# lsmod | grep bon bonding 58984 0 Or automatically. and provides hardware redundancy.2. 36. For bonding to work. root@RHELv4u2:/etc/sysconfig/network-scripts# cat ifcfg-eth0:0 DEVICE=eth0:0 IPADDR=192. where the last zero can be anything else. In this case we used eth0 and eth1. start or restart all network interfaces and services. by adding the alias to /etc/modprobe. This doubles the bandwidth.

168.255.222 NETMASK=255. root@RHELv4u2:~# ifconfig bond0 Link encap:Ethernet HWaddr 00:0C:29:5A:86:D7 inet addr:192.1 MASTER=bond0 SLAVE=yes USERCTL=no root@RHELv4u2:~# cat /etc/sysconfig/network-scripts/ifcfg-eth1 DEVICE=eth1 BROADCAST=192.1.1.229 USERCTL=no root@RHELv4u2:~# To bring up the interface.1 MASTER=bond0 SLAVE=yes USERCTL=no root@RHELv4u2:~# And you need to set up a bonding interface.1.255.0 NETWORK=192.1.255.1.0 NETWORK=192.168.0 IPADDR=192.0 NETMASK=255.1.1.168.0 ONBOOT=yes TYPE=Ethernet GATEWAY=192.1.168.0 ONBOOT=yes TYPE=Ethernet GATEWAY=192. multihomed hosts HWADDR=00:0C:29:5A:86:D7 IPADDR=192.255. we call it bond0.1.0 inet6 addr: fe80::200:ff:fe00:0/64 Scope:Link UP BROADCAST RUNNING MASTER MULTICAST MTU:1500 Metric:1 RX packets:3835 errors:0 dropped:0 overruns:0 frame:0 215 .168. root@RHELv4u2:/etc/sysconfig/network-scripts# ifup bond0 Enslaving eth0 to bond0 Enslaving eth1 to bond0 root@RHELv4u2:~# The ifconfig command will show you all activated interfaces. In this case.168.168. root@RHELv4u2:~# cat /etc/sysconfig/network-scripts/ifcfg-bond0 DEVICE=bond0 BOOTPROTO=none ONBOOT=no NETWORK=192.168.168.255.1.255 HWADDR=00:0C:29:5A:86:E1 IPADDR=192.Chapter 36.255 Mask:255.168.1. just use the ifup bond0 command.232 NETMASK=255.255.168.229 Bcast:192.255.255.

Chapter 36. multihomed hosts
TX packets:1001 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:469645 (458.6 KiB) TX bytes:139816 (136.5 KiB) eth0 Link encap:Ethernet HWaddr 00:0C:29:5A:86:D7 inet6 addr: fe80::20c:29ff:fe5a:86d7/64 Scope:Link UP BROADCAST RUNNING SLAVE MULTICAST MTU:1500 Metric:1 RX packets:3452 errors:0 dropped:0 overruns:0 frame:0 TX packets:837 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:412155 (402.4 KiB) TX bytes:117844 (115.0 KiB) Interrupt:11 Base address:0x1400 eth1 Link encap:Ethernet HWaddr 00:0C:29:5A:86:D7 inet6 addr: fe80::20c:29ff:fe5a:86d7/64 Scope:Link UP BROADCAST RUNNING SLAVE MULTICAST MTU:1500 Metric:1 RX packets:392 errors:0 dropped:0 overruns:0 frame:0 TX packets:177 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:58084 (56.7 KiB) TX bytes:24078 (23.5 KiB) Interrupt:10 Base address:0x1480

36.4. Practice multihomed hosts
1. Add an extra ip address to your server. Test that it works (have your neighbour ssh to it)! 2. Use ifdown and ifup to disable and enable the second ip address. 3. Add a network card to the vmware machine, and bond the two cards as one virtual (double bandwidth and failover) card.

216

Chapter 37. NAS and NFS
37.1. Network Attached Storage (NAS)
NAS means using separate servers with lots of storage, connected over a (hopefully very fast) network. NAS servers offer file-based access over the network with protocols like NCP (old Novell Netware), Sun’s NFS (common on Unix) or SMB (implemented on Unix/Linux with Samba). NAS is not to be confused with SAN, which uses block-based access over proprietary protocols (Fiber Channel, iSCSI, ...). A NAS head is a NAS without on-board storage, which connects to a SAN and acts as a translator between the file-level NAS protocols and the block-level SAN protocols.

37.2. NFS: the Network File System
37.2.1. protocol versions
The older NFS versions 2 and 3 are stateless (udp) by default, but they can use tcp. Clients connect to the server using RPC (on Linux this is controlled by the portmap daemon. Look at rpcinfo to verify that NFS and its related services are running.
root@RHELv4u2:~# /etc/init.d/portmap status portmap (pid 1920) is running... root@RHELv4u2:~# rpcinfo -p program vers proto port 100000 2 tcp 111 portmapper 100000 2 udp 111 portmapper 100024 1 udp 32768 status 100024 1 tcp 32769 status root@RHELv4u2:~# service nfs start Starting NFS services: Starting NFS quotas: Starting NFS daemon: Starting NFS mountd:

[ [ [ [

OK OK OK OK

] ] ] ]

The same rpcinfo command when NFS is started.
root@RHELv4u2:~# rpcinfo -p program vers proto port 100000 2 tcp 111 portmapper 100000 2 udp 111 portmapper 100024 1 udp 32768 status 100024 1 tcp 32769 status 100011 1 udp 985 rquotad 100011 2 udp 985 rquotad 100011 1 tcp 988 rquotad 100011 2 tcp 988 rquotad 100003 2 udp 2049 nfs 100003 3 udp 2049 nfs

217

Chapter 37. NAS and NFS
100003 4 udp 100003 2 tcp 100003 3 tcp 100003 4 tcp 100021 1 udp 100021 3 udp 100021 4 udp 100021 1 tcp 100021 3 tcp 100021 4 tcp 100005 1 udp 100005 1 tcp 100005 2 udp 100005 2 tcp 100005 3 udp 100005 3 tcp root@RHELv4u2:~# 2049 2049 2049 2049 32770 32770 32770 32789 32789 32789 1004 1007 1004 1007 1004 1007 nfs nfs nfs nfs nlockmgr nlockmgr nlockmgr nlockmgr nlockmgr nlockmgr mountd mountd mountd mountd mountd mountd

NFS version 4 requires tcp (port 2049) and supports Kerberos user authentication as an option. NFS authentication only takes place when mounting the share. NFS versions 2 and 3 authenticate only the host.

37.2.2. server configuration
NFS is configured in /etc/exports. Here is a sample /etc/exports to explain the syntax. You need some way (NIS domain or LDAP) to synchronize userid’s across computers when using NFS a lot. The rootsquash option will change UID 0 to the UID of the nfsnobody user account. The sync option will write writes to disk before completing the client request.
paul@laika:~$ cat /etc/exports # Everyone can read this share /mnt/data/iso *(ro) # Only the computers barry and pasha can readwrite this one /var/www pasha(rw) barry(rw) # same, but without root squashing for barry /var/ftp pasha(rw) barry(rw,no_root_squash) # everyone from the netsec.lan domain gets access /var/backup *.netsec.lan(rw) # ro for one network, rw for the other /var/upload 192.168.1.0/24(ro) 192.168.5.0/24(rw)

You don’t need to restart the nfs server to start exporting your newly created exports. You can use the exportfs -va command to do this. It will write the exported directories to /var/lib/nfs/xtab, where they are immediately applied.

218

Chapter 37. NAS and NFS

37.2.3. client configuration
We have seen the mount command and the /etc/fstab file before.
root@RHELv4u2:~# mount -t nfs barry:/mnt/data/iso /home/project55/ root@RHELv4u2:~# cat /etc/fstab | grep nfs barry:/mnt/data/iso /home/iso nfs defaults 0 0 root@RHELv4u2:~#

37.2.4. Mounting NAS
Just a simple fictitious example. Suppose the project55 people tell you they only need a couple of CD-ROM images, and you already have them available on an NFS server. You could issue the following command to mount the network attached storage on their /home/project55 mount point.
root@RHELv4u2:~# mount -t nfs 192.168.1.40:/mnt/data/iso /home/project55/ root@RHELv4u2:~# ls -lh /home/project55/ total 3.6G drwxr-xr-x 2 1000 1000 4.0K Jan 16 17:55 RHELv4u1 drwxr-xr-x 2 1000 1000 4.0K Jan 16 14:14 RHELv4u2 drwxr-xr-x 2 1000 1000 4.0K Jan 16 14:54 RHELv4u3 drwxr-xr-x 2 1000 1000 4.0K Jan 16 11:09 RHELv4u4 -rw-r--r-- 1 root root 1.6G Oct 13 15:22 sled10-vmwarews5-vm.zip root@RHELv4u2:~#

37.3. Practice NFS
1. Create two directories with some files. Use NFS to share one of them as read only, the other must be writable. Have your neighbour connect to them to test. 2. Investigate the user owner of the files created by your neighbour. 3. Protect a share by ip-address or hostname, so only your neighbour can connect.

219

Chapter 38. Introduction to iptables
38.1. Introducing iptables
The Linux kernel has a built-in stateful firewall named iptables. To stop the iptables firewall on Red Hat, use the service command.
root@RHELv4u4:~# service iptables stop Flushing firewall rules: Setting chains to policy ACCEPT: filter Unloading iptables modules: root@RHELv4u4:~#

[ [ [

OK OK OK

] ] ]

The easy way to configure iptables, is to use a graphical tool like KDE’s kmyfirewall or Security Level Configuration Tool. You can find the latter in the GUI menu, somewhere in System Tools Security, or you can start it by typing system-config-securitylevel in bash. These tools allow for some basic firewall configuration. You can decide whether to enable or disable the firewall, and what typical standard ports are allowed when the firewall is active. You can even add some custom ports. When you are done, the configuration is written to /etc/sysconfig/iptables on Red Hat.
root@RHELv4u4:~# cat /etc/sysconfig/iptables # Firewall configuration written by system-config-securitylevel # Manual customization of this file is not recommended. *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] :RH-Firewall-1-INPUT - [0:0] -A INPUT -j RH-Firewall-1-INPUT -A FORWARD -j RH-Firewall-1-INPUT -A RH-Firewall-1-INPUT -i lo -j ACCEPT -A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT -A RH-Firewall-1-INPUT -p 50 -j ACCEPT -A RH-Firewall-1-INPUT -p 51 -j ACCEPT -A RH-Firewall-1-INPUT -p udp --dport 5353 -d 224.0.0.251 -j ACCEPT -A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT -A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 21 -j -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 25 -j -A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited COMMIT root@RHELv4u4:~#

ACCEPT ACCEPT ACCEPT ACCEPT

To start the service, issue the service iptables start command. You can configure iptables to start at boot time with chkconfig.
root@RHELv4u4:~# service iptables start Applying iptables firewall rules:

[

OK

]

220

0/0 0. Good iptables tutorials can be found online here http://iptables-tutorial.ESTABLISHED state NEW tcp dpt:22 state NEW tcp dpt:80 state NEW tcp dpt:21 state NEW tcp dpt:25 reject-with icmp-host-prohib Mastering firewall configuration requires a decent knowledge of tcp/ip.0.0.0.0.0/0 ACCEPT tcp -.0.0.0.0.0.2.0/0 0.0.0/0 ACCEPT all -.frozentux.0.0.0.0.0.0.0.0.0.0/0 0.0.0.0.0.0. root@RHELv4u4:~# service iptables status Table: filter Chain INPUT (policy ACCEPT) target prot opt source destination RH-Firewall-1-INPUT all -.0.html and here http://tldp.0.0.net/iptables-tutorial.0.0/0 root@RHELv4u4:~# destination 0.0.0.0.0.0.0/0 ACCEPT ah -.0.0. 2.0.0.0/0 ACCEPT tcp -.0.0/0 ACCEPT icmp -.0.0/0 0.0.0.0/0 0.0.0.0.0/0 ACCEPT udp -. Introduction to iptables root@RHELv4u4:~# chkconfig iptables on root@RHELv4u4:~# One of the nice features of iptables is that it displays extensive status information when queried with the service iptables status command.0. Practice iptables 1.0/0 Chain OUTPUT (policy ACCEPT) target prot opt source Chain RH-Firewall-1-INPUT (2 references) target prot opt source ACCEPT all -. 221 .0.0/0 ACCEPT tcp -.0/0 icmp type 255 udp dpt:5353 udp dpt:631 state RELATED.0.0.0.0.0.0.0/0 destination destination 0.251 0.0.0/0 0.0.0. Disable the firewall.0.0/0 0.0/0 REJECT all -.0.0.0.0/0 0.0. 38.Chapter 38.0.0/0 0.0/0 ACCEPT esp -.0/0 ACCEPT udp -.org/HOWTO/IP-Masquerade-HOWTO/.0. Verify whether the firewall is running.0.0.0.0.0.0/0 Chain FORWARD (policy ACCEPT) target prot opt source RH-Firewall-1-INPUT all -.0.0.0/0 ACCEPT tcp -.0/0 224.0.0/0 0.

[root@RHELv4u3 conf]# rpm -qa | grep -i vnc vnc-server-4.1 vnc-4.3. About VNC VNC can be configured in gnome or KDE using the Remote Desktop Preferences.0-8. VNC can be used to run your desktop on another computer (kinda like a software X-Terminal).49:2 VNC viewer version 3.localdomain:2 (root)’ desktop is RHELv4u3. tightvnc.0-8. It will default to a very simple graphical interface.1 [root@RHELv4u3 conf]# vncserver :2 You will require a password to access your desktops. 39.Chapter 39. Password: Verify: xauth: creating new authority file /root/. a lot of products (realvnc.localdomain:2. VNC server supports protocol version 3.3. VNC Client You can now use the vncviewer from another machine to connect to your vnc server.2.168. BSD and more.built Nov 20 2006 13:05:04 Copyright (C) 2002-2003 RealVNC Ltd.8 (viewer 3.realvnc. VNC has the added advantage of being operating system independent. See http://www. but you can also use it to see and take over the Desktop of another user. VNC 39.) use the same protocol on Solaris.... xvnc.log [root@RHELv4u3 conf]# 39. Copyright (C) 1994-2000 AT&T Laboratories Cambridge. Linux..vnc/RHELv4u3.3) Password: VNC authentication succeeded 222 . paul@laika:~$ vncviewer 192. The last part can be useful for help desks to show users how to do things.localdomain:2 Creating default startup script /root/.1.vnc/xstartup Starting applications specified in /root/.Xauthority New ’RHELv4u3. .7 . VNC Server Starting the vnc server for the first time.com for information on VNC.1.vnc/xstartup Log file is /root/.

Chapter 39. you can comment out the last two lines of ~/.localdomain:2 Starting applications specified in /root/.vnc/xstartup #!/bin/sh # Uncomment the following two lines for normal desktop: # unset SESSION_MANAGER # exec /etc/X11/xinit/xinitrc [ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup [ -r $HOME/.4. using protocol version 3.vnc/RHELv4u3.Xresources ] && xrdb $HOME/..vnc/xstartup Log file is /root/.3 ..localdomain:2 (root)’ desktop is RHELv4u3. Use VNC to connect from one machine to another.localdomain:2. 223 .localdomain:2 (root)" Connected to VNC server. VNC Desktop name "RHELv4u3. If you don’t like the simple twm window manager. [root@RHELv4u3 ~]# vncserver -kill :2 Killing Xvnc process ID 5785 [root@RHELv4u3 ~]# vncserver :2 New ’RHELv4u3.Xresources xsetroot -solid grey vncconfig -iconic & # xterm -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" & # twm & gnome-session & [root@RHELv4u3 ~]# Don’t forget to restart your vnc server after changing this file.log 39. [root@RHELv4u3 ~]# cat . Practive VNC 1.vnc/xstartup and add a gnome-session & line to have vnc default to gnome instead.

Backup network configuration 40.txt And system-config-network-cmd can also be used to restore these settings. root@RHELv4u4:~# system-config-network-cmd -i -c < NetworkSettings20070208. take a backup of the relevant portions in /etc. The system-config-network-cmd can do this for you.Chapter 40. Red Hat network settings backup It is always a good idea to have a backup of current network settings.1. root@RHELv4u4:~# system-config-network-cmd -e > NetworkSettings20070208. 224 .txt For other Linux Systems.

default gateway (or router) and many more options.conf 225 .leases [dhcpd] (5) . but there are a lot of good examples in the manual page of dhcpd. The DHCP server leases this IP configuration for a certain lease time. then each server will broadcast a DHCPOFFER. You can verify installation with dpkg or rpm (depends on your choice of distribution). [root@RHEL4b ~]# ls -l /etc/dhcpd. About DHCP The Dynamic Host Configuration Protocol is defined in rfc 2131 in 1997 (obsoleting rfc 1541 from 1993).dhcpd configuration file dhcpd.2. 41. which is then confirmed by the server with a DHCPACK.conf [dhcpd] (5) .1 root root 86 Nov 19 2005 /etc/dhcpd.Dynamic Host Configuration Protocol Server dhcpd. rpm -qa | grep dhcpd dpkg -l | grep dhcpd 41. subnet mask.1.conf and a file containing leases in /var/lib/dhcp/dhcpd. inlcuding ip address. DHCP Server 41. First a DHCPDISCOVER is sent from the client.leases. [paul@RHEL4b ~]$ apropos dhcpd dhcpd (8) .conf -rw-rw-r-.DHCP client lease database [paul@RHEL4b ~]$ The default configuration file is very modest. Sniffing DHCP traffic will show four broadcasts. About dhcpd The dhcpd daemon has a configuration file /etc/dhcpd. Is DHCP installed ? The most common DHPC server on Linux is the dhcpd daemon.3. The client will select an offer and broadcasts a DHCPREQUEST. The client will try to renew the lease before it expires by repeating the DHCPREQUEST packet and awaiting the corresponding DHCPACK. The DHCP protocol allows for a DHCP server to provide a DHCP client with a complete IP address configuration.Chapter 41.

1.1 192.55.Chapter 41.100.255.55.55.0 netmask 255.1 192. DHCP Server 41. Example router This is an example subnet configuration with a router (aka default gateway) set to 192. range 192.168.100. [root@RHEL4b etc]# tail /var/lib/dhcp/dhcpd.255.5.0. } [root@RHEL4b etc]# service dhcpd start Starting dhcpd: [ OK ] 41.conf ddns-update-style ad-hoc.0 netmask 255.6.168.0.0 netmask 255.0.conf subnet 192.0.100.55.100 { 226 . [root@RHEL4b etc]# cat dhcpd.168.100. [root@RHEL4b etc]# cat dhcpd.conf that can be used to start dhcpd. The subnet contains 100 available addresses in a 16-bit netmask.55.leases file will contain an overview of all leases current leased by the DHCP server.leases lease 192. subnet 192.55. } 41. } 41. address leases The /var/lib/dhcp/dhcpd.168. Starting dhcpd Below a complete and working example dhcpd. Example subnet Below is a sample configuration for a subnet serviced by the dhcpd daemon. [root@RHEL4b etc]# cat dhcpd.168.168.168.100. range 192.0 { option routers 192.168.55.conf subnet 192.168.0.1.168.0.168.1 192.168.4.255.0 { option routers 192.100. The dhcpd daemon will warn you if the router is unreachable for the subnet clients.7.1.0 { range 192.168.

1.104.conf will provide the client(s) with the ip address of a DNS name server. You can add additional options (like router and DNS server) to the host reservation. and start the dhcp server. Test that it works. binding state active. } 41.8.55. 3. ends 4 2007/08/30 18:09:39.10.191. Create a host reservation with another DNS server for one of your clients. fixed-address 192. 227 .Chapter 41. [root@RHEL4b etc]# grep name dhcpd. Configure a subnet in /etc/dhcpd. } [root@RHEL4b etc]# 41.9.168.168. DNS server option Adding the domain-name-servers option to a subnet (or other) section in /etc/dhcpd. 41. next binding state free. DHCP Server starts 4 2007/08/30 06:09:39.conf with router and DNS options. using the MAC address of the host.conf host WinXP1 { hardware ethernet 00:0C:29:2B:5B:EF. Test with a client that it works.conf option domain-name-servers 192. This is called a DHCP host reservation. Install dhcpd 2. client-hostname "WinXP". [root@RHEL4b etc]# tail -5 dhcpd. hardware ethernet 00:0c:29:2b:5b:ef. uid "\001\000\014)+[\357". Host reservation It is possible to tie a specific configuration to a host. Practice dhcpd 1.

4-16.3. the named manual pages and /etc/named. named The software is called ’bind’.com. [root@RHEL4b etc]# apropos named | grep -i domain named (8) .EL4 42.2. 42.fr for France.net. the daemon runs as ’named’ ! So look for the named daemon. Below the root are the Top Level Domains (TLD’s). And there are country TLD’s. and is represented with a dot.2.4-16.4-16.mil. Reverse lookup zones contain PTR records.EL4 bind-devel-9.gov. Forward lookup zones are most common. .Internet domain name server 228 . It’s primary function is to resolve names to ip addresses.info. most local DNS servers will answer to recursive queries. Domain Name System DNS or Domain Name System is a worldwide distributed hierarchichal database.EL4 bind-libs-9. .2. aero. [root@RHEL4b etc]# rpm -qa | grep -i bind ypbind-1.1. Use rpm or dpkg to verify whether it is installed. bind One of the most common name servers on Linux is the Berkeley Internet Name Domain (bind) server. and to point to internet services like SMTP and LDAP.edu and others. .Chapter 42.17. The internet contains thirteen logical DNS servers for the top of the hierarchy.EL4 bind-9.EL4 bind-utils-9. . There are common TLD’s like . they translate ip addresses to hostnames or FQDN’s. Introduction to BIND 42.2.be for Belgium and . This top is called the root. .4-16. they contain host or A records to translate hostnames or Fully Qualified Domain Names (FQDN) to ip addresses.2-8 bind-chroot-9.conf to work with bind.4-16. like .2.museum. . The internet root name servers will only answer iterative queries.2.

mail. [root@RHEL4b named]# cat classdemo.168. ( 2007083100 .1.local.1. The default /etc/named.classdemo.classdemo.local.conf on RHEL is a caching only name server. Introduction to BIND 42.168. minimum IN NS IN MX IN A rhel4b mail www ftp server2 IN IN IN IN IN A A A A A rhel4b. serial 3H .local.zone". Caching only Name Server A caching only name server is a DNS server that is not authoritative for any zone.1 10 229 .zone named]# Here is an example of a zone file.classdemo.conf zone "classdemo.168.1.zone classdemo. [root@RHEL4b [root@RHEL4b /var/named [root@RHEL4b [root@RHEL4b named]# cd /var/named/ named]# pwd named]# cp localhost. 192. @ IN SOA rhel4b. To create the zone file.191 192. allow-update { none.4. the easy method is to copy an existing zone file (this is easier than writing from scratch).local" IN { type master. Our first zone The way to set up zones in /etc/named.168. It forwards queries to other DNS servers and locally caches the results. refresh 900 .1. admin.local.local.1.191 192. }. file "classdemo.191 192.5. 42.191 192.1.classdemo. Here is an example of such an entry in /etc/named.Chapter 42.168. retry 1W .191 192.168. }.local.local.local. expiry 1D ) .zone $TTL 86400 $ORIGIN classdemo.conf is to create a zone entry with a reference to another file located in /var/named.

230 . 2. Starting the name server When starting the name server. Set up a working DNS server with your own zone. don’t forget to look at the log file to verify that all your zones are properly configured. Introduction to BIND 42.7.6. Set up a master and a slave server.Chapter 42. Practice DNS 1. [root@RHEL4b etc]# service named restart Stopping named: Starting named: [root@RHEL4b etc]# service named status number of zones: 9 debug level: 0 xfers running: 0 xfers deferred: 0 soa queries in progress: 0 query logging is OFF server is up and running [root@RHEL4b etc]# [ [ OK OK ] ] 42. Test that it works.

10-1.9.0. [paul@RHEL4b ~]$ rpm -qa | grep samba samba-common-3.10-1.4E.4E.. paul@laika:~$ aptitude install samba-server 43. 43. then the easiest way is to use the graphical menu (Applications -.0.Chapter 43.2..9 samba-client-3. Looks like Samba 3 in the screenshot here. The non-graphical way is to either use rpm -i followed by the samba-version.0.0.0. Installing Samba Samba is installed by default on Red Hat Enterprise Linux. [paul@RHEL4b ~]$ up2date -i samba Ubuntu and Debian users can use the aptitude program.21-1 samba-swat-3. 231 .10.0. then up2date is the tool to use.0. use rpm -qa. Our Feisty Fawn here uses Samba 3.2 paul@laika:~$ Samba common files used by both the.Add/Remove Applications) and select "Windows File Server" in the Server section.rpm file. [paul@RHEL4b ~]$ rpm -i samba-3.10-1.4E.9 system-config-samba-1.24 paul@laika:~$ dpkg -l | grep samba ii samba-common 3.4E.10-1.9 [paul@RHEL4b ~]$ Use dpkg -l on Debian or Ubuntu.9 samba-3. Don’t forget man smb. Verify installed version To see the version of samba installed on RedHat.rpm Or if you have a subscription to RHN.0.10-1.System Settings -. If Samba is not yet installed. Introduction to Samba 43. version 3.conf.2.1.24-2ubuntu1.3. Documentation Obviously there are manual pages for Samba.4E.

The file can be edited manually.conf 232 .pdf /usr/share/doc/samba-3.conf (. there is also an excellent book called Samba by example (again available as book in shops.conf [smb] (5) .0.10/Samba-HOWTO-Collection.The configuration file for the Samba suite smbpasswd (5) .The Samba encrypted password file smbstatus (1) .report on current Samba connections swat (8) .) paul@laika:~$ ls -l /etc/samba/smb.A Windows SMB/CIFS fileserver for UNIX smb. [paul@RHEL4b ~]$ locate Samba-HOWTO-Collection.pdf Ubuntu packages the docs as a seperate package from Samba.conf Samba configuration is done in the smb.tdb files [root@RHEL4b samba]# Samba comes with excellent documentation in html and pdf format (and also as a free download from Samba.conf -rw-r--r-.Samba documentation (PDF format) root@laika:~# find /usr/share/doc/samba-doc-pdf | grep -i howto /usr/share/doc/samba-doc-pdf/Samba3-HOWTO.1 root root 10836 May 30 23:08 /etc/samba/smb.tool for backing up and ..org and are for sale as a printed book).conf [root@RHEL4b ~]# The default smb.Chapter 43.1 root root 10515 2007-05-24 00:21 /etc/samba/smb.. The file is usually located in /etc/samba.Tool for administration of Samba and remote CIFS servers pdbedit (8) .Samba Web Administration Tool tdbbackup (8) .4.gz Besides the howto. You can find the exact location with smbd -b. Red Hat Enterprise Linux installs the html and pdf version in /usr/share/doc by default.conf -rw-r--r-. root@laika:~# aptitude search samba | grep -i documentation i samba-doc .conf file. [paul@RHEL4b ~]$ ls -l /etc/samba/smb. or you can use a web based interface like webmin or swat to manage it.Samba documentation i samba-doc-pdf . Introduction to Samba [root@RHEL4b samba]# apropos samba cupsaddsmb (8) .. of samba . [root@RHEL4b ~]# smbd -b | grep CONFIGFILE CONFIGFILE: /etc/samba/smb.The Samba NetBIOS hosts file net (8) .conf file contains a lot of examples with explanations.pdf.. and as a free pdf and html). smb.manage the SAM database (Database of Samba Users) samba (7) . 43.export printers to samba for windows clients lmhosts (5) .

4E. C:\Documents and Settings\paul>net view Server Name Remark ------------------------------------------------------------------------------\\RHEL4B Samba 3. 233 .conf. which will output all the global options with their default value. and to be visible to other computers (Microsoft shows computers in Network Neighborhood or My Network Places).conf can get a long list of values behind them. 43.conf is visible to Microsoft computers nearby. Introduction to Samba Below is an example of a very minimalistic smb.conf accepts synonyms like create mode and create mask. Marie.conf [global] workgroup = WORKGROUP [firstshare] path = /srv/samba/public [paul@RHEL4b ~]$ Below is a screenshot of the net view command on Microsoft Windows XP sp2. [paul@RHEL4b ~]$ testparm Load smb config files from /etc/samba/smb. Justine. And on occasion you can even switch words. smb.conf and restarting samba will change the option. and sometimes minor spelling errors like browsable and browseable.5. Suzanne Curious but true. The remark seen by the net view command is the default value for the "server string" option. testparm To verify the syntax of the smb. Sabine \ Amelie. the changed option is visible on the Microsoft computers. valid users = Serena. After a while.0.conf Processing section "[firstshare]" Loaded services file OK. Some parameters in smb. You can continue a line (for clarity) on the next by ending the line with a backslash. Server role: ROLE_STANDALONE Press enter to see a dump of your service definitions [paul@RHEL4b ~]$ An interesting option is testparm -v. [paul@RHEL4b ~]$ cat /etc/samba/smb.10-1. you can use testparm.conf file. Simply adding this value to the global section in smb.Chapter 43. It shows how the Samba server with the minimalistic smb.9 \\W2000 \\WINXP The command completed successfully. Lindsay \ Kim. It allows samba to start. Venus. the guest only parameter is identical to only guest.

[root@RHEL4b samba]# cat smb. Samba daemons Samba 3 consists of three daemons. so it is good practice to keep this file small. The nmbd daemon takes care of all the names and naming. The two comment lines and the default option are no longer there.conf. The testparm -s option allows you to do both.conf # Global parameters [global] server string = Public Test Server [firstshare] path = /srv/samba/public [root@RHEL4b samba]# 43.conf Load smb config files from smb.conf.Chapter 43. and redirect stdout to the real smb. we execute testparm with the -s option. The screenshot below shows you how.conf. First the smb. The samba daemons are constantly (once every 60 seconds) checking the smb. But it is also good practice to document your samba configuration. [root@RHEL4b samba]# cat smb. and handles browsing.full > smb. Introduction to Samba C:\Documents and Settings\paul>net view Server Name Remark ------------------------------------------------------------------------------\\RHEL4B Public File Server \\W2000 \\WINXP The command completed successfully. and to explicitly set options that have the same default values.full) and let testparm parse this for you.conf file.conf.full file with the explicitly set option workgroup to WORKGROUP. It 234 .conf.full [global] workgroup = WORKGROUP # This is a demo of a documented smb. And below is the end result.conf file.6.conf # These two lines are removed by testparm -s server string = Public Test Server [firstshare] path = /srv/samba/public Next. It registers and resolves names. smbd and winbindd. The idea is to have your samba configuration in another file (like smb. they are named nmbd. [root@RHEL4b samba]# testparm -s smb.full Processing section "[firstshare]" Loaded services file OK. It will output the smallest possible samba configuration file. while retaining all your settings.

0. The winbindd daemon is only started to handle Microsoft Windows domain membership.d]# smbclient -NL winxp Anonymous login successful Domain=[WORKGROUP] OS=[Windows 5. It should be started after nmbd. and the name of the Master Browser. [root@RHEL4b ~]# /etc/init.4E.1] Server=[Windows 2000 LAN Manager] 235 . The smbd daemon manages file transfers and authentication.10-1.4E.d/smb start Starting SMB services: Starting NMB services: [root@RHEL4b ~]# service smb restart Shutting down SMB services: Shutting down NMB services: Starting SMB services: Starting NMB services: [root@RHEL4b ~]# [ [ [ [ [ [ OK OK OK OK OK OK ] ] ] ] ] ] 43. The -L switch is followed by the name of the host to check.7. smbclient With smbclient you can see browsing and share information from your smb server.9] Server --------RHEL4B WINXP Workgroup --------WORKGROUP Comment ------Public Test Server Master ------WINXP The screenshot below uses smbclient to display information about a remote smb server (in this case a Windows XP machine).d/samba) on any linux.0. [root@RHEL4b init. You can start the daemons by invoking /etc/init. your workgroup. Red Hat derived systems are happy with service smb start. The -N switch is added to avoid having to enter an empty password.9] Sharename Type Comment -----------------firstshare Disk IPC$ IPC IPC Service (Public Test Server) ADMIN$ IPC IPC Service (Public Test Server) Anonymous login successful Domain=[WORKGROUP] OS=[Unix] Server=[Samba 3. [root@RHEL4b init.10-1.d/smb start (some systems use /etc/init. It will display all your shares.Chapter 43.d]# smbclient -NL rhel4b Anonymous login successful Domain=[WORKGROUP] OS=[Unix] Server=[Samba 3. Introduction to Samba should be the first daemon to start.

0. the browse list is not yet distributed to all clients by the (to be elected) browser master.10). The first one is taken immediately after booting four different computers (one MS Windows 2000. Introduction to Samba Sharename Type Comment -----------------Error returning browse list: NT_STATUS_ACCESS_DENIED Anonymous login successful Domain=[WORKGROUP] OS=[Windows 5. smbtree Another useful tool to troubleshoot Samba or simply to browse the SMB network is smbtree. In its simplest form.8. Let’s take a look at two screenshots of smbtree in action (with blank password).1) \\HM2003 [paul@RHEL4b ~]$ The information displayed in the previous screenshot looks incomplete. one MS Windows XP.0.Chapter 43.1 (Connection refused) cli_full_connection: failed to connect to RHEL4B<20> (127.0. smbtree will do an anonymous browsing on the local subnet. The browsing elections are still ongoing.0.0.1] Server=[Windows 2000 LAN Manager] Server --------RHEL4B W2000 WINXP Workgroup --------WORKGROUP Comment ------Public Test Server Master ------WINXP 43. displaying all SMB computers and (if authorized) their shares. [paul@RHEL4b ~]$ smbtree Password: WORKGROUP PEGASUS \\WINXP \\RHEL4B Pegasus Domain Member Server Error connecting to 127. one MS Windows 2003 and one RHEL 4 with Samba 3. [paul@RHEL4b ~]$ smbtree Password: WORKGROUP \\W2000 [paul@RHEL4b ~]$ 236 . And it shows even less. The next screenshot was taken about one minute later.

Chapter 43.24 paul@laika:~$ smbtree Password: WORKGROUP \\W2000 \\W2000\firstshare \\W2000\C$ Default share \\W2000\ADMIN$ Remote Admin \\W2000\IPC$ Remote IPC PEGASUS \\WINXP cli_rpc_pipe_open: cli_nt_create failed on pipe \srvsvc to machine WINXP. this time it looks a lot nicer. Introduction to Samba So we wait a while. Let us try the old smbtree version on our RHEL server. and then run smbtree again. [paul@RHEL4b ~]$ smbtree Password: WORKGROUP \\W2000 PEGASUS \\WINXP \\RHEL4B Pegasus Domain Member Server \\RHEL4B\ADMIN$ IPC Service (Pegasus Domain Member Server) \\RHEL4B\IPC$ IPC Service (Pegasus Domain Member Server) \\RHEL4B\domaindata Active Directory users only \\HM2003 [paul@RHEL4b ~]$ smbtree --version Version 3. [paul@RHEL4b ~]$ smbtree -UAdministrator%Stargate1 WORKGROUP \\W2000 PEGASUS \\WINXP \\WINXP\C$ Default share 237 . but this time with Administrator credentials (which are the same on all computers).0. to show you the difference when using the latest version of smbtree (below a screenshot taken from Ubuntu Feisty Fawn). Error was NT_STATUS_ACCESS_DENIED paul@laika:~$ The previous screenshot also provides useful errors on why we cannot see shared info on computers winxp and w2003. The latest version shows a more complete overview of machines and shares. paul@laika:~$ smbtree --version Version 3.10-1. Error was NT_STATUS_ACCESS_DENIED \\RHEL4B Pegasus Domain Member Server \\RHEL4B\ADMIN$ IPC Service (Pegasus Domain Member Server) \\RHEL4B\IPC$ IPC Service (Pegasus Domain Member Server) \\RHEL4B\domaindata Active Directory users only \\HM2003 cli_rpc_pipe_open: cli_nt_create failed on pipe \srvsvc to machine HM2003.4E.9 [paul@RHEL4b ~]$ I added the version number of smbtree in the previous screenshot.0.

d/swat to disable = no. [root@RHEL4b samba]# ps fax | grep inet 15026 pts/0 S+ 0:00 \_ grep inet 2771 ? Ss 0:00 xinetd -stayalive -pidfile /var/run/xinetd.1 user = root server = /usr/sbin/swat log_on_failure += USERID disable = no } [root@RHEL4b samba]# /etc/init. To use SWAT. [root@RHEL4b samba]# cat /etc/xinetd.pid [root@RHEL4b samba]# Then edit the inetd..d/swat # default: off # description: SWAT is the Samba Web Admin Tool. 43.. this gives a very nice overview of all SMB computers and their shares. Remote Admin Remote IPC A network share to be used by Local . To enable the tool. The tool is accessible with a web browser on port 901 of the host system.0. first find out whether your system is using the inetd or the xinetd superdaemon. service swat { port = 901 socket_type = stream wait = no only_from = 127. Use swat \ # to configure your Samba server. Introduction to Samba \\WINXP\ADMIN$ \\WINXP\share55 \\WINXP\IPC$ \\RHEL4B \\RHEL4B\ADMIN$ \\RHEL4B\IPC$ \\RHEL4B\domaindata \\HM2003 \\HM2003\NETLOGON \\HM2003\SYSVOL \\HM2003\WSUSTemp \\HM2003\ADMIN$ \\HM2003\tools \\HM2003\IPC$ \\HM2003\WsusContent \\HM2003\C$ [paul@RHEL4b ~]$ Remote Admin Remote IPC Pegasus Domain Member Server IPC Service (Pegasus Domain Member Server) IPC Service (Pegasus Domain Member Server) Active Directory users only Logon server share Logon server share A network share used by Local Publishing . \ # connect to port 901 with your favorite web browser. Samba Web Administration Tool (SWAT) Samba comes with a web based tool to manage your samba configuration file.. Default share As you can see.conf or change the disable = yes line in /etc/xinetd.Chapter 43.9.d/xinetd restart Stopping xinetd: [ OK ] 238 .0..

Write down the name and ip address of this machine.10.. Do the same for all the other (virtual) machines available to you. write down the version of Samba. Verify with smbclient that your Samba server works.conf. !! Make sure you know your student number. Verify that another (Microsoft) computer can see your Samba server. How many A4 pages is this file ? Then look at the same pdf on samba. edit the appropriate hosts files.. Open the Official Samba-3 howto pdf file that is installed on your computer. Change the "Server String" parameter in smb. if you like names. 5. it erases alle your manually edited comments in smb.orig 7. Start Samba with your minimal smb. Create a minimalistic smb. 43. it is updated regularly. Stop the Samba server.conf. Introduction to Samba Starting xinetd: [root@RHEL4b samba]# [ OK ] Be careful when using SWAT.. 11. 9. 14. 4. 6.conf. Make sure Samba is installed. Enable SWAT and take a look at it. name it smb. smbclient. 3.minimal and test it with testparm. My Network Places.Chapter 43. 12.conf.org. Practice 0.conf. Verify that you can logon to a Linux/Unix computer. anything *ANYTHING* you name must include your student number! 1.) ? 239 . 10.conf. 8. Browse the network with net view and smbtree. Verify networking by pinging the machines. 2. Take a backup copy of the original smb. How long does it take before you see the change (net view. 13.

Chapter 43. Which computer is the master browser master in your workgroup ? What is the master browser ? 17. Introduction to Samba 15. Will restarting Samba after a change to smb.conf speed up the change ? 16. 240 . then install a sniffer (ethereal/wireshark) and watch the browser elections. If time permits (or if you are waiting for other students to finish this practice).

Read Only File Server Let’s start with setting up a very simple read only file server with Samba.txt -rw-r--r-.Samba_nobody /srv/samba/readonly/ [root@RHEL4b samba]# chmod 777 /srv/samba/readonly/ [root@RHEL4b samba]# ls -l /srv/samba/ total 4 drwxrwxrwx 2 Samba_nobody Samba_nobody 4096 Jun 22 11:09 readonly [root@RHEL4b samba]# cd /srv/samba/readonly/ [root@RHEL4b readonly]# chown Samba_nobody.txt [root@RHEL4b readonly]# ll total 8 -rw-r--r-. and access to the share is enforced by Samba (remember we gave 777 to the directory).1 root root 17 Jun 22 11:13 summer.Chapter 44." > summer." > winter. [root@RHEL4b samba]# cat smb.Samba_nobody * [root@RHEL4b readonly]# ll total 8 -rw-r--r-.txt [root@RHEL4b readonly]# echo "It is hot today.conf [global] workgroup = WORKGROUP 241 .1 root root 18 Jun 22 11:13 winter.conf file (feel free to test it with testparm). Simple Samba File Servers 44.1 Samba_nobody Samba_nobody 17 Jun 22 11:13 summer.1 Samba_nobody Samba_nobody 18 Jun 22 11:13 winter. (Strictly speaking. [root@RHEL4b ~]# useradd -c "Anonymous Samba Access" -p secret -s /bin/false Samba_nobody [root@RHEL4b samba]# chown Samba_nobody. We put our file server in the default workgroup. [root@RHEL4b samba]# mkdir -p /srv/samba/readonly [root@RHEL4b samba]# ls -l /srv/samba/ total 4 drwxr-xr-x 2 root root 4096 Jun 22 11:07 readonly [root@RHEL4b samba]# cd /srv/samba/readonly/ [root@RHEL4b readonly]# echo "It is cold today.txt [root@RHEL4b readonly]# Linux will always require a user account before giving access to files (the files in our example above are owned by root). give it a descriptive server string.txt -rw-r--r-. Everyone (even anonymous guests) will receive read access.1. you can setup a Samba read only file server without creating an extra user account).txt [root@RHEL4b samba]# It is time to create the smb. The share is called pubread. The first step is to create a directory and put some test files in it. and set the security to share level (more on this later). So we will create a user for our readonly file server and make this user the owner of the directory and all of its files.

9] Server --------RHEL4B WINXP Comment ------Public Test Server Workgroup Master --------------WORKGROUP WINXP [root@RHEL4b readonly]# The final test is to go to a Microsoft Windows computer and read a file on the Samba server. C:\Documents and Settings\paul>net use k: \\rhel4b\pubread The command completed successfully.10-1. restart the samba server and verify the existence of the share with smbclient.0.Chapter 44. and reading the files.4E.0. C:\Documents and Settings\paul>k: K:\>dir Volume in drive K is pubread 242 .4E.0.1 Password: Domain=[WORKGROUP] OS=[Unix] Server=[Samba 3.10-1. Simple Samba File Servers server string = Public Anonymous File Server security = share [pubread] path = /srv/samba/readonly comment = files to read read only = Yes guest ok = Yes [root@RHEL4b samba]# After testing with testparm. First we use the net use command to mount the pubread share on the driveletter k.0. Then we test looking at the contents of the share.9] [ [ [ [ OK OK OK OK ] ] ] ] Sharename Type Comment -----------------pubread Disk files to read IPC$ IPC IPC Service (Public Anonymous File Server) ADMIN$ IPC IPC Service (Public Anonymous File Server) Domain=[WORKGROUP] OS=[Unix] Server=[Samba 3. [root@RHEL4b readonly]# service smb restart Shutting down SMB services: Shutting down NMB services: Starting SMB services: Starting NMB services: [root@RHEL4b readonly]# smbclient -L 127.

.Samba_nobody /srv/samba/writable/ [root@RHEL4b samba]# chmod 777 /srv/samba/writable/ 243 .2. net use. Similar to before. we start by creating a directory. let us try writing.522. Writable File Server In this second example. Make sure the directory is owned properly.3. K:\> Just to be on the safe side. K:\> 44. then share it with Samba. Create a directory in a good location (FHS) to share files for everyone to read. Simple Samba File Servers Volume Serial Number is 0D56-11F2 Directory of K:\ 06/22/2007 11:13 AM <DIR> . 06/22/2007 11:13 AM 18 winter. put a textfile in it. [root@RHEL4b samba]# mkdir /srv/samba/writable [root@RHEL4b samba]# chown Samba_nobody.txt 06/22/2007 11:13 AM 17 summer. 4. we will create a share where everyone can create files and write to files. 2.) that the share is accessible for reading. 06/22/2007 11:09 AM <DIR> ..conf.txt 2 File(s) 35 bytes 2 Dir(s) 2.txt Access is denied. K:\>echo very cold > winter..conf. 3. Verify from your own and from another computer (smbclient.Chapter 44.txt It is cold today.ReadOnlyFileServer. Make a backup copy of your smb.048 bytes free K:\>type winter. and setting ownership to our Samba_nobody user account. . name it smb.763. 44. Practice 1.

conf.conf Processing section "[pubread]" Processing section "[pubwrite]" Loaded services file OK.522. C:\Documents and Settings\paul>net use w: \\rhel4b\pubwrite The command completed successfully.. Server role: ROLE_STANDALONE Press enter to see a dump of your service definitions # Global parameters [global] server string = Public Anonymous File Server security = SHARE [pubread] comment = files to read path = /srv/samba/readonly guest ok = Yes [pubwrite] comment = files to read and write path = /srv/samba/writable read only = No guest ok = Yes Restart Samba. then onto the Windows XP machine and test our writing skills. 06/22/2007 12:31 PM 23 hello. Below the check with testparm. C:\Documents and Settings\paul>w: W:\>echo This is a write test > hello.763.048 bytes free W:\>type hello. Simple Samba File Servers Then we simply add a share to our file server by editing smb.txt W:\>dir Volume in drive W is pubwrite Volume Serial Number is 0D56-272A Directory of W:\ 06/22/2007 12:29 PM <DIR> . [root@RHEL4b samba]# testparm Load smb config files from /etc/samba/smb.txt 1 File(s) 23 bytes 2 Dir(s) 2.txt This is a write test W:\> 244 . 06/22/2007 12:26 PM <DIR> .Chapter 44.txt type hello.

use smbd -b. the linux owner of the files created through this writable share is the linux guest account (usually named nobody). For this we use the force user and force group options. To accomplish this.. It just owns the files and directories that we created for our shares. We just want a clean linux server. [root@RHEL4b samba]# To find out where Samba keeps this information. The goal of this section is to force ownership of files created through the Samba share to belong to our Samba_nobody user. Forcing a User Owner The Samba_nobody user account that we created in the previous examples is actually not used by Samba..1 nobody nobody 0 Jun 22 12:33 test. The nobody user does not have a password. Samba_nobody:502:552902031BEDE9EFAAD3B435B51404EE:878D8014606CDA29677A44.txt -rwxr--r-. [root@RHEL4b samba]# smbpasswd -a Samba_nobody New SMB password: Retype new SMB password: Added user Samba_nobody. [root@RHEL4b samba]# ls -l /srv/samba/writable/ total 4 -rwxr--r-. 245 . Simple Samba File Servers There is one little issue though. [root@RHEL4b samba]# smbd -b | grep -i private PRIVATE_DIR: /etc/samba You can use a simple cat to see the contents of the smbpasswd database.4. nobody needs to know this user account or password. [root@RHEL4b samba]# cat /etc/samba/smbpasswd nobody:99:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXX. we can adjust our writable share to force the ownership of files created through it. [root@RHEL4b samba]# Now that Samba knows about this user. Now we can be sure that all files in the Samba writable share are owned by the same Samba_nobody user. Remember. the Samba_nobody user does have one (it is secret).. our server is still accessible to everyone. 44. We will improve this in the next topic. we first have to tell Samba about this user.Chapter 44.txt [root@RHEL4b samba]# So this is not the cleanest solution. We can do this by adding the account to smbpasswd.1 nobody nobody 23 Jun 22 12:31 hello.. The PRIVATE_DIR variable will show you where the smbpasswd database is located.

9] Server --------RHEL4B WINXP Workgroup --------WORKGROUP [paul@RHEL4b ~]$ Comment ------Public Anonymous File Server Master ------WINXP It can also be used to test user access to a Samba share.9] smb: \> dir . This first screenshot shows how to verify that Samba is running on your localhost.0.10-1. Simple Samba File Servers [root@RHEL4b samba]# testparm -s smb.txt 18 Fri Jun 22 summer.txt 17 Fri Jun 22 45734 blocks of size 262144. If the connection is established..0. we can do the same tests from within linux with smbclient. D 0 Fri Jun 22 . More about smbclient Instead of going to the Microsoft machines. D 0 Fri Jun 22 winter. then we get an smb prompt. You can use exit or q to return to bash.10-1. [paul@RHEL4b ~]$ smbclient -NL localhost Domain=[WORKGROUP] OS=[Unix] Server=[Samba 3.0.4E.10-1.5. First an example of how to test anonymous access to our pubread share. [paul@RHEL4b ~]$ smbclient //rhel4b/pubread -U% Domain=[WORKGROUP] OS=[Unix] Server=[Samba 3.4E. who is the Master Browser of the workgroup and some more information. 10541 blocks available 11:13:15 13:03:54 11:13:11 11:13:15 2007 2007 2007 2007 246 .9] Sharename Type Comment -----------------pubread Disk files to read pubwrite Disk files to read and write authwrite Disk authenticated users only IPC$ IPC IPC Service (Public Anonymous File Server) ADMIN$ IPC IPC Service (Public Anonymous File Server) Domain=[WORKGROUP] OS=[Unix] Server=[Samba 3.conf 2>/dev/null | tail -7 [pubwrite] comment = files to read and write path = /srv/samba/writable force user = Samba_nobody force group = Samba_nobody read only = No guest ok = Yes [root@RHEL4b samba]# 44. how to list all the Samba shares.Chapter 44.4E.

Chapter 44. Simple Samba File Servers
smb: \> exit [paul@RHEL4b ~]$

44.6. NetBIOS name resolving
If your clients are spread across multiple subnets, then it is likely there is a WINS (Microsoft Windows Internet Naming Service) or NBNS (NetBIOS Name Server) available to resolve NetBIOS names. You should then point Samba to the wins server with the wins server parameter.
wins server = 10.0.0.42

You can set the resolving order that Samba should use with the name resolve order parameter.
name resolve order = wins lmhosts host bcast

44.7. Practice
1. Create a directory and share it with Samba. 2. Make sure everyone can read and write files, test writing with smbclient and from a Microsoft computer. 3. Verify the ownership of files created by various users. 4. Use the "force user" and "force group" directives to force ownership of files created in this shared directory. 5. Test that Samba properly registers in a WINS server. 6. Test the working of force user with smbclient and/or net use and/or the MS Windows Explorer.

247

Chapter 45. Samba Servers with authentication and restrictions
45.1. Authenticated User Access
The goal of this example is to set up a file share accessible to a number of different users. The users will need to authenticate with their password before access to this share is granted. We will first create three randomly named users, each with their own password. First we add these users to linux.
[root@RHEL4b samba]# useradd -c "Serena Williams" -p SerenaW Serena [root@RHEL4b samba]# useradd -c "Kim Clijsters" -p KimC Kim [root@RHEL4b samba]# useradd -c "Martina Hingis" -p MartinaH Martina

Then we add them to the smbpasswd file, with the same password.
[root@RHEL4b samba]# smbpasswd -a Serena New SMB password: Retype new SMB password: Added user Serena. [root@RHEL4b samba]# smbpasswd -a Kim New SMB password: Retype new SMB password: Added user Kim. [root@RHEL4b samba]# smbpasswd -a Martina New SMB password: Retype new SMB password: Added user Martina.

We add the following section to our smb.conf (and create the directory /srv/samba/authwrite).
[authwrite] path = /srv/samba/authwrite comment = authenticated users only read only = No guest ok = No

After restarting Samba, we test with different users from within Microsoft computers. First Kim from Windows XP.
C:\>net use m: \\rhel4b\authwrite /user:Kim KimC The command completed successfully. C:\>m: M:\>echo greetings from Kim > greetings.txt

248

Chapter 45. Samba Servers with authentication and restrictions The next screenshot is Martina on a Windows 2000 computer, she succeeds in writing her files, but fails to overwrite the file from Kim.
C:\>net use k: \\rhel4b\authwrite /user:Martina MartinaH The command completed successfully. C:\>k: K:\>echo greetings from martina > Martina.txt K:\>echo test overwrite > greetings.txt Access is denied.

You can also test connecting with authentication with smbclient, first we a wrong password, then with the correct one.

[paul@RHEL4b ~]$ smbclient //rhel4b/authwrite -UMartina%wrongpass Domain=[WORKGROUP] OS=[Unix] Server=[Samba 3.0.10-1.4E.9] tree connect failed: NT_STATUS_WRONG_PASSWORD [paul@RHEL4b ~]$ smbclient //rhel4b/authwrite -UMartina%MartinaH Domain=[WORKGROUP] OS=[Unix] Server=[Samba 3.0.10-1.4E.9] smb: \> more Martina.txt getting file \Martina.txt of size 25 as /tmp/smbmore.Uv6c86 (24.4 kb/s) (average 24.4 kb/ greetings from martina smb: \> q [paul@RHEL4b ~]$

Congratulations, you now have a simple standalone Samba file server with authenticated access. And the files in the shares belong to their proper owners.
[root@RHEL4b samba]# ls -l /srv/samba/authwrite/ total 8 -rwxr--r-- 1 Kim Kim 17 Jun 22 13:05 greetings.txt -rwxr--r-- 1 Martina Martina 25 Jun 22 13:08 Martina.txt

45.2. Frequently used share settings
45.2.1. valid users
To restrict users per share, you can use the valid users parameter. In the example below, only the users listed as valid will be able to access the tennis share.
[tennis] path = /srv/samba/tennis comment = authenticated and valid users only read only = No guest ok = No valid users = serena, kim, venus, justine

249

Chapter 45. Samba Servers with authentication and restrictions

45.2.2. invalid users
If you are paranoia, you can also use invalid users to explicitely deny the listed users access. When a user is in both lists, the user has no access!
[tennis] path = /srv/samba/tennis read only = No guest ok = No valid users = kim, serena, venus, justine invalid users = venus

45.2.3. create mask and inherit permissions
Similar to umask (but not inverted), you can use the create mask and directory mask to set default permissions for newly created files and directories.
[tennis] path = /srv/samba/tennis read only = No guest ok = No create mask = 644

With inherit permissions = Yes you can force newly created files and directories to inherit permissions from their parent directory, overriding the create mask and directory mask settings.

45.2.4. hosts allow
The hosts allow or allow hosts parameter is one of the key advantages of Samba. It allows access control of shares on the ip-address level. To allow only specific hosts to access a share, list the hosts, seperated by comma’s.
allow hosts = 192.168.1.5, 192.168.1.40

Allowing entire subnets is done by ending the range with a dot.
allow hosts = 192.168.1.

Subnet masks can be added in the classical way.
allow hosts = 10.0.0.0/255.0.0.0

250

Chapter 45. Samba Servers with authentication and restrictions You can also allow an entire subnet with exceptions.
hosts allow = 10. except 10.0.0.12

45.2.5. hosts deny
The hosts deny or deny hosts parameter is the logical counterpart of the previous. The syntax is the same as for hosts allow.
hosts deny = 192.168.1.55, 192.168.1.56

45.2.6. hide unreadable
Setting hide unreadableto yes will prevent users from seeing files that cannot be read by them.
hide unreadable = yes

45.2.7. read list
One more setting before we go on to the next topic. Even on a writable share, you can set a list of read only users with the read list parameter.
[authwrite2] path = /srv/samba/authwrite2 comment = authenticated users only read only = No guest ok = No read list = Martina, Roberto

45.3. Practice
0. Make sure you have properly named backups of your smb.conf of the previous practices. 1. Create three users (on the Unix and on the Samba), remember their passwords! 2. Set up a shared directory that is only accessible to authenticated users. 3. Verify that files created by these users belong to them.

251

5. Limit access to the sales share to Sandra. "write list". test that it works.19. Then combine them with "read list".168. Make sure that Roberto cannot access the share. Samba Servers with authentication and restrictions 4. Limit one shared directory to the 192.18.chown) and make a table of minimal mandatory settings for readonly/readwrite shared directories. 6.1. "hosts allow" and "hosts deny". 8. then combine the "read only" and "writable" statements to check which one has priority. Then combine them with file permissions on the linux filesystem (chmod.1. 252 .Chapter 45.0/24 subnet. Test that it works!! 9. Make sure users can only see files and directories that they can read. Even though the share is writable. 7. and another share to the two computers with ip-addresses 192. If time permits (or if you are waiting for other students to finish this practice).17.33 and 172. Set the create mask for files to read and write for everyone. Ann should only have read access.168. Ann and Veronique.

2. Remember. [domaindata] path = /srv/samba/domaindata comment = Active Directory users only read only = No 46. [root@RHEL4b samba]# net rpc join -UAdministrator%Stargate1 Joined domain PEGASUS. we need to provide Samba with a range of uid’s and gid’s that it can use to create these user accounts. [root@RHEL4b samba]# Time to start Samba followed by winbindd. [global] workgroup = PEGASUS server string = Pegasus Domain Member Server security = Domain idmap uid = 20000-22000 idmap gid = 20000-22000 winbindd use default domain = Yes Nothing special is required for the share section in smb. Samba Domain Member Server 46. so we set the security option to domain. Below is our new global section in smb. smb. but by the Active Directory Domain Controllers. Joining the Active Directory Domain While the Samba server is stopped. we do not manually create users in smbpasswd or on the linux (/etc/passwd). Since linux requires a user account for every user accessing its file system. [root@RHEL4b samba]# service smb start Starting SMB services: Starting NMB services: [root@RHEL4b samba]# service winbindd start Starting winbindd services: [root@RHEL4b samba]# [ [ [ OK OK OK ] ] ] 253 .conf.conf.1. Only Active Directory users are allowed access.Chapter 46. Authentication will not be handled by Samba now.conf The workgroup option in the global section should match the netbios name of the Active Directory domain. you can use net rpc join to join the Active Directory Domain. The first Active Directory user to connect will receive linux uid 20000.

Chapter 46.conf file now. Assuming a user account Venus with password VenusW is just created on the Active Directory. nsswitch. only those that have been used. Samba Domain Member Server 46. [root@RHEL4b samba]# getent passwd Justine [root@RHEL4b samba]# wbinfo -a Justine%JustineH plaintext password authentication succeeded challenge/response password authentication succeeded [root@RHEL4b samba]# getent passwd Justine 254 . The screenshot below shows that Kim and Serena are normal linux users in /etc/passwd.conf We need to update the /etc/nsswitch. [root@RHEL4b samba]# wbinfo -a Venus%VenusW plaintext password authentication succeeded challenge/response password authentication succeeded [root@RHEL4b samba]# We can use getent to verify that winbindd is working and actually adding the Active directory users to /etc/passwd. [root@RHEL4b samba]# getent passwd Kim Kim:x:504:504:Kim Clijsters:/home/Kim:/bin/bash [root@RHEL4b samba]# getent passwd Serena Serena:x:503:503:Serena Williams:/home/Serena:/bin/bash [root@RHEL4b samba]# getent passwd Venus venus:*:20000:20000::/home/PEGASUS/venus:/bin/false Not all Active Directory user accounts added to /etc/passwd by winbindd. [root@RHEL4b samba]# wbinfo --set-auth-user=Administrator%Stargate1 We can also use wbinfo -a to verify authentication of a user against Active Directory.3. so user group and host names can be resolved against the winbindd daemon. winbindd The winbindd daemon is talking with the Active Directory domain.conf [root@RHEL4b samba]# grep winbindd /etc/nsswitch.4. With wbinfo you can provide winbindd with credentials to talk to Active Directory. and that the Active Directory user Venus received uid 20000 in /etc/passwd. [root@RHEL4b samba]# vi /etc/nsswitch. we get the following screenshot.conf passwd: files winbindd group: files winbindd hosts: files dns winbindd [root@RHEL4b samba]# 46.

Verify that you have a working Active Directory (AD) domain. Practice 1. Setup Samba as a member server in the domain.1 justine 20000 0 Jun 22 19:54 created_by_justine_on_winxp.txt -rwxr--r-.txt -rwxr--r-. Verify the creation of a computer account in AD for your Samba server. Files created by them. and verify ownership of their files.txt 46. [root@RHEL4b samba]# ll /srv/samba/domaindata/ total 0 -rwxr--r-. 255 . Verify the automatic creation of AD users in /etc/passwd with wbinfo and getent. 2. 5.5. 3. Samba Domain Member Server justine:*:20001:20000::/home/PEGASUS/justine:/bin/false [root@RHEL4b samba]# All the Active Directory users can now easily connect to the Samba share. 4.Chapter 46.1 venus 20000 0 Jun 22 19:55 created_by_venus.1 maria 20000 0 Jun 22 19:57 Maria. belong to them. Connect to Samba shares with AD users.

a Samba 3 domain controller can not share domain control with Windows domain controllers. The same is valid for Samba 3 in an Active Directory Domain with Windows 2000 and/or Windows 2003 DC’s.1.1. 47. Another option would be to use LDAP.1.conf. but as of this writing.conf Now is a good time to start adding comments in your smb.2.1. Samba 3 can only be a member server. About Domain Controllers 47. and it should accept domain logons (domain logons = Yes). About password backends The example below uses the tdbsam password backend. First we’ll take a look at the naming of our domain and server in the [global] section. then the Samba team advises to not use tdbsam. [global] # names workgroup = SPORTS netbios name = DCSPORTS server string = Sports Domain Controller # domain control parameters security = user os level = 80 preferred master = Yes domain master = Yes domain logons = Yes 256 . The security must be set to user (which is the default). In a Windows NT4 domain. In short. When you need more than one Domain Controller. with one Windows NT4 PDC and zero or more BDC’s.1. smb. 47. Samba Domain Controller 47.2. so it should win all browser elections (os level above 32) to become the browser master. Samba 4 Samba 4 can be a domain Controller in an Active Directory domain.Chapter 47. Our Samba server is the most stable system in the network. and at the domain controlling parameters. Samba 3 Samba 3 can act as a domain controller in its own domain. Samba 4 is not released for production! 47. Larger domains will benefit from using LDAP instead of the not so scalable tdbsam.3.

nttennis -p stargate Venus useradd -m -G ntsports.nttennis -p stargate Kim useradd -m -G ntsports. the file /etc/samba/passdb. When you add the first user to tdbsam.ntfootball -p stargate Figo useradd -m -G ntsports. This is the relevant part of smb. Users can all access the general sports file share. to test our Samba server. [sports] comment = Information about all sports path = /srv/samba/sports valid users = @ntsports read only = No [tennis] comment = Information about tennis path = /srv/samba/tennis valid users = @nttennis read only = No [football] comment = Information about football path = /srv/samba/football valid users = @ntfootball read only = No Part of the Microsoft definition of a domain controller is that it should have a netlogon share.3.Chapter 47. [netlogon] comment = Network Logon Service path = /srv/samba/netlogon admin users = root guest ok = Yes browseable = No 47. 257 .tdb will be created. Users and Groups To be able to use users and groups in Samba.ntfootball -p stargate Pfaff Next we must make these users known to Samba with the smbpasswd tool. but only group members can access their own sport share.nttennis -p stargate Serena useradd -m -G ntsports. Samba Domain Controller Then we create some sections for file shares. [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b samba]# samba]# samba]# samba]# samba]# samba]# samba]# samba]# samba]# samba]# groupadd ntadmins groupadd ntsports groupadd nttennis groupadd ntfootball useradd -m -G ntadmins -p Stargate1 Administrator useradd -m -G ntsports.conf to create this netlogon share on Samba. we have to set up some users and groups on the Linux computer.

conf. Samba Domain Controller [root@RHEL4b samba]# smbpasswd -a Administrator New SMB password: Retype new SMB password: Unable to open/create TDB passwd pdb_getsampwnam: Unable to open TDB passwd (/etc/samba/passdb. [root@RHEL4b samba]# smbpasswd -a root New SMB password: Retype new SMB password: Added user root. TDBSAM converted successfully. This computer account also has a password (but you cannot know it) to prevent other computers with the same name from accidentally becoming member of the domain. The computer account created by Samba is visible in the /etc/passwd file on linux. you will be able to logon with Administrator (password Stargate1). Below a screenshot of the winxp$ computer account. [root@RHEL4b samba]# Adding the second user generates less output. created by Samba 3. Computer accounts appear as a normal user account. but end their name with a dollar sign. 47. by adding an add machine script to the global section of smb.4. We will fix this in the next section. [root@RHEL4b samba]# tail -5 /etc/passwd Serena:x:508:512::/home/Serena:/bin/bash Kim:x:509:513::/home/Kim:/bin/bash Figo:x:510:514::/home/Figo:/bin/bash Pfaff:x:511:515::/home/Pfaff:/bin/bash winxp$:x:512:516::/home/nobody:/bin/false To be able to create the account.Chapter 47. Vista) can become a member of a domain. trying to convert it. but you will get an error about your roaming profile.tdb)! TDBSAM version too old (0). 258 . After reboot of the Microsoft computer. Added user Administrator. And we will have to tell Samba how to to this. About Computer Accounts Every NT computer (Windows NT. Joining the domain (by right-clicking on My Computer) means that a computer account will be created in the domain. 2000. you will need to provide credentials of an account with the permission to create accounts (by default only root can do this on Linux). add machine script = /usr/sbin/useradd -s /bin/false -d /home/nobody %u You can now join a Microsoft computer to the sports domain (with the root user). XP.

we also need to set the location of the profiles share (this can be another Samba server) in the global section.1 Venus Venus 524288 Jul 5 2007 NTUSER. logon home = logon path = Microsoft computers store a lot of User Metadata and application data in a user profile. if you want to force local profiles instead of roaming profiles.1 Venus Venus 1024 Jul 5 2007 NTUSER.conf.1 Venus Venus 268 Jul 5 10:03 ntuser.DAT -rwxr--r-.5. logon path = \\%L\Profiles\%U The %L variable is the name of this Samba server.DAT. First we need to add the relevant section in smb.Chapter 47. Making this profile available on the network will enable users to keep their Desktop and Application settings across computers. [Profiles] comment = User Profiles path = /srv/samba/profiles readonly = No profile acls = Yes Besides the share section. After adding a user to smbpasswd and letting the user log on and off. the profile of the user will look like this. User profiles on the network are called roaming profiles or roving profiles. Roaming Profiles For your information.LOG -rw-r--r-. then simply add the following two lines to the global section in smb. [root@RHEL4b samba]# ll /srv/samba/profiles/Venus/ total 568 drwxr-xr-x 4 Venus Venus 4096 Jul 5 10:03 Application Data drwxr-xr-x 2 Venus Venus 4096 Jul 5 10:03 Cookies drwxr-xr-x 3 Venus Venus 4096 Jul 5 10:03 Desktop drwxr-xr-x 3 Venus Venus 4096 Jul 5 10:03 Favorites drwxr-xr-x 4 Venus Venus 4096 Jul 5 10:03 My Documents drwxr-xr-x 2 Venus Venus 4096 Jul 5 10:03 NetHood -rwxr--r-. The Samba domain controller can manage these profiles.ini drwxr-xr-x 2 Venus Venus 4096 Jul 5 10:03 PrintHood drwxr-xr-x 2 Venus Venus 4096 Jul 5 10:03 Recent drwxr-xr-x 2 Venus Venus 4096 Jul 5 10:03 SendTo drwxr-xr-x 3 Venus Venus 4096 Jul 5 10:03 Start Menu drwxr-xr-x 2 Venus Venus 4096 Jul 5 10:03 Templates [root@RHEL4b samba]# 259 . the %U variable translates to the username.conf. Samba Domain Controller 47.

47.Serena. [root@RHEL4b netlogon]# cat start.6.7. choosing algorithmic mapping Successully added group sports to the mapping db [root@RHEL4b samba]# Now you can use the Samba groups on all NTFS volumes on members of the domain.Kim ntfootball:x:509:Figo. make sure it has the proper carriage returns that DOS files have.Figo. [root@RHEL4b netlogon]# Then copy the scripts to the netlogon share..Chapter 47.bat unix2dos: converting file start. logon scripts Before testing a logon script.bat 260 . But the nttennis group is not available on the windows machines. we have groups on Unix that contain those users.Pfaff nttennis:x:508:Venus.bat net use Z: \\DCSPORTS0\SPORTS [root@RHEL4b netlogon]# unix2dos start. all access works fine on the Samba server. logon script = start. [root@RHEL4b samba]# grep nt /etc/group . To do this. and add the following parameter to smb. Samba Domain Controller 47.. we have to map unix groups to windows groups. choosing algorithmic mapping Successully added group football to the mapping db [root@RHEL4b samba]# net groupmap add ntgroup="sports" unixgroup=ntsports type=d No rid or sid specified.Pfaff [root@RHEL4b samba]# We already added Venus to the tdbsam with smbpasswd. To make the groups available on windows (like in the ntfs security tab of files and folders). [root@RHEL4b samba]# net groupmap add ntgroup="tennis" unixgroup=nttennis type=d No rid or sid specified... smbpasswd -a Venus Does this mean that Venus can access the tennis and the sports shares ? Yes.Kim. choosing algorithmic mapping Successully added group tennis to the mapping db [root@RHEL4b samba]# net groupmap add ntgroup="football" unixgroup=ntfootball type=d No rid or sid specified. Groups in NTFS acls We have users on Unix. ntadmins:x:506:Administrator ntsports:x:507:Venus.bat to DOS format .conf. we use the net groupmap command.Serena.

6. Knowing that %s contains the client operating system. create a seperate log file for every computer(account). If time permits (or if you are waiting for other students to finish this practice).%s. Knowing that the %m variable contains the computername.8. 5. include a smb. (The share will only be visible to clients with that OS).Chapter 47. Salesdata must be accessible to all sales people and to all managers. 2. 4. 3. set them up and verify that users receive their home directory mapped under the H:-drive in MS Windows Explorer. Setup and verify the proper working of roaming profiles. Use a couple of samba domain groups with members to set acls on ntfs. salespresentations and meetings. Samba Domain Controller 47. Create the shares salesdata. Practice 1. Verify that it works! 7. SalesPresentations is only for all sales people. Use groups to accomplish this. Join a Microsoft computer to your domain. 261 . Verify the creation of a computer account in /etc/passwd. Setup Samba as a domain controller. then combine "valid users" and "invalid users" with groups and usernames with "hosts allow" and "hosts deny" and make a table of which get priority over which.conf file that contains a share. Meetings is only accessible to all managers. 9. 8. Find information about home directories for users.

enabled since Jan 01 00:00 printer HPColor is idle. Samba Print Servers 48. We make these printers available to everyone for printing..0.244:9100 device for HPColor: parallel:/dev/lp0 HPBlack accepting requests since Jan 01 00:00 HPColor accepting requests since Jan 01 00:00 printer HPBlack is idle.Chapter 48. The lpstat tool will see the printers like this. Type ---IPC IPC Printer Printer Comment ------IPC Service (Public Anonymous Print Server) IPC Service (Public Anonymous Print Server) Local Raw Printer Local Raw Printer 262 .1. Our smb. so the spooler just sends the jobs to the print device (without any kind of processing or interpreting of the print jobs). We set up the CUPS printers without a driver (raw printing device).0. Simple CUPS Print Server Let us start by setting up a Samba print server that serves two printers which are set up with the CUPS web interface (http://localhost:631)..168.0.4E.10-1. enabled since Jan 01 00:00 The windows clients need to install the correct printer driver themselves.9] Sharename --------IPC$ ADMIN$ HPBlack HPColor .1. [root@RHEL4b samba]# smbclient -NL 127.conf looks like this. [global] server string = Public Anonymous Print Server security = share disable spoolss = No printing = cups [printers] path = /var/spool/samba read only = Yes printable = Yes use client driver = Yes Let’s do a quick check with smbclient. [root@RHEL4b samba]# lpstat -t scheduler is running system default destination: HPColor device for HPBlack: socket://192.1 Domain=[WORKGROUP] OS=[Unix] Server=[Samba 3.

Status Local Remote Network ------------------------------------------------------------------------------OK LPT1 \\rhel4b\HPColor Microsoft Windows Network The command completed successfully. except that CUPS is the default. [root@RHEL4b samba]# lpq -a Rank Owner Job File(s) Total Size active nobody 4 smbprn. 263 .conf file is similar to the one for CUPS printing. just browse to your Samba server in the add printer wizard. Or you can connect with the net use command as shown below. [root@RHEL4b samba]# lpstat -t scheduler is running system default destination: HPColor device for HPBlack: socket://192. Simple BSD Print Server The default BSD style print commands (also refered to as LPD/LPR) are defined in rfc 1179.00000002 Mozilla Firefox 120832 bytes For troubleshooting.2.bat C:\shov\shovel. Now you can add the printer to windows computers in the workgroup. C:\shov>net use New connections will be remembered. The smb. C:\shov>print shovel.bat is currently being printed After printing a test page (by rightclicking on the printer icon in windows and then clicking on the print test page button of the properties dialog box) and issuing the print command from within Firefox. The file now looks like this.168. C:\shov>net use lpt1: \\rhel4b\HPColor The command completed successfully.00000001 Test Page 112640 bytes 1st nobody 5 smbprn.1. enabled since Jan 01 00:00 HPBlack-4 nobody 112640 Sat 07 Jul 2007 07:59:33 AM CEST HPBlack-5 nobody 120832 Sat 07 Jul 2007 08:00:04 AM CEST 48.Chapter 48. it can be useful to stop (pause) the printer. Samba Print Servers That looks ok. the print queue looks like this.244:9100 device for HPColor: parallel:/dev/lp0 HPBlack accepting requests since Jan 01 00:00 HPColor accepting requests since Jan 01 00:00 printer HPBlack disabled since Jan 01 00:00 Paused printer HPColor is idle. This way the jobs stay in the queue.

Server role: ROLE_STANDALONE Press enter to see a dump of your service definitions # Global parameters [global] server string = Public Anonymous Print Server printing = bsd print command = lpr -r -P’%p’ %s lpq command = lpq -P’%p’ lprm command = lprm -P’%p’ %j [printers] path = /var/spool/samba guest ok = Yes printable = Yes browseable = No [root@RHEL4b samba]# 48.conf Processing section "[printers]" Loaded services file OK. Simple Unix SysV Print Server SystemV style printing uses the lp command in this form.3.Chapter 48.conf to share Unix System V type printers with Samba. Samba Print Servers [global] server string = Public Anonymous Print Server printing = bsd load printers = yes [printers] path = /var/spool/samba writable = no printable = Yes public = yes Testparm however gives us some more information on values used for the print commands. [global] server string = Public Anonymous Print Server printing = sysv load printers = yes [printers] 264 . So here is a simple smb. we have to add this removal to smb. lp -dprinter -s file Since by default this command does not remove the file. [root@RHEL4b samba]# testparm Load smb config files from /etc/samba/smb.conf.

265 . the log file looks like this.5. Samba Prining tips The printable = Yes line must always be present in Samba printer shares. %s %f %p %j filename with path (of the file to be printed) filename without path name of the destination unix printer print job number 48.00000017.NeDuGj [root@RHEL4b samba]# Here is a list variables that are used by Samba for printing.log Nothing will be printed. Samba Print Servers path = /var/spool/samba writable = no printable = Yes public = yes print command = lp -d%p -s %s .ARQtkM lpr -r -P’HP400’ smbprn. In this case.conf. rm %s 48. Instead of the actual print command. so it cannot be also a printer share. To troubleshoot the print command. Practice 1. The [homes] section automatically creates a share for each user with that username. [printers] path = /var/spool/samba writable = no printable = Yes public = yes print command = echo "lpr -r -P’%p’ %s" >> /tmp/bsdprint. but you can test the print command that is generated by Samba.YbFkuN lpr -r -P’HP400’ smbprn.4.Chapter 48.conf like this.00000013. construct the printers section in smb. you can da a little trick in smb.00000012.log lpr -r -P’HP400’ smbprn. Create two printers (with lpadmin or with the cups web interface) and pause(stop) them. [root@RHEL4b samba]# cat /tmp/bsdprint. It is also important to have a naming convention that prevents printers from having the same name as users. even in the [printers] section.

0/16 subnet to access the printer. Your manager asks you to log the lpr command syntax. If time permits. Samba Print Servers 2. 3..Chapter 48.. 5. 266 . Make sure only Isabelle and Caroline can access one of the printers.5. There are some issues with a BSD printer. its stdout and its stderr to three different files.0. Make sure they have to be on the 10. Connect with a Microsoft computer and test printing. Serve these printers with Samba. 4.

[paul@rhel4 ~]$ rpm -qa | grep -i httpd httpd-2. . scalable.3-3. server-side.. running named as httpd.1.52-25..html) about seventy percent of all web servers are running on Apache. named as apache2. .2-common 2. [root@RHELv4u3 ~]# /etc/init.1-1 httpd-devel-2. .ent paul@laika:~$ dpkg -l | grep apache ii apache2 2.. Some people say that the name is derived from a patchy web server. HTML-embedded .2build1 ii apache2-mpm-prefork 2.52-25.com/archives/web_server_survey..2build1 ii libapache2-mod-php5 5.1-0ubuntu1.netcraft.2.3-3. About According to NetCraft (http://news. use the proper tools (rpm.0..52-25..0.2.ent httpd-suexec-2.2.0..3-3.2. utility programs for webser.. scalable..3. because of all the patches people wrote for the NCSA httpd server. root@laika:~# ps -C apache2 267 .Chapter 49.ent system-config-httpd-1.2 Next generation.0.2build1 ii apache2-utils 2. To verify whether Apache is installed.2.) and grep for apache or httpd.3-3.. Apache 49.. dpkg. Next generation. This is how apache looks when it is installed on Red Hat Enterprise Linux 4.d/httpd status httpd is stopped [root@RHELv4u3 ~]# service httpd start Starting httpd: [root@RHELv4u3 ~]# ps -C httpd PID TTY TIME CMD 4573 ? 00:00:00 httpd 4576 ? 00:00:00 httpd 4577 ? 00:00:00 httpd 4578 ? 00:00:00 httpd 4579 ? 00:00:00 httpd 4580 ? 00:00:00 httpd 4581 ? 00:00:00 httpd 4582 ? 00:00:00 httpd 4583 ? 00:00:00 httpd [root@RHELv4u3 ~]# [ OK ] And here is Apache running on Ubuntu Feisty Fawn.2build1 ii apache2. Traditional model for Apach.52-25.ent httpd-manual-2..

The second test is to connect to your Apache from another computer. The file explains itself./usr/lib/httpd/build conf conf.d logs -> ./var/log/httpd modules -> . (The new way of defining virtual hosts is through seperate config files in the conf.d/apache2 status * Usage: /etc/init.d/apache2 {start|stop|restart|reload|force-reload} root@laika:~# To verify that apache is running../usr/lib/httpd/modules run -> ./. Virtual hosts Virtual hosts can be defined by ip-address. 49.d directory./. by port or by name (host record). and browse to http://localhost..3..conf. But it still takes place in /etc/httpd or /etc/apache. and contains examples for how to set up virtual hosts or configure access.2. An Apache test page should be shown. 49.conf # # This is a small test website # 268 ././.Chapter 49. The http://localhosts/manual url will give you an extensive Apache manual. Apache PID TTY TIME CMD 6170 ? 00:00:00 apache2 6248 ? 00:00:01 apache2 6249 ? 00:00:01 apache2 6250 ? 00:00:00 apache2 6251 ? 00:00:01 apache2 6252 ? 00:00:01 apache2 7520 ? 00:00:01 apache2 8943 ? 00:00:01 apache2 root@laika:~# /etc/init../var/run The main configuration file for the Apache server on RHEL is /etc/httpd/conf/httpd... on Ubuntu it is /etc/apache2/apache2. Apache configuration Configuring Apache changed a bit the past couple of years.conf. [root@rhel4 conf]# tail /etc/httpd/conf/httpd.. open a web browser on the web server.) Below is a very simple virtual host definition. [root@RHELv4u3 ~]# cd /etc/httpd/ [root@RHELv4u3 httpd]# ll total 32 lrwxrwxrwx 1 root root 25 Jan 24 drwxr-xr-x 7 root root 4096 Jan 24 drwxr-xr-x 2 root root 4096 Jan 24 lrwxrwxrwx 1 root root 19 Jan 24 lrwxrwxrwx 1 root root 27 Jan 24 lrwxrwxrwx 1 root root 13 Jan 24 [root@RHELv4u3 httpd]# 09:28 08:48 09:29 08:48 08:48 08:48 build -> ..

245:80> ServerName cobbaut.local-error_log CustomLog logs/testsite.local ErrorLog logs/testsite. [root@rhel4 conf]# cat /var/www/html/testsite/index.217.foo. content can be redirected to another website or web server. Redirect permanent /foo http://www. <VirtualHost 83.php </VirtualHost> 49. Apache <VirtualHost testsite.cobbaut. This virtual hosts overrules the default Apache ErrorDocument directive. like this example shows.local:80> ServerAdmin webmaster@testsite.html <html> <head><title>Test Site</title></head> <body> <p>This is the test site. Alias /paul/ "/home/paul/public_html/" Similarly.be ServerAlias www.4. then you can access this humble website.</p> </body> </html> Below is a sample virtual host configuration.local DocumentRoot /var/www/html/testsite/ ServerName testsite.Chapter 49.cobbaut. Aliases and redirects Apache supports aliases for directories.be DocumentRoot /home/paul/public_html ErrorLog /home/paul/logs/error_log CustomLog /home/paul/logs/access_log common ScriptAlias /cgi-bin/ /home/paul/cgi-bin/ <Directory /home/paul/public_html> Options Indexes IncludesNOEXEC FollowSymLinks allow from all </Directory> ErrorDocument 404 http://www.html file in the directory mentioned in the above screenshot.local-access_log common </VirtualHost> [root@rhel4 conf]# Should you put this little index.76.com/bar 269 .be/cobbaut.

# It can be "All". Securing directories with htpasswd and . # AllowOverride controls what directives may be placed in .htpasswd kim New password: Re-type new password: Adding password for user kim [root@rhel4 testsite]# cat . Apache 49.htpasswd pol:x5vZlyw1V6KXE kim:6/RbvugwsgOI6 [root@rhel4 testsite]# You have now defined two users.htpasswd AuthGroupFile /dev/null AuthName "test access title" AuthType Basic <Limit GET POST> require valid-user </Limit> [root@rhel4 kimonly]# Finally.htpasswd pol New password: Re-type new password: Adding password for user pol [root@rhel4 testsite]# cat .htaccess You can secure files and directories in your website with a userid/password. don’t forget to verify that AllowOverride is set to All in the general Apache configuration file. or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride All 270 .htpasswd pol:x5vZlyw1V6KXE [root@rhel4 testsite]# You can add users to this file.htaccess files. enter your website.htpasswd file that contains a userid and an (encrypted) password.htaccess file in that subdirectory.5.Chapter 49. [root@rhel4 kimonly]# pwd /var/www/html/testsite/kimonly [root@rhel4 kimonly]# cat . Next create a subsdirectory that you want to protect with these two accounts. First. and use the htpasswd command to create a . just don’t use the -c switch again. "None". [root@rhel4 testsite]# htpasswd -c . And put the following . [root@rhel4 testsite]# htpasswd .htaccess AuthUserFile /var/www/html/testsite/.

OR] RewriteCond %{HTTP_REFERER} ^http://(www\. 49. Test from another computer that all virtual hosts work. 4. 6.nu. that user will have to provide a userid/password combo that is defined in your .* .be$ cat .)?www. 271 . Create a virtual hosts that listens to port 8247. 3.)?buy-levitra.Chapter 49.)?buy-viagra. where a number of referer spammers are blocked from the website.7. One example si to use .6.[F.nu.htpasswd.*$ [NC.*$ [NC.. Verify that Apache is installed and running.fw.htaccess.htpasswd and . Like in this case. 49. Traffic Apache keeps a log of all visitors.*$ [NC.OR] RewriteCond %{HTTP_REFERER} ^http://(www\.at. Apache From now on. more on .healthinsurancehelp.*$ [NC] RewriteRule .OR] . RewriteCond %{HTTP_REFERER} ^http://(www\.htaccess You can do much more with . 5.)?buy-adipex.ws.htaccess to prevent people from certain domains to access your website. Practice 1.L] paul@lounge:~/cobbaut. Browse to the Apache HTML manual from another computer.*$ [OR] RewriteCond %{HTTP_REFERER} ^http://(www\. 2. Create a virtual hosts that listens on another ip-address.)?buy-tramadol. Protect a subdirectory of a website with .htaccess # Options +FollowSymlinks RewriteEngine On RewriteCond %{HTTP_REFERER} ^http://(www\.htaccess. The webalizer is often used to parse this log into nice html statistics.be$ 49.asso..fw.8. paul@lounge:~/cobbaut. when a user accesses a file in that subdirectory.lookin.net.

It is developed by the Swedish Company MySQL AB (www.6.17-2-686 #1 SMP Wed Sep 13 16:34:10 UTC 2006 i686 GNU/Linux paul@barry:~$ grep mysql /etc/passwd mysql:x:103:105:MySQL Server„. You can create a personal mysql configuration file and put the password inthere. About MySQL MySQL is a database server that understands Structured Query Laguage (SQL). # Linux laika 2.17-2-686 #1 SMP Wed Sep 13 16:34:10 UTC 2006 i686 GNU/Linux paul@barry:~$ mysql -u root -p Enter password: <cut MySQL Welcome Message> mysql> exit Bye paul@barry:~$ mysql -u root -pSecretPass 272 .:/var/lib/mysql:/bin/false root@laika:~# cat /etc/group | grep -i sql mysql:x:115: # Linux barry 2.6.3. the MySQL Welcome message is cut.Chapter 50. so you don’t have to type it every time.com). It is advised to use a different password than the one for your Unix root account. 50.6. MySQL 50.1. In the screenshot below. any user can issue MySQL root commands using the -u root argument on the commandline. After doing this. # Linux barry 2.20-2-generic #3 SMP Sat Dec 16 07:43:26 UTC 2006 x86_64 GNU/Linux root@laika:~# cat /etc/passwd | grep -i sql mysql:x:109:115:MySQL Server„.2. Creating a MySQL root user With the mysqladmin command you can create a root user to administer your MySQL.:/var/lib/mysql:/bin/false paul@barry:~$ grep mysql /etc/group mysql:x:105: 50. MySQL is very popular for websites in combination with PHP and Apache. root@laika:~# mysqladmin -u root password SecretPass You can now use mysql from the commandline by just typing mysql -u root -p and it will ask you for the password (of the mysql root account).mysql. MySQL users and Groups The installation of MySQL creates a user account and a group account.

4. and restore the access of the wikiuser.* to wikiuser@localhost IDENTIFIED BY "wikipass". paul@laika:~$ mysqldump -u root wikidb > wikidb_backup_20070101. On the other machine. Then i ssh to another computer named barry and copy (with scp) the backup to barry.my.Chapter 50. Then i restore the backup of wikidb on barry.cnf paul@barry:~$ echo password=SecretPass >> . recreate the wikidb.sql . Mediawiki backup and restore Mediawiki wikis can use MySQL as a database.. Restore ownership and rights of these files.cnf.my. and restore the copied /var/lib/. use the GRANT command.my.php and /var/lib/mediawiki-1. first take backup of the wikidb. 0 rows affected (0.6.sql 100% 1629KB 542..cnf paul@barry:~$ cat .my. 50. Backup and restore of MySQL database You can take a backup of a database. MySQL <cut MySQL Welcome Message> mysql> exit Bye paul@barry:~$ 50.03 sec) 50. wikidb_backup_20070101. then take backup of /var/lib/mediawiki-1.5.9KB/s 00:03 273 .cnf You can keep some MySQL private configuration in your home directory in the hidden file .7/LocalSettings. In the screenshot below we put the root password in . or move it to another computer using the mysql and mysqldump commands. To copy a wiki to another server. In the screenshot below. files.sql paul@laika:~$ ssh barry paul@barry:~$ scp laika:~/wikidb_backup_20070101.cnf [client] password=SecretPass paul@barry:~$ mysql -u root <cut MySQL Welcome Message> mysql> To give everyone access to a mysql database. mysql> GRANT ALL ON wikidb. Restore the backup of wikidb. ~/.7/upload/*.my. paul@barry:~$ echo "[client]" > .my. Query OK. i take a backup of the wikidb database on the computer named laika.cnf.

274 .. mysql> use wikidb. let’s logon to our MySQL server and execute the commands show databases. mysql> show databases. +------------------+ | Tables_in_wikidb | +------------------+ | archive | | categorylinks | | externallinks | | filearchive | | hitcounter | | image | | imagelinks | . +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | wikidb | +--------------------+ 3 rows in set (0. This gives us a list of all databases on the server. MySQL paul@barry:~$ mysql -u root wikidb < wikidb_backup_20070101. and use wikidb. mysql> show tables. Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed You can see a list of tables in the wikidb with the show tables. command. paul@barry:~$ mysql -u root . The screenshots below show you how. issue the describe $tablename command as shown below. 31 rows in set (0.sql paul@barry:~$ 50.Chapter 50.01 sec) This makes the wikidb database the current db in use..7. First... Looking at databases and tables You can use the mysql command to take a look at the databases. and to execute SQL queries on them.00 sec) To see a description of the structure of a table..

1. Your MySQL connection id is 2 to server version: 4.xkcd. MySQL mysql> describe externallinks. Commands end with .xkcd. +----------+ | Database | +----------+ | mysql | | test | 275 . mysql> show databases.www. or \g.html | http://com.’ or ’\h’ for help.Chapter 50. There are only two databases defined. +---------+--------------------------------------------+--------------------------------| el_from | el_to | el_index +---------+--------------------------------------------+--------------------------------| 1405 | http://www./wiki/H | 1 | http://www./c149.00 sec) Type exit.com/c196.org/wiki/Help:FAQ | http://org.html | 1 | http://www. Creating a table Let us walk through the creation of a simple table.xkcd.www. mysql> exit Bye paul@barry:~$ 50.html | 1 | http://www.xkcd.com/c178. On Red Hat.com/c149. to get back to your Linux command prompt.00 sec) And finally an example of a simple select query to look at the contents of a table./c196.html +---------+--------------------------------------------+--------------------------------7 rows in set (0.www.12 Type ’help. root has default access to mysql.html | http://com.www./c178. mysql> select * from externallinks.xkcd. +----------+-----------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-----------------+------+-----+---------+-------+ | el_from | int(8) unsigned | NO | MUL | 0 | | | el_to | blob | NO | MUL | | | | el_index | blob | NO | MUL | | | +----------+-----------------+------+-----+---------+-------+ 3 rows in set (0.mediawiki.html | http://com.mediawiki. [root@RHELv4u3 ~]# mysql Welcome to the MySQL monitor. Type ’\c’ to clear the buffer. let us use the test database.8.xkcd. First enter the mysql prompt.

MySQL +----------+ 2 rows in set (0. -> ras varchar(20) default NULL. 0 rows affected (0. -> naam varchar(12) default NULL.’kattin’) | YES | | NULL | | | naam | varchar(12) | YES | | NULL | | | ras | varchar(20) | YES | | NULL | | +-------+-------------------------------------+------+-----+---------+-------+ 4 rows in set (0. the first one being the primary key. mysql> create table dieren ( -> id varchar(4) NOT NULL default ”.’kattin’) default NULL. Empty set (0. +----------------+ | Tables_in_test | +----------------+ | dieren | +----------------+ 1 row in set (0. -> PRIMARY KEY (id) -> ).’kater’.00 sec) So we create a table with four records.’kater’.00 sec) mysql> describe dieren.01 sec) mysql> use test Database changed There are no tables yet in the test database.’teef’.’teef’. mysql> show tables. -> soort enum(’reu’.00 sec) mysql> 276 . +-------+-------------------------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------------------------------+------+-----+---------+-------+ | id | varchar(4) | | PRI | | | | soort | enum(’reu’.Chapter 50.01 sec) Verify the creation of the table mysql> show tables. Query OK.

you can script mysql commands in bash. mysql> INSERT INTO dieren VALUES (’h17’.’Rottweiler x Pitbull’). mysql> select * from dieren. Populating a table Use INSERT to enter data into the table. +-------+----------------------+ | soort | ras | +-------+----------------------+ | reu | Rottweiler x Pitbull | +-------+----------------------+ 1 row in set (0. paul@laika:~$ mysql -uwikiuser -pwikipass -e"show databases" +--------------------+ | Database | +--------------------+ | information_schema | | wikidb | +--------------------+ paul@laika:~$ [root@RHELv4u3 ~]# mysql -e"use test.ras from dieren where id=’h17’.Chapter 50.9. +-----+-------+-------+----------------------+ | id | soort | naam | ras | +-----+-------+-------+----------------------+ | h17 | reu | Pasha | Rottweiler x Pitbull | +-----+-------+-------+----------------------+ 1 row in set (0.ras from dieren where id=’h17’.’reu’." +-------+----------------------+ | soort | ras | +-------+----------------------+ | reu | Rottweiler x Pitbull | +-------+----------------------+ [root@RHELv4u3 ~]# 277 .01 sec) And use SELECT to query the table. MySQL 50.01 sec) mysql> 50.10.’Pasha’. 1 row affected (0. Scripting mysql in bash Using the -e option of the mysql command. Query OK.select soort.00 sec) mysql> select soort.

1. Shell shoveling wth netcat Netcat can be used for a lot of things.bat batchfile that accomnplishes this automatic restart.1. Start on the Microsoft Windows XP computer by downloading netcat for windows NT from www.1.exe shell will end the connection.48 500 Microsoft Windows XP [Version 5.exe file to your XP home directory.440 PM <DIR> 61. Volume Serial Number is A402-2699 Directory of C:\Documents and Settings\paul 06/19/2007 06/19/2007 06/19/2007 06/19/2007 06/19/2007 12/29/2004 10/10/2005 1 File(s) 6 Dir(s) 04:48 04:48 04:46 03:20 04:46 01:07 05:45 PM <DIR> PM <DIR> PM <DIR> PM <DIR> PM <DIR> PM 61.vulnwatch. C:\Documents and Settings\paul>nc -l -p 500 -e cmd. paul@laika:~$ nc 192.exe The next screenshot shows the automatic restart of nc on the target machine.. C:\Documents and Settings\paul>exit paul@laika:~$ It can be useful to change lowercase l to uppercase L.1. Replace 192. Desktop Favorites My Documents nc.exe Start Menu C:\Documents and Settings\paul> Typing exit at the cmd.exe prompt.48 500 278 . nc -L -p 500 -e cmd.168. Then execute the following command to start listening for a netcat client. C:\Documents and Settings\paul>dir dir Volume in drive C has no label. This appendix explains how netcat can deliver a Microsoft Windows XP command prompt in bash.exe Now issue the following command on your linux computer to shovel a cmd. and the contents of the shovel. .071. which will restart the netcat listening when the connection is broken.2600] (C) Copyright 1985-2001 Microsoft Corp.48 with the ip-address of the target machine.936 bytes free . paul@laika:~$ nc 192.168.440 bytes 764.Appendix A. Hackers call this technique shell shoveling.org/netcat/ and extract only the nc.168.

1. C:\Documents and Settings\paul>exit paul@laika:~$ nc 192. Shell shoveling wth netcat Microsoft Windows XP [Version 5.48 500 Microsoft Windows XP [Version 5.Appendix A. C:\Documents and Settings\paul>type shovel.bat nc -L -p 500 -e cmd.2600] (C) Copyright 1985-2001 Microsoft Corp.168.1.bat type shovel.2600] (C) Copyright 1985-2001 Microsoft Corp.1.exe C:\Documents and Settings\paul>exit paul@laika:~$ 279 .

C:\> 280 . C:\>md c:\share1 C:\>dir Volume in drive C has no label. Volume Serial Number is F85C-CC93 Directory of C:\ 03/07/2007 09:27p <DIR> 06/19/2007 05:23p <DIR> 06/19/2007 05:37p <DIR> 06/19/2007 03:05p <DIR> 0 File(s) 0 bytes 4 Dir(s) 4.448 bytes free C:\>net share firstshare=c:\share1 firstshare was shared successfully. Documents and Settings Program Files share1 WINNT C:\>net view W2000 Shared resources at W2000 Share name Type Used as Comment ------------------------------------------------------------------------------firstshare Disk The command completed successfully.577. The net share command How to create a shared folder in Windows.640.Appendix B.

config w98]# echo password="" >> . [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b [root@RHEL4b server=w98 service=hp password= [root@RHEL4b samba]# cd /var/spool/lpd/ lpd]# mkdir w98 lpd]# chown lp:lp w98/ lpd]# chmod 700 w98 lpd]# cd w98/ w98]# chown lp:lp .55 w98 >> /etc/hosts 281 .config w98]# echo server=w98 > . Read the manpage of printcap for more information. Serving a BSD-style printer First we set up a BSD-style printer.Appendix C. The we create a .1. The printer is shared on a Windows 98 computer named w98 as \\w98\hp.168.config w98]# chmod 600 .config w98]# echo 192.config file for smbprint in the spool directory for this printer (and set the correct owner and permissions for this directory).config w98]# cat .config w98]# echo service=hp >> .