Home

Linux course modules pdf

image

Contents

1. ee ee 87 19 2 The Filesystem Hierarchy Standard 2 0 02 ee ee 87 19 3 Shareable and Non Shareable Data 0 0 00 a 88 19 4 Static and Dynamic Data or e ee wea Yee a a a A RARA ae EGA 88 195 Overview of the FHS 0 0002 ee a 88 19 6 FHS Installed Software ee a a eL a R a G a a E a 89 19 7 FHS Other Directories Under usr 2 2 89 19 8 FHS Directories Under War 2 ee 89 19 9 FHS Other Directories 202 0002 cee es 90 19 10 FHS Other Directories 2 202 020 0b es 90 19 11 Finding Programs with which 2e sa sa mes bacia ak de pa ee 90 19 12 The type Built in Command e a a a a A a D AA aD A aa 90 19 13 Checking for Shell Builtins with type a aooaa a ee 91 19 14 Updating the locate Database a 91 19D 7Updatedb COMI a is hoy EA AA E ee sg SE EEN Aa ie 91 ASA Gwe Cass a ae aes RA ae isle he ian teens he ee eee dad Gee tots ee aed aes 92 19 17 Finding Manpages with apropos 1 a a a a 92 19 18 Web Resources 0 000 0 ie a i a a E Ga e a i a a ea OE Ea ao a a 92 TOLTO EXCICISES a a ie wa a a pena scaly AEI A e ca aE ae bat cyte e anar A bat Gh ote va aia gy diane a 92 20 Set and View Disk Quotas 93 2021 Whattare Quotas rides is dd vais MR Se ek YI hee EEE SO ice Le 93 20 2 Hard and Soft LimitS 200000 ee 93 20 3 Per User and Per Group Quotas 00000 eee ee 94 20 4 Block and inode Lim
2. 0 2 0 0 002 o 63 13 3 Hardik Sve Sasso ee Gok SANA yg ats 3 DAS Hee te he ay ol ee Ay 64 13 4 Symlinks and Hard Links Illustrated 2 2 2 o o 64 13 5 Comparing Symlinks and Hard Links 2 e o eo 64 13 6 Examining and Creating Hard Links o e e 65 13 0 gt Preserving Links sg 0 a ria dose decd bee a ic ae os Seren A i et A 65 13 8 Finding Symbolic Links toa File o oo e 65 13 9 Finding Hard Links toa File 0 o o eo 66 13 101 EXCICISCS lt ai a rad a ee GE Bie A dee ES Ad A AA A A Dede Ghd 66 14 Manage File Ownership 67 14 1 Users and Groups s a ee ii e a a oe Ea e 67 14 2 The Superuser ROOL os proto a deh a a da o a AS 67 14 3 Changing File Ownership with chown o e o 68 Copyright 2004 GBdirect Ltd http training gbdirect co uk vi Linux System Administration Contents 14 4 Changing File Group Ownership with chgrp _ o o 145 Changing the Ownership of a Directory and lts Contents 14 6 Changing Ownership and Group Ownership Simultaneously TALA VNEXEICISCS rr amp Geter a Se eee ice ton BAe a he a acd A 15 Use File Permissions to Control Access to Files 15 1 Basic Concepts Permissions on Files 15 2 Basic Concepts Permissions on Directories 15 3 Basic Concepts Permissions for Different Groups of People 15 4
3. Copyright 2004 GBdirect Ltd http training gbdirect co uk 130 Module 28 Maintain an Effective Data Backup Strategy 28 1 Reasons for Backup E Disks fail E Bugs in software can cause corruption E Configuration mistakes by administrator E Accidental deletion or overwriting e g with rm mv or cp Ml Malicious deletion or virus attack E Theft of machines with hard drives in E Fire or other disasters which can destroy hardware 28 2 Backup Media E Traditionally backups have been made onto tapes Can store lots of data on reasonably cheap tapes E Copying to a different hard disk O There is a risk of losing the backup along with the original O Better if on a remote computer E CD writers can be used to store backups on CDs O Convenient for long term storage O Handy to remove to remote locations 131 Linux System Administration Module 28 Maintain an Effective Data Backup Strategy 28 3 Types of Backup E Full backup includes everything of importance O Might not include system files which are from the install CD Can include a lot of files many of which hardly ever change E Differential backup only includes changes since last full backup O Nightly backup only needs to include files changed since the last full backup O Recovery requires the full backup on which it was based E Incremental backup only includes changes since last backup O Nightly backup only includes files changed in the last 24 hours
4. check with 1s c Change the owner of the file to be users d Change the group owner to be any non root user e Change both of the owners back to being root with a single command Copyright 2004 GBdirect Ltd http training gbdirect co uk 69 Module 15 Use File Permissions to Control Access to Files 15 1 Basic Concepts Permissions on Files E Three types of permissions on files each denoted by a letter E A permission represents an action that can be done on the file Permission Letter Description Read y Permission to read the data stored in the file Write w Permission to write new data to the file to truncate the file or to overwrite existing data Execute x Permission to attempt to execute the contents of the file as a program E Occasionally referred to as permission bits E Note that for scripts you need both execute permission and read permission O The script interpreter which runs with your permissions needs to be able to read the script from the file 15 2 Basic Concepts Permissions on Directories E The r w x permissions also have a meaning for directories E The meanings for directories are slightly different Permission Letter Description Read E Permission to get a listing of the directory Write w Permission to create delete or rename files or subdirectories within the directory Execute x Permission to change to the directory or to use the directory as an inter
5. nice n 15 important command amp 55 Linux System Administration Module 10 Modify Process Execution Priorities 10 3 renice E renice changes the niceness of existing processes E Non root users are only permitted to increase a process s niceness E To set the process with pid 2984 to the maximum niceness lower priority renice 20 2984 O The niceness is just a number no extra sign E To set the process with pid 3598 to a lower niceness higher priority renice 15 3598 E You can also change the niceness of all a user s processes renice 15 u mikeb 10 4 Exercises 1 a Create the following shell script called forever in your home directory bin sh while 1 do echo hello gt dev null done Make it executable and run it in the background as follows chmod atrx forever forever b Use ps 1 to check the script s nice level c Run the script with nice and give it a niceness of 15 Try running it alongside a less nice version and see what the difference is in top d Try using nice or renice to make a process niceness less than 0 Copyright 2004 GBdirect Ltd http training gbdirect co uk 56 Module 11 Advanced Shell Usage 11 1 More About Quoting E The shell actually has three different quoting mechanisms O Single quotes O Backslashes O Double quotes 11 2 Quoting Single Quotes E Putting single quotes round something protects it from special interpre
6. O Recovery requires the last full backup and a complete sequence of incremental backups after that 28 4 Backup Strategy E The backup schedule should be regular and well known by those who rely on it O it must be decided what to backup and what can be left out E Typically a full backup is done once a week or once a month O Daily changes are recorded in a differential or incremental backup each night E Large sites might have more than these two levels to their strategy E Monthly tapes might be kept for a long time in case a really old file becomes important 28 5 Archiving Files with tar E tar can package up files for distribution or backup O Originally for tape archive manipulation O Files can be stored anywhere E Encapsulates many files in a single file Known as a tar archive or a tarball E Has unusual command line option syntax Common options are given as single letters No hyphen is needed E tar must be given exactly one action option O Indicates which operation to perform O Must be the first option Copyright 2004 GBdirect Ltd http training gbdirect co uk 132 Linux System Administration Module 28 Maintain an Effective Data Backup Strategy 28 6 Creating Archives with tar E Use the c option to create an archive E For example to create an archive called docs tar gz containing everything in the documents directory tar czf docs tar gz documents O f specifies the archive s filename m Must
7. 79 Linux System Administration Module 17 Control Filesystem Mounting and Unmounting 17 3 Mounting Other Filesystems E mount dev sdb3 mnt extra mounts the filesystem stored in the dev sdb3 device on the mount point mnt extra E You may occasionally need to specify the filesystem type explicitly mount t vfat dev hddl mnt windows O Allowable filesystem types are listed in the mount 8 manpage E To see a list of the filesystems currently mounted run mount without any options 17 4 Unmounting a Filesystem umount E A filesystem can be unmounted with umount O Note the spelling E umount mnt extra unmounts whatever is on the mnt extra mount point E umount dev sdb3 unmounts the filesystem in the dev sdb3 device wherever it is mounted E You normally need to have root permission to unmount a filesystem E It s also impossible to unmount a busy filesystem A filesystem is busy if a process has a file on it open O Or if a process has a directory within it as its current directory 17 5 Configuring mount etc fstab E The etc fstab file contains information about filesystems that are known to the system administrator O Specifying a filesystem in etc fstab makes it possible to use its mount point as the only argument to mount E etc fstab also configures which filesystems should be mounted at boot up E Each line in etc fstab describes one filesystem E Six columns on each line 17 6 Sample etc fstab E A sampl
8. Some commands require them O Parameters are also known as arguments For example echo simply displays its arguments echo echo Hello there Hello there E Commands are case sensitive O Usually lower case echo whisper whisper ECHO SHOUT bash ECHO command not found Copyright 2004 GBdirect Ltd http training gbdirect co uk 3 Linux System Administration Module 1 Introduction 1 9 Files E Data can be stored in a file E Each file has a filename A label referring to a particular file O Permitted characters include letters digits hyphens underscores _ and dots O Case sensitive NewsCrew mov is a different file from NewScrew mov Mi The ls command lists the names of files 1 10 Creating Files with cat E There are many ways of creating a file E One of the simplest is with the cat command cat gt shopping_list cucumber bread yoghurts fish fingers E Note the greater than sign gt this is necessary to create the file The text typed is written to a file with the specified name E Press Ctrl D after a line break to denote the end of the file O The next shell prompt is displayed E 1s demonstrates the existence of the new file 1 11 Displaying Files Contents with cat E There are many ways of viewing the contents of a file E One of the simplest is with the cat command cat shopping _list cucumber bread yoghurts fish fingers E Note that no greater than s
9. e 4 17 2 Mounting a Filesystem mount e eee 17 3 Mounting Other FilesysteMS 0 e 17 4 Unmounting a Filesystem umount 0 e e 17 5 Configuring mount etc fstab o o o e e 17 0 Sample otC IStab toca A AA A a a dea 17 7 Filesystem Types La o A A A IAES q Mount Options 2 6 04 ne ee papa a a bd 17 9 Other Columns in etc fstab 2 0 o eo e 17 10 MountingaFile s lt a se reser tiya 2 00022 o 17 11 Exercises 2 2 5 442 ee rare ve A eee ee ee we G 18 Maintain the Integrity of Filesystems 18 1 Filesystem Concepts eee ee ee 18 2 Potential ProbleMS e eee 18 3 Monitoring Space d me 18 4 Monitoring Inodes df 0 o o o 18 5 Monitoring Disk Usage du 0 e Copyright 2004 GBdirect Ltd http training gbdirect co uk vii Linux System Administration Contents 18 07 AMOPIOAS Td OE O ie ai A aber cds Apa ete eat Oe a A aaa dead Ge ee 85 18 7 Finding and Repairing Filesystem Corruption fsck 2 o o ee ee ee 85 188 RNI I SCK ea arpa wt a ere ee Bee ae a gee at Aria ta 86 18 99 WEXCICISCS re rt a ep See oop aE RAGE Bee as a ded Si Seen AS Aa a 86 19 Find System Files and Place Files in the Correct Location 87 19 1 Unix Filesystem Layout
10. 0 A transitional run level used to tell the system to shut itself down safely Once the system has shut down it needs a manual reboot to reactivate 1 Single user mode used for maintenance Users may not log in and many services usually including all networking facilities are disabled There is only one terminal active on which root is automatically logged in 2 5 Multi user modes Some systems make all of these identical Others disable networking or NFS file sharing in runlevel 2 and or enable a graphical login in runlevel 5 but not in other runlevels 6 A transitional run level used to tell the system to reboot 101 Linux System Administration Module 22 Change Runlevels and Shutdown or Reboot System 22 3 Single User Mode and sulogin Ml Many Linux distributions use a program called sulogin to restrict access to single user mode E sulogin is run when the system enters single user mode E It requires the root password to be typed on the console before switching to single user mode O If the password is not typed sulogin returns the system to the normal runlevel E Why is sulogin needed O Untrusted users may have access to the system s keyboard during bootup O In many configurations this would enable them to boot the system up in single user mode 22 4 Shutting Down and Restarting the System E To safely shut down the system run the halt command as root O This is a safe shutdown it stops all services
11. 10 1 Concepts si a ee he Pega ede ee Gee el whe doe ee eee we 55 102Z NEE a he an a Bld A Gh oe eae a A a a 55 10 3 LEIA eh aema ice ee a e Re ee i ee te A Re RY ee dw ee ee 56 10 4 Exercises S a a csc Ree eh ea ee Ree we O A e a e a 56 11 Advanced Shell Usage 57 TET More About Quoting 2a ee a eg de RE eae hea de don Re Wale 6 aa 57 11 2 Quoting Single Quotes 2 000200 a a a A a aL a a Da aE 57 11 3 Quoting Backslashes o oo a 57 11 4 Quoting Double Quotes a 58 11 5 Quoting Combining Quoting Mechanisms aoao a 58 11 6 Recap Specifying Files with Wildcards oaoa a a ee 58 11 7 Globbing Files Within Directories oaaao aa a a 59 11 8 Globbing to Match a Single Character a 59 11 9 Globbing to Match Certain Characters oaoa a a ee 59 11 10 Generating Filenames aoao 0 0200 2 eee 60 TFL Shel Progamm sarete s A AA ee EP da Ee 60 1 12 Exercises nk nora m a Be ee Be Pe ee ee a ee OR ee Re 60 12 Filesystem Concepts 61 12 1 FIIGSYStEMS iia ie Bed Pe BR Ae ee EA Se A ae ee 61 12 2 The Unified Filesystem 2064 2 aiy tute He aye a Oe ee ee a a ey Ee 61 1239 WEG TYPOS croa seat a Bo deg cae ie ane Re aa aed et gee a ty dp on at 62 12 4 Inodesiand Directories xi Gute A ee Re ee EE a ey a E 62 13 Create and Change Hard and Symbolic Links 63 13 1 SYymbolic LinkS aaa is a A eed ete de eth ea gn Bee a RE a A 63 13 2 Examining and Creating Symbolic Links
12. Use grep to find information about the HTTP protocol in the file etc services b Usually this file contains some comments starting with the symbol Use grep with the v option to ignore lines starting with and look at the rest of the file in less c Add another use of grep v to your pipeline to remove blank lines which match the pattern d Use sed also in the same pipeline to remove the information after the symbol on each line leaving just the names of the protocols and their port numbers Copyright 2004 GBdirect Ltd http training gbdirect co uk 46 Module 8 Job Control 8 1 Job Control Most shells offer job control O The ability to stop restart and background a running process The shell lets you put amp on the end of a command line to start it in the background Or you can hit Ctr1 Z to suspend a running foreground job Suspended and backgrounded jobs are given numbers by the shell These numbers can be given to shell job control built in commands Job control commands include jobs fg and bg jobs The jobs builtin prints a listing of active jobs and their job numbers jobs 1 Stopped vim index html 2 Running netscape amp 3 Stopped man ls Job numbers are given in square brackets But when you use them with other job control builtins you need to write them with percent signs for example 1 The jobs marked and may be accessed as or as well as by numbe
13. alice notes txt E The following are all the same for user fred ed ad cd home fred 2 10 Looking for Files in the System E The command locate lists files which contain the text you give E For example to find files whose name contains the word mkdir locate mkdir usr man manl mkdir 1 gz usr man man2 mkdir 2 gz bin mkdir E locate is useful for finding files when you don t know exactly what they will be called or where they are stored E For many users graphical tools make it easier to navigate the filesystem O Also make file management simpler 2 11 Running Programs E Programs under Linux are files stored in directories like bin and usr bin O Run them from the shell simply by typing their name E Many programs take options which are added after their name and prefixed with E For example the 1 option to 1s gives more information including the size of files and the date they were last modified ls 1 drwxrwxr X 2 fred users 4096 Jan 21 10 57 Accounts rw rw r 1 fred users 345 Jan 21 10 57 notes txt Yw r r 1 fred users 3255 Jan 21 10 57 report txt E Many programs accept filenames after the options O Specify multiple files by separating them with spaces Copyright 2004 GBdirect Ltd http training gbdirect co uk 11 Linux System Administration Module 2 Getting Started 2 12 Specifying Multiple Files E Most programs can be given a list of files O For example t
14. to connect the output of echo to the input of wc echo count these words boy wc Displaying Files with less If a file is too long to fit in the terminal display it with less less README less also makes it easy to clear the terminal of other things so is useful even for small files Often used on the end of a pipe line especially when it is not known how long the output will be Swe txt less Doesn t choke on strange characters so it won t mess up your terminal unlike cat Counting Words and Lines with wc wc counts characters words and lines in a file If used with multiple files outputs counts for each file and a combined total Options O c output character count O 1 output line count O w output word count O Default is clw Examples display word count for essay txt S we w essay txt Display the total number of lines in several text files Swe l txt Copyright 2004 GBdirect Ltd http training gbdirect co uk 25 Linux System Administration Module 4 Process Text Streams Using Text Processing Filters 4 6 4 8 Sorting Lines of Text with sort The sort filter reads lines of text and prints them sorted into order For example to sort a list of words into dictionary order sort words gt sorted words The f option makes the sorting case insensitive The n option sorts numerically rather than lexicographically Removing Duplicate Lines with uni q Use uniq to find unique lines
15. 12 More Complex Crontab Dates 8 Times 21413 YO C CrON AD rte sie rad aS Boe he veg kh EA a Ss 21 14 User CrontabDS es 22 ota ra ee ON ae GO e 27 15 Cron JOD OUUU a se tra a a aa do 27 16 At Command and Cron Job Permissions 20 17 EX6IGISOS fa gain ef ete pee Sina A wee ne el ww 4 28 Maintain an Effective Data Backup Strategy 28 1 Reasons forBackup 0 00002 eee eee eee 28 2 Backup Media i s vto gu bg ae ee Gee a 28 3 TypesofBackup 02 0 00052 bees 28 4 Backup Strategy ion Pe ee ee ae 28 5 Archiving Files With tar 0 0 0 0 0020 eee 28 6 Creating Archives with tar o e e 28 7 Listing the Files in tar Archives o 28 8 Extracting Files from tar Archives 0 28 9 Device Files for Accessing Tapes o 28 10 Using tar for Backups 0 e 2 e 28 11 Controlling Tape Drives With mt o 0008 28 12 Deciding What to Backup o 28 13 What Notto Backup 0 o e e eo 28 14 Scripting Backup iones a ee Ee Ae he SE eS 28 15 Other Backup Software 200220 0000 28 16 Exercises a sa eb eee o ee ee ee Copyright 2004 GBdirect Ltd http training gbdirect co uk Module 1 Introduction 1 1 Unix and Linux E Linux is based on Unix O Unix philosoph
16. 6 Special Dot Directories aooaa aa a a a 10 2 7 Using Dot Directories in Paths aoao aa a a 10 2 8 Hidden Files cette hatte ai a he aE dl ote teed a chats te lt oh a te th Ne E ed 10 2 9 Paths to Home Directorios n su e an a a aE E aE ee 11 2 10 Looking for Files in the System aao a 11 2 11 RUNNING PrograMsS esoo Re egy ee Bay a eB AE Rae Gwe a 11 2 12 Specifying Multiple Files 2 2 2 0 0 002022 a e a E ee 12 2 13 Finding Documentation for Programs 2 e o 12 2 14 Specifying Files with Wildcards 2 2 ee 13 2 15 Chaining Programs Together 2 e 13 2 16 Graphical and Text Interfaces 2 2 ee 13 221 7 EXN EUROS e204 sce Ue ee ee ab tA Ae oe e ete a ea SRA a o ghee a 14 2 18 EXCICISCS gt irradia ely part BAA E a ahah ek ete de gee add 14 Work Effectively on the Unix Command Line 16 3 1 Sul sect ii di a ti A ee A va 16 3 2 The Bash Sh ll trata a A Aa a a ete 16 Linux System Administration Contents 3 3 shell Commands lt a ia Soe ard a Halas E a Pee A ae ek a 17 3 4 Command Line Arguments ea aia E E Aa E eaS a EO A aTa e SD 17 3 5 Syntax of Command Line Options 2 ao eop e e 17 3 6 Examples of Command Line Options aoa aoao a a a a a 18 3 7 Setting Shell Variables 2 Oua a RO aa pi e ga 18 3 8 Environment Yarnables eius ee eg a Ra ER ee ee ede 18 3 9 Where Programs are Found 2 a 19 3 10 Bash Configuration Variables 0 000
17. A process lives as it executes with a lifetime that may be short or long E A process is said to die when it terminates E The kernel identifies each process by a number known as a process id or pid E The kernel keeps track of various properties of each process 9 2 Process Properties E A process has a user id uid and a group id gid which together specify what permissions it has E A process has a parent process id ppid the pid of the process which created it O The kernel starts an init process with pid 1 at boot up Every other process is a descendant of pid 1 E Each process has its own working directory initially inherited from its parent process E There is an environment for each process a collection of named environment variables and their associated values O A process s environment is normally inherited from its parent process 49 Linux System Administration Module 9 Create Monitor and Kill Processes 9 3 Parent and Child Processes E The init process is the ancestor of all other processes init m bash m bash M vi apache m apache m apache apache E Apache starts many child processes so that they can serve HTTP requests at the same time 9 4 Process Monitoring ps E The ps command gives a snapshot of the processes running on a system at a given moment in time E Very flexible in wh
18. Actually has two main parts O A driver program fsck which handles any filesystem type One backend program for each specific filesystem type E The backend program for ext2 is e2fsck but it is always invoked through fsck Copyright 2004 GBdirect Ltd http training gbdirect co uk 85 Linux System Administration Module 18 Maintain the Integrity of Filesystems 18 8 Running fsck E fsck is normally run at system startup O So it gets run automatically if the system was shut down uncleanly E It can also be run manually fsck dev sdb3 O Interactively asks whether to fix problems as they are found E Use f to force checking the filesystem even if fsck thinks it was cleanly umounted E Use y to automatically answer yes to any question E Usually a bad idea to run fsck on a mounted filesystem 18 9 Exercises 1 a Check the free disk space on the computer b Display just the usage information for the partition that contains usr Display this in human readable units c Look at the free space and inodes of the partition of var tmp first Then run these commands mkdir var tmp foo seq f var tmp foo bar 04 f 0 2000 xargs touch What has happened Look at the free space and inodes again Remove the files when you have finished 2 Go into the var directory Run each of the following commands as root and explain the difference in their output a du b du h Cc
19. Boot Messages E When the kernel starts up it prints a flurry of information E This can often be useful in finding problems E A log of this information is kept in var log dmesg E The dmesg command can print the most recent messages O This can show problems which have occurred since boot E After boot most log messages are handled by syslog Copyright 2004 GBdirect Ltd http training gbdirect co uk 99 Linux System Administration Module 21 Boot the System 21 10 Kernel Modules E Many features of the Linux kernel can be built as modules O Can be loaded when needed and unloaded later O Compiled modules are stored under lib modules Mi These commands manage modules O 1smod lists currently loaded modules O xmmod removes an unused module O insmod loads a single module O modprobe loads a module and any other modules it needs E The file etc modules conf configures these commands O etc conf modules on some systems O Has a manpage modules conf 5 21 11 Exercises Look at the compiled modules available on the system o p List the currently loaded modules o Load the parport module and check that it s worked o Unload the parport module and check again e Try unloading a module currently in use What happens 2 a Reboot the computer You can do this safely by quitting all programs logging out then pressing Ctrl Alt Del When the LILO prompt appears list the available optio
20. Debian SUSE Mandrake 1 5 Using a Linux System E Login prompt displayed O When Linux first loads after booting the computer O After another user has logged out E Need to enter a username and password E The login prompt may be graphical or simple text E If text logging in will present a shell E If graphical logging in will present a desktop Some combination of mousing and keystrokes will make a terminal window appear O A shell runs in the terminal window Copyright 2004 GBdirect Ltd http training gbdirect co uk Linux System Administration Module 1 Introduction 1 6 Linux Command Line E The shell is where commands are invoked E A command is typed at a shell prompt O Prompt usually ends in a dollar sign E After typing a command press Enter to invoke it O The shell will try to obey the command O Another prompt will appear E Example date Thu Jun 14 12 28 05 BST 2001 O The dollar represents the prompt in this course do not type it 1 7 Logging Out E To exit from the shell use the exit command E Pressing Ctrl D at the shell prompt will also quit the shell E Quitting all programs should log you out O If in a text only single shell environment exiting the shell should be sufficient O In a window environment the window manager should have a log out command for this purpose E After logging out a new login prompt should be displayed 1 8 Command Syntax E Most commands take parameters
21. Displays hostname 8 23 10 Searching the Content of All Manpages with man K E itis possible to search through the textual content of the entire manual Mi man K note upper case does this man K printer O Filename of each matching page is displayed in turn O Prompt for choosing whether to display it E Not particularly useful O Many false matches obscuring the data you want O Slow to search so much text O Tedious to respond to each prompt Copyright 2004 GBdirect Ltd http training gbdirect co uk 109 Linux System Administration Module 23 Use and Manage Local System Documentation 23 11 Finding the Right Manual Page E Sometimes commands documentation are not quite where expected E Related commands can be grouped together on one page These commands all display the same page man gzip man gunzip man zcat O Can be misleading if you look up one command and start reading the description of another 23 12 Help on Shell Builtins E Shell built in commands are documented in shells manpages O cd 1 refers the reader to bash 1 O echo 1 relates to bin echo but in most shells echo is a separate built in command E The bash 1 manual page has details but is too big O See the section SHELL BUILTIN COMMANDS E For brief explanations of builtin functions use help help help help help s pattern Display helpful information about builtin commands If PATTERN is E Run help witho
22. Don t go E Rarely needed the last example is probably better written as echo She said Don t go 11 6 Recap Specifying Files with Wildcards E in a glob pattern can stand for any sequence of characters ls 1 txt rw rw r 1 fred users 108 Nov 16 13 06 report txt rw rw r 1 fred users 345 Jan 18 08 56 notes txt E on its own expands to all files in the current directory E Glob expansion is done by the shell O So a program can t tell when the user ran it with a glob as an argument Copyright 2004 GBdirect Ltd http training gbdirect co uk 58 Linux System Administration Module 11 Advanced Shell Usage 11 7 Globbing Files Within Directories E You can use globs to get filenames within directories ls Accounts 199 txt Accounts 1997 txt Accounts 1998 txt Accounts 1999 txt ls images gif images logo gif images emblem gif E You can also use globs to expand names of intervening directories cd usr man amp amp ls man lp man1 lpq 1 gz manl lprm 1l gz man4 lp 4 gz man8 lpd 8 gz manl lpr 1 gz man1 lptest l gz man8 lpc 8 gz 11 8 Globbing to Match a Single Character Mi matches any sequence of characters E To match any single character use ls ouse txt Matches mouse txt and house txt but not grouse txt E Can be useful for making sure that you only match files of at least a certain length S rm 2 2 txt Matches any file ending in txt that has at least th
23. E whoami E hostname E uname Copyright 2004 GBdirect Ltd http training gbdirect co uk 6 Linux System Administration Module 1 Introduction E uptime 2 a Use the 1s command to see if you have any files b Create a new file using the cat command as follows cat gt hello txt Hello world This is a text file Press Enter at the end of the last line then Ctr1 D to denote the end of the file c Use 1s again to verify that the new file exists d Display the contents of the file e Display the file again but use the cursor keys to execute the same command again without having to retype it 3 a Create a second file Call it secret of the universe and put in whatever content you deem appropriate b Check its creation with 1s c Display the contents of this file Minimise the typing needed to do this E Scroll back through the command history to the command you used to create the file E Change that command to display secret of the universe instead of creating it 4 After each of the following steps use 1s and cat to verify what has happened a Copy secret of the universe to a new file called answer txt Use Tab to avoid typing the existing file s name in full o Now copy hello txt to answer txt What s happened now Delete the original file hello txt a 0 Rename answer txt to message e Try asking rm to delete a file called missing What happens f Try copying secret of the univer
24. Examining Permissions ls l 0 e 15 5 Preserving Permissions When Copying Files 15 6 How Permissions are Applied 0 e e eee 15 7 Changing File and Directory Permissions chmod 15 8 Specifying Permissions for chmod 15 9 Changing the Permissions of a Directory and Its Contents 15 10 Special Directory Permissions Sticky 0 15 11 Special Directory Permissions Setgid 15 12 Special File Permissions Setgid 0 15 13 Special File Permissions Setuid 0 15 14 Displaying Unusual Permissions 15 15 Permissions as Numbers e 15 16 Default Permissions umask a 2 2002000005 19 17 EXErCISesS oem as al EE a o e ee ee ee 16 Create Partitions and Filesystems 16 1 Concepts Disks and Partitions 0 16 2 DISK Naming anios pd a yada a A ey od 10 39 USING Edita E A A este AA a 16 4 Making New Partitions o o e o 16 5 Changing Partition Types 0 e o o 02 2G 16 6 Making Filesystems with mkfs 16 7 Useful Websites mm 17 Control Filesystem Mounting and Unmounting 17 1 Mounting Filesystems
25. Examples o EP eco wb ae pa eee le beg ae ae A E TE 5 9 Moving Files with mv aoaaa a a a 5 10 Deleting Files with rm aaao a 5 11 Deleting Files with Peculiar Names 5 12 Making Directories with mkdir aaoo a 5 13 Removing Directories with rmdir aoao a 5 14 Identifying Types of Files aoaaa a 5 15 Changing Timestamps with touch aooaa e a a 5 16 EX rciSeS i anui A eed a A ee Be Be 6 Use Unix Streams Pipes and Redirects 6 1 Standard Files ico a ge had e Bee ale S adala ia Ao ae 6 2 Standard Input a aoa a ee 6 3 Standard Output a aoa a a 20220005 6 4 Standard Error aoaaa 2 ee es 6 5 Poson y dicots Bete e dee ca peat ay den Ate ee 6 6 Connecting ProgramstoFiles 6 7 Appending to Files 0 o e 6 8 Redirecting Multiple Files 6 9 Redirection with File Descriptors 6 10 Running Programs With xargs o 0 OL ES a a a Mod ad E E E deg ay Se any 6 12 UEXBICISOS opara ach Ae a E AA ARA a A wk 7 Search Text Files Using Regular Expressions 7 1 Searching Files With grep 0 o ee 72 Pattern Matching 2 o e e 7 3 Matching Repeated Patterns 0 7 4 Matching Alternative Patterns 0 7 5 Extended Regular Expression Syntax 0 7 6 SEA ara Anani A O a e DL aa aes BE Ge Re lg 7 7 Further R
26. Let non root users mount and unmount this filesystem user Like users but non root users can only unmount filesystems that they themselves mounted E Other less common mount options exist as well as many options for individual filesystem types see mount 8 17 9 Other Columns in etc fstab E The fifth column is called dump O Used by the dump and restore backup utilities Few people use those tools O Just use 1 for normal filesystems and 0 for removable filesystems E The sixth column is called pass no O Controls the order in which automatically mounted filesystems are checked by fsck O Use 1 for the root filesystem O Use 0 for filesystems that aren t mounted at boot up O Use 2 for other filesystems Copyright 2004 GBdirect Ltd http training gbdirect co uk 81 Linux System Administration Module 17 Control Filesystem Mounting and Unmounting 17 10 Mounting a File E Using loop devices Linux can mount a filesystem stored in a normal file instead of a disk E Useful for testing images of CD ROMs before burning them to disk E For example to create a filesystem of roughly floppy disk size dd if dev zero of disk img bs 1024 count 1400 mke2fs F disk img E To mount the file so that its contents is accessible through mnt disk mount o loop disk img mnt disk 17 11 Exercises 1 a Use mount to find out which filesystems are mounted b Check the etc fstab file to see whether the floppy drive is co
27. SPWD 3 11 Using History E Previously executed commands can be edited with the Up or Ctrl P keys E This allows old commands to be executed again without re entering E Bash stores a history of old commands in memory Use the built in command history to display the lines remembered O History is stored between sessions in the file Y bash_history E Bash uses the readline library to read input from the user O Allows Emacs like editing of the command line O Left and Right cursor keys and Delete work as expected Copyright 2004 GBdirect Ltd http training gbdirect co uk 19 Linux System Administration Module 3 Work Effectively on the Unix Command Line 3 12 Reusing History Items E Previous commands can be used to build new commands using history expansion E Use to refer to the previous command for example rm index html echo echo rm index html rm index html E More often useful is st ring which inserts the most recent command which started with string O Useful for repeating particular commands without modification ls txt notes txt report txt lIs ls txt notes txt report txt 3 13 Retrieving Arguments from the History E The event designator refers to the last argument of the previous command ls 1 long_file_name html IW r Y 1 jeff users 11170 Oct 31 10 47 long_file_name html rm rm long_file_name html E Similarly refers to the first argument E A command of t
28. Software E cpio alternative archiving program E afio similar to cpio but allows files to be compressed individually O Compressed archives can be made which are resilient to corruption E dump and restore access the filesystem directly rather than through the kernel O Software is specific to filesystem types versions available for ext2 ext3 O Can preserve things which tar etc cannot m File access times tar has to access the file to archive it Special files which archiver programs might not understand Copyright 2004 GBdirect Ltd http training gbdirect co uk 135 Linux System Administration Module 28 Maintain an Effective Data Backup Strategy 28 16 Exercises a Create a single file in your home directory containing a backup of all the contents of etc Create another archive with the same contents but compressed to save disk space Compare the sizes of the two archives List the contents of each of your archives Extract the contents of one of the archives into a directory under your home directory Create a new subdirectory and extract a single file from the archive into it E Your current directory must be the one into which to extract E You will need specfiy the path of the file to be extracted but without a leading slash 2 With an archive of etc extracted under your home directory a Modify at least two files in your extracted copy Re extract one of them from the archiv
29. a pid as an argument to show a specific process and its descendants O Specify a user name as an argument to show process trees owned by that user 9 7 pstree Options Option Description a Display commands arguments C Don t compact identical subtrees G Attempt to use terminal specific line drawing characters h Highlight the ancestors of the current process n Sort processes numerically by pid rather than alphabetically by name p Include pids in the output 9 8 Process Monitoring top E Shows full screen continuously updated snapshots of process activity O Waits a short period of time between each snapshot to give the illusion of real time monitoring E Processes are displayed in descending order of how much processor time they re using E Also displays system uptime load average CPU status and memory information Copyright 2004 GBdirect Ltd http training gbdirect co uk 51 Linux System Administration Module 9 Create Monitor and Kill Processes 9 9 top Command Line Options Option Description Batch mode send snapshots to standard output Exit after displaying num snapshots Wait delay seconds between each snapshot Ignore idle processes Disable interactive commands which could be dangerous if run by the superuser 9 10 top Interactive Commands Key q Ctrl1 L h k Behaviour Quit the program Repaint the screen Show a help screen Prompts for a pid and a signal and sends
30. and waits for a command to be entered E Although this course concentrates on Bash the shell tesh is also popular O Based on the design of the older C Shell csh 16 Linux System Administration Module 3 Work Effectively on the Unix Command Line 3 3 Shell Commands E Shell commands entered consist of words O Separated by spaces whitespace O The first word is the command to run O Subsequent words are options or arguments to the command E For several reasons some commands are built into the shell itself O Called builtins O Only a small number of commands are builtins most are separate programs 3 4 Command Line Arguments E The words after the command name are passed to a command as a list of arguments Hi Most commands group these words into two categories O Options usually starting with one or two hyphens O Filenames directories etc on which to operate E The options usually come first but for most commands they do not need to E There is a special option which indicates the end of the options O Nothing after the double hyphen is treated as an option even if it starts with 3 5 Syntax of Command Line Options E Most Unix commands have a consistent syntax for options Single letter options start with a hyphen e g B O Less cryptic options are whole words or phrases and start with two hyphens for example ignore backups E Some options themselves take arguments O Usually the argument is the next word
31. be followed directly by the filename m Common to use tar extension m Any subsequent options require a hyphen O The z option compresses the archive with gzip E tar gz extension used to indicate compression E tgz extension also popular O The list of files and directories to archive follows the options 28 7 Listing the Files in tar Archives E To check that a tar file has been made correctly use the t operation for list tar tzf docs tar gz E The z and f options work as for the c operation E To show more information about files add the v for verbose option O Shows information similar to 1s 1 Can also be specified with c to list filenames as they are added 28 8 Extracting Files from tar Archives E Use the x operation to extract files from an archive tar xzvf docs tar gz E The v option lists the files as they are extracted E To extract individual files list them on the command line tar xzvf docs tar gz documents phone numbers txt E Other useful options O k keep old files will not overwrite any existing files only extracting missing ones O p preserve permissions will set extracted files to have the permissions they had when archived Copyright 2004 GBdirect Ltd http training gbdirect co uk 133 Linux System Administration Module 28 Maintain an Effective Data Backup Strategy 28 9 Device Files for Accessing Tapes E Under Linux tape drives are accessed through several groups o
32. bob txt PIPE PIPE REDIRECT everyone txt Copyright 2004 GBdirect Ltd http training gbdirect co uk 42 Linux System Administration Module 6 Use Unix Streams Pipes and Redirects 6 12 Exercises 1 a Try the example on the Pipes slide using rev to reverse some text b Try replacing the echo command with some other commands which produce output e g whoami c What happens when you replace rev with cat You might like to try running cat with no arguments and entering some text 2 a Runthe command 1s color ina directory with a few files and directories Some Linux distributions have 1s set up to always use the color option in normal circumstances but in this case we will give it explicitly b Try running the same command but pipe the output into another program e g cat or less You should spot two differences in the output 1s detects whether its output is going straight to a terminal to be viewed by a human directly or into a pipe to be read by another program Copyright 2004 GBdirect Ltd http training gbdirect co uk 43 Module 7 Search Text Files Using Regular Expressions 7 1 Searching Files with grep E grep prints lines from files which match a pattern E For example to find an entry in the password file etc passwd relating to the user nancy grep nancy etc passwd E grep has a few useful options O i makes the matching case insensitive O r searches through files
33. distinguish a symlink from the original it points to Symlinks can point to any type of file normal file directory device file symlink etc Symlinks refer to names so they can point to files on other filesystems Conversely if you rename or delete the original file pointed to by a symlink the symlink gets broken Symlinks may take up additional disk space to store the name pointed to Hard links Multiple hard link style names for the same file are indistinguishable the term hard link is merely conventional Hard links may not point to a directory or on some non Linux systems to a symlink Hard links work by inode number so they can only work within a single filesystem Renaming or deleting the original file pointed to by a hard link has no effect on the hard link Hard links only need as much disk space as a directory entry Copyright 2004 GBdirect Ltd http training gbdirect co uk 64 Linux System Administration Module 13 Create and Change Hard and Symbolic Links 13 6 Examining and Creating Hard Links E Use the 1n command to create a hard link E Don t use the s option when creating hard links E As when creating symlinks the order of the arguments to 1n mimics cp Is 1 dtd IW 1 Y 1 anna anna 11170 Dec 9 14 11 module dtd 1n module dtd chapter dtd ls 1 dtd Yw r r 2 anna anna 11170 Dec 9 14 11 chapter dtd IW Y Y 2 anna anna 11170 Dec 9 14 11 module dtd E Notic
34. du h d du hs e du hs f du hsS g du hsc du bso Copyright 2004 GBdirect Ltd http training gbdirect co uk 86 Module 19 Find System Files and Place Files in the Correct Location 19 1 Unix Filesystem Layout Hi Many common directory names are abbreviated versions of real words E Traditional structure which has developed over many years O Most system files have their proper place O Programs rely on them being in the correct place O Users familiar with Unix directory structure can find their way around any Unix or Linux system E But a user s home directory can be structured however they want 19 2 The Filesystem Hierarchy Standard E Started as an attempt to standardise Linux filesystem layouts O Called the FSSTND when the first version was published in 1994 E Widely accepted by distributors O But few Linux systems are 100 compliant yet E Intended to avoid fragmentation of Linux distributions E Renamed to the File Hierarchy Standard or FHS E Now intended to apply to all Unix like operating systems 87 Linux System Administration Module 19 Find System Files and Place Files in the Correct Location 19 3 Shareable and Non Shareable Data E Some files can be shared between multiple computers using networked filesystems such as NFS O This can save space although cheap hard drives mean that this is not so important now O More importantly it can help to centralise administration
35. een BORE 110 23 13 Location of Manual Pages 2 2 a aa aop ao a Ea a a EE A ERT E R A 110 23 14 IMfO PAGSS aa a eee eee Be E rA S R aa A AA Lay a 111 23 15 Navigating Within Info Pages ipase ga eap ae aoe a a koa auge e eO Kaa pok E ga 111 23 16 Documentation in usr share doc oaoa a a 111 23 17 Contents of usr share doc o 112 23 18 Interrogating Commands for Help a aoaaa a 112 23 19 Finding Documentation 2 0 ae aone a a Eear Eue E a S na a a A E a a aa 112 23 20 EXO CISOS 4 2 x eas eh a we A te os os ee a eat Bd ange a e nd S 112 24 Find Linux Documentation on the Internet 114 24 1 The Linux Documentation Project 2 0 o eo 114 24 2 HOWTOS cc A oe E ed a ew a 114 24 3 Obtaining HOWTOs 2 a a aa ka e aa ea a aa ka aa a a 115 24 4 Vendor and Application Specific Web Sites oaoa a 115 24 5 UsenetNewsgroups 2 a a ee 115 24 62 EAS a keine een hike Bore oe ae Ae ee le A y A de o 116 24 77 LoCaliHelp 2 0 05 ett hed eed ER A a Ee ado eds a gh a A a 116 25 Tune the User Environment and System Environment Variables 117 25 1 Configuration Files s ie ss sss sasaat mia ee 117 25 2 Shell Configuration Files Aa gt aa monea i a Eee let p e E na a E a a aLa 117 25 3 Changing Environment Variables a 118 25 4 Changing the Prompt x ra sa eu 2 ee 118 255 Shel Aliases e idad be a od Pd dd hadi Gob ee Aba A 118 25 6 Setting Up Home Directories for New Accoun
36. home simon echo Bad directory gt amp 2 exit 1 echo Check the download has completed Real at commands include the environment too Hi Remove an at command with at rm atrm 38 27 8 Simple Cron Job Specification E The simplest method for specifying cron jobs is to save each job as a separate file in an appropriate directory O etc cron daily is for jobs to be run daily Once a day each file in that directory is run O The files are typically shell scripts O There are equivalent directories for monthly weekly and possibly hourly jobs O Each job is run with root permissions E Normally only root can set up cron jobs this way E Any required environment variables must be set explicitly Copyright 2004 GBdirect Ltd http training gbdirect co uk 126 Linux System Administration Module 27 Automate and Schedule System Administration Tasks 27 9 More Complex Cron Job Specification E Sometimes more control is needed To run jobs at a non standard time O To run jobs as a user other than root E The directory etc cron d is for this purpose E Each file in that directory must contain lines in a specific format When the command should run For which user the command should be run The command to be run E Such a file is known as a cron table or crontab O Details are in crontab 5 O Easier to have one file per job 27 10 Crontab Format E Blank lines are ignored E Comments are lines starting with a
37. in a file O Removes consecutive duplicate lines O Usually give it sorted input to remove all duplicates Example find out how many unique words are in a dictionary sort usr dict words uniq wc w sort has a u option to do this without using a separate program sort u usr dict words wc w sort uniq can do more than sort u though O uniq c counts how many times each line appeared unig u prints only unique lines uniq d prints only duplicated lines Selecting Parts of Lines with cut Used to select columns or fields from each line of input Select a range of O Characters with c O Fields with f Field separator specified with d defaults to tab E A range is written as start and end position e g 3 5 O Either can be omitted O The first character or field is numbered 1 not 0 Example select usernames of logged in users who cut d f1 sort u Copyright 2004 GBdirect Ltd http training gbdirect co uk 26 Linux System Administration Module 4 Process Text Streams Using Text Processing Filters 4 9 Expanding Tabs to Spaces with expand E Used to replace tabs with spaces in files E Tab size maximum number of spaces for each tab can be set with t number O Default tab size is 8 E To only change tabs at the beginning of lines use i E Example change all tabs in foo txt to three spaces display it to the screen expand t 3 foo txt expand 3 foo txt 4 10 Using fmt
38. must be quoted to protect them from the shell 3 22 Exercises a Use the df command to display the amount of used and available space on your hard drive b Check the man page for df and use it to find an option to the command which will display the free space in a more human friendly form Try both the single letter and long style options c Run the shell bash and see what happens Remember that you were already running it to start with Try leaving the shell you have started with the exit command a Try ls with the a and A options What is the difference between them b Write a for loop which goes through all the files in a directory and prints out their names with echo If you write the whole thing on one line then it will be easy to repeat it using the command line history c Change the loop so that it goes through the names of the people in the room which needn t be the names of files and print greetings to them d Of course a simpler way to print a list of filenames is echo Why might this be useful when we usually use the 1s command a Use the find command to list all the files and directories under your home directory Try the type d and type f criteria to show just files and just directories b Use locate to find files whose name contains the string bashbug Try the same search with find looking over all files on the system You ll need to use the wildcard at the end of the pattern to match files wit
39. of text to check it Does it work if the misspelling occurs more than once on the same line e Use nl to number the lines in the output of the previous question 2 a Try making an empty file and using tail f to monitor it Then add lines to it from a different terminal using a command like this echo testing gt gt filename b Once you have written some lines into your file use tr to display it with all occurances of the letters A F changed to the numbers 0 5 c Try looking at the binary for the 1s command bin Is with less You can use the f option to force it to display the file even though it isn t text d Try viewing the same binary with od Try it in its default mode as well as with the options shown on the slide for outputting in hexadecimal 3 a Use the split command to split the binary of the 1s command into 1Kb chunks You might want to Copyright 2004 GBdirect Ltd http training gbdirect co uk 31 Linux System Administration Module 4 Process Text Streams Using Text Processing Filters create a directory especially for the split files so that it can all be easily deleted later b Put your split 1s command back together again and run it to make sure it still works You will have to make sure you are running the new copy of it for example my_1s and make sure that the program is marked as executable to run it with the following command chmod a rx my_l1s Copyright 2
40. out of disk space E The solution is to use log rotation a scheme whereby existing log files are periodically renamed and ultimately deleted O But syslog continues to write messages into the file with the correct name E Most Linux systems come with a program called logrotate which should be run daily by cron E logrotate can be configured with etc logrotate conf to perform rotation on any or all log files O You can choose for each file how often it is rotated and how many old logs are kept 26 8 Sample etc logrotate conf Gzip rotated files by default compress Keep 5 weeks worth and restart syslogd after rotating var log messages rotate 5 weekly postrotate killall HUP sbin syslogd endscript Keep 1 month s worth Specify ownership and permissions of the new file var log wtmp rotate 1 monthly create 0664 root utmp Copyright 2004 GBdirect Ltd http training gbdirect co uk 122 Linux System Administration Module 26 Configure and Use System Log Files 26 9 Exercises 1 a Log onto your machine as root and use less to browse through var log messages b Start monitoring the file for additions using tail c In another terminal logged on as a normal user try using su to change to root find out what is written to the logs when correct and incorrect passwords are given to su d Look at the configuration file for Logrotate to find out how var log messages is rotated some systems
41. previous command finds lines which match at least one of the words Use to enforce precedence grep i cream fish birthday cakes delicacies txt Use square brackets to build a character class grep Jj loe Bb loggs staff txt Any single character from the class matches and ranges of characters can be expressed as a z Extended Regular Expression Syntax egrep runs grep in a different mode Same as grep E Special characters don t have to be marked with O So is written 1 1 is written etc O In extended regexps is a literal sed sed reads input lines runs editing style commands on them and writes them to stdout sed uses regular expressions as patterns in substitutions sed regular expressions use the same syntax as grep For example to used sed to put at the start of each line sed e s lt input txt gt output txt sed has simple substitution and translation facilities but can also be used like a programming language Copyright 2004 GBdirect Ltd http training gbdirect co uk 45 Linux System Administration Module 7 Search Text Files Using Regular Expressions 7 7 Further Reading M man 7 regex E Sed and Awk 2nd edition by Dale Dougherty and Arnold Robbins 1997 E The Sed FAQ http www dbnet ece ntua gr george sed sedfaq html E The original Sed user manual 1978 http www urc bl ac yu manuals progunix sed txt 7 8 Exercises 1 a
42. setgid set group id files created within it acquire the group ownership of the directory O And directories created within it acquire both the group ownership and setgid permission E Useful for a shared directory where all users working on its files are in a given group E Expressed with an s in group position in a listing ls 1 d data projects drwxrwsr x 16 root staff 4096 Oct 19 13 14 data projects E Enable setgid with chmod g s data projects 15 12 Special File Permissions Setgid E Setgid permission may also be applied to executable files E A process run from a setgid file acquires the group id of the file E Note Linux doesn t directly allow scripts to be setgid only compiled programs E Useful if you want a program to be able to for example edit some files that have a given group owner O Without letting individual users access those files directly Copyright 2004 GBdirect Ltd http training gbdirect co uk 73 Linux System Administration Module 15 Use File Permissions to Control Access to Files 15 13 Special File Permissions Setuid E Files may also have a setuid set user id permission E Equivalent to setgid a process run from a setuid file acquires the user id of the file E As with setgid Linux doesn t allow scripts to be setuid E Expressed with an s in user position in a listing ls l usr bin passwd r s x x 1 root root 12244 Feb 7 2000 usr bin passwd
43. simple mail reader you can use to do this b Make the xeyes command start in a minute s time capable of opening window s on your screen Re member that any error messages from a command failing to run will be mailed to you c Make a clock appear on your screen at four o clock this afternoon 3 a Create a file containing a command which will delete all files in tmp when it is run Make that script be run every hour b Set up a script that once a minute appends the following data to a file E The current date and time E A count of the number of processes currently running Monitor that file and start and stop programs to affect the number reported When you ve finished deactivate the script c Asa non privileged user set up two scripts E In even numbered minutes write the time the system has been running to a particular file E In odd numbered minutes delete that file 4 Set up scripts to run as a non privileged user at the following times you won t be able to test most of them but it gives you practice at getting used to the order of the fields Add the jobs one at a time so that your crontab will be parsed to check for errors after each one E At 09 25 every Sunday in December E At 21 30 on the 1st and 15th of every Month E Every three hours at weekends E Half past every hour during weekdays E The first day of every quarter E The evening of the first and third Thursday of each month E At 17 30 every other day
44. sort o output_file E A few programs use different styles of command line options O For example long options not single letters sometimes start with a single rather than Copyright 2004 GBdirect Ltd http training gbdirect co uk 17 Linux System Administration Module 3 Work Effectively on the Unix Command Line 3 6 3 8 Examples of Command Line Options List all the files in the current directory 1s List the files in the long format giving more information ls 1 List full information about some specific files ls 1 notes txt report txt List full information about all the txt files ls 1 txt List all files in long format even the hidden ones ls 1 a ls la Setting Shell Variables Shell variables can be used to store temporary values Set a shell variable s value as follows files notes txt report txt O The double quotes are needed because the value contains a space O Easiest to put them in all the time Print out the value of a shell variable with the echo command echo files O The dollar tells the shell to insert the variable s value into the command line Use the set command with no arguments to list all the shell variables Environment Variables E Shell variables are private to the shell E A special type of shell variables called environment variables are passed to programs run from the shell E A program s environment is the
45. such as SINFOPATH use the same convention 25 4 Changing the Prompt E Setting PS1 will change the shell prompt for example export PS1 w s E Characters preceded by are given special interpretations for example O Xt and Md display the time and date in the prompt O wor W show the current working directory O shows up as either or depending on whether you are a normal user or root O Vu displays your username O Ah displays the hostname of the machine E PS2 is an alternative prompt displayed when bash needs more input before it can run a complete command 25 5 Shell Aliases E It is often useful to have bash aliases for commands like 1s and 1s 1 perhaps adding options alias l ls color auto F alias 11 1 1 E The alias command with no arguments will show a list of currently defined aliases E To show what one particular alias is set to pass the name to alias without setting it to anything alias 1 Copyright 2004 GBdirect Ltd http training gbdirect co uk 118 Linux System Administration Module 25 Tune the User Environment and System Environment Variables 25 6 Setting Up Home Directories for New Accounts E When anew user account is created a new home directory is also made E Each new home directory is populated with a skeleton set of configuration files O These are copied from etc skel by the useradd command E Setting up these files with useful defaults can make life easier fo
46. that signal to that process Prompts for the number of processes to show information O the default means to show as many as will fit Change the priority niceness of a process Change the number of seconds to delay between updates The number may include fractions of a second 0 5 for example 9 11 Signalling Processes E A process can be sent a signal by the kernel or by another process E Each signal is a very simple message O A small whole number O With a mnemonic name E Signal names are all capitals like INT O They are often written with SIG as part of the name SIGINT E Some signals are treated specially by the kernel others have a conventional meaning E There are about 30 signals available not all of which are very useful Copyright 2004 GBdirect Ltd http training gbdirect co uk 52 Linux System Administration Module 9 Create Monitor and Kill Processes 9 12 Common Signals for Interactive Use E The command kill 1 lists all signals E The following are the most commonly used Name Number INT 2 TERM 15 KILL 9 TSTP 18 HUP 1 Meaning Interrupt stop running Sent by the kernel when you press Ctr1 C in a terminal Please terminate Used to ask a process to exit gracefully Die Forces the process to stop running it is given no opportunity to clean up after itself Requests the process to stop itself temporarily Sent by the kernel when you press Ctr1 2Z
47. the poem file into the new directory Try to find a graphical directory browsing program and find your home directory with it You should also be able to use it to explore some of the system directories Find a text editor program and use it to display and edit the sonnet a From your home directory list the files in the directory usr share Change to that directory and use pwd to check that you are in the right place List the files in the current directory again and then list the files in the directory called doc Next list the files in the parent directory and the directory above that Try the following command and make sure you understand the result echo Use cat to display the contents of a text file which resides in your home directory create one if you Copyright 2004 GBdirect Ltd http training gbdirect co uk 14 Linux System Administration Module 2 Getting Started haven t already using the 7 syntax to refer to it It shouldn t matter what your current directory is when you run the command 4 a Use the hostname command with no options to print the hostname of the machine you are using b Use man to display some documentation on the hostname command Find out how to make it print the IP address of the machine instead of the hostname You will need to scroll down the manpage to the Options section c Use the locate command to find files whose name contains the text h
48. to Format Text Files E Arranges words nicely into lines of consistent length E Use u to convert to uniform spacing O One space between words two between sentences E Use w width to set the maximum line width in characters O Defaults to 75 E Example change the line length of notes txt to a maximum of 70 characters and display it on the screen fmt w 70 notes txt less 4 11 Reading the Start of a File with head E Prints the top of its input and discards the rest E Set the number of lines to print with n linesor lines O Defaults to ten lines E View the headers of a HTML document called homepage html head homepage html E Print the first line of a text file two alternatives head n 1 notes txt head 1 notes txt Copyright 2004 GBdirect Ltd http training gbdirect co uk 27 Linux System Administration Module 4 Process Text Streams Using Text Processing Filters 4 12 Reading the End of a File with tail E Similar to head but prints lines at the end of a file E The f option watches the file forever O Continually updates the display as new entries are appended to the end of the file O Kill it with Ctr1 C E The option n is the same as in head number of lines to print Mi Example monitor HTTP requests on a webserver tail f var log httpd access_log 4 13 Numbering Lines of a File with n1 or cat E Display the input with line numbers against each line E There are options to finely cont
49. 00 ee 19 3 11 USING ElISIONY e 3 Lia Atari oes Bare Shah ae ay es io Lares A en ge ge a en as a 19 3 12 ReusingHistory Moms ee 20 3 13 Retrieving Arguments from the History e 20 3 14 Summary of Bash Editing Keys 2 0 e eo 21 3 15 Combining Commands on One Line 0 000 a 21 3 16 Repeating Commands With for 2 ee 21 3 17 Gommand Substitution 22 6 24 4 a RA Re ee Be E Be cae ee 22 3 18 Finding Files with locate aos aiea a a a e 22 3 19 Finding Files More Flexibly find 2 2 a 22 3 20 Fina Crilenlai 2 8 a bce he a A lac Saree eva ea dee es ee 23 3 21 findActions Executing Programs a s a seresa a a ata k aia E a a De Eea Sa a A aA aoa e A 23 3 22 UEXOICISOS rita a Bieter eee ae eee gee as Gk eR ete gd ARA e EA 23 4 Process Text Streams Using Text Processing Filters 24 4 1 Working with Text Files e 24 4 2 Lines Of TEX a cee he a e ie ea a ee ee Body a eo 24 4 3 Filtering Text and PONG ee 25 4 4 Displaying Files with LESS erk aa ib ri ia A a gb eae eS 25 4 5 Counting Words and Lines with wc 2 aoaaa a a a a a 25 4 6 Sorting Lines of Textwith sort E PA a a a E A E A A 26 4 7 Removing Duplicate Lines with uniq a aooaa a a a ee 26 4 8 Selecting Parts of Lines with cut o oo a 26 4 9 Expanding Tabs to Spaces with expand osoa osoo e a 27 4 10 Using fmt to Format Text Files 2 0 a
50. 004 GBdirect Ltd http training gbdirect co uk 32 Module 5 Perform Basic File Management 5 1 Filesystem Objects E A file is a place to store data a possibly empty sequence of bytes E A directory is a collection of files and other directories E Directories are organized in a hierarchy with the root directory at the top lt gt home Cin E The root directory is referred to as 5 2 Directory and File Names E Files and directories are organized into a filesystem E Refer to files in directories and sub directories by separating their names with for example bin ls usr share dict words home jeff recipe E Paths to files either start at absolute or from some current directory 33 Linux System Administration Module 5 Perform Basic File Management 5 3 File Extensions E its common to put an extension beginning with a dot on the end of a filename E The extension can indicate the type of the file 5 5 txt Text file gif Graphics Interchange Format image jpg Joint Photographic Experts Group image mp3 MPEG 2 Layer 3 audio 9Z Compressed file tar Unix tape archive file tar gz tgz Compressed archive file On Unix and Linux file extensions are just a convention O The kernel just treats them as a normal part of the name A few programs use extensions to determine the type of a file Going Back to Previous Directories The pushd command takes you
51. 14 rmdir deletes empty directories so the files inside must be deleted first For example to delete the images directory rm images rmdir images For non empty directories use rm r directory The p option to rmdir removes the complete path if there are no other files and directories in it O These commands are equivalent rmdir p a b c rmdir a b c a b a Identifying Types of Files The data in files comes in various different formats executable programs text files etc The file command will try to identify the type of a file file bin bash bin bash ELF 32 bit LSB executable Intel 80386 version 1 dynamically linked uses shared libs stripped It also provides extra information about some types of file Useful to find out whether a program is actually a script file usr bin zless usr bin zless Bourne shell script text If file doesn t know about a specific format it will guess file etc passwd etc passwd ASCII text Copyright 2004 GBdirect Ltd http training gbdirect co uk 37 Linux System Administration Module 5 Perform Basic File Management 5 15 Changing Timestamps with touch E Changes the access and modification times of files E Creates files that didn t already exist E Options a change only the access time m change only the modification time t YYYY MMDDhhmm ss set the timestamp of the file to the specified date and time GNU touch has a d opt
52. 27 4 11 Reading the Start of a File with head oaoa a a 27 4 12 Reading the End of a File with tail a aaao a a 28 4 13 Numbering Lines of a File with nl or cat aaao aa a 28 4 14 Dumping Bytes of Binary Data with od a aoaaa a a 28 4 15 Paginating Text Files with pr aaoo a a 29 4 16 Dividing Files into Chunks with split saoao aa a ee 29 A17 Usingssplvt to Span DISKS ce ira Ee Bie ok O Bice iw ge E 29 4 18 Reversing Files with tac a aoao a ee 29 4 19 Translating Sets of Characters with tr aaoo a a ee 30 4 20 Ew EAMES via a EIR ahs A AVALE a hd TE E E eve AA ee gece ees eS 30 4 21 Modifying Files With sed a ee 30 4 22 SUDSttUINO WIN SEd y urec a RA A a ta A tea tered oe a 30 4 23 Put Files Side by Side with paste o eo 31 4 24 Performing Database Joins With join aooaa ea o uo 31 4 25 EXercises 10 ica anes oe ads ghd be e a a a sd a E ti 31 5 Perform Basic File Management 33 5 1 Filesystem Objects ce aTe ar Aen eee a aia AS 33 5 2 Directory and File Names ee 33 5 3 Fille EXTenSionS e ri us E A LAS a Soe Gat a A Ad A A ow 34 Copyright 2004 GBdirect Ltd http training gbdirect co uk iv Linux System Administration Contents 5 4 Going Back to Previous Directories 5 5 Filename Completion 00000 eee eee 5 6 Wildcard Patterns 2 2 0 e 5 7 Copying Files WICE preradama ram L aa e ee 5 8
53. A symlink is created with the 1n s command Its syntax is similar to cp the original name comes first then the name you want to create ln s real file file link ln s real dir dir link ls l file link dir link lrwxrwxrwx 1 bob bob 9 Jan 11 15 22 file link gt real fil lrwxrwxrwx 1 bob bob 8 Jan 11 15 22 dir link gt real dir 63 Linux System Administration Module 13 Create and Change Hard and Symbolic Links 13 3 Hard Links Ml Where symlinks refer to other files by name a hard link refers to another file by inode number O An inode is the data structure that describes a file on disk O It contains information about the file including its type file directory device modification time permissions etc E A directory entry contains a name and an inode number O Soafile s name is not considered to be part of the file itself E You get a hard link when different directory entries on a filesystem refer to the same inode number 13 4 Symlinks and Hard Links Illustrated E A symbolic link refers to filename which in turn refers to an inode entry e data directory _ entry E A hard link is a normal directory entry referring directly to an inode directory entry inode directory data entry 13 5 Comparing Symlinks and Hard Links Symlinks Symlinks are distinctly different from normal files so we can
54. Bdirect Ltd http training gbdirect co uk Contents 1 Introduction 1 1 1 Undand LUX dooce its et how ah AOS GSW dee a Gh BE eh RO A ee A ta 1 1 2 Unix System Architecture 2 e 1 1 3 Unix Philosophy e320 8 otek Bend it te tt ob Ao pe ets 2 1 4 Wiha iSsLInUx A a hoe oe a A AA a Se he ln A A ain a 2 1 5 Using a Linux System Lita way che Boe ce ee oe Bo a Ge a a Ee 2 1 6 Linux Gommand Line dr Be Bey A a eee e A Rie dee ae 3 1 7 LOGGING QU i sex se rs wea Pe wits RO ee A ee Oe on et ee 3 1 8 Command Syntax oa aa de ee a ee ee he be Gwe ee A 3 1 9 FIGS roy 2s i E sheet aca E E Ea Sv eat geek E A bios 4 1 10 Creating Files withscat ag eeu a ap ek ROM aie GON whe bale aod ease a 4 1 11 Displaying Files Contents with cat a o aoaaa a eo 4 1 12 iDeleting Files wihi ss rena medue ae Ae oe ee a eal Sa Fede de Yo 5 1 13 Unix Gommand Feedback 2040 ooo cc a ea a a eee 5 1 14 Copying and Renaming Files with cp and mv 2 o e e 5 1 15 Filename Completion ee 6 1 16 Command History ee 6 1 17 Exercises so beaan ey oe ee EO a OA ee a eR ee a 6 Getting Started 8 2 1 Files and Direcciones u as ede he a e ae we ee ewe eae ee ga He 8 2 2 Examples of Absolute Pains ooo nde A a E A be 8 2 3 Grent DNET aoa pta aa a a aa rr bs e 9 2 4 Making and Deleting Directories o o e o 9 2 5 Relative PALOS s sa d ea mo ee Be ee ee ee Re Bee ee a ee 9 2
55. E Enable setuid with chmod u s usr local bin program 15 14 Displaying Unusual Permissions Mi Use 1s 1 to display file permissions O Setuid and Setgid permissions are shown by an s in the user and group execute positions O The sticky bit is shown by a t in the other execute position E The letters s and t cover up the execute bits O But you can still tell whether the execute bits are set O Lowercase s or t indicates that execute is enabled i e there is an x behind the letter O Uppercase S or T indicates that execute is disabled there is a behind the letter 15 15 Permissions as Numbers E Sometimes you will find numbers referring to sets of permissions E Calculate the number by adding one or more of the following together 4000 Setuid 40 Readable by group owner 2000 Setgid 20 Writable by group owner 1000 Sticky 10 Executable by group owner 400 Readable by owner 4 Readable by anyone 200 Writable by owner 2 Writable by anyone 100 Executable by owner 1 Executable by anyone E You may use numerical permissions with chmod chmod 664 txt is equivalent to chmod ug rw o r txt Copyright 2004 GBdirect Ltd http training gbdirect co uk 74 Linux System Administration Module 15 Use File Permissions to Control Access to Files 15 16 Default Permissions umask E The umask command allows you to affect the default permissions on files and directories you create umask 002 E The argument is
56. Linux System Administration lt gbdirect gt Copyright GBdirect Ltd 2004 http training gbdirect co uk tel 0870 200 7273 Overview 10 11 12 13 14 15 16 17 18 Introduction Getting Started Work Effectively on the Unix Command Line Process Text Streams Using Text Processing Filters Perform Basic File Management Use Unix Streams Pipes and Redirects Search Text Files Using Regular Expressions Job Control Create Monitor and Kill Processes Modify Process Execution Priorities Advanced Shell Usage Filesystem Concepts Create and Change Hard and Symbolic Links Manage File Ownership Use File Permissions to Control Access to Files Create Partitions and Filesystems Control Filesystem Mounting and Unmounting Maintain the Integrity of Filesystems 16 24 33 39 44 47 49 55 57 61 63 67 70 76 79 83 Linux System Administration Overview 19 Find System Files and Place Files in the Correct Location 87 20 Set and View Disk Quotas 93 21 Boot the System 97 22 Change Runlevels and Shutdown or Reboot System 101 23 Use and Manage Local System Documentation 106 24 Find Linux Documentation on the Internet 114 25 Tune the User Environment and System Environment Variables 117 26 Configure and Use System Log Files 120 27 Automate and Schedule System Administration Tasks 124 28 Maintain an Effective Data Backup Strategy 131 Copyright 2004 G
57. O a ped Renee Ge eatery iaa 101 22 3 Single User Mode and sulogin ee 102 22 4 Shutting Down and Restarting the System 2 aaa ee 102 22 5 Setting the Default Runlevel 2 2 ee 102 22 6 Selecting a Different RunlevelatBootup 2 2 2 2 a 103 22 7 Determining the Current Runlevel 2 2 e a a 103 22 8 Switching Runlevel lt sa rs 2 ee 103 22 9 Services in Each Runlevel the init d Directory 2 2 e 104 22 10 Symbolic Linksin rcN d 2 ee 104 22 11 Starting or Stopping Individual Services 2 2 2 00002 ee ee 104 22 12 EXCrCISes e rt td o Boe ah ech i he ate ae AM ee eg 104 23 Use and Manage Local System Documentation 106 23 1 ManualPages oea c ead d a a ee a eee ee be ease 106 23 2 Navigating Within Manual Pages 2 0 e 106 23 3 Sections of a Manual Page 2 a a a 107 23 4 Sections Of the Manual a a e a A G Aa a a 107 23 5 Manual Section Numbering aa aaa 0 a a 108 23 6 Determining Available Manpages With whatis saoao a a 108 23 Printing Manual Pags 3 20d Se eae A da EY Gea a 108 23 8 Searching for Manpages with apropos a 109 23 9 Displaying All Manpages of a Particular Name with man a 0 a a 109 23 10 Searching the Content of All Manpages with man K aoaaa a 109 23 11 Finding the Right Manual Page 1 2 a 110 23 12 Hop on SNo BUITINS 602 Stak ee awardee ed anode Brac Re a al dense ad Heese
58. Windows at most four primary partitions can be made O But they can be extended partitions which can themselves be split into smaller logical partitions m Extended partitions have their own partition table to store information about logical partitions 16 2 Disk Naming E The device files for IDE hard drives are dev hda to dev hdd O hda and hab are the drives on the first IDE channel hdc and hdd the ones on the second channel O The first drive on each channel is the IDE master and the second is the IDE slave Ml Primary partitions are numbered from 1 4 E Logical partitions are numbered from 5 E The devices dev hda etc refer to whole hard disks not partitions O Add the partition number to refer to a specific partition O For example dev hda1 is the first partition on the first IDE disk E SCSI disks are named dev sda dev sab etc 76 Linux System Administration Module 16 Create Partitions and Filesystems 16 3 Using fdisk E The fdisk command is used to create delete and change the partitions on a disk E Give fdisk the name of the disk to edit for example fdisk dev hda E fdisk reads one letter commands from the user Type mto get a list of commands O Use p to show what partitions currently exist O Use q to quit without altering anything Use w to quit and write the changes m Use with caution and triple check what you re doing 16 4 Making New Partitions E Create new partitions with the
59. a user and quota group in their root directories E The following commands will create them touch partition quota user group chmod 600 partition quota user group Copyright 2004 GBdirect Ltd http training gbdirect co uk 94 Linux System Administration Module 20 Set and View Disk Quotas 20 7 Enabling Quota quotaon E quotaon turns on quota support O Can only be done by root Support must be compiled into the kernel but this is done by default on all modern distributions E quotaoff disables quota support E For example to turn on quota on all filesystems quotaon av E Quota can be turned on or off for individual filesystems 20 8 Changing Quota Limits setquota E Command line program to alter quota limits for a user or group E Specify the name of a user or group with u username or g groupname E Specify the filesystem to alter after the u or g option E Finally the limits to set must be specified in the following order O Soft limit for blocks O Hard limit for blocks O Soft limit for inodes O Hard limit for inodes E Setting any limit to O will remove that limit 20 9 edquota E edquota allows quotas to be edited interactively in a text editor O The file in the text editor will be a temporary file O edquota will read it back in when the editor terminates E Use the g option to edit group quotas E Some versions of Red Hat have a bug where you need to delete an extraneous space before t
60. al bin check faxes 27 13 etc crontab E The etc crontab file is an older way of specifying cron jobs E Each job in that file is like a file from etc cron d E Having many unrelated cron jobs in a single file is much harder to manage E This file may be the mechanism by which your system runs the contents of etc cron daily and friends E There is no need to use this file for anything else Copyright 2004 GBdirect Ltd http training gbdirect co uk 128 Linux System Administration Module 27 Automate and Schedule System Administration Tasks 27 14 User Crontabs E Sometimes non root users need to set up cron jobs E Each user has a crontab file O This is not edited directly O The crontab command manipulates it O Use crontab e option to edit the crontab m The editor in the SEDITOR variable is invoked for this O Use crontab 1 to display the crontab E The format is very similar to that of etc rc d crontabs O But there is no username field O All commands run as the owner of the crontab 27 15 Cron Job Output E Cron jobs do not run in a terminal window E Generally they are administrative tasks designed not to produce any output when run successfully E Any output that is generated by a cron job is mailed O The recipient can be specified in the MAILTO environment variable O Otherwise mail is sent to the job s owner O Jobs in etc cron daily et al are owned by root 27 16 At Command and Cron Job Permissions E N
61. amps cp p important txt important txt orig E Alternatively the a option preserves all information possible including permissions and timestamps 15 6 How Permissions are Applied E If you own a file the per owner permissions apply to you E Otherwise if you are in the group that group owns the file the per group permissions apply to you E If neither of those is the case the for everyone else permissions apply to you Copyright 2004 GBdirect Ltd http training gbdirect co uk 71 Linux System Administration Module 15 Use File Permissions to Control Access to Files 15 7 Changing File and Directory Permissions chmod Mi The chmod command changes the permissions of a file or directory O A file s permissions may be changed only by its owner or by the superuser E chmod takes an argument describing the new permissions O Can be specified in many flexible but correspondingly complex ways E Simple example chmod a x new program adds executable permission x for all users a on the file new program 15 8 Specifying Permissions for chmod Ml Permissions can be set using letters in the following format ugoa rwxX E The first letters indicate who to set permissions for O u for the file s owner y for the group owner o for other users or a for all users E sets permissions for files adds permissions to those already set and removes permissions E The final letters indicate which of the r
62. at it shows and how O Normally shows a fairly brief summary of each process O Normally shows only processes which are both owned by the current user and attached to a terminal E Unfortunately it doesn t use standard option syntax E Instead it uses a mixture of options with one of three syntaxes O Traditional BSD ps a single letter with no hyphen Unix98 ps a single letter preceded by a hyphen GNU a word or phrase preceded by two hyphens Copyright 2004 GBdirect Ltd http training gbdirect co uk 50 Linux System Administration Module 9 Create Monitor and Kill Processes 9 5 ps Options E ps has many options E Some of the most commonly used are Option Description a Show processes owned by other users f Display process ancestors in a tree like format u Use the user output format showing user names and process start times w Use a wider output format Normally each line of output is truncated each use of the w option makes the window wider x Include processes which have no controlling terminal e Show information on all processes 1 Use a long output format f Use a full output format C cmd Show only processes named cmd U user Show only processes owned by user 9 6 Process Monitoring pstree E Displays a snapshot of running processes E Always uses a tree like display like ps f O But by default shows only the name of each command E Normally shows all processes O Specify
63. been changed from the default N is printed instead 22 8 Switching Runlevel E The system has a process named init with pid 1 which is the ultimate ancestor of all other processes Ml init is responsible for controlling runlevels so switching runlevels involves telling init to do something O As root run telinit 1 to switch into a given runlevel E You can alternatively use init itself with the same syntax init 5 E Obviously changing runlevels should not be undertaken lightly O In particular changing runlevel can terminate important system services or affect users ability to log in Copyright 2004 GBdirect Ltd http training gbdirect co uk 103 Linux System Administration Module 22 Change Runlevels and Shutdown or Reboot System 22 9 Services in Each Runlevel the init d Directory E etc contains an init d directory and an rcN d directory for each runlevel N O Some distributions notably Red Hat put all these directories in etc rc d not directly under etc E init d contains an init script for each service that can be started E The rcN d directories contain symbolic links to the init scripts These symbolic links control which services are available in each runlevel 22 10 Symbolic Links in rcN d E Symbolic links in the rcN d directory are either start links or stop links O Start links are named SNNservice where NN is a number and service is the name of a service O Stop links are named KNNse
64. calculated by adding together the numeric values for the rwx permissions you don t want on new files and directories O This example has just 2 avoid world writable but turn everything else on E Other common umask values O 022 avoid world and group writable allow everything else O 027 avoid group writable and allow no permissions for anyone else E You normally want to put a call to umask in your shell s startup file 15 17 Exercises 1 a Find out what permissions are set on your home directory as a normal user Can other users access files inside it b If your home directory is only accessible to you then change the permissions to allow other people to read files inside it otherwise change it so that they can t c Check the permissions on bin and bin Is and satisfy yourself that they are reasonable d Check the permissions available on etc passwd and etc shadow e Write one command which would allow people to browse through your home directory and any subdi rectories inside it and read all the files Copyright 2004 GBdirect Ltd http training gbdirect co uk 75 Module 16 Create Partitions and Filesystems 16 1 Concepts Disks and Partitions E A hard disk provides a single large storage space E Usually split into partitions O Information about partitions is stored in the partition table O Linux defaults to using partition tables compatible with Microsoft Windows For compatibility with
65. cation n go to the following Next node p go to the preceding Prev node u go to the parent Up node O The Next Prev and Up destinations are shown at the top 23 16 Documentation in usr share doc E Some programs main or only documentation is not available as man or info pages E usr share doc contains other formats of documentation O Usually plain text O Sometimes HTML O Subdirectory per package such as usr share doc grep 2 4 E On many systems particularly older ones usr doc is used instead of usr share doc E On really awkward systems both directories exist and contain different documentation Copyright 2004 GBdirect Ltd http training gbdirect co uk 111 Linux System Administration Module 23 Use and Manage Local System Documentation 23 17 Contents of usr share doc Documentation in usr share doc is often information only relevant to system administration of a package not users of it O Installation instructions licence change log E Sometimes more user friendly documentation than elsewhere O For example usr share doc ImageMagick 4 2 9 ImageMagick html O HTML help is more common for interactive applications and very rare for traditional Unix commands O Programs ported from other platforms often have documentation in usr share doc rather than man pages 23 18 Interrogating Commands for Help E Some commands have no external documentation but have an
66. chain run concurrently E Use the vertical bar O Sometimes known as the pipe character E Programs don t need to do anything special to use pipes O They read from stdin and write to stdout as normal E For example pipe the output of echo into the program rev which reverses each line of its input echo Happy Birthday rev lyadhtriB yppaH Copyright 2004 GBdirect Ltd http training gbdirect co uk 40 Linux System Administration Module 6 Use Unix Streams Pipes and Redirects 6 6 Connecting Programs to Files E Redirection connects a program to a named file E The lt symbol indicates the file to read input from wc lt thesis txt O The file specified becomes the program s standard input E The gt symbol indicates the file to write output to who gt users txt O The program s standard output goes into the file O If the file already exists it is overwritten E Both can be used at the same time filter lt input file gt output file 6 7 Appending to Files E Use gt gt to append to a file date gt gt log txt O Appends the standard output of the program to the end of an existing file If the file doesn t already exist it is created 6 8 Redirecting Multiple Files E Open files have numbers called file descriptors E These can be used with redirection E The three standard files always have the same numbers Name Descriptor Standard input 0 Standard output 1 Standard error 2 C
67. ctories can be created E Monitoring and checking filesystems regularly can help prevent and correct problems like these 83 Linux System Administration Module 18 Maintain the Integrity of Filesystems 18 3 Monitoring Space df E Run df with no arguments to get a listing of free space on all mounted filesystems E Usually better to use the h option which displays space in human readable units df h Filesystem Size Used Avail Use Mounted on dev hda8 248M 52M 183M 22 dev hdal 15M 5 6M 9 1M 38 boot dev hda6 13G 5 06 7 4G 41 home dev hda5 136 4 66 7 8G 37 usr dev hda7 248M 125M 110M 53 var E The Use column shows what percentage of the filesystem is in use E You can give df directories as extra arguments to make it show space on the filesystems those directories are mounted on 18 4 Monitoring Inodes df E Filesystems rarely run out of inodes but it would be possible if the filesystem contains many small files E Run df i to get information on inode usage on all mounted filesystems df i Filesystem Inodes IUsed IFree IUse Mounted on dev hda8 65736 8411 57325 13 dev hdal 4160 30 4130 1 boot dev hda6 1733312 169727 1563585 10 home dev hda5 1733312 138626 1594686 8 usr dev hda7 65736 1324 64412 2 var E In this example every filesystem has used a smaller percentage of its inodes IUse than of its file space O This is a good sign Copyright 2004 GBdirect Ltd http trai
68. d http training gbdirect co uk 38 Module 6 Use Unix Streams Pipes and Redirects 6 1 Standard Files E Processes are connected to three standard files Standard input Program Standard Standard output error rmm AJ ji E Many programs open other files as well 6 2 Standard Input E Programs can read data from their standard input file E Abbreviated to stdin E By default this reads from the keyboard E Characters typed into an interactive program e g a text editor go to stdin 39 Linux System Administration Module 6 Use Unix Streams Pipes and Redirects 6 3 Standard Output E Programs can write data to their standard output file E Abbreviated to stdout E Used for a program s normal output E By default this is printed on the terminal Standard Error Programs can write data to their standard error output Standard error is similar to standard output but used for error and warning messages Abbreviated to stderr Useful to separate program output from any program errors EEHEEHE gt By default this is written to your terminal O So it gets mixed in with the standard output 6 5 Pipes E A pipe channels the output of one program to the input of another O Allows programs to be chained together O Programs in the
69. deletes characters in start set instead of translating them O s replaces sequences of identical characters with just one squeezes them 4 20 tr Examples E Replace all uppercase characters in input file with lowercase characters two alternatives cat input file tr A Z a z tr A Z a z lt input file E Delete all occurrences of z in story txt cat story txt tr d z E Run together each sequence of repeated f characters in lullaby txt to with just one tr s f lt lullaby txt 4 21 Modifying Files with sed E sed uses a simple script to process each line of a file E Specify the script file with f filename E Or give individual commands with e command E For example if you have a script called spelling sed which corrects your most common mistakes you can feed a file through it sed f spelling sed lt report txt gt corrected txt 4 22 Substituting with sed E Use the s pattern replacement command to substitute text matching the pattern with the replacement O Add the g modifier to replace every occurrence on each line rather than just the first one E For example replace thru with through sed e s thru through g input file gt output file E sed has more complicated facilities which allow commands to be executed conditionally Can be used as a very basic but unpleasantly difficult programming language Copyright 2004 GBdirect Ltd http training gbdirect co uk 30 Linux Syste
70. detecting duplicate programs or aliases which are hiding real programs E See help type for full details Copyright 2004 GBdirect Ltd http training gbdirect co uk 90 Linux System Administration Module 19 Find System Files and Place Files in the Correct Location 19 13 Checking for Shell Builtins with type E Some commands are built into the shell Examples include cd test pwd and ulimit E The Bash shell has a builtin called type which reports on whether a command is a builtin E For example to see whether the test command will run a shell builtin or a real program S type test E The example shows that test will run a shell builtin even though there is a real program with the same name E type will also identify shell aliases and functions 19 14 Updating the Locate Database E Use the updatedb program to refresh the database of files used by locate E Modern versions are configured by giving options to updatedb O e provides a list of directories which will not be searched O f gives the names of filesystem types to miss out O See the manpage for full details E updatedb is usually run by cron every night O Look in etc cron daily for the script which runs it 19 15 updatedb conf E Older versions of GNU updatedb used the configuration file etc updatedb conf For compatibility some modern versions still read it E The configuration is done by setting environment variables E For example to ignore certain filesys
71. disables all network interfaces and unmounts all filesystems E To safely reboot the system run reboot as root O Most systems also let you hit Ctr1 A1t Del on the console E Alternatively the shutdown command allows you to schedule the power down or reboot to give users warning to save their work O Halt at 6pm shutdown h 18 00 O Reboot thirty minutes from now shutdown r 30 22 5 Setting the Default Runlevel E The system s default runlevel on bootup is configured in etc inittab E To configure a default runlevel of 3 etc inittab should contain the line id 3 initdefault Ml There should be only one initdefault line in etc inittab Copyright 2004 GBdirect Ltd http training gbdirect co uk 102 Linux System Administration Module 22 Change Runlevels and Shutdown or Reboot System 22 6 Selecting a Different Runlevel at Bootup E Most bootloaders including LILO give you the ability to type in a kernel command line E Naming a runlevel on the kernel command line selects that runlevel for use on system startup E To start in single user mode linux 1 E To start in emergency mode linux b Emergency mode provides nothing beyond a shell to type into useful for repairing serious system corruption 22 7 Determining the Current Runlevel E The runlevel command prints the system s previous and current runlevels sbin runlevel N 3 E If there is no previous runlevel for example if the runlevel hasn t
72. e etc fstab file device mount point type options dump pass no dev hda3 ext 2 defaults iL dev hdal boot ext2 defaults 2 dev hda5 usr ext2 defaults 2 dev hdb1 usr local ext2 defaults 2 dev hdb2 home ext2 defaults 2 none proc proc defaults 0 0 dev scd0 mnt cdrom iso9660 noauto users ro 0 0 dev fd0 mnt floppy auto noauto users 0 0 Copyright 2004 GBdirect Ltd http training gbdirect co uk 80 Linux System Administration Module 17 Control Filesystem Mounting and Unmounting 17 7 Filesystem Types E The most common filesystem types are Type Usage ext2 The standard Linux filesystem iso9660 The filesystem used on CD ROMs proc Not a real filesystem so uses none as the device Used as a way for the kernel to report system information to user processes vfat The filesystem used by Windows 95 auto Not a real filesystem type Used as a way of asking the mount command to probe for various filesystem types particularly for removable media E Networked filesystems include nfs Unix specific and smbfs Windows or Samba E Other less common types exist see mount 8 17 8 Mount Options E Comma separated options in etc fstab E Alternatively use comma separated options with o on the mount command line Hi Common mount options Option Description noauto In etc fstab prevents the filesystem being mounted at bootup Useful for removable media ro Mount the filesystem read only users
73. e losing your changes in that one file but preserving your changes elsewhere Delete some files in your extracted copy Make tar discover which these are and re extract them from the archive without clobbering changes made to other files Produce a list of the names of all files under home which have been modified in the past day Only include regular files in this list Create a tarball containing all files under home changed modified in the past day Why is including directories in this list not sensible Create a tarball containing all files on the system that have changed in the past day and which are in directories you deem worthy of being backed up Set up acron job to make a daily incremental backup of the system E It should run at 18 00 every day E The files created should be stored under var tmp backup E Each day s backup should be in a file named with that day s date such as var tmp backup 2003 04 07 tgz Copyright 2004 GBdirect Ltd http training gbdirect co uk 136
74. e Files in the Correct Location 19 9 FHS Other Directories E etc contains configuration files E mnt is used to mount other filesystems temporarily O For example floppy discs are mounted on mnt floppy E boot contains files used by LILO to boot the system E dev contains device files which provide access to hardware devices such as disk drives or serial ports E tmp is used by many programs for temporary files E opt can contain packages of software from third parties i e not in the native package management format 19 10 FHS Other Directories E proc provides access to information from the kernel particularly about running processes E home contains directories which belong to each user O Use echo to find out where your home directory is E root is the home directory of the root user 19 11 Finding Programs with which E Searches for programs which can be run E Looks in the same directories as the shell O Determined by the PATH environment variable O Use echo PATH to see what directories are searched E For example to find out where gnumeric is which gnumeric E This is useful if different versions of the same program are installed in different places 19 12 The type Built in Command E type is like which but is built into the shell O It tells you about shell aliases and functions Not available in the C Shell E type p is just like which E type a shows all the commands of the name given O Useful for
75. e a unified filesystem O Any file on any disk drive or network share can be accessed through a name beginning with E The unified filesystem is made up of one or more individual filesystems branches of the unified hierarchy O Each individual filesystem has its own root O That root can be grafted onto any directory in the unified filesystem O The directory where an individual filesystem is grafted into the unified filesystem is the individual filesystem s mount point An individual filesystem lives on a physical device such as a disk drive though not necessarily on the same computer 61 Linux System Administration Module 12 Filesystem Concepts 12 3 File Types E Files directly contain data E Directories provide a hierarchy of files they can contain both files and other directories E Files and directories are both file types E Other file types exist including device special files O Device files provide a way of asking the kernel for access to a given physical device O The data that the device file seems to contain is actually the raw sequence of bytes or sectors on the device itself O Device files are by convention stored under the dev directory 12 4 Inodes and Directories E An inode is the data structure that describes a file on an individual filesystem E It contains information about the file including its type file directory device size modification time permissions etc E You can regard an in
76. e can be put into a file and vice versa E Programming features include variables loops including for and even shell functions E The Unix component approach makes it very easy to write shell scripts to perform fairly complex tasks Hi Common application domains for shell scripting include O Text processing O Automation of system administration tasks 11 12 Exercises Print out the following message SALE o p Try escaping the same string using single quotes double quotes and backslashes Echo the message quoting isn t simple escaping the spaces by putting single quotes around it e a Use the glob pattern to list all the hidden files in your home directory e To find out what shells are available on your system list the programs in bin whose names end in sh f Use brackets to list all the files in usr bin with names starting with a b or c Copyright 2004 GBdirect Ltd http training gbdirect co uk 60 Module 12 Filesystem Concepts 12 1 Filesystems E Some confusion surrounds the use of the term filesystem Hi Commonly used to refer to two distinct concepts 1 The hierarchy of directories and files which humans use to organise data on a system unified filesystem 2 The formatting system which the kernel uses to store blocks of data on physical media such as disks filesystem types 12 2 The Unified Filesystem E Unix and Linux systems hav
77. e new name already exists it is overwritten Copyright 2004 GBdirect Ltd http training gbdirect co uk 5 Linux System Administration Module 1 Introduction 1 15 Filename Completion E The shell can making typing filenames easier E Once an unambiguous prefix has been typed pressing Tab will automatically type the rest E For example after typing this rm sho pressing Tab may turn it into this rm shopping_list E This also works with command names O For example da may be completed to date if no other commands start da 1 16 Command History E Often it is desired to repeat a previously executed command E The shell keeps a command history for this purpose O Use the Up and Down cursor keys to scroll through the list of previous commands O Press Enter to execute the displayed command E Commands can also be edited before being run O Particularly useful for fixing a typo in the previous command O The Left and Right cursor keys navigate across a command O Extra characters can be typed at any point Backspace deletes characters to the left of the cursor Del and Ctr1 D delete characters to the right m Take care not to log out by holding down Ctr1 D too long 1 17 Exercises Log in o p Log out c Log in again Open a terminal window to start a shell o Exit from the shell the terminal window will close e Start another shell Enter each of the following commanas in turn M date
78. e place mail var log maillog 26 4 Reconfiguring syslog E If you change etc syslog conf you need to tell syslog to re read the configuration E Accomplished by sending the syslogd process a SIGHUP signal E The process id to send the signal to can be found with the pidof command kill HUP pidof sbin syslogd E Alternatively use the killall command to kill the syslogd process by name killall HUP sbin syslogd 26 5 Examining Logs less and grep E You sometimes need to manually scan log files for notable activity E Since logs are plain text you can use standard text processing tools like E To review the entire contents of a log file less var log messages Note you may need to be root to do this E To look for messages on a certain topic grep i sshd var log messages Looks for messages from sshd the Secure Shell server to examine them Copyright 2004 GBdirect Ltd http training gbdirect co uk 121 Linux System Administration Module 26 Configure and Use System Log Files 26 6 Examining Logs in Real Time tail E lt is sometimes useful to keep an eye on new messages arriving in a log file E The f option to tail will watch the file forever tail f var log messages E Continually updates the display as new messages are appended to the end of the file O Kill it with Ctr1 C when you re done 26 7 Log Rotation E syslog will normally allow log files to grow without bound O Until you run
79. e that the link count in the listing increases to 2 E The two names are now indistinguishable O Deleting or renaming one doesn t affect the other 13 7 Preserving Links E Commands that operate on files often take options to specify whether links are followed E The tar command notices when two files it s archiving are hard links to each other and stores that fact correctly E By default tar also stores symlinks in archives O Use the h option dereference to instead store the file pointed to E The cp command by default ignores both hard links and symlinks O Use the d option no dereference to preserve all links O Use the R option recursive when copying recursively to ensure that symlinks are preserved O The a option archive implies both d and R 13 8 Finding Symbolic Links to a File E The find command has a 1name option which searches for symbolic links containing some text find lname file printf p gt 1 n E This command prints the names and destinations of all symbolic links whose destination ends in file E Be aware that running find over the entire filesystem is very disk intensive Copyright 2004 GBdirect Ltd http training gbdirect co uk 65 Linux System Administration Module 13 Create and Change Hard and Symbolic Links 13 9 Finding Hard Links to a File E Hard links can be found by searching for directory entries with a given inode number E First identify the fi
80. eading genie eee ade eve Pot a wae A 7 8 EXOICISOS 6 fia ote Gh A ede FS ARA ik 8 Job Control 8 1 JOb Control ate 2 wet amp a BSG eA AE G oe So 8 2 JODS a A so case Lewes A te Gea oe pay ENR AE RB a ae A 8 3 EQ ral Be ise o s te Sa doa eh ele Ak Gh ed 8 4 Gh an a A de et hk Oe Gag GF Ge eae ae Syd 8 5 EX IrciS S or 2 5 20 aed Bohol Re a 9 Create Monitor and Kill Processes 9 1 WhatisaProcess 0 e o 9 2 Process Properties s s mue pia a 0 005002 e 9 3 Parent and Child Processes 0 9 4 Process Monitoring ps 2 e e e 9 5 ps Options i e een ee e ew be ew e ee 9 6 Process Monitoring pstree o eee eee Copyright 2004 GBdirect Ltd http training gbdirect co uk Linux System Administration Contents 9 7 patree Options tia a Soe aera Kahane E A Pe A Paes ek GS RS 51 9 8 Process Monitoring Op sis a ah eo Gedy ed ped bene ed Ard elder oia 51 9 9 top Command Line Options e e 52 9 10 top Interactive Commands 00000 ee ee 52 9 11 Signalling Processes uae hae eed tate A le hee date a a 52 9 12 Common Signals for Interactive Use 0 a 53 9 13 Sending Signals kill ee 53 9 14 Sending Signals to D mons pidof 02 200 ee 53 9 15 NEXGICISOS ha vm e et Sk ie A be aie fe gy i A et alin Ges tae oe a ee ed 53 10 Modify Process Execution Priorities 55
81. esolution description E Section number in brackets E Single line description from the NAME section Ml Useful for quickly discovering what a command does What is tac whatis tac E man f is equivalent to whatis 23 7 Printing Manual Pages E Manpages can be printed out in a nicely formatted way man t head gt head ps O Formats the manpage for head as PostScript and writes it to head ps in the current directory E Alternatively send the PostScript directly to a printer man t head lpr Copyright 2004 GBdirect Ltd http training gbdirect co uk 108 Linux System Administration Module 23 Use and Manage Local System Documentation 23 8 Searching for Manpages with apropos E To search for pages with a NAME section matching a particular keyword use apropos S apropos gif gif2t1ff 1 create a TIFF file from a GIF87 format image file giftopnm 1 convert a GIF file into a portable anymap ppmtogif 1 convert a portable pixmap into a GIF file Data Dumper 3 stringified perl data structures suitable for both printing and eval E Can t restrict the search to a particular section O But can grep the output apropos gif grep 1 Mi man k is equivalent to apropos 23 9 Displaying All Manpages of a Particular Name with man a E To display all pages which have a particular name regardless of their section use man a man a hostname O Displays hostname 1 O Waits for you to quit O
82. ewind go to the start of the tape O offline eject the tape Copyright 2004 GBdirect Ltd http training gbdirect co uk 134 Linux System Administration Module 28 Maintain an Effective Data Backup Strategy 28 12 Deciding What to Backup E Being selective about what is included in the backups can drastically reduce the time and space taken E For example bin sbin lib and usr could be restored from an installation CD O But it might still be worth backing them up to make restoration simpler E The things which are most likely to be important in backups are O home O The CVS repository or other places where project work is stored Some directories under var particularly email 28 13 What Not to Backup E Some other areas which shouldn t be backed up are O tmp usually doesn t contain anything of lasting value O proc automatically generated by the kernel O dev if using devfs this is also generated automatically O mnt some media mounted here like CD ROMS typically aren t backed up O Filesystems mounted remotely whose backup is taken care of elsewhere 28 14 Scripting Backup E lt is common to have a script to perform backups each night O Might perform different types of backup e g a full backup on Saturday night and a differential one on other nights E Such a script can be run with cron making backup automatic E Example scripts are readily available on the WWW 28 15 Other Backup
83. f device files E Each device group has number with the first drive numbered O E These are the most commonly used devices O dev stO SCSI tape drive which will be automatically rewound after each operation O dev nst0 the same drive but with no automatic rewinding O dev ftO floppy tape drive O dev nftO the same without rewinding O dev ht0 ATAPI tape drive O dev nhtO the same without rewinding 28 10 Using tar for Backups E Tape drive devices can be read and written directly by tar E To write a backup of home to the first SCSI tape drive tar cvf dev st0 home E We haven t used compression the z option O This might make the backup slower at least on less powerful machines Compressing the whole archive would make it much less resilient against corruption E Inthe example the auto rewinding device is used so the tape will be rewound after tar is finished and the archive can be extracted tar xvf dev st0 tmp restored home 28 11 Controlling Tape Drives with mt E mt can move tapes backwards and forwards and perform other operations on them E Usage mt f device command count E The f option sets the tape device to use e g dev st0 O The default is usually dev tape which should be a symlink to a non rewinding device like dev nstO E These are some of the more common commands O fsf bsfm move forwards and backwards one or count files O eod go to the end of the valid data O r
84. for a network E Usually programs email and home directories are all shareable E Log files and machine specific configuration files are not shareable 19 4 Static and Dynamic Data E Some files hardly ever need to be changed while others change all the time E It can help to store static files separately from those which regularly change O The static files can be on a partition mounted read only such as a CD ROM E Programs and libraries are usually static except when new software is installed E Home directories and status files are usually more variable 19 5 Overview of the FHS bin boot ot contains essential files needed to boot the system lib mnt opt sbin tmp usr bin include info lib local bin sbin and so on man sbin share var usr contains other packaged software usr local contains non packaged software Copyright 2004 GBdirect Ltd http training gbdirect co uk 88 Linux System Administration Module 19 Find System Files and Place Files in the Correct Location 19 6 FHS Installed Software E Programs are usually found in the bin and sbin directories These are found in usr and usr local E sbinis used for programs likely to be useful to system administrators rather than to general users mail deemon web server etc E These directories are named after binaries Most programs in them are binaries compiled programs although s
85. h extensions c Find out what the find criterion iname does Copyright 2004 GBdirect Ltd http training gbdirect co uk 23 Module 4 Process Text Streams Using Text Processing Filters 4 1 Working with Text Files E Unix like systems are designed to manipulate text very well E The same techniques can be used with plain text or text based formats O Most Unix configuration files are plain text E Text is usually in the ASCII character set O Non English text might use the ISO 8859 character sets 0 Unicode is better but unfortunately many Linux command line utilities don t directly support it yet 4 2 Lines of Text E Text files are naturally divided into lines E In Linux a line ends in a line feed character O Character number 10 hexadecimal Ox0A E Other operating systems use different combinations O Windows and DOS use a carriage return followed by a line feed O Macintosh systems use only a carriage return O Programs are available to convert between the various formats 24 Linux System Administration Module 4 Process Text Streams Using Text Processing Filters 4 3 Filtering Text and Piping The Unix philosophy use small programs and link them together as needed Each tool should be good at one specific job Join programs together with pipes Indicated with the pipe character O The first program prints text to its standard output O That gets fed into the second program s standard input For example
86. had run out of disk space E Grace periods are set per filesystem 93 Linux System Administration Module 20 Set and View Disk Quotas 20 3 Per User and Per Group Quotas E Most quotas are set per user Each user has his or her own soft limit and hard limit E Quotas can also be set per group O A group can be given a soft limit and hard limit E Group quotas apply to all users in a group E If a group hard limit has been reached no user in the group may use more space O Including users who have not yet reached their individual quota 20 4 Block and Inode Limits E Quotas can be set for blocks O Limits the amount of data space that may be used E Quotas can also be set for inodes O Limits the number of files that may be created 20 5 Displaying Quota Limits quota E The quota command displays quota limits E Specifying a username or the name of a group will show information about their quotas quota fred E The v option will show full information about all quotas even where there are no limits 20 6 Options in etc fstab E The options in etc fstab specify which filesystems should have quota enabled O Add the option usrquota to enable user quotas O Use grpquota to enable group quotas O Either or both can be used for each filesystem dev hdal ext2 defaults dev hdb1 home ext2 defaults usrquota dev hdb2 work shared ext2 defaults usrquota grpquota E The filesystems with quota enabled should have files called quot
87. hash E Environment variables can be set PATH usr local bin E Example cron job specification 30 9 root usr local bin check_logins O At 09 30 O On all days O For the root user O Run the command usr local bin check_logins Copyright 2004 GBdirect Ltd http training gbdirect co uk 127 Linux System Administration Module 27 Automate and Schedule System Administration Tasks 27 11 Crontab Date amp Time Specification E Order of the date and time fields O Minute 0 59 O Hour 0 23 O Day of the month 1 31 O Month 1 12 O Day of the week 0 7 0 and 7 are Sunday E Note Fields almost in ascending order E The command is run when the fields match the current time E A field containing an asterisk always matches E Three letter abbreviations can be used for month and day names Run every Friday night at 17 30 30 17 Fri root usr local bin weekly backup 27 12 More Complex Crontab Dates amp Times E A list of alternative values for a field are specified by commas Run at 15 and 45 past each hour 15 45 httpd usr local bin generate stats pag E A range is specified with a hyphen Run every half hour 09 15 17 45 Mon Fri 15 45 9 17 1 5 root usr local bin check faxes E Numbers rather than names must be used for months and days in lists and ranges A step through a range is specified with a slash Run every two hours 08 30 18 30 Mon Fri 30 8 18 2 1 5 root usr loc
88. he file logfile txt E As for chown specify any number of files or directories E The superuser may change the group ownership of any file to any group E The owner of a file may change its group ownership O But only to a group of which the owner is a member 14 5 Changing the Ownership of a Directory and Its Contents E A common requirement is to change the ownership of a directory and its contents E Both chown and chgrp accept a R option chgrp R staff shared directory E Mnemonic recursive E Changes the group ownership of shared directory to staff O And its contents O And its subdirectories recursively E Changing user ownership superuser only chown R root usr local share misc Copyright 2004 GBdirect Ltd http training gbdirect co uk 68 Linux System Administration Module 14 Manage File Ownership 14 6 Changing Ownership and Group Ownership Simultaneously Mi The chown command can change the user owner and group owner of a file simultaneously chown aaronc www docs public_html interesting html E Changes the user owner to aaronc and the group owner to www docs E Can use the R option as normal E A dot may be used instead of a colon chown R aaronc www docs www intranet people aaronc 14 7 Exercises 1 a Find out who owns the file bin ls and who owns your home directory in home b Log on as root and create an empty file with touch The user and group owners should be root
89. he form string replacement replaces the first occurrence of string with replacement in the previous command and runs it echo SHOTSNAME TS ST echo HOSTNAME tiger Copyright 2004 GBdirect Ltd http training gbdirect co uk 20 Linux System Administration Module 3 Work Effectively on the Unix Command Line 3 14 Summary of Bash Editing Keys E These are the basic editing commands by default O Right move cursor to the right Left move cursor to the left Up previous history line Down next history line Ctr1 A move to start of line Ctr1 E move to end of line O Ctr1 D delete current character E There are alternative keys as for the Emacs editor which can be more comfortable to use than the cursor keys E There are other less often used keys which are documented in the bash man page section Readline 3 15 Combining Commands on One Line E You can write multiple commands on one line by separating them with E Useful when the first command might take a long time time consuming program ls E Alternatively use amp amp to arrange for subsequent commands to run only if earlier ones succeeded time consuming potentially failing program amp amp ls 3 16 Repeating Commands with for Hi Commands can be repeated several times using for O Structure for varname in list do commands done E For example to rename all txt files to txt old for file in
90. he time unit when doing edquota t Copyright 2004 GBdirect Ltd http training gbdirect co uk 95 Linux System Administration Module 20 Set and View Disk Quotas 20 10 repquota E The repquota command prints information about the quota limits assigned to each user O Also shows actual number of blocks and inodes used E Use the a option for information on all filesystems or specify the filesystem on the command line E Use g to show group quotas E Use v for more complete information Copyright 2004 GBdirect Ltd http training gbdirect co uk 96 Module 21 Boot the System 21 1 Boot Loaders E When Linux boots the kernel is loaded into memory by a boot loader E Passes parameters to the Linux kernel E Allows one of several operating systems to be loaded O Multiple versions of the Linux kernel O Dual booting with Windows and other OSes E The most popular boot loader is LILO the Linux loader O Full user documentation provided E Look for the a directory called something like usr share doc lilo or usr doc lilo 0 21 m The user guide is in a file called user ps or User_Guide ps 21 2 LILO E LILO runs when the system is booted E The lilo command configures how LILO will next run E The file etc lilo conf specifies the configuration to be set by the 1i1o command O Need to run the 1i1o command for changes to have affect Manual page lilo conf 5 E lilo conf has options in the form name value E Options f
91. hidden files O Use ls A in your home directory to find them O Hidden files have names which start with O Often such files have names ending in rc for run commands for example the Vim editor uses vimrc E Sometimes whole directories of configuration information are present in a home directory for example kde and gnome 25 2 Shell Configuration Files E Bash reads Y bashrc whenever it starts as an interactive shell O That file often sources a global file for example if f etc bashre then etc bashre fi E Bash also reads a profile file if it is a login shell O First it reads the global configuration from etc profile O Then one of Y bash_profile bash_login or 7 profile E Login shells also source 7 bash_logout when the user exits 117 Linux System Administration Module 25 Tune the User Environment and System Environment Variables 25 3 Changing Environment Variables E The value of an environment variable can be set on the command line or in a configuration file as follows export VARIABLE VALUE E To see the current value of a variable echo SVARIABLE E The shell searches for programs to run in a list of directories in the variable PATH which are separated by the character O If you want to run programs which aren t in bin or usr bin then you might want to add them to your PATH for example export PATH SPATH usr local bin usr games E Some other variables
92. ide range of topics O General overviews of topic areas such as Printing HOWTO O Detailed instruction of very specific tasks such as Bash Prompt HOWTO O Information for particular groups of users such as Belgian HOWTO E Various authors E Varying quality 114 Linux System Administration Module 24 Find Linux Documentation on the Internet 24 3 Obtaining HOWTOs E HOWTOs are written in a special mark up language which enables them easily to be produced in several formats O HTML O Plain text O PostScript O PDF Acrobat E Some formats may be installed in usr share doc HOWTOs E They are all on the LDP website Good They are all clearly dated so you can see how recent their advice is O Bad A number of them haven t been updated for several years 24 4 Vendor and Application Specific Web Sites E Unsurprisingly particular programs often have their own web presence O Less http www greenwoodsoftware com less O The Gimp http www gimp org E Linux distributions also have their own websites O Debian http www uk debian org O Red Hat http www redhat com O SuSE http www suse co uk Mandrake http www linux mandrake com E May have specific mailing lists or web based forums 24 5 Usenet Newsgroups E There are many usenet newsgroups related to Linux E The international groups are divided by topic O comp os linux setup 0 comp os linux help 0 comp os linux hardware E Search the archives for answer
93. ign is used E The text in the file is displayed immediately O Starting on the line after the command O Before the next shell prompt Copyright 2004 GBdirect Ltd http training gbdirect co uk 4 Linux System Administration Module 1 Introduction 1 12 Deleting Files with rm E To delete a file use the rm remove command E Simply pass the name of the file to be deleted as an argument rm shopping_list E The file and its contents are removed O There is no recycle bin O There is no unrm command E The 1s command can be used to confirm the deletion 1 13 Unix Command Feedback E Typically succesful commands do not give any output E Messages are displayed in the case of errors E The rm command is typical O lf it manages to delete the specified file it does so silently O There is no File shopping_list has been removed message O But if the command fails for whatever reason a message is displayed E The silence can be be off putting for beginners E itis standard behaviour and doesn t take long to get used to 1 14 Copying and Renaming Files with cp and mv E To copy the contents of a file into another file use the cp commana cp CV pdf old CV pdf E To rename a file use the mv move command mv commitee_minutes txt committee_minutes txt O Similar to using cp then rm E For both commands the existing name is specified as the first argument and the new name as the second O Ifa file with th
94. in a terminal Hang up Sent by the kernel when you log out or disconnect a modem Conventionally used by many deemons as an instruction to re read a configuration file 9 13 Sending Signals ki11 Mi The kill command is used to send a signal to a process O Not just to terminate a running process E itis a normal executable command but many shells also provide it as a built in E Use kill HUP pidorkill s HUP pid to send a SIGHUP to the process with that pid E If you miss out the signal name ki11 will send a SIGTERM E You can specify more than one pid to signal all those processes 9 14 Sending Signals to Demons pidof E On Unix systems long lived processes that provide some service are often referred to as dzemons Deemons typically have a configuration file usually under etc which affects their behaviour Many deemons read their configuration file only at startup If the configuration changes you have to explicitly tell the d mon by sending it a SIGHUP signal You can sometimes use pidof to find the dzemon s pid for example to tell the inetd d mon to reload its configuration run kill HUP pidof usr sbin inetd as root 9 15 Exercises 1 a Use top to show the processes running on your machine Copyright 2004 GBdirect Ltd http training gbdirect co uk 53 Linux System Administration Module 9 Create Monitor and Kill Processes b Make top sort by memory usage so that the most memo
95. in specified directories recursively O 1 prints just the names of files which contain matching lines O c prints the count of matches in each file O n numbers the matching lines in the output O v reverses the test printing lines which don t match 7 2 Pattern Matching E Use grep to find patterns as well as simple strings E Patterns are expressed as regular expressions E Certain punctuation characters have special meanings E For example this might be a better way to search for Nancy s entry in the password file ra grep nancy etc passwd O The caret anchors the pattern to the start of the line E In the same way acts as an anchor when it appears at the end of a string making the pattern match only at the end of a line 44 Linux System Administration Module 7 Search Text Files Using Regular Expressions 7 3 Matching Repeated Patterns Some regexp special characters are also special to the shell and so need to be protected with quotes or backslashes We can match a repeating pattern by adding a modifier grep i continued Dot on its own would match any character so to match an actual dot we escape it with The modifier matches the preceding character zero or more times Similarly the modifier matches one or more times Matching Alternative Patterns Multiple subpatterns can be provided as alternatives separated with for example grep fish chips pies food txt The
96. ion which accepts times in a more flexible format E For example change the time stamp on homework to January 20 2001 5 59p m touch t 200101201759 homework 5 16 Exercises o p o a S o po Use cd to go to your home directory and create a new directory there called dog Create another directory within that one called cat and another within that called mouse Remove all three directories You can either remove them one at a time or all at once If you can delete directories with rm r what is the point of using rmdir for empty directories Try creating the dog cat mouse directory structure with a single command Copy the file etc oasswd to your home directory and then use cat to see what s in it Rename it to users using the mv command Make a directory called programs and copy everything from bin into it Delete all the files in the programs directory Delete the empty programs directory and the users file The touch command can be used to create new empty files Try that now picking a name for the new file touch baked beans Get details about the file using the 1s command ls 1 baked beans Wait for a minute and then try the previous two steps again and see what changes What happens when we don t specify a time to touch Try setting the timestamp on the file to a value in the future When you re finished with it delete the file Copyright 2004 GBdirect Lt
97. is the same file as foo 2 7 Using Dot Directories in Paths E The special and directories can be used in paths just like any other directory name ed other dir O Meaning the directory other dir in the parent directory of the current directory E itis common to see used to go back several directories from the current directory Is far away directory E The directory is most commonly used on its own to mean the current directory 2 8 Hidden Files E The special and directories don t show up when you do 1s O They are hidden files E Simple rule files whose names start with are considered hidden E Make 1s display all files even the hidden ones by giving it the a all option ls a bashre profile report doc E Hidden files are often used for configuration files Usually found in a user s home directory E You can still read hidden files they just don t get listed by 1s by default Copyright 2004 GBdirect Ltd http training gbdirect co uk 10 Linux System Administration Module 2 Getting Started 2 9 Paths to Home Directories Ml The symbol tilde is an abbreviation for your home directory O So for user fred the following are equivalent ed home fred documents ed documents E The is expanded by the shell so programs only see the complete path E You can get the paths to other users home directories using for example cat
98. its 2 0000 ee 94 20 5 Displaying Quota Limits quota ee 94 20 6 Options in ete stade rs ig Se eta Be Bee A Ge ae a a a de Ie otek ke 94 20 7 Enabling QUOA quotaon ease gear ee aa eeu ae at a eee ART RR A fae WO 95 20 8 Changing Quota Limits setquota ee 95 20 9 CAQUICA aa a Ghee ft ee e GP bos 95 ZOO PEW GUOES i vite rh pte Ge those ee God a Wd amp del de dete Gy Bw en he me eR a die Pad w Ue by dower ti 96 21 Boot the System 97 21 Boot Loaders Te wt G2 Behe Go a ee Pe eee E AA AAA 97 a E E E O 2 0000 A at A ete eet RARE at eae te a Ge ie Reco chert dae Bee 97 21 3 Sample HHo confiFilO coc ic ee a a a ee A di be Gl 98 21 4 SelectingWhatto Boot 0 0 0 aiy R a ERE a GER DS A A PLR oa DE a 98 21 5 Other Ways of Starting Linux 2 aa a e 98 21 6 Specifying Kernel Parameters a 99 21 7 Specifying Kernel Parameters in lilo conf ooa a 99 21 8 Useful Kernel Parameters a 99 21 9 Boot Messages 2060 held e eae Baca ae ho oe a Gal pa 99 21 10 Kernel Modules 00000 be ee 100 2111 EXOICISOS heaped ee phate he E heen tate A E EME NE IE EG 100 22 Change Runlevels and Shutdown or Reboot System 101 Copyright 2004 GBdirect Ltd http training gbdirect co uk viii Linux System Administration Contents 22 1 Understanding Runlevels 2 2 e 101 22 2 Typical Runlevels ima rae ee Sh ets a ene SORE ee key G
99. k html E Linux Partition HOWTO http www linuxdoc org HOWTO mini Partition E Table of fdisk commands and partition types http wwwinfo cern ch pdp as linux fdisk index html Copyright 2004 GBdirect Ltd http training gbdirect co uk 78 Module 17 Control Filesystem Mounting and Unmounting 17 1 Mounting Filesystems As far as many parts of a Linux system are concerned a partition contains entirely arbitrary data When installing you set things up so that a partition contains a filesystem a way of organising data into files and directories One filesystem is made the root filesystem the root directory on that filesystem becomes the directory named Other filesystems can be mounted the root directory of that filesystem is grafted onto a directory of the root filesystem O This arranges for every file in every mounted filesystem to be accessible from a single unified name space The directory grafted onto is called the mount point 17 2 Mounting a Filesystem mount Important filesystems are mounted at boot up other filesystems can be mounted or unmounted at any time The mount command mounts a filesystem O You usually need to have root permission to mount a filesystem mount makes it easy to mount filesystems configured by the system administrator For example many systems are configured so that mount mnt cdrom will mount the contents of the machine s CD ROM drive under the directory mnt cdrom
100. ler explanation of the command O OPTIONS O FILES any files the command needs O ENVIRONMENT pertinent environment variables O BUGS O AUTHOR O SEE ALSO 23 4 Sections of the Manual E Each manpage is in a section of the manual E User commands are in section 1 E Different sections can contain pages of the same name O The passwd page in section 1 describes the passwd command O The passwd page in section 5 describes the etc passwd file O These are often referred to as passwd 1 and passwa 5 E A page can be requested from a particular section by specifying its number man 1 passwd man 5 passwd Copyright 2004 GBdirect Ltd http training gbdirect co uk 107 Linux System Administration Module 23 Use and Manage Local System Documentation 23 5 Manual Section Numbering Hi Most commands are documented in section 1 O This is the first place man looks So the passwd command s manpage can also be viewed with man passwd E Other sections you may need O Some system administration commands are in section 8 O File formats are in section 5 O Miscellany is in section 7 E A complete list of sections is in man 7 E Each section has an introduction page called intro man 8 intro 23 6 Determining Available Manpages with whatis E The whatis command lists manpages with the specified name whatis hostname hostname 1 show or set the system s host name hostname 7 host name r
101. lesystem and inode number of the file you re interested in df module dtd Filesystem 1k blocks Used Available Use Mounted on dev sdb3 13647416 5241196 7712972 40 home ls i module dtd 245713 module dtd E Then use find s inum option to look for directory entries in that filesystem with that inode number find home xdev inum 245713 E The xdev option prevents find from recursing down into other filesystems 13 10 Exercises 1 a Make a temporary directory and change into it b Make some test files as follows echo oranges and lemons gt fruit 5 echo spuds gt veg Make a symbolic link called starch to the veg file a eo Make a hard link called citrus to the appropriate file and check that it has the same inode number e Delete the original fruit file and check that citrus still contains the text f Delete the original veg file and try to look at the contents of starch Use 1s to check the symlink 2 a Try to see what the following loop does and then create some htm files and try it for htm in htm do gt ln s htm htm 1 gt done b Make a symlink called dir to a directory such as etc c Try the following commands to display the link and compare the results ls 1 dir ls 1 dir Copyright 2004 GBdirect Ltd http training gbdirect co uk 66 Module 14 Manage File Ownership 14 1 Users and Groups E Anyone using a Linux computer is a user Ml The system keeps t
102. m Administration Module 4 Process Text Streams Using Text Processing Filters 4 23 Put Files Side by Side with paste E paste takes lines from two or more files and puts them in columns of the output E Use d char to set the delimiter between fields in the output O The default is tab O Giving d more than one character sets different delimiters between each pair of columns E Example assign passwords to users separating them with a colon paste d usernames passwords gt htpasswd 4 24 Performing Database Joins with join E Does a database style inner join on two tables stored in text files E The t option sets the field delimiter O By default fields are separated by any number of spaces or tabs E Example show details of suppliers and their products join suppliers txt products txt less E The input files must be sorted E This command is rarely used databases have this facility built in 4 25 Exercises 1 a Type in the example on the cut slide to display a list of users logged in Try just who on its own first to see what is happening b Arrange for the list of usernames in who s output to be sorted and remove any duplicates c Try the command last to display a record of login sessions and then try reversing it with tac Which is more useful What if you pipe the output into 1ess d Use sed to correct the misspelling enviroment to environment Use it on a test file containing a few lines
103. mediate part of a path to a file E The difference between read and execute on directories is specious having one but not the other is almost never what you want 70 Linux System Administration Module 15 Use File Permissions to Control Access to Files 15 3 Basic Concepts Permissions for Different Groups of People E As well as having different types of permission we can apply different sets of permissions to different sets of people E A file or directory has an owner and a group owner E The r w x permissions are specified separately for the owner for the group owner and for everyone else the world 15 4 Examining Permissions 1s 1 Mi The 1s 1 command allows you to look at the permissions on a file ls 1 drwxr x 9 aaronc staff 4096 Oct 12 12 57 accounts rw rw r 1 aaronc staff 11170 Dec 9 14 11 report txt The third and fourth columns are the owner and group owner E The first column is the permissions O One character for the file type d for directories for plain files O Three characters of rwx permissions for the owner or a dash if the permission isn t available O Three characters of rwx permissions for the group owner Three characters of rwx permissions for everyone else 15 5 Preserving Permissions When Copying Files E By default the cp command makes no attempt to preserve permissions and other attributes like timestamps E You can use the p option to preserve permissions and timest
104. n a Dos program which can start Linux from within Dos O Occasionally used to start Linux after a Dos driver has configured some hardware Copyright 2004 GBdirect Ltd http training gbdirect co uk 98 Linux System Administration Module 21 Boot the System 21 6 Specifying Kernel Parameters E Linux kernels take parameters which affect how they run E Parameters can be specified at boot time O Atthe LILO prompt O After the image label LILO linux 2 2 20 root dev hda3 Specifies the root filesystem E Details of parameters are in BootPrompt HOWTO 21 7 Specifying Kernel Parameters in ilo conf E Kernel parameters can also be specified in lilo conf O Sensible to test first at the LILO prompt E Common parameters have lilo conf option names E Any parameter can be set with the append option image vmlinuz 2 2 0 label linux 2 2 20 root dev hda3 append hdc ide scsi 21 8 Useful Kernel Parameters E root device set the filesystem to mount as root E ro and rw mount the root filesystem read only or read write respectively O Usually this should be read only in lilo conf to allow fscks E nfsroot server use a network filesystem as root e g in a diskless workstation E init program the name of the first program the kernel will run which is usually sbin init Can be set to bin sh if starting with init is broken E There are many other parameters to configure specific hardware devices 21 9
105. n command O Choose whether to make a primary extended or logical partition O Choose which number to assign it E fdisk asks where to put the start and end of the partition O The default values make the partition as big as possible The desired size can be specified in megabytes e g 250M E Changes to the partition table are only written when the w command is given 16 5 Changing Partition Types E Each partition has a type code which is a number E The fdisk command 1 shows a list of known types E The command t changes the type of an existing partition Enter the type code at the prompt E Linux partitions are usually of type Linux native type 83 E Other operating systems might use other types of partition many of which can be understood by Linux Copyright 2004 GBdirect Ltd http training gbdirect co uk 77 Linux System Administration Module 16 Create Partitions and Filesystems 16 6 Making Filesystems with mkfs E The mkfs command initializes a filesystem on a new partition O Warning any old data on the partition will be lost O For example to make an ext 2 filesystem on dev hda2 mkfs t ext2 c dev hda2 O t sets the filesystem type to make and c checks for bad blocks on the disk Mi mkfs uses other programs to make specific types of filesystem such as mke2fs and mkdosfs 16 7 Useful Websites E Tutorial on making partitions http www linuxnewbie org nhf intel installation fdisk_nhf Fdis
106. n its own will expand to all the files in the current directory 5 rm O All the files that is except the hidden ones E Names with wildcards in are called globs and the process of expanding them is called globbing 2 15 Chaining Programs Together E The who command lists the users currently logged in E The wc command counts bytes words and lines in its input E We combine them to count how many users are logged in who we 1 E The symbol makes a pipe between the two programs O The output of who is fed into wc E The 1 option makes wc print only the number of lines E Another example to join all the text files together and count the words lines and characters in the result cat txt we 2 16 Graphical and Text Interfaces Hi Most modern desktop Linux systems provide a graphical user interface GUI E Linux systems use the X window system to provide graphics O X is just another program not built into Linux O Usually X is started automatically when the computer boots E Linux can be used without a GUI just using a command line Mi Use Ctrl1 A1t F1 to switch to a text console logging in works as it does in X O Use Ctrl A1t F2 Ctrl Alt F3 etc to switch between virtual terminals usually about 6 are provided O Use Ctrl1 A1t F7 or whatever is after the virtual terminals to switch back to X Copyright 2004 GBdirect Ltd http training gbdirect co uk 13 Linux System Administration Module 2 Getti
107. nfigured properly and find out what its mount point is set to c Mount a floppy disk at the default mount point d Copy a file onto the floppy disk Does Linux write it immediately Unmount the floppy to ensure that everything on it is properly written and it is safe to remove e Try the commands on the last slide to mount a file and try copying some files into it Try using the df command to see how much space is available in the file Unmount mnt disk as you would any other filesystem Copyright 2004 GBdirect Ltd http training gbdirect co uk 82 Module 18 Maintain the Integrity of Filesystems 18 1 Filesystem Concepts E The files stored on a disk partition are organised into a filesystem E There are several filesystem types the common Linux one is called ext2 E A filesystem contains a fixed number of inodes O An inode is the data structure that describes a file on disk O It contains information about the file including its type file directory device modification time permissions etc E A file name refers to an inode not to the file directly O This allows hard links many file names referring to the same inode 18 2 Potential Problems E Over time an active filesystem can develop problems O lt can fill up causing individual programs or even the entire system to fail O it can become corrupted perhaps due to a power failure or a system crash O lt can run out of space for inodes so no new files or dire
108. ng Started 2 17 Text Editors E Text editors are for editing plain text files O Don t provide advanced formatting like word processors O Extremely important manipulating text is Unix s raison d tre E The most popular editors are Emacs and Vim both of which are very sophisticated but take time to learn E Simpler editors include Nano Pico Kedit and Gnotepad E Some programs run a text editor for you 2 18 O They use the SEDITOR variable to decide which editor to use O Usually it is set to vi but it can be changed O Another example of the component philosophy Exercises Use the pwd command to find out what directory you are in If you are not in your home directory home USERNAME then use cd without any arguments to go there and do pwd again Use cd to visit the root directory and list the files there You should see home among the list Change into the directory called home and again list the files present There should be one directory for each user including the user you are logged in as you can use whoami to check that Change into your home directory to confirm that you have gotten back to where you started Create a text file in your home directory called shakespeare containing the following text Shall I compare thee to a summer s day Thou art more lovely and more temperate Rename it to sonnet 18 txt Make a new directory in your home directory called poetry Move
109. ning gbdirect co uk 84 Linux System Administration Module 18 Maintain the Integrity of Filesystems 18 5 Monitoring Disk Usage du E af shows a summary of the free space on a partition E du on the other hand shows information about disk space used in a directory tree E Takes one or more directories on the command line du usr share vim 2156 2460 36 16 16 40 20 156 100 5036 5040 18 6 du Options Option Description usr share vi usr share vi usr share vi usr share vi usr share vi usr share vi usr share vi usr share vi usr share vi usr share vi usr share vi vim vim vin vin vim vim vin vin vin vim 58 doc 58 syntax 58 tutor 58 macros hanoi 58 macros life 58 macros maze 58 macros urm 58 macros 58 tools 58 Show all files not just directories Print a cumulative total for all directories named on the command line Print disk usage in human readable units Print only a summary for each directory named on the command line Make the size reported for a directory be the size of only the files in that directory not the total including the sizes of its subdirectories 18 7 Finding and Repairing Filesystem Corruption fsck E Sometimes filesystems do become corrupted Perhaps there was a power failure Or maybe your kernel version has a bug in it E The fsck program checks the integrity of a filesystem O And can make repairs if necessary E
110. ns Load the default b Reboot again This time pass the parameter init bin sh to the kernel What happens Ml Which directory are you in Ml What s the output of the hostname command E Can you create a new file Exit the shell and reboot again 3 Make a backup of lilo conf then add a new section at the end of the original E Copy the options for the default kernel E Change the label to shell and remove any aliases E Set the first program run by the kernel to bin sh Make the change live then reboot and test it Put things back afterwards Copyright 2004 GBdirect Ltd http training gbdirect co uk 100 Module 22 Change Runlevels and Shutdown or Reboot System 22 1 Understanding Runlevels E A Linux system runs in one of several runlevels modes providing different features and levels of functionality E Linux systems normally have seven runlevels numbered from 0 6 O Three are mandatory 0 halt 6 reboot 1 single user O Four are user defined 2 5 E No consensus between administrators or distributions about how to organise the user defined runlevels Some rely partly on runlevels to define which major subsystems are running O Others prefer the flexibility of starting and stopping subsystems individually without changing runlevel O In every common distribution there is at least one user defined runlevel which has the same services as another 22 2 Typical Runlevels Runlevel Description
111. o delete several files at once rm oldnotes txt tmp txt stuff doc O To make several directories in one go mkdir Accounts Reports E The original use of cat was to join multiple files together O For example to list two files one after another cat notes txt morenotes txt E Ifa filename contains spaces or characters which are interpreted by the shell such as put single quotes around them rm Beatles Strawberry Fields mp3 cat important notes txt 2 13 Finding Documentation for Programs E Use the man command to read the manual for a program E The manual for a program is called its man page O Other things like file formats and library functions also have man pages E To read a man page specify the name of the program to man man mkdir E To quit from the man page viewer press q E Man pages for programs usually have the following information O A description of what it does O A list of options it accepts O Other information such as the name of the author Copyright 2004 GBdirect Ltd http training gbdirect co uk Linux System Administration Module 2 Getting Started 2 14 Specifying Files with Wildcards E Use the wildcard to specify multiple filenames to a program ls 1 txt rw rw r 1 fred users 108 Nov 16 13 06 report txt rw rw r 1 fred users 345 Jan 18 08 56 notes txt E The shell expands the wildcard and passes the full list of files to the program E Just using o
112. ode as being the file itself E The inodes within an individual filesystem are numbered O An inode number is sometimes called an inum E Note that a file s name is stored not in its inode but in a directory O A directory is stored on disk as a list of file and directory names Each name has an inode number associated with it O Separating names from inodes means that you can have multiple directory entries referring to the same file Copyright 2004 GBdirect Ltd http training gbdirect co uk 62 Module 13 Create and Change Hard and Symbolic Links 13 1 Symbolic Links A symbolic link or symlink is a pseudo file which behaves as an alternative name for some other file or directory The contents of the symlink are the real name pointed to When you try to use a file name including a symlink the kernel replaces the symlink component with its contents and starts again Symlinks allow you to keep a file or directory in one place but pretend it lives in another O For example to ensure that an obsolete name continues to work for older software O Or to spread data from a single filesystem hierarchy over multiple disk partitions 13 2 Examining and Creating Symbolic Links ls 1 shows where a symbolic link points to ls l usr tmp lrwxrwxrwx 1 root root 30 Sep 26 2000 usr tmp gt var tmp 1s can also be made to list symlinks in a different colour to other files or to suffix their names with
113. ome are human readable scripts E Libraries are stored in directories called ib found in the same places as bin O These directories should be listed in etc ld so conf 19 7 FHS Other Directories Under usr E usr include contains header files used by C C programs E usr X11R6 contains files used by the X Window system including programs libraries configuration files and documentation E usr local is where software is installed when it is compiled from source code rather than installed as a package E usr share contains files which are not specific to the architecture of a machine e g fonts and icons O Theoretically could be shared between different types of machine over a network E usr src often contains the source code for the Linux kernel O Usually kept in a directory such as linux 2 2 20 with a symbolic link to it called linux 19 8 FHS Directories Under var E var run contains pid files process id files for currently running daemon programs O Also contains utmp a record of user logins E var mail or var spool mail is where each user s email is queued up until it is deleted or saved E var log contains logs produced by various programs including syslog E var cache contains data generated by programs which is cached to save time O Cached data can be regenerated if deleted Copyright 2004 GBdirect Ltd http training gbdirect co uk 89 Linux System Administration Module 19 Find System Files and Plac
114. on root users can be prohibited from having crontabs O If etc cron allow exists then only users listed in it may have a crontab O If it doesn t exist but etc cron deny does then users not listed in the latter may have a crontab O If neither exist then all users may have crontabs Ml Permissions for running at commands are similar O The files etc at allow and etc at deny are analogous If neither file exists then no users may run at commands O If only etc at deny exists but is empty then all users may run at commands Copyright 2004 GBdirect Ltd http training gbdirect co uk 129 Linux System Administration Module 27 Automate and Schedule System Administration Tasks 27 17 Exercises 1 a Setup a command which in a couple of minutes time will write the disk usage of the partition containing home to home use b Change to your home directory Set up a command which in ten minutes time will write the disk usage of the partition containing the current directory to a file Repeat the above for two more directories in other partitions writing to separate files Before the time is up display the list of pending commands Examine each one How do they differ 2 a Set up a command which will mail you a reminder message in a few minutes Remember that output from a job run by the at daemon will be mailed to its owner so there is no need to invoke an explicit mail command Check that the mail arrives Mutt is a
115. option to display some help netscape help E Others do have documentation elsewhere but have an option to display a usage summary vim h E GNU utilities all have a help option for this grep help E Discovering which if any option does this can often only be found by trial and error 23 19 Finding Documentation E Unfortunately some luck is required for finding documentation E With time you pick up the hang of what is likely to be documented where E The locate command can be useful for finding all files related to a particular command Hi Web search engines can sometimes be the fastest way of searching for documentation Many places have the entire manual pages hosted on the web which Google et al have conveniently indexed 23 20 Exercises 1 a Use man man to open the man page which details how to use the man command itself b Press the h help key to see a summary of commands and keystrokes c Find out how to do the following things i Move to the start and the end of the man page ii Move up and down the text one screen at a time Copyright 2004 GBdirect Ltd http training gbdirect co uk 112 Linux System Administration Module 23 Use and Manage Local System Documentation iii Move up and down one line at a time iv Search for a pattern in the text v Repeat a previous search with a single keypress vi Move to a specific line by number 2 a From the man page for man find out what commands to t
116. opyright 2004 GBdirect Ltd http training gbdirect co uk 41 Linux System Administration Module 6 Use Unix Streams Pipes and Redirects 6 9 Redirection with File Descriptors E Redirection normally works with stdin and stdout E Specify different files by putting the file descriptor number before the redirection symbol O To redirect the standard error to a file program 2 gt file O To combine standard error with standard output program gt file 2 gt amp 1 O To save both output streams program gt stdout txt 2 gt stderr txt E The descriptors 3 9 can be connected to normal files and are mainly used in shell scripts 6 10 Running Programs with xargs E xargs reads pieces of text and runs another program with them as its arguments O Usually its input is a list of filenames to give to a file processing program E Syntax xargs command initial args E Use 1 nto use n items each time the command is run O The default is 1 E xargs is very often used with input piped from find E Example if there are too many files in a directory to delete in one go use xargs to delete them ten at a time find tmp rubbish xargs 110 rm f 6 11 tee E The tee program makes a T junction in a pipeline E It copies data from stdin to stdout and also to a file E Like gt and combined E For example to save details of everyone s logins and save Bob s logins in a separate file last tee everyone txt grep bob gt
117. or specifix OSes are indented Linux kernels to install are introduced with image O Other OSes are introduced with other E Other options are generic or are defaults for the OSes 97 Linux System Administration Module 21 Boot the System 21 3 Sample lilo conf File boot dev hda put loader on the MBR root dev hdal device to mount as delay 40 4 second delay compact may make booting faster read only needed to allow root to be fscked image vmlinuz 2 2 20 stable kernel default because it s 1st label linux 2 2 20 alias linux shorter label vga ask let us choose the console size image vmlinuz 2 5 1 cutting edge kernel label linux 2 5 1 other dev hda3 Windows is installed on a different partition label windows table dev hda 21 4 Selecting What to Boot E When LILO runs it displays the prompt LILO O If only some of the letters appear the boot process failed at some point E It waits the specified delay for something to start being typed E Load a particular kernel or OS by entering its label or alias O Just press Enter for the default O Pressing Tab lists the available labels O Some versions of LILO present a menu to select from with the cursor keys E If no key has been pressed by the end of the delay the first kernel or OS is loaded 21 5 Other Ways of Starting Linux E Grub complex boot loader which includes a shell and support for accessing filesystems E LoadLi
118. ostname Which of the filenames printed contain the actual hostname program itself Try running it by entering the program s absolute path to check that you really have found it 5 a The wildcard on its own is expanded by the shell to a list of all the files in the current directory Use the echo command to see the result but make sure you are in a directory with a few files or directories first b Use quoting to make echo print out an actual symbol c Augment the poetry directory you created earlier with another file sonnet 29 txt When in disgrace with Fortune and men s eyes I all alone beweep my outcast state d Use the cat command to display both of the poems using a wildcard e Finally use the rm command to delete the poetry directory and the poems in it Copyright 2004 GBdirect Ltd http training gbdirect co uk 15 Module 3 Work Effectively on the Unix Command Line 3 1 Shells E A shell provides an interface between the user and the operating system kernel E Either a command interpreter or a graphical user interface E Traditional Unix shells are command line interfaces CLIs E Usually started automatically when you log in or open a terminal ae 3 2 The Bash Shell E Linux s most popular command interpreter is called bash O The Bourne Again Shell More sophisticated than the original sh by Steve Bourne O Can be run as sh as a replacement for the original Unix shell E Gives you a prompt
119. out what the watch command does o Use apropos to find programs for editing the partition table of disks e See if the Linux installation you are using has an updatedb conf and look at the current configuration if it has f Log on as root and update the locate database with the updatedb command Copyright 2004 GBdirect Ltd http training gbdirect co uk 92 Module 20 Set and View Disk Quotas 20 1 What are Quotas E Quotas are a way of limiting the amount of disk space that users may take up E Some organisations perhaps those with untrusted external users absolutely need to ensure that O No user can prevent other users from using a reasonable amount of disk space O No user can impede the correct functioning of the system Hi Some organisations don t need to worry about this their users can be trusted not to abuse the system E Unfortunately quota management is unnecessarily hard on Linux 0 Could user education avoid the need for quotas Disk space is cheap 20 2 Hard and Soft Limits E Quotas have hard limits and soft limits E A user can exceed the soft limit without retribution O But only for a certain period of time the grace period The user is also warned that the soft limit has been exceeded E A hard limit may never be exceeded E If a user tries to exceed a hard limit or an expired soft limit the attempt fails O The program gets the same error message it would if the filesystem itself
120. owner 27 4 At Command Specification E A command may be specified on standard input instead of interactively E From a file at 16 30 lt monitor_processes sh The commands contained in the file monitor_processes sh are run at 16 30 27 5 Opening Windows from At Commands Mi The SDISPLAY environment variable is not provided in at commands environments E This needs to be set for an at command to be able to open windows E Discover the current value and type it in again echo DISPLAY beehive 0 at 11 00 at gt DISPLAY beehive 0 xclock at gt lt EOT gt E Use interpolation to embed it in the command echo DISPLAY SDISPLAY clock at 11 00 Copyright 2004 GBdirect Ltd http training gbdirect co uk 125 Linux System Administration Module 27 Automate and Schedule System Administration Tasks 27 6 At Command Date amp Time Specification E Unadorned times are in the next 24 hours S at 09 30 E Tomorrow can be specified explictly at 17 00 tomorrow E A specific date can be used at 11 00 Nov 11 S at 00 30 16 04 06 E Relative times can be specified in minutes hours days or weeks at now 45 minutes at 16 00 3 days 27 7 Managing At Commands E atq lists any pending at commands atq 38 2002 01 16 11 00 a O The number at the start of each line identifies that at command E A particular at command can be displayed with at c at c 38 bin sh umask 2 cd
121. r O gt is the shell s idea of the current job the most recently active job O gt is the previous current job 47 Linux System Administration Module 8 Job Control 8 3 fg E Brings a backgrounded job into the foreground Re starts a suspended job running it in the foreground fg 1 will foreground job number 1 fg with no arguments will operate on the current job bg Re starts a suspended job running it in the background bg 1 will background job number 1 bg with no arguments will operate on the current job Enu EE gt For example after running gv and suspending it with Ctr1 Z use bg to start it running again in the background 8 5 Exercises Start a process by running man bash and suspend it with Ctr1 Z o o Run xclock in the background using amp Use jobs to list the backgrounded and stopped processes a o Use the fg command to bring man into the foreground and quit from it as normal e Use fg to foreground xclock and terminate it with Ctrl C f Run xclock again but this time without amp It should be running in the foreground so you can t use the shell Try suspending it with Ctrl Z and see what happens To properly put it into the background use bg Copyright 2004 GBdirect Ltd http training gbdirect co uk 48 Module 9 Create Monitor and Kill Processes 9 1 Whatis a Process E The kernel considers each program running on your system to be a process E
122. r new users E Linux distributions usually have a simple etc skel directory with a few files in 25 7 Exercises 1 a Use the shell builtin alias to get a list of the aliases currently defined b Define a new alias for changing to the parent directory i e cd For example you could call it up c Edit your bashrc file to add the alias to it permanently so that the alias command is run whenever a shell starts d Login as root and look in the directory etc skel to find out what configuration files a new user will get e Create a text file called signature which is the signature appended to emails you send 2 a Use echo to print the current value of the PS1 environment variable b Try setting it to something different You might like to try putting some of the special sequences in but remember to use single quotes so that the backslashes are not interpreted by the shell c Decide how you would like your prompt to appear and edit your bashrc file to set PS1 every time you start a shell Copyright 2004 GBdirect Ltd http training gbdirect co uk 119 Module 26 Configure and Use System Log Files 26 1 syslog E Many events that occur on a Linux system should be logged for administrative purposes E Linux has a facility called syslog that allows any service or part of the system to log such events E syslog can be configured to log different events to different places Events can be selected based on se
123. rack of different users by username O Security features allow different users to have different privileges E Users can belong to groups allowing security to be managed for collections of people with different requirements E Use su to switch to a different user O Quicker than logging off and back on again E su prompts you for the user s password su bob Password The option makes su behave as if you ve logged in as that user 14 2 The Superuser Root E Every Linux system has a user called root E The root user is all powerful O Can access any files E The root user account should only be used for system administration such as installing software E When logged in as root the shell prompt usually ends in E Usually best to use su for working as root whoami fred su Password whoami root 67 Linux System Administration Module 14 Manage File Ownership 14 3 Changing File Ownership with chown Mi The chown command changes the ownership of files or directories E Simple usage chown aaronc logfile txt E Makes logfile txt be owned by the user aaronc E Specify any number of files or directories E Only the superuser can change the ownership of a file O This is a security feature quotas set uid 14 4 Changing File Group Ownership with chgrp E The chgrp command changes the group ownership of files or directories E Simple usage chgrp staff report txt E Makes staff be the group owner of t
124. ree characters before the dot 11 9 Globbing to Match Certain Characters E Instead of matching any single character we can arrange to match any of a given group of characters E ch matches any file ending in c or h E 0 9 txt matches any text file with a digit before the dot E You can use a caret as the first thing in the brackets to match any character that isn t one of the listed ones E a z 3pg matches any JPEG file that doesn t begin with a lower case letter E To match any hidden file except the and directories Copyright 2004 GBdirect Ltd http training gbdirect co uk 59 Linux System Administration Module 11 Advanced Shell Usage 11 10 Generating Filenames E You can use braces to generate filenames mkdir p Accounts 200 1 2 mkdir Accounts 200 1 2 0 1 2 3 4 5 6 7 8 9 1 0 1 2 E You could even combine those two lines mkdir p Accounts 200 1 2 0 1 2 3 4 5 6 7 8 9 1 0 1 2 E Or combine brace expansion with quoting echo Hello world Mum Hello world Hello Mum E Braces can be used for generating any strings not just filenames E Distinctly different from ordinary glob expansion the words generated don t need to be names of existing files or directories 11 11 Shell Programming E The shell is designed to be both O A convenient environment to type commands into O A simple programming language E Any command that can be typed at the command lin
125. rol the formating E By default blank lines aren t numbered O The option ba numbers every line cat n also numbers lines including blank ones 4 14 Dumping Bytes of Binary Data with od E Prints the numeric values of the bytes in a file E Useful for studying files with non text characters E By default prints two byte words in octal E Specify an alternative with the t option O Give a letter to indicate base o for octal x for hexadecimal u for unsigned decimal etc O Can be followed by the number of bytes per word O Add z to show ASCII equivalents alongside the numbers O A useful format is given by od t x1z hexadecimal one byte words with ASCII E Alternatives to od include xxd and hexdump Copyright 2004 GBdirect Ltd http training gbdirect co uk 28 Linux System Administration Module 4 Process Text Streams Using Text Processing Filters 4 15 Paginating Text Files with pr E Convert a text file into paginated text with headers and page fills Ml Rarely useful for modern printers E Options d double spaced output O h header change from the default header to header O 1 lines change the default lines on a page from 66 to lines O o width set offset the left margin to width E Example pr h My Thesis thesis txt lpr 4 16 Dividing Files into Chunks with split E Splits files into equal sized segments E Syntax split options input output prefix E Use 1 nto split a file into n line chunk
126. rvice E The start links for a runlevel directory indicate which services should be started when that runlevel is entered E Correspondingly the stop links indicate which services should be stopped when the runlevel is entered E The rc shell script usually etc rc d rc or etc init d rc runs the relevant init script appropriately for start links and stop links 22 11 Starting or Stopping Individual Services E You can also start or stop an individual service without changing runlevel E An init script always takes an argument of start or stop to start or stop the relevant service E For example if the MySQL database server has an init script etc init d mysql you can start MySQL with etc init d mysql start or stop it with etc init d mysql stop E Some init scripts also accept an argument of restart stop and then re start or reload reload the service s configuration file 22 12 Exercises 1 a Lookin etc nit d or etc rc d init d to see what services can be started by init b Try running the script for crond and use it to stop the cron service and then start it up again c Take a quick look at the program in a text editor it s a small shell script to get a rough idea of what it Copyright 2004 GBdirect Ltd http training gbdirect co uk 104 Linux System Administration Module 22 Change Runlevels and Shutdown or Reboot System does d Look in the rc3 d directory to see what services are killed and star
127. ry hungry processes appear at the top c Restrict the display to show only processes owned by you d Try killing one of your processes make sure it s nothing important e Display a list of all the processes running on the machine using ps displaying the full command line for them f Get the same listing as a tree using both ps and pst ree g Have ps sort the output by system time used Copyright 2004 GBdirect Ltd http training gbdirect co uk 54 Module 10 Modify Process Execution Priorities 10 1 Concepts Not all tasks require the same amount of execution time Linux has the concept of execution priority to deal with this Process priority is dynamically altered by the kernel You can view the current priority by looking at top or ps 1 and looking at the PRI column The priority can be biased using nice O The current bias can be seen in the NI column in top 10 2 nice Starts a program with a given priority bias Peculiar name nicer processes require fewer resources Niceness ranges from 19 very nice to 20 not very nice Non root users can only specify values from 1 to 19 the root user can specify the full range of values Default niceness when using nice is 10 To run a command at increased niceness lower priority nice 10 long running command amp nice n 10 long running command amp To run a command at decreased niceness higher priority nice 15 important command amp
128. ry with ca cd mnt cdrom S pwd mnt cdrom E Use cd without specifying a path to get back to your home directory 2 4 Making and Deleting Directories E The mkdir command makes new empty directories E For example to make a directory for storing company accounts mkdir Accounts E To delete an empty directory use rmdir rmdir OldAccounts E Use rm with the r recursive option to delete directories and all the files they contain rm r OldAccounts E Be careful rm can be a dangerous tool if misused 2 5 Relative Paths E Paths don t have to start from the root directory O A path which doesn t start with is a relative path O Itis relative to some other directory usually the current directory E For example the following sets of directory changes both end up in the same directory cd usr share doc cd cd usr ed share doc E Relative paths specify files inside directories in the same way as absolute ones Copyright 2004 GBdirect Ltd http training gbdirect co uk 9 Linux System Administration Module 2 Getting Started 2 6 Special Dot Directories E Every directory contains two special filenames which help making relative paths O The directory points to the parent directory ls will list the files in the parent directory O For example if we start from home fred Sed S pwd home S ed pwd E The special directory points to the directory it is in O So foo
129. s E Use b nto split into chunks of n bytes each E Output files are named using the specified output name with aa ab ac etc added to the end of the prefix E Example Split essay txt into 30 line files and save the output to files short_aa short_ab etc split 1 30 essay txt short_ 4 17 Using split to Span Disks E If a file is too big to fit on a single floppy Zip or CD ROM disk it can be split into small enough chunks E Use the b option and with the k and m sufixes to give the chunk size in kilobytes or megabytes E For example to split the file database tar gz into pieces small enough to fit on Zip disks split b 90m database tar gz zip E Use cat to put the pieces back together cat zip gt database tar gz 4 18 Reversing Files with tac E Similar to cat but in reverse E Prints the last line of the input first the penultimate line second and so on E Example show a list of logins and logouts but with the most recent events at the end last tac Copyright 2004 GBdirect Ltd http training gbdirect co uk 29 Linux System Administration Module 4 Process Text Streams Using Text Processing Filters 4 19 Translating Sets of Characters with tr E tr translates one set of characters to another E Usage tr start set end set E Replaces all characters in start set with the corresponding characters in end set E Cannot accept a file as an argument but uses the standard input and output E Options O d
130. s to questions O http groups google co uk advanced_group_search O Formerly DejaNews or just Deja but now hosted by Google O May find the answer much faster O Itirritates people to encounter well answered questions being asked many times E Not always the most friendly places for beginners Copyright 2004 GBdirect Ltd http training gbdirect co uk 115 Linux System Administration Module 24 Find Linux Documentation on the Internet 24 6 FAQs E There have been several attempts to document questions frequently asked about Linux with their answers Hi Many newsgroups have their own FAQs O http www fags org faqs by newsgroup E The LDP have a frequently updated Linux FAQ O http www linuxdoc org FAQ Linux FAQ E Again search these before asking for help 24 7 Local Help E More localized forums are often friendlier Hi UK newsgroup O news uk comp os linux O http www ucolfaq lug org uk E UK Linux users mailing lists O http www ukuug org sigs linux newsgroups shtml E Many areas have their own Linux user groups O http www lug org uk lugs O Meetings O Local mailing lists Copyright 2004 GBdirect Ltd http training gbdirect co uk 116 Module 25 Tune the User Environment and System Environment Variables 25 1 Configuration Files E Many programs including shells read configuration files E Files which apply to only one user are stored in that user s home directory usually as
131. s with cp E Syntax cp options source file destination file Hi Copy multiple files into a directory cp files directory Hi Common options O f force overwriting of destination files O i interactively prompt before overwriting files O a archive copy the contents of directories recursively 5 8 Examples of cp E Copy etc smb conf to the current directory cp etc smb conf E Create an identical copy of a directory called work and call it work backup cp a work work backup E Copy all the GIF and JPEG images in the current directory into images S cp gif jpeg images Copyright 2004 GBdirect Ltd http training gbdirect co uk 35 Linux System Administration Module 5 Perform Basic File Management 5 9 Moving Files with mv E mv can rename files or directories or move them to different directories E It is equivalent to copying and then deleting O But is usually much faster E Options O f force overwrite even if target already exists O i ask user interactively before overwriting files E For example to rename poetry txt to poems txt mv poetry txt poems txt E To move everything in the current directory somewhere else mv old stuff 5 10 Deleting Files with rm E rm deletes removes the specified files E You must have write permission for the directory the file is in to remove it E Use carefully if you are logged in as root E Options O f delete write protected files wi
132. se again but don t specify a filename to which to copy What happens now Copyright 2004 GBdirect Ltd http training gbdirect co uk 7 Module 2 Getting Started 2 1 Files and Directories E A directory is a collection of files and or other directories O Because a directory can contain other directories we get a directory hierarchy E The top level of the hierarchy is the root directory E Files and directories can be named by a path O Shows programs how to find their way to the file O The root directory is referred to as O Other directories are referred to by name and their names are separated by slashes E If a path refers to a directory it can end in O Usually an extra slash at the end of a path makes no difference 2 2 Examples of Absolute Paths E An absolute path starts at the root of the directory hierarchy and names directories under it etc hostname O Meaning the file called hostname in the directory etc in the root directory E We can use 1s to list files in a specific directory by specifying the absolute path ls usr share doc Linux System Administration Module 2 Getting Started 2 3 Current Directory E Your shell has a current directory the directory in which you are currently working E Commands like 1s use the current directory if none is specified E Use the pwd print working directory command to see what your current directory is S pwd home fred Hi Change the current directo
133. set of environment variables it can access O In Bash use export to export a shell variable into the environment files notes txt report txt export files O Or combine those into one line export files notes txt report txt E The env command lists environment variables Copyright 2004 GBdirect Ltd http training gbdirect co uk Linux System Administration Module 3 Work Effectively on the Unix Command Line 3 9 Where Programs are Found E The location of a program can be specified explicitly O sample runs the sample program in the current directory O bin 1s runs the 1s command in the bin directory E Otherwise the shell looks in standard places for the program O The variable called PATH lists the directories to search in O Directory names are separated by colon for example echo PATH bin usr bin usr local bin O So running whoami will run bin whoami or usr bin whoami or usr local bin whoami whichever is found first 3 10 Bash Configuration Variables E Some variables contain information which Bash itself uses O The variable called PS1 Prompt String 1 specifies how to display the shell prompt E Use the echo command with a sign before a varable name to see its value e g echo SPS1 u h AMAS E The special characters u h and W represent shell variables containing respectively your user login name machine s hostname and current working directory i e O SUSER SHOSTNAME
134. tation by the shell xmms Tom Lehrer Poisoning Pigeons in the Park mp3 rm b lls and whistles E But single quotes obviously don t protect single quotes themselves O So you can t quote something like She said Don t go with only single quotes 11 3 Quoting Backslashes E You can put a backslash in front of any single character to turn off its special meaning echo MIES xmms Suzanne Vega 1 Tom s Diner mp3 mail s C MSDOS SYS windows user example com 57 Linux System Administration Module 11 Advanced Shell Usage 11 4 Quoting Double Quotes E Putting double quotes round something protects most things within it from interpretation by the shell O A dollar sign retains its special interpretation O As do backticks O can t be escaped in double quotes E A backslash can be used within double quotes to selectively disable the special interpretation of and mail s C MSDOS SYS windows user example com echo It cost price USAS E Putting a backslash in front of anything else gives you both characters echo TAN Ed 11 5 Quoting Combining Quoting Mechanisms E You can build up an argument for a command by combining several chunks of differently quoted text E Just put the chunks next to each other with no intervening whitespace echo double quoted single quoted unquoted double quoted single quoted unquoted echo She said Don Y t go She said
135. ted when switching to runlevel 3 e Use telinit to change to single user mode f Once in single user mode use top to see what processes are left running 2 a Reboot the machine by changing to runlevel 6 b When the LILO prompt appears type Tab to see a list of operating systems to boot Type the name of the one you want followed by a space and the number 1 to indicate that you want to boot straight into single user mode c Change back to runlevel 3 Copyright 2004 GBdirect Ltd http training gbdirect co uk 105 Module 23 Use and Manage Local System Documentation 23 1 Manual Pages E Most Linux commands have an associated manual page O Often known as a manpage E Viewed with the man command man ls E Press q to quit and return to the shell prompt 23 2 Navigating Within Manual Pages E man uses the less viewer E Use the cursor keys for scrolling E Other common keystrokes Space jump down a page b jump back up a page word search for the next occurrence of word n repeat the previous search g go to the top E Help on all keystokes is available with h 106 Linux System Administration Module 23 Use and Manage Local System Documentation 23 3 Sections of a Manual Page Hi Manpages have a traditional format E Manpages for user commands tend to have some or all of these sections NAME name and single line reason for the command SYNOPSIS possible arguments DESCRIPTION ful
136. tems PRUNEPATHS tmp usr tmp var tmp mnt var spool 5 export PRUNEPATHS E The SPRUNEES variable lists the names for filesystems which should be ignored e g nfs iso9660 etc E These variables are equivalent to the e and f options Copyright 2004 GBdirect Ltd http training gbdirect co uk 91 Linux System Administration Module 19 Find System Files and Place Files in the Correct Location 19 16 whatis E whatis finds manpages with the given name and lists them O Usually only useful when the name of a command is already known E For example to find manpages about bash whatis bash E The database searched by whatis is updated with the makewhatis command O This should be run when new manpages are installed O Debian instead has etc cron daily man db which also expunges old cached man pages 19 17 Finding Manpages with apropos E The apropos command is similar to whatis O The difference is that any word in the title line of a manpage can match the word given E apropos word is identicaltoman k word E For example to find commands relating to directories apropos directories man k directories E apropos also uses the database built by makewhat is 19 18 Web Resources E The FHS http www pathname com fhs 19 19 Exercises Find out whether the 1s command runs a program directly or is a shell alias or function o p Locate the binary of the traceroute program c Use whatis to find
137. thout prompting O i interactive ask the user before deleting files O r recursively delete files and directories E For example clean out everything in tmp without prompting to delete each file S rm rf tmp 5 11 Deleting Files with Peculiar Names E Some files have names which make them hard to delete E Files that begin with a minus sign rm filename rm filename E Files that contain peculiar characters perhaps characters that you can t actually type on your keyboard O Write a wildcard pattern that matches only the name you want to delete rm i name with funny characters O The forces it to be in the current directory O Using the i option to rm makes sure that you won t delete anything else by accident Copyright 2004 GBdirect Ltd http training gbdirect co uk 36 Linux System Administration Module 5 Perform Basic File Management 5 12 Making Directories with mkdir E Syntax mkdir directory names E Options O p create intervening parent directories if they don t already exist O m mode set the access permissions to mode E For example create a directory called mystuff in your home directory with permissions so that only you can write but eveyone can read it mkdir m 755 mystuff E Create a directory tree in tmp using one command with three subdirectories called one two and three mkdir p tmp one two three 5 13 Removing Directories with rmdir 5
138. to another directory like cd But also saves the current directory so that you can go back later For example to visit Fred s home directory and then go back to where you started from pushd fred cd Work Sls popd popd takes you back to the directory where you last did pushd dirs will list the directories you can pop back to Filename Completion Modern shells help you type the names of files and directories by completing partial names Type the start of the name enough to make it unambiguous and press Tab For an ambiguous name there are several possible completions the shell can list the options For Bash type Tab twice in succession O For C shells type Ctrl D Both of these shells will automatically escape spaces and special characters in the filenames Copyright 2004 GBdirect Ltd http training gbdirect co uk 34 Linux System Administration Module 5 Perform Basic File Management 5 6 Wildcard Patterns E Give commands multiple files by specifying patterns E Use the symbol to match any part of a filename S ls txt accounts txt letter txt report txt E Just produces the names of all files in the current directory E The wildcard matches exactly one character rm v data removing data 1 removing data 2 removing data 3 E Note wildcards are turned into filenames by the shell so the program you pass them to can t tell that those names came from wildcard expansion 5 7 Copying File
139. ts 2 o e e ee 119 20 0 HEXGIGISES 4 wer xy ey aye a a Are de Se ew Ry Se ee de A eG A 119 Copyright 2004 GBdirect Ltd http training gbdirect co uk ix Linux System Administration Contents 26 Configure and Use System Log Files 2671 SV STOG a ap eel Ss By in peeve apa dem oes ae at dace be SS a ee Es 26 2 61C SYSIOG CONT a i a a Bere ow AA A Re a A a aTa 26 3 Sample etc sysiog conf 020 a 26 4 Reconfiguringsyslog 0 0 ee ee 26 5 Examining Logs less and grep 26 6 Examining Logs in Real Time tail 26 7 Log Rotation o srecni derra sarra ka ier ene ua 26 8 Sample etc logrotate conf o aooaa 0552 eee 26 9 VEXeICISCS a ade Sale a A goa and a aE A Bes 27 Automate and Schedule System Administration Tasks 27 1 Running Commands in the Future 204 27 2 AtCommands se 2 40 eee ee ee ee ee eee 27 3 Commands Run by the At D mon 0 27 4 At Command Specification 0 27 5 Opening Windows from At Commands 27 6 At Command Date 8 Time Specification 27 7 Managing At Commands o e e e ee 27 8 Simple Cron Job Specification 0 27 9 More Complex Cron Job Specification 27 10 Crontab Format 00 00 ee ee 27 11 Crontab Date amp Time Specification o 27
140. txt gt do gt mv v file file old gt done barbie txt gt barbie txt old food txt gt food txt old quirks txt gt quirks txt old E The command above could also be written on a single line Copyright 2004 GBdirect Ltd http training gbdirect co uk 21 Linux System Administration Module 3 Work Effectively on the Unix Command Line 3 17 Command Substitution Hi Command substitution allows the output of one command to be used as arguments to another E For example use the locate command to find all files called manual htm and print information about them with 1s ls 1 locate manual html ls l locate manual html E The punctuation marks on the second form are opening single quote characters called backticks O The form is usually preferred but backticks are widely used E Line breaks in the output are converted to spaces E Another example use vi to edit the last of the files found vi locate manual html tail 1 3 18 Finding Files with Locate E The locate command is a simple and fast way to find files E For example to find files relating to the email program mutt locate mutt E The locate command searches a database of filenames The database needs to be updated regularly O Usually this is done automatically with cron O But locate will not find files created since the last update E The i option makes the search case insensitive E r treats the pattern as a regular e
141. ut arguments to get a list of builtin commands 23 13 Location of Manual Pages E Manpages are stored in the filesystem E You can use man to find the locations of a given manpage O Use the a and w options to show the locations of all manpages with a given name man aw passwd usr man manl passwd 1 gz usr man man5 passwd 5 gz E Common locations for manpages include usr man and usr share man O Locally installed packages often put manpages under usr local man Copyright 2004 GBdirect Ltd http training gbdirect co uk 110 Linux System Administration Module 23 Use and Manage Local System Documentation 23 14 Info Pages E GNU have a rival documentation system called info O GNU utilities have info pages O Often duplicating man pages O But some GNU utilities have half hearted man pages O A few other programs use info too E An info page is viewed with the info command info cat info ls E Use q to quit and return to the shell E Emacs has a better info viewer built in and there is an alternative slicker viewer available called pinfo 23 15 Navigating Within Info Pages Scroll with the cursor keys PgUp and PgDn E An info page may be split into nodes For example the 1s page has separate nodes covering file selection formatting and sorting Hyperlinks between nodes start with stars O Node navigation keystrokes Tab jump to next hyperlink Enter follow hyperlink 1 return to your previous lo
142. verity level and or on the service that encountered the event facility Messages can go to files to the system console or to a centralised syslog server running on another machine 26 2 etc syslog conf E syslog s configuration is in etc syslog conf each line looks like facility level destination E The facility is the creator of the message one of auth authpriv cron daemon kern lpr mail news syslog user or local0 through local7 E The level is a severity threshold beyond which messages will be logged one of from lowest to highest debug info notice warning err crit alert emerg E The destination indicates where messages selected by the facility and level will be sent O Normally the name of a log file under var log or dev console to send messages to the system console 120 Linux System Administration Module 26 Configure and Use System Log Files 26 3 Sample etc syslog conf Log all kernel messages to the console Logging much else clutters up the screen kern dev console Log anything except mail of level info or higher Don t log private authentication messages Notice that we separate message selectors with a semicolon Note the use of severity none to exclude a facility info mail none news none authpriv none var log messages The authpriv file has restricted access authpriv var log secure Log all the mail messages in on
143. w x permissions to set O Or use capital X to set the x permission but only for directories and already executable files 15 9 Changing the Permissions of a Directory and Its Contents E A common requirement is to change the permissions of a directory and its contents E chmod accepts a R option chmod R g rwX o rX public directory E Mnemonic recursive E Adds rwx permissions on public directory for the group owner and adds rx permissions on it for everyone else O And any subdirectories recursively O Any any contained executable files O Contained non executable files have rw permissions added for the group owner and r permission for everyone else Copyright 2004 GBdirect Ltd http training gbdirect co uk 72 Linux System Administration Module 15 Use File Permissions to Control Access to Files 15 10 Special Directory Permissions Sticky E The imp directory must be world writable so that anyone may create temporary files within it E But that would normally mean that anyone may delete any files within it obviously a security hole E A directory may have sticky permission O Only afile s owner may delete it from a sticky directory E Expressed with a t mnemonic temporary directory in a listing ls 1 d tmp drwxrwxrwt 30 root root 11264 Dec 21 09 35 tmp E Enable sticky permission with chmod t data tmp 15 11 Special Directory Permissions Setgid E Ifa directory is
144. will have the configuration in a file in etc logrotate d Copyright 2004 GBdirect Ltd http training gbdirect co uk 123 Module 27 Automate and Schedule System Administration Tasks 27 1 Running Commands in the Future E There is sometimes a need for commands not to be run immediately but scheduled to run later E One off commands O At 10 00 tomorrow e mail me this reminder message O These are known as at commands E Regularly repeating commands O Every night rebuild the database used by the locate command These are known as cron jobs 27 2 At Commands E At commands are defined using at at 16 30 at gt pstree gt processes at gt lt EOT gt E The time the command should run is given as a parameter to at E at then prompts for the command itself O Command s exactly as they would be typed in the shell O Press Ctrl D to finish E The at d mon will run the command at the specified time O In this example the output of running pst ree at 16 30 will be saved in the file processes 124 Linux System Administration Module 27 Automate and Schedule System Administration Tasks 27 3 Commands Run by the At Demon E A command executed by the at d mon O Has the permissions of its owner O Runs in the directory it was set up O Has the environment in which it was set up O Does not run in a terminal E Output from the command O Cannot be included in a terminal window O Will be mailed to its
145. xpression rather than a simple string 3 19 Finding Files More Flexibly find Ml locate only finds files by name E find can find files by any combination of a wide number of criteria including name E Structure find directories criteria E Simplest possible example find E Finding files with a simple criterion find name manual html Looks for files under the current directory whose name is manual html E The criteria always begin with a single hyphen even though they have long names Copyright 2004 GBdirect Ltd http training gbdirect co uk 22 Linux System Administration Module 3 Work Effectively on the Unix Command Line 3 20 find Criteria 3 21 find accepts many different criteria two of the most useful are O name pattern selects files whose name matches the shell style wildcard pattern O type d type f select directories or plain files respectively You can have complex selections involving and or and not find Actions Executing Programs find lets you specify an action for each file found the default action is simply to print out the name O You can alternatively write that explicitly as print Other actions include executing a program for example to delete all files whose name starts with manual find name manual exec rm The command rm is run for each file with replaced by the filename The and are required by find but
146. y O Unix commands O Unix standards and conventions E There is some variation between Unix operating systems O Especially regarding system administration O Often Linux specific things in these areas 1 2 Unix System Architecture applications y T S 5 Cx snot 9 Xx shell 5 kernel hardware E The shell and the window environment are programs E Programs only access to hardware is via the kernel Linux System Administration Module 1 Introduction 1 3 Unix Philosophy Ml Multi user O A user needs an account to use a computer O Each user must log in O Complete separation of different users files and configuration settings Hi Small components O Each component should perform a single task O Multiple components can be combined and chained together for more complex tasks O An individual component can be subsituted for another without affecting other components 1 4 What is Linux E Linux kernel O Developed by Linus Torvalds O Strictly speaking Linux is just the kernel E Associated utilities O Standard tools found on nearly all Linux systems Many important parts come from the GNU project E Free Software Foundation s project to make a free Unix m Some claim the OS as a whole should be GNU Linux E Linux distributions O Kernel plus utilities plus other tools packaged up for end users O Generally with installation program O Distributors include Red Hat
147. ype to do the following i Get a list of manual pages about the whatis database ii Get a list of manual pages from section 1 whose descriptions contain the word print iii Search for man pages containing the string cdrom but why is this a problem b Practice using man to find out about things which interest you or try some of these examples i Bitmap image formats like JPEG GIF XPM and PNG ii Communications concepts like modems serial connections telnet PCMCIA and PPP iii Filesystems like NFS ext2 FAT vfat msdos and Samba 3 a Take a quick look at the documentation for the tar command in both the man page and the Info documentation How are they different b What happens when you run info without specifying which document to view Copyright 2004 GBdirect Ltd http training gbdirect co uk 113 Module 24 Find Linux Documentation on the Internet 24 1 The Linux Documentation Project E The Linux Documentation Project or LDP promotes and develops Linux documentation E http www linuxdoc org Many mirrors O http www mirror ac uk sites www linuxdoc org O http www doc linux co uk LDP E The LDP is working on developing free high quality documentation for the GNU Linux operating system E The overall goal of the LDP is to collaborate in all of the issues of Linux documentation 24 2 HOWTOs Hi A HOWTO is a document describe how to do something Hi HOWTOs cover a w

Download Pdf Manuals

image

Related Search

Related Contents

JurisCal lettre info 09 10 2010  Osram 64664 HLX  programme de formation outils bureautique journee  SX214A - MyToolService.com  GFK-2784E, PACSystems RXi Industrial PCs QSG  Weber 89374 Owner's Manual  ADVE ADVER ADVERTENCIA  V-Stamp User`s Manual  Hummingbird Communications 531296-1_A User's Manual  RevKit — User Manual  

Copyright © All rights reserved.
Failed to retrieve file