C# 2.0: Practical Guide For Programmers A To Red Hat Linux (3rd Edition) Mark G. Sobell
User Manual:
Open the PDF directly: View PDF .
Page Count: 2541 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- A Practical Guide to Red Hat® Linux®, Third Edition: Fedora™ Core and Red Hat Enterprise Linux
- Table of Contents
- Copyright
- Praise for A Practical Guide to Red Hat® Linux®, Second Edition
- Chapter 1. Welcome to Linux
- Part I: Installing Red Hat Linux
- Part II: Getting Started with Red Hat Linux
- Chapter 4. Introduction to Red Hat Linux
- Chapter 5. The Linux Utilities
- Special Characters
- Basic Utilities
- Working with Files
- | (Pipe): Communicates Between Processes
- Four More Utilities
- Compressing and Archiving Files
- Locating Commands
- Obtaining User and System Information
- Communicating with Other Users
- Tutorial: Creating and Editing a File with vim
- Chapter Summary
- Exercises
- Advanced Exercises
- Chapter 6. The Linux Filesystem
- Chapter 7. The Shell
- Part III: Digging into Red Hat Linux
- Part IV: System Administration
- Part V: Using Clients and Setting Up Servers
- Chapter 18. OpenSSH: Secure Network Communication
- Chapter 19. FTP: Transferring Files Across a Network
- Chapter 20. sendmail: Setting Up Mail Clients, Servers, and More
- Chapter 21. NIS: Network Information Service
- Chapter 22. NFS: Sharing Filesystems
- Chapter 23. Samba: Integrating Linux and Windows
- Chapter 24. DNS/BIND: Tracking Domain Names and Addresses
- Chapter 25. iptables: Setting Up a Firewall
- Chapter 26. Apache (httpd): Setting Up a Web Server
- Introduction
- About Apache
- JumpStart I: Getting Apache Up and Running
- JumpStart II: Setting Up Apache Using system-config-httpd
- Filesystem Layout
- Configuration Directives
- The Red Hat httpd.conf File
- Redirects
- Multiviews
- Server-Generated Directory Listings (Indexing)
- Virtual Hosts
- Troubleshooting
- Modules
- webalizer: Analyzes Web Traffic
- MRTG: Monitors Traffic Loads
- Error Codes
- Chapter Summary
- Exercises
- Advanced Exercises
- Part VI: Programming
- Part VII: Appendixes
- Appendix A. Regular Expressions
- Appendix B. Help
- Appendix C. Security
- Appendix D. The Free Software Definition
- Appendix E. The Linux 2.6 Kernel
- Native Posix Thread Library (NPTL)
- IPSecurity (IPSec)
- Asynchronous I/O (AIO)
- 0(1) Scheduler
- OProfile
- kksymoops
- Reverse Map Virtual Memory (RMAP VM)
- HugeTLBFS: Translation Look-Aside Buffer Filesystem
- remap_file_pages
- 2.6 Network Stack Features (IGMPv3, IPv6, and Others)
- Internet Protocol Virtual Server (IPVS)
- Access Control Lists (ACLs)
- 4GB-4GB Memory Split: Physical Address Extension (PAE)
- Scheduler Support for HyperThreaded CPUs
- Block I/O (BIO) Block Layer
- Support for Filesystems Larger Than 2 Terabytes
- New I/O Elevators
- Interactive Scheduler Response Tuning
- Glossary
- Index
APracticalGuidetoRedHat®Linux®,ThirdEdition:
Fedora™CoreandRedHatEnterpriseLinux
ByMarkG.Sobell
...............................................
Publisher:PrenticeHall
PubDate:June27,2006
PrintISBN-10:0-13-228027-2
PrintISBN-13:978-0-13-228027-3
Pages:1168
TableofContents|Index
"SinceI'minaneducationalenvironment,IfoundthecontentofSobell'sbooktoberight
ontargetandveryhelpfulforanyonemanagingLinuxintheenterprise.Hisstyleofwriting
isveryclear.Hebuildsuptothechapterexercises,whichIfindtoberelevanttoreal-
worldscenariosauseroradminwouldencounter.AnIT/ISstudentwouldfindthisbooka
valuablecomplementtotheireducation.Thevastamountofinformationisextremelywell
balancedandSobellmanagestopresentthecontentwithoutcomplicatedasidesand
meanderingprose.Thisisa'musthave'foranyonemanagingLinuxsystemsina
networkedenvironmentoranyonerunningaLinuxserver.Iwouldalsohighlyrecommend
ittoanexperiencedcomputeruserwhoismovingtotheLinuxplatform."MaryNorbury,
ITDirector,BarbaraDavisCenter/UniversityofColoradoatDenver,fromareviewposted
onslashdot.org
"IhadthechancetouseyourUNIXbookswhenIwhenwasincollegeyearsagoatCal
PolySanLuisObispo,CA.Ihavetosaythatyourbooksareamongthebest!They're
qualitybooksthatteachthetheoreticalaspectsandapplicationsoftheoperatingsystem."
BentonChan,ISEngineer
"ThebookhasmorethanliveduptomyexpectationsfromthemanyreviewsIread,even
thoughittargetsFC2.Ihavefoundsomethingveryrarewithyourbook:Itdoesn'tread
likethestandardatechnicaltext,itreadsmorelikeastory.It'sapleasuretoreadand
hardtoputdown.DidIsaythat?!:-)"DavidHopkins,BusinessProcessArchitect
"Thanksforyourworkandforthebookyouwrote.Therearereallyfewbooksthatcan
helppeopletobecomemoreefficientadministratorsofdifferentworkstations.Wehope(in
Russia)thatyouwillcontinuebringingusanewlevelofunderstandingofLinux/UNIX
systems."AntonPetukhov
"MarkSobellhaswrittenabookasapproachableasitisauthoritative."JeffreyBianchine,
Advocate,Author,Journalist
"Excellentreferencebook,wellsuitedforthesysadminofaLinuxcluster,ortheownerofa
PCcontemplatinginstallingarecentstableLinux.Don'tbeputoffbythedauntingheftof
thebook.Sobellhasstriventobeasinclusiveaspossible,intryingtoanticipateyour
systemadministrationneeds."WesBoudville,Inventor
"APracticalGuidetoRedHat®Linux®isabrilliantbook.ThankyouMarkSobell."C.
Pozrikidis,UniversityofCaliforniaatSanDiego
"ThisbookpresentsthebestoverviewoftheLinuxoperatingsystemthatIhavefound...
.Itshouldbeveryhelpfulandunderstandablenomatterwhatthereader'sbackgroundis:
traditionalUNIXuser,newLinuxdevotee,orevenWindowsuser.Eachtopicispresentedin
aclear,completefashionandveryfewassumptionsaremadeaboutwhatthereader
knows....Thebookisextremelyusefulasareference,asitcontainsa70-pageglossary
oftermsandisverywellindexed.Itisorganizedinsuchawaythatthereadercanfocus
onsimpletaskswithouthavingtowadethroughmoreadvancedtopicsuntiltheyare
ready."CamMarshall,MarshallInformationServiceLLC,MemberofFrontRangeUNIX
UsersGroupFRUUG,Boulder,Colorado
"Conclusively,thisisTHEbooktogetifyouareanewLinuxuserandyoujustgotinto
RH/Fedoraworld.There'snootherbookthatdiscussessomanydifferenttopicsandin
suchdepth."EugeniaLoli-Queru,EditorinChief,OSNews.com
TheBestJustBecameBETTERAgain!CompletelyRevisedtoMeetAllYourFedora
CoreandRedHatEnterpriseLinuxNeeds!
FedoraCoreandRedHatEnterpriseLinuxareadvancedoperatingsystems.Youneeda
bookthat'sjustasadvanced.ThisbookexplainsLinuxclearlyandeffectivelywithafocus
onfeaturesyoucareabout,fromsystemsecurityandInternetserversetuptoWindows
file/printersharing.Best-sellingauthorMarkSobellstartsatthebeginningandwalksyou
througheverythingthatmatters,frominstallingLinuxusingtheincludedDVDtoworking
withGNOME,KDE,Samba,sendmail,Apache,DNS,NIS,andiptables.
Thiseditioncontainsextensivecoverage,includingfullchaptersonusingLinuxfromthe
commandlineandGUI;evenmorethoroughsystemadministrationandsecurityguidance;
andup-to-the-minute,step-by-stepinstructionsforsettingupnetworksandeverymajor
typeofInternetserver.Alongtheway,youlearnthe"hows"andthe"whys."MarkSobell
knowseveryLinuxnookandcranny,hastaughthundredsofthousandsofreaders,and
neverforgetswhatit'sliketobenewtoLinux.Whetheryouareauser,anadministrator,
oraprogrammer,thisbookgivesyouallyouneedandmore.
Don'tsettleforyesterday'sLinuxbook...gettheONLYbookthatmeetstoday's
challengesandtomorrow's!
ComparedwiththeotherLinuxbooksoutthere,APracticalGuidetoRedHat®
Linux®,ThirdEdition,delivers...
CompletecoverageofFedoraCoreandRedHatEnterpriseLinux
DeepercoverageofthecommandlineandtheGNOMEandKDEGUIs,includingGUI
customization
MorepracticalcoverageoffilesharingwithSamba,NFS,andFTP
Moredetailed,usablecoverageofInternetserverconfigurationincludingApache,
sendmail,NFS,andDNS/BIND
Morestate-of-the-artsecuritytechniques,includingSELinux(SecurityEnhanced
Linux),ACLs(AccessControlLists),firewallsetupusingtheRedHatGUIandusing
iptables,andafullchapteronOpenSSH
Moreandbettercoverageof"meat-and-potatoes"system/networkadministration
tasks
Amorepracticalintroductiontowritingbashshellscripts
CompleteinstructionsonhowtokeepyourLinuxsystemup-to-dateusingyum
Andmuchmore...includinga500+termglossaryandacomprehensiveindextohelp
youfindwhatyouneedfast!
IncludesDVD!GetthefullversionofRedHat'sFedoraCore5release!
APracticalGuidetoRedHat®Linux®,ThirdEdition:
Fedora™CoreandRedHatEnterpriseLinux
ByMarkG.Sobell
...............................................
Publisher:PrenticeHall
PubDate:June27,2006
PrintISBN-10:0-13-228027-2
PrintISBN-13:978-0-13-228027-3
Pages:1168
TableofContents|Index
Copyright
PraiseforAPracticalGuidetoRedHat®Linux®,SecondEdition
Preface
Chapter1.WelcometoLinux
TheGNULinuxConnection
TheLinux2.6Kernel
TheHeritageofLinux:UNIX
WhatIsSoGoodAboutLinux?
OverviewofLinux
AdditionalFeaturesofLinux
ConventionsUsedinThisBook
ChapterSummary
Exercises
PartI:InstallingRedHatLinux
Chapter2.InstallationOverview
MoreInformation
PlanningtheInstallation
HowtheInstallationWorks
TheMedium:WhereIstheSourceData?
Downloading,Burning,andInstallingaCDSetoraDVD(FEDORA)
RescueCD
GatheringInformationAbouttheSystem
FindingtheInstallationManual
ChapterSummary
Exercises
AdvancedExercises
Chapter3.Step-by-StepInstallation
InstallingRedHatLinux
InstallationTasks
TheXWindowSystem
ChapterSummary
Exercises
AdvancedExercises
PartII:GettingStartedwithRedHatLinux
Chapter4.IntroductiontoRedHatLinux
CurbingYourPower:Superuser/rootAccess
ATouroftheRedHatLinuxDesktop
GettingtheFacts:WheretoFindDocumentation
MoreAboutLoggingIn
ChapterSummary
Exercises
AdvancedExercises
Chapter5.TheLinuxUtilities
SpecialCharacters
BasicUtilities
WorkingwithFiles
|(Pipe):CommunicatesBetweenProcesses
FourMoreUtilities
CompressingandArchivingFiles
LocatingCommands
ObtainingUserandSystemInformation
CommunicatingwithOtherUsers
Email
Tutorial:CreatingandEditingaFilewithvim
ChapterSummary
Exercises
AdvancedExercises
Chapter6.TheLinuxFilesystem
TheHierarchicalFilesystem
DirectoryFilesandOrdinaryFiles
Pathnames
DirectoryCommands
WorkingwithDirectories
AccessPermissions
ACLs:AccessControlLists
Links
ChapterSummary
Exercises
AdvancedExercises
Chapter7.TheShell
TheCommandLine
StandardInputandStandardOutput
RunningaProgramintheBackground
FilenameGeneration/PathnameExpansion
Builtins
ChapterSummary
Exercises
AdvancedExercises
PartIII:DiggingintoRedHatLinux
Chapter8.LinuxGuis:X,Gnome,andKDE
XWindowSystem
UsingGNOME
UsingKDE
ChapterSummary
Exercises
AdvancedExercises
Chapter9.TheBourneAgainShell
Background
ShellBasics
ParametersandVariables
SpecialCharacters
Processes
History
Aliases
Functions
ControllingbashFeaturesandOptions
ProcessingtheCommandLine
ChapterSummary
Exercises
AdvancedExercises
Chapter10.NetworkingandtheInternet
TypesofNetworksandHowTheyWork
CommunicateOveraNetwork
NetworkUtilities
DistributedComputing
Usenet
WWW:WorldWideWeb
ChapterSummary
Exercises
AdvancedExercises
PartIV:SystemAdministration
Chapter11.SystemAdministration:CoreConcepts
SystemAdministratorandSuperuser
RescueMode
SELinux
SystemOperation
SystemAdministrationUtilities
SettingUpaServer
nsswitch.conf:WhichServicetoLookatFirst
PAM
ChapterSummary
Exercises
AdvancedExercises
Chapter12.Files,Directories,andFilesystems
ImportantFilesandDirectories
FileTypes
Filesystems
ChapterSummary
Exercises
AdvancedExercises
Chapter13.DownloadingandInstallingSoftware
yum:KeepstheSystemUp-to-Date(FEDORA)
pirut:AddsandRemovesSoftwarePackages(FEDORA)
BitTorrent(FEDORA)
rpm:RedHatPackageManager
InstallingNon-rpmSoftware
KeepingSoftwareUp-to-Date
wget:DownloadsFilesNoninteractively
ChapterSummary
Exercises
AdvancedExercises
Chapter14.PrintingwithCUPS
Introduction
JumpStartI:ConfiguringaLocalPrinterUsingsystem-config-printer
JumpStartII:ConfiguringaRemotePrinterUsingCUPS
TraditionalUNIXPrinting
ConfiguringPrintersUsingCUPS
TheKDEPrintingManager
IntegrationwithWindows
ChapterSummary
Exercises
AdvancedExercises
Chapter15.RebuildingtheLinuxKernel
PreparingtheSourceCode
ReadtheDocumentation
ConfiguringandCompilingtheLinuxKernel
InstallingtheKernelandAssociatedFiles
Rebooting
BootLoader
dmesg:DisplaysKernelMessages
ChapterSummary
Exercises
AdvancedExercises
Chapter16.AdministrationTasks
ConfiguringUserandGroupAccounts
BackingUpFiles
SchedulingTasks
SystemReports
KeepingUsersInformed
CreatingProblems
SolvingProblems
ChapterSummary
Exercises
AdvancedExercises
Chapter17.ConfiguringaLAN
SettingUptheHardware
ConfiguringtheSystems
SettingUpServers
MoreInformation
ChapterSummary
Exercises
AdvancedExercises
PartV:UsingClientsandSettingUpServers
Chapter18.OpenSSH:SecureNetworkCommunication
Introduction
AboutOpenSSH
OpenSSHClients
sshd:OpenSSHServer
Troubleshooting
Tunneling/PortForwarding
ChapterSummary
Exercises
AdvancedExercises
Chapter19.FTP:TransferringFilesAcrossaNetwork
Introduction
MoreInformation
FTPClient
FTPServer(vsftpd)
ChapterSummary
Exercises
AdvancedExercises
Chapter20.sendmail:SettingUpMailClients,Servers,andMore
Introduction
JumpStartI:ConfiguringsendmailonaClient
JumpStartII:ConfiguringsendmailonaServer
HowsendmailWorks
Configuringsendmail
AdditionalEmailTools
AuthenticatedRelaying
Alternativestosendmail
ChapterSummary
Exercises
AdvancedExercises
Chapter21.NIS:NetworkInformationService
IntroductiontoNIS
HowNISWorks
SettingUpanNISClient
SettingUpanNISServer
ChapterSummary
Exercises
AdvancedExercises
Chapter22.NFS:SharingFilesystems
Introduction
MoreInformation
SettingUpanNFSClient
SettingUpanNFSServer
automount:AutomaticallyMountsDirectoryHierarchies
ChapterSummary
Exercises
AdvancedExercises
Chapter23.Samba:IntegratingLinuxandWindows
Introduction
AboutSamba
JumpStart:ConfiguringaSambaServerUsingsystem-config-samba
swat:ConfiguresaSambaServer
ManuallyConfiguringaSambaServer
AccessingLinuxSharesfromWindows
AccessingWindowsSharesfromLinux
Troubleshooting
ChapterSummary
Exercises
AdvancedExercises
Chapter24.DNS/BIND:TrackingDomainNamesandAddresses
IntroductiontoDNS
AboutDNS
JumpStartI:SettingUpaDNSCache
JumpStartII:SettingUpaDomainUsingsystem-config-bind(FEDORA)
SettingUpBIND
Troubleshooting
AFull-FunctionedNameserver
ASlaveServer
ASplitHorizonServer
ChapterSummary
Exercises
AdvancedExercises
Chapter25.iptables:SettingUpaFirewall
HowiptablesWorks
Aboutiptables
JumpStart:BuildingaFirewallUsingsystem-config-securitylevel
AnatomyofaniptablesCommand
BuildingaSetofRules
system-config-securitylevel:GeneratesaSetofRules
SharinganInternetConnectionUsingNAT
ChapterSummary
Exercises
AdvancedExercises
Chapter26.Apache(httpd):SettingUpaWebServer
Introduction
AboutApache
JumpStartI:GettingApacheUpandRunning
JumpStartII:SettingUpApacheUsingsystem-config-httpd
FilesystemLayout
ConfigurationDirectives
TheRedHathttpd.confFile
Redirects
Multiviews
Server-GeneratedDirectoryListings(Indexing)
VirtualHosts
Troubleshooting
Modules
webalizer:AnalyzesWebTraffic
MRTG:MonitorsTrafficLoads
ErrorCodes
ChapterSummary
Exercises
AdvancedExercises
PartVI:Programming
Chapter27.ProgrammingTools
ProgramminginC
UsingSharedLibraries
make:KeepsaSetofProgramsCurrent
DebuggingCPrograms
Threads
SystemCalls
SourceCodeManagement
ChapterSummary
Exercises
AdvancedExercises
Chapter28.ProgrammingtheBourneAgainShell
ControlStructures
FileDescriptors
ParametersandVariables
BuiltinCommands
Expressions
ShellPrograms
ChapterSummary
Exercises
AdvancedExercises
PartVII:Appendixes
AppendixA.RegularExpressions
Characters
Delimiters
SimpleStrings
SpecialCharacters
Rules
BracketingExpressions
TheReplacementString
ExtendedRegularExpressions
AppendixSummary
AppendixB.Help
SolvingaProblem
FindingLinux-RelatedInformation
SpecifyingaTerminal
AppendixC.Security
Encryption
FileSecurity
EmailSecurity
NetworkSecurity
HostSecurity
SecurityResources
AppendixSummary
AppendixD.TheFreeSoftwareDefinition
AppendixE.TheLinux2.6Kernel
NativePosixThreadLibrary(NPTL)
IPSecurity(IPSec)
AsynchronousI/O(AIO)
0(1)Scheduler
OProfile
kksymoops
ReverseMapVirtualMemory(RMAPVM)
HugeTLBFS:TranslationLook-AsideBufferFilesystem
remap_file_pages
2.6NetworkStackFeatures(IGMPv3,IPv6,andOthers)
InternetProtocolVirtualServer(IPVS)
AccessControlLists(ACLs)
4GB-4GBMemorySplit:PhysicalAddressExtension(PAE)
SchedulerSupportforHyperThreadedCPUs
BlockI/O(BIO)BlockLayer
SupportforFilesystemsLargerThan2Terabytes
NewI/OElevators
InteractiveSchedulerResponseTuning
Glossary
Index
Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andthepublisherwas
awareofatrademarkclaim,thedesignationshavebeenprinted
withinitialcapitallettersorinallcapitals.
Theauthorandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany
kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin
connectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales,which
mayincludeelectronicversionsand/orcustomcoversand
contentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,please
contact:
U.S.CorporateandGovernmentSales
(800)382-3419
corpsales@pearsontechgroup.com
ForsalesoutsidetheUnitedStates,pleasecontact:
InternationalSales
international@pearsoned.com
LibraryofCongressCataloging-in-PublicationData:
Sobell,MarkG.
ApracticalguidetoRedHatLinux:FedoraCoreandRedHat
EnterpriseLinux/MarkG.Sobell.3rded.
p.cm.
Includesindex.
ISBN0-13-228027-2(pbk.:alk.paper)
1.Linux.2.Operatingsystems(Computers)I.Title.
QA76.76.O63S594852006
005'4'32dc22
2006014003
Copyright©2007MarkG.Sobell
Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationisprotectedbycopyright,andpermissionmustbe
obtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissionin
anyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Forinformationregarding
permissions,writeto:
PearsonEducation,Inc.
RightsandContractsDepartment
OneLakeStreet
UpperSaddleRiver,NJ07458
Fax:(201)236-3290
TextprintedintheUnitedStatesonrecycledpaperatCourierin
Stoughton,Massachusetts.
Firstprinting,June2006
Dedication
Formyuncle,DavidZ.Levitov(1920-2005),whogavemethe
world.
PraiseforAPracticalGuidetoRedHat®
Linux®,SecondEdition
"SinceI'minaneducationalenvironment,Ifoundthe
contentofSobell'sbooktoberightontargetandvery
helpfulforanyonemanagingLinuxintheenterprise.His
styleofwritingisveryclear.Hebuildsuptothechapter
exercises,whichIfindtoberelevanttoreal-world
scenariosauseroradminwouldencounter.AnIT/IS
studentwouldfindthisbookavaluablecomplementto
theireducation.Thevastamountofinformationis
extremelywellbalancedandSobellmanagestopresent
thecontentwithoutcomplicatedasidesandmeandering
prose.Thisisa'musthave'foranyonemanagingLinux
systemsinanetworkedenvironmentoranyonerunninga
Linuxserver.Iwouldalsohighlyrecommendittoan
experiencedcomputeruserwhoismovingtotheLinux
platform."
MaryNorbury
ITDirector
BarbaraDavisCenter/
UniversityofColoradoatDenver
fromareviewpostedonslashdot.org
"IhadthechancetouseyourUNIXbookswhenIwhen
wasincollegeyearsagoatCalPolySanLuisObispo,CA.I
havetosaythatyourbooksareamongthebest!They're
qualitybooksthatteachthetheoreticalaspectsand
applicationsoftheoperatingsystem."
BentonChan
ISEngineer
"Thebookhasmorethanliveduptomyexpectations
fromthemanyreviewsIread,eventhoughittargetsFC2.
Ihavefoundsomethingveryrarewithyourbook:It
doesn'treadlikethestandardatechnicaltext,itreads
morelikeastory.It'sapleasuretoreadandhardtoput
down.DidIsaythat?!:-)"
DavidHopkins
BusinessProcessArchitect
"Thanksforyourworkandforthebookyouwrote.There
arereallyfewbooksthatcanhelppeopletobecomemore
efficientadministratorsofdifferentworkstations.Wehope
(inRussia)thatyouwillcontinuebringingusanewlevel
ofunderstandingofLinux/UNIXsystems."
AntonPetukhov
"MarkSobellhaswrittenabookasapproachableasitis
authoritative."
JeffreyBianchine
Advocate,Author,Journalist
"Excellentreferencebook,wellsuitedforthesysadminof
aLinuxcluster,ortheownerofaPCcontemplating
installingarecentstableLinux.Don'tbeputoffbythe
dauntingheftofthebook.Sobellhasstriventobeas
inclusiveaspossible,intryingtoanticipateyoursystem
administrationneeds."
WesBoudville
Inventor
"APracticalGuidetoRedHat®Linux®isabrilliantbook.
ThankyouMarkSobell."
C.Pozrikidis
UniversityofCaliforniaatSanDiego
"ThisbookpresentsthebestoverviewoftheLinux
operatingsystemthatIhavefound....[It]shouldbe
veryhelpfulandunderstandablenomatterwhatthe
reader'sbackgroundis:traditionalUNIXuser,newLinux
devotee,orevenWindowsuser.Eachtopicispresentedin
aclear,completefashionandveryfewassumptionsare
madeaboutwhatthereaderknows....Thebookis
extremelyusefulasareference,asitcontainsa70-page
glossaryoftermsandisverywellindexed.Itisorganized
insuchawaythatthereadercanfocusonsimpletasks
withouthavingtowadethroughmoreadvancedtopics
untiltheyareready."
CamMarshall
MarshallInformationServiceLLC
MemberofFrontRangeUNIX
UsersGroup[FRUUG]
Boulder,Colorado
"Conclusively,thisisTHEbooktogetifyouareanew
LinuxuserandyoujustgotintoRH/Fedoraworld.There's
nootherbookthatdiscussessomanydifferenttopicsand
insuchdepth."
EugeniaLoli-Queru
EditorinChief
OSNews.com
Preface
Thebook
Whetheryouareanenduser,asystemadministrator,oralittle
ofeach,thisbookexplainswithstep-by-stepexampleshowto
getthemostoutofaFedoraCoreorRedHatEnterpriseLinux
system.In28chapters,thisbooktakesyoufrominstallinga
FedoraCoreorRedHatEnterpriseLinuxsystemthrough
understandingitsinnerworkingstosettingupsecureservers
thatrunonthesystem.
Theaudience
Thisbookisdesignedforawiderangeofreaders.Itdoesnot
requireyoutohaveprogrammingexperience,buthavingsome
experienceusingageneral-purposecomputerishelpful.This
bookisappropriatefor
StudentswhoaretakingaclassinwhichtheyuseLinux
Homeuserswhowanttosetupand/orrunLinux
ProfessionalswhouseLinuxatwork
Systemadministratorswhoneedanunderstandingof
Linuxandthetoolsthatareavailabletothem
ComputersciencestudentswhoarestudyingtheLinux
operatingsystem
ProgrammerswhoneedtounderstandtheLinux
programmingenvironment
Technicalexecutiveswhowanttogetagroundingin
Linux
Benefits
APracticalGuidetoRedHat®Linux®:FedoraCore™andRed
HatEnterpriseLinux,ThirdEdition,givesyouabroad
understandingofmanyfacetsofLinux,frominstallingRedHat
Linuxthroughusingandcustomizingit.Nomatterwhatyour
background,thisbookgivesyoutheknowledgeyouneedtoget
onwithyourwork.Youwillcomeawayfromthisbook
understandinghowtouseLinux,andthisbookwillremaina
valuablereferenceforyearstocome.
Overlap
IfyoureadAPracticalGuidetoLinux®Commands,Editors,and
ShellProgramming,youwillnoticesomeoverlapbetweenthat
bookandtheoneyouarereadingnow.Thefirstchapter,and
thechaptersontheutilities,thefilesystem,programmingtools,
andtheappendixonregularexpressionsareverysimilarinthe
twobooks,asarethethreechaptersontheBourneAgainShell
(bash).ChaptersthatappearinthisbookbutnotinAPractical
GuidetoLinux®Commands,Editors,andShellProgramming
includeChapters2and3(installation),Chapters4and8(Red
HatLinuxandtheGUI),Chapter10(networking),allofthe
chaptersinPartIV(systemadministration)andPartV
(servers),andAppendixC(security).
ThisBookIncludesFedoraCore5onaDVD
APracticalGuidetoRedHat®Linux®,ThirdEdition,includesa
DVDthatyoucanusetoinstallorupgradetoFedoraCore5.
Chapter2helpsyougetreadytoinstallFedoraCore.Chapter3
providesstep-by-stepinstructionsforinstallingFedoraCore
fromthisDVD.Thisbookguidesyouthroughlearningabout,
using,andadministratingFedoraCoreorRedHatEnterprise
Linux.
WhatIsNewinThisEdition?
ThethirdeditionofAPracticalGuidetoRedHat®Linux®covers
FedoraCore5andRedHatEnterpriseLinuxversion4.Allthe
changes,largeandsmall,thathavebeenmadetothese
productssincethesecondeditionofthisbookhavebeen
incorporatedintotheexplanationsandexamples.Thefollowing
listdetailsthesectionsofthisbookthathaveundergonethe
mostmajorchanges.
AccessControlLists(ACLs;page185)Asecurityfeature
thatprovidesfiner-grainedcontroloverwhichuserscan
accessspecificdirectoriesandfilesthandotraditionalLinux
permissions.
SELinux(SecurityEnhancedLinux;page400)Asecurity
featurethatenforcessecuritypoliciesthatlimitwhatauser
orprogramcando.
bash(theBourneAgainShell;Chapters7,9,and28)These
chaptershavebeenreorganizedandrewrittentoprovide
clearerexplanationsandbetterexamplesofhowbash
worksbothfromthecommandlineinday-to-dayworkand
asaprogramminglanguagetowriteshellscripts.
yum(page476)AprogramthatkeepsFedoraCoresystems
up-to-date.Theyumutilitydownloadssoftwarefrom
repositoriesontheInternet.Itcanupgradeexisting
softwareandinstallnewsoftware.Youcanrunyum
manuallyorhaveitrunautomaticallyeverynight.
pirut(page483)Agraphicalsoftwarepackagemanagement
utility.Thepirututilityissimilartoyumexceptthatitworks
withgroupsofsoftwarepackages.Forexample,youcan
usepiruttodownloadandinstalltheentireKDEdesktop
environmentwithonecommand.
parted(page65)Acommandlineutilitythatreportsonand
manipulatesharddiskpartitions.
FeaturesofThisBook
Thisbookisdesignedandorganizedsoyoucangetthemost
outofitintheshortestamountoftime.Youdonothavetoread
thisbookstraightthroughinpageorder.Onceyouare
comfortableusingLinux,youcanusethisbookasareference:
Lookupatopicofinterestinthetableofcontentsorindexand
readaboutit.OrthinkofthebookasacatalogofLinuxtopics:
Flipthroughthepagesuntilatopiccatchesyoureye.Thebook
includesmanypointerstoWebsiteswhereyoucanget
additionalinformation:ConsidertheInternetanextensionof
thisbook.
APracticalGuidetoRedHat®Linux®,ThirdEdition,is
structuredwiththefollowingfeatures:
Inthisbook,thetermRedHatLinuxreferstoboth
FedoraCoreandRedHatEnterpriseLinux.Features
thatapplytoonlyoneoperatingsystemortheotherare
markedassuchusingtheseindicators:FEDORAorRHEL.
Optionalsectionsenableyoutoreadthebookatdifferent
levels,returningtomoredifficultmaterialwhenyouare
readytodelveintoit.
Cautionboxeshighlightproceduresthatcaneasilygo
wrong,givingyouguidancebeforeyourunintotrouble.
Tipboxeshighlightwaysthatyoucansavetimebydoing
somethingdifferentlyorsituationswhenitmaybeusefulor
justinterestingtohaveadditionalinformation.
Securityboxespointoutplaceswhereyoucanmakea
systemmoresecure.Thesecurityappendixpresentsa
quickbackgroundinsystemsecurityissues.
Conceptsareillustratedbypracticalexamplesthroughout
thebook.
Chaptersummariesreviewtheimportantpointscovered
ineachchapter.
Reviewexercisesareincludedattheendofeachchapter
forreaderswhowanttofurtherhonetheirskills.Answersto
even-numberedexercisesareatwww.sobell.com.
Thisbookprovidesresourcesforfindingsoftwareonthe
Internet.Italsoexplainshowdownloadandinstall
softwareusingyum,BitTorrent,and,forRedHatEnterprise
Linux,RedHatNetwork(RHN).
Theglossarydefinesmorethan500commonterms.
ThebookdescribesindetailmanyimportantGNUtools,
includingthegccCcompiler,thegdbdebugger,theGNU
ConfigureandBuildSystem,make,andgzip.
Pointersthroughoutthetextprovidehelpinobtaining
onlinedocumentationfrommanysourcesincludingthe
localsystem,theRedHatWebsite,andotherlocationson
theInternet.
ManyusefulURLs(Internetaddresses)pointtositeswhere
youcanobtainsoftware,securityprogramsand
information,andmore.
Thecomprehensiveindexhelpsyoulocatetopicsquickly
andeasily.
KeyTopicsCoveredinThisBook
Thisbookcontainsalotofinformation.Thissectiondistillsand
summarizesitscontents.Youmaywanttoreviewthetableof
contentsformoredetail.Thisbook
Installation
DescribeshowtodownloadfromtheInternetandburna
FedoraCoreinstallationDVDorCDs.
Helpsyouplanthelayoutofthesystem'sharddiskand
assistsyouinusingDiskDruidorpartedtopartitionthe
harddisk.
ExplainshowtousetheLogicalVolumeManager(LVM2)to
setup,grow,andmigratelogicalvolumes,whicharesimilar
infunctiontotraditionaldiskpartitions.
DescribesindetailhowtoinstallRedHatLinuxfromaDVD,
CDs,aharddisk,oroveranetworkusingFTP,NFS,or
HTTP.
Coversresponsestotheboot:promptandexplainshowto
workwithAnaconda,RedHat'sinstallationprogram.
CoversthedetailsofinstallingandcustomizingtheX.org
versionoftheXWindowSystem.
WorkingwithRedHatLinux
Introducesthegraphicaldesktop(GUI)andexplainshowto
usedesktoptoolsincludingthepanel,Panelmenu,Main
menu,WindowOperationsmenu,Desktopmenu,Desktop
switcher,andterminalemulator.
PresentstheKDEdesktopandcoversusingKonquerorto
managefiles,startprograms,andbrowsetheWeb.
CoverstheGNOMEdesktopandtheNautilusfilemanager.
Explainshowtocustomizeyourdesktoptopleaseyour
sensesandhelpyouworkmoreefficiently.
CoverstheBourneAgainShell(bash)inthreechapters,
includinganentirechapteronshellprogrammingthat
includesmanysampleshellscripts.
Explainsthecommandlineinterfaceandintroducesmore
than30commandlineutilities.
Presentsatutorialonthevim(viwork-alike)textualeditor.
Coverstypesofnetworks,networkprotocols,andnetwork
utilities.
Explainshostnames,IPaddresses,andsubnets,and
exploreshowtousehostanddigtolookupdomainnames
andIPaddressesontheInternet.
Coversdistributedcomputingandtheclient/servermodel.
Systemadministration
ExplainshowtousetheRedHatsystem-config-*toolsto
configurethedisplay,DNS,Apache,anetworkinterface,
andmore.Youcanalsousethesetoolstoaddusersand
managelocalandremoteprinters.(Seepage415foralist
ofthetools.)
Describeshowtousethefollowingtoolstodownload
softwareandkeepasystemcurrent:
yumDownloadsandinstallssoftwarepackagesfromthe
Internet,keepingasystemup-to-dateandresolving
dependenciesasitprocessesthepackages.Youcanrun
yummanuallyorsetituptorunautomaticallyevery
night.
BitTorrentGoodfordistributinglargeamountsofdata
suchastheFedorainstallationDVDandCDs.Themore
peoplewhouseBitTorrenttodownloadafile,thefaster
itworks.
up2dateTheRedHatEnterpriseLinuxtoolforkeeping
systemsoftwarecurrent.
Coversgraphicalsystemadministrationtools,includingthe
Mainmenu,GNOMEandKDEmenusystems,KDEControl
Center,andKDEControlpanel.
Explainssystemoperation,includingthebootprocess,init
scripts,emergencymode,rescuemode,single-userand
multiusermodes,andstepstotakeifthesystemcrashes.
Describesfiles,directories,andfilesystems,includingtypes
offilesandfilesystems,fstab(thefilesystemtable),
automaticallymountedfilesystems,filesystemintegrity
checks,filesystemutilities,andfine-tuningoffilesystems.
Coversbackuputilitiesincludingtar,cpio,dump,andrestore.
ExplainshowtocustomizeandbuildaLinuxkernel.
Security
Helpsyoumanagebasicsystemsecurityissuesusingssh
(secureshell),vsftpd(secureFTPserver),Apache(the
httpdWebserver),iptables(firewall),andmore.
PresentsacompletesectiononSELinux(SecurityEnhanced
Linux),includinginstructionsforusingsystem-config-
securityleveltoconfigureSELinux.
Coversusingsystem-config-securityleveltosetupabasic
firewalltoprotectthesystem.
ProvidesinstructionsonusingiptablestoshareanInternet
connectionoveraLANandtobuildadvancedfirewalls.
Describeshowtosetupachrootjailtoprotectaserver
system.
ExplainshowtouseTCPwrapperstocontrolwhocan
accessaserver.
Coverscontrollingserversusingthexinetdsuperserver.
Clientsandservers
ExplainshowtosetupandusethemostpopularLinux
servers,providingachapteroneach:Apache,Samba,
OpenSSH,sendmail,DNS,NFS,FTP,iptables,andNIS(allof
whichareincludedwithRedHatLinux).
DescribeshowtosetupaCUPSprinterserver.
DescribeshowtosetupanduseaDHCPserver.
Programming
CoversprogrammingtoolsincludingtheGNUgcccompiler,
thegdbdebugger,make,andCVSformanagingsourcecode.
ExplainshowtodebugaCprogram.
Describeshowtoworkwithsharedlibraries.
Providesacompletechapteronshellprogrammingusing
bash,includingmanyexamples.
Details
PartI
PartI,"InstallingRedHatLinux,"discusseshowtoinstall
FedoraCoreorRedHatEnterpriseLinux.Chapter2presents
anoverviewoftheprocessofinstallingRedHatLinux,including
hardwarerequirements,downloadingandburningaDVDor
CDs,andplanningthelayoutoftheharddisk.Chapter3isa
step-by-stepguidetoinstallingeitherversionofRedHatLinux
andcoversinstallingfromaDVDorCDs,fromalocalharddisk,
andoverthenetworkusingFTP,NFS,orHTTP.Italsoshows
howtosetuptheXWindowSystemandcustomizeyour
graphicaluserinterface(GUI).
PartII
PartII,"GettingStartedwithRedHatLinux,"familiarizesyou
withRedHatLinux,coveringloggingin,theGUI,utilities,the
filesystem,andtheshell.Chapter4introducesdesktop
features,includingthepanelandtheMainmenu;explainshow
touseKonquerortomanagefiles,runprograms,andbrowse
theWeb;andcoversfindingdocumentation,dealingwithlogin
problems,andusingthewindowmanager.Chapter5
introducestheshellcommandlineinterface,describesmore
than30usefulutilities,andpresentsatutorialonthevimtext
editor.Chapter6discussestheLinuxhierarchicalfilesystem,
coveringfiles,filenames,pathnames,workingwithdirectories,
accesspermissions,andhardandsymboliclinks.Chapter7
introducestheBourneAgainShell(bash)anddiscusses
commandlineargumentsandoptions,redirectinginputtoand
outputfromcommands,runningprogramsinthebackground,
andusingtheshelltogenerateandexpandfilenames.
Tip:Experiencedusersmaywanttoskim
PartII
IfyouhaveusedaUNIXorLinuxsystembefore,you
maywanttoskimoverorskipsomeorallofthe
chaptersinPartII.Allreadersshouldtakealookat
"ConventionsUsedinThisBook"(page17),which
explainsthetypographicandlayoutconventionsthat
thisbookuses,and"GettingtheFacts:Whereto
FindDocumentation"(page102),whichpointsout
bothlocalandremotesourcesofLinuxandRedHat
documentation.
PartIII
PartIII,"DiggingintoRedHatLinux,"goesintomoredetail
aboutworkingwiththesystem.Chapter8discussestheGUI
andincludesasectiononhowtorunagraphicalprogramona
remotesystemandhavethedisplayappearlocally.Thesection
onGNOMEdescribesGNOMEutilitiesandexplainshowtouse
theNautilusfilemanager,includingitsspatialview,whilethe
sectiononKDEexplainsmoreaboutKonquerorandKDE
utilities.Chapter9extendsthebashcoveragefromChapter7,
explaininghowtoredirecterroroutput,avoidoverwritingfiles,
andworkwithjobcontrol,processes,startupfiles,important
shellbuiltincommands,parameters,shellvariables,and
aliases.Chapter10explainsnetworks,networksecurity,and
theInternetanddiscussestypesofnetworks,subnets,
protocols,addresses,hostnames,andvariousnetworkutilities.
Thesectionondistributedcomputingdescribestheclient/server
modelandsomeoftheserversyoucanuseonanetwork.
Detailsofsettingupandusingclientsandserversarereserved
untilPartV.
PartIV
PartIVcoverssystemadministration.Chapter11discusses
coreconceptssuchasSuperuser,SELinux(SecurityEnhanced
Linux),systemoperation,generalinformationabouthowtoset
upaserver,DHCP,andPAM.Chapter12explainstheLinux
filesystem,goingintodetailabouttypesoffiles,including
specialanddevicefiles,theuseoffscktoverifytheintegrityof
andrepairfilesystems,andtheuseoftune2fstochange
filesystemparameters.Chapter13explainshowtokeepa
systemup-to-datebydownloadingsoftwarefromtheInternet
andinstallingit,includingexamplesofusingyum,BitTorrent,
andRedHat'sup2dateutility.Chapter14explainshowtosetup
theCUPSprintingsystemsoyoucanprintonthelocalsystem
aswellasonremotesystems.Chapter15detailscustomizing
andbuildingaLinuxkernel.Chapter16coversadditional
administrationtasks,includingsettingupuseraccounts,
backingupfiles,schedulingautomatedtasks,trackingdisk
usage,andsolvinggeneralproblems.Chapter17explainshow
tosetupalocalareanetwork(LAN),includingbothhardware
(includingwireless)andsoftwaresetup.
PartV
PartVgoesintodetailaboutsettingupandrunningserversand
connectingtothemwithclients.Thechaptersinthispartofthe
bookcoverthefollowingclients/servers:
OpenSSHSetupanOpenSSHserverandusesh,scp,and
sftptocommunicatesecurelyovertheInternet.
FTPSetupavsftpdsecureFTPserveranduseanyof
severalFTPclientstoexchangefileswiththeserver.
MailConfiguresendmailanduseWebmail,POP3,orIMAP
toretrieveemail;useSpamAssassintocombatspam.
NISSetupNIStofacilitatesystemadministrationofaLAN.
NFSSharefilesystemsbetweensystemsonanetwork.
SambaSharefilesystemsandprintersbetweenWindows
andLinuxsystems.
DNS/BINDSetupadomainnameservertoletother
systemsontheInternetknowthenamesandIPaddresses
ofyoursystemstheymayneedtocontact.
iptablesShareasingleInternetconnectionbetween
systemsonaLANandsetupafirewalltoprotectlocal
systems.
ApacheSetupanHTTPserverthatservesWebpagesthat
browserscandisplay.
PartVI
PartVIcoversprogramming.Chapter27discusses
programmingtoolsandenvironmentsavailableunderRedHat
Linux,includingtheCprogramminglanguageanddebugger,
make,sharedlibraries,andsourcecodemanagementusingCVS.
Chapter28goesintogreaterdepthaboutshellprogramming
usingbash,withthediscussionbeingenhancedbyextensive
examples.
PartVII
PartVIIincludesappendixesonregularexpressions,helpful
Websites,systemsecurity,andfreesoftware.Thispartalso
includesanextensiveglossarywithmorethan500entriesand
acomprehensiveindex.
Supplements
Theauthor'shomepage(www.sobell.com)contains
downloadablelistingsofthelongerprogramsfromthisbookas
wellaspointerstomanyinterestingandusefulLinuxsiteson
theWorldWideWeb,alistofcorrectionstothebook,answers
toeven-numberedexercises,andasolicitationforcorrections,
comments,andsuggestions.
Thanks
FirstandforemostIwanttothankMarkL.Taub,editor-in-chief,
PrenticeHall,whoencouragedandproddedme(carrot-and-
stickapproach)andkeptmeontrack.Markisuniqueinmy25
yearsofbookwritingexperience:aneditorwhoworkswiththe
toolsIamwritingabout.BecauseMarkrunsLinuxonhishome
computer,weshareexperiencesasIwrite.Hiscommentsand
directionareinvaluable.Thankyou,MarkT.
ThanksalsotothefolksatPrenticeHallwhohelpedbringthis
booktolife,especiallyJulieNahil,full-serviceproduction
manager,whogavemeguidanceandmuchlatitudewhile
keepingmetoscheduleinproducingthebook;JohnFuller,
managingeditor,whokeptthelargeviewincheck;Noreen
Regina,editorialassistant,whoattendedtothemanydetails
involvedinpublishingthisbook;HeatherFox,publicist;Dan
Scherf,mediadeveloper;SandraSchroeder,designmanager;
KimSpilker,marketingmanager;andeveryoneelsewho
workedbehindthescenestomakethisbookhappen.
IamalsoindebtedtoDenisHowe,theeditorofTheFreeOn-
lineDictionaryofComputing(FOLDOC).Denishasgraciously
permittedmetouseentriesfromhiscompilation.Besureto
lookatthedictionary(www.foldoc.org).
Abig"thankyou"tothefolkswhoreadthroughthedraftsof
thebookandmadecommentsthatcausedmetorefocusparts
ofthebookwherethingswerenotclearorwereleftout
altogether:DavidChisnall;ChrisKarr,NorthwesternUniversity;
JesseKeating,FedoraProject;ScottMann,IBM,Systems
ManagementandIntegrationProfessional;MatthewMiller,
BostonUniversity;andGeorgeVish,SeniorEducation
Consultant,HPUSLinuxProgramManager,Hewlett-Packard
Company.
Thanksalsotothefollowingpeoplewhohelpedwiththefirst
andsecondeditionsofthisbook:CarstenPfeiffer,Software
EngineerandKDEDeveloper;AaronWeber,Ximian;Cristof
Falk,SoftwareDeveloperatCritterDesign;SteveElgersma,
ComputerScienceDepartment,PrincetonUniversity;ScottDier,
UniversityofMinnesota;RobertHaskins,ComputerNetWorks;
LarsKellogg-Stedman,HarvardUniversity;JimA.Lola,Principal
SystemsConsultant,PrivateerSystems,LLC;EricS.Raymond,
cofounder,OpenSourceInitiative;ScottMann;Randall
Lechlitner,IndependentComputerConsultant;JasonWertz,
ComputerScienceInstructor,MontgomeryCountyCommunity
College;JustinHowell,SolanoCommunityCollege;EdSawicki,
TheAcceleratedLearningCenter;DavidMercer,Contechst;
JeffreyBianchine,Advocate,Author,Journalist;JohnKennedy;
andJimDennis,StarshineTechnicalServices.
ThanksalsotoDustinPuryear,PuryearInformationTechnology;
GaborLiptak,IndependentConsultant;BartSchaefer,Chief
TechnicalOfficer,iPost;MichaelJ.Jordan,WebDeveloper,Linux
OnlineInc.;StevenGibson,ownerofSuperAnt.com;John
Viega,founderandChiefScientist,SecureSoftware,Inc.;K.
RachaelTreu,InternetSecurityAnalyst,GlobalCrossing;Kara
Pritchard,K&SPritchardEnterprises,Inc.;GlenWiley,Capital
OneFinances;KarelBaloun,SeniorSoftwareEngineer,
Looksmart,Ltd.;MatthewWhitworth;DameonD.Welch-
Abernathy,NokiaSystems;JoshSimon,Consultant;Stan
Isaacs;andDr.EricH.HerrinII,VicePresident,HerrinSoftware
Development,Inc.AndthankstoDougHughes,long-time
systemdesignerandadministrator,whogavemeabighand
withthesectionsonsystemadministration,networks,the
Internet,andprogramming.
MorethanksgotoconsultantsLorraineCallahanandSteve
Wampler;RonaldHiller,GraburnTechnology,Inc.;CharlesA.
Plater,WayneStateUniversity;BobPalowoda;TomBialaski,
SunMicrosystems;RogerHartmuller,TISLabsatNetwork
Associates;KaowenLiu;AndySpitzer;RikSchneider;JesseSt.
Laurent;SteveBellenot;RayW.Hiltbrand;JenniferWitham;
Gert-JanHagenaars;andCasperDik.
APracticalGuidetoRedHat®Linux®,ThirdEdition,isbasedin
partontwoofmypreviousUNIXbooks:UNIXSystemV:A
PracticalGuideandAPracticalGuidetotheUNIXSystem.Many
peoplehelpedmewiththosebooks,andthanksheregotoPat
Parseghian,Dr.KathleenHemenway,andBrianLaRose;Byron
A.Jeff,ClarkAtlantaUniversity;CharlesStross;JeffGitlin,
LucentTechnologies;KurtHockenbury;MauryBach,IntelIsrael
Ltd.;PeterH.Salus;RahulDave,UniversityofPennsylvania;
SeanWalton,IntelligentAlgorithmicSolutions;TimSegall,
ComputerSciencesCorporation;BehrouzForouzan,DeAnza
College;MikeKeenan,VirginiaPolytechnicInstituteandState
University;MikeJohnson,OregonStateUniversity;Jandelyn
Plane,UniversityofMaryland;ArnoldRobbinsandSathis
Menon,GeorgiaInstituteofTechnology;CliffShaffer,Virginia
PolytechnicInstituteandStateUniversity;andSteven
Stepanek,CaliforniaStateUniversity,Northridge,forreviewing
thebook.
Icontinuetobegratefultothemanypeoplewhohelpedwith
theearlyeditionsofmyUNIXbooks.Specialthanksaredueto
RogerSippl,LauraKing,andRoyHarringtonforintroducingme
totheUNIXsystem.Mymother,Dr.HelenSobell,provided
invaluablecommentsontheoriginalmanuscriptatseveral
junctures.Also,thanksgotoIsaacRabinovitch,Professor
RaphaelFinkel,ProfessorRandolphBentson,BobGreenberg,
ProfessorUdoPooch,JudyRoss,Dr.RobertVeroff,Dr.Mike
Denny,JoeDiMartino,Dr.JohnMashey,DianeSchulz,Robert
Jung,CharlesWhitaker,DonCragun,BrianDougherty,Dr.
RobertFish,GuyHarris,PingLiao,GaryLindgren,Dr.Jarrett
Rosenberg,Dr.PeterSmith,BillWeber,MikeBianchi,Scooter
Morris,ClarkeEchols,OliverGrillmeyer,Dr.DavidKorn,Dr.
ScottWeikart,andDr.RichardCurtis.
Itakeresponsibilityforanyerrorsandomissionsinthisbook.If
youfindoneorjusthaveacomment,letmeknow
(mgs@sobell.com)andIwillfixitinthenextprinting.Myhome
page(www.sobell.com)containsalistoferrorsandcredits
thosewhofoundthem.Italsoofferscopiesofthelongerscripts
fromthebookandpointerstomanyinterestingLinuxpages.
MarkG.Sobell
SanFrancisco,California
1.WelcometoLinux
INTHISCHAPTER
TheGNU-LinuxConnection 2
TheLinux2.6Kernel 5
TheHeritageofLinux:UNIX 5
WhatIsSoGoodAboutLinux? 6
OverviewofLinux 10
AdditionalFeaturesofLinux 14
ConventionsUsedinThisBook 17
TheLinuxkernelwasdevelopedbyFinnishundergraduate
studentLinusTorvalds,whousedtheInternettomakethe
sourcecodeimmediatelyavailabletoothersforfree.Torvalds
releasedLinuxversion0.01inSeptember1991.
Thenewoperatingsystemcametogetherthroughalotofhard
work.Programmersaroundtheworldwerequicktoextendthe
kernelanddevelopothertools,addingfunctionalitytomatch
thatalreadyfoundinbothBSDUNIXandSystemVUNIX
(SVR4)aswellasnewfunctionality.
TheLinuxoperatingsystem,developedthroughthecooperation
ofmany,manypeoplearoundtheworld,isaproductofthe
Internetandisafreeoperatingsystem.Inotherwords,allthe
sourcecodeisfree.Youarefreetostudyit,redistributeit,and
modifyit.Asaresult,thecodeisavailablefreeofcostnocharge
forthesoftware,source,documentation,orsupport(via
newsgroups,mailinglists,andotherInternetresources).Asthe
GNUFreeSoftwareDefinition(reproducedinAppendixD)puts
it:
Freebeer
"Freesoftware"isamatterofliberty,notprice.To
understandtheconcept,youshouldthinkof"free"asin
"freespeech,"notasin"freebeer."
TheGNULinuxConnection
Anoperatingsystemisthelow-levelsoftwarethatschedules
tasks,allocatesstorage,andhandlestheinterfacesto
peripheralhardware,suchasprinters,diskdrives,thescreen,
keyboard,andmouse.Anoperatingsystemhastwomainparts:
thekernelandthesystemprograms.Thekernelallocates
machineresources,includingmemory,diskspace,andCPU
(page1026)cycles,toallotherprogramsthatrunonthe
computer.Thesystemprogramsperformhigher-level
housekeepingtasks,oftenactingasserversinaclient/server
relationship.LinuxisthenameofthekernelthatLinusTorvalds
presentedtotheworldin1991andthatmanyothershave
workedonsincethentoenhance,stabilize,expand,andmake
moresecure.
TheHistoryofGNULinux
Thissectionpresentssomebackgroundontherelationship
betweenGNUandLinux.
Fadeto1983
RichardStallman(www.stallman.org)announced[1]theGNU
Projectforcreatinganoperatingsystem,bothkerneland
systemprograms,andpresentedtheGNUManifesto,[2]which
beginsasfollows:
[1]www.gnu.org/gnu/initial-announcement.html
[2]www.gnu.org/gnu/manifesto.html
GNU,whichstandsforGnu'sNotUNIX,isthenamefor
thecompleteUNIX-compatiblesoftwaresystemwhichI
amwritingsothatIcangiveitawayfreetoeveryonewho
canuseit.
Someyearslater,Stallmanaddedafootnotetothepreceding
sentencewhenherealizedthatitwascreatingconfusion:
Thewordingherewascareless.Theintentionwasthat
nobodywouldhavetopayfor*permission*tousethe
GNUsystem.Butthewordsdon'tmakethisclear,and
peopleofteninterpretthemassayingthatcopiesofGNU
shouldalwaysbedistributedatlittleornocharge.That
wasnevertheintent;lateron,themanifestomentionsthe
possibilityofcompaniesprovidingtheserviceof
distributionforaprofit.SubsequentlyIhavelearnedto
distinguishcarefullybetween"free"inthesenseof
freedomand"free"inthesenseofprice.Freesoftwareis
softwarethatusershavethefreedomtodistributeand
change.Someusersmayobtaincopiesatnocharge,
whileotherspaytoobtaincopiesandifthefundshelp
supportimprovingthesoftware,somuchthebetter.The
importantthingisthateveryonewhohasacopyhasthe
freedomtocooperatewithothersinusingit.
Inthemanifesto,afterexplainingalittleabouttheprojectand
whathasbeenaccomplishedsofar,Stallmancontinues:
WhyIMustWriteGNU
IconsiderthatthegoldenrulerequiresthatifIlikea
programImustshareitwithotherpeoplewholikeit.
Softwaresellerswanttodividetheusersandconquer
them,makingeachuseragreenottosharewithothers.I
refusetobreaksolidaritywithotherusersinthisway.I
cannotingoodconsciencesignanondisclosureagreement
orasoftwarelicenseagreement.ForyearsIworked
withintheArtificialIntelligenceLabtoresistsuch
tendenciesandotherinhospitalities,buteventuallythey
hadgonetoofar:Icouldnotremaininaninstitution
wheresuchthingsaredoneformeagainstmywill.
SothatIcancontinuetousecomputerswithoutdishonor,
Ihavedecidedtoputtogetherasufficientbodyoffree
softwaresothatIwillbeabletogetalongwithoutany
softwarethatisnotfree.IhaveresignedfromtheAILab
todenyMITanylegalexcusetopreventmefromgiving
GNUaway.
NextScene,1991
TheGNUProjecthasmovedwellalongtowarditsgoal.Muchof
theGNUoperatingsystem,exceptforthekernel,iscomplete.
RichardStallmanlaterwrites:
Bytheearly'90swehadputtogetherthewholesystem
asidefromthekernel(andwewerealsoworkingona
kernel,theGNUHurd,[3]whichrunsontopofMach[4]).
Developingthiskernelhasbeenalotharderthanwe
expected,andwearestillworkingonfinishingit.[5]
...[M]anybelievethatonceLinusTorvaldsfinishedwriting
thekernel,hisfriendslookedaroundforotherfree
software,andfornoparticularreasonmosteverything
necessarytomakeaUNIX-likesystemwasalready
available.
WhattheyfoundwasnoaccidentitwastheGNUsystem.
Theavailablefreesoftware[6]addeduptoacomplete
systembecausetheGNUProjecthadbeenworkingsince
1984tomakeone.TheGNUManifestohadsetforththe
goalofdevelopingafreeUNIX-likesystem,calledGNU.
TheInitialAnnouncementoftheGNUProjectalsooutlines
someoftheoriginalplansfortheGNUsystem.Bythe
timeLinuxwaswritten,the[GNU]systemwasalmost
finished.[7]
[3]www.gnu.org/software/hurd/hurd.html
[4]www.gnu.org/software/hurd/gnumach.html
[5]www.gnu.org/software/hurd/hurd-and-linux.html
[6]SeeAppendixDorwww.gnu.org/philosophy/free-sw.html.
[7]www.gnu.org/gnu/linux-and-gnu.html
TodaytheGNU"operatingsystem"runsontopoftheFreeBSD
(www.freebsd.org)andNetBSD(www.netbsd.org)kernelswith
completeLinuxbinarycompatibilityandontopofHurdpre-
releasesandDarwin(developer.apple.com/opensource)without
thiscompatibility.
TheCodeIsFree
ThetraditionoffreesoftwaredatesbacktothedayswhenUNIX
wasreleasedtouniversitiesatnominalcost,whichcontributed
toitsportabilityandsuccess.ThistraditiondiedasUNIXwas
commercializedandmanufacturersregardedthesourcecodeas
proprietary,makingiteffectivelyunavailable.Anotherproblem
withthecommercialversionsofUNIXrelatedtotheir
complexity.AseachmanufacturertunedUNIXforaspecific
architecture,itbecamelessportableandtoounwieldyfor
teachingandexperimentation.
MINIX
Twoprofessorscreatedtheirownstripped-downUNIXlook-
alikesforeducationalpurposes:DougComercreatedXINU
(www.cs.purdue.edu/research/xinu.html)andAndrew
TanenbaumcreatedMINIX(www.cs.vu.nl/~ast/minix.html).
LinusTorvaldscreatedLinuxtocounteracttheshortcomingsin
MINIX.Everytimetherewasachoicebetweencodesimplicity
andefficiency/features,Tanenbaumchosesimplicity(tomakeit
easytoteachwithMINIX),whichmeantthatthissystemlacked
manyfeaturespeoplewanted.Linuxgoesintheopposite
direction.
YoucanobtainLinuxatnocostovertheInternet(page35).
YoucanalsoobtaintheGNUcodeviatheU.S.mailatamodest
costformaterialsandshipping.YoucansupporttheFree
SoftwareFoundation(www.fsf.org)bybuyingthesame(GNU)
codeinhigher-pricedpackages,andyoucanbuycommercial
packagedreleasesofLinux(calleddistributions),suchasRed
HatLinux,thatincludeinstallationinstructions,software,and
support.
GPL
LinuxandGNUsoftwarearedistributedunderthetermsofthe
GNUGeneralPublicLicense(GPL,
www.gnu.org/licenses/licenses.html).TheGPLsaysyouhave
therighttocopy,modify,andredistributethecodecoveredby
theagreement.Whenyouredistributethecode,however,you
mustalsodistributethesamelicensewiththecode,makingthe
codeandthelicenseinseparable.Ifyougetsourcecodeoffthe
InternetforanaccountingprogramthatisundertheGPLand
thenmodifythatcodeandredistributeanexecutableversionof
theprogram,youmustalsodistributethemodifiedsourcecode
andtheGPLagreementwithit.Becausethisarrangementisthe
reverseofthewayanormalcopyrightworks(itgivesrights
insteadoflimitingthem),ithasbeentermedacopyleft.(This
paragraphisnotalegalinterpretationoftheGPL;itishere
merelytogiveyouanideaofhowitworks.RefertotheGPL
itselfwhenyouwanttomakeuseofit.)
HaveFun!
TwokeywordsforLinuxare"HaveFun!"Thesewordspopupin
promptsanddocumentation.TheUNIXnowLinuxcultureis
steepedinhumorthatcanbeseenthroughoutthesystem.For
example,lessismoreGNUhasreplacedtheUNIXpagingutility
namedmorewithanimprovedutilitynamedless.Theutilityto
viewPostScriptdocumentsisnamedghostscript,andoneof
severalreplacementsforthevieditorisnamedelvis.While
machineswithIntelprocessorshave"IntelInside"logoson
theiroutside,someLinuxmachinessport"LinuxInside"logos.
AndTorvaldshimselfhasbeenseenwearingaT-shirtbearinga
"LinusInside"logo.
TheLinux2.6Kernel
TheLinux2.6kernelwasreleasedonDecember17,2003.This
kernelhasmanyfeaturesthatofferincreasedsecurityand
speed.Someofthesefeaturesbenefitendusersdirectly;others
helpdevelopersproducebettercodeandfindproblemsmore
quickly.SeeAppendixEforadescriptionofthenewfeaturesin
theLinux2.6kernel.
TheHeritageofLinux:UNIX
TheUNIXsystemwasdevelopedbyresearcherswhoneededa
setofmoderncomputingtoolstohelpthemwiththeirprojects.
Thesystemallowedagroupofpeopleworkingtogetherona
projecttoshareselecteddataandprogramswhilekeeping
otherinformationprivate.
Universitiesandcollegesplayedamajorroleinfurtheringthe
popularityoftheUNIXoperatingsystemthroughthe"four-year
effect."WhentheUNIXoperatingsystembecamewidely
availablein1975,BellLabsofferedittoeducationalinstitutions
atnominalcost.Theschools,inturn,useditintheircomputer
scienceprograms,ensuringthatcomputersciencestudents
becamefamiliarwithit.BecauseUNIXwassuchanadvanced
developmentsystem,thestudentsbecameacclimatedtoa
sophisticatedprogrammingenvironment.Asthesestudents
graduatedandwentintoindustry,theyexpectedtoworkina
similarlyadvancedenvironment.Asmoreofthemworkedtheir
wayuptheladderinthecommercialworld,theUNIXoperating
systemfounditswayintoindustry.
InadditiontointroducingstudentstotheUNIXoperating
system,theComputerSystemsResearchGroup(CSRG)atthe
UniversityofCaliforniaatBerkeleymadesignificantadditions
andchangestoit.Infact,itmadesomanypopularchanges
thatoneversionofthesystemiscalledtheBerkeleySoftware
Distribution(BSD)oftheUNIXsystem(orjustBerkeleyUNIX).
TheothermajorversionisUNIXSystemV(SVR4),which
descendedfromversionsdevelopedandmaintainedbyAT&T
andUNIXSystemLaboratories.
WhatIsSoGoodAboutLinux?
InrecentyearsLinuxhasemergedasapowerfulandinnovative
UNIXwork-alike.ItspopularityissurpassingthatofitsUNIX
predecessors.AlthoughitmimicsUNIXinmanyways,theLinux
operatingsystemdepartsfromUNIXinseveralsignificantways:
TheLinuxkernelisimplementedindependentlyofbothBSDand
SystemV,thecontinuingdevelopmentofLinuxistakingplace
throughthecombinedeffortsofmanycapableindividuals
throughouttheworld,andLinuxputsthepowerofUNIXwithin
easyreachofbusinessandpersonalcomputerusers.Usingthe
Internet,today'sskilledprogrammerssubmitadditionsand
improvementstotheoperatingsystemtoLinusTorvalds,GNU,
oroneoftheotherauthorsofLinux.
Applications
ArichselectionofapplicationsisavailableforLinuxbothfree
andcommercialaswellasawidevarietyoftools:graphical,
wordprocessing,networking,security,administration,Web
server,andmanyothers.Largesoftwarecompanieshave
recentlyseenthebenefitinsupportingLinuxandnowhaveon-
staffprogrammerswhosejobitistodesignandcodetheLinux
kernel,GNU,KDE,orothersoftwarethatrunsonLinux.For
example,IBM(www.ibm.com/linux)isamajorLinuxsupporter.
LinuxconformsincreasinglymorecloselytoPOSIXstandards,
andsomedistributionsandpartsofothersmeetthisstandard.
(See"Standards"onpage8formoreinformation.)These
developmentsmeanthatLinuxisbecomingmoremainstream
andisrespectedasanattractivealternativetootherpopular
operatingsystems.
Peripherals
AnotheraspectofLinuxthatappealstousersistheamazing
rangeofperipheralsthatissupportedandthespeedwithwhich
supportfornewperipheralsemerges.Linuxoftensupportsa
peripheralorinterfacecardbeforeanycompanydoes.
Unfortunatelysometypesofperipheralsparticularlyproprietary
graphicscardslagintheirsupportbecausethemanufacturersdo
notreleasespecificationsorsourcecodefordriversinatimely
manner,ifatall.
Software
Alsoimportanttousersistheamountofsoftwarethatis
availablenotjustsourcecode(whichneedstobecompiled)but
alsoprebuiltbinariesthatareeasytoinstallandreadytorun.
Theseincludemorethanfreesoftware.Netscape,forexample,
hasbeenavailableforLinuxfromthestartandincludedJava
supportbeforeitwasavailablefrommanycommercialvendors.
NowitssiblingMozilla/Thunder-bird/Firefoxisalsoaviable
browser,mailclient,andnewsreader,performingmanyother
functionsaswell.
Platforms
LinuxisnotjustforIntel-basedplatforms:Ithasbeenportedto
andrunsonthePowerPCincludingApplecomputers(ppclinux),
Compaq's(néeDigitalEquipmentCorporation)Alpha-based
machines,MIPS-basedmachines,Motorola's68K-based
machines,various64-bitsystems,andIBM'sS/390.Noris
Linuxjustforsingle-processormachines:Asofversion2.0,it
runsonmultiple-processormachines(SMPs).Italsoincludesan
O(1)scheduler,whichdramaticallyincreasesscalabilityonSMP
systems.
Emulators
Linuxsupportsprograms,calledemulators,thatruncode
intendedforotheroperatingsystems.Byusingemulatorsyou
canrunsomeDOS,Windows,andMacintoshprogramsunder
Linux.Wine(www.winehq.com)isanopen-source
implementationoftheWindowsAPIontopoftheXWindow
SystemandUNIX/Linux;QEMU(fabrice.bellard.free.fr/qemu)is
aCPU-onlyemulatorthatexecutesx86Linuxbinariesonnon-
x86Linuxsystems.
Xen
Xen,whichwascreatedattheUniversityofCambridgeandis
nowbeingdevelopedintheopen-sourcecommunity,isan
open-sourcevirtualmachinemonitor(VMM).AVMMenables
severalvirtualmachines(VMs),eachrunninganinstanceofa
separateoperatingsystem,torunonasinglecomputer.Xen
isolatestheVMssothatifonecrashesitdoesnotaffectanyof
theothers.Inaddition,Xenintroducesminimalperformance
overheadwhencomparedwithrunningeachoftheoperating
systemsnatively.
UsingVMs,youcanexperimentwithcutting-edgereleasesof
operatingsystemsandapplicationswithoutconcernforthe
base(stable)system,allonasinglemachine.Youcanalsoset
upandtestnetworksofsystemsonasinglemachine.Xen
presentsasandbox,anarea(system)thatyoucanworkin
withoutregardfortheresultsofyourworkorfortheneedto
cleanup.
FedoraCore5includesXen3.0.Thisbookdoesnotcoverthe
installationoruseofXen.See
www.fedoraproject.org/wiki/FedoraXenQuickstartFC5for
installationinstructions.
FormoreinformationonXen,refertothewikiat
wiki.xensource.com/xenwikiandtheXenhomepageat
www.cl.cam.ac.uk/Research/SRG/netos/xen.
WhyLinuxIsPopularwithHardwareCompanies
andDevelopers
Twotrendsinthecomputerindustrysetthestageforthe
popularityofUNIXandLinux.First,advancesinhardware
technologycreatedtheneedforanoperatingsystemthatcould
takeadvantageofavailablehardwarepower.Inthemid-1970s,
minicomputersbeganchallengingthelargemainframe
computersbecause,inmanyapplications,minicomputerscould
performthesamefunctionslessexpensively.Morerecently,
powerful64-bitprocessorchips,plentifulandinexpensive
memory,andlower-pricedharddiskstoragehaveallowed
hardwarecompaniestoinstallmultiuseroperatingsystemson
desktopcomputers.
Proprietaryoperatingsystems
Second,withthecostofhardwarecontinuallydropping,
hardwaremanufacturerscouldnolongeraffordtodevelopand
supportproprietaryoperatingsystems.Aproprietaryoperating
systemiswrittenandownedbythemanufacturerofthe
hardware(forexample,DEC/CompaqownsVMS).Today's
manufacturersneedagenericoperatingsystemthattheycan
easilyadapttotheirmachines.
Genericoperatingsystems
Agenericoperatingsystemiswrittenoutsideofthecompany
manufacturingthehardwareandissold(UNIX,Windows)or
given(Linux)tothemanufacturer.Linuxisagenericoperating
systembecauseitrunsondifferenttypesofhardwareproduced
bydifferentmanufacturers.Ofcourse,ifmanufacturerscanpay
onlyfordevelopmentandavoidper-unitcosts(astheyhaveto
paytoMicrosoftforeachcopyofWindowstheysell),
manufacturersaremuchbetteroff.Inturn,softwaredevelopers
needtokeepthepricesoftheirproductsdown;theycannot
affordtoconverttheirproductstorunundermanydifferent
proprietaryoperatingsystems.Likehardwaremanufacturers,
softwaredevelopersneedagenericoperatingsystem.
AlthoughtheUNIXsystemoncemettheneedsofhardware
companiesandresearchersforagenericoperatingsystem,over
timeithasbecomemoreproprietaryaseachmanufacturer
addedsupportforspecializedfeaturesandintroducednew
softwarelibrariesandutilities.
Linuxemergedtoservebothneeds.Itisagenericoperating
systemthattakesadvantageofavailablehardwarepower.
LinuxIsPortable
Aportableoperatingsystemisonethatcanrunonmany
differentmachines.Morethan95percentoftheLinuxoperating
systemiswrittenintheCprogramminglanguage,andCis
portablebecauseitiswritteninahigher-level,machine-
independentlanguage.(TheCcompileriswritteninC.)
BecauseLinuxisportable,itcanbeadapted(ported)to
differentmachinesandcanmeetspecialrequirements.For
example,Linuxisusedinembeddedcomputers,suchasthe
onesfoundincellphones,PDAs,andthecableboxesontopof
manyTVs.Thefilestructuretakesfulladvantageoflarge,fast
harddisks.Equallyimportant,Linuxwasoriginallydesignedas
amultiuseroperatingsystemitwasnotmodifiedtoserve
severalusersasanafterthought.Sharingthecomputer'spower
amongmanyusersandgivingthemtheabilitytosharedata
andprogramsarecentralfeaturesofthesystem.
Becauseitisadaptableandtakesadvantageofavailable
hardware,Linuxrunsonmanydifferentmicroprocessor-based
systemsaswellasmainframes.Thepopularityofthe
microprocessor-basedhardwaredrivesLinux;these
microcomputersaregettingfasterallthetime,ataboutthe
samepricepoint.Linuxonafastmicrocomputerhasbecome
goodenoughtodisplaceworkstationsonmanydesktops.Linux
benefitsbothusers,whodonotlikehavingtolearnanew
operatingsystemforeachvendor'shardware,andsystem
administrators,wholikehavingaconsistentsoftware
environment.
Theadventofastandardoperatingsystemhasaidedthe
developmentofthesoftwareindustry.Nowsoftware
manufacturerscanaffordtomakeoneversionofaproduct
availableonmachinesfromdifferentmanufacturers.
Standards
Individualsfromcompaniesthroughoutthecomputerindustry
havejoinedtogethertodevelopthePOSIX(PortableOperating
SystemInterfaceforComputerEnvironments)standard,which
isbasedlargelyontheUNIXSystemVInterfaceDefinition
(SVID)andotherearlierstandardizationefforts.Theseefforts
havebeenspurredbytheU.S.government,whichneedsa
standardcomputingenvironmenttominimizeitstrainingand
procurementcosts.Nowthatthesestandardsaregaining
acceptance,softwaredevelopersareabletodevelop
applicationsthatrunonallconformingversionsofUNIX,Linux,
andotheroperatingsystems.
TheCProgrammingLanguage
KenThompsonwrotetheUNIXoperatingsystemin1969in
PDP-7assemblylanguage.Assemblylanguageismachine
dependent:Programswritteninassemblylanguageworkon
onlyonemachineor,atbest,onefamilyofmachines.The
originalUNIXoperatingsystemthereforecouldnoteasilybe
transportedtorunonothermachines(itwasnotportable).
TomakeUNIXportable,ThompsondevelopedtheB
programminglanguage,amachine-independentlanguage,from
theBCPLlanguage.DennisRitchiedevelopedtheC
programminglanguagebymodifyingBand,withThompson,
rewroteUNIXinCin1973.Therevisedoperatingsystemcould
betransportedmoreeasilytorunonothermachines.
ThatdevelopmentmarkedthestartofC.Itsrootsrevealsome
ofthereasonswhyitissuchapowerfultool.Ccanbeusedto
writemachine-independentprograms.Aprogrammerwho
designsaprogramtobeportablecaneasilymoveittoany
computerthathasaCcompiler.Cisalsodesignedtocompile
intoveryefficientcode.WiththeadventofC,aprogrammerno
longerhadtoresorttoassemblylanguagetogetcodethat
wouldrunwell(thatis,quicklyalthoughanassemblerwill
alwaysgeneratemoreefficientcodethanahigh-level
language).
Cisagoodsystemslanguage.Youcanwriteacompileroran
operatingsysteminC.Itishighlystructuredbutisnot
necessarilyahigh-levellanguage.Callowsaprogrammerto
manipulatebitsandbytes,asisnecessarywhenwritingan
operatingsystem.Butitalsohashigh-levelconstructsthat
allowefficient,modularprogramming.
Inthelate1980stheAmericanNationalStandardsInstitute
(ANSI)definedastandardversionoftheClanguage,commonly
referredtoasANSICorC89(fortheyearthestandardwas
published).TenyearslatertheC99standardwaspublished;it
ismostlysupportedbytheGNUProject'sCcompiler(named
gcc).Theoriginalversionofthelanguageisoftenreferredtoas
Kernighan&Ritchie(orK&R)C,namedfortheauthorsofthe
bookthatfirstdescribedtheClanguage.
AnotherresearcheratBellLabs,BjarneStroustrup,createdan
object-orientedprogramminglanguagenamedC++,whichis
builtonthefoundationofC.Becauseobject-oriented
programmingisdesiredbymanyemployerstoday,C++is
preferredoverCinmanyenvironments.Anotherlanguageof
choiceisObjective-C,whichwasusedtowritethefirstWeb
browser.TheGNUProject'sCcompilersupportsC,C++,and
Objective-C.
OverviewofLinux
TheLinuxoperatingsystemhasmanyuniqueandpowerful
features.Likeotheroperatingsystems,Linuxisacontrol
programforcomputers.ButlikeUNIX,itisalsoawell-thought-
outfamilyofutilityprograms(Figure1-1)andasetoftools
thatallowuserstoconnectandusetheseutilitiestobuild
systemsandapplications.
Figure1-1.AlayeredviewoftheLinuxoperating
system
[Viewfullsizeimage]
LinuxHasaKernelProgrammingInterface
TheLinuxkerneltheheartoftheLinuxoperatingsystemis
responsibleforallocatingthecomputer'sresourcesand
schedulinguserjobssothateachonegetsitsfairshareof
systemresources,includingaccesstotheCPU;peripheral
devices,suchasdisk,DVD,andCD-ROMstorage;printers;and
tapedrives.Programsinteractwiththekernelthroughsystem
calls,specialfunctionswithwell-knownnames.Aprogrammer
canuseasinglesystemcalltointeractwithmanykindsof
devices.Forexample,thereisonewrite()systemcall,not
manydevice-specificones.Whenaprogramissuesawrite()
request,thekernelinterpretsthecontextandpassesthe
requesttotheappropriatedevice.Thisflexibilityallowsold
utilitiestoworkwithdevicesthatdidnotexistwhentheutilities
wereoriginallywritten.Italsomakesitpossibletomove
programstonewversionsoftheoperatingsystemwithout
rewritingthem(providedthatthenewversionrecognizesthe
samesystemcalls).Seepage1011forinformationontheLinux
2.6kernel.
LinuxCanSupportManyUsers
Dependingonthehardwareandthetypesoftasksthatthe
computerperforms,aLinuxsystemcansupportfrom1tomore
than1,000users,eachconcurrentlyrunningadifferentsetof
programs.Theper-usercostofacomputerthatcanbeusedby
manypeopleatthesametimeislessthanthatofacomputer
thatcanbeusedbyonlyasinglepersonatatime.Itisless
becauseonepersoncannotgenerallytakeadvantageofallthe
resourcesacomputerhastooffer.Thatis,noonecankeepall
theprintersgoingconstantly,keepallthesystemmemoryin
use,keepallthedisksbusyreadingandwriting,keepthe
Internetconnectioninuse,andkeepalltheterminalsbusyat
thesametime.Amultiuseroperatingsystemallowsmany
peopletouseallthesystemresourcesalmostsimultaneously.
Theuseofcostlyresourcescanbemaximizedandthecostper
usercanbeminimizedtheprimaryobjectivesofamultiuser
operatingsystem.
LinuxCanRunManyTasks
Linuxisafullyprotectedmultitaskingoperatingsystem,
allowingeachusertorunmorethanonejobatatime.
Processescancommunicatewithoneanotherbutremainfully
protectedfromoneanother,justasthekernelremains
protectedfromallprocesses.Youcanrunseveraljobsinthe
backgroundwhilegivingallyourattentiontothejobbeing
displayedonthescreen,andyoucanswitchbackandforth
betweenjobs.IfyouarerunningtheXWindowSystem(page
15),youcanrundifferentprogramsindifferentwindowsonthe
samescreenandwatchallofthem.Thiscapabilityensuresthat
userscanbemoreproductive.
LinuxProvidesaSecureHierarchicalFilesystem
Afileisacollectionofinformation,suchastextforamemoor
report,anaccumulationofsalesfigures,animage,asong,or
anexecutableprogram.Eachfileisstoredunderaunique
identifieronastoragedevice,suchasaharddisk.TheLinux
filesystemprovidesastructurewherebyfilesarearranged
underdirectories,whicharelikefoldersorboxes.Eachdirectory
hasanameandcanholdotherfilesanddirectories.Directories,
inturn,arearrangedunderotherdirectories,andsoforth,ina
treelikeorganization.Thisstructurehelpsuserskeeptrackof
largenumbersoffilesbygroupingrelatedfilesintodirectories.
Eachuserhasoneprimarydirectoryandasmanysubdirectories
asrequired(Figure1-2).
Figure1-2.TheLinuxfilesystemstructure
Standards
Withtheideaofmakinglifeeasierforsystemadministrators
andsoftwaredevelopers,agroupgottogetherovertheInternet
anddevelopedtheLinuxFilesystemStandard(FSSTND),which
hassinceevolvedintotheLinuxFilesystemHierarchyStandard
(FHS).Beforethisstandardwasadopted,keyprogramswere
locatedindifferentplacesindifferentLinuxdistributions.Today
youcansitdownataLinuxsystemandknowwheretoexpect
tofindanygivenstandardprogram(page176).
Links
Alinkallowsagivenfiletobeaccessedbymeansoftwoor
morenames.Thealternativenamescanbelocatedinthesame
directoryastheoriginalfileorinanotherdirectory.Linkscan
makethesamefileappearinseveralusers'directories,
enablingthoseuserstosharethefileeasily.Windowsusesthe
termshortcutinplaceoflink.Macintoshuserswillbemore
familiarwiththetermalias.UnderLinux,analiasisdifferent
fromalink;itisacommandmacrofeatureprovidedbythe
shell(page318).
Security
Likemostmultiuseroperatingsystems,Linuxallowsusersto
protecttheirdatafromaccessbyotherusers.Italsoallows
userstoshareselecteddataandprogramswithcertainother
usersbymeansofasimplebuteffectiveprotectionscheme.
Thislevelofsecurityisprovidedbyfileaccesspermissions,
whichlimitwhichuserscanreadfrom,writeto,orexecutea
file.AccessControlLists(ACLs)haverecentlybeenaddedto
theLinuxkernelandareavailableinRedHatLinux.ACLsgive
usersandadministratorsfiner-grainedcontroloverfileaccess
permissions.
TheShell:CommandInterpreterand
ProgrammingLanguage
Inatextualenvironment,theshellthecommandinterpreteracts
asaninterfacebetweenyouandtheoperatingsystem.When
youenteracommandonthescreen,theshellinterpretsthe
commandandcallstheprogramyouwant.Anumberofshells
areavailableforLinux.Thethreemostpopularonesare
describedhere:
TheBourneAgainShell(bash),anenhancedversionofthe
originalBourneShell.ItisoneoftheoriginalUNIXshells.
TheTCShell(tcsh),anenhancedversionoftheCShell.It
wasdevelopedaspartofBSDUNIX.
TheZShell(zsh).Itincorporatesfeaturesfromanumberof
shells,includingtheKornShell.
Becauseusersoftenpreferdifferentshells,multiusersystems
canhaveseveraldifferentshellsinuseatanygiventime.The
choiceofshellsdemonstratesoneoftheadvantagesofthe
Linuxoperatingsystem:theabilitytoprovideacustomized
interfaceforeachuser.
Shellscripts
Besidesperformingitsfunctionofinterpretingcommandsfrom
akeyboardandsendingthosecommandstotheoperating
system,theshellisahigh-levelprogramminglanguage.Shell
commandscanbearrangedinafileforlaterexecution(Linux
callsthesefilesshellscripts;Windowscallthembatchfiles).
Thisflexibilityallowsuserstoperformcomplexoperationswith
relativeease,oftenwithrathershortcommands,ortobuild
withsurprisinglylittleeffortelaborateprogramsthatperform
highlycomplexoperations.
FilenameGeneration
Wildcardsandambiguousfilereferences
Whenyouaretypingcommandstobeprocessedbytheshell,
youcanconstructpatternsusingcharactersthathavespecial
meaningstotheshell.Thesecharactersarecalledwildcard
characters.Thepatterns,whicharecalledambiguousfile
references,areakindofshorthand:Ratherthantypingin
completefilenames,userscantypeinpatternsandtheshellwill
expandthemintomatchingfilenames.Anambiguousfile
referencecansaveyoutheeffortoftypinginalongfilenameor
alongseriesofsimilarfilenames.Forexample,theshellmight
expandthepatternmak*tomake-3.80.tar.gz.Patternscan
alsobeusefulwhenyouknowonlypartofafilenameorcannot
remembertheexactspelling.
Device-IndependentInputandOutput
Redirection
Devices(suchasaprinterorterminal)anddiskfilesappearas
filestoLinuxprograms.WhenyougiveacommandtotheLinux
operatingsystem,youcaninstructittosendtheoutputtoany
oneofseveraldevicesorfiles.Thisdiversioniscalledoutput
redirection.
Deviceindependence
Inasimilarmanner,aprogram'sinputthatnormallycomes
fromakeyboardcanberedirectedsothatitcomesfromadisk
fileinstead.Inputandoutputaredeviceindependent;theycan
beredirectedtoorfromanyappropriatedevice.
Asanexample,thecatutilitynormallydisplaysthecontentsofa
fileonthescreen.Whenyourunacatcommand,youcaneasily
causeitsoutputtogotoadiskfileinsteadofthescreen.
ShellFunctions
Oneofthemostimportantfeaturesoftheshellisthatuserscan
useitasaprogramminglanguage.Becausetheshellisan
interpreter,itdoesnotcompileprogramswrittenforitbut
ratherinterpretsprogramseachtimetheyareloadedfromthe
disk.Loadingandinterpretingprogramscanbetime-
consuming.
Manyshells,includingtheBourneAgainShell,includeshell
functionsthattheshellholdsinmemorysothatitdoesnot
havetoreadthemfromthediskeachtimeyouwanttoexecute
them.Theshellalsokeepsfunctionsinaninternalformatso
thatitdoesnothavetospendasmuchtimeinterpretingthem.
JobControl
Jobcontrolisashellfeaturethatallowsuserstoworkon
severaljobsatonce,switchingbackandforthbetweenthemas
desired.Whenyoustartajob,itisfrequentlyintheforeground
soitisconnectedtotheterminal.Usingjobcontrol,youcan
movethejobyouareworkingwithintothebackgroundand
continuerunningittherewhileworkingonorobservinganother
jobintheforeground.Ifabackgroundjobthenneedsyour
attention,youcanmoveitintotheforegroundsothatitisonce
againattachedtotheterminal.Theconceptofjobcontrol
originatedwithBSDUNIX,whereitappearedintheCShell.
ALargeCollectionofUsefulUtilities
Linuxincludesafamilyofseveralhundredutilityprograms,
oftenreferredtoascommands.Theseutilitiesperform
functionsthatareuniversallyrequiredbyusers.Thesortutility,
forexample,putslists(orgroupsoflists)inalphabeticalor
numericalorderandcanbeusedtosortlistsbypartnumber,
lastname,city,ZIPcode,telephonenumber,age,size,cost,
andsoforth.Thesortutilityisanimportantprogrammingtool
andispartofthestandardLinuxsystem.Otherutilitiesallow
userstocreate,display,print,copy,search,anddeletefilesas
wellastoedit,format,andtypesettext.Theman(formanual)
andinfoutilitiesprovideonlinedocumentationforLinuxitself.
InterprocessCommunication
Pipesandfilters
Linuxallowsuserstoestablishbothpipesandfiltersonthe
commandline.Apipesendstheoutputofoneprogramto
anotherprogramasinput.Afilterisaspecialkindofpipethat
processesastreamofinputdatatoyieldastreamofoutput
data.Afilterprocessesanotherprogram'soutput,alteringitas
aresult.Thefilter'soutputthenbecomesinputtoanother
program.
Pipesandfiltersfrequentlyjoinutilitiestoperformaspecific
task.Forexample,youcanuseapipetosendtheoutputofthe
catutilitytosort,afilter,andcanthenuseanotherpipetosend
theoutputofsorttoathirdutility,lpr,thatsendsthedatatoa
printer.Thus,inonecommandline,youcanusethreeutilities
togethertosortandprintafile.
SystemAdministration
OnaLinuxsystemthesystemadministratorisfrequentlythe
ownerandonlyuserofthesystem.Thispersonhasmany
responsibilities.Thefirstresponsibilitymaybetosetupthe
systemandinstallthesoftware.
Oncethesystemisupandrunning,thesystemadministratoris
responsiblefordownloadingandinstallingsoftware(including
upgradingtheoperatingsystem),backingupandrestoringfiles,
andmanagingsuchsystemfacilitiesasprinters,terminals,
servers,andalocalnetwork.Thesystemadministratorisalso
responsibleforsettingupaccountsfornewusersonamultiuser
system,bringingthesystemupanddownasneeded,and
takingcareofanyproblemsthatarise.
AdditionalFeaturesofLinux
ThedevelopersofLinuxincludedfeaturesfromBSD,SystemV,
andSunMicrosystems'Solaris,aswellasnewfeatures,intheir
operatingsystem.AlthoughmostofthetoolsfoundonUNIX
existforLinux,insomecasesthesetoolshavebeenreplacedby
moremoderncounterparts.Thissectiondescribessomeofthe
populartoolsandfeaturesavailableunderLinux.
GUIs:GraphicalUserInterfaces
TheXWindowSystem(alsocalledXorX11)wasdevelopedin
partbyresearchersatMIT(MassachusettsInstituteof
Technology)andprovidesthefoundationfortheGUIsavailable
withLinux.Givenaterminalorworkstationscreenthat
supportsX,ausercaninteractwiththecomputerthrough
multiplewindowsonthescreen,displaygraphicalinformation,
orusespecial-purposeapplicationstodrawpictures,monitor
processes,orpreviewformattedoutput.Xisanacross-the-
networkprotocolthatallowsausertoopenawindowona
workstationorcomputersystemthatisremotefromtheCPU
generatingthewindow.
Desktopmanager
UsuallytwolayersrununderX:adesktopmanageranda
windowmanager.Adesktopmanagerisapicture-orienteduser
interfacethatenablesyoutointeractwithsystemprogramsby
manipulatingiconsinsteadoftypingthecorresponding
commandstoashell.RedHatLinuxincludesGNOME(Figure1-
3,www.gnome.org)andKDE(www.kde.org),themostpopular
desktopmanagers.
Figure1-3.AGNOMEworkspace
[Viewfullsizeimage]
Windowmanager
Awindowmanagerisaprogramthatrunsunderthedesktop
managerandallowsyoutoopenandclosewindows,run
programs,andsetupamousesoitdoesvariousthings
dependingonhowandwhereyouclick.Thewindowmanager
alsogivesthescreenitspersonality.WhereasMicrosoft
Windowsallowsyoutochangethecolorofkeyelementsina
window,awindowmanagerunderXallowsyoutocustomize
theoveralllookandfeelofthescreen:Youcanchangetheway
awindowlooksandworks(bygivingitdifferentborders,
buttons,andscrollbars),setupvirtualdesktops,createmenus,
andmore.
SeveralpopularwindowmanagersrununderXandLinux.Red
HatLinuxprovidesMetacity(thedefaultunderGNOME)and
kwin(thedefaultunderKDE).Otherwindowmanagers,suchas
SawfishandWindowMaker,arealsoavailable.Chapters4and8
havemoreinformationonGUIs.
(Inter)NetworkingUtilities
Linuxnetworksupportincludesmanyutilitiesthatenableyouto
accessremotesystemsoveravarietyofnetworks.Inaddition
tosendingemailtousersonothersystems,youcanaccessfiles
ondisksmountedonothercomputersasiftheywerelocated
onthelocalsystem,makeyourfilesavailabletoothersystems
inasimilarmanner,copyfilesbackandforth,runprogramson
remotesystemswhiledisplayingtheresultsonthelocal
system,andperformmanyotheroperationsacrosslocalarea
networks(LANs)andwideareanetworks(WANs),includingthe
Internet.
Layeredontopofthisnetworkaccessisawiderangeof
applicationprogramsthatextendthecomputer'sresources
aroundtheglobe.Youcancarryonconversationswithpeople
throughouttheworld,gatherinformationonawidevarietyof
subjects,anddownloadnewsoftwareovertheInternetquickly
andreliably.Chapter10discussesnetworks,theInternet,and
theLinuxnetworkfacilities.
SoftwareDevelopment
OneofLinux'smostimpressivestrengthsisitsrichsoftware
developmentenvironment.Youcanfindcompilersand
interpretersformanycomputerlanguages.BesidesCandC++,
languagesavailableforLinuxincludeAda,Fortran,Java,Lisp,
Pascal,Perl,andPython.Thebisonutilitygeneratesparsingcode
thatmakesiteasiertowriteprogramstobuildcompilers(tools
thatparsefilescontainingstructuredinformation).Theflex
utilitygeneratesscanners(codethatrecognizeslexicalpatterns
intext).ThemakeutilityandtheGNUConfigureandBuild
Systemmakeiteasiertomanagecomplexdevelopment
projects.Sourcecodemanagementsystems,suchasCVS,
simplifyversioncontrol.Severaldebuggers,includingupsand
gdb,helpintrackingdownandrepairingsoftwaredefects.The
GNUCcompiler(gcc)workswiththegprofprofilingutilitytohelp
programmersidentifypotentialbottlenecksinaprogram's
performance.TheCcompilerincludesoptionstoperform
extensivecheckingofCcodethatcanmakethecodemore
portableandreducedebuggingtime.Theseandothersoftware
developmenttoolsarediscussedinChapter27.TableB-4on
page982listssomesitesthatyoucandownloadsoftwarefrom.
ConventionsUsedinThisBook
Thisbookusesconventionstomakeitsexplanationsshorter
andclearer.Thefollowingparagraphsdescribethese
conventions.
RedHatLinux
Inthisbook,thetermRedHatLinuxreferstobothFedoraCore
andRedHatEnterpriseLinux.Featuresthatapplytoone
operatingsystemortheotheronlyaremarkedassuch,using
thesemarkers:FEDORAorRHEL.
Textandexamples
Thetextissetinthistype,whereasexamplesareshownina
monospacedfont(alsocalledafixed-widthfont):
$catpractice
ThisisasmallfileIcreated
withatexteditor.
Itemsyouenter
Everythingyouenteratthekeyboardisshowninabold
typeface:Withinthetext,thisboldtypefaceisused;within
examplesandscreens,thisoneisused.Intheprevious
example,thedollarsign($)onthefirstlineisapromptthat
Linuxdisplays,soitisnotbold;theremainderofthefirstlineis
enteredbyauser,soitisbold.
Utilitynames
Namesofutilitiesareprintedinthisboldsansseriftypeface.This
bookreferencestheemacstexteditorandthelsutilityorls
command(orjustls)butinstructsyoutoenterlsaonthe
commandline.Inthiswaythetextdistinguishesbetween
utilities,whichareprograms,andtheinstructionsyougiveon
thecommandlinetoinvoketheutilities.
Filenames
Filenamesappearinaboldtypeface.Examplesarememo5,
letter.1283,andreports.Filenamesmayincludeuppercase
andlowercaseletters;however,Linuxiscasesensitive(page
1023),somemo5,MEMO5,andMemo5namethreedifferent
files.
Characterstrings
Withinthetext,charactersandcharacterstringsaremarkedby
puttingtheminaboldtypeface.Thisconventionavoidsthe
needforquotationmarksorotherdelimitersbeforeandaftera
string.Anexampleisthefollowingstring,whichisdisplayedby
thepasswdutility:Sorry,passwordsdonotmatch.
Buttonsandlabels
Wordsappearinaboldtypefaceinthesectionsofthebookthat
describeaGUI.Thisfontindicatesthatyoucanclickamouse
buttonwhenthemousepointerisoverthesewordsonthe
screenoroverabuttonwiththisname.
Keysandcharacters
ThisbookusesSMALLCAPSforthreekindsofitems:
Keyboardkeys,suchastheSPACEbarandtheRETURN[8]
ESCAPE,andTABkeys.
[8]Differentkeyboardsusedifferentkeystomovethecursor(page1027)tothe
beginningofthenextline.Thisbookalwaysreferstothekeythatendsalineasthe
RETURNkey.YourkeyboardmayhaveaRET,NEWLINE,ENTER,RETURN,orotherkey.
Usethecorrespondingkeyonyourkeyboardeachtimethisbookasksyoutopress
RETURN.
Thecharactersthatkeysgenerate,suchastheSPACEs
generatedbytheSPACEbar.
KeyboardkeysthatyoupresswiththeCONTROLkey,such
asCONTROL-D.(EventhoughDisshownasanuppercase
letter,youdonothavetopresstheSHIFTkey;enter
CONTROL-DbyholdingtheCONTROLkeydownandpressing
d.)
PromptsandRETURNs
MostexamplesincludetheshellpromptthesignalthatLinuxis
waitingforacommandasadollarsign($),apoundsign(#),or
sometimesapercentsign(%).Thepromptisnotinabold
typefacebecauseyoudonotenterit.Donottypetheprompt
onthekeyboardwhenyouareexperimentingwithexamples
fromthisbook.Ifyoudo,theexampleswillnotwork.
ExamplesomittheRETURNkeystrokethatyoumustuseto
executethem.Anexampleofacommandlineis
$vimmemo.1204
Tousethisexampleasamodelforrunningthevimtexteditor,
givethecommandvimmemo.1204andpresstheRETURN
key.(PressESCAPEZZtoexitfromvim;seepage152foravim
tutorial.)Thismethodofenteringcommandsmakesthe
examplesinthebookcorrespondtowhatappearsonthe
screen.
Menuselectionpath
Themenuselectionpathisthenameofthemenuorthe
locationofthemenu,followedbyacolon,aSPACE,andthe
menuselection(s)separatedby s.Theentiremenuselection
pathisinboldtype.YoucanreadKonquerormenubar:
Tools Findas"FromtheKonquerormenubar,selectTools;
fromTools,selectFind."
Definitions
AllglossaryentriesmarkedwithFOLDOCarecourtesyofDenis
Howe,editoroftheFreeOnlineDictionaryofComputing
(www.foldoc.org),andareusedwithpermission.Thissiteisan
ongoingworkcontainingdefinitions,anecdotes,andtrivia.
Optional:OptionalInformation
Passagesmarkedasoptionalappearinagrayboxandarenotcentraltothe
ideaspresentedinthechapterbutofteninvolvemorechallengingconcepts.A
goodstrategywhenreadingachapteristoskiptheoptionalsectionsandthen
returntothemwhenyouarecomfortablewiththemainideaspresentedinthe
chapter.Thisisanoptionalparagraph.
URLs(Webaddresses)
Webaddresses,orURLs,haveanimplicithttp://prefix,unless
ftp://orhttps://isshown.Youdonotnormallyneedto
specifyaprefixwhentheprefixishttp://,butyoumustusea
prefixfromabrowserwhenyouspecifyanFTPorsecureHTTP
site.ThusyoucanspecifyaURLinabrowserexactlyasshown
inthisbook.
Tip,caution,andsecurityboxes
Thefollowingboxeshighlightinformationthatmaybehelpful
whileyouareusingoradministratingaLinuxsystem.
Tip:Thisisatipbox
Atipboxmayhelpyouavoidrepeatingacommon
mistakeormaypointtowardadditionalinformation.
Caution:Thisboxwarnsyouabout
something
Acautionboxwarnsyouaboutapotentialpitfall.
Security:Thisboxmarksasecuritynote
Asecurityboxhighlightsapotentialsecurityissue.
Thesenotesareusuallyforsystemadministrators,
butsomeapplytoallusers.
ChapterSummary
TheLinuxoperatingsystemgrewoutoftheUNIXheritageto
becomeapopularalternativetotraditionalsystems(thatis,
Windows)availableformicrocomputer(PC)hardware.UNIX
userswillfindafamiliarenvironmentinLinux.Distributionsof
LinuxcontaintheexpectedcomplementofUNIXutilities,
contributedbyprogrammersaroundtheworld,includingtheset
oftoolsdevelopedaspartoftheGNUProject.TheLinux
communityiscommittedtothecontinueddevelopmentofthis
system.Supportfornewmicrocomputerdevicesandfeaturesis
addedsoonafterthehardwarebecomesavailable,andthetools
availableonLinuxcontinuetoberefined.Withmany
commercialsoftwarepackagesavailabletorunonLinux
platformsandmanyhardwaremanufacturersofferingLinuxon
theirsystems,itisclearthatthesystemhasevolvedwell
beyonditsoriginasanundergraduateprojecttobecomean
operatingsystemofchoiceforacademic,commercial,
professional,andpersonaluse.
Exercises
1. Whatisfreesoftware?Listthreecharacteristicsoffreesoftware.
2. WhyisLinuxpopular?Whyisitpopularinacademia?
3. Whataremultiusersystems?Whyaretheysuccessful?
4.
WhatistheFreeSoftwareFoundation/GNU?WhatisLinux?Whichpartsofthe
Linuxoperatingsystemdideachprovide?Whoelsehashelpedbuildandrefinethis
operatingsystem?
5. InwhatlanguageisLinuxwritten?Whatdoesthelanguagehavetodowiththe
successofLinux?
6. Whatisautilityprogram?
7. Whatisashell?Howdoesitworkwiththekernel?Withtheuser?
8. Howcanyouuseutilityprogramsandashelltocreateyourownapplications?
9. WhyistheLinuxfilesystemreferredtoashierarchical?
10. Whatisthedifferencebetweenamultiprocessorandamultiprocessingsystem?
11. Giveanexampleofwhenyouwouldwanttouseamultiprocessingsystem.
12. ApproximatelyhowmanypeoplewroteLinux?Whyisthisunique?
13. WhatarethekeytermsoftheGNUGeneralPublicLicense?
2.InstallationOverview
INTHISCHAPTER
MoreInformation 24
PlanningtheInstallation 24
SettingUptheHardDisk 28
LVM:LogicalVolumeManager 32
HowtheInstallationWorks 33
TheMedium:WhereIstheSourceData? 34
Downloading,Burning,andInstallingaCDSetoraDVD(FEDORA) 35
UsingBitTorrenttoDownloadtheISOImageFiles 39
RescueCD 40
GatheringInformationAbouttheSystem 40
InstallingRedHatLinuxistheprocessofcopyingoperating
systemfilesfrommediatothelocalsystemandsettingup
configurationfilessothatLinuxrunsproperlyonthelocal
hardware.YoucaninstallLinuxfrommanytypesofmedia,
includingCDs,aDVD,thelocalharddisk,oraharddiskand
filesonanothersystemthatisaccessedoveranetwork.
Severaltypesofinstallationsarealsopossible,includingfresh
installations,upgradesfromolderversionsofRedHatLinux,
anddual-bootinstallations.Youcanperformtheinstallation
manuallyorsetupKickstarttoinstallRedHatLinux
automatically.
Thischapterdiscussestheinstallationprocessingeneral:
planning,partitioningtheharddisk,obtainingthefilesforthe
installation,burningCDsoraDVDifnecessary,andcollecting
informationaboutthehardwareyouwillneedwhenyouinstall
thesystem.Chapter3coverstheactualinstallation.
RedHatdevelopedAnaconda,aninstallationtoolthatperforms
aninteractiveinstallationusingagraphicalortextualinterface,
toautomateandmakefriendliertheprocessofinstallingLinux.
ToinstallLinuxonstandardhardware,youcantypicallyinsert
thefirstinstallationCDortheinstallationDVD,bootthe
system,pressRETURNafewtimes,andchangeCDsafew
timesifyouareinstallingfromCDs.However,youmaywantto
customizethesystemoryoumaybeinstallingonnonstandard
hardware:Anacondagivesyoumanychoicesastheinstallation
processunfolds.Referto"BootingtheSystem:Theboot:
Prompt"(page44)and"TheAnacondaInstaller"(page47)for
informationaboutcustomizingaRedHatLinuxinstallation.
MoreInformation
Local
lvmmanpageincludingthe"Seealso"pageslistedatthe
bottom
Web
SELinuxFAQpeople.redhat.com/kwade/fedora-docs/selinux-
faq-en
X.orgreleaseinformationwiki.x.org
memtest86+www.memtest.org
Hardwarecompatibilityhardware.redhat.com
PartitionHOWTOtldp.org/HOWTO/Partition
LVMResourcePage(includesmanylinks)sourceware.org/lvm2
LVMHOWTOwww.tldp.org/HOWTO/LVM-HOWTO
BitTorrentwww.bittorrent.com
PXEwww.kegel.com/linux/pxe.html
PXEandKickstartwww.stanford.edu/~alfw/PXE-Kickstart/PXE-
Kickstart.html
Downloads
FEDORADownloadinstructionsfedora.redhat.com/download
FEDORABitTorrenttrackerstorrent.fedoraproject.org
FEDORADownloadserver
download.fedora.redhat.com/pub/fedora/linux/core
FEDORAMirrorsfedora.redhat.com/download/mirrors.html
RHELftp://ftp.redhat.com/pub/redhat/linux/enterprise
PlanningtheInstallation
Themajordecisionswhenplanninganinstallationare
determininghowtodividetheharddiskintopartitionsor,inthe
caseofadual-bootsystem,wheretoputtheLinuxpartitions,
anddecidingwhichsoftwarepackagestoinstall.Inadditionto
thesetopics,thissectiondiscusseshardwarerequirementsfor
RedHatLinux,FedoraCoreversusRedHatEnterpriseLinux,
andfreshinstallationsversusupgrades.
Considerations
SELinux
IfyouplantouseSELinux,turnitonduringFirstboot(page
56).BecauseSELinuxsetsextendedattributesonfiles,itcan
beatime-consumingprocesstoturnonSELinuxafteryou
installLinux.
GUI
Onmostinstallations(exceptforservers),youwillprobably
wanttoinstallagraphicaldesktopenvironment.GNOMEis
installedbydefault.YoucanalsoinstallKDEorbothGNOME
andKDE.
Chapter4,"IntroductiontoRedHatLinux,"usesexamplesfrom
KDEtointroducethegraphicaldesktop.InstallKDEifyouwant
tofollowtheseexamples.YoucanremoveKDElaterifyoulike.
Onaserver,younormallydedicateasmanyresourcestothe
serveraspossibleandfewresourcestoanythingnotrequired
bytheserver.Forthisreason,serversrarelyincludeagraphical
interface.
Softwareandservices
Asyouinstallmoresoftwarepackagesonasystem,thenumber
ofupdatesandtheinteractionsbetweenthepackagesincrease.
Serverpackagesthatlistenfornetworkconnectionsmakethe
systemmorevulnerablebyincreasingthenumberofwaysthe
systemcanbeattacked.Additionalservicescanalsoslowthe
systemdown.
Forasystemtolearnon,orforadevelopmentsystem,
additionalpackagesandservicesmaybeuseful.However,fora
moresecureproductionsystem,itisbesttoinstalland
maintaintheminimumnumberofpackagesrequiredandenable
onlyneededservices.
Requirements
Hardware
RedHatLinuxcanrunonmanydifferenttypesofhardware.
Thissectiondetailsinstallationon32-bitIntelandcompatible
platformssuchasAMD,Cyrix,andVIAaswellas64-bit
platformssuchasAMD64processors(bothAthlon64and
Opteron)andIntelprocessorswithIntelExtendedMemory64
Technology(EM64T).Refertothereleasenotesifyouare
installingRedHatLinuxonPowerPC(PPC)hardware.Within
theseplatforms,RedHatLinuxrunsonmuchoftheavailable
hardware.YoucanviewRedHat'slistofcompatibleand
supportedhardwareathardware.redhat.com.Althoughthese
listsapplytoRedHatEnterpriseLinux,theyserveasagood
guidetowhatFedoraCorewillrunon.ManyInternetsites
discussLinuxhardware;useGoogle(www.google.com/linux)to
searchonlinuxhardware,fedorahardware,orlinuxand
thespecifichardwareyouwantmoreinformationon(for
example,linuxsataorlinuxa8n).Inaddition,manyHOWTOs
coverspecifichardware.ThereisalsoaLinuxHardware
CompatibilityHOWTO,althoughitbecomesdatedrather
quickly.RedHatLinuxusuallyrunsonsystemsthatWindows
runson,unlessthesystemincludesaveryneworunusual
component.
Memory(RAM)
Youneedaminimumof128megabytesofRAMfora32-bitx86
systemthatrunsintextmode(noGUI)and192256megabytes
foragraphicalsystem.Fora64-bitx86_64system,youneed
atleast128megabytesfortextmodeand256512megabytes
foragraphicalsystem.Linuxmakesgooduseofextramemory:
Themorememoryasystemhas,thefasteritwillrun.Adding
memoryisoneofthemostcost-effectivewaysyoucanspeed
upaLinuxsystem.
CPU
RedHatLinuxrequiresaminimumofa200-megahertz
Pentium-classprocessorortheequivalentAMDorother
processorfortextualmodeandatleasta400-megahertz
PentiumIIprocessorortheequivalentforgraphicalmode.
Harddiskspace
Theamountofharddiskspaceyouneeddependsonwhich
versionofRedHatLinuxyouinstall,whichpackagesyouinstall,
howmanylanguagesyouinstall,andhowmuchspaceyouneed
foruserdata(yourfiles).Theoperatingsystemcanoccupy
fromabout600megabytestoover9gigabytes.
BIOSsetup
ModerncomputerscanbesettobootfromaCD/DVD,floppy
diskette,orharddisk.TheBIOSdeterminestheorderinwhich
thesystemtriestobootfromeachdevice.Youmayneedto
changethisorder:MakesuretheBIOSissetuptotrybooting
fromtheCD/DVDbeforeittriestobootfromtheharddisk.
CMOS
CMOSisthepersistentmemorythatstoressystem
configurationinformation.TochangetheBIOSsetup,youneed
toedittheinformationstoredinCMOS.Whenthesystemboots,
itdisplaysabriefmessageabouthowtoenterSystemSetupor
CMOSSetupmode.UsuallyyouneedtopressDelorF2while
thesystemisbooting.Pressthekeythatiscalledforandmove
thecursortothescreenandlinethatdealwithbootingthe
system.Generallythereisalistofthreeorfourdevicesthatthe
systemtriestobootfrom;ifthefirstattemptfails,thesystem
triestheseconddevice,andsoon.Manipulatethelistsothe
CD/DVDisthefirstchoice,saveyourchoices,andreboot.Refer
tothehardware/BIOSmanualformoreinformation.
WhichAreYouInstalling:FedoraCoreorRed
HatEnterpriseLinux?
Thisbookdescribestwoproducts:FedoraCoreandRedHat
EnterpriseLinux.Thissectionbrieflyhighlightsthedifferences
betweentheseproducts.
FEDORA
TheFedoraProjectissponsoredbyRedHatandsupportedby
theopen-sourcecommunity.Withreleases,calledFedoraCore,
comingoutabouteverysixmonths,thisLinuxdistributiontests
cutting-edgecode;itisnotasupportedRedHatproductandis
notrecommendedforproductionenvironmentswherestability
isimportant.Fedoraaimstoreflecttheupstreamprojectsit
incorporates,includingthekernel.Incontrast,RedHat
EnterpriseLinuxincludesmanychangesintroducedbyFedora
Core.ArchitecturessupportedbytheFedoraProjectinclude
i386Intelx86-compatibleprocessors,includingIntel
PentiumandPentiumMMX,PentiumPro,PentiumII,
PentiumIII,Celeron,Pentium4,andXeon;VIAC3/C3-m
andEden/Eden-N;andAMDAthlon,AthlonXP,Duron,
AthlonMP,andSempron.
ppcPowerPCprocessors(foundinApplePowerMacintosh,
G3,G4,andG5,andIBMpSeriessystems).
x86_6464-bitAMDprocessorsincludingAthlon64,
Turion64,andOpteron;andIntel64-bitprocessorsthat
incorporateEM64Ttechnology.
RHEL
Althoughyoucandownloadthecodeforfree(referto"More
Information"onpage24),RedHatEnterpriseLinuxistypically
soldbyannualsubscriptionthatincludestheRedHatNetwork
(page498)andtechnicalsupport.Itismorestablebutless
cuttingedgethanFedoraCore.
RedHatEnterpriseLinuxAS(advancedserver)andRedHat
EnterpriseLinuxES(enterpriseserver)functionidenticallyand
aredesignedtorunservers.ESislicensedforx86-compatible,
AMD64,IntelEM64T,andIntelItanium2systemswithoneor
twoCPUsandupto16gigabytesofmemory.ASislicensedfor
serversofanysizeandsupportsIBMzSeries,POWERseries,
andS/390seriessystemsinadditiontothesystemsthatES
supports.
RedHatEnterpriseLinuxWS(workstation)supportsthesame
architecturesasESonthedesktop/clientside,runningoffice
productivityandsoftwaredevelopmentapplications.WS
supportssystemswithoneortwoCPUs,upto4gigabytesof
memory,anddoesnotincludealltheserverapplicationsthat
comewithASandES.Itisnotdesignedforaserver
environment.
InstallingaFreshCopyorUpgradinganExisting
RedHatSystem?
Upgrade
AnupgradereplacestheLinuxkernelandutilitiesonanalready
installedversionofRedHatLinuxwithnewerversions.During
anupgrade,theinstallationprogramattemptstopreserveboth
systemanduserdatafiles.Anupgradebringsutilitiesthatare
presentintheoldversionup-to-datebutdoesnotinstallnew
utilities(youcaninstallthemlaterifyoulike).Existing
configurationfilesarepreservedandnewonesaddedwitha
.rpmnewfilenameextension.Alogoftheupgradeiskeptin
/root/upgrade.log.Beforeyouupgradeasystem,backupall
filesonthesystem.
Caution:Afreshinstallationyieldsa
morestablesystemthananupgrade
Forbettersystemstability,RedHatrecommends
thatyoubackupdataonasystemandperforma
freshinstallationratherthananupgrade.
Cleaninstall
Aninstallation,sometimesreferredtoasacleaninstall,writes
allfreshdatatoadisk.Theinstallationprogramoverwritesall
systemprogramsanddataaswellasthekernel.Youcan
preservesomeuserdataduringaninstallationdependingon
whereitislocatedandhowyouformat/partitionthedisk.
GraphicalorTextualInstallation?
ThereareseveralwaystoinstallRedHatLinux.Youcanchoose
agraphicalinstallation,whichdisplaysgraphicsonthescreen
andallowsyoutousethemouse,windowbuttons,andscroll
liststochoosehowyouwanttoconfigurethesystem.Ifyou
haveasmallersystemwithlessmemoryorasystemwithan
unsupportedgraphicsboard,youcanrunatextualinstallation.
Thistypeofinstallationperformsthesamefunctionsasa
graphicalinstallation,butusesapseudographicalinterfaceto
stepyouthroughtheprocessofconfiguringthesystem.The
Anacondautilitycontrolsbothtypesofinstallations.
SettingUptheHardDisk
Formattingandfreespace
Harddisksmustbepreparedinseveralwayssoanoperating
systemcanwritetoandreadfromthem.Low-levelformatting
isthefirststepinpreparingadiskforuse.Normallyyouwill
notneedtolow-levelformataharddisk,asthistaskisdoneat
thefactory.Thenextstepinpreparingadiskforuseistodivide
itintopartitions.Theareaofthediskthatisnotoccupiedby
partitionsiscalledfreespace.Anewdiskhasnopartitions:Itis
allfreespace.UnderDOS/Windows,thetermformattingmeans
writingafilesystemonapartition;see"Filesystems"below.
Partitions
Apartition,orslice,isasectionofaharddiskthathasadevice
name,suchas/dev/hda1,soyoucanaddressitseparately
fromothersections.DuringinstallationyouuseDiskDruid
(page58)tocreatepartitionsontheharddisk.Afterinstallation
youcanuseparted(page65)tomanipulatepartitions.
LVM
DiskDruidcansetuplogicalvolumes(LVs)thatfunctionlike
partitions.WhenyousetupLVs,youcanusetheLogical
VolumeManager(LVM,page32)tochangethesizesof
volumes.Itismuchmoredifficulttochangethesizesof
partitions.
Filesystems
Beforemostprogramscanwritetoapartition,adatastructure
(page1028),calledafilesystem,needstobewrittenona
partition.Themkfs(makefilesystem)utility,whichissimilarto
theDOS/Windowsformatutility,writesafilesystemona
partition.Manytypesoffilesystemsexist.RedHatLinux
typicallycreatesext3filesystemsfordata,whileWindowsuses
FATandNTFSfilesystems.AppleusesHFS(Hierarchical
Filesystem)andHFS+.OSXuseseitherHFS+orUFS.Under
DOS/Windows,filesystemsarelabeledC:,D:,andsoon
(sometimesawholediskisasinglepartition).UnderLinux,
typicalhierarchicalfilesystemnamesare/(root),/boot,/var,
and/usr.Youcanhavedifferenttypesofpartitionsonthe
sameharddisk,includingbothWindowsandLinuxpartitions.
UnderLinux,thefsck(filesystemcheck)utility(page470)
checkstheintegrityoffilesystemdatastructures.
Filesystemindependence
Thestateofonefilesystemdoesnotaffectotherfilesystems:
Onefilesystemonadrivemaybecorruptandunreadablewhile
otherfilesystemsfunctionnormally.Onefilesystemmaybefull
soyoucannotwritetoitwhileothershaveplentyofroomfor
moredata.
PrimaryandExtendedPartitions
PartitioningallowsyoutodivideanIDEdiskintoamaximumof
63separatepartitions,orsubdisks.ASCSIdiskcanbedivided
into15partitionsatmost.Youcanuseeachpartition
independentlyforswapdevices,filesystems,databases,other
resources,andevenotheroperatingsystems.
Unfortunatelydiskpartitionsfollowthetemplateestablishedfor
DOSmachinesalongtimeago.Atmost,adiskcanholdfour
primarypartitions.Oneoftheseprimarypartitionscanbe
dividedintomultiple,logicalpartitions;thisdividedprimary
partitioniscalledanextendedpartition.Ifyouwantmorethan
fourpartitionsonadriveandyouusuallydoyoumustsetupan
extendedpartition.
Atypicaldiskisdividedintothreeprimarypartitionsandone
extendedpartition.Thethreeprimarypartitionsarethesizes
youwantthefinalpartitionstobe.Theextendedpartition
occupiestherestofthedisk.Onceyouestablishtheextended
partition,youcansubdivideitintoadditionalpartitionsthatare
eachthesizeyouwant.
PartitioningaDisk
Duringinstallation,AnacondacallsDiskDruidtosetupdisk
partitions.Thissectiondiscusseshowtoplanpartitionsizes.
Althoughthissectionusesthetermpartition,theplanningand
sizingofLVs(page32)isthesame.Formoreinformationrefer
to"UsingDiskDruidtoPartitiontheDisk"onpage58andto
theLinuxPartitionHOWTOatwww.tldp.org/HOWTO/Partition.
Tip:UnderRedHatLinux,druidmeans
wizard
RedHatusesthetermdruidaspartofthenamesof
programsthatguideyouthroughatask-drivenchain
ofsteps.Otheroperatingsystemscallthesetypesof
programswizards.
PlanningPartitions
Simplesetup
Itcanbedifficulttoplanpartitionsizesappropriatelyifyouare
newtoLinux.Forthisreasonmanypeoplechoosetohaveonly
threepartitions.Thefirstpartitionholdstheinformationthe
systemneedstoboot:thekernelimageandotherfiles.This
partitionismountedas/bootandcanrangeinsizefrom50to
300megabytes.Asecondpartitionistheswappartition,which
canbeanysizefrom512megabytesto2ormoregigabytes.
Thelastpartitionisdesignatedasroot(/)andcontainsthe
remainderofthediskspace.Thissetupmakesmanagingspace
quiteeasy.Butifaprogramrunsamokorifyoursystem
receivesaDoSattack(page1030),theentirediskcanfillup,
andsystemaccountingandlogginginformation(whichmay
containdatathatcantellyouwhatwentwrong)maybelost.
WhenyouaskDiskDruidtosetupthediskwiththedefault
layout,itusestheschemedescribedabove,withtherootand
swapspacesetupasLVs.
PartitionSuggestions
Thissectiondiscussesadditionalpartitionsyoumaywantto
create.ConsidersettingupLVM(page32)beforeyoucreate
partitions(LVs);LVMallowsyoutochangepartitionsizeseasily
afterthesystemisinstalled.
(swap)
Linuxtemporarilystoresprogramsanddataonaswappartition
whenitdoesnothaveenoughRAMtoholdalltheinformationit
isprocessing(page458).Thesizeoftheswappartitionshould
betwicethesizeoftheRAMinthesystem,withaminimum
sizeof512megabytes.Forexample,asystemwith1gigabyte
ofRAMshouldhavea2-gigabyteswappartition.Althoughitis
notrequired,mostsystemsperformbetterwithaswap
partition.
/boot
Thispartitionholdsthekernelandotherdatathesystemneeds
whenitboots.RedHatrecommendsthatthe/bootpartitionbe
100megabytes,althoughtheamountofspacerequired
dependsonhowmanykernelimagesyouwanttokeepon
hand.Thispartitioncanbeassmallas50megabytes.Although
youcanomitthe/bootpartition,itisusefulinmanycases.
SomeolderBIOSsrequirethe/bootpartition(ortheroot[/]
partitionifthereisno/bootpartition)tobenearthebeginning
ofthedisk.
/var
Thenamevarisshortforvariable:Thedatainthispartition
changesfrequently.Becauseitholdsthebulkofsystemlogs,
packageinformation,andaccountingdata,making/vara
separatepartitionisagoodidea.Inthisway,ifauserrunsa
jobthatusesupallthediskspace,thelogswillnotbeaffected.
The/varpartitioncanoccupyfrom500megabytesupto
severalgigabytesforextremelyactivesystemswithmany
verbosedaemonsandalotofprinteractivity(filesintheprint
queuearestoredon/var).Systemsthatarelicenseserversfor
licensedsoftwareoftenqualifyasextremelyactivesystems.
/home
Itisacommonstrategytoputuserhomedirectoriesontheir
owndiskorpartition.Ifyoudonothaveaseparatediskforthe
homedirectories,putthemintheirownpartition.These
partitionsareoftennamed/homeor/usr/home.
Tip:Setuppartitionstoaidinmaking
backups
Planpartitionsaroundwhatdatayouwanttoback
upandhowoftenyouwanttobackitup.Onevery
largepartitioncanbemoredifficulttobackupthan
severalsmallerones.
/(root)
Someadministratorschoosetoseparatetheroot(/),/boot,
and/usrpartitions.Byitself,therootpartitionusually
consumeslessthan30megabytesofdiskspace.However,/lib,
whichcanconsumemorethan200megabytes,ispartofthe
rootpartition.Onoccasion,youmayinstallaspecialprogram
thathasmanykerneldriversthatconsumealotofspaceinthe
rootpartition.Allot1gigabytetotherootpartitionata
minimum.
/usr
Separatingthe/usrpartitioncanbeusefulifyouplantoexport
/usrtoanothersystemandwantthesecuritythataseparate
partitioncangive.Thesizeof/usrdependsonthenumberof
packagesyouinstall.
Tip:Wheretoputthe/bootpartition
Onoldersystems,the/bootpartitionmustreside
completelybelowcylinder1023ofthedisk.When
youhavemorethanoneharddisk,the/boot
partitionmustalsoresideonadriveon
MultipleIDEorEIDEdrives:theprimary
controller
MultipleSCSIdrives:ID0orID1
MultipleIDEandSCSIdrives:theprimaryIDE
controllerorSCSIID0
/usr/localand/opt
Both/usr/localand/optarealsocandidatesforseparation.If
youplantoinstallmanypackagesinadditiontoRedHatLinux,
youmaywanttokeepthemonaseparatepartition.Ifyou
installtheadditionalsoftwareinthesamepartitionastheusers'
homedirectories,forexample,itmayencroachontheusers'
diskspace.Manysiteskeepall/usr/localor/optsoftwareon
oneserverandexportittoothersystems.Ifyouchooseto
createa/usr/localor/optpartition,itssizeshouldbe
appropriatetothesoftwareyouplantoinstall.
Table2-1givesguidelinesforminimumsizesforpartitionsused
byLinux.Sizeotherpartitions,suchas/home,/opt,and
/usr/local,accordingtoneedandthesizeoftheharddisk.If
youarenotsurehowyouwilluseadditionaldiskspace,youcan
createextrapartitionsusingwhatevernamesyoulike(for
example,/b01,/b02,andsoon).
Table2-1.Examplepartitionsizes
Partition Examplesize
/boot 50100megabytes.
/(root) 1gigabyte.
(swap) TwotimestheamountofRAM(memory)inthesystem
withaminimumof512megabytes.
/home Aslargeasnecessary;dependsonthenumberofusers
andthetypeofworktheydo.
/tmp Minimumof500megabytes.
/usr Minimumof1.75.5gigabytes,dependingonwhichRed
HatLinuxprogramsyouinstall.Thesefiguresassume
/usr/localisaseparatepartition.
/var Minimumof500megabytes.
RAID
RAID(RedundantArrayofInexpensive/IndependentDisks)
employstwoormoreharddiskdrivesorpartitionsin
combinationtoimprovefaulttoleranceand/orperformance.
Applicationsandutilitiesseethesemultipledrives/partitionsas
asinglelogicaldevice.RAID,whichcanbeimplementedin
hardwareorsoftware(RedHatgivesyouthisoption),spreads
dataacrossmultipledisks.Dependingonwhichlevelyou
choose,RAIDcanprovidedataredundancytoprotectdatain
thecaseofhardwarefailure.Althoughitcanalsoimprovedisk
performancebyincreasingread/writespeed,RAIDusesquitea
bitofCPUtime,whichmaybeaconsiderationinsome
situations.FedoraCore5introducedsupportformotherboard-
basedRAIDchipsthroughthedmraiddriverset.
Caution:Donotreplacebackupswith
RAID
DonotuseRAIDasareplacementforregular
backups.Ifyoursystemundergoesacatastrophic
failure,RAIDwillbeuseless.Earthquake,fire,theft,
andotherdisastersmayleavetheentiresystem
inaccessible(ifyourharddisksaredestroyedor
missing).RAIDalsodoesnottakecareofsomething
assimpleasreplacingafilewhenyoudeleteitby
accident.Inthesecases,abackuponaremovable
medium(thathasbeenremoved)istheonlyway
youwillbeabletorestoreafilesystem.
DiskDruidgivesyouthechoiceofimplementingRAIDlevel0,
1,5,or6:
RAIDlevel0(striping)Improvesperformancebutoffers
noredundancy.ThestoragecapacityoftheRAIDdeviceis
equaltothatofthememberpartitionsordisks.
RAIDlevel1(mirroring)Providessimpleredundancy,
improvingdatareliability,andcanimprovetheperformance
ofread-intensiveapplications.Thestoragecapacityofthe
RAIDdeviceisequaltooneofthememberpartitionsor
disks.
RAIDlevel5(diskstripingwithparity)Provides
redundancyandimproves(mostnotably,read)
performance.ThestoragecapacityoftheRAIDdeviceis
equaltothatofthememberpartitionsordisks,minusone
ofthepartitionsordisks(assumingtheyareallthesame
size).
RAIDlevel6(diskstripingwithdoubleparity)
Improvesuponlevel5RAIDbyprotectingdatawhentwo
disksfailatonce.Level6RAIDisinefficientwithasmall
numberofdrives.
LVM:LogicalVolumeManager
TheLogicalVolumeManager(LVM2,whichwillbereferredtoas
LVM)allowsyoutochangethesizeoflogicalvolumes(LVs,the
LVMequivalentofpartitions)onthefly.WithLVM,ifyoumakea
mistakeinsettingupLVsoryourneedschange,youcanuse
system-config-lvmtomakeLVssmallerorlargereasilywithout
affectinguserdata.YoumustchoosetouseLVMatthetime
youinstallthesystemoraddaharddisk;youcannot
retroactivelyapplyittoadiskfullofdata.LVMsupportsIDE
andSCSIdrivesaswellasmultipledevicessuchasthosefound
inRAIDpartitions.
LVMgroupsdiskcomponents(partitions,harddisks,orstorage
devicearrays),calledphysicalvolumes(PVs),intoastorage
pool,orvirtualdisk,calledavolumegroup(VG).SeeFigure2-
1.YouallocateaportionofaVGtocreatealogicalvolume.
Figure2-1.LVM:LogicalVolumeManager
[Viewfullsizeimage]
AnLVissimilarinfunctiontoatraditionaldiskpartitioninthat
youcancreateafilesystemonanLV.Itismucheasier,
however,tochangeandmoveLVsthanpartitions:Whenyou
runoutofspaceonafilesystemonanLV,youcangrow
(expand)theLVanditsfilesystemintoemptyornewdisk
space,oryoucanmovethefilesystemtoalargerLV.LVM'sdisk
spacemanipulationistransparenttousers;serviceisnot
interrupted.
LVMalsoeasestheburdenofstoragemigration.Whenyou
outgroworneedtoupgradePVs,LVMcanmovedatatonew
PVs.ToreadmoreaboutLVM,refertotheresourceslisting
under"MoreInformation"onpage24.
HowtheInstallationWorks
ThefollowingstepsoutlinetheprocessofinstallingRedHat
LinuxfromCDsoraDVDusingAnaconda.Installationfrom
othermediafollowssimilarsteps.SeeChapter3forthe
specificsofhowtoperformtheinstallation.
1. InsertthefirstinstallationCDortheinstallationDVDinthe
computerandturnonorresetthecomputer.
2. Aftergoingthroughcomputer-specifichardware
diagnostics,thecomputerdisplaystheinitialinstallscreen
withtheboot:promptatthebottom(page44).
3. YoucanentercommandsandpressRETURNfollowingthe
boot:prompt,pressRETURNwithoutenteringcommands,
orwaitforaminutewithoutenteringanything;the
computerbootsRedHatLinuxfromtheCDorDVD.
4. Aspartofthebootprocess,RedHatLinuxcreatesmultiple
RAMdisks(page1051)thatitusesinplaceofaharddisk
usedforanormalbootoperation.Toolsrequiredforthe
installationarecopiedtotheRAMdisks.TheuseofRAM
disksallowstheinstallationprocesstorunthroughthe
specificationanddesignphaseswithoutwritingtothehard
diskandenablesyoutooptoutoftheinstallationatany
pointbeforethesystemwarnsyouitisabouttowriteto
theharddisk.Ifyouoptoutbeforethispoint,thesystem
isleftinitsoriginalstate.Formoreinformationreferto
"BeginInstallation"onpage54.
5. Youcanchecktheinstallationmediaatthispoint.
6. Anacondastarts,usuallyprobingthehardwarebefore
startingtheXWindowSystemforagraphicalinstallation.
7. Anacondacollectsinformationabouthowyouwantto
installRedHatLinux.
8. WhenAnacondaisfinishedcollectinginformation,it
displaysascreenthatinformsyouitisabouttobegin
installation(Figure3-9,page55)andwritestheoperating
systemfilestotheharddisk.
9. Whenyourebootthesystem,Firstbootaskyousome
questionsthatarerequiredtocompletetheinstallation
(page56).
10. TheRedHatLinuxsystemisreadytouse.
TheMedium:WhereIstheSourceData?
WhenyouinstallRedHatLinux,youcopyoperatingsystemfiles
fromasourcefrequentlyCDsoraDVDtothetargetcomputer's
harddisk.Therearetwoformatsandmanypossiblesourcesfor
thefiles.
Formats
RedHatLinuxoperatingsystemfilescanbestoredintwoways:
asdirectoryhierarchiesonCDs,aDVD,oraharddisk;orasCD
imagesoraDVDimageonaharddisk(calledISOimagesafter
ISO9660,thestandarddefiningtheCDfilesystem).Although
theformatisdifferent,thecontentisthesame.Youcaninstall
RedHatLinuxorburnCDsoraDVDfromeitherformat,
althoughmostpeopleusetheISOimagestoburnCDsoraDVD
becauseitismoreconvenient.
Sources
Thischapterandthenextprovideinformationaboutinstalling
RedHatLinuxfromCDscontainingISOimagefilesorfroma
DVDcontainingasingleISOimagefile.Theproceduresare
identicalwithoneexception:WhenworkingwithaDVDyoudo
nothavetochangemediaduringinstallation.Thesechaptersdo
notcoverinstallingfromdirectoryhierarchies;youuseexactly
thesametechniquestoinstallfromadirectoryhierarchyas
fromanISOimage.Directoryhierarchiesaremorecumbersome
toworkwiththanISOimagesbecausetheycontainmanyfiles;
eachISOimageisasinglefile.
YoucanautomatetheinstallationusingKickstart(page63).
CDsorDVD
RHEL
RedHatEnterpriseLinuxCDsaresoldbyRedHatandits
distributors.ISOimagesforRedHatEnterpriseLinuxare
availablefromRedHatNetwork.Todownloadtheseimages,go
torhn.redhat.com,createanaccountifyoudonothaveone,
login,clickChannelsonthemenubaratthetopofthepage,
clickthenameoftheproductyouwanttodownload,andclick
Downloads.ThepagethatyoudownloadRedHatEnterprise
Linuxfromhasinstructionsonhowtodownloadtheinstallation
orsourcedisks.Seealso"CheckingtheFiles"(page39)and
"BurningtheCDsorDVD"(page39)formoreinformation.
FEDORA
ThisbookincludestheDVDnecessaryforinstallingFedora
Core.Alternatively,youcanpurchaseFedoraCDsorDVDfrom
third-partyvendorsoryoucandownloadtheFedoraISO
image(s)andinstallfromtheimagesorburnCDsoraDVD
(nextsection).
HardDisk
YoucanstoreISOimagefilesonthetargetsystem'sharddiskif
itisalreadyrunningLinux.Youneedtoburnonlythefirst
installationCD,therescueCD,ortheDVD(page40)toboot
thesystemforaharddiskinstallation.
Network
YoucanuseISOimagefileslocatedonaserversystemthatthe
machineyouareinstallingLinuxoncanconnecttoovera
networkduringinstallation.YoucanuseFTP,NFS,orHTTPfor
networkinstallations.UnlessyouhaveafastInternet
connection,however,itisnotadvisabletoperforman
installationovertheInternetbecauseitcantakeaverylong
time;downloadingISOfilesisamorereliableandpossiblyless
frustratingoption.Youneedtoburnonlythefirstinstallation
CD,therescueCD,ortheDVD(page40)tobootthesystemfor
anetworkinstallation.
YoucanalsoperformaremotenetworkbootusingPXE.See
"MoreInformation"onpage24forsourcesofinformationon
PXE.
Downloading,Burning,andInstallingaCDSet
oraDVD(FEDORA)
YoucandownloadandburnFedoraCoreCDs.Althoughyouwill
notgetthecustomersupportthatcomeswithRedHat
EnterpriseLinux,youwillnotpayRedHatforthesoftware.One
ofthebeautiesoffreesoftware(AppendixD)isthatitisalways
availableforfree.RedHatmakesiteasytoobtainanduse
FedoraCorebyprovidingISOimagesofitsCDsonline.These
filesarelargealmost700megabyteseachandtherearefiveof
them,sotheytakedaystodownloadusinga56Kmodemand
hoursusingabroadbandconnection.TheDVDISOmorethan3
gigabytes.
Tip:Youmustuse700-megabyteCD-
ROMblanks
WhenyouburnFedoraCoreCDsfromtheISO
imagesyoumustuse700-megabyteblanks.The
smaller650-megabyteblankswillnotworkbecause
thereistoomuchdatatofitonthem.
Thissectiontellsyouhowtofindthefilesyouneed,download
themusingacoupleofdifferenttechniques,checkthatthey
downloadedcorrectly,andburnthemtoCDsoraDVD.
FindingaSitetoDownloadFrom
TheFedoraWebsitemaintainstheISOimagesyouneed.Other
(mirror)sitesalsomaintainthesepackages.YoucanuseaWeb
browserorftptodownloadthefilesfromoneofthesesites.
Alternatively,youcanuseBitTorrenttodownloadtheISO
images;seepage39.
Tip:YoucandownloadandburntheCDs
orDVDonanyoperatingsystem
YoucandownloadandburntheCDsorDVDonany
computerthatisconnectedtotheInternet,hasa
browser,hasenoughspaceontheharddisktohold
theISOfiles(about3gigabytes),andcanburnaCD
orDVD.Ifyoudonothaveenoughspaceonthe
harddiskforallfiveCDs,youcandownloadand
burnthemoneatatime(eachrequiresslightlyless
than700megabytes).Youcanuseftpinplaceofa
browsertodownloadthefiles.Formoreinformation
referto"JumpStart:DownloadingFilesUsingftp"on
page604.
Toconservenetworkbandwidth,trytodownloadfromamirror
sitethatisclosetoyou.Failingthat,youcandownloadfromthe
RedHatsite.
Mirrorsites
LocateamirrorsitebypointingabrowseratthefollowingURL:
fedora.redhat.com/download/mirrors.html
Scrollthroughthelistofmirrorsitestofindasitenearyouand
clickthatsite'sURL.Thedisplaywillbesimilartothatshownin
Figure2-2,whichshowstheFedoradownloaddirectory.To
displaythisdirectory,pointabrowseratfedora.redhat.com,
clickDownloadfromthetabsattheleftsideofthescreen,and
thenclickDownloadServerfromtheexpandedDownloadtab.
FTPandHTTPsiteslookalittledifferentfromeachother.
Figure2-2.TheFedoradownloadserver,core
directory
[Viewfullsizeimage]
RedHatsite
TodownloadfilesfromtheRedHatFedorasite,pointabrowser
atthefollowingURL,whichlocatestheRedHatWebpageatthe
topofthedirectoryhierarchythatholdstheFedoraCorefiles
(Figure2-2):
download.fedora.redhat.com/pub/fedora/linux/core
Whenyouhavelocatedasitetodownloadfrom,continuewith
thenextsection.
FindingtheRightFilesandDownloadingThem
ThepathnamesoftheFedoraCoreISOimagefilesdifferfrom
sitetosite,asshowninthefollowingexamples:
/pub/linux/fedora/core/5/i386/iso
/fedora/core/5/i386/iso
/fedora/linux/core/5/i386/iso
Allsitesshareacommonpathfollowingthecoredirectory
(boldintheprecedinglist).Table2-2showsthehierarchybelow
thecore/5directory,thedirectoryhierarchythatholdsthe
FedoraCore5release.Ifyouaredownloadingotherthan
FedoraCore5,gotothedirectoryhierarchybelowthe
appropriatelynumbereddirectory(3,4,andsoon).The
structureofthesehierarchiesparallelsthatoftheFedoraCore5
directory.
Table2-2.RelativelocationsofFedoraCorefiles(FedoraCore
5shown)
Locationinthe
*/fedora/linuxdirectory
hierarchy Contains
core/5 FedoraCoreversion5directoryhierarchy.
core/5/source FedoraCoresourcefiles.
core/5/source/SRPMS IndividualFedoraCoresourceRPMfiles.
core/5/source/iso FedoraCoresourceISOimagefiles.
core/5/i386 FedoraCorefilesforthe32-bitarchitectures.
Seethelistofprocessorsunder"WhichAreYou
Installing:FedoraCoreorRedHatEnterprise
Linux?"onpage26.
core/5/i386/debug FedoraCoredebuggingprogramRPMfiles.
core/5/i386/iso/FC-5-
i386-disc*.iso
FedoraCoreinstallationCDISOimagefiles1
through5.
core/5/i386/iso/FC-5-
i386-DVD.iso
FedoraCoreinstallationDVDISOimagefile.
core/5/i386/iso/FC-5-
i386-rescuecd.iso
FedoraCorerescueCDISOimagefile(page40).
core/5/i386/iso/SHA1SUM SHA1checksumsfortheISOfilesinthesame
directory.
core/5/i386/os IndividualFedoraCorerpmpackages.
core/5/i386/os/RELEASE-
NOTES-en
FedoraCorereleasenotesinEnglish.Foran
HTMLversion,downloadRELEASE-NOTES-
en.html.Seethecopyat
fedora.redhat.com/docs/release-notesforthe
mostup-to-dateversion.
core/5/ppc FedoraCorefilesforthePPCarchitecture.This
directoryhierarchyisalmostthesameasthe
i386hierarchy.
core/5/x86_64 FedoraCorefilesfor64-bitarchitectures.See
thelistofprocessorsunder"WhichAreYou
Installing:FedoraCoreorRedHatEnterprise
Linux?"onpage26.Thisdirectoryhierarchyis
almostthesameasthei386hierarchy.
Click(open)directoriesuntilyougettotheisodirectoryforthe
releaseyouwanttodownload(Figure2-3).TodownloadtheCD
ISOimagefiles,clickthefivefileslistedbelow,oneatatime.
ReplaceFC-5withthenameofthereleaseyouare
downloading.TodownloadtheDVDISOimagefile,clickFC-5-
i386-DVD.iso.
FC-5-i386-disc1.iso
FC-5-i386-disc2.iso
FC-5-i386-disc3.iso
FC-5-i386-disc4.iso
FC-5-i386-disc5.iso
SHA1SUM
Figure2-3.TheisodirectoryforFedoraCore5
[Viewfullsizeimage]
Thefivelarge*.isofilesholdtheISOimagesoftheFedora
CoreCDs.TheshortSHA1SUMfileholdstheSHA1checksums
thatyoucanusetoconfirmthedownloadedfilesarecorrect
(page39).YoumaywanttodownloadtherescueCDimage
(FC-5-i386-rescuecd.iso)aswell(page40).TheFC-5-
SRPMS-disc*.isofilesholdthesourcecodeforFedoraCore;
youdonotnormallyneedthesefilestoinstallFedora.
DependinghowfasttheInternetconnectionisandhowbusy
thesiteyouaredownloadingfromis,itmaybebettertowait
untilonedownloadfinishesbeforestartingthenext.(Usingftp
[page604],youcanqueuethedownloadssotheyproceed
sequentiallywithoutintervention.)
OnceyouhavedownloadedthefiveinstallationISOfilesorthe
DVDISO,theSHA1checksumfile,andoptionallytherescueCD
ISOfile,thenextstepistocheckthatthefilesarecorrect.See
"CheckingtheFiles."
UsingBitTorrenttoDownloadtheISOImage
Files
YoucanuseBitTorrent(page484)toobtaintheISOimages.
BecauseBitTorrentisavailableforbothWindowsandMacOSX
(www.bittorrent.com),youcandownloadandburntheFedora
CDsorDVDonaWindowsmachineoraMacintosh.Seepage
484forinformationonusingBitTorrentfromLinux.Youcan
obtainBitTorrentforFedoraandthetrackerfortheISOfiles
fromtorrent.fedoraproject.org.
CheckingtheFiles
TheSHA1SUMfilecontainstheSHA1(page1054)sumsfor
eachoftheISOfiles.Whenyouprocessafileusingthesha1sum
utility,sha1sumgeneratesanumberbasedonthefile.Ifthat
numbermatchesthecorrespondingnumberintheSHA1SUM
file,thedownloadedfileiscorrect:
$grepi386-disc1SHA1SUM;sha1sumFC-5-i386-disc1.iso
43546c0e0d1fc64b6b80fe1fa99fb6509af5c0a0FC-5-i386-disc1.iso
43546c0e0d1fc64b6b80fe1fa99fb6509af5c0a0FC-5-i386-disc1.iso
CheckeachoftheISOimagesyoudownloadedinthesame
manner.ComputinganSHA1sumforalargefiletakesawhile.
Thetwolongstringsthattheprecedingcommanddisplaysmust
beidentical:Iftheyarenot,youmustdownloadthefileagain.
RHELusesanMD5SUMfileinsteadofSHA1SUMandthe
md5sumutilityinsteadofsha1sum.
Tip:TesttheISOfilesandtesttheCDsor
DVD
ItisagoodideatotesttheISOimagefileswhen
theyaredownloadedandtheburnedCDsorDVD
beforeyouusethemtoinstallRedHatLinux.Abad
fileonaCDmaynotshowupuntilyoufinish
installingRedHatLinuxandhaveitrunning.Atthat
point,itmaybedifficultandtime-consumingto
figureoutwheretheproblemlies.Testingthefiles
andCDsorDVDtakesafewminutes,butcansave
youhoursoftroubleifsomethingisnotright.Ifyou
wanttodoonlyonetest,testtheCDsorDVD.
BurningtheCDsorDVD
AnISOimagefileisanexactimageofwhatneedstobeonthe
CDorDVD.PuttingthatimageonaCDorDVDinvolvesa
differentprocessthancopyingfilestoaCDorDVD.The
CD/DVDburningsoftwareyouusehasaspecialselectionfor
burninganISOimage.Itwillbelabeledsomethingsimilarto
RecordCDfromCDImageorBurnCDImage.Refertothe
instructionsforthesoftwareyouareusingforinformationon
howtoburnanISOimagefiletoaCDorDVD.
Tip:YouneedonlyburntherescueCD
foraharddiskornetworkinstallation
IfyouareinstallingLinuxfromfilesonaharddisk
onthetargetsystemorfromfilesonanothersystem
onanetworkusingFTP,NFS,orHTTP,youneeda
waytobootthesystemtobegintheinstallation.The
rescueCD,thefirstinstallationCD,orthe
installationDVDcanservethatpurpose.Oncethe
systemisbooted,youhavenoneedfortheCDsor
DVD.
Tip:Makesurethesoftwareissetupto
burnanISOimage
BurninganISOimageisnotthesameascopying
filestoaCDorDVD.MakesuretheCD/DVDburning
softwareissetuptoburnanISOimage.Ifyou
simplycopytheISOfiletotheCDorDVD,itwillnot
workwhenyoutrytoinstallFedoraCore.
RescueCD
TherescueCDcannotdoanythingthefirstinstallationCD
cannotdo.However,itholdslessinformationsoyoucan
downloadandburnitmorequicklythanthefirstinstallationCD.
Rescuemode
YoucanusetherescueCD,thefirstinstallationCD,orthe
installationDVDtobringthesystemupinrescuemode.
Bringingasystemupandworkinginrescuemodearediscussed
onpage397.
Harddiskornetworkinstallation
YoucanusetherescueCDthesamewayyouusethefirst
installationCDortheinstallationDVDtobootthesystemto
beginaharddiskornetworkinstallation:Whilebootingfrom
eitherCDortheDVD,givethecommandlinuxaskmethodin
responsetotheboot:prompt.Seepage45formore
information.
GatheringInformationAbouttheSystem
ItisnotdifficulttoinstallandbringupaLinuxsystem,butthe
moreyouknowabouttheprocessbeforeyoustart,theeasierit
willbe.Theinstallationsoftwarecollectsinformationaboutthe
systemandcanhelpyoumakedecisionsduringtheinstallation
process.However,thesystemwillworkbetterwhenyouknow
howyouwantyourdiskpartitionedratherthanlettingthe
installationprogramcreatepartitionswithoutyourinput.The
screenwillbeeasiertouseifyouknowwhatresolutionyou
want.Therearemanydetails,andthemoredetailsyoutake
controlof,themorepleasedyouarelikelytobewiththe
finishedproduct.Findingtheinformationthatthissectionasks
forwillhelpensurethatyouendupwithasystemyou
understandandknowhowtochangewhennecessary.Moreand
more,theinstallationsoftwareprobesthehardwareandfigures
outwhatyouhave.Newerequipmentismorelikelytoreporton
itselfthanolderequipmentis.
Itiscriticaltohavecertainpiecesofinformationbeforeyou
start.OnethingLinuxcanneverfigureoutisalltherelevant
namesandIPaddresses(unlessyouareusingDHCP,inwhich
casetheaddressesaresetupforyou).
Followingisalistofitemsyoumayneedinformationabout.Get
asmuchinformationoneachitemasyoucan:manufacturer,
modelnumber,size(megabytes,gigabytes,andsoforth),
numberofbuttons,chipset(forboards),andsoon.Some
items,suchasthenetworkinterfacecard,maybebuiltintothe
motherboard.
Harddisks.
Memory(youdon'tneeditforinstallation,butitisgoodto
know).
SCSIinterfacecard.
Networkinterfacecard(NIC).
Videointerfacecard(includingtheamountofvideo
RAM/memory).
Soundcardandcompatibilitywithstandards,suchas
SoundBlaster.
Mouse(PS/2,USB,AT,andnumberofbuttons).
Monitor(size,maximumresolution).
IPaddressesandnames,unlessyouareusingDHCP(page
431),inwhichcasetheIPaddressesforthesystemare
automaticallyassigned.Mostofthisinformationcomesfrom
thesystemadministratororISP.
Systemhostname(anythingyoulike)
Systemaddress
Networkmask(netmask)
Gatewayaddress(theconnectingpointtothenetwork
orInternet)oraphonenumberwhenyouuseadial-up
connection
Addressesfornameservers,alsocalledDNSaddresses
Domainname(notrequired)
FindingtheInstallationManual
ThedefinitiveresourceforinstructionsonhowtoinstallRedHat
LinuxistheRedHatInstallationGuideforthereleaseyouare
installingandtheplatformyouareinstallingiton.Youcanview
ordownloadinstallationguidesatthefollowingsites:
RHELGotowww.redhat.com/docs/manuals/enterprise.
Additionalinstallation,setup,andtroubleshootingresources
areavailablefromRedHatat
www.redhat.com/apps/support.Youcanalsosearchfora
keywordorwordsusingtheSearchRedHatboxatthe
upper-rightcornerofmostRedHatWebpages.
FEDORAGotofedora.redhat.com,clickDocumentation
fromthetabsattheleftsideofthescreen,andthenclick
InstallationGuide.Additionalhelpisavailableat
fedoraproject.org.
ChapterSummary
WhenyouinstallRedHatLinux,youcopyoperatingsystemfiles
frommediatothelocalsystemandsetupconfigurationfilesso
thatLinuxrunsproperlyonthelocalhardware.Youcaninstall
Linuxfrommanytypesofmedia,includingCDs,DVD,orhard
disk,andfromfilesonothersystemsthatareaccessedovera
network.Operatingsystemfilescanbestoredasdirectory
hierarchiesonCDs,aDVD,oraharddisk,orasCDorDVD
(ISO)imagesonaharddisk.Youcanuseabrowser,ftp,or
BitTorrenttodownloadtheISOimages.Itisagoodideatotest
theISOimagefileswhentheyaredownloadedandtheburned
CDsbeforeyouusethemtoinstallRedHatLinux.
Themajordecisionstobemadewhenplanninganinstallation
arehowtodividetheharddiskintopartitionsandwhich
softwarepackagestoinstall.IfyouplantouseSELinux,turnit
onduringFirstboot,afteryouinstallLinux.BecauseSELinux
setsextendedattributesonfiles,itcanbeatime-consuming
processtoturnonSELinuxafterLinuxisinstalled.
TheFedoraProjectissponsoredbyRedHatandsupportedby
theopen-sourcecommunity.FedoraCoreisaLinuxreleasethat
testscutting-edgecode;itisnotrecommendedforproduction
environments.RedHatEnterpriseLinuxismorestablethan
FedoraCore.
Exercises
1. Briefly,whatdoestheprocessofinstallinganoperatingsystemsuchasRedHat
Linuxinvolve?
2. WhatisAnaconda?
3. WouldyousetupaGUIonaserversystem?Whyorwhynot?
4. Asystembootsfromtheharddisk.ToinstallLinux,youneedittobootfromaCD.
HowcanyoumakethesystembootfromaCD?
5. Whatisfreespaceonaharddisk?Whatisafilesystem?
6. WhatisanISOimage?HowdoyouburnanISOimagetoaCDorDVD?
AdvancedExercises
7. ListtworeasonswhyyoushouldnotuseRAIDtoreplacebackups.
8. WhatareRAMdisksandhowaretheyusedduringinstallation?
9. WhatisSHA1?HowdoesitworktoensurethatanISOimagefileyoudownloadis
correct?
3.Step-by-StepInstallation
INTHISCHAPTER
BootingtheSystem:Theboot:Prompt 44
TheAnacondaInstaller 47
UsingDiskDruidtoPartitiontheDisk 58
LVs:LogicalVolumes 61
SettingUpaDual-BootSystem 68
TheXWindowSystem 69
system-config-display:ConfigurestheDisplay 70
Chapter2coveredplanningtheinstallationofRedHatLinux:
determiningtherequirements;performinganupgradeversusa
cleaninstallation;planningthelayoutoftheharddisk;
obtainingthefilesyouneedfortheinstallation,includinghowto
downloadandburnCDandDVDISOimages;andcollectingthe
informationaboutthesystemyouwillneedduringinstallation.
ThischapterfocusesoninstallingFedoraCore.Theprocessof
installingRedHatEnterpriseLinuxissimilar.Frequentlythe
installationisquitesimple,especiallyifyouhavedoneagood
jobofplanning.Sometimesyoumayrunintoaproblemorhave
aspecialcircumstance;thischaptergivesyoutoolstousein
thesecases.
InstallingRedHatLinux
Tobeginmostinstallations,insertthefirstinstallationCDorthe
installationDVDintotheCD/DVDdriveandturnonorresetthe
system.Forharddisk-andnetwork-basedinstallations,youcan
usetherescueCD(page40)insteadoftheCDorDVD.
ThesystembootsfromtheCDorDVDanddisplaysascreenof
instructionswithaboot:promptatthebottom.Referto"BIOS
setup"onpage26ifthesystemdoesnotbootfromtheCDor
DVD.
Youcannotbootfromafloppydiskette
Becausemostkernelshavegrowntoolargetofitonafloppy
diskette,youcannotbootfromafloppy.Specificallyyoucannot
fitastandardFedoraCoreorRedHatEnterpriseLinuxkernelon
afloppydiskette.Fedoragivesyoutheoptionofbootingfroma
USBpendriveusingthediskboot.imgfile.
BootingtheSystem:Theboot:Prompt
Normalinstallation
Youcansupplymanydifferentparametersfollowingtheboot:
prompt.YoumustpressRETURNafterenteringanyofthese
parameters.IfyouareinstallingfromCDsoraDVD,youcan
generallypressRETURNwithoutenteringanythingtostart
installingRedHatLinux.Oryoucanjustwaitifyoudonottype
anythingforaminute,theinstallationproceedsasthoughyou
pressedRETURN.
Tip:CDandDVDinstallationsworkthe
sameway
Ontheinstallationscreens,thetermCDmeansCD
orDVD.AsidefromchangingCDsduringan
installation,thereisnodifferencebetweeninstalling
fromCDsandinstallingfromaDVD.
Displayproblems
Ifyouencounterproblemswiththedisplayduringinstallation,
supplythefollowingparameters,whichturnoffvideomemory,
inresponsetotheboot:prompt:
boot:linuxnofb
Non-CD/DVDinstallation
IfyouareinstallingfromotherthanCDsoraDVDthatis,ifyou
areinstallingfromfilesonthelocalharddiskorfromfileson
anothersystemusingFTP,NFS,orHTTPsupplythefollowing
parametersinresponsetotheboot:prompt:
boot:linuxaskmethod
Seepage45forinformationonusingtheaskmethod
parameter.
Booting
Asthesystemboots,textscrollsonthemonitor,pausing
occasionally.Afterawhile(uptoafewminutes,dependingon
thespeedofthesystem),theinstallerdisplaysagraphicalor
pseudographicaldisplay,dependingonthesystemyouare
installingandthecommandsyougaveattheboot:prompt.
Thebalanceofthissectioncoverstheparametersyoucan
supplyfollowingtheboot:prompt.Unlessyouarehaving
problemswiththeinstallationorhavespecialrequirements,you
canskiptothenextsection,"TheCDFoundScreen,"onpage
46.
BootParameters
Alloftheparameters(exceptformemtest86)youcansupply
followingtheboot:promptconsistofthewordlinuxfollowed
byanargumentthatispassedtothekernelortotheAnaconda
installer.Manyoftheseparameterscanbecombined.For
example,toinstallLinuxintextmodeusingaterminalrunning
at115,200baud,noparity,8bits,connectedtothefirstserial
device,givethefollowingparameters(the,115200n8is
optional):
boot:linuxtextconsole=ttyS0,115200n8
ThenextsetofparametersinstallsRedHatLinuxingraphical
mode(bydefault)onamonitorwitharesolutionof1024x768,
withoutprobingforanydevices.Theinstallationprogramasks
youtospecifythesourceoftheinstallationdata(CD,DVD,FTP
site,orother).
boot:linuxresolution=1024x768noprobeaskmethod
Followingaresomeoftheparametersyoucangiveattheboot:
prompt.AsetofparametersmustbeterminatedwithRETURN
keystroke.
RETURN
Withoutenteringaparameter,pressRETURNinresponsetothe
boot:prompttoperformagraphicalinstallationfromCDsora
DVD.Thisinstallationprobesthecomputertodetermineas
muchaspossibleaboutthehardware.
memtest86
Callsmemtest86+whenyoubootfromaCDorDVDonly.TheGPL-
licensedmemtest86+utilityisastand-alonememorytestforx86-
basedcomputers.PressCtoconfigurethetest;pressESCAPE
toexit.Seewww.memtest.orgformoreinformation.
linuxaskmethod
Presentsachoiceofinstallationsources:localCD/DVDorhard
disk,oroveranetworkusingNFS,FTP,orHTTP.
LocalCDROM(UseforbothCDandDVDinstallations.)
DisplaystheCDFoundscreen,whichallowsyoutotestthe
installationmedia(thesameasifyouhadpressedRETURN
withoutenteringaparameterattheboot:prompt).
HarddrivePromptsforthepartitionanddirectorythat
containstheISOimagesoftheinstallationCDsorDVD.Do
notincludethenameofthemountpointwhenyouspecify
thenameofthedirectory.Forexample,iftheISOimages
areinthe/home/sam/FC5directoryand/dev/hda6
holdsthepartitionthatisnormallymountedon/home,
youwouldspecifythepartitionas/dev/hda6andthe
directoryassam/FC5(noleadingslash).
NFS,FTP,orHTTPDisplaystheConfigureTCP/IPscreen
fromwhichyoucanselectDHCPorenterthesystem'sIP
addressandnetmask,andtheIPaddressesofthedefault
gatewayandprimarynameserver.
WhenusingNFS,theremote(server)systemmustexport
(page685)thedirectoryhierarchythatholdstheISOimagesof
theinstallationCDsorDVD.TheNFSSetupscreenrequiresyou
toentertheNFSservernameandnameoftheFedoraCore
directory.Entertheserver'sIPaddressandthenameofthe
exporteddirectory,notitsdevicename.
linuxlowres
Runstheinstallationprogramataresolutionof640x480
pixels.Seealsolinuxresolution.
linuxmem=xxxM
Overridesthedetectedmemorysize.Replacexxxwiththe
numberofmegabytesofRAMinthecomputer.
linuxmediacheck
TeststheintegrityofoneormoreinstallationCDsorDVDs
usinganSHA1sum.ThisoptionworkswiththeCD,DVD,hard
diskISO,andNFSISOinstallationmethods.Formore
informationrefertothe"TesttheCDsortheDVD"tiponpage
47.Youarealwaysaskedifyouwanttoperformthistestduring
anormalCDorDVDinstallation.
linuxnofb
noframebufferTurnsofftheframebuffer(videomemory).
Usefulwhenproblemsoccurwhenthegraphicalphaseofthe
installationstarts.ParticularlyusefulforsystemswithLCD
displays.
linuxnoprobe
Disableshardwareprobingforalldevices,includingnetwork
interfacecards(NICs),graphicscards,andthemonitor.Forces
youtoselectdevicesfromalist.Youmustknowexactlywhich
cardsorchipsthesystemuseswhenyouusetheseparameters.
Usetheseparameterswhenprobingcausestheinstallationto
hangorotherwisefail.Theseparametersallowyoutogive
argumentsforeachdevicedriveryouspecify.
linuxrescue
Putsthesysteminrescuemode;seepage397fordetails.
linuxresolution=WxH
Specifiestheresolutionofthemonitoryouareusingfora
graphicalinstallation.Forexample,resolution=1024x768
specifiesamonitorwitharesolutionof1024x768pixels.
linuxskipddc
Allowsyoutoconfigurethemonitormanually;seelinux
noprobeformoreinformation.
linuxtext
InstallsLinuxintextual(pseudographical)mode.Althoughthe
imagesonthescreenappeartobegraphical,theyare
composedentirelyoftextcharacters.
linuxvnc
InstallsoveraVNC(VirtualNetworkComputing)remote
desktopsession.AfterprovidinganIPaddress,youcancontrol
theinstallationremotelyusingaVNCclientfromaremote
computer.YoucandownloadtheVNCclient,whichrunson
severalplatforms,fromwww.realvnc.com.
TheCDFoundScreen
Thefirstscreenthattheinstallationprocessdisplaysisthe
pseudographicalCDFoundscreen.Becauseitisnotatrue
graphicalscreen,themousedoesnotwork.Instead,youmust
usetheTABorARROWkeystohighlightdifferentchoicesand
pressRETURNtoselectthehighlightedchoice.Thisscreen
allowsyoutotestasmanyinstallationCDsorDVDsasyoulike,
inanyorder.ChooseOKtotestthemediaorSkiptobypass
thetest.Seethefollowingcautionbox.
Caution:TesttheCDsortheDVD
FEDORABecauseRedHatdoesnotmanufacture
Fedoradisks,duringaCD-orDVD-basedFedora
installation,AnacondadisplaystheCDFoundscreen
beforestartingtheinstallation.Fromthisscreen,
youcanverifythattheinstallationCDsorDVDdo
nothaveanyerrors.TestingtheCDsorDVDtakesa
fewminutesandcansaveyouhoursofaggravation
iftheinstallationfailsduetobadmedia.
RHEL+FEDORAYoucanforcethedisplayoftheCD
Foundscreenbysupplyingtheparameterslinux
mediacheckinresponsetotheboot:prompt(page
46).
ACDorDVDmayfailthemediatestifthesoftwarethatwas
usedtoburnthediskdidnotincludepadding.IfaCDorDVD
failsthemediatest,trybootingwiththefollowingparameter:
linuxide=nodma
IftheCDorDVDpassesthemediatestwhenyoubootthe
systemwiththisparameter,rebootthesystemwithoutthis
parameterbeforeinstallingRedHatLinux.IfyouinstallLinux
afterhavingbootedwiththisparameter,thekernelwillbeset
uptoalwaysusethisparameterandtheinstallationand
operationofthesystemmaybeveryslow.
TheAnacondaInstaller
Anaconda,whichiswritteninPythonandC,identifiesthe
hardware,buildsthefilesystems,andinstallsorupgradesthe
RedHatLinuxoperatingsystem.Anacondacanrunintextualor
graphical(default)interactivemodeorinbatchmode(see
"UsingtheKickstartConfigurator"onpage63).
Tip:Anacondadoesnotwritetothehard
diskuntilitdisplaystheBegin
Installationscreen
WhileyouareinstallingRedHatLinux,until
AnacondadisplaystheBeginInstallationscreen
(Figure3-9,page55),youcanpressCONTROL-ALT-
DELtoaborttheinstallationprocessandrebootthe
systemwithoutmakinganychangestothehard
disk.However,ifAnacondadisplaystheinitialize
warningdialogbox(page49),whenyouclickYes,it
writestothediskimmediately.
ExactlywhichscreensAnacondadisplaysdependsonwhether
youareinstallingFedoraCoreorRedHatEnterpriseLinuxand
whichparametersyouspecifiedfollowingtheboot:prompt.
Withsomeexceptionsmostnotablyifyouarerunningatextual
installationAnacondaprobesthevideocardandmonitorand
startsanativeXserverwithalogin/tmp/X.log.(Thislogis
notpreservedunlessyoucompletetheinstallation.)
Whileitisrunning,Anacondaopensthevirtualconsoles(page
113)showninTable3-1.Youcandisplayavirtualconsoleby
pressingCONTROL-ALT-Fx,wherexisthevirtualconsole
numberandFxisthefunctionkeythatcorrespondstothe
virtualconsolenumber.
Table3-1.Virtualconsoleassignmentsduring
installation
Virtual
console Informationdisplayedduringinstallation
1Installationdialog
2Shell
3Installationlog
4Systemmessages
5Miscellaneousmessages
7GUIinteractiveinstallation
Atanytimeduringtheinstallation,youcanswitchtovirtual
console2(CONTROL-ALT-F2)andgivecommandstoseewhatis
goingon.Donotgiveanycommandsthatchangeanypartof
theinstallationprocess.Toswitchbacktothegraphical
installationscreen,pressCONTROL-ALT-F7.
UsingAnaconda
AnacondaprovidesaNextbuttonatthelower-rightcornerof
eachoftheinstallationscreensandaBackbuttonnexttoiton
mostscreens.Whenyouhavecompletedtheentriesonan
installationscreen,clickNextor,fromatextualinstallation,
presstheTABkeyuntiltheNextbuttonishighlightedandthen
pressRETURN.SelectBacktoreturntothepreviousscreen.
ClickReleaseNotesatthelower-leftcornerofthescreento
displaythereleasenotesfortheversionofRedHatLinuxyou
areinstalling.
AnacondaScreens
Anacondadisplaysdifferentscreensdependingonwhich
commandsyougiveandwhichchoicesyoumake.Duringa
graphicalinstallation,whenyouleavetheCDFoundscreen,
Anacondastarts,loadsdrivers,andprobesforthedevicesitwill
useduringinstallation.Afterprobing,itstartstheXserver.This
sectiondescribesthescreensthatAnacondadisplaysduringa
defaultinstallationandexplainsthechoicesyoucanmakeon
eachofthem.
Logo
AnacondadisplaystheLogoscreen(Figure3-1)afteritobtains
enoughinformationtostarttheXWindowSystem.Thereis
nothingforyoutodoonthisscreenexceptdisplaytherelease
notes.SelectNext.
Figure3-1.TheLogoscreen
[Viewfullsizeimage]
Language
Selectthelanguageyouwanttousefortheinstallation.This
languageisnotnecessarilythesamelanguagethattheinstalled
systemwilldisplay.
Keyboard
Selectthetypeofkeyboardattachedtothesystem.
Monitor
AnacondadisplaystheMonitorscreenonlyifitcannotprobethe
monitorsuccessfully.Selectthebrandandmodelofthemonitor
attachedtothesystem.SelectagenericLCDorCRTdisplayif
themonitorisnotlisted.YoucanspecifytheSyncfrequencies
inplaceofthemonitorbrandandmodel,butbecareful:
Specifyingthewrongvaluescanruinsomeolderhardware.
Initializewarning
Thiswarningisdisplayediftheharddiskhasnotbeenused
before.Thedialogboxsaysthatthepartitiontableonthe
devicewasunreadableandasksifyouwanttoinitializethe
drive.Whenyouinitializeadrive,alldataonthedriveislost.
ClickYesifitisanewdriveorifyoudonotneedthedataon
thedrive.Anacondainitializestheharddiskimmediately.
InstallorUpgrade
AnacondadisplaystheInstallorUpgradescreen(Figure3-2)
onlyifitdetectsaversionofRedHatLinuxontheharddisk
thatitcanupgrade.Anacondagivesyouthechoiceof
upgradingtheexistinginstallationoroverwritingtheexisting
installationwithanewone.Referto"InstallingaFreshCopyor
UpgradinganExistingRedHatSystem?"onpage27forhelpin
makingthisselection.
Figure3-2.TheInstallorUpgradescreen
[Viewfullsizeimage]
PartitiontheDisk
ThePartitiontheDiskscreen(Figure3-3)allowsyoutospecify
partitioninformationandtoselectwhichdrivesyouwantto
installRedHatLinuxon(assumingthesystemhasmorethan
onedrive).SpecifywhichdrivesyouwanttoinstallLinuxonin
theframelabeledSelectthedrive(s)touseforthis
installation.Anacondapresentsthefollowingoptionsina
combobox;clicktheboxandthenclickthechoiceyouwant:
Removeallpartitionsonselecteddrivesandcreate
defaultlayout.Deletesalldataonthediskandcreatesa
freespacethesizeofthedisktoworkwith,asthoughyou
wereworkingwithanewdrive.
Removelinuxpartitionsonselecteddrivesandcreate
defaultlayout.RemovesallLinuxpartitions,deletingthe
dataonthosepartitionsandcreatingoneormorechunksof
freespace(page1033)onthedisk.Youcancreatenew
partitionsusingthefreespace.IfthereisonlyaLinux
systemonthedisk,thischoiceisthesameastheprevious
one.
Usefreespaceonselecteddrivesandcreatedefault
layout.InstallsRedHatLinuxinthefreespaceonthedisk.
Doesnotworkifthereisnotenoughfreespace.
Createcustomlayout.Doesnotalterdiskpartitions.This
choicecausesAnacondatorunDiskDruid(page58)sothat
youcanpreservethepartitionsyouwanttokeepand
overwriteotherpartitions.ItisgoodforinstallingRedHat
Linuxoveranexistingsystemwhereyouwanttokeep
/home,forexample,butwantacleaninstallandnotan
upgrade.
Figure3-3.ThePartitiontheDiskscreen
[Viewfullsizeimage]
Thedefaultlayoutthatthefirstthreechoicescreateincludes
twologicalvolumes(LVs:swapandroot[/])andonestandard
partition(/boot).Withthissetup,mostofthespaceonthe
diskisassignedtotherootpartition.Forinformationonthe
LogicalVolumeManager,seepage32.
IfyouputacheckmarkintheboxlabeledReviewandmodify
partitioninglayoutorifyouselectCreatecustomlayoutin
thecombobox,AnacondarunsDiskDruid(page58)sothat
youcanverifyandmodifythelayoutbeforeitiswrittentothe
disk.
Tip:Thediskisnotpartitioneduntillater
Withoneexception,Anacondadoesnotwritetothe
harddiskwhenyouspecifypartitions.Instead,it
createsatablethatspecifieshowyouwantthehard
disktobepartitioned.Thediskisactuallypartitioned
andformattedwhenyouclickNextfromtheBegin
installationscreen(page54).However,ifAnaconda
displaystheinitializewarningdialogbox(page49),
whenyouclickYes,itwritestothedisk
immediately.
DiskDruid
AnacondarunsDiskDruidonlyifyouputacheckmarkinthe
boxlabeledReviewandmodifypartitioninglayoutorifyou
selectCreatecustomlayoutfromthecomboboxasdescribed
intheprevioussection.Seepage58forinformationontheDisk
Druiddisk-partitioningprogram.
Warning
Displaysawarningifyouareremovingorformattingpartitions.
ClickFormatorYestoproceed.
BootLoaderConfiguration
AnacondadisplaystheBootLoaderConfigurationscreen(Figure
3-4)onlywhenyouputacheckmarkintheboxlabeled
ReviewandmodifypartitioninglayoutorselectCreate
customlayoutinthecomboboxinthePartitiontheDisk
screen.Bydefault,Anacondainstallsthegrubbootloader(page
533).Ifyoudonotwanttoinstallabootloader,clicktheradio
buttonnexttoNobootloaderwillbeinstalled.Whenyou
installRedHatLinuxonamachinethatalreadyrunsanother
operatingsystem,Anacondafrequentlyrecognizestheother
operatingsystemandsetsupgrubsoyoucanbootfromeither
operatingsystem.Referto"SettingUpaDual-BootSystem"on
page68.Tomanuallyaddotheroperatingsystemstogrub'slist
ofbootablesystems,clickAddandspecifyalabelanddeviceto
bootfrom.Foramoresecuresystem,specifyabootloader
password.
Figure3-4.TheBootLoaderConfigurationscreen
[Viewfullsizeimage]
NetworkConfiguration
TheNetworkConfigurationscreen,whichallowsyoutospecify
networkconfigurationinformation,hasthreeparts:Network
Devices,Hostname,andMiscellaneousSettings(Figure3-5).If
youareusingDHCPtosetupthenetworkinterface,youdonot
needtochangeanythingonthisscreen.
Figure3-5.TheNetworkConfigurationscreen
[Viewfullsizeimage]
TheNetworkDevicesframeliststhenetworkdevicesthatthe
installerfinds.Normallyyouwantnetworkdevicestobecome
activewhenthesystemboots.Removethecheckmarkfrom
theboxattheleftofadeviceifyoudonotwantittobecome
activewhenthesystemboots.
Toconfigureanetworkdevicemanually(notusingDHCP),
highlightthedeviceandclickEdittotherightofthelistof
devices.AnacondadisplaystheEditInterfacewindow(Figure3-
6).RemovethecheckmarkfromtheboxlabeledConfigure
usingDHCPandentertheIPaddressandnetmaskofthe
systemintheappropriateboxesbeforeclickingOK.
Figure3-6.TheNetworkConfiguration:Edit
Interfacewindow
[Viewfullsizeimage]
IfyouarenotusingDHCP,clickmanuallyunderSetthe
hostnameintheNetworkConfigurationscreenandenterthe
nameofthesystem.WhenyouturnoffDHCPconfigurationin
NetworkDevices,Anacondaallowsyoutospecifyagateway
addressandoneormoreDNS(nameserver)addresses.Youdo
nothavetospecifymorethanoneDNSaddress,althoughitcan
beusefultohavetwoincaseonenameserverstopsworking.
ClickNexttocontinue.
TimeZone
TheTimeZonescreenallowsyoutospecifythetimezonethe
systemislocatedin.Clickalocationonthemaptoenlargethe
selectedportionofthemapandthenclickacityinthelocal
system'stimezone.Alternatively,youcanscrollthroughthelist
inthecomboboxandhighlighttheappropriateselection.Puta
checkmarkintheboxnexttoSystemclockusesUTCifthe
systemclockissettoUTC(page1062).
RootPassword
Specifytherootpasswordtwicetomakesureyoudidnotmake
amistaketypingit.
Tip:InstallKDEtofollowtheexamplesin
Chapter4
Chapter4usesexamplesfromKDEtointroducethe
graphicaldesktop.InstallKDEifyouwanttofollow
theseexamples.YoucanremoveKDElaterifyou
like.ToinstallKDE,clicktheradiobuttonnextto
CustomizenowontheSoftwareSelectionscreen
andfollowtheinstructionsinthetext.
SoftwareSelection
AstheSoftwareSelectionscreenexplains,bydefaultAnaconda
installsabasicFedoraCoresystemincludingsoftwarethat
allowsyoutousetheInternet.SeeFigure3-7(nextpage).The
screenhasthreeboxesthatyoucanputcheckmarksinto
selectadditionalcategoriesofsoftwaretoinstall:
OfficeandProductivity
SoftwareDevelopment
Webserver
Figure3-7.TheSoftwareSelectionscreen
[Viewfullsizeimage]
Towardthebottomofthescreenaretworadiobuttons:
CustomizelaterInstallsthedefaultpackagesplusthose
requiredtoperformthetasksselectedfromthelistatthe
topofthisscreen.Ifthesystemcanconnecttothe
Internet,youcaneasilyinstallotherpackagesusingpirut
(page483)afterthesystemisupandrunning.
CustomizenowCallspirut(nextsection)afteryouclick
Nextonthisscreensothatyoucanselectspecific
categoriesofsoftwareandpackagegroupsthatyouwantto
install.IfyouwanttosetupserversasdescribedinPartV
ofthisbook,selectCustomizenowandinstalltheminthe
nextstep.SeetheprecedingtipaboutinstallingKDE.
Inmostcasesitisagoodideatocustomizethesoftware
selectionbeforeinstallation.TheexamplesinChapter4are
basedonKDE.Ifyouwanttofollowtheseexamples,clickthe
radiobuttonnexttoCustomizenowandfollowthe
instructionsinthenextstep.
WhenyouselectCustomizenowintheprecedingstep,
Anacondarunsthepirututility(page483),whichallowsyouto
specifythesoftwareyouwanttoinstall.Regardlessofthe
softwareyouselectnow,youcanusepiruttochangewhich
softwareisinstalledonasystemanytimeafterthesystemis
upandrunning(aslongasthesystemcanconnecttothe
Internet).
Thepirututilitydisplaystwoadjacentframestowardthetopof
thescreen(Figure3-8).Selectasoftwarecategoryfromthe
frameontheleftandpackagegroupsfromtheframeonthe
right.Forexample,toinstallKDE,whichisnotinstalledby
default,clickDesktopEnvironmentsontheleft.Thepirut
utilityhighlightsyourselectionanddisplaysalistofdesktop
environmentsyoucaninstallontheright.Clicktheboxnextto
KDE(KDesktopEnvironment)sothereisacheckmarkinit;
piruthighlightsKDE,displaysinformationaboutKDEinthetext
frametowardthebottomofthewindow,displaysthenumberof
optionalpackagesthatareselected,andactivatestheOptional
packagesbutton.Togetstarted,acceptthedefaultoptional
packages.Seepage484forinformationaboutinstallingother
optionalpackages.Ifyouwillberunningserversonthesystem,
clickServersontheleftandselecttheserversyouwantto
installfromthelistontheright.Selectotherpackage
categoriesinthesamemanner.Whenyouaredone,clickNext.
Figure3-8.Thepirutpackageselectionutilitywith
KDEselected
[Viewfullsizeimage]
BeginInstallation
ClickingNextontheBeginInstallationscreen(Figure3-9)
beginstheprocessofwritingtotheharddisk.FirstAnaconda
partitionsandformatsthediskasnecessary;nextitinstallsRed
HatLinuxbasedonwhatyouhavespecifiedinthepreceding
screens,placingalogoftheinstallationin/root/install.log
andaKickstartfile(page63)in/root/anaconda-ks.cfg.
ClickingBackallowsyoutostepbackthroughtheinstallation
screensandmakechanges.Tocompletelychangethewayyou
setupFedoraCore,youcanpressCONTROL-ALT-DELtoreboot
thesystemandstartover.Ifyourebootthesystem,youwill
losealltheworkyoudiduptothispoint.ClickNexttoinstall
RedHatLinux.
Figure3-9.TheBeginInstallationscreen
[Viewfullsizeimage]
Caution:ThisiswhenAnacondawritesto
theharddisk
YoucanaborttheinstallationbypressingCONTROL-
ALT-DELatanypointuptoandincludingtheBegin
Installationscreen(Figure3-9)withoutmakingany
changestothesystem.OnceyoupressNextinthis
screen,Anacondawritestotheharddisk.However,
ifAnacondadisplayedtheinitializewarningdialog
box(page49),whenyouclickedYes,itwrotetothe
harddiskatthattime.
InstallingRedHatLinuxcantakeawhile.Theamountoftimeit
takesdependsonthehardwareyouareinstallingtheoperating
systemonandthenumberofsoftwarepackagesyouare
installing.IfyouareinstallingfromCDs,Anacondawill
periodicallypromptyoutoswitchCDs.
InstallationComplete
WhenAnacondaisfinished,ittellsyouthattheinstallationis
complete.RemovetheCDorDVD(ifthatisthemediumyou
wereinstallingfrom)andclickReboot.
Firstboot:WhenYouReboot
Whenthesystemreboots,itisrunningRedHatLinux.Thefirst
timeitboots,RedHatLinuxrunsFirstboot,whichasksafew
questionsbeforeallowingyoutologin.
Welcome
ThereisnothingforyoutodoontheWelcomescreen(Figure3-
10).ClickForward.
Figure3-10.TheWelcomescreen
[Viewfullsizeimage]
LicenseAgreement
AftertheWelcomescreen,FirstbootdisplaystheLicense
Agreementscreen.SelectYes,IagreetotheLicense
Agreementifyouagreewiththetermsofthelicense
agreementandclickForward.
Firewall
Nextyouaregiventheopportunitytosetupaverybasic
firewall.FirstselectEnabledorDisabledfromtheFirewall
combobox(Figure3-11).Ifyouenablethefirewall,selectthe
servicesthatyouwantthefirewalltoallowtopassthroughto
thesystem.Theseservicesaretheonesthatthesystemis
providingbymeansofserversyousetup.Forexample,youdo
notneedtoenableWWWtobrowsetheWebusingFirefox;you
needtodosoonlyifyouwanttosetupanApache(HTTP)
server.SelectingWWW(HTTP)doesnotallowHTTPS(secure
HTTP),whichisusedforsecurebrowserconnectionstofinancial
institutionsandwhengivingcreditcardinformation,through
thefirewall.SelectSecureWWW(HTTPS)toallowsecure
HTTPtopass.IntheOtherPortstextbox,listotherportsand
protocolsyouwantthefirewalltopass.TheFirewallscreenis
thesameastheonedisplayedbythesystem-config-securitylevel
utility.Formoreinformationreferto"JumpStart:Buildinga
FirewallUsingsystem-config-securitylevel"onpage768.Chapter25
oniptableshasinformationonhowtobuildamorecompleteand
functionalfirewall.ClickForward.
Figure3-11.TheFirewallscreen
[Viewfullsizeimage]
SELinux
SELinux,whichstandsforSecurityEnhancedLinux,enforces
securitypoliciesthatlimitwhatauserorprogramcando.On
thisscreenyoucanchooseoneoftwopolicies,Enforcingor
Permissive,oryoucandisableSELinux.IfyouenableSELinux,
youcanalsomodifyitspolicy.ThepolicydefaultstoEnforcing,
whichpreventsanyuserorprogramfromdoinganythingthatis
notpermittedbythepolicy.Ifyouwillneverwanttouse
SELinux,disableit.Ifyoudonotwanttouseitnowbutmay
wanttodosointhefuture,establishaPermissivepolicyit
issueswarningsbutdoesnotenforcethepolicy.Itcantakea
lotoftimetoturnonSELinuxonasystemwhereithasbeen
disabled.Formoreinformationreferto"SELinux"onpage400.
ClickForward.
DateandTime
Thenextscreenallowsyoutosetthedateandtime.Running
theNetworkTimeProtocol(NTP)causesthesystemclockto
resetitselfperiodicallyfromaclockontheInternet.Ifthe
systemisconnectedtotheInternet,youmaywanttoenable
NTPbyclickingtheNetworkTimeProtocoltabandputtinga
checkmarkintheboxnexttoEnableNetworkTime
Protocol.ClickForward.
Display
NextFirstbootdisplaystheDisplayscreen,whichallowsyouto
specifythetype,resolution,andcolordepthofthemonitor.For
moreinformationreferto"system-config-display:Configuresthe
Display"onpage70.ClickForward.
SystemUser
Thenextscreenallowsyoutosetupuseraccounts.Youcanset
upuseraccountseithernoworafterthesystemisfully
operational.Formoreinformationreferto"ConfiguringUser
andGroupAccounts"onpage538.
SoundCard
TheSoundCardwindowidentifiesthesoundcard(s)andhasa
buttonthatcanplayatestsound.Youcanspecifythedefault
audiocardandPCM(digitalaudio)devicefromtheSoundCard
screen.ClickFinish.
WhentheSoundCardscreencloses,youaredonewiththe
installation.Youcannowusethesystemandsetitupasyou
desire.Youmaywanttocustomizethedesktopasexplainedin
Chapters4and8orsetupserversasdiscussedinPartVofthis
book.
InitializingDatabasesandUpdatingtheSystem
Afterbootingthesystem,loginasorsutoroot.Updatethe
whatisdatabasesothatwhatis(page146)andapropos(page
145)workproperly.Nextupdatethelocatedatabasesothat
locateworksproperly.(Thelocateutilityindexesandallowsyouto
searchforfilesonyoursystemquicklyandsecurely.)Insteadof
updatingthesedatabaseswhenyouinstallthesystem,youcan
waitforcron(page547)torunthemovernight,butbeaware
thatwhatis,apropos,andlocatewillnotworkuntilthenextday.
Thebestwaytoupdatethesedatabasesisviathecronscripts
thatrunthemdaily.Workingasroot,givethefollowing
commands:
#/etc/cron.daily/makewhatis.cron
#/etc/cron.daily/mlocate.cron
Theseutilitiesrunforseveralminutesandmaycomplainabout
notbeingabletofindafileortwo.Whenthesystemdisplaysa
prompt,thewhatisandlocatedatabasesareup-to-date.
IfthesystemispermanentlyconnectedtotheInternet,youcan
setupyum(page476)toupdatethesystemsoftwareand
utilitiesnightly.IfitisconnectedtotheInternetperiodically,
youmustrunyummanuallytoupdatethesystem.Workingas
root,givethefollowingcommands:
#/sbin/serviceyumstart
#/sbin/chkconfigyumon
Seepage482formoreinformation.
InstallationTasks
Thissectiondetailssomecommontasksyoumayneedto
performduringorafterinstallation.ItcoversusingDiskDruid
topartitionthediskduringinstallation,usingpartedtomodify
partitionsafterinstallation,usingKickstarttoautomate
installation,andsettingupasystemthatwillbooteither
WindowsorLinux(adual-bootsystem).
UsingDiskDruidtoPartitiontheDisk
DiskDruid,agraphicaldisk-partitioningprogramthatcanadd,
delete,andmodifypartitionsonaharddisk,ispartoftheRed
Hatinstallationsystem.YoucanuseDiskDruidonlywhileyou
areinstallingasystem:Itcannotberunonitsown.Youcan
useparted(page65)tomanipulatepartitionsandsystem-config-lvm
toworkwithLVsafteryouinstallRedHatLinux.Asexplained
earlier,ifyouwantabasicsetofpartitions,youcanallow
Anacondatopartitiontheharddiskautomatically.
AnacondarunsDiskDruidwhenyouputacheckmarkinthe
boxlabeledReviewandmodifypartitioninglayoutorifyou
selectCreatecustomlayoutinthePartitiontheDiskscreen
(page50).
CloneandRAID
DiskDruidincludesClone,atoolthatcopiesthepartitioning
schemefromasingledrivetootherdrives.Cloneisusefulfor
makingmultiplecopiesofaRAIDpartition/drivewhenyouare
creatingalargeRAIDarrayofidenticalpartitionsoridentically
partitioneddrives.ClicktheRAIDbuttontoaccesstheClone
tool,whichisactiveonlywhenatleastoneunallocatedRAID
partitionexists.FormoreinformationonRAID,seepage31.
Figure3-12showstheDiskDruidmainscreenasitappears
whenyouhavechosenthedefaultlayoutfortheharddisk(see
"PartitiontheDisk"onpage50).Thisscreenhasthreesections
(goingfromtoptobottom):agraphicalrepresentationofthe
diskdrivesshowinghoweachispartitioned(notshownFigure
3-12),arowofbuttons,andagraphicaltablelistingone
partitionorLVperline.
Figure3-12.DiskDruid:mainscreen,default
layout
[Viewfullsizeimage]
Thefollowingbuttonsappearnearthetopofthescreen:
NewAddsanewpartitiontothedisk(page60).
EditEditsthehighlightedpartitionorLV(bothonpage61).
DeleteDeletesthehighlightedpartitionorLV.
ResetCancelsthechangesyouhavemadeandcausesthe
DiskDruidtabletorevertsoitmatchesthelayoutofthe
disk.
RAIDEnablesyoutocreatesoftwareRAIDpartitionsandto
jointwoormoreRAIDpartitionsintoaRAIDdevice(page
31).
LVMEnablesyoutocreatephysicalvolumes(PVs),which
youcanthenusetocreateLVs(page32).
TheDiskDruidtablecontainsthefollowingcolumns:
DeviceThenameofthedeviceinthe/devdirectory(for
example,/dev/hda1).
MountPoint/RAID/VolumeSpecifieswherethepartition
willbemountedwhenthesystemisbroughtup(for
example,/usr).AlsousedtospecifytheRAIDdeviceor
LVMvolumethepartitionispartof.
TypeThetypeofpartition,suchasext3,swap,orPV.
FormatAcheckmarkinthiscolumnindicatesthepartition
willbeformattedaspartoftheinstallationprocedure.All
dataonthepartitionwillbelost.
Size(MB)ThesizeofthepartitionorLVinmegabytes.
StartThenumberoftheblockthepartitionstartson.
EndThenumberoftheblockthepartitionendson.
Atthebottomofthescreenisaboxthatallowsyoutohide
RAIDdeviceandLVMvolumegroupmembers.Donotputa
checkmarkinthisboxifyouwanttoseeallinformationabout
thediskdrives.
Addanewpartition
Toaddanewpartitiontoaharddisk,theharddiskmusthave
enoughfreespacetoaccommodatethepartition.ClicktheNew
buttontoaddapartition;DiskDruiddisplaystheAddPartition
window(Figure3-13).Specifythemountpoint(thenameof
thedirectorythatthepartitionwillbemountedover[page
466])andthefilesystemtype;usethearrowbuttonsatthe
rightendofthesetextboxestodisplaydrop-downmenusof
choices.Ifthereismorethanonedrive,putacheckmarkin
theboxnexttothedriveyouwantthepartitiontobecreated
onintheAllowableDrivesframe.Specifythesizeofthe
partitionand,intheAdditionalSizeOptionsframe,markFixed
sizetocreatethepartitionclosetothesizeyouspecify.
Becauseofblock-sizeconstraints,partitionsarenotusually
exactlythesizeyouspecify.MarkFillallspaceupto(MB)
andfillinthemaximumsizeyouwantthepartitiontobeto
createapartitionthattakesuptheexistingfreespace,upto
themaximumsizeyouspecify.Inotherwords,DiskDruiddoes
notcomplainifitcannotcreatethepartitionaslargeasyou
wouldlike.Markthethirdchoice,Filltomaximumallowable
size,tocausethepartitiontooccupyalltheremainingfree
spaceonthedisk,regardlessofsize.(Ifyoucreateanother
partitionaftercreatingaFilltomaximumallowablesize
partition,thenewpartitionwillpullblocksfromtheexisting
maximumsizepartition.)Putacheckmarkintheboxlabeled
Forcetobeaprimarypartitiontocreateaprimarypartition.
ClickOK,andDiskDruidaddsthepartitiontoitstable(but
doesnotwritetotheharddisk).
Figure3-13.DiskDruid:AddPartitionwindow,
ext3filesystem
[Viewfullsizeimage]
Editanexistingpartition
Tomodifyanexistingpartition,highlightthepartitioninthe
DiskDruidtableorthegraphicalrepresentationoftheharddisk
andclicktheEditbutton;DiskDruiddisplaystheEditPartition
window.Fromthiswindow,youcanchangethemountpointof
apartitionorformatthepartitionasanothertype(ext3,vfat,
swap,andsoon).Youcannotchangethesizeofapartition
fromthiswindow.Todosoyoumustdeletethepartitionand
createanewpartitionofthedesiredsize.
LVs:LogicalVolumes
WhenyouaskAnacondatopartitiontheharddiskwithadefault
layout(see"PartitiontheDisk"onpage50),itusesLVM(page
32)tosetupmostoftheharddisk,creatingLVsinsteadof
partitions.Itplaces/bootonthefirstpartitiononthedrive,
notunderthecontrolofLVM.LVMcreatesaVG(volumegroup)
namedVolGroup00.WithinthisVGitcreatestwoLVs:swap
(LogVol01)androot(/,LogVol00).TheswapLVoccupiesup
toafewgigabytes;therootLVtakesuptherestofthedrive.
ThissectionexplainshowtomaketherootLVsmallersothat
youcanaddadditionalLVstoVolGroup00.
IfyouclicktheLVMbuttonwiththedefaultsetup(withtheroot
LVoccupyingallofthediskthatisnotoccupiedbytheswapLV
andthe/bootpartition),DiskDruiddisplaysadialogboxthat
advisesyouthattherearenotenoughphysicalvolumesand
suggeststhatyoucreateanewpartition.Becausetheexisting
partitionsoccupythewholedisk,youcannotcreateanew
partition.
TomaketherootLVsmallerandmakeroomforadditional
partitions,firsthighlighttherootpartition(LogVol00)andthen
clickEdit.DiskDruiddisplaystheEditLVMVolumeGroup
window(Figure3-14).ThefigureshowsthatVolGroup00has
nofreespace(seethelineinthemiddleofthewindow).It
showstwoLVs:swap,whichdoesnothaveamountpoint,and
root,withamountpointof/.
Figure3-14.DiskDruid:EditLVMVolumeGroup
window
[Viewfullsizeimage]
Highlightroot(LogVol00)intheLogicalVolumesframeand
clickEdit.DiskDruiddisplaystheEditLogicalVolumewindow
(Figure3-15),whichallowsyoutochangethesizeoftheroot
partition.ReplacethenumbersintheSize(MB)textboxwith
thenumberofmegabytesyouwanttoassigntotheroot
partition.Figure3-15showsthesizeoftherootpartitionbeing
changedto10gigabytes(10,000megabytes).ClickOK.
Figure3-15.DiskDruid:EditLogicalVolume
window
[Viewfullsizeimage]
Onceyoudecreasethesizeoftherootpartition,theEditLVM
VolumeGroupwindowshowsthattheVGhasfreespace.You
cannowaddanotherLVtotheVG.ClickAddintheEditLVM
VolumeGroupwindowtodisplaytheMakeLogicalVolume
window(Figure3-16).Selectamountpoint,filesystemtype,
andsizefortheLV.YoucanchangetheLVnameifyoulike,
althoughDiskDruidassignslogical,sequentialnamesthatare
easytouse.Figure3-16showsa/homeLVbeingcreatedwith
asizeof25gigabytes.ClickOKwhentheLVissetuptheway
youwant.
Figure3-16.DiskDruid:MakeLogicalVolume
UsingtheKickstartConfigurator
KickstartisRedHat'sprogramthatcompletelyorpartially
automatesthesameinstallationandpostinstallation
configurationononeormoremachines.TouseKickstart,you
createasinglefilethatanswersallthequestionsthatare
normallyaskedduringaninstallation.Anacondathenrefersto
thisfileinsteadofaskingyouquestions.UsingKickstart,you
canautomatelanguageselection,networkconfiguration,
keyboardselection,bootloaderinstallation,diskpartitioning,X
WindowSystemconfiguration,andmore.
Thesystem-config-kickstartutility(partofthesystem-config-
kickstartpackagethatyoucaninstallusingyum[page478])
displaystheKickstartConfiguratorwindow(Figure3-18),which
createsaKickstartinstallationscript.OnRHELsystemsyou
mayneedtodownloadthepackagethatcontainsKickstart
usingRedHatNetwork(page498).
Figure3-18.KickstartConfigurator
[Viewfullsizeimage]
Figure3-18showsthefirstwindowtheKickstartConfigurator
displays.TogenerateaKickstartfile(ks.cfgbydefault),go
througheachsectionofthiswindow(theitemsalongtheleft
side)andfillintheanswersandputcheckmarksinthe
appropriateboxes.ClickHelponthemenubarforinstructions
oncompletingthesetasks.Whenyouarefinished,clickFile
Save.TheKickstartConfiguratorgivesyouachancetoreview
thegeneratedscriptbeforeitsavesthefile.
parted:ReportsonandPartitionsaHardDisk
Theparted(partitioneditor)utilityreportsonandmanipulates
harddiskpartitions.Thefollowingexampleshowshowtouse
partedfromthecommandline.Itusestheprintcommandto
displayinformationaboutthepartitionsonthe/dev/hda
drive:
#/sbin/parted/dev/hdaprint
Diskgeometryfor/dev/hda:0kB-165GB
Disklabeltype:msdos
NumberStartEndSizeTypeFilesystemFlags
132kB1045MB1045MBprimaryext3boot
21045MB12GB10GBprimaryext3
312GB22GB10GBprimaryext3
422GB165GB143GBextended
522GB23GB1045MBlogicallinux-swap
623GB41GB18GBlogicalext3
741GB82GB41GBlogicalext3
Information:Don'tforgettoupdate/etc/fstab,ifnecessary.
Figure3-19graphicallydepictsthepartitionsshowninthe
example.Thefirstlinethatparteddisplaysspecifiesthedevice
beingreportedon(/dev/hda)anditssize(165gigabytes).
Theprintcommanddisplaysthefollowingcolumns:
NumberTheminordevicenumber(page463)ofthe
deviceholdingthepartition.Thisnumberisthesameasthe
lastnumberinthedevicename.Intheexample,4
correspondsto/dev/hda4.
StartThelocationonthediskwherethepartitionstarts.
Thepartedutilityspecifiesalocationonthediskasthe
distance,inbytes,fromthestartofthedisk.Thuspartition
3starts12gigabytesfromthestartofthedisk.
EndThelocationonthediskwherethepartitionstops.
Althoughpartition2ends12gigabytesfromthestartofthe
diskandpartition3startsatthesamelocation,partedtakes
carethatthepartitionsdonotoverlapatthissinglebyte.
SizeThesizeofthepartitioninkilobytes(kB),megabytes
(MB),orgigabytes(GB).
TypeThepartitiontype:primary,extended,orlogical.See
Figure3-19(nextpage)andpage28forinformationon
partitions.
FilesystemThefilesystemtype:ext2,ext3,fat32,
linux-swap,etc.SeeTable12-1onpage464foralistof
filesystemtypes.
FlagsTheflagsthatareturnedonforthepartition,
includingboot,swap,raid,andlvm.Intheexample,
partition1isbootable.
Figure3-19.Theprimaryandextendedpartitions
fromtheexample
Intheprecedingexample,partition4definesanextended
partitionthatincludes143gigabytesofthe165gigabytedisk
(Figure3-19).Youcannotmakechangestoanextended
partitionwithoutaffectingalllogicalpartitionswithinit.
Inadditiontoreportingonthelayoutandsizeofadiskdrive,
youcanusepartedinteractivelytomodifythedisklayout.Be
extremelycarefulwhenusingpartedinthismanner,andalways
backupthesystembeforestartingtoworkwiththisutility.
Changingthepartitioninformation(thepartitiontable)ona
diskcandestroytheinformationonthedisk.Readthepartedinfo
pagebeforemodifyingapartitiontable.
Caution:partedcandestroyeverything
Beascarefulwithpartedasyouwouldbewitha
utilitythatformatsaharddisk.Changesyoumake
withpartedcaneasilyresultinthelossoflarge
amountsofdata.Ifyouareusingpartedandhave
anyquestionaboutwhatyouaredoing,quitwithaq
commandbeforemakinganychanges.Onceyou
givepartedacommand,itimmediatelymakesthe
changeyourequested.
Topartitionadisk,givethecommandpartedfollowedbythe
nameofthedeviceyouwanttoworkwith.Following,after
startingparted,theusergivesahelp(orjusth)command,
whichdisplaysalistofpartedcommands:
#/sbin/parted/dev/hdb
GNUParted1.6.25
...
Using/dev/hda
(parted)help
checkNUMBERdoasimplecheckonthefilesystem
cp[FROM-DEVICE]FROM-NUMBERTO-NUMBERcopyfilesystemtoanotherpartition
help[COMMAND]printsgeneralhelp,orhelponCOMMAND
mklabelLABEL-TYPEcreateanewdisklabel(partitiontable)
mkfsNUMBERFS-TYPEmakeaFS-TYPEfilesystemonpartititonNUMBER
mkpartPART-TYPE[FS-TYPE]STARTENDmakeapartition
mkpartfsPART-TYPEFS-TYPESTARTENDmakeapartitionwithafilesystem
moveNUMBERSTARTENDmovepartitionNUMBER
nameNUMBERNAMEnamepartitionNUMBERasNAME
print[NUMBER]displaythepartitiontable,orapartition
quitexitprogram
rescueSTARTENDrescuealostpartitionnearSTARTandEND
resizeNUMBERSTARTENDresizepartitionNUMBERanditsfilesystem
rmNUMBERdeletepartitionNUMBER
selectDEVICEchoosethedevicetoedit
setNUMBERFLAGSTATEchangeaflagonpartitionNUMBER
unitUNITsetthedefaultunittoUNIT
(parted)
Inresponsetothe(parted)promptyoucangivethecommand
helpfollowedbythenameofthecommandyouwantmore
informationabout.Seethefollowingexample.Whenyougivea
print(orjustp)command,parteddisplayscurrentpartition
informationjustasaprintcommandonthecommandline
does.
Thepartedutilitywillnotallowyoutosetupoverlapping
partitions(exceptforlogicalpartitionsoverlappingtheir
containingextendedpartition)anditwillnotallowyoutocreate
apartitionthatstartsattheverybeginningofthedisk(cylinder
0).Bothofthesesituationscancauselossofdata.Following
areguidelinestorememberwhendefiningapartitiontablefora
disk.Formoreinformationreferto"PartitioningaDisk"onpage
29.
Donotdeleteormodifythepartitionthatdefinesthe
extendedpartitionunlessyouarewillingtolosealldataon
allofthelogicalpartitionswithintheextendedpartition.
Itisagoodideatoput/bootatthebeginningofthedrive
(partition1)sothatthereisnoissueofLinuxhavingto
bootfromapartitiontoofarintothedrive.Whenyoucan
affordthediskspace,itisdesirabletoputeachmajor
filesystemonaseparatepartition.Manypeoplechooseto
combineroot,/var,and/usrintoasinglepartition,which
generallyresultsinlesswastedspacebutcan,onrare
occasions,causeproblems.Althoughitisnot
recommended,youcanputthecontentsoftheboot
directoryintherootfilesystem.
Althoughpartedcancreatesometypesoffilesystems,itis
usuallyeasiesttousepartedtocreatepartitionsandthen
usemkfsandmkswaptocreatefilesystemsonthepartitions.
Thefollowingsequenceofcommandsdefinesa300-megabyte,
bootable,Linuxpartitionaspartition1onacleandisk:
#/sbin/parted/dev/hdb
...
Using/dev/hdb
(parted)mkpart(createnewpartition)
Partitiontype?primary/extended?primary(selectprimarypartition)
Filesystemtype?[ext2]?(defaulttoanext2filesystem)
Start?1(startatthebeginningofthedisk)
End?300m(specifya300-megabytepartition)
(parted)helpset(usehelptocheckthesyntaxofthesetcommand)
setNUMBERFLAGSTATEchangeaflagonpartitionNUMBER
NUMBERisthepartitionnumberusedbyLinux.Onmsdosdisklabels,theprimary
partitionsnumberfrom1to4,logicalpartitionsfrom5onwards.
FLAGisoneof:boot,root,swap,hidden,raid,lvm,lba,hp-service,palo,
prep,msftres
STATEisoneof:on,off
(parted)set1booton(turnonthebootflagonpartition1)
(parted)print(verifythatthepartitioniscorrect)
Diskgeometryfor/dev/hdb:0kB-250GB
Disklabeltype:msdos
NumberStartEndSizeTypeFilesystemFlags
11kB300MB300MBprimaryext2boot
(parted)quit
Information:Don'tforgettoupdate/etc/fstab,ifnecessary.
Whenyouspecifyasizewithinparted,youcanuseasuffixofk
(kilobytes),m(megabytes),org(gigabytes).Aftercreatinga
partitiongiveaprintcommandtoseewherethepartitionends.
Performthistaskbeforedefiningthenextcontiguouspartition
sothatyoudonotwastespaceorhaveanyoverlap.After
settingupallthepartitions,exitfrompartedwithaquit
command.
Next,makeafilesystem(mkfs,page419)oneachpartitionthat
istoholdafilesystem(notswap).Makeallpartitions,except
swapand/boot,typeext3,unlessyouhaveareasontodo
otherwise.Makethe/bootpartitiontypeext2.Usemkswap
(page458)tosetupaswapareaonapartition.Youcanuse
e2label(page418)tolabelapartition.
SettingUpaDual-BootSystem
Adual-bootsystemisonethatcanbootoneoftwooperating
systems.Inthissection,dual-bootreferstoasystemthatcan
bootWindowsorLinux.Thebiggestprobleminsettingupa
dual-bootsystem,assumingyouwanttoaddLinuxtoa
Windowssystem,isfindingenoughdiskspaceforLinux.The
Linux+WindowsNTmini-HOWTOcoversinstallingLinuxfirstand
WindowsNTsecond(ortheotherwayaround).Thenext
sectiondiscussesseveralwaystocreatetheneededspace.
CreatingFreeSpaceonaWindowsSystem
TypicallyyouinstallRedHatLinuxinfreespaceonaharddisk.
ToaddRedHatLinuxtoaWindowssystem,youmustprovide
enoughfreespace(referto"Harddiskspace"onpage26)ona
harddiskthatalreadycontainsWindows.Thereareseveral
waystoprovideorcreatethisfreespace.Thefollowingways
areorderedfromeasiesttomostdifficult:
Useexistingfreespace
IfthereissufficientfreespaceontheWindowsdisk,youcan
installLinuxthere.Thistechniqueistheoptimalchoice,but
thereisrarelyenoughfreespaceonaninstalledharddisk.
ResizeWindowspartitions
YoucanuseWindowssoftware,suchasPartitionMagic,to
resizeexistingWindowspartitionstoopenupfreespacein
whichtoinstallLinux.
Addanewdiskdrive
AddanotherdiskdrivetothesystemandinstallLinuxonthe
newdisk,whichcontainsonlyfreespace.Thistechniqueisvery
easyandcleanbutrequiresanewdiskdrive.
RemoveaWindowspartition
IfyoucandeleteabigenoughWindowspartition,youcan
installLinuxinitsplace.TodeleteaWindowspartition,you
musthavemultiplepartitionsunderWindowsandbewillingto
loseanydatainthepartitionyoudelete.Inmanycases,you
canmovethedatafromthepartitionyouwilldeletetoanother
Windowspartition.
Onceyouaresureapartitioncontainsnousefulinformation,
youcanuseDiskDruidtodeleteitwhenyouinstallLinux:From
thePartitiontheDiskscreen(page50),choosetocreatea
customlayoutwithDiskDruid,highlightthepartitionyouwant
todelete,andclicktheDeletebutton.Afterdeletingthe
partition,youcaninstallRedHatLinuxinthefreespaceleftby
thepartitionyouremoved.
InstallingRedHatLinuxastheSecondOperatingSystem
AftercreatingenoughfreespaceonaWindowssystem(as
discussedintheprevioussection),youcanbegininstallingRed
HatLinux.WhenyougettothePartitiontheDiskscreen(page
50),chooseUsefreespaceonselecteddrivesandcreate
defaultlayouttohaveAnacondapartitionthefreespaceon
theharddiskautomatically.IfyouneedtodeleteaWindows
partition,youmustchooseCreatecustomlayout,whichcalls
DiskDruid(page58)sothatyoucandeletetheappropriate
WindowspartitionandcreateLinuxpartitionsinthefreespace.
Whenyouboot,youwillbeabletochoosewhichoperating
systemyouwanttorun.
TheXWindowSystem
Ifyouspecifiedagraphicaldesktopenvironmentsuchas
GNOMEorKDE,youinstalledtheX.org(x.org)implementation
oftheXWindowSystemwhenyouinstalledLinux.TheX
WindowSystemreleaseX11R7.0comprisesalmost20rpm
packages;theeasiestwaytoinstallX.orgonanalready
installedLinuxsystemistousepirut(page483)andchoose
BaseSystem XWindowSystem.TheXconfigurationfiles
arekeptin/etc/X11;theconfigurationfilethatguidesthe
initialsetupis/etc/X11/xorg.conf.
system-config-display:ConfigurestheDisplay
Thesystem-config-displayutilitydisplaystheDisplaysettings
window(Figure3-20),whichallowsyoutoconfigureX.org,
includingthemonitortypeandvideocard.Torunthisutility,
entersystem-config-displayonacommandline.FromKDE
selectMainmenu:Administration DisplayorfromGNOME
selectSystem:Administration Display.
Figure3-20.TheDisplaysettingswindow,
Settingstab
[Viewfullsizeimage]
Figure3-20showstheSettingstaboftheDisplaysettings
window,whichallowsyoutospecifytheresolutionandcolor
depthforthemonitor.Normallythesystemprobesthemonitor
andfillsinthesevalues.Ifthesevaluesaremissing,checkthe
specificationsforthemonitorandselecttheappropriatevalues
fromthecomboboxes.Noharmisdoneifyouspecifyalower
resolutionthanthemonitoriscapableofdisplaying,butyoucan
damageanoldermonitorbyspecifyingaresolutionhigherthan
themonitoriscapableofdisplaying.Acolordepthof8bits
equatesto256colors,16bitstothousandsofcolors,and24or
32bitstomillionsofcolors.
NextclicktheHardwaretab.Thesystemnormallyprobesfor
themonitortypeandbrandaswellasthemodelofvideocard;
thesevaluesappearnexttothewordsMonitorTypeand
VideoCard.Youcanmanuallyselectamonitororvideocard.
Figure3-21showstheMonitorwindowontopoftheHardware
taboftheDisplaysettingswindow.
Figure3-21.TheDisplaySettingswindow,
Hardwaretab,Monitorwindow
Specifyingamonitor
Tospecifyamonitor,clickConfigureacrossfromthewords
MonitorType;system-config-displaydisplaystheMonitorwindow.
Scrolldownuntilthenameofthemanufacturerofthemonitor
youareusingappearsandclickthetriangletotheleftofthat
name;system-config-displayopensalistofmodelsmadebythat
manufacturer.Scrollthroughthelistofmodels.Clickto
highlightthemodelyouareusingandthenclickOK.Ifan
appropriatemodelisnotlisted,scrolltothetopofthelistand
clickthetrianglenexttoGenericCRTDisplayorGenericLCD
Display,dependingonthetypeofmonitoryouaresettingup.
Fromoneoftheselists,selectthemaximumresolutionthe
monitoriscapableofdisplaying.ClickOK.
Specifyingavideocard
Tospecifyavideocard,clickConfigureadjacenttothewords
VideoCard;system-config-displaydisplaystheVideoCardwindow.
Scrolldownuntilyouseethemanufacturerandmodelofthe
videocardinyoursystem.ClickOK.
Specifyingtwomonitors
TheDualheadtaballowsyoutospecifyasecondvideocard
thatcandriveasecondmonitor.Specifythemonitortype,video
card,resolution,andcolordepthasyoudidearlier.Youcan
choosetohaveeachmonitordisplayadesktoportohavethe
twomonitorsdisplayasingledesktop(spanningdesktops).
ClickOKtoclosetheDisplaysettingswindow.
Thesystem-config-displayutilitygeneratesanxorg.conffile
(discussedinthenextsection)withtheinformationyou
entered.
Thexorg.confFile
The/etc/X11/xorg.conffilecomprisessectionsthatcan
appearinanyorder.Theformatofasectionis
Section"name"
entry
...
EndSection
wherenameisthenameofthesection.Atypicalentry
occupiesmultiplephysicallinesbutisactuallyjustonelogical
line,consistingofakeywordfollowedbyzeroormoreinteger,
real,orstringarguments.Keywordsinthesefilesarenotcase
sensitive;underscores(_)withinkeywordsareignored.Most
stringsarenotcasesensitive,andSPACEsandunderscoresin
moststringsareignored.Allstringsmustappearwithindouble
quotationmarks.
TheOptionkeywordprovidesfree-formdatatoserver
componentsandisfollowedbythenameoftheoptionand
optionallyavalue.AllOptionvaluesmustbeenclosedwithin
doublequotationmarks.
BooleanOptionstakeavalueofTRUE(1,on,true,yes)or
FALSE(0,off,false,no);novalueisthesameasTRUE.You
canprependNotothenameofaBooleanOptiontoreversethe
senseoftheOption.
Thefollowingsectionscanappearinanxorg.conffile:
ServerFlags GlobalOptions(optional)
ServerLayout BindsScreen(s)andInputDevice(s)
Files Locationsofconfigurationfiles
Module Modulestobeloaded(optional)
InputDevice Keyboard(s)andpointer(s)
Monitor Monitor(s)
Device Videocard(s)
Screen Bindsdevice(s)andmonitor(s)
VideoAdaptor ConfigurestheXvextension(optional)
Modes Videomodes(optional)
DRI DirectRenderingInfrastructure(optional)
Vendor Vendor-specificinformation(optional)
Thischaptercoversthesectionsyoumostlikelyneedtowork
with:ServerLayout,InputDevice,Monitor,Device,andScreen.
Seethexorg.confmanpageformoreinformation.
ServerLayoutSection
TheServerLayoutsectionappearsfirstinsomexorg.conffiles
becauseitsummarizestheothersectionsthatareusedto
specifytheserver.ThefollowingServerLayoutsectionnames
theserversingleheadconfigurationandspecifiesthatthe
servercomprisesthesectionsnamedScreen0,Mouse0,
Keyboard0,andDevInputMice.
Thetermcoreinthisfilemeansprimary;theremustbeexactly
oneCoreKeyboardandoneCorePointer.TheAlwaysCore
argumentindicatesthatthedevicereportscoreeventsandis
usedheretoallowanon-USBmouseandaUSBmousetowork
atthesametime.Theresultisthatyoucanuseeithertypeof
mouseinterchangeablywithoutmodifyingthexorg.conffile:
Section"ServerLayout"
Identifier"singleheadconfiguration"
Screen0"Screen0"00
InputDevice"Mouse0""CorePointer"
InputDevice"Keyboard0""CoreKeyboard"
InputDevice"DevInputMice""AlwaysCore"
EndSection
Refertothefollowingsectionsforexplanationsofthesections
specifiedinServerLayout.
InputDeviceSection
TheremustbeatleasttwoInputDevicesections:onespecifying
thekeyboardandonespecifyingthepointer(usuallyamouse).
TheformatofanInputDevicesectionis
Section"InputDevice"
Identifier"id_name"
Driver"drv_name"
options
...
EndSection
whereid_nameisauniquenameforthedeviceand
drv_nameisthedrivertouseforthedevice,typically
keyboardormouse.Thesystem-config-displayutilitytypically
createsthreeInputDevicesections.Thefollowingsection
definesakeyboarddevicenamedKeyboard0thatusesthe
keyboarddriver.Thekeyboardmodelisa105-keyPC
keyboard.Youcanchangepc105tomicrosoftifyouareusing
aU.S.MicrosoftNaturalkeyboard,althoughthedifferencesare
minimal.
Section"InputDevice"
Identifier"Keyboard0"
Driver"keyboard"
Option"XkbModel""pc105"
Option"XkbLayout""us"
EndSection
Tochangethelanguagethekeyboardsupports,changethe
argumenttotheXkbLayoutOptionto,forexample,frfor
French.
ThenextInputDevicesectiondefinesamousenamedMouse0
thatusesthemousedriver.TheDeviceOptionspecifiesaPS2
device.TheZAxisMappingOptionmapstheZaxis,themouse
wheel,tovirtualmousebuttons4and5,whichareusedto
scrollawindow.Formoreinformationreferto"Remapping
MouseButtons"onpage239.WhensettoYES,the
Emulate3ButtonsOptionenablestheuserofatwo-button
mousetoemulateathree-buttonmousebypressingthetwo
buttonssimultaneously.
Section"InputDevice"
Identifier"Mouse0"
Driver"mouse"
Option"Protocol""IMPS/2"
Option"Device""/dev/psaux"
Option"ZAxisMapping""45"
Option"Emulate3Buttons""no"
EndSection
ThenextInputDevicesectionissimilartothepreviousone
excepttheDeviceOptionspecifiesaUSBmouse.See
"ServerLayoutSection"onpage72foradiscussion.
Section"InputDevice"
#IfthenormalCorePointermouseisnotaUSBmousethen
#thisinputdevicecanbeusedinAlwaysCoremodetoletyou
#alsouseUSBmiceatthesametime.
Identifier"DevInputMice"
Driver"mouse"
Option"Protocol""IMPS/2"
Option"Device""/dev/input/mice"
Option"ZAxisMapping""45"
Option"Emulate3Buttons""no"
EndSection
MonitorSection
Thexorg.conffilemusthaveatleastoneMonitorsection.The
easiestwaytosetupthissectionistousethesystem-config-
displayutility,whicheitherdeterminesthetypeofmonitor
automaticallybyprobingorallowsyoutoselectfromalistof
monitors.
Caution:Donotguessatvaluesfor
HorizSyncorVert-Refresh
IfyouconfiguretheMonitorsectionmanually,donot
guessatthescanrates(HorizSyncandVertRefresh);
onoldermonitors,youcandestroythehardwareby
choosingscanratesthataretoohigh.
ThefollowingsectiondefinesamonitornamedMonitor0.The
VendorNameandModelNameareforreferenceonlyanddonot
affectthewaythesystemworks.TheoptionalDisplaySize
specifiestheheightandwidthofthescreeninmillimeters,
allowingXtocalculatetheDPIofthemonitor.HorizSyncand
VertRefreshspecifyrangesofverticalrefreshfrequenciesand
horizontalsyncfrequenciesforthemonitor;thesevaluesare
availablefromthemanufacturer.ThedpmsOptionspecifiesthe
monitorisDPMS(page1030)compliant(hasbuilt-inenergy-
savingfeatures).
Section"Monitor"
Identifier"Monitor0"
VendorName"MonitorVendor"
ModelName"DellD1028L"
DisplaySize360290
HorizSync31.0-70.0
VertRefresh50.0-120.0
Option"dpms"
EndSection
AMonitorsectionmaymentionDDC(DisplayDataChannel);
DDCcanbeusedbyamonitortoinformavideocardaboutits
properties.IfyouomitorcommentouttheHorizSyncand
VertRefreshlines,XwilluseDDCprobingtodetermineproper
values.
DeviceSection
Thexorg.conffilemusthaveatleastoneDevicesectionto
specifythetypeofvideocardinthesystem.TheVendorName
andBoardNameareforreferenceonlyanddonotaffectthe
waythesystemworks.Theeasiestwaytosetupthissectionis
tousethesystem-config-displayutility,whichusuallydetermines
thetypeofvideocardbyprobing.ThefollowingDevicesection
specifiesthatVideocard0usesthetdfxdriver:
Section"Device"
Identifier"Videocard0"
Driver"tdfx"
VendorName"Videocardvendor"
BoardName"Voodoo3(generic)"
EndSection
ScreenSection
Thexorg.conffilemustcontainatleastoneScreensection.
ThissectionbindsavideocardspecifiedintheDevicesectionto
adisplayspecifiedintheMonitorsection.ThefollowingScreen
sectionspecifiesthatScreen0comprisesVideocard0and
Monitor0,bothdefinedelsewhereinthefile.TheDefaultDepth
entryspecifiesthedefaultcolordepth(page1025),whichcan
beoverriddenintheDisplaysubsection.
EachScreensectionmusthaveatleastoneDisplaysubsection.
ThefollowingsubsectionspecifiesacolorDepthandthree
Modes.TheModesspecifythescreenresolutionsinunitsofdots
perinch(dpi).ThefirstModeisthedefault;youcanswitch
betweenModeswhileXisrunningbypressingCONTROL-ALT-
KEYPAD+orCONTROL-ALT-KEYPAD.Youmustusetheplusor
minusonthenumerickeypadwhengivingthesecommands.X
ignoresinvalidModes.
Section"Screen"
Identifier"Screen0"
Device"Videocard0"
Monitor"Monitor0"
DefaultDepth24
SubSection"Display"
Depth24
Modes"1024x768""800x600""640x480"
EndSubSection
EndSection
IfyouomitorcommentouttheDepthandModeslines,Xwill
useDDCprobingtodetermineoptimalvalues.
MultipleMonitors
Xhassupportedmultiplescreensforalongtime.X.org
supportsmultimonitorconfigurationsusingeithertwographics
cardsoradual-headcard.Bothsetupsareusuallyconfigured
thesamewaybecausethedriversfordual-headcardsprovidea
secondaryvirtualdevice.
TraditionallyeachscreeninXistreatedasasingleentity.That
is,eachwindowmustbeononescreenoranother.More
recentlytheXineramaextensionallowswindowstobesplit
acrosstwoormoremonitors.Thisextensionissupportedby
X.organdworkswithmostvideodrivers.WhenusingXinerama,
youmustsetallscreenstothesamecolordepth.
Foreachscreen,youmustdefineaDevice,Monitor,andScreen
sectioninthexorg.conffile.Thesesectionsareexactlythe
sameasforasingle-screenconfiguration;eachscreenmust
haveauniqueidentifier.Ifyouareusingadual-headcard,the
DevicesectionforthesecondheadislikelytorequireaBusID
valuetoenablethedrivertodeterminethatyouarenot
referringtotheprimarydisplay.Thefollowingsectionidentifies
thetwoheadsonanATIRadeon8500card.Forotherdual-head
cards,consultthedocumentationprovidedwiththedriver(for
example,givethecommandmanmgatodisplayinformation
onthemgadriver):
Section"Device"
Identifier"Videocard0"
Driver"radeon"
VendorName"ATI"
BoardName"Radeon8500"
EndSection
Section"Device"
Identifier"Videocard1"
Driver"radeon"
VendorName"ATI"
BoardName"Radeon8500"
BusID"PCI:1:5:0"
EndSection
Onceyouhavedefinedthescreens,usetheServerLayout
sectiontotellXwheretheyareinrelationtoeachother.Each
screenisdefinedinthefollowingform:
Screen[ScreenNumber]"Identifier"Position
TheScreenNumberisoptional.Ifitisomitted,Xnumbers
screensintheordertheyarespecified,startingwith0.The
IdentifieristhesameIdentifierusedintheScreensections.
ThePositioncanbeeitherabsoluteorrelative.Theeasiest
waytodefinescreenpositionsistogiveonescreenanabsolute
position,usuallywiththecoordinatesoftheorigin,andthen
usetheLeftOf,RightOf,Above,andBelowkeywordsto
indicatethepositionsoftheotherscreens:
Section"ServerLayout"
Identifier"Multiheadlayout"
Screen0"Screen0"LeftOf"Screen1"
Screen1"Screen1"00
InputDevice"Mouse0""CorePointer"
InputDevice"Keyboard0""CoreKeyboard"
InputDevice"DevInputMice""AlwaysCore"
Option"Xinerama""on"
Option"Clone""off"
EndSection
Twooptionscancontrolthebehaviorofamultimonitorlayout:
Xineramacausesthescreenstoactasiftheywereasingle
screenandClonecauseseachofthescreenstodisplaythe
samething.
gdm:DisplaysaGraphicalLogin
Traditionallyusersloggedinonatextualterminalandthen
startedtheXserver.Todaymostsystemsprovideagraphical
login.RedHatLinuxusestheGNOMEdisplaymanager(gdm)to
providethisfunctionality,evenifyouarebringingupaKDE
desktop.
Configuringgdm
Thegdmsetuputilityconfigurestheloginpresentedbygdmby
editingtheheavilycommented/etc/gdm/custom.conf
(FEDORA)or/etc/X11/gdm/gdm.conf(RHEL)file.By
default,rootcanloginbothlocallyandremotely.Itisagood
ideatodisableremoterootloginsbecause,whenauserlogsin
remotelyusinggdm,thepasswordissentincleartextacrossthe
network.FromGNOMEyoucanselectSystem:
Administration LoginScreentoconfiguregdm.
Usingkdm
ThekdmutilityistheKDEequivalentofgdm.Thereisnobenefit
inusingkdminplaceofgdm:Bothperformthesamefunction.
UsinggdmdoesnotforceyoutouseGNOME.
Theconfigurationfileforkdm,/etc/X11/xdm/kdmrc,is
heavilycommented.Youcaneditthekdmconfigurationusing
theKDEcontrolpanel,butdoingsoremovesthecomments
fromthefile.
MoreInformation
Web
X.orgX.org,freedesktop.org
X.orgdocumentationftp.x.org/pub/X11R7.0/doc/html
ChapterSummary
MostinstallationsofRedHatLinuxbeginbybootingfromthe
firstinstallationCDortheinstallationDVD.Whenthesystem
bootsfromtheCDorDVD,itdisplaysaboot:prompt.Youcan
respondtothispromptbyenteringavarietyofcommands,by
pressingRETURNwithoutenteringacommand,orbynotdoing
anything.Inallcases,thesystembootsRedHatLinuxfromthe
CD.Ifyouareinstallingfromfilesonthelocalharddiskorover
anetwork,givethecommandlinuxaskmethodinresponseto
theboot:prompt.
TheprogramthatinstallsRedHatLinuxisnamedAnaconda.
Anacondaidentifiesthehardware,buildsthefilesystems,and
installsorupgradestheRedHatLinuxoperatingsystem.
Anacondacanrunintextualorgraphical(default)interactive
modeorinbatchmode(Kickstart).Anacondadoesnotwriteto
theharddiskuntilitdisplaystheBeginInstallationscreen.Until
itdisplaysthisscreen,youcanpressCONTROL-ALT-DELtoabort
theinstallationwithoutmakinganychangestotheharddisk.
TheDiskDruidgraphicaldisk-partitioningprogramcanadd,
delete,andmodifypartitionsandlogicalvolumes(LVs)ona
harddiskduringinstallation.Thepartedutilityreportsonand
manipulatesharddiskpartitionsbeforeorafterinstallation.The
system-config-lvmutilityworkswithLVsafterinstallation.
Adual-bootsystemcanbootoneoftwooperatingsystems,
frequentlyWindowsandLinux.Thebiggestprobleminsetting
upadual-bootsystem,assumingyouwanttoaddLinuxtoa
Windowssystem,isfindingenoughdiskspaceforLinux.
FedoraCore5usestheX.orgXWindowSystemversion
X11R7.0.UnderX.org,theprimaryconfigurationfileisnamed
/etc/X11/xorg.conf.
RedHatLinuxusestheGNOMEdisplaymanager(gdm)to
provideagraphicallogin,evenifyouareusingaKDEdesktop.
Thegdmsetuputilityconfigurestheloginpresentedbygdmby
editingthe/etc/gdm/custom.conf(FEDORA)or
/etc/X11/gdm/gdm.conf(RHEL)file.
Exercises
1. WhatisthedifferencebetweenXineramaandtraditionalmultimonitorX11?
2. Whichcommandwouldyougiveinresponsetotheboot:prompttobeginanFTP
installation?
3. DescribetheAnacondainstaller.
4. Whereonthediskshouldyouputyour/bootpartitionortheroot(/)partitionif
youdonotusea/bootpartition?
5. Ifthegraphicalinstallerdoesnotwork,whatthreethingsshouldyoutry?
6. Whenshouldyouspecifyanext2filesysteminsteadofext3?
7. DescribeDiskDruid.
8. WhendoesaRedHatLinuxsystemstartXbydefault?
AdvancedExercises
9. Ifyoudonotinstallgrubonthemasterbootrecordoftheharddisk,howcanyou
bootLinux?
10. Whywouldyouplace/varatthestartofthedisk?
11.
Assumeyouhaveconfiguredfourscreens,screen0throughscreen3.Howwould
youinstructX.orgthatyourscreenlayoutwasaTshapewiththefirstscreenat
thebottomandtheotherthreescreensinarowaboveit?
4.IntroductiontoRedHatLinux
INTHISCHAPTER
CurbingYourPower:Superuser/rootAccess 82
ATouroftheRedHatLinuxDesktop 82
UsingKonquerortoManageFiles,RunPrograms,andBrowse
theWeb
94
CustomizingYourDesktopwiththeKDEControlCenter 97
CustomizingtheMainPanelUsingthePanelMenu 100
GettingtheFacts:WheretoFindDocumentation 102
HOWTOs:FindingOutHowThingsWork 109
MoreAboutLoggingIn 111
WhattoDoifYouCannotLogIn 112
Onewayoranotheryouaresittinginfrontofacomputerthat
isrunningRedHatLinux.Thischaptertakesyouonatourof
thesystemtogiveyousomeideasaboutwhatyoucandowith
it.Thetourdoesnotgointodepthaboutchoices,options,
menus,andsoon;thatisleftforyoutoexperimentwithandto
exploreingreaterdetailinlaterchapters.Instead,thischapter
presentsacook'stouroftheLinuxkitchen;asyoureadit,you
willhaveachancetosamplethedishesthatyouwillenjoy
morefullyasyoureadtherestofthebook.
FollowingthetouraresectionsthatdescribewheretofindLinux
documentation(page102)andoffermoreaboutlogginginon
thesystem,includinginformationaboutpasswords(page111).
Thechapterconcludeswithamoreadvanced,optionalsection
aboutworkingwithwindows(page119).
Inthenextsection,besuretoreadthewarningaboutthe
dangersofmisusingthepowersofSuperuser.Heedthat
warning,butfeelfreetoexperimentwiththesystem:Give
commands,createfiles,clickicons,chooseitemsfrommenus,
followtheexamplesinthisbook,andhavefun.
CurbingYourPower:Superuser/rootAccess
Whileyouareloggedinastheusernamedroot,youare
referredtoasSuperuseroradministratorandhave
extraordinaryprivileges.Youcanreadfromorwritetoanyfile
onthesystem,executeprogramsthatordinaryuserscannot,
andmore.Onamultiusersystemyoumaynotbepermittedto
knowtherootpassword,butsomeoneusuallythesystem
administratorknowstherootpasswordandmaintainsthe
system.WhenyouarerunningLinuxonyourowncomputer,
youwillassignapasswordtorootwhenyouinstallLinux.Refer
to"SystemAdministratorandSuperuser"onpage391formore
information.
Caution:DonotexperimentasSuperuser
Feelfreetoexperimentwhenyouareloggedinasa
nonprivilegeduser,suchaswhenyouloginas
yourself.Whenyouloginasroot(Superuser)or
wheneveryougivetheSuperuser/rootpassword,
however,doonlywhatyouhavetodoandmake
sureyouknowexactlywhatyouaredoing.Afteryou
havecompletedthetaskathand,reverttoworking
asyourself.WhenworkingasSuperuser/root,you
candamagetheLinuxsystemtosuchanextentthat
youwillneedtoreinstallRedHatLinuxtogetit
workingagain.
"SystemAdministration"onpage99describestasks
youmaywanttoperformworkingasroot.
ATouroftheRedHatLinuxDesktop
GNOME(www.gnome.org),aproductoftheGNUproject(page
4),istheuser-friendlydefaultdesktopmanagerunderRedHat
Linux.KDE(www.kde.org),theKDesktopEnvironment,isa
powerfuldesktopmanagerandcompletesetoftoolsyoucan
useinplaceofGNOME.ThistourfocusesonKDE.Thisfull-
featured,maturedesktopenvironmentboastsarichassortment
ofconfigurabletoolsandfeatures.Afteryoulogin,thissection
discussesseveralimportantfeaturesofthedesktop,including
theMainpanelandtheMainmenu,andexploreshowtouse
someoftheuniquefeaturesofwindowsunderKDE.Alongthe
way,youwillseehowtorollupawindowsoonlyitstitlebar
remainsonthedesktop,howtomoveeasilyfromonedesktop
orwindowtoanother,andhowtoconfigurethedesktopto
pleaseyoursenses.Asthetourcontinues,youwilllearnto
workwithfilesandbrowsetheWebusingKonqueror,oneofthe
primaryKDEtools.ThetourconcludeswithcoverageoftheKDE
ControlCenter,thekeytocustomizingyourdesktop,anda
discussionofhowtousethePanelmenutomodifythepanel(at
thebottomofthescreen)tobestsuityourneeds.
AsRedHatLinuxisinstalled,whenyoulogin,youuseGNOME.
BecausetheexamplesinthissectionarebasedonKDE,you
musttellthesystemthatyouwanttorunKDEbeforeyoulog
in.ThefollowingsectionexplainshowtologintoaKDE
desktopenvironment.
Startingwith"GettingtheFacts:WheretoFindDocumentation"
onpage102,thechaptercoversbothKDEandGNOME.
LoggingInontheSystem
Typically,whenyoubootaRedHatLinuxsystem,itdisplaysa
Loginscreenonthesystemconsole.Thisscreenhasatextbox
labeledUsernamewithfourword/iconbuttonsbelowit.These
buttonsallowyoutoworkinadifferentlanguage(Language),
specifyadesktopmanager(Session),rebootthesystem
(Restart),andturnthesystemoff(ShutDown).Formore
informationreferto"TheLoginScreen"onpage111.Click
SessionandthesystemdisplaystheSessionsdialogbox,
whichallowsyoutochoosewhetheryouwanttorunGNOMEor
KDE,ormakeanotherchoice.Tofollowtheexamplesinthis
section,clicktheradiobuttonnexttoKDEandthenclick
ChangeSessiontoclosethedialogbox.IftheKDEradio
buttonisnotvisible,KDEisprobablynotinstalled;refertothe
"IfKDEisnotinstalled"tiponpage84.
EnteryourusernameinthetextboxlabeledUsernameand
pressRETURN.ThelabelchangestoPassword.Enteryour
passwordandpressRETURN.Ifyougetanerrormessage,try
enteringyourusernameandpasswordagain.Makesurethe
CAPSLOCKkeyisnoton;yourentriesarecasesensitive.See
page112forhelpwithproblemslogginginandpage114ifyou
wanttochangeyourpassword.
RHEL
ThechangeyoumakeintheSessionsdialogboxaffectsonly
thecurrentsession.Thenexttimeyoulogin,youreverttoyour
defaultdesktopenvironment(KDEorGNOME).Useswitchdesk
(page116)tochangeyourdefaultdesktopenvironment.
FEDORA
Oncethesystemhasdeterminedthatyouareallowedtologin,
itdisplaysadialogboxthatasks,DoyouwanttomakeKDE
thedefaultforfuturesessions?Itdisplaysthisdialogbox
becauseyouelectedtochangeyoursessiontoKDEbeforeyou
loggedin.Thedialogboxhasthreebuttonsthatallowyouto
makethechangeeffectiveJustForThisSession(untilyoulog
off),Cancelthechange,orMakeDefault(makethenew
desktopmanageryourdefaultdesktopmanager).Toworkwith
theexamplesinthischapter,chooseMakeDefault.
Thesystemtakesafewmomentstosetthingsupandthen
displaysaworkspacewithapanelalongthebottomandsome
iconsattheupperleft(Figure4-1).
Figure4-1.TheinitialKDEscreen(FEDORA)
[Viewfullsizeimage]
Tip:IfKDEisnotinstalled
TheKDEdesktopenvironmentshouldbeinstalledon
thesystemtofollowtheexamplesinthischapter.
YoucanusetheGNOMEdesktopenvironment,but
someoftheexampleswillnotworkthesameway.
ToinstallKDE,loginonthesystemasdescribed
earlier,omittingthestepthathasyouclickSession
(donotclicktheKDEradiobutton).
Thisprocedureworksonlyifthesystemisconnected
totheInternet.WithoutanInternetconnection,itis
easiesttoreinstallRedHatLinuxwithKDE.
RHELUseup2date(page494)todownloadandinstall
thefollowingpackages:kdeaddons,kdeadmin,
kdeartwork,kdebase,kdegraphics,kdelibs,
kdemultimedia,kdenetwork,kdepim,kdeutils.
NowyoucanlogintotheKDEenvironmentas
describedin"LoggingInontheSystem"onpage83.
FEDORAOnceyouareloggedinunderGNOME,click
Applicationsattheleftendofthepanelatthetop
ofthescreen.GNOMEdisplaysadrop-downmenu.
Slidethemousepointeruntilitisover
Add/RemoveSoftwareatthebottomofthe
submenuandthenclick.Supplytherootpassword
whenthesystemasksforit.Afterapause,the
systemdisplaysthepirutPackageManagerwindow
(Figure4-2).
Figure4-2.ThepirutPackageManager
window
[Viewfullsizeimage]
ClickDesktopEnvironmentsintheleftframeand
pirutdisplaysGNOMEDesktopEnvironment,KDE(K
DesktopEnvironment),andXFCEintherightframe.
ClickthesmallboxnexttoKDEsothatacheckmark
appears.ClickApplyatthebottomrightofthe
screenandpirutdisplaysthePackageSelections
windowthatasksyoutoconfirmwhichpackagesyou
wanttoinstall.ClickContinueandpirutdisplays
variouswindowsasitresolvesdependencies(checks
whetherthesystemneedsanyothersoftwareto
supportthepackagesyouareinstalling),downloads
theKDEpackagesfromtheInternet,andinstalls
them.Whenitisfinisheditdisplaysadialogwindow
thatsaysSoftwareinstallationsuccessfully
completed.ClickOKandyouarefinishedinstalling
KDE.ClickSystemfromthepanelatthetopofthe
screen,selectLogOutfromthedrop-downmenu,
andclickLogoutfromthewindowthatGNOME
displays.NowyoucanlogintotheKDEdesktop
environmentasdescribedin"LoggingInonthe
System"onpage83.
Seepage483formoreinformationonpirut.
Tip:Clickandright-click
Thisbookusesthetermclickwhenyouneedto
clicktheleftmousebuttonandright-clickwhen
youneedtoclicktherightmousebutton.Seepage
98toadaptthemouseforleft-handeduse.
GettingtheMostfromtheDesktop
Whenyouareworkinginacomplexenvironmentandusing
manywindowstorunavarietyofprogramssimultaneously,itis
convenienttodividethedesktopintoseveralareas,each
appearingasadesktopuntoitselfandoccupyingtheentire
screen.Theseareasarevirtualdesktops.Theworkspace
compriseswhatisonthescreen:buttons/icons,
toolbars/panels,windows,andtherootwindow(theunoccupied
areaoftheworkspace).TypicallyGNOMEandKDEaresetup
withadesktopthatincludesfourworkspaces.
Desktoptheme
InaGUI,athemeisarecurringpatternandoveralllookthat
(ideally)pleasestheeyeandiseasytointerpretanduse.To
viewawidevarietyofthemes,gotothemes.freshmeat.net,
www.kde-look.org,orart.gnome.org.Usingthemes,youcan
controltheappearanceofKDE,GNOME,andmostother
desktopenvironments.
Tip:Isitadesktop,aworkspace,or
what?
Confusionreignsovernamingthesubcomponents,
ordivisions,ofadesktop.Thisbook,inconformance
withGNOMEdocumentation,referstoeverything
thatusuallyoccupiesthedisplaymonitor,orscreen,
asaworkspace;desktopreferstothesumofthe
workspaces.Putanotherway,thedesktopisdivided
intoworkspaces.
KDEdocumentationandwindowsusetheterm
desktopinsteadofworkspace.
ThePoweroftheDesktop:UsingtheMainPanel
Whenyoulogin,KDEdisplaysaworkspacethatincludesthe
KDEMainpanel,whichisessentialtogettingyourworkdone
easilyandefficiently.TheMainpanelisthestripwithiconsthat
actasbuttons(Figure4-3)alongthebottomoftheworkspace.
Apaneldoesnotallowyoutodoanythingyoucouldnotdo
otherwise;ratheritsimplycollectsthingsinoneplaceand
makesyourworkwiththesystemeasier.BecausetheMain
paneliseasytoconfigure,youcansetituptoholdthetools
youusefrequently,arrangedthewayyouwant:application
launcherstostart,forexample,emailandwordprocessing
programs,menus(includingtheMainmenu,representedbythe
redhatorFedoralogo),applets(applicationsthataresmall
enoughtobeexecutedwithinapanel),andspecialobjects
(suchasaLogoutbutton).Youcancreateadditionalpanels,
calledextensionsorextensionpanels,toholddifferentgroups
oftools.
Figure4-3.TheKDEMainpanel
[Viewfullsizeimage]
Tooltips
Tooltips(Figure4-4),availableunderbothGNOMEandKDE,is
aminicontexthelpsystemthatyouactivatebymovingthe
mousepointeroverabutton,icon,windowborder,orapplet
(suchasthoseonapanel)andleavingitthereforamoment
(calledhovering).Whenthemousepointerhoversoveran
object,GNOMEandKDEdisplayabriefexplanationofthe
object.
Figure4-4.TheFirefoxtooltip
Icons/buttons
Theicons/buttonsonthepaneldisplaymenus,launch
programs,andpresentinformation.TheWebbrowserbutton
(themousewithitscordwrappedaroundtheworld)starts
Firefoxbydefault.Theemailbutton(thestampandletter)
startsEvolution,anemailandcalendaringapplication
(www.gnome.org/projects/evolution).Youcanstartalmostany
utilityorprogramonthesystemusingabuttononapanel.
PanelIconmenu
EachicononapanelhasaPanelIconmenu,whichallowsyou
tomovetheiconwithinthepanel,viewandchange(configure)
theicon'sproperties,andremovetheiconfromthepanel.It
alsocontainsthePanelmenu(page100)asasubmenu.Some
iconshaveadditionalcontext-basedselectionswhereassome
appletshaveadifferentmenu.Right-clickanicononthepanel
todisplayitsPanelIconmenu.
Pager
EachrectangleinthePager,thegroupofrectangleslabeled14
onthepanel,representsaworkspace(Figure4-5).Clicka
rectangletodisplaythecorrespondingworkspace.Forexample,
clicktherectanglelabeled2.Thisrectanglebecomeslighterto
indicatethatyouareviewingworkspace2.Whileyouare
workingwithworkspace2,clicktheFirefoxicononthepanel.
KDEopenstheFirefoxwindowandasmallwindowwiththe
Firefoxlogoinitappearsinrectanglenumber2inthePager.
Figure4-5.ThePager(left)andtheTaskbar
(right)
Nowclicktherectanglelabeled3andopentheOpenOffice.org
WriterbyclickingtheMainmenuicon(theredhatorFedora
logo),clickingOfficefromthepop-upmenu,andthenclicking
WordProcessorfromthesubmenu.WithWriterinworkspace
3andFirefoxinworkspace2,youcanclicktherectanglesinthe
Pagertoswitchbackandforthbetweentheworkspaces.
GNOMEcallsthistooltheWorkspaceSwitcher.
Taskbar
TotherightofthePageristheTaskbar,agroupofskinny,
horizontalrectangleswithaniconandthenameofaprogramin
eachone.YoucanusetheTaskbartodisplayaspecificwindow
regardlessofwhichworkspaceitappearsin.Clickoneofthe
rectanglesandthecorrespondingprogram/windowappearson
thescreen;KDEswitchestoadifferentworkspaceifnecessary.
Ifthewindowrunningtheprogramyouclickedonisnotvisible
becauseitisburiedunderotherwindows,youcanclicka
rectangleontheTaskbartopopthewindowtothetopofthe
stackofwindows.GNOMEcallsthistooltheWindowList.Ifyou
havealotofapplicationsrunningonvariousworkspaces,you
canconfiguretheTaskbartoshowonlythoseapplicationson
thecurrentworkspace.See"Configuringthepanel"onpage
101formoreinformationonconfiguringtheTaskbar.
LaunchingApplicationsfromtheMainMenu
TheredhatorFedoraiconattheleftendoftheKDEMainpanel
hasafunctionsimilartothatoftheStartbuttononaWindows
system;clickittodisplaytheMainmenu.FromtheMainmenu
anditssubmenus,youcanlaunchmanyoftheapplicationson
thesystem.ThismenudiffersunderGNOMEandKDE.
KNotes
YoucanusetheMainmenutolaunchKNotes,areminder
systemthatdisplayswindowsthatlooklikePost-itnotes.After
youdisplaytheMainmenu,slidethemousepointeroverthe
MainmenuuntilitisoverUtilities.Thesystemdisplaysthe
Utilitiessubmenu.IfyouclickUtilities,KDEfreezestheUtilities
submenu.WithorwithoutclickingUtilities,movethemouse
pointeruntilitisoverDesktopandKDEdisplaysanother
submenu.NowslidethemousepointeruntilitisoverKNotes
andclicktodisplayasmall,yellowwindowthatyoucantypein
(Figure4-6).
Figure4-6.KNotes
[Viewfullsizeimage]
Youcanusethesewindowstoleaveyourselfreminders.
AlthoughKNotesmayseemtrivial,itoffersmanythingsto
experimentwith.Clickanddragthetitlebaratthetopofa
KNotetomoveit.Right-clickthetitlebartodisplaytheKNotes
menu.WhenyoustartKNotes,itputsanicontowardtheright
endofthepanel.Right-clickthisiconandseewhathappens.
Copyiconstoapanel
TocopyaselectionfromtheMainmenutoapanel,left-dragthe
itemfromtheMainmenutoapanel.Toremoveaniconfroma
panel,right-clicktheiconandchooseRemovefromthepop-up
menu.
Loggingout
AtthebottomoftheMainmenuisLogOut.Clickthisselection
todimtheworkspaceanddisplayawindowwithfourbuttons:
EndCurrentSession(logout),TurnOffComputer,Restart
Computer,andCancel(donotlogout).Logoutorcontinue
experimentingasyouplease.
Feelfreetoexperiment
TryselectingdifferentitemsfromtheMainmenuandseewhat
youdiscover.Manyofthesubmenusprovidesubmenuswith
evenmoreselections(suchasKNotes).Followingaresome
applicationsyoumaywanttoexplore:
OpenOffice.org'sWriterisafull-featuredwordprocessor
thatcanimportandexportWorddocuments.FromtheMain
menu,selectOffice WordProcessor(RHELusesOffice
OpenOffice.orgWriter[onlywiththeopenoffice.org
packageinstalled]).
Firefoxisapowerful,full-featuredWebbrowser.Clickthe
paneliconoftheworldwithamousewrappedarounditto
startFirefox.YoucanalsoselectMainmenu:Internet
FirefoxWebBrowser.
ThegaimInstantMessenger(IM)clientallowsyoutochaton
theInternetwithpeoplewhoareusingIMclientssuchas
AOL,MSN,andYahoo!Tostartgaim,selectMainmenu:
Internet InstantMessenger.
Thefirsttimeyoustartgaim,itopenstheAccountswindow
andtheAddAccountwindowautomatically.IntheAdd
Accountwindow,putcheckmarksintheboxesnextto
RememberpasswordandAuto-loginifyouwantgaimto
logyouinautomaticallywhenyoustartit.ClickSave.In
themaingaimwindow,enteryourIMpasswordifnecessary
andclickSignon.Gotogaim.sourceforge.netformore
information,includinggaimdocumentationandpluginsthat
addfeaturestogaim.
ControllingWindows
Onthescreen,awindowisaregionthatruns,oriscontrolled
by,aparticularprogram(Figure4-7).Becauseyoucancontrol
thelookandfeelofwindows,eventhebuttonstheydisplay,
yourwindowsmaynotlookliketheonesshowninthisbook.
(SelectMainmenu:Settings DesktopSettingsWizardto
customizewindowsinyouraccount[FEDORAonly].Youcan
furthercustomizewindowsbyselectingMainmenu:Control
CenterandthenclickingeitherAppearancesandThemes
andselectingoneofthesubtabsorbyclickingDesktopand
selectingWindowBehavior.)
Figure4-7.Atypicalwindow
[Viewfullsizeimage]
Resizingawindow
Toresizeawindow,movethemousepointeroveranedgeof
thewindow;thepointerturnsintoadoublearrow.Clickand
dragthesideofthewindowasyoudesire.Whenyouposition
themousepointeroveracornerofthewindowanddrag,you
canresizetheheightandwidthofthewindowatthesame
time.
Titlebar
Atitlebar(Figures4-7and4-8)appearsatthetopofmost
windowsandinmanywayscontrolsthewindowitisattached
to.Youcanchangetheappearanceandfunctionofatitlebar,
butitwillusuallyhaveatleastthefunctionalityofthebuttons
showninFigure4-8.
Figure4-8.Atitlebar
Theminimizebuttoncollapsesthewindowtoitsrectangleinthe
Taskbaronthepanel;clicktherectangleontheTaskbarto
restorethewindow.Clickingthemaximizebuttonexpandsthe
windowsoitoccupiesthewholeworkspace;clickthesame
buttononthetitlebarofamaximizedwindow(thebuttonhasa
double-windowicon)torestorethewindowtoitsformersize.
Clickingthemaximizebuttonwiththemiddleorrightmouse
buttonexpandsthewindowverticallyorhorizontally.Usethe
sameoradifferentmousebuttontoclickthemaximizebutton
againandseewhathappens.Clickingtheclosebuttoncloses
thewindowandterminatestheprogramthatwasrunninginit.
Left-clickthetitlebaranddragthewindowtorepositionit.
WindowOperationsmenu
TheWindowOperationsmenu(Figure4-8)containsmostofthe
commonoperationsthatyouneedtoperformonanywindow.
ClicktheWindowOperationsmenubuttonorright-clickthe
titlebartodisplaythismenu.
Toolbar
Atoolbar(Figure4-7)usuallyappearsatthetopofawindow
andcontainsicons,text,applets,menus,andmore.Manykinds
oftoolbarsexist.Thetitlebarisnotatoolbar;itispartofthe
windowdecorationplacedtherebythewindowmanager(page
121).
Contextmenu
Acontextmenuisamenuthatappliesspecificallytothe
windowyouclick.Frequentlyaright-clickbringsupacontext
menu.Tryright-clickingontheiconsonthedesktop.Depending
onwhattheiconrepresents,yougetadifferentmenu.For
example,thecontext(icon)menuisdifferentfortheTrash,
CD/DVD,andfoldericons.Tryright-clickingwiththemouse
pointerindifferentplaces;youwillfindsomeinteresting
menus.
ChangingtheInputFocus(WindowCycling)
Thewindowwiththeinputfocusistheonethatreceives
keyboardcharactersandcommandsyoutype.Inadditionto
usingtheTaskbar(page86),youcanchangewhichwindowon
thecurrentworkspacehastheinputfocusbyusingthe
keyboard;thisprocessiscalledwindowcycling.Whenyou
pressALT-TAB,theinputfocusshiftstothewindowthatwas
activejustbeforethecurrentlyactivewindow,makingiteasyto
switchbackandforthbetweentwowindows.Whenyouhold
ALTandpressTABmultipletimes,thefocusmovesfrom
windowtowindow,andKDEdisplaysinthecenterofthe
workspaceaboxthatholdsthetitlebarinformationfromthe
windowthatcurrentlyhastheinputfocus.UnderKDE,youcan
holdALTandSHIFTandrepeatedlypressTABtocycleinthe
otherdirection.
ShadingaWindow
Whenyoudouble-clickaKDEtitlebar(Figure4-8),thewindow
rollsuplikeawindowshade,leavingonlythetitlebarvisible.
Double-clickthetitlebaragaintorestorethewindow.Ifthe
windowdoesnotrollup,trydouble-clickingmorequickly.
CuttingandPastingObjectsUsingtheClipboard
Therearetwosimilarwaystocut/copyandpasteobjects(e.g.,
iconsandwindows)andtextonthedesktop.Youcanusethe
clipboard,technicallycalledthecopybuffer,tocopyormove
objectsortext:Youexplicitlycopyanobjectortexttothe
bufferandthenpasteitsomewhereelse.Applicationsthat
followtheuserinterfaceguidelinesuseCONTROL-Xtocut,
CONTROL-Ctocopy,andCONTROL-Vtopaste.
Youmaybelessfamiliarwiththeselectionorprimarybuffer,
whichalwayscontainsthetextyoumostrecentlyselected
(highlighted).Youcannotusethismethodtocopyobjects.
Clickingthemiddlemousebutton(clickthescrollwheelona
mousethathasone)pastesthecontentsoftheselectionbuffer
atthelocationofthemousepointer(ifyouareusingatwo-
buttonmouse,clickbothbuttonsatthesametimetosimulate
clickingthemiddlebutton).
Withbothofthesetechniques,youstartbyhighlightingthe
objectsortextyouwanttoselect.Youcandragaboxaround
objectstoselectthemordragthemousepointerovertextto
selectit.Double-clicktoselectawordortriple-clicktoselecta
line.
Next,tousetheclipboard,explicitlycopy(CONTROL-C)orcut
(CONTROL-X)theobjectsortext.[1]Ifyouwanttousethe
selectionbuffer,skipthisstep.
[1]Thesecontrolcharactersdonotworkinaterminalemulatorwindowbecausetheshell
runninginthewindowinterceptsthembeforetheterminalemulatorcanreceivethem.
Youmusteitherusetheselectionbufferinthisenvironmentorusecopy/pastefromthe
Editselectiononthemenubarorfromthecontextmenu(right-click).
Topastetheselectedobjectsortext,eitherpositionthemouse
pointerwhereyouwanttoputthem(it)andpressCONTROL-V
(clipboardmethod)orpressthemiddlemousebutton(selection
buffermethod).
Usingtheclipboard,youcangiveasmanycommandsasyou
likebetweentheCONTROL-CorCONTROL-XandCONTROL-V,as
longasyoudonotuseanotherCONTROL-CorCONTROL-X.
Usingtheselectionbuffer,youcangiveothercommandsafter
selectingtextandbeforepastingit,aslongasyoudonotselect
(highlight)othertext.
Youcanuseklipper,theKDEclipboardutility,topastepreviously
selectedobjects.Seepage262forinformationonklipper.
ControllingtheDesktopUsingtheRootWindow
Therootwindowisanypartoftheworkspacethatisnot
occupiedbyawindow,panel,icon,orotherobject.Itisthepart
oftheworkspacewhereyoucanseethebackground.
Desktopicons
Iconsontherootwindowrespondappropriatelytoadouble-
click:Aprogramstartsrunning,adatafile(suchasaletter,
calendar,orURL)runstheprogramthatcreatedit(withthe
datafileloadedor,inthecaseofaURL,withthebrowser
displayingtheappropriateWebpage),andadirectorybringsup
theKonquerorfilemanager(page94).WithinKonqueror,you
canmove,copy,orlinkafileordirectorybydraggingand
droppingitandselectingMove/Copy/Linkfromtheresulting
pop-upmenu;youcanrunoreditafilebydouble-clickingit.
Iconcontextmenus
DisplayanIconcontextmenubyright-clickinganiconthatis
notonapanel.TheIconcontextmenuistheonlywayto
performsomeoperationswithiconsontherootwindow.Figure
4-9showstheIconcontextmenufortheTrashicon.
Figure4-9.TheIconcontextmenufortheTrash
icon
Desktopmenu
DisplaytheDesktopmenubyright-clickingtherootwindow.
Youcanopenawindoworperformanothertaskbymakinga
selectionfromtheDesktopmenu.BothKDEandGNOMEhave
Desktopmenus,althougheachpresentsadifferentsetof
choices.
ConfigureDesktop
TheConfigureDesktopselectionontheDesktopmenuopens
theConfigurewindow(Figure4-10),whichpresentsmany
choicesforyoutoexperimentwith.Eachiconinthevertical
panelontheleftofthiswindowdisplaysadifferentsetof
choices.Somechoices,suchasBehavior,displaymultipletabs
ontheright,witheachtabdisplayingadifferentsetofchoices.
Figure4-10.TheConfigurewindow,Background
selection
[Viewfullsizeimage]
Desktopbackground
ClickBackgroundontheleftpaneloftheConfigurewindowto
changethedesktopbackgroundsettings(Figure4-10).Near
thetopoftherightsideofthiswindowisacomboboxlabeled
Settingfordesktop.InitiallytheboxsaysAllDesktops,
meaningthatwhateverchangesyoumaketothedesktopusing
therestofthiswindowapplytoall(four)workspaces.ClickAll
Desktopsandchooseasingledesktopfromthedrop-down
menutohavethesettingsapplyonlytoasingleworkspace.
Usingthistechniqueyoucanmakeeachofyourworkspaces
lookdifferent.
ClicktheradiobuttonnexttoPictureandchooseafilethat
containsanimagetouseaswallpaperfromthecomboboxto
therightofthisbutton.Alternatively,youcanclickNopicture
andchooseapatternandcolor(s)forthedesktopbackground.
ChooseapatternfromthecomboboxadjacenttoColorsand
clickoneofthetwocolorbarsunderthecombobox.KDE
displaystheSelectColorwindow.Thiswindowpresentsseveral
waysofselectingacolor.Clickthepaletteicon,movethe
resultingcrosshairscursoroveracoloryoulikeanywhereon
thescreen,andthenclickagaintoselectthecolor.ClickOK.
Referto"kcolorchooser:SelectsaColor"onpage260formore
informationontheSelectColorwindow.
ExperimentwiththechoicesintheBackgroundandOptions
framestocreateadesktopbackgroundthatpleasesyou.Click
theGetNewWallpapersbuttonunderthepictureofa
monitortochooseanddownloadnewbackgroundsthatyoucan
selectinthePicturecombobox.SelectPicture,choose
default,andthenclickApplytoreturnthebackgroundtoits
initialstate.
GNOMEandKDE
TheConfigurewindowpresentsnumerouschoicesforhowyou
cansetuptheappearanceandfunctionalityofthedesktop.This
abundanceofchoicesdemonstratesamajordifferencebetween
KDEandGNOME,thetwomajorLinuxdesktopmanagers.While
GNOMEhasmovedtowardsimplesophistication,givingtheuser
astandardinterfacewithfewerchoices,KDEhasemphasized
configurability.IfyoutrytoconfiguretheGNOMEdesktop
manager,youwillhavefewerchoicesbuteachchoiceiswell
thoughtoutandpowerful.Someuserspreferoneapproach;
othersprefertheother.
RunningCommandsfromtheTerminalEmulator/Shell
Aterminalemulatorisawindowthatfunctionsasatextual
(character-based)terminalandisdisplayedinagraphical
environment(Figure4-11).Toopenaterminalemulator
windowunderKDE,right-clicktherootwindow(thedesktop)to
displaytheDesktopmenuandselectKonsole(RHELusesMain
menu:SystemTools Terminal).UnderGNOME,select
Applications:Accessories Terminal(RHELuses
Applications:SystemTools Terminal).Becauseyouare
alreadyloggedinandarecreatingasubshellinadesktop
environment,youdonotneedtologinagain.Onceyouhave
openedaterminal,trygivingthecommandmanmantoread
aboutthemanutility(page104),whichdisplaysLinuxmanual
pages.Chapter5describesutilitiesthatyoucanrunfroma
terminalemulator.
Figure4-11.Akonsoleterminalemulatorwindow
[Viewfullsizeimage]
Youcanruncharacter-basedprogramsthatwouldnormallyrun
onaterminalinaterminalemulatorwindow.Youcanalsostart
graphicalprograms,suchasxeyes,fromthiswindow.Agraphical
programopensitsownwindow.Whenyourunaprogramfrom
GNOMEorKDE,youmaybeaskedwhetheryouwanttorunthe
programinaterminal.Whenyouansweryes,theprogramruns
inaterminalemulatorwindow.
Whenyouaretypinginaterminalemulatorwindow,several
characters,including*,?,|,[,and],havespecialmeanings.
Avoidusingthesecharactersuntilyouhaveread"Special
Characters"onpage126.
Theshell
Onceyouopenaterminalemulatorwindow,youare
communicatingwiththecommandinterpreterknownasthe
shell.Theshellplaysanimportantpartinmuchofyour
communicationwithLinux.Whenyouenteracommandatthe
keyboardinresponsetotheshellpromptonthescreen,the
shellinterpretsthecommandandinitiatestheappropriate
actionforexample,executingaprogram;callingacompiler,a
Linuxutility,oranotherstandardprogram;ordisplayingan
errormessageindicatingthatyouenteredacommand
incorrectly.WhenyouareworkingonaGUI,youbypassthe
shellandexecuteaprogrambyclickinganiconorname.Refer
toChapter7formoreinformationontheshell.
SessionManagement
Asessionstartswhenyouloginandendswhenyoulogoutor
resetthesession.WithafullycompliantGNOMEorKDE
application,thesedesktopmanagerscansession-manageyour
data.Whenyourunamanagedsession,thedesktoplooks
muchthesamewhenyouloginasitdidwhenyouloggedout
theprevioustime.Thedatainthiscaseincludesnotonlythe
datathattheapplicationmanipulatesbutalsoinformationabout
thestateoftheapplicationwhenyouendyoursession:which
windowswereopenandwheretheywerelocated,whateachof
theapplicationswasdoing,andsoforth.
UsingKonquerortoManageFiles,Run
Programs,andBrowsetheWeb
Konqueroristhedesktoptoolyouwillprobablyusemostoften
(Figure4-12).ItissimilartobutmorepowerfulthanWindows
(Internet)Explorerandeasilymorphsintoafilemanager,
browser,andexecutorofmanyprograms,bothwithinand
outsidethebordersofitswindow.EventhoughKonqueroris
muchmorethanaWebbrowser,itsnameindicatesitsplacein
theevolutionofbrowsers:Navigator,Explorer,andnow
Konqueror,spelledwithaKbecauseitispartofKDE.[2]
[2]AppleusedKHTML,Konqueror'sHTMLrenderingengine,tocreateitsbrowserand
continuedthetradition,namingthebrowserSafari.
Figure4-12.KonquerortheWebbrowser
[Viewfullsizeimage]
Konquerorprovidesnetworktransparentaccess,whichmeans
thatitisaseasytoworkwithfilesonremotesystemsasitisto
workwithlocalfiles.WithKonqueror,youcancopyfilesfromor
toaremotesystem,usingthesametechniquesyouusefor
copyingfileslocally.
Becauseitopensanapplicationwithinitself,Konquerormakes
theprocessofclickingandviewingalmostanytypeoffile
transparent.ClickaPDF(Acrobat)fileiconwithinKonqueror,
anditopensthefilewithintheKonquerorwindow.
ThemostimportantfeatureoftheWebbrowser,thefile
manager,andtheotherfacesofKonqueroristhateachofthese
separatetoolsisseamlesslyintegratedintothesamewindow
andsharesthesameappearance,tools(suchasbookmarks),
menusystem,icons,andfunctionalcharacteristics.Asaresult,
youcanbrowsefromaWebsitetoanFTPsite,copyafilefrom
theFTPsitetothelocalfilesystemordesktopasthoughyou
werecopyingitlocally,andrun,edit,ordisplaythefilewithin
Konquerororinanotherwindow.
Gettingstarted
YoucanbringupKonquerorasabrowserorafilemanager,and
youcanswitchfromonetotheotherwhileyouareworking
withit.Double-clicktheHomeorTrashiconontheworkspace
toopenKonquerorthefilemanager.OnceKonquerorisopen,
enteraURL,suchasfedora.redhat.com,inthelocationbar
andpressRETURNtoswitchKonquerortobrowsermode.You
cantoggletheNavigationpanel(thenarrowsubwindowonthe
left;seeFigure4-14onpage97)onandoffbypressingF9or
selectingKonquerormenubar:Window Show/Hide
NavigationPanel.
Becauseyoucanchangetheappearanceandfunctionalityof
Konqueror,whatyoursystemdisplaysmaynotmatchwhatis
shownanddescribedinthisbook.
Konquerorworkswithmanydifferentkindsoftargets:plain
files(includingexecutable,sound,andgraphical,among
others),directoryfiles,andURLs,includingHTTPandFTP
addresses.Youselectthetargetbyclickingthetarget'sicon
withinKonquerororbyenteringitspathnameoraddressinthe
locationbar.Konqueror'sreactionreflectsthekindoftargetyou
select:
Plainfile(localorremote):Ifthefileisexecutable,runs
thefile(see"MIME/executingfiles,"onthenextpage).Ifit
isnotexecutable,triestofindtheappropriateutilityor
applicationtoopenthefile.
Directoryfile:Displaysthecontentsofthedirectoryina
KonquerorFileManagerview.
HTTPaddress:OpenstheURLintheHTML(Web)viewer,
whichhasbeenloadedandembeddedwithintheKonqueror
window.
FTPaddress:TreatsafileobtainedbyFTPjustasitwould
treatalocalplainordirectoryfile.
MIME/executingfiles
MIME(MultipurposeInternetMailExtension)typeswere
originallyusedtodescribehowspecifictypesoffilesthatwere
attachedtoemailweretobehandled.TodayMIMEtypes
describehowmanytypesoffilesaretobehandled,basedon
theircontentsorfilenameextensions.BothGNOMEandKDE
useMIMEtypestofigureoutwhichprogramtousetoopena
file.AnexampleofaMIMEtypeisimage/jpeg:TheMIME
groupisimageandtheMIMEsubtypeisjpeg.ThisMIMEtype
isassociatedwiththekuickshowKDEimagedisplayutility.(Many
MIMEgroupsexist,includingapplication,audio,image,inode,
message,text,andvideo.)
Whenyouclickafilewhosenameissam.jpg,KDEexamines
thefile'smagicnumber(page1042)todetermineitsMIME
type.Ifthattechniquefails,KDElooksatthefile'sfilename
extensioninthiscase,jpg.WhenKDEdeterminesthefile's
MIMEtypeisimage/jpeg,itcallskuickshowtoopenthefile.
Optional
FromtheMainmenu,selectControlCenter.WhentheKDEControlCenter
windowopens,clickKDEComponentsandthenFleAssociationstodisplaya
completelistoftheMIMEtypesthatKDEcanworkwith.Becarefulwhenmaking
changesinthiswindowaschangesherecanaffecthowKonquerorandother
programsworkwithfiles.
Runningaprogram
IntheKonquerorlocationbar,enter/usr/bin/xclock,the
pathnameofanexecutablefilethatrunsagraphicalprogram.
PressRETURN.Aftercheckingthatyoureallywanttorunit,
Konquerorrunsxclock.
Whenyouwanttorunatextualprogram,selectMainmenu:
RunCommandorpressALT-F2toopentheRunCommand
window.ThiswindowispartofKDE,notKonqueror.After
enteringthenameoftheprogramyouwanttorun,click
OptionsandputacheckmarkintheboxadjacenttoRunin
terminalwindow.Formoreinformationreferto"Run
Command"onpage261.
Views
ThetermviewdescribesasubwindowwithintheKonqueror
window(Figure4-13).ChooseKonquerormenubar:Window
toaddandremoveviewsintheKonquerorwindow.Thechoices
inthismenualwaysworkintheactiveview,theonewitha
greendotatthelower-leftcorner(ortheonlyview).Formore
informationreferto"MoreAboutViews"onpage256.
Figure4-13.Konquerordisplayingbrowserand
FileManagerviews
[Viewfullsizeimage]
Toolbar
TheKonquerortoolbar(thebarwiththeiconsinFigure4-13)is
straightforward.Arightarrowattherightendofthetoolbar
indicatesthatnotalltheiconsfitinthewidthofthewindow.
Clickthearrowtodisplay(andchoosefrom)theremaining
icons.
FileManager
TheKonquerorFileManagerviewallowsyoutoworkwiththe
filesystemgraphically(Figure4-14).PressF9todisplaythe
Navigationpanel,whichhelpsyounavigatethefilesystem.Try
clickingeithertherootorhomefoldericonintheverticalstack
oficonsattheleftoftheNavigationpanel.Thenclicka
directoryintheNavigationpaneltodisplayitscontentsinthe
Directorywindow.Double-clickafileintheDirectorywindowto
executeit,displayitscontents,andsoon,dependingonthe
contentsofthefile.
Figure4-14.TheKonquerorfilemanager
displayingicons
[Viewfullsizeimage]
CustomizingYourDesktopwiththeKDEControl
Center
TheKDEControlCenterandtheGNOMEDesktopPreferences
windowpresentinformationonandallowyoutocontrolmany
aspectsofthedesktopenvironment.Eachtoolworksdifferently.
ThissectiondiscussestheKDEControlCenter.Thegnome-control-
centerutilitydisplaystheGNOMEDesktopPreferenceswindow.
DisplaytheKDEControlCenter(Figure4-15)bychoosingMain
menu:ControlCenter.
Figure4-15.TheKDEControlCenter
[Viewfullsizeimage]
ThecolumnattheleftsideoftheKDEControlCenterwindow
displaysalistofcategoriessuchasAppearance&Themesand
PowerControl.Youmayhavetoclicktheclearbutton(the
broomanddustpan)atthetopleftofthecolumntodisplaythis
list.Clickonacategorytoexpanditanddisplaythetopics
withinthatcategory;clickonitagaintohidethetopics.
Whenyouclickatopic,theKDEControlCenterdisplays
informationaboutthetopicontherightsideofthewindow.
Frequentlytabsappearatthetopofthisinformation.Clickthe
tabs,makethechangesyouwant,andclickApplyatthelower-
rightcornerofthewindowtomakeyourchangestakeeffect.
Left-handedmouse
Forexample,youcanchangethesetupofthemousebuttonsso
itissuitableforaleft-handedpersonbyclickingtheplussignin
theboxnexttoPeripheralstoexpandthiscategoryandthen
clickingMouse(Figure4-16).Ontherightsideofthewindow,
clickthetabmarkedGeneral.UnderButtonOrder,clickthe
radiobuttonnexttoLefthanded.FinallyclicktheApply
buttonatthelower-rightcornerofthewindow.Nowthe
functionsoftherightandleftmousebuttonsarereversed.See
page239forinstructionsonhowtoperformthesamefunction
underGNOME.
Figure4-16.TheKDEControlCentermousetopic
[Viewfullsizeimage]
Ifyouchangethesetupofthemousebuttons,rememberto
reinterpretthedescriptionsinthisbookaccordingly.Whenthis
bookasksyoutoclicktheleftbuttonordoesnotspecifya
buttontoclick,usetherightbutton,andviceversa.
Help
SelectHelp What'sThisfromthemenubar;KDEaddsa
questionmarktothemousepointer.Ifyouclicktheitemyou
wantmoreinformationon,KDEwilldisplayabriefmessage
aboutthisitem.
Administratormode
Sometopics,suchasthoseintheSystemAdministration
category,controlsystemfunctionsandrequireAdministrator
mode(Superuser)accesstothesystemtomakechanges.
WhentheKDEControlCenterdisplaystheAdministrator
Modebuttonatthebottomofthewindowanditemsinthe
windowaregrayedout,clickthisbuttonandenterthe
Superuser(root)passwordtodisplayandworkwiththese
topics.
Followingarebriefdescriptionsofsomeofthecategoriesand
topicsintheKDEControlCenter.
Appearance&Themes
Controlshowinformationispresentedtotheuser,including
desktopelements(background,colors,fonts,andicons),the
screensaver,andwindowdecorations.
Desktop
Controlshowthedesktop,includingpanelsandwindows,
works.
Internet&Network
Controlsfilesharinganddesktopsharing.Thiscategory
includesasubcategoryforsettingupWebbrowsingwith
Konqueror(page95);thesubcategorycontrolstheuseof
cache,cookies,plugins,stylesheets,browseridentification,and
otherKonqueror-specificsettings.
KDEComponents
Configuresfileassociations(referto"MIME/executingfiles"on
page96),Konqueror'sFileManagermode(page97),KDE
sessions(page94),andKDEspellchecking.
Peripherals
Controlsthesystemmonitor(display),thesystemkeyboard
andmouse,systemprinters,andanoptionaldigitalcamera.
PowerControl
Controlsbatteryoperationandmonitoringforbattery-powered
computers.
Regional&Accessibility
Controlsaccessibilityfordisabledusers,country-andlanguage-
specificsettings,andthekeyboardlayoutandshortcuts.
Security&Privacy
Controlshowpasswordsaredisplayedandremembered,
privacysettings,andcryptographicsettings,including
configuringSSLandmanagingcertificates.
Sound&Multimedia
Controlsthesoundsystem,playingofaudioCDs,thesystem
bell,andsystemnotifications.
SystemAdministration
Manyofthetopicsinthiscategoryrequireyoutoclick
AdministratorModeandentertheSuperuser(root)
password.Workingasyourself,youcanmodifyyourpassword
andperformsomeothertasks.WorkingasSuperuser,youcan
changethesystemdateandtime,installfonts,andchangethe
wayusersloginonthesystem.
CustomizingtheMainPanelUsingthePanel
Menu
Handles
Right-clickinganicondisplaysthePanelIconmenuformost
icons.Someicons,suchastheKNotesiconandthePagerand
Taskbar,displayIconcontextmenus(page91)whenyouright-
clickthem.Thistypeoficonhasahandle.Right-clickormiddle-
clickthehandleadjacenttotheicon(nottheiconitself)towork
withthePanelIconmenu.
KDEdoesnotdisplayahandleuntilyoupositionthemouse
pointeroveranicon.Thehandleappearstotheleftofitsicon
asanarrowverticalspacewithatriangleatthetopand
hatchmarksonitsleft(Figure4-17).Withthemousepointer
hoveringoverahandle,KDEdisplaysatooltipthatincludesthe
wordhandle.
Figure4-17.Ahandle
Iconsthatdisplaypop-upmenuswhenyouclickthemhavean
indicatorthatissimilartoahandle.However,thisindicatordoes
nothavehatchmarksandthetriangleisnotfilledin.In
addition,thetooltipdisplaysthenameofthemenuanddoes
notincludethewordhandle.
Addingicons
ThePanelmenuprovidestoolstocustomizethepanel.Right-
clickaniconorhandleonthepanelandselectPanelMenuor
right-clickanemptyspaceonthepaneltodisplaythePanel
menu(Figure4-18).
Figure4-18.ThePanelmenu
FromthePanelmenuyoucanaddandremoveappletsand
applicationsandconfigurethepanel.Youcanalsoadddifferent
typesofpanelstothedesktop.Feelfreetoexperimentby
addingiconstothepanelyoucannotdoanyharm.
Addingapplications
YoucananaddanapplicationfromtheMainmenubyclicking
AddApplicationtoPanelinthePanelmenu,selectingan
applicationcategory,andthenselectinganapplication.For
example,Panelmenu:AddApplicationtoPanel Office
WordProcessoraddsaniconfortheOpenOfficeword
processortothepanel.
AtthetopofeachmenuthatyoudisplaybyselectingAdd
ApplicationtoPanelisanAddThisMenuselection;clickit
toaddtheentiremenutothepanel.Whenyouclicktheicon
thataddingamenuplacesonthepanel,KDEdisplaysapop-up
menu.
Removingicons
Toremoveaniconfromthepanelright-clicktheiconorhandle
todisplaythePanelIconmenuandthenselectRemove.You
canalsoremoveaniconbyselectingRemoveFromPanel
fromthePanelmenu,selectingAppletorApplicationfromthe
resultingpop-upmenu,andclickingthenameoftheiconyou
wanttoremove.
Movingicons
Youcanmoveapaneliconbyclickingtheiconwiththemiddle
mousebuttonanddraggingit.Foriconswithhandles,clickand
dragthehandle.Tocauseanicontoshoveasidebordering
iconsandnotjumpoverthem,holdtheSHIFTkeywhile
dragging.
Configuringthepanel
TheConfigurePanelselectiononthePanelmenudisplaysthe
ConfigureKDEPanelwindow,whichdeterminesthelocation,
appearance,andfunctionalityofthepanel(Figure4-19).Click
theiconsontheleftsideofthewindowtodisplaypageswhere
youcanmodifythepanel.OneiconselectstheTaskbar(page
86)formodification.
Figure4-19.TheConfigureKDEPanelwindow,
Arrangementpage
[Viewfullsizeimage]
Trychangingtheappearanceorarrangementofthepanel.Click
Applytomakeyourchangestakeeffect.ClickDefaultsand
thenApplytoreturnthingstothewaytheywerewhenthe
systemwasinstalled.
Whenmorethanonepanelappearsintheworkspace,KDE
displaysacomboboxlabeledSettingsforatthetopofthe
Arrangementpage.Usethiscomboboxtospecifywhichpanel
youwanttoworkwith.
GettingtheFacts:WheretoFindDocumentation
DistributionsofLinux,includingRedHatLinux,typicallydonot
comewithhardcopyreferencemanuals.However,itsonline
documentationhasalwaysbeenoneofLinux'sstrengths.The
manual(orman)andinfopageshavebeenavailableviatheman
andinfoutilitiessinceearlyreleasesoftheoperatingsystem.
BoththeGNOMEandKDEdesktopsprovidegraphicalHelp
Centers.Notsurprisingly,withthegrowthofLinuxandthe
Internet,thesourcesofdocumentationhaveexpandedaswell.
Thissectiondiscussessomeoftheplacesyoucanlookfor
informationonLinuxingeneralandRedHatLinuxinparticular.
TheKDEHelpCenter
DisplaytheKDEHelpCenterbyclickingMainmenu:Help.If
theHelpCenterdisplaysawindowthataskswhetheryouwant
tocreateasearchindex,clickCreate.TheHelpCenterthen
displaystheBuildSearchIndexwindow.Putacheckmarkin
eachoftheboxesintheSearchScopecolumnofthiswindow
andclickBuildIndex.Thewindowthatappearsshowsthe
progressbeingmadeinbuildingtheindex.Whenitiscomplete,
clickClose.
TheHelpCenterwindowcontainstwoverticalsections
separatedbyathinbarwithhatchmarksonit.(SeeFigure4-17
onpage100foranexampleofabarwithsimilarmarks.)Click
thehatchmarksanddragthebarleftorrighttoadjustthesizes
ofthetwosectionsofthewindow.
TheleftsideoftheHelpCenterwindowcontainsthreetabs:
Contents,Glossary,andSearchOptions.ClicktheContentstab
todisplayalistoftheHelpCentercontentsontheleft.Thislist
includestheKDEFAQ,theKDEUser'sManual,Linux(UNIX)man
pages,GNUinfopages,KDEControlCentermodules,andmore.
Clickanitemonthislisttodisplayalistofsubitemsavailable
forfurtherexploration.Clickasubitemtodisplaythatitemon
theright.Figure4-20showstheHelpCenter,Contentstab,
displayinginformationontheControlCenterModules Font
Installer.
Figure4-20.TheKDEHelpCenter
[Viewfullsizeimage]
ClickingtheGlossarytabdisplaysdefinitionsofwordsrelated
toLinuxsortedeitheralphabeticallyorbytopic.Whenyouclick
theSearchOptionstabandselectoneormoreitemsfromthe
Scopecolumn,youcanenterawordtosearchforinthesmall
textboxjustabovethetabs.ClickSearchtodisplaytheresults
ofthesearchintherightportionofthewindow.Figure4-21
showstheresultofasearchoftheLinux(calledUNIXinthis
window)manualpagesfortheworduptime.
Figure4-21.Resultofasearchforuptimeinthe
KDEHelpCenter
GNOMEHelp
TodisplaytheGNOMEHelpwindow(Figure4-22),select
System:Help(RHELusesApplications:Help)fromthepanel
atthetopofthescreen.ClicktopicsinthiswindowuntilGNOME
displaystheinformationyouarelookingfor.ClickCommand
LineHelptodisplaymanandinfopages.
Figure4-22.TheGNOMEHelpwindow
[Viewfullsizeimage]
man:DisplaystheSystemManual
InadditiontotheKDEHelpCenterandGNOMEHelp,the
character-basedman(manual)utilitydisplayspages(manpages)
fromthesystemdocumentation.Thisdocumentationishelpful
whenyouknowwhichutilityyouwanttousebuthaveforgotten
exactlyhowtouseit.Youcanalsorefertothemanpagestoget
moreinformationaboutspecifictopicsortodeterminewhich
featuresareavailablewithLinux.Becausethedescriptionsin
thesystemdocumentationareoftenterse,theyaremost
helpfulifyoualreadyunderstandthebasicfunctionsofthe
utility.
Becausemanisacharacter-basedutility,youneedtoopena
terminalemulatorwindow(page93)torunit.Youcanalsolog
inonavirtualterminal(page113)andruntheutilityfrom
there.
Tofindoutmoreaboutautility,givethecommandman,
followedbythenameoftheutility.Figure4-23showsman
displayinginformationaboutitself,aftertheuserentereda
manmancommand.
Figure4-23.Themanutilitydisplaying
informationaboutitself
[Viewfullsizeimage]
less(pager)
Themanutilityautomaticallysendsitsoutputthrougha
pagerusuallyless(page128),whichdisplaysafileonescreenat
atime.Whenyouaccessamanualpageinthismanner,less
displaysaprompt(:)atthebottomofthescreenaftereach
screenoftextandwaitsforyoutorequestanotherscreenby
pressingtheSPACEbar.Pressingh(help)displaysalistofless
commands.Pressingq(quit)stopslessandcausestheshellto
displayaprompt.Youcansearchfortopicscoveredbyman
pagesbyusingtheaproposutility(page145).
BasedontheFHS(FilesystemHierarchyStandard,page176),
theLinuxsystemmanualandthemanpagesaredividedintoten
sections.Eachsectiondescribesrelatedtools:
1. UserCommands
2. SystemCalls
3. Subroutines
4. Devices
5. FileFormats
6. Games
7. Miscellaneous
8. SystemAdministration
9. Kernel
10. New
ThislayoutcloselymimicsthewaythesetofUNIXmanualshas
alwaysbeendivided.Unlessyouspecifyamanualsection,man
displaystheearliestoccurrenceinthemanualofthewordyou
specifyonthecommandline.Mostusersfindtheinformation
theyneedinsections1,6,and7;programmersandsystem
administratorsfrequentlyneedtoconsulttheothersections.
Tip:YoucanuseKonquerortoviewman
andinfopages
Youcanviewmanandinfopagesbyentering,for
example,man:catorinfo:catinKonqueror's
locationbar(Figure4-13,page96)orintheRun
Commandbox(page96).TheKDEHelpCenteralso
offersdirectaccesstothesepagesasUNIXmanual
pages.GNOMEHelpreferstothemasCommand
LineHelp.
Insomecasesthemanualcontainsentriesfordifferenttools
withthesamename.Forexample,thefollowingcommand
displaysthemanpageforthewriteutility(page150)from
section1ofthesystemmanual:
$manwrite
Toseethemanpageforthewritesystemcallfromsection2,
enter
$man2write
Theprecedingcommandinstructsmantolookonlyinsection2
forthemanpage.Usetheaoption(seetheadjacenttip)toview
allmanpagesforagivensubject(pressqtomovetothenext
manpage).Forexample,givethecommandmanawriteto
viewallmanpagesforwrite.
Tip:Options
Anoptionmodifiesthewayautilityorcommand
works.Optionsareusuallyspecifiedasoneormore
lettersthatareprecededbyoneortwohyphens.
Theoptionappearsfollowingthenameoftheutility
youarecallingandaSPACE.Otherarguments(page
1019)tothecommandfollowtheoptionanda
SPACE.Formoreinformationreferto"Options"on
page203.
Tip:manandinfodisplaydifferent
information
Theinfoutilitydisplaysmorecompleteandup-to-
dateinformationonGNUutilitiesthandoesman.
Whenamanpagedisplaysabbreviatedinformation
onautilitythatiscoveredbyinfo,themanpage
refersyoutoinfo.Themanutilityfrequentlydisplays
theonlyinformationavailableonnon-GNUutilities.
Wheninfodisplaysinformationonnon-GNUutilities,
itisfrequentlyacopyofthemanpage.
info:DisplaysInformationAboutUtilities
Thecharacter-basedinfoutilityisamenu-basedhypertext
systemdevelopedbytheGNUproject(page2)anddistributed
withRedHatLinux.Theinfoutilityincludesatutorialonitself
(gotowww.gnu.org/software/texinfo/manual/infoorgivethe
commandinfoinfo)anddocumentationonmanyLinuxshells,
utilities,andprogramsdevelopedbytheGNUproject.Figure4-
24showsthescreenthatinfodisplayswhenyougivethe
commandinfo.
Figure4-24.Thefirstscreenthatinfodisplays
[Viewfullsizeimage]
Becausetheinformationonthisscreenisdrawnfroman
editablefile,yourdisplaymaydifferfromthoseshowninthis
section.Whenyouseetheinitialinfoscreen,youcanpressany
ofthefollowingkeysorkeycombinations:
htogothroughaninteractivetutorialoninfo
?tolistinfocommands
SPACEtoscrollthroughthemenuofitemsforwhich
informationisavailable
mfollowedbythenameofthemenuyouwanttodisplayor
aSPACEtodisplayalistofmenus
qorCONTROL-Ctoquit
Thenotationinfousestodescribekeyboardkeysmaynotbe
familiartoyou.ThenotationC-histhesameasCONTROL-H.
SimilarlyM-xmeansholddowntheMETAorALTkeyandpress
x.(OnsomesystemsyouneedtopressESCAPEandthenxto
duplicatethefunctionofMETA-x.)
Tip:Youmayfindpinfoeasiertousethan
info
Thepinfoutilityissimilartoinfobutismoreintuitive
ifyouarenotfamiliarwiththeemacseditor.This
utilityrunsinatextualenvironment,asdoesinfo.
Whenitisavailable,pinfousescolortomakeits
interfaceeasiertouse.
Aftergivingthecommandinfo,presstheSPACEbarafew
timestoscrollthroughthedisplay.Figure4-25showstheentry
forsleep.Theasteriskattheleftendofthelinemeansthatthis
entryisamenuitem.Followingtheasteriskisthenameofthe
menuitem,acolon,thenameofthepackage(inparentheses)
thatthemenuitembelongsto,otherinformation,anda
descriptionoftheitemontheright.Inmostcasesthepackage
namecorrespondstothenameoftherpmpackage(page487)
thatcontainstheitem.Figure4-25showsthatthesleeputilityis
partofthecoreutilspackage.
Figure4-25.Thescreenthatinfodisplaysafter
youpresstheSPACEbarafewtimes
[Viewfullsizeimage]
Eachmenuitemisalinktotheinfopagethatdescribesthe
item.Tojumptothatpage,movethecursortotheline
containingthemenuitemandpressRETURN.Alternatively,you
cantypethenameofthemenuiteminamenucommandto
viewtheinformation.Todisplayinformationonsleep,for
example,youcangivethecommandmsleep,followedby
RETURN.Whenyoutypem(formenu),thecursormovestothe
bottomlineofthescreenanddisplaysMenuitem:.Typing
sleepdisplayssleeponthatline,andpressingRETURN
displaysinformationaboutthemenuitemyouhavechosen.
Figure4-26showsthetopnodeofinformationonsleep.Anode
isonegroupofinformationthatyoucanscrollthroughwiththe
SPACEbar.Todisplaythenextnode,pressn.Pressptodisplay
thepreviousnode.Youcanalwayspressdtodisplaytheinitial
menu(Figure4-24).
Figure4-26.Theinfopageonthesleeputility
[Viewfullsizeimage]
Asyoureadthroughthisbookandlearnaboutnewutilities,you
canusemanorinfotofindoutmoreabouttheutilities.Ifyou
canprintPostScriptdocuments,youcanprintamanualpage
withthemanutilityusingthetoption(forexample,mantcat|
lprprintsinformationaboutthecatutility).youcanalsousea
browsertodisplaythedocumentationatwww.tldp.org,
fedora.redhat.com/docs,fedoraproject.org/wiki/Docs,or
www.redhat.comandthenprintthedesiredinformationfrom
thebrowser.
ThehelpOption
Anothertoolyoucanuseinatextualenvironmentisthehelp
option.MostGNUutilitiesprovideahelpoptionthatdisplays
informationabouttheutility.Non-GNUutilitiesmayuseahor
helpoptiontodisplayHelpinformation.
$cat--help
Usage:cat[OPTION][FILE]...
ConcatenateFILE(s),orstandardinput,tostandardoutput.
-A,--show-allequivalentto-vET
-b,--number-nonblanknumbernonblankoutputlines
-eequivalentto-vE
-E,--show-endsdisplay$atendofeachline
...
Iftheinformationthathelpdisplaysrunsoffthescreen,send
theoutputthroughthelesspager(page104)usingapipe(page
52):
$ls--help|less
HOWTOs:FindingOutHowThingsWork
AHOWTOdocumentexplainsindetailhowtodosomething
relatedtoLinuxfromsettingupaspecializedpieceofhardware
toperformingasystemadministrationtasktosettingup
specificnetworkingsoftware.Mini-HOWTOsoffershorter
explanations.AswithLinuxsoftware,onepersonorafew
peoplegenerallyareresponsibleforaHOWTOdocument,but
manypeoplemaycontributetoit.
TheLinuxDocumentationProject(LDP,page110)sitehouses
mostHOWTOandmini-HOWTOdocuments.Useabrowsertogo
towww.tldp.org,clickHOWTOs,andpicktheindexyouwant
tousetofindaHOWTOormini-HOWTO.Youcanalsousethe
LDPsearchfeatureonitshomepagetofindHOWTOsandmore.
GettingHelpwiththeSystem
KDEandGNOMEprovidesimilarHelpfacilities.Eachprovides
tooltips(page86),acontext-sensitiveHelpsystem,andthe
Helpsystemsdiscussedonpages102and103.
FindingHelpLocally
The/usr/src/linux/Documentation(presentonlyifyou
installedthekernelsourcecodeasexplainedinChapter15)and
/usr/share/docdirectoriesoftencontainmoredetailedand
differentinformationaboutautilitythanmanorinfoprovides.
Frequentlythisinformationismeantforpeoplewhowillbe
compilingandmodifyingtheutility,notjustusingit.These
directoriesholdthousandsoffiles,eachcontaininginformation
onaseparatetopic.
UsingtheInternettoGetHelp
TheInternetprovidesmanyhelpfulsitesrelatedtoLinux.Aside
fromsitesthatcarryvariousformsofdocumentation,youcan
enteranerrormessagethatyouarehavingaproblemwithina
searchenginesuchasGoogle(www.google.com,oritsLinux-
specificversionatwww.google.com/linux).Enclosetheerror
messagewithindoublequotationmarkstoimprovethequality
oftheresults.Thesearchwilllikelyyieldapostconcerningyour
problemandsuggestionsabouthowtosolveit.SeeFigure4-27
onthenextpage.
Figure4-27.Googlereportingonanerror
message
[Viewfullsizeimage]
TheRedHatWebsite
TheRedHatandFedoraWebsitesarerichsourcesof
information.Thefollowinglistidentifiesofsomelocationsthat
maybeofinterest:
ManualsforRedHatLinuxthroughRedHatLinux9and
RHELareavailableatwww.redhat.com/docs.
Varioustypesofsupportdocumentsandsupportare
availableatwww.redhat.com/apps/support.
YoucanquerytheRedHatKnowledgebase(requiresfree
registration)atkbase.redhat.com.
FEDORAdocumentationisavailableat
fedora.redhat.com/docs,andfedoraproject.org(click
Documentation).
RHEL+FEDORAThehomepages(www.redhat.com,
fedora.redhat.com,andfedoraproject.org),haveawealthof
information.
RHEL+FEDORAsupportforumsareonlinediscussionsabout
anyRedHatrelatedissuesthatpeoplewanttoraise.One
forumisdedicatedtonewusers;otherstoApache,theX
WindowSystem,andsoon.Goto
www.redhat.com/mailman/listinfotobrowsethelists.
Anothersitethathassimilar,usefulinformationis
fedoraforum.org.
FEDORAinformationisavailableatfedoranews.org.
RHELhardwarehelpisavailablefromtheRedHathardware
catalogathardware.redhat.com.ThehardwarethatFEDORA
supportsismostlyasupersetofthatsupportedbyRHEL.
GNU
GNUmanualsareavailableatwww.gnu.org/manual.In
addition,youcanvisittheGNUhomepage(www.gnu.org)for
moredocumentationandotherGNUresources.Manyofthe
GNUpagesandresourcesareavailableinawidevarietyof
languages.
TheLinuxDocumentationProject
TheLinuxDocumentationProject(www.tldp.org),whichhas
beenaroundforalmostaslongasLinux,housesacomplete
collectionofguides,HOWTOs,FAQs,manpages,andLinux
magazines.ThehomepageisavailableinEnglish,Portuguese,
Spanish,Italian,Korean,andFrench.Itiseasytouseand
supportslocaltextsearches.Italsoprovidesacompletesetof
links(Figure4-28)thatyoucanusetofindalmostanythingyou
wantthatisrelatedtoLinux(clickLinksintheSearchboxor
gotowww.tldp.org/links).Thelinkspageincludessectionson
generalinformation,events,gettingstarted,usergroups,
mailinglists,andnewsgroups,witheachsectioncontaining
manysubsections.
Figure4-28.TheLinuxDocumentationProject
homepage
[Viewfullsizeimage]
MoreAboutLoggingIn
Referto"LoggingInontheSystem"onpage83forinformation
aboutlogginginonthesystemandchangingyourdefault
desktopenvironment(KDEorGNOME).
Security:Alwaysuseapassword
Unlessyouaretheonlyuserofasystem;the
systemisnotconnectedtoanyothersystems,the
Internet,oramodem;andyouaretheonlyonewith
physicalaccesstothesystem,itispoorpracticeto
allowanyusertologinwithoutapassword.
TheLoginScreen
Fouricon/wordbuttonsappearbelowtheUsername/Password
textboxontheLoginscreen.Clicktheseiconstochange
aspectsofthesessionyouareabouttologinto.Youcanalso
pressF10todisplayapop-upmenuwithsimilarchoices.
LanguageDisplaysawindowfromwhichyoucanselectthe
languageforthesessionyouareabouttostart.Thischange
affectswindowtitles,prompts,errormessages,andother
textualitemsdisplayedbyGNOME,KDE,andmany
applications.Justafteryoulogin,thesystemaskswhether
youwanttomakethischangeinlanguagespermanentorif
itisaone-timechange.
SessionDisplaystheSessionsdialogbox,whichpresents
severalchoicesconcerningthesessionyouareaboutto
start.Chooseoneofthefollowing,clickOK,andcontinue
loggingin:
LastSessionBringsupthesamedesktopenvironment
youusedthelasttimeyouloggedin.
DefaultSystemSessionBringsupthedefaultdesktop
environment.
GNOMEBringsuptheGNOMEdesktopenvironment.
KDEBringsuptheKDEDesktopEnvironment.
FailsafeGNOMEBringsupadefaultGNOMEsession
withoutrunninganystartupscripts.Usethischoiceto
fixproblemsthatpreventyoufromlogginginnormally.
FailsafeTerminalBringsupanxtermterminalemulator
windowwithoutadesktopmanagerandwithoutrunning
anystartupscripts.Thissetupallowsyoutologinona
minimaldesktopwhenyourstandardlogindoesnot
workwellenoughtoallowyoutologintofixalogin
problem.Givethecommandexitfromthextermwindow
tologoutanddisplaytheLoginscreen.
RHEL
AnychangesyoumakeintheSessionsdialogboxaffectthe
currentsessiononly.Thenexttimeyoulogin,youwill
reverttoyourdefaultdesktopenvironment(KDEor
GNOME).Afteryoulogin,useswitchdesk(page116)to
changeyourdefaultdesktopenvironment.
FEDORA
Justafteryoulogin,thesystemaskswhetherthechange
madeintheSessionsdialogboxisjustforthissessionorif
youwanttomakeitpermanent.Thefailsafeloginsdonot
askthisquestion.
RestartShutsdownandrebootsthesystem.
ShutdownShutsdownthesystemandturnsoffthepower.
WhattoDoifYouCannotLogIn
Ifyouentereitheryourusernameorpasswordincorrectly,the
systemdisplaysanerrormessageafteryouenterbothyour
usernameandyourpassword.Thismessageindicatesthatyou
haveenteredeithertheusernameorthepasswordincorrectly
orthattheyarenotvalid.Itdoesnotdifferentiatebetweenan
unacceptableusernameandanunacceptablepassworda
strategymeanttodiscourageunauthorizedpeoplefrom
guessingnamesandpasswordstogainaccesstothesystem.
Herearesomecommonreasonswhyloginsfail:
Theusernameandpasswordarecasesensitive.Make
suretheCAPSLOCKkeyisoffandthatyouenteryour
usernameandpasswordexactlyasspecifiedorasyouset
themup.
Youarenotlogginginontherightmachine.The
login/passwordcombinationmaynotbevalidifyouare
tryingtologinonthewrongmachine.Onalarger,
networkedsystem,youmayhavetospecifythemachine
thatyouwanttoconnecttobeforeyoucanlogin.
Makesureyourusernameisvalid.Thelogin/password
combinationmaynotbevalidifyouhavenotbeensetup
asauser.Ifyouarethesystemadministrator,referto
"ConfiguringUserandGroupAccounts"onpage538.
Otherwise,checkwiththesystemadministrator.
Referto"ChangingYourPassword"onpage114whenyouwant
tochangeyourpassword.
LoggingOut
TologoutofaKDEgraphicalenvironment,clicktheredhator
Fedoralogoatthelower-leftcornerofthedisplayandchoose
Logoutfromthepop-upmenu.FromGNOME,selectSystem
orActionsfromthepanelatthetopofthescreenandclick
LogOut.Fromatextualenvironment,pressCONTROL-Dorgive
thecommandexitinresponsetotheshellprompt.
UsingVirtualConsoles
WhenrunningLinuxonapersonalcomputer,youfrequently
workwiththedisplayandkeyboardattachedtothecomputer.
Usingthisphysicalconsole,youcanaccessasmanyas63
virtualconsoles(alsocalledvirtualterminals).Somearesetup
toallowlogins;othersactasgraphicaldisplays.Toswitch
betweenvirtualconsoles,holdtheCONTROLandALTkeysdown
andpressthefunctionkeythatcorrespondstotheconsoleyou
wanttoview.Forexample,CONTROL-ALT-F5displaysthefifth
virtualconsole.Thisbookreferstotheconsolethatyousee
whenyoufirstbootasystem(orpressCONTROL-ALT-F1)asthe
systemconsole(orjustconsole).
Bydefault,sixvirtualconsolesareactiveandhavetextlogin
sessionsrunning.Whenyouwanttousebothtextualand
graphicalinterfaces,youcansetupatextualsessiononone
virtualconsoleandagraphicalsessiononanother.Nomatter
whichvirtualconsoleyoustartagraphicalsessionfrom,the
graphicalsessionrunsonthefirstunusedvirtualconsole
(numbersevenbydefault).
LoggingInRemotely:TerminalEmulationand
sshortelnet
Whenyouarenotusingaconsole,terminal,orotherdevice
connecteddirectlytotheLinuxsystemyouarelogginginon,
youareprobablyconnectedtotheLinuxsystemusingterminal
emulationsoftwareonanothersystem.Runningonyourlocal
computer,thissoftwareconnectstotheLinuxsystemviaa
network(Ethernet,asynchronousphoneline,PPP,orother
type)andallowsyoutologinontheLinuxmachine.
Tip:MakesureTERMissetcorrectly
Nomatterhowyouconnect,makesureyouhavethe
TERMvariablesettothetypeofterminalyour
emulatorisemulating.Formoreinformationreferto
"SpecifyingaTerminal"onpage984.
Whenyouloginviaadial-upline,theconnectionis
straightforward:Youinstructtheemulatorprogramtocontact
thecomputer,itdialsthephone,andyougetaloginprompt
fromtheremotesystem.Whenyouloginviaadirectly
connectednetwork,youusessh(secure,page585)ortelnet(not
secure,page363)toconnecttothecomputer.Thesshprogram
hasbeenimplementedonmanymachines,notjustonLinux
systems.Manyuserinterfacestosshincludeaterminal
emulator.FromanApple,PC,orUNIXmachine,openthe
programthatrunssshandgiveitthenameorIPaddress(refer
to"HostAddress"onpage353)ofthesystemyouwanttolog
inon.Forexamplesandmoredetailonworkingwithaterminal
emulator,referto"RunningCommandsfromtheTerminal
Emulator/Shell"onpage93.Formoreinformationabout
logginginfromaterminalemulator,see"LoggingInona
Terminal"onpage116.
ChangingYourPassword
Ifsomeoneelseinitiallyassignedyourpassword,itisagood
ideatogiveyourselfanewone.Agoodpasswordissevenor
eightcharacterslongandcontainsacombinationofnumbers,
uppercaseandlowercaseletters,andpunctuationcharacters.
Avoidusingcontrolcharacters(suchasCONTROL-H)because
theymayhaveaspecialmeaningtothesystem,makingit
impossibleforyoutologin.Donotusenames,wordsfrom
Englishorotherlanguages,orotherfamiliarwordsthat
someonecaneasilyguess.
Forsecurityreasonsnoneofthepasswordsyouenteris
displayedbyanyutility.
Security:Protectyourpassword
Donotallowsomeonetofindoutyourpassword:Do
notputyourpasswordinafilethatisnotencrypted,
allowsomeonetowatchyoutypeyourpassword,or
giveyourpasswordtosomeoneyoudonotknow(a
systemadministratorneverneedstoknowyour
password).Youcanalwayswriteyourpassword
downandkeepitinasafe,privateplace.
Security:Chooseapasswordthatis
difficulttoguess
Dousephonenumbers,namesofpetsorkids,
birthdays,wordsadictionary(notevenaforeign
language),andsoforth.Donotusepermutationsof
theseitems.
Security:Differentiatebetween
importantandlessimportantpasswords
Itisagoodideatodifferentiatebetweenimportant
andlessimportantpasswords.Forexample,Web
sitepasswordsforblogsordownloadaccessarenot
veryimportant;itisnotbadifyouchoosethesame
passwordforthesetypesofsites.However,your
login,mailserver,andbankaccountWebsite
passwordsarecritical:Neverusethesepasswords
foranunimportantWebsite.
Tochangeyourpasswordfromaterminalemulatororother
commandline,givethecommandpasswd.Tochangeyour
passwordfromKDE,selectMainmenu:Settings Password
(RHELusesMainmenu:Preferences Password).From
GNOMEselectSystem:Preferences AboutMeandclick
ChangePassword(RHELusesApplications:Preferences
Password).
Thefirstitemthesystemasksforisyourcurrent(old)
password.Thispasswordisverifiedtoensurethatan
unauthorizeduserisnottryingtoalteryourpassword.The
systemthenrequeststhenewpassword.
Apasswordshouldmeetthefollowingcriteriatoberelatively
secure.Onlythefirstitemismandatory.
Itmustbeatleastsixcharacterslong(orlongerifthe
systemadministratorsetsitupthatway).
Itshouldnotbeawordinadictionaryofanylanguage,no
matterhowseeminglyobscure.
Itshouldnotbethenameofaperson,place,pet,orother
thingthatmightbediscoveredeasily.
Itshouldcontainatleasttwolettersandonedigit.
Itshouldnotbeyourusername,thereverseofyour
username,oryourusernameshiftedbyoneormore
characters.
Ifyouarechangingyourpassword,thenewpassword
shoulddifferfromtheoldonebyatleastthreecharacters.
Changingthecaseofacharacterdoesnotmakeitcountas
adifferentcharacter.
Referto"KeepingtheSystemSecure"onpage556formore
informationaboutchoosingapassword.
Afteryouenteryournewpassword,thesystemasksyouto
retypeittomakesureyoudidnotmakeamistakewhenyou
entereditthefirsttime.Ifthenewpasswordisthesameboth
timesyouenterit,yourpasswordischanged.Ifthepasswords
differ,thenyoumadeanerrorinoneofthem.Inthissituation
thesystemdisplaysanerrormessageordoesnotallowyouto
clicktheOKbutton.
Ifthepasswordyouenterisnotlongenough,thesystem
displaysthefollowingmessage:
BADPASSWORD:itistooshort
Ifitistoosimple,thesystemdisplaysthismessage:
BADPASSWORD:itistoosimplistic/systematic
Ifthepasswordisformedfromwords,thesystemdisplaysthis
message:
BADPASSWORD:itisbasedonadictionaryword
Ifthesystemdisplaysoneofthesemessages,enteralongeror
morecomplexpasswordinresponsetotheNewUNIX
password:prompt.
Whenyousuccessfullychangeyourpassword,youchangethe
wayyoulogin.Ifyouforgetyourpassword,Superusercan
changeitandtellyouthenewpassword.
switchdesk:ChangesYourDefaultDesktop
RHEL
Theswitchdeskutilitytellsthesystemwhichdesktopyouwantto
logintobydefault:KDEorGNOME.Initiallyyouraccountisset
uptologintoGNOMEbydefault.Touseswitchdesk,givethe
commandswitchdeskfollowedbythenameofthedesktop
youwanttobethedefault(gnomeorkde).
FEDORA
Theswitchdeskutilityisnotinstalledbydefaultbecauseitisnot
needed.Itispartoftheswitchdeskpackage.
LoggingInonaTerminal
Beforeyouloginonaterminal,terminalemulator,orother
textualdevice,thesystemdisplaysamessagecalledissue
(storedinthe/etc/issuefile)thatidentifiestheversionofRed
HatLinuxrunningonthesystem.Asampleissuemessage
follows:
FedoraCorerelease5(Bordeaux
Kernel2.6.15-1.2054_FC5onani686
Theissuemessageisfollowedbyaprompttologin.Enteryour
usernameandpasswordinresponsetothesystemprompts.If
youareusingaterminal(page1059)andyourscreendoesnot
displaythelogin:prompt,checkwhethertheterminalis
pluggedinandturnedon,andthenpresstheRETURNkeyafew
times.Iflogin:stilldoesnotappear,trypressingCONTROL-Q.
Ifyouareusingaworkstation(page1064),makesureitis
running.Runssh(page585),telnet(page363),orwhatever
communications/emulationsoftwareyouhavetologinonthe
system.Tryloggingin,makingsurethatyouenteryour
usernameandpasswordastheywerespecifiedwhenyour
accountwassetup;theroutinethatverifiestheusernameand
passwordiscasesensitive.
Security:Didyouloginlast?
Asyouareloggingintoatextualenvironment,after
youenteryourusernameandpassword,thesystem
displaysinformationaboutthelastloginonthis
account,showingwhenittookplaceandwhereit
originated.Youcanusethisinformationto
determinewhetheranyoneelsehasaccessedthe
accountsinceyoulastusedit.Ifsomeonehas,
perhapsanunauthorizeduserhaslearnedyour
passwordandloggedonasyou.Intheinterestof
security,advisethesystemadministratorofany
circumstancesthatmakeyoususpiciousandchange
yourpassword(page114).
Nexttheshellprompt(orjustprompt)appears,indicatingthat
youhavesuccessfullyloggedin;itindicatesthatthesystemis
readyforyoutogiveacommand.Thefirstshellpromptline
maybeprecededbyashortmessagecalledthemessageofthe
day,ormotd(page453),whichisstoredinthe/etc/motd
file.Theusualpromptisadollarsign($).RedHatLinux
establishesapromptof[user@hostdirectory]$,whereuser
isyourusername,hostisthenameofthelocalsystem,and
directoryisthenameofthedirectoryyouareworkingin.For
informationonhowtochangetheprompt,refertopage293.
BringingaGUIUpfromaCharacter-BasedDisplay
Bydefault,RedHatsystemspresentagraphicalinterfacewhen
theyfirstcomeup.Ifthesystemcomesupwithatextual
interface,youcanloginonavirtualconsoleandstarta
graphicaldisplaybygivingthefollowingcommandtobringup
yourdefaultdesktopenvironment:
$startx
Ifstartxdoesnotwork,runsystem-config-display(page70)toset
upthegraphicscardandmonitorconfigurationfortheX
WindowSystem.
CorrectingMistakes
Thissectionexplainshowtocorrecttypographicalandother
errorsyoumaymakewhileyouareloggedinonacharacter-
baseddisplay(eitheravirtualconsoleoraterminalemulator).
Becausetheshellandmostotherutilitiesdonotinterpretthe
commandlineorothertextuntilafteryoupressRETURN,you
canreadilycorrecttypingmistakesbeforeyoupressRETURN.
Youcancorrecttypingmistakesinseveralways:eraseone
characteratatime,backupawordatatime,orbackuptothe
beginningofthecommandlineinonestep.Afteryoupress
RETURN,itistoolatetocorrectamistake:Youmusteitherwait
forthecommandtoruntocompletionorabortexecutionofthe
program(page118).
ErasingaCharacter
Whileenteringcharactersfromthekeyboard,youcanbackup
anderaseamistakebypressingtheerasekeyonceforeach
characteryouwanttodelete.Theerasekeybacksoveras
manycharactersasyouwish.Itdoesnot,ingeneral,backup
pastthebeginningoftheline.
ThedefaulterasekeyisBACKSPACE.Ifthiskeydoesnotwork,
tryDELETEorCONTROL-H.Ifthesekeysdonotwork,givethe
followingstty[3]commandtosettheeraseandlinekill(see
"DeletingaLine"onthenextpage)keystotheirdefaultvalues:
[3]Thecommandsttyisanabbreviationforsetteletypewriter,thefirstterminalthatUNIX
wasrunon.Todaysttyiscommonlythoughtofassetterminal.
$sttyek
DeletingaWord
YoucandeleteawordyouenteredbypressingCONTROL-W.A
wordisanysequenceofcharactersthatdoesnotcontaina
SPACEorTAB.WhenyoupressCONTROL-W,thecursormoves
lefttothebeginningofthecurrentword(asyouareenteringa
word)orthepreviousword(whenyouhavejustentereda
SPACEorTAB),removingtheword.
Tip:CONTROL-Zsuspendsaprogram
Althoughitisnotawayofcorrectingamistake,you
maypressthesuspendkey(typicallyCONTROL-Z)
bymistakeandwonderwhathappened(youwillsee
amessagecontainingthewordStopped).Youhave
juststoppedyourjob,usingjobcontrol(page280).
Givethecommandfgtocontinueyourjobinthe
foreground,andyoushouldreturntowhereyou
werebeforeyoupressedthesuspendkey.Formore
informationreferto"bg:SendsaJobtothe
Background"onpage281.
DeletingaLine
AnytimebeforeyoupressRETURN,youcandeletethelineyou
areenteringbypressingthelinekillkey(orkillkey).Whenyou
pressthiskey,thecursormovestotheleft,erasingcharacters
asitgoes,backtothebeginningoftheline.Thedefaultlinekill
keyisCONTROL-U.Ifthiskeydoesnotwork,tryCONTROL-X.If
thesekeysdonotwork,givethefollowingcommandtosetthe
eraseandlinekillkeystotheirdefaultvalues:
$sttyek
AbortingExecution
Sometimesyoumaywanttoterminatearunningprogram.For
example,youmaywanttostopaprogramthatisperforminga
lengthytasksuchasdisplayingthecontentsofafilethatis
severalhundredpageslongorcopyingafilethatisnottheone
youmeanttocopy.
Toterminateaprogramfromacharacter-baseddisplay,press
theinterruptkey(CONTROL-CorsometimesDELETEorDEL).
Whenyoupressthiskey,theLinuxoperatingsystemsendsa
terminalinterruptsignaltotheprogramyouarerunningandto
theshell.Exactlywhateffectthissignalhasdependsonthe
particularprogram.Someprogramsstopexecution
immediately,someignorethesignal,andsometakeother
actions.Whenitreceivesaterminalinterruptsignal,theshell
displaysapromptandwaitsforanothercommand.
Ifthesemethodsdonotterminatetheprogram,trystopping
theprogramwiththesuspendkey(typicallyCONTROL-Z),giving
thejobscommandtoverifythejobnumberoftheprogram,
andusingkilltoaborttheprogram.Thejobnumberisthe
numberwithinthebracketsattheleftendofthelinethatjobs
displays([1]).Thekillcommand(page395)usesTERMto
sendaterminationsignal[4]tothejobspecifiedbythejob
number,whichisprecededbyapercentsign(%1):
[4]Whentheterminalinterruptsignaldoesnotwork,usethekill(KILL)signal.Arunning
programcannotignoreakillsignal;itissuretoaborttheprogram(page395).
$bigjob
^Z
[1]+Stoppedbigjob
$jobs
[1]+Stoppedbigjob
$kill-TERM%1
$RETURN
[1]+Killedbigjob
Thekillcommandreturnsaprompt;pressRETURNagaintosee
theconfirmationmessage.Formoreinformationonjobcontrol,
referto"RunningaProgramintheBackground"onpage219.
KillingajobthatisrunningunderaGUIisstraightforward.At
theupper-rightcornerofmostwindowsisabuttonwithanXon
it(theclosebuttoninFigure4-8onpage89).Movethemouse
pointersothatitstipisovertheX.Ifyouleavethemouse
stationaryforamoment,instructionsonhowtokillthewindow
appear.WiththemousepointerovertheX,killthewindowby
clickingtheleftmousebutton.Youmayneedtoclickseveral
times.
Repeating/EditingCommandLines
Torepeatapreviouslygivencommand,presstheUPARROW
key.Eachtimeyoupressit,theshelldisplaysanearlier
commandline.Toreexecutethedisplayedcommandline,press
RETURN.PressDOWNARROWtobrowsethroughthecommand
linesintheotherdirection.
TheRIGHTandLEFTARROWkeysmovethecursorbackand
forthalongthedisplayedcommandline.Atanypointalongthe
commandline,youcanaddcharactersbytypingthem.Usethe
erasekeytoremovecharactersfromthecommandline.
Forinformationaboutmorecomplexcommandlineediting,see
page304.
ChangingtheInputFocus
Whenyoutypeonthekeyboard,thewindowmanager(page121)directsthe
charactersyoutypesomewhere,usuallytoawindow.Theactivewindow(the
windowacceptinginputfromthekeyboard)issaidtohavetheinputfocus.
Dependingonhowyousetupyouraccount,youcanusethemouseinoneof
threewaystochangetheinputfocus(youcanalsousethekeyboard;seepage
90):
Click-to-focus(explicitfocus)Givestheinputfocustoawindowwhenyou
clickthewindow.Thatwindowcontinuestoacceptinputfromthekeyboard
regardlessofthepositionofthemousepointer.Thewindowlosesthefocus
whenyouclickanotherwindow.Althoughclickingthemiddleortheright
mousebuttonalsoactivatesawindow,useonlytheleftmousebuttonfor
thispurpose;otherbuttonsmayhaveunexpectedeffectswhenyouuse
themtoactivateawindow.
Focus-follows-mouse(sloppyfocus,pointtogivefocus,orenter-only)
Givestheinputfocustoawindowwhenyoumovethemousepointeronto
thewindow.Thatwindowmaintainstheinputfocusuntilyoumovethe
mousepointerontoanotherwindow,atwhichpointthenewwindowgets
thefocus.Specifically,whenyoumovethemousepointeroffawindowand
ontotherootwindow,thewindowthathadthefocusdoesnotloseit.
Focus-under-mouseSameasfocus-follows-mouse(KDE).
Focus-strictly-under-mouse(enter-exit)Givestheinputfocustoa
windowwhenyoumovethemousepointerontothewindow.Thatwindow
maintainstheinputfocusuntilyoumovethemousepointeroffthewindow
withthefocus,atwhichpointnowindowhasthefocus.Specifically,when
youmovethemousepointeroffawindowandontotherootwindow,the
windowthathadthefocuslosesit,andinputfromthekeyboardislost.
GNOME
UnderGNOMEselectSystem:Preferences Windows(RHEL
usesApplications:Preferences Windows)tochangethe
focuspolicy.PutamarkinthecheckboxnexttoSelect
windowswhenthemousemovesoverthemtoselectthe
focus-follows-mousepolicy.Whenthereisnomarkinthischeck
box,click-to-focusisineffect.ClickClose.
KDE
UnderKDEusetheKDEControlCentertochangethefocus
policy:SelectMainmenu:ControlCenter;fromtheKDE
ControlCenterselectDesktop WindowBehaviorand
choosethedesiredfocuspolicy.ClickApply.
Todeterminewhichwindowhastheinputfocus,comparethe
windowborders.Thebordercoloroftheactivewindowis
differentfromtheothersor,onamonochromedisplay,is
darker.Anotherindicationthatawindowisactiveisthatthe
keyboardcursorisasolidrectanglethere;inwindowsthatare
notactive,thecursorisanoutlineofarectangle.
Usethefollowingteststodeterminewhichkeyboardfocus
methodyouareusing.Ifyoupositionthemousepointerina
windowandthatwindowdoesnotgettheinputfocus,your
windowmanagerisconfiguredtousetheclick-to-focusmethod.
Iftheborderofthewindowchanges,youareusingthefocus-
follows-mouse/focus-under-mouseorfocus-strictly-under-
mousemethod.Todeterminewhichofthelattermethodsyou
areusing,starttypingsomething,withthemousepointer
positionedontheactivewindow.Thenmovethemousepointer
overtherootwindowandcontinuetyping.Ifcharacters
continuetoappearwithinthewindow,youareusingfocus-
follows-mouse/focus-under-mouse.Otherwise,youareusing
focus-strictly-under-mouse.
ChangingtheResolutionoftheDisplay
TheXserver(thebasisfortheLinuxgraphicalinterface,see
page234)startsataspecificdisplayresolutionandcolordepth.
Althoughyoucanchangethecolordepthonlywhenyoustart
anXserver,youcanchangetheresolutionwhiletheXserveris
running.Thenumberofresolutionsavailabledependsbothon
thedisplayhardwareandontheconfigurationoftheXserver
(seepage70fordetails).Manyusersprefertodomostoftheir
workatahigherresolutionbutmightwanttoswitchtoalower
resolutionforsometasks,suchasplayinggames.Youcan
switchbetweendifferentdisplayresolutionsbypressingeither
CONTROL-ALT-KEYPAD-+orCONTROL-ALT-KEYPAD-,usingthe+
andonthekeyboard'snumerickeypad.
Changingtoalowerresolutionhastheeffectofzoominginon
thedisplay;asaresult,youmaynolongerbeabletoviewthe
entireworkspaceatonce.Youcanscrollthedisplaybypushing
themousepointeragainsttheedgeofthescreen.
TheWindowManager
Awindowmanagertheprogramthatcontrolsthelookandfeel
ofthebasicGUIrunsunderadesktopmanager(typicallyKDEor
GNOME)andcontrolsallaspectsofthewindowsintheX
WindowSystemenvironment.Thewindowmanagerdefinesthe
appearanceofthewindowsonthedesktopandcontrolshow
youoperateandpositionthem:open,close,move,resize,
iconify,andsoon.Itmayalsohandlesomesession
managementfunctions,suchashowasessionispaused,
resumed,restarted,orended(page94).
Awindowmanagercontrolswindowdecorationsthatis,the
titlebarandborderofawindow.Asidefromtheaesthetic
aspectsofchangingwindowdecorations,youcanaltertheir
functionalitybymodifyingthenumberandplacementofbuttons
onthetitlebar.
Thewindowmanagertakescareofwindowmanipulationsothat
theclientprogramsdonotneedto.Thissetupisverydifferent
fromthatofmanyotheroperatingsystems,andthewaythat
GNOMEandKDEdealwithwindowmanagersisdifferentfrom
howotherdesktopenvironmentswork.Windowmanagersdo
morethansimplymanagewindowstheyprovideauseful,good-
looking,graphicalshelltoworkfrom.Theiropendesignallows
userstodefinetheirownpolicydowntothefinedetails.
TheoreticallyGNOMEandKDEarenotdependentonany
particularwindowmanagerandcanworkwithanyofseveral
windowmanagers.Becauseoftheirflexibility,youwouldnot
seemajorpartsofthedesktopenvironmentchangeifyouwere
toswitchfromonewindowmanagertoanother.Thesedesktop
managerscollaboratewiththewindowmanagertomakeyour
workenvironmentintuitiveandeasytouse.Althoughthe
desktopmanagerdoesnotcontrolwindowplacement,itdoes
getinformationfromthewindowmanageraboutwindow
placement.
RedHatLinuxWindowManagers
Metacity,thedefaultwindowmanagerforGNOME,provides
windowmanagementandstartsmanycomponentsthrough
GNOMEpanelcommands.Italsocommunicateswithand
facilitatesaccesstoothercomponentsintheenvironment.The
kwinwindowmanageristhedefaultwindowmanagerforKDE.
UsingthestandardXlibraries,programmershavecreatedother
windowmanagersincludingblackbox,fluxbox,wmx,and
WindowMaker.UnderFEDORAyoucanuseyum(page478)to
installanyofthesepackages.
UsingaWindowManagerWithoutaDesktop
Manager
Itisinterestingtoseeexactlywherethelinethatseparatesthe
windowmanagerandthedesktopmanagerfalls.Towardthis
end,youcanruntheFailsafeTerminalfromtheLoginscreen:
SpecifySession FailsafeTerminalandlogin.Youshould
seeacleanscreenwithanundecoratedwindowrunningxterm.
Youcangivecommandsfromthiswindowtoopenother
windows.Tryxeyes,xterm,andxclock.Givethecommandexitto
returntotheLoginscreen.
ChapterSummary
Aswithmanyoperatingsystems,youraccesstoaLinuxsystem
isauthorizedwhenyoulogin.Youenteryourusernameonthe
Loginscreen,followedbyyourpassword.Youcanchangeyour
passwordanytimewhileyouareloggedin.Chooseapassword
thatisdifficulttoguessandthatconformstothecriteria
imposedbytheutilitythatchangesyourpassword.
Thesystemadministratorisresponsibleformaintainingthe
system.Onasingle-usersystem,youarethesystem
administrator.Onasmall,multiusersystem,youoranother
usermayactasthesystemadministrator,orthisjobmaybe
shared.Onalarge,multiusersystemornetworkofsystems,
thereisfrequentlyafull-timesystemadministrator.Whenextra
privilegesarerequiredtoperformcertainsystemtasks,the
systemadministratorlogsinastherootuserbyenteringthe
usernamerootandtherootpassword;thisuseriscalled
Superuseroradministrator.Onamultiusersystem,several
trustedusersmaybegiventherootpassword.
DonotworkasSuperuserasamatterofcourse.Whenyou
havetodosomethingthatrequiresSuperuserprivileges,work
asSuperuserforonlyaslongasabsolutelynecessary;revertto
workingasyourselfassoonaspossible.
Understandingthedesktopanditscomponentsisessentialto
gettingthemostoutofthesystem.TheMainpaneloffersa
convenientwaytolaunchapplications,eitherbyclickingicons
orbyusingtheMainmenu.TheMainmenuisamultilevelmenu
thatyoucanusetomaintainthesystemandtostartmanyof
themostcommonapplicationsonthesystem.Awindowisthe
graphicalmanifestationofanapplication.Youcancontrolits
size,location,andappearancebyclickingbuttonsonthe
window'stitlebar.Aterminalemulatorallowsyoutousethe
Linuxcommandlineinterfacefromagraphicalenvironment.
Youcanuseaterminalemulatortolaunchbothtextualand
graphicalprograms.
Konquerorisamultipurposetooloneofthemostimportanton
thedesktop.Youcanuseittorunprograms,browsetheWeb,
andmanagefiles.Konqueroristransparenttothenetwork:You
canworkwithlocalorremotefilesandnotbeawareofthe
difference.Konqueror'spowerderivesfromtheseamless
integrationofitsfunctions.
TheKDEControlCenterprovidesawayofsettingandchanging
manycharacteristicsofKDEandkwin,theKDEwindow
manager.UsingtheKDEControlCenter,youcancontrolWeb
andfilebrowsingwithKonqueror,thelookandfeelofyour
desktop,thesoundcomponentofthesystem,networkaspects
ofthedesktop,andpersonalizationofthedesktop,including
optionsthatmakeiteasierforpeoplewithspecialneedstouse.
ForSuperuser,theKDEControlCentercontainsasystem
administrationmodule.
Themanutilityprovidesonlinedocumentationforsystem
utilities.ThisutilityishelpfulbothtonewLinuxusersandto
experienceduserswhomustoftendelveintothesystem
documentationforinformationonthefinerpointsofautility's
behavior.Theinfoutilityhelpsthebeginnerandtheexpertalike.
Itincludesatutorialonitsuseanddocumentationonmany
Linuxutilities.
Exercises
1.
Thesystemdisplaysthefollowingmessagewhenyouattempttologinwithan
incorrectusernameoranincorrectpassword:
Incorrectusernameorpassword.Lettersmustbetypedinthecorrect
case.
Thismessagedoesnotindicatewhetheryourusername,yourpassword,orboth
areinvalid.Whydoesitnotrevealthisinformation?
2.
Givethreeexamplesofpoorpasswordchoices.Whatiswrongwitheach?Include
onethatistooshort.Givetheerrormessagedisplayedbythesystemineach
situation.
3. Isfidoanacceptablepassword?Giveseveralreasonswhyorwhynot.
4. Whatisacontextmenu?Howdoesacontextmenudifferfromothermenus?
5. Whatappearswhenyouright-clicktherootwindow?Howcanyouusethisobject?
6. WhereistheMainmenubutton,andwhatdoesitlooklike?Whyisitan
importanttool(KDEonly)?
7. WhatistheprimaryfunctionoftheMainmenu?
8.
Whatistheinputfocus?Whennowindowhastheinputfocus,whathappenstothe
lettersyoutypeonthekeyboard?Whichtypeofinputfocuswouldyoupreferto
workwith?Why?
9. WhatarethefunctionsofaWindowOperationsmenu?Howdoyoudisplaythis
menu?
10. WhatistheMainpanel?WhatdoesyourMainpanelshowyou,andwhatcanyou
dowithit?WhatdothePagerandTaskbarappletsdo?
11. Whataretooltips?Howaretheyuseful?
AdvancedExercises
12.
Whatchangedoesthemousepointerundergowhenyoumoveittotheedgeofa
window?Whathappenswhenyouright-clickanddragthemousepointerwhenit
lookslikethis?Repeatthisexperimentwiththemousepointeratthecornerofa
window.
13.
Trytheexperimentdescribedin"UsingaWindowManagerWithoutaDesktop
Manager"onpage122.Whatismissingfromthescreen?Basedonlyonwhatyou
see,describewhatawindowmanagerdoes.Howdoesadesktopmanagermakeit
easiertoworkwithaGUI?
14. Whenthecharactersyoutypedonotappearonthescreen,whatmightbewrong?
Howcanyoufixthisproblem?
15. WhathappenswhenyourunvimfromtheRunCommandwindowwithout
specifyingthatitberuninaterminal?Wheredoestheoutputgo?
16.
Theexampleonpage105showsthatthemanpagesforwriteappearinsections1
and2ofthesystemmanual.Explainhowyoucanusemantodeterminewhich
sectionsofthesystemmanualcontainamanualpagewithagivenname.
17. HowmanymanpagesareintheDevicessubsectionofthesystemmanual?(Hint:
DevicesisasubsectionofSpecialFiles.)
5.TheLinuxUtilities
INTHISCHAPTER
SpecialCharacters 126
BasicUtilities 127
lessIsmore:DisplayaTextFileOneScreenataTime 128
WorkingwithFiles 129
lpr:PrintsaFile 131
|(Pipe):CommunicatesBetweenProcesses 136
CompressingandArchivingFiles 139
ObtainingUserandSystemInformation 146
Tutorial:CreatingandEditingaFilewithvim 152
WhenLinusTorvaldsintroducedLinuxandforalongtime
thereafter,Linuxdidnothaveagraphicaluserinterface(GUI):
Itranoncharacter-basedterminalsonly.Allthetoolsranfrom
acommandline.TodaytheLinuxGUIisimportantbutmany
peopleespeciallysystemadministratorsrunmanycommandline
programs.Commandlineutilitiesareoftenfaster,more
powerful,ormorecompletethantheirGUIcounterparts.
SometimesthereisnoGUIcounterparttoatextualutility;
somepeoplejustpreferthehands-onfeelingofthecommand
line.
Whenyouworkwithacommandlineinterface,youareworking
withashell(Chapters7,9,and28).Beforeyoustartworking
withashell,itisimportantthatyouunderstandsomething
aboutthecharactersthatarespecialtotheshell,sothis
chapterstartswithadiscussionofspecialcharacters.The
chapterthendescribesfivebasicutilities:ls,cat,rm,less,and
hostname.Itcontinuesbydescribingseveralotherfile
manipulationutilitiesaswellasutilitiesthatfindoutwhois
loggedin;thatcommunicatewithotherusers;thatprint,
compress,anddecompressfiles;andthatpackandunpack
archivefiles.
Tip:Runtheseutilitiesfromacommand
line
Thischapterdescribescommandline,ortextual,
utilities.Youcanexperimentwiththeseutilitiesfrom
aterminal,aterminalemulatorwithinaGUI(page
93),oravirtualconsole(page113).
SpecialCharacters
Specialcharacters,whichhaveaspecialmeaningtotheshell,
arediscussedin"FilenameGeneration/PathnameExpansion"on
page221.Thesecharactersarementionedheresothatyoucan
avoidaccidentallyusingthemasregularcharactersuntilyou
understandhowtheshellinterpretsthem.Forexample,itis
besttoavoidusinganyofthefollowingcharactersinafilename
(eventhoughemacsandsomeotherprogramsdo)becausethey
makethefilehardertoreferenceonthecommandline:
&;|*?'"'[]()$<>{}#/\!~
Whitespace
Althoughnotconsideredspecialcharacters,RETURN,SPACE,
andTABalsohavespecialmeaningstotheshell.RETURN
usuallyendsacommandlineandinitiatesexecutionofa
command.TheSPACEandTABcharactersseparateelementson
thecommandlineandarecollectivelyknownaswhitespaceor
blanks.
Quotingspecialcharacters
Ifyouneedtouseacharacterthathasaspecialmeaningtothe
shellasaregularcharacter,youcanquote(orescape)it.When
youquoteaspecialcharacter,youkeeptheshellfromgivingit
specialmeaning.Theshelltreatsaquotedspecialcharacteras
aregularcharacter.However,aslash(/)isalwaysaseparator
inapathname,evenwhenyouquoteit.
Backslash
Toquoteacharacter,precedeitwithabackslash(\).Whentwo
ormorespecialcharactersappeartogether,youmustprecede
eachwithabackslash(forexample,youwouldenter**as
\*\*).Youcanquoteabackslashjustasyouwouldquoteany
otherspecialcharacterbyprecedingitwithabackslash(\\).
Singlequotationmarks
Anotherwayofquotingspecialcharactersistoenclosethem
betweensinglequotationmarks:'**'.Youcanquotemany
specialandregularcharactersbetweenapairofsingle
quotationmarks:'Thisisaspecialcharacter:>'.Theregular
charactersareinterpretedasusual,andtheshellalsointerprets
thespecialcharactersasregularcharacters.
Theonlywaytoquotetheerasecharacter(CONTROL-H),the
linekillcharacter(CONTROL-U),andothercontrolcharacters
(tryCONTROL-M)isbyprecedingeachwithaCONTROL-V.
Singlequotationmarksandbackslashesdonotwork.Trythe
following:
$echo'xxxxxxCONTROL-U'
$echoxxxxxxCONTROL-VCONTROL-U
Optional
AlthoughyoucannotseetheCONTROL-Udisplayedbythesecondofthe
precedingpairofcommands,itisthere.Thefollowingcommandsendsthe
outputofecho(page137)throughapipe(page136)tood(seetheodmanpage)
todisplayCONTROL-Uasoctal25(025):
$echoxxxxxxCONTROL-VCONTROL-U|od-c
0000000xxxxxx025\n
0000010
The\nistheNEWLINEcharacterthatechosendsattheendofitsoutput.
BasicUtilities
OneoftheimportantadvantagesofLinuxisthatitcomeswith
thousandsofutilitiesthatperformmyriadfunctions.Youwill
useutilitieswheneveryouworkwithLinux,whetheryouuse
themdirectlybynamefromthecommandlineorindirectlyfrom
amenuoricon.Thefollowingsectionsdiscusssomeofthemost
basicandimportantutilities;theseutilitiesareavailablefroma
character-basedinterface.Someofthemoreimportantutilities
arealsoavailablefromaGUI;othersareavailableonlyfroma
GUI.
Folder
Thetermdirectoryisusedextensivelyinthenextsections.A
directoryisaresourcethatcanholdfiles.Onotheroperating
systems,includingWindowsandMacintosh,andfrequently
whenspeakingaboutaLinuxGUI,adirectoryisreferredtoasa
folder.Thatisagoodanalogy:Atraditionalmanilafolderholds
filesjustasadirectorydoes.
Tip:Inthischapteryouworkinyour
homedirectory
Whenyouloginonthesystem,youareworkingin
yourhomedirectory.Inthischapterthatistheonly
directoryyouuse:Allthefilesyoucreateinthis
chapterareinyourhomedirectory.Chapter6goes
intomoredetailaboutdirectories.
ls:ListstheNamesofFiles
Usingtheeditorofyourchoice,createasmallfilenamed
practice.(Atutorialonthevimeditorappearsonpage152.)
Afterexitingfromtheeditor,youcanusethels(list)utilityto
displayalistofthenamesofthefilesinyourhomedirectory.In
thefirstcommandinFigure5-1(nextpage),lsliststhenameof
thepracticefile.(Youmayalsoseefilesthesystemora
programcreatedautomatically.)Subsequentcommandsin
Figure5-1displaythecontentsofthefileandremovethefile.
Thesecommandsaredescribednext.
Figure5-1.Usingls,cat,andrmonthefilenamed
practice
$ls
practice
$catpractice
ThisisasmallfilethatIcreated
withatexteditor.
$rmpractice
$ls
$catpractice
cat:practice:Nosuchfileordirectory
$
cat:DisplaysaTextFile
Thecatutilitydisplaysthecontentsofatextfile.Thenameof
thecommandisderivedfromcatenate,whichmeanstojoin
together,oneaftertheother.(Figure7-8onpage212shows
howtousecattostringtogetherthecontentsofthreefiles.)
Aconvenientwaytodisplaythecontentsofafiletothescreen
isbygivingthecommandcat,followedbyaSPACEandthe
filename.Figure5-1showscatdisplayingthecontentsof
practice.Thisfigureshowsthedifferencebetweenthelsand
catutilities:Thelsutilitydisplaysthenameofafile,whereascat
displaysthecontentsofafile.
rm:DeletesaFile
Therm(remove)utilitydeletesafile.Figure5-1showsrm
deletingthefilenamedpractice.Afterrmdeletesthefile,lsand
catshowthatpracticeisnolongerinthedirectory.Thelsutility
doesnotlistitsfilename,andcatsaysthatnosuchfileexists.
Usermcarefully.
Tip:Asaferwayofremovingfiles
Youcanusetheinteractiveformofrmtomakesure
thatyoudeleteonlythefile(s)youintendtodelete.
Whenyoufollowrmwiththeioption(seepage105
foratiponoptions)andthenameofthefileyou
wanttodelete,rmdisplaysthenameofthefileand
thenwaitsforyoutorespondwithy(yes)beforeit
deletesthefile.Itdoesnotdeletethefileifyou
respondwithastringthatdoesnotbeginwithy.
Theioptionissetupbydefaultfortherootuser
underRedHatLinux:
$rm-itoollist
rm:removeregularfile'toollist'?y
Optional:Youcancreateanalias(page318)for
rmiandputitinyourstartupfile(page170)sothat
rmalwaysrunsininteractivemode.
lessIsmore:DisplayaTextFileOneScreenata
Time
Pagers
Whenyouwanttoviewafilethatislongerthanonescreen,
youcanuseeitherthelessutilityorthemoreutility.Eachof
theseutilitiespausesafterdisplayingascreenoftext.Because
theseutilitiesshowonepageatatime,theyarecalledpagers.
Althoughlessandmoreareverysimilar,theyhavesubtle
differences.Attheendofthefile,forexample,lessdisplaysan
EOF(endoffile)messageandwaitsforyoutopressqbefore
returningyoutotheshell.Incontrast,morereturnsyoudirectly
totheshell.InbothutilitiesyoucanpresshtodisplayaHelp
screenthatlistscommandsyoucanusewhilepagingthrougha
file.Givethecommandslesspracticeandmorepracticein
placeofthecatcommandinFigure5-1toseehowthese
commandswork.Usethecommandless/etc/termcap
insteadifyouwanttoexperimentwithalongerfile.Refertothe
lessmanpageformoreinformation.
hostname:DisplaystheSystemName
Thehostnameutilitydisplaysthenameofthesystemyouare
workingon.Usethisutilityifyouarenotsurethatyouare
loggedinontherightmachine.
$hostname
bravo.example.com
WorkingwithFiles
Thissectiondescribesutilitiesthatcopy,move,print,search
through,display,sort,andcomparefiles.
Tip:Filenamecompletion
Afteryouenteroneormorelettersofafilename
(followingacommand)onacommandline,press
TABandtheBourneAgainShellwillcompleteas
muchofthefilenameasitcan.Whenonlyone
filenamestartswiththecharactersyouentered,the
shellcompletesthefilenameandplacesaSPACE
afterit.Youcankeeptypingoryoucanpress
RETURNtoexecutethecommandatthispoint.When
thecharactersyouentereddonotuniquelyidentifya
filename,theshellcompleteswhatitcanandwaits
formoreinput.WhenpressingTABdoesnotchange
thedisplay,pressTABagaintodisplayalistof
possiblecompletions.Formoreinformationreferto
"PathnameCompletion"onpage314.
cp:CopiesaFile
Thecp(copy)utility(Figure5-2)makesacopyofafile.This
utilitycancopyanyfile,includingtextandexecutableprogram
(binary)files.Youcanusecptomakeabackupcopyofafileor
acopytoexperimentwith.
Figure5-2.cpcopiesafile
$ls
memo
$cpmemomemo.copy
$ls
memomemo.copy
Thecpcommandlineusesthefollowingsyntaxtospecifysource
anddestinationfiles:
cpsource-filedestination-file
Thesource-fileisthenameofthefilethatcpwillcopy.The
destination-fileisthenamethatcpassignstotheresulting
(new)copyofthefile.
ThecpcommandlineinFigure5-2copiesthefilenamedmemo
tomemo.copy.Theperiodispartofthefilenamejustanother
character.Theinitiallscommandshowsthatmemoistheonly
fileinthedirectory.Afterthecpcommand,asecondlsshows
twofilesinthedirectory,memoandmemo.copy.
Sometimesitisusefultoincorporatethedateinthenameofa
copyofafile.ThefollowingexampleincludesthedateJanuary
30(0130)inthecopiedfile:
$cpmemomemo.0130
AlthoughithasnosignificancetoLinux,thedatecanhelpyou
findaversionofafilethatyoucreatedonacertaindate.
Includingthedatecanalsohelpyouavoidoverwritingexisting
filesbyprovidingauniquefilenameeachday.Formore
informationreferto"Filenames"onpage167.
Usescp(page583)orftp(page601)whenyouneedtocopya
filefromonesystemtoanotheronacommonnetwork.
Caution:cpcandestroyafile
Ifthedestination-fileexistsbeforeyougiveacp
command,cpoverwritesit.Becausecpoverwrites
(anddestroysthecontentsof)anexisting
destination-filewithoutwarning,youmusttake
carenottocausecptooverwriteafilethatyoustill
need.Thecpi(interactive)optionpromptsyou
beforeitoverwritesafile.Seepage105foratipon
options.
Thefollowingexampleassumesthatthefilenamed
orange.2existsbeforeyougivethecpcommand.
Theuseranswersytooverwritethefile:
$cpiorangeorange.2
cp:overwrite'orange.2'?y
mv:ChangestheNameofaFile
Themv(move)utilitycanrenameafilewithoutmakingacopy
ofit.Themvcommandlinespecifiesanexistingfileandanew
filenameusingthesamesyntaxascp:
mvexisting-filenamenew-filename
ThecommandlineinFigure5-3changesthenameofthefile
memotomemo.0130.Theinitiallscommandshowsthat
memoistheonlyfileinthedirectory.Afteryougivethemv
command,memo.0130istheonlyfileinthedirectory.
Comparethisresulttothatoftheearliercpexample.
Figure5-3.mvrenamesafile
$ls
memo
$mvmemomemo.0130
$ls
memo.0130
Themvutilitycanbeusedformorethanchangingthenameof
afile.Referto"mv,cp:MoveorCopyFiles"onpage179.See
themvinfopageformoreinformation.
Caution:mvcandestroyafile
Justascpcandestroyafile,socanmv.Alsolikecp,
mvhasai(interactive)option.Seethecautionbox
labeled"cpcandestroyafile."
lpr:PrintsaFile
Thelpr(lineprinter)utilityplacesoneormorefilesinaprint
queueforprinting.Linuxprovidesprintqueuessothatonlyone
jobisprintedonagivenprinteratatime.Aqueueallows
severalpeopleorjobstosendoutputsimultaneouslytoasingle
printerwiththeexpectedresults.Onsystemsthathaveaccess
tomorethanoneprinter,youcanuselpstatptodisplayalist
ofavailableprinters.UsethePoptiontoinstructlprtoplacethe
fileinthequeueforaspecificprinterevenonethatisconnected
toanothersystemonthenetwork.Thefollowingcommand
printsthefilenamedreport:
$lprreport
Becausethiscommanddoesnotspecifyaprinter,theoutput
goestothedefaultprinter,whichistheprinterwhenyouhave
onlyoneprinter.
Thenextcommandlineprintsthesamefileontheprinter
namedmailroom:
$lpr-Pmailroomreport
Youcanseewhichjobsareintheprintqueuebygivingan
lpstatocommandorbyusingthelpqutility:
$lpq
lpisreadyandprinting
RankOwnerJobFilesTotalSize
activealex86(standardinput)954061bytes
Inthisexample,Alexhasonejobthatisbeingprinted;noother
jobsareinthequeue.Youcanusethejobnumber(86inthis
case)withthelprmutilitytoremovethejobfromtheprint
queueandstopitfromprinting:
$lprm86
Youcansendmorethanonefiletotheprinterwithasingle
command.Thefollowingcommandlineprintsthreefilesonthe
printernamedlaser1:
$lpr-Plaser105.txt108.txt12.txt
RefertoChapter14forinformationonsettingupaprinterand
definingthedefaultprinter.
grep:SearchesforaString
Thegrep[1]utilitysearchesthroughoneormorefilestosee
whetheranycontainaspecifiedstringofcharacters.Thisutility
doesnotchangethefileitsearchesbutsimplydisplayseach
linethatcontainsthestring.
[1]OriginallythenamegrepwasaplayonanedanoriginalUNIXeditor,availableonRed
HatLinuxcommand:g/re/p.Inthiscommandgstandsforglobal,reisaregular
expressiondelimitedbyslashes,andpmeansprint.
ThegrepcommandinFigure5-4searchesthroughthefile
memoforlinesthatcontainthestringcreditanddisplaysa
singlelinethatmeetsthiscriterion.Ifmemocontainedsuch
wordsasdiscredit,creditor,oraccreditation,grepwould
havedisplayedthoselinesaswellbecausetheycontainthe
stringitwassearchingfor.Thewoptioncausesgreptomatch
onlywholewords.Althoughyoudonotneedtoenclosethe
stringyouaresearchingforinsinglequotationmarks,doingso
allowsyoutoputSPACEsandspecialcharactersinthesearch
string.
Figure5-4.grepsearchesforastring
$catmemo
Helen:
InourmeetingonJune6we
discussedtheissueofcredit.
Haveyouhadanyfurtherthoughts
aboutit?
Alex
$grep'credit'memo
discussedtheissueofcredit.
Thegreputilitycandomuchmorethansearchforasimple
stringinasinglefile.RefertothegrepinfopageandAppendixA,
"RegularExpressions,"formoreinformation.
head:DisplaystheBeginningofaFile
Bydefaulttheheadutilitydisplaysthefirsttenlinesofafile.You
canuseheadtohelpyourememberwhataparticularfile
contains.Forexample,ifyouhaveafilenamedmonthsthat
liststhe12monthsoftheyearincalendarorder,onetoaline,
thenheaddisplaysJanthroughOct(Figure5-5).
Figure5-5.headdisplaysthefirsttenlinesofa
file
$catmonths
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
$headmonths
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Thisutilitycandisplayanynumberoflines,soyoucanuseitto
lookatonlythefirstlineofafile,atafullscreen,orevenmore.
Tospecifythenumberoflinesdisplayed,includeahyphen
followedbythenumberoflinesintheheadcommand.For
example,thefollowingcommanddisplaysonlythefirstlineof
months:
$head-1months
Jan
Theheadutilitycanalsodisplaypartsofafilebasedonacount
ofblocksorcharactersratherthanlines.Refertotheheadinfo
pageformoreinformation.
tail:DisplaystheEndofaFile
Thetailutilityissimilartoheadbutbydefaultdisplaysthelast
tenlinesofafile.Dependingonhowyouinvokeit,thisutility
candisplayfewerormorethantenlines,useacountofblocks
orcharactersratherthanlinestodisplaypartsofafile,and
displaylinesbeingaddedtoafilethatischanging.The
followingcommandcausestailtodisplaythelastfivelines,Aug
throughDec,ofthemonthsfileshowninFigure5-5:
$tail-5months
Aug
Sep
Oct
Nov
Dec
Youcanmonitorlinesastheyareaddedtotheendofthe
growingfilenamedlogfilewiththefollowingcommand:
$tail-flogfile
Presstheinterruptkey(usuallyCONTROL-C)tostoptailand
displaytheshellprompt.Refertothetailinfopageformore
information.
sort:DisplaysaFileinOrder
Thesortutilitydisplaysthecontentsofafileinorderbylinesbut
doesnotchangetheoriginalfile.Forexample,ifafilenamed
dayscontainsthenameofeachdayoftheweekincalendar
order,eachonaseparateline,thensortdisplaysthefilein
alphabeticalorder(Figure5-6).
Figure5-6.sortdisplaysthelinesofafileinorder
$catdays
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
$sortdays
Friday
Monday
Saturday
Sunday
Thursday
Tuesday
Wednesday
Thesortutilityisusefulforputtinglistsinorder.Theuoption
generatesasortedlistinwhicheachlineisunique(no
duplicates).Thenoptionputsalistofnumbersinorder.Refer
tothesortinfopageformoreinformation.
uniq:RemovesDuplicateLinesfromaFile
Theuniq(unique)utilitydisplaysafile,skippingadjacent
duplicatelines,butdoesnotchangetheoriginalfile.Ifafile
containsalistofnamesandhastwosuccessiveentriesforthe
sameperson,uniqskipstheextraline(Figure5-7).
Figure5-7.uniqremovesduplicatelines
$catdups
Cathy
Fred
Joe
John
Mary
Mary
Paula
$uniqdups
Cathy
Fred
Joe
John
Mary
Paula
Ifafileissortedbeforeitisprocessedbyuniq,thisutility
ensuresthatnotwolinesinthefilearethesame.(Ofcourse,
sortcandothatallbyitselfwiththeuoption.)Refertotheuniq
infopageformoreinformation.
diff:ComparesTwoFiles
Thediff(difference)utilitycomparestwofilesanddisplaysalist
ofthedifferencesbetweenthem.Thisutilitydoesnotchange
eitherfile,soitisusefulwhenyouwanttocomparetwo
versionsofaletterorareportortwoversionsofthesource
codeforaprogram.
Thediffutilitywiththeu(unifiedoutputformat)optionfirst
displaystwolinesindicatingwhichofthefilesyouare
comparingwillbedenotedbyaplussign(+)andwhichbya
minussign().InFigure5-8,aminussignindicatesthe
colors.1file;aplussignindicatesthecolors.2file.
Figure5-8.diffdisplayingtheunifiedoutput
format
$diff-ucolors.1colors.2
---colors.1FriNov2515:45:322005
+++colors.2FriNov2515:24:462005
@@-1,6+1,5@@
red
+blue
green
yellow
-pink
-purple
orange
Thediffucommandbreakslong,multilinetextintohunks.
Eachhunkisprecededbyalinestartingandendingwithtwoat
signs(@@).Thishunkidentifierindicatesthestartingline
numberandthenumberoflinesfromeachfileforthishunk.In
Figure5-8,thehunkcoversthesectionofthecolors.1file
(indicatedbyaminussign)fromthefirstlinethroughthesixth
line.The+1,5thenindicatesthatthehunkcoverscolors.2
fromthefirstlinethroughthefifthline.
Followingtheseheaderlines,diffudisplayseachlineoftext
withaleadingminussign,aleadingplussign,ornothing.A
leadingminussignindicatesthatthelineoccursonlyinthefile
denotedbytheminussign.Aleadingplussignindicatesthat
thelinecomesfromthefiledenotedbytheplussign.Aline
thatbeginswithneitheraplussignnoraminussignoccursin
bothfilesinthesamelocation.Refertothediffinfopagefor
moreinformation.
file:TeststheContentsofaFile
Youcanusethefileutilitytolearnaboutthecontentsofanyfile
onaLinuxsystemwithouthavingtoopenandexaminethefile
yourself.Inthefollowingexample,filereportsthat
letter_e.bz2containsdatathatwascompressedbythebzip2
|(Pipe):CommunicatesBetweenProcesses
BecausepipesareintegraltothefunctioningofaLinuxsystem,
theyareintroducedhereforuseinexamples.Pipesarecovered
indetailbeginningonpage216.
AprocessistheexecutionofacommandbyLinux(page300).
Communicationbetweenprocessesisoneofthehallmarksof
bothUNIXandLinux.Apipe(writtenasaverticalbar,|,onthe
commandlineandappearingasasolidorbrokenverticalline
onkeyboards)providesthesimplestformofthiskindof
communication.Simplyput,apipetakestheoutputofone
utilityandsendsthatoutputasinputtoanotherutility.Using
UNIX/Linuxterminology,apipetakesstandardoutputofone
processandredirectsittobecomestandardinputofanother
process.(Formoreinformationreferto"StandardInputand
StandardOutput"onpage208.)Mostofwhataprocess
displaysonthescreenissenttostandardoutput.Ifyoudonot
redirectit,thisoutputappearsonthescreen.Usingapipe,you
canredirecttheoutputsothatitbecomesinsteadstandard
inputofanotherutility.Forexample,autilitysuchasheadcan
takeitsinputfromafilewhosenameyouspecifyonthe
commandlinefollowingthewordhead,oritcantakeitsinput
fromstandardinput.Thus,youcangivethecommandshownin
Figure5-5onpage133asfollows:
$catmonths|head
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Thenextcommanddisplaysthenumberoffilesinadirectory.
Thewc(wordcount)utilitywiththewoptiondisplaysthe
numberofwordsinitsstandardinputorinafileyouspecifyon
thecommandline:
$ls|wc-w
14
Youcanuseapipetosendoutputofaprogramtotheprinter:
$tailmonths|lpr
FourMoreUtilities
Theechoanddateutilitiesaretwoofthemostfrequentlyused
membersofthelargecollectionofLinuxutilities.Thescript
utilityrecordspartofasessioninafile,andunix2dosmakesa
copyofatextfilethatcanbereadoneitheraWindowsora
Macintoshmachine.
echo:DisplaysText
Theechoutilitycopiesanythingyouputonthecommandline
afterechotothescreen.SomeexamplesappearinFigure5-9.
Thelastexampleshowswhattheshelldoeswithanunquoted
asterisk(*)onthecommandline:Itexpandstheasteriskintoa
listoffilenamesinthedirectory.
Figure5-9.echocopiesthecommandline(butnot
thewordecho)tothescreen
$ls
memomemo.0714practice
$echoHi
Hi
$echoThisisasentence.
Thisisasentence.
$echostar:*
star:memomemo.0714practice
$
Theechoutilityisagoodtoolforlearningabouttheshelland
otherLinuxprograms.Someexamplesonpage222useechoto
illustratehowspecialcharacters,suchastheasterisk,work.
ThroughoutChapters7,9,and28,echohelpsexplainhowshell
variablesworkandhowyoucansendmessagesfromshell
scriptstothescreen.Refertotheechoinfopageformore
information.
date:DisplaystheTimeandDate
Thedateutilitydisplaysthecurrentdateandtime:
$date
ThuJan2010:24:00PST2005
Thefollowingexampleshowshowyoucanchoosetheformat
andselectthecontentsoftheoutputofdate:
$date+"%A%B%d"
ThursdayJanuary20
Refertothedateinfopageformoreinformation.
script:RecordsaShellSession
Thescriptutilityrecordsallorpartofaloginsession,including
yourinputandthesystem'sresponses.Thisutilityisusefulonly
fromcharacter-baseddevices,suchasaterminaloraterminal
emulator.Itdoescaptureasessionwithvim;however,because
vimusescontrolcharacterstopositionthecursoranddisplay
differenttypefaces,suchasbold,theoutputwillbedifficultto
readandmaynotbeuseful.Whenyoucatafilethathas
capturedavimsession,thesessionquicklypassesbeforeyour
eyes.
Bydefaultscriptcapturesthesessioninafilenamed
typescript.Touseadifferentfilename,followthescript
commandwithaSPACEandthenewfilename.Toappendtoa
file,usetheaoptionafterscriptbutbeforethefilename;
otherwisescriptoverwritesanexistingfile.Followingisasession
beingrecordedbyscript:
$script
Scriptstarted,fileistypescript
$date
ThuJan2010:28:56PST2005
$whoami
alexpts/4Jan822:15
$
$aproposmtools
mtools(1)-utilitiestoaccessDOSdisksinUnix
mtools.conf[mtools](5)-mtoolsconfigurationfiles
mtoolstest(1)-testsanddisplaystheconfiguration
$exit
Scriptdone,fileistypescript
$
Usetheexitcommandtoterminateascriptsession.Youcanthen
viewthefileyoucreatedwithcat,less,more,oraneditor.
Followingisthefilethatwascreatedbytheprecedingscript
command:
$cattypescript
ScriptstartedonThuJan2010:28:562005
$date
ThuJan2010:28:56PST2005
$whoami
alexpts/4Jan822:15
$
$aproposmtools
mtools(1)-utilitiestoaccessDOSdisksinUnix
mtools.conf[mtools](5)-mtoolsconfigurationfiles
mtoolstest(1)-testsanddisplaystheconfiguration
$exit
ScriptdoneonThuJan2010:29:582005
$
Ifyouwillbeeditingthefilewithvim,emacs,oranothereditor,
youcanusedos2unixtoeliminatefromthetypescriptfilethe
^Mcharactersthatappearattheendsofthelines.Refertothe
scriptmanpageformoreinformation.
unix2dos:ConvertsLinuxandMacintoshFilesto
WindowsFormat
IfyouwanttoshareatextfilethatyoucreatedonaLinux
systemwithsomeoneonaWindowsorMacintoshsystem,you
needtoconvertthefilebeforethepersonontheothersystem
canreaditeasily.Theunix2dosutilityconvertsaLinuxtextfile
sothatitcanbereadonaWindowsorMacintoshsystem.Give
thefollowingcommandtoconvertafilenamedmemo.txt
(createdwithatexteditor)toaDOS-formatfile:
$unix2dosmemo.txt
Withoutanyoptionsunix2dosoverwritestheoriginalfile.Youcan
nowemailthefileasanattachmenttosomeoneonaWindows
orMacintoshsystem.
dos2unix
Youcanusethedos2unixutilitytoconvertWindowsorMacintosh
filessotheycanbereadonaLinuxsystem:
$dos2unixmemo.txt
Seetheunix2dosanddos2unixmanpagesformoreinformation.
YoucanalsousetrtochangeaWindowsorMacintoshtextfile
intoaLinuxtextfile.Inthefollowingexample,thedoption
causestrtoremoveRETURNs(representedby\r)asitmakesa
copyofthefile:
$catmemo|tr-d'\r'>memo.txt
Thegreaterthan(>)symbolredirectsthestandardoutputoftr
tothefilenamedmemo.txt.Formoreinformationreferto
"RedirectingStandardOutput"onpage210.Convertingafile
theotherwaywithoutusingunix2dosisnotaseasy.
CompressingandArchivingFiles
Largefilesusealotofdiskspaceandtakelongerthansmaller
filestotransferfromonesystemtoanotheroveranetwork.If
youdonotneedtolookatthecontentsofalargefilevery
often,youmaywanttosaveitonaCD,DVD,oranother
mediumandremoveitfromtheharddisk.Ifyouhavea
continuingneedforthefile,retrievingacopyfromaCDmaybe
inconvenient.Toreducetheamountofdiskspaceyouuse
withoutremovingthefileentirely,youcancompressthefile
withoutlosinganyoftheinformationitholds.Similarlyasingle
archiveofseveralfilespackedintoalargerfileiseasierto
manipulate,upload,download,andemailthanmultiplefiles.
Youmayfrequentlydownloadcompressed,archivedfilesfrom
theInternet.Theutilitiesdescribedinthissectioncompressand
decompressfilesandpackandunpackarchives.
bzip2:CompressesaFile
Thebzip2utilitycompressesafilebyanalyzingitandrecodingit
moreefficiently.Thenewversionofthefilelookscompletely
different.Infact,becausethenewfilecontainsmany
nonprintingcharacters,youcannotviewitdirectly.Thebzip2
utilityworksparticularlywellonfilesthatcontainalotof
repeatedinformation,suchastextandimagedata,although
mostimagedataisalreadyinacompressedformat.
Thefollowingexampleshowsaboringfile.Eachofthe8,000
linesoftheletter_efilecontains72e'sandaNEWLINE
characterthatmarkstheendoftheline.Thefileoccupiesmore
thanhalfamegabyteofdiskstorage.
$ls-l
-rw-rw-r--1samsam584000Mar122:31letter_e
Thel(long)optioncauseslstodisplaymoreinformationabout
afile.Hereitshowsthatletter_eis584,000byteslong.The
verbose(orv)optioncausesbzip2toreporthowmuchitwas
abletoreducethesizeofthefile.Inthiscase,itshrankthefile
by99.99percent:
$bzip2-vletter_e
letter_e:11680.00:1,0.001bits/byte,99.99%saved,584000in,50out.
$ls-l
-rw-rw-r--1samsam50Mar122:31letter_e.bz2
.bz2filenameextension
Nowthefileisonly50byteslong.Thebzip2utilityalsorenamed
thefile,appending.bz2toitsname.Thisnamingconvention
remindsyouthatthefileiscompressed;youwouldnotwantto
displayorprintit,forexample,withoutfirstdecompressingit.
Thebzip2utilitydoesnotchangethemodificationdate
associatedwiththefile,eventhoughitcompletelychangesthe
file'scontents.
Inthefollowing,morerealisticexample,thefilezach.jpg
containsacomputergraphicsimage:
$ls-l
-rw-r--r--1samsam33287Mar122:40zach.jpg
Thebzip2utilitycanreducethesizeofthefilebyonly28
percentbecausetheimageisalreadyinacompressedformat:
$bzip2-vzach.jpg
zach.jpg:1.391:1,5.749bits/byte,28.13%saved,33287in,23922out.
$ls-l
-rw-r--r--1samsam23922Mar122:40zach.jpg.bz2
Refertothebzip2manpage,www.bzip.org,andtheBzip2mini-
HOWTO(seepage109)formoreinformation.
bunzip2andbzcat:DecompressaFile
Youcanusethebunzip2utilitytorestoreafilethathasbeen
compressedwithbzip2:
$bunzip2letter_e.bz2
$ls-l
-rw-rw-r--1samsam584000Mar122:31letter_e
$bunzip2zach.jpg.bz2
$ls-l
-rw-r--r--1samsam33287Mar122:40zach.jpg
Thebzcatutilitydisplaysafilethathasbeencompressedwith
bzip2.Theequivalentofcatfor.bz2files,bzcatdecompressesthe
compresseddataanddisplaysthecontentsofthe
decompressedfile.Likecat,bzcatdoesnotchangethesource
file.Thepipeinthefollowingexampleredirectstheoutputof
bzcatsothatinsteadofbeingdisplayedonthescreenitbecomes
theinputtohead,whichdisplaysthefirsttwolinesofthefile:
$bzcatletter_e.bz2|head-2
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
Afterbzcatisrun,thecontentsofletter_e.bzisunchanged;the
fileisstillstoredonthediskincompressedform.
bzip2recover
Thebzip2recoverutilitysupportslimiteddatarecoveryfrommedia
errors.Givethecommandbzip2recoverfollowedbythename
ofthecompressed,corruptedfilefromwhichyouwanttotryto
recoverdata.
gzip:CompressesaFile
gunzipandzcat
Thegzip(GNUzip)utilityisolderandlessefficientthanbzip2.Its
flagsandoperationareverysimilartothoseofbzip2.Afile
compressedbygzipismarkedbya.gzfilenameextension.
Linuxstoresmanualpagesingzipformattosavediskspace;
likewise,filesyoudownloadfromtheInternetarefrequentlyin
gzipformat.Usegzip,gunzip,andzcatjustasyouwouldusebzip2,
bunzip2,andbzcat,respectively.Refertothegzipinfopagefor
moreinformation.
compress
Thecompressutilitycanalsocompressfiles,albeitnotaswellas
gzip.Thisutilitymarksafileithascompressedbyadding.Zto
itsname.
Tip:gzipversuszip
Donotconfusegzipandgunzipwiththezipandunzip
utilities.Theselasttwoareusedtopackandunpack
ziparchivescontainingseveralfilescompressedinto
asinglefilethathasbeenimportedfromorisbeing
exportedtoasystemrunningWindows.Thezip
utilityconstructsaziparchive,whereasunzipunpacks
ziparchives.Thezipandunziputilitiesarecompatible
withPKZIP,aWindowsprogramthatcompresses
andarchivesfiles.
tar:PacksandUnpacksArchives
Thetarutilityperformsmanyfunctions.Itsnameisshortfor
tapearchive,asitsoriginalfunctionwastocreateandread
archiveandbackuptapes.Todayitisusedtocreateasinglefile
(calledatarfile,archive,ortarball)frommultiplefilesor
directoryhierarchiesandtoextractfilesfromatarfile.Thecpio
utilityperformsasimilarfunction.
Inthefollowingexample,thefirstlsshowstheexistenceand
sizesofthefilesg,b,andd.Nexttarusesthec(create),v
(verbose),andf(writetoorreadfromafile)options[2]to
createanarchivenamedall.tarfromthesefiles.Eachline
outputdisplaysthenameofthefiletarisappendingtothe
archiveitiscreating.
[2]AlthoughtheoriginalUNIXtardidnotusealeadinghyphentoindicateanoptionon
thecommandline,itnowacceptshyphens.TheGNUtardescribedherewillaccepttar
commandswithorwithoutaleadinghyphen.Thisbookusesthehyphenforconsistency
withmostotherutilities.
Thetarutilityaddsoverheadwhenitcreatesanarchive.The
nextcommandshowsthatthearchivefileall.taroccupies
about9,700bytes,whereasthesumofthesizesofthethree
filesisabout6,000bytes.Thisoverheadismoreappreciableon
smallerfiles,suchastheonesinthisexample.
$ls-lgbd
-rw-r--r--1jennyjenny1302Aug2014:16g
-rw-r--r--1jennyother1178Aug2014:16b
-rw-r--r--1jennyjenny3783Aug2014:17d
$tar-cvfall.targbd
g
b
d
$ls-lall.tar
-rw-r--r--1jennyjenny9728Aug2014:17all.tar
$tar-tvfall.tar
-rw-r--r--jenny/jenny13022005-08-2014:16g
-rw-r--r--jenny/other11782005-08-2014:16b
-rw-r--r--jenny/jenny37832005-08-2014:17d
Thefinalcommandintheprecedingexampleusesthetoption
todisplayatableofcontentsforthearchive.Usexinsteadoft
toextractfilesfromatararchive.Omitthevoptionifyouwant
tartodoitsworksilently.
Youcanusebzip2,compress,orgziptocompresstarfiles,making
themeasiertostoreandhandle.Manyfilesyoudownloadfrom
theInternetwillalreadybeinoneoftheseformats.Filesthat
havebeenprocessedbytarandcompressedbybzip2frequently
haveafilenameextensionof.tar.bz2or.tbz.Thoseprocessed
bytarandgziphaveanextensionof.tar.gzor.tz,whereasfiles
processedbytarandcompressuse.tar.Zastheextension.
Youcanunpackatarredandgzippedfileintwosteps.(Follow
thesameprocedureifthefilewascompressedbybzip2,butuse
bunzip2insteadofgunzip.)Thenextexampleshowshowto
unpacktheGNUmakeutilityafterithasbeendownloaded
(ftp.gnu.org/pub/gnu/make/make-3.80.tar.gz):
$ls-lmak*
-rw-rw-r--1samsam1211924Jan2011:49make-3.80.tar.gz
$gunzipmak*
$ls-lmak*
-rw-rw-r--1samsam4823040Jan2011:49make-3.80.tar
$tar-xvfmak*
make-3.80/
make-3.80/po/
make-3.80/po/Makefile.in.in
...
make-3.80/tests/run_make_tests.pl
make-3.80/tests/test_driver.pl
Thefirstcommandliststhedownloadedtarredandgzippedfile:
make-3.80.tar.gz(about1.2megabytes).Theasterisk(*)in
thefilenamematchesanycharactersinanyfilenames(page
222),soyouendupwithalistoffileswhosenamesbeginwith
mak;inthiscasethereisonlyone.Usinganasterisksaves
typingandcanimproveaccuracywithlongfilenames.Thegunzip
commanddecompressesthefileandyieldsmake-3.80.tar(no
.gzextension),whichisabout4.8megabytes.Thetarcommand
createsthemake-3.80directoryintheworkingdirectoryand
unpacksthefilesintoit.
$ls-ldmak*
drwxrwxr-x8samsam4096Oct32002make-3.80
-rw-rw-r--1samsam4823040Jan2011:49make-3.80.tar
$ls-lmake-3.80
total1816
-rw-r--r--1samsam24687Oct32002ABOUT-NLS
-rw-r--r--1samsam1554Jul82002AUTHORS
-rw-r--r--1samsam18043Dec101996COPYING
-rw-r--r--1samsam32922Oct32002ChangeLog
...
-rw-r--r--1samsam16520Jan212000vmsify.c
-rw-r--r--1samsam16409Aug92002vpath.c
drwxrwxr-x5samsam4096Oct32002w32
Aftertarextractsthefilesfromthearchive,theworking
directorycontainstwofileswhosenamesstartwithmak:
make-3.80.tarandmake-3.80.Thed(directory)option
causeslstodisplayonlyfileanddirectorynames,notthe
contentsofdirectoriesasitnormallydoes.Thefinallscommand
showsthefilesanddirectoriesinthemake-3.80directory.
Refertothetarinfopageformoreinformation.
Caution:tar:thexoptionmayextracta
lotoffiles
Sometararchivescontainmanyfiles.Tolistthefiles
inthearchivewithoutunpackingthem,runtarwith
thetoptionandthenameofthetarfile.Insome
casesyoumaywanttocreateanewdirectory(mkdir
[page173]),movethetarfileintothatdirectory,and
expanditthere.Thatwaytheunpackedfileswillnot
minglewithyourexistingfiles,andnoconfusionwill
occur.Thisstrategyalsomakesiteasiertodelete
theextractedfiles.Sometarfilesautomatically
createanewdirectoryandputthefilesintoit.Refer
totheprecedingexample.
Caution:tar:thexoptioncanoverwrite
files
Thexoptiontotaroverwritesafilethathasthe
samefilenameasafileyouareextracting.Follow
thesuggestionintheprecedingcautionboxtoavoid
overwritingfiles.
Optional
Youcancombinethegunzipandtarcommandsononecommandlinewithapipe
(|),whichredirectstheoutputofgunzipsothatitbecomestheinputtotar:
$gunzip-cmake-3.80.tar.gz|tar-xvf-
Thecoptioncausesgunziptosenditsoutputthroughthepipeinsteadofcreating
afile.Referto"Pipes"(page216)andgzip(page141)formoreinformation
abouthowthiscommandlineworks.
Asimplersolutionistousethezoptiontotar.Thisoptioncausestartocallgunzip
(orgzipwhenyouarecreatinganarchive)directlyandsimplifiesthepreceding
commandlineto
$tar-xvzfmake-3.80.tar.gz
Inasimilarmanner,thejoptioncallsbzip2orbunzip2.
LocatingCommands
Thewhereisandaproposutilitiescanhelpyoufindacommand
whosenameyouhaveforgottenorwhoselocationyoudonot
know.Whenmultiplecopiesofautilityorprogramarepresent,
whichtellsyouwhichcopyyouwillrun.Thelocateutilitysearches
forfilesonthelocalsystem.
whichandwhereis:LocateaUtility
WhenyougiveLinuxacommand,theshellsearchesalistof
directoriesforaprogramwiththatnameandrunsthefirstone
itfinds.Thislistofdirectoriesiscalledasearchpath.For
informationonhowtochangethesearchpath,referto"PATH:
WheretheShellLooksforPrograms"onpage292.Ifyoudonot
changethesearchpath,theshellsearchesonlyastandardset
ofdirectoriesandthenstopssearching.Otherdirectoriesonthe
systemmayalsocontainusefulutilities,however.
which
Thewhichutilitylocatesutilitiesbydisplayingthefullpathname
ofthefilefortheutility.(Chapter6containsmoreinformation
onpathnamesandthestructureoftheLinuxfilesystem.)The
localsystemmayincludeseveralcommandsthathavethesame
name.Whenyoutypethenameofacommand,theshell
searchesforthecommandinyoursearchpathandrunsthe
firstoneitfinds.Youcanfindoutwhichcopyoftheprogram
theshellwillrunbyusingwhich.Inthefollowingexample,which
reportsthelocationofthetarcommand:
$whichtar
/bin/tar
Thewhichutilitycanbehelpfulwhenacommandseemstobe
workinginunexpectedways.Byrunningwhich,youmay
discoverthatyouarerunninganonstandardversionofatoolor
adifferentonethanyouexpected.("ImportantStandard
DirectoriesandFiles"onpage176providesalistofstandard
locationsforexecutablefiles.)Forexample,iftarisnotworking
properlyandyoufindthatyouarerunning/usr/local/bin/tar
insteadof/bin/tar,youmightsuspectthatthelocalversionis
broken.
Caution:which,whereis,andbuiltin
commands
Boththewhichandwhereisutilitiesreportonlythe
namesforcommandsastheyarefoundonthedisk;
theydonotreportshellbuiltins(utilitiesthatare
builtintoashell;seepage225).Whenyouuse
whereistotrytofindwheretheechocommand(which
existsasbothautilityprogramandashellbuiltin)is
kept,yougetthefollowingresult:
$whereisecho
echo:/bin/echo/usr/share/man/man1/echo.1.gz/usr/share/man/man1p/echo.1p.
gz/usr/share/man/man3/echo.3x.gz
Thewhereisutilitydoesnotdisplaytheechobuiltin.
Eventhewhichutilityreportsthewronginformation:
$whichecho
/bin/echo
Underbashyoucanusethetypebuiltin(page927)to
determinewhetheracommandisabuiltin:
$typeecho
echoisashellbuiltin
whereis
Thewhereisutilitysearchesforfilesrelatedtoautilitybylooking
instandardlocationsinsteadofusingyoursearchpath.For
example,youcanfindthelocationsforfilesrelatedtotar:
$whereistar
tar:/bin/tar/usr/include/tar.h/usr/share/man/man1/tar.1.gz
Inthisexamplewhereisfindsthreereferencestotar:thetarutility
file,atarheaderfile,andthetarmanpage.
Tip:whichversuswhereis
Giventhenameofaprogram,whichlooksthrough
thedirectoriesinyoursearchpath,inorder,and
locatestheprogram.Ifthesearchpathincludes
morethanoneprogramwiththespecifiedname,
whichdisplaysthenameofonlythefirstone(theone
youwouldrun).
Thewhereisutilitylooksthroughalistofstandard
directoriesandworksindependentlyofyoursearch
path.Usewhereistolocateabinary(executable)file,
anymanualpages,andsourcecodeforaprogram
youspecify;whereisdisplaysallthefilesitfinds.
apropos:SearchesforaKeyword
Whenyoudonotknowthenameofthecommandyouneedto
carryoutaparticulartask,youcanuseaproposwithakeyword
tosearchforit.Thisutilitysearchesforthekeywordinthe
shortdescriptionline(thetopline)ofallmanpagesanddisplays
thosethatcontainamatch.Themanutility,whencalledwiththe
k(keyword)option,givesyouthesameoutputasapropos(itis
thesamecommand).
Thedatabaseaproposuses,namedwhatis,isnotonRedHat
Linuxsystemswhentheyarefirstinstalled,butisbuilt
automaticallybycron(page547)usingmakewhatis.(Thecron
utilityrunsthe/etc/cron.weekly/makewhatis.cronscriptto
buildthewhatisdatabase.)Ifyouturnthesystemoff
periodically(aswithalaptop),thescriptmaynotberun.If
aproposdoesnotproduceanyoutput,runthecommand
makewhatiswasroot.
Thefollowingexampleshowstheoutputofaproposwhenyoucall
itwiththewhokeyword.Theoutputincludesthenameofeach
command,thesectionofthemanualthatcontainsit,andthe
briefdescriptionfromthetopofthemanpage.Thislistincludes
theutilitythatyouneed(who)andidentifiesother,relatedtools
thatyoumightfinduseful:
$aproposwho
at.allow[at](5)-determinewhocansubmitjobsviaatorbatch
at.deny[at](5)-determinewhocansubmitjobsviaatorbatch
jwhois(1)-clientforthewhoisservice
ldapwhoami(1)-LDAPwhoami?tool
w(1)-Showwhoisloggedonandwhattheyaredoing
who(1)-showwhoisloggedon
whoami(1)-printeffectiveuserid
whatis
Thewhatisutilityissimilartoaproposbutfindsonlycomplete
wordmatchesforthenameoftheutility:
$whatiswho
who(1)-showwhoisloggedon
locate:SearchesforaFile
Thelocateutilitysearchesforfilesonthelocalsystem:
$locatemotd
/etc/motd
/lib/security/pam_motd.so
/usr/share/man/man5/motd.5.gz
Beforeyoucanuselocatetheupdatedbutilitymustbuildorupdate
thelocatedatabase.Typicallythedatabaseisupdatedoncea
daybyacronscript(page547).
Tip:Ifyouarenotonanetwork,skipthe
restofthischapter
Ifyouaretheonlyuseronasystemthatisnot
connectedtoanetwork,youmaywanttoskipthe
restofthischapter.Ifyouarenotonanetworkbut
aresetuptosendandreceiveemail,read"Email"
page152.
ObtainingUserandSystemInformation
Thissectioncoversutilitiesthatprovideinformationaboutwho
isusingthesystem,whatthoseusersaredoing,andhowthe
systemisrunning.Tofindoutwhoisusingthelocalsystem,
youcanemployoneofseveralutilitiesthatvaryinthedetails
theyprovideandtheoptionstheysupport.Theoldestutility,
who,producesalistofuserswhoareloggedinonthelocal
system,thedeviceeachpersonisusing,andthetimeeach
personloggedin.
Thewandfingerutilitiesshowmoredetail,suchaseachuser's
fullnameandthecommandlineeachuserisrunning.Youcan
usethefingerutilitytoretrieveinformationaboutuserson
remotesystemsifyourcomputerisattachedtoanetwork.
Table5-1onpage150summarizestheoutputoftheseutilities.
Table5-1.Comparisonofw,who,andfinger
Informationdisplayed w who finger
Username x x x
Terminal-lineidentification(tty) x x x
Logindayandtime x
Logindateandtime x x
Idletime x x
Programtheuserisexecuting x
Locationtheuserloggedinfrom x
CPUtimeused x
Fullname(orotherinformationfrom
/etc/passwd)x
User-suppliedvanityinformation x
Systemuptimeandloadaverage x
who:ListsUsersontheSystem
Thewhoutilitydisplaysalistofuserswhoareloggedin.In
Figure5-10thefirstcolumnthatwhodisplaysshowsthatAlex
andJennyareloggedin.(Alexisloggedinfromtwolocations.)
Thesecondcolumnshowsthedevicethateachuser'sterminal,
workstation,orterminalemulatorisconnectedto.Thethird
columnshowsthedateandtimetheuserloggedin.Anoptional
fourthcolumnshows(inparentheses)thenameofthesystem
thataremoteuserloggedinfrom;thiscolumndoesnotappear
inFigure5-10.
Figure5-10.wholistswhoisloggedin
$who
rootconsoleMar2705:00
alexpts/4Mar2712:23
alexpts/5Mar2712:33
jennypts/7Mar2608:45
Theinformationthatwhodisplaysisusefulwhenyouwantto
communicatewithauseratyourinstallation.Whentheuseris
loggedin,youcanusewrite(page150)toestablish
communicationimmediately.Ifwhodoesnotlisttheuserorif
youdonotneedtocommunicateimmediately,youcansend
emailtothatperson(page152).
Iftheoutputofwhoscrollsoffthescreen,youcanredirectthe
outputthroughapipe(|,page136)sothatitbecomesthe
inputtoless,whichdisplaystheoutputonepageatatime.You
canalsouseapipetoredirecttheoutputthroughgreptolook
foraspecificname.
Ifyouneedtofindoutwhichterminalyouareusingorwhat
timeyouloggedin,youcanusethecommandwhoami:
$whoami
alexpts/5Mar2712:33
finger:ListsUsersontheSystem
Youcanusefingertodisplayalistoftheuserswhoareloggedin
onthesystem.Inadditiontousernames,fingersupplieseach
user'sfullnamealongwithinformationaboutwhichdevicethe
user'sterminalisconnectedto,howrecentlytheusertyped
somethingonthekeyboard,whentheuserloggedin,andwhat
contactinformationisavailable.Iftheuserhasloggedinover
thenetwork,thenameoftheremotesystemisshownasthe
user'slocation.Forexample,inFigure5-11jennyandhlsare
loggedinfromtheremotesystemnamedbravo.Theasterisk
(*)infrontofthenameofHelen'sdevice(TTY)indicatesthat
shehasblockedothersfromsendingmessagesdirectlytoher
terminal(referto"mesg:DeniesorAcceptsMessages"onpage
151).
Figure5-11.fingerI:listswhoisloggedin
$finger
LoginNameTtyIdleLoginTimeOfficeOfficePhone
rootroot11:35May2408:38
alexAlexWatson/0Jun712:46(:0)
alexAlexWatson/119Jun712:47(:0)
jennJennyChen/22:24Jun205:33(bravo.example.com)
hlsHelenSimpson*/22Jun205:33(bravo.example.com)
Security:fingercanbeasecurityrisk
Onsystemswheresecurityisaconcern,thesystem
administratormaydisablefinger.Thisutilitycan
revealinformationthatcanhelpamalicioususer
breakintoasystem.
Youcanalsousefingertolearnmoreaboutanindividualby
specifyingthenameofthatuseronthecommandline.In
Figure5-12,fingerdisplaysdetailedinformationabouttheuser
namedAlex.Alexisloggedinandactivelyusingoneofhis
terminals(pts/1);hehasnotusedhisotherterminal(pts/0)
for5minutesand52seconds.Youalsolearnfromfingerthatif
youwanttosetupameetingwithAlex,youshouldcontact
Jennyatextension1693.
Figure5-12.fingerII:listsdetailsaboutoneuser
$fingeralex
Login:alexName:AlexWatson
Directory:/home/alexShell:/bin/bash
OnsinceWedJun712:46(PDT)onpts/0from:0
5minutes52secondsidle
OnsinceWedJun712:47(PDT)onpts/1frombravo
LastloginWedJun712:47(PDT)on1frombravo
NewmailreceivedWedJun713:162006(PDT)
UnreadsinceFriMay2615:322006(PDT)
Plan:
IwillbeataconferenceinHawaiiallnextweek.Ifyouneed
toseeme,contactJennyChen,x1693.
.planand.project
MostoftheinformationinFigure5-12wascollectedbyfinger
fromsystemfiles.Theinformationshownaftertheheading
Plan:,however,wassuppliedbyAlex.Thefingerutilitysearched
forafilenamed.planinAlex'shomedirectoryanddisplayedits
contents.(Filenamesthatbeginwithaperiod,suchas.plan,
arenotnormallylistedbylsandarecalledhiddenfilenames
[page170].)Youmayfindithelpfultocreatea.planfilefor
yourself;itcancontainanyinformationyouchoose,suchas
yourschedule,interests,phonenumber,oraddress.Inasimilar
manner,fingerdisplaysthecontentsofthe.projectand
.pgpkeyfilesinyourhomedirectory.IfAlexhadnotbeen
loggedin,fingerwouldhavereportedonlyhisuserinformation,
thelasttimeheloggedin,thelasttimehereadhisemail,and
hisplan.
Youcanalsousefingertodisplayauser'susername.For
example,onasystemwithausernamedHelenSimpson,you
mightknowthatHelen'slastnameisSimpsonbutmightnot
guessthatherusernameishls.Thefingerutility,whichisnot
casesensitive,cansearchforinformationonHelenusingher
firstorlastname.Thefollowingcommandsfindtheinformation
youseekaswellasinformationonotheruserswhosenames
areHelenorSimpson:
$fingerHELEN
Login:hlsName:HelenSimpson.
...
$fingersimpson
Login:hlsName:HelenSimpson.
...
Seepage360forinformationaboutusingfingeroveranetwork.
w:ListsUsersontheSystem
Thewutilitydisplaysalistoftheuserswhoareloggedin.As
discussedinthesectiononwho,theinformationthatwdisplays
isusefulwhenyouwanttocommunicatewithsomeoneatyour
installation.
ThefirstcolumninFigure5-13showsthatAlex,Jenny,and
Scottareloggedin.Thesecondcolumnshowsthedesignation
ofthedevicethateachuser'sterminalisconnectedto.The
thirdcolumnshowsthesystemthataremoteuserisloggedin
from.Thefourthcolumnshowsthetimewheneachuserlogged
in.Thefifthcolumnindicateshowlongeachuserhasbeenidle
(howmuchtimehaselapsedsincetheuserpressedakeyon
thekeyboard).Thenexttwocolumnsidentifyhowmuch
computerprocessortimeeachuserhasusedduringthislogin
sessionandonthetaskthatisrunning.Thelastcolumnshows
thecommandeachuserisrunning.
Figure5-13.Thewutility
$w
8:20amup4days,2:28,3users,loadaverage:0.04,0.04,0.00
USERTTYFROMLOGIN@IDLEJCPUPCPUWHAT
alexpts/4:05:55am13:450.15s0.07sw
alexpts/5:05:55am272:551:01bash
jennypts/7bravo5:56am13:440.51s30svim3.txt
scottpts/12bravo7:17pm1.00s0:14srun_bdgt
Thefirstlinethatthewutilitydisplaysincludesthetimeofday,
theperiodoftimethecomputerhasbeenrunning(indays,
hours,andminutes),thenumberofusersloggedin,andthe
loadaverage(howbusythesystemis).Thethreeloadaverage
numbersrepresentthenumberofjobswaitingtorun,averaged
overthepast1,5,and15minutes.Usetheuptimeutilityto
displayjustthisline.Table5-1comparesthew,who,andfinger
utilities.
CommunicatingwithOtherUsers
Theutilitiesdiscussedinthissectionexchangemessagesand
fileswithotheruserseitherinteractivelyorthroughemail.
write:SendsaMessage
Thewriteutilitysendsamessagetoanotheruserwhoislogged
in.Whenyouandanotheruserusewritetosendmessagesto
eachother,youestablishtwo-waycommunication.Initiallya
writecommand(Figure5-14)displaysabannerontheother
user'sterminal,sayingthatyouareabouttosendamessage.
Figure5-14.ThewriteutilityI
$writealex
HiAlex,areyouthere?o
Thesyntaxofawritecommandlineis
writeusername[terminal]
Theusernameistheusernameoftheuseryouwantto
communicatewith.Theterminalisanoptionaldevicename
thatisusefuliftheuserisloggedinmorethanonce.Youcan
displaytheusernamesanddevicenamesofalluserswhoare
loggedinonthelocalsystembyusingwho,w,orfinger.
Toestablishtwo-waycommunicationwithanotheruser,youand
theotherusermusteachexecutewrite,specifyingtheother's
usernameastheusername.Thewriteutilitythencopiestext,
linebyline,fromonekeyboard/displaytotheother(Figure5-
15).Sometimesithelpstoestablishaconvention,suchas
typingo(for"over")whenyouarereadyfortheotherpersonto
typeandtypingoo(for"overandout")whenyouarereadyto
endtheconversation.Whenyouwanttostopcommunicating
withtheotheruser,pressCONTROL-Datthebeginningofaline.
PressingCONTROL-Dtellswritetoquit,displaysEOF(endoffile)
ontheotheruser'sterminal,andreturnsyoutotheshell.The
otherusermustdothesame.
Figure5-15.ThewriteutilityII
$writealex
HiAlex,areyouthere?o
Messagefromalex@bravo.example.comonpts/0at16:23...
YesJenny,I'mhere.o
IftheMessagefrombannerappearsonyourscreenand
obscuressomethingyouareworkingon,pressCONTROL-Lor
CONTROL-Rtorefreshthescreenandremovethebanner.Then
youcancleanup,exitfromyourwork,andrespondtothe
personwhoiswritingtoyou.Youhavetorememberwhois
writingtoyou,however,becausethebannerwillnolonger
appearonthescreen.
mesg:DeniesorAcceptsMessages
Givethefollowingcommandwhenyoudonotwishtoreceive
messagesfromanotheruser:
$mesgn
IfAlexhadgiventhiscommandbeforeJennytriedtosendhim
amessage,Jennywouldhaveseenthefollowingmessage:
$writealex
Permissiondenied
Youcanallowmessagesagainbyenteringmesgy.Givethe
commandmesgbyitselftodisplayisy(for"yes,messagesare
allowed")orisn(for"no,messagesarenotallowed").
Email
Emailenablesyoutocommunicatewithusersonthelocal
systemand,iftheinstallationispartofanetwork,withother
usersonthenetwork.IfyouareconnectedtotheInternet,you
cancommunicateelectronicallywithusersaroundtheworld.
Emailutilitiesdifferfromwriteinthatemailutilitiescansenda
messagewhentherecipientisnotloggedin.Theseutilitiescan
alsosendthesamemessagetomorethanoneuseratatime.
ManyemailprogramsareavailableforLinux,includingthe
originalcharacter-basedmailprogram,Mozilla/Thunderbird,pine,
mailthroughemacs,KMail,andevolution.Anotherpopular
graphicalemailprogramissylpheed(sylpheed.good-day.net).
Twoprogramsareavailablethatcanmakeanyemailprogram
easiertouseandmoresecure.Theprocmailprogram
(www.procmail.org)createsandmaintainsemailserversand
mailinglists;preprocessesemailbysortingitintoappropriate
filesanddirectories;startsvariousprogramsdependingonthe
characteristicsofincomingemail;forwardsemail;andsoon.
TheGNUPrivacyGuard(GPGorGNUpg,page992)encrypts
anddecryptsemailandmakesitalmostimpossibleforan
unauthorizedpersontoread.
RefertoChapter20formoreinformationonsettingemail
clientsandservers.Seepage648forinstructionsonsettingup
KMailtosendandreceiveemail.
Networkaddresses
IfyoursystemispartofaLAN,youcangenerallysendemailto
andreceiveemailfromusersonothersystemsontheLANby
usingtheirusernames.SomeonesendingAlexemailonthe
Internetwouldneedtospecifyhisdomainname(page1030)
alongwithhisusername.Usethisaddresstosendemailtothe
authorofthisbook:mgs@sobell.com.
Tutorial:CreatingandEditingaFilewithvim
Thissectionexplainshowtostartvim,entertext,movethe
cursor,correcttext,savethefiletothedisk,andexitfromvim.
Thetutorialdiscussesthreeofthemodesofoperationofvim
andexplainshowtoswitchfromonemodetoanother.
vimtutor
Inadditiontoworkingwiththistutorial,youmaywanttotry
vim'stutor,namedvimtutor:Giveitsnameasacommandtorun
it.
Specifyingaterminal
Becausevimtakesadvantageoffeaturesthatarespecificto
variouskindsofterminals,youmusttellitwhattypeofterminal
orterminalemulatoryouareusing.Onmanysystems,and
usuallywhenyouworkonaterminalemulator,yourterminal
typeissetautomatically.Ifyouneedtospecifyyourterminal
typeexplicitly,referto"SpecifyingaTerminal"onpage984.
Startingvim
Startvimwiththefollowingcommandlinetocreateandedita
filenamedpractice:
$vimpractice
WhenyoupressRETURN,thecommandlinedisappears,andthe
screenlookssimilartotheoneshowninFigure5-16.
Figure5-16.Startingvim
[Viewfullsizeimage]
Thetildes(~)attheleftofthescreenindicatethatthefileis
empty.Theydisappearasyouaddlinesoftexttothefile.If
yourscreenlookslikeadistortedversionoftheoneshownin
Figure5-16,yourterminaltypeisprobablynotsetcorrectly.
Tip:Thevicommandrunsvim
OnRedHatLinuxsystemsthecommandvirunsa
minimalbuildofvimthatiscompactandfasterto
loadthanvimbutincludesfewerfeatures.See"The
compatibleParameter"onpage159forinformationon
runningviminvi-compatiblemode.
Ifyoustartvimwithaterminaltypethatisnotintheterminfo
database,vimdisplaysanerrormessageandtheterminaltype
defaultstoansi,whichworksonmanyterminals.Inthe
followingexample,theusermistypedvt100andsetthe
terminaltypetovg100:
E558:Terminalentrynotfoundinterminfo
'vg100'notknown.Availablebuiltinterminalsare:
builtin_riscos
builtin_amiga
builtin_beos-ansi
builtin_ansi
builtin_pcansi
builtin_win32
builtin_vt320
builtin_vt52
builtin_xterm
builtin_iris-ansi
builtin_debug
builtin_dumb
defaultingto'ansi'
Toresettheterminaltype,pressESCAPEandthengivethe
followingcommandtoexitfromvimandgettheshellprompt
back:
:q!
Whenyouenterthecolon(:),vimmovesthecursortothe
bottomlineofthescreen.Thecharactersq!tellvimtoquit
withoutsavingyourwork.(Youwillnotordinarilyexitfromvim
thiswaybecauseyoutypicallywanttosaveyourwork.)You
mustpressRETURNafteryougivethiscommand.Onceyouget
theshellpromptback,referto"SpecifyingaTerminal"onpage
984,andthenstartvimagain.
Ifyoustartthiseditorwithoutafilename,vimassumesthatyou
areanoviceandtellsyouhowtogetstarted(Figure5-17).
Figure5-17.Startingvimwithoutafilename
[Viewfullsizeimage]
Thepracticefileisnewsoitdoesnotcontainanytext.Thevim
editordisplaysamessagesimilartotheoneshowninFigure5-
16onthestatus(bottom)lineoftheterminaltoindicatethat
youarecreatingandeditinganewfile.Whenyoueditan
existingfile,vimdisplaysthefirstfewlinesofthefileandgives
statusinformationaboutthefileonthestatusline.
CommandandInputModes
Twoofvim'smodesofoperationareCommandmode(also
calledNormalmode)andInputmode(Figure5-18).Whilevim
isinCommandmode,youcangivevimcommands.For
example,youcandeletetextorexitfromvim.Youcanalso
commandvimtoenterInputmode.InInputmode,vimaccepts
anythingyouenterastextanddisplaysitonthescreen.Press
ESCAPEtoreturnvimtoCommandmode.Bydefaultthevim
editorkeepsyouinformedaboutwhichmodeitisin:Itdisplays
INSERTatthelower-leftcornerofthescreenwhileitisin
Insertmode.
Figure5-18.Modesinvim
Thefollowingcommandcausesvimtodisplaylinenumbersnext
tothetextyouareediting:
:setnumberRETURN
LastLinemode
Thecolon(:)intheprecedingcommandputsvimintoanother
mode,LastLinemode.Whileinthismode,vimkeepsthecursor
onthebottomlineofthescreen.Whenyoufinishenteringthe
commandbypressingRETURN,vimrestoresthecursortoits
placeinthetext.Givethecommand:setnonumberRETURN
toturnofflinenumbers.
vimiscasesensitive
Whenyougivevimacommand,rememberthattheeditoris
casesensitive.Inotherwords,viminterpretsthesameletteras
twodifferentcommands,dependingonwhetheryouenteran
uppercaseorlowercasecharacter.BewareoftheCAPSLOCK
(SHIFTLOCK)key.Ifyousetthiskeytoenteruppercasetext
whileyouareinInputmodeandthenexittoCommandmode,
viminterpretsyourcommandsasuppercaseletters.Itcanbe
confusingwhenthishappensbecausevimdoesnotappeartobe
executingthecommandsyouareentering.
EnteringText
i/a(Inputmode)
Whenyoustartvim,youmustputitinInputmodebeforeyou
canentertext.ToputviminInputmode,presstheikey(insert
beforethecursor)ortheakey(appendafterthecursor).
IfyouarenotsurewhethervimiscurrentlyinInputmode,
presstheESCAPEkey;vimreturnstoCommandmodeifitwas
inInputmodeorbeeps,flashes,ordoesnothingifitisalready
inCommandmode.YoucanputvimbackinInputmodeby
pressingtheiorakeyagain.
WhilevimisinInputmode,youcanentertextbytypingonthe
keyboard.Ifthetextdoesnotappearonthescreenasyou
type,vimisnotinInputmode.
Tocontinuewiththistutorial,enterthesampleparagraph
showninFigure5-19,pressingtheRETURNkeyattheendof
eachline.IfyoudonotpressRETURNbeforethecursorreaches
therightsideofthescreenorwindow,vimwillwrapthetextso
thatitappearstostartanewline.Physicallineswillnot
correspondtoprogrammatic(logical)linesinthissituation,so
editingwillbemoredifficult.Whileyouareusingvim,youcan
alwayscorrectanytypingmistakesyoumake.Ifyounoticea
mistakeonthelineyouareentering,youcancorrectitbefore
youcontinue(page157).Youcancorrectothermistakeslater.
Whenyoufinishenteringtheparagraph,pressESCAPEtoreturn
vimtoCommandmode.
Figure5-19.Enteringtextwithvim
[Viewfullsizeimage]
GettingHelp
Togethelpwhileyouareusingvim,givethecommand:help
[feature]followedbyRETURN(youmustbeinCommand
modewhenyougivethiscommand).Thecolonmovesthe
cursortothelastlineofthescreen.Ifyoutype:help,vim
displaysanintroductiontovimHelp(Figure5-20).Eachdark
bandnearthebottomofthescreennamesthefilethatis
displayedaboveit.(Eachareaofthescreenthatdisplaysafile,
suchasthetwoareasshowninFigure5-20,isavim"window.")
Thehelp.txtfileoccupiesmostofthescreen(theupper
window)inFigure5-20.Thefilethatisbeingedited(practice)
occupiesafewlinesinthelowerportionofthescreen(the
lowerwindow).
Figure5-20.ThemainvimHelpscreen
[Viewfullsizeimage]
ReadthroughtheintroductiontoHelpbyscrollingthetextas
youread.PressjortheDOWNARROWkeytomovethecursor
downonelineatatime;pressCONTROL-DorCONTROL-Uto
scrollthecursordownoruphalfawindowatatime.Givethe
command:qtoclosetheHelpwindow.
Youcangethelpwiththeinsertcommandsbygivingthe
command:helpinsertwhilevimisinCommandmode(Figure
5-21).
Figure5-21.Helpwithinsertcommands
[Viewfullsizeimage]
CorrectingTextasYouInsertIt
Thekeysthatbackupandcorrectashellcommandlineserve
thesamefunctionswhenvimisinInputmode.Thesekeys
includetheerase,linekill,andwordkillkeys(usuallyCONTROL-
H,CONTROL-U,andCONTROL-W,respectively).Althoughvim
maynotremovedeletedtextfromthescreenasyoubackup
overitusingoneofthesekeys,theeditordoesremoveitwhen
youtypeoverthetextorpressRETURN.
MovingtheCursor
Youneedtobeabletomovethecursoronthescreensothat
youcandelete,insert,andcorrecttext.Whilevimisin
Commandmode,youcanusetheRETURNkey,theSPACEbar,
andtheARROWkeystomovethecursor.Ifyouprefertokeep
yourhandclosertothecenterofthekeyboard,ifyourterminal
doesnothaveARROWkeys,oriftheemulatoryouareusing
doesnotsupportthem,youcanusetheh,j,k,andl
(lowercase"l")keystomovethecursorleft,down,up,and
right,respectively.
DeletingText
x(Deletecharacter)dw(Deleteword)dd(Delete
line)
Youcandeleteasinglecharacterbymovingthecursoruntilitis
overthecharacteryouwanttodeleteandthengivingthe
commandx.Youcandeleteawordbypositioningthecursoron
thefirstletterofthewordandthengivingthecommanddw
(Deleteword).Youcandeletealineoftextbymovingthe
cursoruntilitisanywhereonthelineandthengivingthe
commanddd.
UndoingMistakes
u(Undo)
Ifyoudeleteacharacter,line,orwordbymistakeorgiveany
commandyouwanttoreverse,givethecommandu(Undo)
immediatelyafterthecommandyouwanttoundo.Thevim
editorwillrestorethetexttothewayitwasbeforeyougave
thelastcommand.Ifyougivetheucommandagain,vimwill
undothecommandyougavebeforetheoneitjustundid.You
canusethistechniquetobackupovermanyofyouractions.
Withthecompatibleparameter(page159)set,however,vim
canundoonlythemostrecentchange.
:redo(Redo)
Ifyouundoacommandyoudidnotmeantoundo,giveaRedo
command:CONTROL-Ror:redo(followedbyaRETURN).The
vimeditorwillredotheundonecommand.AswiththeUndo
command,youcangivetheRedocommandmanytimesina
row.
EnteringAdditionalText
i(Insert)a(Append)
Whenyouwanttoinsertnewtextwithinexistingtext,movethe
cursorsoitisonthecharacterthatfollowsthenewtextyou
plantoenter.Thengivethei(Insert)commandtoputvimin
Inputmode,enterthenewtext,andpressESCAPEtoreturnvim
toCommandmode.Alternatively,youcanpositionthecursor
onthecharacterthatprecedesthenewtextandusethea
(Append)command.
o/O(Open)
Toenteroneormorelines,positionthecursoronthelineabove
whereyouwantthenewtexttogo.Givethecommando
(Open).Thevimeditoropensablankline,putsthecursoronit,
andgoesintoInputmode.Enterthenewtext,endingeachline
withaRETURN.Whenyouarefinishedenteringtext,press
ESCAPEtoreturnvimtoCommandmode.TheOcommand
worksinthesamewayoworks,exceptthatitopensablank
lineabovethelinethecursorison.
CorrectingText
Tocorrecttext,usedd,dw,orxtoremovetheincorrecttext.
Thenusei,a,o,orOtoinsertthecorrecttext.
Forexample,tochangethewordpressingtohittinginFigure
5-19onpage156,youmightusetheARROWkeystomovethe
cursoruntilitisontopofthepinpressing.Thengivethe
commanddwtodeletethewordpressing.PutviminInput
modebygivinganicommand,enterthewordhittingfollowed
byaSPACE,andpressESCAPE.Thewordischangedandvimis
inCommandmode,waitingforanothercommand.Ashorthand
forthetwocommandsdwfollowedbytheicommandiscw
(Changeword).ThecommandcwputsvimintoInputmode.
Tip:Pagebreaksfortheprinter
CONTROL-Ltellstheprintertoskiptothetopofthe
nextpage.Youcanenterthischaracteranywherein
adocumentbypressingCONTROL-Lwhileyouarein
Inputmode.If^Ldoesnotappear,pressCONTROL-
VbeforeCONTROL-L.
EndingtheEditingSession
Whileyouareediting,vimkeepstheeditedtextinanarea
namedtheWorkbuffer.Whenyoufinishediting,youmustwrite
outthecontentsoftheWorkbuffertoadiskfilesothatthe
editedtextissavedandavailablewhenyounextwantit.
MakesurethatvimisinCommandmode,andthenusetheZZ
command(youmustuseuppercaseZ's)towriteyournewly
enteredtexttothediskandendtheeditingsession.Afteryou
givetheZZcommand,vimreturnscontroltotheshell.Youcan
exitwith:q!ifyoudonotwanttosaveyourwork.
Caution:DonotconfuseZZwith
CONTROL-Z
WhenyouexitfromvimwithZZ,makesurethatyou
typeZZandnotCONTROL-Z(typicallythesuspend
key).WhenyoupressCONTROL-Z,vimdisappears
fromyourscreen,almostasthoughyouhadexited
fromit.Infact,vimwillcontinuerunninginthe
backgroundwithyourworkunsaved.Referto"Job
Control"onpage280.Ifyoutrytostarteditingthe
samefilewithanewvimcommand,vimdisplaysa
messageaboutaswapfile.
ThecompatibleParameter
Thecompatibleparametermakesvimmorecompatiblewithvi.
Bydefaultthisparameterisnotset.Fromthecommandline
usetheCoptiontosetthecompatibleparameterandusethe
Noptiontounsetit.Togetstartedwithvimyoucanignorethis
parameter.
Settingthecompatibleparameterchangesmanyaspectsof
howvimworks.Forexample,whenthecompatibleparameter
isset,theUndocommand(page158)canundoonlyyourmost
recentchange;incontrast,withthecompatibleparameter
unset,youcancallUndorepeatedlytoundomanychanges.To
obtainmoredetailsonthecompatibleparameter,givethe
command:helpcompatibleRETURN.Todisplayacompletelist
ofvim'sdifferencesfromtheoriginalvi,use:helpvi-diff
RETURN.Seepage156foradiscussionofthehelpcommand.
ChapterSummary
Theutilitiesintroducedinthischapterareasmallbutpowerful
subsetofthemanyutilitiesavailableonaRedHatLinux
system.Becauseyouwillusethemfrequentlyandbecausethey
areintegraltothefollowingchapters,itisimportantthatyou
becomecomfortableusingthem.
TheutilitieslistedinTable5-2manipulate,display,compare,
andprintfiles.
Table5-2.Fileutilities
Utility Function
cp Copiesoneormorefiles(page129)
diff Displaysthedifferencesbetweentwofiles(page135)
file Displaysinformationaboutthecontentsofafile(page
135)
grep Searchesfile(s)forastring(page131)
head Displaysthelinesatthebeginningofafile(page132)
lpq Displaysalistofjobsintheprintqueue(page131)
lpr Placesfile(s)intheprintqueue(page131)
lprm Removesajobfromtheprintqueue(page131)
mv Renamesafileormovesfile(s)toanotherdirectory
(page130)
sort Putsafileinorderbylines(page133)
tail Displaysthelinesattheendofafile(page132)
uniq Displaysthecontentsofafile,skippingsuccessive
duplicatelines(page134)
Toreducetheamountofdiskspaceafileoccupies,youcan
compressitwiththebzip2utility.Compressionworksespecially
wellonfilesthatcontainpatterns,asdomosttextfiles,but
reducesthesizeofalmostallfiles.Theinverseof
bzip2bunzip2restoresafiletoitsoriginal,decompressedform.
Table5-3listsutilitiesthatcompressanddecompressfiles.The
bzip2utilityisthemostefficientofthese.
Table5-3.(De)compressionutilities
Utility Function
bunzip2 Returnsafilecompressedwithbzip2toitsoriginalsize
andformat(page140)
bzcat Displaysafilecompressedwithbzip2(page140)
bzip2 Compressesafile(page140)
compress Compressesafile(notaswellasgzip)(page141)
gunzip Returnsafilecompressedwithgziporcompresstoits
originalsizeandformat(page141)
gzip Compressesafile(page141)
zcat Displaysafilecompressedwithgzip(page141)
Anarchiveisafile,frequentlycompressed,thatcontainsa
groupoffiles.Thetarutility(Table5-4)packsandunpacks
archives.Thefilenameextensions.tar.bz2,.tar.gz,and.tgz
identifycompressedtararchivefilesandareoftenseenon
softwarepackagesobtainedovertheInternet.
Table5-4.Archiveutility
Utility Function
tar Createsorextractsfilesfromanarchivefile(page141)
TheutilitieslistedinTable5-5determinethelocationofautility
onthelocalsystem.Forexample,theycandisplaythe
pathnameofautilityoralistofC++compilersavailableonthe
localsystem.
Table5-5.Locationutilities
Utility Function
apropos Searchesthemanpageone-linedescriptionsfora
keyword(page145)
locate Searchesforfilesonthelocalsystem(page146)
whereis Displaysthefullpathnamesofautility,sourcecode,or
manpage(page144)
which Displaysthefullpathnameofacommandyoucanrun
(page144)
Table5-6listsutilitiesthatdisplayinformationaboutother
users.Youcaneasilylearnauser'sfullname,theuser'slogin
status,theloginshelloftheuser,andotheritemsof
informationmaintainedbythesystem.
Table5-6.Userandsysteminformationutilities
Utility Function
finger Displaysdetailedinformationaboutusers,including
theirfullnames(page147)
hostname Displaysthenameofthelocalsystem(page129)
wDisplaysdetailedinformationaboutuserswhoare
loggedin(page149)
who Displaysinformationaboutuserswhoareloggedin
(page147)
TheutilitiesshowninTable5-7canhelpyoustayintouchwith
otherusersonthelocalnetwork.
Table5-7.Usercommunicationutilities
Utility Function
mesg Permitsordeniesmessagessentbywrite(page151)
write Sendsamessagetoanotheruserwhoisloggedin
(page150)
Table5-8listsmiscellaneousutilities.
Table5-8.Miscellaneousutilities
Exercises
1. Whichcommandscanyouusetodeterminewhoisloggedinonaspecific
terminal?
2. Howcanyoukeepotherusersfromusingwritetocommunicatewithyou?Why
wouldyouwantto?
3.
Whathappenswhenyougivethefollowingcommandsifthefilenameddone
alreadyexists?
$cpto_dodone
$mvto_dodone
4. Howcanyoufindoutwhichutilitiesareavailableonyoursystemforeditingfiles?
Whichutilitiesareavailableforeditingonyoursystem?
5.
HowcanyoufindthephonenumberforAceElectronicsinafilenamedphonethat
containsalistofnamesandphonenumbers?Whichcommandcanyouuseto
displaytheentirefileinalphabeticalorder?Howcanyouremoveadjacent
duplicatelinesfromthefile?Howcanyouremoveallduplicates?
6.
Whathappenswhenyouusedifftocomparetwobinaryfilesthatarenotidentical?
(Youcanusegziptocreatethebinaryfiles.)Explainwhythediffoutputforbinary
filesisdifferentfromthediffoutputforASCIIfiles.
7. Createa.planfileinyourhomedirectory.Doesfingerdisplaythecontentsofyour
.planfile?
8. Whatistheresultofgivingthewhichutilitythenameofacommandthatresidesin
adirectorythatisnotinyoursearchpath?
9. Areanyoftheutilitiesdiscussedinthischapterlocatedinmorethanonedirectory
onyoursystem?Ifso,whichones?
10. Experimentbycallingthefileutilitywiththenamesoffilesin/usr/bin.Howmany
differenttypesoffilesarethere?
11. Whichcommandcanyouusetolookatthefirstfewlinesofafilenamed
status.report?Whichcommandcanyouusetolookattheendofthefile?
AdvancedExercises
12. Re-createthecolors.1andcolors.2filesusedinFigure5-8onpage135.Test
yourfilesbyrunningdiffuonthem.Doyougetthesameresultsasinthefigure?
13.
Trygivingthesetwocommands:
$echocat
$catecho
Explainthedifferencesbetweenthem.
14.
Repeatexercise5usingthefilephone.gz,acompressedversionofthelistof
namesandphonenumbers.Considermorethanoneapproachtoanswereach
question,andexplainhowyoumadeyourchoices.
15.
Findexistingfilesorcreatefilesthat
a. gzipcompressesbymorethan80percent.
b. gzipcompressesbylessthan10percent.
c. Getlargerwhencompressedwithgzip.
d. Uselsltodeterminethesizesofthefilesinquestion.Canyoucharacterize
thefilesina,b,andc?
16.
Olderemailprogramswerenotabletohandlebinaryfiles.Supposethatyouare
emailingafilethathasbeencompressedwithgzip,whichproducesabinaryfile,
andtherecipientisusinganoldemailprogram.Refertothemanpageonuuencode,
whichconvertsabinaryfiletoASCII.Learnabouttheutilityandhowtouseit.
a. ConvertacompressedfiletoASCIIusinguuencode.Istheencodedfilelarger
orsmallerthanthecompressedfile?Explain.(Ifuuencodeisnotonthelocal
system,youcaninstallitusingyum[page476];itispartofthesharutils
package.)
b. Woulditevermakesensetouseuuencodeonafilebeforecompressingit?
Explain.
6.TheLinuxFilesystem
INTHISCHAPTER
TheHierarchicalFilesystem 166
DirectoryFilesandOrdinaryFiles 166
TheWorkingDirectory 170
YourHomeDirectory 170
Pathnames 171
RelativePathnames 172
WorkingwithDirectories 178
AccessPermissions 180
ACLs:AccessControlLists 185
HardLinks 192
SymbolicLinks 194
Afilesystemisasetofdatastructures(page1028)thatusually
residesonpartofadiskandthatholdsdirectoriesoffiles.
Filesystemsstoreuserandsystemdatathatarethebasisof
users'workonthesystemandthesystem'sexistence.This
chapterdiscussestheorganizationandterminologyoftheLinux
filesystem,definesordinaryanddirectoryfiles,andexplainsthe
rulesfornamingthem.Italsoshowshowtocreateanddelete
directories,movethroughthefilesystem,anduseabsoluteand
relativepathnamestoaccessfilesinvariousdirectories.It
includesadiscussionofimportantfilesanddirectoriesaswell
asfileaccesspermissionsandAccessControlLists(ACLs),
whichallowyoutoshareselectedfileswithotherusers.It
concludeswithadiscussionofhardandsymboliclinks,which
canmakeasinglefileappearinmorethanonedirectory.
Inadditiontoreadingthischapter,youmaywanttorefertothe
dfinfopageandtothefsck,mkfs,andtune2fsmanpagesformore
informationonfilesystems.
TheHierarchicalFilesystem
Familytree
Ahierarchicalstructure(page1035)frequentlytakestheshape
ofapyramid.Oneexampleofthistypeofstructureisfoundby
tracingafamily'slineage:Acouplehasachild,whomayinturn
haveseveralchildren,eachofwhommayhavemorechildren.
Thishierarchicalstructureiscalledafamilytree(Figure6-1).
Figure6-1.Afamilytree
Directorytree
Likethefamilytreeitresembles,theLinuxfilesystemiscalleda
tree.Itconsistsofasetofconnectedfiles.Thisstructureallows
youtoorganizefilessoyoucaneasilyfindanyparticularone.
OnastandardLinuxsystem,eachuserstartswithone
directory,towhichtheusercanaddsubdirectoriestoany
desiredlevel.Bycreatingmultiplelevelsofsubdirectories,a
usercanexpandthestructureasneeded.
Subdirectories
Typicallyeachsubdirectoryisdedicatedtoasinglesubject,such
asaperson,project,orevent.Thesubjectdictateswhethera
subdirectoryshouldbesubdividedfurther.Forexample,Figure
6-2showsasecretary'ssubdirectorynamedcorrespond.This
directorycontainsthreesubdirectories:business,memos,and
personal.Thebusinessdirectorycontainsfilesthatstoreeach
letterthesecretarytypes.Ifyouexpectmanyletterstogoto
oneclient,asisthecasewithmilk_co,youcandedicatea
subdirectorytothatclient.
Figure6-2.Asecretary'sdirectories
OnemajorstrengthoftheLinuxfilesystemisitsabilitytoadapt
tousers'needs.Youcantakeadvantageofthisstrengthby
strategicallyorganizingyourfilessotheyaremostconvenient
andusefulforyou.
DirectoryFilesandOrdinaryFiles
Likeafamilytree,thetreerepresentingthefilesystemis
usuallypicturedupsidedown,withitsrootatthetop.Figures6-
2and6-3showthatthetree"grows"downwardfromtheroot,
withpathsconnectingtheroottoeachoftheotherfiles.Atthe
endofeachpathiseitheranordinaryfileoradirectoryfile.
Specialfiles,whichcanalsobeattheendsofpaths,are
describedonpage460.Ordinaryfiles,orsimplyfiles,appearat
theendsofpathsthatcannotsupportotherpaths.Directory
files,alsoreferredtoasdirectoriesorfolders,arethepoints
thatotherpathscanbranchofffrom.(Figures6-2and6-3show
someemptydirectories.)Whenyourefertothetree,upis
towardtherootanddownisawayfromtheroot.Directories
directlyconnectedbyapatharecalledparents(closertothe
root)andchildren(fartherfromtheroot).Apathnameisa
seriesofnamesthattraceapathalongbranchesfromonefile
toanother.Moreinformationaboutpathnamesappearsonpage
171.
Figure6-3.Directoriesandordinaryfiles
Filenames
Everyfilehasafilename.Themaximumlengthofafilename
varieswiththetypeoffilesystem;Linuxsupportsseveraltypes
offilesystems.Althoughmostoftoday'sfilesystemsallowyou
tocreatefileswithnamesupto255characterslong,some
filesystemsrestrictyoutoshorternames.Whileyoucanuse
almostanycharacterinafilename,youwillavoidconfusionif
youchoosecharactersfromthefollowinglist:
Uppercaseletters(AZ)
Lowercaseletters(az)
Numbers(09)
Underscore(_)
Period(.)
Comma(,)
/orroot
Therootdirectoryisalwaysnamed/(slash)andreferredtoby
thissinglecharacter.Nootherfilecanusethisnameorhavea
/initsname.However,inapathname,whichisastringof
filenamesincludingdirectorynames,theslashseparatesfile-
names(page171).
Likethechildrenofoneparent,notwofilesinthesame
directorycanhavethesamename.(Parentsgivetheirchildren
differentnamesbecauseitmakesgoodsense,butLinux
requiresit.)Filesindifferentdirectories,likethechildrenof
differentparents,canhavethesamename.
Thefilenamesyouchooseshouldmeansomething.Toooftena
directoryisfilledwithimportantfileswithsuchunhelpfulnames
ashold1,wombat,andjunk,nottomentionfooandfoobar.
Suchnamesarepoorchoicesbecausetheydonothelpyou
recallwhatyoustoredinafile.Thefollowingfilenamesconform
tothesuggestedsyntaxandconveyinformationaboutthe
contentsofthefile:
correspond
january
davis
reports
2001
acct_payable
Filenamelength
Whenyoushareyourfileswithusersonothersystems,you
mayneedtomakelongfilenamesdifferwithinthefirstfew
characters.SystemsrunningDOSorolderversionsofWindows
havean8-characterfilenamebodylengthanda3-character
filenameextensionlengthlimit.SomeUNIXsystemshavea14-
characterlimitandolderMacintoshsystemshavea31-
characterlimit.Ifyoukeepthefilenamesshort,theyareeasy
totype;lateryoucanaddextensionstothemwithout
exceedingtheshorterlimitsimposedbysomefilesystems.The
disadvantageofshortfilenamesisthattheyaretypicallyless
descriptivethanlongfilenames.Seestatonpage420foraway
todeterminethemaximumlengthofafilenameonthelocal
system.
Longfilenamesenableyoutoassigndescriptivenamestofiles.
Tohelpyouselectamongfileswithouttypingentirefilenames,
shellssupportfilenamecompletion.Formoreinformationabout
thisfeature,seethe"Filenamecompletion"tiponpage129.
Casesensitivity
Youcanuseuppercaseand/orlowercaseletterswithin
filenames.Linuxiscasesensitive,sofilesnamedJANUARY,
January,andjanuaryrepresentthreedistinctfiles.
Caution:DonotuseSPACEswithin
filenames
AlthoughyoucanuseSPACEswithinfilenames,itis
apooridea.BecauseaSPACEisaspecialcharacter,
youmustquoteitonacommandline.Quotinga
characteronacommandlinecanbedifficultfora
noviceuserandcumbersomeforanexperienced
user.UseperiodsorunderscoresinsteadofSPACEs:
joe.05.04.26,new_stuff.
Ifyouareworkingwithafilenamethatincludesa
SPACE,suchasafilefromanotheroperating
system,youmustquotetheSPACEonthecommand
linebyprecedingitwithabackslashorbyplacing
quotationmarksoneithersideofthefilename.The
twofollowingcommandssendthefilenamedmyfile
totheprinter.
$lprmy\file
$lpr"myfile"
FilenameExtensions
Afilenameextensionisthepartofthefilenamefollowingan
embeddedperiod.InthefilenameslistedinTable6-1,filename
extensionshelpdescribethecontentsofthefile.Some
programs,suchastheCprogramminglanguagecompiler,
defaulttospecificfilenameextensions;inmostcases,however,
filenameextensionsareoptional.Useextensionsfreelytomake
filenameseasytounderstand.Ifyoulike,youcanuseseveral
periodswithinthesamefilenameforexample,notes.4.10.01
orfiles.tar.gz.
Table6-1.Filenameextensions
Filenamewithextension Meaningofextension
compute.c ACprogramminglanguagesourcefile
compute.o Theobjectcodefortheprogram
compute Thesameprogramasanexecutablefile
memo.0410.txt Atextfile
memo.pdf APDFfile;viewwithxpdfunderaGUI
memo.ps APostScriptfile;viewwithgsunderaGUI
memo.Z Afilecompressedwithcompress(page
141);useuncompressorgunzip(page141)
todecompress
memo.tgzor
memo.tar.gz
Atar(page141)archiveoffiles
compressedwithgzip(page141)
memo.gz Afilecompressedwithgzip(page141);
viewwithzcatordecompresswithgunzip
(bothonpage141)
memo.bz2 Afilecompressedwithbzip2(page140);
viewwithbzcatordecompresswithbunzip2
(bothonpage140)
memo.html AfilemeanttobeviewedusingaWeb
browser,suchasFirefox
photo.gif,photo.jpg,
photo.jpeg,photo.bmp,
photo.tif,orphoto.tiff
Afilecontaininggraphicalinformation,
suchasapicture
HiddenFilenames
Afilenamethatbeginswithaperiodiscalledahiddenfilename
(orahiddenfileorsometimesaninvisiblefile)becauselsdoes
notnormallydisplayit.Thecommandlsadisplaysall
filenames,evenhiddenones.Namesofstartupfiles(page170)
usuallybeginwithaperiodsothattheyarehiddenanddonot
clutteradirectorylisting.The.planfile(page148)isalso
hidden.Twospecialhiddenentriesasingleanddoubleperiod(.
and..)appearineverydirectory(page175).
TheWorkingDirectory
pwd
Whileyouareloggedinonacharacter-basedinterfacetoa
Linuxsystem,youarealwaysassociatedwithadirectory.The
directoryyouareassociatedwithiscalledtheworkingdirectory
orcurrentdirectory.Sometimesthisassociationisreferredtoin
aphysicalsense:"Youarein(orworkingin)thejenny
directory."Thepwd(printworkingdirectory)utilitydisplaysthe
pathnameoftheworkingdirectory.
YourHomeDirectory
WhenyoufirstloginonaLinuxsystemorstartaterminal
emulatorwindow,yourworkingdirectoryisyourhome
directory.Todisplaythepathnameofyourhomedirectory,use
pwdjustafteryoulogin(Figure6-4).
Figure6-4.Logginginanddisplayingthe
pathnameofyourhomedirectory
login:alex
Password:
Lastlogin:WedOct2011:14:21frombravo
$pwd
/home/alex
Whenusedwithoutanyarguments,thelsutilitydisplaysalist
ofthefilesintheworkingdirectory.Becauseyourhome
directoryhasbeentheonlyworkingdirectoryyouhaveusedso
far,lshasalwaysdisplayedalistoffilesinyourhomedirectory.
(Allthefilesyouhavecreateduptothispointwerecreatedin
yourhomedirectory.)
StartupFiles
Startupfiles,whichappearinyourhomedirectory,givethe
shellandotherprogramsinformationaboutyouandyour
preferences.Frequentlyoneofthesefilestellstheshellwhat
kindofterminalyouareusing(page984)andexecutesthestty
(setterminal)utilitytoestablishtheerase(page117)andline
kill(page118)keys.
Eitheryouorthesystemadministratorcanputashellstartup
filecontainingshellcommandsinyourhomedirectory.Theshell
executesthecommandsinthisfileeachtimeyoulogin.
Becausethestartupfileshavehiddenfilenames,youmustuse
thelsacommandtoseewhetheroneisinyourhomedirectory.
AGUIhasmanystartupfiles.Usuallyyoudonotneedtowork
withthesefilesdirectlybutcancontrolstartupsequencesby
usingiconsonthedesktop.Seepage267formoreinformation
aboutstartupfiles.
Pathnames
Thissectiondiscussesabsoluteandrelativepathnamesand
explainshowtousethemtoyouradvantage.
AbsolutePathnames
Everyfilehasapathname.Figure6-5showsthepathnamesof
directoriesandordinaryfilesinpartofafilesystemhierarchy.
Anabsolutepathnamealwaysstartswithaslash(/),thename
oftherootdirectory.Youcanthenbuildtheabsolutepathname
ofafilebytracingapathfromtherootdirectorythroughallthe
intermediatedirectoriestothefile.Stringallthefilenamesin
thepathtogether,separatingeachfromthenextwithaslash
(/)andprecedingtheentiregroupoffilenameswithaslash
(/).Thispathoffilenamesiscalledanabsolutepathname
becauseitlocatesafileabsolutelybytracingapathfromthe
rootdirectorytothefile.Thepartofapathnamefollowingthe
finalslashiscalledasimplefilename,filename,orbasename.
Figure6-5.Absolutepathnames
[Viewfullsizeimage]
~(Tilde)inPathnames
Inanotherformofabsolutepathname,theshellexpandsthe
characters~/(atildefollowedbyaslash)atthestartofa
pathnameintothepathnameofyourhomedirectory.Usingthis
shortcut,youcandisplayyour.bashrcstartupfile(page267)
withthefollowingcommand,nomatterwhichdirectoryisyour
workingdirectory:
$less~/.bashrc
Atildequicklyreferencespathsthatstartwithyourorsomeone
else'shomedirectory.Theshellexpandsatildefollowedbya
usernameatthebeginningofapathnameintothepathnameof
thatuser'shomedirectory.Forexample,assuminghehas
permissiontodoso,AlexcanexamineScott's.bashrcfilewith
thefollowingcommand:
$less~scott/.bashrc
Referto"TildeExpansion"onpage331formoreinformation.
RelativePathnames
Arelativepathnametracesapathfromtheworkingdirectoryto
afile.Thepathnameisrelativetotheworkingdirectory.Any
pathnamethatdoesnotbeginwiththerootdirectory(/)ora
tilde(~)isarelativepathname.Likeabsolutepathnames,
relativepathnamescantraceapaththroughmanydirectories.
Thesimplestrelativepathnameisasimplefilename,which
identifiesafileintheworkingdirectory.Theexamplesinthe
nextsectionsuseabsoluteandrelativepathnames.
Caution:Whenusingarelative
pathname,knowwhichdirectoryisthe
workingdirectory
Thelocationofthefilethatyouareaccessingwitha
relativepathnameisdependenton(isrelativeto)
theworkingdirectory.Alwaysmakesureyouknow
whichdirectoryistheworkingdirectorybeforeyou
usearelativepathname.Usepwdtoverifythe
directory.Ifyouareusingmkdirandyouarenot
whereyouthinkyouareinthefilehierarchy,the
newdirectorywillendupinanunexpectedlocation.
Itdoesnotmatterwhichdirectoryistheworking
directorywhenyouuseanabsolutepathname.
SignificanceoftheWorkingDirectory
Toaccessanyfileintheworkingdirectory,youneedonlya
simplefilename.Toaccessafileinanotherdirectory,youmust
useapathname.Typingalongpathnameistediousand
increasesthechanceofmakingamistake.Thispossibilityis
lesslikelyunderaGUI,whereyouclickfilenamesoricons.You
canchooseaworkingdirectoryforanyparticulartasktoreduce
theneedforlongpathnames.Yourchoiceofaworkingdirectory
doesnotallowyoutodoanythingyoucouldnotdootherwiseit
justmakessomeoperationseasier.
RefertoFigure6-6asyoureadthisparagraph.Filesthatare
childrenoftheworkingdirectorycanbereferencedbysimple
filenames.Grandchildrenoftheworkingdirectorycanbe
referencedbyshortrelativepathnames:twofilenames
separatedbyaslash.Whenyoumanipulatefilesinalarge
directorystructure,usingshortrelativepathnamescansave
youtimeandaggravation.Ifyouchooseaworkingdirectory
thatcontainsthefilesusedmostoftenforaparticulartask,you
needtousefewerlong,cumbersomepathnames.
Figure6-6.Relativepathnames
DirectoryCommands
Thissectiondiscusseshowtocreatedirectories(mkdir),switch
betweendirectories(cd),removedirectories(rmdir),use
pathnamestomakeyourworkeasier,andmoveandcopyfiles
anddirectoriesbetweendirectories.
mkdir:CreatesaDirectory
Themkdirutilitycreatesadirectory.Theargument(page1019)
tomkdirbecomesthepathnameofthenewdirectory.The
followingexamplesdevelopthedirectorystructureshownin
Figure6-7.Inthefigure,thedirectoriesthatareaddedappear
inalightershadethantheothersandareconnectedbydashes.
Figure6-7.Thefilestructuredevelopedinthe
examples
InFigure6-8(nextpage),pwdshowsthatAlexisworkinginhis
homedirectory(/home/alex)andlsshowsthenamesofthe
filesinhishomedirectory:demo,names,andtemp.Using
mkdir,Alexcreatesadirectorynamedliteratureasachildof
hishomedirectory.Heusesarelativepathname(asimple
filename)becausehewantstheliteraturedirectorytobea
childoftheworkingdirectory.Ofcourse,Alexcouldhaveused
anabsolutepathnametocreatethesamedirectory:
mkdir/home/alex/literature.
Figure6-8.Themkdirutility
$pwd
/home/alex
$ls
demonamestemp
$mkdirliterature
$ls
demoliteraturenamestemp
$ls-F
demoliterature/namestemp
$lsliterature
$
ThesecondlsinFigure6-8verifiesthepresenceofthenew
directory.TheFoptiontolsdisplaysaslashafterthenameof
eachdirectoryandanasteriskaftereachexecutablefile(shell
script,utility,orapplication).Whenyoucallitwithanargument
thatisthenameofadirectory,lsliststhecontentsofthat
directory.Thefinallsdoesnotdisplayanythingbecausethere
arenofilesintheliteraturedirectory.
Thefollowingcommandsshowtwowaystocreatethepromo
directoryasachildofthenewlycreatedliteraturedirectory.
Thefirstwaychecksthat/home/alexistheworkingdirectory
andusesarelativepathname:
$pwd
/home/alex
$mkdirliterature/promo
Thesecondwayusesanabsolutepathname:
$mkdir/home/alex/literature/promo
Usethep(parents)optiontomkdirtocreateboththe
literatureandpromodirectorieswithonecommand:
$pwd
/home/alex
$ls
demonamestemp
$mkdir-pliterature/promo
or
$mkdir-p/home/alex/literature/promo
cd:ChangestoAnotherWorkingDirectory
Thecd(changedirectory)utilitymakesanotherdirectorythe
workingdirectorybutdoesnotchangethecontentsofthe
workingdirectory.Figure6-9showstwowaystomakethe
/home/alex/literaturedirectorytheworkingdirectory,as
verifiedbypwd.FirstAlexusescdwithanabsolutepathnameto
makeliteraturehisworkingdirectoryitdoesnotmatterwhich
isyourworkingdirectorywhenyougiveacommandwithan
absolutepathname.Apwdcommandconfirmsthechangemade
byAlex.Whenusedwithoutanargument,cdmakesyourhome
directorytheworkingdirectory,asitwaswhenyouloggedin.
ThesecondcdcommandinFigure6-9doesnothavean
argumentsoitmakesAlex'shomedirectorytheworking
directory.Finally,knowingthatheisworkinginhishome
directory,Alexusesasimplefilenametomaketheliterature
directoryhisworkingdirectory(cdliterature)andconfirmsthe
changewithpwd.
Figure6-9.cdchangesyourworkingdirectory
$cd/home/alex/literature
$pwd
/home/alex/literature
$cd
$pwd
/home/alex
$cdliterature
$pwd
/home/alex/literature
Tip:Theworkingdirectoryversusyour
homedirectory
Theworkingdirectoryisnotthesameasyourhome
directory.Yourhomedirectoryremainsthesamefor
thedurationofyoursessionandusuallyfrom
sessiontosession.Immediatelyafteryoulogin,you
arealwaysworkinginthesamedirectory:your
homedirectory.
Unlikeyourhomedirectory,theworkingdirectory
canchangeasoftenasyoulike.Youhavenoset
workingdirectory,whichexplainswhysomepeople
refertoitasthecurrentdirectory.Whenyoulogin
anduntilyouchangedirectoriesbyusingcd,your
homedirectoryisyourworkingdirectory.Ifyou
weretochangedirectoriestoScott'shomedirectory,
thenScott'shomedirectorywouldbeyourworking
directory.
The.and..DirectoryEntries
Themkdirutilityautomaticallyputstwoentriesineachdirectory
youcreate:asingleperiod(.)andadoubleperiod(..).The.is
synonymouswiththepathnameoftheworkingdirectoryand
canbeusedinitsplace;the..issynonymouswiththe
pathnameoftheparentoftheworkingdirectory.Theseentries
arehiddenbecausetheirfilenamesbeginwithaperiod.
Withtheliteraturedirectoryastheworkingdirectory,the
followingexampleuses..threetimes:firsttolistthecontents
oftheparentdirectory(/home/alex),secondtocopythe
memoAfiletotheparentdirectory,andthirdtolistthe
contentsoftheparentdirectoryagain.
$pwd
/home/alex/literature
$ls..
demoliteraturenamestemp
$cpmemoA..
$ls..
demoliteraturememoAnamestemp
Afterusingcdtomakepromo(asubdirectoryofliterature)his
workingdirectory,Alexcanusearelativepathnametocallvim
toeditafileinhishomedirectory.
$cdpromo
$vim../../names
Youcanuseanabsoluteorrelativepathnameorasimple
filenamevirtuallyanywherethatautilityorprogramrequiresa
filenameorpathname.Thisusageholdstrueforls,vim,mkdir,
rm,andmostotherLinuxutilities.
ImportantStandardDirectoriesandFiles
OriginallyfilesonaLinuxsystemwerenotlocatedinstandard
places.Thescatteredfilesmadeitdifficulttodocumentand
maintainaLinuxsystemandjustaboutimpossibleforsomeone
toreleaseasoftwarepackagethatwouldcompileandrunonall
Linuxsystems.ThefirststandardfortheLinuxfilesystem,the
FSSTND(LinuxFilesystemStandard),wasreleasedonFebruary
14,1994.Inearly1995workwasstartedonabroader
standardcoveringmanyUNIX-likesystems:FHS(Linux
FilesystemHierarchyStandard,www.pathname.com/fhs).More
recentlyFHShasbeenincorporatedinLSB(LinuxStandard
Base,www.linuxbase.org),aworkgroupofFSG(FreeStandards
Group,www.freestandards.org).Figure6-10showsthe
locationsofsomeimportantdirectoriesandfilesasspecifiedby
FHS.Thesignificanceofmanyofthesedirectorieswillbecome
clearasyoucontinuereading.
Figure6-10.AtypicalFHS-basedLinuxfilesystem
structure
[Viewfullsizeimage]
ThefollowinglistdescribesthedirectoriesshowninFigure6-10,
someofthedirectoriesspecifiedbyFHS,andsomeother
directories.RedHatLinux,however,doesnotuseallthe
directoriesspecifiedbyFHS.Beawarethatyoucannotalways
determinethefunctionofadirectorybyitsname.Forexample,
although/optstoresadd-onsoftware,/etc/optstores
configurationfilesforthesoftwarein/opt.Seealso"Important
FilesandDirectories"onpage448.
/
RootTherootdirectory,presentinallLinuxfilesystem
structures,istheancestorofallfilesinthefilesystem.
/bin
EssentialcommandbinariesHoldsthefilesneededtobring
thesystemupandrunitwhenitfirstcomesupinsingle-user
mode(page409).
/boot
StaticfilesofthebootloaderContainsallofthefilesneeded
tobootthesystem.
/dev
DevicefilesContainsallfilesthatrepresentperipheraldevices,
suchasdiskdrives,terminals,andprinters.Previouslythis
directorywasfilledwithallpossibledevices.AsofFedoraCore
3andRHELv.4,udev(page461)providesadynamicdevice
directorythatenables/devtocontainonlydevicesthatare
presentonthesystem.
/etc
MachinelocalsystemconfigurationfilesHolds
administrative,configuration,andothersystemfiles.Oneofthe
mostimportantis/etc/passwd,whichcontainsalistofall
userswhohavepermissiontousethesystem.
/etc/opt
Configurationfilesforadd-onsoftwarepackageskeptin
/opt
/etc/X11
MachinelocalconfigurationfilesfortheXWindowSystem
/home
UserhomedirectoriesEachuser'shomedirectoryistypically
oneofmanysubdirectoriesofthe/homedirectory.Asan
example,assumingthatusers'directoriesareunder/home,
theabsolutepathnameofJenny'shomedirectoryis
/home/jenny.Onsomesystemstheusers'directoriesmay
notbefoundunder/homebutinsteadmightbespreadamong
otherdirectoriessuchas/inhouseand/clients.
/lib
Sharedlibraries
/lib/modules
Loadablekernelmodules
/mnt
Mountpointfortemporarilymountingfilesystems
/opt
Add-onsoftwarepackages(optionalpackages)
/proc
Kernelandprocessinformationvirtualfilesystem
/root
Homedirectoryforroot
/sbin
EssentialsystembinariesUtilitiesusedforsystem
administrationarestoredin/sbinand/usr/sbin.The/sbin
directoryincludesutilitiesneededduringthebootingprocess,
and/usr/sbinholdsutilitiesusedafterthesystemisupand
running.InolderversionsofLinux,manysystemadministration
utilitieswerescatteredthroughseveraldirectoriesthatoften
includedothersystemfiles(/etc,/usr/bin,/usr/adm,
/usr/include).
/sys
DevicepseudofilesystemSeeudevonpage461formore
information.
/tmp
Temporaryfiles
/usr
SecondmajorhierarchyTraditionallyincludessubdirectories
thatcontaininformationusedbythesystem.Filesin/usr
subdirectoriesdonotchangeoftenandmaybesharedby
severalsystems.
LocalhierarchyHoldslocallyimportantfilesanddirectories
thatareaddedtothesystem.Subdirectoriescanincludebin,
games,include,lib,sbin,share,andsrc.
/usr/man
Onlinemanuals
/usr/sbin
NonvitalsystemadministrationbinariesSee/sbin.
/usr/share
Architecture-independentdataSubdirectoriescaninclude
dict,doc,games,info,locale,man,misc,terminfo,and
zoneinfo.
/usr/share/doc
Documentation
/usr/share/info
GNUinfosystem'sprimarydirectory
/usr/src
Sourcecode
/var
VariabledataFileswithcontentsthatvaryasthesystemruns
arekeptinsubdirectoriesunder/var.Themostcommon
examplesaretemporaryfiles,systemlogfiles,spooledfiles,
andusermailboxfiles.Subdirectoriescanincludecache,lib,
lock,log,opt,run,spool,tmp,andyp.Olderversionsof
Linuxscatteredsuchfilesthroughseveralsubdirectoriesof/usr
(/usr/adm,/usr/mail,/usr/spool,/usr/tmp).
/var/log
LogfilesContainslastlog(arecordofthelastloginbyeach
user),messages(systemmessagesfromsyslogd),andwtmp
(arecordofalllogins/logouts).
/var/spool
SpooledapplicationdataContainsanacron,at,cron,lpd,
mail,mqueue,samba,andotherdirectories.Thefile
/var/spool/mailtypicallyhasasymboliclinkin/var.
WorkingwithDirectories
Thissectioncoversdeletingdirectories,copyingandmoving
filesbetweendirectories,andmovingdirectories.Italso
describeshowtousepathnamestomakeyourworkwithLinux
easier.
rmdir:DeletesaDirectory
Thermdir(removedirectory)utilitydeletesadirectory.You
cannotdeletetheworkingdirectoryoradirectorythatcontains
filesotherthanthe.and..entries.Ifyouneedtodeletea
directorythathasfilesinit,firstusermtodeletethefilesand
thendeletethedirectory.Youdonothaveto(norcanyou)
deletethe.and..entries;rmdirremovesthemautomatically.
Thefollowingcommanddeletesthepromodirectory:
$rmdir/home/alex/literature/promo
Thermutilityhasaroption(rmrfilename)thatrecursively
deletesfiles,includingdirectories,withinadirectoryandalso
deletesthedirectoryitself.
Caution:Usermrcarefully,ifatall
Althoughrmrisahandycommand,youmustuseit
carefully.Donotuseitwithanambiguousfile
referencesuchas*.Itisfrighteninglyeasytowipe
outyourentirehomedirectorywithasingleshort
command.
UsingPathnames
touch
Useatexteditortocreateafilenamedletterifyouwantto
experimentwiththeexamplesthatfollow.Alternativelyyoucan
usetouchtocreateanemptyfile:
$cd
$pwd
/home/alex
$touchletter
With/home/alexastheworkingdirectory,thefollowing
exampleusescpwitharelativepathnametocopythefileletter
tothe/home/alex/literature/promodirectory(youwill
needtocreatepromoagainifyoudeleteditearlier).Thecopy
ofthefilehasthesimplefilenameletter.0610:
$cpletterliterature/promo/letter.0610
IfAlexdoesnotchangetoanotherdirectory,hecanusevimto
editthecopyofthefilehejustmade:
$vimliterature/promo/letter.0610
IfAlexdoesnotwanttousealongpathnametospecifythefile,
hecanusecdtomakepromotheworkingdirectorybefore
usingvim:
$cdliterature/promo
$pwd
/home/alex/literature/promo
$vimletter.0610
Tomaketheparentoftheworkingdirectory(named
/home/alex/literature)thenewworkingdirectory,Alexcan
givethefollowingcommand,whichtakesadvantageofthe..
directoryentry:
$cd..
$pwd
/home/alex/literature
mv,cp:MoveorCopyFiles
Chapter5discussedtheuseofmvtorenamefiles.However,mv
worksevenmoregenerally:Youcanusethisutilitytomove
filesfromonedirectorytoanother(changethepathnameofa
file)aswellastochangeasimplefilename.Whenusedtomove
oneormorefilestoanewdirectory,themvcommandhasthis
syntax:
mvexisting-file-listdirectory
Iftheworkingdirectoryis/home/alex,Alexcanusethe
followingcommandtomovethefilesnamesandtempfrom
theworkingdirectorytotheliteraturedirectory:
$mvnamestempliterature
Thiscommandchangestheabsolutepathnamesofthenames
andtempfilesfrom/home/alex/namesand
/home/alex/tempto/home/alex/literature/namesand
/home/alex/literature/temp,respectively(Figure6-11).
LikemostLinuxcommands,mvacceptseitherabsoluteor
relativepathnames.
Figure6-11.Usingmvtomovenamesandtemp
AsyouworkwithLinuxandcreatemorefiles,youwillneedto
createnewdirectoriesusingmkdirtokeepthefilesorganized.
Themvutilityisausefultoolformovingfilesfromonedirectory
toanotherasyouextendyourdirectoryhierarchy.
Thecputilityworksinthesamewayasmvdoes,exceptthatit
makescopiesoftheexisting-file-listinthespecified
directory.
mv:MovesaDirectory
Justasitmovesordinaryfilesfromonedirectorytoanother,so
mvcanmovedirectories.Thesyntaxissimilarexceptthatyou
specifyoneormoredirectories,notordinaryfiles,tomove:
mvexisting-directory-listnew-directory
Ifnew-directorydoesnotexist,theexisting-directory-list
mustcontainjustonedirectoryname,whichmvchangesto
new-directory(mvrenamesthedirectory).Althoughyoucan
renamedirectoriesusingmv,youcannotcopytheircontents
withcpunlessyouusetheroption.Refertothetarandcpioman
pagesforotherwaystocopyandmovedirectories.
AccessPermissions
InadditiontothecontrolsimposedbySELinux(page400),Red
HatLinuxsupportstwomethodsofcontrollingwhocanaccessa
fileandhowtheycanaccessit:traditionalLinuxaccess
permissionsandAccessControlLists(ACLs,page185).ACLs
providefiner-grainedcontrolofaccessprivileges.Thissection
describestraditionalLinuxaccesspermissions.
Threetypesofuserscanaccessafile:theownerofthefile
(owner),amemberofagroupthatthefileisassociatedwith
(group;seepage451formoreinformationongroups),and
everyoneelse(other).Ausercanattempttoaccessanordinary
fileinthreeways:bytryingtoreadfrom,writeto,orexecute
it.
lsl:DisplaysPermissions
Whenyoucalllswiththeloptionandthenameofoneormore
ordinaryfiles,lsdisplaysalineofinformationaboutthefile.The
followingexampledisplaysinformationfortwofiles.Thefile
letter.0610containsthetextofaletter,andcheck_spell
containsashellscript,aprogramwritteninahigh-levelshell
programminglanguage:
$ls-lletter.0610check_spell
-rw-r--r--1alexpubs3355May210:52letter.0610
-rwxr-xr-x2alexpubs852May514:03check_spell
Fromlefttoright,thelinesthatanlslcommanddisplays
containthefollowinginformation(refertoFigure6-12):
Thetypeoffile(firstcharacter)
Thefile'saccesspermissions(thenextninecharacters)
TheACLflag(presentifthefilehasanACL,page185)
Thenumberoflinkstothefile(page190)
Thenameoftheownerofthefile(usuallythepersonwho
createdthefile)
Thenameofthegroupthatthefileisassociatedwith
Thesizeofthefileincharacters(bytes)
Thedateandtimethefilewascreatedorlastmodified
Thenameofthefile
Figure6-12.Thecolumnsdisplayedbythelsl
command
Thetypeoffile(firstcolumn)forletter.0610isahyphen()
becauseitisanordinaryfile(directoryfileshaveadinthis
column).
Thenextthreecharactersspecifytheaccesspermissionsforthe
ownerofthefile:rindicatesreadpermission,windicateswrite
permission,andxindicatesexecutepermission.Ainacolumn
indicatesthattheownerdoesnothavethepermissionthat
wouldhaveappearedinthatposition.
Inasimilarmannerthenextthreecharactersrepresent
permissionsforthegroup,andthefinalthreecharacters
representpermissionsforother(everyoneelse).Inthe
precedingexample,theownerofletter.0610canreadfrom
andwritetothefile,whereasthegroupandotherscanonly
readfromthefileandnooneisallowedtoexecuteit.Although
executepermissioncanbeallowedforanyfile,itdoesnotmake
sensetoassignexecutepermissiontoafilethatcontainsa
document,suchasaletter.Thecheck_spellfileisan
executableshellscript,soexecutepermissionisappropriatefor
it.(Theowner,group,andothershaveexecuteaccess
permission.)
chmod:ChangesAccessPermissions
Theownerofafilecontrolswhichusershavepermissionto
accessthefileandhowtheycanaccessit.Whenyouownafile,
youcanusethechmod(changemode)utilitytochangeaccess
permissionsforthatfile.Inthefollowingexample,chmodadds
(+)readandwritepermissions(rw)forall(a)users:
$chmoda+rwletter.0610
$ls-lletter.0610
-rw-rw-rw-1alexpubs3355May210:52letter.0610
Tip:Youmusthavereadpermissionto
executeashellscript
Becauseashellneedstoreadashellscript(atext
filecontainingshellcommands)beforeitcan
executethecommandswithinthatscript,youmust
havereadpermissionforthefilecontainingthe
scripttoexecuteit.Youalsoneedexecute
permissiontoexecuteashellscriptdirectlyonthe
commandline.Incontrast,binary(program)filesdo
notneedtoberead;theyareexecuteddirectly.You
needonlyexecutepermissiontorunabinary
(nonshell)program.
Inthenextexample,chmodremoves()read(r)andexecute(x)
permissionsforusersother(o)thantheownerofthefile(alex)
andmembersofthegroupthefileisassociatedwith(pubs):
$chmodo-rxcheck_spell
$ls-lcheck_spell
-rwxr-x---2alexpubs852May514:03check_spell
Inadditiontoa(all)ando(other),youcanuseg(group)and
u(user,althoughuserreferstotheownerofthefilewhomay
ormaynotbetheuserofthefileatanygiventime)inthe
argumenttochmod.Youcanalsouseabsolute,ornumeric,
argumentswithchmod.Refertopage273formoreinformation
onusingchmodtomakeafileexecutableandtothechmodman
pageforinformationonabsoluteargumentsandchmodin
general.Refertopage451formoreinformationongroups.
TheLinuxfileaccesspermissionschemeletsyougiveother
usersaccesstothefilesyouwanttoshareyetkeepyour
privatefilesconfidential.Youcanallowotheruserstoreadfrom
andwritetoafile(handyifyouareoneofseveralpeople
workingonajointproject).Youcanallowothersonlytoread
fromafile(perhapsaprojectspecificationyouareproposing).
Oryoucanallowothersonlytowritetoafile(similartoan
inboxormailbox,whereyouwantotherstobeabletosendyou
mailbutdonotwantthemtoreadyourmail).Similarlyyoucan
protectentiredirectoriesfrombeingscanned(coveredshortly).
Tip:chmod:oforother,uforowner
Whenusingchmod,manypeopleassumethattheo
standsforowner;itdoesnot.Theostandsforother,
whereasustandsforowner(user).Theacronym
UGO(user-group-other)canhelpyouremember
howpermissionsarenamed.
Thereisanexceptiontotheaccesspermissionsjustdescribed.
AnyonewhoknowstherootpasswordcanloginasSuperuser
(page391)andgainfullaccesstoallfiles,regardlessofthe
file'sowneroraccesspermissions.
SetuidandSetgidPermissions
Whenyouexecuteafilethathassetuid(setuserID)
permission,theprocessexecutingthefiletakesonthe
privilegesofthefile'sowner.Forexample,ifyourunasetuid
programthatremovesallfilesinadirectory,youcanremove
filesinanyofthefileowner'sdirectories,evenifyoudonot
normallyhavepermissiontodoso.
Security:Minimizeuseofsetuidand
setgidprogramsownedbyroot
Executablefilesthataresetuidandownedbyroot
haveSuperuserprivilegeswhentheyarerun,evenif
theyarenotrunbyroot.Thistypeofprogramis
verypowerfulbecauseitcandoanythingthat
Superusercando(andthattheprogramisdesigned
todo).Similarlyexecutablefilesthataresetgidand
belongtothegrouproothaveextensiveprivileges.
Becauseofthepowertheyholdandtheirpotential
fordestruction,itiswisetoavoidindiscriminately
creatingandusingsetuidandsetgidprograms
ownedbyorbelongingtothegrouproot.Becauseof
theirinherentdangers,manysitesminimizetheuse
oftheseprogramsontheirsystems.Onenecessary
setuidprogramispasswd.Seepage393foratipon
setuidfilesownedbyrootandpage399fora
commandthatlistssetuidfilesonthelocalsystem.
Inasimilarmanner,setgid(setgroupID)permissionmeans
thattheprocessexecutingthefiletakesontheprivilegesofthe
groupthefileisassociatedwith.Thelsutilityshowssetuid
permissionbyplacingansintheowner'sexecutableposition
andsetgidpermissionbyplacingansinthegroup'sexecutable
position:
$ls-lprogram1
-rwxr-xr-x1alexpubs15828Nov506:28program1
$chmodu+sprogram1
$ls-lprogram1
-rwsr-xr-x1alexpubs15828Nov506:28program1
$chmodg+sprogram1
$ls-lprogram1
-rwsr-sr-x1alexpubs15828Nov506:28program1
Security:Donotwritesetuidshellscripts
Nevergiveshellscriptssetuidpermission.Several
techniquesforsubvertingthemarewellknown.
DirectoryAccessPermissions
Accesspermissionshaveslightlydifferentmeaningswhenthey
areusedwithdirectories.Althoughthethreetypesofuserscan
readfromorwritetoadirectory,thedirectorycannotbe
executed.Executeaccesspermissionisredefinedfora
directory:Itmeansthatyoucancdintothedirectoryand/or
examinefilesthatyouhavepermissiontoreadfrominthe
directory.Ithasnothingtodowithexecutingafile.
Whenyouhaveonlyexecutepermissionforadirectory,youcan
uselstolistafileinthedirectoryifyouknowitsname.You
cannotuselswithoutanargumenttolisttheentirecontentsof
thedirectory.Inthefollowingexchange,Jennyfirstverifiesthat
sheisloggedinasherself.Thenshechecksthepermissionson
Alex'sinfodirectory.Youcanviewtheaccesspermissions
associatedwithadirectorybyrunninglswiththed(directory)
andl(long)options:
$whoami
jennypts/7Aug2110:02
$ls-ld/home/alex/info
drwx-----x2alexpubs512Aug2109:31/home/alex/info
$ls-l/home/alex/info
ls:/home/alex/info:Permissiondenied
Thedattheleftendofthelinethatlsdisplaysindicatesthat
/home/alex/infoisadirectory.Alexhasread,write,and
executepermissions;membersofthepubsgrouphaveno
accesspermissions;andotherusershaveexecutepermission
only,asindicatedbythexattherightendofthepermissions.
BecauseJennydoesnothavereadpermissionforthedirectory,
thelslcommandreturnsanerror.
WhenJennyspecifiesthenamesofthefilesshewants
informationabout,sheisnotreadingnewdirectoryinformation
butrathersearchingforspecificinformation,whichsheis
allowedtodowithexecuteaccesstothedirectory.Shehasread
permissionfornotessoshehasnoproblemusingcattodisplay
thefile.Shecannotdisplayfinancialbecauseshedoesnot
havereadpermissionforit:
$ls-l/home/alex/info/financial/home/alex/info/notes
-rw-------1alexpubs34Aug2109:31/home/alex/info/financial
-rw-r--r--1alexpubs30Aug2109:32/home/alex/info/notes
$cat/home/alex/info/notes
Thisisthefilenamednotes.
$cat/home/alex/info/financial
cat:/home/alex/info/financial:Permissiondenied
NextAlexgivesothersreadaccesstohisinfodirectory:
$chmodo+r/home/alex/info
WhenJennychecksheraccesspermissionsoninfo,shefinds
thatshehasbothreadandexecuteaccesstothedirectory.Now
lslworksjustfinewithoutarguments,butshestillcannotread
financial.(Thisrestrictionisanissueoffilepermissions,not
directorypermissions.)Finally,Jennytriestocreateafile
namednewfilebyusingtouch.IfAlexweretogiveherwrite
permissiontotheinfodirectory,Jennywouldbeabletocreate
newfilesinit:
$ls-ld/home/alex/info
drwx---r-x2alexpubs512Aug2109:31/home/alex/info
$ls-l/home/alex/info
total8
-rw-------1alexpubs34Aug2109:31financial
-rw-r--r--1alexpubs30Aug2109:32notes
$cat/home/alex/info/financial
cat:financial:Permissiondenied
$touch/home/alex/info/newfile
touch:cannottouch'/home/alex/info/newfile':Permissiondenied
ACLs:AccessControlLists
AccessControlLists(ACLs)providefiner-grainedcontrolover
whichuserscanaccessspecificdirectoriesandfilesthando
traditionalLinuxpermissions(page180).UsingACLsyoucan
specifythewaysinwhicheachofseveraluserscanaccessa
directoryorfile.BecauseACLscanreduceperformance,donot
enablethemonfilesystemsthatholdsystemfiles,wherethe
traditionalLinuxpermissionsaresufficient.Alsobecarefulwhen
moving,copying,orarchivingfiles:Notallutilitiespreserve
ACLs.Inaddition,youcannotcopyACLstofilesystemsthatdo
notsupportACLs.
Caution:Mostutilitiesdonotpreserve
ACLs
Whenusedwiththep(preserve)ora(archive)
option,cppreservesACLswhenitcopiesfiles.
AnotherutilitythatissuppliedwithRedHatLinux
thatpreservesACLsismv.Whenyouusecpwiththe
poraoptionanditisnotabletocopyACLs,andin
thecasewheremvisunabletopreserveACLs,the
utilityperformstheoperationandissuesanerror
message:
$mvreport/tmp
mv:preservingpermissionsfor'/tmp/report':Operationnotsupported
Otherutilities,suchastar,cpio,anddump,donot
supportACLs.Youcanusecpwiththeaoptionto
copydirectoryhierarchies,includingACLs.
YoucannevercopyACLstoafilesystemthatdoes
notsupportACLsortoafilesystemthatdoesnot
haveACLsupportturnedon.
AnACLcomprisesasetofrules.Arulespecifieshowaspecific
userorgroupcanaccessthefilethattheACLisassociated
with.Therearetwokindsofrules:accessrulesanddefault
rules.(ThedocumentationreferstoaccessACLsanddefault
ACLs,eventhoughthereisonlyonetypeofACL:Thereisone
typeoflist[ACL]andtherearetwotypesofrulesthatanACL
cancontain.)
Anaccessrulespecifiesaccessinformationforasinglefileor
directory.AdefaultACLpertainstoadirectoryonly;itspecifies
defaultaccessinformation(anACL)foranyfileinthedirectory
thatisnotgivenanexplicitACL.
EnablingACLs
RedHatLinuxofficiallysupportsACLsonext2andext3
filesystemsonly,althoughinformalsupportforACLsisavailable
onotherfilesystems.TouseACLsonanext2orext3
filesystem,youmustmountthedevicewiththeacloption
(no_aclisthedefault).Forexample,ifyouwanttomountthe
devicerepresentedby/homesothatyoucanuseACLsonfiles
in/home,youcanaddacltoitsoptionslistin/etc/fstab:
$grephome/etc/fstab
LABEL=/home/homeext3defaults,acl12
Afterchangingfstab,youneedtoremount/homebeforeyou
canuseACLs.Ifnooneelseisusingthesystem,youcan
unmountitandmountitagain(workingasroot)aslongas
yourworkingdirectoryisnotinthe/homehierarchy.
Alternativelyyoucanusetheremountoptiontomountto
remount/homewhilethedeviceisinuse:
#mount-v-oremount/home
/dev/hda3on/hometypeext3(rw,acl)
Seepage469forinformationonfstabandpage466for
informationonmount.
WorkingwithAccessRules
Thesetfaclutilitymodifiesafile'sACLandthegetfaclutility
displaysafile'sACL.Whenyouusegetfacltoobtaininformation
aboutafilethatdoesnothaveanACL,itdisplaysthesame
informationasanlslcommand,albeitinadifferentformat:
$ls-lreport
-rw-r--r--1maxmax9537Jan1223:17report
$getfaclreport
#file:report
#owner:max
#group:max
user::rw
group::r--
other::r--
Thefirstthreelinesofthegetfacloutputarecalledtheheader;
theyspecifythenameofthefile,theownerofthefile,andthe
groupthefileisassociatedwith.Formoreinformationreferto
"lsl:DisplaysPermissions"onpage181.Theomit-header(or
justomit)optioncausesgetfaclnottodisplaytheheader:
$getfacl--omit-headerreport
user::rw
group::r--
other::r--
Inthelinethatstartswithuser,thetwocolons(::)withno
namebetweenthemindicatethatthelinespecifiesthe
permissionsfortheownerofthefile.Similarly,thetwocolons
inthegrouplineindicatethatthelinespecifiespermissionsfor
thegroupthefileisassociatedwith.Thetwocolonsfollowing
otherarethereforconsistency:Nonamecanbeassociated
withother.
Thesetfaclmodify(orm)optionaddsormodifiesoneormore
rulesinafile'sACLusingthefollowingformat:
setfaclmodifyugo:name:permissionsfile-list
whereugocanbeeitheru,g,orotoindicatethatthe
commandsetsfilepermissionsforauser,agroup,orallother
users,respectively;nameisthenameoftheuserorgroupthat
permissionsarebeingsetfor;permissionsisthepermissions
ineithersymbolicorabsoluteformat;andfile-lististhelistof
filesthatthepermissionsaretobeappliedto.Youmustomit
namewhenyouspecifypermissionsforotherusers(o).
Symbolicpermissionsuseletterstorepresentfilepermissions
(rwx,rx,andsoon),whereasabsolutepermissionsusean
octalnumber.Whilechmodusesthreesetsofpermissionsor
threeoctalnumbers(oneeachfortheowner,group,andother
users),setfaclusesasinglesetofpermissionsorasingleoctal
numbertorepresentthepermissionsbeinggrantedtotheuser
orgrouprepresentedbyugoandname.
Forexample,bothofthefollowingcommandsaddaruletothe
ACLforthereportfilethatgivesSamreadandwrite
permissiontothatfile:
$setfacl--modifyu:sam:rw-report
or
$setfacl--modifyu:sam:6report
$getfaclreport
#file:report
#owner:max
#group:max
user::rw-
user:sam:rw-
group::r--
mask::rw--
other::r--
Thelinecontaininguser:sam:rwshowsthattheusernamed
samhasreadandwriteaccess(rw)tothefile.Seepage181
foranexplanationofhowtoreadsymbolicaccesspermissions.
Seethefollowingoptionalsectionforadescriptionoftheline
thatstartswithmask.
WhenafilehasanACL,lsldisplaysaplussign(+)following
thepermissions,eveniftheACLisempty:
$ls-lreport
-rw-rw-r--+1maxmax9537Jan1223:17report
Optional:EffectiveRightsMask
Thelinethatstartswithmaskspecifiestheeffectiverightsmask.Thismask
limitstheeffectivepermissionsgrantedtoACLgroupsandusers.Itdoesnot
affecttheownerofthefileorthegroupthefileisassociatedwith.Inother
words,itdoesnotaffecttraditionalLinuxpermissions.However,becausegetfacl
alwayssetstheeffectiverightsmasktotheleastrestrictiveACLpermissionsfor
thefile,themaskhasnoeffectunlessyousetitexplicitlyafteryousetupan
ACLforthefile.Youcansetthemaskbyspecifyingmaskinplaceofugoandby
notspecifyinganameinasetfaclcommand.
Thefollowingexamplesetstheeffectiverightsmasktoreadforthereportfile:
$setfacl-mmask::r--report
Themasklineinthefollowinggetfacloutputshowstheeffectiverightsmaskset
toread(r).ThelinethatdisplaysSam'sfileaccesspermissionsshowsthemstill
settoreadandwrite.However,thecommentattherightendofthelineshows
thathiseffectivepermissionisread.
$getfaclreport
#file:report
#owner:max
#group:max
user::rw-
user:sam:rw-#effective:r--
group::r--
mask::r--
other::r--
Asthenextexampleshows,setfaclcanmodifyACLrulesandcan
setmorethanoneACLruleatatime:
$setfacl-mu:sam:r--,u:zach:rw-report
$getfacl--omit-headerreport
user::rw--
user:sam:r--
user:zach:rw--
group::r--
mask::rw--
other::r--
ThexoptionremovesACLrulesforauseroragroup.Ithasno
effectonpermissionsfortheownerofthefileorthegroupthat
thefileisassociatedwith.Thenextexampleshowssetfacl
removingtherulethatgivesSampermissiontoaccessthefile:
$setfacl-xu:samreport
$getfacl--omit-headerreport
user::rw--
user:zach:rw--
group::r--
mask::rw--
other::r--
Youmustnotspecifypermissionswhenyouusethexoption.
Instead,specifyonlytheugoandname.Theboption,followed
byafilenameonly,removesallACLrulesandtheACLitself
fromthefileordirectoryyouspecify.
Bothsetfaclandgetfaclhavemanyoptions.Usethehelpoption
todisplaybrieflistsofoptionsorrefertothemanpagesfor
details.
SettingDefaultRulesforaDirectory
Thefollowingexampleshowsthatthedirdirectoryinitiallyhas
noACL.Thesetfaclcommandusesthedoptiontoaddtwo
defaultrulestotheACLfordir.Theserulesapplytoallfilesin
thedirdirectorythatdonothaveexplicitACLs.Therulesgive
membersofthepubsgroupreadandexecutepermissionsand
givemembersoftheadmingroupread,write,andexecute
permissions.
$ls-lddir
drwx------2maxmax4096Feb1223:15dir
$getfacldir
#file:dir
#owner:max
#group:max
user::rwx
group::---
other::---
$setfacl-d-mg:pubs:r-x,g:admin:rwxdir
Thefollowinglscommandshowsthatthedirdirectorynowhas
anACL,asindicatedbythe+totherightofthepermissions.
Eachofthedefaultrulesthatgetfacldisplaysstartswith
default:.Thefirsttwodefaultrulesandthelastdefaultrule
specifythepermissionsfortheownerofthefile,thegroupthat
thefileisassociatedwith,andallotherusers.Thesethreerules
specifythetraditionalLinuxpermissionsandtakeprecedence
overotherACLrules.Thethirdandfourthrulesspecifythe
permissionsforthepubsandadmingroups.Nextisthe
defaulteffectiverightsmask.
$ls-lddir
drwx------+2maxmax4096Feb1223:15dir
$getfacldir
#file:dir
#owner:max
#group:max
user::rwx
group::---
other::---
default:user::rwx
default:group::---
default:group:pubs:r-x
default:group:admin:rwx
default:mask::rwx
default:other::---
Rememberthatthedefaultrulespertaintofilesheldinthe
directorythatarenotassignedACLsexplicitly.Youcanalso
specifyaccessrulesforthedirectoryitself.
Whenyoucreateafilewithinadirectorythathasdefaultrules
initsACL,theeffectiverightsmaskforthatfileiscreatedbased
onthefile'spermissions.Insomecasesthemaskmayoverride
defaultACLrules.
Inthenextexample,touchcreatesafilenamednewinthedir
directory.ThelscommandshowsthatthisfilehasanACL.
Basedonthevalueofumask(page420),boththeownerandthe
groupthatthefileisassociatedwithhavereadandwrite
permissionsforthefile.Theeffectiverightsmaskissettoread
andwritesothattheeffectivepermissionforpubsisreadand
theeffectivepermissionsforadminarereadandwrite.Neither
grouphasexecutepermission.
$cddir
$touchnew
$ls-lnew
-rw-rw----+1maxmax0Feb1300:39new
$getfacl--omitnew
user::rw-
group::---
group:pubs:r-x#effective:r--
group:admin:rwx#effective:rw-
mask::rw-
other::---
Ifyouchangethefile'straditionalpermissionstoread,write,
andexecutefortheownerandthegroup,theeffectiverights
maskchangestoread,write,andexecuteandthegroups
specifiedbythedefaultrulesgainexecuteaccesstothefile.
$chmod770new
$ls-lnew
-rwxrwx---+1maxmax0Feb1300:39new
$getfacl--omitnew
user::rwx
group::---
group:pubs:r-x
group:admin:rwx
mask::rwx
other::---
Links
Alinkisapointertoafile.Everytimeyoucreateafilebyusing
vim,touch,cp,oranyothermeans,youareputtingapointerina
directory.Thispointerassociatesafilenamewithaplaceonthe
disk.Whenyouspecifyafilenameinacommand,youare
indirectlypointingtotheplaceonthediskthatholdsthe
informationyouwant.
Sharingfilescanbeusefulwhentwoormorepeopleare
workingonthesameprojectandneedtosharesome
information.Youcanmakeiteasyforotheruserstoaccessone
ofyourfilesbycreatingadditionallinkstothefile.
Toshareafilewithanotheruser,firstgivetheuserpermission
toreadfromandwritetothefile(page182).Youmayalso
havetochangetheaccesspermissionsoftheparentdirectory
ofthefiletogivetheuserread,write,orexecutepermission
(page184).Oncethepermissionsareappropriatelyset,the
usercancreatealinktothefilesothateachofyoucanaccess
thefilefromyourseparatedirectoryhierarchies.
Alinkcanalsobeusefultoasingleuserwithalargedirectory
hierarchy.Youcancreatelinkstocross-classifyfilesinyour
directoryhierarchy,usingdifferentclassificationsfordifferent
tasks.Forexample,ifyouhavethefilelayoutdepictedinFigure
6-2onpage167,afilenamedto_domightappearineach
subdirectoryofthecorresponddirectorythatis,inpersonal,
memos,andbusiness.Ifyoufinditdifficulttokeeptrackof
everythingyouneedtodo,youcancreateaseparatedirectory
namedto_dointhecorresponddirectory.Youcanthenlink
eachsubdirectory'sto-dolistintothatdirectory.Forexample,
youcouldlinkthefilenamedto_dointhememosdirectoryto
afilenamedmemosintheto_dodirectory.Thissetoflinksis
showninFigure6-13.
Figure6-13.Usinglinkstocross-classifyfiles
[Viewfullsizeimage]
Althoughitmaysoundcomplicated,thistechniquekeepsall
yourto-dolistsconvenientlyinoneplace.Theappropriatelistis
easilyaccessibleinthetask-relateddirectorywhenyouare
busycomposingletters,writingmemos,orhandlingpersonal
business.
Tip:Aboutthediscussionofhardlinks
Twokindsoflinksexist:hardlinksandsymbolic
(soft)links.Hardlinksareolderandbecoming
outdated.Thesectiononhardlinksismarkedas
optional;youcanskipit,althoughitdiscusses
inodesandgivesyouinsightintothestructureofthe
filesystem.
Optional:HardLinks
Ahardlinktoafileappearsasanotherfile.Ifthefileappearsinthesame
directoryasthelinked-tofile,thelinksmusthavedifferentfilenamesbecause
twofilesinthesamedirectorycannothavethesamename.Youcancreatea
hardlinktoafileonlyfromwithinthefilesystemthatholdsthefile.
ln:CreatesaHardLink
Theln(link)utility(withoutthesorsymbolicoption)createsahardlinktoan
existingfileusingthefollowingsyntax:
lnexisting-filenew-link
ThenextcommandmakesthelinkshowninFigure6-14bycreatinganewlink
named/home/alex/lettertoanexistingfilenameddraftinJenny'shome
directory:
$pwd
/home/jenny
$lndraft/home/alex/letter
Figure6-14.Twolinkstothesamefile:/home/alex/letterand
/home/jenny/draft
Thenewlinkappearsinthe/home/alexdirectorywiththe
filenameletter.Inpractice,Alexmayneedtochangethe
directoryandfilepermissionssothatJennywillbeableto
accessthefile.Eventhough/home/alex/letterappearsin
Alex'sdirectory,Jennyistheownerofthefilebecauseshe
createdit.
Thelnutilitycreatesanadditionalpointertoanexistingfilebut
itdoesnotmakeanothercopyofthefile.Becausethereisonly
onefile,thefilestatusinformationsuchasaccesspermissions,
owner,andthetimethefilewaslastmodifiedisthesameforall
links;onlythefilenamesdiffer.WhenJennymodifies
/home/jenny/draft,forexample,Alexseesthechangesin
/home/alex/letter.
cpversusln
Thefollowingcommandsverifythatlndoesnotmakean
additionalcopyofafile.Createafile,uselntomakean
additionallinktothefile,changethecontentsofthefile
throughonelink,andverifythechangethroughtheotherlink:
$catfile_a
ThisisfileA.
$lnfile_afile_b
$catfile_b
ThisisfileA.
$vimfile_b
...
$catfile_b
ThisisfileBafterthechange.
$catfile_a
ThisisfileBafterthechange.
Ifyoutrythesameexperimentusingcpinsteadoflnand
changeacopyofthefile,thedifferencebetweenthetwo
utilitieswillbecomeclearer.Onceyouchangeacopyofafile,
thetwofilesaredifferent:
$catfile_c
ThisisfileC.
$cpfile_cfile_d
$catfile_d
ThisisfileC.
$vimfile_d
...
$catfile_d
ThisisfileDafterthechange.
$catfile_c
ThisisfileC.
lsandlinkcounts
Youcanuselswiththeloption,followedbythenamesofthe
filesyouwanttocompare,toconfirmthatthestatus
informationisthesamefortwolinkstothesamefileandis
differentforfilesthatarenotlinked.Inthefollowingexample,
the2inthelinksfield(justtotheleftofalex)showsthereare
twolinkstofile_aandfile_b:
$ls-lfile_afile_bfile_cfile_d
-rw-r--r--2alexpubs33May2410:52file_a
-rw-r--r--2alexpubs33May2410:52file_b
-rw-r--r--1alexpubs16May2410:55file_c
-rw-r--r--1alexpubs33May2410:57file_d
Althoughitiseasytoguesswhichfilesarelinkedtoone
anotherinthisexample,lsdoesnotexplicitlytellyou.
lsandinodes
Uselswiththeioptiontodeterminewithoutadoubtwhichfiles
arelinked.Theioptionliststheinode(page1037)numberfor
eachfile.Aninodeisthecontrolstructureforafile.Ifthetwo
filenameshavethesameinodenumber,theysharethesame
controlstructureandarelinkstothesamefile.Conversely,
whentwofilenameshavedifferentinodenumbers,theyare
differentfiles.Thefollowingexampleshowsthatfile_aand
file_bhavethesameinodenumberandthatfile_candfile_d
havedifferentinodenumbers:
$ls-ifile_afile_bfile_cfile_d
3534file_a3534file_b5800file_c7328file_d
Alllinkstoafileareofequalvalue:Theoperatingsystem
cannotdistinguishtheorderinwhichmultiplelinkswere
created.Whenafilehastwolinks,youcanremoveeitherone
andstillaccessthefilethroughtheremaininglink.Youcan
removethelinkusedtocreatethefile,forexample,and,as
longasonelinkremains,stillaccessthefilethroughthatlink.
SymbolicLinks
Inadditiontohardlinks,Linuxsupportssymboliclinks,also
calledsoftlinksorsymlinks.Ahardlinkisapointertoafile
(thedirectoryentrypointstotheinode),whereasasymbolic
linkisanindirectpointertoafile(thedirectoryentrycontains
thepathnameofthepointed-tofileapointertothehardlinkto
thefile).
Advantagesofsymboliclinks
Symboliclinksweredevelopedbecauseofthelimitations
inherentinhardlinks.Youcannotcreateahardlinktoa
directory,butyoucancreateasymboliclinktoadirectory.
InmanycasestheLinuxfilehierarchyencompassesseveral
filesystems.Becauseeachfilesystemkeepsseparatecontrol
information(thatis,separateinodetablesorfilesystem
structures)forthefilesitholds,itisnotpossibletocreatehard
linksbetweenfilesindifferentfilesystems.Asymboliclinkcan
pointtoanyfile,regardlessofwhereitislocatedinthefile
structure,butahardlinktoafilemustbeinthesame
filesystemastheotherhardlink(s)tothefile.Whenyoucreate
linksonlyamongfilesinyourhomedirectory,youwillnot
noticethislimitation.
Amajoradvantageofasymboliclinkisthatitcanpointtoa
nonexistentfile.Thisabilityisusefulifyouneedalinktoafile
thatisperiodicallyremovedandrecreated.Ahardlinkkeeps
pointingtoa"removed"file,whichthelinkkeepsaliveeven
afteranewfileiscreated.Incontrast,asymboliclinkalways
pointstothenewlycreatedfileanddoesnotinterferewhenyou
deletetheoldfile.Forexample,asymboliclinkcouldpointtoa
filethatgetscheckedinandoutunderasourcecodecontrol
system,a.ofilethatisre-createdbytheCcompilereachtime
yourunmake,oralogfilethatisrepeatedlyarchived.
Althoughtheyaremoregeneralthanhardlinks,symboliclinks
havesomedisadvantages.Whereasallhardlinkstoafilehave
equalstatus,symboliclinksdonothavethesamestatusas
hardlinks.Whenafilehasmultiplehardlinks,itisanalogousto
apersonhavingmultiplefulllegalnames,asmanymarried
womendo.Incontrast,symboliclinksareanalogousto
nicknames.Anyonecanhaveoneormorenicknames,butthese
nicknameshavealesserstatusthanlegalnames.Thefollowing
sectionsdescribesomeofthepeculiaritiesofsymboliclinks.
ln:CreatesaSymbolicLink
Youuselnwiththesymbolic(ors)optiontocreateasymbolic
link.Thefollowingexamplecreatesasymboliclink/tmp/s3to
thefilesuminAlex'shomedirectory.Whenyouuseanlsl
commandtolookatthesymboliclink,lsdisplaysthenameof
thelinkandthenameofthefileitpointsto.Thefirstcharacter
ofthelistingisl(forlink).
$ln--symbolic/home/alex/sum/tmp/s3
$ls-l/home/alex/sum/tmp/s3
-rw-rw-r--1alexalex38Jun1209:51/home/alex/sum
lrwxrwxrwx1alexalex14Jun1209:52/tmp/s3->/home/alex/sum
$cat/tmp/s3
Thisissum.
Thesizesandtimesofthelastmodificationsofthetwofilesare
different.Unlikeahardlink,asymboliclinktoafiledoesnot
havethesamestatusinformationasthefileitself.
Youcanalsouselntocreateasymboliclinktoadirectory.
Whenyouusethesymbolicoption,lndoesnotcarewhether
thefileyouarecreatingalinktoisanordinaryfileora
directory.
Tip:Useabsolutepathnameswith
symboliclinks
Symboliclinksareliteralandarenotawareof
directories.Alinkthatpointstoarelativepathname,
whichincludessimplefilenames,assumesthatthe
relativepathnameisrelativetothedirectorythat
thelinkwascreatedin(notthedirectorythelink
wascreatedfrom).Inthefollowingexample,thelink
pointstothefilenamedsuminthe/tmpdirectory.
Becausenosuchfileexists,catgivesanerror
message:
$pwd
/home/alex
$ln--symbolicsum/tmp/s4
$ls-lsum/tmp/s4
lrwxrwxrwx1alexalex3Jun1210:13/tmp/s4->sum
-rw-rw-r--1alexalex38Jun1209:51sum
$cat/tmp/s4
cat:/tmp/s4:Nosuchfileordirectory
Optional:cdandSymbolicLinks
Whenyouuseasymboliclinkasanargumenttocdtochangedirectories,the
resultscanbeconfusing,particularlyifyoudidnotrealizethatyouwereusinga
symboliclink.
Ifyouusecdtochangetoadirectorythatisrepresentedbyasymboliclink,the
pwdshellbuiltinliststhenameofthesymboliclink.Thepwdutility(/bin/pwd)
liststhenameofthelinked-todirectory,notthelink,regardlessofhowyougot
there.
$ln-s/home/alex/grades/tmp/grades.old
$pwd
/home/alex
$cd/tmp/grades.old
$pwd
/tmp/grades.old
$/bin/pwd
/home/alex/grades
Whenyouchangedirectoriesbacktotheparent,youendupinthedirectory
holdingthesymboliclink:
$cd..
$pwd
/tmp
$/bin/pwd
/tmp
rm:RemovesaLink
Whenyoucreateafile,thereisonehardlinktoit.Youcanthen
deletethefileor,usingLinuxterminology,removethelinkwith
thermutility.Whenyouremovethelasthardlinktoafile,you
cannolongeraccesstheinformationstoredthereandthe
operatingsystemreleasesthespacethefileoccupiedonthe
diskforsubsequentusebyotherfiles.Thisspaceisreleased
evenifsymboliclinkstothefileremain.Whenthereismore
thanonehardlinktoafile,youcanremoveahardlinkandstill
accessthefilefromanyremaininglink.UnlikeDOSand
Windows,Linuxdoesnotprovideaneasywaytoundeleteafile
onceyouhaveremovedit.Askilledhacker,however,can
sometimespiecethefiletogetherwithtimeandeffort.
Whenyouremoveallhardlinkstoafile,youwillnotbeableto
accessthefilethroughasymboliclink.Inthefollowing
example,catreportsthatthefiletotaldoesnotexistbecauseit
isasymboliclinktoafilethathasbeenremoved:
$ls-lsum
-rw-r--r--1alexpubs981May2411:05sum
$ln-ssumtotal
$rmsum
$cattotal
cat:total:Nosuchfileordirectory
$ls-ltotal
lrwxrwxrwx1alexpubs6May2411:09total->sum
Whenyouremoveafile,besuretoremoveallsymboliclinksto
it.Removeasymboliclinkinthesamewayyouremoveother
files:
$rmtotal
ChapterSummary
Linuxhasahierarchical,ortreelike,filestructurethatmakesit
possibletoorganizefilessothatyoucanfindthemquicklyand
easily.Thefilestructurecontainsdirectoryfilesandordinary
files.Directoriescontainotherfiles,includingotherdirectories;
ordinaryfilesgenerallycontaintext,programs,orimages.The
ancestorofallfilesistherootdirectorynamed/.
MostLinuxfilesystemssupport255-characterfilenames.
Nonetheless,itisagoodideatokeepfilenamessimpleand
intuitive.Filenameextensionscanhelpmakefilenamesmore
meaningful.
Whenyouareloggedin,youarealwaysassociatedwitha
workingdirectory.Yourhomedirectoryisyourworkingdirectory
fromthetimeyouloginuntilyouusecdtochangedirectories.
Anabsolutepathnamestartswiththerootdirectoryand
containsallthefilenamesthattraceapathtoagivenfile.The
pathnamestartswithaslash,representingtherootdirectory,
andcontainsadditionalslashesbetweentheotherfilenamesin
thepath.
Arelativepathnameissimilartoanabsolutepathnamebut
tracesthepathstartingfromtheworkingdirectory.Asimple
filenameisthelastelementofapathnameandisaformofa
relativepathname.
ALinuxfilesystemcontainsmanyimportantdirectories,
including/usr/bin,whichstoresmostoftheLinuxutility
commands,and/dev,whichstoresdevicefiles,manyofwhich
representphysicalpiecesofhardware.Animportantstandard
fileis/etc/passwd;itcontainsinformationaboutusers,such
aseachuser'sIDandfullname.
Amongtheattributesassociatedwitheachfileareaccess
permissions.Theydeterminewhocanaccessthefileandhow
thefilemaybeaccessed.Threegroupsofuserscanpotentially
accessthefile:theowner,themembersofagroup,andall
otherusers.Anordinaryfilecanbeaccessedinthreeways:
read,write,andexecute.Thelsutilitywiththeloptiondisplays
thesepermissions.Fordirectories,executeaccessisredefined
tomeanthatthedirectorycanbesearched.
TheownerofafileorSuperusercanusethechmodutilityto
changetheaccesspermissionsofafile.Thisutilityspecifies
read,write,andexecutepermissionsforthefile'sowner,the
group,andallotherusersonthesystem.
AccessControlLists(ACLs)providefiner-grainedcontrolover
whichuserscanaccessspecificdirectoriesandfilesthando
traditionalLinuxpermissions.UsingACLsyoucanspecifythe
waysinwhicheachofseveraluserscanaccessadirectoryor
file.FewutilitiespreserveACLswhenworkingwiththesefiles.
Anordinaryfilestoresuserdata,suchastextualinformation,
programs,orimages.Adirectoryisastandard-formatdiskfile
thatstoresinformation,includingnames,aboutordinaryfiles
andotherdirectoryfiles.Aninodeisadatastructure,storedon
disk,thatdefinesafile'sexistenceandisidentifiedbyaninode
number.Adirectoryrelateseachofthefilenamesitstorestoa
specificinode.
Alinkisapointertoafile.Youcanhaveseverallinkstoasingle
filesothatyoucansharethefilewithotherusersorhavethe
fileappearinmorethanonedirectory.Becauseonlyonecopy
ofafilewithmultiplelinksexists,changingthefilethroughany
onelinkcausesthechangestoappearinallthelinks.Hardlinks
cannotlinkdirectoriesorspanfilesystems,whereassymbolic
linkscan.
Table6-2summarizestheutilitiesintroducedinthischapter.
Table6-2.UtilitiesintroducedinChapter6
Table6-2.UtilitiesintroducedinChapter6
Utility Function
cd Associatesyouwithanotherworkingdirectory(page
174)
chmod Changestheaccesspermissionsonafile(page182)
getfacl Displaysafile'sACL(page186)
ln Makesalinktoanexistingfile(page192)
mkdir Createsadirectory(page173)
pwd Displaysthepathnameoftheworkingdirectory(page
170)
rmdir Deletesadirectory(page178)
setfacl Modifiesafile'sACL(page186)
Exercises
1.
Iseachofthefollowinganabsolutepathname,arelativepathname,orasimple
filename?
a. milk_co
b. correspond/business/milk_co
c. /home/alex
d. /home/alex/literature/promo
e. ..
f. letter.0610
2.
Listthecommandsyoucanusetoperformtheseoperations:
a. Makeyourhomedirectorytheworkingdirectory
b. Identifytheworkingdirectory
3.
Ifyourworkingdirectoryis/home/alexwithasubdirectorynamedliterature,
givethreesetsofcommandsthatyoucanusetocreateasubdirectorynamed
classicsunderliterature.Alsogiveseveralsetsofcommandsyoucanuseto
removetheclassicsdirectoryanditscontents.
4.
Thedfutilitydisplaysallmountedfilesystemsalongwithinformationabouteach.
Usethedfutilitywiththeh(human-readable)optiontoanswerthefollowing
questions.
a. HowmanyfilesystemsaremountedonyourLinuxsystem?
b. Whichfilesystemstoresyourhomedirectory?
c. Assumingthatyouranswertoexercise4aistwoormore,attempttocreate
ahardlinktoafileonanotherfilesystem.Whaterrormessagedoyouget?
Whathappenswhenyouattempttocreateasymboliclinktothefileinstead?
5. Supposethatyouhaveafilethatislinkedtoafileownedbyanotheruser.How
canyouensurethatchangestothefilearenolongershared?
Youshouldhavereadpermissionforthe/etc/passwdfile.Toanswerthe
followingquestions,usecatorlesstodisplay/etc/passwd.Lookatthefieldsof
6.
informationin/etc/passwdfortheusersonyoursystem.
a. Whichcharacterisusedtoseparatefieldsin/etc/passwd?
b. Howmanyfieldsareusedtodescribeeachuser?
c. Howmanyusersareonyoursystem?
d. Howmanydifferentloginshellsareinuseonyoursystem?(Hint:Lookatthe
lastfield.)
e. Thesecondfieldof/etc/passwdstoresuserpasswordsinencodedform.If
thepasswordfieldcontainsanx,yoursystemusesshadowpasswordsand
storestheencodedpasswordselsewhere.Doesyoursystemuseshadow
passwords?
7.
If/home/jenny/draftand/home/alex/letterarelinkstothesamefileand
thefollowingsequenceofeventsoccurs,whatwillbethedateintheopeningof
theletter?
a. Alexgivesthecommandvimletter.
b. Jennygivesthecommandvimdraft.
c. JennychangesthedateintheopeningofthelettertoJanuary31,2006,
writesthefile,andexitsfromvim.
d. AlexchangesthedatetoFebruary1,2006,writesthefile,andexitsfrom
vim.
8.
Supposethatauserbelongstoagroupthathasallpermissionsonafilenamed
jobs_list,buttheuser,astheownerofthefile,hasnopermissions.Describe
whichoperations,ifany,theuser/ownercanperformonjobs_list.Which
commandcantheuser/ownergivethatwillgranttheuser/ownerallpermissions
onthefile?
9.
Doestherootdirectoryhaveanysubdirectoriesthatyoucannotsearchasa
regularuser?Doestherootdirectoryhaveanysubdirectoriesthatyoucannotread
asaregularuser?Explain.
10.
AssumethatyouaregiventhedirectorystructureshowninFigure6-2onpage
167andthefollowingdirectorypermissions:
d--x--x---3jennypubs512Mar1015:16business
drwxr-xr-x2jennypubs512Mar1015:16business/milk_co
Foreachcategoryofpermissionsowner,group,andotherwhathappenswhenyou
runeachofthefollowingcommands?Assumethattheworkingdirectoryisthe
parentofcorrespondandthatthefilecheese_coisreadablebyeveryone.
a. cdcorrespond/business/milk_co
b. lslcorrespond/business
c. catcorrespond/business/cheese_co
AdvancedExercises
11. Whatisaninode?Whathappenstotheinodewhenyoumoveafilewithina
filesystem?
12. Whatdoesthe..entryinadirectorypointto?Whatdoesthisentrypointtointhe
root(/)directory?
13. Howcanyoucreateafilenamedi?Whichtechniquesdonotwork,andwhydo
theynotwork?Howcanyouremovethefilenamedi?
14.
Supposethattheworkingdirectorycontainsasinglefilenamedandor.Whaterror
messagedoyougetwhenyourunthefollowingcommandline?
$mvandorand\/or
Underwhatcircumstancesisitpossibletorunthecommandwithoutproducingan
error?
15.
Thelsicommanddisplaysafilenameprecededbytheinodenumberofthefile
(page193).Writeacommandtooutputinode/filenamepairsforthefilesinthe
workingdirectory,sortedbyinodenumber.(Hint:Useapipe.)
16. Doyouthinkthatthesystemadministratorhasaccesstoaprogramthatcan
decodeuserpasswords?Whyorwhynot?(Seeexercise6.)
17. Isitpossibletodistinguishafilefromahardlinktoafile?Thatis,givena
filename,canyoutellwhetheritwascreatedusinganlncommand?Explain.
18.
Explaintheerrormessagesdisplayedinthefollowingsequenceofcommands:
$ls-l
total1
drwxrwxr-x2alexpubs1024Mar217:57dirtmp
$lsdirtmp
$rmdirdirtmp
rmdir:dirtmp:Directorynotempty
$rmdirtmp/*
rm:Nomatch.
7.TheShell
INTHISCHAPTER
TheCommandLine 202
StandardInputandStandardOutput 208
Redirection 210
Pipes 216
RunningaProgramintheBackground 219
kill:AbortingaBackgroundJob 220
FilenameGeneration/PathnameExpansion 221
Builtins 225
Thischaptertakesacloselookattheshellandexplainshowto
usesomeofitsfeatures.Forexample,itdiscussescommand
linesyntaxandalsodescribeshowtheshellprocessesa
commandlineandinitiatesexecutionofaprogram.Thechapter
alsoexplainshowtoredirectinputtoandoutputfroma
command,constructpipesandfiltersonthecommandline,and
runacommandinthebackground.Thefinalsectioncovers
filenameexpansionandexplainshowyoucanusethisfeature
inyoureverydaywork.
Theexactwordingoftheshelloutputdiffersfromshelltoshell:
TheCommandLine
Theshellexecutesaprogramwhenyougiveitacommandin
responsetoitsprompt.Forexample,whenyougivethels
command,theshellexecutestheutilityprogramnamedls.You
cancausetheshelltoexecuteothertypesofprogramssuchas
shellscripts,applicationprograms,andprogramsyouhave
writteninthesameway.Thelinethatcontainsthecommand,
includinganyarguments,iscalledthecommandline.Inthis
bookthetermcommandreferstothecharactersyoutypeon
thecommandlineaswellastotheprogramthatactioninvokes.
Syntax
Commandlinesyntaxdictatestheorderingandseparationof
theelementsonacommandline.WhenyoupresstheRETURN
keyafterenteringacommand,theshellscansthecommand
lineforpropersyntax.Thesyntaxforabasiccommandlineis
command[arg1][arg2]...[argn]RETURN
OneormoreSPACEsmustseparateelementsonthecommand
line.Thecommandisthenameofthecommand,arg1
throughargnarearguments,andRETURNisthekeystrokethat
terminatesallcommandlines.Thebracketsinthecommand
linesyntaxindicatethattheargumentstheyencloseare
optional.Notallcommandsrequirearguments:Some
commandsdonotallowarguments;othercommandsallowa
variablenumberofarguments;andothersrequireaspecific
numberofarguments.Options,aspecialkindofargument,are
usuallyprecededbyoneortwohyphens(alsocalledadashor
minussign:).
CommandName
Usagemessage
SomeusefulLinuxcommandlinesconsistofonlythenameof
thecommandwithoutanyarguments.Forexample,lsbyitself
liststhecontentsoftheworkingdirectory.Mostcommands
acceptoneormorearguments.Commandsthatrequire
argumentstypicallygiveashorterrormessage,calledausage
message,whenyouusethemwithoutarguments,withincorrect
arguments,orwiththewrongnumberofarguments.
Arguments
Onthecommandlineeachsequenceofnonblankcharactersis
calledatokenorword.Anargumentisatoken,suchasa
filename,stringoftext,number,orotherobjectthata
commandactson.Forexample,theargumenttoavimoremacs
commandisthenameofthefileyouwanttoedit.
Thefollowingcommandlineshowscpcopyingthefilenamed
temptotempcopy:
$cptemptempcopy
Argumentsarenumberedstartingwiththecommanditselfas
argumentzero.Inthisexamplecpisargumentzero,tempis
argumentone,andtempcopyisargumenttwo.Thecputility
requirestwoargumentsonthecommandline.(Theutilitycan
takemoreargumentsbutnotfewer.)Argumentoneisthename
ofanexistingfile.Argumenttwoisthenameofthefilethatcp
iscreatingoroverwriting.Heretheargumentsarenotoptional;
bothargumentsmustbepresentforthecommandtowork.
Whenyoudonotsupplytherightnumberorkindofarguments,
cpdisplaysausagemessage.Trytypingcpandthenpressing
RETURN.
Options
Anoptionisanargumentthatmodifiestheeffectsofa
command.Youcanfrequentlyspecifymorethanoneoption,
modifyingthecommandinseveraldifferentways.Optionsare
specifictoandinterpretedbytheprogramthatthecommand
linecalls,nottheshell.
Byconventionoptionsareseparateargumentsthatfollowthe
nameofthecommandandusuallyprecedeotherarguments,
suchasfilenames.Mostutilitiesrequireyoutoprefixoptions
withasinglehyphen.However,thisrequirementisspecificto
theutilityandnottheshell.GNUprogramoptionsare
frequentlyprecededbytwohyphensinarow.Forexample,
helpgeneratesa(sometimesextensive)usagemessage.
Figure7-1firstshowswhathappenswhenyougiveanls
commandwithoutanyoptions.Bydefaultlsliststhecontentsof
theworkingdirectoryinalphabeticalorder,verticallysortedin
columns.Nextther(reverseorder;becausethisisaGNU
utility,youcanalsousereverse)optioncausesthelsutilityto
displaythelistoffilesinreversealphabeticalorder,stillsorted
incolumns.Thexoptioncauseslstodisplaythelistoffilesin
horizontallysortedrows.
Figure7-1.Usingoptions
$ls
alexhousemarkofficepersonaltest
holdjennynamesoldstufftemp
$ls-r
testpersonalofficemarkhousealex
tempoldstuffnamesjennyhold
$ls-x
alexholdhousejennymarknames
officeoldstuffpersonaltemptest
$ls-rx
testtemppersonaloldstuffofficenames
markjennyhouseholdalex
Combiningoptions
Whenyouneedtouseseveraloptions,youcanusuallygroup
multiplesingle-letteroptionsintooneargumentthatstartswith
asinglehyphen;donotputSPACEsbetweentheoptions.You
cannotcombineoptionsthatareprecededbytwohyphensin
thisway,however.Specificrulesforcombiningoptionsdepend
ontheprogramyouarerunning.Figure7-1showsbothther
andxoptionswiththelsutility.Togethertheseoptionsgenerate
alistoffilenamesinhorizontallysortedcolumns,inreverse
alphabeticalorder.Mostutilitiesallowyoutolistoptionsinany
order;thuslsxrproducesthesameresultsaslsrx.The
commandlsxralsogeneratesthesamelist.
Tip:Displayingreadablefilesizes:theh
option
Mostutilitiesthatreportonfilesizesspecifythesize
ofafileinbytes.Bytesworkwellwhenyouare
dealingwithsmallerfiles,butthenumberscanbe
difficulttoreadwhenyouareworkingwithfilesizes
thataremeasuredinmegabytesorgigabytes.Use
theh(orhuman-readable)optiontodisplayfile
sizesinkilo-,mega-,andgigabytes.Experiment
withdfh(diskfree)andlslhcommands.
Optionarguments
Someutilitieshaveoptionsthatthemselvesrequirearguments.
Forexample,thegccutilityhasaooptionthatmustbefollowed
bythenameyouwanttogivetheexecutablefilethatgcc
generates.Typicallyanargumenttoanoptionisseparatedfrom
itsoptionletterbyaSPACE:
$gcc-oprogprog.c
Argumentsthatstartwithahyphen
Anotherconventionallowsutilitiestoworkwitharguments,
suchasfilenames,thatstartwithahyphen.Ifafile'snameisl,
thefollowingcommandisambiguous:
$ls-l
Thiscommandcouldmeanalonglistingofallfilesinthe
workingdirectoryoralistingofthefilenamedl.Itis
interpretedastheformer.Youshouldavoidcreatingfileswhose
namesbeginwithhyphens.Ifyoudocreatethem,many
utilitiesfollowtheconventionthataargument(twoconsecutive
hyphens)indicatestheendoftheoptions(andthebeginningof
thearguments).Todisambiguatethecommand,youcantype
$ls---l
Youcanuseanalternativeformatinwhichtheperiodrefersto
theworkingdirectoryandtheslashindicatesthatthename
referstoafileintheworkingdirectory:
$ls./-l
Assumingthatyouareworkinginthe/home/alexdirectory,
theprecedingcommandisfunctionallyequivalentto
$ls/home/alex/-l
Youcangivethefollowingcommandtogetalonglistingofthis
file:
$ls-l---l
Theseareconventions,nothard-and-fastrules,andanumber
ofutilitiesdonotfollowthem(e.g.,find).Followingsuch
conventionsisagoodidea;itmakesitmucheasierforusersto
workwithyourprogram.Whenyouwriteshellprogramsthat
requireoptions,followtheLinuxoptionconventions.
Tip:Thehelpoption
Manyutilitiesdisplaya(sometimesextensive)help
messagewhenyoucallthemwithanargumentof
help.AllutilitiesdevelopedbytheGNUProject
(page2)acceptthisoption.Anexamplefollows.
$bzip2--help
bzip2,ablock-sortingfilecompressor.Version1.0.2,30-Dec-2001.
usage:bzip2[flagsandinputfilesinanyorder]
-h--helpprintthismessage
-d--decompressforcedecompression
-z--compressforcecompression
-k--keepkeep(don'tdelete)inputfiles
-f--forceoverwriteexistingoutputfiles
-t--testtestcompressedfileintegrity
-c--stdoutoutputtostandardout
-q--quietsuppressnoncriticalerrormessages
-v--verbosebeverbose(a2nd-vgivesmore)
...
ProcessingtheCommandLine
Asyouenteracommandline,theLinuxttydevicedriver(part
oftheLinuxoperatingsystemkernel)examineseachcharacter
toseewhetheritmusttakeimmediateaction.Whenyoupress
CONTROL-H(toeraseacharacter)orCONTROL-U(tokillaline),
thedevicedriverimmediatelyadjuststhecommandlineas
required;theshellneverseesthecharacter(s)youerasedor
thelineyoukilled.Oftenasimilaradjustmentoccurswhenyou
pressCONTROL-W(toeraseaword).Whenthecharacteryou
entereddoesnotrequireimmediateaction,thedevicedriver
storesthecharacterinabufferandwaitsforadditional
characters.WhenyoupressRETURN,thedevicedriverpasses
thecommandlinetotheshellforprocessing.
Parsingthecommandline
Whentheshellprocessesacommandline,itlooksatthelineas
awholeandparses(breaks)itintoitscomponentparts(Figure
7-2).Nexttheshelllooksforthenameofthecommand.
Usuallythenameofthecommandisthefirstitemonthe
commandlineaftertheprompt(argumentzero).Theshell
takesthefirstcharactersonthecommandlineuptothefirst
blank(TABorSPACE)andthenlooksforacommandwiththat
name.Thecommandname(thefirsttoken)canbespecifiedon
thecommandlineeitherasasimplefilenameorasa
pathname.Forexample,youcancallthelscommandineither
ofthefollowingways:
$ls
$/bin/ls
Figure7-2.Processingthecommandline
Optional
Theshelldoesnotrequirethatthenameoftheprogramappearfirstonthe
commandline.Thusyoucanstructureacommandlineasfollows:
$>bb<aacat
Thiscommandrunscatwithstandardinputcomingfromthefilenamedaaand
standardoutputgoingtothefilenamedbb.Whentheshellrecognizesthe
redirectsymbols(page210),itrecognizesandprocessesthemandtheir
argumentsbeforefindingthenameoftheprogramthatthecommandlineis
calling.Thisisaproperlystructuredalbeitrarelyencounteredandpossibly
confusingcommandline.
Absoluteversusrelativepathnames
Whenyougiveanabsolutepathnameonthecommandlineora
relativepathnamethatisnotasimplefilename(i.e.,any
pathnamethatincludesatleastoneslash),theshelllooksin
thespecifieddirectory(/bininthecaseofthe/bin/ls
command)forafilethathasthenamelsandthatyouhave
permissiontoexecute.Whenyougiveasimplefilename,the
shellsearchesthroughalistofdirectoriesforafilenamethat
matchesthespecifiednameandthatyouhaveexecute
permissionfor.Theshelldoesnotlookthroughalldirectories
butonlytheonesspecifiedbythevariablenamedPATH.Refer
topage292formoreinformationonPATH.Alsorefertothe
discussionofthewhichandwhereisutilitiesonpage144.
Whenitcannotfindtheexecutablefile,theBourneAgainShell
(bash)displaysamessagesuchasthefollowing:
$abc
bash:abc:commandnotfound
Onereasontheshellmaynotbeabletofindtheexecutablefile
isthatitisnotinadirectoryinyourPATH.Underbashthe
followingcommandtemporarilyaddstheworkingdirectory(.)
toyourPATH:
$PATH=$PATH:.
Forsecurityreasons,youmaynotwanttoaddtheworking
directorytoPATHpermanently;seetheadjacenttipandthe
oneonpage293.
Tip:Trygivingacommandas
./command
Youcanalwaysexecuteanexecutablefileinthe
workingdirectorybyprepending./tothenameof
thefile.Forexample,ifmyprogisanexecutablefile
intheworkingdirectory,youcanexecuteitwiththe
followingcommand,regardlessofhowPATHisset:
$./myprog
Whentheshellfindstheprogrambutcannotexecuteit(youdo
nothaveexecutepermissionforthefilethatcontainsthe
program),itdisplaysamessagesimilarto
$def
bash:./def:Permissiondenied
See"lsl:DisplaysPermissions"onpage181forinformationon
displayingaccesspermissionsforafileand"chmod:Changes
AccessPermissions"onpage182forinstructionsonhowto
changefileaccesspermissions.
ExecutingtheCommandLine
Process
Ifitfindsanexecutablefilewiththesamenameasthe
command,theshellstartsanewprocess.Aprocessisthe
executionofacommandbyLinux(page300).Theshellmakes
eachcommandlineargument,includingoptionsandthename
ofthecommand,availabletothecalledprogram.Whilethe
commandisexecuting,theshellwaitsfortheprocesstofinish.
Atthispointtheshellisinaninactivestatecalledsleep.When
theprogramfinishesexecution,itpassesitsexitstatus(page
920)totheshell.Theshellthenreturnstoanactivestate
(wakesup),issuesaprompt,andwaitsforanothercommand.
Theshelldoesnotprocessarguments
Becausetheshelldoesnotprocesscommandlinearguments
butonlyhandsthemtothecalledprogram,theshellhasno
wayofknowingwhetheraparticularoptionorotherargument
isvalidforagivenprogram.Anyerrororusagemessages
aboutoptionsorargumentscomefromtheprogramitself.
Someutilitiesignorebadoptions.
EditingtheCommandLine
Youcanrepeatandeditpreviouscommandsandeditthe
currentcommandline.Seepages119and304formore
information.
StandardInputandStandardOutput
Standardoutputisaplacethataprogramcansend
information,suchastext.Theprogramnever"knows"where
theinformationitsendstostandardoutputisgoing(Figure7-
3).Theinformationcangotoaprinter,anordinaryfile,orthe
screen.Thefollowingsectionsshowthatbydefaulttheshell
directsstandardoutputfromacommandtothescreen[1]and
describehowyoucancausetheshelltoredirectthisoutputto
anotherfile.
[1]Thetermscreenisusedthroughoutthisbooktomeanscreen,terminalemulator
window,orworkstation.Screenreferstothedevicethatyouseethepromptand
messagesdisplayedon.
Figure7-3.Thecommanddoesnotknowwhere
standardinputcomesfromorwherestandard
outputandstandarderrorgo
Standardinputisaplacethataprogramgetsinformationfrom.
Aswithstandardoutputtheprogramnever"knows"wherethe
informationcamefrom.Thefollowingsectionsalsoexplainhow
toredirectstandardinputtoacommandsothatitcomesfrom
anordinaryfileinsteadoffromthekeyboard(thedefault).
Inadditiontostandardinputandstandardoutput,arunning
programnormallyhasaplacetosenderrormessages:standard
error.Refertopage270formoreinformationonhandling
standarderror.
TheScreenasaFile
Chapter6introducedordinaryfiles,directoryfiles,andhardand
softlinks.Linuxhasanadditionaltypeoffile:adevicefile.A
devicefileresidesintheLinuxfilestructure,usuallyinthe/dev
directory,andrepresentsaperipheraldevice,suchasaterminal
emulatorwindow,screen,printer,ordiskdrive.
Thedevicenamethatthewhoutilitydisplaysafteryour
usernameisthefilenameofyourscreen.Forexample,when
whodisplaysthedevicenamepts/4,thepathnameofyour
screenis/dev/pts/4.Whenyouworkwithmultiplewindows,
eachwindowhasitsowndevicename.Youcanalsousethetty
utilitytodisplaythenameofthedevicethatyougivethe
commandfrom.Althoughyouwouldnotnormallyhaveoccasion
todoso,youcanreadfromandwritetothisfileasthoughit
wereatextfile.Writingtoitdisplayswhatyouwroteonthe
screen;readingfromitreadswhatyouenteredonthe
keyboard.
Tip:chsh:changesyourloginshell
Thepersonwhosetsupyouraccountdetermines
whichshellyouwillusewhenyoufirstloginonthe
systemorwhenyouopenaterminalemulator
windowinaGUIenvironment.Youcanrunanyshell
youlikeonceyouareloggedin.Enterthenameof
theshellyouwanttouse(bash,tcsh,oranothershell)
andpressRETURN;thenextpromptwillbethatof
thenewshell.Giveanexitcommandtoreturnto
thepreviousshell.Becauseshellsyoucallinthis
mannerarenested(onerunsontopoftheother),
youwillbeabletologoutonlyfromyouroriginal
shell.Whenyouhavenestedseveralshells,keep
givingexitcommandsuntilyoureachyouroriginal
shell.Youwillthenbeabletologout.
Usethechshutilitywhenyouwanttochangeyour
loginshellpermanently.Firstgivethecommand
chsh.Theninresponsetothepromptsenteryour
passwordandtheabsolutepathnameoftheshell
youwanttouse(/bin/bash,/bin/tcsh,orthe
pathnameofanothershell).Whenyouchangeyour
loginshellinthismannerusingaterminalemulator
(page93)underaGUI,subsequentterminal
emulatorwindowswillnotreflectthechangeuntil
youlogoutofthesystemandlogbackin.
TheKeyboardandScreenasStandardInputand
StandardOutput
Whenyoufirstlogin,theshelldirectsstandardoutputofyour
commandstothedevicefilethatrepresentsyourscreen(Figure
7-4).Directingoutputinthismannercausesittoappearon
yourscreen.Theshellalsodirectsstandardinputtocomefrom
thesamefile,sothatyourcommandsreceiveasinputanything
youtypeonthekeyboard.
Figure7-4.Bydefault,standardinputcomesfrom
thekeyboardandstandardoutputgoestothe
screen
cat
Thecatutilityprovidesagoodexampleofthewaythekeyboard
andthescreenfunctionasstandardinputandstandardoutput,
respectively.Whenyouusecat,itcopiesafiletostandard
output.Becausetheshelldirectsstandardoutputtothescreen,
catdisplaysthefileonthescreen.
Uptothispointcathastakenitsinputfromthefilename
(argument)youspecifiedonthecommandline.Whenyoudo
notgivecatanargument(thatis,whenyougivethecommand
catfollowedimmediatelybyRETURN),cattakesitsinputfrom
standardinput.Thus,whencalledwithoutanargument,cat
copiesstandardinputtostandardoutput,onelineatatime.
Toseehowcatworks,typecatandpressRETURNinresponseto
theshellprompt.Nothinghappens.Enteralineoftextand
pressRETURN.Thesamelineappearsjustundertheoneyou
entered.Thecatutilityisworking.Becausetheshellassociates
cat'sstandardinputwiththekeyboardandcat'sstandardoutput
withthescreen,whenyoutypealineoftextcatcopiesthetext
fromstandardinput(thekeyboard)tostandardoutput(the
screen).ThisexchangeisshowninFigure7-5.
Figure7-5.Thecatutilitycopiesstandardinputto
standardoutput
$cat
Thisisalineoftext.
Thisisalineoftext.
Catkeepscopyinglinesoftext
Catkeepscopyinglinesoftext
untilyoupressCONTROL-Datthebeginning
untilyoupressCONTROL-Datthebeginning
ofaline.
ofaline.
CONTROL-D
$
CONTROL-DsignalsEOF
ThecatutilitykeepscopyingtextuntilyouenterCONTROL-Don
alinebyitself.PressingCONTROL-DsendsanEOF(endoffile)
signaltocattoindicatethatithasreachedtheendofstandard
inputandthereisnomoretextforittocopy.Thecatutilitythen
finishesexecutionandreturnscontroltotheshell,which
displaysaprompt.
Redirection
Thetermredirectionencompassesthevariouswaysyoucan
causetheshelltoalterwherestandardinputofacommand
comesfromandwherestandardoutputgoesto.Bydefaultthe
shellassociatesstandardinputandstandardoutputofa
commandwiththekeyboardandthescreenasmentioned
earlier.Youcancausetheshelltoredirectstandardinputor
standardoutputofanycommandbyassociatingtheinputor
outputwithacommandorfileotherthanthedevicefile
representingthekeyboardorthescreen.Thissection
demonstrateshowtoredirectinputfromandoutputtoordinary
textfilesandutilities.
RedirectingStandardOutput
Theredirectoutputsymbol(>)instructstheshelltoredirect
theoutputofacommandtothespecifiedfileinsteadoftothe
screen(Figure7-6).Theformatofacommandlinethat
redirectsoutputis
command[arguments]>filename
Figure7-6.Redirectingstandardoutput
wherecommandisanyexecutableprogram(suchasan
applicationprogramorautility),argumentsareoptional
arguments,andfilenameisthenameoftheordinaryfilethe
shellredirectstheoutputto.
Figure7-7usescattodemonstrateoutputredirection.This
figurecontrastswithFigure7-3onpage208,whereboth
standardinputandstandardoutputareassociatedwiththe
keyboardandthescreen.TheinputinFigure7-7comesfrom
thekeyboard.Theredirectoutputsymbolonthecommandline
causestheshelltoassociatecat'sstandardoutputwiththe
sample.txtfilespecifiedonthecommandline.
Figure7-7.catwithitsoutputredirected
$cat>sample.txt
Thistextisbeingenteredatthekeyboardand
catiscopyingittoafile.
PressCONTROL-Dtoindicatethe
endoffile.
CONTROL-D
$
AftergivingthecommandandtypingthetextshowninFigure
7-7,thesample.txtfilecontainsthetextyouentered.Youcan
usecatwithanargumentofsample.txttodisplaythisfile.The
nextsectionshowsanotherwaytousecattodisplaythefile.
Caution:Redirectingoutputcandestroy
afileI
Usecautionwhenyouredirectoutputtoafile.Ifthe
fileexists,theshellwilloverwriteitanddestroyits
contents.Formoreinformationseethetip
"RedirectingoutputcandestroyafileII"onpage
214.
Figure7-7showsthatredirectingtheoutputfromcatisahandy
waytocreateafilewithoutusinganeditor.Thedrawbackis
thatonceyouenteralineandpressRETURN,youcannotedit
thetext.Whileyouareenteringaline,theeraseandkillkeys
worktodeletetext.Thisprocedureisusefulformakingshort,
simplefiles.
Figure7-8showshowtousecatandtheredirectoutputsymbol
tocatenate(joinoneaftertheotherthederivationofthename
ofthecatutility)severalfilesintoonelargerfile.Thefirstthree
commandsdisplaythecontentsofthreefiles:stationery,
tape,andpens.Thenextcommandshowscatwiththree
filenamesasarguments.Whenyoucallitwithmorethanone
filename,catcopiesthefiles,oneatatime,tostandardoutput.
Inthiscasestandardoutputisredirectedtothefile
supply_orders.Thefinalcatcommandshowsthat
supply_orderscontainsthecontentsofallthreefiles.
Figure7-8.Usingcattocatenatefiles
$catstationery
2,000sheetsletterheadordered:10/7/05
$cattape
1boxmaskingtapeordered:10/14/05
5boxesfilamenttapeordered:10/28/05
$catpens
12doz.blackpensordered:10/4/05
$catstationerytapepens>supply_orders
$catsupply_orders
2,000sheetsletterheadordered:10/7/05
1boxmaskingtapeordered:10/14/05
5boxesfilamenttapeordered:10/28/05
12doz.blackpensordered:10/4/05
$
RedirectingStandardInput
Justasyoucanredirectstandardoutput,soyoucanredirect
standardinput.Theredirectinputsymbol(<)instructstheshell
toredirectacommand'sinputtocomefromthespecifiedfile
insteadoffromthekeyboard(Figure7-9).Theformatofa
commandlinethatredirectsinputis
command[arguments]<filename
wherecommandisanyexecutableprogram(suchasan
applicationprogramorautility),argumentsareoptional
arguments,andfilenameisthenameoftheordinaryfilethe
shellredirectstheinputfrom.
Figure7-9.Redirectingstandardinput
Figure7-10showscatwithitsinputredirectedfromthe
supply_ordersfilethatwascreatedinFigure7-8andstandard
outputgoingtothescreen.Thissetupcausescattodisplaythe
samplefileonthescreen.Thesystemautomaticallysuppliesan
EOF(endoffile)signalattheendofanordinaryfile.
Figure7-10.catwithitsinputredirected
$cat<supply_orders
2,000sheetsletterheadordered:10/7/05
1boxmaskingtapeordered:10/14/05
5boxesfilamenttapeordered:10/28/05
12doz.blackpensordered:10/4/05
Utilitiesthattakeinputfromafileorstandardinput
Givingacatcommandwithinputredirectedfromafileyieldsthe
sameresultasgivingacatcommandwiththefilenameasan
argument.ThecatutilityisamemberofaclassofLinuxutilities
thatfunctioninthismanner.Othermembersofthisclassof
utilitiesincludelpr,sort,andgrep.Theseutilitiesfirstexaminethe
commandlinethatyouusetocallthem.Ifyouincludea
filenameonthecommandline,theutilitytakesitsinputfrom
thefileyouspecify.Ifyoudonotspecifyafilename,theutility
takesitsinputfromstandardinput.Itistheutilityor
programnottheshelloroperatingsystemthatfunctionsinthis
manner.
noclobber:AvoidsOverwritingFiles
Theshellprovidesafeaturecallednoclobberthatstopsyou
frominadvertentlyoverwritinganexistingfileusingredirection.
Whenyouenablethisfeaturebysettingthenoclobbervariable
andthenattempttoredirectoutputtoanexistingfile,theshell
displaysanerrormessageanddoesnotexecutethecommand.
Iftheprecedingexamplesresultinoneofthefollowing
messages,thenoclobberfeaturehasbeenset.Thefollowing
examplessetnoclobber,attempttoredirecttheoutputfrom
echointoanexistingfile,andthenunsetnoclobber:
$set-onoclobber
$echo"hithere">tmp
bash:tmp:Cannotoverwriteexistingfile
$set+onoclobber
$echo"hithere">tmp
$
Youcanoverridenoclobberbyputtingapipesymbolafterthe
symbolyouuseforredirectingoutput(>|).
Inthefollowingexample,theuserfirstcreatesafilenameda
byredirectingtheoutputofdatetothefile.Nexttheusersets
thenoclobbervariableandtriesredirectingoutputtoaagain.
Theshellreturnsanerrormessage.Thentheusertriesthe
samethingbutusingapipesymbolaftertheredirectsymbol.
Thistimetheshellallowstheusertooverwritethefile.Finally,
theuserunsetsnoclobber(usingaplussigninplaceofthe
hyphen)andverifiesthatitisnolongerset.
$date>a
$set-onoclobber
$date>a
bash:a:Cannotoverwriteexistingfile
$date>|a
$set+onoclobber
$date>a
Caution:Redirectingoutputcandestroy
afileII
Dependingonwhichshellyouareusingandhow
yourenvironmenthasbeensetup,acommandsuch
asthefollowingmaygiveyouundesiredresults:
$catorangepear>orange
cat:orange:inputfileisoutputfile
Althoughcatdisplaysanerrormessage,theshell
goesaheadanddestroysthecontentsoftheexisting
orangefile.Theneworangefilewillhavethesame
contentsaspearbecausethefirstactiontheshell
takeswhenitseestheredirectionsymbol(>)isto
removethecontentsoftheoriginalorangefile.If
youwanttocatenatetwofilesintoone,usecatto
putthetwofilesintoatemporaryfileandthenuse
mvtorenamethisthirdfile:
$catorangepear>temp
$mvtemporange
Whathappensinthenextexamplecanbeeven
worse.Theusergivingthecommandwantsto
searchthroughfilesa,b,andcforthewordapple
andredirecttheoutputfromgrep(page131)tothe
filea.output.Unfortunatelytheuserentersthe
filenameasaoutput,omittingtheperiodand
insertingaSPACEinitsplace:
$grepappleabc>aoutput
grep:output:Nosuchfileordirectory
Theshellobedientlyremovesthecontentsofaand
thencallsgrep.Theerrormessagemaytakea
momenttoappear,givingyouasensethatthe
commandisrunningcorrectly.Evenafteryousee
theerrormessage,itmaytakeawhiletorealize
thatyoudestroyedthecontentsofa.
AppendingStandardOutputtoaFile
Theappendoutputsymbol(>>)causestheshelltoaddnew
informationtotheendofafile,leavinganyexistinginformation
intact.Thissymbolprovidesaconvenientwayofcatenatingtwo
filesintoone.Thefollowingcommandsdemonstratetheaction
oftheappendoutputsymbol.Thesecondcommand
accomplishesthecatenationdescribedintheprecedingcaution
box:
$catorange
thisisorange
$catpear>>orange
$catorange
thisisorange
thisispear
Youfirstseethecontentsoftheorangefile.Nextthecontents
ofthepearfileisaddedtotheendof(catenatedwith)the
orangefile.Thefinalcatshowstheresult.
Caution:Donottrustnoclobber
Appendingoutputissimplerthanthetwo-step
proceduredescribedintheprecedingcautionbox
butyoumustbecarefultoincludebothgreaterthan
signs.Ifyouaccidentallyuseonlyoneandthe
noclobberfeatureisnoton,youwilloverwritethe
orangefile.Evenifyouhavethenoclobberfeature
turnedon,itisagoodideatokeepbackupcopiesof
filesyouaremanipulatinginthesewaysincaseyou
makeamistake.
Althoughitprotectsyoufrommakinganerroneous
redirection,noclobberdoesnotstopyoufrom
overwritinganexistingfileusingcpormv.These
utilitiesincludethei(interactive)optionthathelps
protectyoufromthistypeofmistakebyverifying
yourintentionswhenyoutrytooverwriteafile.For
moreinformationseethetip"cpcandestroyafile"
onpage130.
Thenextexampleshowshowtocreateafilethatcontainsthe
dateandtime(theoutputfromdate),followedbyalistofwhois
loggedin(theoutputfromwho).ThefirstlineinFigure7-11
redirectstheoutputfromdatetothefilenamedwhoson.Then
catdisplaysthefile.Nexttheexampleappendstheoutputfrom
whotothewhosonfile.Finallycatdisplaysthefilecontaining
theoutputofbothutilities.
Figure7-11.Redirectingandappendingoutput
$date>whoson
$catwhoson
ThuMar2414:31:18PST2005
$who>>whoson
$catwhoson
ThuMar2414:31:18PST2005
rootconsoleMar2405:00(:0)
alexpts/4Mar2412:23(:0.0)
alexpts/5Mar2412:33(:0.0)
jennypts/7Mar2308:45(bravo.example.com)
/dev/null:MakingDataDisappear
The/dev/nulldeviceisadatasink,commonlyreferredtoasa
bitbucket.Youcanredirectoutputthatyoudonotwanttokeep
orseeto/dev/null.Theoutputdisappearswithoutatrace:
$echo"hithere">/dev/null
$
Whenyoureadfrom/dev/null,yougetanullstring.Givethe
followingcatcommandtotruncateafilenamedmessagesto
zerolengthwhilepreservingtheownershipandpermissionsof
thefile:
$ls-lmessages
-rw-r--r--1alexpubs25315Oct2410:55messages
$cat/dev/null>messages
$ls-lmessages
-rw-r--r--1alexpubs0Oct2411:02messages
Pipes
Theshellusesapipetoconnectstandardoutputofone
commanddirectlytostandardinputofanothercommand.A
pipe(sometimesreferredtoasapipeline)hasthesameeffect
asredirectingstandardoutputofonecommandtoafileand
thenusingthatfileasstandardinputtoanothercommand.A
pipedoesawaywithseparatecommandsandtheintermediate
file.Thesymbolforapipeisaverticalbar(|).Thesyntaxofa
commandlineusingapipeis
command_a[arguments]|command_b[arguments]
Theprecedingcommandlineusesapipetogeneratethesame
resultasthefollowinggroupofcommandlines:
command_a[arguments]>temp
command_b[arguments]<temp
rmtemp
Intheprecedingsequenceofcommands,thefirstlineredirects
standardoutputfromcommand_atoanintermediatefile
namedtemp.Thesecondlineredirectsstandardinputfor
command_btocomefromtemp.Thefinallinedeletestemp.
Thecommandusingapipeisnotonlyeasiertotype,butis
generallymoreefficientbecauseitdoesnotcreateatemporary
file.
tr
YoucanuseapipewithanyoftheLinuxutilitiesthataccept
inputeitherfromafilespecifiedonthecommandlineorfrom
standardinput.Youcanalsousepipeswithcommandsthat
acceptinputonlyfromstandardinput.Forexample,thetr
(translate)utilitytakesitsinputfromstandardinputonly.Inits
simplestusagetrhasthefollowingformat:
trstring1string2
Thetrutilityacceptsinputfromstandardinputandlooksfor
charactersthatmatchoneofthecharactersinstring1.Upon
findingamatch,trtranslatesthematchedcharacterinstring1
tothecorrespondingcharacterinstring2.(Thefirstcharacter
instring1translatesintothefirstcharacterinstring2,andso
forth.)Thetrutilitysendsitsoutputtostandardoutput.Inboth
ofthefollowingexamples,trdisplaysthecontentsofthe
abstractfilewiththelettersa,b,andctranslatedintoA,B,
andC,respectively:
$catabstract|trabcABC
$trabcABC<abstract
Thetrutilitydoesnotchangethecontentsoftheoriginalfile;it
cannotchangetheoriginalfilebecauseitdoesnot"know"the
sourceofitsinput.
lpr
Thelpr(lineprinter)utilityalsoacceptsinputfromeitherafile
orstandardinput.Whenyoutypethenameofafilefollowing
lpronthecommandline,itplacesthatfileintheprintqueue.
Whenyoudonotspecifyafilenameonthecommandline,lpr
takesinputfromstandardinput.Thisfeatureenablesyouto
useapipetoredirectinputtolpr.Thefirstsetofcommandsin
Figure7-12showshowyoucanuselsandlprwithan
intermediatefile(temp)tosendalistofthefilesintheworking
directorytotheprinter.Ifthetempfileexists,thefirst
commandoverwritesitscontents.Thesecondsetofcommands
sendsthesamelist(withtheexceptionoftemp)totheprinter
usingapipe.
Figure7-12.Apipe
$ls>temp
$lprtemp
$rmtemp
or
$ls|lpr
ThecommandsinFigure7-13redirecttheoutputfromthewho
utilitytotempandthendisplaythisfileinsortedorder.Thesort
utility(page133)takesitsinputfromthefilespecifiedonthe
commandlineor,whenafileisnotspecified,fromstandard
inputandsendsitsoutputtostandardoutput.Thesort
commandlineinFigure7-13takesitsinputfromstandard
input,whichisredirected(<)tocomefromtemp.Theoutput
thatsortsendstothescreenliststheusersinsorted
(alphabetical)order.
Figure7-13.Usingatemporaryfiletostore
intermediateresults
$who>temp
$sort<temp
alexpts/4Mar2412:23
alexpts/5Mar2412:33
jennypts/7Mar2308:45
rootconsoleMar2405:00
$rmtemp
Becausesortcantakeitsinputfromstandardinputorfroma
filenameonthecommandline,omittingthe<symbolfrom
Figure7-13yieldsthesameresult.
Figure7-14achievesthesameresultwithoutcreatingthetemp
file.Usingapipetheshellredirectstheoutputfromwhotothe
inputofsort.Thesortutilitytakesinputfromstandardinput
becausenofilenamefollowsitonthecommandline.
Figure7-14.Apipedoingtheworkofatemporary
file
$who|sort
alexpts/4Mar2412:23
alexpts/5Mar2412:33
jennypts/7Mar2308:45
rootconsoleMar2405:00
Whenmanypeopleareusingthesystemandyouwant
informationaboutonlyoneofthem,youcansendtheoutput
fromwhotogrep(page131)usingapipe.Thegreputility
displaysthelinecontainingthestringyouspecifyrootinthe
followingexample:
$who|grep'root'
rootconsoleMar2405:00
Anotherwayofhandlingoutputthatistoolongtofitonthe
screen,suchasalistoffilesinacrowdeddirectory,istousea
pipetosendtheoutputthroughlessormore(bothonpage128).
$ls|less
Thelessutilitydisplaystextonescreenatatime.Toview
anotherscreen,presstheSPACEbar.Toviewonemoreline,
pressRETURN.Presshforhelpandqtoquit.
Someutilitieschangetheformatoftheiroutputwhenyou
redirectit.Comparetheoutputoflsbyitselfandwhenyou
senditthroughapipetoless.
Filters
Afilterisacommandthatprocessesaninputstreamofdatato
produceanoutputstreamofdata.Acommandlinethat
includesafilterusesapipetoconnectstandardoutputofone
commandtothefilter'sstandardinput.Anotherpipeconnects
thefilter'sstandardoutputtostandardinputofanother
command.Notallutilitiescanbeusedasfilters.
Inthefollowingexample,sortisafilter,takingstandardinput
fromstandardoutputofwhoandusingapipetoredirect
standardoutputtostandardinputoflpr.Thiscommandline
sendsthesortedoutputofwhototheprinter:
$who|sort|lpr
Theprecedingexampledemonstratesthepoweroftheshell
combinedwiththeversatilityofLinuxutilities.Thethreeutilities
who,sort,andlprwerenotspecificallydesignedtoworkwith
eachother,buttheyallusestandardinputandstandardoutput
intheconventionalway.Byusingtheshelltohandleinputand
output,youcanpiecestandardutilitiestogetheronthe
commandlinetoachievetheresultsyouwant.
tee:SendsOutputinTwoDirections
Theteeutilitycopiesitsstandardinputbothtoafileandto
standardoutput.Theutilityisaptlynamed:Ittakesasingle
inputandsendstheoutputintwodirections.InFigure7-15the
outputofwhoissentviaapipetostandardinputoftee.Thetee
utilitysavesacopyofstandardinputinafilenamedwho.out
andalsosendsacopytostandardoutput.Standardoutputof
teegoesviaapipetostandardinputofgrep,whichdisplayslines
containingthestringroot.
Figure7-15.Usingtee
$who|teewho.out|greproot
rootconsoleMar2405:00
$catwho.out
rootconsoleMar2405:00
alexpts/4Mar2412:23
alexpts/5Mar2412:33
jennypts/7Mar2308:45
RunningaProgramintheBackground
Foreground
Inalltheexamplessofarinthisbook,commandswererunin
theforeground.Whenyourunacommandintheforeground,
theshellwaitsforittofinishbeforegivingyouanotherprompt
andallowingyoutocontinue.Whenyourunacommandinthe
background,youdonothavetowaitforthecommandtofinish
beforeyoustartrunninganothercommand.
Jobs
Ajobisaseriesofoneormorecommandsthatcanbe
connectedbypipes.Youcanhaveonlyoneforegroundjobina
windoworonascreen,butyoucanhavemanybackground
jobs.Byrunningmorethanonejobatatime,youareusing
oneofLinux'simportantfeatures:multitasking.Runninga
commandinthebackgroundcanbeusefulwhenthecommand
willrunforalongtimeanddoesnotneedsupervision.Itleaves
thescreenfreesothatyoucanuseitforotherwork.Ofcourse,
whenyouareusingaGUI,youcanopenanotherwindowtorun
anotherjob.
Jobnumber,PIDnumber
Torunacommandinthebackground,typeanampersand(&)
justbeforetheRETURNthatendsthecommandline.Theshell
assignsasmallnumbertothejobanddisplaysthisjobnumber
betweenbrackets.Followingthejobnumber,theshelldisplays
theprocessidentification(PID)numberalargernumber
assignedbytheoperatingsystem.Eachofthesenumbers
identifiesthecommandrunninginthebackground.Thenthe
shelldisplaysanotherpromptandyoucanenteranother
command.Whenthebackgroundjobfinishesrunning,theshell
displaysamessagegivingboththejobnumberandthe
commandlineusedtorunthecommand.
Thenextexamplerunsinthebackgroundandsendsitsoutput
throughapipetolpr,whichsendsittotheprinter.
$ls-l|lpr&
[1]22092
$
The[1]followingthecommandlineindicatesthattheshellhas
assignedjobnumber1tothisjob.The22092isthePID
numberofthefirstcommandinthejob.Whenthisbackground
jobcompletesexecution,youseethemessage
[1]+Donels-l|lpr
(Inplaceoflsl,theshellmaydisplaysomethingsimilartols
color=ttyl.Thisdifferenceisduetothefactthatlsisaliased
[page318]tolscolor=tty.)
MovingaJobfromtheForegroundtothe
Background
CONTROL-Z
Youcansuspendaforegroundjob(stopitfromrunning)by
pressingthesuspendkey,usuallyCONTROL-Z.Theshellthen
stopstheprocessanddisconnectsstandardinputfromthe
keyboard.Youcanputasuspendedjobinthebackgroundand
restartitbyusingthebgcommandfollowedbythejobnumber.
Youdonotneedtousethejobnumberwhenthereisonlyone
stoppedjob.
Onlytheforegroundjobcantakeinputfromthekeyboard.To
connectthekeyboardtoaprogramrunninginthebackground,
youmustbringitintotheforeground.Typefgwithoutany
argumentswhenonlyonejobisinthebackground.Whenmore
thanonejobisinthebackground,typefg,orapercentsign
(%),followedbythenumberofthejobyouwanttobringinto
theforeground.Theshelldisplaysthecommandyouusedto
startthejob(promptmeinthefollowingexample),andyou
canenteranyinputtheprogramrequirestocontinue:
bash$fg1
promptme
Redirecttheoutputofajobyouruninthebackgroundtokeep
itfrominterferingwithwhateveryouaredoingonthescreen.
Referto"SeparatingandGroupingCommands"onpage276for
moredetailaboutbackgroundtasks.
kill:AbortingaBackgroundJob
Theinterruptkey(usuallyCONTROL-C)cannotabortaprocess
youarerunninginthebackground;youmustusekill(page
395)forthispurpose.Followkillonthecommandlinewith
eitherthePIDnumberoftheprocessyouwanttoabortora
percentsign(%)followedbythejobnumber.
DeterminingaPIDnumberwithps
IfyouforgetthePIDnumber,youcanusetheps(process
status)utility(page300)todisplayit.Thefollowingexample
runsatailfoutfilecommand(thefoptioncausestailtowatch
outfileanddisplaynewlinesastheyarewrittentothefile)as
abackgroundjob,usespstodisplaythePIDnumberofthe
process,andabortsthejobwithkill:
$tail-foutfile&
[1]18228
$ps|greptail
18228pts/400:00:00tail
$kill18228
[1]+Terminatedtail-foutfile
$
Ifyouforgetthejobnumber,youcanusethejobscommandto
displayalistofjobnumbers.Thenextexampleissimilartothe
previousonebutusesthejobnumberinsteadofthePID
numbertokillthejob.Sometimesthemessagesayingthatthe
jobisterminateddoesnotappearuntilyoupressRETURNafter
theRETURNthatendsthekillcommand:
$tail-foutfile&
[1]18236
$bigjob&
[2]18237
$jobs
[1]-Runningtail-foutfile&
[2]+Runningbigjob&
$kill%1
$RETURN
[1]-Terminatedtail-foutfile
$
FilenameGeneration/PathnameExpansion
Wildcards,globbing
Whenyougivetheshellabbreviatedfilenamesthatcontain
specialcharacters,alsocalledmetacharacters,theshellcan
generatefilenamesthatmatchthenamesofexistingfiles.
Thesespecialcharactersarealsoreferredtoaswildcards
becausetheyactasthejokersdoinadeckofcards.Whenone
ofthesecharactersappearsinanargumentonthecommand
line,theshellexpandsthatargumentinsortedorderintoalist
offilenamesandpassesthelisttotheprogramthatthe
commandlinecalls.Filenamesthatcontainthesespecial
charactersarecalledambiguousfilereferencesbecausetheydo
notrefertoanyonespecificfile.Theprocessthattheshell
performsonthesefilenamesiscalledpathnameexpansionor
globbing.
Ambiguousfilereferencesrefertoagroupoffileswithsimilar
namesquickly,savingyoutheeffortoftypingthenames
individually.Theycanalsohelpyoufindafilewhosenameyou
donotrememberinitsentirety.Ifnofilenamematchesthe
ambiguousfilereference,theshellgenerallypassesthe
unexpandedreferencespecialcharactersandalltothe
command.
The?SpecialCharacter
Thequestionmark(?)isaspecialcharacterthatcausesthe
shelltogeneratefilenames.Itmatchesanysinglecharacterin
thenameofanexistingfile.Thefollowingcommandusesthis
specialcharacterinanargumenttothelprutility:
$lprmemo?
Theshellexpandsthememo?argumentandgeneratesalistof
filesintheworkingdirectorythathavenamescomposedof
memofollowedbyanysinglecharacter.Theshellthenpasses
thislisttolpr.Thelprutilitynever"knows"thattheshell
generatedthefilenamesitwascalledwith.Ifnofilename
matchestheambiguousfilereference,theshellpassesthe
stringitself(memo?)tolpror,ifitissetuptodoso,passesa
nullstring(seenullglobonpage327).
Thefollowingexampleuseslsfirsttodisplaythenamesofall
filesintheworkingdirectoryandthentodisplaythefilenames
thatmemo?matches:
$ls
memmemo12memo9memoalexnewmemo5
memomemo5memoamemos
$lsmemo?
memo5memo9memoamemos
Thememo?ambiguousfilereferencedoesnotmatchmem,
memo,memo12,memoalex,ornewmemo5.Youcanalso
useaquestionmarkinthemiddleofanambiguousfile
reference:
$ls
7may4reportmay4reportmayqreportmay_report
may14reportmay4report.79mayreportmay.report
$lsmay?report
may.reportmay4reportmay_reportmayqreport
Topracticegeneratingfilenames,youcanuseechoandls.The
echoutilitydisplaystheargumentsthattheshellpassestoit:
$echomay?report
may.reportmay4reportmay_reportmayqreport
Theshellfirstexpandstheambiguousfilereferenceintoalistof
allfilesintheworkingdirectorythatmatchthestringmay?
reportandthenpassesthislisttoecho,asthoughyouhad
enteredthelistoffilenamesasargumentstoecho.Nextecho
displaysthelistoffilenames.
Aquestionmarkdoesnotmatchaleadingperiod(onethat
indicatesahiddenfilename;seepage170).Whenyouwantto
matchfilenamesthatbeginwithaperiod,youmustexplicitly
includetheperiodintheambiguousfilereference.
The*SpecialCharacter
Theasterisk(*)performsafunctionsimilartothatofthe
questionmarkbutmatchesanynumberofcharacters,including
zerocharacters,inafilename.Thefollowingexampleshowsall
ofthefilesintheworkingdirectoryandthenshowsthree
commandsthatdisplayallthefilenamesthatbeginwiththe
stringmemo,endwiththestringmo,andcontainthestring
alx:
$ls
amemomemomemoalx.0620memosallyuser.memo
memmemo.0612memoalx.keepsallymemo
memalxmemoamemorandumtypescript
$echomemo*
memomemo.0612memoamemoalx.0620memoalx.keepmemorandummemosally
$echo*mo
amemomemosallymemouser.memo
$echo*alx*
memalxmemoalx.0620memoalx.keep
Theambiguousfilereferencememo*doesnotmatchamemo,
mem,sallymemo,oruser.memo.Likethequestionmark,an
asteriskdoesnotmatchaleadingperiodinafilename.
Theaoptioncauseslstodisplayhiddenfilenames.The
commandecho*doesnotdisplay.(theworkingdirectory),..
(theparentoftheworkingdirectory),.aaa,or.profile.In
contrast,thecommandecho.*displaysonlythosefour
names:
$ls
aaamemo.sallysally.0612thurs
memo.0612reportsaturday
$ls-a
..aaaaaamemo.sallysally.0612thurs
...profilememo.0612reportsaturday
$echo*
aaamemo.0612memo.sallyreportsally.0612saturdaythurs
$echo.*
....aaa.profile
Inthefollowingexample.p*doesnotmatchmemo.0612,
private,reminder,orreport.Nextthels.*commandcauses
lstolist.privateand.profileinadditiontothecontentsofthe
.directory(theworkingdirectory)andthe..directory(the
parentoftheworkingdirectory).Whencalledwiththesame
argument,echodisplaysthenamesoffiles(including
directories)intheworkingdirectorythatbeginwithadot(.),
butnotthecontentsofdirectories.
$ls-a
..privatememo.0612reminder
...profileprivatereport
$echo.p*
.private.profile
$ls.*
.private.profile
.:
memo.0612privatereminderreport
..:
.
.
$echo.*
....private.profile
Youcantakeadvantageofambiguousfilereferenceswhenyou
establishconventionsfornamingfiles.Forexample,whenyou
endalltextfilenameswith.txt,youcanreferencethatgroupof
fileswith*.txt.Thenextcommandusesthisconventionto
sendallthetextfilesintheworkingdirectorytotheprinter.The
ampersandcauseslprtoruninthebackground.
$lpr*.txt&
The[]SpecialCharacters
Apairofbracketssurroundingalistofcharacterscausesthe
shelltomatchfilenamescontainingtheindividualcharacters.
Whereasmemo?matchesmemofollowedbyanycharacter,
memo[17a]ismorerestrictive,andmatchesonlymemo1,
memo7,andmemoa.Thebracketsdefineacharacterclass
thatincludesallthecharacterswithinthebrackets.(GNUcalls
thisacharacterlist;aGNUcharacterclassissomething
different.)Theshellexpandsanargumentthatincludesa
character-classdefinition,bysubstitutingeachmemberofthe
characterclass,oneatatime,inplaceofthebracketsandtheir
contents.Theshellthenpassesthelistofmatchingfilenamesto
theprogramitiscalling.
Eachcharacter-classdefinitioncanreplaceonlyasingle
characterwithinafilename.Thebracketsandtheircontentsare
likeaquestionmarkthatsubstitutesonlythemembersofthe
characterclass.
Thefirstofthefollowingcommandsliststhenamesofallthe
filesintheworkingdirectorythatbeginwitha,e,i,o,oru.
Thesecondcommanddisplaysthecontentsofthefilesnamed
page2.txt,page4.txt,page6.txt,andpage8.txt.
$echo[aeiou]*
...
$lesspage[2468].txt
...
Ahyphenwithinbracketsdefinesarangeofcharacterswithina
character-classdefinition.Forexample,[69]represents
[6789],[az]representsalllowercaselettersinEnglish,and
[azAZ]representsallletters,bothuppercaseandlowercase,in
English.
Thefollowingcommandlinesshowthreewaystoprintthefiles
namedpart0,part1,part2,part3,andpart5.Eachofthese
commandlinescausestheshelltocalllprwithfivefilenames:
$lprpart0part1part2part3part5
$lprpart[01235]
$lprpart[0-35]
Thefirstcommandlineexplicitlyspecifiesthefivefilenames.
Thesecondandthirdcommandlinesuseambiguousfile
references,incorporatingcharacter-classdefinitions.Theshell
expandstheargumentonthesecondcommandlinetoinclude
allfilesthathavenamesbeginningwithpartandendingwith
anyofthecharactersinthecharacterclass.Thecharacterclass
isexplicitlydefinedas0,1,2,3,and5.Thethirdcommand
linealsousesacharacter-classdefinitionbutdefinesthe
characterclasstobeallcharactersintherange03plus5.
Thefollowingcommandlineprints39files,part0through
part38:
$lprpart[0-9]part[12][0-9]part3[0-8]
Thenexttwoexampleslistthenamesofsomeofthefilesinthe
workingdirectory.Thefirstliststhefileswhosenamesstart
withathroughm.Thesecondlistsfileswhosenamesendwith
x,y,orz.
$echo[a-m]*
...
$echo*[x-z]
...
Optional
Whenanexclamationpoint(!)oracaret(^)immediatelyfollowstheopening
bracket([)thatdefinesacharacterclass,thestringenclosedbythebrackets
matchesanycharacternotbetweenthebrackets.Thus[^ab]*matchesany
filenamethatdoesnotbeginwithaorb.
Thefollowingexamplesshowthat*[^ab]matchesfilenamesthatdonotend
withthelettersaorbandthat[b-d]*matchesfilenamesthatbeginwithb,c,
ord.
$ls
aaabacadbabbbcbdccdd
$ls*[^ab]
acadbcbdccddccdd
$ls[b-d]*
babbbcbdccdd
Youcanmatchahyphen()oraclosingbracket(])byplacingitimmediately
beforethefinalclosingbracket.
Thenextexampledemonstratesthatthelsutilitycannot
interpretambiguousfilereferences.Firstlsiscalledwithan
argumentof?old.Theshellexpands?oldintoamatching
filename,hold,andpassesthatnametols.Thesecond
commandisthesameasthefirst,exceptthe?isquoted(refer
to"SpecialCharacters"onpage126).Theshelldoesnot
recognizethisquestionmarkasaspecialcharacterandpasses
itontols.Thelsutilitygeneratesanerrormessagesayingthat
itcannotfindafilenamed?old(becausethereisnofilenamed
?old).
$ls?old
hold
$ls\?old
ls:?old:Nosuchfileordirectory
Likemostutilitiesandprograms,lscannotinterpretambiguous
filereferences;thatworkislefttotheshell.
Tip:Theshellexpandsambiguousfile
references
Theshelldoestheexpansionwhenitprocessesan
ambiguousfilereference,nottheprogramthatthe
shellruns.Intheexamplesinthissection,the
utilities(ls,cat,echo,lpr)neverseetheambiguousfile
references.Theshellexpandstheambiguousfile
referencesandpassesalistofordinaryfilenamesto
theutility.Inthepreviousexamples,echoshowsthis
tobetruebecauseitsimplydisplaysitsarguments;
itneverdisplaystheambiguousfilereference.
Builtins
Abuiltinisautility(alsocalledacommand)thatisbuiltintoa
shell.Eachoftheshellshasitsownsetofbuiltins.Whenitruns
abuiltin,theshelldoesnotforkanewprocess.Consequently
builtinsrunmorequicklyandcanaffecttheenvironmentofthe
currentshell.Becausebuiltinsareusedinthesamewayas
utilities,youwillnottypicallybeawareofwhetherautilityis
builtintotheshellorisastand-aloneutility.
Theechoutilityisashellbuiltin.Theshellalwaysexecutesa
shellbuiltinbeforetryingtofindacommandorutilitywiththe
samename.Seepage926foranin-depthdiscussionofbuiltin
commandsandpage939foralistofbashbuiltins.
Listingbashbuiltins
Togetacompletelistofbashbuiltins,givethecommandinfo
bashbuiltin.Todisplayapagewithmoreinformationoneach
builtin,movethecursortooneofthelineslistingabuiltin
commandandpressRETURN.Alternatively,aftertypinginfo
bash,givethecommand/builtintosearchthebash
documentationforthestringbuiltin.Thecursorwillrestonthe
wordBuiltininamenu;pressRETURNtodisplaythebuiltins
menu.
BecausebashwaswrittenbyGNU,theinfopagehasbetter
informationthandoesthemanpage.Ifyouwanttoreadabout
builtinsinthemanpage,givethecommandmanbashandthen
searchforthesectiononbuiltinswiththecommand/^SHELL
BUILTINCOMMANDS(searchforalinethatbeginswith
SHELL...).
ChapterSummary
TheshellistheLinuxcommandinterpreter.Itscansthe
commandlineforpropersyntax,pickingoutthecommand
nameandanyarguments.Thefirstargumentisargumentone,
thesecondisargumenttwo,andsoon.Thenameofthe
commanditselfisargumentzero.Manyprogramsuseoptions
tomodifytheeffectsofacommand.MostLinuxutilitiesidentify
anoptionbyitsleadingoneortwohyphens.
Whenyougiveitacommand,theshelltriestofindan
executableprogramwiththesamenameasthecommand.
Whenitdoes,theshellexecutestheprogram.Whenitdoes
not,theshelltellsyouthatitcannotfindorexecutethe
program.Ifthecommandisasimplefilename,theshell
searchesthedirectoriesgiveninthevariablePATHinan
attempttolocatethecommand.
Whenitexecutesacommand,theshellassignsonefiletothe
command'sstandardinputandanotherfiletoitsstandard
output.Bydefaulttheshellcausesacommand'sstandardinput
tocomefromthekeyboardanditsstandardoutputtogotothe
screen.Youcaninstructtheshelltoredirectacommand's
standardinputfromorstandardoutputtoanyfileordevice.
Youcanalsoconnectstandardoutputofonecommandto
standardinputofanothercommandusingapipe.Afilterisa
commandthatreadsitsstandardinputfromstandardoutputof
onecommandandwritesitsstandardoutputtostandardinput
ofanothercommand.
Whenacommandrunsintheforeground,theshellwaitsforit
tofinishbeforeitdisplaysapromptandallowsyoutocontinue.
Whenyouputanampersand(&)attheendofacommandline,
theshellexecutesthecommandinthebackgroundanddisplays
anotherpromptimmediately.Runslowcommandsinthe
backgroundwhenyouwanttoenterothercommandsatthe
shellprompt.Thejobsbuiltindisplaysalistofjobsandincludes
thejobnumberofeach.
Theshellinterpretsspecialcharactersonacommandlineto
generatefilenames.Aquestionmarkrepresentsanysingle
character,andanasteriskrepresentszeroormorecharacters.A
singlecharactermayalsoberepresentedbyacharacterclass:
alistofcharacterswithinbrackets.Areferencethatuses
specialcharacters(wildcards)toabbreviatealistofoneor
morefilenamesiscalledanambiguousfilereference.
Abuiltinisautilitythatisbuiltintoashell.Eachshellhasits
ownsetofbuiltins.Whenitrunsabuiltin,theshelldoesnot
forkanewprocess.Consequentlybuiltinsrunmorequicklyand
canaffecttheenvironmentofthecurrentshell.
UtilitiesandBuiltinsIntroducedinThisChapter
Table7-1liststheutilitiesintroducedinthischapter.
Table7-1.Newutilities
Utility Function
tr Mapsonestringofcharactersintoanother(page216)
tee Sendsstandardinputtobothafileandstandardoutput
(page218)
bg Movesaprocessintothebackground(page219)
fg Movesaprocessintotheforeground(page220)
jobs Displaysalistofcurrentlyrunningjobs(page220)
Exercises
1.
Whatdoestheshellordinarilydowhileacommandisexecuting?Whatshouldyou
doifyoudonotwanttowaitforacommandtofinishbeforerunninganother
command?
2.
Usingsortasafilter,rewritethefollowingsequenceofcommands:
$sortlist>temp
$lprtemp
$rmtemp
3.
WhatisaPIDnumber?Whyarethesenumbersusefulwhenyourunprocessesin
thebackground?WhichutilitydisplaysthePIDnumbersofthecommandsyouare
running?
4.
Assumethatthefollowingfilesareintheworkingdirectory:
$ls
intronotesbref2section1section3section4b
notesaref1ref3section2section4asentrev
Givecommandsforeachofthefollowing,usingwildcardstoexpressfilenames
withasfewcharactersaspossible.
a. Listallfilesthatbeginwithsection.
b. Listthesection1,section2,andsection3filesonly.
c. Listtheintrofileonly.
d. Listthesection1,section3,ref1,andref3files.
5.
Refertothedocumentationofutilitiesinthemanpagestodeterminewhich
commandswill
a. Outputthenumberoflinesinthestandardinputthatcontainthewordaor
A.
b. Outputonlythenamesofthefilesintheworkingdirectorythatcontainthe
pattern$(.
c. Listthefilesintheworkingdirectoryintheirreversealphabeticalorder.
d. Sendalistoffilesintheworkingdirectorytotheprinter,sortedbysize.
6.
Giveacommand
a. Redirectthestandardoutputfromasortcommandintoafilenamed
phone_list.Assumethattheinputfileisnamednumbers.
b. Translatealloccurrencesofthecharacters[and{tothecharacter(,andall
occurrencesofthecharacters]and}tothecharacter)inthefile
permdemos.c.(Hint:Refertothetrmanpage.)
c. Createafilenamedbookthatcontainsthecontentsoftwootherfiles:part1
andpart2.
7.
Thelprandsortutilitiesacceptinputeitherfromafilenamedonthecommandline
orfromstandardinput.
a. Nametwootherutilitiesthatfunctioninasimilarmanner.
b. Nameautilitythatacceptsitsinputonlyfromstandardinput.
8.
Giveanexampleofacommandthatusesgrep
a. Withbothinputandoutputredirected.
b. Withonlyinputredirected.
c. Withonlyoutputredirected.
d. Withinapipe.
Inwhichoftheprecedingisgrepusedasafilter?
9.
Explainthefollowingerrormessage.Whatfilenameswouldasubsequentls
display?
$ls
abcabdabeabfabgabh
$rmabcab*
rm:cannotremove'abc':Nosuchfileordirectory
AdvancedExercises
10.
Whenyouusetheredirectoutputsymbol(>)withacommand,theshellcreates
theoutputfileimmediately,beforethecommandisexecuted.Demonstratethat
thisistrue.
11.
Inexperimentingwithshellvariables,AlexaccidentallydeleteshisPATHvariable.
HedecidesthathedoesnotneedthePATHvariable.Discusssomeofthe
problemshemaysoonencounterandexplainthereasonsfortheseproblems.How
couldheeasilyreturnPATHtoitsoriginalvalue?
12.
Assumethatyourpermissionsallowyoutowritetoafilebutnottodeleteit.
a. Giveacommandtoemptythefilewithoutinvokinganeditor.
b. Explainhowyoumighthavepermissiontomodifyafilethatyoucannot
delete.
13. Ifyouaccidentallycreateafilenamethatcontainsanonprintingcharacter,suchas
aCONTROLcharacter,howcanyourenamethefile?
14. Whydoesthenoclobbervariablenotprotectyoufromoverwritinganexistingfile
withcpormv?
15.
WhydocommandnamesandfilenamesusuallynothaveembeddedSPACEs?How
wouldyoucreateafilenamecontainingaSPACE?Howwouldyouremoveit?(This
isathoughtexercise,notrecommendedpractice.Ifyouwanttoexperiment,
createandworkinadirectorythatcontainsonlyyourexperimentalfile.)
16.
Createafilenamedanswerandgivethefollowingcommand:
$>answers.0102<answercat
Explainwhatthecommanddoesandwhy.Whatisamoreconventionalwayof
expressingthiscommand?
8.LinuxGuis:X,Gnome,andKDE
INTHISCHAPTER
XWindowSystem 234
StartingXfromaCharacter-BasedDisplay 236
RemoteComputingandLocalDisplays 237
WindowManagers 240
TheNautilusFileManager 242
GNOMEUtilities 248
KonquerorBrowser/FileManager 252
KDEUtilities 260
ThischaptercoverstheLinuxgraphicaluserinterface(GUI).It
continueswhereChapter4leftoff,goingintomoredetailabout
theXWindowSystem,thebasisfortheLinuxGUI.Itpresentsa
briefhistoryofGNOMEandKDEanddiscussessomeofthe
problemsandbenefitsofhavingtwomajorLinuxdesktop
environments.ThesectiononGNOMEcoverstheNautilusfile
manager,includingitsspatialinterface,andseveralimportant
GNOMEutilities.ThefinalsectioncoversKDE,presenting
informationaboutsomeofthemoreadvancedfeaturesof
Konqueror,anddescribingafewKDEutilities.
XWindowSystem
HistoryofX
TheXWindowSystem(www.x.org)wascreatedin1984atthe
MassachusettsInstituteofTechnology(MIT)byresearchers
workingonadistributedcomputingprojectandacampuswide
distributedenvironment,calledProjectAthena.Thissystemwas
notthefirstwindowingsoftwaretorunonaUNIXsystem,butit
wasthefirsttobecomewidelyavailableandaccepted.In1985,
MITreleasedX(version9)tothepublic,forusewithouta
license.Threeyearslater,agroupofvendorsformedtheX
ConsortiumtosupportthecontinueddevelopmentofX,under
theleadershipofMIT.By1998,theXConsortiumhadbecome
partoftheOpenGroup.In2001,theOpenGroupreleasedX
version11,release6.6(commonlycalledX11R6.6).
TheXWindowSystemwasinspiredbytheideasandfeatures
foundinearlierproprietarywindowsystemsbutiswrittentobe
portableandflexible.Xisdesignedtorunonaworkstation,
typicallyattachedtoaLAN.ThedesignersbuiltXwiththe
networkinmind.Ifyoucancommunicatewitharemote
computeroveranetwork,runninganXapplicationonthat
computerandsendingtheresultstoalocaldisplayare
straightforward.
WhiletheXprotocolhasremainedstableforquitealongtime,
additionsintheformofextensionsarequitecommon.Oneof
themostinteresting,albeitonethathasnotyetmadeitsway
intoproduction,istheMediaApplicationServer,whichaimsto
providethesamelevelofnetworktransparencyforsoundand
videothatXdoesforsimplewindowingapplications.
XFree86andX.org
RedHatLinuxusedtheXFree86Xserver,whichinheritedits
licensefromtheoriginalMITXserver,throughrelease4.3.In
early2004,justbeforethereleaseofXFree864.4,theXFree86
licensewaschangedtoonethatismorerestrictiveandnot
compatiblewiththeGPL(page4).Anumberofdistributions,
includingRedHatLinux,abandonedXFree86andreplacedit
withanX.orgXserverthatisbasedonapre-releaseversionof
XFree864.4,whichpredateschangeintheXFree86license.
TheX.orgXserver,namedXorg,isfunctionallyequivalenttothe
onedistributedbyXFree86becausemostofthecodeisthe
same.Modulesdesignedtoworkwithoneserverworkwiththe
other.
TheXstack
TheLinuxGUIisbuiltinlayers(Figure8-1).Thebottomlayeris
thekernel,whichprovidesthebasicinterfacestothehardware.
OntopofthekernelistheXserver,whichisresponsiblefor
managingwindowsanddrawingbasicgraphicalprimitivessuch
aslinesandbitmaps.RatherthandirectlygeneratingX
commands,mostprogramsuseXlib,thenextlayer,whichisa
standardlibraryforinterfacingwithanXserver.Xlibis
complicatedanddoesnotprovidehigh-levelabstractions,such
asbuttonsandtextboxes.RatherthanusingXlibdirectly,most
programsrelyonatoolkitthatprovideshigh-levelabstractions.
Usingalibrarynotonlymakesprogrammingeasier,buthasthe
addedadvantageofbringingconsistencytoapplications.
Figure8-1.TheXstack
Inrecentyears,thepopularityofXhasextendedoutsidethe
UNIXcommunityandbeyondtheworkstationclassof
computersitwasoriginallyconceivedfor.TodayXisavailable
forMacintoshcomputersaswellasforPCsrunningWindows.It
isalsoavailableonaspecialkindofdisplayterminal,knownas
anXterminal,developedspecificallytorunX.
Client/serverenvironment
ComputernetworksarecentraltothedesignofX.Itispossible
torunanapplicationononecomputeranddisplaytheresults
onascreenattachedtoadifferentcomputer;theeasewith
whichthiscanbedonedistinguishesXfromotherwindow
systemsavailabletoday.Thankstothiscapability,ascientist
canrunandmanipulateaprogramonapowerful
supercomputerinanotherbuildingoranothercountryandview
theresultsonapersonalworkstationorlaptopcomputer.For
moreinformationreferto"RemoteComputingandLocal
Displays"onpage237.
WhenyoustartanXWindowSystemsession,yousetupa
client/serverenvironment.Oneprocess,calledtheXserver,
displaysdesktopsandwindowsunderX.Eachapplication
programandutilitythatmakesarequestoftheXserverisa
clientofthatserver.ExamplesofXclientsincludexterm,kwin,
xclock,andsuchgeneralapplicationsaswordprocessingand
spreadsheetprograms.Atypicalrequestfromaclientisto
displayanimageoropenawindow.
Tip:TherolesofXclientandservermay
becounterintuitive
Thetermsclientandserver,whenreferringtoX,
havetheoppositemeaningsofhowyoumightthink
ofthemintuitively:Theserverrunsthemouse,
keyboard,anddisplay;theapplicationprogramis
theclient.
Thisdisparitybecomesevenmoreapparentwhen
yourunanapplicationprogramonaremotesystem.
Youmightthinkofthesystemrunningtheprogram
astheserverandthesystemprovidingthedisplay
astheclient,butinfactitistheotherwayaround.
WithX,thesystemprovidingthedisplayisthe
server,andthesystemrunningtheprogramisthe
client.
Events
Theserveralsomonitorskeyboardandmouseactions(events)
andpassesthemtotheappropriateclients.Forexample,when
youclicktheborderofawindow,theserversendsthiseventto
thewindowmanager(client).Charactersyoutypeintoa
terminalemulationwindowaresenttothatterminalemulator
(client).Theclienttakesappropriateactionwhenitreceivesan
eventforexample,makingawindowactiveordisplayingthe
typedcharacterontheserver.
Separatingthephysicalcontrolofthedisplay(theserver)from
theprocessesneedingaccesstothedisplay(theclient)makes
itpossibletoruntheserverononecomputerandtheclienton
anothercomputer.Ingeneral,thisbookdiscussesrunningtheX
serverandclientapplicationsonasinglesystem.Referto
"RemoteComputingandLocalDisplays"forinformationon
usingXinadistributedenvironment.
Optional
Youcanrunxev(Xevent)bygivingthecommand/usr/bin/xevfroma
terminalemulationwindowandthenwatchtheinformationflowfromtheclient
totheserverandbackagain.Thisutilityopensawindowwithaboxinitand
askstheXservertosenditeventseachtimeanythinghappens,suchasmoving
themousepointer,clickingamousebutton,movingthemousepointerintothe
box,typing,orresizingthewindow.Thexevutilitydisplaysinformationabout
eacheventinthewindowthatyouopeneditfrom.Youcanusexevasan
educationaltool:Startitandseehowmuchinformationisbeingprocessedeach
timeyoumovethemouse.ClosetheEventTesterwindowtoexitfromxev.
UsingX
Thissectionprovidesbasicinformationaboutstartingand
configuringXfromthecommandline.
Caution:Killingagraphicalprogram
WhenyoupressCONTROL-ALT-ESCAPE,themouse
pointerchangesintoaskullandcrossbones.When
youmovethismousepointeroverthewindowofa
misbehavingorfrozenapplicationandclick,the
systemkillstheprogramthatcontrolsthewindow.
Usethistechniquewithcare.Ifyoudecidethatyou
donotwanttokillaprogram,pressESCAPEto
returnthemousepointertoitsnormalmode.Killing
thewrongprogram,suchasthedesktop,canbe
problematic.
StartingXfromaCharacter-BasedDisplay
Onceyouhaveloggedinonavirtualconsole(page113),you
canstartanXWindowSystemserverbyusingstartx.Seepage
404forinformationonchangingtheinitdefaultentryinthe
/etc/inittabfilesoLinuxbootsintocharacter(andnot
graphical)mode.Whenyourunstartx,theXserverdisplaysanX
screen,usingthefirstavailablevirtualconsole.Thefollowing
commandcausesstartxtoruninthebackgroundsothatyoucan
switchbacktothisvirtualconsoleandgiveothercommands:
$startx&
RemoteComputingandLocalDisplays
ToidentifythedisplaythatanXapplicationistouse,youcan
eithersetaglobalshellvariableorgiveacommandlineoption.
TheDISPLAYVariable
Themostcommonmethodofidentifyingadisplayistousethe
DISPLAYshellenvironmentvariable.Thislocallyunique
identificationstringisautomaticallysetbyxinitwhenitstarts
theXserver.
TheDISPLAYvariableholdsthescreennumberofadisplay:
$echo$DISPLAY
:0
Theformatofthecomplete(globallyunique)IDstringfora
displayis
[hostname]:display-number[.screen-number]
wherehostnameisthenameofthesystemrunningtheX
server,display-numberisthenumberofthelogical(physical)
display(0unlessmultiplemonitorsorgraphicalterminalsare
attachedtothesystem,orifyouarerunningXoverssh),and
screen-numberisthelogicalnumberofthe(virtual)terminal
(0unlessyouarerunningmultipleinstancesofX).Whenyou
areworkingwithasinglephysicalscreen,youcanshortenthe
identificationstring.Forexample,youcanusebravo:0.0or
bravo:0toidentifytheonlyphysicaldisplayonthesystem
namedbravo.WhentheXserverandtheXclientsarerunning
onthesamesystem,youcanshortenthisidentificationstring
evenfurtherto:0.0or:0.Ansshconnection(page583)shows
DISPLAYaslocalhost:10.0.
IfDISPLAYisemptyornotset,thescreenyouareworking
fromisnotrunningX.Anapplication(theXclient)usesthe
valueoftheDISPLAYvariabletodeterminewhichdisplay,
keyboard,andmouse(collectively,theXserver)touse.One
waytorunanXapplication,suchasxclock,onthelocalsystem
buthaveitusetheXWindowSystemdisplayonaremote
systemistochangethevalueoftheDISPLAYvariableonthe
localsystemtoidentifytheremoteXserver.Ifyougeta
refusedornotauthorizederror,refertothetip"xhostgrants
accesstoadisplay"(nextpage).
$exportDISPLAY=bravo:0.0
$xclock&
TheprecedingexamplestartsxclockwiththedefaultXserver
runningonthesystemnamedbravo.Aftersettingthe
DISPLAYvariabletotheIDofthebravoserver,allXprograms
(clients)youstartwillusebravoastheirserver(output
appearsonbravo'sdisplayandinputcomesfrombravo's
keyboardandmouse).
Tip:Whenyouchangethevalueof
DISPLAY
WhenyouchangethevalueoftheDISPLAY
variable,allXprogramssendtheiroutputtothe
displaynamedbyDISPLAY.
ThedisplayOption
TooverridethedefaultXserver,youcanspecifythedisplay
(andkeyboardandmouse)youwanttouseonthecommand
line:
$xclock-displaybravo:0.0
ManyXprogramsacceptthedisplayoption,whichaffectsjust
thecommandyouuseitwith.AllotherX-relatedcommandswill
sendtheiroutputtothedisplayspecifiedbytheDISPLAY
variable.
Tip:xhostgrantsaccesstoadisplay
Ifthesystemdisplaysanerrormessagewhenyou
trytoopenawindowonaremotedisplay,the
remoteuserneedstorunxhosttograntyouaccess
tothatdisplay.Forexample,ifyouareloggedinon
asystemnamedkudosandyouwanttocreatea
windowonAlex'sdisplay,Alexneedstorunthe
followingcommand:
$xhost+kudos
IfAlexwantstoallowanyonetocreatewindowson
hisdisplay,hecangivethefollowingcommand,
whichgrantsaccesstoallsystems:
$xhost+
Ifyoufrequentlyworkwithotherusersviaa
network,youmayfinditconvenienttoaddanxhost
linetoyour.bash_profilefile(page267).Be
selectiveingrantingaccesstoyourXdisplaywith
xhost,however;ifanothersystemhasaccesstoyour
display,youmayfindthatyourworkisinterrupted
alltoooften.
Security:Securityandxhost
Allowingaremotesystemaccesstoyourdisplay
usingxhostmeansthatanyuserontheremote
systemcanwatcheverythingyoutypeinaterminal
emulationwindow,includingpasswords.Forthis
reason,somesoftwarepackages,suchastheTcl/Tk
developmentsystem(www.tcl.tk),restricttheirown
capabilitieswhenxhostisused.Ifyouareconcerned
aboutsecurityorwanttotakefulladvantageof
systemssuchasTcl/Tk,youshoulduseasafer
meansofgrantingremoteaccesstoyourXsession.
Seethexauthmanpageforinformationaboutamore
securereplacementforxhost.
RunningMultipleXServers
YoucanstartmultipleXserversonasinglesystem.Themost
commonreasonforstartingasecondXserveristousea
seconddisplaythatallocatesadifferentnumberofbitstoeach
screenpixel.Thepossiblevaluesare8,16,24,and32bitsper
pixel.MostXserversavailableforLinuxdefaultto24or32bits
perpixel,permittingtheuseofmillionsofcolors
simultaneously.StartinganXserverwith8bitsperpixel
permitstheuseofanycombinationof256colorsatthesame
time.Themaximumnumberofbitsperpixelalloweddepends
onthecomputergraphicshardwareandXserver.Withfewer
bitsperpixel,thesystemhastotransferlessdata,possibly
makingitmoreresponsive.Inaddition,manygamesworkwith
only256colors.
WhenyoustartmultipleXservers,eachmusthaveadifferent
IDstring.ThefollowingcommandstartsasecondXserver;do
notgivethiscommandfromaterminalemulator:
$startx--:1
Theoptionmarkstheendofthestartxoptionsandarguments.
Argumentstotheleftofthisoptionbelongtostartx.Thestartx
scriptpassesargumentsthatappeartotherightofthisoption
totheXserver.ThefollowingcommandstartsanXserver
runningat16bitsperpixel:Thefollowingcommandstartsa
secondXserverrunningat16bitsperpixel:
$startx---depth16&
Referto"UsingVirtualConsoles"onpage113forinformation
onhowtoswitchtoavirtualconsoletostartasecondserver.
KDE
FEDORAUnderKDEyoucanselectMainmenu:SwitchUser
StartaNewSessiontostartanotherXserver.
Xoverssh
See"Tunneling/PortForwarding"onpage596forinformation
aboutrunningXoveransshconnection.
StoppingtheXServer
Howyouterminateawindowmanagerdependsonwhich
windowmanageryouarerunningandhowitisconfigured.IfX
stopsresponding,switchtoavirtualterminal,loginfrom
anotherterminaloraremotesystem,orusesshtogainaccess
tothesystem.Thenkill(page395)theprocessrunningXorg.
YoucanalsopressCONTROL-ALT-BACKSPACEtoquittheX
server.ThismethodmaynotshutdowntheXsessioncleanly,
however,soitshouldbeusedonlyasalastresort.
RemappingMouseButtons
Throughoutthisbook,eachdescriptionofamouseclickrefers
tothebuttonbyitsposition(left,middle,orright,withleft
impliedwhennobuttonisspecified)becausethepositionofa
mousebuttonismoreintuitivethananarbitrarynameor
number.Xterminologynumbersbuttonsstartingattheleftand
continuingwiththemousewheel.Thebuttonsonathree-
buttonmousearenumbered1(left),2(middle),and3(right).
Amousewheel,ifpresent,is4(rollingitup)and5(rollingit
down).Clickingthewheelisequivalenttoclickingthemiddle
mousebutton.Thebuttonsonatwo-buttonmouseare1(left)
and2(right).
Ifyouareright-handed,youcanconvenientlypresstheleft
mousebuttonwithyourindexfinger;Xprogramstake
advantageofthisfactbyrelyingonbutton1forthemost
commonoperations.Ifyouareleft-handed,yourindexfinger
restsmostconvenientlyonbutton2or3(therightbuttonona
two-orthree-buttonmouse).
Toexchangethefunctionsoftheleftandrightmousebuttons
whenyouarerunningGNOME,fromthepanelatthetopofthe
windowselectSystem:Preferences Mouse(RHELuses
Applications:Preferences Mouse)andputacheckmarkin
theboxlabeledLeft-handedmouse.FromKDEchooseMain
menu:ControlCenter Peripherals Mouseandselect
LefthandedfromtheGeneraltab.
YoucanalsochangehowXinterpretsthemousebuttonsby
usingxmodmap.Ifyouareleft-handedandusingathree-button
mousewithawheel,thefollowingcommandcausesXto
interprettherightbuttonasbutton1andtheleftbuttonas
button3:
$xmodmap-e'pointer=32145'
Omitthe4and5ifthemousedoesnothaveawheel.The
followingcommandworksforatwo-buttonmousewithouta
wheel:
$xmodmap-e'pointer=21'
Ifxmodmapdisplaysanerrormessagecomplainingaboutthe
numberofbuttons,usetheppoptiontoxmodmaptodisplaythe
numberofbuttonsthatXhasdefinedforthemouse:
$xmodmap-pp
Thereare9pointerbuttonsdefined.
PhysicalButton
ButtonCode
11
22
33
44
55
66
77
88
99
Thenexpandthepreviouscommand,addingnumbersto
completethelist.Iftheppoptionshowsninebuttons,givethe
followingcommand:
$xmodmap-e'pointer=321456789'
Changingtheorderofthefirstthreebuttonsiscriticalto
makingthemousesuitableforaleft-handeduser.Whenyou
remapthemousebuttons,remembertoreinterpretthe
descriptionsinthisbookaccordingly.Whenthisbookasksyou
toclicktheleftbutton,ordoesnotspecifyabuttontoclick,use
therightbutton,andviceversa.
WindowManagers
ConceptuallyXisverysimpleanddoesnotprovidesomeofthe
morecommonfeaturesfoundinGUIs,suchastheabilityto
dragwindows.TheUNIX/Linuxphilosophyisoneofmodularity:
Xreliesonawindowmanager,suchasMetacityorkwin,todraw
windowbordersandhandlemovingandresizingoperations.
Unlikeawindowmanager,whichhasaclearlydefinedtask,a
desktopenvironment(manager)doesmanythings.Ingeneral,
adesktopenvironment,suchasKDEorGNOME,providesa
meansoflaunchingapplicationsandutilities,suchasafile
manager,thatawindowmanagercanuse.
KDEandGNOME
TheKDEprojectbeganin1996,withtheaimofcreatinga
consistent,user-friendlydesktopenvironmentforfreeUNIX-like
operatingsystems.KDEisbasedontheQttoolkitmadeby
Trolltech.WhenKDEdevelopmentbegan,theQtlicensewasnot
compatiblewiththeGPL(page4).ForthisreasontheFree
SoftwareFoundationdecidedtosupportadifferentproject,the
GNUNetworkObjectModelEnvironment(GNOME).More
recentlyQthasbeenreleasedunderthetermsoftheGPL,
removingpartoftherationaleforGNOME'sexistence.
KDE
KDEiswritteninC++ontopoftheQtframework.KDEtriesto
useexistingtechnology,ifitcanbereused,butcreatesitsown
ifnothingelseisavailableorasuperiorsolutionisneeded.For
example,KDEimplementedanHTMLrenderingenginelong
beforetheMozillaprojectwasborn.Similarly,workonKOffice
beganalongtimebeforeStarOfficebecametheopen-source
OpenOffice.Incontrast,theGNOMEofficeapplicationsare
stand-aloneprogramsthatoriginatedoutsidetheGNOME
project.TheGNOMEWebbrowserusestheHTMLrendering
enginedevelopedbytheMozillaproject.
KDE'sportabilitywasrecentlydemonstratedwhenaversionof
mostofthecorecomponents,includingKonquerorandKOffice,
wasreleasedforMacOSX.
KParts
Byitself,Konquerorhasverylittlefunctionality;thisapplication
usesotherapplicationstodoallitswork.Konquerortakes
advantageofKDEi/oslavesandcomponents(KParts).Thei/o
slavesacceptorgatherinputandchangeittoastandard
formatthatacomponentcandisplay.Whenyouopen
Konquerortoviewyourhomedirectory,KonquerorcallstheFile
i/oslave,whichgathersinformationaboutthefilesystemand
usestheIconviewcomponent(Konquerormenubar:View
ViewMode IconView)ortheTextviewcomponent
(Konquerormenubar:View ViewMode TextView)to
displaytheinformationitgetsfromtheFilei/oslave.
Thei/oslavesarediscretemodules;itisrelativelyeasytowrite
anewone.Konquerorusesani/oslaveautomaticallywhenyou
putitinthedirectorystructure
($KDEDIR/lib/kde3/kio_protocol.*and
$KDEDIR/share/services/protocol.desktop,where
$KDEDIRis/usrbydefaultandprotocolisthenameofthe
protocol).Examplesofi/oslavesandtheiroutputformat
includeFTP(virtualfilesystem),POP3(eachretrievedpieceof
emailappearsasafile),andtheaudioCDbrowser
(kio_audiocd;eachtrackappearsasafile).
Thecomponentsdisplaytheinformationtheyreceivefromthe
i/oslaves.Onei/oslavecanfeedseveraldifferentcomponents,
andonecomponentcanreceiveinputfromseveraldifferenti/o
slaves.Bothani/oslaveandacomponentpairmustbe
availabletodisplayinformationwithinaKonquerorview.
GNOME
GNOMEisthedefaultdesktopenvironmentforRedHatLinux.It
providesasimple,coherentuserinterfacesuitableforcorporate
use.GNOMEusesGTKfordrawingwidgets.GTK,developedfor
theGNUImageManipulationProgram(gimp),iswritteninC,
althoughbindingsforC++andotherlanguagesareavailable.
GNOMEdoesnottakemuchadvantageofitscomponent
architecture.Instead,itcontinuestosupportthetraditional
UNIXphilosophyofhavingmanysmallprograms,eachofwhich
isgoodatdoingaspecifictask.
Interoperability
Sinceversion2,GNOMEhasfocusedonsimplifyingitsuser
interface,removingoptionswheretheyaredeemed
unnecessary,andaimingforasetofdefaultsettingsthatthe
enduserwillnotwishtochange.KDEhasmovedinthe
oppositedirection,emphasizingconfigurability.
Thefreedesktop.orggroup(freedesktop.org),whosemembers
aredrawnfromtheGNOMEandKDEprojects,isimproving
interoperabilityandaimstoproducestandardsthatwillallow
thetwoenvironmentstoworktogether.Onestandardreleased
byfreedesktop.orgallowsapplicationstousethenotification
areaofeithertheGNOMEorKDEpanelwithoutbeingawareof
whichdesktopenvironmenttheyarerunningin.
GNUStep
TheGNUStepproject(www.gnustep.org),whichbeganbefore
boththeKDEandGNOMEprojects,iscreatinganopen-source
implementationoftheOPENSTEPAPIanddesktopenvironment.
Theresultisaveryclean,fastuserinterface.
ThedefaultlookofWindowMaker,theGNUStepwindow
manager,issomewhatdated,butthemesupportiscurrentlyin
beta.Theuserinterfaceiswidelyregardedasoneofthemost
intuitiveofanyUNIXplatform.GNUStephaslessoverheadthan
KDEandGNOME,soitrunsbetteronolderhardware.Ifyouare
runningLinuxonhardwarethatstruggleswithGNOMEandKDE
oryouwouldliketotryauserinterfacethatdoesnottryto
mimicWindows,tryGNUStep.WindowMakerisprovidedinthe
WindowMakerpackage.
UsingGNOME
ThissectiondiscussestheNautilusfilemanagerandseveral
GNOMEutilities.
TheNautilusFileManager
Nautilusisasimple,powerfulfilemanager.Youcanuseitto
create,open,view,move,andcopyfilesanddirectoriesaswell
asexecuteprogramsandscripts.Nautilusgivesyoutwoways
toworkwithfiles:aninnovativespatialview(Figure8-2)anda
traditionalFileBrowserview(Figure8-4onpage244).
Figure8-2.TheNautilusspatialview
[Viewfullsizeimage]
SpatialView
TheNautilusobjectwindowpresentsaspatialview(Figure8-
2).Thisviewhasmanypowerfulfeaturesbutmaytakesome
gettingusedto.Thespatial(asin"havingthenatureofspace")
viewalwaysprovidesonewindowperfolder.Bydefault,when
youopenafolder,Nautilusdisplaysanewwindow.
Toopenaspatialviewofyourhomedirectory,double-clickthe
homeicononthedesktopandexperimentasyoureadthis
section.Ifyoudouble-clicktheDesktopiconinthespatialview,
NautilusopensanewwindowthatdisplaystheDesktopfolder.
Aspatialviewcandisplayiconsoralistoffilenames;select
yourpreferredformatbychoosingoneoftheViewas
selectionsfromViewonthemenubar.Tocreatefilesto
experimentwith,right-clickinthewindow(notonanicon)to
displaytheNautiluscontextmenuandselectCreateFolderor
CreateDocument.
Tip:GNOMEdesktopandNautilus
TheGNOMEdesktopisrunfromaback-endprocess
thatrunsaspartofNautilus.Ifthatprocessstops
running,itusuallyrestartsautomatically.Ifitdoes
notrestart,givethecommandnautilustorestore
thedesktop.YoudonothavetokeeptheNautilus
windowopentokeepthedesktopalive.
Tip:UseSHIFTtoclosethecurrent
windowasyouopenanotherwindow
IfyouholdtheSHIFTkeydownwhenyoudouble-
clicktoopenanewwindow,Nautilusclosesthe
currentwindowasitopensthenewone.This
behaviormaybemorefamiliarandcanhelpkeep
thedesktopfrombecomingoverlycluttered.Ifyou
donotwanttousethekeyboard,youcanachieve
thesameresultbydouble-clickingthemiddlemouse
button.
Windowmemory
Movethewindowbydraggingthetitlebar.Thespatialviewhas
windowmemory.Thenexttimeyouopenthatfolder,Nautilus
opensitatthesamesizeinthesamelocation.Eventhe
scrollbarwillbeinthesameposition.
Parent-foldersbutton
Thekeytoclosingthecurrentwindowandreturningtothe
windowoftheparentdirectoryistheParent-foldersbutton
(Figure8-2).ClickthisbuttontodisplaytheParent-folderspop-
upmenu(Figure8-3).Selectthedirectoryyouwanttoopen
fromthismenu.Nautilusthendisplaysinaspatialviewthe
directoryyouspecified.
Figure8-3.TheParent-folderspop-upmenu
[Viewfullsizeimage]
Fromaspatialview,youcanopenafolderinatraditionalview
byright-clickingthefolderandselectingBrowseFolder.
TraditionalView
Figure8-4showsthetraditional,orfilebrowser,windowwitha
Sidepane(sometimescalledasidebar),Viewpane,menubar,
toolbar,andlocationbar.ToopenaBrowserviewofyourhome
directory,eitherright-clickthehomeicononthedesktopand
selectBrowseFolderorselectApplications:SystemTools
FileBrowser.
Figure8-4.Nautilustraditional(filebrowser)
window
[Viewfullsizeimage]
SidePane
ClickthebuttonatthetopoftheSidepanetodisplaytheSide
panemenu.Fromthismenuselectthetypeofitemsyouwant
NautilustodisplayintheSidepane:Places,Information
(informationaboutthefolderdisplayedintheViewpane;see
Figure8-4),Tree(directoryhierarchy),History(listofrecent
locationsdisplayedbyNautilus),Notes,orEmblems(drag
emblems[page247]tofilesintheViewpane).
ViewPane
YoucandisplayiconsoralistoffilenamesintheViewpane.
Chooseyourpreferredviewbymakingaselectionfromthe
drop-downmenuthatappearsattherightendofthelocation
bar.ViewasIconsisshowninFigure8-4andViewasListis
showninFigure8-5.
Figure8-5.NautilusdisplayingaListview
[Viewfullsizeimage]
ControlBars
Thissectiondiscussesthethreecontrolbarsmenubar,toolbar,
andlocationbarthatinitiallyappearatthetopofaNautilus
browserwindow(Figure8-4).
Menubar
Themenubarpresentsadrop-downmenuwhenyouclickoneof
itsselections.ThemenuselectionsdependonwhatNautilusis
displayingintheViewpane.
Toolbar
TheNautilustoolbarholdsnavigationtoolicons:Back,Forward,
Up,Stop,Reload,Home,Computer,andSearch.Clickthedown
arrowbuttonattherightendofthetoolbartodisplayand
selecticonsthatdonotfitonthetoolbar.
Locationbar
Thebuttonsonthelocationbardepictthepathnameofthe
directorythatisdisplayedintheViewpaneandhighlightedin
theTreetab,whenitisdisplayedintheSidepane.Youcan
displayatextboxinthelocationbarbypressingCONTROL-L.In
thistextboxyoucanspecifyalocaldirectorythatyouwantto
displayintheViewpane.Whenyouentertheabsolute
pathnameofthedirectoryandpressRETURN,Nautilusdisplays
thecontentsofthedirectory.
Thelocationbaralsoholdsthemagnificationselectorandthe
Viewasdrop-downmenu.Tochangethemagnificationofthe
displayintheViewpane,clicktheplusorminussignoneither
sideofthemagnificationpercentage;clickthemagnification
percentageitselftoreturnto100%magnification.ClickView
as(totherightofthemagnifyingglass)todisplayandchoose
fromtheviewingselections.
FeaturesAvailablefromBothSpatialandTraditionalViews
OpenLocationdialogbox
Youcandisplaydeeplynesteddirectoriesquicklybyusingthe
OpenLocationdialogbox(Figure8-6)orthelocationbar.Press
CONTROL-LwhilethecursorisoveraNautiluswindowtodisplay
theOpenLocationdialogbox(spatialview)ortomovethe
cursortothelocationbar(traditionalview).Entertheabsolute
pathnameofthedirectoryyouwanttodisplay.Nautilus
providesassistancebycompletingdirectorynamesasyoutype.
PressTABtoacceptasuggestedcompletionorkeeptypingto
ignoreit.
Figure8-6.OpenLocationdialogbox
Zoomingimages
UsetheOpenLocationdialogboxorthelocationbartodisplay
thedirectorynamed/usr/share/backgrounds/images.
Double-clickanimagefiletodisplaythatfileinapreview
window.Positionthemousepointerovertheimageandusethe
mousewheeltozoomtheimage.Whentheimageisbigger
thanthewindow,youcandragtheimagetoviewdifferentparts
ofit.
Openingfiles
Bydefault,youdouble-clickafilenameoricontoopenit,oryou
canright-clicktheiconorfilenameandchooseOpenfromthe
pop-upmenu.Whenyouopenafile,Nautilusfiguresoutthe
appropriatetooltousebydeterminingthefile'sMIMEtype
(page96).GNOMEassociateseachfilenameextensionwitha
MIMEtypeandeachMIMEtypewithaprogram.InitiallyGNOME
usesthefilenameextensiontotrytodetermineafile'sMIME
type.Forexample,whenyouopenafilewithafilename
extensionofps,NautiluscallsKGhostView,whichdisplaysthe
PostScriptfileinareadableformat.Whenyouopenatextfile,
Nautilusopensatexteditorthatdisplaysandallowsyoutoedit
thefile.Whenyouopenadirectory,Nautilusdisplaysits
contents.WhenyouopenanexecutablefilesuchasFirefox,
Nautilusrunstheexecutable.WhenNautiluscannotdetermine
whichtooltousetoopenafile,itasksyouforassistance.See
"OpenWith"onpage248forinformationonhowtochangethe
programthatGNOMEassociateswithaMIMEtype.
Properties
Youcanviewinformationaboutafile,suchasownership,
permissions,size,waystoworkwithit,andsoon,byright-
clickingafilenameoriconandselectingPropertiesfromthe
drop-downmenu.ThePropertieswindowinitiallydisplayssome
basicinformation.Clickthetabsatthetopofthewindowto
displayadditionalinformation.Differenttypesoffilesdisplay
differentsetsoftabs,dependingonwhatisappropriatetothe
file.Youcanmodifythesettingsinthiswindowonlyifyouhave
permissiontodoso.
Basic
TheBasictabdisplaysinformationaboutthefileandenables
youtoselectacustomiconforthefileorchangeitsname.To
changethenameofthefile,makeyourchangesinthetextbox.
Ifthefilenameisnotlistedinatextbox,youdonothave
permissiontochangeit.
Emblems
TheEmblemstab(Figure8-7,left)allowsyoutoaddorremove
emblemsassociatedwiththefilebyplacing(removing)acheck
markintheboxnexttoanemblem.Figure8-8showssome
emblemsonafileicon.Nautilusdisplaysemblemsinbothits
IconandListviews,althoughtheremaynotberoomformore
thanoneiconintheListview.Youcanalsoplaceanemblemon
aniconbydraggingitfromtheSidepaneEmblemstabtoan
iconintheViewpane.DragtheEraseemblemtoaniconto
removeallemblemsfromtheicon.
Figure8-7.Propertieswindow:Emblemstab
(left);Permissionstab(right)
[Viewfullsizeimage]
permissions(page181).Whentheboxtotheleftoftheword
ReadintheOwnerrow(calleduserelsewhere;seethetip
"chmod:oforother,uforowner"onpage183)hasacheckmark
init,theownerhaspermissiontoreadthefile.Whenyouclick
theboxesintheOwnerrowsoallofthemcontaincheckmarks,
theownerhasread,write,andexecutepermissions.Theowner
ofafilecanchangethegroupthatthefileisassociatedwithto
anyothergrouptheownerisassociatedwith.Whenyourunas
Superuser,youcanchangethenameoftheuserwhoownsthe
fileandthegroupthefileisassociatedwith.Directory
permissionsworkasexplainedonpage184.Seepage183for
informationonsetuserIDandsetgroupIDpermissions,and
page1057foradescriptionofthestickybit.
OpenWith
Whenyouaskittoopenafilethatisnotexecutable(by
double-clickingitsiconorright-clickingandselectingOpen
with),GNOMEmustfigureoutwhichapplicationorutilityto
usewhenopeningthefile.GNOMEusesseveraltechniquesto
determinetheMIMEtype(page96)ofafileandselectsan
appropriateapplicationbasedonthatdetermination.
TheOpenWithtab(Figure8-9)enablesyoutochangewhich
applicationsGNOMEusestoopenthecurrentfileandotherfiles
ofthesameMIMEtype(typicallyfileswiththesamefilename
extension).ClickAddtoaddanapplicationandthenclickthe
radiobuttonnexttotheapplicationtocauseGNOMEtousethat
applicationtoopenthecurrentfileandothersofthesame
MIMEtype.HighlightanapplicationandclickRemoveto
removeanapplicationfromthelist.Youcannotremovethe
defaultapplication.
Figure8-9.Propertieswindow,OpenWithtab
GNOMEUtilities
GNOMEcomeswithnumerousutilitiesintendedtomakeyour
workonthedesktopeasierandmoreproductive.Thissection
coversseveraltoolsthatareintegraltotheuseofGNOME.
beagle:DesktopSearch(FEDORA)
Torunbeagle,enterbeagle-searchonacommandlineorselect
Places:Searchonthepanelatthetopofthescreen.This
utilitydisplaystheDesktopSearchwindow(Figure8-10),from
whichyoucansearchforastringofcharactersinafilename
andinthecontentsofafile.Tochoosethetypeoffilesyou
wanttosearch,makeaselectionfromthemenudisplayed
whenyouclickSearchonthemenubar.Bydefault,beagle
searchesfilesinyourhomedirectoryhierarchy.ClickSearch
Preferences Indexingtoinstructbeagletosearchother
directories.If,whenyoustartbeagle,itdisplaysDaemonnot
running,clickStartthedaemontostartthebeagled
daemon.
Figure8-10.DesktopSearchwindow
[Viewfullsizeimage]
Tobeginasearch,enterthewordorstringofcharactersyou
wanttosearchforintheFindtextbox.Thebeagleutilitystarts
searchingamomentafteryoustoptyping.ClickFindNowto
displayadditionalinformationabouttheselectedfile.
TheSortselectiononthemenubarallowsyoutosorttheresults
ofasearchalphabeticallybyfilename,bythedatethefilewas
modified,orbytherelevanceofeachresult.
FontPreferences
TodisplaytheGNOMEFontPreferenceswindow(Figure8-11,
nextpage),entergnome-font-propertiesonacommandline.
YoucanalsoselectSystem:Preferences Fontsfromthe
panelatthetopofthescreen.Clickoneofthefivefontbarsin
theupperpartofthewindowtodisplaythePickaFontwindow
(discussedinthenextsection).Inthiswindowyoucanchange
thefontthatGNOMEusesforapplications,documents,the
desktop,windowtitles,orterminalemulators(fixedwidth).
Figure8-11.FontPreferenceswindow
ExaminethefoursampleboxesintheFontRenderingframein
thelowerpartofthewindowandselecttheonewiththebest
appearance.SubpixelsmoothingisusuallybestforLCD
monitors.ClickDetailstorefinethefontrenderingfurther,
againpickingtheboxineachframethathasthebest
appearance.
PickaFontWindow
ThePickaFontwindow(Figure8-12)appearswhenyouneed
tochooseafont.Fromthiswindowyoucanselectafontfamily,
astyle,andasizeyouwanttouse.Apreviewofyourchoice
appearsinthePreviewframeinthelowerpartofthewindow.
ClickOKwhenyouaresatisfiedwithyourchoice.
Figure8-12.PickaFontwindow
PickaColorWindow
ThePickaColorwindow(Figure8-13)appearswhenyouneed
tochooseacolor,suchaswhenyouchooseDesktopmenu:
ChangeDesktopBackgroundandclicktheboxbelowandto
therightofDesktopColors.WhenthePickaColorwindow
opens,thebarbelowthecolorcircledisplaysthecurrentcolor.
Clickthedesiredcolorfromthecolorring,andclick/dragthe
lightnessofthatcolorinthetriangle.Asyouchangethecolor,
therightendofthebarpreviewsthecoloryouareselecting,
whiletheleftendcontinuestodisplaythecurrentcolor.Usethe
eyedroppertopickupacolorfromtheworkspace:Clickthe
eyedropper,andthenclicktheresultingeyedroppermouse
pointeronthecoloryouwant.Thecoloryouchoosewillappear
inthebar.
Figure8-13.PickaColorwindow
RunApplicationWindow
TheRunApplicationwindow(Figure8-14)enablesyoutoruna
programasthoughyouhadinitiateditfromacommandline.To
displaytheRunApplicationwindow,pressAlt-F2.Entera
command;clickRunwithfiletospecifyafilenametouseas
anargumenttothecommandinthetextbox.ClickRunin
terminaltoruntextualapplications,suchasvim,inaterminal
emulatorwindow.
Figure8-14.RunApplicationwindow
GNOMETerminalEmulator/Shell
TheGNOMEterminalemulator(gnome-terminal;seeFigure8-15)
displaysawindowthatmimicsacharacter-basedterminal
(page93).Todisplaytheterminalemulatorwindow,select
Applications:Accessories Terminalfromthepanelatthe
topofthescreen.WhentheGNOMEterminalemulatoris
alreadydisplayed,selectMenubar:File OpenTerminalto
displayadifferentterminalemulatorwindow.
Figure8-15.GNOMEterminalemulator
[Viewfullsizeimage]
Toopenanadditionalterminalsessionwithinthesamewindow,
right-clickthewindowandselectOpenTabfromthecontext
menuorselectMenubar:File OpenTab.Arowoftabs
appearsbelowthemenubarasgnome-terminalopensanother
terminalsessionontopoftheexistingone.Addasmany
terminalsessionsasyoulike;clickthetabstoswitchbetween
sessions.
Asessionyouaddfromthecontextmenuusesthesameprofile
asthesessionyouopenitfrom.Whenyouusethemenubarto
openasession,GNOMEgivesyouachoiceofprofiles,ifmore
thanoneisavailable.Youcanaddandmodifyprofiles,including
theDefaultprofile,byselectingMenubar:Edit Profiles.
HighlighttheprofileyouwanttomodifyorclickNewtodesign
anewprofile.
UsingKDE
BecauseKDEhassomanyfeatures,associatedutilities,and
programs,thissectioncannothopetocoverthemall.Instead,
itattemptstofamiliarizeyouwiththecontentandstyleofKDE;
itisuptoyoutoexploreandfindoutmore.Oneofthebest
waystolearnaboutKDEistogothroughtheonline
documentationandexperiment.Youcanalsolookthroughthe
Mainmenuandbrowsewww.kde.org.
KonquerorBrowser/FileManager
Konquerorwasintroducedonpage94.Thissectiondescribes
additionalKonquerorfeatures.
Tip:WhatisaKDEdesktop?
InKDEdocumentation,thetermdesktopreferstoa
singledivisionofalargerarea.Thisbook,in
conformancewiththeGNOMEdocumentation,
dividesthelargerarea,calledthedesktop,into
workspaces.Youmaynoticethedisparitybetween
theterminologyontheKDEdesktopandthatinthis
book.
WebShortcuts
KonquerorWebShortcuts(differentfromregularshortcuts
[page258])enableyoutosearchforakeywordrapidly,using
thedefaultoraspecifiedsearchengine.Searchenginescan
includedictionaries,bug-trackingsystems,classicsearch
engines,andmore.Forexample,tolookuptheword
colocationintheFreeOnlineDictionaryofComputing,enter
theshortcutfoldoc:colocationinthelocationbar.Tosearch
fordiscussionsaboutSambaonGoogleGroups,enter
groups:samba.Otherabbreviationsthatyoumayfinduseful
areggforGoogle(standardsearch),webster(Merriam-
WebsterDictionary),andfmforFreshmeat.
Whenyouenterakeywordonthelocationbarwithout
specifyingasearchengine,Konquerorlooksitupusingthe
defaultsearchengine.UseMenubar:Settings Configure
Konqueror,scrolldownthetabsontheright,andclickWeb
Shortcutsfromthecolumnonthelefttospecifyadefault
searchengineandworkwithWebShortcuts.
Tip:YoucanuseWebShortcutsby
pressingAlt-F2
YoucanalsouseWebShortcutsfromtheRun
Commanddialogbox,whichyoucanopenby
pressingAlt-F2.Seepage261fordetails.
Bookmarks
Aswithanybrowser,Konquerorbookmarksgiveauser-friendly
nametoaURLorlocalpathnameandallowyoutoreturntothe
bookmarkedlocationbyselectingthenamefromamenu.
Figure8-16showstheKonquerorBookmarksmenu,whichis
availableonthemenubar.Thebookmarkslistappearsbelow
thestandardentriesintheBookmarksmenu(Add,Bookmark
TabsasFolder,Edit,andNewBookmarkFolder).Whenyouclick
thebookmarkofthelocationyouwanttovisit,Konqueror
displaysthatlocation.
Figure8-16.KonquerorBookmarksmenu
ChooseKonquerormenubar:Bookmarks AddBookmark
(orpressCONTROL-B)toaddthelocationdisplayedintheactive
viewtothebookmarkslist.Youcanalsoworkwithbookmarks
fromtheNavigationpanel(Figure4-14,page97).Clicka
bookmarkentryontheNavigationpanelorontheBookmark
toolbar(page255)todisplaythatentry.
Toopen,checkthestatusof,oreditthenameoforlocation
associatedwithabookmark,opentheBookmarkEditorwindow
(Konquerormenubar:Bookmarks EditBookmarks)and
right-clicktheentryyouwanttoworkwith;choosethe
appropriateselectionfromthepop-upmenu.Youcanalsouse
theBookmarkEditortochangetheorderofthebookmarks:Use
themousetodragthehighlightedbookmarkwhereyouwantit
toappearinthelistorusetheupanddownarrowkeystomove
thehighlightedbookmarkwithinthelist.Therightandleft
arrowkeysopenandclosedirectoriesandfolderscontaining
bookmarks.ClickNewFoldertoinsertanewfolderbelowthe
highlightedbookmark.
Menubar
ThemenusontheKonquerormenubar(Figure8-17)change
dependingonwhatKonquerorisdisplaying.Clickingaselection
onthemenubardisplaysadrop-downmenu.
Figure8-17.Konquerormenubarandtoolbars
[Viewfullsizeimage]
Toolbars
Konquerorhasfivetoolbarsthatyoucanturnonandofffrom
Konquerormenubar:Settings Toolbars:Main,Extra,
Location,Bookmark,andSpeech.Thesemenuentriestoggle
thetoolbarsonandoff.Whenacheckmarkappearstotheleft
ofatoolbarname,Konquerordisplaysthattoolbar.Figure8-17
showsthreetoolbars.Eachtoolbarhasahandlethatyoucan
usetomovethetoolbar.Thehandleistheareawith
hatchmarks,usuallyattheleftendofthetoolbar;seeFigure4-
17onpage100foracloseuppictureofahandle.Right-click
almostanywhereonatoolbarthathasahandletodisplaythe
toolbarmenu.
MainToolbar
TheKonquerorMaintoolbartypicallyhasleftandrightarrows
thatmovelinearlythroughthelocationsyouhaveviewedwith
Konqueror.Theuparrowmovesupinadirectoryhierarchy.
Clickingthehouseicondisplaysyourhomedirectory;clicking
thereloadbutton(thearrowsgoinginacircle)reloadsaWeb
pageorfilestructurethatmayhavechanged.Clickingthestop
button(theXthatisredwhenthereisanactionyoucanstop)
haltsthesearchfororloadingofaWebpage,andclickingthe
printbutton(theprinter)sendstheimageintheactiveviewto
theprinter.
ExtraToolbar
ChooseKonquerormenubar:Settings Toolbars Extra
ToolbartodisplaytheExtratoolbar.UseKonqueror
menubar:Settings ConfigureToolbars ExtraToolbar
tochangewhichiconsappearonthistoolbar.
LocationToolbar
TheLocationtoolbarhastwoitemsyoucanworkwith:thetext
boxandtheclearbutton.Theclearbutton(thebroomand
dustpanattheleftendofthetoolbar)clearsthetextbox.To
displayalocation,youcanenteralocalorremotefilenameor
URL,modifythecontentsofthetextbox,orclickthedown
arrowattherightofthisboxandchoosefromthelocationsyou
havevisited.
Bydefault,theSearchtoolbarappearstotherightofthe
Locationtoolbar.YoucanremovethistoolbarfromtheLocation
toolbarbyusingKonquerormenubar:Settings Configure
Toolbars LocationToolbar.
BookmarkToolbar
TheBookmarktoolbargivesyouquickaccesstobookmarks
(page253).DisplaytheBookmarktoolbarwithKonqueror
menubar:Settings Toolbars BookmarkToolbar.
kfind:FindsFiles
StartkfindbyclickingMainmenu:FindFiles/Foldersorby
selectingKonquerormenubar:Tools Findfile(this
selectionisnotactivewhenKonquerorisworkingasa
browser).Konqueroropensanewviewthathasthreetabs:
Name/Location,Contents,andProperties.Theviewopensto
theName/Locationtabwithadefaultfilenametosearchforof
*,whichmatchesallfilenames,includingthosethatbeginwith
aperiod,andyourhomedirectoryastheplacetostartthe
search.Ifyouusedkfindpreviouslyinthecurrentsession,kfind
specifiesthepreviousnameyousearchedforinsteadofthe*.
IntheNamedtextbox,enterthenameofthefileyouwantto
searchfor(youcanincludewildcardcharacters);intheLookin
textbox,enterthedirectoryyouwanttostartthesearchin.
ClicktheBrowsebuttontohelplocatethedirectoryyouwant
tostartthesearchin.Putacheckmarkintheboxnextto
Includesubfolderstosearchthroughsubdirectories.Click
Findtostartthesearch.Thepartofthewindowwiththefields
youjustfilledindimsaskfindtabulatesanddisplaystheresults
ofthesearchinthelowerpartofthewindow.Youcando
whateveryouwantwiththefoundfiles:copy,move,delete,
edit,anddisplaythem,amongotherthings.
Figure8-18showsasearchforallfileswhosenamesendwith
rc(*rc)inSam'shomedirectoryandallsubdirectories.The
asteriskmatchesfilenamesthatbeginwithaperiod.
Figure8-18.FindFileswindow
[Viewfullsizeimage]
InadditiontoorinsteadoffillingintheName/Locationtab,you
canclicktheContentstabtospecifyatextstringthatthefiles
youarelookingforcontain.Putacheckmarkintheboxnextto
Casesensitivetoperformacase-sensitivesearchforthetext
intheContainingtextbox.Forafiletobefoundwhenyou
specifyatextstring,thefilemustmatchtheName/Location
criteriaandtheContentscriteria.
YoucanalsousethePropertiestabtospecifythetype,creation
ormodificationdate,owner,orsizeofthefileyouaresearching
for.
YoucansavetheresultsofthesearchtoafilebyclickingSave
As,twobuttonsbelowtheFindbuttonontherightsideofthe
window.Youwillbegivenachoiceoffilename,location,and
typeoffile(textorHTML)youwanttosave.
MoreAboutViews
Views,orsubwindows,arekeytotakingadvantageof
Konqueror'spower.Thissectionexpandsonwhatwascovered
in"Views"onpage97andexploressomeofthebuttons,
indicators,andmenuchoicesthatworkwithviews.
Figure8-19showstwoviewsside-by-side.Twoindicatorsare
importantwhenyouworkwithmorethanoneview
simultaneously:theActiveViewindicatorandtheLinkindicator
(Figure4-13,page96).
Figure8-19.Konquerordisplayingtwoviews
[Viewfullsizeimage]
ActiveViewIndicator
Thesmallcircleatthelower-leftcornerofeachviewisgreenin
theactiveviewandgrayinotherviews.Theactiveviewhasthe
inputfocusandisthetargetofallKonquerormenucommands.
Thelocationbardisplaysthelocationofthefiledisplayedinthe
activeview.Clickwithinaviewtomakeittheactiveview.
Tip:Konquerorterminology:viewversus
window
TheKonquerorwindowconsistsoftheentirewindow
withfoursidesadjacenttotherootwindow,the
edgeoftheworkspace,orotherwindows,usually
withamenubar,locationbar,andtoolbar.The
Konquerorwindowcanhousemultipleviewsthatis,
subwindowswithintheKonquerorwindow.The
Navigationpanelandterminalemulatorareviews
withspecialproperties.InFigure8-19,the
Konquerorwindowisdisplayingtwoviews.
LinkIndicator
ClickKonquerormenubar:View Linkviewtolinkthetwo
viewsthatweremostrecentlyactive.Alinkofchainappearsin
thesmallrectangleatthelower-rightcornerofeachlinked
view.Twolinkedviewsalwaysshowthesamelocation,withone
usefulexceptionthatiscoveredinthenextparagraph.Although
linkedviewsdisplaythesameinformation,eachmaypresentit
differently.Forexample,onemaydisplayanIconviewandthe
otheraListview.
LocktoCurrentLocation
ChooseKonquerormenubar:View LocktoCurrent
Locationtoplaceacheckmarknexttothisselectionandcause
thecontentsoftheactiveviewtoremainconstant,regardless
ofwhichlinks(URLs)youclickinthatview.Withanormal(not
locked)view,whenyouclickalink,theviewisreplacedbythe
contentsofthatlink.Withtwolinkedviews,neitherofwhichis
locked,whenyouclickalinkinone,bothviewschangeto
reflectthecontentsofthelink.Whenalockedviewislinkedto
anunlockedviewandyouclickalinkinthelockedview,the
contentsofthelinkappearsintheunlockedview.Clickthe
sameselectiontoremovethecheckmarkandunlocktheactive
view.
Toseehowlinkedviewswithoneviewlockedcanbeuseful,
openKonqueror,hidetheNavigationpanelifitispresent(press
F9),maximizethewindow,enterfedora.redhat.com/docsin
thelocationbar,andpressRETURN.Konquerordisplaysthe
FedoraUserDocumentationpage.NextclickWindow Split
ViewLeft/Righttodisplaytwoidenticalviewsside-by-side.
Linktheviews(View LinkView);alinkofchainappearsat
thelower-rightcornerofeachview.Maketheleftviewactiveby
clickinganywhereintheviewthatisnotalinkandthenlock
theview(View LocktoCurrentLocation).Nowwhenyou
clickalinkintheleftview,thelinked-topageappearsinthe
rightview.YoucanviewseverallinksfromtheUser
Documentationpagewithoutconstantlyreturningtothispage
asyouwouldhavetowithasingleview.
Shortcuts
AKonquerorshortcut(notaWebShortcut[page253])isthe
connectionbetweenakeyorkeys(CONTROL-C,forexample)
thatyouholdorpressatthesametimeandanactionthatthe
systemperformswhenyoudoso.OpentheConfigureShortcuts
window(Figure8-20)byselectingKonquerormenubar:
Settings ConfigureShortcuts.InFigure8-20theaction
Copy,whichappearsatthetopofthelistofshortcuts,shows
thatCONTROL-C(Ctrl+C)isashortcutforcopyandthat
CONTROL-Insertisanalternateshortcut.TheactionFindFileis
highlighted;ithasashortcutofALT-F.Thebottomframeinthe
windowshowsthatALT-FisaCustomshortcut.WithCopy
highlighted,thisframewouldshowthatCONTROL-CisaDefault
shortcut.
Figure8-20.ConfigureShortcutswindow
Whenyouclickandhighlightanaction,youcanremoveits
shortcutbyselectingNoneoryoucanreverttothedefault
shortcut(ifoneexists)byselectingDefault.Toassignor
changeacustombinding,clickthekeycapbutton(thebutton
labeledAlt+FinFigure8-20)ortheCustomradiobutton.A
secondConfigureShortcutswindowopens.Tospecifya
shortcut,clearanyexistingshortcutbyclickingthebroomand
dustpanicon,pressthekey(s)youwanttousefortheshortcut,
andclickOK.Thenamesofthekeysthatarenowboundtothe
highlightedactionappearonthekeycapbutton.
TheshortcutsyousetintheConfigureShortcutswindowapply
toactionsyoutakewithinKonqueror.Youcansetglobaland
applicationshortcutsinasimilarmannerbyselectingMain
menu:ControlCenter Regional&Accessibility
KeyboardShortcuts).WithinKonqueror,thebindingsyou
establishintheKonquerorConfigureShortcutswindowtake
precedenceoverbindingsyousetupintheControlCenter.
NavigationPanel
ToselecttheinformationdisplayedbytheKonquerorNavigation
panel,clickoneoftheicons/tabsthatappearsinastackatthe
leftofthepanel.Ontheactivetab,textreplacestheicon.
Figure8-21showstheNavigationpanelwiththeHistorytab
active.
Figure8-21.Navigationpanel,Historytab
ToggletheNavigationpanelonandoffbyusingKonqueror
menubar:Window ShowNavigationpanelorbypressing
F9.AlthoughtheNavigationpanelisaview,ithasadifferent
backgroundthanotherviewsandcannotbeactive.Whenyou
clickanentryintheNavigationpanel,intheactiveview
Konqueroropensthefileordirectorythatthatentrypointsto.
Clickoneoftheicons/tabsintheNavigationpaneltodisplaya
listofdirectoriesandfilesthatcorrespondstothaticon.Inthis
list,clicktheplussigninthesmallboxtoexpandadirectory
andclickaminussigninasmallboxtocollapseadirectory.
ClickinganentrywithoutaboxcausesKonquerortodisplay
thatentryintheactiveview.Whenyouclickadirectoryinthis
manner,KonquerordisplaysaFileManagerviewofthe
directory.WhenyouclickaURLofaWebsite,Konqueror
displaystheWebsite.(The
$KDEHOME/share/apps/konqsidebartng/entriesdirectory
holdsfilesthatcorrespondtotheiconsintheNavigationpanel.
$KDEHOMEdefaultsto/usr.)
Eachoftheinitialicons/tabsintheNavigationpanelgivesyoua
differentperspectiveonthesystemandwhatyouhavebeen
doingwithit.Youcanmodify,delete,andaddtosomeofthese
iconsbyright-clickingtheicon.Right-clickintheemptyspace
blowthetabstomodifytheNavigationpanel.
KDEUtilities
ManyutilitiesareavailableontheMainmenuandontheKDE
Website.Youcanalsotakeadvantageofutilities,suchasthe
GNOMEutilities,thatwerenotspecificallydesignedwithKDEin
mind.Thissectionlistsafewofthemostcommonlyused
utilities.
konsole:TerminalEmulator
TheKDEterminalemulator(konsole)displaysawindowthat
mimicsacharacter-basedterminal.Bringupaterminal
emulatorbyselectingMainmenu:System Terminalorby
selectingKonsolefromtheDesktopmenu.
Youcandisplaymultipleterminalsessionswithinasingle
Konsolewindow.WiththeKonsolewindowopen,makea
selectionfromMenubar:Session NewShellorclickthe
yellowicon(attheleftendofthetoolbar,usuallyatthebottom
ofthewindow)toopenanothersession.Clickandholdthisicon
forafewmomentstodisplaytheSessionmenu,whichoffersa
choiceofsessionstostart.Switchbetweensessionsbyclicking
theterminalicons,alsoonthetoolbar,orbyholdingSHIFTand
pressingtheRIGHTorLEFTARROWkey.
kcolorchooser:SelectsaColor
TheSelectColorwindow(kcolorchooser;seeFigure8-22)appears
whenyouclickacolorbar,suchasoneofthetwothatappear
intheOptionsframewhenyouselectConfigureDesktopfrom
theDesktopmenuandthenclickBackgroundinthestackof
verticaltabsattheleftsideoftheConfigurewindow.The
squarecenteredontopofthelineabovetheOKandCancel
buttonsalwaysdisplaystheselectedcolor.Whenyouclickthe
OKbutton,thiscolorreturnstothecolorbarthatyouinitially
clicked.
Figure8-22.SelectColorwindow
Thereareseveralwaystoselectacolor:
Clickthecolor/shadeyouwantonthemulticoloredboxat
theupper-leftportionofthewindow.
ClickthepalettetotherightoftheAddtoCustomColors
button.Themousepointerturnsintocrosshairs.Position
thecrosshairsoverthecoloryouwant,anywhereonthe
workspace,andclick.Thecoloryouclickonbecomesthe
selectedcolor.
Choosealinefromthecomboboxattheupper-rightcorner
ofthewindow(FortyColorsinFigure8-22).Youhavea
choiceofseveralgroupsofcolors,includingRecentColors
(anautomaticallygeneratedlistofcolorsyouhaveselected)
andCustomColors(colorsyouhaveaddedtothelistof
customcolorsbyselectingandthenclickingAddto
CustomColors).Clickacolorintheareabelowthecombo
boxtoselectit.
EntertheHTMLspecificationofthecoloryouwant.
EntertheappropriatenumbersintheH,S,andV(hue,
saturation,value)columnoftextboxesorintheR,G,and
B(red,green,blue)column.
Afteryouselectacolor,youcanadjustitsbrightnessbyclicking
theverticalbartotherightofthemulticolorboxorbydragging
thepointerontherightsideofthisbarupordown.ClickOK
whenyouhaveselectedthecoloryouwant.
RunCommand
Torunacharacter-basedprogram,displaytheRunCommand
windowbyselectingRunCommandfromtheMainmenuor
theDesktopmenu,orbypressingALT-F2.Enterthenameofthe
programintheCommandtextbox,clickOptions,putacheck
markintheboxadjacenttoRuninterminalwindow,and
clickRun.KDEthenrunstheprograminaKonsolewindow.
Whenyourunwhointhismanner,forexample,KDEdisplaysthe
outputofwhoinanewwindowanddisplays<Finished>onthe
titlebarofthewindow.Closethewindowwhenyouarefinished
viewingtheoutput;youcandonofurtherworkinit.Ifyourun
aprogramsuchassshfromaRunCommandwindow,the
windowremainsactiveuntilyouexitfromssh.
YoucanalsousetheRunCommandwindowtostartgraphical
programs(enterthenameoftheprogram),displayWebpages
(entertheURL),orenterWebShortcuts(seepage253).
klipper:ClipboardUtility
Theklipperutilityisasophisticatedmultiple-buffercut-and-paste
utility.Inadditiontocuttingandpastingfrommultiplebuffers,
klippercanexecuteacommandbasedonthecontentsofa
buffer.AsdistributedwithRedHatLinux,klipperisstartedby
defaultwhenyoulogin.Ifyouneedtostartklippermanually,
chooseMainmenu:RunCommand,enterklipper,andclick
Run.Theklipperutilitydoesnotstartasecondoccurrenceof
itselfwhenitisalreadyrunning.Theklippericon(aclipboard
andpencil)appearsattherightoftheMainpanel.
Eachtimeyouhighlighttext,klippercopiesthetexttooneofits
buffers.ClicktheklippericonorpressCONTROL-ALT-Vtodisplay
theklipperpop-upmenu(Figure8-23).Thetoppartofthis
menuliststhetextthatklipperisholdinginitsbuffers.Whenthe
linesaretoolongtofitinsidethewindow,klipperusesellipses
(...)toindicatemissingmaterial.Topastethetextfromabuffer
toadocument,displaytheklipperpop-upmenuandclickthe
lineyouwanttopaste;thepop-upmenucloses.Movethe
mousepointertothelocationwhereyouwanttopastethetext
andmiddle-click.Inaterminalemulatorwindow,thetextis
alwayspastedatthelocationofthetextcursor.
Figure8-23.klipperpop-upmenu
ChapterSummary
TheXWindowSystemGUIisportableandflexibleandmakesit
easytowriteapplicationsthatworkonmanydifferenttypesof
systemswithouthavingtoknowlow-leveldetailsaboutthe
individualsystems.ThisGUIcanoperateinanetworked
environment,allowingausertorunaprogramonaremote
systemandsendtheresultstoalocaldisplay.Theclient/server
conceptisintegraltotheoperationoftheXWindowSystem,in
whichtheXserverisresponsibleforfulfillingrequestsmadeof
XWindowSystemapplicationsorclients.Hundredsofclients
areavailablethatcanrununderX,andprogrammerscanalso
writetheirownclients,usingtoolssuchastheQtandKDE
librariestowriteKDEprogramsandtheGTK+andGTK+2
GNOMElibrariestowriteGNOMEprograms.
Thewindowmanagers,andvirtuallyallXapplications,are
designedtohelpuserstailortheirworkenvironmentsinsimple
orcomplexways.Youcandesignateapplicationsthatstart
automatically,setsuchattributesascolorsandfonts,andeven
alterthewaykeyboardstrokesandmouseclicksare
interpreted.
BuiltontopoftheXWindowSystem,GNOMEisadesktop
managerthatyoucanuseasisorcustomizetobettersuityour
needs.Itisagraphicaluserinterfacetosystemservices
(commands),thefilesystem,applications,andmore.Although
notpartofit,theMetacitywindowmanagerworkscloselywith
GNOMEandisthedefaultwindowmanagerforGNOMEunder
RedHatLinux.Thewindowmanagercontrolsallaspectsofthe
windows:placement,decoration,grouping,minimizingand
maximizing,sizing,moving,andsoon.
GNOMEalsoprovidesmanygraphicalutilitiesthatyoucanuse
tocustomizeandworkwiththedesktop.ItsupportsMIME
typessothatwhenyoudouble-clickanicon,itgenerallyknows
whichtooltousetodisplaythedatarepresentedbytheicon.In
sum,GNOMEisapowerfuldesktopmanagerthatcanmake
yourjobeasierandmorefun.
TheKDEdesktopenvironmentoffersanextensivearrayof
tools,includingmultiplehelpsystems;aflexiblefilemanager
andbrowser;anofficepackagethatincludeswordprocessing,
spreadsheet,presentation,charting,andemailapplications;
numerouspanelsandmenusthatyoucanconfigureinmany
ways;andenoughoptionstopleasethemostcriticaluser.
Konqueror,theKDEfilemanagerandbrowser,hasverylittle
functionalityofitsown.Instead,itdependsonotherprograms
todoitswork.Konqueroropenstheseprogramswithinitsown
window,givingtheimpressionthatitisverycapableagood
exampleofseamlessprogramintegration.Whenyouask
Konquerortoopenafile(whichcanbealocalorremotetext,
music,picture,orHTMLfile),itfiguresoutwhatkindoffileitis
(thefile'sMIMEtype)soitknowswhichprogramtousetoopen
ordisplaythefile.
Panelsandmenus,whicharecloselyrelated,enableyouto
selectanobject(whichcanbejustaboutanythingonthe
system)fromalist.Onapanel,yougenerallyclickaniconfrom
aboxoficons(thepanel);onamenu,youtypicallyclicktextin
alist.
TheKDEenvironmentprovidesthecasualuser,theoffice
worker,thepoweruser,andtheprogrammer/systemdesignera
spacetoworkinandasetoftoolstoworkwith.KDEalso
providesoff-the-shelfproductivityandalmostlimitlesswaysto
customizeitslook,feel,andresponse.
Exercises
1.
RegardingKonquerorthefilemanager:
a. WhatisKonqueror?
b. ListfourthingsthatyoucandowithKonqueror.
c. HowdoyouuseKonquerortosearchforafile?
2. Whatisaterminalemulator?WhatdoesitallowyoutodofromaGUIthatyou
wouldnotbeabletodowithoutone?
3. Whatisklipper?Howdoyouuseittocutandpastetext?
4.
a. WhatisNautilus?
b. ListtwowaysthatyoucanyouopenafileusingNautilus.
c. HowdoesNautilus"know"whichprogramtousetoopendifferenttypesof
files?
d. WhicharethethreecommonNautiluscontrolbars?Whatkindsoftoolsdo
youfindoneach?
e. DiscusstheuseoftheNautiluslocationbar.
AdvancedExercises
5. DiscussKonqueror'slackoffunctionalityanditsabilitytoperformsomanytasks.
WhatisaKPart?
6.
RegardingKonquerortheWebbrowser:
a. HowcanyousearchtheWebforawordorphrasewithoutenteringitina
searchengine?
b. HowwouldyouuseKonquerortotransferlocalfilestoaremoteFTPsite?
DescribehowyouwoulddothisusingaKonquerorwindowwithtwoviews.
7.
Describethreewaysto
a. Changethesizeofawindow.
b. Deleteawindow.
8. ExplainthepurposeofMIME.HowdoesitfacilitatetheuseofaGUI?
9.
Writeanxeyescommandtodisplayawindowthatis600pixelswideand400pixels
tall,islocated200pixelsfromtherightedgeofthescreenand300pixelsfromthe
topofthescreen,andcontainsorangeeyesoutlinedinbluewithredpupils.(Hint:
Refertothexeyesmanpage.)
9.TheBourneAgainShell
INTHISCHAPTER
StartupFiles 267
RedirectingStandardError 270
WritingaSimpleShellScript 272
JobControl 280
ManipulatingtheDirectoryStack 282
ParametersandVariables 285
Processes 300
History 302
ReexecutingandEditingCommands 304
Aliases 318
Functions 321
ControllingbashFeaturesandOptions 324
ProcessingtheCommandLine 328
ThischapterpicksupwhereChapter7leftoff.Chapter28
expandsonthischapter,exploringcontrolflowcommandsand
moreadvancedaspectsofprogrammingtheBourneAgain
Shell.Thebashhomepageiswww.gnu.org/software/bash.The
bashinfopageisacompleteBourneAgainShellreference.
TheBourneAgainShellisacommandinterpreterandhigh-level
programminglanguage.Asacommandinterpreter,itprocesses
commandsyouenteronthecommandlineinresponsetoa
prompt.Whenyouusetheshellasaprogramminglanguage,it
processescommandsstoredinfilescalledshellscripts.Like
otherlanguages,shellshavevariablesandcontrolflow
commands(forexample,forloopsandifstatements).
Whenyouuseashellasacommandinterpreter,youcan
customizetheenvironmentyouworkin.Youcanmakeyour
promptdisplaythenameoftheworkingdirectory,createa
functionoraliasforcpthatkeepsitfromoverwritingcertain
kindsoffiles,takeadvantageofkeywordvariablestochange
aspectsofhowtheshellworks,andsoon.Youcanalsowrite
shellscriptsthatdoyourbidding,fromaone-linescriptthat
storesalong,complexcommandtoalongerscriptthatrunsa
setofreports,printsthem,andmailsyouareminderwhenthe
jobisdone.Morecomplexshellscriptsarethemselves
programs;theydonotjustrunotherprograms.Chapter28has
someexamplesofthesetypesofscripts.
MostsystemshellscriptsarewrittentorunundertheBourne
AgainShell.Ifyouwilleverworkinsingle-usermodeaswhen
youbootyoursystemordosystemmaintenance,
administration,orrepairwork,forexampleitisagoodideato
becomefamiliarwiththisshell.
Thischapterexpandsontheinteractivefeaturesoftheshell
describedinChapter7,explainshowtocreateandrunsimple
shellscripts,discussesjobcontrol,introducesthebasicaspects
ofshellprogramming,talksabouthistoryandaliases,and
describescommandlineexpansion.Chapter28presentssome
morechallengingshellprogrammingproblems.
Background
TheBourneAgainShellisbasedontheBourneShell(theearly
UNIXshell;thisbookreferstoitastheoriginalBourneShellto
avoidconfusion),whichwaswrittenbySteveBourneofAT&T's
BellLaboratories.OvertheyearstheoriginalBourneShellhas
beenexpandedbutitremainsthebasicshellprovidedwith
manycommercialversionsofUNIX.
shShell
Becauseofitslongandsuccessfulhistory,theoriginalBourne
Shellhasbeenusedtowritemanyoftheshellscriptsthathelp
manageUNIXsystems.SomeofthesescriptsappearinLinux
asBourneAgainShellscripts.AlthoughtheBourneAgainShell
includesmanyextensionsandfeaturesnotfoundintheoriginal
BourneShell,bashmaintainscompatibilitywiththeoriginal
BourneShellsoyoucanrunBourneShellscriptsunderbash.On
UNIXsystemstheoriginalBourneShellisnamedsh.OnLinux
systemsshisasymboliclinktobashensuringthatscriptsthat
requirethepresenceoftheBourneShellstillrun.Whencalled
assh,bashdoesitsbesttoemulatetheoriginalBourneShell.
KornShell
SystemVUNIXintroducedtheKornShell(ksh),writtenby
DavidKorn.Thisshellextendedmanyfeaturesoftheoriginal
BourneShellandaddedmanynewfeatures.Somefeaturesof
theBourneAgainShell,suchascommandaliasesand
commandlineediting,arebasedonsimilarfeaturesfromthe
KornShell.
POSIXstandards
ThePOSIX(thePortableOperatingSystemInterface)familyof
relatedstandardsisbeingdevelopedbyPASC(IEEE'sPortable
ApplicationStandardsCommittee,www.pasc.org).A
comprehensiveFAQonPOSIX,includingmanylinks,appearsat
www.opengroup.org/austin/papers/posix_faq.html.
POSIXstandard1003.2describesshellfunctionality.TheBourne
AgainShellprovidesthefeaturesthatmatchtherequirements
ofthisPOSIXstandard.Effortsareunderwaytomakethe
BourneAgainShellfullycomplywiththePOSIXstandard.Inthe
meantime,ifyouinvokebashwiththeposixoption,the
behavioroftheBourneAgainShellwillmorecloselymatchthe
POSIXrequirements.
ShellBasics
Thissectioncoverswritingandusingstartupfiles,redirecting
standarderror,writingandexecutingsimpleshellscripts,
separatingandgroupingcommands,implementingjobcontrol,
andmanipulatingthedirectorystack.
StartupFiles
Whenashellstarts,itrunsstartupfilestoinitializeitself.Which
filestheshellrunsdependsonwhetheritisaloginshell,an
interactiveshellthatisnotaloginshell(suchasyougetby
givingthecommandbash),oranoninteractiveshell(oneused
toexecuteashellscript).Youmusthavereadaccesstoa
startupfiletoexecutethecommandsinit.RedHatLinuxputs
appropriatecommandsinsomeofthesefiles.Thissection
coversbashstartupfiles.
LoginShells
Thefilescoveredinthissectionareexecutedbyloginshellsand
shellsthatyoustartwiththeloginoption.Loginshellsare,by
theirnature,interactive.
/etc/profile
Theshellfirstexecutesthecommandsin/etc/profile.
Superusercansetupthisfiletoestablishsystemwidedefault
characteristicsforbashusers.
.bash_profile
.bash_login.
.profile
Nexttheshelllooksfor~/.bash_profile,~/.bash_login,and
~/.profile(~/isshorthandforyourhomedirectory),inthat
order,executingthecommandsinthefirstofthesefilesitfinds.
Youcanputcommandsinoneofthesefilestooverridethe
defaultssetin/etc/profile.
.bash_logout
Whenyoulogout,bashexecutescommandsinthe
~/.bash_logoutfile.Frequentlycommandsthatcleanupafter
asession,suchasthosethatremovetemporaryfiles,gointhis
file.
InteractiveNonloginShells
Thecommandsintheprecedingstartupfilesarenotexecuted
byinteractive,nonloginshells.However,theseshellsinherit
fromtheloginshellvariablesthataresetbythesestartupfiles.
/etc/bashrc
Althoughnotcalledbybashdirectly,many~/.bashrcfilescall
/etc/bashrc.ThissetupallowsSuperusertoestablish
systemwidedefaultcharacteristicsfornonloginbashshells.
.bashrc
Aninteractivenonloginshellexecutescommandsinthe
~/.bashrcfile.Typicallyastartupfileforaloginshell,suchas
.bash_profile,runsthisfile,sothatbothloginandnonlogin
shellsbenefitfromthecommandsin.bashrc.
NoninteractiveShells
Thecommandsinthepreviouslydescribedstartupfilesarenot
executedbynoninteractiveshells,suchasthosethatrunsshell
scripts.However,theseshellsinheritfromtheloginshell
variablesthataresetbythesestartupfiles.
BASH_ENV
Noninteractiveshellslookfortheenvironmentvariable
BASH_ENV(orENV,iftheshelliscalledassh)andexecute
commandsinthefilenamedbythisvariable.
SettingUpStartupFiles
Althoughmanystartupfilesandtypesofshellsexist,usuallyall
youneedarethe.bash_profileand.bashrcfilesinyourhome
directory.Commandssimilartothefollowingin.bash_profile
runcommandsfrom.bashrcforloginshells(when.bashrc
exists).Withthissetup,thecommandsin.bashrcareexecuted
byloginandnon-loginshells.
if[-f~/.bashrc];thensource~/.bashrc;fi
The[f~/.bashrc]testswhetherthefilenamed.bashrcin
yourhomedirectoryexists.Seepages879and881formore
informationontestanditssynonym[].
Tip:Use.bash_profiletosetPATH
Becausecommandsin.bashrcmaybeexecuted
manytimes,andbecausesubshellsinheritexported
variables,itisagoodideatoputcommandsthat
addtoexistingvariablesinthe.bash_profilefile.
Forexample,thefollowingcommandaddsthebin
subdirectoryofthehomedirectorytoPATH(page
292)andshouldgoin.bash_profile:
PATH=$PATH:$HOME/bin
Whenyouputthiscommandin.bash_profileand
notin.bashrc,thestringisaddedtothePATH
variableonlyonce,whenyoulogin.
Modifyingavariablein.bash_profileallows
changesyoumakeinaninteractivesessionto
propagatetosubshells.Incontrast,modifyinga
variablein.bashrcoverrideschangesinheritedfrom
aparentshell.
Sample.bash_profileand.bashrcfilesfollow.Someofthe
commandsusedinthesefilesarenotcovereduntillaterinthis
chapter.Inanystartupfile,youmustexportvariablesand
functionsthatyouwanttobeavailabletochildprocesses.For
moreinformationreferto"LocalityofVariables"onpage916.
$cat~/.bash_profile
if[-f~/.bashrc];then
source~/.bashrc#readlocalstartupfileifitexists
fi
PATH=$PATH:.#addtheworkingdirectorytoPATH
exportPS1='[\h\W\!]\$'#setprompt
Thefirstcommandinthepreceding.bash_profilefileexecutes
thecommandsintheuser's.bashrcfileifitexists.Thenext
commandaddstothePATHvariable(page292).Typically
PATHissetandexportedin/etc/profilesoitdoesnotneed
tobeexportedinauser'sstartupfile.Thefinalcommandsets
andexportsPS1(page293),whichcontrolstheuser'sprompt.
Nextisasample.bashrcfile.Thefirstcommandexecutesthe
commandsinthe/etc/bashrcfileifitexists.NexttheLANG
(page298)andVIMINIT(forviminitialization)variablesare
setandexportedandseveralaliases(page318)are
established.Thefinalcommanddefinesafunction(page321)
thatswapsthenamesoftwofiles.
$cat~/.bashrc
if[-f/etc/bashrc];then
source/etc/bashrc#readglobalstartupfileifitexists
fi
set-onoclobber#preventoverwritingfiles
unsetMAILCHECK#turnoff"youhavenewmail"notice
exportLANG=C#setLANGvariable
exportVIMINIT='setaiaw'#setvimoptions
aliasdf='df-h'#setupaliases
aliasrm='rm-i'#alwaysdointeractiverm's
aliaslt='ls-ltrh|tail'
aliash='history|tail'
aliasch='chmod755'
functionswitch()#afunctiontoexchangethenames
{#oftwofiles
localtmp=$$switch
mv"$1"$tmp
mv"$2""$1"
mv$tmp"$2"
}
.(Dot)orsource:RunsaStartupFileintheCurrentShell
Afteryoueditastartupfilesuchas.bashrc,youdonothaveto
logoutandloginagaintoputthechangesintoeffect.Youcan
runthestartupfileusingthe.(dot)orsourcebuiltin(theyare
thesamecommand).Aswithallothercommands,the.mustbe
followedbyaSPACEonthecommandline.Usingthe.orsource
builtinissimilartorunningashellscript,exceptthatthese
commandsrunthescriptaspartofthecurrentprocess.
Consequently,whenyouuse.orsourcetorunascript,changes
youmaketovariablesfromwithinthescriptaffecttheshellthat
yourunthescriptfrom.Youcanusethe.orsourcecommandto
runanyshellscriptnotjustastartupfilebutundesirableside
effects(suchaschangesinthevaluesofshellvariablesyourely
on)mayoccur.Ifyouranastartupfileasaregularshellscript
anddidnotusethe.orsourcebuiltin,thevariablescreatedinthe
startupfilewouldremainineffectonlyinthesubshellrunning
thescriptnotintheshellyouranthescriptfrom.Formore
informationreferto"LocalityofVariables"onpage916.
Inthefollowingexample,.bashrcsetsseveralvariablesand
setsPS1,theprompt,tothenameofthehost.The.builtin
putsthenewvaluesintoeffect.
$cat~/.bashrc
exportTERM=vt100#settheterminaltype
exportPS1="$(hostname-f):"#setthepromptstring
exportCDPATH=:$HOME#addHOMEtoCDPATHstring
sttykill'^u'#setkilllinetocontrol-u
$.~/.bashrc
bravo.example.com:
CommandsThatAreSymbols
TheBourneAgainShellusesthesymbols(,),[,],and$ina
varietyofways.Tominimizeconfusion,Table9-1liststhemost
commonuseofeachofthesesymbols,eventhoughsomeof
themarenotintroduceduntillater.
Table9-1.Builtincommandsthataresymbols
Symbol Command
() Subshell(page279)
$() Commandsubstitution(page334)
(()) Arithmeticevaluation;asynonymforlet(usewhenthe
enclosedvaluecontainsanequalsign)(page940)
$(()) Arithmeticexpansion(notforusewithanenclosed
equalsign)(page332)
[] Thetestcommand(pages879,881,and894)
[[]] Conditionalexpression;similarto[]butaddsstring
comparisons(page941)
RedirectingStandardError
Chapter7coveredtheconceptofstandardoutputand
explainedhowtoredirectstandardoutputofacommand.In
additiontostandardoutput,commandscansendoutputto
standarderror.Acommandcansenderrormessagesto
standarderrortokeepthemfromgettingmixedupwiththe
informationitsendstostandardoutput.
Justasitdoeswithstandardoutput,bydefaulttheshellsends
acommand'sstandarderrortothescreen.Unlessyouredirect
oneortheother,youmaynotknowthedifferencebetweenthe
outputacommandsendstostandardoutputandtheoutputit
sendstostandarderror.Thissectioncoversthesyntaxusedby
theBourneAgainShell.
Filedescriptors
Afiledescriptoristheplaceaprogramsendsitsoutputtoand
getsitsinputfrom.Whenyouexecuteaprogram,theprocess
runningtheprogramopensthreefiledescriptors:0(standard
input),1(standardoutput),and2(standarderror).The
redirectoutputsymbol(>[page210])isshorthandfor1>,
whichtellstheshelltoredirectstandardoutput.Similarly<
(page212)isshortfor0<,whichredirectsstandardinput.The
symbols2>redirectstandarderror.Formoreinformationrefer
to"FileDescriptors"onpage911.
Thefollowingexamplesdemonstratehowtoredirectstandard
outputandstandarderrortodifferentfilesandtothesamefile.
Whenyourunthecatutilitywiththenameofafilethatdoesnot
existandthenameofafilethatdoesexist,catsendsanerror
messagetostandarderrorandcopiesthefilethatdoesexistto
standardoutput.Unlessyouredirectthem,bothmessages
appearonthescreen.
$caty
Thisisy.
$catx
cat:x:Nosuchfileordirectory
$catxy
cat:x:Nosuchfileordirectory
Thisisy.
Whenyouredirectstandardoutputofacommand,outputsent
tostandarderrorisnotaffectedandstillappearsonthescreen.
$catxy>hold
cat:x:Nosuchfileordirectory
$cathold
Thisisy.
Similarly,whenyousendstandardoutputthroughapipe,
standarderrorisnotaffected.Thefollowingexamplesends
standardoutputofcatthroughapipetotr,whichinthis
exampleconvertslowercasecharacterstouppercase.(Seethe
trinfopageformoreinformation.)Thetextthatcatsendsto
standarderrorisnottranslatedbecauseitgoesdirectlytothe
screenratherthanthroughthepipe.
$catxy|tr"[a-z]""[A-Z]"
cat:x:Nosuchfileordirectory
THISISY.
Thefollowingexampleredirectsstandardoutputandstandard
errortodifferentfiles.Thenotation2>tellstheshellwhereto
redirectstandarderror(filedescriptor2).The1>tellstheshell
wheretoredirectstandardoutput(filedescriptor1).Youcan
use>inplaceof1>.
$catxy1>hold12>hold2
$cathold1
Thisisy.
$cathold2
cat:x:Nosuchfileordirectory
Duplicatingafiledescriptor
Inthenextexample,1>redirectsstandardoutputtohold.
Then2>&1declaresfiledescriptor2tobeaduplicateoffile
descriptor1.Asaresultbothstandardoutputandstandard
errorareredirectedtohold.
$catxy1>hold2>&1
$cathold
cat:x:Nosuchfileordirectory
Thisisy.
Intheprecedingexample,1>holdprecedes2>&1.Ifthey
hadbeenlistedintheoppositeorder,standarderrorwouldhave
beenmadeaduplicateofstandardoutputbeforestandard
outputwasredirectedtohold.Inthatcaseonlystandard
outputwouldhavebeenredirectedtohold.
Thenextexampledeclaresfiledescriptor2tobeaduplicateof
filedescriptor1andsendstheoutputforfiledescriptor1
throughapipetothetrcommand.
$catxy2>&1|tr"[a-z]""[A-Z]"
CAT:X:NOSUCHFILEORDIRECTORY
THISISY.
Sendingerrorstostandarderror
Youcanalsouse1>&2toredirectstandardoutputofa
commandtostandarderror.Thistechniqueisusedinshell
scriptstosendtheoutputofechotostandarderror.Inthe
followingscript,standardoutputofthefirstechoisredirectedto
standarderror:
$catmessage_demo
echoThisisanerrormessage.1>&2
echoThisisnotanerrormessage.
Ifyouredirectstandardoutputofmessage_demo,error
messagessuchastheoneproducedbythefirstechowillstillgo
tothescreenbecauseyouhavenotredirectedstandarderror.
Becausestandardoutputofashellscriptisfrequently
redirectedtoanotherfile,youcanusethistechniquetodisplay
onthescreenerrormessagesgeneratedbythescript.Thelnks
script(page886)usesthistechnique.Youcanalsousetheexec
builtintocreateadditionalfiledescriptorsandtoredirect
standardinput,standardoutput,andstandarderrorofashell
scriptfromwithinthescript(page930).
TheBourneAgainShellsupportstheredirectionoperators
showninTable9-2.
Table9-2.Redirectionoperators
Operator Meaning
<filename Redirectsstandardinputfromfilename.
>filename Redirectsstandardoutputtofilenameunlessfilename
existsandnoclobber(page213)isset.Ifnoclobber
isnotset,thisredirectioncreatesfilenameifitdoes
notexist.
>|filename Redirectsstandardoutputtofilename,evenifthefile
existsandnoclobber(page213)isset.
>>filename Redirectsandappendsstandardoutputtofilename
unlessfilenameexistsandnoclobber(page213)is
set.Ifnoclobberisnotset,thisredirectioncreates
filenameifitdoesnotexist.
<&mDuplicatesstandardinputfromfiledescriptorm(page
912).
[n]>&mDuplicatesstandardoutputorfiledescriptornif
specifiedfromfiledescriptorm(page912).
[n]<&- Closesstandardinputorfiledescriptornifspecified
(page912).
[n]>&- Closesstandardoutputorfiledescriptornifspecified.
WritingaSimpleShellScript
Ashellscriptisafilethatcontainscommandsthattheshellcan
execute.Thecommandsinashellscriptcanbeanycommands
youcanenterinresponsetoashellprompt.Forexample,a
commandinashellscriptmightrunaLinuxutility,acompiled
program,oranothershellscript.Likethecommandsyougive
onthecommandline,acommandinashellscriptcanuse
ambiguousfilereferencesandcanhaveitsinputoroutput
redirectedfromortoafileorsentthroughapipe(page216).
Youcanalsousepipesandredirectionwiththeinputandoutput
ofthescriptitself.
Inadditiontothecommandsyouwouldordinarilyuseonthe
commandline,controlflowcommands(alsocalledcontrol
structures)findmostoftheiruseinshellscripts.Thisgroupof
commandsenablesyoutoaltertheorderofexecutionof
commandsinascriptjustasyouwouldaltertheorderof
executionofstatementsusingastructuredprogramming
language.Referto"ControlStructures"onpage878for
specifics.
Theshellinterpretsandexecutesthecommandsinashell
script,oneafteranother.Thusashellscriptenablesyouto
simplyandquicklyinitiateacomplexseriesoftasksora
repetitiveprocedure.
chmod:MakesaFileExecutable
Toexecuteashellscriptbygivingitsnameasacommand,you
musthavepermissiontoreadandexecutethefilethatcontains
thescript(referto"AccessPermissions"onpage180).Read
permissionenablesyoutoreadthefilethatholdsthescript.
Executepermissiontellstheshellandthesystemthatthe
owner,group,and/orpublichaspermissiontoexecutethefile;
itimpliesthatthecontentofthefileisexecutable.
Whenyoucreateashellscriptusinganeditor,thefiledoesnot
typicallyhaveitsexecutepermissionset.Thefollowingexample
showsafilenamedwhosonthatcontainsashellscript:
$catwhoson
date
echo"UsersCurrentlyLoggedIn"
who
$whoson
bash:./whoson:Permissiondenied
Youcannotexecutewhosonbygivingitsnameasacommand
becauseyoudonothaveexecutepermissionforthefile.The
shelldoesnotrecognizewhosonasanexecutablefileand
issuesanerrormessagewhenyoutrytoexecuteit.Whenyou
givethefilenameasanargumenttobash(bashwhoson),bash
takestheargumenttobeashellscriptandexecutesit.Inthis
casebashisexecutableandwhosonisanargumentthatbash
executessoyoudonotneedtohavepermissiontoexecute
whoson.
Tip:Commandnotfound?
Ifyougetthemessage
$whoson
bash:whoson:commandnotfound
theshellisnotsetuptosearchforexecutablefiles
intheworkingdirectory.Givethiscommandinstead:
$./whoson
The./tellstheshellexplicitlytolookforan
executablefileintheworkingdirectory.Tochange
theenvironmentsothattheshellsearchesthe
workingdirectoryautomatically,seepage292.
Thechmodutilitychangestheaccessprivilegesassociatedwitha
file.Figure9-1showslswiththeloptiondisplayingtheaccess
privilegesofwhosonbeforeandafterchmodgivesexecute
permissiontothefile'sowner.
Figure9-1.Usingchmodtomakeashellscript
executable
[Viewfullsizeimage]
Thefirstlsdisplaysahyphen()asthefourthcharacter,
indicatingthattheownerdoesnothavepermissiontoexecute
thefile.Nextchmodgivestheownerexecutepermission:The
u+xcauseschmodtoadd(+)executepermission(x)forthe
owner(u).(Theustandsforuser,althoughitmeanstheowner
ofthefilewhomaybetheuserofthefileatanygiventime.)
Thesecondargumentisthenameofthefile.Thesecondls
showsanxinthefourthposition,indicatingthattheownernow
hasexecutepermission.
Ifotheruserswillexecutethefile,youmustalsochangegroup
and/orpublicaccesspermissionsforthefile.Anyusermust
haveexecuteaccesstousethefile'snameasacommand.If
thefileisashellscript,theusertryingtoexecutethefilemust
alsohavereadaccesstothefile.Youdonotneedreadaccess
toexecuteabinaryexecutable(compiledprogram).
ThefinalcommandinFigure9-1showstheshellexecutingthe
filewhenitsnameisgivenasacommand.Formoreinformation
referto"AccessPermissions"onpage180,ls(page181),and
chmod(page182).
#!SpecifiesaShell
Youcanputaspecialsequenceofcharactersonthefirstlineof
afiletotelltheoperatingsystemwhichshellshouldexecutethe
file.Becausetheoperatingsystemcheckstheinitialcharacters
ofaprogrambeforeattemptingtoexecit,thesecharacters
savethesystemfrommakinganunsuccessfulattempt.If#!
arethefirsttwocharactersofascript,thesysteminterprets
thecharactersthatfollowastheabsolutepathnameofthe
utilitythatshouldexecutethescript.Thiscanbethepathname
ofanyprogram,notjustashell.Thefollowingexample
specifiesthatbashshouldrunthescript:
$catbash_script
#!/bin/bash
echo"ThisisaBourneAgainShellscript."
The#!charactersareusefulifyouhaveascriptthatyouwant
torunwithashellotherthantheshellyouarerunningthe
scriptfrom.Thefollowingexampleshowsascriptthatshould
beexecutedbytcsh:
$cattcsh_script
#!/bin/tcsh
echo"Thisisatcshscript."
setperson=jenny
echo"personis$person"
Becauseofthe#!line,theoperatingsystemensuresthattcsh
executesthescriptnomatterwhichshellyourunitfrom.
Youcanusepsfwithinashellscripttodisplaythenameofthe
shellthatisexecutingthescript.Thethreelinesthatpsdisplays
inthefollowingexampleshowtheprocessrunningtheparent
bashshell,theprocessrunningthetcshscript,andtheprocess
runningthepscommand:
$cattcsh_script2
#!/bin/tcsh
ps-f
$tcsh_script2
UIDPIDPPIDCSTIMETTYTIMECMD
alex303130300Nov16pts/400:00:00-bash
alex93583031021:13pts/400:00:00/bin/tcsh./tcsh_script2
alex93759358021:13pts/400:00:00ps-f
Ifyoudonotfollow#!withthenameofanexecutable
program,theshellreportsthatitcannotfindthecommandthat
youaskedittorun.Youcanoptionallyfollow#!withSPACEs.If
youomitthe#!lineandtrytorun,forexample,atcshscript
frombash,theshellmaygenerateerrormessagesorthescript
maynotrunproperly.
#BeginsaComment
Commentsmakeshellscriptsandallcodeeasiertoreadand
maintainbyyouandothers.Ifapoundsign(#)inthefirst
characterpositionofthefirstlineofascriptisnotimmediately
followedbyanexclamationpoint(!)orifapoundsignoccursin
anyotherlocationinascript,theshellinterpretsitasthe
beginningofacomment.Theshellthenignoreseverything
betweenthepoundsignandtheendoftheline(thenext
NEWLINEcharacter).
RunningaShellScript
forkandexecsystemcalls
Acommandonthecommandlinecausestheshelltoforka
newprocess,creatingaduplicateoftheshellprocess(a
subshell).Thenewprocessattemptstoexec(execute)the
command.Likefork,theexecroutineisexecutedbythe
operatingsystem(asystemcall).Ifthecommandisabinary
executableprogram,suchasacompiledCprogram,exec
succeedsandthesystemoverlaysthenewlycreatedsubshell
withtheexecutableprogram.Ifthecommandisashellscript,
execfails.Whenexecfails,thecommandisassumedtobea
shellscript,andthesubshellrunsthecommandsinthescript.
Unlikealoginshell,whichexpectsinputfromthecommand
line,thesub-shelltakesitsinputfromafile:theshellscript.
Asdiscussedearlier,ifyouhaveashellscriptinafilethatyou
donothaveexecutepermissionfor,youcanrunthecommands
inthescriptbyusingabashcommandtoexecashelltorunthe
scriptdirectly.Inthefollowingexample,bashcreatesanewshell
thattakesitsinputfromthefilenamedwhoson:
$bashwhoson
Becausethebashcommandexpectstoreadafilecontaining
commands,youdonotneedexecutepermissionforwhoson.
(Youdoneedreadpermission.)Eventhoughbashreadsand
executesthecommandsinwhoson,standardinput,standard
output,andstandarderrorremainconnectedtotheterminal.
Althoughyoucanusebashtoexecuteashellscript,this
techniquecausesthescripttorunmoreslowlythangiving
yourselfexecutepermissionanddirectlyinvokingthescript.
Userstypicallyprefertomakethefileexecutableandrunthe
scriptbytypingitsnameonthecommandline.Itisalsoeasier
totypethename,andthispracticeisconsistentwiththeway
otherkindsofprogramsareinvoked(soyoudonotneedto
knowwhetheryouarerunningashellscriptoranotherkindof
program).However,ifbashisnotyourinteractiveshellorifyou
wanttoseehowthescriptrunswithdifferentshells,youmay
wanttorunascriptasanargumenttobashortcsh.
Caution:shdoesnotcalltheoriginal
BourneShell
TheoriginalBourneShellwasinvokedwiththe
commandsh.Althoughyoucancallbashwithansh
command,itisnottheoriginalBourneShell.Thesh
command(/bin/sh)isasymboliclinkto
/bin/bash,soitissimplyanothernameforthe
bashcommand.Whenyoucallbashusingthe
commandsh,bashtriestomimicthebehaviorof
theoriginalBourneShellascloselyaspossible.It
doesnotalwayssucceed.
SeparatingandGroupingCommands
Whetheryougivetheshellcommandsinteractivelyorwritea
shellscript,youmustseparatecommandsfromoneanother.
Thissectionreviewsthewaystoseparatecommandsthatwere
coveredinChapter7andintroducesafewnewones.
;andNEWLINESeparateCommands
TheNEWLINEcharacterisauniquecommandseparatorbecause
itinitiatesexecutionofthecommandprecedingit.Youhave
seenthisthroughoutthisbookeachtimeyoupresstheRETURN
keyattheendofacommandline.
Thesemicolon(;)isacommandseparatorthatdoesnotinitiate
executionofacommandanddoesnotchangeanyaspectof
howthecommandfunctions.Youcanexecuteaseriesof
commandssequentiallybyenteringthemonasinglecommand
lineandseparatingeachfromthenextwithasemicolon(;).You
initiateexecutionofthesequenceofcommandsbypressing
RETURN:
$x;y;z
Ifx,y,andzarecommands,theprecedingcommandline
yieldsthesameresultsasthenextthreecommands.The
differenceisthatinthenextexampletheshellissuesaprompt
aftereachofthecommands(x,y,andz)finishesexecuting,
whereastheprecedingcommandlinecausestheshelltoissuea
promptonlyafterziscomplete:
$x
$y
$z
Whitespace
Althoughthewhitespacearoundthesemicolonsintheearlier
examplemakesthecommandlineeasiertoread,itisnot
necessary.Noneofthecommandseparatorsneedstobe
surroundedbySPACEsorTABs.
\ContinuesaCommand
Whenyouenteralongcommandlineandthecursorreaches
therightsideofthescreen,youcanuseabackslash(\)
charactertocontinuethecommandonthenextline.The
backslashquotes,orescapes,theNEWLINEcharacterthat
followsitsothattheshelldoesnottreattheNEWLINEasa
commandterminator.Enclosingabackslashwithinsingle
quotationmarksturnsoffthepowerofabackslashtoquote
specialcharacterssuchasNEWLINE.Enclosingabackslash
withindoublequotationmarkshasnoeffectonthepowerofthe
backslash.
Althoughyoucanbreakalineinthemiddleofaword(token),
itistypicallyeasiertobreakalinejustbeforeorafter
whitespace.
Optional
YoucanenteraRETURNinthemiddleofaquotedstringonacommandline
withoutusingabackslash.TheNEWLINE(RETURN)thatyouenterwillthenbe
partofthestring:
$echo"Pleaseenterthethreevalues
>requiredtocompletethetransaction."
Pleaseenterthethreevalues
requiredtocompletethetransaction.
Inthethreeexamplesinthissection,theshelldoesnotinterpretRETURNasa
commandterminatorbecauseitoccurswithinaquotedstring.The>isa
secondarypromptindicatingthattheshelliswaitingforyoutocontinuethe
unfinishedcommand.Inthenextexample,thefirstRETURNisquoted(escaped)
sotheshelltreatsitasaseparatoranddoesnotinterpretitliterally.
$echo"Pleaseenterthethreevalues\
>requiredtocompletethetransaction."
Pleaseenterthethreevaluesrequiredtocompletethetransaction.
Singlequotationmarkscausetheshelltointerpretabackslashliterally:
$echo'Pleaseenterthethreevalues\
>requiredtocompletethetransaction.'
Pleaseenterthethreevalues\
requiredtocompletethetransaction.
|and&SeparateCommandsandDoSomethingElse
Thepipesymbol(|)andthebackgroundtasksymbol(&)are
alsocommandseparators.Theydonotstartexecutionofa
commandbutdochangesomeaspectofhowthecommand
functions.Thepipesymbolaltersthesourceofstandardinput
orthedestinationofstandardoutput.Thebackgroundtask
symbolcausestheshelltoexecutethetaskinthebackground
soyougetapromptimmediatelyandcancontinueworkingon
othertasks.
Eachofthefollowingcommandlinesinitiatesasinglejob
comprisingthreetasks:
$x|y|z
$ls-l|greptmp|less
Inthefirstjob,theshellredirectsstandardoutputoftaskxto
standardinputoftaskyandredirectsy'sstandardoutputtoz's
standardinput.Becauseitrunstheentirejobintheforeground,
theshelldoesnotdisplayapromptuntiltaskzrunsto
completion:Taskzdoesnotfinishuntiltaskyfinishes,andtask
ydoesnotfinishuntiltaskxfinishes.Inthesecondjob,taskx
isanlslcommand,taskyisgreptmp,andtaskzisthepager
less.Theshelldisplaysalong(wide)listingofthefilesinthe
workingdirectorythatcontainthestringtmp,pipedthrough
less.
Thenextcommandlineexecutestasksdandeinthe
backgroundandtaskfintheforeground:
$d&e&f
[1]14271
[2]14272
Theshelldisplaysthejobnumberbetweenbracketsandthe
PID(processidentification)numberforeachprocessrunningin
thebackground.Yougetapromptassoonasffinishes,which
maybebeforedorefinishes.
Beforedisplayingapromptforanewcommand,theshell
checkswhetheranybackgroundjobshavecompleted.Foreach
jobthathascompleted,theshelldisplaysitsjobnumber,the
wordDone,andthecommandlinethatinvokedthejob;then
theshelldisplaysaprompt.Whenthejobnumbersarelisted,
thenumberofthelastjobstartedisfollowedbya+character
andthejobnumberofthepreviousjobisfollowedbya
character.AnyotherjobslistedshowaSPACEcharacter.After
runningthelastcommand,theshelldisplaysthefollowing
beforeissuingaprompt:
[1]-Doned
[2]+Donee
Thenextcommandlineexecutesallthreetasksasbackground
jobs.Yougetashellpromptimmediately:
$d&e&f&
[1]14290
[2]14291
[3]14292
Youcanusepipestosendtheoutputfromonetasktothenext
taskandanampersand(&)toruntheentirejobasa
backgroundtask.Againthepromptcomesbackimmediately.
Theshellregardsthecommandsjoinedbyapipeasbeinga
singlejob.Thatis,ittreatsallpipesassinglejobs,nomatter
howmanytasksareconnectedwiththepipe(|)symbolorhow
complextheyare.TheBourneAgainShellshowsonlyone
processplacedinthebackground:
$d|e|f&
[1]14295
Optional:()GroupsCommands
Youcanuseparenthesestogroupcommands.Theshellcreatesacopyofitself,
calledasubshell,foreachgroup.Ittreatseachgroupofcommandsasajoband
createsanewprocesstoexecuteeachcommand(referto"ProcessStructure"on
page300formoreinformationoncreatingsubshells).Eachsubshell(job)hasits
ownenvironment,meaningthatithasitsownsetofvariableswithvaluesthat
candifferfromthoseofothersubshells.
Thefollowingcommandlineexecutescommandsaandbsequentiallyinthe
backgroundwhileexecutingcinthebackground.Theshellpromptreturns
immediately.
$(a;b)&c&
[1]15520
[2]15521
Theprecedingexamplediffersfromtheearlierexampled&e&f&inthattasks
aandbareinitiatedsequentially,notconcurrently.
Similarlythefollowingcommandlineexecutesaandbsequentiallyinthe
backgroundand,atthesametime,executescanddsequentiallyinthe
background.Thesubshellrunningaandbandthesubshellrunningcanddrun
concurrently.Thepromptreturnsimmediately.
$(a;b)&(c;d)&
[1]15528
[2]15529
Thenextscriptcopiesonedirectorytoanother.Thesecondpairofparentheses
createsasubshelltorunthecommandsfollowingthepipe.Becauseofthese
parentheses,theoutputofthefirsttarcommandisavailableforthesecondtar
commanddespitetheinterveningcdcommand.Withouttheparentheses,the
outputofthefirsttarcommandwouldbesenttocdandlostbecausecddoesnot
processinputfromstandardinput.Theshellvariables$1and$2representthe
firstandsecondcommandlinearguments(page921),respectively.Thefirstpair
ofparentheses,whichcreatesasubshelltorunthefirsttwocommands,allows
userstocallcpdirwithrelativepathnames.Withoutthemthefirstcdcommand
wouldchangetheworkingdirectoryofthescript(andconsequentlytheworking
directoryofthesecondcdcommand).Withthemonlytheworkingdirectoryof
thesubshellischanged.
$catcpdir
(cd$1;tar-cf-.)|(cd$2;tar-xvf-)
$cpdir/home/alex/sources/home/alex/memo/biblio
Thecpdircommandlinecopiesthefilesanddirectoriesinthe
/home/alex/sourcesdirectorytothedirectorynamed
/home/alex/memo/biblio.Thisshellscriptisalmostthesameasusingcp
withtheroption.Refertothecpandtarmanpagesformoreinformation.
JobControl
Ajobisacommandpipeline.Yourunasimplejobwhenever
yougivetheshellacommand.Forexample,typedateonthe
commandlineandpressRETURN:Youhaverunajob.Youcan
alsocreateseveraljobswithmultiplecommandsonasingle
commandline:
$find.-print|sort|lpr&grep-lalex/tmp/*>alexfiles&
[1]18839
[2]18876
Theportionofthecommandlineuptothefirst&isonejob
consistingofthreeprocessesconnectedbypipes:find,sort(page
133),andlpr(page131).Thesecondjobisasingleprocess
runninggrep.Bothjobshavebeenputintothebackgroundby
thetrailing&characters,sobashdoesnotwaitforthemto
completebeforedisplayingaprompt.
Usingjobcontrolyoucanmovecommandsfromtheforeground
tothebackground(andviceversa),stopcommands
temporarily,andlistallthecommandsthatarerunninginthe
backgroundorstopped.
jobs:ListsJobs
Thejobsbuiltinlistsallbackgroundjobs.Thefollowingsequence
demonstrateswhathappenswhenyougiveajobscommand.
Herethesleepcommandrunsinthebackgroundandcreatesa
backgroundjobthatjobsreportson:
$sleep60&
[1]7809
$jobs
[1]+Runningsleep60&
fg:BringsaJobtotheForeground
Theshellassignsjobnumberstocommandsyouruninthe
background(page278).Severaljobsarestartedinthe
backgroundinthenextexample.Foreachjobtheshellliststhe
jobnumberandPIDnumberimmediately,justbeforeitissuesa
prompt.
$xclock&
[1]1246
$date&
[2]1247
$SunDec411:44:40PST2005
[2]+Donedate
$find/usr-nameace-print>findout&
[2]1269
$jobs
[1]-Runningxclock&
[2]+Runningfind/usr-nameace-print>findout&
Jobnumbers,whicharediscardedwhenajobisfinished,can
bereused.Whenyoustartorputajobinthebackground,the
shellassignsajobnumberthatisonemorethanthehighest
jobnumberinuse.
Intheprecedingexample,thejobscommandliststhefirstjob,
xclock,asjob1.Thedatecommanddoesnotappearinthejobs
listbecauseitfinishedbeforejobswasrun.Becausethedate
commandwascompletedbeforefindwasrun,thefindcommand
becamejob2.
Tomoveabackgroundjobintotheforeground,usethefg
builtinfollowedbythejobnumber.Alternatively,youcangivea
percentsign(%)followedbythejobnumberasacommand.
Eitherofthefollowingcommandsmovesjob2intothe
foreground:
$fg2
or
$%2
Youcanalsorefertoajobbyfollowingthepercentsignwitha
stringthatuniquelyidentifiesthebeginningofthecommand
lineusedtostartthejob.Insteadoftheprecedingcommand,
youcouldhaveusedeitherfg%findorfg%fbecauseboth
uniquelyidentifyjob2.Ifyoufollowthepercentsignwitha
questionmarkandastring,thestringcanmatchanypartof
thecommandline.Intheprecedingexample,fg%?acealso
bringsjob2intotheforeground.
Oftenthejobyouwishtobringintotheforegroundistheonly
jobrunninginthebackgroundoristhejobthatjobslistswitha
plus(+).Inthesecasesyoucanusefgwithoutanargument.
bg:SendsaJobtotheBackground
Tomovetheforegroundjobtothebackground,youmustfirst
suspend(temporarilystop)thejobbypressingthesuspendkey
(usuallyCONTROL-Z).Pressingthesuspendkeyimmediately
suspendsthejobintheforeground.Youcanthenusethebg
builtintoresumeexecutionofthejobinthebackground.
$bg
Ifabackgroundjobattemptstoreadfromtheterminal,the
shellstopsitandnotifiesyouthatthejobhasbeenstoppedand
iswaitingforinput.Youmustthenmovethejobintothe
foregroundsothatitcanreadfromtheterminal.Theshell
displaysthecommandlinewhenitmovesthejobintothe
foreground.
$(sleep5;cat>mytext)&
[1]1343
$date
SunDec411:58:20PST2005
[1]+Stopped(sleep5;cat>mytext)
$fg
(sleep5;cat>mytext)
Remembertoletthecatout!
CONTROL-D
$
Intheprecedingexample,theshelldisplaysthejobnumber
andPIDnumberofthebackgroundjobassoonasitstarts,
followedbyaprompt.Demonstratingthatyoucangivea
commandatthispoint,theusergivesthecommanddateandits
outputappearsonthescreen.Theshellwaitsuntiljustbeforeit
issuesaprompt(afterdatehasfinished)tonotifyyouthatjob1
isstopped.Whenyougiveanfgcommand,theshellputsthe
jobintheforegroundandyoucanentertheinputthatthe
commandiswaitingfor.Inthiscasetheinputneedstobe
terminatedwithaCONTROL-DtosignifyEOF(endoffile).The
shellthendisplaysanotherprompt.
Theshellkeepsyouinformedaboutchangesinthestatusofa
job,notifyingyouwhenabackgroundjobstarts,completes,or
isstopped,perhapswaitingforinputfromtheterminal.The
shellalsoletsyouknowwhenaforegroundjobissuspended.
Becausenoticesaboutajobbeingruninthebackgroundcan
disruptyourwork,theshelldelaysdisplayingthesenoticesuntil
justbeforeitdisplaysaprompt.Youcansetnotify(page327)
tomaketheshelldisplaythesenoticeswithoutdelay.
Ifyoutrytoexitfromashellwhilejobsarestopped,theshell
issuesawarninganddoesnotallowyoutoexit.Ifyouthenuse
jobstoreviewthelistofjobsoryouimmediatelytrytoleavethe
shellagain,theshellallowsyoutoleaveandterminatesthe
stoppedjobs.Jobsthatarerunning(notstopped)inthe
backgroundcontinuetorun.Inthefollowingexample,find(job
1)continuestorunafterthesecondexitterminatestheshell,
butcat(job2)isterminated:
$find/-size+100k>$HOME/bigfiles2>&1&
[1]1426
$cat>mytest&
[2]1428
[2]+Stoppedcat>mytest
$exit
exit
Therearestoppedjobs.
$exit
exit
login:
ManipulatingtheDirectoryStack
TheBourneAgainShellallowsyoutostorealistofdirectories
youareworkingwith,enablingyoutomoveeasilyamongthem.
Thislistisreferredtoasastack.Itisanalogoustoastackof
dinnerplates:Youtypicallyaddplatestoandremoveplates
fromthetopofthestack,creatingalast-infirst-out,(LIFO)
stack.
dirs:DisplaystheStack
Thedirsbuiltindisplaysthecontentsofthedirectorystack.If
youcalldirswhenthedirectorystackisempty,itdisplaysthe
nameoftheworkingdirectory:
$dirs
~/literature
Thedirsbuiltinusesatilde(~)torepresentthenameofthe
homedirectory.Theexamplesinthenextseveralsections
assumethatyouarereferringtothedirectorystructureshown
inFigure9-2.
Figure9-2.Thedirectorystructureinthe
examples
pushd:PushesaDirectoryontheStack
Tochangedirectoriesandatthesametimeaddanewdirectory
tothetopofthestack,usethepushd(pushdirectory)builtin.In
additiontochangingdirectories,thepushdbuiltindisplaysthe
contentsofthestack.Thefollowingexampleisillustratedin
Figure9-3:
$pushd../demo
~/demo~/literature
$pwd
/home/sam/demo
$pushd../names
~/names~/demo~/literature
$pwd
/home/sam/names
Figure9-3.Creatingadirectorystack
Usingpushdinthisway,youcaneasilymovebackandforth
betweentwodirectories.Youcanalsousecdtochangetothe
previousdirectory,whetherornotyouhaveexplicitlycreateda
directorystack.Toaccessanotherdirectoryinthestack,call
pushdwithanumericargumentprecededbyaplussign.The
directoriesinthestackarenumberedstartingwiththetop
directory,whichisnumber0.Thefollowingpushdcommand
continueswiththepreviousexample,changingtheworking
directorytoliteratureandmovingliteraturetothetopofthe
stack:
$pushd+2
~/literature~/demo~/names
$pwd
/home/sam/literature
popd:PopsaDirectoryOfftheStack
Toremoveadirectoryfromthestack,usethepopd(pop
directory)builtin.AsthefollowingexampleandFigure9-5
show,popdusedwithoutanargumentremovesthetopdirectory
fromthestackandchangestheworkingdirectorytothenew
topdirectory:
$dirs
~/literature~/demo~/names
$popd
~/demo~/names
$pwd
/home/sam/demo
Figure9-5.Usingpopdtoremoveadirectoryfrom
thestack
Toremoveadirectoryotherthanthetoponefromthestack,
usepopdwithanumericargumentprecededbyaplussign.The
followingexampleremovesdirectorynumber1,demo:
$dirs
~/literature~/demo~/names
$popd+1
~/literature~/names
Removingadirectoryotherthandirectorynumber0doesnot
changetheworkingdirectory.
ParametersandVariables
Variables
Withinashell,ashellparameterisassociatedwithavaluethat
isaccessibletotheuser.Thereareseveralkindsofshell
parameters.Parameterswhosenamesconsistofletters,digits,
andunderscoresareoftenreferredtoasshellvariables,or
simplyvariables.Avariablenamemuststartwithaletteror
underscore,notwithanumber.ThusA76,MY_CAT,and
___X___arevalidvariablenames,whereas69TH_STREET
(startswithadigit)andMY-NAME(containsahyphen)arenot.
User-createdvariables
Shellvariablesthatyounameandassignvaluestoareuser-
createdvariables.Youcanchangethevaluesofuser-created
variablesatanytime,oryoucanmakethemreadonlysothat
theirvaluescannotbechanged.Youcanalsomakeuser-
createdvariablesglobal.Aglobalvariable(alsocalledan
environmentvariable)isavailabletoallshellsandother
programsyouforkfromtheoriginalshell.Onenaming
conventionistouseonlyuppercaselettersforglobalvariables
andtousemixed-caseorlowercaselettersforothervariables.
Referto"LocalityofVariables"onpage916formore
informationonglobalvariables.
ToassignavaluetoavariableintheBourneAgainShell,use
thefollowingsyntax:
VARIABLE=value
Therecanbenowhitespaceoneithersideoftheequalsign
(=).Anexampleassignmentfollows:
$myvar=abc
TheBourneAgainShellpermitsyoutoputvariableassignments
onacommandline.Theseassignmentsarelocaltothe
commandshellthatis,theyapplytothecommandonly.The
my_scriptshellscriptdisplaysthevalueofTEMPDIR.The
followingcommandrunsmy_scriptwithTEMPDIRsetto
/home/sam/temp.Theechobuiltinshowsthattheinteractive
shellhasnovalueforTEMPDIRafterrunningmy_script.If
TEMPDIRhadbeensetintheinteractiveshell,running
my_scriptinthismannerwouldhavehadnoeffectonits
value.
$catmy_script
echo$TEMPDIR
$TEMPDIR=/home/sam/tempmy_script
/home/sam/temp
$echo$TEMPDIR
$
Keywordvariables
Keywordshellvariables(orsimplykeywordvariables)have
specialmeaningtotheshellandusuallyhaveshort,mnemonic
names.Whenyoustartashell(byloggingin,forexample),the
shellinheritsseveralkeywordvariablesfromtheenvironment.
AmongthesevariablesareHOME,whichidentifiesyourhome
directory,andPATH,whichdetermineswhichdirectoriesthe
shellsearchesandinwhatordertolocatecommandsthatyou
givetheshell.Theshellcreatesandinitializes(withdefault
values)otherkeywordvariableswhenyoustartit.Stillother
variablesdonotexistuntilyousetthem.
Youcanchangethevaluesofmostofthekeywordshell
variablesatanytimebutitisusuallynotnecessarytochange
thevaluesofkeywordvariablesinitializedinthe/etc/profile
or/etc/csh.cshrcsystemwidestartupfiles.Ifyouneedto
changethevalueofabashkeywordvariable,dosoinoneof
yourstartupfiles(page267).Justasyoucanmakeuser-
createdvariablesglobal,soyoucanmakekeywordvariables
global;thisisusuallydoneautomaticallyinthestartupfiles.
Youcanalsomakeakeywordvariablereadonly.
Positionalandspecialparameters
Thenamesofpositionalandspecialparametersdonot
resemblevariablenames.Mostoftheseparametershaveone-
characternames(forexample,1,?,and#)andarereferenced
(asareallvariables)byprecedingthenamewithadollarsign
($1,$?,and$#).Thevaluesoftheseparametersreflect
differentaspectsofyourongoinginteractionwiththeshell.
Wheneveryougiveacommand,eachargumentonthe
commandlinebecomesthevalueofapositionalparameter.
Positionalparameters(page920)enableyoutoaccess
commandlinearguments,acapabilitythatyouwilloften
requirewhenyouwriteshellscripts.Thesetbuiltin(page924)
enablesyoutoassignvaluestopositionalparameters.
Otherfrequentlyneededshellscriptvalues,suchasthename
ofthelastcommandexecuted,thenumberofcommandline
arguments,andthestatusofthemostrecentlyexecuted
command,areavailableasspecialparameters.Youcannot
assignvaluestospecialparameters.
User-CreatedVariables
Thefirstlineinthefollowingexampledeclaresthevariable
namedpersonandinitializesitwiththevaluealex:
$person=alex
$echoperson
person
$echo$person
alex
Becausetheechobuiltincopiesitsargumentstostandard
output,youcanuseittodisplaythevaluesofvariables.The
secondlineoftheprecedingexampleshowsthatpersondoes
notrepresentalex.Instead,thestringpersonisechoedas
person.Theshellsubstitutesthevalueofavariableonlywhen
youprecedethenameofthevariablewithadollarsign($).The
commandecho$persondisplaysthevalueofthevariable
person;itdoesnotdisplay$personbecausetheshelldoes
notpass$persontoechoasanargument.Becauseofthe
leading$,theshellrecognizesthat$personisthenameofa
variable,substitutesthevalueofthevariable,andpassesthat
valuetoecho.Theechobuiltindisplaysthevalueofthe
variablenotitsnameneverknowingthatyoucalleditwitha
variable.
Quotingthe$
Youcanpreventtheshellfromsubstitutingthevalueofa
variablebyquotingtheleading$.Doublequotationmarksdo
notpreventthesubstitution;singlequotationmarksora
backslash(\)do.
$echo$person
alex
$echo"$person"
alex
$echo'$person'
$person
$echo\$person
$person
SPACEs
Becausetheydonotpreventvariablesubstitutionbutdoturn
offthespecialmeaningsofmostothercharacters,double
quotationmarksareusefulwhenyouassignvaluestovariables
andwhenyouusethosevalues.Toassignavaluethatcontains
SPACEsorTABstoavariable,usedoublequotationmarks
aroundthevalue.Althoughdoublequotationmarksarenot
requiredinallcases,usingthemisagoodhabit.
$person="alexandjenny"
$echo$person
alexandjenny
$person=alexandjenny
bash:and:commandnotfound
WhenyoureferenceavariablethatcontainsTABsormultiple
adjacentSPACEs,youneedtousequotationmarkstopreserve
thespacing.Ifyoudonotquotethevariable,theshellcollapses
eachstringofblankcharactersintoasingleSPACEbefore
passingthevariabletotheutility:
$person="alexandjenny"
$echo$person
alexandjenny
$echo"$person"
alexandjenny
Whenyouexecuteacommandwithavariableasanargument,
theshellreplacesthenameofthevariablewiththevalueofthe
variableandpassesthatvaluetotheprogrambeingexecuted.
Ifthevalueofthevariablecontainsaspecialcharacter,suchas
*or?,theshellmayexpandthatvariable.
Pathnameexpansioninassignments
Thefirstlineinthefollowingsequenceofcommandsassigns
thestringalex*tothevariablememo.TheBourneAgainShell
doesnotexpandthestringbecausebashdoesnotperform
pathnameexpansion(page221)whenassigningavaluetoa
variable.Allshellsprocessacommandlineinaspecificorder.
Withinthisorderbashexpandsvariablesbeforeitinterprets
commands.Inthefollowingechocommandline,thedouble
quotationmarksquotetheasterisk(*)intheexpandedvalueof
$memoandpreventbashfromperformingpathnameexpansion
ontheexpandedmemovariablebeforepassingitsvaluetothe
echocommand:
$memo=alex*
$echo"$memo"
alex*
Allshellsinterpretspecialcharactersasspecialwhenyou
referenceavariablethatcontainsanunquotedspecial
character.Inthefollowingexample,theshellexpandsthevalue
ofthememovariablebecauseitisnotquoted:
$ls
alex.report
alex.summary
$echo$memo
alex.reportalex.summary
Heretheshellexpandsthe$memovariabletoalex*,expands
alex*toalex.reportandalex.summary,andpassesthese
twovaluestoecho.
Optional
Braces
The$VARIABLEsyntaxisaspecialcaseofthemoregeneral
syntax${VARIABLE},inwhichthevariablenameisenclosed
by${}.Thebracesinsulatethevariablename.Bracesare
necessarywhencatenatingavariablevaluewithastring:
$PREF=counter
$WAY=$PREFclockwise
$FAKE=$PREFfeit
$echo$WAY$FAKE
$
Theprecedingexampledoesnotworkasplanned.Onlyablank
lineisoutputbecause,althoughthesymbolsPREFclockwise
andPREFfeitarevalidvariablenames,theyarenotset.By
defaultbashevaluatesanunsetvariableasanempty(null)
stringanddisplaysthisvalue.Toachievetheintentofthese
statements,refertothePREFvariableusingbraces:
$PREF=counter
$WAY=${PREF}clockwise
$FAKE=${PREF}feit
$echo$WAY$FAKE
counterclockwisecounterfeit
TheBourneAgainShellreferstotheargumentsonits
commandlinebyposition,usingthespecialvariables$1,$2,
$3,andsoforthupto$9.Ifyouwishtorefertoarguments
pasttheninthargument,youmustusebraces:${10}.The
nameofthecommandisheldin$0(page921).
unset:RemovesaVariable
Unlessyouremoveavariable,itexistsaslongastheshellin
whichitwascreatedexists.Toremovethevalueofavariable
butnotthevariableitself,setthevaluetonull:
$person=
$echo$person
$
Youcanremoveavariablewiththeunsetbuiltin.Toremovethe
variableperson,givethefollowingcommand:
$unsetperson
VariableAttributes
Thissectiondiscussesattributesandexplainshowtoassign
themtovariables.
readonly:MakestheValueofaVariablePermanent
Youcanusethereadonlybuiltintoensurethatthevalueofa
variablecannotbechanged.Thenextexampledeclaresthe
variablepersontobereadonly.Youmustassignavaluetoa
variablebeforeyoudeclareittobereadonly;youcannot
changeitsvalueafterthedeclaration.Whenyouattemptto
unsetorchangethevalueofareadonlyvariable,theshell
displaysanerrormessage:
$person=jenny
$echo$person
jenny
$readonlyperson
$person=helen
bash:person:readonlyvariable
Ifyouusethereadonlybuiltinwithoutanargument,itdisplaysa
listofallreadonlyshellvariables.Thislistincludeskeyword
variablesthatareautomaticallysetasreadonlyaswellas
keywordoruser-createdvariablesthatyouhavedeclaredas
readonly.See"Listingvariableattributes"onpage290foran
example(readonlyanddeclarerproducethesameoutput).
declareandtypeset:AssignAttributestoVariables
Thedeclareandtypesetbuiltins(twonamesforthesame
command)setattributesandvaluesforshellvariables.Table9-
3listsfiveoftheseattributes.
Table9-3.Variableattributes(typesetordeclare)
Attribute Meaning
-a Declaresavariableasanarray(page914)
-f Declaresavariabletobeafunctionname(page321)
-i Declaresavariabletobeoftypeinteger(page291)
-r Makesavariablereadonly;alsoreadonly(page289)
-x Exportsavariable(makesitglobal);alsoexport(page916)
Thefollowingcommandsdeclareseveralvariablesandsetsome
attributes.Thefirstlinedeclaresperson1andassignsita
valueofalex.Thiscommandhasthesameeffectwithor
withouttheworddeclare.
$declareperson1=alex
$declare-rperson2=jenny
$declare-rxperson3=helen
$declare-xperson4
Thereadonlyandexportbuiltinsaresynonymsforthecommands
declareranddeclarex,respectively.Itislegaltodeclarea
variablewithoutassigningavaluetoit,asthepreceding
declarationofthevariableperson4illustrates.Thisdeclaration
makesperson4availabletoallsubshells(makesitglobal).
Untilanassignmentismadetothevariable,ithasanullvalue.
Youcanlisttheoptionstodeclareseparatelyinanyorder.The
followingisequivalenttotheprecedingdeclarationofperson3:
$declare-x-rperson3=helen
Usethe+characterinplaceofwhenyouwanttoremovean
attributefromavariable.Youcannotremoveareadonly
attributehowever.Afterthefollowingcommandisgiven,the
variableperson3isnolongerexportedbutitisstillreadonly.
$declare+xperson3
Youcanalsousetypesetinsteadofdeclare.
Listingvariableattributes
Withoutanyargumentsoroptions,thedeclarebuiltinlistsall
shellvariables.Thesamelistisoutputwhenyourunset(page
924)withoutanyarguments.
Ifyouuseadeclarebuiltinwithoptionsbutnovariablenamesas
arguments,thecommandlistsallshellvariablesthathavethe
indicatedattributesset.Forexample,theoptionrwithdeclare
givesalistofallreadonlyshellvariables.Thislististhesame
asthatproducedbyareadonlycommandwithoutany
arguments.Afterthedeclarationsintheprecedingexample
havebeengiven,theresultsareasfollows:
$declare-r
declare-arBASH_VERSINFO='([0]="2"[1]="05b"[2]="0"[3]="1"...)'
declare-irEUID="500"
declare-irPPID="936"
declare-rSHELLOPTS="braceexpand:emacs:hashall:histexpand:history:..."
declare-irUID="500"
declare-rperson2="jenny"
declare-rxperson3="helen"
Thefirstfiveentriesarekeywordvariablesthatare
automaticallydeclaredasread-only.Someofthesevariables
arestoredasintegers(i).Theaoptionindicatesthat
BASH_VERSINFOisanarrayvariable;thevalueofeach
elementofthearrayislistedtotherightofanequalsign.
Integer
Bydefaultthevaluesofvariablesarestoredasstrings.When
youperformarithmeticonastringvariable,theshellconverts
thevariableintoanumber,manipulatesit,andthenconvertsit
backtoastring.Avariablewiththeintegerattributeisstored
asaninteger.Assigntheintegerattributeasfollows:
$typeset-iCOUNT
KeywordVariables
Keywordvariableseitherareinheritedoraredeclaredand
initializedbytheshellwhenitstarts.Youcanassignvaluesto
thesevariablesfromthecommandlineorfromastartupfile.
Typicallyyouwantthesevariablestoapplytoallsubshellsyou
startaswellastoyourloginshell.Forthosevariablesnot
automaticallyexportedbytheshell,youmustuseexport(page
916)tomakethemavailabletochildshells.
HOME:YourHomeDirectory
Bydefaultyourhomedirectoryisyourworkingdirectorywhen
youlogin.Yourhomedirectoryisdeterminedwhenyou
establishyouraccount;itsnameisstoredinthe/etc/passwd
file.
$grepsam/etc/passwd
sam:x:501:501:SamS.x301:/home/sam:/bin/bash
Whenyoulogin,theshellinheritsthepathnameofyourhome
directoryandassignsittothevariableHOME.Whenyougivea
cdcommandwithoutanargument,cdmakesthedirectory
whosenameisstoredinHOMEtheworkingdirectory:
$pwd
/home/alex/laptop
$echo$HOME
/home/alex
$cd
$pwd
/home/alex
ThisexampleshowsthevalueoftheHOMEvariableandthe
effectofthecdbuiltin.Afteryouexecutecdwithoutan
argument,thepathnameoftheworkingdirectoryisthesame
asthevalueofHOME:yourhomedirectory.
Tilde(~)
TheshellusesthevalueofHOMEtoexpandpathnamesthat
usetheshorthandtilde(~)notation(page171)todenotea
user'shomedirectory.Thefollowingexampleusesechoto
displaythevalueofthisshortcutandthenuseslstolistthefiles
inAlex'slaptopdirectory,whichisasubdirectoryofhishome
directory:
$echo~
/home/alex
$ls~/laptop
testercountlineup
PATH:WheretheShellLooksforPrograms
Whenyougivetheshellanabsoluteorrelativepathname
ratherthanasimplefilenameasacommand,itlooksinthe
specifieddirectoryforanexecutablefilewiththespecified
filename.Ifthefilewiththepathnameyouspecifieddoesnot
exist,theshellreportscommandnotfound.Ifthefileexists
asspecifiedbutyoudonothaveexecutepermissionforit,orin
thecaseofashellscriptyoudonothavereadandexecute
permissionforit,theshellreportsPermissiondenied.
Ifyougiveasimplefilenameasacommand,theshellsearches
throughcertaindirectoriesfortheprogramyouwantto
execute.Itlooksinseveraldirectoriesforafilethathasthe
samenameasthecommandandthatyouhaveexecute
permissionfor(acompiledprogram)orreadandexecute
permissionfor(ashellscript).ThePATHshellvariablecontrols
thissearch.
ThedefaultvalueofPATHisdeterminedwhenbashiscompiled.
Itisnotsetinastartupfile,althoughitmaybemodifiedthere.
Normallythedefaultspecifiesthattheshellsearchseveral
systemdirectoriesusedtoholdcommoncommandsandthen
searchtheworkingdirectory.Thesesystemdirectoriesinclude
/binand/usr/binandotherdirectoriesappropriatetothe
localsystem.Whenyougiveacommand,iftheshelldoesnot
findtheexecutableand,inthecaseofashellscript,readablefile
namedbythecommandinanyofthedirectorieslistedin
PATH,theshellgeneratesoneoftheaforementionederror
messages.
Workingdirectory
ThePATHvariablespecifiesthedirectoriesintheorderthe
shellshouldsearchthem.Eachdirectorymustbeseparated
fromthenextbyacolon.ThefollowingcommandsetsPATHso
thatasearchforanexecutablefilestartswiththe
/usr/local/bindirec-tory.Ifitdoesnotfindthefileinthis
directory,theshellfirstlooksin/bin,andthenin/usr/bin.If
thesearchfailsinthosedirectories,theshelllooksinthebin
directory,asubdirectoryoftheuser'shomedirectory.Finally
theshelllooksintheworkingdirectory.ExportingPATHmakes
itsvalueaccessibletosubshells:
$exportPATH=/usr/local/bin:/bin:/usr/bin:~/bin:
Anullvalueinthestringindicatestheworkingdirectory.Inthe
precedingexample,anullvalue(nothingbetweenthecolonand
theendoftheline)appearsasthelastelementofthestring.
Theworkingdirectoryisrepresentedbyaleadingcolon(not
recommended;seethefollowingsecuritytip),atrailingcolon
(asintheexample),ortwocolonsnexttoeachotheranywhere
inthestring.Youcanalsorepresenttheworkingdirectory
explicitlywithaperiod(.).
BecauseLinuxstoresmanyexecutablefilesindirectories
namedbin(binary),userstypicallyputtheirownexecutable
filesintheirown~/bindirectories.Ifyouputyourownbin
directoryattheendofyourPATH,asinthepreceding
example,theshelllooksthereforanycommandsthatitcannot
findindirectorieslistedearlierinPATH.
Security:PATHandsecurity
DonotputtheworkingdirectoryfirstinPATHwhen
securityisaconcern.Ifyouarerunningas
Superuser,youshouldneverputtheworking
directoryfirstinPATH.ItiscommonforSuperuser
PATHtoomittheworkingdirectoryentirely.Youcan
alwaysexecuteafileintheworkingdirectoryby
prepending./tothename:./ls.
PuttingtheworkingdirectoryfirstinPATHcan
createasecurityhole.Mostpeopletypelsasthe
firstcommandwhenenteringadirectory.Ifthe
ownerofadirectoryplacesanexecutablefilenamed
lsinthedirectory,andtheworkingdirectory
appearsfirstinauser'sPATH,theusergivinganls
commandfromthedirectoryexecutesthels
programintheworkingdirectoryinsteadofthe
systemlsutility,possiblywithundesirableresults.
IfyouwanttoadddirectoriestoPATH,youcanreferencethe
oldvalueofthePATHvariablewhileyouaresettingPATHtoa
newvalue(butseetheprecedingsecuritytip).Thefollowing
commandadds/usr/local/bintothebeginningofthecurrent
PATHandthebindirectoryintheuser'shomedirectory
(~/bin)totheend:
$PATH=/usr/local/bin:$PATH:~/bin
MAIL:WhereYourMailIsKept
TheMAILvariablecontainsthepathnameofthefilethatholds
yourmail(yourmailbox,usually/var/spool/mail/name,
wherenameisyourusername).IfMAILissetandMAILPATH
(next)isnotset,theshellinformsyouwhenmailarrivesinthe
filespecifiedbyMAIL.Inagraphicalenvironmentyoucan
unsetMAILsothattheshelldoesnotdisplaymailremindersin
aterminalemulatorwindow(assumingyouareusinga
graphicalmailprogram).
TheMAILPATHvariablecontainsalistoffilenamesseparated
bycolons.Ifthisvariableisset,theshellinformsyouwhenany
oneofthefilesismodified(forexample,whenmailarrives).
Youcanfollowanyofthefilenamesinthelistwithaquestion
mark(?),followedbyamessage.Themessagereplacesthe
youhavemailmessagewhenyougetmailwhileyouare
loggedin.
TheMAILCHECKvariablespecifieshowoften,inseconds,the
shellchecksfornewmail.Thedefaultis60seconds.Ifyouset
thisvariabletozero,theshellchecksbeforeeachprompt.
PS1:UserPrompt(Primary)
ThedefaultBourneAgainShellpromptisadollarsign($).
Whenyourunbashasroot,youmayhaveapoundsign(#)
prompt.ThePS1variableholdsthepromptstringthattheshell
usestoletyouknowthatitiswaitingforacommand.When
youchangethevalueofPS1,youchangetheappearanceof
yourprompt.
YoucancustomizethepromptdisplayedbyPS1.Forexample,
theassignment
$PS1="[\u@\h\W\!]$"
displaysthefollowingprompt:
[user@hostdirectoryevent]$
whereuseristheusername,hostisthehostnameuptothe
firstperiod,directoryisthebasenameoftheworking
directory,andeventistheeventnumberofthecurrent
command.
Ifyouareworkingonmorethanonesystem,itcanbehelpful
toincorporatethesystemnameintoyourprompt.Forexample,
youmightchangetheprompttothenameofthesystemyou
areusing,followedbyacolonandaSPACE(aSPACEattheend
ofthepromptmakesthecommandsthatyouenterafterthe
prompteasiertoread):
$PS1="$(hostname):"
bravo.example.com:echotest
test
bravo.example.com:
Thefirstexamplethatfollowschangestheprompttothename
ofthelocalhost,aSPACE,andadollarsign(or,iftheuseris
runningasroot,apoundsign).Thesecondexamplechanges
theprompttothetimefollowedbythenameoftheuser.The
thirdexamplechangestheprompttotheoneusedinthisbook
(apoundsignforrootandadollarsignotherwise):
$PS1='\h\$'
bravo$
$PS1='\@\u$'
09:44PMalex$
$PS1='\$'
$
Table9-4describessomeofthesymbolsyoucanuseinPS1.
Foracompletelistofspecialcharactersyoucanuseinthe
promptstrings,openthebashmanpageandsearchforthe
secondoccurrenceofPROMPTING(givethecommand
/PROMPTINGandthenpressn).
Table9-4.PS1symbols
Symbol Displayinprompt
\$ #iftheuserisrunningasroot;otherwise,$
\w Pathnameoftheworkingdirectory
\W Basenameoftheworkingdirectory
\! Currentevent(history)number(page307)
\d DateinWeekdayMonthDateformat
\h Machinehostname,withoutthedomain
\H Fullmachinehostname,includingthedomain
\u Usernameofthecurrentuser
\@ Currenttimeofdayin12-hour,AM/PMformat
\T Currenttimeofdayin12-hourHH:MM:SSformat
\A Currenttimeofdayin24-hourHH:MMformat
\t Currenttimeofdayin24-hourHH:MM:SSformat
PS2:UserPrompt(Secondary)
PromptString2isasecondarypromptthattheshellstoresin
PS2.Onthefirstlineofthenextexample,anunclosedquoted
stringfollowsecho.Theshellassumesthatthecommandisnot
finishedand,onthesecondline,givesthedefaultsecondary
prompt(>).Thispromptindicatesthattheshelliswaitingfor
theusertocontinuethecommandline.Theshellwaitsuntilit
receivesthequotationmarkthatclosesthestringandthen
executesthecommand:
$echo"demonstrationofpromptstring
>2"
demonstrationofpromptstring
2
$PS2="secondaryprompt:"
$echo"thisdemonstrates
secondaryprompt:promptstring2"
thisdemonstrates
promptstring2
Thesecondcommandchangesthesecondarypromptto
secondaryprompt:followedbyaSPACE.Amultilineecho
demonstratesthenewprompt.
PS3:MenuPrompt
PS3holdsthemenupromptfortheselectcontrolstructure
(page908).
PS4:DebuggingPrompt
PS4holdsthebashdebuggingsymbol(page890).
IFS:SeparatesInputFields(WordSplitting)
TheIFS(InternalFieldSeparator)shellvariablespecifiesthe
charactersthatyoucanusetoseparateargumentsona
commandlineandhasthedefaultvalueofSPACETABNEWLINE.
RegardlessofthevalueofIFS,youcanalwaysuseoneormore
SPACEorTABcharacterstoseparateargumentsonthe
commandline,providedthatthesecharactersarenotquotedor
escaped.WhenyouassignIFScharactervalues,these
characterscanalsoseparatefieldsbutonlyiftheyundergo
expansion.Thistypeofinterpretationofthecommandlineis
calledwordsplitting.
Caution:BecarefulwhenchangingIFS
ChangingIFShasavarietyofsideeffectssowork
cautiously.Youmayfinditusefultofirstsavethe
valueofIFSbeforechangingit;youcaneasilythen
restoretheoriginalvalueifyougetunexpected
results.Alternatively,youcanforkanewshellwitha
bashcommandbeforeexperimentingwithIFS;if
yougetintotrouble,youcanexitbacktotheold
shell,whereIFSisworkingproperly.Youcanalso
setIFStoitsdefaultvaluewiththefollowing
command:
$IFS='\t\n'
ThefollowingexampledemonstrateshowsettingIFScanaffect
theinterpretationofacommandline:
$a=w:x:y:z
$cat$a
cat:w:x:y:z:Nosuchfileordirectory
$IFS=":"
$cat$a
cat:w:Nosuchfileordirectory
cat:x:Nosuchfileordirectory
cat:y:Nosuchfileordirectory
cat:z:Nosuchfileordirectory
Thefirsttimecatiscalled,theshellexpandsthevariablea,
interpretingthestringw:x:y:zasasinglewordtobeusedas
theargumenttocat.Thecatutilitycannotfindafilenamed
w:x:y:zandreportsanerrorforthatfilename.AfterIFSisset
toacolon(:),theshellexpandsthevariableaintofourwords,
eachofwhichisanargumenttocat.Nowcatreportsanerrorfor
fourseparatefiles:w,x,y,andz.Wordsplittingbasedonthe
colon(:)takesplaceonlyafterthevariableaisexpanded.
Theshellsplitsallexpandedwordsonacommandline
accordingtotheseparatingcharactersfoundinIFS.When
thereisnoexpansion,thereisnosplitting.Considerthe
followingcommands:
$IFS="p"
$exportVAR
AlthoughIFSissettop,thepontheexportcommandlineis
notexpandedsothewordexportisnotsplit.
Thefollowingexampleusesvariableexpansioninanattemptto
produceanexportcommand:
$IFS="p"
$aa=export
$echo$aa
exort
Thistimeexpansionoccurssothatthecharacterpinthetoken
exportisinterpretedasaseparatorastheprecedingecho
commandshows.Nowwhenyoutrytousethevalueoftheaa
variabletoexporttheVARvariable,theshellparsesthe$aa
VARcommandlineasexortVAR.Theeffectisthatthe
commandlinestartstheexeditorwithtwofilenames:ortand
VAR.
$$aaVAR
2filestoedit
"ort"[NewFile]
EnteringExmode.Type"visual"togotoNormalmode.
:q
E173:1morefiletoedit
:q
$
IfyouunsetIFS,onlySPACEsandTABsworkasfield
separators.
Tip:Multipleseparatorcharacters
AlthoughsequencesofmultipleSPACEorTAB
charactersaretreatedassingleseparators,each
occurrenceofanotherfield-separatorcharacteracts
asaseparator.
CDPATH:BroadenstheScopeofcd
TheCDPATHvariableallowsyoutouseasimplefilenameasan
argumenttothecdbuiltintochangetheworkingdirectorytoa
directoryotherthanachildoftheworkingdirectory.Ifyouhave
severaldirectoriesyouliketoworkoutof,thisvariablecan
speedthingsupandsaveyouthetediumofusingcdwithlonger
pathnamestoswitchamongthem.
WhenCDPATHisnotsetandyouspecifyasimplefilenameas
anargumenttocd,cdsearchestheworkingdirectoryfora
subdirectorywiththesamenameastheargument.Ifthe
subdirectorydoesnotexist,cddisplaysanerrormessage.When
CDPATHisset,cdsearchesforanappropriatelynamed
subdirectoryinthedirectoriesintheCDPATHlist.Ifcdfinds
one,thatdirectorybecomestheworkingdirectory.With
CDPATHset,youcanusecdandasimplefilenametochange
theworkingdirectorytoachildofanyofthedirectorieslistedin
CDPATH.
TheCDPATHvariabletakesonthevalueofacolon-separated
listofdirectorypathnames(similartothePATHvariable).Itis
usuallysetinthe~/.bash_profilestartupfilewithacommand
linesuchasthefollowing:
exportCDPATH=$HOME:$HOME/literature
Thiscommandcausescdtosearchyourhomedirectory,the
literaturedirectory,andthentheworkingdirectorywhenyou
giveacdcommand.Ifyoudonotincludetheworkingdirectory
inCDPATH,cdsearchestheworkingdirectoryifthesearchof
alltheotherdirectoriesinCDPATHfails.Ifyouwantcdto
searchtheworkingdirectoryfirst(whichyoushouldneverdo
whenyouareloggedinasrootrefertothetiponpage293),
includeanullstring,representedbytwocolons(::),asthefirst
entryinCDPATH:
exportCDPATH=::$HOME:$HOME/literature
Iftheargumenttothecdbuiltinisanabsolutepathnameone
startingwithaslash(/)theshelldoesnotconsultCDPATH.
KeywordVariables:ASummary
Table9-5liststhebashkeywordvariables.
Table9-5.bashkeywordvariables
Variable Value
BASH_ENV Thepathnameofthestartupfilefornoninteractive
shells(page268)
CDPATH Thecdsearchpath(page297)
COLUMNS Thewidthofthedisplayusedbyselect(page907)
FCEDIT Thenameoftheeditorthatfcusesbydefault(page
305)
HISTFILE Thepathnameofthefilethatholdsthehistorylist
(default:~/.bash_history;page302)
HISTFILESIZE ThemaximumnumberofentriessavedinHISTFILE
(default:500;page302)
HISTSIZE Themaximumnumberofentriessavedinthehistory
list(default:500;page302)
HOME Thepathnameoftheuser'shomedirectory(page291);
usedasthedefaultargumentforcdandintilde
expansion(page171)
IFS InternalFieldSeparator(page295);usedforword
splitting(page335)
INPUTRC ThepathnameoftheReadlinestartupfile(default:
~/.inputrc;page315)
LANG Thelocalecategorywhenthatcategoryisnot
specificallysetwithanLC_*variable
LC_* Agroupofvariablesthatspecifylocalecategories
includingLC_COLLATE,LC_CTYPE,LC_MESSAGES,
andLC_NUMERIC;usethelocalebuiltintodisplaya
completelistwithvalues
LINES Theheightofthedisplayusedbyselect(page907)
MAIL Thepathnameofthefilethatholdsauser'smail(page
293)
MAILCHECK Howoften,inseconds,bashchecksformail(page293)
MAILPATH Acolon-separatedlistoffilepathnamesthatbashchecks
formailin(page293)
PATH Acolon-separatedlistofdirectorypathnamesthatbash
looksforcommandsin(page292)
PROMPT_COMMAND Acommandthatbashexecutesjustbeforeitdisplays
theprimaryprompt
PS1 PromptString1;theprimaryprompt(default:'\s-
\v\$';page293)
PS2 PromptString2;thesecondaryprompt(default:'>';
page295)
PS3 Thepromptissuedbyselect(page907)
PS4 Thebashdebuggingsymbol(page890)
REPLY Holdsthelinethatreadaccepts(page928);alsoused
byselect(page907)
SpecialCharacters
Table9-6listsmostofthecharactersthatarespecialtothebash
shell.
Table9-6.Shellspecialcharacters
Character Use
NEWLINE Initiatesexecutionofacommand(page276)
;Separatescommands(page276)
() Groupscommands(page279)forexecutionbya
subshelloridentifiesafunction(page321)
&Executesacommandinthebackground(pages219and
278)
|Sendsstandardoutputofprecedingcommandto
standardinputoffollowingcommand(pipe;page278)
>Redirectsstandardoutput(page210)
>> Appendsstandardoutput(page214)
<Redirectsstandardinput(page212)
<< Heredocument(page909)
*Anystringofzeroormorecharactersinanambiguous
filereference(page222)
?Anysinglecharacterinanambiguousfilereference
(page221)
\Quotesthefollowingcharacter(page126)
' Quotesastring,preventingallsubstitution(page126)
"Quotesastring,allowingonlyvariableandcommand
substitution(pages126and287)
'...' Performscommandsubstitution(page334)
[] Characterclassinanambiguousfilereference(page
223)
$Referencesavariable(page285)
.(dotbuiltin) Executesacommand(onlyatthebeginningofaline,
page269)
#Beginsacomment(page275)
{} Usedtosurroundthecontentsofafunction(page321)
:(nullbuiltin) Returnstrue(page935)
&&(Boolean
AND)
Executescommandonrightonlyifcommandonleft
succeeds(returnsazeroexitstatus,page946)
||(Boolean
OR)
Executescommandonrightonlyifcommandonleft
fails(returnsanonzeroexitstatus;page946)
!(Boolean
NOT)
Reversesexitstatusofacommand
$() Performscommandsubstitution(preferredform;page
334)
[] Evaluatesanarithmeticexpression(page332)
Processes
AprocessistheexecutionofacommandbyLinux.Theshell
thatstartswhenyouloginisacommand,oraprocess,likeany
other.WhenyougivethenameofaLinuxutilityonthe
commandline,youinitiateaprocess.Whenyourunashell
script,anothershellprocessisstartedandadditionalprocesses
arecreatedforeachcommandinthescript.Dependingonhow
youinvoketheshellscript,thescriptisruneitherbythe
currentshellor,moretypically,byasubshell(child)ofthe
currentshell.Aprocessisnotstartedwhenyourunashell
builtin,suchascd.
ProcessStructure
forksystemcall
Likethefilestructure,theprocessstructureishierarchical,with
parents,children,andevenaroot.Aparentprocessforksa
childprocess,whichinturncanforkotherprocesses.(Theterm
forkindicatesthat,aswithaforkintheroad,oneprocessturns
intotwo.Initiallythetwoforksareidenticalexceptthatoneis
identifiedastheparentandoneasthechild.Youcanalsouse
thetermspawn;thewordsareinterchangeable.)Theoperating
systemroutine,orsystemcall,thatcreatesanewprocessis
namedfork.
WhenLinuxbeginsexecutionwhenasystemisstarted,itstarts
init,asingleprocesscalledaspontaneousprocess,withPID
number1.Thisprocessholdsthesamepositionintheprocess
structureastherootdirectorydoesinthefilestructure:Itis
theancestorofallprocessesthatthesystemanduserswork
with.Whenthesystemisinmultiusermode,initrunsgettyor
mingettyprocesses,whichdisplaylogin:promptsonterminals
andvirtualconsoles.Whensomeonerespondstotheprompt
andpressesRETURN,gettyhandscontrolovertoautilitynamed
login,whichcheckstheusernameandpasswordcombination.
Aftertheuserlogsin,theloginprocessbecomestheuser'sshell
process.
ProcessIdentification
PIDnumber
LinuxassignsauniquePID(processidentification)numberat
theinceptionofeachprocess.Aslongasaprocessexists,it
keepsthesamePIDnumber.Duringonesessionthesame
processisalwaysexecutingtheloginshell.Whenyouforka
newprocessforexample,whenyouuseaneditorthePID
numberofthenew(child)processisdifferentfromthatofits
parentprocess.Whenyoureturntotheloginshell,itisstill
beingexecutedbythesameprocessandhasthesamePID
numberaswhenyouloggedin.
Thefollowingexampleshowsthattheprocessrunningtheshell
forked(istheparentof)theprocessrunningps(page220).
Whenyoucallitwiththefoption,psdisplaysafulllistingof
informationabouteachprocess.Thelineofthepsdisplaywith
bashintheCMDcolumnreferstotheprocessrunningthe
shell.ThecolumnheadedbyPIDidentifiesthePIDnumber.
ThecolumnheadedPPIDidentifiesthePIDnumberofthe
parentoftheprocess.FromthePIDandPPIDcolumnsyoucan
seethattheprocessrunningtheshell(PID21341)istheparent
oftheprocessrunningsleep(PID22789).TheparentPID
numberofsleepisthesameasthePIDnumberoftheshell
(21341).
$sleep10&
[1]22789
$ps-f
UIDPIDPPIDCSTIMETTYTIMECMD
alex2134121340010:42pts/1600:00:00bash
alex2278921341017:30pts/1600:00:00sleep10
alex2279021341017:30pts/1600:00:00ps-f
Refertothepsmanpageformoreinformationonpsandthe
columnsitdisplayswiththefoption.Asecondpairofsleep
andpsfcommandsshowsthattheshellisstillbeingrunbythe
sameprocessbutthatitforkedanotherprocesstorunsleep:
$sleep10&
[1]22791
$ps-f
UIDPIDPPIDCSTIMETTYTIMECMD
alex2134121340010:42pts/1600:00:00bash
alex2279121341017:31pts/1600:00:00sleep10
alex2279221341017:31pts/1600:00:00ps-f
Youcanalsousepstree(orpsforest,withorwithoutthee
option)toseetheparentchildrelationshipofprocesses.The
nextexampleshowsthepoptiontopstree,whichcausesitto
displayPIDnumbers:
$pstree-p
init(1)-+-acpid(1395)
|-atd(1758)
|-crond(1702)
...
|-kdeinit(2223)-+-firefox(8914)---run-mozilla.sh(8920)---firefox-bin(8925)
||-gaim(2306)
||-gqview(14062)
||-kdeinit(2228)
||-kdeinit(2294)
||-kdeinit(2314)-+-bash(2329)---ssh(2561)
|||-bash(2339)
||'-bash(15821)---bash(16778)
||-kdeinit(16448)
||-kdeinit(20888)
||-oclock(2317)
|'-pam-panel-icon(2305)---pam_timestamp_c(2307)
...
|-login(1823)---bash(20986)-+-pstree(21028)
|'-sleep(21026)
...
Theprecedingoutputisabbreviated.Thelinethatstartswith
kdeinitshowsagraphicaluserrunningmanyprocesses,
includingfirefox,gaim,andoclock.Thelinethatstartswith
loginshowsatextualuserrunningsleepinthebackground
whilerunningpstreeintheforeground.Referto"$$:PIDNumber"
onpage919foradescriptionofhowtoinstructtheshellto
reportonPIDnumbers.
ExecutingaCommand
forkandsleep
Whenyougivetheshellacommand,itusuallyforks(spawns)a
childprocesstoexecutethecommand.Whilethechildprocess
isexecutingthecommand,theparentprocesssleeps.Whilea
processissleeping,itdoesnotuseanycomputertimebut
remainsinactive,waitingtowakeup.Whenthechildprocess
finishesexecutingthecommand,ittellsitsparentofitssuccess
orfailureviaitsexitstatusandthendies.Theparentprocess
(whichisrunningtheshell)wakesupandpromptsforanother
command.
Backgroundprocess
Whenyourunaprocessinthebackgroundbyendinga
commandwithanampersand(&),theshellforksachild
processwithoutgoingtosleepandwithoutwaitingforthechild
processtoruntocompletion.Theparentprocess,whichis
executingtheshell,reportsthejobnumberandPIDnumberof
thechildandpromptsforanothercommand.Thechildprocess
runsinthebackground,independentofitsparent.
Builtins
Althoughtheshellforksaprocesstorunmostofthecommands
yougiveit,somecommandsarebuiltintotheshell.Theshell
doesnotneedtoforkaprocesstorunbuiltins.Formore
informationreferto"Builtins"onpage225.
Variables
Withinagivenprocess,suchasyourloginshellorasubshell,
youcandeclare,initialize,read,andchangevariables.By
defaulthowever,avariableislocaltoaprocess.Whenaprocess
forksachildprocess,theparentdoesnotpassthevalueofa
variabletothechild.Youcanmakethevalueofavariable
availabletochildprocesses(global)byusingtheexportbuiltin
(page916).
History
Thehistorymechanism,afeatureadaptedfromtheCShell,
maintainsalistofrecentlyissuedcommandlines,alsocalled
events,providingaquickwaytoreexecuteanyoftheeventsin
thelist.Thismechanismalsoenablesyoutoexecutevariations
ofpreviouscommandsandtoreuseargumentsfromthem.You
canreplicatecomplicatedcommandsandargumentsthatyou
usedearlierinthisloginsessionorinapreviousoneandenter
aseriesofcommandsthatdifferfromoneanotherinminor
ways.Thehistorylistalsoservesasarecordofwhatyouhave
done.Itcanprovehelpfulwhenyouhavemadeamistakeand
arenotsurewhatyoudidorwhenyouwanttokeeparecordof
aprocedurethatinvolvedaseriesofcommands.
Thehistorybuiltindisplaysthehistorylist.Ifitdoesnot,read
onyouneedtosetsomevariables.
VariablesThatControlHistory
ThevalueoftheHISTSIZEvariabledeterminesthenumberof
eventspreservedinthehistorylistduringasession.Avaluein
therangeof100to1,000isnormal.
Whenyouexitfromtheshell,themostrecentlyexecuted
commandsaresavedinthefilegivenbytheHISTFILEvariable
(thedefaultis~/.bash_history).Thenexttimeyoustartthe
shell,thisfileinitializesthehistorylist.Thevalueofthe
HISTFILESIZEvariabledeterminesthenumberoflinesof
historysavedinHISTFILE(notnecessarilythesameas
HISTSIZE).HISTSIZEholdsthenumberofevents
rememberedduringasession,HISTFILESIZEholdsthe
numberrememberedbetweensessions,andthefiledesignated
byHISTFILEholdsthehistorylist.SeeTable9-7.
Table9-7.Historyvariables
Variable Default Function
HISTSIZE 500events Maximumnumberofeventssavedduring
asession
HISTFILE ~/.bash_history Locationofthehistoryfile
HISTFILESIZE 500events Maximumnumberofeventssaved
betweensessions
Tip:historycanhelptrackdownmistakes
Whenyouhavemadeacommandlinemistake(not
anerrorwithinascriptorprogram)andarenotsure
whatyoudidwrong,lookatthehistorylisttoreview
yourrecentcommands.Sometimesthislistcanhelp
youfigureoutwhatwentwrongandhowtofix
things.
Eventnumber
TheBourneAgainShellassignsasequentialeventnumberto
eachcommandline.Youcandisplaythiseventnumberaspart
ofthebashpromptbyincluding\!inPS1(page293).Examples
inthissectionshownumberedpromptswhentheyhelpto
illustratethebehaviorofacommand.
Givethefollowingcommandmanuallyorplaceitin
~/.bash_profile(toaffectfuturesessions)toestablisha
historylistofthe100mostrecentevents:
$HISTSIZE=100
Thefollowingcommandcausesbashtosavethe100mostrecent
eventsacrossloginsessions:
$HISTFILESIZE=100
AfteryousetHISTFILESIZE,youcanlogoutandloginagain,
andthe100mostrecenteventsfromthepreviousloginsession
willappearinyourhistorylist.
Givethecommandhistorytodisplaytheeventsinthehistory
list.Thelistofeventsisorderedwitholdesteventsatthetopof
thelist.Thefollowinghistorylistincludesacommandtomodify
thebashpromptsothatitdisplaysthehistoryeventnumber.
Thelasteventinthehistorylististhehistorycommandthat
displayedthelist.
32$history|tail
23PS1="\!bash$"
24ls-l
25cattemp
26rmtemp
27vimmemo
28lprmemo
29vimmemo
30lprmemo
31rmmemo
32history|tail
Asyouruncommandsandyourhistorylistbecomeslonger,it
mayrunoffthetopofthescreenwhenyouusethehistory
builtin.Pipetheoutputofhistorythroughlesstobrowsethrough
it,orgivethecommandhistory10tolookatthetenmost
recentcommands.
ReexecutingandEditingCommands
Youcanreexecuteanyeventinthehistorylist.Thisfeaturecan
saveyoutime,effort,andaggravation.Nothavingtoreenter
longcommandlinesallowsyoutoreexecuteeventsmoreeasily,
quickly,andaccuratelythanyoucouldifyouhadtoretypethe
entirecommandline.Youcanrecall,modify,andreexecute
previouslyexecutedeventsinthreeways:Youcanusethefc
builtin(coverednext);theexclamationpointcommands(page
306);ortheReadlineLibrary,whichusesaone-linevi-oremacs-
likeeditortoeditandexecuteevents(page312).
Tip:Whichmethodtouse?
Ifyouaremorefamiliarwithvioremacsandless
familiarwiththeCorTCShell,usefcortheReadline
Library.IfyouaremorefamiliarwiththeCorTC
Shellandlessfamiliarwithviandemacs,usethe
exclamationpointcommands.Ifitisatoss-up,try
theReadlineLibrary;itwillbenefityouinother
areasofLinuxmorethanlearningtheexclamation
pointcommandswill.
fc:Displays,Edits,andReexecutesCommands
Thefc(fixcommand)builtinenablesyoutodisplaythehistory
listandtoeditandreexecutepreviouscommands.Itprovides
manyofthesamecapabilitiesasthecommandlineeditors.
ViewingtheHistoryList
Whenyoucallfcwiththeloption,itdisplayscommandsfrom
thehistorylist.Withoutanyarguments,fclliststhe16most
recentcommandsinanumberedlist,withtheoldestappearing
first:
$fc-l
1024cd
1025viewcalendar
1026vimletter.adams01
1027aspell-cletter.adams01
1028vimletter.adams01
1029lprletter.adams01
1030cd../memos
1031ls
1032rm*0405
1033fc-l
1034cd
1035whereisaspell
1036manaspell
1037cd/usr/share/doc/*aspell*
1038pwd
1039ls
1040lsman-html
Thefcbuiltincantakezero,one,ortwoargumentswiththel
option.Theargumentsspecifythepartofthehistorylisttobe
displayed:
fcl[first[last]]
Thefcbuiltinlistscommandsbeginningwiththemostrecent
eventthatmatchesfirst.Theargumentcanbeanevent
number,thefirstfewcharactersofthecommandline,ora
negativenumber,whichistakentobethenthprevious
command.Ifyouprovidelast,fcdisplayscommandsfromthe
mostrecenteventthatmatchesfirstthroughthemostrecent
eventthatmatcheslast.Thenextcommanddisplaysthe
historylistfromevent1030throughevent1035:
$fc-l10301035
1030cd../memos
1031ls
1032rm*0405
1033fc-l
1034cd
1035whereisaspell
Thefollowingcommandliststhemostrecenteventthatbegins
withviewthroughthemostrecentcommandlinethatbegins
withwhereis:
$fc-lviewwhereis
1025viewcalendar
1026vimletter.adams01
1027aspell-cletter.adams01
1028vimletter.adams01
1029lprletter.adams01
1030cd../memos
1031ls
1032rm*0405
1033fc-l
1034cd
1035whereisaspell
Tolistasinglecommandfromthehistorylist,usethesame
identifierforthefirstandsecondarguments.Thefollowing
commandlistsevent1027:
$fc-l10271027
1027aspell-cletter.adams01
EditingandReexecutingPreviousCommands
Youcanusefctoeditandreexecutepreviouscommands.
fc[eeditor][first[last]]
Whenyoucallfcwiththeeoptionfollowedbythenameofan
editor,fccallstheeditorwithevent(s)intheWorkbuffer.
Withoutfirstandlast,fcdefaultstothemostrecentcommand.
Thenextexampleinvokesthevi(m)editortoeditthemost
recentcommand:
$fc-evi
Thefcbuiltinusesthestand-alonevi(m)editor.Ifyousetthe
FCEDITvariable,youdonotneedtousetheeoptiontospecify
aneditoronthecommandline.BecausethevalueofFCEDIT
hasbeenchangedto/usr/bin/emacsandfchasno
arguments,thefollowingcommandeditsthemostrecent
commandwiththeemacseditor:
$exportFCEDIT=/usr/bin/emacs
$fc
Ifyoucallitwithasingleargument,fcinvokestheeditoronthe
specifiedcommand.Thefollowingexamplestartstheeditor
withevent21intheWorkbuffer.Whenyouexitfromtheeditor,
theshellexecutesthecommand:
$fc21
Againyoucanidentifycommandswithnumbersorbyspecifying
thefirstfewcharactersofthecommandname.Thefollowing
examplecallstheeditortoworkoneventsfromthemostrecent
eventthatbeginswiththelettersvimthroughevent206:
$fcvim206
Caution:Cleanupthefcbuffer
Whenyouexecuteanfccommand,theshell
executeswhateveryouleaveintheeditorbuffer,
possiblywithunwantedresults.Ifyoudecideyoudo
notwanttoexecuteacommand,deleteeverything
fromthebufferbeforeyouexitfromtheeditor.
ReexecutingCommandsWithoutCallingtheEditor
Youcanreexecutepreviouscommandswithoutgoingintoan
editor.Ifyoucallfcwiththesoption,itskipstheeditingphase
andreexecutesthecommand.Thefollowingexample
reexecutesevent1029:
$fc-s1029
lprletter.adams01
Thenextexamplereexecutesthepreviouscommand:
$fc-s
Whenyoureexecuteacommandyoucantellfctosubstitute
onestringforanother.Thenextexamplesubstitutesthestring
johnforthestringadamsinevent1029andexecutesthe
modifiedevent:
$fc-sadams=john1029
lprletter.john01
UsinganExclamationPoint(!)toReferenceEvents
TheCShellhistorymechanismusesanexclamationpointto
referenceeventsandisavailableunderbash.Itisfrequently
morecumbersometousethanfcbutneverthelesshassome
usefulfeatures.Forexample,the!!commandreexecutesthe
previousevent,andthe!$tokenrepresentsthelastwordon
thepreviouscommandline.
Youcanreferenceaneventbyusingitsabsoluteeventnumber,
itsrelativeeventnumber,orthetextitcontains.Allreferences
toevents,calledeventdesignators,beginwithanexclamation
point(!).Oneormorecharactersfollowtheexclamationpoint
tospecifyanevent.
Youcanputhistoryeventsanywhereonacommandline.To
escapeanexclamationpointsothatitistreatedliterallyinstead
ofasthestartofahistoryevent,precedeitwithabackslash
(\)orencloseitwithinsinglequotationmarks.
EventDesignators
Aneventdesignatorspecifiesacommandinthehistorylist.See
Table9-8onpage308foralistofeventdesignators.
Table9-8.Eventdesignators
Designator Meaning
!Startsahistoryeventunlessfollowedimmediatelyby
SPACE,NEWLINE,=,or(.
!! Thepreviouscommand.
!nCommandnumberninthehistorylist.
!-n Thenthprecedingcommand.
!string Themostrecentcommandlinethatstartedwithstring.
!?string[?] Themostrecentcommandthatcontainedstring.The
last?isoptional.
!# Thecurrentcommand(asyouhaveittypedsofar).
!{event}Theeventisaneventdesignator.Thebracesisolate
eventfromthesurroundingtext.Forexample,!{-3}3
isthethirdmostrecentlyexecutedcommandfollowed
bya3.
!!reexecutesthepreviousevent
Youcanalwaysreexecutethepreviouseventbygivinga!!
command.Inthefollowingexample,event45reexecutesevent
44:
44$ls-ltext
-rw-rw-r--1alexgroup45Apr3014:53text
45$!!
ls-ltext
-rw-rw-r--1alexgroup45Apr3014:53text
The!!commandworkswhetherornotyourpromptdisplaysan
eventnumber.Asthisexampleshows,whenyouusethehistory
mechanismtoreexecuteanevent,theshelldisplaysthe
commanditisreexecuting.
!neventnumber
Anumberfollowinganexclamationpointreferstoanevent.If
thateventisinthehistorylist,theshellexecutesit.Otherwise,
theshelldisplaysanerrormessage.Anegativenumber
followinganexclamationpointreferencesaneventrelativeto
thecurrentevent.Forexample,thecommand!3referstothe
thirdprecedingevent.Afteryouissueacommand,therelative
eventnumberofagiveneventchanges(event3becomes
event4).Bothofthefollowingcommandsreexecuteevent44:
51$!44
ls-ltext
-rw-rw-r--1alexgroup45Nov3014:53text
52$!-8
ls-ltext
-rw-rw-r--1alexgroup45Nov3014:53text
!stringeventtext
Whenastringoftextfollowsanexclamationpoint,theshell
searchesforandexecutesthemostrecenteventthatbegan
withthatstring.Ifyouenclosethestringbetweenquestion
marks,theshellexecutesthemostrecenteventthatcontained
thatstring.ThefinalquestionmarkisoptionalifaRETURN
wouldimmediatelyfollowit.
68$history10
59ls-ltext*
60tailtext5
61cattext1text5>letter
62vimletter
63catletter
64catmemo
65lprmemo
66pinejenny
67ls-l
68history
69$!l
ls-l
...
70$!lpr
lprmemo
71$!?letter?
catletter
...
Optional
WordDesignators
Aworddesignatorspecifiesawordorseriesofwordsfromanevent.Table9-9
onpage310listsworddesignators.
Table9-9.Worddesignators
Designator Meaning
nThenthword.Word0isnormallythecommandname.
^Thefirstword(afterthecommandname).
$Thelastword.
mn Allwordsfromwordnumbermthroughwordnumber
n;mdefaultsto0ifyouomitit(0-n).
n* Allwordsfromwordnumbernthroughthelastword.
*Allwordsexceptthecommandname.Thesameas1*.
%Thewordmatchedbythemostrecent?string?search.
Thewordsarenumberedstartingwith0(thefirstwordonthelineusuallythe
command),continuingwith1(thefirstwordfollowingthecommand),andgoing
throughn(thelastwordontheline).
Tospecifyaparticularwordfromapreviousevent,followtheeventdesignator
(suchas!14)withacolonandthenumberofthewordinthepreviousevent.
Forexample,!14:3specifiesthethirdwordfollowingthecommandfromevent
14.Youcanspecifythefirstwordfollowingthecommand(wordnumber1)by
usingacaret(^)andthelastwordbyusingadollarsign($).Youcanspecifya
rangeofwordsbyseparatingtwoworddesignatorswithahyphen.
72$echoapplegrapeorangepear
applegrapeorangepear
73$echo!72:2
echogrape
grape
74$echo!72:^
echoapple
apple
75$!72:0!72:$
echopear
pear
76$echo!72:2-4
echograpeorangepear
grapeorangepear
77$!72:0-$
echoapplegrapeorangepear
applegrapeorangepear
Asthenextexampleshows,!$referstothelastwordofthepreviousevent.You
canusethisshorthandtoedit,forexample,afileyoujustdisplayedwithcat:
$catreport.718
...
$vim!$
vimreport.718
...
Ifaneventcontainsasinglecommand,thewordnumberscorrespondtothe
argumentnumbers.Ifaneventcontainsmorethanonecommand,this
correspondencedoesnotholdtrueforcommandsafterthefirst.Inthefollowing
exampleevent78containstwocommandsseparatedbyasemicolonsothatthe
shellexecutesthemsequentially;thesemicoloniswordnumber5.
78$!72;echohelenjennybarbara
echoapplegrapeorangepear;echohelenjennybarbara
applegrapeorangepear
helenjennybarbara
79$echo!78:7
echohelen
helen
80$echo!78:4-7
echopear;echohelen
pear
helen
Modifiers
Onoccasionyoumaywanttochangeanaspectofaneventyouarereexecuting.
Perhapsyouenteredacomplexcommandlinewithatypoorincorrectpathname
oryouwanttospecifyadifferentargument.Youcanmodifyaneventoraword
ofaneventbyputtingoneormoremodifiersaftertheworddesignator,orafter
theeventdesignatorifthereisnoworddesignator.Eachmodifiermustbe
precededbyacolon(:).
Substitutemodifier
Thesubstitutemodifierismorecomplexthantheother
modifiers.Thefollowingexampleshowsthesubstitutemodifier
correctingatypointhepreviousevent:
$car/home/jenny/memo.0507/home/alex/letter.0507
bash:car:commandnotfound
$!!:s/car/cat
cat/home/jenny/memo.0507/home/alex/letter.0507
...
Thesubstitutemodifierhasthefollowingsyntax:
[g]s/old/new/
whereoldistheoriginalstring(notaregularexpression),and
newisthestringthatreplacesold.Thesubstitutemodifier
substitutesthefirstoccurrenceofoldwithnew.Placingag
beforethes(asings/old/new/)causesaglobalsubstitution,
replacingalloccurrencesofold.The/isthedelimiterinthe
examplesbutyoucanuseanycharacterthatisnotineitherold
ornew.ThefinaldelimiterisoptionalifaRETURNwould
immediatelyfollowit.AswiththevimSubstitutecommand,the
historymechanismreplacesanampersand(&)innewwith
old.Theshellreplacesanulloldstring(s//new/)withthe
previousoldstringorstringwithinacommandthatyou
searchedforwith?string?.
Quicksubstitution
Anabbreviatedformofthesubstitutemodifierisquick
substitution.Useittoreexecutethemostrecenteventwhile
changingsomeoftheeventtext.Thequicksubstitution
characteristhecaret(^).Forexample,thecommand
$^old^new^
producesthesameresultsas
$!!:s/old/new/
Thussubstitutingcatforcarinthepreviouseventcouldhave
beenenteredas
$^car^cat
cat/home/jenny/memo.0507/home/alex/letter.0507
...
Youcanomitthefinalcaretifitwouldbefollowedimmediately
byaRETURN.Aswithothercommandlinesubstitutions,the
shelldisplaysthecommandlineasitappearsafterthe
substitution.
Othermodifiers
Modifiers(otherthanthesubstitutemodifier)performsimple
editsonthepartoftheeventthathasbeenselectedbythe
eventdesignatorandtheoptionalworddesignators.Youcan
usemultiplemodifiers,eachprecededbyacolon(:).
Thefollowingseriesofcommandsuseslstolistthenameofa
file,repeatsthecommandwithoutexecutingit(pmodifier),
andrepeatsthelastcommand,removingthelastpartofthe
pathname(hmodifier)againwithoutexecutingit:
$ls/etc/sysconfig/harddisks
/etc/sysconfig/harddisks
$!!:p
ls/etc/sysconfig/harddisks
$!!:h:p
ls/etc/sysconfig
$
Table9-10listseventmodifiersotherthanthesubstitute
modifier.
Table9-10.Modifiers
Modifier Function
e(extension) Removesallbutthefilenameextension
h(head) Removesthelastpartofapathname
p(print-not) Displaysthecommand,butdoesnotexecuteit
q(quote) Quotesthesubstitutiontopreventfurthersubstitutions
onit
r(root) Removesthefilenameextension
t(tail) Removesallelementsofapathnameexceptthelast
xLikeqbutquoteseachwordinthesubstitution
individually
TheReadlineLibrary
CommandlineeditingundertheBourneAgainShellis
implementedthroughtheReadlineLibrary,whichisavailableto
anyapplicationwritteninC.Anyapplicationthatusesthe
ReadlineLibrarysupportslineeditingthatisconsistentwiththat
providedbybash.ProgramsthatusetheReadlineLibrary,
includingbash,read~/.inputrc(page315)forkeybinding
informationandconfigurationsettings.Thenoediting
commandlineoptionturnsoffcommandlineeditinginbash.
vimode
Youcanchooseoneoftwoeditingmodeswhenusingthe
ReadlineLibraryinbash:emacsorvi(m).Bothmodesprovide
manyofthecommandsavailableinthestand-aloneversionsof
thevi(m)andemacseditors.YoucanalsousetheARROWkeysto
movearound.Upanddownmovementsmoveyoubackward
andforwardthroughthehistorylist.Inaddition,Readline
providesseveraltypesofinteractivewordcompletion(page
314).Thedefaultmodeisemacs;youcanswitchtovimodewith
thefollowingcommand:
$set-ovi
emacsmode
Thenextcommandswitchesbacktoemacsmode:
$set-oemacs
viEditingMode
Beforeyoustartmakesureyouareinvimode.
Whenyouenterbashcommandswhileinvieditingmode,you
areinInputmode(page154).Asyouenteracommand,ifyou
discoveranerrorbeforeyoupressRETURN,youcanpress
ESCAPEtoswitchtoviCommandmode.Thissetupisdifferent
fromthestand-alonevi(m)editor'sinitialmode.Whilein
Commandmodeyoucanusemanyvi(m)commandstoeditthe
commandline.Itisasthoughyouwereusingvi(m)toedita
copyofthehistoryfilewithascreenthathasroomforonlyone
command.WhenyouusethekcommandortheUPARROWto
moveupaline,youaccessthepreviouscommand.Ifyouthen
usethejcommandortheDOWNARROWtomovedownaline,
youwillreturntotheoriginalcommand.Tousethekandjkeys
tomovebetweencommandsyoumustbeinCommandmode;
youcanusetheARROWkeysinbothCommandandInput
modes.
Tip:Thestand-aloneeditorstartsin
Commandmode
Thestand-alonevimeditorstartsinCommandmode,
whereasthecommandlinevi(m)editorstartsin
Inputmode.Ifcommandsdisplaycharactersanddo
notworkproperly,youareinInputmode.Press
ESCAPEandenterthecommandagain.
Inadditiontocursor-positioningcommands,youcanusethe
search-backward(?)commandfollowedbyasearchstringto
lookbackthroughyourhistorylistforthemostrecent
commandcontainingthatstring.Ifyouhavemovedbackin
yourhistorylist,useaforwardslash(/)tosearchforward
towardyourmostrecentcommand.Unlikethesearchstringsin
thestand-alonevi(m)editor,thesesearchstringscannotcontain
regularexpressions.Youcan,however,startthesearchstring
withacaret(^)toforcetheshelltolocatecommandsthatstart
withthesearchstring.Asinvi(m),pressingnafterasuccessful
searchlooksforthenextoccurrenceofthesamestring.
Youcanalsoaccesseventsinthehistorylistbyusingevent
numbers.WhileyouareinCommandmode(pressESCAPE),
entertheeventnumberfollowedbyaGtogotothecommand
withthateventnumber.
Whenyouuse/,?,orGtomovetoacommandline,youarein
Commandmode,notInputmode.Nowyoucaneditthe
commandasyoulikeorpressRETURNtoexecuteit.
Oncethecommandyouwanttoeditisdisplayed,youcan
modifythecommandlineusingvi(m)Commandmodeediting
commandssuchasx(deletecharacter),r(replacecharacter),
~(changecase),and.(repeatlastchange).TochangetoInput
mode,useanInsert(i,I),Append(a,A),Replace(R),or
Change(c,C)command.Youdonothavetoreturnto
Commandmodetorunacommand;simplypressRETURN,even
ifthecursorisinthemiddleofthecommandline.
emacsEditingMode
Unlikethevi(m)editor,emacsismodeless.Youneednotswitch
betweenCommandmodeandInputmodebecausemostemacs
commandsarecontrolcharacters,allowingemacstodistinguish
betweeninputandcommands.Likevi(m),theemacscommand
lineeditorprovidescommandsformovingthecursoronthe
commandlineandthroughthecommandhistorylistandfor
modifyingpartorallofacommand.Theemacscommandline
editorcommandsdifferinafewcasesfromthecommandsin
thestand-aloneemacseditor.
InemacsyouperformcursormovementbyusingbothCONTROL
andESCAPEcommands.Tomovethecursoronecharacter
backwardonthecommandline,pressCONTROL-B.Press
CONTROL-Ftomoveonecharacterforward.Asinvi,youmay
precedethesemovementswithcounts.Touseacountyoumust
firstpressESCAPE;otherwise,thenumbersyoutypewillappear
onthecommandline.
Likevi(m),emacsprovideswordandlinemovementcommands.
Tomovebackwardorforwardonewordonthecommandline,
pressESCAPEborESCAPEf.Tomoveseveralwordsbyusinga
count,pressESCAPEfollowedbythenumberandthe
appropriateescapesequence.Togettothebeginningofthe
line,pressCONTROL-A;totheendoftheline,pressCONTROL-
E;andtothenextinstanceofthecharacterc,pressCONTROL-X
CONTROL-Ffollowedbyc.
Youcanaddtexttothecommandlinebymovingthecursorto
thecorrectplaceandtypingthedesiredtext.Todeletetext,
movethecursorjusttotherightofthecharactersthatyou
wanttodeleteandpresstheerasekey(page117)oncefor
eachcharacteryouwanttodelete.
Tip:CONTROL-Dcanterminateyour
screensession
Ifyouwanttodeletethecharacterdirectlyunderthe
cursor,pressCONTROL-D.IfyouenterCONTROL-Dat
thebeginningoftheline,itmayterminateyourshell
session.
Ifyouwanttodeletetheentirecommandline,typethelinekill
character(page118).Youcantypethischaracterwhilethe
cursorisanywhereinthecommandline.Ifyouwanttodelete
fromthecursortotheendoftheline,useCONTROL-K.
ReadlineCompletionCommands
YoucanusetheTABkeytocompletewordsyouareenteringon
thecommandline.Thisfacility,calledcompletion,worksinboth
viandemacseditingmodes.Severaltypesofcompletionare
possible,andwhichoneyouusedependsonwhichpartofa
commandlineyouaretypingwhenyoupressTAB.
CommandCompletion
Ifyouaretypingthenameofacommand(thefirstwordonthe
commandline),pressingTABresultsincommandcompletion.
Thatis,bashlooksforacommandwhosenamestartswiththe
partofthewordyouhavetyped.Ifnocommandstartswith
whatyouhaveentered,bashbeeps.Ifthereisonesuch
command,bashcompletesthecommandnameforyou.Ifthere
ismorethanonechoice,bashdoesnothinginvimodeandbeeps
inemacsmode.PressingTABasecondtimecausesbashto
displayalistofcommandswhosenamesstartwiththeprefix
youtypedandallowsyoutofinishtypingthecommandname.
Inthefollowingexample,theusertypesbzandpressesTAB.
Theshellbeeps(theuserisinemacsmode)toindicatethat
severalcommandsstartwiththelettersbz.Theuserenters
anotherTABtocausetheshelltodisplayalistofcommands
thatstartwithbzfollowedbythecommandlineastheuserhad
entereditsofar:
$bz TAB(beep) TAB
bzcatbzdiffbzip2bzless
bzcmpbzgrepbzip2recoverbzmore
$bzn
NexttheusertypescandpressesTABtwice.Theshelldisplays
thetwocommandsthatstartwithbzc.Theusertypesa
followedbyTABandtheshellthencompletesthecommand
becauseonlyonecommandstartswithbzca.
$bzc TAB(beep) TAB
bzcatbzcmp
$bzca TAB t
PathnameCompletion
Pathnamecompletion,whichalsousesTABs,allowsyoutotype
aportionofapathnameandhavebashsupplytherest.Ifthe
portionofthepathnamethatyouhavetypedissufficientto
determineauniquepathname,bashdisplaysthatpathname.If
morethanonepathnamewouldmatchit,bashcompletesthe
pathnameuptothepointwheretherearechoicessothatyou
cantypemore.
Whenyouareenteringapathname,includingasimple
filename,andpressTAB,theshellbeeps(iftheshellisinemacs
modeinvimodethereisnobeep).Itthenextendsthe
commandlineasfarasitcan.
$catfilms/dar TAB(beep)catfilms/dark_
Inthefilmsdirectoryeveryfilethatstartswithdarhask_as
thenextcharacters,sobashcannotextendthelinefurther
withoutmakingachoiceamongfiles.Youareleftwiththe
cursorjustpastthe_character.Atthispointyoucancontinue
typingthepathnameorpressTABtwice.Inthelattercasebash
beeps,displaysyourchoices,redisplaysthecommandline,and
againleavesthecursorjustafterthe_character.
$catfilms/dark_ TAB(beep) TAB
dark_passagedark_victory
$catfilms/dark_
Whenyouaddenoughinformationtodistinguishbetweenthe
twopossiblefilesandpressTAB,bashdisplaystheunique
pathname.IfyouenterpfollowedbyTABafterthe_character,
theshellcompletesthecommandline:
$catfilms/dark_p TAB assage
Becausethereisnofurtherambiguity,theshellappendsa
SPACEsoyoucanfinishtypingthecommandlineorjustpress
RETURNtoexecutethecommand.Ifthecompletepathnameis
thatofadirectory,bashappendsaslash(/)inplaceofaSPACE.
VariableCompletion
Whentypingavariablename,pressingTABresultsinvariable
completion,wherebashtriestocompletethenameofthe
variable.Incaseofanambiguity,pressingTABtwicedisplaysa
listofchoices:
$echo$HO TAB TAB
$HOME$HOSTNAME$HOSTTYPE
$echo$HOM TAB E
Caution:PressingRETURNexecutesthe
command
PressingRETURNcausestheshelltoexecutethe
commandregardlessofwherethecursorisonthe
commandline.
.inputrc:ConfiguringReadline
TheBourneAgainShellandotherprogramsthatusethe
ReadlineLibraryreadthefilespecifiedbytheINPUTRC
environmentvariabletoobtaininitializationinformation.If
INPUTRCisnotset,theseprogramsreadth~/.inputrcfile.
Theyignorelinesof.inputrcthatareblankorthatstartwitha
poundsign(#).
Variables
Youcansetvariablesin.inputrctocontrolthebehaviorofthe
ReadlineLibraryusingthefollowingsyntax:
setvariablevalue
Table9-11listssomevariablesandvaluesyoucanuse.See
ReadlineVariablesinthebashmanorinfopageforacomplete
list.
Table9-11.Readlinevariables
Variable Effect
editing-mode SettovitostartReadlineinvimode.Setto
emacstostartReadlineinemacsmode(the
default).Similartotheset-oviandset-o
emacsshellcommands(page312).
horizontal-scroll-
mode
Settoontocauselonglinestoextendoffthe
rightedgeofthedisplayarea.Movingthecursor
totherightwhenitisattherightedgeofthe
displayareashiftsthelinetotheleftsoyoucan
seemoreoftheline.Youcanshiftthelineback
bymovingthecursorbackpasttheleftedge.
Thedefaultvalueisoff,whichcauseslonglines
towrapontomultiplelinesofthedisplay.
mark-directories SettoofftocauseReadlinenottoplaceaslash
(/)attheendofdirectorynamesitcompletes.
Normallyitison.
mark-modified-
lines
SettoontocauseReadlinetoprecedemodified
historylineswithanasterisk.Thedefaultvalue
isoff.
KeyBindings
Youcanspecifybindingsthatmapkeystrokesequencesto
Readlinecommands,allowingyoutochangeorextendthe
defaultbindings.Asinemacs,theReadlineLibraryincludesmany
commandsthatarenotboundtoakeystrokesequence.Touse
anunboundcommand,youmustmapitusingoneofthe
followingforms:
keyname:command_name
"keystroke_sequence":command_name
Inthefirstform,youspelloutthenameforasinglekey.For
example,CONTROL-Uwouldbewrittenascontrol-u.Thisform
isusefulforbindingcommandstosinglekeys.
Inthesecondform,youspecifyastringthatdescribesa
sequenceofkeysthatwillbeboundtothecommand.Youcan
usetheemacs-stylebackslashescapesequencestorepresent
thespecialkeysCONTROL(\C),META(\M),andESCAPE(\e).
Specifyabackslashbyescapingitwithanotherbackslash:\\.
Similarly,adoubleorsinglequotationmarkcanbeescaped
withabackslash:\"or\'.
Thekill-whole-linecommand,availableinemacsmodeonly,
deletesthecurrentline.Putthefollowingcommandin.inputrc
tobindthekill-whole-linecommand(whichisunboundby
default)tothekeystrokesequenceCONTROL-R.
control-r:kill-whole-line
bind
GivethecommandbindPtodisplayalistofallReadline
commands.Ifacommandisboundtoakeysequence,that
sequenceisshown.Commandsyoucanuseinvimodestart
withvi.Forexample,vi-next-wordandvi-prev-wordmove
thecursortothebeginningofthenextandpreviouswords,
respectively.Commandsthatdonotbeginwithviaregenerally
availableinemacsmode.
Usebindqtodeterminewhichkeysequenceisboundtoa
command:
$bind-qkill-whole-line
kill-whole-linecanbeinvokedvia"\C-r".
Youcanalsobindtextbyenclosingitwithindoublequotation
marks(emacsmodeonly):
"QQ":"TheLinuxOperatingSystem"
ThiscommandcausesbashtoinsertthestringTheLinux
OperatingSystemwhenyoutypeQQ.
ConditionalConstructs
Youcanconditionallyselectpartsofthe.inputrcfileusingthe
$ifdirective.Thesyntaxoftheconditionalconstructis
$iftest[=value]
commands
[$else
commands]
$endif
wheretestismode,term,orbash.Iftestequalsvalueorif
testistrue,thisstructureexecutesthefirstsetofcommands.
Iftestdoesnotequalvalueoriftestisfalse,itexecutesthe
secondsetofcommandsiftheyarepresentorexitsfromthe
structureiftheyarenotpresent.
Thepowerofthe$ifdirectiveliesinthethreetypesoftestsit
canperform.
1. Youcantesttoseewhichmodeiscurrentlyset.
$ifmode=vi
TheprecedingtestistrueifthecurrentReadlinemodeisvi
andfalseother-wise.Youcantestforvioremacs.
2. Youcantestthetypeofterminal.
$ifterm=xterm
TheprecedingtestistrueiftheTERMvariableissetto
xterm.YoucantestforanyvalueofTERM.
3. Youcantesttheapplicationname.
$ifbash
Theprecedingtestistruewhenyouarerunningbashand
notanotherprogramthatusestheReadlineLibrary.Youcan
testforanyapplicationname.
ThesetestscancustomizetheReadlineLibrarybasedonthe
currentmode,thetypeofterminal,andtheapplicationyouare
using.Theygiveyouagreatdealofpowerandflexibilitywhen
usingtheReadlineLibrarywithbashandotherprograms.
Thefollowingcommandsin.inputrccauseCONTROL-Ytomove
thecursortothebeginningofthenextwordregardlessof
whetherbashisinvioremacsmode:
$cat~/.inputrc
setediting-modevi
$ifmode=vi
"\C-y":vi-next-word
$else
"\C-y":forward-word
$endif
Becausebashreadstheprecedingconditionalconstructwhenit
isstarted,youmustsettheeditingmodein.inputrc.Changing
modesinteractivelyusingsetwillnotchangethebindingof
CONTROL-Y.
FormoreinformationontheReadlineLibrary,openthebashman
pageandgivethecommand/^READLINE,whichsearchesfor
thewordREADLINEatthebeginningofaline.
Tip:IfReadlinecommandsdonotwork,
logoutandloginagain
TheBourneAgainShellreads~/.inputrcwhenyou
login.Afteryoumakechangestothisfile,you
shouldlogoutandloginagainbeforetestingthe
changes.
Aliases
Analiasisa(usuallyshort)namethattheshelltranslatesinto
another(usuallylonger)nameor(complex)command.Aliases
allowyoutodefinenewcommandsbysubstitutingastringfor
thefirsttokenofasimplecommand.Theyaretypicallyplaced
inthe~/.bashrcstartupfilessothattheyareavailableto
interactivesubshells.
Thesyntaxofthealiasbuiltinis
alias[name[=value]]
NoSPACEsarepermittedaroundtheequalsign.Ifvalue
containsSPACEsorTABs,youmustenclosevaluebetween
quotationmarks.Analiasdoesnotacceptanargumentfrom
thecommandlineinvalue.Useafunction(page321)when
youneedtouseanargument.
Analiasdoesnotreplaceitself,whichavoidsthepossibilityof
infiniterecursioninhandlinganaliassuchasthefollowing:
$aliasls='ls-F'
Youcannestaliases.Aliasesaredisabledfornoninteractive
shells(thatis,shellscripts).Toseealistofthecurrentaliases,
givethecommandalias.Toviewthealiasforaparticular
name,usealiasfollowedbythenameandnothingelse.Youcan
usetheunaliasbuiltintoremoveanalias.
Whenyougiveanaliasbuiltincommandwithoutanyarguments,
theshelldisplaysalistofalldefinedaliases:
$alias
aliasll='ls-l'
aliasl='ls-ltr'
aliasls='ls-F'
aliaszap='rm-i'
RedHatLinuxdefinessomealiases.Giveanaliascommandto
seewhichaliasesareineffect.Youcandeletethealiasesyou
donotwantfromtheappropriatestartupfile.
SingleVersusDoubleQuotationMarksin
Aliases
Thechoiceofsingleordoublequotationmarksissignificantin
thealiassyntaxwhenthealiasincludesvariables.Ifyou
enclosevaluewithindoublequotationmarks,anyvariables
thatappearinvalueareexpandedwhenthealiasiscreated.If
youenclosevaluewithinsinglequotationmarks,variablesare
notexpandeduntilthealiasisused.Thefollowingexample
illustratesthedifference.
ThePWDkeywordvariableholdsthepathnameoftheworking
directory.Alexcreatestwoaliaseswhileheisworkinginhis
homedirectory.Becauseheusesdoublequotationmarkswhen
hecreatesthedirAalias,theshellsubstitutesthevalueofthe
workingdirectorywhenhecreatesthisalias.ThealiasdirA
commanddisplaysthedirAaliasandshowsthatthe
substitutionhasalreadytakenplace:
$echo$PWD
/home/alex
$aliasdirA="echoWorkingdirectoryis$PWD"
$aliasdirA
aliasdirA='echoWorkingdirectoryis/home/alex'
WhenAlexcreatesthedirBalias,heusessinglequotation
marks,whichpreventtheshellfromexpandingthe$PWD
variable.ThealiasdirBcommandshowsthatthedirBalias
stillholdstheunexpanded$PWDvariable:
$aliasdirB='echoWorkingdirectoryis$PWD'
$aliasdirB
aliasdirB='echoWorkingdirectoryis$PWD'
AftercreatingthedirAanddirBaliases,Alexusescdtomake
carshisworkingdirectoryandgiveseachofthealiasesas
commands.Thealiasthathecreatedwithdoublequotation
marksdisplaysthenameofthedirectorythathecreatedthe
aliasinastheworkingdirectory(whichiswrong)andthedirB
aliasdisplaysthepropernameoftheworkingdirectory:
$cdcars
$dirA
Workingdirectoryis/home/alex
$dirB
Workingdirectoryis/home/alex/cars
Tip:Howtopreventtheshellfrom
invokinganalias
Theshellchecksonlysimple,unquotedcommands
toseeiftheyarealiases.Commandsgivenas
relativeorabsolutepathnamesandquoted
commandsarenotchecked.Whenyouwanttogive
acommandthathasanaliasbutdonotwanttouse
thealias,precedethecommandwithabackslash,
specifythecommand'sabsolutepathname,orgive
thecommandas./command.
ExamplesofAliases
Thefollowingaliasallowsyoutotypertorepeattheprevious
commandorrabctorepeatthelastcommandlinethatbegan
withabc:
$aliasr='fc-s'
Ifyouusethecommandlsltrfrequently,youcancreatean
aliasthatsubstituteslsltrwhenyougivethecommandl:
$aliasl='ls-ltr'
$l
total41
-rw-r--r--1alexgroup30015Mar12004flute.ps
-rw-r-----1alexgroup3089Feb112005XTerm.ad
-rw-r--r--1alexgroup641Apr12005fixtax.icn
-rw-r--r--1alexgroup484Apr92005maptax.icn
drwxrwxr-x2alexgroup1024Aug917:41Tiger
drwxrwxr-x2alexgroup1024Sep1011:32testdir
-rwxr-xr-x1alexgroup485Oct2108:03floor
drwxrwxr-x2alexgroup1024Oct2720:19Test_Emacs
Anothercommonuseofaliasesistoprotectyourselffrom
mistakes.Thefollowingexamplesubstitutestheinteractive
versionofthermutilitywhenyougivethecommandzap:
$aliaszap='rm-i'
$zapf*
rm:remove'fixtax.icn'?n
rm:remove'flute.ps'?n
rm:remove'floor'?n
Theioptioncausesrmtoaskyoutoverifyeachfilethatwould
bedeleted,tohelpyouavoidaccidentallydeletingthewrong
file.Youcanalsoaliasrmwiththermicommand:alias
rm='rmi'.
Thealiasesinthenextexamplecausetheshelltosubstitutelsl
eachtimeyougiveanllcommandandlsFwhenyouusels:
$aliasls='ls-F'
$aliasll='ls-l'
$ll
total41
drwxrwxr-x2alexgroup1024Oct2720:19Test_Emacs/
drwxrwxr-x2alexgroup1024Aug917:41Tiger/
-rw-r-----1alexgroup3089Feb112005XTerm.ad
-rw-r--r--1alexgroup641Apr12005fixtax.icn
-rw-r--r--1alexgroup30015Mar12004flute.ps
-rwxr-xr-x1alexgroup485Oct2108:03floor*
-rw-r--r--1alexgroup484Apr92005maptax.icn
drwxrwxr-x2alexgroup1024Sep1011:32testdir/
TheFoptioncauseslstoprintaslash(/)attheendof
directorynamesandanasterisk(*)attheendofthenamesof
executablefiles.Inthisexample,thestringthatreplacesthe
aliasll(lsl)itselfcontainsanalias(ls).Whenitreplacesan
aliaswithitsvalue,theshelllooksatthefirstwordofthe
replacementstringtoseewhetheritisanalias.Inthe
precedingexample,thereplacementstringcontainsthealiasls,
soasecondsubstitutionoccurstoproducethefinalcommand
lsFl.(Toavoidarecursiveplunge,thelsinthereplacement
text,althoughanalias,isnotexpandedasecondtime.)
Whengivenalistofaliaseswithoutthe=valueorvaluefield,
thealiasbuiltinrespondsbydisplayingthevalueofeachdefined
alias.Thealiasbuiltinreportsanerrorifanaliashasnotbeen
defined:
$aliasllllszapwx
aliasll='ls-l'
aliasl='ls-ltr'
aliasls='ls-F'
aliaszap='rm-i'
bash:alias:wx:notfound
Youcanavoidaliassubstitutionbyprecedingthealiased
commandwithabackslash(\):
$\ls
Test_EmacsXTerm.adflute.psmaptax.icn
Tigerfixtax.icnfloortestdir
Becausethereplacementofanaliasnamewiththealiasvalue
doesnotchangetherestofthecommandline,anyarguments
arestillreceivedbythecommandthatgetsexecuted:
$llf*
-rw-r--r--1alexgroup641Apr12005fixtax.icn
-rw-r--r--1alexgroup30015Mar12004flute.ps
-rwxr-xr-x1alexgroup485Oct2108:03floor*
Youcanremoveanaliaswiththeunaliasbuiltin.Whenthezap
aliasisremoved,itisnolongerdisplayedwiththealiasbuiltin
anditssubsequentuseresultsinanerrormessage:
$unaliaszap
$alias
aliasll='ls-l'
aliasl='ls-ltr'
aliasls='ls-F'
$zapmaptax.icn
bash:zap:commandnotfound
Functions
Ashellfunctionissimilartoashellscriptinthatitstoresa
seriesofcommandsforexecutionatalatertime.However,
becausetheshellstoresafunctioninthecomputer'smain
memory(RAM)insteadofinafileonthedisk,theshellcan
accessitmorequicklythantheshellcanaccessascript.The
shellalsopreprocesses(parses)afunctionsothatitstartsup
morequicklythanascript.Finallytheshellexecutesashell
functioninthesameshellthatcalledit.Ifyoudefinetoomany
functions,theoverheadofstartingasubshell(aswhenyourun
ascript)canbecomeunacceptable.
Youcandeclareashellfunctioninthe~/.bash_profilestartup
file,inthescriptthatusesit,ordirectlyfromthecommandline.
Youcanremovefunctionswiththeunsetbuiltin.Theshelldoes
notkeepfunctionsonceyoulogout.
Tip:Removingvariablesandfunctions
Ifyouhaveashellvariableandafunctionwiththe
samename,usingunsetremovestheshellvariable.If
youthenuseunsetagainwiththesamename,it
removesthefunction.
Thesyntaxthatdeclaresashellfunctionis
[function]function-name()
{
commands
}
wherethewordfunctionisoptional,function-nameisthe
nameyouusetocallthefunction,andcommandscomprise
thelistofcommandsthefunctionexecuteswhenyoucallit.
Thecommandscanbeanythingyouwouldincludeinashell
script,includingcallstootherfunctions.
Thefirstbrace({)canappearonthesamelineasthefunction
name.Aliasesandvariablesareexpandedwhenafunctionis
read,notwhenitisexecuted.Youcanusethebreakstatement
(page900)withinafunctiontoterminateitsexecution.
Shellfunctionsareusefulasashorthandaswellastodefine
specialcommands.Thefollowingfunctionstartsaprocess
namedprocessinthebackground,withtheoutputnormally
displayedbyprocessbeingsavedin.process.out:
start_process(){
process>.process.out2>&1&
}
Thenextexampleshowshowtocreateasimplefunctionthat
displaysthedate,aheader,andalistofthepeoplewhoare
usingthesystem.Thisfunctionrunsthesamecommandsas
thewhosonscriptdescribedonpage273.Inthisexamplethe
functionisbeingenteredfromthekeyboard.Thegreater-than
(>)signsaresecondaryshellprompts(PS2);donotenter
them.
$functionwhoson()
>{
>date
>echo"UsersCurrentlyLoggedOn"
>who
>}
$whoson
SunAug715:44:58PDT2005
UsersCurrentlyLoggedOn
hlsconsoleAug608:59(:0)
alexpts/4Aug609:33(0.0)
jennypts/7Aug609:23(bravo.example.com)
Functionsinstartupfiles
Ifyouwanttohavethewhosonfunctionalwaysbeavailable
withouthavingtoenteriteachtimeyoulogin,putitsdefinition
in~/.bash_profile.Thenrun.bash_profile,usingthe.(dot)
commandtoputthechangesintoeffectimmediately:
$cat~/.bash_profile
exportTERM=vt100
sttykill'^u'
whoson()
{
date
echo"UsersCurrentlyLoggedOn"
who
}
$.~/.bash_profile
Youcanspecifyargumentswhenyoucallafunction.Withinthe
functiontheseargumentsareavailableaspositionalparameters
(page920).Thefollowingexampleshowsthearg1function
enteredfromthekeyboard.
Optional
Thefollowingfunctionallowsyoutoexportvariablesusingtcshsyntax.Theenv
builtinlistsallenvironmentvariablesandtheirvaluesandverifiesthatsetenv
workedcorrectly:
$cat.bash_profile
...
#setenv-keeptcshusershappy
functionsetenv()
{
if[$#-eq2]
then
eval$1=$2
export$1
else
echo"Usage:setenvNAMEVALUE"1>&2
fi
}
$.~/.bash_profile
$setenvTCL_LIBRARY/usr/local/lib/tcl
$env|grepTCL_LIBRARY
TCL_LIBRARY=/usr/local/lib/tcl
eval
The$#specialparameter(page921)takesonthevalueofthe
numberofcommandlinearguments.Thisfunctionusestheeval
builtintoforcebashtoscanthecommand$1=$2twice.
Because$1=$2beginswithadollarsign($),theshelltreats
theentirestringasasingletokenacommand.Withvariable
substitutionperformed,thecommandnamebecomes
TCL_LIBRARY=/usr/local/lib/tcl,whichresultsinanerror.
Usingeval,asecondscanningsplitsthestringintothethree
desiredtokens,andthecorrectassignmentoccurs.
ControllingbashFeaturesandOptions
Thissectionexplainshowtocontrolbashfeaturesandoptions
usingcommandlineoptionsandthesetandshoptbuiltins.
CommandLineOptions
Twokindsofcommandlineoptionsareavailable:shortand
long.Shortoptionsconsistofahyphenfollowedbyaletter;
longoptionshavetwohyphensfollowedbymultiplecharacters.
Longoptionsmustappearbeforeshortoptionsonacommand
linethatcallsbash.Table9-12listssomecommonlyused
commandlineoptions.
Table9-12.Commandlineoptions
Option Explanation Syntax
Help Displaysausagemessage. --help
Noedit PreventsusersfromusingtheReadline
Library(page312)toeditcommandlines
inaninteractiveshell.
--noediting
Noprofile Preventsreadingthesestartupfiles(page
267):/etc/profile,~/.bash_profile,
~/.bash_login,and~/.profile.
--noprofile
Norc Preventsreadingthe~/.bashrcstartup
file(page267).Thisoptionisonby
defaultiftheshelliscalledassh.
--norc
POSIX RunsbashinPOSIXmode. --posix
Version Displaysbashversioninformationand
exits.
--version
Login Causesbashtorunasthoughitwerea
loginshell.
-l(lowercase
"l")
Shopt Runsashellwiththeoptshoptoption
(page325).A-O(uppercase"O")sets
theoption;+Ounsetsit.
[±]O[opt]
Endof
options
Onthecommandline,signalstheendof
options.Subsequenttokensaretreated
asargumentseveniftheybeginwitha
hyphen(-).
--
ShellFeatures
YoucancontrolthebehavioroftheBourneAgainShellby
turningfeaturesonandoff.Differentfeaturesusedifferent
methodstoturnfeaturesonandoff.Thesetbuiltincontrolsone
groupoffeatures,whiletheshoptbuiltincontrolsanothergroup.
Youcanalsocontrolmanyfeaturesfromthecommandlineyou
usetocallbash.
Tip:Features,options,variables?
Toavoidconfusingterminology,thisbookrefersto
thevariousshellbehaviorsthatyoucancontrolas
features.Thebashinfopagereferstothemas
"options"and"valuesofvariablescontrolling
optionalshellbehavior."
set±o:TurnsShellFeaturesOnandOff
Thesetbuiltin,whenusedwiththeoor+ooption,enables,
disables,andlistscertainbashfeatures.Forexample,the
followingcommandturnsonthenoclobberfeature(page
213):
$set-onoclobber
Youcanturnthisfeatureoff(thedefault)bygivingthe
command
$set+onoclobber
Thecommandsetowithoutanoptionlistseachofthefeatures
controlledbysetfollowedbyitsstate(onoroff).Thecommand
set+owithoutanoptionliststhesamefeaturesinaformthat
youcanuseasinputtotheshell.Table9-13listsbashfeatures.
Table9-13.bashfeature
Feature Description Syntax Alternate
syntax
allexport Automaticallyexportsallvariablesand
functionsthatyoucreateormodify
aftergivingthiscommand.
set-o
allexport
set-a
braceexpand Causesbashtoperformbrace
expansion(thedefault;page330).
set-o
braceexpand
set-B
cdspell Correctsminorspellingerrorsin
directorynamesusedasargumentsto
cd.
shopt-s
cdspell
cmdhist Savesalllinesofamultilinecommand
inthesamehistoryentry,adding
semicolonsasneeded.
shopt-s
cmdhist
dotglob Causesshellspecialcharacters
(wildcards;page221)inan
ambiguousfilereferencetomatcha
leadingperiodinafilename.By
defaultspecialcharactersdonotto
matchaleadingperiod.Youmust
alwaysspecifythefilenames.and..
explicitlybecausenopatternever
matchesthem.
shopt-s
dotglob
emacs Specifiesemacseditingmodefor
commandlineediting(thedefault;
page313).
set-oemacs
errexit Causesbashtoexitwhenasimple
command(notacontrolstructure)
fails.
set-oerrexit set-e
execfail Causesashellscripttocontinue
runningwhenitcannotfindthefile
thatisgivenasanargumenttoexec.
Bydefaultascriptterminateswhen
execcannotfindthefilethatisgiven
asitsargument.
shopt-s
execfail
expand_aliases Causesaliases(page318)tobe
expanded(bydefaultitisonfor
interactiveshellsandofffor
noninteractiveshells).
shopt-s
expand_alias
hashall Causesbashtorememberwhere
commandsithasfoundusingPATH
(page292)arelocated(default).
set-o
hashall
set-h
histappend Causesbashtoappendthehistorylist
tothefilenamedbyHISTFILE(page
302)whentheshellexits.Bydefault
bashoverwritesthisfile.
shopt-s
histappend
histexpand Causesthehistorymechanism(which
usesexclamationpoints;page306)to
work(default).Turnthisfeatureoffto
turnoffhistoryexpansion.
set-o
histexpand
set-H
history Enablecommandhistory(onby set-ohistory
default;page302).
ignoreeof Specifiesthatbashmustreceiveten
EOFcharactersbeforeitexits.Useful
onnoisydial-uplines.
set-o
ignoreeof
monitor Enablesjobcontrol(onbydefault,
page280).
set-o
monitor
set-m
nocaseglob Causesambiguousfilereferences
(page221)tomatchfilenames
withoutregardtocase(offby
default).
shopt-s
nocaseglob
noclobber Helpspreventoverwritingfiles(offby
default;page213).
set-o
noclobber
set-C
noglob Disablespathnameexpansion(offby
default;page221).
set-onoglob set-f
notify Withjobcontrol(page280)enabled,
reportstheterminationstatusof
backgroundjobsimmediately.The
defaultbehavioristodisplaythe
statusjustbeforethenextprompt.
set-onotify set-b
nounset Displaysanerrorandexitsfroma
shellscriptwhenyouuseanunset
variableinaninteractiveshell.The
defaultistodisplayanullvalueforan
unsetvariable.
set-o
nounset
set-u
nullglob Causesbashtoexpandambiguousfile
references(page221)thatdonot
matchafilenametoanullstring.By
defaultbashpassesthesefile
referenceswithoutexpandingthem.
shopt-s
nullglob
posix RunsbashinPOSIXmode. set-oposix
verbose Displayscommandlinesasbashreads
them.
set-o
verbose
set-v
vi Specifiesvieditingmodeforcommand set-ovi
lineediting(page312).
xpg_echo Causestheechobuiltintoexpand
backslashescapesequenceswithout
theneedforthe-eoption(page904).
shopt-s
xpg_echo
xtrace Turnsonshelldebugging(page890). set-oxtrace set-x
shopt:TurnsShellFeaturesOnandOff
Theshopt(shelloption)builtinenables,disables,andlistscertain
bashfeaturesthatcontrolthebehavioroftheshell.Forexample,
thefollowingcommandcausesbashtoincludefilenamesthat
beginwithaperiod(.)whenitexpandsambiguousfile
references(thesstandsforset):
$shopt-sdotglob
Youcanturnthisfeatureoff(thedefault)bygivingthe
command(theustandsforunset)
$shopt-udotglob
Theshelldisplayshowafeatureissetifyougivethenameof
thefeatureastheonlyargumenttoshopt:
$shoptdotglob
dotgloboff
Thecommandshoptwithoutanyoptionsorargumentsliststhe
featurescontrolledbyshoptandtheirstate.Thecommand
shoptswithoutanargumentliststhefeaturescontrolledby
shoptthataresetoron.Thecommandshoptuliststhe
featuresthatareunsetoroff.Table9-13listsbashfeatures.
Tip:Settingset±ofeaturesusingshopt
Youcanuseshopttoset/unsetfeaturesthatare
otherwisecontrolledbyset±o.Usetheregular
shoptsyntaxwithsoruandincludetheooption.
Forexample,thefollowingcommandturnsonthe
noclobberfeature:
$shopt-o-snoclobber
ProcessingtheCommandLine
Whetheryouareworkinginteractivelyorrunningashellscript,
bashneedstoreadacommandlinebeforeitcanstart
processingitbashalwaysreadsatleastonelinebefore
processingacommand.Somebashbuiltins,suchasifandcase,
aswellasfunctionsandquotedstrings,spanmultiplelines.
Whenbashrecognizesacommandthatcoversmorethanone
line,itreadstheentirecommandbeforeprocessingit.In
interactivesessionsbashpromptsyouwiththesecondary
prompt(PS2,>bydefault;page295)asyoutypeeachlineof
amultilinecommanduntilitrecognizestheendofthe
command:
$echo'hi
>end'
hi
end
$functionhello()
{
>echohellothere
>}
$
Afterreadingacommandline,bashapplieshistoryexpansion
andaliassubstitutiontotheline.
HistoryExpansion
"ReexecutingandEditingCommands"onpage304discusses
thecommandsyoucangivetomodifyandreexecutecommand
linesfromthehistorylist.Historyexpansionistheprocessthat
bashusestoturnahistorycommandintoanexecutable
commandline.Forexample,whenyougivethecommand!!,
historyexpansionchangesthatcommandlinesoitisthesame
asthepreviousone.Historyexpansionisturnedonbydefault
forinteractiveshells;set+ohistexpandturnsitoff.History
expansiondoesnotapplytononinteractiveshells(shellscripts).
AliasSubstitution
Aliases(page318)substituteastringforthefirstwordofa
simplecommand.Bydefaultaliasesareturnedonfor
interactiveshellsandofffornoninteractiveshells.Givethe
commandshoptuexpand_aliasestoturnaliasesoff.
ParsingandScanningtheCommandLine
Afterprocessinghistorycommandsandaliases,bashdoesnot
executethecommandimmediately.Oneofthefirstthingsthe
shelldoesistoparse(isolatestringsofcharactersin)the
commandlineintotokensorwords.Theshellthenscanseach
tokenforspecialcharactersandpatternsthatinstructtheshell
totakecertainactions.Theseactionscaninvolvesubstituting
onewordorwordsforanother.Whentheshellparsesthe
followingcommandline,itbreaksitintothreetokens(cp,
~/letter,and.):
$cp~/letter.
Afterseparatingtokensandbeforeexecutingthecommand,the
shellscansthetokensandperformscommandlineexpansion.
CommandLineExpansion
Inbothinteractiveandnoninteractiveuse,theshelltransforms
thecommandlineusingcommandlineexpansionbefore
passingthecommandlinetotheprogrambeingcalled.Youcan
useashellwithoutknowingmuchaboutcommandline
expansion,butyoucanusewhatashellhastooffertoabetter
advantagewithanunderstandingofthistopic.Thissection
coversBourneAgainShellcommandlineexpansion.
TheBourneAgainShellscanseachtokenforthevarioustypes
ofexpansionandsubstitutioninthefollowingorder.Mostof
theseprocessesexpandawordintoasingleword.Onlybrace
expansion,wordsplitting,andpathnameexpansioncanchange
thenumberofwordsinacommand(exceptfortheexpansion
ofthevariable"$@"page922).
1. Braceexpansion(page330)
2. Tildeexpansion(page331)
3. Parameterandvariableexpansion(page332)
4. Arithmeticexpansion(page332)
5. Commandsubstitution(page334)
6. Wordsplitting(page335)
7. Pathnameexpansion(page335)
8. Processsubstitution(page337)
Quoteremoval
Afterbashfinisheswiththeprecedinglist,itremovesfromthe
commandlinesinglequotationmarks,doublequotationmarks,
andbackslashesthatarenotaresultofanexpansion.This
processiscalledquoteremoval.
OrderofExpansion
Theorderinwhichbashcarriesoutthesestepsaffectsthe
interpretationofcommands.Forexample,ifyousetavariable
toavaluethatlooksliketheinstructionforoutputredirection
andthenenteracommandthatusesthevariable'svalueto
performredirection,youmightexpectbashtoredirectthe
output.
$SENDIT=">/tmp/saveit"
$echoxxx$SENDIT
xxx>/tmp/saveit
$cat/tmp/saveit
cat:/tmp/saveit:Nosuchfileordirectory
Infact,theshelldoesnotredirecttheoutputitrecognizesinput
andoutputredirectionbeforeitevaluatesvariables.Whenit
executesthecommandline,theshellchecksforredirection
and,findingnone,evaluatestheSENDITvariable.After
replacingthevariablewith>/tmp/saveit,bashpassesthe
argumentstoecho,whichdutifullycopiesitsargumentsto
standardoutput.No/tmp/saveitfileiscreated.
Thefollowingsectionsprovidemoredetaileddescriptionsofthe
stepsinvolvedincommandprocessing.Keepinmindthat
doubleandsinglequotationmarkscausetheshelltobehave
differentlywhenperformingexpansions.Doublequotation
markspermitparameterandvariableexpansionbutsuppress
othertypesofexpansion.Singlequotationmarkssuppressall
typesofexpansion.
BraceExpansion
Braceexpansion,whichoriginatedintheCShell,providesa
convenientwaytospecifyfilenameswhenpathnameexpansion
doesnotapply.Althoughbraceexpansionisalmostalwaysused
tospecifyfilenames,themechanismcanbeusedtogenerate
arbitrarystrings;theshelldoesnotattempttomatchthebrace
notationwiththenamesofexistingfiles.
Braceexpansionisturnedonininteractiveandnoninteractive
shellsbydefault;youcanturnitoffwithset+obraceexpand.
Theshellalsousesbracestoisolatevariablenames(page288).
Thefollowingexampleillustrateshowbraceexpansionworks.
Thelscommanddoesnotdisplayanyoutputbecausethereare
nofilesintheworkingdirectory.Theechobuiltindisplaysthe
stringsthattheshellgenerateswithbraceexpansion.Inthis
casethestringsdonotmatchfilenames(therearenofilesin
theworkingdirectory.)
$ls
$echochap_{one,two,three}.txt
chap_one.txtchap_two.txtchap_three.txt
Theshellexpandsthecomma-separatedstringsinsidethe
bracesintheechocommandintoaSPACE-separatedlistof
strings.Eachstringfromthelistisprependedwiththestring
chap_,calledthepreamble,andappendedwiththestring.txt,
calledthepostscript.Boththepreambleandthepostscriptare
optional.Theleft-to-rightorderofthestringswithinthebraces
ispreservedintheexpansion.Fortheshelltotreattheleftand
rightbracesspeciallyandforbraceexpansiontooccur,atleast
onecommaandnounquotedwhitespacecharactersmustbe
insidethebraces.Youcannestbraceexpansions.
Braceexpansionisusefulwhenthereisalongpreambleor
postscript.Thefollowingexamplecopiesthefourfilesmain.c,
f1.c,f2.c,andtmp.clocatedinthe/usr/local/src/C
directorytotheworkingdirectory:
$cp/usr/local/src/C/{main,f1,f2,tmp}.c.
Youcanalsousebraceexpansiontocreatedirectorieswith
relatednames:
$ls-F
file1file2file3
$mkdirvrs{A,B,C,D,E}
$ls-F
file1file2file3vrsA/vrsB/vrsC/vrsD/vrsE/
TheFoptioncauseslstodisplayaslash(/)afteradirectory
andanasterisk(*)afteranexecutablefile.
Ifyoutriedtouseanambiguousfilereferenceinsteadofbraces
tospecifythedirectories,theresultwouldbedifferent(andnot
whatyouwanted):
$rmdirvrs*
$mkdirvrs[A-E]
$ls-F
file1file2file3vrs[A-E]/
Anambiguousfilereferencematchesthenamesofexisting
files.Becauseitfoundnofilenamesmatchingvrs[AE],bash
passedtheambiguousfilereferencetomkdir,whichcreateda
directorywiththatname.Page223hasadiscussionofbrackets
inambiguousfilereferences.
TildeExpansion
Chapter6showedashorthandnotationtospecifyyourhome
directoryorthehomedirectoryofanotheruser.Thissection
providesamoredetailedexplanationoftildeexpansion.
Thetilde(~)isaspecialcharacterwhenitappearsatthestart
ofatokenonacommandline.Whenitseesatildeinthis
position,bashlooksatthefollowingstringofcharactersuptothe
firstslash(/)ortotheendofthewordifthereisnoslashasa
possibleusername.Ifthispossibleusernameisnull(thatis,if
thetildeappearsasawordbyitselforifitisimmediately
followedbyaslash),theshellsubstitutesthevalueofthe
HOMEvariableforthetilde.Thefollowingexample
demonstratesthisexpansion,wherethelastcommandcopies
thefilenamedletterfromAlex'shomedirectorytotheworking
directory:
$echo$HOME
/home/alex
$echo~
/home/alex
$echo~/letter
/home/alex/letter
$cp~/letter.
Ifthestringofcharactersfollowingthetildeformsavalid
username,theshellsubstitutesthepathofthehomedirectory
associatedwiththatusernameforthetildeandname.Ifitis
notnullandnotavalidusername,theshelldoesnotmakeany
substitution:
$echo~jenny
/home/jenny
$echo~root
/root
$echo~xx
~xx
Tildesarealsousedindirectorystackmanipulation(page282).
Inaddition,~+isasynonymforPWD(thenameofthe
workingdirectory),and~isasynonymforOLDPWD(the
nameofthepreviousworkingdirectory).
ParameterandVariableExpansion
Onacommandlineadollarsign($)thatisnotfollowedbyan
openparenthesisintroducesparameterorvariableexpansion.
Parametersincludecommandline,orpositional,parameters
(page920)andspecialparameters(page918).Variables
includeuser-createdvariables(page286)andkeyword
variables(page291).Thebashmanandinfopagesdonotmake
thisdistinction,however.
Parametersandvariablesarenotexpandediftheyareenclosed
withinsinglequotationmarksoriftheleadingdollarsignis
escaped(precededwithabackslash).Iftheyareenclosed
withindoublequotationmarks,theshellexpandsparameters
andvariables.
ArithmeticExpansion
Theshellperformsarithmeticexpansionbyevaluatingan
arithmeticexpressionandreplacingitwiththeresult.Under
bashthesyntaxforarithmeticexpansionis
$((expression))
Theshellevaluatesexpressionandreplaces$((expression))
withtheresultoftheevaluation.Thissyntaxissimilartothe
syntaxusedforcommandsubstitution[$(...)]andperformsa
parallelfunction.Youcanuse$((expression))asanargument
toacommandorinplaceofanynumericvalueonacommand
line.
Therulesforformingexpressionarethesameasthosefound
intheCprogramminglanguage;allstandardCarithmetic
operatorsareavailable(seeTable28-8onpage943).
Arithmeticinbashisdoneusingintegers.Unlessyouuse
variablesoftypeinteger(page291)oractualintegers,
however,theshellmustconvertstring-valuedvariablesto
integersforthepurposeofthearithmeticevaluation.
Youdonotneedtoprecedevariablenameswithinexpression
withadollarsign($).Inthefollowingexample,anarithmetic
expressiondetermineshowmanyyearsareleftuntilage60:
$catage_check
#!/bin/bash
echo-n"Howoldareyou?"
readage
echo"Wow,in$((60-age))years,you'llbe60!"
$age_check
Howoldareyou?55
Wow,in5years,you'llbe60!
Youdonotneedtoenclosetheexpressionwithinquotation
marksbecausebashdoesnotperformfilenameexpansiononit.
Thisfeaturemakesiteasierforyoutouseanasterisk(*)for
multiplication,asthefollowingexampleshows:
$echoThereare$((60*60*24*365))secondsinanon-leapyear.
Thereare31536000secondsinanon-leapyear.
Thenextexampleuseswc,cut,arithmeticexpansion,and
commandsubstitutiontoestimatethenumberofpages
requiredtoprintthecontentsofthefileletter.txt.Theoutput
ofthewc(wordcount)utilityusedwiththeloptionisthe
numberoflinesinthefile,incolumns1through4,followedby
aSPACEandthenameofthefile(thefirstcommandfollowing).
Thecututilitywiththec14optionextractsthefirstfour
columns.
$wc-lletter.txt
351letter.txt
$wc-lletter.txt|cut-c1-4
351
Thedollarsignandsingleparenthesisinstructtheshellto
performcommandsubstitution;thedollarsignanddouble
parenthesesindicatearithmeticexpansion:
$echo$(($(wc-lletter.txt|cut-c1-4)/66+1))
6
Theprecedingexamplesendsstandardoutputfromwcto
standardinputofcutviaapipe.Becauseofcommand
substitution,theoutputofbothcommandsreplacesthe
commandsbetweenthe$(andthematching)onthecommand
line.Arithmeticexpansionthendividesthisnumberby66,the
numberoflinesonapage.A1isaddedattheendbecausethe
integerdivisionresultsinanyremainderbeingdiscarded.
Tip:Fewerdollarsigns($)
Whenyouusevariableswithin$((and)),thedollar
signsthatprecedeindividualvariablereferencesare
optional:
$x=23y=37
$echo$((2*$x+3*$y))
157
$echo$((2*x+3*y))
157
Anotherwaytogetthesameresultwithoutusingcutisto
redirecttheinputtowcinsteadofhavingwcgetitsinputfroma
fileyounameonthecommandline.Whenyouredirectits
input,wcdoesnotdisplaythenameofthefile:
$wc-l<letter.txt
351
Itiscommonpracticetoassigntheresultofarithmetic
expansiontoavariable:
$numpages=$(($(wc-l<letter.txt)/66+1))
letbuiltin
Theletbuiltinevaluatesarithmeticexpressionsjustasthe$((
))syntaxdoes.Thefollowingcommandisequivalenttothe
precedingone:
$let"numpages=$(wc-l<letter.txt)/66+1"
ThedoublequotationmarkskeeptheSPACEs(boththoseyou
canseeandthosethatresultfromthecommandsubstitution)
fromseparatingtheexpressionintoseparateargumentstolet.
Thevalueofthelastexpressiondeterminestheexitstatusof
let.Ifthevalueofthelastexpressionis0,theexitstatusoflet
is1;otherwise,theexitstatusis0.
Youcangivemultipleargumentstoletonasinglecommand
line:
$leta=5+3b=7+2
$echo$a$b
89
Whenyourefertovariableswhendoingarithmeticexpansion
withletor$(()),theshelldoesnotrequireyoutobeginthe
variablenamewithadollarsign($).Nevertheless,itisagood
practicetodoso,asinmostplacesyoumustincludethis
symbol.
CommandSubstitution
Commandsubstitutionreplacesacommandwiththeoutputof
thatcommand.Thepreferredsyntaxforcommandsubstitution
underbashfollows:
$(command)
Underbashyoucanalsousethefollowingsyntax:
'command'
Theshellexecutescommandwithinasubshellandreplaces
command,alongwiththesurroundingpunctuation,with
standardoutputofcommand.
Inthefollowingexample,theshellexecutespwdandsubstitutes
theoutputofthecommandforthecommandandsurrounding
punctuation.Thentheshellpassestheoutputofthecommand,
whichisnowanargument,toecho,whichdisplaysit.
$echo$(pwd)
/home/alex
Thenextscriptassignstheoutputofthepwdbuiltintothe
variablewhereanddisplaysamessagecontainingthevalueof
thisvariable:
$catwhere
where=$(pwd)
echo"Youareusingthe$wheredirectory."
$where
Youareusingthe/home/jennydirectory.
Althoughitillustrateshowtoassigntheoutputofacommand
toavariable,thisexampleisnotrealistic.Youcanmoredirectly
displaytheoutputofpwdwithoutusingavariable:
$catwhere2
echo"Youareusingthe$(pwd)directory."
$where2
Youareusingthe/home/jennydirectory.
Thefollowingcommandusesfindtolocatefileswiththename
READMEinthedirectorytreewithitsrootattheworking
directory.Thislistoffilesisstandardoutputoffindandbecomes
thelistofargumentstols.
$ls-l$(find.-nameREADME-print)
Thenextcommandlineshowstheolder`command`syntax:
$ls-l`find.-nameREADME-print`
Oneadvantageofthenewersyntaxisthatitavoidstherather
arcanerulesfortokenhandling,quotationmarkhandling,and
escapedbacktickswithintheoldsyntax.Anotheradvantageof
thenewsyntaxisthatitcanbenested,unliketheoldsyntax.
Forexample,youcanproducealonglistingofallREADMEfiles
whosesizeexceedsthesizeof./READMEwiththefollowing
command:
$ls-l$(find.-nameREADME-size+$(echo$(cat./README|wc-c)c)-print)
Trygivingthiscommandaftergivingasetxcommand(page
890)toseehowbashexpandsit.IfthereisnoREADMEfile,
youjustgettheoutputoflsl.
Foradditionalscriptsthatusecommandsubstitution,seepages
886,905,and935.
Tip:$((Versus$(
Thesymbols$((constituteaseparatetoken.They
introduceanarithmeticexpression,notacommand
substitution.Thus,ifyouwanttousea
parenthesizedsubshell(page279)within$(),you
mustinsertaSPACEbetweenthe$(andthenext(.
WordSplitting
Theresultsofparameterandvariableexpansion,command
substitution,andarithmeticexpansionarecandidatesforword
splitting.UsingeachcharacterofIFS(page295)asapossible
delimiter,bashsplitsthesecandidatesintowordsortokens.If
IFSisunset,bashusesitsdefaultvalue(SPACE-TAB-NEWLINE).
IfIFSisnull,bashdoesnotsplitwords.
PathnameExpansion
Pathnameexpansion(page221),alsocalledfilename
generationorglobbing,istheprocessofinterpretingambiguous
filereferencesandsubstitutingtheappropriatelistoffilenames.
Unlessnoglob(page327)isset,theshellperformsthis
functionwhenitencountersanambiguousfilereferenceatoken
containinganyoftheunquotedcharacters*,?,[,or].Ifbash
cannotlocateanyfilesthatmatchthespecifiedpattern,the
tokenwiththeambiguousfilereferenceisleftalone.Theshell
doesnotdeletethetokenorreplaceitwithanullstringbut
ratherpassesittotheprogramasis(exceptseenullglobon
page327).
Inthefirstechocommandinthefollowingexample,theshell
expandstheambiguousfilereferencetmp*andpassesthree
tokens(tmp1,tmp2,andtmp3)toecho.Theechobuiltin
displaysthethreefilenamesitwaspassedbytheshell.Afterrm
removesthethreetmp*files,theshellfindsnofilenamesthat
matchtmp*whenittriestoexpandit.Thusitpassesthe
unexpandedstringtotheechobuiltin,whichdisplaysthestring
itwaspassed.
$ls
tmp1tmp2tmp3
$echotmp*
tmp1tmp2tmp3
$rmtmp*
$echotmp*
tmp*
Aperiodthateitherstartsapathnameorfollowsaslash(/)in
apathnamemustbematchedexplicitlyunlessyouhaveset
dotglob(page326).Theoptionnocaseglob(page327)
causesambiguousfilereferencestomatchfilenameswithout
regardtocase.
Quotationmarks
Puttingdoublequotationmarksaroundanargumentcausesthe
shelltosuppresspathnameandallotherexpansionexcept
parameterandvariableexpansion.Puttingsinglequotation
marksaroundanargumentsuppressesalltypesofexpansion.
Thesecondechocommandinthefollowingexampleshowsthe
variable$alexbetweendoublequotationmarks,whichallow
variableexpansion.Asaresulttheshellexpandsthevariableto
itsvalue:sonar.Thisexpansiondoesnotoccurinthethirdecho
command,whichusessinglequotationmarks.Becauseneither
singlenordoublequotationmarksallowpathnameexpansion,
thelasttwocommandsdisplaytheunexpandedargument
tmp*.
$echotmp*$alex
tmp1tmp2tmp3sonar
$echo"tmp*$alex"
tmp*sonar
$echo'tmp*$alex'
tmp*$alex
Theshelldistinguishesbetweenthevalueofavariableanda
referencetothevariableanddoesnotexpandambiguousfile
referencesiftheyoccurinthevalueofavariable.Asa
consequenceyoucanassigntoavariableavaluethatincludes
specialcharacters,suchasanasterisk(*).
Levelsofexpansion
Inthenextexample,theworkingdirectoryhasthreefiles
whosenamesbeginwithletter.Whenyouassignthevalue
letter*tothevariablevar,theshelldoesnotexpandthe
ambiguousfilereferencebecauseitoccursinthevalueofa
variable(intheassignmentstatementforthevariable).No
quotationmarkssurroundthestringletter*;contextalone
preventstheexpansion.Aftertheassignmentthesetbuiltin
(withthehelpofgrep)showsthevalueofvartobeletter*.
Thethreeechocommandsdemonstratethreelevelsof
expansion.When$varisquotedwithsinglequotationmarks,
theshellperformsnoexpansionandpassesthecharacterstring
$vartoecho,whichdisplaysit.Whenyouusedoublequotation
marks,theshellperformsvariableexpansiononlyand
substitutesthevalueofthevarvariableforitsname,preceded
byadollarsign.Nopathnameexpansionisperformedonthis
commandbecausedoublequotationmarkssuppressit.Inthe
finalcommand,theshell,withoutthelimitationsofquotation
marks,performsvariablesubstitutionandthenpathname
expansionbeforepassingtheargumentstoecho.
$lsletter*
letter1letter2letter3
$var=letter*
$set|grepvar
var='letter*'
$echo'$var'
$var
$echo"$var"
letter*
$echo$var
letter1letter2letter3
ProcessSubstitution
AspecialfeatureoftheBourneAgainShellistheabilityto
replacefilenameargumentswithprocesses.Anargumentwith
thesyntax<(command)causescommandtobeexecutedand
theoutputwrittentoanamedpipe(FIFO).Theshellreplaces
thatargumentwiththenameofthepipe.Ifthatargumentis
thenusedasthenameofaninputfileduringprocessing,the
outputofcommandisread.Similarlyanargumentwiththe
syntax>(command)isreplacedbythenameofapipethat
commandreadsasstandardinput.
Thefollowingexampleusessort(page133)withthem(merge,
whichworkscorrectlyonlyiftheinputfilesarealreadysorted)
optiontocombinetwowordlistsintoasinglelist.Eachwordlist
isgeneratedbyapipethatextractswordsmatchingapattern
fromafileandsortsthewordsinthatlist.
$sort-m-f<(grep"[^A-Z]..$"memo1|sort)<(grep".
ChapterSummary
Theshellisbothacommandinterpreterandaprogramming
language.Asacommandinterpreter,theshellexecutes
commandsyouenterinresponsetoitsprompt.Asa
programminglanguage,theshellexecutescommandsfromfiles
calledshellscripts.Whenyoustartashell,ittypicallyrunsone
ormorestartupfiles.
Runningashellscript
Assumingthatthefileholdingashellscriptisintheworking
directory,therearethreebasicwaystoexecutetheshellscript
fromthecommandline.
1. Typethesimplefilenameofthefilethatholdsthescript.
2. Typearelativepathname,includingthesimplefilename
precededby./.
3. Typebashfollowedbythenameofthefile.
Technique1requiresthattheworkingdirectorybeinthePATH
variable.Techniques1and2requirethatyouhaveexecuteand
readpermissionforthefileholdingthescript.Technique3
requiresthatyouhavereadpermissionforthefileholdingthe
script.
Jobcontrol
Ajobisoneormorecommandsconnectedbypipes.Youcan
bringajobrunninginthebackgroundintotheforegroundby
usingthefgbuiltin.Youcanputaforegroundjobintothe
backgroundbyusingthebgbuiltin,providedthatyoufirst
suspendthejobbypressingthesuspendkey(typically
CONTROL-Z).Usethejobsbuiltintoseewhichjobsarerunning
orsuspended.
Variables
Theshellallowsyoutodefinevariables.Youcandeclareand
initializeavariablebyassigningavaluetoit;youcanremovea
variabledeclarationbyusingunset.Variablesarelocaltoa
processunlesstheyareexportedusingtheexportbuiltinto
makethemavailabletochildprocesses.Variablesyoudeclare
arecalleduser-createdvariables.Theshellalsodefinescalled
keywordvariables.Withinashellscriptyoucanworkwiththe
commandline(positional)parametersthescriptwascalled
with.
Process
Eachprocesshasauniqueidentification(PID)numberandis
theexecutionofasingleLinuxcommand.Whenyougiveita
command,theshellforksanew(child)processtoexecutethe
command,unlessthecommandisbuiltintotheshell(page
225).Whilethechildprocessisrunning,theshellisinastate
calledsleep.Byendingacommandlinewithanampersand(&),
youcanrunachildprocessinthebackgroundandbypassthe
sleepstatesothattheshellpromptreturnsimmediatelyafter
youpressRETURN.Eachcommandinashellscriptforksa
separateprocess,eachofwhichmayinturnforkother
processes.Whenaprocessterminates,itreturnsitsexitstatus
toitsparentprocess.Anexitstatusofzerosignifiessuccess
andnonzerosignifiesfailure.
History
Thehistorymechanism,afeatureadaptedfromtheCShell,
maintainsalistofrecentlyissuedcommandlines,alsocalled
events,thatprovidesawaytoreexecutepreviouscommands
quickly.Thereareseveralwaystoworkwiththehistorylist;
oneoftheeasiestistouseacommandlineeditor.
Commandlineeditors
WhenusinganinteractiveBourneAgainShell,youcanedityour
commandlineandcommandsfromthehistoryfile,usingeither
oftheBourneAgainShell'scommandlineeditors(vi[m]or
emacs).Whenyouusethevi(m)commandlineeditor,youstartin
Inputmode,unlikethewayyounormallyentervi(m).Youcan
switchbetweenCommandandInputmodes.Theemacseditoris
modelessanddistinguishescommandsfromeditorinputby
recognizingcontrolcharactersascommands.
Aliases
Analiasisanamethattheshelltranslatesintoanothername
or(complex)command.Aliasesallowyoutodefinenew
commandsbysubstitutingastringforthefirsttokenofa
simplecommand.
Functions
Ashellfunctionisaseriesofcommandsthat,unlikeashell
script,areparsedpriortobeingstoredinmemorysothatthey
runfasterthanshellscripts.Shellscriptsareparsedatruntime
andarestoredondisk.Afunctioncanbedefinedonthe
commandlineorwithinashellscript.Ifyouwantthefunction
definitiontoremainineffectacrossloginsessions,youcan
defineitinastartupfile.Likethefunctionsofaprogramming
language,ashellfunctioniscalledbygivingitsnamefollowed
byanyarguments.
Shellfeatures
Thereareseveralwaystocustomizetheshell'sbehavior.You
canuseoptionsonthecommandlinewhenyoucallbashand
youcanusethebashsetandshoptbuiltinstoturnfeaturesonand
off.
Commandlineexpansion
Whenitprocessesacommandline,theBourneAgainShellmay
replacesomewordswithexpandedtext.Mosttypesof
commandlineexpansionareinvokedbytheappearanceofa
specialcharacterwithinaword(forexample,aleadingdollar
signdenotesavariable).SeeTable9-6onpage299foralistof
specialcharacters.Theexpansionstakeplaceinaspecificorder.
Followingthehistoryandaliasexpansions,thecommon
expansionsareparameterandvariableexpansion,command
substitution,andpathnameexpansion.Surroundingawordwith
doublequotationmarkssuppressesalltypesofexpansion
exceptparameterandvariableexpansion.Singlequotation
markssuppressalltypesofexpansion,asdoesquoting
(escaping)aspecialcharacterbyprecedingitwithabackslash.
Exercises
1.
Explainthefollowingunexpectedresult:
$whereisdate
date:/bin/date...
$echo$PATH
.:/usr/local/bin:/usr/bin:/bin
$cat>date
echo"Thisismyownversionofdate."
$date
TueMay2411:45:49PDT2005
2.
Whataretwowaysyoucanexecuteashellscriptwhenyoudonothaveexecute
accesspermissionforthefilecontainingthescript?Canyouexecuteashellscript
ifyoudonothavereadaccesspermissionforthefilecontainingthescript?
3.
WhatisthepurposeofthePATHvariable?
a. SetthePATHvariablesothatitcausestheshelltosearchthefollowing
directoriesinorder:
/usr/local/bin
/usr/bin
/bin
/usr/kerberos/bin
Thebindirectoryinyourhomedirectory
Theworkingdirectory
b. Ifthereisafilenameddoitin/usr/binandanotherfilewiththesame
nameinyour~/bin,whichonewillbeexecuted?(Assumethatyouhave
executepermissionforbothfiles.)
c. IfyourPATHvariableisnotsettosearchtheworkingdirectory,howcanyou
executeaprogramlocatedthere?
d. Whichcommandcanyouusetoaddthedirectory/usr/gamestotheendof
thelistofdirectoriesinPATH?
Assumethatyouhavemadethefollowingassignment:
$person=jenny
4. Givetheoutputofeachofthefollowingcommands:
a. echo$person
b. echo'$person'
c. echo"$person"
5.
Thefollowingshellscriptaddsentriestoafilenamedjournal-fileinyourhome
directory.Thisscripthelpsyoukeeptrackofphoneconversationsandmeetings.
$catjournal
#journal:addjournalentriestothefile
#$HOME/journal-file
file=$HOME/journal-file
date>>$file
echo-n"Enternameofpersonorgroup:"
readname
echo"$name">>$file
echo>>$file
cat>>$file
echo"----------------------------------------------------">>$file
echo>>$file
a. Whatdoyouhavetodotothescripttobeabletoexecuteit?
b. Whydoesthescriptusethereadbuiltin(page927)thefirsttimeitaccepts
inputfromtheterminalandthecatutilitythesecondtime?
6.
Assumethatthe/home/jenny/grants/bibliosand/home/jenny/biblios
directoriesexist.GiveJenny'sworkingdirectoryaftersheexecuteseachsequence
ofcommandsgiven.Explainwhathappensineachcase.
a. $pwd
/home/jenny/grants
$CDPATH=$(pwd)
$cd
$cdbiblios
b. $pwd
/home/jenny/grants
$CDPATH=$(pwd)
$cd$HOME/biblios
7. NametwowaysyoucanidentifythePIDnumberofyourloginshell.
8.
Givethefollowingcommand:
$sleep30|cat/etc/inittab
Isthereanyoutputfromsleep?Wheredoescatgetitsinputfrom?Whathasto
happenbeforetheshelldisplaysanotherprompt?
AdvancedExercises
9. Writeasequenceofcommandsorascriptthatdemonstratesthatvariable
expansionoccursbeforepathnameexpansion.
10. Writeashellscriptthatoutputsthenameoftheshellthatisexecutingit.
11.
Explainthebehaviorofthefollowingshellscript:
$catquote_demo
twoliner="Thisisline1.
Thisisline2."
echo"$twoliner"
echo$twoliner
a. Howmanyargumentsdoeseachechocommandseeinthisscript?Explain.
b. RedefinetheIFSshellvariablesothattheoutputofthesecondechoisthe
sameasthefirst.
12.
Addtheexitstatusofthepreviouscommandtoyourpromptsothatitbehaves
similarlytothefollowing:
$[0]lsxxx
ls:xxx:Nosuchfileordirectory
$[1]
13.
Thedirnameutilitytreatsitsargumentasapathnameandwritestostandardoutput
thepathprefixthatis,everythinguptobutnotincludingthelastcomponent:
$dirnamea/b/c/d
a/b/c
Ifyougivedirnameasimplefilename(no/characters)asanargument,
dirnamewritesa.tostandardoutput:
$dirnamesimple
.
Implementdirnameasabashfunction.Makesurethatitbehavessensiblywhen
givensuchargumentsas/.
14.
Implementthebasenameutility,whichwritesthelastcomponentofitspathname
argumenttostandardoutput,asabashfunction.Forexample,giventhepathname
a/b/c/d,basenamewritesdtostandardoutput:
$basenamea/b/c/d
d
15.
TheLinuxbasenameutilityhasanoptionalsecondargument.Ifyougivethe
commandbasenamepathsuffix,basenameremovesthesuffixandtheprefix
frompath:
$basenamesrc/shellfiles/prog.bash.bash
prog
$basenamesrc/shellfiles/prog.bash.c
prog.bash
Addthisfeaturetothefunctionyouwroteforexercise14.
10.NetworkingandtheInternet
INTHISCHAPTER
TypesofNetworksandHowTheyWork 345
NetworkProtocols 351
NetworkUtilities 362
ping:TestsaNetworkConnection 365
traceroute:TracesaRouteOvertheInternet 366
hostanddig:QueryInternetNameservers 368
DistributedComputing 369
Usenet 378
WWW:WorldWideWeb 381
Thecommunicationsfacilitieslinkingcomputersarecontinually
improving,allowingfasterandmoreeconomicalconnections.
Theearliestcomputerswereunconnectedstand-alonesystems.
Totransferinformationfromonesystemtoanother,youhadto
storeitinsomeform(usuallymagnetictape,papertape,or
punchcardscalledIBMorHollerithcards),carryittoa
compatiblesystem,andreaditbackin.Anotableadvance
occurredwhencomputersbegantoexchangedataoverserial
lines,althoughthetransferratewasslow(hundredsofbitsper
second).Peoplequicklyinventednewwaystotakeadvantage
ofthiscomputingpower,suchasemail,newsretrieval,and
bulletinboardservices.Withthespeedoftoday'snetworks,a
pieceofemailcancrossthecountryoreventravelhalfway
aroundtheworldinafewseconds.
Todayitwouldbedifficulttofindacomputerfacilitythatdoes
notincludeaLANtolinkitssystems.Linuxsystemsare
typicallyattachedtoanEthernet(page1031)network.Wireless
networksarealsoprevalent.Largecomputerfacilitiesusually
maintainseveralnetworks,oftenofdifferenttypes,andalmost
certainlyhaveconnectionstolargernetworks(companywideor
campuswideandbeyond).
Internet
TheInternetisalooselyadministerednetworkofnetworks(an
internetwork)thatlinkscomputersondiverseLANsaroundthe
globe.Aninternet(smalli)isagenericnetworkofnetworks
thatmaysharesomepartsincommonwiththepublicInternet.
ItistheInternetthatmakesitpossibletosendanemail
messagetoacolleaguethousandsofmilesawayandreceivea
replywithinminutes.Arelatedterm,intranet,referstothe
networkinginfrastructurewithinacompanyorotherinstitution.
Intranetsareusuallyprivate;accesstothemfromexternal
networksmaybelimitedandcarefullycontrolled,typicallyusing
firewalls(page349).
Networkservices
Overthepastdecademanynetworkserviceshaveemergedand
becomestandardized.OnLinuxandUNIXsystems,special
processescalleddaemons(page1027)supportsuchservicesby
exchangingspecializedmessageswithothersystemsoverthe
network.Severalsoftwaresystemshavebeencreatedtoallow
computerstosharefilesystemswithoneanother,makingit
appearasthoughremotefilesarestoredonlocaldisks.Sharing
remotefilesystemsallowsuserstoshareinformationwithout
knowingwherethefilesphysicallyreside,withoutmaking
unnecessarycopies,andwithoutlearninganewsetofutilities
tomanipulatethem.Becausethefilesappeartobestored
locally,youcanusestandardutilities(suchascat,vim,lpr,mv,or
theirgraphicalcounterparts)toworkwiththem.
Developershavecreatednewtoolsandextendedexistingones
totakeadvantageofhighernetworkspeedsandtoworkwithin
morecrowdednetworks.Therlogin,rsh,andtelnetutilities,which
weredesignedlongago,havelargelybeensupplantedbyssh
(secureshell,page579)inrecentyears.Thesshutilityallowsa
usertologinonorexecutecommandssecurelyonaremote
computer.Usersrelyonsuchutilitiesasscpandftptotransfer
filesfromonesystemtoanotheracrossthenetwork.
Communicationutilities,includingemailutilitiesandchat
programs(e.g.,talk,InternetRelayChat[IRC],ICQ,andinstant
messenger[IM]programs,suchasAOL'sAIMandgaim)have
becomesoprevalentthatmanypeoplewithverylittlecomputer
expertiseusethemonadailybasistokeepintouchwith
friends,family,andcolleagues.
Intranet
Anintranetisanetworkthatconnectscomputingresourcesata
school,company,orotherorganizationbut,unliketheInternet,
typicallyrestrictsaccesstointernalusers.Anintranetisvery
similartoaLAN(localareanetwork)butisbasedonInternet
technology.Anintranetcanprovidedatabase,email,andWeb
pageaccesstoalimitedgroupofpeople,regardlessoftheir
geographiclocation.
Theabilityofanintranettoconnectdissimilarmachinesisone
ofitsstrengths.Thinkofallthemachinesyoucanfindonthe
Internet:Macintoshsystems,PCsrunningdifferentversionsof
Windows,machinesrunningUNIXandLinux,andsoon.Eachof
thesemachinescancommunicateviaIP(page351),acommon
protocol.Soitiswithanintranet:Dissimilarmachinescanall
talktooneanother.
AnotherkeydifferencebetweentheInternetandanintranetis
thattheInternettransmitsonlyoneprotocolsuite:IP.In
contrast,anintranetcanbesetuptouseanumberof
protocols,suchasIP,IPX,AppleTalk,DECnet,XNS,orother
protocolsdevelopedbyvendorsovertheyears.Althoughthese
protocolscannotbetransmitteddirectlyovertheInternet,you
cansetupspecialgatewayboxesatremotesitesthattunnelor
encapsulatetheseprotocolsintoIPpacketsandthenusethe
Internettopassthem.
Youcanuseanextranet(alsocalledapartnernet)oravirtual
privatenetwork(VPN)toimprovesecurity.Theseterms
describewaystoconnectremotesitessecurelytoalocalsite,
typicallybyusingthepublicInternetasacarrierandemploying
encryptionasameansofprotectingdataintransit.
Followingaresometermsyoumaywanttobecomefamiliar
withbeforeyoureadtherestofthischapter:
ASP(page1019)hub(page1036)packet(page1047)
bridge(page1022)internet(page1037)router(page1053)
TypesofNetworksandHowTheyWork
Computerscommunicateovernetworksusinguniqueaddresses
assignedbysystemsoftware.Acomputermessage,calleda
packet,frame,ordatagram,includestheaddressofthe
destinationcomputerandthesender'sreturnaddress.The
threemostcommontypesofnetworksarebroadcast,point-to-
point,andswitched.Oncepopulartoken-basednetworks(such
asFDDIandtokenring)arerarelyseenanymore.
SpeediscriticaltotheproperfunctioningoftheInternet.Newer
specifications(cat6andcat7)arebeingstandardizedfor
1000BaseT(1gigabitpersecond,calledgigabitEthernet,or
GIG-E)andfasternetworking.Someofthenetworksthatform
thebackboneoftheInternetrunatspeedsofalmost10
gigabitspersecond(OC192)toaccommodatetheever-
increasingdemandfornetworkservices.Table10-1listssome
ofthespecificationsinusetoday.
Table10-1.Networkspecifications
Specification Speed
DS0 64kilobitspersecond
ISDN TwoDS0linesplussignaling(16kilobitspersecond)or
128kilobitspersecond
T-1 1.544megabitspersecond(24DS0lines)
T-3 43.232megabitspersecond(28T-1s)
OC3 155megabitspersecond(100T-1s)
OC12 622megabitspersecond(4OC3s)
OC48 2.5gigabitsperseconds(4OC12s)
OC192 9.6gigabitspersecond(4OC48s)
BroadcastNetworks
Onabroadcastnetwork,suchasEthernet,anyofthemany
systemsattachedtothenetworkcablecansendamessageat
anytime;eachsystemexaminestheaddressineachmessage
andrespondsonlytomessagesaddressedtoit.Aproblem
occursonabroadcastnetworkwhenmultiplesystemssend
dataatthesametime,resultinginacollisionofthemessages
onthecable.Whenmessagescollide,theycanbecomegarbled.
Thesendingsystemnoticesthegarbledmessageandresendsit
afterwaitingashortbutrandomamountoftime.Waitinga
randomamountoftimehelpspreventthosesamesystemsfrom
resendingthedataatthesamemomentandexperiencingyet
anothercollision.Theextratrafficthatresultsfromcollisions
canstrainthenetwork;ifthecollisionrategetstoohigh,
retransmissionsmayresultinmorecollisions.Ultimatelythe
networkmaybecomeunusable.
Point-to-PointNetworks
Apoint-to-pointlinkdoesnotseemlikemuchofanetwork
becauseonlytwoendpointsareinvolved.However,most
connectionstoWANs(wideareanetworks)gothroughpoint-to-
pointlinks,usingwirecable,radio,orsatellitelinks.The
advantageofapoint-to-pointlinkisitssimplicity:Becauseonly
twosystemsareinvolved,thetrafficonthelinkislimitedand
wellunderstood.Adisadvantageisthateachsystemcan
typicallybeequippedforonlyasmallnumberofsuchlinks;itis
impracticalandcostlytoestablishpoint-to-pointlinksthat
connecteachcomputertoalltherest.
Point-to-pointlinksoftenuseseriallinesandmodems.The
combinationofamodemwithapoint-to-pointlinkallowsan
isolatedsystemtoconnectinexpensivelytoalargernetwork.
Themostcommontypesofpoint-to-pointlinksaretheones
usedtoconnecttotheInternet.WhenyouuseDSL[1](digital
subscriberline),youareusingapoint-to-pointlinktoconnect
totheInternet.Seriallines,suchasT-1,T-3,ATMlinks,and
ISDN,areallpoint-to-point.Althoughitmightseemlikea
point-to-pointlink,acablemodemisbasedonbroadcast
technologyandinthatwayissimilartoEthernet.
[1]ThetermDSLincorporatesthexDSLsuiteoftechnologies,whichincludesADSL,
XDSL,SDSL,andHDSL.
SwitchedNetworks
Aswitchisadevicethatestablishesavirtualpathbetween
sourceanddestinationhostsinsuchawaythateachpath
appearstobeapoint-to-pointlink,muchlikearailroad
roundhouse.Theswitchcreatesandtearsdownvirtualpathsas
hostsseektocommunicatewitheachother.Eachhostthinksit
hasadirectpoint-to-pointpathtothehostitistalkingto.
Contrastthisapproachwithabroadcastnetwork,whereeach
hostalsoseestrafficboundforotherhosts.Theadvantageofa
switchednetworkoverapurepoint-to-pointnetworkisthat
eachhostrequiresonlyoneconnection:theconnectiontothe
switch.Usingpurepoint-to-pointconnections,eachhostmust
haveaconnectiontoeveryotherhost.Scalabilityisprovidedby
furtherlinkingswitches.
LAN:LocalAreaNetwork
Localareanetworks(LANs)areconfinedtoarelativelysmall
areaasinglecomputerfacility,building,orcampus.Todaymost
LANsrunovercopperorfiberoptic(glassorplastic)cable,but
otherwirelesstechnologies,suchasinfrared(similartomost
televisionremotecontroldevices)andradiowave(wireless,or
Wi-Fi),arebecomingmorepopular.
Ifitsdestinationaddressisnotonthelocalnetwork,apacket
mustbepassedontoanothernetworkbyarouter(page348).
Aroutermaybeageneral-purposecomputeroraspecial-
purposedeviceattachedtomultiplenetworkstoactasa
gatewayamongthem.
Ethernet
ALinuxsystemconnectedtoaLANusuallyconnectstoa
networkusingEthernet.AtypicalEthernetconnectioncan
supportdatatransferratesfrom10megabitspersecondto1
gigabitpersecond,withfurtherspeedenhancementsplanned
forthefuture.Asaresultofcomputerload,competingnetwork
traffic,andnetworkoverhead,filetransferratesonanEthernet
arealwaysslowerthanthemaximum,theoreticaltransferrate.
Cables
AnEthernetnetworktransfersdatausingcopperorfiberoptic
cableorwirelesstransmittersandreceivers.Originally,each
computerwasattachedtoathickcoaxialcable(calledthicknet)
attappointsspacedatsix-footintervalsalongthecable.The
thickcablewasawkwardtodealwith,soothersolutions,
includingathinnercoaxialcablecalledthinnet,or10Base2,
[2]weredeveloped.TodaymostEthernetconnectionsareeither
wirelessormadeoverunshieldedtwistedpair(referredtoas
UTP,Category5[cat5],Category5e[cat5e],Category6[cat
6],10BaseT,or100BaseT)wiresimilartothetypeofwireused
fortelephonelinesandserialdatacommunications.
[2]VersionsofEthernetareclassifiedasXBaseY,whereXisthedatarateinmegabits
persecond,Basemeansbaseband(asopposedtoradiofrequency),andYisthe
categoryofcabling.
Switch
AswitchedEthernetnetworkisaspecialcaseofabroadcast
networkthatworkswithanetworkswitch(orjustswitch),
whichisatypeofintelligenthub.Insteadofhavingadumb
repeater(passivehub)thatbroadcastseverypacketitreceives
outofeveryport,aswitchlearnswhichdevicesareconnected
towhichofitsports.Aswitchsortspacketsandthensendsthe
traffictoonlythemachineitisintendedfor.Aswitchalsohas
buffersforholdingandqueuingpackets.
SomeEthernetswitcheshaveenoughbandwidthto
communicatesimultaneously,infull-duplexmode,withallthe
devicesconnectedtothem.Anonswitched(hub-based)
broadcastnetworkcanruninonlyhalf-duplexmode.Full-
duplexEthernetfurtherimprovesthingsbyeliminating
collisions.Eachhostonaswitchednetworkcantransmitand
receivesimultaneouslyat10/100/1,000megabitspersecond
foraneffectivebandwidthbetweenhostsof20/200/2,000
megabitspersecond,dependingonthecapacityoftheswitch.
Wireless
Wirelessnetworksarebecomingincreasinglycommon.Theyare
foundinoffices,homes,andpublicplaces,suchasuniversities,
coffeeshops,andairports.Wirelessaccesspointsprovide
functionalitysimilartoanEthernethub.Theyallowmultiple
userstointeractviaacommonradiofrequencyspectrum.A
wireless,point-to-pointconnectionallowsyoutowanderabout
yourhomeorofficewithalaptop,usinganantennatolinktoa
LANortotheInternetviaanin-housebasestation.Linux
includesdriversformanyofthecommonwirelessboards.A
wirelessaccesspoint,orbasestation,connectsawireless
networktoawirednetworksothatnospecialprotocolis
requiredforawirelessconnection.Refertopage572andtothe
LinuxWirelessLANHOWTOat
www.hpl.hp.com/personal/Jean_Tourrilhes/Linux.
WAN:WideAreaNetwork
Awideareanetwork(WAN)coversalargegeographicarea.In
contrast,thetechnologies(suchasEthernet)usedforLANs
weredesignedtoworkoverlimiteddistancesandforacertain
numberofhostconnections.AWANmayspanlongdistances
overdedicateddatalines(leasedfromatelephonecompany)or
radioorsatellitelinks.Suchnetworksareoftenusedto
interconnectLANs.MajorInternetserviceprovidersrelyon
WANstoconnecttotheircustomerswithinacountryand
aroundtheglobe.
MAN
SomenetworksdonotfitintoeithertheLANortheWAN
designation.AMAN(metropolitanareanetwork)isanetwork
thatiscontainedinasmallergeographicarea,suchasacity.
LikeWANs,MANsaretypicallyusedtointerconnectLANs.
InternetworkingThroughGatewaysandRouters
Gateway
ALANconnectstoaWANthroughagateway,agenerictermfor
acomputeroraspecialdevicewithmultiplenetwork
connectionsthatpassesdatafromonenetworktoanother.A
gatewayconvertsthedatatrafficfromtheformatusedonthe
LANtothatusedontheWAN.Datathatcrossesthecountry
fromoneEthernettoanotheroveraWAN,forexample,is
repackagedfromtheEthernetformattoadifferentformatthat
canbeprocessedbythecommunicationsequipmentthatmakes
uptheWANbackbone.Whenitreachestheendofitsjourney
overtheWAN,thedataisconvertedbyanothergatewaytoa
formatappropriateforthereceivingnetwork.Forthemostpart,
thesedetailsareofconcernonlytothenetworkadministrators;
theenduserdoesnotneedtoknowanythingabouthowthe
datatransfertakesplace.
Router
Arouteristhemostpopularformofgateway.Routersplayan
importantroleininternetworking.Justasyoumightstudya
maptoplanyourroutewhenyouneedtodrivetoanunfamiliar
place,soacomputerneedstoknowhowtodeliveramessage
toasystemattachedtoadistantnetworkbypassingthrough
intermediarysystemsandnetworksalongtheway.Although
youmightenvisionusingagiantnetworkroadmaptochoose
theroutethatyourdatashouldfollow,astaticmapofcomputer
routesisusuallyapoorchoiceforalargenetwork.Computers
andnetworksalongtherouteyouchoosemaybeoverloadedor
down,withoutprovidingadetourforyourmessage.
Routersinsteadcommunicatedynamically,keepingeachother
informedaboutwhichroutesareopenforuse.Toextendthe
analogy,thissituationwouldbelikeheadingoutonacartrip
withoutconsultingamaptofindaroutetoyourdestination;
insteadyouheadforanearbygasstationandaskdirections.
Throughoutthejourneyyoucontinuetostopatonegasstation
afteranother,gettingdirectionsateachtofindthenextone.
Althoughitwouldtakeawhiletomakethestops,theownerof
eachgasstationwouldadviseyouofbadtraffic,closedroads,
alternativeroutes,andshortcuts.
Thestopsmadebythedataaremuchquickerthanthoseyou
wouldmakeinyourcar,buteachmessageleaveseachrouter
onapathchosenbasedonthemostcurrentinformation.Think
ofthissystemasaGPS(globalpositioningsystem)setupthat
automaticallygetsupdatesateachintersectionandtellsyou
wheretogonext,basedontrafficandhighwayconditions.
Figure10-1(nextpage)showsanexampleofhowLANsmight
besetupatthreesitesinterconnectedbyaWAN(theInternet).
Inthistypeofnetworkdiagram,EthernetLANsaredrawnas
straightlines,withdevicesattachedatrightangles;WANsare
representedasclouds,indicatingthatthedetailshavebeenleft
out;andwirelessconnectionsaredrawnaszigzaglineswith
breaks,indicatingthattheconnectionmaybeintermittent.
Figure10-1.AsliceoftheInternet
[Viewfullsizeimage]
InFigure10-1,agatewayorarouterrelaysmessagesbetween
eachLANandtheInternet.ThreeoftheroutersintheInternet
areshown(forexample,theoneclosesttoeachsite).SiteA
hasaserver,aworkstation,anetworkcomputer,andaPC
sharingasingleEthernetLAN.SiteBhasanEthernetLANthat
servesaprinterandfourLinuxworkstations.Afirewallpermits
onlycertaintraffictopassbetweentheInternetrouterandthe
site'slocalrouter.SiteChasthreeLANslinkedbyasingle
router,perhapstoreducethetrafficloadthatwouldresultifthe
LANswerecombinedortokeepworkgroupsorlocationson
separatenetworks.SiteCalsoincludesawirelessaccesspoint
thatenableswirelesscommunicationwithnearbycomputers.
Firewall
Afirewallinacarseparatestheenginecompartmentfromthe
passengercompartment,protectingthedriverandpassengers
fromenginefires,noise,andfumes.Inmuchthesameway,
computerfirewallsseparatecomputersfrommaliciousand
unwantedusers.
Afirewallpreventscertaintypesoftrafficfromenteringor
leavinganetwork.Forexample,afirewallmightpreventtraffic
fromyourIPaddressfromleavingthenetworkandprevent
anyoneexceptusersfromselecteddomainsfromusingFTPto
retrievedatafromthenetwork.Theimplementationsof
firewallsvarywidelyfromLinuxmachineswithtwointerfaces
(page1037)runningcustomsoftwaretoarouter(page1053)
withsimpleaccessliststoesoteric,vendor-suppliedfirewall
appliances.Mostlargerinstallationshaveatleastonekindof
firewallinplace.Afirewallisoftenaccompaniedbyaproxy
server/gateway(page377)thatprovidesanintermediatepoint
betweenyouandthehostyouarecommunicatingwith.
Inadditiontothefirewallsfoundinmultipurposecomputers,
firewallsarebecomingincreasinglycommoninconsumer
appliances.Forexample,theyarebuiltintocablemodems,
wirelessgateways,routers,andstand-alonedevices.
TypicallyasingleLinuxmachinewillincludeaminimalfirewall.
AsmallgroupofLinuxsystemsmayhaveaninexpensiveLinux
machinewithtwonetworkinterfacesandpacket-filtering
softwarefunctioningasadedicatedfirewall.Oneofthe
interfacesconnectstotheInternet,modems,andotheroutside
datasources.Theotherconnects,normallythroughahubor
switch,tothelocalnetwork.RefertoChapter25forinformation
oniptablesandsettingupafirewallandtoAppendixCfora
discussionofsecurity.
NetworkProtocols
Toexchangeinformationoveranetwork,computersmust
communicateusingacommonlanguage,orprotocol(page
1050).Theprotocoldeterminestheformatofmessagepackets.
ThepredominantnetworkprotocolsusedbyLinuxsystemsare
TCPandIP,[3]collectivelyreferredtoasTCP/IP(Transmission
ControlProtocolandInternetProtocol).Networkservicesthat
needhighlyreliableconnections,suchassshandscp,tendto
useTCP/IP.Anotherprotocolusedforsomesystemservicesis
UDP(UserDatagramProtocol).Networkservicesthatdonot
requireguaranteeddelivery,suchasRealAudioandRealVideo,
operatesatisfactorilywiththesimplerUDP.[4]
[3]AllreferencestoIPimplyIPv4(page1038).
[4]Voiceandvideoprotocolsaredelaysensitive,notintegritysensitive.Thehumanear
andeyeacceptandinterpolatelossinanaudioorvideostreambutcannotdealwith
variabledelay.TheguaranteeddeliverythatTCPprovidesintroducesadelayonabusy
networkwhenpacketsgetretransmitted.Thisdelayisnotacceptableforvideoandaudio
transmissions,whereaslessthan100percentintegrityisacceptable.
IP:InternetProtocol
Layeringwasintroducedtofacilitateprotocoldesign:Layers
distinguishfunctionaldifferencesbetweenadjacentprotocols.A
groupingoflayerscanbestandardizedintoaprotocolmodel.IP
hasamodelthatdistinguishesprotocollayers.TheIPmodel
differsfromtheISOseven-layerprotocolmodel(alsocalledthe
OSImodel)thatisoftenillustratedinnetworkingtextbooks.
SpecificallyIPusesthefollowingsimplifiedfive-layermodel:
1. ThefirstlayeroftheIPprotocol,calledthephysicallayer,
describesthephysicalmedium(copper,fiber,wireless)and
thedataencodingusedtotransmitsignalsonthatmedium
(pulsesoflight,electricalwaves,orradiowaves,for
instance).
2. Thesecondlayer,calledthedatalinklayer,coversmedia
accessbynetworkdevicesanddescribeshowtoputdata
intopackets,transmitthedata,andcheckitforerrors.
Ethernetisfoundatthislayer,asis802.11(page1018)
wireless.
3. Thethirdlayer,calledthenetworklayer,frequentlyusesIP
andaddressesandroutespackets.
4. Thefourthlayer,calledthetransportlayer,iswhereTCP
andUDPexist.Thislayerprovidesameansforapplications
tocommunicatewitheachother.Functionscommonly
performedbythetransportlayerincludeguaranteed
delivery,deliveryofpacketsintheorderoftheir
transmission,flowcontrol,errordetection,anderror
correction.Thetransportlayerisresponsiblefordividing
datastreamsintopackets.Inaddition,thislayerperforms
portaddressing,whichallowsittodistinguishamong
differentservicesusingthesametransportprotocol.Port
addressingkeepsthedatafrommultipleapplicationsusing
thesameprotocol(forexample,TCP)separate.
5. Anythingabovethetransportlayeristhedomainofthe
applicationandispartofthefifthlayer.UnliketheISO
model,theInternetmodeldoesnotdistinguishamong
application,presentation,andsessionlayers.Allofthe
upper-layercharacteristics,suchascharacterencoding,
encryption,andGUIs,arepartoftheapplication.
Applicationschoosethetransportcharacteristicsthey
requireaswellasthecorrespondingtransportlayerprotocol
withwhichtosendandreceivedata.
TCP:TransmissionControlProtocol
TCPismostfrequentlyrunontopofIPinacombination
referredtoasTCP/IP.Thisprotocolprovideserrorrecoveryand
guaranteeddeliveryinpackettransmissionorder;italsoworks
withmultipleportssothatitcanhandlemorethanone
application.TCPisaconnection-orientedprotocol(page1026),
alsoknownasastream-basedprotocol.Onceestablished,a
TCPconnectionlookslikeastreamofdata,notindividualIP
packets.Theconnectionisassumedtoremainupandbe
uniquelyaddressable.Everypieceofinformationyouwriteto
theconnectionalwaysgoestothesamedestinationandarrives
intheorderitwassent.BecauseTCPisconnectionorientedand
establishesavirtualcircuitbetweentwosystems,thisprotocol
isnotsuitableforone-to-manytransmissions(seethe
discussionofUDP,following).TCPhasbuiltinmechanismsfor
dealingwithcongestion(orflow)controloverbusynetworks
andthrottlesback(slowsthespeedofdataflow)whenithasto
retransmitdroppedpackets.TCPcanalsodealwith
acknowledgments,widearealinks,high-delaylinks,andother
situations.
UDP:UserDatagramProtocol
UDPrunsatlayer4oftheIPstack,justasTCPdoes,butis
muchsimpler.LikeTCP,UDPworkswithmultipleportsand
multipleapplications.Ithaschecksumsforerrordetectionbut
doesnotautomaticallyretransmitdatagrams(page1028)that
failthechecksumtest.UDPisadatagram-orientedprotocol:
Eachdatagrammustcarryitsownaddressandport
information.Eachrouteralongthewayexamineseach
datagramtodeterminethedestination,onehopatatime.You
canbroadcastormulticastUDPdatagramstomanydestinations
atthesametimebyusingspecialaddresses.
PPP:Point-to-PointProtocol
PPPprovidesseriallinepoint-to-pointconnectionsthatsupport
IP.Thisprotocolcompressesdatatomakethemostofthe
limitedbandwidthavailableonserialconnections.PPP,which
replacesSLIP[5](SerialLineIP),actsasapoint-to-pointlayer
2/3transportthatmanyothertypesofprotocolscanrideon.It
isusedmostlyforIP-basedservicesandconnections,suchas
TCPorUDP.
[5]SLIPwasoneofthefirstseriallineimplementationsofIPandhasslightlyless
overheadthanPPP.PPPsupportsmultipleprotocols(suchasAppleTalkandIPX),
whereasSLIPsupportsonlyIP.
XremoteandLBX
Twoprotocolsthatspeedupdatatransferoverseriallinesare
XremoteandLBX.XremotecompressestheXWindowSystem
protocolsothatitismoreefficientoverslowerseriallines.LBX
(low-bandwidthX)isbasedontheXremotetechnologyandis
partofXWindowSystemreleaseX11R6andhigher.
HostAddress
Eachcomputerinterfaceisidentifiedbyauniqueaddress,or
hostnumber,onitsnetwork.Asystemattachedtomorethan
onenetworkhasmultipleinterfacesoneforeachnetwork,each
withauniqueaddress.
Eachpacketofinformationthatisbroadcastoverthenetwork
hasadestinationaddress.Allhostsonthenetworkmust
processeachbroadcastpackettoseewhetheritisaddressedto
thathost.[6]Ifthepacketisaddressedtoagivenhost,that
hostcontinuestoprocessit.Ifnot,thehostignoresthepacket.
[6]Contrastbroadcastpacketswithunicastpackets:Ethernethardwareonacomputer
filtersoutunicastpacketsthatarenotaddressedtothatmachine;theoperatingsystem
onthatmachineneverseesthesepackets.
ThenetworkaddressofamachineisanIPaddress,which,
underIPv4,isrepresentedasonenumberbrokenintofour
segmentsseparatedbyperiods(forexample,192.168.184.5).
DomainnamesandIPaddressesareassignedthroughahighly
distributedsystemcoordinatedbyICANN(InternetCorporation
forAssignedNamesandNumberswww.icann.org)viamany
registrars(seewww.internic.net).ICANNisfundedbythe
variousdomainnameregistriesandregistrarsandbyIP
addressregistries,whichsupplygloballyuniqueidentifiersfor
hostsandservicesontheInternet.Althoughyoumaynotdeal
withanyoftheseagenciesdirectly,yourInternetservice
providermostassuredlydoes.
HowacompanyusesIPaddressesisdeterminedbythesystem
ornetworkadministrator.Forexample,theleftmosttwosetsof
numbersinanIPaddressmightrepresentalargenetwork
(campuswideorcompanywide);thethirdset,asubnetwork
(perhapsadepartmentorasinglefloorinabuilding);andthe
rightmostnumber,anindividualcomputer.Theoperating
systemusestheaddressinadifferent,lower-levelform,
convertingittoitsbinaryequivalent,aseriesof1sand0s.See
thefollowingoptionalsectionformoreinformation.Referto
"Privateaddressspace"onpage570forinformationabout
addressesyoucanuseonaLANwithoutregisteringthem.
StaticVersusDynamicIPAddresses
AstaticIPaddressisonethatalwaysremainsthesame.A
dynamicIPaddressisonethatcanchangeeachtimeyou
connecttothenetwork.Adynamicaddressremainsthesame
duringasingleloginsession.Anyserver(mail,Web,andsoon)
musthaveastaticaddresssoclientscanfindthemachinethat
isactingastheserver.End-usersystemsusuallyworkwellwith
dynamicaddresses.Duringagivenloginsession,theycan
functionasaclient(yourWebbrowser,forexample)because
theymaintainaconstantIPaddress.Whenyoulogoutandlog
inagain,itdoesnotmatterthatyouhaveadifferentIPaddress
becauseyourcomputer,actingasaclient,establishesanew
connectionwithaserver.Theadvantageofdynamicaddressing
isthatitallowsinactiveaddressestobereused,reducingthe
totalnumberofIPaddressesneeded.
Optional:IPClasses
TofacilitateroutingontheInternet,IPaddressesaredividedintoclasses.Theseclasses,
whicharelabeledclassAthroughclassE,allowtheInternetaddressspacetobebrokeninto
blocksofsmall,medium,andlargenetworksthataredesignedtobeassignedbasedonthe
numberofhostswithinanetwork.
Whenyouneedtosendamessagetoanaddressoutsidethelocalnetwork,yoursystem
looksuptheaddressblock/classinitsroutingtableandsendsthemessagetothenext
routeronthewaytothefinaldestination.Everyrouteralongthewaydoesasimilarlookup
andforwardsthemessageaccordingly.Atthedestination,localroutersdirectthemessage
tothespecificaddress.Withoutclassesandblocks,yourhostwouldhavetoknowevery
networkandsubnetworkaddressontheInternetbeforeitcouldsendamessage.Thissetup
wouldbeimpracticalbecauseofthehugenumberofaddressesontheInternet.
EachofthefournumbersintheIPaddressisintherange0255becauseeachsegmentof
theIPaddressisrepresentedby8bits(anoctet),witheachbitbeingcapableoftakingon
twovalues;thetotalnumberofvaluesistherefore28=256.Whenyoustartcountingat0,
therange1256becomes0255.[7]EachIPaddressisdividedintoanetaddress(netid)
portion,whichispartoftheclass,andahostaddress(hostid)portion.SeeTable10-2.
Table10-2.IPclasses
Class Start
bits Addressrange Allbits(includingstartbits)
07 815 1623 2431
ClassA 0 001.000.000.000126.000.000.000 0netid ========hostid=========
ClassB 10 129.000.000.000191.255.000.000 10-----netid------ =====hostid=====
ClassC 110 192.000.000.000223.255.255.000 110-------netid--------- =hostid=
ClassD
(multicast)
1110 224.000.000.000239.255.255.000 1110
ClassE
(reserved)
11110 240.000.000.000255.255.255.000 11110
Thefirstsetofaddresses,definingclassAnetworks,isreservedforextremelylarge
corporations,suchasGeneralElectric(3.0.0.0)andHewlett-Packard(15.0.0.0),andfor
ISPs.Onestartbit(0)inthefirstpositiondesignatesaclassAnetwork,7bitsholdsthe
networkportionoftheaddress(netid),and24bitsholdsthehostportionoftheaddress
(hostid;seeTable10-2).ThissetupmeansthatGEcanhave224,orapproximately16
million,hostsonitsnetwork.Unusedaddressspaceandsubnets(page1057)lowerthis
numberquiteabit.The127.0.0.0subnet(page359)isreserved,asareseveralothers(see
privateaddressspaceonpage1049).
Twostartbits(10)inthefirsttwopositionsdesignatesaclassBnetwork,14bitsholdsthe
networkportionoftheaddress(netid),and16bitsholdsthehostportionoftheaddress,for
apotentialtotalof65,534hosts.[8]AclassCnetworkuses3startbits(100),21netidbits
(2millionnetworks),and8hostidbits(254hosts).Todayanewlargecustomerwillnot
receiveaclassAorBnetworkbutislikelytoreceiveaclassCorseveral(usually
contiguous)classCnetworks,ifmerited.
Severalotherclassesofnetworksexist.ClassDnetworksarereservedformulticast(page
1044)networks.WhenyourunnetstatnronaLinuxsystem,youcanseewhetherthe
machineisamemberofamulticastnetwork.A224.0.0.0intheDestinationcolumnthat
netstatdisplaysindicatesaclassD,multicastaddress(Table10-2).Amulticastislikea
broadcast,butonlyhoststhatsubscribetothemulticastgroupreceivethemessage.Touse
Webterminology,abroadcastislikea"push."Ahostpushesabroadcastonthenetwork,
andeveryhostonthenetworkmustcheckeachpackettoseewhetheritcontainsrelevant
data.Amulticastislikea"pull."Ahostwillseeamulticastonlyifitregistersitselfas
subscribedtoamulticastgrouporserviceandpullstheappropriatepacketsfromthe
network.
Table10-3showssomeofthecomputationsfortheIPaddress131.204.027.027.Each
addressisshownindecimal,hexadecimal,andbinaryform.Binaryistheeasiesttowork
withforbitwise(binary)computations.ThefirstthreelinesshowtheIPaddress.Thenext
threelinesshowthesubnetmask(page1058)inthreebases.NexttheIPaddressandthe
subnetmaskareANDedtogetherbitwisetoyieldthesubnetnumber(page1058),whichis
showninthreebases.Thelastthreelinesshowthebroadcastaddress(page1022),whichis
computedbytakingthesubnetnumberandturningthehostidbitsto1s.Thesubnetnumber
identifiesthelocalnetwork.Thesubnetnumberandthesubnetmaskdeterminewhatrange
theIPaddressofthemachinemustbein.Theyarealsousedbyrouterstosegmenttraffic;
seenetworksegment(page1045).Abroadcastonthisnetworkgoestoallhostsinthe
range131.204.27.1through131.204.27.254butwillbeactedononlybyhoststhathavea
useforit.
Table10-3.ComputationsforIPaddress131.204.027.027
----------ClassB-----
--- netid hostid
131 .204 .027 .027 decimal
IPaddress 83 CC 1B 1B hexadecimal
10000011 11001100 00011011 00011011 binary
255 .255 .255 .000 decimal
Subnetmask FF FF FF 00 hexadecimal
11111111 11111111 11111111 00000000 binary
IPaddressbitwise
AND
10000011 11001100 00011011 00011011
Subnetmask 11111111 11111111 11111111 00000000 binary
=Subnetnumber 10000011 11001100 00011011 00000000
131 .204 .027 .000 decimal
Subnetnumber 83 CC 1B 00 hexadecimal
10000011 11001100 00011011 00000000 binary
131 .204 .27 .255 decimal
Broadcastaddress 83 CC 1B FF hexadecimal
(sethostbitsto1) 10000011 11001100 00011011 11111111 binary
Subnets
Eachhostonanetworkmustprocesseachbroadcastpackettodetermine
whethertheinformationinthepacketisusefultothathost.Ifthenetwork
includesnumeroushosts,eachhostmustprocessmanypackets.Tomaintain
efficiencymostnetworks,andparticularlysharedmedianetworkssuchas
Ethernetneedtobesplitintosubnetworks,orsubnets.[9]Themorehostsona
network,themoredramaticallynetworkperformanceisaffected.Organizations
userouterandswitchtechnologycalledVLANs(virtuallocalareanetworks)to
groupsimilarhostsintobroadcastdomains(subnets)basedonfunction.For
example,itisnotuncommontoseeaswitchwithdifferentportsbeingpartof
differentsubnets.Seepage423forinformationonhowtospecifyasubnet.
Asubnetmask(oraddressmask)isabitmaskthatidentifieswhichpartsofan
IPaddresscorrespondtothenetworkaddressandthesubnetportionofthe
address.Thismaskhas1sinpositionscorrespondingtothenetworkandsubnet
numbersand0sinthehostnumberpositions.WhenyouperformabitwiseAND
onanIPaddressandasubnetmask(Table10-3),theresultingaddresscontains
everythingexceptthehostaddress(hostid)portion.
Thereareseveralwaystorepresentasubnetmask:Anetworkcouldhavea
subnetmaskof255.255.255.0(decimal),FFFFFF00(hexadecimal),or/24(the
numberofbitsusedforthesubnetmask).IfitwereaclassBnetwork(ofwhich
16bitsarealreadyfixed),thisyields28(24totalbits16fixedbits=8bits,28=
256)networks[10]with282(2562=254)hosts[11]oneachnetwork.
Forexample,whenyoudividetheclassCaddress192.25.4.0intoeightsubnets,
yougetasubnetmaskof255.255.255.224,FFFFFFE0,or/27(271s).Theeight
resultantnetworksare192.25.4.0,192.25.4.32,192.25.4.64,192.25.4.96,
192.25.4.128,192.25.4.160,192.25.4.192,and192.25.4.224.Youcanusea
Web-basedsubnetmaskcalculatortocalculatesubnetmasks(referto"Network
Calculators"onpage983).Tousethiscalculatortodeterminethepreceding
subnetmask,startwithanIPhostaddressof192.25.4.0.
[9]Splittinganetworkisalsoanissuewithotherprotocols,particularlyAppleTalk.
[10]Thefirstandlastnetworksarereservedinamannersimilartothefirstandlasthosts,althoughthe
standardisflexible.Youcanconfigurerouterstoreclaimthefirstandlastnetworksinasubnet.Different
routershavedifferenttechniquesforreclaimingthesenetworks.
[11]Subtract2becausethefirstandlasthostaddressesoneverynetworkarereserved.
CIDR:ClasslessInter-DomainRouting
CIDR(pronounced"cider")allowsgroupsofaddressesthataresmallerthana
classCblocktobeassignedtoanorganizationorISPandthenfurther
subdividedandparceledout.Inaddition,ithelpstoalleviatethepotential
problemofroutingtablesonmajorInternetbackboneandpeeringdevices
becomingtoolargetomanage.
ThepoolofavailableIPv4addresseshasbeendepletedtothepointthatnoone
getsaclassAaddressanymore.Thetrendistoreclaimthesehugeaddress
blocks,ifpossible,andrecyclethemintogroupsofsmalleraddresses.Also,as
moreclassCaddressesareassigned,routingtablesontheInternetarefillingup
andcausingmemoryoverflows.Thesolutionistoaggregate[12]groupsof
addressesintoblocksandallocatethemtoISPs,whichinturnsubdividethese
blocksandallocatethemtotheircustomers.Theaddressclassdesignations(A,
B,andC)describedintheprevioussectionareusedlessoftentoday,although
youmaystillencountersubnets.Whenyourequestanaddressblock,yourISP
usuallygivesyouasmanyaddressesasyouneedandnomore.TheISP
aggregatesseveralcontiguoussmallerblocksandroutesthemtoyourlocation.
ThisaggregationisCIDR.WithoutCIDR,theInternetasweknowitwouldnot
function.
Forexample,youmightbeallocatedthe192.168.5.0/22IPaddressblock,which
couldsupport210hosts(3222=10).YourISPwouldsetitsrouterssothatany
packetsgoingtoanaddressinthatblockwouldbesenttoyournetwork.
Internally,yourownroutersmightfurthersubdividethisblockof1,024potential
hostsintosubnets,perhapsintofournetworks.Fournetworksrequirean
additionaltwobitsofaddressing(22=4).Youcouldthereforesetupyourrouter
tosupportfournetworkswiththisallocation:192.168.5.0/24,192.168.6.0/24,
192.168.7.0/24,and192.168.8.0/24.Eachofthesenetworkscouldthenhave
254hosts.CIDRletsyouarbitrarilydividenetworksandsubnetworksinto
increasinglysmallerblocksalongtheway.Eachrouterhasenoughmemoryto
keeptrackoftheaddressesitneedstodirectandaggregatestherest.
Thisschemeusesmemoryandaddressspaceefficiently.Forexample,youcould
take192.168.8.0/24andfurtherdivideitinto16networkswith14hostseach.
The16networksrequirefourmorebits(24=16),soyouwouldhave
192.168.8.0/28,192.168.8.16/28,192.168.8.32/28,andsoon,upthroughthe
lastsubnetof192.168.8.240/16,whichwouldhavethehosts192.168.8.241
through192.168.8.254.
[12]Aggregatemeanstojoin.InCIDR,theaggregateof208.178.99.124and208.178.99.125is
208.178.99.124/23(theaggregationoftwoclassCblocks).
[7]Internally,theIPaddressisrepresentedasasetoffourunsigned8-bitfieldsora32-bit
unsignednumber,dependingonhowprogramsareusingit.Themostcommonformatin
Cistorepresentitasaunionofanunsigned32-bitlonginteger,fourunsignedchars,
andtwounsignedshortintegers.
[8]A16-bit(classB)addresscanaddress216=65,536hosts,yetthepotentialnumberof
hostsistwofewerthanthatbecausethefirstandlastaddressesonanynetworkare
reserved.Inasimilarmanner,an8-bit(classC)addresscanaddressonly254hosts(28
2=254).The0hostaddress(forexample,194.16.100.0foraclassCnetworkor
131.204.0.0foraclassBnetwork)isreservedasadesignatorforthenetworkitself.
Severalolderoperatingsystemsusethisasabroadcastaddress.The255hostaddress
(forexample,194.16.100.255foraclassCnetworkor131.204.255.255foraclassB
network)isreservedastheIPbroadcastaddress.AnIPpacket(datagram)thatissentto
thisaddressisbroadcasttoallhostsonthenetwork.
Thenetidportionofasubnetdoesnothavethesamelimitations.Oftenyouaregiventhe
choiceofreservingthefirstandlastnetworksinarangeasyouwouldahostid,butthisis
rarelydoneinpractice.Moreoftenthefirstandlastnetworksinthenetidrangeprovide
moreusableaddressspace.Referto"Subnets"onpage357.
[9]Splittinganetworkisalsoanissuewithotherprotocols,particularlyAppleTalk.
[10]Thefirstandlastnetworksarereservedinamannersimilartothefirstandlasthosts,
althoughthestandardisflexible.Youcanconfigurerouterstoreclaimthefirstandlast
networksinasubnet.Differentroutershavedifferenttechniquesforreclaimingthese
networks.
[11]Subtract2becausethefirstandlasthostaddressesoneverynetworkarereserved.
[12]Aggregatemeanstojoin.InCIDR,theaggregateof208.178.99.124and
208.178.99.125is208.178.99.124/23(theaggregationoftwoclassCblocks).
Hostnames
Peoplegenerallyfinditeasiertoworkwithnamesthanwith
numbers,soLinuxprovidesseveralwaystoassociate
hostnameswithIPaddresses.Theoldestmethodistoconsulta
listofnamesandaddressesthatarestoredinthe/etc/hosts
file:
$cat/etc/hosts
127.0.0.1localhost
130.128.52.1gwexample.example.comgw-example
130.128.52.2bravo.example.combravo
130.128.52.3hurrah.example.comhurrah
130.128.52.4kudos.example.comkudos
localhost=127.0.0.1
Theaddress127.0.0.1isreservedforthespecialhostname
localhost,whichservesasahookforthesystem'snetworking
softwaretooperateonthelocalmachinewithoutgoingontoa
physicalnetwork.Thenamesoftheothersystemsareshownin
twoforms:inafullyqualifieddomainname(FQDN)formatthat
isuniqueontheInternetandasanicknamethatislocally
unique.
NIS
Asmorehostsjoinednetworks,storingthesename-to-address
mappingsinatextfileprovedtobeinefficientand
inconvenient.Thehostsfilegrewincreasinglylargerand
becameimpossibletokeepup-to-date.Tosolvethisproblem
LinuxsupportsNIS(NetworkInformationService,page373),
whichwasdevelopedforuseonSuncomputers.NISstores
informationinadatabase,makingiteasiertofindaspecific
address,butitisusefulonlyforhostinformationwithinasingle
administrativedomain.Hostsoutsidethedomaincannotaccess
theinformation.
DNS
ThesolutiontothisdilemmaisDNS(DomainNameService,
page371).DNSeffectivelyaddressestheefficiencyandupdate
issuesbyarrangingtheentirenetworknamespace(page1044)
asahierarchy.EachdomainintheDNSmanagesitsown
namespace(addressingandnameresolution),andeachdomain
caneasilyqueryforanyhostorIPaddressbyfollowingthetree
upordownthenamespaceuntilitfindstheappropriate
domain.Byprovidingahierarchicalnamingstructure,DNS
distributesnameadministrationacrosstheentireInternet.
IPv6
TheexplosivegrowthoftheInternethasuncovereddeficiencies
inthedesignofthecurrentaddressplanmostnotablythe
shortageofaddresses.Overthenextfewyears,arevised
protocol,namedIPng(IPNextGeneration),alsoknownasIPv6
(IPversion6),[13]willbephasedin.(Itmaytakelongerthe
phase-inisgoingquiteslowly.)Thisnewschemeisdesignedto
overcomethemajorlimitationsofthecurrentapproachandcan
beimplementedgraduallybecauseitiscompatiblewiththe
existingaddressusage.IPv6makesitpossibletoassignmany
moreuniqueInternetaddresses(2128,or340undecillion
[1036]).Italsosupportsmoreadvancedsecurityand
performancecontrolfeatures:
[13]IPv5referredtoanexperimentalreal-timestreamprotocolnamedSTthusthejump
fromIPv4toIPv6.
IPv6enablesautoconfiguration.WithIPv4,
autoconfigurationisavailableusingoptionalDHCP(page
431).WithIPv6,autoconfigurationismandatory,makingit
easyforhoststoconfiguretheirIPaddressesautomatically.
IPv6reserves24bitsintheheaderforadvancedservices,
suchasresourcereservationprotocols,betterbackbone
routing,andimprovedtrafficengineering.
IPv6makesmulticastprotocolsmandatoryandusesthem
extensively.InIPv4,multicast,whichimprovesscalability,is
optional.
IPv6aggregatesaddressblocksmoreefficientlybecauseof
thehugeaddressspace.Thisaggregationmakesobsolete
NAT(page1044),whichdecreasedscalabilityand
introducedprotocolissues.
IPv6providesasimplifiedpacketheaderthatallows
hardwareacceleratorstoworkbetter.
AsampleIPv6addressisfe80::a00:20ff:feff:5be2/10.Each
groupoffourhexadecimaldigitsisequivalenttoanumber
between0and65,536(164).Apairofadjacentcolonsindicates
ahexvalueof0x0000;leading0sneednotbeshown.With
eightsetsofhexadecimalgroupings,65,5368=2128addresses
arepossible.InanIPv6addressonahostwiththedefault
autoconfiguration,thefirstcharactersintheaddressarealways
fe80.Thelast64bitsholdaninterfaceIDdesignation,whichis
oftentheMACaddress(page1041)ofthesystem'sEthernet
controller.
CommunicateOveraNetwork
Manycommandsthatyoucanusetocommunicatewithother
usersonasinglecomputersystemhavebeenextendedtowork
overanetwork.Examplesofextendedutilitiesincludeelectronic
mailprograms,information-gatheringutilities(suchasfinger,
page147),andcommunicationsutilities(suchastalk).These
utilitiesareexamplesoftheUNIXphilosophy:Insteadof
creatinganew,special-purposetool,modifyanexistingone.
Manyutilitiesunderstandaconventionfortheformatof
networkaddresses:user@host(spokenas"userathost").
Whenyouusean@signinanargumenttooneofthese
utilities,theutilityinterpretsthetextthatfollowsasthename
ofaremotehost.Whenyouomitthe@sign,autilityassumes
thatyouarerequestinginformationfromorcorrespondingwith
someoneonthelocalsystem.
Thepromptsshownintheexamplesinthischapterincludethe
hostnameofthesystemyouareusing.Ifyoufrequentlyuse
morethanonesystemoveranetwork,youmayfinditdifficult
tokeeptrackofwhichsystemyouareinteractingwithatany
particularmoment.Ifyousetyourprompttoincludethe
hostnameofthecurrentsystem,itwillalwaysbeclearwhich
systemyouareusing.Toidentifythecomputeryouareusing,
runhostnameorunamen:
$hostname
kudos
Seepage293forinformationonhowyoucanchangethe
prompt.
finger:DisplaysInformationAboutRemoteUsers
Thefingerutilitydisplaysinformationaboutoneormoreusers
onasystem.Thisutilitywasdesignedforlocaluse,butwhen
networksbecamepopular,itwasobviousthatfingershouldbe
enhancedtoreachoutandcollectinformationremotely.Inthe
followingexamples,fingerdisplaysinformationaboutallusers
loggedinonthesystemnamedbravo:
[kudos]$finger@bravo
[bravo.example.com]
LoginNameTtyIdleLoginTimeOfficeOfficePhone
rootroot*11:35Oct225:00
alexAlexWatson4Oct2212:23(kudos)
alexAlexWatson519Oct2212:33(:0)
jennyJennyChen72:24Oct228:45(:0)
hlsHelenSimpson112dOct2012:23(:0)
Auser'susernameinfrontofthe@signcausesfingertodisplay
informationfromtheremotesystemforthespecifieduseronly.
Iftheremotesystemhasmultiplematchesforthatname,finger
displaystheresultsforallofthem:
[kudos]$fingeralex@bravo
[bravo.example.com]
LoginNameTtyIdleLoginTimeOfficeOfficePhone
alexAlexWatson4Oct2212:23(kudos)
alexAlexWatson519Oct2212:33(:0)
Thefingerutilityworksbyqueryingastandardnetworkservice,
thein.fingerddaemon,thatrunsonthesystembeingqueried.
AlthoughthisserviceissuppliedwithRedHatLinux,somesites
choosenottorunittominimizetheloadontheirsystems,
reducesecurityrisks,ormaintainprivacy.Whenyouusefinger
toobtaininformationaboutsomeoneatsuchasite,youwillsee
anerrormessageornothingatall.Theremotein.fingerd
daemondetermineshowmuchinformationtoshareandinwhat
format.Asaresult,thereportdisplayedforanygivensystem
maydifferfromthatshownintheprecedingexamples.
Security:Thein.fingerddaemon
Thefingerdaemon(in.fingerd)givesawaysystem
accountinformationthatcanaidamalicioususer.
Somesitesdisablefingerorrandomizeuseraccount
IDstomakeamalicioususer'sjobmoredifficult.
Disablefingerbysettingdisable=yesin
/etc/xinetd.d/fingerandrestartingxinetd.For
moreinformationreferto"ThexinetdSuperserver"
onpage425.
Theinformationforremotefingerlooksmuchthesameasit
doeswhenfingerrunsonthelocalsystem,withonedifference:
Beforedisplayingtheresults,fingerreportsthenameofthe
remotesystemthatansweredthequery(bravo,asshownin
bracketsintheprecedingexample).Thenameofthehostthat
answersmaybedifferentfromthesystemnameyouspecified
onthecommandline,dependingonhowthefingerdaemon
serviceisconfiguredontheremotesystem.Insomecases,
severalhostnamesmaybelistedifonefingerdaemoncontacts
anothertoretrievetheinformation.
SendingMailtoaRemoteUser
Givenauser'susernameonaremotesystemandthenameof
theremotesystemoritsdomain,youcanuseanemailprogram
tosendamessageoverthenetworkortheInternet,usingthe
@formofanaddress:
jenny@bravo
or
jenny@example.com
AlthoughmanyLinuxutilitiesrecognizethe@formofanetwork
address,youmayfindthatyoucanreachmoreremote
computerswithemailthanwiththeothernetworkingutilities
describedinthischapter.Thisdisparityarisesbecausetheemail
systemcandeliveramessagetoahostthatdoesnotrunIP,
eventhoughitappearstohaveanInternetaddress.The
messagemayberoutedoverthenetwork,forexample,untilit
reachesaremotesystemthathasapoint-to-point,dial-up
connectiontothedestinationsystem.Otherutilities,suchas
talk,relyonIPandoperateonlybetweennetworkedhosts.
MailingListServers
Amailinglistserver(listserv[14])allowsyoutocreateand
manageanemaillist.Anelectronicmailinglistprovidesa
meansforpeopleinterestedinaparticulartopictoparticipate
inanelectronicdiscussionandforapersontodisseminate
informationperiodicallytoapotentiallylargemailinglist.Oneof
themostpowerfulfeaturesofmostlistserversistheirabilityto
archiveemailpostingstothelist,createanarchiveindex,and
allowuserstoretrievepostingsfromthearchivebasedon
keywordsordiscussionthreads.Typicallyyoucansubscribeand
unsubscribefromthelistwithorwithouthumanintervention.
Theownerofthelistcanrestrictwhocansubscribe,
unsubscribe,andpostmessagestothelist.Popularlistservers
includeLISTSERV(www.lsoft.com),Lyris(www.lyris.com),
Majordomo(www.greatcircle.com/majordomo),Mailman
(www.list.org,page646),andListProc(www.listproc.net).Red
Hatmaintainsquiteafewmailinglistsandlistarchivesfor
thosemailinglistsatwww.redhat.com/mailman/listinfo.Use
Googletosearchonlinuxmailinglisttofindotherlists.
[14]Althoughthetermlistservissometimesusedgenericallytoincludemanydifferentlist
serverprograms,itisaspecificproductandaregisteredtrademarkofL-soft
International,Inc.:LISTSERV(formoreinformationgotowww.lsoft.com).
NetworkUtilities
Torealizethefullbenefitsofanetworkedenvironment,itmade
sensetoextendcertaintools,someofwhichhavealreadybeen
described.Theadventofnetworksalsocreatedaneedfornew
utilitiestocontrolandmonitorthem,spurringthedevelopment
ofnewtoolsthattookadvantageofnetworkspeedand
connectivity.Thissectiondescribesconceptsandutilitiesfor
systemsattachedtoanetwork.
TrustedHosts
Somecommands,suchasrcpandrsh,workonlyiftheremote
systemtrustsyourlocalcomputer(thatis,iftheremotesystem
knowsyourlocalcomputerandbelievesthatitisnotpretending
tobeanothersystem).The/etc/hosts.equivfileliststrusted
systems.Forreasonsofsecurity,theSuperuseraccountdoes
notrelyonthisfiletoidentifytrustedSuperusersfromother
systems.
Host-basedtrustislargelyobsolete.Becausetherearemany
waystocircumventtrustedhostsecurity,includingsubverting
DNSsystemsandIPspoofing(page1038),authentication
basedonIPaddressiswidelyregardedasinsecureand
obsolete.Inasmallhomogeneousnetworkofmachineswith
localDNScontrol,itcanbe"goodenough."Itsgreatereaseof
useinthesesituationsmayoutweighthesecurityconcerns.
Security:Donotshareyourloginaccount
Youcanusea.rhostsfiletoallowanotheruserto
loginasyoufromaremotesystemwithoutknowing
yourpassword.Thissetupisnotrecommended.Do
notcompromisethesecurityofyourfilesorthe
entiresystembysharingyourloginaccount.Usessh
andscpinsteadofrshandrcpwheneverpossible.
OpenSSHTools
TheOpenSSHprojectprovidesasetoftoolsthatreplacercp,
rsh,andotherswithsecureequivalents.Thesetoolsareinstalled
bydefaultinRedHatLinuxandcanbeusedasdrop-in
replacementsfortheirinsecurecounterparts.TheOpenSSHtool
suiteiscoveredindetailinChapter18.
telnet:LogsInonaRemoteSystem
YoucanusetheTELNETprotocoltointeractwitharemote
computer.Thetelnetutility,auserinterfacetothisprotocol,is
olderthansshandisnotsecure.Nevertheless,itmaywork
wheressh(page585)isnotavailable(thereismorenon-UNIX
supportforTELNETaccessthanforsshaccess).Inaddition,
manylegacydevices,suchasterminalserversandnetwork
devices,donotsupportssh.
[bravo]$telnetkudos
Trying172.19.52.2...
Connectedtokudos.example.com
Escapecharacteris'^]'.
WelcometoSuSELinux7.3(i386)-Kernel2.4.10-4GB(2).
kudoslogin:watson
Password:
Youhaveoldmailin/var/mail/watson.
Lastlogin:MonFeb2714:46:55frombravo.example.com
watson@kudos:~>
...
watson@kudos:~>logout
Connectionclosedbyforeignhost.
[bravo]$
telnetversusssh
WhenyouconnecttoaremoteUNIXorLinuxsystemusing
telnet,youarepresentedwitharegular,textuallogin:prompt.
Unlessyouspecifydifferently,thesshutilityassumesthatyour
usernameontheremotesystemmatchesthatonthelocal
system.Becausetelnetisdesignedtoworkwithnon-UNIXand
non-Linuxsystems,itmakesnosuchassumptions.
Security:telnetisnotsecure
Wheneveryouentersensitiveinformation,suchas
yourpassword,whileyouareusingtelnet,itis
transmittedincleartextandcanbereadbysomeone
whoislisteninginonthesession.
Anotherdifferencebetweenthesetwoutilitiesisthattelnet
allowsyoutoconfiguremanyspecialparameters,suchashow
RETURNsorinterruptsareprocessed.Whenusingtelnetbetween
UNIXand/orLinuxsystems,yourarelyneedtochangeany
parameters.
Whenyoudonotspecifythenameofaremotehostonthe
commandline,telnetrunsinaninteractivemode.Thefollowing
exampleisequivalenttotheprevioustelnetexample:
[bravo]$telnet
telnet>openkudos
Trying172.19.52.2...
Connectedtokudos.example.com
Escapecharacteris'^]'.
...
Beforeconnectingyoutoaremotesystem,telnettellsyouwhat
theescapecharacteris;inmostcases,itis^](where^
representstheCONTROLkey).WhenyoupressCONTROL-],you
escapetotelnet'sinteractivemode.Continuingthepreceding
example:
[kudos]$CONTROL-]
telnet>?
(displayshelpinformation)
telnet>close
Connectionclosed.
[bravo]$
Whenyouenteraquestionmarkinresponsetothetelnet>
prompt,telnetlistsitscommands.Theclosecommandendsthe
currenttelnetsession,returningyoutothelocalsystem.Toget
outoftelnet'sinteractivemodeandresumecommunicationwith
theremotesystem,pressRETURNinresponsetoaprompt.
Youcanusetelnettoaccessspecialremoteservicesatsitesthat
havechosentomakesuchservicesavailable.However,manyof
theseservices,suchastheU.S.LibraryofCongressInformation
System(LOCIS),havemovedtotheWeb.Asaconsequence,
youcannowobtainthesameinformationusingaWebbrowser.
UsingtelnettoConnecttoOtherPorts
Bydefaulttelnetconnectstoport23,whichisusedforremote
logins.However,youcanusetelnettoconnecttootherservices
byspecifyingaportnumber.Inadditiontostandardservices,
manyofthespecialremoteservicesavailableontheInternet
useunallocatedportnumbers.Forexample,youcanaccess
somemultiplayertextgames,calledMUDs(Multi-User
Dungeons,orDimensions),usingtelnettoconnecttoaspecified
port,suchas4000or8888.Unliketheportnumbersfor
standardprotocols,theseportnumberscanbepickedarbitrarily
bytheadministratorofthegame.
Whiletelnetisnolongercommonlyemployedtologinonremote
systems,itisstillusedextensivelyasadebuggingtool.This
utilityallowsyoutocommunicatedirectlywithaTCPserver.
Somestandardprotocolsaresimpleenoughthatan
experiencedusercandebugproblemsbyconnectingtoa
remoteservicedirectlyusingtelnet.Ifyouarehavingaproblem
withanetworkserver,agoodfirststepistotrytoconnecttoit
usingtelnet.
Inthefollowingexample,asystemadministratorwhois
debuggingaproblemwithemaildeliveryusestelnettoconnect
totheSMTPport(port25)onatheserveratexample.comto
seewhyitisbouncingmailfromthespammer.comdomain.
ThefirstlineofoutputindicateswhichIPaddresstelnetistrying
toconnectto.AftertelnetdisplaystheConnectedto
smtpsrv.example.commessage,theuseremulatesanSMTP
dialog,followingthestandardSMTPprotocol.Thefirstline,
whichstartswithhelo,beginsthesessionandidentifiesthe
localsystem.AftertheSMTPserverresponds,theuserentersa
linethatidentifiesthemailsenderasuser@spammer.com.
TheSMTPserver'sresponseexplainswhythemessageis
bouncing,sotheuserendsthesessionwithquit.
$telnetsmtpsrv25
Trying192.168.1.1...
Connectedtosmtpsrv.example.com.
Escapecharacteris'^]'.
heloexample.com
220smtpsrv.example.comESMTPSendmail8.13.1/8.13.1;Wed,4May200500:13:43-0500(CDT)
250smtpsrv.example.comHellodesktop.example.com[192.168.1.97],pleasedtomeetyou
mailfrom:user@spammer.com
5715.0.0Domainbannedforspamming
quit
2212.0.0smtpsrv.example.comclosingconnection
Thetelnetutilityallowsyoutouseanyprotocolyouwant,as
longasyouknowitwellenoughtotypecommandsmanually.
ftp:TransfersFilesOveraNetwork
TheFileTransferProtocol(FTP)isamethodofdownloadingfiles
fromanduploadingfilestoanothersystemusingTCP/IPovera
network.FTPisnotasecureprotocol;useitonlyfor
downloadingpublicinformationfromapublicserver.MostWeb
browserscandownloadfilesfromFTPservers.Chapter19
coversFTPclientsandservers.
ping:TestsaNetworkConnection
Theping[15]utility(http://ftp.arl.mil/~mike/ping.html)sendsan
ECHO_REQUESTpackettoaremotecomputer.Thispacket
causestheremotesystemtosendbackareply.Thisexchange
isaquickwaytoverifythataremotesystemisavailableandto
checkhowwellthenetworkisoperating,suchashowfastitis
orwhetheritisdroppingdatapackets.Thepingutilityusesthe
ICMP(InternetControlMessageProtocol)protocol.Withoutany
options,pingteststheconnectiononceperseconduntilyou
abortexecutionwithCONTROL-C.
[15]Thenamepingmimicsthesoundofasonarburstusedbysubmarinestoidentifyand
communicatewitheachother.Thewordpingalsoexpandstopacketinternetgroper.
$pingtsx-11.mit.edu
PINGtsx-11.mit.edu(18.7.14.121)56(84)bytesofdata.
64bytesfromTSX-11.MIT.EDU(18.7.14.121):icmp_seq=0ttl=45time=97.2ms
64bytesfromTSX-11.MIT.EDU(18.7.14.121):icmp_seq=1ttl=45time=96.1ms
64bytesfromTSX-11.MIT.EDU(18.7.14.121):icmp_seq=2ttl=45time=95.7ms
64bytesfromTSX-11.MIT.EDU(18.7.14.121):icmp_seq=3ttl=45time=96.3ms
CONTROL-C
---tsx-11.mit.edupingstatistics---
4packetstransmitted,4received,0%packetloss,time3001ms
rttmin/avg/max/mdev=95.755/96.361/97.202/0.653ms
Thisexampleshowsthattheremotesystemnamedtsx-
11.mit.eduisupandavailableoverthenetwork.
Bydefaultpingsendspacketscontaining64bytes(56data
bytesand8bytesofprotocolheaderinformation).Inthe
precedingexample,fourpacketsweresenttothesystemtsx-
11.mit.edubeforetheuserinterruptedpingbypressing
CONTROL-C.Thefour-partnumberinparenthesesoneachline
istheremotesystem'sIPaddress.Apacketsequencenumber
(calledicmp_seq)isalsogiven.Ifapacketisdropped,agap
occursinthesequencenumbers.Theround-triptimeislisted
last;itrepresentsthetime(inmilliseconds)thatelapsedfrom
whenthepacketwassentfromthelocalsystemtotheremote
systemuntilthereplyfromtheremotesystemwasreceivedby
thelocalsystem.Thistimeisaffectedbythedistancebetween
thetwosystems,networktraffic,andtheloadonboth
computers.Beforeitterminates,pingsummarizestheresults,
indicatinghowmanypacketsweresentandreceivedaswellas
theminimum,average,maximum,andmeandeviationround-
triptimesitmeasured.Useping6totestIPv6networks.
Tip:Whenpingcannotconnect
Ifitisunabletocontacttheremotesystem,ping
continuestryinguntilyouinterruptitwithCONTROL-
C.Asystemmaynotanswerforanyofseveral
reasons:Theremotecomputermaybedown,the
networkinterfaceorsomepartofthenetwork
betweenthesystemsmaybebroken,asoftware
failuremayhaveoccurred,ortheremotemachine
maybesetup,forreasonsofsecurity,nottoreturn
pings(trypingingwww.microsoft.comor
www.ibm.com).
traceroute:TracesaRouteOvertheInternet
ThetracerouteutilitytracestheroutethatanIPpacketfollows,
includingallintermediarypointstraversed(callednetwork
hops),toitsdestination(theargumenttotracerouteanInternet
host).Itdisplaysanumberedlistofhostnames,ifavailable,
andIPaddresses,togetherwiththeround-triptimeittookfora
packettoreacheachrouteralongthewayandan
acknowledgmenttogetback.Youcanputthisinformationto
goodusewhenyouaretryingtoidentifythelocationofa
networkbottleneck.
Thetracerouteutilityhasnoconceptofthepathfromonehostto
thenext;instead,itsimplysendsoutpacketswithincreasing
TTL(timetolive)values.TTLisanIPheaderfieldthatindicates
howmanymorehopsthepacketshouldbeallowedtomake
beforebeingdiscardedorreturned.Inthecaseofatraceroute
packet,thepacketisreturnedbythehostthathasthepacket
whentheTTLvalueiszero.Theresultisalistofhoststhatthe
packettraveledthroughtogettoitsdestination.
Thetracerouteutilitycanhelpyousolveroutingconfiguration
problemsandlocateroutingpathfailures.Whenyoucannot
reachahost,usetraceroutetodiscoverwhatpaththepacket
follows,howfaritgets,andwhatthedelayis.
Thenextexampleshowstheoutputoftraceroutewhenitfollows
aroutefromalocalcomputertowww.linux.org.Thefirstline
indicatestheIPaddressofthetarget,themaximumnumberof
hopsthatwillbetraced,andthesizeofthepacketsthatwillbe
used.EachnumberedlinecontainsthenameandIPaddressof
theintermediatedestination,followedbythetimeittakesa
packettomakeatriptothatdestinationandbackagain.The
tracerouteutilitysendsthreepacketstoeachdestination;thus
threetimesappearoneachline.Line1showsthestatistics
whenapacketissenttothelocalgateway(lessthan3
milliseconds).Lines46showthepacketbouncingaround
MountainView(California)beforeitgoestoSanJose.Between
hops13and14thepackettravelsacrosstheUnitedStates
(SanFranciscotosomewhereintheEast).Byhop18thepacket
hasfoundwww.linux.org.Thetracerouteutilitydisplays
asteriskswhenitdoesnotreceivearesponse.Eachasterisk
indicatesthattraceroutehaswaitedthreeseconds.Usetraceroute6
totestIPv6networks.
$/usr/sbin/traceroutewww.linux.org
traceroutetowww.linux.org(198.182.196.56),30hopsmax,38bytepackets
1gw.localco.com.(204.94.139.65)2.904ms2.425ms2.783ms
2covad-gw2.meer.net(209.157.140.1)19.727ms23.287ms24.783ms
3gw-mv1.meer.net(140.174.164.1)18.795ms24.973ms19.207ms
4d1-4-2.a02.mtvwca01.us.ra.verio.net(206.184.210.241)59.091msd1-10-0-0-200.a03.
mtvwca01.us.ra.verio.net(206.86.28.5)54.948ms39.485ms
5fa-11-0-0.a01.mtvwca01.us.ra.verio.net(206.184.188.1)40.182ms44.405ms49.362ms
6p1-1-0-0.a09.mtvwca01.us.ra.verio.net(205.149.170.66)78.688ms66.266ms28.003ms
7p1-12-0-0.a01.snjsca01.us.ra.verio.net(209.157.181.166)32.424ms94.337ms54.946ms
8f4-1-0.sjc0.verio.net(129.250.31.81)38.952ms63.111ms49.083ms
9sjc0.nuq0.verio.net(129.250.3.98)45.031ms43.496ms44.925ms
10mae-west1.US.CRL.NET(198.32.136.10)48.525ms66.296ms38.996ms
11t3-ames.3.sfo.us.crl.net(165.113.0.249)138.808ms78.579ms68.699ms
12E0-CRL-SFO-02-E0X0.US.CRL.NET(165.113.55.2)43.023ms51.910ms42.967ms
13sfo2-vva1.ATM.us.crl.net(165.113.0.254)135.551ms154.606ms178.632ms
14mae-east-02.ix.ai.net(192.41.177.202)158.351ms201.811ms204.560ms
15oc12-3-0-0.mae-east.ix.ai.net(205.134.161.2)202.851ms155.667ms219.116ms
16border-ai.invlogic.com(205.134.175.254)214.622ms*190.423ms
17router.invlogic.com(198.182.196.1)224.378ms235.427ms228.856ms
18www.linux.org(198.182.196.56)207.964ms178.683ms179.483ms
hostanddig:QueryInternetNameservers
ThehostutilitylooksupanIPaddressgivenaname,orvice
versa.Thefollowingexampleshowshowtousehosttolookup
thedomainnameofamachine,givenanIPaddress:
$host140.174.164.2
2.164.174.140.in-addr.arpa.domainnamepointerns.meer.net.
YoucanalsousehosttodeterminetheIPaddressofadomain
name:
$hostns.meer.net
ns.meer.net.hasaddress140.174.164.2
Thedig(domaininformationgroper)utilityqueriesDNSservers
andindividualmachinesforinformationaboutadomain.A
powerfulutility,dighasmanyfeaturesthatyoumayneveruse.
Itismorecomplexthanhost.
Chapter24onDNShasmanyexamplesoftheuseofhostand
dig.
jwhois:LooksUpInformationAboutanInternet
Site
Thejwhoisutilityreplaceswhoisandqueriesawhoisserverfor
informationaboutanInternetsite.Thisutilityreturnssite
contactandInterNICorotherregistryinformationthatcanhelp
youtrackdownthepersonwhoisresponsibleforasite:
Perhapsthatpersonissendingyouoryourcompanyspam
(page1056).ManysitesontheInternetareeasiertouseand
fasterthanjwhois.Useabrowserandsearchenginetosearch
onwhoisorgotowww.networksolutions.com/whoisor
www.ripe.net/perl/whoistogetstarted.
Whenyoudonotspecifyawhoisserver,jwhoisdefaultsto
whois.internic.net.Usethehoptiontojwhoistospecifya
differentwhoisserver.Seethejwhoisinfopageformoreoptions
andsetupinformation.
Toobtaininformationonadomainname,specifythecomplete
domainname,asinthefollowingexample:
$jwhoissobell.com
[Queryingwhois.internic.net]
[Redirectedtowhois.godaddy.com]
[Queryingwhois.godaddy.com]
[whois.godaddy.com]
ThedatacontainedinGoDaddySoftware,Inc.'sWhoIsdatabase,
...
Registrant:
SobellAssociatesInc
POBox460068
SanFrancisco,California94146-0068
UnitedStates
Registeredthrough:GoDaddy.com
DomainName:SOBELL.COM
Createdon:07-Apr-95
Expireson:08-Apr-13
LastUpdatedon:16-Jan-04
AdministrativeContact:
Sobell,Marksobell@meer.net
SobellAssociatesInc
POBOX460068
SANFRANCISCO,California94146-0068
UnitedStates
9999999999Fax--9999999999
TechnicalContact:
,hostmaster@meer.net
meer.net
pobox390804
MountainView,California94039
UnitedStates
18888446337Fax--18888446337
Domainserversinlistedorder:
NS.MEER.NET
NS2.MEER.NET
Severaltop-levelregistriesservevariousregionsoftheworld.
Youaremostlikelytousethefollowingones:
NorthAmericanregistry whois.arin.net
Europeanregistry www.ripe.net
Asia-Pacificregistry www.apnic.net
U.S.military whois.nic.mil
U.S.government www.nic.gov
DistributedComputing
Whenmanysimilarsystemsarefoundonthesamenetwork,it
isoftendesirabletosharecommonfilesandutilitiesamong
them.Forexample,asystemadministratormightchooseto
keepacopyofthesystemdocumentationononecomputer's
diskandtomakethosefilesavailabletoremotesystems.In
thiscase,thesystemadministratorconfiguresthefilessousers
whoneedtoaccesstheonlinedocumentationarenotaware
thatthefilesarestoredonaremotesystem.Thistypeofsetup,
whichisanexampleofdistributedcomputing,notonly
conservesdiskspacebutalsoallowsyoutoupdateonecentral
copyofthedocumentationratherthantrackingdownand
updatingcopiesscatteredthroughoutthenetworkonmany
differentsystems.
Figure10-2illustratesafileserverthatstoresthesystem
manualpagesandusers'homedirectories.Withthis
arrangement,auser'sfilesarealwaysavailabletothatuserno
matterwhichsystemtheuserlogsinon.Eachsystem'sdisk
mightcontainadirectorytoholdtemporaryfilesaswellasa
copyoftheoperatingsystem.Chapter22containsinstructions
forsettingupNFSclientsandserversinnetworked
configurations.
Figure10-2.Afileserver
TheClient/ServerModel
Mainframemodel
Theclient/servermodelwasnotthefirstcomputationalmodel.
Firstcamethemainframe,whichfollowsaone-machine-does-
it-allmodel.Thatis,alltheintelligenceresidesinonesystem,
includingthedataandtheprogramthatmanipulatesand
reportsonthedata.Usersconnecttoamainframeusing
terminals.
File-sharingmodel
WiththeintroductionofPCs,file-sharingnetworksbecame
available.Inthisschemedataisdownloadedfromashared
locationtoauser'sPC,whereaprogramthenmanipulatesthe
data.Thefile-sharingmodelranintoproblemsasnetworks
expandedandmoreusersneededaccesstothedata.
Client/servermodel
Intheclient/servermodel,aclientusesaprotocol,suchasFTP,
torequestservices,andaserverprovidestheservicesthatthe
clientrequests.Ratherthanprovidingdatafilesasthefile-
sharingmodeldoes,theserverinaclient/serverrelationshipis
adatabasethatprovidesonlythosepiecesofinformationthat
theclientneedsorrequests.
Theclient/servermodeldominatesUNIXandLinuxsystem
networkingandunderliesmostofthenetworkservices
describedinthisbook.FTP,NFS,DNS,email,andHTTP(the
Webbrowsingprotocol)allrelyontheclient/servermodel.
Someservers,suchasWebserversandbrowserclients,are
designedtointeractwithspecificutilities.Otherservers,such
asthosesupportingDNS,communicatewithoneanother,in
additiontoansweringqueriesfromavarietyofclients.Clients
andserverscanresideonthesameordifferentsystems
runningthesameordifferentoperatingsystems.Thesystems
canbeproximateorthousandsofmilesapart.Asystemthatis
aservertoonesystemcanturnaroundandactasaclientto
another.Aservercanresideonasinglesystemor,asisthe
casewithDNS,bedistributedamongthousandsof
geographicallyseparatedsystemsrunningmanydifferent
operatingsystems.
Peer-to-peermodel
Thepeer-to-peer(PTP)model,inwhicheitherprogramcan
initiateatransaction,standsincontrasttotheclient/server
model.PTPprotocolsarecommononsmallnetworks.For
example,Microsoft'sNetworkNeighborhoodandApple's
AppleTalkbothrelyonbroadcast-basedPTPprotocolsfor
browsingandautomaticconfiguration.TheZeroconfmulticast
DNSprotocolisaPTPalternativeDNSforsmallnetworks.The
highest-profilePTPnetworksarethoseusedforfilesharing,
suchasKazaaandGNUtella.Manyofthesenetworksarenot
purePTPtopologies.PurePTPnetworksdonotscalewell,so
networkssuchasNapsterandKazaaemployahybridapproach.
DNS:DomainNameService
DNSisadistributedservice:Nameserversonthousandsof
machinesaroundtheworldcooperatetokeepthedatabaseup-
to-date.Thedatabaseitself,whichmapshundredsofthousands
ofalphanumerichostnamestonumericIPaddresses,doesnot
existinoneplace.Thatis,nosystemhasacompletecopyof
thedatabase.Instead,eachsystemthatrunsDNSknowswhich
hostsarelocaltothatsiteandunderstandshowtocontact
othernameserverstolearnaboutother,nonlocalhosts.
LiketheLinuxfilesystem,DNSisorganizedhierarchically.Each
countryhasanISO(InternationalOrganizationfor
Standardization)countrycodedesignationasitsdomainname.
(Forexample,AUrepresentsAustralia,ILisIsrael,andJPis
Japan;seewww.iana.org/cctld/cctld.htmforacompletelist.)
AlthoughtheUnitedStatesisrepresentedinthesameway
(US)andusesthestandardtwo-letterPostalService
abbreviationstoidentifythenextlevelofthedomain,only
governmentsandafeworganizationsusethesecodes.Schools
intheUSdomainarerepresentedbyathird-(andsometimes
second-)leveldomain:k12.Forexample,thedomainnamefor
MyschoolinNewYorkstatecouldbewww.myschool.k12.ny.us.
Followingisalistofthesixoriginaltop-leveldomains.These
domainsareusedextensivelywithintheUnitedStatesand,toa
lesserdegree,byusersinothercountries:
COM Commercialenterprises
EDU Educationalinstitutions
GOV Nonmilitarygovernment
agencies
MIL Militarygovernment
agencies
NET Networkingorganizations
ORG Other(oftennonprofit)
organizations
Asthisbookwasbeingwritten,thefollowingadditionaltop-
leveldomainshadbeenapprovedforuse:
AERO Air-transportindustry
BIZ Business
COOP Cooperatives
INFO Unrestricteduse
MUSEUM Museums
NAME Nameregistries
LikeInternetaddresses,domainnameswereonceassignedby
theNetworkInformationCenter(NIC,page353);nowtheyare
assignedbyseveralcompanies.Asystem'sfullname,referred
toasitsfullyqualifieddomainname(FQDN),isunambiguousin
thewaythatasimplehostnamecannotbe.Thesystem
okeeffe.berkeley.eduattheUniversityofCaliforniaat
Berkeley(Figure10-3)isnotthesameasonenamed
okeeffe.moma.org,whichmightrepresentahostatthe
MuseumofModernArt.Thedomainnamenotonlytellsyou
somethingaboutwherethesystemislocatedbutalsoadds
enoughdiversitytothenamespacetoavoidconfusionwhen
differentsiteschoosesimilarnamesfortheirsystems.
Figure10-3.U.S.top-leveldomains
Unlikethefilesystemhierarchy,thetop-leveldomainname
appearslast(readingfromlefttoright).Also,domainnames
arenotcasesensitive,sothenamesokeeffe.berkeley.edu,
okeeffe.Berkeley.edu,andokeeffe.Berkeley.EDUreferto
thesamecomputer.Onceadomainhasbeenassigned,the
localsiteisfreetoextendthehierarchytomeetlocalneeds.
WithDNS,emailaddressedtouser@example.comcanbe
deliveredtothecomputernamedexample.comthathandles
thecorporatemailandknowshowtoforwardmessagestouser
mailboxesonindividualmachines.Asthecompanygrows,its
siteadministratormightdecidetocreateorganizationalor
geographicalsubdomains.Thenamedelta.ca.example.com
mightrefertoasystemthatsupportsCaliforniaoffices,for
example,whilealpha.co.example.comisdedicatedto
Colorado.Functionalsubdomainsmightbeanotherchoice,with
delta.sales.example.comandalpha.dev.example.com
representingthesalesanddevelopmentdivisions,respectively.
BIND
OnLinuxsystems,themostcommoninterfacetotheDNSis
BIND(BerkeleyInternetNameDomain).BINDfollowsthe
client/servermodel.Onanygivenlocalnetwork,oneormore
systemsmayberunninganameserver,supportingallthelocal
hostsasclients.Whenitwantstosendamessagetoanother
host,asystemqueriesthenearestnameservertolearnthe
remotehost'sIPaddress.Theclient,calledaresolver,maybea
processrunningonthesamecomputerasthenameserver,orit
maypasstherequestoverthenetworktoreachaserver.To
reducenetworktrafficandfacilitatenamelookups,thelocal
nameservermaintainssomeknowledgeofdistanthosts.Ifthe
localservermustcontactaremoteservertopickupan
address,whentheanswercomesback,thelocalserveradds
thataddresstoitsinternaltableandreusesitforawhile.The
nameserverdeletesthenonlocalinformationbeforeitcan
becomeoutdated.Referto"TTL"onpage1060.
Thesystem'stranslationofsymbolichostnamesintoaddresses
istransparenttomostusers;onlythesystemadministratorofa
networkedsystemneedstobeconcernedwiththedetailsof
nameresolution.SystemsthatuseDNSfornameresolutionare
generallycapableofcommunicatingwiththegreatestnumber
ofhostsmorethanwouldbepracticaltomaintainina
/etc/hostsfileorprivateNISdatabase.Chapter24covers
settingupandrunningaDNSserver.
Threecommonsourcesarereferencedforhostnameresolution:
NIS,DNS,andsystemfiles(suchas/etc/hosts).Linuxdoes
notaskyoutochooseamongthesesources;rather,the
nsswitch.conffile(page435)allowsyoutochooseanyof
thesesources,inanycombination,andinanyorder.
Ports
Portsarelogicalchannelsonanetworkinterfaceandare
numberedfrom1to65,535.Eachnetworkconnectionis
uniquelyidentifiedbytheIPaddressandportnumberofeach
endpoint.
Inasystemthathasmanynetworkconnectionsopen
simultaneously,theuseofportskeepspackets(page1047)
flowingtoandfromtheappropriateprograms.Aprogramthat
needstoreceivedatabindstoaportandthenusesthatportfor
communication.
Privilegedports
Servicesareassociatedwithspecificports,generallywith
numberslessthan1024.Theseportsarecalledprivileged(or
reserved)ports.Forsecurityreasons,onlyrootcanbindto
privilegedports.Aservicerunonaprivilegedportprovides
assurancethattheserviceisbeingprovidedbysomeonewith
authorityoverthesystem,withtheexceptionthatanyuseron
Windows98andearlierWindowssystemscanbindtoanyport.
Commonlyusedportsinclude22(SSH),23(TELNET),80
(HTTP),111(SunRPC),and201208(AppleTalk).
NIS:NetworkInformationService
NIS(NetworkInformationService)simplifiesthemaintenance
offrequentlyusedadministrativefilesbykeepingthemina
centraldatabaseandhavingclientscontactthedatabaseserver
toretrieveinformationfromthedatabase.JustasDNS
addressestheproblemofkeepingmultiplecopiesofhostsfiles
up-to-date,NISdealswiththeissueofkeepingsystem-
independentconfigurationfiles(suchas/etc/passwd)
current.RefertoChapter21forcoverageofNIS.
NFS:NetworkFilesystem
TheNFS(NetworkFilesystem)protocolallowsaservertoshare
selectedlocaldirectoryhierarchieswithclientsystemsona
heterogeneousnetwork.Filesontheremotefileserverappear
asiftheyarepresentonthelocalsystem.NFSiscoveredin
Chapter22.
Optional:InternetServices
LinuxInternetservicesareprovidedbydaemonsthatruncontinuouslyorbya
daemonthatisstartedautomaticallybythexinetddaemon(page376)whena
servicerequestcomesin.The/etc/servicesfilelistsnetworkservices(for
example,telnet,ftp,andssh)andtheirassociatednumbers.Anyservicethat
usesTCP/IPorUDP/IPhasanentryinthisfile.IANA(InternetAssigned
NumbersAuthority)maintainsadatabaseofallpermanent,registeredservices.
The/etc/servicesfileusuallylistsasmall,commonlyusedsubsetofservices.
Visitwww.rfc.net/rfc1700.htmlformoreinformationandacompletelistof
registeredservices.
Mostofthedaemons(theexecutablefiles)arestoredin/usr/sbin.By
conventionthenamesofmanydaemonsendwiththeletterdtodistinguish
themfromutilities(onecommondaemonwhosenamedoesnotendindis
sendmail).Theprefixin.orrpc.isoftenusedfordaemonnames.Lookat
/usr/sbin/*dtoseealistofmanyofthedaemonprogramsonthelocal
system.Referto"InitScripts:StartandStopSystemServices"onpage404and
"service:ConfiguresServicesI"onpage406forinformationaboutstartingand
stoppingthesedaemons.
Toseehowadaemonworks,considerwhathappenswhenyourunssh.Thelocal
systemcontactsthesshdaemon(sshd)ontheremotesystemtoestablisha
connection.Thetwosystemsnegotiatetheconnectionaccordingtoafixed
protocol.Eachsystemidentifiesitselftotheother,andthentheytaketurns
askingeachotherspecificquestionsandwaitingforvalidreplies.Eachnetwork
servicefollowsitsownprotocol.
Inadditiontothedaemonsthatsupporttheutilitiesdescribeduptothispoint,
manyotherdaemonssupportsystem-levelnetworkservicesthatyouwillnot
typicallyinteractwith.Table10-4listssomeofthesedaemons.
Table10-4.Commondaemons
Daemon Usedfororby Function
acpid Advanced
configurationand
powerinterface
Flexibledaemonfordelivering
ACPIevents.Replacesapmd.
apmd Advancedpower
management
Reportsandtakesactionon
specifiedchangesinsystempower,
includingshutdowns.Usefulwith
machines,suchaslaptops,that
runonbatteries.
atd at Executesacommandonceata
specifictimeanddate.Seecrond
forperiodicexecutionofa
command.
automount Automaticmounting Automaticallymountsfilesystems
whentheyareaccessed.
Automaticmountingisawayof
demand-mountingremote
directorieswithouthavingtohard-
configuretheminto/etc/fstab.
crond cron Usedforperiodicexecutionof
tasks.Thisdaemonlooksinthe
/var/spool/crondirectoryfor
fileswithfilenamesthat
correspondtousers'usernames.It
alsolooksatthe/etc/crontab
fileandatfilesinthe/etc/cron.d
directory.Whenataskcomesup
forexecution,crondexecutesit
astheuserwhoownsthefilethat
describesthetask.
dhcpcd DHCP DHCPclientdaemon(page432).
dhcpd DHCP AssignsInternetaddress,subnet
mask,defaultgateway,DNS,and
otherinformationtohosts.This
protocolanswersDHCPrequests
and,optionally,BOOTPrequests.
Referto"DHCP:ConfiguresHosts"
onpage431.
ftpd FTP HandlesFTPrequests.Referto"ftp:
TransfersFilesoveraNetwork"on
page365.Seealsovsftpd(page
601).Launchedbyxinetd.
gpm General-purpose
mouseorGNUpaste
manager
Allowsyoutouseamousetocut
andpastetextonconsole
applications.
httpd HTTP TheWebserverdaemon(Apache,
page785).
in.fingerd finger Handlesrequestsforuser
informationfromthefingerutility.
Launchedbyxinetd.
inetd Deprecatedinfavorofxinetd.
lpd Lineprinterspooler
daemon
Launchedbyxinetdwhenprinting
requestscometothemachine.
NotusedwithCUPS.
named DNS SupportsDNS(page719).
nfsd,statd,
lockd,
mountd,
rquotad
NFS Thesefivedaemonsoperate
togethertohandleNFS(page673)
operations.Thenfsddaemon
handlesfileanddirectory
requests.Thestatdandlockd
daemonsimplementnetworkfile
andrecordlocking.Themountd
daemonconvertsfilesystemname
requestsfromthemountutility
intoNFShandlesandchecks
accesspermissions.Ifdiskquotas
areenabled,rquotadhandles
those.
ntpd NTP Synchronizestimeonnetwork
computers.Requiresa
/etc/ntp.conffile.Formore
informationgotowww.ntp.org.
portmap RPC MapsincomingrequestsforRPC
servicenumberstoTCPorUDP
portnumbersonthelocalsystem.
Referto"RPCNetworkServices"
onpage377.
pppd PPP Foramodem,thisprotocol
controlsthepseudointerface
representedbytheIPconnection
betweenthelocalcomputeranda
remotecomputer.Referto"PPP:
Point-to-PointProtocol"onpage
353.
rexecd rexec Allowsaremoteuserwithavalid
usernameandpasswordtorun
programsonasystem.Itsuseis
generallydeprecatedforsecurity
reasons;certainprograms,such
asPC-basedXservers,maystill
haveitasanoption.Launchedby
xinetd.
routed Routingtables Managestheroutingtablesso
yoursystemknowswheretosend
messagesthataredestinedfor
remotenetworks.Ifyoursystem
doesnothavea
/etc/defaultrouterfile,routed
isstartedautomaticallytolistento
incomingroutingmessagesandto
advertiseoutgoingroutestoother
systemsonthelocalnetwork.A
newerdaemon,thegateway
daemon(gated),offersenhanced
configurabilityandsupportfor
moreroutingprotocolsandis
proportionallymorecomplex.
sendmail Mailprograms Thesendmaildaemoncamefrom
BerkeleyUNIXandhasbeen
availableforalongtime.Thede
factomailtransferprogramonthe
Internet,thesendmaildaemon
alwayslistensonport25for
incomingmailconnectionsand
thencallsalocaldeliveryagent,
suchas/bin/mail.Mailuser
agents,suchasKMailand
Thunderbird,typicallyuse
sendmailtodelivermail
messages.
smbd,nmbd Samba AllowWindowsPCstosharefiles
andprinterswithUNIXandLinux
computers(page695).
sshd ssh,scp Enablessecureloginsbetween
remotesystems(page591).
syslogd Systemlog Transcribesimportantsystem
eventsandstorestheminfiles
and/orforwardsthemtousersor
anotherhostrunningthesyslogd
daemon.Thisdaemonis
configuredwith/etc/syslog.conf
andusedwiththesyslogutility.See
page562.
talkd talk Allowsyoutohaveaconversation
withanotheruseronthesameor
aremotemachine.Thetalkd
daemonhandlestheconnections
betweenthemachines.Thetalk
utilityoneachsystemcontactsthe
talkddaemonontheother
systemforabidirectional
conversation.Launchedbyxinetd.
telnetd TELNET OneoftheoriginalInternet
remoteaccessprotocols(page
363).Launchedbyxinetd.
tftpd TFTP Usedtobootasystemorget
informationfromanetwork.
Examplesincludenetwork
computers,routers,andsome
printers.Launchedbyxinetd.
timed Timeserver OnaLANsynchronizestimewith
othercomputersthatarealso
runningtimed.
xinetd Internetsuperserver Listensforservicerequestson
networkconnectionsandstartsup
theappropriatedaemonto
respondtoanyparticularrequest.
Becauseofxinetd,asystemdoes
notneedthedaemonsrunning
continuallytohandlevarious
networkrequests.Formore
informationreferto"Thexinetd
Superserver"onpage425.
ProxyServers
Aproxyisanetworkservicethatisauthorizedtoactforasystemwhilenot
beingpartofthatsystem.Aproxyserverorproxygatewayprovidesproxy
services;itisatransparentintermediary,relayingcommunicationsbackand
forthbetweenanapplication,suchasabrowserandaserver,usuallyoutsideof
aLANandfrequentlyontheInternet.Whenmorethanoneprocessusesthe
proxygateway/server,theproxymustkeeptrackofwhichprocessesare
connectingtowhichhosts/serverssothatitcanroutethereturnmessagesto
theproperprocess.ThemostcommonlyencounteredproxiesareemailandWeb
proxies.
Aproxyserver/gatewayinsulatesthelocalcomputerfromallothercomputersor
fromspecifieddomainsbyusingatleasttwoIPaddresses:onetocommunicate
withthelocalcomputerandonetocommunicatewithaserver.Theproxy
server/gatewayexaminesandchangestheheaderinformationonallpacketsit
handlessothatitcanencode,route,anddecodethemproperly.Thedifference
betweenaproxygatewayandaproxyserveristhattheproxyserverusually
includescache(page1023)tostorefrequentlyusedWebpagessothatthenext
requestforthatpageisavailablelocallyandquickly;aproxygatewaytypically
doesnotusecache.Theterms"proxyserver"and"proxygateway"are
frequentlyusedinterchangeably.
Proxyservers/gatewaysareavailableforsuchcommonInternetservicesas
HTTP,HTTPS,FTP,SMTP,andSNMP.WhenanHTTPproxysendsqueriesfrom
localsystems,itpresentsasingleorganizationwideIPaddress(theexternalIP
addressoftheproxyserver/gateway)toallservers.Itfunnelsalluserrequests
totheappropriateserversandkeepstrackofthem.Whentheresponsescome
back,theHTTPproxyfansthemouttotheappropriateapplicationsusingeach
machine'suniqueIPaddress,therebyprotectinglocaladdressesfrom
remote/specifiedservers.
Proxyservers/gatewaysaregenerallyjustonepartofanoverallfirewallstrategy
topreventintrudersfromstealinginformationordamaginganinternalnetwork.
Otherfunctions,whichcanbeeithercombinedwithorkeptseparatefromthe
proxyserver/gateway,includepacketfiltering,whichblockstrafficbasedon
originandtype,anduseractivityreporting,whichhelpsmanagementlearnhow
theInternetisbeingused.
RPCNetworkServices
Muchoftheclient/serverinteractionoveranetworkisimplementedusingthe
RPC(RemoteProcedureCall)protocol,whichisimplementedasasetoflibrary
callsthatmakenetworkaccesstransparenttotheclientandserver.RPC
specifiesandinterpretsmessagesbutdoesnotconcernitselfwithtransport
protocols;itrunsontopofTCP/IPandUDP/IP.ServicesthatuseRPCinclude
NFSandNIS.RPCwasdevelopedbySunasONCRPC(OpenNetworkComputing
RemoteProcedureCalls)anddiffersfromMicrosoftRPC.
Intheclient/servermodel,aclientcontactsaserveronaspecificport(page
373)toavoidanymixupbetweenservices,clients,andservers.Toavoid
maintainingalonglistofportnumbersandtoenablenewclients/serverstostart
upwithoutregisteringaportnumberwithacentralregistry,whenaserverthat
usesRPCstarts,itspecifiestheportitexpectstobecontactedon.RPCservers
typicallyuseportnumbersthathavebeendefinedbySun.Ifaserverdoesnot
useapredefinedportnumber,itpicksanarbitrarynumber.
TheserverthenregistersthisportwiththeRPCportmapper(theportmap
daemon)onthelocalsystem.Theservertellsthedaemonwhichportnumberit
islisteningonandwhichRPCprogramnumbersitserves.Throughthese
exchanges,theportmapdaemonlearnsthelocationofeveryregisteredporton
thehostandtheprogramsthatareavailableoneachport.Theportmap
daemon,whichalwayslistensonport111forbothTCPandUDP,mustbe
runningtomakeRPCcalls.
Files
The/etc/rpcfile(page456)mapsRPCservicestoRPC
numbers.The/etc/servicesfile(page456)listssystem
services.
RPCclient/servercommunication
ThesequenceofeventsforcommunicationbetweenanRPC
clientandserveroccursasfollows:
1. TheclientprogramontheclientsystemmakesanRPCcall
toobtaindatafroma(remote)serversystem.(Theclient
issuesa"readrecordfromafile"request.)
2. IfRPChasnotyetestablishedaconnectionwiththeserver
systemfortheclientprogram,itcontactsportmaponport
111oftheserverandaskswhichportthedesiredRPC
serverislisteningon(forexample,rpc.nfsd).
3. Theportmapdaemonontheremoteserverlooksinits
tablesandreturnsaUDPorTCPportnumbertothelocal
system,theclient(typically2049fornfs).
4. TheRPClibrariesontheserversystemreceivethecallfrom
theclientandpasstherequesttotheappropriateserver
program.Theoriginoftherequestistransparenttothe
serverprogram.(Thefilesystemreceivesthe"readrecord
fromfile"request.)
5. Theserverrespondstotherequest.(Thefilesystemreads
therecord.)
6. TheRPClibrariesontheremoteserverreturntheresult
overthenetworktotheclientprogram.(Thereadrecordis
returnedtothecallingprogram.)
BecausestandardRPCserversarenormallystartedbythe
xinetddaemon(page389),theportmapdaemonmustbe
startedbeforethexinetddaemonisinvoked.Theinitscripts
(page404)makesureportmapstartsbeforexinetd.Youcan
confirmthissequencebylookingatthenumbersassociated
with/etc/rc.d/*/S*portmapand/etc/rc.d/*/S*/xinetd.
Iftheportmapdaemonstops,youmustrestartallRPCservers
onthelocalsystem.
Usenet
Oneoftheearliestinformationservicesavailableonthe
Internet,Usenetisanelectronicbulletinboardthatallowsusers
withcommonintereststoexchangeinformation.Usenet
comprisesaninformal,looselyconnectednetworkofsystems
thatexchangeemailandnewsitems(commonlyreferredtoas
netnews).Itwasformedin1979whenafewsitesdecidedto
sharesomesoftwareandinformationontopicsofcommon
interest.Theyagreedtocontactoneanotherandtopassthe
informationalongoverdial-uptelephonelines(atthattime
runningat1,200baudatbest),usingUNIX'suucputility(UNIX-
to-UNIXcopyprogram).
ThepopularityofUsenetledtomajorchangesinuucptohandle
theescalatingvolumeofmessagesandsites.Todaymuchof
thenewsflowsovernetworklinksusingasophisticatedprotocol
designedespeciallyforthispurpose:NNTP(NetworkNews
TransferProtocol).Thenewsmessagesarestoredinastandard
format,andthemanypublicdomainprogramsavailableletyou
readthem.Anold,simpleinterfaceisnamedreadnews.Other
interfaces,suchasrn,itsXWindowSystemcousinxrn,tin,nn,
andxvnews,havemanyfeaturesthathelpyoubrowsethrough
andreplytothearticlesthatareavailableorcreatearticlesof
yourown.Inaddition,NetscapeandMozillaincludeaninterface
thatyoucanusetoreadnews(Netscape/MozillaNews)aspart
oftheirWebbrowsers.Oneoftheeasiestwaystoreadnetnews
istogotogroups.google.com.Theprogramyouselecttoread
netnewsislargelyamatterofpersonaltaste.
Asprogramstoreadnetnewsarticleshavebeenportedtonon-
UNIXandnon-Linuxsystems,thecommunityofnetnewsusers
hasbecomehighlydiversified.IntheUNIXtradition,categories
ofnetnewsgroupsarestructuredhierarchically.Thetoplevel
includessuchdesignationsascomp(computer-related),misc
(miscellaneous),rec(recreation),sci(science),soc(social
issues),andtalk(ongoingdiscussions).Usuallyatleastone
regionalcategoryisatthetoplevel,suchasba(SanFrancisco
BayArea),andincludesinformationaboutlocalevents.New
categoriesarecontinuallybeingaddedtothemorethan30,000
newsgroups.Thenamesofnewsgroupsresembledomain
namesbutarereadfromlefttoright(likeLinuxfilenames):
comp.os.unix.misc,comp.lang.c,misc.jobs.offered,
rec.skiing,sci.med,soc.singles,andtalk.politicsarebuta
fewexamples.Thefollowingarticleappearedin
linux.redhat.install:
[Viewfullwidth]
>IhavejustinstalledFedora5andwhenitrytostartXIgetthe
>followingerrormessage:
>
>FatalServerError.
>noscreensfound
>
>XIO:FatalIOerr104(connectionresetbypeer)onXserver",0.0"after
>0requests(0knownprocessed)with0eventsremaining.
>
>HowcanIsolvethisproblem?
>
>Thanks,
>Fred
Fred,
ItwouldappearthatyourXconfigurationisincorrectormissing.Youshouldrun
system-config-displayandsetuptheconfigurationforyourvideocardandmonitor.
Carl
AgreatdealofusefulinformationisavailableonUsenet,but
youneedpatienceandperseverancetofindwhatyouare
lookingfor.Youcanaskaquestion,astheuserdidinthe
previousexample,andsomeonefromhalfwayaroundtheworld
mightanswerit.Beforeposingsuchasimplequestionand
causingittoappearonthousandsofsystemsaroundtheworld,
however,firstaskyourselfwhetheryoucangethelpinaless
invasiveway.Trythefollowing:
Refertothemanpagesandinfo.
Lookthroughthefilesin/usr/share/doc.
Askthesystemadministratororanotheruserforhelp.
AllofthepopularnewsgroupshaveFAQs(listsoffrequently
askedquestions).Consulttheselistsandseewhetheryour
questionhasbeenanswered.FAQsareperiodicallyposted
tothenewsgroups;inaddition,alltheFAQsarearchivedat
sitesaroundtheInternet,includingGooglegroups
(groups.google.com).
Becausesomeonehasprobablyaskedthesamequestion
earlier,searchthenetnewsarchivesforananswer.Try
lookingatgroups.google.com,whichhasacomplete
netnewsarchive.
Useasearchenginetofindananswer.Onegoodwaytoget
helpistosearchonanerrormessage.
Reviewsupportdocumentsatwww.redhat.com.
ContactaRedHatLinuxusers'group.
PostaquerytotheworldwideUsenetcommunityasalast
resort.IfyouarestuckonaLinuxquestionandcannotfindany
otherhelp,trysubmittingittooneofthesenewsgroups:
linux.redhat.install
linux.redhat.misc
Formoregenericquestions,trytheselists:
comp.os.linux.misc
comp.os.linux.networking
comp.os.linux.security
comp.os.linux.setup
linux.redhat.rpm
Onewaytofindoutaboutnewtoolsandservicesistoread
Usenetnews.Thecomp.os.linuxhierarchyisofparticular
interesttoLinuxusers;forexample,newsaboutnewlyreleased
softwareforLinuxispostedtocomp.os.linux.announce.
Peopleoftenannouncetheavailabilityoffreesoftwarethere,
alongwithinstructionsonhowtogetacopyforyourownuse
usinganonymousFTP(page607).Othertoolstohelpyoufind
resources,botholdandnew,existonthenetwork;see
AppendixB.
WWW:WorldWideWeb
TheWorldWideWeb(WWW,W3,ortheWeb)providesa
unified,interconnectedinterfacetothevastamountof
informationstoredoncomputersaroundtheworld.Theidea
thatspawnedtheWorldWideWebcamefromthemindofTim
Berners-Lee(www.w3.org/People/Berners-Lee)oftheEuropean
ParticlePhysicsLaboratory(CERN)inresponsetoaneedto
improvecommunicationsthroughoutthehigh-energyphysics
community.Thefirst-generationsolutionconsistedofa
notebookprogramnamedEnquire,shortforEnquireWithin
UponEverything(thenameofabookfromBerners-Lee's
childhood),whichhecreatedin1980onaNeXTcomputerand
whichsupportedlinksbetweennamednodes.Notuntil1989
wastheconceptproposedasaglobalhypertextprojecttobe
knownastheWorldWideWeb.In1990,Berners-Leewrotea
proposalforahypertextproject,whicheventuallyproduced
HTML(HypertextMarkupLanguage),thecommonlanguageof
theWeb.TheWorldWideWebprogrambecameavailableonthe
Internetinthesummerof1991.Bydesigningthetoolstowork
withexistingprotocols,suchasFTPandgopher,theresearchers
whocreatedtheWebproducedasystemthatisgenerallyuseful
formanytypesofinformationandacrossmanytypesof
hardwareandoperatingsystems.
TheWWWisanotherexampleoftheclient/serverparadigm.
YouuseaWWWclientapplication,orbrowser,toretrieveand
displayinformationstoredonaserverthatmaybelocated
anywhereonyourlocalnetworkortheInternet.WWWclients
caninteractwithmanytypesofservers.Forexample,youcan
useaWWWclienttocontactaremoteFTPserveranddisplay
thelistoffilesitoffersforanonymousFTP.Mostcommonlyyou
useaWWWclienttocontactaWWWserver,whichoffers
supportforthespecialfeaturesoftheWorldWideWebthatare
describedintheremainderofthischapter.
ThepoweroftheWebderivesfromitsuseofhypertext,away
tonavigatethroughinformationbyfollowingcross-references
(calledlinks)fromonepieceofinformationtoanother.Touse
theWebeffectively,youneedtoruninteractivenetwork
applications.ThefirstGUIforbrowsingtheWebwasatool
namedMosaic,whichwasreleasedinFebruary1993.Designed
attheNationalCenterforSupercomputerApplicationsatthe
UniversityofIllinois,itsintroductionsparkedadramatic
increaseinthenumberofusersoftheWorldWideWeb.Marc
Andreessen,whoparticipatedintheMosaicprojectatthe
UniversityofIllinois,latercofoundedNetscapeCommunications
withthefounderofSiliconGraphics,JimClark.Thepaircreated
NetscapeNavigator,aWebclientprogramthatwasdesignedto
performbetterandsupportmorefeaturesthantheMosaic
browser.NetscapeNavigatorhasenjoyedimmensesuccessand
hasbecomeapopularchoiceforexploringtheWorldWideWeb.
ImportantforLinuxusersisthefactthatfromitsinception
NetscapehasprovidedversionsofitstoolsthatrunonLinux.
Also,NetscapecreatedMozilla(mozilla.org)asanopen-source
browserproject.
ThesebrowsersprovideGUIsthatallowyoutolistentosounds,
watchWebeventsorlivenewsreports,anddisplaypicturesas
wellastext,givingyouaccesstohypermedia.Apictureonyour
screenmaybealinktomoredetailed,nonverbalinformation,
suchasacopyofthesamepictureatahigherresolutionora
shortanimation.Ifyoursystemcanproduceaudiooutput,you
canlistentoaudioclipsthathavebeenlinkedtoadocument.
URL:UniformResourceLocator
ConsidertheURLhttp://www.w3.org/Consortium/siteindex.The
firstcomponentintheURLindicatesthetypeofresource,in
thiscasehttp(HTTPHypertextTransferProtocol).Othervalid
resourcenames,suchashttps(HTTPSsecureHTTP)andftp
(FTPFileTransferProtocol),representinformationavailableon
theWebusingotherprotocols.Nextcomeacolonanddouble
slash(://).Frequentlythehttp://stringisomittedfroma
URLinprint,asyouseldomneedtoenterittoreachtheURL.
Thenextelementisthefullnameofthehostthatactsasthe
serverfortheinformation(www.w3.org/).Therestofthe
URLconsistsofarelativepathnametothefilethatcontainsthe
information(Consortium/siteindex).IfyouenteraURLinthe
locationbarofaWebbrowser,theWebserverreturnsthepage,
frequentlyanHTML(page1036)file,pointedtobythisURL.
ByconventionmanysitesidentifytheirWWWserversby
prefixingahostordomainnamewithwww.Forexample,you
canreachtheWebserverattheNewJerseyInstituteof
Technologyatwww.njit.edu.Whenyouuseabrowsertoexplore
theWorldWideWeb,youmayneverneedtoenteraURL.
However,asmoreinformationispublishedinhypertextform,
youcannothelpbutfindURLseverywherenotjustonlinein
emailmessagesandUsenetarticles,butalsoinnewspapers,in
advertisements,andonproductlabels.
Browsers
Mozilla(www.mozilla.org)istheopen-sourcecounterpartto
Netscape.Mozilla,whichwasfirstreleasedinMarch1998,was
basedonNetscape4code.Sincethen,Mozillahasbeenunder
continuousdevelopmentbyemployeesofNetscape(nowa
divisionofAOL),RedHat,andothercompaniesandby
contributorsfromthecommunity.FirefoxistheWebbrowser
componentofMozilla.KDEoffersKonqueror,anall-purposefile
managerandWebbrowser(page94).Otherbrowsersinclude
Epiphany(www.gnome.org/projects/epiphany)andOpera
(www.opera.com).AlthougheachWebbrowserisunique,allof
themallowyoutomoveabouttheInternet,viewingHTML
documents,listeningtosounds,andretrievingfiles.Ifyoudo
notusetheXWindowSystem,tryatextbrowser,suchaslynx
orlinks.ThelynxbrowserworkswellwithBrailleterminals.
SearchEngines
Searchengineisanamethatappliestoagroupofhardware
andsoftwaretoolsthathelpyousearchforWorldWideWeb
sitesthatcontainspecificinformation.Asearchenginerelieson
adatabaseofinformationcollectedbyaWebcrawler,a
programthatregularlylooksthroughthemillionsofpagesthat
makeuptheWorldWideWeb.Asearchenginemustalsohave
awayofcollatingtheinformationtheWebcrawlercollectsso
thatyoucanaccessitquickly,easily,andinamannerthat
makesitmostusefultoyou.Thispartofthesearchengine,
calledanindex,allowsyoutosearchforaword,agroupof
words,oraconcept;itreturnstheURLsofWebpagesthat
pertaintowhatyouaresearchingfor.Manydifferenttypesof
searchenginesareavailableontheInternet,eachwithitsown
setofstrengthsandweaknesses.
ChapterSummary
ALinuxsystemattachedtoanetworkisprobably
communicatingonanEthernet,whichmayinturnbelinkedto
otherlocalareanetworks(LANs)andwideareanetworks
(WANs).CommunicationbetweenLANsandWANsrequiresthe
useofgatewaysandrouters.Gatewaystranslatethelocaldata
intoaformatsuitablefortheWAN,androutersmakedecisions
abouttheoptimalroutingofthedataalongtheway.Themost
widelyusednetwork,byfar,istheInternet.
BasicnetworkingtoolsallowLinuxuserstologinandrun
commandsonremotesystems(ssh,telnet)andcopyfilesquickly
fromonesystemtoanother(scp,ftp/sftp).Manytoolsthatwere
originallydesignedtosupportcommunicationonasingle-host
computer(forexample,fingerandtalk)havesincebeen
extendedtorecognizenetworkaddresses,thusallowingusers
ondifferentsystemstointeractwithoneanother.Other
features,suchastheNetworkFilesystem(NFS),werecreated
toextendthebasicUNIXmodelandtosimplifyinformation
sharing.
Concernisgrowingaboutourabilitytoprotectthesecurityand
privacyofmachinesconnectedtonetworksandofdata
transmittedovernetworks.Towardthisend,manynewtools
andprotocolshavebeencreated:ssh,scp,HTTPS,IPv6,firewall
hardwareandsoftware,VPN,andsoon.Manyofthesetools
takeadvantageofnewer,moreimpenetrableencryption
techniques.Inaddition,someweakerconcepts(suchasthatof
trustedhosts)andsometools(suchasfingerandrwho)are
beingdiscardedinthenameofsecurity.
Computernetworksoffertwomajoradvantagesofoverother
waysofconnectingcomputers:Theyenablesystemsto
communicateathighspeedsandtheyrequirefewphysical
interconnections(typicallyonepersystem,oftenonashared
cable).TheInternetProtocol(IP),theuniversallanguageofthe
Internet,hasmadeitpossiblefordissimilarcomputersystems
aroundtheworldtoreadilycommunicatewithoneanother.
Technologicaladvancescontinuetoimprovetheperformanceof
computersystemsandthenetworksthatlinkthem.
OnewaytogatherinformationontheInternetisviaUsenet.
ManyLinuxusersroutinelyperuseUsenetnews(netnews)to
learnaboutthelatestresourcesavailablefortheirsystems.
Usenetnewsisorganizedintonewsgroupsthatcoverawide
rangeoftopics,computer-relatedandotherwise.Toread
Usenetnews,youneedtohaveaccesstoanewsserverandthe
appropriateclientsoftware.Manymodernemailprograms,such
asMozillaandNetscape,candisplaynetnews.
Therapidincreaseofnetworkcommunicationspeedsinrecent
yearshasencouragedthedevelopmentofmanynew
applicationsandservices.TheWorldWideWebprovidesaccess
tovastinformationstoresontheInternetandmakesextensive
useofhypertextlinkstopromoteefficientsearchingthrough
relateddocuments.Itadherestotheclient/servermodelthatis
sopervasiveinnetworking.TypicallytheWWWclientislocalto
asiteorismadeavailablethroughanInternetserviceprovider.
WWWserversareresponsibleforprovidingtheinformation
requestedbytheirmanyclients.
Mozilla/FirefoxisaWWWclientprogramthathasenormous
popularappeal.FirefoxandotherbrowsersuseaGUItogive
youaccesstotext,picture,andaudioinformation:Making
extensiveuseofthesehypermediasimplifiesaccesstoand
enhancesthepresentationofinformation.
Exercises
1.
Describethesimilaritiesanddifferencesbetweentheseutilities:
a. scpandftp
b. sshandtelnet
c. rshandssh
2. AssumingrwhoisdisabledonthesystemsonyourLAN,describetwowaystofind
outwhoisloggedinonsomeoftheothermachinesattachedtoyournetwork.
3. Explaintheclient/servermodel.GivethreeexamplesofservicesonLinuxsystems
thattakeadvantageofthismodel.
4. AsoftwareimplementationofchesswasdevelopedbyGNUandisavailablefor
free.HowcanyouusetheInternettofindacopyanddownloadit?
5. WhatisthedifferencebetweentheWorldWideWebandtheInternet?
6.
IfyouhaveaccesstotheWorldWideWeb,answerthefollowingquestions.
a. Whichbrowserdoyouuse?
b. WhatistheURLoftheauthorofthisbook'shomepage?Howmanylinks
doesithave?
c. Doesyourbrowserallowyoutocreatebookmarks?Ifso,howdoyoucreate
abookmark?Howcanyoudeleteone?
7. Giveoneadvantageandtwodisadvantagesofusingawirelessnetwork.
AdvancedExercises
8.
Supposethelinkbetweenrouters1and2isdownintheInternetshowninFigure
10-1onpage350.WhathappensifsomeoneatsiteCsendsamessagetoauser
onaworkstationattachedtotheEthernetcableatsiteA?Whathappensifthe
routeratsiteAisdown?Whatdoesthistellyouaboutdesigningnetwork
configurations?
9.
IfyouhaveaclassBnetworkandwanttodivideitintosubnets,eachwith126
hosts,whichsubnetmaskshouldyouuse?Howmanynetworkswillbeavailable?
Whatarethefouraddresses(broadcastandnetworknumber)forthenetwork
startingat131.204.18?
10.
Supposeyouhave300hostsandwanttohavenomorethan50hostspersubnet.
WhatsizeofaddressblockshouldyourequestfromyourISP?Howmanyclass
Cequivalentaddresseswouldyouneed?Howmanysubnetswouldyouhaveleft
overfromyourallocation?
11.
a. Onyoursystem,findtwodaemonsrunningthatarenotlistedinthischapter
andexplainwhatpurposetheyserve.
b. Reviewwhichservices/daemonsareautomaticallystartedonyoursystem,
andconsiderwhichyoumightturnoff.Arethereanyservices/daemonsin
thelistinTable10-4onpage374thatyouwouldconsideradding?
PartIV:SystemAdministration
Chapter11SystemAdministration:CoreConcepts
Chapter12Files,Directories,andFilesystems
Chapter13DownloadingandInstallingSoftware
Chapter14PrintingwithCUPS
Chapter15RebuildingtheLinuxKernel
Chapter16AdministrationTasks
Chapter17ConfiguringaLAN
11.SystemAdministration:Core
Concepts
INTHISCHAPTER
SystemAdministratorandSuperuser 391
RescueMode 397
SELinux 400
RedHatConfigurationTools 415
rpcinfo:DisplaysInformationAboutportmap 423
ThexinetdSuperserver 425
TCPWrappers:Client/ServerSecurity(hosts.allowand
hosts.deny)
427
SettingUpachrootJail 428
DHCP:ConfiguresHosts 431
nsswitch.conf:WhichServicetoLookatFirst 435
PAM 438
Thejobofasystemadministratoristokeeponeormore
systemsinausefulandconvenientstateforusers.OnaLinux
system,theadministratorandusermaybothbeyou,withyou
andthecomputerbeingseparatedbyonlyafewfeet.Orthe
systemadministratormaybehalfwayaroundtheworld,
supportinganetworkofsystems,withyoubeingsimplyoneof
thousandsofusers.Asystemadministratorcanbeoneperson
whoworkspart-timetakingcareofasystemandperhapsis
alsoauserofthesystem.Ortheadministratorcanbeseveral
people,allworkingfull-timetokeepmanysystemsrunning.
Awell-maintainedsystem
Runsquicklyenoughsousersdonotgettoofrustrated
waitingforthesystemtorespondorcompleteatask.
Hasenoughstoragetoaccommodateusers'reasonable
needs.
Providesaworkingenvironmentappropriatetoeachuser's
abilitiesandrequirements.
Issecurefrommaliciousandaccidentalactsalteringits
performanceorcompromisingthesecurityofthedatait
holdsandexchangeswithothersystems.
Isbackedupregularly,withrecentlybacked-upfilesreadily
availabletousers.
Hasrecentcopiesofthesoftwarethatusersneedtoget
theirjobsdone.
Iseasiertoadministerthanapoorlymaintainedsystem.
Inaddition,asystemadministratorshouldbeavailabletohelp
userswithalltypesofsystem-relatedproblemsfromloggingin
toobtainingandinstallingsoftwareupdatestotrackingdown
andfixingobscurenetworkissues.
PartVofthisbookbreakssystemadministrationintoseven
chapters:
Chapter11coversthecoreconceptsofsystem
administration,includingSuperuser,systemoperation,the
RedHatconfigurationtoolsandotherusefulutilities,
generalinformationaboutsettingupandsecuringaserver
(includingasectiononDHCP),andPAM.
Chapter12coversfiles,directories,andfilesystemsfroman
administrator'spointofview.
Chapter13coversinstallingsoftwareonthesystem,
includinghowtouseyum,pirut,RedHatNetwork(RHN),
up2date,BitTorrent,andwget.
Chapter14discusseshowtosetuplocalandremote
printersthatusetheCUPSprintingsystem.
Chapter15explainshowtorebuildtheLinuxkernel.
Chapter16coversadditionalsystemadministratortasks
andtools,includingsettingupusersandgroups,backingup
files,schedulingtasks,printingsystemreports,andgeneral
problemsolving.
Chapter17goesintodetailabouthowtosetupaLAN,
includingsettingupandconfiguringthenetworkhardware
andconfiguringthesoftware.
BecauseLinuxisconfigurableandrunsonavarietyofplatforms
(SunSPARC,DEC/CompaqAlpha,Intelx86,AMD,PowerPC,and
more),thischaptercannotdiscusseverysystemconfiguration
oreveryactionyouwillhavetotakeasasystemadministrator.
Instead,thischapterseekstofamiliarizeyouwiththeconcepts
youneedtounderstandandthetoolsyouneedtouseto
maintainaRedHatEnterpriseLinuxorFedoraCoresystem.
Whereitisnotpossibletogointodepthaboutasubject,the
chapterprovidesreferencestoothersources.
Thischapterassumesthatyouarefamiliarwiththefollowing
terms:
blockdevice(page1021)filesystem(page
1032)
rootfilesystem(page
1053)
daemon(page1027)fork(page1032)runlevel(page1054)
device(page1028)kernel(page1039)signal(page1055)
devicefilename(page
1029)
loginshell(page
1041)
spawn(page1056)
diskpartition(page1029)mount(page1043)systemconsole(page
1059)
environment(page1031)process(page1049)Xserver(page1064)
Tip:Ifsomethingdoesnotwork,seeif
theproblemiscausedbySELinux
Ifaserverorothersystemsoftwaredoesnotwork
properly,especiallyifitdisplaysapermissions-
relatederrormessage,theproblemmayliewith
SELinux.ToseeifSELinuxisthecauseofthe
problem,putSELinuxinpermissivemodeandrun
thesoftwareagain.Iftheproblemgoesaway,you
needtomodifytheSELinuxpolicy.Rememberto
turnSELinuxbackon.Formoreinformationreferto
SystemAdministratorandSuperuser
Muchofwhatasystemadministratordoesisworkthatordinary
usersdonothavepermissiontodo.Whenperformingoneof
thesetasks,thesystemadministratorlogsinasroot(oruses
anothermethod;seetheliststartingonpage392)tohave
systemwidepowersthatarebeyondthoseofordinaryusers:A
userwithrootprivilegesisreferredtoasSuperuser.The
usernameisrootbydefault.Superuserhasthefollowing
powersandmore:
Somecommands,suchasthosethataddnewusers,
partitionharddrives,andchangesystemconfiguration,can
beexecutedonlybyroot.Superusercanusecertaintools,
suchassudo,togivespecificuserspermissiontoperform
tasksthatarenormallyreservedforSuperuser.
Read,write,andexecutefileaccessanddirectoryaccess
permissionsdonotaffectroot:Superusercanreadfrom,
writeto,andexecuteallfiles,aswellasexamineandwork
inalldirectories.
Somerestrictionsandsafeguardsthatarebuiltintosome
commandsdonotapplytoroot.Forexample,rootcan
changeanyuser'spasswordwithoutknowingtheold
password.
Whenyouarerunningwithroot(Superuser)privileges,the
shellbyconventiondisplaysaspecialprompttoremindyouof
yourstatus.Bydefaultthispromptisorendswithapoundsign
(#).
TolessenthechancethatauserotherthanSuperuserwilltryto
usethembymistake,manyoftheutilitiesthatSuperuserruns
arekeptinthe/sbinand/usr/sbindirectories,ratherthanin
/binand/usr/bin.(Manyoftheseutilitiescanberunby
ordinaryusers.)Youcanexecutetheseutilitiesbygivingtheir
fullpathnamesonthecommandline(forexample,
/sbin/runlevel).Whenyouloginasroot,thesedirectories
areinyourPATH(page292)bydefault.
Caution:Leastprivilege
Whenyouareworkingonthecomputer,especially
whenyouareworkingasthesystemadministrator,
performanytaskbyusingtheleastprivilege
possible.Whenyoucanperformataskloggedinas
anordinaryuser,doso.Whenyoumustbeloggedin
asSuperuser,doasmuchasyoucanasanordinary
user,loginorusesusothatyouhaveroot
privileges,completethepartofthetaskthathasto
bedoneasSuperuser,andreverttobeingan
ordinaryuserassoonasyoucan.Becauseyouare
morelikelytomakeamistakewhenyouare
rushing,thisconceptbecomesmoreimportantwhen
youhavelesstimetoapplyit.
YoucangainorgrantSuperuserprivilegesinanumberofways:
1. Whenyoubringthesystemupinsingle-usermode(page
409),youareSuperuser.
2. Oncethesystemisupandrunninginmultiusermode(page
410),youcanloginasroot.Whenyousupplytheproper
password,youwillbeSuperuser.
3. Youcangiveansu(substituteuser)commandwhileyouare
loggedinasyourselfand,withtheproperpassword,you
willhaveSuperuserprivileges.Formoreinformationrefer
to"su:GivesYouAnotherUser'sPrivileges"onpage393.
4. YoucanusesudoselectivelytogiveusersSuperuser
privilegesforalimitedamountoftimeonaper-userand
per-commandbasis.Thesudoutilityiscontrolledbythe
/etc/sudoersfile,whichmustbesetupbyroot.Referto
thesudomanpageformoreinformation.
5. Anyusercancreateasetuid(setuserID)file(page183).
Setuidprogramsrunonbehalfoftheownerofthefileand
havealltheaccessprivilegesthattheownerhas.Whileyou
arerunningasSuperuser,youcanchangethepermissions
ofafileownedbyroottosetuid.Whenanordinaryuser
executesafilethatisownedbyrootandhassetuid
permissions,theprogramhasfullrootprivileges.Inother
words,theprogramcandoanythingthatrootcandoand
thattheprogramdoesorallowstheusertodo.Theuser's
privilegesdonotchange.Whentheprogramfinishes
running,alluserprivilegesreverttothewaytheywere
beforetheprogramstarted.Setuidprogramsthatare
ownedbyrootarebothextremelypowerfulandextremely
dangeroustosystemsecurity,whichiswhyasystem
containsveryfewofthem.Examplesofsetuidprograms
thatareownedbyrootincludepasswd,at,andcrontab.The
followingexampleshowstwowaysforSuperusertogivea
programsetuidprivileges:
#ls-lmy*
rwxrxrx1rootother24152Apr2916:30myprog
rwxrxrx1rootother24152Apr2916:31myprog2
#chmod4755myprog
#chmodu+smyprog2
#ls-lmy*
rwsrxrx1rootother24152Apr2916:30myprog
rwsrxrx1rootother24152Apr2916:31myprog2
Thesintheownerexecutepositionofthelsloutput(page
181)indicatesthatthefilehassetuidpermission.
Security:root-ownedsetuidprogramsare
extremelydangerous
Becausearoot-ownedsetuidprogramallows
someonewhodoesnotknowtherootpasswordto
havethepowersofSuperuser,itisatempting
targetforamalicioususer.Asystemshouldhaveas
fewoftheseprogramsasnecessary.Youcandisable
setuidprogramsatthefilesystemlevelbymounting
afilesystemwiththenosuidoption(page467).
YoucanalsouseSELinux(page400)todisable
setuidprograms.Seepage399foracommandthat
listssetuidfilesonthelocalsystem.
6. Someprogramsaskyouforapassword(eitheryour
passwordortherootpassword,dependingontheparticular
commandandtheconfigurationofthesystem)whenthey
start.Whenyouprovidetherootpassword,theprogram
runswithSuperuserprivileges.
Whenaprogramrequeststherootpasswordwhenitstarts,
youstoprunningastheprivilegeduserwhenyouquitusing
theprogram.Thissetupkeepsyoufromremaininglogged
inasSuperuserwhenyoudonotneedorintendtobe.
Referto"consolehelper:RunsProgramsasroot"onpage
394.
Sometechniqueslimitthenumberofwaystobecome
Superuser.PAM(page438)controlsthewho,when,andhowof
loggingin.The/etc/securettyfilecontrolswhichterminals
(ttys)ausercanloginonasroot.The
/etc/security/access.conffileaddsanotherdimensionto
logincontrol(seethefilefordetails).
Security:Donotallowrootaccessover
theInternet
Prohibitingrootloginsusingloginoveranetworkis
thedefaultpolicyofRedHatEnterpriseLinuxand
FedoraCoreandisimplementedbythePAM
securettymodule.The
/etc/security/access.conffilemustcontainthe
namesofallusersandterminals/workstationsthat
youwantausertobeabletologinonasroot.
Initiallyeverylineinaccess.confiscommented
out.
Youcan,however,loginasrootoveranetwork
usingssh(page579).AsshippedbyRedHat,ssh
doesnotfollowtheinstructionsinsecurettyor
access.conf.Also,in/etc/ssh/sshd_config,Red
HatsetsPermitRootLogintoYES(itissetby
default)topermitroottologinusingssh(page
594).
SystemAdministrationTools
Manytoolscanhelpyoubeanefficientandthoroughsystem
administrator.Afewofthesetools/utilitiesaredescribedinthis
section,anothergroupofadministrationutilitiesisdescribed
startingonpage415,andothersarescatteredthroughoutPart
IV.
su:GivesYouAnotherUser'sPrivileges
Thesu(substituteuser)utilitycancreateashellorexecutea
programwiththeidentityandpermissionsofaspecifieduser.
Followsuonthecommandlinewiththenameofauser;ifyou
arerootorifyouknowtheuser'spassword,youtakeonthe
identityofthatuser.Whenyougiveansucommandwithoutan
argument,sudefaultstoSuperusersothatyoutakeonthe
identityofroot(youhavetoknowtherootpassword).
Tobesurethatyouareusingthesystem'sofficialversionofsu
(andnotoneplantedonyoursystembyamalicioususer),
specifysu'sabsolutepathname(/bin/su)whenyouuseit.(Of
course,ifsomeonehascompromisedyoursystemenoughthat
youarerunningafakesucommand,youareinserioustrouble
anywaybutusinganabsolutepathnameforsuisstillagood
idea.)
WhenyougiveansucommandtobecomeSuperuser,you
spawnanewshell,whichdisplaysthe#prompt.Youreturnto
yournormalstatus(andyourformershellandprompt)by
terminatingthisshell:PressCONTROL-D,orgiveanexit
command.Givingansucommandbyitselfchangesyouruser
andgroupIDsbutmakesminimalchangestoyour
environment.YoustillhavethesamePATHyoudidwhenyou
loggedinasyourself.Whenyourunautilitythatisnormally
runbyroot(theutilitiesin/sbinand/usr/sbin),youneedto
specifyanabsolutepathnamefortheutility(suchas
/sbin/service).Whenyougivethecommandsu(youcanuse
lorlogininplaceofthehyphen),yougetarootloginshell:It
isasthoughyouloggedinasroot.Notonlyareyouruserand
groupIDsthoseofroot,butyourentireenvironmentisthatof
root.Theloginshellexecutestheappropriatestartupscripts
beforedisplayingaprompt,andyourPATHissettowhatit
wouldbeifyouhadloggedinasroot,typicallyincluding/sbin
and/usr/sbin.
Usetheidutilitytodisplaythechangesinyouruserandgroup
IDsandinthegroupsyouareassociatedwith.Inthefollowing
example,theinformationthatstartswithcontextpertainsto
SELinux:
$id
uid=500(alex)gid=500(alex)groups=500(alex)context=user_u:system_r:unconfined_t
$su
Password:
#id
uid=0(root)gid=0(root)groups=0(root),1(bin),2(daemon),3(sys),...
Youcanusesuwiththecoptiontorunasinglecommandwith
rootprivileges,returningtoyouroriginalshellwhenthe
commandfinishesexecuting.Thefollowingexamplefirstshows
thatauserisnotpermittedtokillaprocess.Withtheuseofsu
candtherootpassword,theuserispermittedtokill(page
395)theprocess.Thequotationmarksarenecessarybecause
suctakesitscommandasasingleargument.
$kill-154982
-bash:kill:(4982)-Operationnotpermitted
$su-c"kill-154982"
Password:
$
consolehelper:RunsProgramsasroot
Theconsolehelperutilitycanmakeiteasierforsomeonewhois
loggedinonthesystemconsolebutnotloggedinasrootto
runsystemprogramsthatnormallycanberunonlybyroot.
PAM(page438),whichauthenticatesusers,canbesettotrust
allconsoleusers,torequireuserpasswords(nottheroot
password),ortorequirerootpasswordsbeforegrantingtrust.
Theconceptunderlyingconsolehelperisthatyoumaywantto
considerastrustworthyanyonewhohasaccesstotheconsole.
Forexample,Alexcanloginontheconsoleashimselfandrun
haltwithoutknowingtherootpassword.Formoreinformation
refertothediscussionofconsolehelperonpage413andtothe
consolehelpermanpage.
Security:Superuser,PATH,andsecurity
ThefewerdirectoriesyoukeepinyourPATHwhen
youareroot,thelesslikelyyouwillbetoexecute
anuntrustedprogramasroot.Ifpossible,keeponly
thedefaultdirectories,alongwith/sbinand
/usr/sbin,inroot'sPATH.Neverincludethe
workingdirectory(as.or::anywhereinPATH,or
:asthelastelementofPATH).Formore
informationreferto"PATH:WheretheShellLooks
forPrograms"onpage292.
kill:SendsaSignaltoaProcess
Thekillbuiltinsendsasignaltoaprocess.Thissignalmayor
maynotterminate(kill)theprocess,dependingonwhichsignal
issentandhowtheprocessisdesigned.Referto"trap:Catches
aSignal"onpage933foradiscussionofthevarioussignals
andtheirinteractionwithaprocess.Runningkillisnotthefirst
methodauserorsystemadministratorshouldtrywhena
processneedstobeaborted.
Caution:kill:Usethekillsignal(KILLor
9)asamethodoflastresort
Whenyoudoneedtousekill,sendthetermination
signal(killTERMorkill15)first.Onlyifthattactic
doesnotworkshouldyouattempttousethekill
signal(killKILLorkill9).
Becauseofitsinherentdangers,usingakillsignalis
amethodoflastresort,especiallywhenyouare
runningasSuperuser.Onekillcommandissuedby
rootcanbringthesystemdownwithoutwarning.
Usuallyausercankillaprocessbyworkinginanotherwindow
orbylogginginonanotherterminal.Sometimesyoumayhave
tologinasroot(orusesu)tokillaprocessforauser.Tokilla
process,youneedtoknowitsPID.Thepsutilitycanprovidethis
informationonceyoudeterminethenameoftheprogramthe
userisrunningand/ortheusernameoftheuser.Thetoputility
(page550)canalsobehelpfulinfindingandkilling(seetop'sk
command)arunawayprocess.
Inthefollowingexample,Samcomplainsthatxeyesisstuckand
thathecannotdoanythingfromthexeyeswindow,noteven
closeit.Amoreexperiencedusercouldopenanotherwindow
andkilltheprocess,butinthiscase,youkillitforSam.First
usepswiththeuoption,followedbythenameoftheuserand
thef(full/wide)optiontoviewalltheprocessesassociatedwith
thatuser.
$ps-usam-f
UIDPIDPPIDCSTIMETTYTIMECMD
sam22942259009:31?00:00:00/bin/sh/usr/bin/startkde
sam23392294009:31?00:00:00/usr/bin/ssh-agent/usr/bin/dbus-launch
sam23421009:31?00:00:00dbus-daemon--fork--print-pid8--prin
sam23431009:31?00:00:00/usr/bin/dbus-launch--exit-with-sessio
sam23961009:31?00:00:00kdeinitRunning...
sam23991009:31?00:00:00dcopserver[kdeinit]--nosid
sam24012396009:31?00:00:00klauncher[kdeinit]
sam24031009:31?00:00:00kded[kdeinit]
sam24051009:31?00:00:00/usr/libexec/gam_server
sam24132396009:31?00:00:00/usr/bin/artsd-F10-S4096-s60-ma
sam24151009:31?00:00:00kaccess[kdeinit]
sam24162294009:31?00:00:00kwrapperksmserver
sam24181009:31?00:00:00ksmserver[kdeinit]
sam24212396009:31?00:00:00kwin[kdeinit]-session1070626e6a00011
sam24241009:31?00:00:01kdesktop[kdeinit]
sam24261009:31?00:00:01kicker[kdeinit]
sam24292396009:31?00:00:00kio_file[kdeinit]file/tmp/ksocket-ma
sam24342396009:31?00:00:00konsole[kdeinit]-session1070626e6a00
sam24352396009:31?00:00:00/bin/sh/usr/lib/firefox-1.5/firefox-U
sam24462435009:31?00:00:00/bin/sh/usr/lib/firefox-1.5/run-mozill
sam24512446009:31?00:00:01/usr/lib/firefox-1.5/firefox-bin-UILoc
sam24532434009:31pts/200:00:00/bin/bash
sam24741009:31?00:00:00/usr/libexec/gconfd-210
sam24821009:32?00:00:00synergycjam
sam35683567013:55pts/300:00:00-bash
sam37261014:07?00:00:00knotify[kdeinit]
sam37281014:07?00:00:00/usr/bin/artsd-F10-S4096-s60-ma
sam37302424014:07?00:00:00xeyes
sam37313568014:07pts/300:00:00ps-usam-f
Thislistisfairlyshort,andtheprocessrunningxeyesiseasyto
find.Anotherwaytosearchforaprocessistousepstoproduce
alonglistofallprocessesandthenusegreptofindwhichones
arerunningxeyes.
$ps-ef|grepxeyes
sam37302424014:07?00:00:00xeyes
sam37663568014:14pts/300:00:00grepxeyes
Ifseveralpeoplearerunningxeyes,youmayneedtolookinthe
leftcolumntofindthenameoftheusersoyoucankilltheright
process.Youcancombinethetwocommandsaspsusamf|
grepxeyes.
NowthatyouknowSam'sprocessrunningxeyeshasaPIDof
3730,youcanusekilltoterminateit.Thesafestwaytodosois
tologinasSam(perhapsallowhimtologinforyouorsuto
sam[susam]ifyouareloggedinasroot)andgiveanyofthe
followingcommands(theyallsendaterminationsignalto
process3730):
$kill3730
or
$kill-153730
or
$killTERM3730
Onlyifthiscommandfailsshouldyousendthekillsignal:
$killKILL3730
TheKILLoptioninstructskilltosendaSIGKILLsignal,which
theprocesscannotignore.Youcangivethesamecommand
whileyouareloggedinasroot,butatypingmistakecanhave
muchmorefar-reachingconsequencesinthiscircumstance
thanwhenyoumakethemistakewhileyouareloggedinasan
ordinaryuser.Ausercankillonlyherownprocesses,whereas
Superusercankillanyprocess,includingsystemprocesses.
Asacompromisebetweenspeedandsafety,youcancombine
thesuandkillutilitiesbyusingthecoptiontosu.Thefollowing
commandrunsthepartofthecommandlinefollowingthec
withtheidentityofSam:
#susam-c"kill-TERM3730"
Twousefulutilitiesrelatedtokillarekillallandpidof.Thekillall
utilityisverysimilartokillbutusesacommandnameinstead
ofaPIDnumber.Tokillallyourprocessesthatarerunningxeyes
orvi,youcangivethefollowingcommand:
$killallxeyesvi
Whenrootgivesthiscommand,allprocessesthatarerunning
xeyesorvionthesystemarekilled.
ThepidofutilitydisplaysthePIDnumberofeachprocess
runningthecommandyouspecify.Becausethisutilityresidesin
/sbin,youmustgivetheabsolutepathnameifyouarenot
runningasroot:
$/sbin/pidofhttpd
567566565564563562561560553
Ifitisdifficulttofindtherightprocess,tryusingtop.Referto
themanpagesfortheseutilitiesformoreinformation,including
listsofoptions.
RescueMode
Rescuemodeisanenvironmentyoucanusetofixasystem
thatdoesnotbootnormally.Tobringasystemupinrescue
mode,bootthesystemfromtherescueCD,thefirstinstallation
CD,ortheinstallationDVD.FromtherescueCD,attheboot:
promptpressRETURNwithoutenteringacommand.Givethe
commandlinuxrescueinresponsetheboot:promptfromthe
firstinstallationCDortheinstallationDVD.Thesystemthen
comesupinrescuemode.Thebootprocessmaytakeseveral
minutes.
Inrescuemode,youcanchangeorreplaceconfigurationfiles,
checkandrepairpartitionsusingfsck(page470),rewriteboot
information,andmore.Therescuesetupfirstasksifyouwant
tosetupthenetworkinterface.Thisinterfaceisrequiredifyou
wanttocopyfilesfromothersystemsontheLANordownload
filesfromtheInternet.Whenyouchoosetosetupthenetwork
interface,youneedtochoosewhethertohaveDHCP
automaticallyconfigurethenetworkconnectionortomanually
supplytheIPaddressandnetmaskoftheinterface,aswellas
theIPaddressesofthegatewayanduptothreeDNS
addresses.
IftherescuesetupfindsanexistingLinuxinstallation,youcan
choosetomountitunder/mnt/sysimage,optionallyin
readonlymode.Withtheexistinginstallationmounted,oncethe
systemdisplaysashellprompt(similartosh-3.1#),youcan
givethecommandchroot/mnt/sysimagetomountthe
existinginstallationasitwouldbeifyoubootednormally,with
theexistinginstallation'srootmountedat/(root).(Seepage
428formoreinformationonchroot.)Ifyouchoosenottomount
theexistinginstallation,youarerunningarescuesystemwith
standardtoolsmountedinstandardlocations(/bin,/usr/bin,
andsoon).Partitionsfromyourlocalinstallationareavailable
forfixingormounting.Whenyouexitfromtherescueshell,the
systemreboots.RemovetheCDorDVDifyouwanttoboot
fromtheharddrive.
AvoidingaTrojanHorse
ATrojanhorseisaprogramthatdoessomethingdestructiveor
disruptivetoasystemwhileappearingtobebenign.Asan
example,youcouldstorethefollowingscriptinanexecutable
filenamedmkfs:
whiletrue
do
echo'GoodMorningMr.Jones.Howareyou?HaHaHa.'>/dev/console
done
IfyouarerunningasSuperuserwhenyourunthiscommand,it
wouldcontinuouslywriteamessagetotheconsole.Ifthe
programmerweremalicious,itcoulddoworse.Theonlything
missinginthisplotisaccesspermissions.
AmalicioususercouldimplementthisTrojanhorsebychanging
Superuser'sPATHvariabletoincludeapubliclywritable
directoryatthestartofthePATHstring.(Thecatchisthatyou
needtobeabletowriteto/etc/profilewherethePATH
variableissetforrootandonlyrootcandothat.)Thenyou
wouldneedtoputthebogusmkfsprogramfileinthatdirectory.
Becausethefraudulentversionappearsinadirectory
mentionedearlierthantherealoneinPATH,theshellrunsit.
ThenexttimeSuperusertriestorunmkfs,thefraudulent
versionwouldrun.
Trojanhorsesthatlieinwaitforandtakeadvantageofthe
misspellingsthatmostpeoplemakeareamongthemost
insidioustypes.Forexample,youmighttypeslinsteadofls.
Becauseyoudonotregularlyexecuteautilitynamedslandyou
maynotremembertypingthecommandsl,itismoredifficult
totrackdownthistypeofTrojanhorsethanonethattakesthe
nameofamorefamiliarutility.
AgoodwaytohelppreventtheexecutionofaTrojanhorseisto
makesurethatyourPATHvariabledoesnotcontainasingle
colon(:)atthebeginningorendofthePATHstringoraperiod
(.)ordoublecolon(::)anywhereinthePATHstring.This
precautionensuresthatyouwillnotexecuteafileinthe
workingdirectorybyaccident.TocheckforapossibleTrojan
horse,examinethefilesystemperiodicallyforfileswithsetuid
(refertoitem5onpage392)permission.Thefollowing
commandliststhesefiles:
Listingsetuidfiles
#find/perm4000execlslh{}\;2>/dev/null
rwsrxrx1rootroot13KFeb1200:18/sbin/pam_timestamp_check
rwsrxrx1rootroot22KFeb1200:18/sbin/unix_chkpwd
rwsrxrx1rootroot84KFeb1212:38/bin/mount
rwsrxrx1rootroot61KFeb1212:38/bin/umount
rwsrxrx1rootroot25KFeb1022:43/bin/su
rwsrxrx1rootroot36KFeb1115:06/bin/ping
rwsrxrx1rootroot32KFeb1115:06/bin/ping6
rwsxx1rootroot37KFeb1210:43/usr/sbin/userhelper
...
Thiscommandusesfindtolocateallfilesthathavetheirsetuid
bitset(mode4000).Thehyphenprecedingthemodecauses
findtoreportonanyfilethathasthisbitset,regardlessofhow
theotherbitsareset.Theoutputsenttostandarderroris
redirectedto/dev/nullsothatitdoesnotclutterthescreen.
Youcanalsosetupaprogram,suchasAIDE(Advanced
IntrusionDetectionEnvironment),thatwilltakeasnapshotof
yoursystemandcheckitperiodicallyasyouspecify.See
sourceforge.net/projects/aideformoreinformation.
GettingHelp
TheRedHatLinuxdistributioncomeswithextensive
documentation(page102).RedHatmaintainsapagethat
pointsyoutowardmanyusefulsupportdocuments:
https://www.redhat.com/apps/support.Youcanalsofindhelp
ontheSystemAdministratorsGuildsite(www.sage.org).The
Internetisanotherrichsourceofinformationonmanaginga
Linuxsystem;refertoAppendixB(page977)andtothe
author'shomepage(www.sobell.com)forpointerstouseful
sites.
YoudonotneedtoactasaRedHatsystemadministratorin
isolation;alargecommunityofLinux/RedHatexpertsiswilling
toassistyouingettingthemostoutofyoursystem,although
youwillgetbetterhelpifyouhavealreadytriedtosolvea
problemyourselfbyreadingtheavailabledocumentation.Ifyou
areunabletosolveaproblembyconsultingthedocumentation,
awell-thought-outquestiontotheappropriatenewsgroup,such
ascomp.os.linux.misc,ormailinglistcanoftengenerate
usefulinformation.Besureyoudescribetheproblemaccurately
andidentifyyoursystemcarefully.Includeinformationabout
yourversionofRedHatEnterpriseLinuxorFedoraCoreand
anysoftwarepackagesandhardwarethatyouthinkrelateto
theproblem.Thenewsgroupcomp.os.linux.answerscontains
postingsofsolutionstocommonproblemsandperiodicpostings
ofthemostup-to-dateversionsofFAQsandHOWTO
SELinux
TraditionalLinuxsecurity,calledDiscretionaryAccessControl
(DAC),isbasedonusersandgroups.Becauseaprocessrunby
auserhasaccesstoanythingtheuserhasaccessto,fine-
grainedaccesscontrolisdifficulttoachieve.Fine-grained
accesscontrolisparticularlyimportantonservers,whichoften
holdprogramsthatrequirerootprivilegestorun.
SELinux(SecurityEnhancedLinux),developedbytheU.S.
NationalSecurityAgency(NSA),implementsMandatoryAccess
Control(MAC)intheLinuxkernel.MACenforcessecurity
policiesthatlimitwhatauserorprogramcando.Itdefinesa
securitypolicythatcontrolssomeorallobjects,suchasfiles,
devices,sockets,andports,andsomeorallsubjects,suchas
processes.UsingSELinux,youcangrantaprocessonlythose
permissionsitneedstobefunctional,followingtheprincipleof
leastprivilege(page392).MACisanimportanttoolforlimiting
securitythreatsthatcomefromusererrors,softwareflaws,and
malicioususers.ThekernelchecksMACrulesafteritchecks
DACrules.
SELinuxcanbeinoneofthreestates(modes):
Enforcing/ActiveThedefaultstate,whereinSELinux
securitypolicyisenforced.Nouserorprogramwillbeable
todoanythingnotpermittedbythesecuritypolicy.
Permissive/WarnThediagnosticstate,whereinSELinux
sendswarningmessagestoalogbutdoesnotenforcethe
securitypolicy.Youcanusethelogtobuildasecuritypolicy
thatmatchesyourrequirements.
DisabledSELinuxdoesnotenforceasecuritypolicy
becausenopolicyisloaded.
RunningSELinuxinpermissiveorenforcingstatedegrades
systemperformancebetween5and10percent.Although
SELinuxisusuallyofnobenefitonasingle-usersystem,you
maywanttoconsiderSELinuxforaserverthatconnectstothe
Internet.IfyouareunsurewhethertouseSELinux,selecting
permissivestateallowsyoutochangetodisabledorenforcing
stateeasilyatalaterdate.
SELinuximplementsoneofthefollowingpolicies:
TargetedAppliesSELinuxMACcontrolsonlytocertain
(targeted)processes(default).
StrictAppliesSELinuxMACcontrolstoallprocesses.
Thissectiondiscussesthetargetedpolicy.Withsuchapolicy,
daemonsandsystemprocessesthatdonothaveaspecified
policyarecontrolledbytraditionalLinuxDACs.Withthestrict
policy,allprocessesarecontrolledbySELinux(MACs).Setting
upasystemthatrunsunderstrictpolicyisbeyondthescopeof
thisbook.
Thereisalwaysatradeoffbetweensecurityandusability.The
targetedpolicyislesssecurethanthestrictpolicy,butitis
mucheasiertomaintain.Whenyourunthestrictpolicyyouwill
likelyhavetocustomizethepolicysothatuserscandotheir
workandthesystemcanfunctionasyouwouldlikeitto.
Youcanswitchfromonepolicytotheother(asexplained
shortly).However,itisnotagoodideatoswitchfroma
targetedtoastrictpolicyonaproductionsystem.Ifyoudoso,
someusersmaynotbeabletodotheirwork.Youwouldneed
tocustomizethepolicyinsuchacase.Changingfromastrictto
atargetedpolicyshouldnotcreateanyproblems.
MoreInformation
Web
NSA:www.nsa.gov/selinux
FedoraSELinuxWiki:fedoraproject.org/wiki/SELinux
FedoraFAQ:fedora.redhat.com/docs/selinux-faq
SELinuxNews:selinuxnews.org
SELinuxforDistributions(Sourceforge):selinux.sourceforge.net
UnofficialFAQ:www.crypt.gen.nz/selinux/faq.html
FedoraSELinuxmailinglist:
www.redhat.com/mailman/listinfo/fedora-selinux-list
Tip:TurningoffSELinux
TherearetwowaystodisableSELinux.Youcan
eithermodifythe/etc/selinux/configfilesothat
itincludesthelineSELINUX=disabledandreboot
thesystem,oryoucanusesystem-
configsecuritylevel(asexplainedonthenext
page).
IfthereisachanceyouwillwanttoenableSELinux
inthefuture,puttingSELinuxinpermissivemodeis
abetterchoicethandisablingit.Thisstrategyallows
youtoturnonSELinuxmorequicklywhenyou
decidetodoso.
config:TheSELinuxConfigurationFile
The/etc/selinux/configfile,whichhasalinkat
/etc/sysconfig/selinux,controlsthestateofSELinuxonthe
localsystem.Althoughyoucanmodifythisfile,itmaybemore
straightforwardtoworkwithsystem-config-securitylevel(as
explainedinthenextsection).Inthefollowingexample,the
policyissettotargeted,butthatsettingisofnoconsequence
becauseSELinuxisdisabled:
$cat/etc/selinux/config
#ThisfilecontrolsthestateofSELinuxonthesystem.
#SELINUX=cantakeoneofthesethreevalues:
#enforcing-SELinuxsecuritypolicyisenforced.
#permissive-SELinuxprintswarningsinsteadofenforcing.
#disabled-SELinuxisfullydisabled.
SELINUX=disabled
#SELINUXTYPE=typeofpolicyinuse.Possiblevaluesare:
#targeted-Onlytargetednetworkdaemonsareprotected.
#strict-FullSELinuxprotection.
SELINUXTYPE=targeted
#SETLOCALDEFS=Checklocaldefinitionchanges
SETLOCALDEFS=0
ToputSELinuxinenforcingmode,changethelinecontaining
theSELINUXassignmenttoSELINUX=enforcing.Similarly
youcanchangethepolicybysettingSELINUXTYPE.Always
setSETLOCALDEFSto0.
Tip:IfyouwilluseSELinuxinthefuture
IfyouwilluseSELinuxinthefuturebutnotnow,
turnitonwhenyouinstallLinux,andrunitin
permissivestatewiththepolicysettothepolicyyou
willeventuallyuse.Permissivestatewritesthe
requiredextendedinformationtoinodes,butitdoes
notstopyoufromdoinganythingonthesystem.
IfyouturnonSELinuxafterithasbeendisabled,
whenyourebootthesystemSELinuxhastoadd
extendedattributestothefilesinthefilesystem.
Thisprocesscantakealongtimeonalarge
filesystem.IfyouarenevergoingtouseSELinux,
disableit.
sestatus:DisplaystheStateofSELinux
ThesestatusutilitydisplaysasummaryofthestateofSELinuxon
thelocalsystem:
#sestatus
SELinuxstatus:enabled
SELinuxfsmount:/selinux
Currentmode:permissive
Modefromconfigfile:permissive
Policyversion:20
Policyfromconfigfile:targeted
SettingtheTargetedPolicywithsystem-config-
securitylevel
Thesystem-config-securitylevelutilitydisplaystheSecurityLevel
Configurationwindow(Figure11-1),whichcontrolsSELinux.To
runthisutility,entersystem-configsecuritylevelfroma
commandlineinagraphicalenvironment.FromKDEselect
Mainmenu:Administration SecurityLevelandFirewall
orfromGNOMEselectSystem:Administration Security
LevelandFirewall.FromtheSecurityLevelConfiguration
window,clicktheSELinuxtabandchooseEnforcing(default),
Permissive,orDisabledfromtheSELinuxSettingcombobox.
Seepage768forinformationontheFirewallOptionstab.
Figure11-1.SecurityLevelConfigurationwindow,
SELinuxtab(system-config-securitylevel)
Thelowerframe,whichoccupiesmostoftheSecurityLevel
Configurationwindow,holdstheModifySELinuxPolicymenu.
Youopenandclosealistofsubmenusoroptionsbyclickingthe
triangleadjacenttoasubmenu.
ClickthetrianglenexttoModifySELinuxPolicytodisplayalist
ofsubmenus.Someofthesesubmenusarequitesimple.For
example,opentheSpamAssassin(page640)submenuto
displaythesinglechoice:AllowSpamAssassindaemon
networkaccess.Bydefaultthetargetedpolicydoesnotallow
theSpamAssassindaemon,spamd,toaccessthenetwork.
Clicktheboxnexttothischoicetodisplayacheckmarkand
allownetworkaccessforthisdaemon.
TheNFSsubmenupresentsthreechoicesconcerningNFS
filesystems.TheSELinuxServiceProtectionsubmenuallows
youtodisableSELinuxprotectionforalonglistofdaemons.
Thetargetedpolicyworkswithspecificsystemservices
(daemons):crond,ftpd,httpd,named,NFS,NIS,CUPS,
Samba,SpamAssassin,SQUID,andsshd.Tochangethe
SELinuxpolicyforoneoftheserviceslistedinthesubmenu,
openthatsubmenuandselectfromthechoices.Whenyouare
finishedmakingchanges,clickOK.
SystemOperation
Thissectioncoversthebasicsofhowthesystemfunctionsand
howyoucanmakeintelligentdecisionsasasystem
administrator.Itdoesnotexamineeveryaspectofsystem
administrationinthedepthnecessarytosetupormodifyall
systemfunctions.Instead,itprovidesaguidetobringinga
systemupandkeepingitrunningfromdaytoday.
BootingtheSystem
BootingasystemistheprocessofreadingtheLinuxkernel
(page1039)intosystemmemoryandstartingitrunning.Refer
to"BootLoader"onpage533formoreinformationontheinitial
stepsofbringingasystemup.
Asthelaststepofthebootprocedure,Linuxrunstheinit
programasPIDnumber1.Theinitprogramisthefirstgenuine
processtorunafterbootingandistheparentofallsystem
processes.(Thatiswhywhenyourunasrootandkillprocess
1,thesystemdies.)
initdefault
Theinitdefaultentryinthe/etc/inittabfile(page452)tells
initwhatrunleveltobringthesystemto(Table11-1).Set
initdefaultto3tocausethesystemtopresentatextlogin
messagewhenitboots;setinitdefaultto5topresenta
graphicalloginscreen(default).
Table11-1.Runlevels
Table11-1.Runlevels
Number Name Login Network Filesystems
0Halt
1(notSors) Singleuser Textual Down Mounted
2Multiuser
withoutNFS
Textual Up(partially) Mounted
3Multiuser Textual Up Mounted
4Userdefined
5Multiuser
withX
Graphical Up Mounted
6Reboot
InitScripts:StartandStopSystemServices
Thefirstscriptthatinitrunsis/etc/rc.d/rc.sysinit,which
performsbasicsystemconfiguration,includingsettingthe
systemclock,hostname,andkeyboardmapping;settingup
swappartitions;checkingthefilesystemsforerrors;andturning
onquotamanagement(page561).
Tip:Listthekernelbootmessages
Tosavealistofkernelbootmessages,givethe
followingcommandimmediatelyafterbootingthe
systemandloggingin:
$dmesg>dmesg.boot
Thiscommandsavesthekernelmessagesinafile
nameddmesg.boot.Thislistcanbeeducational.It
canalsobeusefulwhenyouarehavingaproblem
withthebootprocess.Formoreinformationreferto
"dmesg:DisplaysKernelMessages"onpage535.
rcscripts
Nextthe/etc/rc.d/rcinitscriptrunsthescriptsforthe
servicesthatneedtobestartedwhenyoufirstbringthesystem
upandthatneedtobestartedorstoppedwhenthesystem
goesfromsingle-usertomultiusermodeandbackdownagain.
Theinit(initialization)scripts,alsocalledrc(runcommand)
scripts,areshellscriptslocatedinthe/etc/rc.d/init.d
directoryandrunviasymboliclinksinthe/etc/rc.d/rcn.d
directories,wherenistherunlevelthesystemisentering.
The/etc/rc.d/rcn.ddirectoriescontainscriptswhosenames
beginwithK(K15httpd,K72autofs,K30sendmail,andso
on)andscriptswhosenamesbeginwithS(S05kudzu,
S10network,S13portmap,andsoon).Whenenteringanew
runlevel,eachK(kill)scriptisexecutedwithanargumentof
stop,andtheneachS(start)scriptisexecutedwithan
argumentofstart.EachoftheKfilesisruninnumericalorder.
TheSfilesareruninsimilarfashion.Thissetupallowsthe
personwhosetsupthesefilestocontrolwhichservicesare
stoppedandwhicharestarted,andinwhatorder,wheneverthe
systementersagivenrunlevel.Usingscriptswithstartand
stopargumentspromotesflexibilitybecauseitallowsonescript
tobothstartandkillaprocess,dependingontheargumentitis
calledwith.
Tocustomizesysteminitialization,youcanaddshellscriptsto
the/etc/rc.d/init.ddirectoryandplacelinkstothesefilesin
the/etc/rc.d/rcn.ddirectories.Thefollowingexampleshows
severallinkstothecupsscript.Theselinksarecalledtorunthe
cupsinitscripttostartorstopthecupsddaemonatvarious
runlevels:
$pwd
/etc/rc.d
$ls-l*/*cups
-rwxr-xr-x1rootroot2312Jan1703:59init.d/cups
lrwxrwxrwx1rootroot14Jan1720:38rc0.d/K10cups->../init.d/cups
lrwxrwxrwx1rootroot14Jan1720:38rc1.d/K10cups->../init.d/cups
lrwxrwxrwx1rootroot14Jan1720:38rc2.d/S55cups->../init.d/cups
lrwxrwxrwx1rootroot14Jan1720:38rc3.d/S55cups->../init.d/cups
lrwxrwxrwx1rootroot14Jan1720:38rc4.d/S55cups->../init.d/cups
lrwxrwxrwx1rootroot14Jan1720:38rc5.d/S55cups->../init.d/cups
lrwxrwxrwx1rootroot14Jan1720:38rc6.d/K10cups->../init.d/cups
Eachlinkin/etc/rc.d/rcn.dshouldpointtoafilein
/etc/rc.d/init.d.Forexample,thefile
/etc/rc.d/rc1.d/K10cupsisalinktothefilenamedcupsin
/etc/rc.d/init.d.(Thenumbersthatarepartofthefilenames
ofthelinksinthe/etc/rc.d/rcn.ddirec-toriesmaychange
fromonereleaseoftheoperatingsystemtothenext,butthe
scriptsin/etc/rc.d/init.dalwayshavethesamenames.)The
namesoffilesinthe/etc/rc.d/init.ddirectoryarefunctional.
Thus,whenyouwanttoturnNFSservicesonoroff,usethenfs
script.Whenyouwanttoturnbasicnetworkservicesonoroff,
runthenetworkscript.Thecupsscriptcontrolstheprinter
daemon.Eachscripttakesanargumentofstoporstart,
dependingonwhatyouwanttodo.Somescriptsalsotake
otherarguments,suchasrestart,reload,andstatus.Runa
scriptwithoutanargumenttodisplayausagemessage
indicatingwhichargumentsitaccepts.
Followingarethreeexamplesofcallstoinitscripts.Youmay
finditeasiertouseservice(discussednext)inplaceofthe
pathnamesinthesecommands:
#/etc/rc.d/init.d/nfsstop
#/etc/rc.d/init.d/networkstart
#/etc/rc.d/init.d/networkrestart
ThefirstexamplestopsallNFSprocesses(processesrelatedto
servingfilesystemsoverthenetwork).Thesecondexample
startsallprocessesrelatedtobasicnetworkservices.Thethird
examplestopsandthenrestartsthesesameprocesses.
Tip:Maintainthelinksinthe/etc/rc*.d
hierarchy
Refertopage408forinformationaboutusing
chkconfigtomaintainthesymboliclinksinthe
/etc/rc*.dhierarchy.
The/etc/rc.d/rc.localfileisexecutedaftertheotherinit
scripts.Putcommandsthatcustomizethesysteminrc.local.
Althoughyoucanaddanycommandsyouliketorc.local,itis
besttoruntheminthebackgroundsothatiftheyhang,they
donotstopthebootprocess.
service:ConfiguresServicesI
RedHatprovidesservice,ahandyutilitythatreportsonor
changesthestatusofanyofthesystemservicesin
/etc/rc.d/init.d.Inplaceofthecommandsdescribedatthe
endoftheprevioussection,youcangivethefollowing
commandsfromanydirectory:
#/sbin/servicenfsstop
#/sbin/servicenetworkstart
#/sbin/servicenetworkrestart
Thecommand/sbin/servicestatus-alldisplaysthestatusof
allsystemservices.Thenextsectionexploresyetanotherway
toconfiguresystemservices.
system-config-services:ConfiguresServicesII
Thesystem-config-servicesutilitydisplaystheServiceConfiguration
window(Figure11-2).Thisutilityhastwofunctions:Itturns
systemservicesonandoff,anditcontrolswhichservicesare
stoppedandstartedwhenthesystementersandleaves
runlevels3,4(notused),and5.
Figure11-2.TheServiceConfigurationwindow,
BackgroundServicestab
[Viewfullsizeimage]
Torunthisutility,entersystem-config-servicesfroma
commandlineinagraphicalenvironment.FromKDEselect
Mainmenu:Administration ServerSettings Services
orfromGNOMEselectSystem:Administration Server
Settings Services.
Thesystem-config-servicesutilityworkswithmanyoftheservices
listedin/etc/rc.d/init.daswellaswiththosecontrolledby
xinetd(page425)andlistedin/etc/xinetd.d(orasspecified
in/etc/xinetd.conf).
RHEL
TheRHELandFEDORAversionsofthisutilityarrangethe
informationaboutservicescontrolledbyxinetdsomewhat
differently.TheRHELversiondisplaysallservicesinasinglelist.
Whenyouhighlightaservicethatiscontrolledbyxinetd,the
noticexinetdisrequiredforthisserviceappearsinthe
Descriptionframe.
FEDORA
TheFEDORAversionofsystem-config-serviceshastwotabs.The
BackgroundServicestablistsallservicesexceptthose
controlledbyxinetd,whiletheOnDemandServicestab
displaysservicescontrolledbyxinetd.Thissectiondescribes
theFEDORAversionoftheutility.
BackgroundServicesTab
WhenyouclicktheBackgroundServicestab,thelinebelowthe
noteaboutbackgroundservicesdisplaysthecurrentrunlevel
(seeTable11-1onpage404)ofthesystemandtherunlevel
thatyouareediting.Servicesthatareturnedonattherun-
levelyouareeditingareindicatedbyacheckmarkinthebox
adjacenttotheservice.Tochangetherunlevelyouareediting,
clickEditRunlevelonthemenubarandthenselectthe
runlevelyouwanttoedit.WhenyouselectRunlevelAll,system-
config-servicesdisplaysatablelistingrunlevels3,4,and5.
Scrolltoandhighlighttheserviceyouareinterestedin.Ashort
descriptionappearsintheDescriptionframeandthestatusof
theserviceappearsintheStatusframe.
Withabackgroundservicehighlighted,clickthetoolbaror
makeaselectionfromActionsinthemenubartostop,start,or
restart(stopandthenstart)theservice.Thesystemturnson
(off)theserviceimmediately;thechangedoesnotaffect
whethertheservicewillrunthenexttimeyoubootthesystem,
enteranotherrun-level,orreenterthecurrentrunlevel.These
changesareequivalenttothoseyouwouldmakewiththeservice
utility(page406).
Youcanalsousesystem-config-servicestocontrolthefuture
executionofbackgroundservicesinrunlevels3,4,and5.
Selecttherunlevelyouwanttoaffect,usingtheEditRunlevel
selectionfromthemenubar.Clicktheboxnexttotheservice
youwanttoconfigure.Acheckmarkintheboxindicatesthat
theservicewillbeonatthespecifiedrunlevel;theabsenceofa
checkmarkindicatesthatitwillbeoff.ClicktheSavebutton.
Whenyouenterthatrunlevelinthefuture,theservicewillbe
onoroffasyouspecified.Thecurrentstateoftheserviceisnot
changed.
OnDemandServicesTab
TheOnDemandServicestaballowsyoutoturnxinetd-
controlledservicesonoroff.AswiththeBackgroundServices
tab,highlightaservicetoreadadescriptionofit.Clickthebox
adjacenttoaservicetoturnitonoroffandthenclicktheSave
button.Thisactionchangestheyes/noparameterofthe
disablelinediscussedonpage426.WhenyouclickSave,the
systemrestartsxinetdwiththeservicestatuschangeyou
requested.Thischangeaffectsallrunlevelsandwillremainin
effectthroughchangesinrunlevelsandrebootsunlessyou
changeitagain.Thesechangesareequivalenttothoseyou
wouldmakewiththechkconfigutility(seethenextsection).
chkconfig:ConfiguresServicesIII
Thechkconfigcharacter-basedutilityduplicatesmuchofwhat
system-config-servicesdoes:Itmakesiteasierforasystem
administratortomaintainthe/etc/rc.ddirectoryhierarchy.
Thisutilitycanadd,remove,liststartupinformation,andcheck
thestateofsystemservices.Itchangestheconfigurationonlyit
doesnotchangethecurrentstateofanyservice.Toseealistof
allservices,givethefollowingcommand:
$/sbin/chkconfig--list
NetworkManager0:off1:off2:off3:off4:off5:off6:off
NetworkManagerDispatcher0:off1:off2:off3:off4:off5:off6:off
acpid0:off1:off2:off3:on4:on5:on6:off
anacron0:off1:off2:on3:on4:on5:on6:off
apmd0:off1:off2:on3:on4:on5:on6:off
atd0:off1:off2:off3:on4:on5:on6:off
auditd0:off1:off2:on3:on4:on5:on6:off
autofs0:off1:off2:off3:on4:on5:on6:off
avahi-daemon0:off1:off2:off3:on4:on5:on6:off
bluetooth0:off1:off2:on3:on4:on5:on6:off
cpuspeed0:off1:on2:on3:on4:on5:on6:off
...
xinetdbasedservices:
chargen:off
chargen-udp:off
daytime:off
daytime-udp:off
echo:off
echo-udp:off
...
Allservicesthatruntheirowndaemonsarelisted,onetoaline,
followedbytheirconfiguredstateforeachrunlevel.Following
thatlist,chkconfigdisplayseachofthexinetd-basedservices
anditscurrentstatus.Youcancheckhowaspecificdaemonis
configuredbyaddingitsnametothepreviouscommand:
$/sbin/chkconfig--listsshd
sshd0:off1:off2:on3:on4:on5:on6:off
Inthenextexample,chkconfigconfiguresthe/etc/rc.d
directoryhierarchysothatsshdwillbeoffinrunlevels2,3,4,
and5andthenconfirmsthechange.Tomakechangesusing
chkconfig,youmustworkasroot:
#/sbin/chkconfig--level2345sshdoff
.#/sbin/chkconfig--listsshd
sshd0:off1:off2:off3:off4:off5:off6:off
Forconvenience,youcanomitthelevel2345part.Whenyou
specifyaninitscriptandonoroff,chkconfigdefaultsto
runlevels2,3,4,and5.Thefollowingcommandisequivalent
tothefirstoftheprecedingcommands:
#chkconfigsshdoff
Bothpsandserviceconfirmthateventhoughchkconfigsetthings
upsothatsshdwouldbeoffinallrunlevels,thisdaemonisstill
running.Thechkconfigutilitydidnotshutdownsshd.Inthe
followingexample,thesecondcommandlineshowsthatwhen
yougiveaservicecommandfollowedbythenameofaninit
script,yougettheusagemessagefromthescript:
#ps-ef|grepsshd
root69710Oct01?00:00:00/usr/sbin/sshd
root1718521650015:15pts/400:00:00grepsshd
#/sbin/servicesshd
Usage:/etc/init.d/sshd{start|stop|restart|reload|condrestart|status}
#/sbin/servicesshdstatus
sshd(pid697)isrunning...
Withtheprecedingchanges,whenyourebootthesystem,sshd
willnotstart.Youcanstopitmoreeasilyusingservice,however:
#/sbin/servicesshdstop
Stoppingsshd:[OK]
#ps-ef|grepsshd
root1720921650015:16pts/400:00:00grepsshd
#/sbin/servicesshdstatus
sshdisstopped
Single-UserMode
Whenthesystemisinsingle-usermode,onlythesystem
consoleisenabled.Youcanrunprogramsfromtheconsolein
single-usermodeasyouwouldfromanyterminalinmultiuser
mode.Thedifferenceisthatfewofthesystemdaemonswillbe
running.Thescriptsin/etc/rc.d/rc1.darerunaspartof
single-userinitialization.Seepage414forinstructionson
bringingthesystemtosingle-usermode.
Withthesysteminsingle-usermode,youcanperformsystem
maintenancethatrequiresfilesystemstobeunmountedorthat
requiresjustaquietsystemnooneexceptyouusingit,sothat
nouserprogramsinterferewithdiskmaintenanceandbackup
programs.TheclassicalUNIXtermforthisstateisquiescent.
See"BackingUpFiles"onpage540foradiscussionofoneof
themostimportantandoftenneglectedareasofsystem
administration.
GoingtoMultiuserMode
Afteryouhavedeterminedthatalliswellwiththefilesystems,
youcanbringtheoperatingsystemuptomultiusermode.
Whenyouexitfromthesingle-usershell,initbringsthesystem
tothedefaultrunlevelusually5(page404).Alternativelyyou
cangivethefollowingcommandinresponsetotheSuperuser
prompttobringthesystemto(textual)multiusermode(use5
togotographical[multiuser]mode):
#/sbin/telinit3
Thetelinitutilitytellsinitwhichrunleveltoenter.Thetelinit
executableisasymboliclinktotheinitexecutablebut,by
convention,runningtelinitispreferredtorunninginitdirectly.
Whenitgoesfromsingle-userto(textual)multiusermode,the
systemexecutestheK(killorstop)scriptsandthentheS
(start)scriptsin/etc/rc.d/rc3.d.Formoreinformationrefer
to"InitScripts:StartandStopSystemServices"onpage404.
Usechkconfig(page408)tostoponeofthesescriptsfrom
runningwhenthesystementersthenewrunlevel.
Runlevel2isreferredtoasmultiusermode,andrunlevel3is
calledextendedmultiusermode.Butbecauserunlevel2is
rarelyused,thischapterusesthetermmultiusertoreferto
runlevel3.Runlevel4isnotused,andrunlevel5isgraphicsor
X11mode.
Multiuser/Graphicalmode
Multiuser/graphicalmodeisthedefaultstateforaRedHat
Linuxsystem.Inthismodeallappropriatefilesystemsare
mounted,anduserscanloginfromallconnectedterminals,
dial-uplines,andnetworkconnections.Allsupportservicesand
daemonsareenabledandrunning.Oncethesystemisin
multiuser/graphicalmode,youwillseealoginscreenonthe
console.Mostsystemsaresetuptobootdirectlyto
multiuser/graphicalmodewithoutstoppingatsingle-usermode.
LoggingIn
Textuallogin
Withatextuallogin,thesystemusesinit,mingetty,andloginto
allowausertologin;loginusesPAMmodules(page438)to
authenticateusers.Oncethesystemisinmultiusermode,initis
responsibleforspawningamingettyprocessoneachofthelines
thatausercanusetologin.
Whenyouenteryourusername,mingettyestablishesthe
characteristicsofyourterminal.Itthenoverlaysitselfwitha
loginprocessandpassestotheloginprocesswhateveryou
enteredinresponsetothelogin:prompt.Theloginprocess
usesPAMtoconsultthe/etc/passwdfiletoseewhethera
usernamematchestheusernameyouentered.PAMthen
consultsthe/etc/shadowfiletoseewhetherapasswordis
associatedwiththeusername.Ifitis,loginpromptsyoufora
password;ifnot,itcontinueswithoutrequiringapassword.
Whenyourusernamerequiresapassword,loginverifiesthe
passwordyouenterbycheckingthe/etc/shadowfileagain.If
eitheryourusernameoryourpasswordisnotcorrect,login
displaysLoginincorrectandpromptsyoutologinagain.
Allpasswordsinthe/etc/shadowfileareencryptedorhashed
usingMD5(page1042).Itisnotfeasibletorecoveran
encryptedpassword.Whenyoulogin,theloginprocess
encrypts/hashesthepasswordyoutypeatthepromptand
comparesittotheencrypted/hashedpasswordin
/etc/shadow.Ifthetwopasswordsmatch,youare
authenticated.
Graphicallogin
Withagraphicallogin,theinitprocessspawnsgdm(theGNOME
displaymanager)onthefirstfreevirtualterminal,providing
featuressimilartomingettyandlogin.ThegdmutilitystartsanX
serverandpresentsaloginwindow.Thegdmdisplaymanager
thenusesPAMtoauthenticatetheuserandrunsthescriptsin
the/etc/gdm/PreSessiondirectory.Thesescriptsinspectthe
user's~/.dmrcfile,whichstorestheuser'sdefaultsessionand
language,andlaunchtheuser'ssession.BothGNOMEandKDE
desktopenvironmentsstorethestateofthelastsavedsession
andattempttorestoreitwhentheuserlogsbackin.
WithNIS,logincomparesyourusernameandpasswordwiththe
informationintheappropriatenamingserviceinsteadof(orin
additionto)thepasswdandshadowfiles.Ifthesystemis
configuredtousebothmethods(/etc/passwdandNIS),it
checksthe/etc/nsswitch.conffile(page435)toseeinwhich
orderitshouldconsultthem.
PAM(page438),thePluggableAuthenticationModulefacility,
allowsyougreatercontroloveruserloginsthanthe
/etc/passwdand/etc/shadowfilesdo.UsingPAM,youcan
specifymultiplelevelsofauthentication,mutuallyexclusive
authenticationmethods,orparallelmethods,eachofwhichis
byitselfsufficienttograntaccesstothesystem.Forexample,
youcanhavedifferentauthenticationmethodsforconsole
loginsandforsshlogins.Likewise,youcanrequirethatmodem
usersauthenticatethemselvesviatwoormoremethods(such
asasmartcardorbadgereaderandapassword).PAMmodules
alsoprovidesecuritytechnologyvendorswithaconvenientway
tointerfacetheirhardwareorsoftwareproductswithasystem.
Whentheusernameandpasswordarecorrect,loginorthe
scriptsinPreSessionconsulttheappropriateservicesto
initializeyouruserandgroupIDs,establishyourhome
directory,anddeterminewhichshellordesktopmanageryou
willbeworkingwith.
Theloginutility/PreSessionscriptsassignvaluestotheHOME,
PATH,LOGNAME,SHELL,TERM,andMAILvariables.They
lookinthe/etc/groupfile(page451)toidentifythegroups
theuserbelongsto.Whenloginhasfinisheditswork,itoverlays
itselfwiththeloginshell,whichinheritsthevariablessetby
login.Inagraphicalenvironment,thePreSessionscriptsstart
thedesktopmanager.
Duringatextuallogin,theloginshellassignsvaluesto
additionalshellvariablesandexecutesthecommandsinthe
systemstartupshellscripts/etc/profileand/etc/bashrc.
Somesystemshaveadditionalsystemstartupshellscripts.The
actionsperformedbythesescriptsaresystemdependent,but
theyusuallydisplaythecontentsofthe/etc/motd(message
oftheday)and/etc/issuefiles,letyouknowthatyouhave
mail,andsetumask(page420),thefile-creationmask.
Afterexecutingthesystemstartupcommands,theshell
executesthecommandsfromthepersonalstartupshellscripts
inyourhomedirectory.Foralistofthesescripts,refertopage
267.Becausetheshellexecutesthepersonalstartupscripts
afterthesystemscripts,asophisticatedusercanoverrideany
variablesorconventionsthatwereestablishedbythesystem,
whereasanewusercanremainuninvolvedinthesematters.
LoggingOut
Whenyouseeashellprompt,youcaneitherexecuteaprogram
orexitfromtheshell.Ifyouexitfromtheshell,theprocess
runningtheshelldiesandtheparentprocesswakesup.When
theshellisachildofanothershell,theparentshellwakesup
anddisplaysaprompt.Exitingfromaloginshellcausesthe
operatingsystemtosendinitasignalthatoneofitschildren
hasdied.Uponreceivingthissignal,inittakesactionbasedon
thecontentsofthe/etc/inittabfile.Inthecaseofaprocess
controllingalineforaterminal,initinformsmingettythattheline
isfreeforanotheruser.
Whenyouareatrunlevel5andexitfromaGUI,theGNOME
displaymanager,gdm,initiatesanewlogindisplay.
BringingtheSystemDown
Theshutdownandhaltutilitiesperformthetasksneededtobring
thesystemdownsafely.Theseutilitiescanrestartthesystem,
preparethesystemtobeturnedoff,putthesysteminsingle-
usermode,and,onsomehardware,powerdownthesystem.
Thepoweroffandrebootutilitiesarelinkedtohalt.Ifyoucallhalt
whenthesystemisnotshuttingdown(runlevel0)orrebooting
(runlevel6),haltcallsshutdown.(Whenyouarerunningasother
thanSuperuser,thelinkgoesthroughconsolehelper[page394].)
Youmusttellshutdownwhenyouwouldliketobringthesystem
down.Thistimecanbeexpressedasanabsolutetimeofday,
asin19:15,whichcausestheshutdowntooccurat7:15P.M.
Alternatively,youcangivethenumberofminutesfromthe
presenttime,asin+15,whichmeans15minutesfromnow.To
bringthesystemdownimmediately(recommendedfor
emergencyshutdownsonlyorwhenyouaretheonlyuser
loggedin),youcangivetheargument+0,oritssynonym,
now.Whenshutdowntimesexceed5minutes,allnonroot
loginsaredisabledforthelast5minutesbeforeshutdown.
Callingshutdownwiththeroptioncausesthesystemtoreboot
(sameastherebootcommandexceptthatrebootimpliesnow).
Addingthefoptionforcesafastreboot,inwhichfilesystem
checkingisdisabled(seetheshutdownmanpagefordetails).
Usinghinsteadofrforcesthesystemtohalt(sameasthehalt
commandexceptthathaltimpliesnow).Amessageappears
oncethesystemhasbeensafelyhalted:Systemhalted.Most
ATXsystemsturnoffautomaticallyaftershutdown,however,so
youwillnotseethismessage.
BecauseLinuxisamultiusersystem,shutdownwarnsallusers
beforetakingaction.Thiswarninggivesusersachanceto
preparefortheshutdown,perhapsbywritingouteditorfilesor
exitingfromnetworkingapplications.Youcanreplacethe
defaultshutdownmessagewithoneofyourownbyfollowing
thetimespecificationonthecommandlinewithamessage:
#/sbin/shutdown-h09:30Goingdown9:30toinstalldisk,upby10am.
CONTROL-ALT-DEL:RebootstheSystem
Bydefaultthe/etc/inittabfileonanIntel-basedcomputer
containstheentry
ca::ctrlaltdel:/sbin/shutdown-t3-rnow
Caution:Donotturnthepoweroff
beforebringingthesystemdown
DonotturnthepoweroffonaLinuxsystemwithout
firstbringingitdownasdescribedhere.LikeUNIX,
Linuxspeedsdiskaccessbykeepinganin-memory
collectionofdiskbuffersthatarewrittentothedisk
periodicallyorwhensystemuseismomentarilylow.
Whenyouturnofforresetthecomputerwithout
writingthecontentsofthesediskbufferstothedisk,
youloseanyinformationinthebuffers.Running
shutdownforcesthesebufferstobewritten.Youcan
forcethebufferstobewrittenatanytimebyissuing
asynccommand.However,syncdoesnotunmount
filesystems,nordoesitbringthesystemdown.
Thisentryallowsanyuser[1]torebootthecomputersafelyby
pressingthekeysequenceCONTROL-ALT-DEL(alsoreferredto
asthethree-fingersaluteortheVulcandeathgrip)froma
textualloginontheconsole.(Althoughitisnotrecommended,
youcanpressCONTROL-ALT-F1fromagraphicalsessionto
switchtothesystemconsoleandthenuseCONTROL-ALT-DEL.)
Becauseofitshooksintothekeyboarddriver,thiskeysequence
sendsaSIGINTsignaltotheinitprocess,whichinresponse
runsshutdown.Becauseitrunsasroot,initcausesshutdowntorun
asroot,evenifanordinaryuserinitiatesthekeysequence.
YoucandisableCONTROL-ALT-DELbydeletingtheprecedingline
from/etc/inittab(orputtinga#atthebeginningoftheline)
andthensendinginitaHUPsignal(killHUP1),whichcausesit
torereadthe/etc/inittabfile.
[1]Whenyouincludetheaoptionintheshutdowncommandin/etc/inittabandthe
/etc/shutdown.allowfileexists,oneoftheuserswhosenamesappearinthisfile(or
root)mustbeloggedinononeofthevirtualconsolesforanonrootusertorunshutdown
fromavirtualconsole.
consolehelper:AllowsanOrdinaryUsertoRunaPrivileged
Command
Twoexecutablehaltfilesexist:
$file/sbin/halt/usr/bin/halt
/sbin/halt:ELF32-bitLSBexecutable,Intel80386,version1(SYSV)...
/usr/bin/halt:symboliclinkto'consolehelper'
Thefilein/sbinrunsthehaltutility,whereasthefilein
/usr/binisalinktoconsole-helper.Inroot'sPATHvariable,
/sbinnormallyprecedes/usr/bin.Thus,whensomeone
runningasrootgivesahaltcommand,theshellexecutes
/sbin/halt(thehaltutility).Normally/sbindoesnotappearin
anordinaryuser'sPATH;whenanordinaryusergivesahalt
command,theshellfollowsthelinkfrom/usr/bin/haltand
executes/usr/bin/consolehelper.
WhatconsolehelperdoesdependsonhowPAMissetup(see
/etc/pam.d/haltforthemodulesitcallsand
/usr/share/doc/pam-*/txts/*fordescriptionsofthe
modules).Referto"PAM"onpage438formoreinformation.As
shippedbyRedHat,consolehelperdoesnotrequiretheroot
password;anyusercangiveahaltcommandfromthesystem
consoletoshutthesystemdown.
GoingtoSingle-UserMode
Becausegoingfrommultiusertosingle-usermodecanaffect
otherusers,youmustbeSuperusertomakethischange.Make
surethatyougiveotherusersenoughwarningbeforeswitching
tosingle-usermode;otherwise,theymaylosewhateverthey
wereworkingon.
Thefollowingstepsdescribeamethodofmanuallybringingthe
systemdowntosingle-usermodethepointwhereitissafeto
turnthepoweroff.YoumustberunningasSuperuserto
performthesetasks.
1. Usewall(writeall)towarneveryonewhoisusingthe
systemtologout.
2. IfyouaresharingfilesviaNFS,useexportfsuatodisable
networkaccesstothesharedfilesystems.(Useexportfs
withoutanargumenttoseewhichfilesystemsarebeing
shared.)
3. Confirmthatnocriticalprocessesarerunninginthe
background(someonerunninganunattendedcompileor
someotherjob).
4. Givethecommand/sbin/telinit1tobringthesystem
downtosingle-usermode.
Thesystemwilldisplaymessagesabouttheservicesitis
shuttingdownandfinallydisplayabashshellpromptsimilar
tosh-3.1#.Therunlevelutilityconfirmsthatthesystemisin
runlevel1(Sforsingle-usermode):
#/sbin/telinit1
sh-3.1#runlevel
1S
5. Useumountatounmountallmounteddevicesthatarenot
inuse.Usemountwithoutanargumenttomakesurethat
nodevicesotherthanroot(/)aremountedbefore
continuing.
TurningthePowerOff
Oncethesystemisinsingle-usermode,shuttingitdownis
quitestraightforward.Givethecommandtelinit0(preferred)
orhalttobringthesystemdown.Youcanbuildakernelwith
apmsoitturnsthemachineoffattheappropriatetime.Ifyour
machineisnotsetupthisway,turnthepoweroffwhenthe
appropriatepromptappearsorwhenthesystemstarts
rebooting.
Crash
Acrashoccurswhenthesystemsuddenlystopsorfailswhen
youdonotintenditto.Acrashmayresultfromsoftwareor
hardwareproblemsorfromalossofpower.Asarunning
systemlosespower,itmaybehaveinerraticorunpredictable
ways.Inafractionofasecond,somecomponentsaresupplied
withenoughvoltage;othersarenot.Buffersarenotflushed,
corruptdatamaybewrittentotheharddisk,andsoon.IDE
drivesdonotbehaveaspredictablyasSCSIdrivesunderthese
circumstances.Afteracrash,youmustbringtheoperating
systemupcarefullytominimizepossibledamagetothe
filesystems.Frequentlylittleornodamagewillhaveoccurred.
RepairingaFilesystem
Althoughthefilesystemsarecheckedautomaticallyduringthe
bootprocessifneeded,youwillhavetocheckthemmanuallyif
aproblemcannotberepairedautomatically.Tocheckthe
filesystemsmanuallyafteracrash,bootthesystemupin
rescuemode(page397).Donotmountanydevicesotherthan
root,whichLinuxmountsautomatically.Runfsck(page470)on
alllocalfilesystemsthatweremountedatthetimeofthecrash,
repairingthemasneeded.Dependingonhowthesystemisset
up,whenfsckcannotrepairafilesystemautomatically,the
systemmayenteremergencymodesoyoucanrunfsck
manually.Makenoteofanyordinaryfilesordirectoriesthatyou
repair(andcanidentify),andinformtheirownersthatthey
maynotbecompleteorcorrect.Lookinthelost+found
directoryineachfilesystemformissingfiles.Aftersuccessfully
runningfsck,typeexittoexitfromthesingle-usershelland
resumebooting.
Iffilesarenotcorrectoraremissingaltogether,youmayhave
torecreatethemfromabackupcopyofthefilesystem.For
moreinformationreferto"BackingUpFiles"onpage540.
WhentheSystemDoesNotBoot
Whenyoucannotbootthecomputerfromtheharddrive,you
cantrytobootthesystemintorescuemode.Formore
informationreferto"RescueMode"onpage397.Ifthesystem
comesupinrescuemode,runfsckontherootfilesystemand
trybootingfromtheharddriveagain.
Whenallelsefails,gothroughtheinstallprocedure,and
performan"upgrade"tothecurrentversionofLinux.RedHat
Linuxsystemscanperformanondestructiveupgradeandcan
fixquiteabitintheprocess.Formoreinformationrefertopage
27.
SystemAdministrationUtilities
Thissectionbrieflydescribesafewofthemanyutilitiesthatcan
helpyouperformsystemadministrationtasks.Someofthese
utilitiesareincorporatedaspartoftheMainmenu,andsome
areusefultousersotherthanthesystemadministrator.
RedHatConfigurationTools
MostoftheRedHatconfigurationtoolsarenamedsystem-config-
*.Manyofthesetoolsbringupagraphicaldisplaywhencalled
fromaGUIandatextualdisplaywhencalledfromanon-GUI
commandline.Ingeneral,thesetools,whicharelistedinTable
11-2,aresimpletouseandrequirelittleexplanationbeyond
whatthetoolpresents.SomehaveHelpselectionsontheir
toolbar;mostdonothavemanpages.
Table11-2.RedHatconfigurationtools
Tool Function
system-config-authentication DisplaystheAuthenticationConfiguration
windowwithtwotabs:UserInformation
andAuthentication.TheUserInformation
taballowsyoutoenableNIS,LDAP,
Hesiod,andWinbindsupport.The
Authenticationtaballowsyoutouse
shadowandMD5(page1042)passwords
aswellastoenableLDAP,Kerberos,SMB,
andWinbindsupport.
system-config-bind(FEDORA)DisplaystheDomainNameService
window.Formoreinformationseepage
734.
system-config-boot DisplaystheBootConfigurationwindow,
whichallowsyoutospecifywhichboot
entryin/etc/grub.conf(page533)the
systemshouldbootfrom.
system-config-date DisplaystheDate/TimeProperties
windowwithtwotabs:Date&Timeand
TimeZone.Youcansetthedateandtime
orenableNTP(NetworkTimeProtocol)
fromthefirsttab.TheTimeZonetab
allowsyoutospecifythetimezoneofthe
systemclockorsetthesystemclockto
UTC(page1062).
system-config-display BringsuptheDisplaySettingswindow
withthreetabs:Settings,Hardware,and
DualHead.Formoreinformationsee
page70.
system-config-httpd DisplaystheHTTPwindowwithfourtabs:
Main,VirtualHosts,Server,and
PerformanceTuning.Formore
informationseepage790.
system-config-keyboard DisplaystheKeyboardwindow,which
allowsyoutoselectthetypeofkeyboard
attachedtothesystem.Youusethis
utilitytoselectthekeyboardwhenyou
installthesystem.
system-config-kickstart DisplaystheKickstartConfigurator
window,whichallowsyoutocreatea
Kickstartscript.Formoreinformationsee
page63.
system-config-language DisplaystheLanguageSelectionwindow,
whichallowsyoutospecifythedefault
systemlanguagefromamongthosethat
areinstalled.Youusethisutilitytoselect
thesystemlanguagewhenyouinstallthe
system.
system-config-lvm DisplaystheLogicalVolumeManagement
window,whichallowsyoutomodify
existinglogicalvolumes.Formore
informationseepage32.
system-config-mouse(RHEL) DisplaystheMouseConfigurationwindow,
whichallowsyoutospecifythetypeof
mousethatisattachedtothesystem.
Youusethisutilitytoselectthesystem
mousewhenyouinstallthesystem.
system-config-netboot DisplaystheNetworkInstallationand
DisklessEnvironmentwindow,which
allowsyoutoconfigurethenetwork
installationoradisklessenvironment.
Thefirsttimeyourunthisutility,it
displaystheFirstTimeDruidwindow.
system-config-network DisplaystheNetworkConfiguration
window.Formoreinformationseepage
571.
system-config-network-cmd Displaystheparametersthatsystem-config-
networkuses.
system-config-nfs DisplaystheNFSServerConfiguration
window.Formoreinformationseepage
683.
system-config-packages(RHEL) DisplaysthePackageManagement
window.Youusethisutilitytocustomize
thelistofpackagesyouinstallwhenyou
installthesystem.
system-config-printer DisplaysthePrinterConfiguration
window,whichallowsyoutosetup
printersandeditprinterconfigurations.
Formoreinformationseepage505.
system-config-rootpassword DisplaystheRootPasswordwindow,
whichallowsyoutochangetheroot
password.Whileloggedinasroot,you
canalsousepasswdfromacommandline
tochangetherootpassword.
system-config-samba DisplaystheSambaServerConfiguration
window,whichcanhelpyouconfigure
Samba.Formoreinformationseepage
699.
system-config-securitylevel DisplaystheSecurityLevelConfiguration
windowwithtwotabs:FirewallOptions
(page768)andSELinux(page402).
system-config-services DisplaystheServiceConfiguration
window,whichallowsyoutospecify
whichdaemons(services)runateach
runlevel.Formoreinformationseepage
406.
system-config-soundcard DisplaystheAudioDeviceswindow,which
tellsyouwhichaudiodevicethesystem
detectedandgivesyoutheoptionof
playingasoundtotestthedevice.
system-config-users DisplaystheUserManagerwindow,which
allowsyoutoworkwithusersandgroups.
Formoreinformationseepage538.
system-logviewer(RHEL) DisplaystheSystemLogswindow,which
candisplayvarioussystemlogs.
system-switch-mail Displaysthesystem-switch-mailwindow,
whichallowsyoutochoosebetweenthe
sendmail(page627)andPostfix(page
652)MTAs.
Ifthetoolisnotpresentonyoursystem,useyum(page476)
onFEDORAsystemsorRHN(page498)onRHELsystemsto
installit.
CommandLineUtilities
Thissectiondescribesafewcommandlinesystem
administrationtoolsyoumayfinduseful.Tolearnmoreabout
mostoftheseutilities,readthemanpages.Forumaskanduname,
seetheinfopages.
chsh
Changestheloginshellforauser.Whenyoucallchshwithoutan
argument,youchangeyourownloginshell.Superusercan
changetheshellforanyuserbycallingchshwiththatuser's
usernameasanargument.Whenchangingaloginshellwith
chsh,youmustspecifyaninstalledshellthatislistedinthefile
/etc/shells;otherentriesarerejected.Also,youmustgive
thepathnametotheshellexactlyasitappearsin/etc/shells.
Thechshlist-shellscommanddisplaysthelistofavailable
shells.Inthefollowingexample,SuperuserchangesSam'sshell
totcsh:
#chshsam
Changingshellforsam.
Newshell[/bin/bash]:/bin/tcsh
Shellchanged.
clear
Clearsthescreen.YoucanalsouseCONTROL-Lfromthebash
shelltoclearthescreen.Thevalueoftheenvironmentvariable
TERM(page984)isusedtodeterminehowtoclearthescreen.
dmesg
Displaysrecentsystemlogmessages(page535).
e2label
Displaysorcreatesavolumelabelonanext2orext3disk
partition.Ane2labelcommandhasthefollowingformat:
e2labeldevice[newlabel]
wheredeviceisthenameofthedevice(/dev/hda2,
/dev/sdb1,/dev/fd0,andsoon)youwanttoworkwith.
Whenyouincludetheoptionalnewlabelparameter,e2label
changesthelabelondevicetonewlabel.Withoutthis
parameter,e2labeldisplaysthelabel.Youcanalsocreatea
volumelabelwiththeLoptionoftune2fs(page471).
kudzu
Findsnewandchangedhardwareandconfiguresit.Thisutility
determineswhichhardwareisnewbyprobingalldeviceson
internalandexternalbusesandcomparingtheresultstothe
/etc/sysconfig/hwconfdatabase.Inthedefault
configuration,the/etc/rc.d/init.d/kudzuscriptrunsand
callskudzuasthemachineentersrunlevels3and5.Whenit
findsneworchangedhardware,kudzugivesyouachanceto
configureitandpermitsyoutodeconfigureanyhardwarethat
youhaveremoved.
mkfs
Createsanewfilesystemonadevice.Thisutilityisafrontend
formanyutilities,eachofwhichbuildsadifferenttypeof
filesystem.Bydefault,mkfsbuildsanext2filesystemandworks
oneitheraharddiskpartitionorafloppydiskette.Althoughit
cantakemanyoptionsandarguments,youcanusemkfssimply
as
#mkfsdevice
wheredeviceisthenameofthedevice(/dev/hda2,
/dev/sdb1,/dev/fd0,andsoon)youwanttomakea
filesystemon.Usethetoptiontospecifyatypeoffilesystem.
Thefollowingcommandcreatesanext3filesystemondevice:
#mkfs-text3device
ping
Sendspacketstoaremotesystem.Thisutilitydetermines
whetheryoucanreacharemotesystemthroughthenetwork
anddetermineshowmuchtimeittakestoexchangemessages
withtheremotesystem.Referto"ping:TestsaNetwork
Connection"onpage365.
reset(linktotset)
Resetsterminalcharacteristics.Thevalueoftheenvironment
variableTERM(page984)determineshowtoresetthescreen.
Thescreeniscleared,thekillandinterruptcharactersaresetto
theirdefaultvalues,andcharacterechoisturnedon.Froma
graphicalterminalemulator,thiscommandalsochangesthe
sizeofthewindowtoitsdefault.Theresetutilityisusefulto
restoreyourscreentoasanestateafterithasbeencorrupted.
Itissimilartoansttysanecommand.
setserial
Getsandsetsserialportinformation.Superusercanusethis
utilitytoconfigureaserialport.Thefollowingcommandsets
theinputaddressof/dev/ttys0to0x100,theinterrupt(IRQ)
to5,andthebaudrateto115,000baud:
#setserial/dev/ttys0port0x100irq5spd_vhi
Youcanalsochecktheconfigurationofaserialportwith
setserial:
#setserial/dev/ttys0
/dev/ttyS0,UART:16550A,Port:0x0100,IRQ:5,Flags:spd_vhi
Normally,setserialiscalledwhenthesystemisbootingifaserial
portneedscustomconfiguration.
stat
Displaysinformationaboutafileorfilesystem.Thef
(filesystem)optionfollowedbythedevicenameormountpoint
ofafilesystemdisplaysinformationaboutthefilesystem
includingthemaximumlengthoffilenames(Nameleninthe
followingexample).Seethestatmanpageformoreinformation.
$stat-f/dev/hda
File:"/dev/hda"
ID:0Namelen:255Type:tmpfs
Blocksize:4096Fundamentalblocksize:4096
Blocks:Total:121237Free:121206Available:121206
Inodes:Total:121237Free:120932
umask
Ashellbuiltinthatspecifiesamaskthesystemusestosetup
accesspermissionswhenyoucreateafile.Aumaskcommand
hasthefollowingformat:
umask[mask]
wheremaskisathree-digitoctalnumberorasymbolicvalue
suchasyouwouldusewithchmod(page182).Themask
specifiesthepermissionsthatarenotallowed.Whenmaskis
anoctalnumber,thedigitscorrespondtothepermissionsfor
theownerofthefile,membersofthegroupthefileis
associatedwith,andeveryoneelse.Becausemaskspecifiesthe
permissionsthatarenotallowed,thesystemsubtractseachof
thethreedigitsfrom7whenyoucreateafile.Theresultis
threeoctalnumbersthatspecifytheaccesspermissionsforthe
file(thenumbersyouwouldusewithchmod).Amaskthatyou
specifyusingsymbolicvaluesspecifiesthepermissionsthatare
allowed.
Mostutilitiesandapplicationsdonotattempttocreatefileswith
executepermissions,regardlessofthevalueofmask;they
assumeyoudonotwantanexecutablefile.Asaresult,whena
utilityorapplication(suchastouch)createsafile,thesystem
subtractseachofthethreedigitsinmaskfrom6.Anexception
ismkdir,whichassumesthatyouwanttheexecute(accessin
thecaseofadirectory)bitset.
Thefollowingcommandssetthefile-creationpermissionsmask
anddisplaythemaskanditseffectwhenyoucreateafileanda
directory.Themaskof022,whensubtractedfrom777,gives
permissionsof644(rwrr)forafileand755(rwxr-xr-x)fora
directory.
$umask022
$umask
0022
$touchafile
$mkdiradirectory
$ls-ldafileadirectory
drwxr-xr-x2samsam4096May223:57adirectory
-rw-r--r--1samsam0May223:57afile
Thenextexamplesetsthesamemaskusingsymbolicvalues.
TheSoptiondisplaysthemasksymbolically:
$umasku=rwx,g=rx,o=rx
$umask
0022
$umask-S
u=rwx,g=rx,o=rx
uname
Displaysinformationaboutthesystem.Withoutanyarguments,
thisutilitydisplaysthenameoftheoperatingsystem(Linux).
Withaa(all)option,itdisplaystheoperatingsystemname,
hostname,versionnumberandreleasedateoftheoperating
system,andtypeofhardwareyouareusing:
#unamea
Linuxpbnj2.6.15-1.1871_FC5#1MonJan2315:53:52EST2006i686athloni386GNU/Linux
SettingUpaServer
Thissectiondiscussesissuesthatyoumayneedtoaddress
whensettingupaserver:howtowriteconfigurationfiles;how
tospecifyhostsandsubnets;howtouseport-map,rpcinfo,
xinetd,andTCPwrappers(hosts.allowandhosts.deny);and
howtosetupachrootjail.Settingupspecificserversiscovered
inChapters14and1826.SettingupaLANiscoveredin
Chapter17.
StandardRulesinConfigurationFiles
Mostconfigurationfiles,whicharetypicallynamed*.conf,rely
onthefollowingconventions:
Blanklinesareignored.
A#anywhereonalinestartsacommentthatcontinuesto
theendoftheline.Commentsareignored.
WhenanamecontainsaSPACE,youmustquotetheSPACE
byprecedingitwithabackslash(\)orbyenclosingthe
entirenamewithinsingleordoublequotationmarks.
Tomakelonglineseasiertoreadandedit,youcanbreak
themintoseveralshorterlines.Breakalinebyinsertinga
backslash(\)immediatelyfollowedbyaNEWLINE(press
RETURNinatexteditor).WhenyouinserttheNEWLINE
beforeorafteraSPACE,youcanindentthefollowinglineto
makeiteasiertoread.Donotbreaklinesinthismanner
whileeditingonaWindowsmachine,astheNEWLINEsmay
notbeproperlyescaped(WindowsusesRETURN-LINEFEEDs
toendlines).
Configurationfilesthatdonotfollowtheseconventionsare
notedinthetext.
SpecifyingClients
Table11-3showssomecommonwaystospecifyahostora
subnet.Mostofthetimeyoucanspecifymultiplehostsor
subnetsbyseparatingthehostorsubnetspecificationswith
SPACEs.
Table11-3.Specifyingaclient
Clientnamepattern Matches
n.n.n.n OneIPaddress.
name Onehostname,eitherlocalorremote.
Namethatstartswith.Matchesahostnamethatendswiththe
specifiedstring.Forexample,.tcorp.com
matchesthesystemskudos.tcorp.com
andspeedy.tcorp.com,amongothers.
IPaddressthatendswith.Matchesahostaddressthatstartswith
thespecifiednumbers.Forexample,
192.168.0.matches192.168.0.0
192.168.0.255.Ifyouomitthetrailing
period,thisformatdoesnotwork.
Startswith@Specifiesanetgroup
.n.n.n.n/m.m.m.mor
n.n.n.n/mm
AnIPaddressandsubnetmaskspecifya
subnet.
Startswith/ Anabsolutepathnameofafilecontaining
oneormorenamesoraddressesas
specifiedinthistable.
Wildcard Matches
*and?Matchesone(?)ormore(*)charactersin
asimplehostnameorIPaddress.These
wildcardsdonotmatchperiodsina
domainname.
ALL Alwaysmatches.
LOCAL Matchesanyhostnamethatdoesnot
containaperiod.
Operator
EXCEPT Matchesanythingintheprecedinglist
thatisnotinthefollowinglist.For
example,abcdEXCEPTcmatchesa,
b,andd.Thusyoucoulduse192.168.
EXCEPT192.168.0.1tomatchallIP
addressesthatstartwith192.168.
except192.168.0.1.
Examples
Eachofthefollowingexamplesspecifiesoneormoresystems:
10.10. MatchesallsystemswithIPaddressesthatstartwith
10.10.
.redhat.com MatchesallnamedhostsontheRedHatnetwork
localhost Matchesthelocalsystem
127.0.0.1 Theloopbackaddress;alwaysresolvestolocalhost
192.168.*.1 Couldmatchallroutersonanetworkof/24subnets
SpecifyingaSubnet
Whenyousetupaserver,youfrequentlyneedtospecifywhich
clientsareallowedtoconnecttotheserver.Sometimesitis
convenienttospecifyarangeofIPaddresses,calledasubnet.
Thediscussiononpage357explainswhatasubnetisandhow
touseasubnetmasktospecifyasubnet.Usually,youcan
specifyasubnetas
n.n.n.n/m.m.m.m
or
n.n.n.n/maskbits
wheren.n.n.nisthebaseIPaddressandthesubnetis
representedbym.m.m.m(thesubnetmask)ormaskbits(the
numberofbitsusedforthesubnetmask).Forexample,
192.168.0.1/255.255.255.0representsthesamesubnetas
192.168.0.1/24.Inbinary,decimal255.255.255.0is
representedby24onesfollowedby8zeros.The/24is
shorthandforasubnetmaskwith24ones.EachlineinTable
11-4presentstwonotationsforthesamesubnetfollowedby
therangeofIPaddressesthatthesubnetincludes.
Table11-4.Differentwaystorepresentasubnet
Bits Mask Range
10.0.0.0/8 10.0.0.0/255.0.0.0 10.0.0.010.255.255.255
172.16.0.0/12 172.16.0.0/255.240.0.0 172.16.0.0172.31.255.255
192.168.0.0/16 192.168.0.0/255.255.0.0 192.168.0.0
192.168.255.255
rpcinfo:DisplaysInformationAboutportmap
Therpcinfoutilitydisplaysinformationaboutprograms
registeredwithportmapandmakesRPCcallstoprogramsto
seeiftheyarealive.Formoreinformationonportmap,referto
"RPCNetworkServices"onpage377.Therpcinfoutilitytakes
thefollowingoptionsandarguments:
rpcinfop[host]
rpcinfo[nport]u|thostprogram[version]
rpcinfob|dprogramversion
p
(probe)ListsallRPCprogramsregisteredwithportmapon
hostoronthelocalsystemifhostisnotspecified.
n
(portnumber)Withtoru,usestheportnumberedport
insteadoftheportnumberspecifiedbyportmap.
u
(UDP)MakesaUDPRPCcalltoversion(ifspecified)of
programonhostandreportswhetheritreceivedaresponse.
t
(TCP)MakesaTCPRPCcalltoversion(ifspecified)of
programonhostandreportswhetheritreceivedaresponse.
b
(broadcast)MakesanRPCbroadcasttoversionofprogram
andlistshoststhatrespond.
d
(delete)RemoveslocalRPCregistrationforversionof
program.AvailabletoSuperuseronly.
GivethefollowingcommandtoseewhichRPCprogramsare
registeredwiththeportmapdaemononthesystemnamed
peach:
$/usr/sbin/rpcinfo-ppeach
programversprotoport
1000002tcp111portmapper
1000002udp111portmapper
1000241udp32768status
1000241tcp32768status
1000211udp32769nlockmgr
1000213udp32769nlockmgr
...
Usetheuoptiontodisplayalistofversionsofadaemon,such
asypserv,registeredonaremotesystem(peach):
$/usr/sbin/rpcinfo-upeachypserv
program100004version1readyandwaiting
program100004version2readyandwaiting
Specifylocalhosttodisplayalistofversionsofadaemon
registeredonthelocalsystem:
$/usr/sbin/rpcinfo-ulocalhostnfs
program100003version2readyandwaiting
program100003version3readyandwaiting
Lockingdownportmap
Becausetheportmapdaemonholdsinformationaboutwhich
serversarerunningonthelocalsystemandwhichporteach
serverisrunningon,onlytrustedsystemsshouldhaveaccess
tothisinformation.Onewaytoensurethatonlyselected
systemshaveaccesstoportmapistolockitdowninthe
/etc/hosts.allowand/etc/hosts.denyfiles(page427).Put
thefollowinglineinhosts.denytopreventallsystemsfrom
usingportmaponthelocal(server)system:
portmap:ALL
Testthissetupfromaremotesystemwiththefollowing
command:
$/usr/sbin/rpcinfo-phostname
Noremoteprogramsregistered.
Replacehostnamewiththenameoftheremotesystemthatyou
changedthehosts.denyfileon.Thechangeisimmediate;you
donotneedtokill/restartadaemon.
Nextaddthefollowinglinetothehosts.allowfileontheserver
system:
portmap:host-IP
wherehost-IPistheIPaddressofthetrusted,remotesystem
thatyougavetheprecedingrpcinfocommandfrom.UseonlyIP
addresseswithportmapinhosts.allow;donotusesystem
namesthatportmapcouldgetstucktryingtoresolve.Givethe
samerpcinfocommand,andyoushouldnowseealistofthe
serversthatRPCknowsabout,includingportmap.Seepage
661formoreexamples.
Caution:Settheclocks
Theportmapdaemonreliesontheclient'sandthe
server'sclocksbeingsynchronized.AsimpleDoS
attack(page1030)canbeinitiatedbysettingthe
server'sclocktothewrongtime.
ThexinetdSuperserver
Thexinetddaemonisamoresecurereplacementfortheinetd
superserverthatwasoriginallyshippedwith4.3BSD.The
xinetdsuperserverlistensfornetworkconnections.Whenone
ismade,itlaunchesaspecifiedserverdaemonandforwards
thedatafromthesocket(page462)tothedaemon'sstandard
input.
TheversionofxinetddistributedwithRedHatLinuxislinked
againstlibwrap.a,soitcanusethe/etc/hosts.allowand
/etc/hosts.denyfilesforaccesscontrol(see"TCPWrappers"
onpage427formoreinformation).UsingTCPwrapperscan
simplifyconfigurationbuthidessomeofthemoreadvanced
featuresofxinetd.
Tip:xinetdmaynotbeinstalled
Workingasroot,givethefollowingcommandto
installxinetdonaFEDORAsystem:
#yuminstallxinetd
UseRHNtoinstallitonaRHELsystem.
Thebaseconfigurationforxinetdisstoredinthe
/etc/xinetd.conffile.Ifthisfileisnotpresent,xinetdis
probablynotinstalled.Seetheprecedingtip.Thefilesupplied
withRedHatLinuxisshownhere:
$cat/etc/xinetd.conf
#
#Simpleconfigurationfileforxinetd
#
#Somedefaults,andinclude/etc/xinetd.d/
defaults
{
instances=60
log_type=SYSLOGauthpriv
log_on_success=HOSTPID
log_on_failure=HOST
cps=2530
}
includedir/etc/xinetd.d
Thedefaultssectionspecifiesthedefaultconfigurationof
xinetd;thefilesintheincludeddirectory,/etc/xinetd.d,
specifyserver-specificconfigurations.Defaultscanbe
overriddenbyserver-specificconfigurationfiles.
Intheprecedingfile,theinstancesdirectivespecifiesthatno
daemonmayrunmorethan60copiesofitselfatonetime.The
log_typedirectivespecifiesthatxinetdsendmessagestothe
systemlogdaemon(syslogd,page562)usingtheauthpriv
facility.Thenexttwolinesspecifywhattologonsuccessand
onfailure.Thecps(connectionspersecond)directivespecifies
thatnomorethan25connectionstoaspecificserviceshould
bemadepersecondandthattheserviceshouldbedisabledfor
30secondsifthislimitisexceeded.
Thefollowingxinetdconfigurationfileallowstelnetconnections
fromthelocalsystemandanysystemwithanIPaddressthat
startswith192.168..Thisconfigurationfiledoesnotrelyon
TCPwrappers,soitdoesnotrelyonthehosts.allowand
hosts.denyfiles.
$cat/etc/xinetd.d/telnet
servicetelnet
{
socket_type=stream
wait=no
user=root
server=/usr/sbin/in.telnetd
only_from=192.168.0.0/16127.0.0.1
disable=no
}
Thesocket_typeindicateswhetherthesocketusesTCPor
UDP.TCP-basedprotocolsestablishaconnectionbetweenthe
clientandtheserverandareidentifiedbythetypestream.
UDP-basedprotocolsrelyonthetransmissionofindividual
datagramsandareidentifiedbythetypedgram.
Whenwaitissettono,xinetdhandlesmultipleconcurrent
connectionstothisservice.Settingwaittoyescausesxinetd
towaitfortheserverprocesstocompletebeforehandlingthe
nextrequestforthatservice.Ingeneral,UDPservicesshould
besettoyesandTCPservicestono.Ifyouweretosetwaitto
yesforaservicesuchastelnet,onlyonepersonwouldbeable
tousetheserviceatanygiventime.
Theuserspecifieswhichusertheserverrunsas.Ifthisuseris
amemberofmultiplegroups,youcanalsospecifythegroupon
aseparatelinewiththekeywordgroup.Theuserdirectiveis
ignoredifxinetdisrunasotherthanroot.Theserver
providesthepathnameoftheserverprogramthatxinetdruns
forthisservice.
Theonly_fromspecifieswhichsystemsxinetdallowstouse
theservice.ItisagoodideatouseIPaddressesonlyusing
hostnamescanmaketheserviceunavailableifDNSfails.Zeros
attherightofanIPaddressaretreatedaswildcards.For
example,192.168.0.0allowsaccessfromanysysteminthe
192.168subnet.
Thedisablelinecandisableaservicewithoutremovingthe
configurationfile.AsshippedbyRedHat,anumberofservices
includeanxinetdconfigurationfilewithdisablesettoyes.To
runoneoftheseservices,changedisabletonointhe
appropriatefileinxinetd.dandrestartxinetd:
#/sbin/servicexinetdrestart
Stoppingxinetd:[OK]
Startingxinetd:[OK]
SecuringaServer
YoumaysecureaservereitherbyusingTCPwrappersorby
settingupachrootjail.
TCPWrappers:Client/ServerSecurity(hosts.allowand
hosts.deny)
Whenyouopenalocalsystemtoaccessfromremotesystems,
youmustensurethatthefollowingcriteriaaremet:
Openthelocalsystemonlytosystemsyouwanttoallowto
accessit.
Alloweachremotesystemtoaccessonlythedatayouwant
ittoaccess.
Alloweachremotesystemtoaccessdataonlyinthe
appropriatemanner(readonly,read/write,writeonly).
Aspartoftheclient/servermodel,TCPwrappers,whichcanbe
usedforanydaemonthatislinkedagainstlibwrap.a,relyon
the/etc/hosts.allowand/etc/hosts.denyfilesasthebasis
ofasimpleaccesscontrollanguage.Thisaccesscontrol
languagedefinesrulesthatselectivelyallowclientstoaccess
serverdaemonsonalocalsystembasedontheclient'saddress
andthedaemontheclienttriestoaccess.
Eachlineinthehosts.allowandhosts.denyfileshasthe
followingformat:
daemon_list:client_list[:command]
wheredaemon_listisacomma-separatedlistofoneormore
serverdaemons(suchasportmap,vsftpd,orsshd),
client_listisacomma-separatedlistofoneormoreclients
(seeTable11-3,"Specifyingaclient,"onpage422),andthe
optionalcommandisthecommandthatisexecutedwhena
clientfromclient_listtriestoaccessaserverdaemonfrom
daemon_list.
Whenaclientrequestsaconnectionwithalocalserver,the
hosts.allowandhosts.denyfilesareconsultedasfollowsuntil
amatchisfound:
1. Ifthedaemon/clientpairmatchesalineinhosts.allow,
accessisgranted.
2. Ifthedaemon/clientpairmatchesalineinhosts.deny,
accessisdenied.
3. Ifthereisnomatchineitherthehosts.alloworthe
hosts.denyfiles,accessisgranted.
Thefirstmatchdetermineswhethertheclientisallowedto
accesstheserver.Wheneitherhosts.alloworhosts.deny
doesnotexist,itisasthoughthatfilewasempty.Althoughitis
notrecommended,youcanallowaccesstoalldaemonsforall
clientsbyremovingbothfiles.
Examples
Foramoresecuresystem,putthefollowinglineinhosts.deny
toblockallaccess:
$cat/etc/hosts.deny...
ALL:ALL:echo'%ctriedtoconnectto%dandwasblocked'>>/var/log/tcpwrappers.log
Thislinepreventsanyclientfromconnectingtoanyservice,
unlessspecificallypermittedinhosts.allow.Whenthisruleis
matched,itaddsalinetothefilenamed
/var/log/tcpwrappers.log.The%cexpandstoclient
informationandthe%dexpandstothenameofthedaemon
theclientattemptedtoconnectto.
Withtheprecedinghosts.denyfileinplace,youcaninclude
linesinhosts.allowthatexplicitlyallowaccesstocertain
servicesandsystems.Forexample,thefollowinghosts.allow
fileallowsanyonetoconnecttotheOpenSSHdaemon(ssh,scp,
sftp)butallowstelnetconnectionsonlyfromthesamenetworkas
thelocalsystemandusersonthe192.168.subnet:
$cat/etc/hosts.allow
sshd:ALL
in.telnet:LOCAL
in.telnet:192.168.*127.0.0.1
...
Thefirstlineallowsconnectionfromanysystem(ALL)tosshd.
Thesecondlineallowsconnectionfromanysysteminthesame
domainastheserver(LOCAL).Thethirdlinematchesany
systemwhoseIPaddressstarts192.168.andthelocalsystem.
SettingUpachrootJail
OnearlyUNIXsystems,therootdirectorywasafixedpointin
thefilesystem.OnmodernUNIXvariants,includingLinux,you
candefinetherootdirectoryonaper-processbasis.Thechroot
utilityallowsyoutorunaprocesswitharootdirectoryother
than/.
Therootdirectoryappearsatthetopofthedirectoryhierarchy
andhasnoparent:Aprocesscannotaccessanyfilesabovethe
rootdirectory(becausetheydonotexist).If,forexample,you
runaprogram(process)andspecifyitsrootdirectoryas
/home/sam/jail,theprogramwouldhavenoconceptofany
filesin/home/samorabove:jailistheprogram'sroot
directoryandislabeled/(notjail).
Bycreatinganartificialrootdirectory,frequentlycalleda
(chroot)jail,youpreventaprogramfromaccessingor
modifyingpossiblymaliciouslyfilesoutsidethedirectory
hierarchystartingatitsroot.Youmustsetupachrootjail
properlytoincreasesecurity:Ifyoudonotsetupachrootjail
correctly,youcanactuallymakeiteasierforamalicioususerto
gainaccesstoasystemthaniftherewerenochrootjail.
Usingchroot
Creatingachrootjailissimple:Workingasroot,givethe
command/usr/sbin/chrootdirectory.Thedirectory
becomestherootdirectoryandtheprocessattemptstorunthe
defaultshell.Workingasrootfromthe/home/samdirectory,
thefollowingcommandsetsupachrootjailinthe(existing)
/home/sam/jaildirectory:
#/usr/sbin/chroot/home/sam/jail
/usr/sbin/chroot:cannotruncommand'/bin/bash':Nosuchfileordirectory
Thisexamplesetsupachrootjail,butwhenitattemptstorun
thebashshell,itfails.Oncethejailissetup,thedirectorythat
wasnamedjailtakesonthenameoftherootdirectory,/,so
chrootcannotfindthefileidentifiedbythepathname
/bin/bash.Inthissituationthechrootjailisworkingbutisnot
useful.
Gettingachrootjailtoworkthewayyouwantisabitmore
complicated.Tohavetheprecedingexamplerunbashinachroot
jail,youneedtocreateabindirectoryinjail
(/home/sam/jail/bin)andcopy/bin/bashtothisdirectory.
Becausethebashbinaryisdynamicallylinkedtosharedlibraries
(page840),youneedtocopytheselibrariesintojailaswell.
Thelibrariesgoinlib.Thenextexamplecreatesthenecessary
directories,copiesbash,useslddtodisplaythesharedlibrary
dependenciesofbash,andcopiesthenecessarylibrariesintolib.
Thelinux-gate.so.1fileisadynamicallysharedobject(DSO)
providedbythekerneltospeedsystemcalls;youdonotneed
tocopyittothelibdirectory.
$pwd
/home/sam/jail
$mkdirbinlib
$cp/bin/bashbin
$lddbin/bash
linux-gate.so.1=>(0x0089c000)
libtermcap.so.2=>/lib/libtermcap.so.2(0x00cdb000)
libdl.so.2=>/lib/libdl.so.2(0x00b1b000)
libc.so.6=>/lib/libc.so.6(0x009cb000)
/lib/ld-linux.so.2(0x009ae000)
$cp/lib/{libtermcap.so.2,libdl.so.2,libc.so.6,ld-linux.so.2}lib
Nowthateverythingissetup,youcanstartthechrootjailagain.
Althoughallofthesetupcanbedonebyanordinaryuser,you
havetorunchrootasSuperuser:
$su
Password:
#/usr/sbin/chroot.
bash-3.1#pwd
/
bash-3.1#ls
bash:ls:commandnotfound
bash-3.1#
Thistimethechrootfindsandstartsbash,whichdisplaysits
defaultprompt(bash-3.1#).Thepwdcommandworksbecause
itisashellbuiltin(page225).However,bashcannotfindthels
utility(itisnotinthechrootjail).Youcancopy/bin/lsandits
librariesintothejailifyouwantusersinthejailtobeableto
usels.
Tosetupausefulchrootjail,firstdeterminewhichutilitiesthe
usersofthechrootjailwillneed.Thencopytheappropriate
binariesandtheirlibrariesintothejail.Alternativelyyoucan
buildstaticcopiesofthebinariesandputtheminthejail
withoutinstallingseparatelibraries.(Thestaticallylinked
binariesareconsiderablylargerthantheirdynamic
counterparts.Thebasesystemwithbashandthecoreutilities
exceeds50megabytes.)Youcanfindthesourcecodeformost
ofthecommonutilitiesinthebashandcoreutilsSRPMS
(sourcerpm)packages.
Whichevertechniqueyouchoose,youmustputacopyofsuin
thejail.Thesucommandisrequiredtorunprogramsasauser
otherthanroot.Becauserootcanbreakoutofachrootjail,itis
imperativethatyourunaprograminthechrootjailasauser
otherthanroot.
ThedynamicversionofsudistributedbyRedHatrequiresPAM
andwillnotworkwithinajail.Youneedtobuildacopyofsu
fromthesourcetouseinajail.Bydefaultanycopyofsuyou
builddoesnotrequirePAM.Referto"GNUConfigureandBuild
System"onpage491forinstructionsonhowtobuildpackages
suchascoreutils(whichincludessu).
Tousesu,youmustcopytherelevantlinesfromthe
/etc/passwdand/etc/shadowfilesintofileswiththesame
namesintheetcdirectoryinsidethejail.
Tip:Keepingmultiplechrootjails
Ifyouplantodeploymultiplechrootjails,itisagood
ideatokeepacleancopyofthebinandlibfiles
somewhereotherthaninoneoftheactivejails.
RunningaServiceinachrootJail
Runningashellinsideajailhaslimitedusefulness.Insteadyou
aremorelikelytoneedtorunaspecificserviceinsidethejail.
Torunaserviceinsideajail,youmustmakesureallfiles
neededbythatserviceareinsidethejail.Theformatofa
commandtostartaserviceinachrootjailis
#/usr/sbin/chrootjailpath/bin/suuserdaemonname&
wherejailpathisthepathnameofthejaildirectory,useristhe
usernamethatrunsthedaemon,anddaemonnameisthepath
(insidethejail)ofthedaemonthatprovidestheservice.
Someserversarealreadysetuptotakeadvantageofchroot
jails.YoucansetupDNSsothatnamedrunsinajail(page
750),andthevsftpdFTPservercanautomaticallystartchroot
jailsforclients(page616).
SecurityConsiderations
Someservicesneedtoberunasroot,buttheyreleasetheir
rootprivilegeoncestarted(Procmailandvsftpdare
examples).Ifyouarerunningsuchaservice,youdonotneed
toputsuinsidethejail.
Aprocessrunasrootcouldpotentiallyescapefromachrootjail.
Forthisreason,youshouldalwayssutoanotheruserbefore
startingaprogramrunninginsidethejail.Also,becarefulabout
whichsetuid(page183)binariesyouallowinsideajaila
securityholeinoneofthemcouldcompromisethesecurityof
thejail.Inaddition,makesuretheusercannotaccess
executablefilesthatheuploads.
DHCP:ConfiguresHosts
Insteadofstoringnetworkconfigurationinformationinlocal
filesoneachsystem,DHCP(DynamicHostConfiguration
Protocol)enablesclientsystemstoretrievenetwork
configurationinformationeachtimetheyconnecttothe
network.ADHCPserverassignsanIPaddressesfromapoolof
addressestoclientsasneeded.Assignedaddressesaretypically
temporary,butneednotbe.
Thistechniquehasseveraladvantagesoverstoringnetwork
configurationinformationinlocalfiles:
AnewusercansetupanInternetconnectionwithout
havingtodealwithIPaddresses,netmasks,DNS
addresses,andothertechnicaldetails.Anexperienceduser
cansetupaconnectionmorequickly.
DHCPfacilitatesassignmentandmanagementofIP
addressesandrelatednetworkinformationbycentralizing
theprocessonaserver.Asystemadministratorcan
configurenewsystems,includinglaptopsthatconnectto
thenetworkfromdifferentlocations,touseDHCP;DHCP
thenassignsIPaddressesonlywheneachsystemconnects
tothenetwork.ThepoolofIPaddressesismanagedasa
groupontheDHCPserver.
IPaddressescanbeusedbymorethanonesystem,
reducingthetotalnumberofIPaddressesneeded.This
conservationofaddressesisimportantbecausetheInternet
isquicklyrunningoutofIPv4addresses.Althougha
particularIPaddresscanbeusedbyonlyonesystemata
time,manyend-usersystemsrequireaddressesonly
occasionally,whentheyconnecttotheInternet.Byreusing
IPaddresses,DHCPlengthensthelifeoftheIPv4protocol.
DHCPappliestoIPv4only,asIPv6forcessystemsto
configuretheirIPaddressesautomatically(called
autoconfiguration)whentheyconnecttoanetwork(page
359).
DHCPisparticularlyusefulforadministratorswhoare
responsibleformaintainingalargenumberofsystemsbecause
individualsystemsnolongerneedtostoreuniqueconfiguration
information.WithDHCP,theadministratorcansetupamaster
systemanddeploynewsystemswithacopyofthemaster's
harddisk.Ineducationalestablishmentsandotheropenaccess
facilities,theharddiskimagemaybestoredonashareddrive,
witheachworkstationautomaticallyrestoringitselftopristine
conditionattheendofeachday.
MoreInformation
Web
www.dhcp.org
FAQ
www.dhcp-handbook.com/dhcp_faq.html
HOWTO
DHCPMiniHOWTO
HowDHCPWorks
Theclientdaemon,dhclient(partofthedhcppackage),
contactstheserverdaemon,dhcpd,toobtaintheIPaddress,
netmask,broadcastaddress,nameserveraddress,andother
networkingparameters.TheserverprovidesaleaseontheIP
addresstotheclient.Theclientcanrequestthespecificterms
ofthelease,includingitsduration;theservercan,inturn,limit
theseterms.Whileconnectedtothenetwork,aclienttypically
requestsextensionsofitsleaseasnecessarysoitsIPaddress
remainsthesame.Theleasecanexpireoncetheclientis
disconnectedfromthenetwork,withtheservergivingtheclient
anewIPaddresswhenitrequestsanewlease.Youcanalsoset
upaDHCPservertoprovidestaticIPaddressesforspecific
clients(referto"StaticVersusDynamicIPAddresses"onpage
354).
DHCPisbroadcastbased,sobothclientandservermustbeon
thesamesubnet(page357).
DHCPClient
ADHCPclientrequestsnetworkconfigurationparametersfrom
theDHCPserverandusesthoseparameterstoconfigureits
networkinterface.
Prerequisites
Installthefollowingpackage:
dhclient
dhclient:TheDHCPClient
WhenaDHCPclientsystemconnectstothenetwork,dhclient
requestsaleasefromtheDHCPserverandconfiguresthe
client'snetworkinterface(s).OnceaDHCPclienthasrequested
andestablishedalease,itstoresinformationabouttheleasein
afilenameddhclient.leases,whichisstoredin
/var/lib/dhcp(RHEL)or/var/lib/dhclient(FEDORA).This
informationisusedtoreestablishaleasewheneithertheserver
ortheclientneedstoreboot.TheDHCPclientconfigurationfile,
/etc/dhclient.conf,isrequiredonlyforcustomconfigurations.
Thefollowingdhclient.conffilespecifiesasingleinterface,
eth0:
$cat/etc/dhclient.conf
interface"eth0"
{
senddhcp-client-identifier1:xx:xx:xx:xx:xx:xx;
senddhcp-lease-time86400;
}
Intheprecedingfile,the1inthedhcp-client-identifier
specifiesanEthernetnetworkandxx:xx:xx:xx:xx:xxisthe
MACaddress(page1041)ofthedevicecontrollingthat
interface.Seepage434forinstructionsonhowtodisplaya
MACaddress.Thedhcp-lease-timeistheduration,inseconds,
oftheleaseontheIPaddress.Whiletheclientisconnectedto
thenetwork,dhclientautomaticallyrenewstheleaseeachtime
halfoftheleaseisup.Theleasetimeof8,6400seconds(orone
day)isareasonablechoiceforaworkstation.
DHCPServer
TheDHCPservermaintainsalistofIPaddressesandother
configurationparameters.Whenrequestedtodoso,theDHCP
serverprovidesconfigurationparameterstoaclient.
Prerequisites
Installthefollowingpackage:
dhcp
Runchkconfigtocausedhcpdtostartwhenthesystementers
multiusermode:
#/sbin/chkconfigdhcpdon
Startdhcpd:
#/sbin/servicedhcpdstart
dhcpd:TheDHCPDaemon
AsimpleDCHPserverallowsyoutoaddclientstoanetwork
withoutmaintainingalistofassignedIPaddresses.Asimple
network,suchasahomeLANsharinganInternetconnection,
canuseDHCPtoassignadynamicIPaddresstoalmostall
nodes.Theexceptionsareserversandrouters,whichmustbe
atknownnetworklocationstobeabletoreceiveconnections.If
serversandroutersareconfiguredwithoutDHCP,youcan
specifyasimpleDHCPserverconfigurationin
/etc/dhcpd.conf:
$cat/etc/dhcpd.conf
default-lease-time600;
max-lease-time86400;
optionsubnet-mask255.255.255.0;
optionbroadcast-address192.168.1.255;
optionrouters192.168.1.1;
optiondomain-name-servers192.168.1.1;
subnet192.168.1.0netmask255.255.255.0{
range192.168.1.2192.168.1.200;
}
TheprecedingconfigurationfilespecifiesaLANwherethe
routerandDNSarebothlocatedon192.168.1.1.Thedefault-
lease-timespecifiesthenumberofsecondsthedynamicIP
leasewillremainvalidiftheclientdoesnotspecifyaduration.
Themax-lease-timeisthemaximumtimeallowedforalease.
Theinformationintheoptionlinesissenttoeachclientwhen
itconnects.Thenamesfollowingthewordoptionspecifywhat
thefollowingargumentrepresents.Forexample,theoption
broadcast-addresslinespecifiesthebroadcastaddressofthe
network.Theroutersanddomain-name-serversoptions
allowmultiplevaluesseparatedbycommas.
Thesubnetsectionincludesarangelinethatspecifiesthe
rangeofIPaddressesthattheDHCPservercanassign.Ifyou
definemultiplesubnets,youcandefineoptions,suchas
subnet-mask,insidethesubnetsection.Optionsdefined
outsideallsubnetsectionsareglobalandapplytoallsubnets.
Theprecedingconfigurationfileassignsaddressesintherange
between192.168.1.2and192.168.1.200.TheDHCPserver
startsatthebottomofthisrangeandattemptstoassignanew
IPaddresstoeachnewclient.OncetheDHCPserverreaches
thetopoftherange,itstartsreassigningIPaddressesthat
havebeenusedinthepast,butarenotcurrentlyinuse.Ifyou
havefewersystemsthanIPaddresses,theIPaddressofeach
systemshouldremainfairlyconstant.Youcannotusethesame
IPaddressformorethanonesystematatime.
OnceyouhaveconfiguredaDHCPserver,youcanstart(or
restart)itbyusingthedhcpdinitscript:
#/sbin/servicedhcpdrestart
Oncetheserverisrunning,clientsconfiguredtoobtainanIP
addressfromtheserverusingDHCPshouldbeabletodoso.
StaticIPAddresses
Asmentionedearlier,routersandserverstypicallyrequirestatic
IPaddresses.WhileyoucanmanuallyconfigureIPaddresses
forthesesystems,itmaybemoreconvenienttohavetheDHCP
serverprovidethemwithstaticIPaddresses.
WhenasystemthatrequiresaspecificstaticIPaddress
connectstothenetworkandcontactstheDHCPserver,the
serverneedsawaytoidentifythesystemsotheservercan
assigntheproperIPaddresstothesystem.TheDHCPserver
usestheMACaddress(page1041)ofthesystem'sEthernet
card(NIC)asanidentifier.Whenyousetuptheserver,you
mustknowtheMACaddressofeachsystemthatrequiresa
staticIPaddress.
DisplayingaMACaddress
YoucanuseifconfigtodisplaytheMACaddressesofthe
Ethernetcards(NICs)inasystem.Inthefollowingexample,
theMACaddressesarethecolon-separatedseriesof
hexadecimalnumberpairsfollowingHWaddr:
$/sbin/ifconfig|grep-ihwaddr
eth0Linkencap:EthernetHWaddrBA:DF:00:DF:C0:FF
eth1Linkencap:EthernetHWaddr00:02:B3:41:35:98
RunifconfigoneachsystemthatrequiresastaticIPaddress.
OnceyouhavedeterminedtheMACaddressofeachofthese
systems,youcanaddahostsectiontothe/etc/dhcpd.conf
fileforeachsystem,instructingtheDHCPservertoassigna
specificaddresstothesystem.Thefollowinghostsection
assignstheaddress192.168.1.1tothesystemwiththeMAC
addressofBA:DF:00:DF:C0:FF:
$cat/etc/dhcpd.conf
...
hostrouter{
hardwareethernetBA:DF:00:DF:C0:FF;
fixed-address192.168.1.1;
optionhost-namerouter;
}
Thenamefollowinghostisusedinternallybydhcpd.The
namespecifiedafteroptionhost-nameispassedtotheclient
andcanbeahostnameoranFQDN.
Aftermakingchangestodhcpd.conf,restartdhcpdusing
serviceandthedhcpdinitscript(page433).
nsswitch.conf:WhichServicetoLookatFirst
WiththeadventofNISandDNS,findinguserandsystem
informationwasnolongerasimplematterofsearchingalocal
file.Whereonceyoulookedin/etc/passwdtogetuser
informationandin/etc/hoststofindsystemaddress
information,youcannowuseseveralmethodstofindthistype
ofinformation.The/etc/nsswitch.conf(nameserviceswitch
configuration)filespecifieswhichmethodstouseandtheorder
inwhichtousethemwhenlookingforacertaintypeof
information.Youcanalsospecifywhatactionthesystemtakes
basedonwhetheramethodworksorfails.
Format
Eachlineinnsswitch.confspecifieshowtosearchforapiece
ofinformation,suchasauser'spassword.Alinein
nsswitch.confhasthefollowingformat:
info:method[[action]][method[[action]]...]
whereinfospecifiesthetypeofinformationthattheline
describes,methodisthemethodusedtofindtheinformation,
andactionistheresponsetothereturnstatusofthepreceding
method.Theactionisenclosedwithinsquarebrackets.
Hownsswitch.confWorks
Whencalledupontosupplyinformationthatnsswitch.conf
describes,thesystemexaminesthelinewiththeappropriate
infofield.Itusesthemethodsspecifiedonthelinestarting
withthemethodontheleft.Bydefault,whenitfindsthe
desiredinformation,thesystemstopssearching.Withoutan
actionspecification,whenamethodfailstoreturnaresult,the
systemtriesthenextaction.Itispossibleforthesearchtoend
withoutfindingtherequestedinformation.
Information
Thensswitch.conffilecommonlycontrolssearchesforusers
(inpasswd),passwords(inshadow),hostIPaddresses,and
groupinformation.Thefollowinglistdescribesmostofthetypes
ofinformation(infointheformatdiscussedearlier)that
nsswitch.confcontrolssearchesfor.
automount Automount(/etc/auto.masterand/etc/auto.misc,
page690)
bootparams Disklessandotherbootingoptions(Seethe
bootparammanpage.)
ethers MACaddress(page1041)
group Groupsofusers(/etc/group,page451)
hosts Systeminformation(/etc/hosts,page452)
netgroup Netgroupinformation(/etc/netgroup,page453)
networks Networkinformation(/etc/networks)
passwd Userinformation(/etc/passwd,page454)
protocols Protocolinformation(/etc/protocols,page455)
publickey UsedforNFSrunninginsecuremode
rpc RPCnamesandnumbers(/etc/rpc,page456)
services Servicesinformation(/etc/services,page456)
shadow Shadowpasswordinformation(/etc/shadow,page
456)
Methods
Followingisalistofthetypesofinformationthat
nsswitch.confcontrolssearchesfor(methodintheformaton
page435).Foreachtypeofinformation,youcanspecifyoneor
moreofthefollowingmethods:[2]
[2]Thereareother,lesscommonlyusedmethods.Seethedefault/etc/nsswitch.conffile
andthensswitch.confmanpageformoreinformation.AlthoughNIS+belongsinthis
list,itisnotimplementedforLinuxandisnotdiscussedinthisbook.
files Searcheslocalfilessuchas/etc/passwdand
/etc/hosts
nis SearchestheNISdatabase;ypisanaliasfornis
dns QueriestheDNS(hostsqueriesonly)
compat ±syntaxinpasswd,group,andshadowfiles(page
438)
SearchOrder
Theinformationprovidedbytwoormoremethodsmayoverlap:
Forexample,filesandnismayeachprovidepassword
informationforthesameuser.Withoverlappinginformation,
youneedtoconsiderwhichmethodyouwanttobe
authoritative(takeprecedence),andputthatmethodattheleft
ofthelistofmethods.
Thedefaultnsswitch.conffilelistsmethodswithoutactions,
assumingnooverlap(whichisnormal).Inthiscase,theorder
isnotcritical:Whenonemethodfails,thesystemgoestothe
nextone;allthatislostisalittletime.Orderbecomescritical
whenyouuseactionsbetweenmethods,orwhenoverlapping
entriesdiffer.
Thefirstofthefollowinglinesfromnsswitch.confcausesthe
systemtosearchforpasswordinformationin/etc/passwd
and,ifthatfails,touseNIStofindtheinformation.Iftheuser
youarelookingforislistedinbothplaces,theinformationin
thelocalfilewouldbeusedandthereforewouldbe
authoritative.ThesecondlineusesNIS;ifthatfails,itsearches
/etc/hosts;ifthatfails,itcheckswithDNStofindhost
information.
passwdfilesnis
hostsnisfilesdns
ActionItems
Eachmethodcanoptionallybefollowedbyanactionitemthat
specifieswhattodoifthemethodsucceedsorfailsforanyofa
numberofreasons.Anactionitemhasthefollowingformat:
[[!]STATUS=action]
wheretheopeningandclosingsquarebracketsarepartofthe
formatanddonotindicatethatthecontentsareoptional;
STATUS(byconventionuppercasealthoughitisnotcase
sensitive)isthestatusbeingtestedfor;andactionisthe
actiontobetakenifSTATUSmatchesthestatusreturnedby
theprecedingmethod.Theleadingexclamationpoint(!)is
optionalandnegatesthestatus.
STATUS
ValuesforSTATUSareasfollows:
NOTFOUNDThemethodworkedbutthevaluebeingsearched
forwasnotfound.Defaultactioniscontinue.
SUCCESSThemethodworkedandthevaluebeingsearchedfor
wasfound;noerrorwasreturned.Defaultactionisreturn.
UNAVAILThemethodfailedbecauseitispermanently
unavailable.Forexample,therequiredfilemaynotbe
accessibleortherequiredservermaybedown.Defaultactionis
continue.
TRYAGAINThemethodfailedbecauseitwastemporarily
unavailable.Forexample,afilemaybelockedoraserver
overloaded.Defaultactioniscontinue.
action
Valuesforactionareasfollows:
returnReturnstothecallingroutinewithorwithoutavalue.
continueContinueswiththenextmethod.Anyreturnedvalue
isoverwrittenbyavaluefoundbythenextmethod.
Example
Forexample,thefollowinglinefromnsswitch.confcausesthe
systemfirsttouseDNStosearchfortheIPaddressofagiven
host.TheactionitemfollowingtheDNSmethodtestswhether
thestatusreturnedbythemethodisnot(!)UNAVAIL.
hostsdns[!UNAVAIL=return]files
ThesystemtakestheactionassociatedwiththeSTATUS
(return)iftheDNSmethoddoesnotreturnUNAVAIL
(!UNAVAIL)thatis,ifDNSreturnsSUCCESS,NOTFOUND,or
TRYAGAIN.Theresultisthatthefollowingmethod(files)is
usedonlywhentheDNSserverisunavailable:IftheDNS
serverisnotunavailable(readthetwonegativesas"is
available"),thesearchreturnsthedomainnameorreportsthat
thedomainnamewasnotfound.Thesearchusesthefiles
method(checkthelocal/etc/hostsfile)onlyiftheserveris
notavailable.
compatMethod:±inpasswd,group,andshadowFiles
Youcanputspecialcodesinthe/etc/passwd,/etc/group,
and/etc/shadowfilesthatcausethesystem,whenyou
specifythecompatmethodinnsswitch.conf,tocombineand
modifyentriesinthelocalfilesandtheNISmaps.
Aplussign(+)atthebeginningofalineinoneofthesefiles
addsNISinformation;aminussign()removesinformation.For
example,tousethesecodesinthepasswdfile,specify
passwd:compatinnsswitch.conf.Thesystemthengoes
throughthepasswdfileinorder,addingorremovingthe
appropriateNISentrieswhenitreacheseachlinethatstarts
witha+or.
Althoughyoucanputaplussignattheendofthepasswdfile,
specifypasswd:compatinnsswitch.conftosearchthelocal
passwdfile,andthengothroughtheNISmap,itismore
efficienttoputpasswd:filenisinnsswitch.confandnot
modifythepasswdfile.
PAM
PAM(actuallyLinux-PAM,orLinuxPluggableAuthentication
Modules)allowsasystemadministratortodeterminehow
applicationsuseauthentication(page1020)toverifythe
identityofauser.PAMprovidessharedlibraries(page840)of
modules(locatedin/lib/security)that,whencalledbyan
application,authenticateauser.Theterm"Pluggable"inPAM's
namereferstotheeasewithwhichyoucanaddandremove
modulesfromtheauthenticationstack.Theconfigurationfiles
keptinthe/etc/pam.ddirectorydeterminethemethodof
authenticationandcontainalist,orstack,ofcallstothe
modules.PAMmayalsouseotherfiles,suchas/etc/passwd,
whennecessary.
Insteadofbuildingtheauthenticationcodeintoeach
application,PAMprovidessharedlibrariesthatkeepthe
authenticationcodeseparatefromtheapplicationcode.The
techniquesofauthenticatingusersstaythesamefrom
applicationtoapplication.PAMenablesasystemadministrator
tochangetheauthenticationmechanismforagivenapplication
withoutevertouchingtheapplication.
PAMprovidesauthenticationforavarietyofsystem-entry
services(login,ftp,andsoon).YoucantakeadvantageofPAM's
abilitytostackauthenticationmodulestointegratesystem-
entryserviceswithdifferentauthenticationmechanisms,such
asRSA,DCE,Kerberos,andsmartcards.
Fromloginthroughusingsutoshuttingthesystemdown,
wheneveryouareaskedforapassword(ornotaskedfora
passwordbecausethesystemtruststhatyouarewhoyousay
youare),PAMmakesitpossibleforsystemadministratorsto
configuretheauthenticationprocess.Italsomakesthe
configurationprocessessentiallythesameforallapplications
thatusePAMforauthentication.
Theconfigurationfilesstoredin/etc/pam.ddescribethe
authenticationprocedureforeachapplication.Thesefiles
usuallyhavenamesthatarethesameasorsimilartothename
oftheapplicationthattheyauthenticatefor.Forexample,
authenticationfortheloginutilityisconfiguredin
/etc/pam.d/login.Thenameofthefileisthenameofthe
PAMservice[3]thatthefileconfigures.Occasionallyonefilemay
servetwoprograms.PAMacceptsonlylowercaselettersinthe
namesoffilesinthe/etc/pam.ddirectory.
[3]ThereisnorelationshipbetweenPAMservicesandthe/etc/servicesfile.Thenameof
thePAMserviceisanarbitrarystringthateachapplicationgivestoPAM;PAMthenlooks
uptheconfigurationfilewiththatnameandusesittocontrolauthentication.Thereisno
centralregistryofPAMservicenames.
Caution:Donotlockyourselfoutofthe
system
EditingPAMconfigurationfilescorrectlytakescare
andattention.Itisalltooeasytolockyourselfout
ofthecomputerwithasinglemistake.Toavoidthis
problem,alwayskeepbackupcopiesofthePAM
configurationfilesyouedit,testeverychange
thoroughly,andmakesureyoucanstillloginonce
thechangeisinstalled.KeepaSuperusersession
openuntilyouhavefinishedtesting.Whenachange
failsandyoucannotlogin,usetheSuperuser
sessiontoreplacethenewlyeditedfileswiththeir
backupcopies.
PAMwarnsyouabouterrorsitencounters,loggingthemtothe
/var/log/messagesor/var/log/securefiles.Reviewthese
filesifyouaretryingtofigureoutwhyachangedPAMfileisnot
workingproperly.Topreventamalicioususerfromseeing
informationaboutPAMunnecessarily,PAMsendserror
messagestoafileratherthantothescreen.
MoreInformation
Local
/usr/share/doc/pam-*/html/index.html
Web
Linux-PAMSystemAdministrators'Guide
www.kernel.org/pub/linux/libs/pam/Linux-PAM-html/pam.html
HOWTO
UserAuthenticationHOWTO
ConfigurationFiles,ModuleTypes,andControl
Flags
FollowingisanexampleofaPAMconfigurationfile.Comment
linesbeginwithapoundsign(#).
Loginmodule
$cat/etc/pam.d/login
%PAM-1.0authrequiredpam_securetty.so
authincludesystem-auth
accountrequiredpam_nologin.so
accountincludesystem-auth
passwordincludesystem-auth
pam_selinux.socloseshouldbethefirstsessionrule
sessionrequiredpam_selinux.soclose
sessionincludesystem-auth
sessionrequiredpam_loginuid.so
sessionoptionalpam_console.so
pam_selinux.soopenshouldbethelastsessionrule
sessionrequiredpam_selinux.soopen
Thefirstlineisaspecialcomment;itwillbecomesignificant
onlyifanotherPAMformatisreleased.Donotuse#%other
thaninthefirstlineoftheprecedingexample.
TherestofthelinestellPAMtodosomethingaspartofthe
authenticationprocess.Linesthatbeginwith#arecomments.
Thefirstwordoneachlineisamoduletypeindicator:account,
auth,password,orsession(Table11-5).Thesecondisa
controlflag(Table11-6),whichindicatestheactionPAMshould
takeifauthenticationfails.Therestofthelinecontainsthe
nameofaPAMmodule(locatedin/lib/security)andany
argumentsforthatmodule.ThePAMlibraryitselfusesthe
/etc/pam.dfilestodeterminewhichmodulestodelegatework
to.
Table11-5.Moduletypeindicators
Moduletype Description Controls
account Account
management
Determiningwhetheranalready
authenticateduserisallowedtousethe
servicesheistryingtouse.(Thatis,has
theaccountexpired?Istheuserallowed
tousethisserviceatthistimeofday?)
auth Authentication Provingthattheuserisauthorizedtouse
theservice.Thismaybedoneusing
passwordsoranothermechanism.
password Password
modification
Updatingauthenticationmechanismssuch
asuserpasswords.
session Session
management
Settingthingsupwhentheserviceis
started(aswhentheuserlogsin)and
breakingthemdownwhentheserviceis
terminated(aswhentheuserlogsout).
YoucanuseoneofthecontrolflagkeywordslistedinTable11-
6tosetthecontrolflags.
Table11-6.Controlflagkeywords
Keyword Flagfunction
required Successisrequiredforauthenticationtosucceed.
Controlandafailureresultarereturnedafterall
modulesinthestackhavebeenexecuted.The
techniqueofdelayingthereporttothecallingprogram
untilallmoduleshavebeenexecutedmaykeep
attackersfromknowingwhatcausedtheir
authenticationattemptstofailandtellthemlessabout
thesystem,makingitmoredifficultforthemtobreak
in.
requisite Successisrequiredforauthenticationtosucceed.
Furthermoduleprocessingisaborted,andcontrolis
returnedimmediatelyafteramodulefails.This
techniquemayexposeinformationaboutthesystemto
anattacker.However,ifitpreventsauserfromgivinga
passwordoveraninsecureconnection,itmightkeep
informationoutofthehandsofanattacker.
sufficient Successindicatesthatthismoduletypehassucceeded,
andnosubsequentrequiredmodulesofthistypeare
executed.Failureisnotfataltothestackofthismodule
type.Thistechniqueisgenerallyusedwhenoneformof
authenticationoranotherisgoodenough:Ifonefails,
PAMtriestheother.Forexample,whenyouusershto
connecttoanothercomputer,pam_rhostsfirstchecks
whetheryourconnectioncanbetrustedwithouta
password.Iftheconnectioncanbetrusted,the
pam_rhostsmodulereportssuccess,andPAM
immediatelyreportssuccesstothershdaemonthat
calledit.Youwillnotbeaskedforapassword.Ifyour
connectionisnotconsideredtrustworthy,PAMstartsthe
authenticationover,askingforapassword.Ifthis
secondauthenticationsucceeds,PAMignoresthefact
thatthepam_rhostsmodulereportedfailure.Ifboth
modulesfail,youwillnotbeabletologin.
optional Resultisgenerallyignored.Anoptionalmoduleis
relevantonlywhenitistheonlymoduleonthestack
foraparticularservice.
PAMuseseachofthemoduletypesasrequestedbythe
application.Thatis,theapplicationwillaskPAMseparatelyto
authenticate,checkaccountstatus,managesessions,and
changethepassword.PAMwilluseoneormoremodulesfrom
the/lib/securitydirectorytoaccomplisheachofthesetasks.
Theconfigurationfilesin/etc/pam.dlistthesetofmodulesto
beusedforeachapplicationtoperformeachtask.Eachsuch
setofthesamemoduletypesiscalledastack.PAMcallsthe
modulesoneatatimeinorder,fromthetopofthestack(the
firstmodulelistedintheconfigurationfile)tothebottom.Each
modulereportssuccessorfailurebacktoPAM.Whenallstacks
ofmodules(withsomeexceptions)withinaconfigurationfile
havebeencalled,thePAMlibraryreportssuccessorfailureback
totheapplication.
Example
Partoftheloginservice'sauthenticationstackfollows:
$cat/etc/pam.d/login
#%PAM-1.0
authrequiredpam_securetty.so
authincludesystem-auth
accountrequiredpam_nologin.so
...
TheloginutilityfirstasksforausernameandthenasksPAMto
runthisstacktoauthenticatetheuser.RefertoTable11-5and
Table11-6onpage440.
1. PAMfirstcallsthepam_securetty(securetty)moduleto
makesurethattherootuserlogsinonlyfromanallowed
terminal(bydefault,rootisnotallowedtorunloginover
thenetwork;thispolicyhelpspreventsecuritybreaches).
Thepam_securettymoduleisrequiredtosucceedifthe
authenticationstackistosucceed.Thepam_securetty
modulereportsfailureonlyifsomeoneistryingtologinas
rootfromanunauthorizedterminal.Otherwise(ifthe
usernamebeingauthenticatedisnotrootorifthe
usernameisrootandtheloginattemptisbeingmadefrom
asecureterminal),thepam_securettymodulereports
success.
SuccessandfailurewithinPAMareopaqueconceptsthat
applyonlytoPAM.Theydonotequatetotrueandfalseas
usedelsewhereintheoperatingsystem.
2. Thesystem-authmodulechecksthattheuserwhois
logginginisauthorizedtodoso,includingverificationofthe
usernameandpassword.
3. Thepam_nologinmodulemakessurethatifthe
/etc/nologin.txtfileexists,onlytherootuserisallowed
tologin.(Thatis,thepam_nologinmodulereports
successonlyif/etc/nologin.txtdoesnotexistorifthe
rootuserisloggingin.)Thus,whenashutdownhasbeen
scheduledforsometimeinthenearfuture,thesystem
administratorcankeepusersfromlogginginonthesystem
onlytoexperienceashutdownmomentslater.
Theaccountmoduletypeworksliketheauthmoduletypebut
iscalledaftertheuserhasbeenauthenticated;itactsasan
additionalsecuritycheckorrequirementforausertogain
accesstothesystem.Forexample,accountmodulesmight
enforceapolicythatausercanloginonlyduringbusiness
hours.
Thesessionmoduletypesetsupandtearsdownthesession
(perhapsmountingandunmountingtheuser'shomedirectory).
OnecommonsessionmoduleonaRedHatLinuxsystemisthe
pam_consolemodule,whichsetsthesystemupespeciallyfor
userswhologinatthephysicalconsole,ratherthanremotely.
AlocaluserisabletoaccessthefloppyandCDdrives,the
soundcard,andsometimesotherdevicesasdefinedbythe
systemadministrator.
Thepasswordmoduletypeisabitunusual:Allmodulesinthe
stackarecalledonce;theyaretoldtogetallinformationthey
needtostorethepasswordtopersistentmemory,suchasa
disk,butnotactuallytostoreit.Ifitdeterminesthatitcannot
orshouldnotstorethepassword,amodulereportsfailure.Ifall
passwordmodulesinthestackreportsuccess,theyarecalled
asecondtimeandtoldtostoretopersistentmemorythe
passwordtheyobtainedonthefirstpass.Thepassword
moduleisresponsibleforupdatingtheauthentication
information(thatis,changingtheuser'spassword).
Anyonemodulecanactasmorethanonemoduletype;many
modulescanactasallfourmoduletypes.
ModifyingthePAMConfiguration
SomeUNIXsystemsrequirethatauserbeamemberofthe
wheelgrouptousethesucommand.AlthoughRedHatLinuxis
notconfiguredthiswaybydefault,PAMallowsyoutochange
thedefaultbyeditingthe/etc/pam.d/sufile:
$cat/etc/pam.d/su
#%PAM-1.0
authsufficientpam_rootok.so
#Uncommentthefollowinglinetoimplicitlytrustusersinthe"wheel"group.
#authsufficientpam_wheel.sotrustuse_uid
#Uncommentthefollowinglinetorequireausertobeinthe"wheel"group.
#authrequiredpam_wheel.souse_uid
authincludesystem-auth
accountincludesystem-auth
passwordincludesystem-auth
sessionincludesystem-auth
sessionoptionalpam_xauth.so
Thethirdthroughsixthlinesofthesumodulecontain
commentsthatincludethelinesnecessarytopermitmembers
ofthewheelgrouptorunsuwithoutsupplyingapassword
(sufficient)andtopermitonlyuserswhoareinthewheel
grouptousesu(required).Uncommentoneoftheselineswhen
youwantthesystemtofollowoneoftheserules.
Caution:Brackets([])inthecontrol
flagsfield
Youcansetthecontrolflagsinamorecomplexway
thandescribedinthissection.Whenyousee
brackets([])inthecontrolflagspositioninaPAM
configurationfile,thenewer,morecomplexmethod
isinuse.Eachcomma-delimitedargumentisa
value=actionpair.Whentheresultreturnedbythe
functionmatchesvalue,actionisevaluated.For
moreinformationrefertothePAMSystem
Administrator'sGuide(/usr/share/doc/pam-
*/txts/pam.txt).
Caution:Donotcreate/etc/pam.conf
YoumayhaveencounteredPAMonothersystems
whereallconfigurationisarrangedinasinglefile
(/etc/pam.conf).ThisfiledoesnotexistonRed
HatLinuxsystems.Instead,the/etc/pam.d
directorycontainsindividualconfigurationfiles,one
perapplicationthatusesPAM.Thissetupmakesit
easytoinstallanduninstallapplicationsthatuse
PAMbecauseyoudonothavetomodifythe
/etc/pam.conffileeachtime.Ifyoucreatea
/etc/pam.conffileonasystemthatdoesnotuse
thisfile,thePAMconfigurationmaybecome
confused.DonotusePAMdocumentationfroma
differentsystem.Also,therequisitecontrolflagis
notavailableonsomesystemsthatsupportPAM.
ChapterSummary
Asystemadministratorissomeonewhokeepsthesystem
usefulandconvenientforitsusers.Muchoftheworkyoudoas
thesystemadministratorrequiresyoutologinasroot.The
rootuser,calledSuperuser,hasextensivesystemwidepowers
thatnormalusersdonothave.Superusercanreadfromand
writetoanyfileandcanexecuteprogramsthatordinaryusers
arenotpermittedtoexecute.
Youcanbringupthesysteminsingle-usermode.Inthismode,
onlythesystemconsoleisfunctional.Whenthesystemisin
single-usermode,youcanbackupfilesandusefscktocheck
theintegrityoffilesystemsbeforeyoumountthem.Thetelinit
utilitybringsthesystemtoitsnormalmultiuserstate.Withthe
systemrunninginmultiusermode,youcanstillperformmany
administrationtasks,suchasaddingusersandprinters.
Thesystemadministratorcontrolssystemoperation,which
includesmanytasks:configuringthesystem;bootingup;
runninginitscripts;settingupservers;workinginsingle-user,
multiuser,andrescuemodes;bringingthesystemdown;and
handlingsystemcrashes.RedHatLinuxprovidesmany
configurationtools,bothgraphicalandtextual.Manyofthese
toolsarenamedsystem-config-*.
Thexinetdsuperserverstartsserverdaemonsasneededand
canhelpsecureasystembycontrollingwhocanusewhich
services.YoucanalsouseTCPwrapperstocontrolwhocanuse
whichsystemservicesbyeditingthehosts.allowand
hosts.denyfilesinthe/etcdirectory.Bylimitingtheportionof
thefilesystemausersees,settingupachrootjailcanhelp
controlthedamageamalicioususercando.
YoucansetupaDHCPserversoyoudonothavetoconfigure
eachsystemonanetworkmanually.Thistaskcanentailsetting
upbothstaticanddynamicIPaddressesusingDHCP.Whethera
systemusesNIS,DNS,localfiles,oracombination(andin
whatorder)asasourceofinformationisdeterminedby
/etc/nsswitch.conf.Linux-PAMenablesyoutomaintainfine-
grainedcontroloverwhocanaccessthesystem,howtheycan
accessit,andwhattheycando.
Exercises
1. Howdoessingle-usermodedifferfrommultiusermode?
2.
Howwouldyoucommunicateeachofthefollowingmessages?
a. Thesystemiscomingdowntomorrowat6:00intheeveningforperiodic
maintenance.
b. Thesystemiscomingdownin5minutes.
c. Jenny'sjobsareslowingthesystemdowndrastically,andsheshould
postponethem.
d. Alex'swifejusthadababygirl.
3.
Whatdothelettersofthesucommandstandfor?(Hint:ItisnotSuperuser.)What
canyoudowithsubesidesgiveyourselfSuperuserprivileges?Howwouldyoulog
inasAlexifyoudidnotknowhispasswordbutknewtherootpassword?How
wouldyouestablishthesameenvironmentthatAlexhaswhenhefirstlogsin?
4. Howwouldyouallowausertoexecuteprivilegedcommandswithoutgivingthe
usertheSuperuserpassword?
5. AssumeyouareworkingasSuperuser.Howdoyoukillprocess1648?Howdoyou
killallprocessesrunningkmail?
6. HowcanyoudisableSELinux?
7. Developastrategyforcomingupwithapasswordthatanintruderwouldnotbe
likelytoguessbutthatyouwillbeabletoremember.
AdvancedExercises
8.
Givethecommand
$/sbin/fuser-uv/
Whatisthisalistof?Whyisitsolong?Givethesamecommandasroot(orask
thesystemadministratortodosoandemailyoutheresults).Howdoesthislist
differfromthefirst?Whyisitdifferent?
9.
Whenitputsfilesinalost+founddirectory,fsckhaslostthedirectoryinformation
forthefilesandthushaslostthenamesofthefiles.Eachfileisgivenanewname,
whichisthesameastheinodenumberforthefile:
$lslglost+found
rwrr1alexpubs110Jun1010:5551262
Whatcanyoudotoidentifythesefilesandrestorethem?
10. Takealookat/usr/bin/lesspipe.sh.Explainwhatitdoesandsixwaysitworks.
11. Whyaresetuidshellscriptsinherentlyunsafe?
12.
Whenauserlogsin,youwouldlikethesystemtofirstcheckthelocal
/etc/passwdfileforausernameandthencheckNIS.Howdoyouimplementthis
strategy?
13. Someolderkernelscontainavulnerabilitythatallowsalocalusertogainroot
privileges.Explainhowthiskindofvulnerabilitynegatesthevalueofachrootjail.
12.Files,Directories,andFilesystems
INTHISCHAPTER
ImportantFilesandDirectories 448
OrdinaryFiles,Directories,Links,andInodes 460
SpecialFiles 460
Filesystems 464
mount:MountsaFilesystem 466
fstab:KeepsTrackofFilesystems 469
fsck:ChecksFilesystemIntegrity 470
Filesystemsholddirectoriesoffiles.Thesestructuresstoreuser
dataandsystemdatathatarethebasisofusers'workonthe
systemandthesystem'sexistence.Thischapterdiscusses
importantfilesanddirectories,varioustypesoffilesandhowto
workwiththem,andtheuseandmaintenanceoffilesystems.
ImportantFilesandDirectories
Thissectiondetailsthemostcommonfilesusedtoadminister
thesystem.Alsoreferto"ImportantStandardDirectoriesand
Files"onpage176.
~/.bash_profile
Containsanindividualuser'sloginshellinitializationscript.The
shellexecutesthecommandsinthisfileinthesame
environmentastheshelleachtimeauserlogsin.Thefilemust
belocatedinauser'shomedirectory.
ThedefaultRedHat.bash_profilefileexecutesthecommands
in~/.bashrc.Youcanuse.bash_profiletospecifyaterminal
type(forvi,terminalemulators,andotherprograms),runsttyto
establishtheterminalcharacteristics,setupaliases,and
performotherhousekeepingfunctionswhenauserlogsin.
Asimple.bash_profilefilespecifyingavt100terminaland
CONTROL-Hastheerasekeyfollows:
$cat.bash_profile
exportTERM=vt100
sttyerase'^h'
~/.bashrc
Containsanindividualuser'sinteractive,nonloginshell
initializationscript.Theshellexecutesthecommandsinthisfile
inthesameenvironmentasthe(new)shelleachtimeauser
createsanewinteractiveshell.The.bashrcscriptdiffersfrom
.bash_profileinthatitisexecutedeachtimeanewshellis
spawned,notjustwhenauserlogsin.ThedefaultRedHat
.bash_profilefileexecutesthecommandsin~/.bashrcso
thatthesecommandsareexecutedwhenauserlogsin.For
moreinformationreferto"StartupFiles"onpage267.
/dev/null
Alsocalledabitbucket,outputsenttothisfiledisappears.The
/dev/nullfileisadevicefileandmustbecreatedwithmknod.
Inputthatyouredirecttocomefromthisfileappearsasnulls,
creatinganemptyfile.Youcancreateanemptyfilenamed
nothingbygivingthefollowingcommand:
$cat/dev/null>nothing
or
$cp/dev/nullnothing
or,withoutexplicitlyusing/dev/null,
$>nothing
Thislastcommandredirectstheoutputofanullcommandto
thefilewiththesameresultasthepreviouscommands.You
canuseanyofthesecommandstotruncateanexistingfileto
zerolengthwithoutchangingitspermissions.Youcanalsouse
/dev/nulltogetridofoutputthatyoudonotwant:
$grepportable*2>/dev/null
Thiscommandlooksforthestringportableinallfilesinthe
workingdirectory.Anyoutputtostandarderror(page270),
suchaspermissionordirectoryerrors,isdiscarded,while
outputtostandardoutputappearsonthescreen.
/dev/pts
The/dev/ptspseudofilesystemisahookintotheLinuxkernel;
itispartofthepseudoterminalsupport.Pseudoterminalsare
usedbyremoteloginprograms,suchassshandtelnet,andxterm
aswellasbyothergraphicalterminalemulators.Thefollowing
sequenceofcommandsdemonstratesthattheuserisloggedin
on/dev/pts/1.Afterusingwhoamitoverifythelinethe
userisloggedinonandusinglstoshowthatthislineexists,
theuserredirectstheoutputofanechocommandto
/dev/pts/1,whereupontheoutputappearsontheuser's
screen:
$whoami
alexpts/12006-02-1612:30(bravo.example.com)
$ls/dev/pts
01234
$echoHithere>/dev/pts/1
Hithere
/dev/randomand/dev/urandom
Thesefilesareinterfacestothekernel'srandomnumber
generator.Youcanuseeitheronewithddtocreateafilefilled
withpseudorandombytes.
$ddif=/dev/urandomof=randfile2bs=1count=100
100+0recordsin
100+0recordsout
100bytes(100B)copied,0.001241seconds,80.6kB/s
Theprecedingcommandreadsfrom/dev/urandomand
writestothefilenamedrandfile.Theblocksizeis1andthe
countis100sorandfileis100byteslong.Forbytesthatare
morerandom,youcanreadfrom/dev/random.Seethe
urandomandrandommanpagesformoreinformation.
Optional
Wipingafile
Youcanuseasimilartechniquetowipedatafromafilebefore
deletingit,makingitalmostimpossibletorecoverdatafrom
thedeletedfile.Youmightwanttowipeafileforsecurity
reasons.
Inthefollowingexample,lsshowsthesizeofthefilenamed
secret.Withablocksizeof1andacountcorrespondingtothe
numberofbytesinsecret,ddwipesthefile.The
conv=notruncargumentensuresthatddwritesoverthedata
inthefileandnotanotherplaceonthedisk.
$ls-lsecret
rwrwr1samsam3496Jan2521:48secret
$ddif=/dev/urandomof=secretbs=1count=3496conv=notrunc
3496+0recordsin
3496+0recordsout
3496bytes(3.5kB)copied,0.029557seconds,118kB/s
$rmsecret
Foraddedsecurity,runsynctoflushthediskbuffersafter
runningdd,andrepeatthetwocommandsseveraltimesbefore
deletingthefile.
/dev/zero
Inputyoutakefromthisfilecontainsaninfinitestringofzeros
(numericalzeros,notASCIIzeros).Youcanfillafile(suchasa
swapfile,page458)oroverwriteafilewithzeroswitha
commandsuchasthefollowing:
$ddif=/dev/zeroof=zerosbs=1024count=10
10+0recordsin
10+0recordsout
10240bytes(10kB)copied,0.000195seconds,52.5MB/s
$odczeros
0000000\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0
*
0024000
Theodutilityshowsthecontentsofthenewfile.
Whenyoutrytodowith/dev/zerowhatyoucandowith
/dev/null,youfillthepartitionyouareworkingin:
$cp/dev/zerobigzero
cp:writing'bigzero':Nospaceleftondevice
$rmbigzero
/etc/aliases
Usedbythemaildeliverysystem(typicallysendmail)tohold
aliasesforusers.Editthisfiletosuitlocalneeds.Formore
informationreferto"/etc/aliases"onpage633.
/etc/at.allow,/etc/at.deny,/etc/cron.allow,
and/etc/cron.deny
Bydefault,userscanusetheatandcrontabutilities.The
at.allowfileliststheuserswhoareallowedtouseat.The
cron.allowfileworksinthesamemannerforcrontab.The
at.denyandcron.denyfilesspecifyuserswhoarenot
permittedtousethecorrespondingutilities.AsRedHatLinuxis
configured,anemptyat.denyfileandtheabsenceofan
at.allowfileallowsanyonetouseat;theabsenceof
cron.allowandcron.denyfilesallowsanyonetousecrontab.To
preventanyoneexceptSuperuserfromusingat,removethe
at.allowandat.denyfiles.Topreventanyoneexcept
Superuserfromusingcrontab,createacron.allowfilewiththe
singleentryroot.Formoreinfooncrontab,referto"Scheduling
Tasks"onpage547.
/etc/dumpdates
Containsinformationaboutthelastexecutionofdump.Foreach
filesystem,itstoresthetimeofthelastdumpatagivendump
level.Thedumputilityusesthisinformationtodeterminewhich
filestobackupwhenexecutingataparticulardumplevel.
Referto"BackingUpFiles"onpage540andthedumpmanpage
formoreinformation.Followingisasample/etc/dumpdates
filefromasystemwithfourfilesystemsandabackupschedule
thatusesthreedumplevels:
/dev/hda15ThuApr2003:53:552006
/dev/hda82SunApr1608:25:242006
/dev/hda92SunApr1608:57:322006
/dev/hda102SunApr1608:58:062006
/dev/hda12SunApr1609:02:272006
/dev/hda10SunMar1922:08:352006
/dev/hda80SunMar1922:33:402006
/dev/hda90SunMar1922:35:222006
/dev/hda100SunMar1922:43:452006
Thefirstcolumncontainsthedevicenameofthedumped
filesystem.Thesecondcolumncontainsthedumplevelandthe
dateofthedump.
/etc/fstab
filesystem(mount)tableContainsalistofallmountable
devicesasspecifiedbythesystemadministrator.Programsdo
notwritetothisfilebutonlyreadfromit.Referto"fstab:Keeps
TrackofFilesystems"onpage469.
/etc/group
Groupsallowuserstosharefilesorprogramswithoutgivingall
systemusersaccesstothosefilesorprograms.Thisschemeis
usefulwhenseveralusersareworkingwithfilesthatarenot
public.The/etc/groupfileassociatesoneormoreusernames
witheachgroup(number).Referto"ACLs:AccessControlLists"
onpage185foranotherwaytocontrolfileaccess.
Anentryinthe/etc/groupfilehasfourfieldsarrangedinthe
followingformat:
group-name:password:group-ID:login-name-list
Thegroup-nameisthenameofthegroup.Thepasswordis
anoptionalencryptedpassword.Thisfieldfrequentlycontains
anx,indicatingthatgrouppasswordsarenotused.Thegroup-
IDisanumber,with1499reservedforsystemaccounts.The
login-name-listisacomma-separatedlistofuserswhobelong
tothegroup.Ifanentryistoolongtofitononeline,endthe
linewithabackslash(\),whichquotesthefollowingRETURN,
andcontinuetheentryonthenextline.Asampleentryfroma
groupfilefollows.Thegroupisnamedpubs,hasnopassword,
andhasagroupIDof503:
pubs:x:503:alex,jenny,scott,hls,barbara
Youcanusethegroupsutilitytodisplaythegroupsthatauser
belongsto:
$groupsalex
alex:alexpubs
Eachuserhasaprimarygroup,whichisthegroupthatuseris
assignedinthe/etc/passwdfile.Bydefault,RedHatLinux
hasuserprivategroups:Eachuser'sprimarygrouphasthe
samenameastheuser.Inaddition,ausercanbelongtoother
groups,dependingonwhichlogin-name-liststheuserappears
oninthe/etc/groupfile.Ineffect,yousimultaneouslybelong
bothtoyourprimarygroupandtoanygroupsyouareassigned
toin/etc/group.Whenyouattempttoaccessafileyoudo
notown,theoperatingsystemcheckswhetheryouarea
memberofthegroupthathasaccesstothefile.Ifyouare,you
aresubjecttothegroupaccesspermissionsforthefile.Ifyou
arenotamemberofthegroupthathasaccesstothefileand
youdonotownthefile,youaresubjecttothepublicaccess
permissionsforthefile.
Whenyoucreateanewfile,itisassignedtothegroup
associatedwiththedirectorythefileisbeingwritteninto,
assumingthatyoubelongtothatgroup.Ifyoudonotbelongto
thegroupthathasaccesstothedirectory,thefileisassignedto
yourprimarygroup.
Refertopage539forinformationonusingsystem-config-usersto
workwithgroups.
/etc/hosts
The/etc/hostsfilestoresthename,IPaddress,andoptional
aliasesoftheothersystemsthatthelocalsystemknowsabout.
Attheveryleast,thisfilemusthavethehostnameandIP
addressthatyouhavechosenforthelocalsystemandaspecial
entryforlocalhost.Thisentrysupportstheloopbackservice,
whichallowsthelocalsystemtotalktoitself(forexample,for
RPCservices).TheIPaddressoftheloopbackserviceisalways
127.0.0.1.Followingisasimple/etc/hostsfileforthesystem
namedrosewithanIPaddressof192.168.0.10:
$cat/etc/hosts
#Donotremovethefollowingline,orvariousprograms
#thatrequirenetworkfunctionalitywillfail.
127.0.0.1roselocalhost.localdomainlocalhost
192.168.0.1bravo.example.combravo
192.168.0.4mp3server
192.168.0.5workstation
192.168.0.10rose
...
IfyouarenotusingNISorDNStolookuphostnames(called
hostnameresolution),youmustincludein/etc/hostsall
systemsthatyouwantthelocalsystemtobeabletocontact.
Thehostsentryinthe/etc/nsswitch.conffile(page435)
controlstheorderinwhichhostnameresolutionservicesare
checked.
/etc/inittab
initializationtableControlshowtheinitprocessbehaves.
Eachlineininittabcontainsfourcolon-separatedfields:
id:runlevel:action:process
Theiduniquelyidentifiesanentryintheinittabfile.The
runlevelisthesystemrunlevel(s)atwhichprocessis
executed.Therunlevelconsistsofzeroormorecharacters
chosenfrom0123456S.Ifmorethanonerunlevelislisted,the
associatedprocessisexecutedateachofthespecified
runlevels.Whenyoudonotspecifyarunlevel,initexecutes
processatallrunlevels.Whenthesystemchangesrunlevels,
theprocessesspecifiedbyallentriesininittabthatdonot
includethenewrunlevelaresenttheSIGTERMsignaltoallow
themtoterminategracefully.After5seconds,theseprocesses
arekilledwithSIGKILLiftheyarestillrunning.Theprocessis
anybashcommandline.
Theactionisoneofthefollowingkeywords:respawn,wait,
once,boot,bootwait,ondemand,powerfail,powerwait,
powerokwait,powerfailnow,ctrlaltdel,kbrequest,off,
ondemand,initdefault,orsysinit.Thiskeywordcontrolshow
theprocessistreatedwhenitisexecuted.Themostcommonly
usedkeywordsarewaitandrespawn.
Thewaitkeywordinstructsinittostarttheprocessandwait
forittoterminate.Allsubsequentscansofinittabignorethis
waitentry.Becauseawaitentryisstartedonlyonce(on
enteringrunlevel)andisnotexecutedagainwhilethesystem
remainsatrunlevel,itisoftenusedtoredirectinitoutputto
theconsole.
Therespawnentrytellsinittostarttheprocessifitdoesnot
existbutnottowaitforittoterminate.Iftheprocessdoes
exist,initmovesontothenextentryininittab.Theinitutility
continuestorescaninittab,lookingforprocessesthathave
died.Whenaprocessdies,arespawnentrycausesinitto
restartit.
Theinitdefaultentrytellsinitwhichrunleveltobringthe
systemtowhenitboots(seeTable11-1onpage404).Without
thisinformation,initpromptsforarunlevelonthesystem
console.Thevalueoftheinitdefaultentryissetwhenyou
configurethesystemorwhenyoueditinittabdirectly.By
default,RedHatLinuxsetsinitdefaultto5,whichcausesthe
systemtocomeupingraphicalmultiusermode.
Caution:Usecautionwhenyouedit
inittab
Becarefulwhenyoueditinittabmanually.Always
makeabackupcopyinthesamedirectorybefore
youeditthisfile.Ifyoumakeamistake,youmay
notbeabletobootthesystem.Ifyoucannotboot
thesystem,referto"RescueMode"onpage397.
Eachvirtualconsole(page113)hasininittabamingetty
entrythatincludesauniqueterminalidentifier(suchastty1,
whichisshortfor/dev/tty1).Youcanaddorremove
mingettylinestoaddorremovevirtualconsoles.Rememberto
leaveavirtualconsoleforeachXwindowthatyouwanttorun.
Followingisthemingettyentryfor/dev/tty2:
2:2345:respawn:/sbin/mingettytty2
Theidonamingettylinecorrespondstothettynumber.
Alloftheactionsaredocumentedintheinittabmanpage.For
moreinformationreferto"BootingtheSystem"onpage403.
/etc/motd
Containsthemessageoftheday,whichcanbedisplayedeach
timesomeonelogsinusingatextuallogin.Thisfiletypically
containssitepolicyandlegalinformation.Keepthisfileshort
becauseuserstendtoseethemessagemanytimes.
/etc/mtab
Whenyoucallmountwithoutanyarguments,itconsultsthisfile
anddisplaysalistofmounteddevices.Eachtimeyou(oraninit
script)callmountorumount,theseutilitiesmakethenecessary
changestomtab.AlthoughthisisanASCIItextfile,youshould
noteditit.Seealso/etc/fstab.
Tip:Fixingmtab
Theoperatingsystemmaintainsitsowninternal
mounttablein/proc/mounts.Youcanusecatto
displaythecontentsof/proc/mountssothatyou
canreviewtheinternalmounttable.Sometimesthe
listoffilesin/etc/mtabmaynotbesynchronized
withthepartitionsinthistable.Tobringthemtab
fileinlinewiththeoperatingsystem'smounttable,
youcaneitherrebootthesystemorreplace
/etc/mtabwithasymboliclinkto/proc/mounts
(someinformationmaybelost).
#rm/etc/mtab
#ln-s/proc/mounts/etc/mtab
/etc/netgroup
Definesnetgroups,whichareusedforcheckingpermissions
whenperformingremoteloginsandremotemountsandwhen
startingremoteshells.
/etc/nsswitch.conf
Specifieswhetherasystemusesasthesourceofcertain
informationNIS,DNS,localfiles,oracombination,andinwhat
orderitconsultstheseservices(page435).
/etc/pam.d
Filesinthisdirectoryspecifytheauthenticationmethodsused
byPAM(page438)applications.
Caution:BecautiouswhenchangingPAM
files
UnlessyouunderstandhowtoconfigurePAM,avoid
changingthefilesin/etc/pam.d.Mistakesinthe
configurationofPAMcanmakethesystemunusable.
/etc/passwd
Describesuserstothesystem.Donoteditthisfiledirectly;
instead,useoneoftheutilitiesdiscussedin"ConfiguringUser
andGroupAccounts"onpage538.Eachlineinpasswdhas
sevencolon-separatedfieldsthatdescribeoneuser:
login-name:dummy-password:user-ID:group-
ID:info:directory:program
Thelogin-nameistheuser'susernamethenameyouenterin
responsetothelogin:promptorGUIloginscreen.Thevalueof
thedummy-passwordisthecharacterx.An
encrypted/hashedpasswordisstoredin/etc/shadow(page
456).Forsecurityreasons,everyaccountshouldhavea
password.Byconvention,disabledaccountshaveanasterisk
(*)inthisfield.
Theuser-IDisanumber,with0indicatingSuperuserand1499
beingreservedforsystemaccounts.Thegroup-IDidentifies
theuserasamemberofagroup.Itisanumber,with0499
beingreservedforsystemaccounts;see/etc/group.Youcan
changethesevaluesandsetmaximumvaluesin
/etc/login.defs.
Theinfoisinformationthatvariousprograms,suchas
accountingprogramsandemail,usetoidentifytheuserfurther.
Normallyitcontainsatleastthefirstandlastnamesoftheuser.
ItisreferredtoastheGECOS(page1033)field.
Thedirectoryistheabsolutepathnameoftheuser'shome
directory.Theprogramistheprogramthatrunsoncetheuser
logsin.Ifprogramisnotpresent,avalueof/bin/bashis
assumed.Youcanput/bin/tcshheretologinusingtheTC
Shellor/bin/zshtologinusingtheZShell,assumingthe
shellyouspecifyisinstalled.Thechshutility(page418)changes
thisvalue.
Theprogramisusuallyashell,butitcanbeanyprogram.The
followinglineinthepasswdfilecreatesa"user"whoseonly
purposeistoexecutethewhoutility:
who:x:1000:1000:executewho:/usr:/usr/bin/who
Usingwhoasausernamecausesthesystemtologyouin,
executethewhoutility,andlogyouout.Theoutputofwho
flashesbyinahurrybecausethenewloginpromptclearsthe
screenimmediatelyafterwhofinishesrunning.Thisentryinthe
passwdfiledoesnotprovideashell,soyoucannotstaylogged
inafterwhofinishesexecuting.
Thistechniqueisusefulforprovidingspecialaccountsthatmay
doonlyonething.Forinstance,sitesmaycreateanFTP(page
601)accounttoenableanonymousFTPaccesstotheirsystems.
Becausenoonelogsinonthisaccount,theshellissetto
/bin/false(whichreturnsafalseexitstatus)orto
/sbin/nologin(whichdoesnotpermittheusertologin).
Whenyouputamessagein/etc/nologin.txt,nologindisplays
thatmessage(exceptithasthesameproblemastheoutputof
who:Itisremovedsoquicklythatyoucannotseeit).
Security:Donotreplacealoginshell
withashellscript
Donotuseshellscriptsasreplacementsforshellsin
/etc/passwd.Ausermaybeabletointerrupta
shellscript,givinghimorherfullshellaccesswhen
youdidnotintendtodoso.Wheninstallinga
dummyshell,useacompiledprogram,notashell
script.
/etc/printcap
Theprintercapabilitydatabase.Thisfiledescribessystem
printersandisderivedfrom4.3BSDUNIX.
/etc/profile
Containsasystemwideinteractiveshellinitializationscriptfor
environmentandstart-upprograms.Whenyoulogin,theshell
immediatelyexecutesthecommandsinthisfileinthesame
environmentastheshell.(Formoreinformationonexecutinga
shellscriptinthismanner,refertothediscussionofthe.[dot]
commandonpage269.)Thisfileallowsthesystem
administratortoestablishsystemwideenvironmentparameters
thatindividualuserscanoverride.Forexample,youcanset
shellvariables,executeutilities,setupaliases,andtakecareof
otherhousekeepingtasks.Seealso~/.bash_profileonpage
448.
Followingisanexampleofa/etc/profilefilethatdisplaysthe
messageoftheday(the/etc/motdfile),setsthefile-creation
mask(umask,page420),andsetstheinterruptcharacterto
CONTROL-C:
#cat/etc/profile
cat/etc/motd
umask022
sttyintr'^c'
Seethe/etc/profilefileonthelocalsystemforamore
complexexample.
/etc/protocols
Providesprotocolnumbers,aliases,andbriefdefinitionsfor
DARPAInternetTCP/IPprotocols.Donotmodifythisfile.
/etc/rc.d
Holdsthesysteminitscripts,alsocalledruncommand(rc)
scripts.Theinitprogramexecutesseveralinitscriptseachtime
thesystemchangesstateorrunlevel.Formoreinformation
referto"InitScripts:StartandStopSystemServices"onpage
404.
/etc/resolv.conf
Theresolver(page722)configurationfile,usedtoprovide
accesstoDNS.
Thefollowingexampleshowstheresolv.conffileforthe
example.comdomain.Aresolv.conffileusuallyhasatleast
twolinesadomainlineandanameserverline:
#cat/etc/resolv.conf
domainexample.com
nameserver10.0.0.50
nameserver10.0.0.51
Thefirstline(optional)specifiesthedomainname.A
resolv.conffilemayusesearchinplaceofdomain:Inthe
simplecase,thetwoperformthesamefunction.Ineithercase,
thisdomainnameisappendedtoallhostnamesthatarenot
fullyqualified.SeeFQDNonpage1032.
Thedomainkeywordtakesasingledomainnameasan
argument:ThisnameisappendedtoallDNSqueries,
shorteningthetimeneededtoquerylocalhosts.Whenyouput
domainexample.cominresolv.conf,anyreferencetoahost
withintheexample.comdomainorasubdomain(suchas
marketing.example.com)canusetheabbreviatedformof
thehost.Forexample,insteadofissuingthecommandping
speedy.marketing.example.com,youcanuseping
speedy.marketing.
Thissearchkeywordissimilartodomainbutcancontainupto
sixdomainnames.Thedomainsaresearchedinorderinthe
processofresolvingahostname.Thefollowinglinein
resolv.confcausesthemarketingsubdomaintobesearched
first,followedbysales,andfinallytheentireexample.com
domain:
searchmarketing.example.comsales.example.comexample.com
Itisagoodideatoputthemostfrequentlyuseddomainnames
firsttotrytooutguesspossibleconflicts.Ifboth
speedy.marketing.example.comandspeedy.example.com
exist,theorderofthesearchdetermineswhichoneisselected
whenyouinvokeDNS.Donotoverusethisfeature.Thelonger
thesearchpath,themorenetworkDNSrequestsgenerated,
andtheslowertheresponse.Threeorfournamesaretypically
sufficient.
Thenameserverline(s)indicatewhichsystemsthelocal
systemshouldquerytoresolvehostnamestoIPaddresses,and
viceversa.Thesemachinesareconsultedintheorderthey
appearwitha10-secondtimeoutbetweenqueries.The
precedingfilecausesthismachinetoquery10.0.0.50,followed
by10.0.0.51whenthefirstmachinedoesnotanswerwithin10
seconds.Theresolv.conffilemaybeautomaticallyupdated
whenaPPP-(Point-to-PointProtocol)orDHCP-(DynamicHost
ConfigurationProtocol)controlledinterfaceisactivated.Referto
theresolv.confandresolvermanpagesformoreinformation.
/etc/rpc
MapsRPCservicestoRPCnumbers.Thethreecolumnsinthis
fileshowthenameoftheserverfortheRPCprogram,theRPC
programnumber,andanyaliases.
/etc/services
Listssystemservices.Thethreecolumnsinthisfileshowthe
informalnameoftheservice,theportnumber/protocolthe
servicefrequentlyuses,andanyaliasesfortheservice.Thisfile
doesnotspecifywhichservicesarerunningonthelocalsystem,
nordoesitmapservicestoportnumbers.Theservicesfileis
usedinternallytomapportnumberstoservicesfordisplay
purposes.
/etc/shadow
ContainsencryptedorMD5(page1042)hasheduser
passwords.Eachentryoccupiesonelinecomposedofnine
fields,separatedbycolons:
login-name:password:last-
mod:min:max:warn:inactive:expire:flag
Thelogin-nameistheuser'susernamethenamethattheuser
entersinresponsetothelogin:promptorGUIloginscreen.
Thepasswordisanencryptedorhashedpasswordthatpasswd
putsintothisfile.Whensettingupnewuseraccountsmanually,
runpasswdasSuperusertoassignapasswordtoanewuser.
Thelast-modfieldindicateswhenthepasswordwaslast
modified.Theministheminimumnumberofdaysthatmust
elapsebeforethepasswordcanbechanged;themaxisthe
maximumnumberofdaysbeforethepasswordmustbe
changed.Thewarnspecifieshowmuchadvancewarning(in
days)togivetheuserbeforethepasswordexpires.Theaccount
willbeclosedifthenumberofdaysbetweenloginsessions
exceedsthenumberofdaysspecifiedintheinactivefield.The
accountwillalsobeclosedasofthedateintheexpirefield.
Thelastfieldinanentry,flag,isreservedforfutureuse.You
canusethePasswordInfotabinsystem-config-users("Modifyinga
user"onpage538)tomodifythesefields.
Theshadowpasswordfileshouldbeownedbyrootandshould
notbepubliclyreadableorwritable.Settingownershipand
permissionsthiswaymakesitmoredifficultforsomeoneto
breakintothesystembyidentifyingaccountswithout
passwordsorbyusingspecializedprogramsthattrytomatch
hashedpasswords.
Anumberofconventionsexistforcreatingspecialshadow
entries.Anentryof*LK*orNPinthepasswordfieldindicates
lockedornopassword,respectively.Nopasswordisdifferent
fromanemptypassword,implyingthatthisisanadministrative
accountthatnooneeverlogsinondirectly.Occasionally
programswillrunwiththeprivilegesofthisaccountforsystem
maintenancefunctions.Theseaccountsaresetupunderthe
principleofleastprivilege(page392).
Entriesintheshadowfilemustappearinthesameorderasin
thepasswdfile.Theremustbeexactlyoneshadowentryfor
eachpasswdentry.
/etc/sysconfig
Adirectorycontainingahierarchyofsystemconfigurationfiles.
Formoreinformationrefertothe
/usr/share/doc/initscripts*/sysconfig.txtfile.
/proc
The/procpseudofilesystemprovidesawindowintotheLinux
kernel.Through/procyoucanobtaininformationonany
processrunningonyourcomputer,includingitscurrentstate,
memoryusage,CPUusage,terminal,parent,andgroup.You
canextractinformationdirectlyfromthefilesin/proc.An
examplefollows:
$sleep1000&
[1]4567
$cd/proc/4567
$ls-l
total0
dr-xr-xr-x2samsam0Jan2521:57attr
-r--------1samsam0Jan2521:57auxv
-r--r--r--1samsam0Jan2521:57cmdline
lrwxrwxrwx1samsam0Jan2521:57cwd->/home/sam
-r--------1samsam0Jan2521:57environ
lrwxrwxrwx1samsam0Jan2521:57exe->/bin/sleep
dr-x------2samsam0Jan2521:57fd
...
-r--r--r--1samsam0Jan2521:57status
dr-xr-xr-x3samsam0Jan2521:57task
-r--r--r--1samsam0Jan2521:57wchan
$catstatus
Name:sleep
State:S(sleeping)
SleepAVG:78%
Tgid:4567
Pid:4567
PPid:4548
TracerPid:0
Uid:500500500500
Gid:500500500500
FDSize:256
Groups:500
VmPeak:3584kB
VmSize:3584kB
...
Inthisexample,bashcreatesabackgroundprocess(PID4567)
forsleep.Nexttheuserchangesdirectoriestothedirectoryin
/procthathasthesamenameasthePIDofthesubject
backgroundprocess(cd/proc/4567).Thisdirectoryholds
informationabouttheprocessforwhichitisnamed.Inthis
case,itholdsinformationaboutthesleepprocess.Thelsl
commandshowsthatsomeentriesinthisdirectoryarelinks
(cwdisalinktothedirectorytheprocesswasstartedfrom,
andexeisalinktotheexecutablefilethatthisprocessis
running)andsomeappeartobeordinaryfiles.Allappeartobe
empty.Whenyoucatoneofthesepseudofiles(statusinthe
example),yougettheoutputshown.Obviouslythisisnotan
ordinaryfile.
/sbin/shutdown
Autilitythatbringsthesystemdown(seepage412).
swap
Eventhoughswapisnotafile,swapspacecanbeaddedand
deletedfromthesystemdynamically.Swapspaceisusedby
thevirtualmemorysubsystem.Whenitrunslowonreal
memory(RAM),thesystemwritesmemorypagesfromRAMto
theswapspaceonthedisk.Whichpagesarewrittenandwhen
theyarewrittenarecontrolledbyfinelytunedalgorithmsinthe
Linuxkernel.Whenneededbyrunningprograms,thesepages
arebroughtbackintoRAMatechniqueiscalledpaging(page
1047).Whenasystemisrunningveryshortonmemory,an
entireprocessmaybepagedouttodisk.
Runninganapplicationthatrequiresalargeamountofvirtual
memorymayresultintheneedforadditionalswapspace.If
yourunoutofswapspace,youcanusemkswaptocreateanew
swapfileandswapontoenableit.Normallyyouuseadisk
partitionasswapspace,butyoucanalsouseafile.Adisk
partitionprovidesmuchbetterperformancethanafile.
Ifyouareusingafileasswapspace,firstusedftoensurethat
thepartitionhasadequatespaceforthefile.Inthefollowing
sequenceofcommands,theadministratorfirstusesddand
/dev/zero(page450)tocreateanemptyfile(donotusecpas
youmaycreateafilewithholes,whichmaynotwork)inthe
workingdirectory.Nextmkswaptakesasanargumentthename
ofthefilecreatedinthefirststeptosetuptheswapspace.For
securityreasons,changethefilesothatitcannotbereadfrom
orwrittentobyanyonebutroot.Useswaponwiththesame
argumenttoturntheswapfileon;thenuseswaponsto
confirmthattheswapspaceisavailable.Thefinaltwo
commandsturnofftheswapfileandremoveit:
#ddif=/dev/zeroof=swapfilebs=1024count=65536
65536+0recordsin
65536+0recordsout
67108864bytes(67MB)copied,0.684039seconds,98.1MB/s
#mkswapswapfile
Settingupswapspaceversion1,size=67104kB
#chmod600swapfile
#swaponswapfile
#swapon-s
FilenameTypeSizeUsed
Priority
/dev/hda5partition10200880-1
/root/swapfilefile655280-2
#swapoffswapfile
#rmswapfile
rm:removeregularfile'swapfile'?y
/sys
The/syspseudofilesystemwasaddedintheLinux2.6kernel
tomakeiteasyforprogramsrunninginkernelspace,suchas
devicedrivers,toexchangeinformationwithprogramsrunning
inuserspace.Refertoudevonpage461.
/usr/share/magic
Mostfilesbeginwithauniqueidentifiercalledamagicnumber.
Thisfileisatextdatabaselistingallknownmagicnumberson
thesystem.Whenyouusethefileutility,itconsults
/usr/share/magictodeterminethetypeofafile.
Occasionallyyoumayacquireanewtoolthatcreatesanew
typeoffilethatisunrecognizedbythefileutility.Inthis
situationyouneedtoupdatethe/usr/share/magicfile;refer
tothemagicmanpagefordetails.Seealso"magicnumber"on
page1042.
/var/log
Holdssystemlogfiles.
/var/log/messages
Containsmessagesfromdaemons,theLinuxkernel,and
securityprograms.Forexample,youwillfindfilesystemfull
warningmessages,errormessagesfromsystemdaemons
(NFS,syslog,printerdaemons),SCSIandIDEdiskerror
messages,andmoreinmessages.Check
/var/log/messagesperiodicallytokeepinformedabout
importantsystemevents.Muchoftheinformationdisplayedon
thesystemconsoleisalsosenttomessages.Ifthesystem
experiencesaproblemandyoucannotaccesstheconsole,
checkthisfileformessagesabouttheproblem.
/var/log/secure
Holdsmessagesfromsecurity-relatedprogramssuchassuand
thesshddaemon.
FileTypes
Linuxsupportsmanytypesoffiles.Thefollowingsections
discussthesetypesoffiles:
Ordinaryfiles,directories,links,andinodes(discussed
next)
Symboliclinks(page460)
Specialfiles(page460)
FIFOspecialfile(namedpipe)(page462)
Sockets(page462)
Blockandcharacterdevices(page463)
Rawdevices(page464)
OrdinaryFiles,Directories,Links,andInodes
Ordinaryanddirectoryfiles
Anordinaryfilestoresuserdata,suchastextualinformation,
programs,orimages,suchasajpegortifffile.Adirectoryisa
standard-formatdiskfilethatstoresinformation,including
names,aboutordinaryfilesandotherdirectoryfiles.
Inodes
Aninodeisadatastructure(page1028),storedondisk,that
definesafile'sexistenceandisidentifiedbyaninodenumber.
Aninodecontainscriticalinformation,suchasthenameofthe
ownerofthefile,whereitisphysicallylocatedonthedisk,and
howmanyhardlinkspointtoit.Inaddition,SELinux(page
400)storesextendedinformationaboutfilesininodes.A
directoryrelateseachofthefilenamesitstorestoaninode.
Whenyoumove(mv)afilewithinafilesystem,youchangethe
filenameportionofthedirectoryentryassociatedwiththeinode
thatdescribesthefile.Youdonotcreateanewinode.Ifyou
moveafiletoanotherfilesystem,mvfirstcreatesanewinode
onthedestinationfilesystemandthendeletestheoriginal
inode.Youcanalsousemvtomoveadirectoryrecursively,in
whichcaseallfilesinthedirectoryarecopiedanddeleted.
Whenyoumakeanadditionalhardlink(ln,page192)toafile,
youcreateanotherreference(anadditionalfilename)tothe
inodethatdescribesthefile.Youdonotcreateanewinode.
Whenyouremove(rm)afile,youdeletethedirectoryentrythat
describesthefile.Whenyouremovethelasthardlinktoafile,
theoperatingsystemputsallblockstheinodepointedtoback
inthefreelist(thelistofblocksthatareavailableforuseon
thedisk)andfreestheinodetobeusedagain.
The.and...directoryentries
Everydirectorycontainsatleasttwoentries(.and..).The.
entryisalinktothedirectoryitself.The..entryisalinktothe
parentdirectory.Inthecaseoftherootdirectory,thereisno
parentandthe..entryisalinktotherootdirectoryitself.Itis
notpossibletocreatehardlinkstodirectories.
Symboliclinks
Becauseeachfilesystemhasaseparatesetofinodes,youcan
createhardlinkstoafileonlyfromwithinthefilesystemthat
holdsthatfile.Togetaroundthislimitation,Linuxprovides
symboliclinks,whicharefilesthatpointtootherfiles.Filesthat
arelinkedbyasymboliclinkdonotshareaninode.Asa
consequence,youcancreateasymboliclinktoafilefromany
filesystem.Youcanalsocreateasymboliclinktoadirectory,
device,orotherspecialfile.Formoreinformationreferto
"SymbolicLinks"onpage194.
SpecialFiles
SpecialfilesrepresentLinuxkernelroutinesthatprovideaccess
toanoperatingsystemfeature.FIFO(firstin,firstout)special
filesallowunrelatedprogramstoexchangeinformation.Sockets
allowunrelatedprocessesonthesameordifferentcomputers
toexchangeinformation.Onetypeofsocket,theUNIXdomain
socket,isaspecialfile.Symboliclinksareanothertypeof
specialfile.
Devicefiles
Devicefiles,whichincludebothblockandcharacterspecial
files,representdevicedriversthatletyoucommunicatewith
peripheraldevices,suchasterminals,printers,andharddisks.
Byconvention,devicefilesappearinthe/devdirectoryandits
subdirectories.Eachdevicefilerepresentsadevice:Youread
fromandwritetothefiletoreadfromandwritetothedeviceit
represents.Forexample,usingcattosendanaudiofileto
/dev/dspplaysthefile.Thefollowingexampleshowspartof
theoutputthatanlslcommandproducesforthe/dev
directory:
$lsl/dev
total0
crwrw1rootroot14,12Jan2508:33adsp
crw1rootroot10,175Jan2508:33agpgart
crw1zachroot14,4Jan2508:33audio
drwxrxrx3rootroot60Jan2508:33bus
lrwxrwxrwx1rootroot3Jan2508:33cdrom>hdb
lrwxrwxrwx1rootroot3Jan2508:33cdwriter>hdb
crw1zachroot5,1Jan2508:33console
lrwxrwxrwx1rootroot11Jan2508:33core>/proc/kcore
drwxrxrx6rootroot120Jan2508:33disk
crw1zachroot14,3Jan2508:33dsp
lrwxrwxrwx1rootroot13Jan2508:33fd>/proc/self/fd
brwrw1zachfloppy2,0Jan2508:33fd0
brwrw1zachfloppy2,84Jan2508:33fd0u1040
brwrw1zachfloppy2,88Jan2508:33fd0u1120
...
lrwxrwxrwx1rootroot3Jan2508:33floppy>fd0
crwrwrw1rootroot1,7Jan2508:33full
brwr1rootdisk3,0Jan2500:33hda
brwr1rootdisk3,1Jan2508:33hda1
brwr1rootdisk3,2Jan2508:33hda2
brwr1rootdisk3,3Jan2500:33hda3
...
Thefirstcharacterofeachlineisalways,b,c,d,l,orp,
representingordinary(plain),block,character,directory,
symboliclink,ornamedpipe(seethefollowingsection),
respectively.Thenextninecharactersidentifythepermissions
forthefile,followedbythenumberofhardlinksandthenames
oftheownerandgroup.Wherethenumberofbytesinafile
wouldappearforanordinaryordirectoryfile,adevicefile
showsmajorandminordevicenumbers(page463)separated
byacomma.Therestofthelineisthesameasanyotherlsl
listing(page181).
udev
Theudevutilitymanagesdevicenamingdynamically.Itreplaces
theearlierdevfsandmovesthedevicenamingfunctionality
fromthekerneltouserspace.Becausedevicesareaddedtoand
removedfromasysteminfrequently,theperformancepenalty
associatedwiththischangeisminimal.Thebenefitofthemove
isthatabuginudevcannotcompromiseorcrashthekernel.
Theudevutilityispartofthehotplugsystem(discussednext).
Whenadeviceisaddedtoorremovedfromthesystem,the
kernelcreatesadevicenameinthe/syspseudofilesystemand
notifieshotplugoftheevent,whichisreceivedbyudev.Theudev
utilitythencreatesthedevicefile,usuallyinthe/devdirectory,
orremovesthedevicefilefromthesystem.Theudevutilitycan
alsorenamenetworkinterfaces.See
fedora.redhat.com/docs/udevand
www.kernel.org/pub/linux/utils/kernel/hotplug/udev.htmlfor
moreinformation.
Hotplug
Thehotplugsystemallowsyoutoplugadeviceintothesystem
anduseitimmediately.Althoughhotplugwasavailableinthe
Linux2.4kernel,the2.6kernelintegrateshotplugwiththe
unifieddevicedrivermodelframework(thedrivermodelcore)
sothatanybuscanreportaneventwhenadeviceisaddedto
orremovedfromthesystem.Usersoftwarecanbenotifiedof
theeventsoitcantakeappropriateaction.Seelinux-
hotplug.sourceforge.netformoreinformation.
FIFOSpecialFile(NamedPipe)
AFIFOspecialfile,alsocalledanamedpipe,representsapipe:
Youreadfromandwritetothefiletoreadfromandwritetothe
pipe.ThetermFIFOstandsforfirstin,firstoutthewayanypipe
works.Inotherwords,thefirstinformationthatyouputinone
endisthefirstinformationthatcomesouttheotherend.When
youuseapipeonacommandlinetosendtheoutputofa
programtotheprinter,theprinteroutputstheinformationin
thesameorderthattheprogramproduceditandsentittothe
pipe.
Unlessyouarewritingsophisticatedprograms,youwillnotbe
workingwithFIFOspecialfiles.However,programsthatyouuse
onLinuxusenamedpipesforinterprocesscommunication.You
cancreateapipeusingmkfifo:
$mkfifoAA
$ls-lAA
prwrwr1zachzach0Apr2613:11AA
Thepattheleftendoftheoutputoflslindicatesthatthefile
isapipe.
TheUNIXandLinuxsystemshaveincludedpipesformany
generations.Withoutnamedpipes,onlyprocessesthatwere
childrenofthesameancestorcouldusepipestoexchange
information.Usingnamedpipes,anytwoprocessesonasingle
systemcanexchangeinformation.Whenoneprogramwritesto
aFIFOspecialfile,anotherprogramcanreadfromthesame
file.Theprogramsdonothavetorunatthesametimeorbe
awareofeachother'sactivity.Theoperatingsystemhandlesall
bufferingandinformationstorage.Thistypeofcommunication
istermedasynchronous(async)becauseprogramsontheends
ofthepipedonothavetobesynchronized.
Sockets
LikeaFIFOspecialfile,asocketallowsasynchronousprocesses
thatarenotchildrenofthesameancestortoexchange
information.Socketsarethecentralmechanismofthe
interprocesscommunicationthatformsthebasisofthe
networkingfacility.Whenyouusenetworkingutilities,pairsof
cooperatingsocketsmanagethecommunicationbetweenthe
processesonthelocalcomputerandtheremotecomputer.
Socketsformthebasisofsuchutilitiesassshandscp.
MajorandMinorDeviceNumbers
Amajordevicenumberpointstoadriverinthekernelthat
workswithaclassofhardwaredevices:terminal,printer,tape
drive,harddisk,andsoon.Inthelistofthe/devdirectoryon
page461,alloftheharddiskpartitionshaveamajordevice
numberof3.
Aminordevicenumberrepresentsaparticularpieceof
hardwarewithinaclass.Althoughallharddiskpartitionsare
groupedtogetherbytheirmajordevicenumber,eachhasa
differentminordevicenumber(hda1is1,hda2is2,andso
on).Thissetupallowsonepieceofsoftware(thedevicedriver)
toserviceallsimilarhardwareyettobeabletodistinguish
amongdifferentphysicalunits.
BlockandCharacterDevices
Thissectiondescribestypicaldevicedrivers.Becausedevice
driverscanbechangedtosuitaparticularpurpose,the
descriptionsinthissectiondonotpertaintoeverysystem.
AblockdeviceisanI/O(input/output)devicethatis
characterizedby
Beingabletoperformrandomaccessreads.
Havingaspecificblocksize.
Handlingonlysingleblocksofdataatatime.
Acceptingonlytransactionsthatinvolvewholeblocksof
data.
Beingabletohaveafilesystemmountedonit.
HavingtheLinuxkernelbufferitsinputandoutput.
Appearingtotheoperatingsystemasaseriesofblocks
numberedfrom0throughn1,wherenisthenumberof
blocksonthedevice.
BlockdevicescommonlyfoundonaLinuxsystemincludehard
disks,floppydiskettes,andCD-ROMs.
Acharacterdeviceisanydevicethatisnotablockdevice.
Examplesofcharacterdevicesincludeprinters,terminals,tape
drives,andmodems.
Thedevicedriverforacharacterdevicedetermineshowa
programreadsfromandwritestothatdevice.Forexample,the
devicedriverforaterminalallowsaprogramtoreadthe
informationyoutypeontheterminalintwoways.First,a
programcanreadsinglecharactersfromaterminalinraw
modethatis,withoutthedriverdoinganyinterpretationofthe
characters.(Thismodehasnothingtodowiththerawdevice
describedinthefollowingsection.)Alternatively,aprogramcan
readonelineatatime.Whenaprogramreadsonelineata
time,thedriverhandlestheeraseandkillcharacterssothe
programneverseestypingmistakesthathavebeencorrected.
Inthiscase,theprogramreadseverythingfromthebeginning
ofalinetotheRETURNthatendsaline;thenumberof
charactersinalinecanvary.
RawDevices
Devicedriverprogramsforblockdevicesusuallyhavetwoentry
pointssotheycanbeusedintwoways:asblockdevicesoras
characterdevices.Thecharacterdeviceformofablockdevice
iscalledarawdevice.Arawdeviceischaracterizedby
DirectI/O(nobufferingthroughtheLinuxkernel).
Aone-to-onecorrespondencebetweensystemcallsand
hardwarerequests.
Device-dependentrestrictionsonI/O.
Anexampleofautilitythatusesarawdeviceisfsck.Itismore
efficientforfscktooperateonthediskasarawdevice,rather
thanbeingrestrictedbythefixedsizeofblocksintheblock
deviceinterface.Becauseithasfullknowledgeoftheunderlying
filesystemstructure,fsckcanoperateontherawdeviceusing
thelargestpossibleunits.Whenafilesystemismounted,
processesnormallyaccessthediskthroughtheblockdevice
interface,whichexplainswhyitisimportanttoallowfsckto
modifyonlyanunmountedfilesystem.Onamounted
filesystem,thereisthedangerthat,whilefsckisrearrangingthe
underlyingstructurethroughtherawdevice,anotherprocess
couldchangeadiskblockusingtheblockdevice,resultingina
corruptedfilesystem.
Filesystems
Table12-1listssomeofthetypesoffilesystemsavailableunder
Linux.
Table12-1.Filesystems
Filesystem Features
adfs AdvancedDiscFilingSystem.UsedonAcorncomputers.
ThewordAdvanceddifferentiatedthisfilesystemfrom
itspredecessor,DFS,whichdidnotsupportadvanced
featuressuchasahierarchicalfilesystem.
affs AmigaFastFilesystem(FFS).
autofs Automountingfilesystem(page690).
coda CODAdistributedfilesystem(developedatCarnegie
Mellon).
devpts Apseudofilesystemforpseudoterminals(page449).
ext2 AstandardfilesystemforRedHatsystems,usuallywith
theext3extension.
ext3 Ajournaling(page1039)extensiontotheext2
filesystem.Itgreatlyimprovesrecoverytimefrom
crashes(ittakesalotlesstimetorunfsck),promoting
increasedavailability.Aswithanyfilesystem,a
journalingfilesystemcanlosedataduringasystem
crashorhardwarefailure.
GFS GlobalFilesystem.GFSisajournaling,clustering
filesystem.ItenablesaclusterofLinuxserverstoshare
acommonstoragepool.
hfs HierarchicalFilesystem:usedbyolderMacintosh
systems.NewerMacintoshsystemsusehfs+.
hpfs High-PerformanceFilesystem:thenativefilesystemfor
IBM'sOS/2.
iso9660 ThestandardfilesystemforCD-ROMs.
minix VerysimilartoLinux,thefilesystemofasmall
operatingsystemthatwaswrittenforeducational
purposesbyAndrewS.Tanenbaum(www.minix3.org).
msdos ThefilesystemusedbyDOSandsubsequentMicrosoft
operatingsystems.Donotusemsdosformounting
Windowsfilesystems;itdoesnotreadVFATattributes.
ncpfs NovellNetWareNCPProtocolFilesystem:usedtomount
remotefilesystemsunderNetWare.
nfs NetworkFilesystem.DevelopedbySunMicrosystems,
thisprotocolallowsacomputertoaccessremotefiles
overanetworkasiftheywerelocal(page673).
ntfs NTFilesystem:thenativefilesystemofWindowsNT.
proc AninterfacetoseveralLinuxkerneldatastructures
(page1028)thatbehaveslikeafilesystem(page457).
qnx4 QNX4operatingsystemfilesystem.
reiserfs Ajournaling(page1039)filesystem,basedon
balanced-treealgorithms.Seeext3formoreon
journalingfilesystems.
romfs Adumb,readonlyfilesystemusedmainlyforRAMdisks
(page1051)duringinstallation.
smbfs SambaFilesystem(page695).
software
RAID
RAIDimplementedinsoftware.Referto"RAID
Filesystem"onpage473.
sysv SystemVUNIXfilesystem.
ufs DefaultfilesystemunderSun'sSolarisoperatingsystem
andotherUNIXs.
umsdos Afull-featureUNIX-likefilesystemthatrunsontopofa
DOSFATfilesystem.
vfat DevelopedbyMicrosoft,astandardthatallowslong
filenamesonFATpartitions.
xfs SGI'sjournaledfilesystem(portedfromIrix).
mount:MountsaFilesystem
Themountutilityconnectsdirectoryhierarchiestypically
filesystemstotheLinuxdirectoryhierarchy.Thesedirectory
hierarchiescanbeonremoteandlocaldisks,CDs,andfloppy
diskettes.Linuxalsoallowsyoutomountvirtualfilesystems
thathavebeenbuiltinsideordinaryfiles,filesystemsbuiltfor
otheroperatingsystems,andthespecial/procfilesystem
(page457),whichmapsusefulLinuxkernelinformationtoa
pseudodirectory.
Mountpoint
Themountpointforthefilesystem/directoryhierarchythatyou
aremountingisadirectoryinthelocalfilesystem.This
directorymustexistbeforeyoucanmountafilesystem;its
contentsdisappearaslongasafilesystemismountedonitand
reappearwhenyouunmountthefilesystem.
Withoutanyarguments,mountliststhecurrentlymounted
filesystems,showingthephysicaldeviceholdingeach
filesystem,themountpoint,thetypeoffilesystem,andany
optionssetwheneachfilesystemwasmounted:
$mount
procon/proctypeproc(rw)
/dev/hdb1on/typeext2(rw)
/dev/hdb4on/tmptypeext2(rw)
/dev/hda5on/usrtypeext3(rw)
/dev/sda1on/usr/X386typeext2(rw)
/dev/sda3on/usr/localtypeext2(rw)
/dev/hdb3on/hometypeext3(rw)
/dev/hda1on/dostypemsdos(rw,umask=000)
tuna:/p04on/p04typenfs(rw,addr=192.168.0.8)
/dev/scd0on/mnt/cdromtypeiso9660(ro,noexec,nosuid,nodev)
Themountutilitygetsthisinformationfromthe/etc/mtabfile
(page453).Thissectioncoversmountinglocalfilesystems;
refertopage673forinformationonusingNFStomount
remotedirectoryhierarchies.
Thefirstentryintheprecedingexampleshowsthe/proc
pseudofilesystem(page457).Thenextsixentriesidentifydisk
partitionsholdingstandardLinuxext2andext3filesystems.
Thesepartitionsarefoundonthreedisks:twoIDEdisks(hda,
hdb)andoneSCSIdisk(sda).Diskpartition/dev/hda1hasa
DOS(msdos)filesystemmountedatthedirectory/dosinthe
Linuxfilesystem.YoucanaccesstheDOSfilesanddirectories
onthispartitionasiftheywereLinuxfilesanddirectories,using
Linuxutilitiesandapplications.Thelinestartingwithtuna
showsamounted,remoteNFSfilesystem.Thelastlineshowsa
CDmountedonaSCSICDdrive(/dev/scd0).
Ifthelistoffilesystemsin/etc/mtabisnotcorrect,seethetip
onpage453.
Whenyouaddalineforafilesystemtothe/etc/fstabfile
(page451),youcanmountthatfilesystembygivingthe
associatedmountpoint(orthedevice)astheargumentto
mount.Forexample,theSCSICDlistedearlierwasmounted
usingthefollowingcommand:
$mount/mnt/cdrom
Caution:Donotmountanythingonroot(
/)
Alwaysmountnetworkdirectoryhierarchiesand
removabledevicesatleastonelevelbelowtheroot
levelofthefilesystem.Therootfilesystemis
mountedon/;youcannotmounttwofilesystemsin
thesameplace.Ifyouweretotrytomount
somethingon/,allfiles,directories,andfilesystems
thatwereundertherootdirectorywouldnolonger
beavailable,andthesystemwouldcrash.
Thiscommandworkedbecause/etc/fstabcontainsthe
additionalinformationneededtomountthefile:
/dev/scd0/mnt/cdromiso9660user,noauto,ro00
Youcanalsomountfilesystemsthatdonotappearin
/etc/fstab.Forexample,whenyouinsertafloppydiskette
thatholdsaDOSfilesystemintothefloppydiskettedrive,you
canmountthatfilesystemusingthefollowingcommand:
#mounttmsdos/dev/fd0/mnt/floppy
Thetmsdosspecifiesafilesystemtypeofmsdos.Youcan
mountDOSfilesystemsonlyifyouhaveconfiguredtheLinux
kernel(page525)toacceptDOSfilesystems.Youdonotneed
tomountaDOSfilesystemtoreadfromandwritetoit,suchas
whenyouusemcopy(page139).However,youdoneedto
mountaDOSfilesystemtouseLinuxcommands(otherthan
Mtoolscommands)onfilesonthefilesystem(whichmaybeon
adiskette).
MountOptions
Themountutilitytakesmanyoptions,whichyoucanspecifyon
thecommandlineorinthe/etc/fstabfile(page469).Fora
completelistofmountoptionsforlocalfilesystems,seethemount
manpage;forremotedirectoryhierarchies,seethenfsmanpage.
ThenoautooptioncausesLinuxnottomountthefilesystem
automatically.Thenosuidoptionforcesmountedsetuid
executablestorunwithregularpermissions(noeffectiveuser
IDchange)onthelocalsystem(thesystemthatmountedthe
filesystem).
Security:Mountremovabledeviceswith
thenosuidoption
Alwaysmountremovabledeviceswiththenosuid
optionsothatamalicioususerdoesnot,for
example,putasetuidcopyofbashonadiskand
havearootshell.
Unlessyouspecifytheuser,users,orowneroption,only
Superusercanmountandunmountafilesystem.Theuser
optionmeansthatanyusercanmountthefilesystem,butthe
filesystemcanbeunmountedonlybythesameuserwho
mountedit;usersmeansthatanyusercanmountand
unmountthefilesystem.Theseoptionsarefrequentlyspecified
forCDandfloppydrives.Theowneroption,whichisusedonly
underspecialcircumstances,issimilartotheuseroption
exceptthattheusermountingthedevicemustownthedevice.
MountingaLinuxFloppyDiskette
MountingaLinuxfloppydisketteissimilartomountinga
partitionofaharddisk.Putanentrysimilartothefollowingin
/etc/fstabforadisketteinthefirstfloppydrive:
/dev/fd0/mnt/floppyautonoauto,users00
Specifyingafilesystemtypeofautocausesthesystemto
probethefilesystemtodetermineitstypeandallowsusersto
mountavarietyofdiskettes.Createthe/mnt/floppydirectory
ifnecessary.Insertadisketteandtrytomountit.Thediskette
mustbeformatted(usefdformat).Inthefollowingexamples,the
errormessagefollowingthefirstcommandusuallyindicates
thereisnofilesystemonthediskette.Usemkfs(page419)to
createafilesystembutbecareful,becausemkfsdestroysalldata
onthediskette:
#mount/dev/fd0
mount:youmustspecifythefilesystemtype
#mkfs/dev/fd0
mke2fs1.38(30-Jun-2005)
Filesystemlabel=
OStype:Linux
Blocksize=1024(log=0)
Fragmentsize=1024(log=0)
184inodes,1440blocks
72blocks(5.00%)reservedforthesuperuser
Firstdatablock=1
Maximumfilesystemblocks=1572864
1blockgroup
8192blockspergroup,8192fragmentspergroup
184inodespergroup
Writinginodetables:done
Writingsuperblocksandfilesystemaccountinginformation:done
Thisfilesystemwillbeautomaticallycheckedevery24mountsor
180days,whichevercomesfirst.Usetune2fs-cor-itooverride.
Trythemountcommandagain:
#mount/dev/fd0
#mount
...
/dev/fd0on/mnt/floppytypeext2(rw,noexec,nosuid,nodev)
#df-h/dev/fd0
FilesystemSizeUsedAvailUse%Mountedon
/dev/fd01.4M19K1.3M2%/mnt/floppy
Themountcommandwithoutanyargumentsanddfh
/dev/fd0showthefloppyismountedandreadyforuse.
umount:UnmountsaFilesystem
Theumountutilityunmountsafilesystemaslongasitdoesnot
containanyfilesordirectoriesthatareinuse(open).For
example,alogged-inuser'sworkingdirectorymustnotbeon
thefilesystemyouwanttounmount.Thenextcommand
unmountstheCDmountedearlier:
$umount/mnt/cdrom
Unmountafloppyoraremotedirectoryhierarchythesameway
youwouldunmountapartitionofaharddrive.
Theumountutilityconsults/etc/fstabtogetthenecessary
informationandthenunmountstheappropriatefilesystemfrom
itsserver.Whenaprocesshasafileopenonthefilesystemthat
youaretryingtounmount,umountdisplaysamessagesimilarto
thefollowing:
umount:/home:deviceisbusy
Tip:Whenyoucannotunmountadevice
becauseitisinuse
Whenaprocesshasafileopenonadeviceyouneed
tounmount,usefusertodeterminewhichprocess
hasthefileopenandtokillit.Forexample,when
youwanttounmountthefloppydiskette,givethe
commandfuserki/mnt/floppy(substitutethe
mountpointforthedisketteonthelocalsystemfor
/mnt/floppy.Aftercheckingwithyou,this
commandkillstheprocessusingthediskette.
Usetheaoptiontoumounttounmountallfilesystems,except
fortheonemountedat/,whichcanneverbeunmounted.You
cancombineawiththetoptiontounmountfilesystemsofa
giventype(ext3,nfs,orothers).Forexample,thefollowing
commandunmountsallmountednfsdirectoryhierarchiesthat
arenotbeingused:
#umount-atnfs
fstab:KeepsTrackofFilesystems
Thesystemadministratormaintainsthe/etc/fstabfile,which
listslocalandremotedirectoryhierarchies,mostofwhichthe
systemmountsautomaticallywhenitboots.Thefstabfilehas
sixcolumns;ahyphenkeepstheplaceofacolumnthathasno
value:
1. NameThenameoftheblockdevice(page463)orremote
directoryhierarchy.Aremotedirectoryhierarchyappearsas
hostname:pathname,wherehostnameisthenameof
thehostthathousesthefilesystem,andpathnameisthe
absolutepathnameofthedirectorythatistobemounted.
Youcansubstitutethevolumelabelofalocalfilesystemby
usingtheformLABEL=xx,wherexxisthevolumelabel.
Refertoe2labelonpage418.
2. MountpointThenameofadirectoryfilethatthe
filesystem/directoryhierarchyistobemountedon.Ifit
doesnotalreadyexist,createthisdirectorywithmkdir.
3. TypeThetypeoffilesystem/directoryhierarchythatisto
bemounted.Localfilesystemsaregenerallyoftypeext2or
ext3,andremotedirectoryhierarchiesareoftypenfs.
Table12-1onpage464providesalistoffilesystemtypes.
4. MountoptionsAcomma-separatedlistofmountoptions,
suchaswhetherthefilesystemismountedforreadingand
writing(rw,thedefault)orreadonly(ro).Refertothemount
andnfsmanpagesforlistsofoptions.
5. DumpUsedbydump(page545)todeterminewhentoback
upthefilesystem.
6. FsckSpecifiestheorderinwhichfsckchecksfilesystems.
Root(/)shouldhavea1inthiscolumn.Filesystemsthat
aremountedtoadirectoryjustbelowtherootdirectory
shouldhavea2.Filesystemsthataremountedonanother
mountedfilesystem(otherthanroot)shouldhavea3.For
example,iflocalisaseparatefilesystemfrom/usrand
localismountedon/usr(as/usr/local),thenlocal
shouldhavea3.Filesystemsanddirectoryhierarchiesthat
donotneedtobechecked(forexample,remotelymounted
directoryhierarchiesoraCD)shouldhavea0.
Thefollowingexampleshowsatypicalfstabfile:
#cat/etc/fstab
LABEL=/1/ext3defaults11
LABEL=/boot1/bootext3defaults12
devpts/dev/ptsdevptsgid=5,mode=62000
tmpfs/dev/shmtmpfsdefaults00
LABEL=/home1/homeext3defaults12
proc/procprocdefaults00
sysfs/syssysfsdefaults00
LABEL=SWAP-hda5swapswapdefaults00
/dev/hda3/oldhomeext3defaults00
tuna:/p04/p04nfsdefaults00
/dev/fd0/mnt/floppyautonoauto,users00
fsck:ChecksFilesystemIntegrity
Thefsck(filesystemcheck)utilityverifiestheintegrityof
filesystemsand,ifpossible,repairsanyproblemsitfinds.
Becausemanyfilesystemrepairscandestroydata,particularly
onanonjournalingfilesystem(page1039),suchasext2,by
defaultfsckasksyouforconfirmationbeforemakingeachrepair.
Caution:Donotrunfsckonamounted
filesystem
Donotrunfsckonamountedfilesystem(except/).
Whenyouattempttocheckamountedfilesystem,
fsckwarnsyouandasksyouwhetheryouwantto
continue.Replyno.YoucanrunfsckwiththeN
optiononamountedfilesystemasitwillnotwriteto
thefilesystem;asaresult,noharmcancomeof
runningit.
Thefollowingcommandchecksallunmountedfilesystemsthat
aremarkedtobecheckedin/etc/fstab(page451)exceptfor
therootfilesystem:
#fsck-AR
Youcancheckaspecificfilesystemwithacommandsimilarto
oneofthefollowing:
#fsck/home
or
#fsck/dev/hda6
Crashflag
The/etc/rc.d/rc.sysinitstart-upscriptlooksfortwoflagsin
therootdirectoryofeachpartitiontodeterminewhetherfsck
needstoberunonthatpartitionbeforeitismounted.The
.autofsckflag(thecrashflag)indicatesthatthepartition
shouldbechecked.Bydefault,thepersonbringingupthe
systemhas5secondstorespondtoapromptwithay;ifno
responseismade,thecheckisskipped.Whentheotherflag,
forcefsck,isset,theuserisgivennochoice;fsckis
automaticallyrunonthepartition.Thesechecksareinaddition
tothoseestablishedbytune2fs(seenextsection).The.autofsck
flagispresentwhilethesystemisrunningandisremovedwhen
thesystemisproperlyshutdown.Whenthesystemcrashes,
theflagispresentwhenthesystemisbroughtup.The
forcefsckflagisplacedonthefilesystemwhenthedisk
containsanerrorandmustbechecked.
tune2fs:ChangesFilesystemParameters
Thetune2fsutilitydisplaysandmodifiesfilesystemparameters
onext2filesystemsandonext3filesystems,astheyare
modifiedext2filesystems.Thisutilitycanalsosetupjournaling
onanext2filesystem,turningitintoanext3filesystem.With
theintroductionofincreasinglymorereliablehardwareand
software,systemsarerebootedlessfrequently,soitis
importanttocheckfilesystemsregularly.Bydefault,fsckisrun
oneachpartitionwhilethesystemisbroughtup,beforethe
partitionismounted.(Thechecksscheduledbytune2fsare
separateandscheduleddifferentlyfromthechecksthatare
donefollowingasystemcrashorharddiskerror[seethe
previoussection].)Dependingontheflags,fsckmaydonothing
morethandisplayamessagesayingthatthefilesystemis
clean.Thelargerthepartition,themoretimeittakestocheck
it,assuminganonjournalingfilesystem.Thesechecksareoften
unnecessary.Thetune2fsutilityhelpsyoutofindahappy
mediumbetweencheckingfilesystemseachtimeyourebootthe
systemandnevercheckingthem.Itdoessobyscheduling
whenfsckchecksafilesystem(thesechecksoccuronlywhen
thesystemisbooted).[1]Youcanusetwoschedulingpatterns:
timeelapsedsincethelastcheckandnumberofmountssince
thelastcheck.Thefollowingcommandcauses/dev/hda6to
becheckedwhenfsckrunsafterithasbeenmountedeight
timesorafter15dayshaveelapsedsinceitslastcheck,
whicheverhappensfirst:
[1]Forsystemswhosepurposeinlifeistoruncontinuously,thiskindofschedulingdoes
notwork.Youmustdevelopaschedulethatisnotbasedonsystemrebootsbutratheron
aclock.Eachfilesystemmustbeunmountedperiodically,checkedwithfsck(preceding
section),andthenremounted.
#tune2fs-c8-i15/dev/hda3
tune2fs1.38(30-Jun-2005)
Settingmaximalmountcountto8
Settingintervalbetweenchecksto1296000seconds
Thenexttune2fscommandissimilarbutworksonadifferent
partitionandsetsthecurrentmountcountto4.Whenyoudo
notspecifyacurrentmountcount,itissettozero:
#tune2fs-c8-i15-C4/dev/hda3
tune2fs1.38(30-Jun-2005)
Settingmaximalmountcountto8
Settingcurrentmountcountto4
Settingintervalbetweenchecksto1296000seconds
Theloptiondisplaysalistofinformationaboutthepartition.
Youcancombinethisoptionwithothers.BelowtheMaximum
mountcountis1,whichmeansthatfsckandthekernelignore
themountcountinformation.Amaximummountcountof0
worksthesameway:
#tune2fs-l/dev/hda3
tune2fs1.38(30-Jun-2005)
Filesystemvolumename:/home
Lastmountedon:<notavailable>
FilesystemUUID:70929327f5d2486abe446f7b677ab6b6
Filesystemmagicnumber:0xEF53
Filesystemrevision#:1(dynamic)
Filesystemfeatures:has_journalext_attrresize_inodedir_index
filetypeneeds_recoverysparse_superlarge_file
Defaultmountoptions:(none)
Filesystemstate:clean
Errorsbehavior:Continue
FilesystemOStype:Linux
Inodecount:2560864
Blockcount:2560359
...
Lastmounttime:WedJan2508:33:302006
Lastwritetime:WedJan2510:13:272006
Mountcount:4
Maximummountcount:8
Lastchecked:TueJun2803:03:552005
Checkinterval:1296000(2weeks,1day)
...
Setthefilesystemparametersonthelocalsystemsothatthey
areappropriatetothewayyouuseit.UsingtheCoptionto
staggerthechecksensuresthatallchecksdonotoccuratthe
sametime.Alwayschecknewandupgradedfilesystemsto
makesurethattheyhavechecksscheduledasyoudesire.
Tochangeanext2filesystemtoanext3filesystem,youmust
putajournal(page1039)onthefilesystem,andthekernel
mustsupportext3filesystems.Usethejoptiontosetupa
journalonanunmountedfilesystem:
#tune2fs-j/dev/hda7
tune2fs1.38(30-Jun-2005)
Creatingjournalinode:done
Thisfilesystemwillbeautomaticallycheckedevery23mountsor
180days,whichevercomesfirst.Usetune2fs-cor-itooverride.
Beforeyoucanusefstab(page451)tomountthechanged
filesystem,youmustmodifyitsentryinthefstabfiletoreflect
itsnewtype.Changethethirdcolumntoext3.
Thefollowingcommandchangesanunmountedext3filesystem
toanext2filesystem:
#tune2fs-O^has_journal/dev/hda7
tune2fs1.38(30-Jun-2005)
Refertothetune2fsmanpageformoredetails.
RAIDFilesystem
RAID(RedundantArraysofInexpensive/IndependentDisks)
spreadsinformationacrossseveraldiskstocombineseveral
physicaldisksintoonelargervirtualdevice.RAIDimproves
performanceandcreatesredundancy.Morethansixtypesof
RAIDconfigurationsexist.UsingRedHattools,youcansetup
softwareRAID.HardwareRAIDrequireshardwarethatis
designedtoimplementRAIDandisnotcoveredhere.
Caution:Donotreplacebackupswith
RAID
DonotuseRAIDasareplacementforregular
backups.Ifyoursystemexperiencesacatastrophic
failure,RAIDwillbeuseless.Earthquake,fire,theft,
oranotherdisastermayleaveyourentiresystem
inaccessible(ifyourharddrivesaredestroyedor
missing).RAIDdoesnottakecareofsomethingas
simpleasreplacingafilewhenyoudeleteitby
accident.Inthesecasesabackuponaremovable
medium(thathasbeenremoved)istheonlyway
youwillbeabletorestoreafilesystem.
RAIDcanbeaneffectiveadditiontoabackup.RedHatoffers
RAIDsoftwarethatyoucaninstalleitherwhenyouinstallaRed
Hatsystemorasanafterthought.TheLinuxkernelcan
automaticallydetectRAIDdiskpartitionsatboottimeifthe
partitionIDissetto0xfd,whichfdiskrecognizesasLinuxraid
autodetect.
SoftwareRAID,asimplementedinthekernel,ismuchcheaper
thanhardwareRAID.Notonlydoesthissoftwareavoid
specializedRAIDdiskcontrollers,butitalsoworkswiththeless
expensiveIDEdisksaswellasSCSIdisks.Formoreinformation
refertotheSoftware-RAIDHOWTO.
ChapterSummary
Filesystemsholddirectoriesoffiles.Thesestructuresstoreuser
dataandsystemdatathatarethebasisofusers'workonthe
systemandthesystem'sexistence.Linuxsupportsmanytypes
offilesincludingordinaryfiles,directories,links,andspecial
files.Specialfilesprovideaccesstooperatingsystemfeatures.
Thekernelusesmajorandminordevicenumberstoidentify
classesofdevicesandspecificdeviceswithineachclass.
CharacterandblockdevicesrepresentI/Odevicessuchashard
disksandprinters.Inodes,whichareidentifiedbyinode
numbers,arestoredondiskanddefineafile'sexistence.
Whenthesystemcomesup,the/etc/fstabfilecontrolswhich
filesystemsaremountedandhowtheyaremounted(readonly,
readwrite,andsoon).Afterasystemcrash,filesystemsare
automaticallyverifiedandrepairedifnecessarybyfsck.Youcan
usetune2fstoforcethesystemtorunfsckonafilesystem
periodicallywhenthesystemboots.
Exercises
1. Whatisthefunctionofthe/etc/hostsfile?Whichservicescanyouuseinplace
of,ortosupplement,thehostsfile?
2. Whatdoesthe/etc/resolv.conffiledo?Whatdoesthenameserverlineinthis
filedo?
3. Whatisaninode?Whathappenstotheinodewhenyoumoveafilewithina
filesystem?
4. Whatdoesthe..entryinadirectorypointto?Whatdoesthisentrypointtointhe
root(/)directory?
5. Whatisadevicefile?Wherearedevicefileslocated?
6. WhatisaFIFO?WhatdoesFIFOstandfor?WhatisanothernameforaFIFO?How
doesaFIFOwork?
AdvancedExercises
7.
Writealineforthe/etc/fstabfilethatwouldmountthe/dev/hdb1ext3
filesystemon/extrawiththefollowingcharacteristics:Thefilesystemwillnotbe
mountedautomaticallywhenthesystemboots,andanyonecanmountand
unmountthefilesystem.
8. Withoutusingrm,howcanyoudeleteafile?(Hint:Howdoyourenameafile?)
9. AfterburninganISOimagefilenamedimage.isotoaCDon/dev/hdc,howcan
youcanverifythecopyfromthecommandline?
10. Whyshould/varresideonaseparatepartitionfrom/usr?
11. CreateaFIFO.Usingtheshell,demonstratethattwouserscanusethisFIFOto
communicateasynchronously.
12. HowwouldyoumountanISOimagesothatyoucouldcopyfilesfromitwithout
burningittoaCD?
13.DownloadingandInstallingSoftware
INTHISCHAPTER
yum:KeepstheSystemUp-to-Date(FEDORA) 476
pirut:AddsandRemovesSoftwarePackages(FEDORA) 483
BitTorrent(FEDORA) 484
rpm:RedHatPackageManager 487
KeepingSoftwareUp-to-Date 493
up2date:KeepsSoftwareUp-to-Date(RHEL) 494
RedHatNetwork(RHEL) 498
wget:DownloadsFilesNoninteractively 500
Asoftwarepackageisthecollectionofscripts,programs,files,
anddirectoriesrequiredtorunasoftwareapplication,including
utilitiesandsystemsoftware.Usingpackagesmakesiteasierto
transfer,install,anduninstallapplications.Apackagecontains
eitherexecutablefilesorsourcecodefiles.Executablefilesare
precompiledforaspecificprocessorandoperatingsystem,
whereassourcefilesneedtobecompiledbutwillrunonawide
rangeofmachinesandoperatingsystems.
Softwareforyoursystemcancomeindifferentkindsof
packages,suchasrpm(page487),theGNUConfigureandBuild
System(page491),tar,compressedtar,andothers.Themost
popularpackageisrpm.Otherpackages(suchastar),which
werepopularbeforetheintroductionofrpm,areusedlessoften
todaybecausetheyrequiremoreworkonthepartofthe
installer(you)anddonotprovidethedepthofprerequisiteand
compatibilitycheckingthatrpmoffers.Newerprogramssuchas
yum(discussednext)notonlycheckforcompatibilitybutalso
obtainovertheInternetadditionalsoftwarerequiredtoinstall
andrunagivensoftwarepackage.
yum:KeepstheSystemUp-to-Date(FEDORA)
EarlyreleasesofRedHatLinuxdidnotincludeatoolfor
managingupdates.Althoughtherpmutilitycouldinstallor
upgradeindividualsoftwarepackages,itwasuptotheuserto
locateapackageandanypackagesitwasdependenton.When
TerraSoftproduceditsRedHatbasedLinuxdistributionforthe
PowerPC,thecompanycreatedtheYellowDogUpdatertofill
thisgap.Thisprogramhassincebeenportedtoother
architecturesanddistributions.Theresult,namedYellowDog
Updater,Modified(yum,linux.duke.edu/projects/yum),is
includedwithFedoraCore.
rpmpackages
Theyumutilityworkswithrpmpackages.Whenyuminstallsor
upgradesasoftwarepackage,italsoinstallsorupgrades
packagesthatthepackageisdependenton.Refertopage487
formoreinformationonrpm.
Repositories
Theyumutilitydownloadspackageheadersandpackagesfrom
serverscalledrepositories.AlthoughFedoraprovides
repositories,yumissetuptousecopiesoftheserepositories
thatarekeptonmirrorsites.Thenextsectioncoversrepository
selection.
Configuringyum
Youdonotneedtoconfigureyum:Asitisinstalled,itisreadyto
use.Thissectiondescribestheyumconfigurationfilesforusers
whowanttomodifythem.Theprimaryconfigurationfile,
/etc/yum.conf,holdsglobalsettings.Asdistributedwith
Fedora,secondaryfilesinthe/etc/yum.repos.ddirectory
definerepositories.ThefirstexampleshowstheFedora
yum.conffile:
$cat/etc/yum.conf
[main]
cachedir=/var/cache/yum
keepcache=0
debuglevel=2
logfile=/var/log/yum.log
pkgpolicy=newest
distroverpkg=redhat-release
tolerant=1
exactarch=1
obsoletes=1
gpgcheck=1
plugins=1
metadata_expire=1800
#PUTYOURREPOSHEREORINseparatefilesnamedfile.repo
#in/etc/yum.repos.d
Thesectionlabeled[main]definesglobalconfigurationoptions.
Thecachedirspecifiesthedirectorythatyumwillstore
downloadedpackagesin,althoughwithkeepcachesetto0,
yumdoesnotstoreheadersandpackagesafterinstallingthem.
Theamountofinformationloggedisspecifiedbydebuglevel,
withavalueof10producingthemostinformation.Thelogfile
specifieswhereyumkeepsitslog.
Thepkgpolicydefineswhichversionofasoftwarepackageyum
installs;setittonewesttoinstallthemostrecentversionsof
packages.Youcanalsoconfigureyumtotrytoinstallfroma
specificserver,fallingbacktootherserversincaseoffailure.
Theyumutilityusesdistroverpkgtodeterminewhichversion
ofthedistributionthesystemisrunning.Youshouldnotneed
tochangethissetting.
Withtolerantsetto1,yumcorrectssimplecommandline
errors,suchasattemptingtoinstallapackagethatisalready
presentonthesystem;settingtolerantto0turnsthisfeature
off.Settingexactarchto1causesyumtoupdatepackagesonly
withpackagesofthesamearchitecture,therebypreventingan
i686packagefromreplacingani386package,forexample.You
canuseretriestospecifythenumberoftimesyumwilltryto
retrieveafilebeforereturninganerror(thedefaultis6).Set
thisparameterto0tocauseyumtocontinuetryingforever.
Settingobsoletesto1causesyumtoreplaceobsolete
packageswhendoinganupdate;ithasnoeffectduringan
install.Whengpgcheckissetto1,yumcheckstheGPG(page
992)signaturesonpackagesitinstalls.Thischeckverifiesthe
authenticityofthepackages.Settingpluginsto1enablesyum
plugins,whichextendyumfunctionality.(See
wiki.linux.duke.edu/YumPluginsandyuminsection8oftheman
pagesformoreinformationonyumplugins.)The
metadata_expireparameterspecifiesthenumberofseconds
thatyumusesthemetadataitdownloadsfromtherepository
aboutpackagesbeforeitdownloadstheinformationagain.
Althoughthebalanceoftheyumconfigurationinformation,
whichspecifiestheyumrepositories,canappearinthe
yum.conffile,FedoraCoreputsinformationabouteach
repositoryinaseparatefileinthe/etc/yum.repos.d
directory.Aparametersetinarepositorysectionoverridesthe
sameparametersetinthe[main]section.
$ls/etc/yum.repos.d
fedora-core.repofedora-legacy.repo
fedora-development.repofedora-updates.repo
fedora-extras-development.repofedora-updates-testing.repo
fedora-extras.repo
Eachofthesefilescontainsaheader,suchas[core],which
providesauniquenamefortherepository.Thenameofthefile
isgenerallysimilartotherepositoryname,withtheadditionof
afedora-prefixanda.repofilenameextension.Commonly
usedrepositoriesarecore(heldinthefedora-core.repofile),
whichcontainsthepackagespresentontheinstallationCDs;
updates(heldinthefedora-updates.repofile),which
containsupdatedversionsofthestablepackages;and
updates-testing,whichcontainsupdatesthatarenotready
forrelease.Thislastrepositoryisnotenabled;donotenableit
unlessyouaretestingunstablepackages.Neverenablethis
repositoryonaproductionsystem.
Optional
Each*.repofileincludesspecificationsforseveralrelatedrepositories,whichare
usuallydisabled.Forexample,thefedora-core.repofileholds[core-
debuginfo]and[core-source]inadditionto[core].Youcannotdownload
sourcefilesusingyum.Useyumdownloader(page482)forthistask.
Thenextexampleshowspartofthefedora-core.repofilethat
specifiestheparametersforthecorerepository:
$cat/etc/yum.repos.d/fedora-core.repo
[core]
name=FedoraCore$releasever-$basearch
#baseurl=http://download.fedora.redhat.com/pub/fedora/linux/core/$releasever/$basearch/os/
mirrorlist=http://fedora.redhat.com/download/mirrors/fedora-core-$releasever
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-fedorafile:///etc/pki/rpm-gpg/RPM-GPG-KEY
Repositoryspecification
Eachrepositoryspecificationcontainsthenameofthe
repositoryenclosedinbrackets([]),aname,abaseurl,anda
mirrorlist.Thenameprovidesaninformalnameforthe
repositorythatyumdisplays.Thebaseurlindicatesthelocation
ofthemainrepository;itiscommentedoutbydefault.The
mirrorlistspecifiestheURLofafilethatholdsalistof
baseurls,ormirrorsofthemainrepository.Thesedefinitions
usetwovariables:yumsets$basearchtothearchitectureof
thesystemand$releasevertotheversionoftherelease(such
as5forFedoraCore5).
Therepositorydescribedbythefileisenabled(yumwilluseit)if
enabledissetto1andisdisabledifenabledissetto0.As
describedearlier,gpgcheckdetermineswhetheryumchecks
GPGsignaturesonfilesitdownloads.Thegpgkeyspecifiesthe
locationoftheGPGkey.Refertotheyum.confmanpagefor
moreoptions.
UsingyumtoUpdate,Install,andRemove
Packages
Workingasroot,youcanrunyumfromacommandline.The
behaviorofyumdependsontheoptionsyouspecify.The
updateoption,withoutadditionalparameters,updatesall
installedpackages.Itdownloadspackageheadersforinstalled
packages,determineswhichpackagesneedtobeupdated,
promptsyoutocontinue,anddownloadsandinstallsthe
updatedpackages.
Updatingpackages
Inthefollowingexample,yumdeterminesthattwopackages,
gokandgedit,needtobeupdated.Theyumutilitysearches
thethreeenabledrepositories:core,extras,andupdates.Once
ithasdeterminedwhatitneedstodo,yumadvisesyouofthe
action(s)itwilltakeandpromptswithIsthisok[y/N].
#yumupdate
Loading"installonlyn"plugin
SettingupUpdateProcess
Settinguprepositories
core[1/3]
extras[2/3]
updates[3/3]
Readingrepositorymetadatainfromlocalfiles
ResolvingDependencies
-->Populatingtransactionsetwithselectedpackages.Pleasewait.
--->Downloadingheaderforgoktopackintotransactionset.
gok-1.0.7-1.i386.rpm100%|=========================|112kB00:01
--->Packagegok.i3860:1.0.7-1settobeupdated
--->Downloadingheaderforgedittopackintotransactionset.
gedit-2.14.1-1.i386.rpm100%|=========================|62kB00:00
--->Packagegedit.i3861:2.14.1-1settobeupdated
-->Runningtransactioncheck
DependenciesResolved
=============================================================================
PackageArchVersionRepositorySize
=============================================================================
Updating:
gediti3861:2.14.1-1updates3.2M
goki3861.0.7-1updates1.5M
TransactionSummary
=============================================================================
Install0Package(s)
Update2Package(s)
Remove0Package(s)
Totaldownloadsize:4.7M
Isthisok[y/N]:y
DownloadingPackages:
(1/2):gok-1.0.7-1.i386.r100%|=========================|1.5MB00:06
(2/2):gedit-2.14.1-1.i38100%|=========================|3.2MB00:14
RunningTransactionTest
FinishedTransactionTest
TransactionTestSucceeded
RunningTransaction
Updating:gedit#########################[1/4]
Updating:gok#########################[2/4]
Cleanup:gok#########################[3/4]
Cleanup:gedit#########################[4/4]
Updated:gedit.i3861:2.14.1-1gok.i3860:1.0.7-1
Complete!
Optional
Somepackagesshouldonlybeinstalled;theyshouldnotbeupdated.The
parameterinstallonlypkgsidentifiesthesepackages.Packagesrelatedtothe
kerneldefaulttoinstallonlypkgs.Thetokeepparameterspecifiesthenumber
ofversionsofinstallonlypkgspackagesthatyumkeeps.Theinstallonlyn
pluginsetstokeepto2.
Youcanupdateindividualpackagesbyspecifyingthenamesof
thepackagesonthecommandlinefollowingthewordupdate.
Installingpackages
Toinstallanewpackagetogetherwiththepackagesitis
dependenton,givethecommandyuminstall,followedbythe
nameofthepackage.Afteryumdetermineswhatitneedstodo,
itasksforconfirmation.Thenextexampleinstallsthetcsh
package:
#yuminstalltcsh
Loading"installonlyn"plugin
SettingupInstallProcess
Settinguprepositories
core[1/3]
extras[2/3]
updates[3/3]
Readingrepositorymetadatainfromlocalfiles
Parsingpackageinstallarguments
ResolvingDependencies
-->Populatingtransactionsetwithselectedpackages.Pleasewait.
--->Downloadingheaderfortcshtopackintotransactionset.
tcsh-6.14-6.fc5.1.i386.rp100%|=========================|11kB00:00
--->Packagetcsh.i3860:6.14-6.fc5.1settobeupdated
-->Runningtransactioncheck
...
Isthisok[y/N]:y
DownloadingPackages:
(1/1):tcsh-6.14-6.fc5.1.100%|=========================|465kB00:01
RunningTransactionTest
FinishedTransactionTest
TransactionTestSucceeded
RunningTransaction
Installing:tcsh#########################[1/1]
Installed:tcsh.i3860:6.14-6.fc5.1
Complete!
Youcanalsouseyumtoremovepackages,usingasimilar
syntax.Thefollowingexampleremovesthetcshpackage:
#yumremovetcsh
Loading"installonlyn"plugin
SettingupRemoveProcess
ResolvingDependencies
-->Populatingtransactionsetwithselectedpackages.Pleasewait.
--->Packagetcsh.i3860:6.14-6.fc5.1settobeerased
-->Runningtransactioncheck
...
Isthisok[y/N]:y
DownloadingPackages:
RunningTransactionTest
FinishedTransactionTest
TransactionTestSucceeded
RunningTransaction
Removing:tcsh#########################[1/1]
Removed:tcsh.i3860:6.14-6.fc5.1
Complete!
yumGroups
Inadditiontoworkingwithsinglepackages,yumcanworkwith
groupsofpackages.Thenextexampleshowshowtodisplaya
listofinstalledandavailablegroups:
#yumgrouplist
Loading"installonlyn"plugin
SettingupGroupProcess
Settinguprepositories
core[1/3]
extras[2/3]
updates[3/3]
InstalledGroups:
Office/Productivity
MySQLDatabase
Editors
SystemTools
...
AdministrationTools
DevelopmentTools
GraphicalInternet
AvailableGroups:
EngineeringandScientific
WindowManagers
XFCESoftwareDevelopment
...
PostgreSQLDatabase
NewsServer
Done
Thecommandyumgroupinfofollowedbythenameofagroup
displaysinformationaboutthegroup,includingadescriptionof
thegroupandalistofmandatory,default,andoptional
packages.Thenextexampledisplaysinformationaboutthe
MySQLDatabasegroupofpackages.Ifthenameofthe
packageincludesaSPACE,youmustquoteit.
#yumgroupinfo"MySQLDatabase"
Loading"installonlyn"plugin
SettingupGroupProcess
Settinguprepositories
core[1/3]
extras[2/3]
updates[3/3]
Group:MySQLDatabase
Description:ThispackagegroupcontainspackagesusefulforusewithMySQL.
MandatoryPackages:
mysql
DefaultPackages:
unixODBC
mysql-server
MySQL-python
mysql-connector-odbc
libdbi-dbd-mysql
perl-DBD-MySQL
OptionalPackages:
mod_auth_mysql
mysql-devel
qt-MySQL
mysql-bench
php-mysql
Toinstallagroupofpackages,givethecommandyum
groupinstallfollowedbythenameofthepackage.
OtheryumCommands
Manyyumcommandsandoptionsareavailable.Afewofthe
moreusefulcommandsaredescribedhere.Seetheyumman
pageforacompletelist.
check-update
Listspackagesthatareinstalledonthelocalsystemandhave
updatesavailableintheyumrepositories.
cleanall
Removesheaderfilesthatyumusesforresolvingdependencies.
Alsoremovescachedpackagesyumdoesnotautomatically
removepackagesoncetheyhavebeendownloadedand
installed,unlessyousetkeepcacheto0.
cleanmetadata
Removesthefilesthatyumusestodetermineremotepackage
availability.Usingthisoptionforcesyumtodownloadall
metadatathenexttimeyourunit.
listavailable
Listsallpackagesthatcanbeinstalledfromtheyum
repositories.
searchword
Searchesforwordinthepackagedescription,summary,
packager,andname.
RunningyumAutomatically
Fedoraincludesaservicethatwillcallyumnightlytoupdatethe
localsystem.Thisservicereliesonacronscriptin
/etc/cron.daily/yum.cron.Useservice(page406)and
chkconfig(page408)toturnonthenightlyupdateservice.The
logiskeptin/var/log/yum.logorasspecifiedinyum.conf.
#/sbin/serviceyumstart
Enablingnightlyyumupdate:[OK]
#/sbin/chkconfigyumon
UpgradingaSystemwithyum
Usingyumtoupgradeasystemfromonereleasetoanothercan
beproblematicandisnotrecommended.See
fedoraproject.org/wiki/YumUpgradeFaqformoreinformation.
DownloadingrpmPackageFileswith
yumdownloader
Theyumdownloaderutilitylocatesanddownloadsbutdoesnot
installrpmfiles.Ifthisutilityisnotavailableonthelocalsystem,
useyumtodownloadandinstalltheyum-utilspackagebefore
attemptingtorunyumdownloader.
Thefollowingexampledownloadsthesambarpmfileintothe
workingdirectory:
$yumdownloadersamba
core[1/3]
extras[2/3]
updates[3/3]
samba-3.0.21b-2.i386.rpm100%|=========================|16MB06:49
Downloadingsourcefiles
Youcanuseyumdownloaderwiththesourceoptiontodownload
rpmsourcepackagefiles.Todownloadsourcefiles,youmust
enablethesourcerepositoryinthe*.repofileyouwanttouse.
Forexample,todownloadthekernelsourcecode,change
enabled=0toenabled=1inthesectionofthefedora-
core.repofilefollowingthe[core-source]header.The
followingexampledownloadsintheworkingdirectorytherpm
fileforthelatestversionofthekernelsourcecodeforthe
installedrelease:
#yumdownloader--sourcekernel
core[1/4]
core-source[2/4]
extras[3/4]
updates[4/4]
kernel-2.6.15-1.2054_FC5.100%|=========================|46MB01:18
Withoutthesourceoption,yumdownloaderdownloadsthe
executablekernelrpmfile.
pirut:AddsandRemovesSoftwarePackages
(FEDORA)
RedHatLinuxmakestheprocessofgraphicallyaddingand
removingsoftwarepackageseasierwiththepirutpackage
managerutility.Thisisthesametoolyouuseduringinstallation
whenyouselectpackagesmanually.Forclosercontroloverthe
packagesyouinstallandremove,useyum(page478).Under
RHELusethesystem-config-packagesutility.TodisplaythePackage
ManagerwindowFigure13-1,enterpirutonacommandline.
FromKDEselectMainmenu:System Add/Remove
SoftwareorfromGNOMEselectApplications:Add/Remove
Software.
Figure13-1.ThepirutPackageManagerwindow
[Viewfullsizeimage]
ThePackageManagerwindowhasthreeiconsontheleft:
Search,Browse,andList.WithBrowseselected(thedefault),
pirutdisplaystwoframestowardthetopofthewindowanda
textframebelowtheseframes.Theleftframedisplayssix
categoriesofsoftware:DesktopEnvironments,Applications,
Development,Servers,BaseSystem,andLanguages.Whenyou
clickoneofthecategoriesintheleftframe,therightframe
displaysalistofthepackagegroupsinthatcategory.
Figure13-1showssevenofthetenpackagegroupsinthe
Applicationscategory.Whenyouhighlightapackagegroup,pirut
displaysinformationaboutthegroupinthetextframe.
Initiallyacheckmarkintheboxadjacenttoapackagegroup
indicatesthatthepackagegroupisinstalled.Uninstallpackage
groupsbyremovingthecheckmark;installthembyaddinga
checkmark.
Optionalpackages
Withacheckmarkintheboxadjacenttoahighlightedpackage
group,pirutdisplaysthemessage[nofnnoptionalpackages
installed]andactivatestheOptionalpackagesbutton.Click
thisbuttontoopenawindowthatliststheoptionalpackagesin
thepackagegroup.
Thepirututilitydoesnotlistthemandatorypackagesina
packagegroup.Toselecttheoptionalpackagesyouwant
installedonthelocalsystem,placecheckmarksintheboxes
adjacenttothepackagenamesintheoptionalpackages
windowandthenclickClose.
Whenyouhaveselectedthepackagegroupsandpackagesyou
wanttoaddanddeselectedthoseyouwanttoremove,click
Applyatthelower-rightcornerofthePackageManager
window.Thepirututilitywilldisplayprogressmessagesasit
proceedsandaskyoutoclickOKwhenitisfinishedinstalling
andremovingpackages.
BitTorrent(FEDORA)
TheBitTorrentprotocolimplementsahybridclient/serverand
P2P(page1047)filetransfermechanism.BitTorrentefficiently
distributeslargeamountsofstaticdata,suchastheFedora
installationISOimages(page35).Itcanreplaceprotocolssuch
asanonymousFTP,whereclientauthenticationisnotrequired.
EachBitTorrentclientthatdownloadsafileprovidesadditional
bandwidthforuploadingthefile,therebyreducingtheloadon
theinitialsource.Ingeneral,BitTorrentdownloadsproceed
fasterthanFTPdownloads.
UnlikeprotocolssuchasFTP,BitTorrentgroupsmultiplefiles
intoasinglepackagecalledatorrent.Forexample,youcan
downloadtheFedoraCoreISOimages,togetherwiththe
releasenotesandMD5values,asasingletorrent.
BitTorrent,likeotherP2Psystems,doesnotuseadedicated
server.Instead,thefunctionsofaserverareperformedbythe
tracker,peers,andseeds.Thetrackerallowsclientsto
communicatewitheachother.Aclientcalledapeerwhenithas
downloadedpartofthetorrentandaseedonceithas
downloadedtheentiretorrentactsasanadditionalsourcefor
thetorrent.AswithaP2Pnetwork,eachpeer/seedthat
downloadsatorrentuploadstootherclientsthesectionsofthe
torrentithasalreadydownloaded.Thereisnothingspecial
aboutaseed:Itcanberemovedatanytimeoncethetorrentis
availablefordownloadfromotherseeds.
ThefirststepindownloadingatorrentusingBitTorrentisto
locateoracquirea.torrentfile.Suchafilecontainspertinent
informationaboutthetorrent,suchasitssizeandthelocation
ofthetracker.Youcanobtaina.torrentfilebyaccessingits
URI(page1061),oryoucanacquireitviatheWeb,anemail
attachment,orothermeans.TheBitTorrentclientcanthen
connecttothetrackertolearnthelocationsofotherclientsthat
itcandownloadthetorrentfrom.
Onceyouhavedownloadedatorrent,itisgoodmannersto
allowBitTorrenttocontinuetorunsootherclientscanuploadat
leastasmuchinformationasyouhavedownloaded.
Prerequisites
Usewhereistodeterminewhetherbittorrent-cursesisinstalledon
thelocalsystem.Ifitisnotinstalled,useyum(page478)to
installthebittorrentpackage.BecauseBitTorrentiswrittenin
PythonandrunsonanyplatformwithaPythoninterpreter,itis
notdependentonsystemarchitecture.(Thenoarchinthe
nameoftherpmfilestandsfor"noarchitecture.")Pythonis
installedin/usr/bin/pythonandisavailableinthepython
package.
TheBitTorrentprogram,bittorrent-curses,isatextualclientthat
providesapseudographicalinterface.Complementingbittorrent-
curses,otherclientsprovideadditionalfeatures.Someofthese
clientsareavailableonsourceforge.net.
UsingBitTorrent
Copythe.torrentfileforthetorrentyouwanttodownloadto
theworkingdirectory.Forexample,toobtainthe.torrentfile
forFedoraCore,pointabrowserattorrent.fedoraproject.org.
(Seepage35forinformationaboutburninginstallationCDs
fromISOimages.)Selecttherelease(e.g.,FedoraCore5),
architecture(e.g.,i386),andtheformat(CDunlessDVDis
specifiedinthenameofthetorrent).Downloadthe.torrentfile
(itisusuallylessthan300kilobytes);itwillhaveaname
somethinglikebordeaux-binary-i386.torrent.Withthe
.torrentfileintheworkingdirectory,thesimplestcommand
youcanusetodownloadthetorrentis
$bittorrent-cursesbordeaux-binary-i386.torrent
Theprecedingcommandsavesthedownloadedfilesina
directorynamedbordeaux(thenameoftheFedorarelease)as
specifiedbythe.torrentfile.Figure13-2(nextpage)shows
bittorrent-cursesrunning.DependingonthespeedoftheInternet
connectionandthenumberofseeds,downloadingalarge
torrentcantakefromhourstodays.
Figure13-2.bittorrent-cursesworkingwiththe
FedoraCoretorrent
[Viewfullsizeimage]
Caution:Makesureyouhaveenough
roomtodownloadthetorrent
Sometorrentsarehuge.FedoraCorecomprisesfiles
thattotalmorethan3gigabytes.Makesurethe
partitionyouareworkinginhasenoughroomto
holdthefilesyouaredownloading.
Foralistofoptions,givethecommandbittorrent-curses
help.Oneofthemostusefuloptionsismax_upload_rate,
whichlimitshowmuchbandwidthotherBitTorrentuserscan
usewhiledownloadingthetorrentfromyou.Thedefaultis20;
specify0whenyoudonotwanttolimittheuploadbandwidth.
ThefollowingcommandpreventsBitTorrentfromusingmore
than10kilobytespersecondofupstreambandwidth:
$bittorrent-curses--max_upload_rate10bordeaux-binary-i386.torrent
BitTorrentusuallyallowshigherdownloadratesforclientsthat
uploadmoredata,soitistoyouradvantagetoincreasethis
valueifyouhavesparebandwidth.Youneedtoleaveenough
freeupstreambandwidthfortheacknowledgmentpacketsfrom
yourdownloadtogetthroughorelsethedownloadwillbevery
slow.Bydefault,theclientuploadstoamaximumofseven
otherclientsatonce.Youcanchangethisnumberbyusingthe
max_uploadsargument,followedbythenumberofconcurrent
uploadsyouwishtopermit.Thedefaultvalue,whichcanbe
specifiedby1,isareasonablenumberbasedonthe
max_upload_rate.Ifyouaredownloadingoveramodem,try
settingmax_upload_rateto3andmax_uploadsto2.
ThenameofthefileordirectorythatBitTorrentsavesafileor
filesinisspecifiedaspartofthe.torrentfile.Youcanspecifya
differentfileordirectorynamebyusingthesave_asoption.
Thetorrentinfo-consoleutilitydisplaysthenameofthefileor
directorythatthetorrentwillbesavedin,thesizesofthefiles,
andotherinformationaboutthetorrent:
$torrentinfo-consolebordeaux-binary-i386.torrent
torrentinfo-console4.4.0-decodeBitTorrentmetainfofiles
metainfofile......:bordeaux-binary-i386.torrent
infohash...........:7be29789a9e257a4edaebec3417bf98e3ed459a3
directoryname......:bordeaux-binary-i386
files...............:
FC-5-i386-disc1.iso(687235072)
FC-5-i386-disc2.iso(700618752)
FC-5-i386-disc3.iso(721016832)
FC-5-i386-disc4.iso(720910336)
FC-5-i386-disc5.iso(387753984)
FC-5-i386-rescuecd.iso(79122432)
SHA1SUM(671)
archivesize........:3296658079(12575*262144+197279)
trackerannounceurl:http://torrent.linux.duke.edu:6969/announce
comment.............:
YoucanabortthedownloadbypressingCONTROL-C.The
downloadwillautomaticallyresumefromwhereitleftoffwhen
youdownloadthesametorrenttothesamelocationagain.
rpm:RedHatPackageManager
Therpm(RedHatPackageManager)utilityworksonlywith
softwarepackagesthathavebeenbuiltforprocessingbyrpm;it
installs,uninstalls,upgrades,queries,andverifiesrpm
packages.BecauseRedHatreleasedrpmundertheGPL(page
4),rpmisusedbyseveraldistributions.Therpmutilitykeeps
trackofthelocationswheresoftwarepackagesareinstalled,
theversionsoftheinstalledpackages,andthedependencies
betweenthepackages.
Sourcerpmpackagesarefrequentlyfoundinadirectorynamed
SRPMS(sourcerpms),whereasbinaryrpmpackagesusually
resideinRPMS.Whenyoudownloadbinarypackages,make
surethattheyarerelevanttothelocaloperatingsystem(both
distributionandreleaseforexample,FedoraCore5).[1]They
shouldalsobecompiledfortheappropriatearchitecture:
[1]Manyrpmpackagesrunonreleasesandevendistributionsotherthantheonesthey
werecompiledfor.However,installingpackagesintendedforotherdistributionscan
createproblems.Inparticular,Mandrivapackagesarerarelycompatiblewithother
systems.
i386coversallIntel-andmostAMD-basedsystems.
i586coversPentium-classprocessorsandabove.
i686referstoPentiumIIorbetter,andincludesMMX
extensions.
S390isforIBMSystem/390.
ia64isforthe64-bitIntelprocessor.
alphaisfortheDEC/CompaqAlphachip.
athlondenotestheAMDAthlonfamilyincludingx86_64
andAMD64.
ppcisforthePowerPCchip.
sparccoverstheSunSparcprocessor).
Thenameoftherpmfilecontainsalmostallthenecessary
information.
yumdownloader
Seepage482forinstructionsonusingyumdownloaderto
downloadrpmpackagefiles.
Fedoradownloadsite
Gotodownload.fedora.redhat.com/pub/fedora/linuxtobrowse
theFedoraProject'sextensivecollectionoffilesthatyoucan
download.Fromthispageselectcoreforpackagesthatare
partoftheFedorareleaseandextrasforotherpackages.Next
selectthereleaseofFedorayouwanttodownloadapackageor
updatesfor.FinallyselectthearchitectureorSRPMSifyou
wanttodownloadsourcefiles.Selectamirrorsitefromthelist
atfedora.redhat.com/download/mirrors.htmliftheRedHatsite
isbusy.
rpmfind.net
Othersites,suchasrpmfind.net,alsoholdrpmpackages.Each
ofthefollowinglinesfromasearchforsendmailon
rpmfind.netprovidestheinformationyouneedtoselectthe
appropriatesendmailpackage:
[Viewfullwidth]
sendmail-8.13.5-2mdk.x86_64.html...Mandrivadevelcookeramd64sendmail-8.13
.5-2mdk.x86_64.rpm
sendmail-8.13.5-2mdk.i586.html...Mandrivadevelcookeri586sendmail-8.13
.5-2mdk.i586.rpm
sendmail-8.13.5-2mdk.i586.html...Mandrivadevelcookercookersendmail-8.13
.5-2mdk.i586.rpm
sendmail-8.13.5-2mdk.src.html...MandrivadevelcookerSRPMSsendmail-8.13
.5-2mdk.src.rpm
sendmail-8.13.5-2.5.0.amd64.html...OpenPKGsendmail-8.13.5-2
.5.0.amd64.rpm
sendmail-8.13.5-2.5.0.ix86.html...OpenPKGsendmail-8.13.5-2
.5.0.ix86.rpm
sendmail-8.13.5-2.5.0.sparc64.html...OpenPKGsendmail-8.13.5-2
.5.0.sparc64.rpm
sendmail-8.13.5-2.1.ppc.html...FedoraCoreDevelopmentppcsendmail-8.13.5-2
.1.ppc.rpm
sendmail-8.13.5-2.1.s390.html...FedoraCoreDevelopments390sendmail-8.13.5-2
.1.s390.rpm
sendmail-8.13.5-2.1.s390x.html...FedoraCoreDevelopments390xsendmail-8.13.5-2
.1.s390x.rpm
sendmail-8.13.5-2.1.ppc64.html...FedoraCoreDevelopmentppc64sendmail-8.13.5-2
.1.ppc64.rpm
sendmail-8.13.5-2.1.x86_64.html...FedoraCoreDevelopmentx86_64sendmail-8.13.5-2
.1.x86_64.rpm
sendmail-8.13.5-2.1.i386.html...FedoraCoreDevelopmenti386sendmail-8.13.5-2
.1.i386.rpm
sendmail-8.13.5-2.1.ia64.html...FedoraCoreDevelopmentia64sendmail-8.13.5-2
.1.ia64.rpm
sendmail-8.13.5-2.1.src.html...FedoraCoreDevelopmentSourcessendmail-8.13.5-2
.1.src.rpm
Clickthehtmlfilenameatthelefttodisplaymoreinformation
aboutthefile.(NotallpackageshaveanHTMLdescriptionfile.)
Clicktherpmfilenameattherighttodownloadthefile.Bothof
thesenamestellyouthenameoftheprogram,itsversion
number,anditsformat(sourceorcompiledfori386,alpha,
ia64,andsoon).Thecolumntotheleftoftherpmfilename
tellsyouwhichdistributionthefileisfor.
Packagesmarkednoarch("noarchitecture")containresources,
suchasimagesorscripts,thatarerunbyaninterpreter.You
caninstallandrunnoarchpackagesonanyarchitecture.
QueryingPackagesandFiles
Therpmutilitycanberunfromacommandline.Userpmqato
getalistofone-linesummariesofallpackagesinstalledonthe
system(anyusercanrunthisutility).Userpmq,followedby
thenameofthepackage,todisplaymoreinformationabouta
particularpackage.Forinstance,rpmqnistellsyouwhether
NISisinstalledand,ifso,whichversion.Usetheqloptionsto
listthefilesinapackage:
$rpm-qnis
packagenisisnotinstalled
$rpm-qllogrotate
/etc/cron.daily/logrotate
/etc/logrotate.conf
/etc/logrotate.d
/usr/sbin/logrotate
/usr/share/doc/logrotate-3.7.3
/usr/share/doc/logrotate-3.7.3/CHANGES
/usr/share/man/man8/logrotate.8.gz
/var/lib/logrotate.status
Withtheqioptions,rpmdisplaysinformationaboutapackage:
$rpm-qilogrotate
Name:logrotateRelocations:(notrelocatable)
Version:3.7.3Vendor:RedHat,Inc.
Release:2.2.1BuildDate:Sat11Feb200605:02:04PMPST
InstallDate:Mon13Feb200602:29:03AMPSTBuildHost:hs20-bc1-4.build.redhat.com
Group:SystemEnvironment/BaseSourceRPM:logrotate-3.7.3-2.2.1.src.rpm
Size:53982License:GPL
Signature:(none)
Packager:RedHat,Inc.<http://bugzilla.redhat.com/bugzilla>
Summary:Rotates,compresses,removesandmailssystemlogfiles.
Description:
Thelogrotateutilityisdesignedtosimplifytheadministrationof
logfilesonasystemwhichgeneratesalotoflogfiles.Logrotate
allowsfortheautomaticrotationcompression,removalandmailingof
logfiles.Logrotatecanbesettohandlealogfiledaily,weekly,
monthlyorwhenthelogfilegetstoacertainsize.Normally,
logrotaterunsasadailycronjob.
Installthelogrotatepackageifyouneedautilitytodealwiththe
logfilesonyoursystem.
Youcanusetheqfoptionstodeterminewhichpackageafile
belongsto.Thefollowingcommandshowsthatmoreispartof
theutil-linuxpackage.
$rpm-qf/bin/more
util-linux-2.13-0.20
Youcanincludethepoptionwithotheroptionstoqueryan
uninstalledrpmfile.
Installing,Upgrading,andRemovingPackages
Althoughitisfrequentlyeasiertouseyum(page478)orpirut
(page483),youcanuserpmtoinstall,upgrade,orremovea
package.Loginasorsutoroot.(Althoughyoucanrunrpmasa
nonprivilegeduser,youwillnothavepermissiontowritetothe
necessarydirectoriesduringaninstalloruninstall,andthe
procedurewillfail.Duringaquery,youdonotneedthis
permission,soyoucanandshouldworkasanonprivileged
user.)GivetheUoption,followedbythenameofthefilethat
containstherpmversionofthepackageyouwanttoinstall.The
Uoptionupgradesexistingpackagesandinstallsnewpackages
(asthoughyouhadusedtheioption).Forkernels,usei(not
U)toleavetheoldkernelintactwhenyouinstallanewkernel.
Addthev(verbose)optiontodisplaymoreinformationabout
whatishappeningandtheh(orhash)optiontodisplayhash
marksasthepackageisunpackedandinstalled.Forexample,
whileyouareloggedinasroot,givethefollowingcommandto
installsambaonthelocalsystem:
#rpm-Uvhsamba-3.0.21b-2.i386.rpm
Preparing...###########################################[100%]
1:samba###########################################[100%]
Whenyouinstallapackage,therpmfilemustbeintheworking
directoryoryoumustuseapathnamethatpointstotherpm
file.
Toremovethesamepackage,givethefollowingcommandfrom
anydirectory:
#rpm-esamba
error:Faileddependencies:
sambaisneededby(installed)system-config-samba-1.2.34-1.noarch
Whenyourunthiscommand,rpmreportsthatanotherpackage,
system-config-samba,isdependentonthesambapackage.To
removethesambapackage,youhavetwochoices:Youcan
ignorethedependencybyincludingrpm'snodepsoptionoryou
canremovethedependentpackageandthenremovethesamba
package.
#rpm-esystem-config-samba
#rpm-esamba
Ifyouremovethesambapackagewithoutremovingthepackage
thatisdependentonit,theutilitieswithinthedependent
packagewillnotwork.Intheprecedingexample,thesystem-
config-sambautilitywillnotwork.
Whenyouuserpmtoremoveapackage,rpmqueriesits
databasetofindtheinformationitneedstouninstallthe
packageandremoveslinks,unloadsdevicedrivers,andstops
daemonsasnecessary.Refertotherpmmanpageformorerpm
options.
InstallingaLinuxKernelBinary
ThefollowingstepsinstallanewLinuxkernelbinary.Referto
Chapter15whenyouwanttoconfigureandrebuildakernel
fromsourcefiles,ratherthaninstallinganew,prebuiltkernel
binary.
1. Runrpmwiththeioptiontoinstallthenewkernel.Donot
usetheUoption:Youareinstallinganewkernelthathasa
differentnamethantheoldkernel;youarenotupgrading
theexistingkernel.
2. Makesurethenewkernelworksbeforeyouremovetheold
kernel.Toverifythatthenewkernelworks,rebootthe
systemusingthenewkernel.
3. Removetheoldkernelbyremovingfileswhosenames
containthereleasenumber(andEXTRAVERSIONnumber
[page530],ifapplicable)from/bootor/(root).Remove
informationabouttheoldkernelfromgrub.conf.Youmay
wanttowaitawhilebeforeremovingtheoldkerneltomake
surethatnoproblemsarisewiththenewone.Insteadof
removingtheoldkernelmanually,youmaybeableto
removeitwiththetoolyouusedtoinstallit(rpm,yum,or
other).
InstallingNon-rpmSoftware
Mostsoftwarethatisnotinrpmformatcomeswithdetailed
instructionsonhowtoconfigure,build(ifnecessary),andinstall
it.Somebinarydistributions(thosecontainingprebuilt
executablesthatrunonRedHatLinux)requireyoutounpack
thesoftwarefromtherootdirectory.
The/optand/usr/localDirectories
Somenewerapplicationpackagesincludescriptstoinstall
themselvesautomaticallyintoadirectoryhierarchyunder/opt,
withfilesina/optsubdirectorythatisnamedafterthe
packageandexecutablesin/opt/binor/opt/package/bin.
ThesescriptsarerelativelynewadditionstoRedHatLinuxbut
arefamiliartoSunSolarisusers.
Othersoftwarepackagesallowyoutochoosewhereyouunpack
them.Becausemanydifferentpeopledevelopsoftwarefor
Linux,thereisnoconsistentmethodforinstallingit.Asyou
acquiresoftware,installitonthelocalsysteminasconsistent
andpredictableamanneraspossible.ThestandardLinuxfile
structurehasadirectoryhierarchyunder/usr/localfor
binaries(/usr/local/bin),manualpages(/usr/local/man),
andsoforth.Topreventconfusionlaterandtoavoidoverwriting
orlosingthesoftwarewhenyouinstallstandardsoftware
upgradesinthefuture,avoidinstallingnonstandardsoftwarein
standardsystemdirectories(suchas/usr/bin).Onamultiuser
system,makesurethatusersknowwheretofindthelocal
softwareandmakeanannouncementwheneveryouinstall,
change,orremovelocaltools.
GNUConfigureandBuildSystem
TheGNUConfigureandBuildSystemmakesiteasytobuilda
programthatisdistributedassourcecode(seeautoconfat
developer.gnome.org/tools/build.html).Thistwo-stepprocess
doesnotrequirespecialtoolsotherthanashell,make,andgcc
(theGNUCcompiler).Youdonotneedtoworkwithroot
privilegesforeitherofthesesteps.
ThefollowingexampleassumesyouhavedownloadedtheGNU
chessprogram(www.gnu.org/software/chess/chess.html)to
theworkingdirectory.Firstunpackanddecompressthefileand
cdtothenewdirectory:
$tar-xvzfgnuchess*
gnuchess-5.03/
gnuchess-5.03/book/
gnuchess-5.03/book/README
...
$cdgnuchess*
AfterreadingtheREADMEandINSTALLfiles,runtheconfigure
script,whichgathersinformationaboutthelocalsystemand
generatestheMakefilefile:
$./configure
checkingforaBSDcompatibleinstall.../usr/bin/install-c
checkingwhetherbuildenvironmentissane...yes
checkingformawk...mawk
checkingwhethermakesets${MAKE}...yes
checkingforgcc...gcc
checkingforCcompilerdefaultoutput...a.out
checkingwhethertheCcompilerworks...yes
...
checkingformemset...yes
configure:creating./config.status
config.status:creatingMakefile
config.status:creatingsrc/Makefile
config.status:creatingsrc/config.h
Refertotheconfigureinfopage,specificallytheprefixoption,
whichcausestheinstallphasetoplacethesoftwareina
directoryotherthan/usr/local.Thesecondstepistorun
make:
$make
Makingallinsrc
make[1]:Enteringdirectory'/hdd4/gnuchess-5.03/src'
cd..\
&&CONFIG_FILES=CONFIG_HEADERS=src/config.h\
/bin/sh./config.status
config.status:creatingsrc/config.h
config.status:src/config.hisunchanged
makeall-am
make[2]:Enteringdirectory'/hdd4/gnuchess-5.03/src'
source='atak.c'object='atak.o'libtool=no\
depfile='.deps/atak.Po'tmpdepfile='.deps/atak.TPo'\
depmode=gcc3/bin/sh../depcomp\
gcc-DHAVE_CONFIG_H-I.-I.-I.-g-O2-c'test-fatak.c||echo'./''atak.c
...
gcc-g-O2-ognuchessatak.obook.ocmd.oepd.oeval.ogenmove.ohash.ohung.oinit.o
iterate.omain.omove.onull.ooutput.oplayers.opgn.oquiesce.orandom.orepeat.o
search.osolve.osort.oswap.otest.ottable.outil.oversion.o-lreadline-lncurses-lm
make[2]:Leavingdirectory'/hdd4/gnuchess-5.03/src'
make[1]:Leavingdirectory'/hdd4/gnuchess-5.03/src'
make[1]:Enteringdirectory'/hdd4/gnuchess-5.03'
make[1]:Nothingtobedonefor'all-am'.
make[1]:Leavingdirectory'/hdd4/gnuchess-5.03'
$lssrc/gnuchess
src/gnuchess
Aftermakefinishes,thegnuchessexecutableisfoundinthesrc
directory.Ifyouwanttoinstallit,givethefollowingcommand
whilerunningwithrootprivileges:
#makeinstall
Makinginstallinsrc
make[1]:Enteringdirectory'/hdd4/gnuchess-5.03/src'
make[2]:Enteringdirectory'/hdd4/gnuchess-5.03/src'
/bin/sh../mkinstalldirs/usr/local/bin
/usr/bin/install-cgnuchess/usr/local/bin/gnuchess
make[2]:Nothingtobedonefor'install-data-am'.
...
Youcanrunthetwostepsandinstallthesoftwarewiththis
commandline:
#./configure&&make&&makeinstall
TheBooleanANDoperator,&&,allowstheexecutionofthe
secondsteponlyifthefirststepreturnedasuccessfulexit
status.
KeepingSoftwareUp-to-Date
Ofthemanyreasonstokeepsoftwareup-to-date,oneofthe
mostimportantissecurity.Althoughyoumayhearabout
software-basedsecuritybreachesafterthefact,yourarelyhear
aboutthefixesthatwereavailablebutneverinstalledbefore
thebreachoccurred.Timelyinstallationofsoftwareupdatesis
criticaltosystemsecurity.Linuxopen-sourcesoftwareisthe
idealenvironmenttofindandfixbugsandmakerepaired
softwareavailablequickly.Whenyoukeepthesystemand
applicationsoftwareup-to-date,youkeepabreastofbugfixes,
newfeatures,supportfornewhardware,speedenhancements,
andmore.
Bugs
Abugisanunwantedandunintendedprogramproperty,
especiallyonethatcausestheprogramtomalfunction
(definitioncourtesywww.foldoc.org).Bugshavebeenaround
forever,inmanytypesofsystems,machinery,thinking,andso
on.Allsophisticatedsoftwarecontainsbugs.Bugsinsystem
softwareorapplicationpackagescancrashthesystemorcause
programsnottoruncorrectly.Securityholes(atypeofbug)
cancompromisethesecurityofthesystem,allowingmalicious
userstoreadandwritefiles,sendmailtoyourcontactsinyour
name,ordestroyalldataonthesystem,renderingthesystem
useless.
Eveniftheengineersfixedallthebugs,therewouldstillbe
featurerequestsaslongasanyoneusedthesoftware.Bugs,
featurerequests,andsecurityholesareheretostay.Thusthey
mustbeproperlytrackedifdevelopersaretofixthemost
dangerous/importantbugsfirst,usersaretoresearchand
reportbugsinalogicalmanner,andadministratorsaretoapply
thedevelopers'fixesquicklyandeasily.
Bugtracking
Earlyon,Netscapeusedaninternalbug-trackingsystemnamed
BugSplat.Later,afterNetscapecreatedMozilla(mozilla.org)as
anopen-sourcebrowserproject,theMozillateamdecidedthat
itneededitsownbug-trackingsystem.Netscape'sIS
departmentwroteaveryshort-livedversionofBugzilla.Terry
Weissman,whohadbeenmaintainingBugSplat,thenwrotea
newopen-sourceversionofBugzillainTcl,rewritingitinPerla
coupleofmonthslater.
Bugzillabelongstoaclassofprogramsformallyknownas
defecttrackingsystems,ofwhichBugzillaisnowpreeminent.
AlmostallLinuxdevelopersusethistooltotrackproblemsand
enhancementrequestsfortheirsoftware.RedHatusesBugzilla
totrackbugsandbugfixesforitsLinuxdistributions;RedHat
NetworktakesadvantageofBugzillatonotifyusersofand
distributethesefixes.TouseBugzilla,goto
bugzilla.redhat.com.
Errata
ForbothRedHatEnterpriseLinuxandFedoraCore,RedHat
processessecurity,bugfix,andnewfeature(enhancement)
updates.Theeasiestwaytolearnaboutnewupdatesandto
obtainandinstallthemistouseup2date(page494)onRHEL
systemsandyum(page476)onFEDORAsystems.
AstheLinuxcommunity,includingRedHat,findsandfixes
operatingsystemandsoftwarepackagebugs,includingsecurity
holes,RedHatgeneratesrpmfiles(page487)thatcontainthe
codethatfixestheproblems.Whenyouupgradeasystem
softwarepackage,rpmrenamesmodifiedconfigurationfileswith
a.rpmsaveextension.Youmustmanuallymergethechanges
youmadetotheoriginalfilesintothenewfiles.
RHEL
IfyouarerunningRHEL,youprobablyhaveasubscriptionto
RHN(page498)andcanusethisservicetofindanddownload
updates.
FEDORA
ForinformationonFedoraCoreupdates,pointabrowserat
fedora.redhat.comandclickDownloadandthenDownload
Server.Selectcoreandupdates.Informationaboutupdates
ispostedtowww.redhat.com/mailman/listinfo/fedora-
announce-list(theFedoraAnnounceList).Youcanalsouseyum
tofind,download,andinstallupdates.
up2date:KeepsSoftwareUp-to-Date(RHEL)
Theroundbuttononthepanelthatchangescolorstoletyou
knowwhenupdatesareavailableiscalledtheRedHatNetwork
(RHN)AlertNotificationTool(page497).
WorkingwiththeRHNserver,theup2dateutilitydownloadsand
optionallyinstallsrpmpackagesusingyum-liketools.Itworks
withmanyfilesanddirectories,ingraphicalandcharacter-
basedmodes,andhasmanyoptions.
Theconfigureoptiongenerates
/etc/sysconfig/rhn/up2date,up2date'ssystemprofilefile.
Theup2date-configutility(discussedinthenextsection)isalink
toup2datewiththeconfigureoption.Youdonotnormallyuse
thisoptionbecauseup2dateconfiguresitself(createstheup2date
systemprofile)whennecessary.Thenoxoption(alsoup2date-
nox)runsup2dateintextualmode.Refertotheup2datemanpage
formoreinformation.
Inadditiontoupdatingpackagesonthesystem,up2datecan
downloadandinstallRedHatpackagesthatarenotonthe
system.Inthefollowingexample,Superusercallslinks,the
character-basedbrowserprogram,findslinksisnotonthe
system,andconfirmsthatfindingwithwhereis.Thenup2date,with
thewhatprovidesoption,queriestheRHELrepositorytofind
thattheelinkspackageprovideslinks.Finallyup2date,withan
argumentofthenameoftherpmpackagetobeinstalled,
downloadstheelinkspackage.Inthiscase,up2dateinstallsthe
packagebecausethatiswhattheup2dateprofileissetuptodo.
Youmustrunup2dateasSuperusertoinstallorupgradea
package.
#links
bash:/usr/bin/links:Nosuchfileordirectory
#whereislinks
links:
#up2date--whatprovideslinks
elinks-0.9.2-3.2
#up2dateelinks
FetchingObsoleteslistforchannel:rhel-i386-es-4...
Fetchingrpmheaders...
########################################
NameVersionRel
----------------------------------------------------------
elinks0.9.23.2i386
Testingpackageset/solvingRPMinter-dependencies...
########################################
elinks-0.9.2-3.2.i386.rpm:##########################Done.
Preparing###########################################[100%]
Installing...
1:elinks###########################################[100%]
Whenyougiveitacommand,up2datedetermineswheretolook
forthefileyourequestedbylookingatthe
/etc/sysconfig/rhn/sourcesconfigurationfile.Initiallythe
lineup2datedefaultinthisfilecausesup2datetousethe
repositoryspecifiedintheup2dateconfigurationfile
(/etc/sysconfig/rhn/up2date).
up2date-config:Configuresup2date
Theup2date-configutilitysetsparametersin
/etc/sysconfig/rhn/up2date,theup2dateconfigurationfile.
Althoughyoucanrunup2date-configfromacommandline,youdo
notusuallyneedtodosobecauseup2dateconfiguresitselfas
necessarythefirsttimeyourunit.Inagraphicalenvironment,
thistooldisplaysawindowwiththreetabs:General,
Retrieval/Installation(Figure13-3),andPackageExceptions.
SeeTable13-1(nextpage).
Figure13-3.Configuringup2date,
Retrieval/Installationtab
Table13-1.Configuringup2date
Textboxorcheckbox Function
General/NetworkSettings
SelectaRedHatNetworkServer
touse
Thistextboxisalreadyfilledin.
Donotchangeitunlessyouhave
reasontodoso.
EnableHTTPProxy Ifyouneedtouseaproxyserver,
entertheHTTPproxyserverinthe
requiredformat.
UseAuthentication SelectUseAuthenticationand
fillintheUsernameandPassword
textboxeswhentheproxyserver
requiresauthentication.These
spacesarefortheproxyserver,
notfortheRHNusernameand
password.
Retrieval/Installation
PackageRetrievalOptions
Donotinstallpackagesafter
retrieval
Download,butdonotinstall
packages.Youwillneedtoinstall
thenewpackagesmanually.
Donotupgradepackageswhen
localconfigurationfilehasbeen
modified
Donotdownloadorinstall
packagesthathavebeen
customized.Thisoptionisnot
necessaryunlessyouareusing
packagesotherthanthestandard
RedHatpackages.
Retrievesourcerpmalongwith
binarypackage
Downloadthesourcecode
(*.src.rpm)fileinadditiontothe
binaryfile(*.arch.rpm)thatisto
beinstalled.Theup2dateutilitydoes
nothingwiththesourcefileexcept
downloadit.
PackageVerificationOptions
UseGPGtoverifypackage
integrity
UseRedHat'sGPGsignatureto
verifytheauthenticityofthefiles
youaredownloading.IftheRed
Hatsignatureisnotonthelocal
system,up2dateaskswhetheryou
wantthesystemtodownloaditfor
you.Thisisacriticalsecuritylink;
itisagoodideatoselectthis
option.
PackageInstallationOptions
Afterinstallation,keepbinary
packagesondisk
Normallybinaryrpmfilesare
removedoncethefilesthey
containhavebeeninstalled.Select
thisoptionifyouwantthemleft
onthesysteminthepackage
storagedirectory.
Enablerpmrollbacks(allows
"undo"butrequiresadditional
storagespace)
Byusingextradiskspace,up2date
canstoreinformationsoitcan
uninstallapackageithasinstalled
andreinstalltheversionthatwas
installedpreviously.
OverrideversionstoredinSystem
Profile
Downloadandinstallpackagesfor
aversionofRedHatLinuxthat
youspecifyinthetextbox,
overridingtheversionnumberthat
isstoredinthesystemprofile.
Packagestoragedirectory Specifyadirectorytostorethe
downloadedfilesin.Bydefault,
theyarestoredin
/var/spool/up2date.
PackageExceptions Specifypackagesandfilesthat
youdonotwanttodownload.
Thesenamescanincludewildcard
characters.
PackageNamestoSkip Bydefault,kernel*appearsin
thislistbox,meaningthatnorpm
packageswhosenamesbeginwith
theletterskernelwillbe
downloaded.Installinganew
kernelisanimportantevent,and
RedHatLinuxassumesyoudonot
wantthistohappenwithoutyour
knowledge.UsetheAdd,Edit,
andRemovebuttonstoadjustthe
listboxtomeetyour
requirements.Normallyyoudonot
havetomakeanychangeshere.
FileNamestoSkip SimilartoPackageNamestoSkip
exceptyouspecifyfilenamesyou
wanttoskip.
RedHatNetworkAlertNotificationTool
TheRedHatNetwork(RHN)AlertNotificationToolcantakecare
ofeverythingyouneedtodofromthesystemtosetupandrun
up2datetokeepasystemup-to-date.TheRHNAlertNotification
ToolisrepresentedbyaroundbuttononboththeGNOMEand
KDEMainpanels.Itshowsoneoffouricons:
Bluewithacheckmarkindicatesthatalliswell:Thereare
nopendingdownloads.
Redwithanexclamationpointindicatesthatfilesneedtobe
downloaded.
Greenwithhalf-arrowspointingleftandrightindicatesthat
thesystemiscommunicatingwiththeserver.
Graywithaquestionmarkindicatesthatanerrorhas
occurred.Clicktheicontodisplaytheerrormessage.
IfthebuttonisnotontheMainpanel,runrhn-applet-guifrom
RunApplicationontheGNOMEActionmenuonthepanelat
thetopofthescreenorRunCommandontheKDEMainmenu
todisplayit.Table13-2(nextpage)describestheselectionson
theRHNAlertNotificationToolIconmenu(right-clicktodisplay
theseoptions).
Table13-2.RedHatNetworkAlertNotificationTool
Iconmenu
Selection Function
Checkforupdates Runsup2date(page494)inthebackgroundto
checkforupdates.Thegreeniconwitharrows
ontheRedHatNetworkAlertNotificationbutton
showsthatthesystemiscommunicatingwith
theserver.
Launchup2date Runsup2date(page494)intheforeground,
openingaseriesofwindowsthatdonotgiveyou
manyoptions.
Configuration Opensaseriesofwindowsthatdisplaytheterms
ofservice,allowyoutoconfigureaproxy,and
checkforupdates.
RHNWebsite OpensaFirefoxwindowdisplayingtheRHNWeb
site.
RedHatNetwork(RHEL)
RedHatNetwork(rhn.redhat.com),aserviceprovidedbyRed
Hat,isanInternet-basedsystemthatcankeepthesoftwareon
oneormoreRHELsystemsup-to-datewithminimalworkon
yourpart.YoumustsubscribetotheRHNservicetouseit.Red
Hatusesthetermentitletoindicatethatasystemsubscribesto
RHN:Asystemmustbeentitledbeforeitcantakeadvantageof
RHN.YoucanchoosetomakeRHNmoreorlessautomated,
givingyouvaryingdegreesofcontrolovertheupdateprocess.
RedHatchargesafeeforthisservice.
Theentitledsystemsaretheclients;RedHatmaintainsthe
RHNserver.TheRHNserverismuchmorethanasingleserver:
Itinvolvesmanysystemsanddatabasesthatarereplicatedand
locatedindifferentareas.Forthepurposeofunderstandinghow
tousetheclienttoolsonthelocalsystem,picturetheRHN
serverasasingleserver.Foradditionalinformation,refertothe
RedHatNetworkmanualsat
www.redhat.com/docs/manuals/RHNetwork.
WhenRedHatbuiltRHN,securitywasitspriority.Whenever
youallowaremotesystemtoputaprogramonasystemand
runit,thesetupmustbeveryclosetothetheoreticalidealof
absolutelysecure.Towardthisend,RHNneverinitiates
communicationwithasystem.Onceaprogramrunningona
systemsendsamessagetotheRHNserver,theservercan
respondandthesystemcantrusttheresponse.
SubscribingtoRedHatNetwork(RHEL)
PerformthefollowingtaskstosubscribetoandstartusingRHN:
1. Givethecommandup2dateregistertoopentheRHN
registrationwindow.RHELpromptsyoufortheroot
password.
2. ReadtheWelcomepageandclickForward.
3. TheRedHatLoginwindowopens.Choosewhetheryouwant
toCreateNewAccountorUseExistingAccount.Fillin
therequestedinformation.ClickNetworkConfigurationif
youneedtoenableanHTTPproxy.ClickReadourPrivacy
StatementtoreviewRedHat'sprivacypolicy.Click
Forward.
4. TheActivatewindowopens.Enterasubscriptionnumberor
choosetouseanexisting,activesubscription.Thewindow
allowsyoutoconfirmthatyouwanttoincludehardware
andpackageinformationintheprofileinformationthatthe
systemwillsendtoRHNattheendofthisprocess.Enter
thenameyouwouldlikeRHNtousewhenreferringtothe
localsystem.Youcanputanyinformationtohelpidentify
thesysteminthistextbox;usuallythesimplehostnameis
agoodchoice.WhenyouclickForward,theprogram
compilesalistofthehardwareandrpmpackagesinstalled
onthesystemandsendsthelocalsystem'sprofiletoRHN.
5. TheChannelswindowopens.Verifytheinformationinthis
window.ClickForwardtodisplayalistofpackagesonthe
localsystemthatneedtobeupdated.Youcanchooseto
updatethesystematthistimeorwaituntillater.Whenyou
finish,theregistrationwindowcloses.
Ifnecessary,entitlethesystem.TheerrorServicenot
enabledforserverprofile:"profilename"meansthatthe
systemisnotentitled.Ifyougetthismessage,goto
rhn.redhat.com,andloginwiththeusernameandpassword
yousetupintheRedHatLoginwindow(step3).Clickthe
Systemstabatthetopofthepage,andthenclicktheSystem
Entitlementsboxattheleft.Thesystemyoujustregistered
shouldbelisted.Clickthecheckboxadjacenttothesystemyou
wanttoentitleandthenclickeitherSettoUpdateEntitledor
SettoManagementEntitled.Followtheinstructionsonthe
pageifyouneedmoreentitlements.
Youcancheckforupdatesatanytime.Runup2date,orchoose
RHNAlertNotificationToolIconmenu:Checkforupdates
(page498)toseeiftheRHNserverdownloadsfilestoor
exchangesinformationwiththelocalsystem.Alternatively,give
thecommandup2datelisttoseewhetheranypackagesare
availableforthesystem,therebytestingtheconnectionwith
theRHNserver.
Youcanstarttheflowofupdateseitherfromthesystemor
fromtheWebsite.Fromthesystem,runup2date.FromtheWeb
site,login,clicktheSystemstab,clickthenameofthesystem
inthetable,clickupdatenowifapplicable,andclickApply
Errata.Ineithercase,thenexttimetherhnsddaemononthe
localsystemcontactstheRHNserver,thesystemwillreceive
updatespertheup2dateprofile(installedornot,leftonthe
systemornot,sourcecodeornot,andsoon).
rhnsd:RHNDaemon
TheRHNdaemon(rhnsd)isabackgroundservicethat
periodicallyqueriestheRHNservertodeterminewhetherany
newpackagesareavailabletobedownloaded.Thisdaemonis
oneofthekeystoRHNsecurity:Itinitiatescontactwiththe
RHNserversotheserverneverhastoinitiatecontactwiththe
localsystem.Referto"service:ConfiguresServicesI"onpage
406forinformationonhowtostart,stop,ordisplaythestatus
ofrhnsdimmediately;referto"system-config-services:Configures
ServicesII"onpage406orto"chkconfig:ConfiguresServices
III"onpage408forinformationonhowtostartorstoprhnsd
atspecifiedrunlevels.
wget:DownloadsFilesNoninteractively
Thewgetutilityisanoninteractive,commandlineutilitythatcan
retrievefilesfromtheWebusingHTTP,HTTPS,andFTP.
ThefollowingsimpleexampleuseswgettodownloadRedHat's
homepage,namedindex.html,toafilewiththesamename:
$wgethttp://www.redhat.com
--19:42:53--http://www.redhat.com/
=>'index.html'
Resolvingwww.redhat.com...209.132.177.50
Connectingtowww.redhat.com|209.132.177.50|:80...connected.
HTTPrequestsent,awaitingresponse...200OK
Length:12,544(12K)[text/html]
100%[==========================================================>]12,544--.--K/s
19:42:54(102.49KB/s)-'index.html'saved[12544/12544]
Usetheboptiontorunwgetinthebackgroundandtoredirect
itsstandarderrortoafilenamedwget-log:
$wget-bhttp://example.com/big_file.tar.gz
Continuinginbackground,pid10752.
Outputwillbewrittento'wget-log'.
Ifyoudownloadafilethatwouldoverwritealocalfile,wget
appendsaperiodfollowedbyanumbertothefilename.
Subsequentbackgrounddownloadsarethenloggedtowget-
log.1,wget-log.2,andsoon.
Thecoptioncontinuesaninterrupteddownload.Thenext
commandcontinuesthedownloadfromthepreviousexamplein
thebackground:
$wget-b-chttp://example.com/big_file.tar.gz
ChapterSummary
Asasystemadministrator,youneedtokeepapplicationsand
systemsoftwarecurrent.Ofthemanyreasonstokeepthe
softwareonasystemup-to-date,oneofthemostimportantis
systemsecurity.Thedevelopmentofrpmpackageshasmade
theprocessofaddingandremovingthesoftwarepackages
quiteeasy.
OnFedoraCoresystems,youcanuseyumtoinstalland
upgradesoftwarepackages.Theyumutilityisinstalledby
defaultandiseasytoconfigureanduse.
Inaddition,youcanusetherpmutilitytoinstall,uninstall,
upgrade,query,andverifyrpmpackages.Forpackages
distributedassourcecode,theGNUConfigureandBuildSystem
makesiteasytobuildexecutablefiles.
BitTorrentisahandytoolfordownloadinglargestaticdatafiles
suchastheFedorainstallationISOimages.BitTorrentcan
replaceprotocolssuchasanonymousFTP,whereclient
authenticationisnotrequired.
RedHatNetwork(RHN),aserviceprovidedbyRedHat,isan
Internet-basedsystemthatcankeepthesoftwareononeor
moreRedHatEnterpriseLinuxsystemsup-to-date.
Exercises
1. WhywouldyouuseHTTPorFTPinsteadofBitTorrentfordownloadinglargefiles?
2.
Whichcommandwouldyougivetoperformacompleteupgradeusing
a. up2date?
b. yum?
3. Whywouldyoubuildapackagefromitssourcecodewhena(binary)rpmfileis
available?
4. Suggesttwoadvantagesthatrpmfileshaveoversourcedistributions.
AdvancedExercises
5. Whenyoucompileapackageyourself,ratherthanfromanrpmfile,whichdirectory
hierarchyshouldyouputitin?
6. Whataresomestepsyoushouldtakebeforeperforminganupgradeonamission-
criticalserver?
7. WhenshouldyouuserpmiinsteadofrpmU?
14.PrintingwithCUPS
INTHISCHAPTER
JumpStartI:ConfiguringaLocalPrinterUsingsystem-config-
printer
505
JumpStartII:ConfiguringaRemotePrinterUsingCUPS 508
TraditionalUNIXPrinting 510
TheCUPSWebInterface 512
CUPSontheCommandLine 514
IntegrationwithWindows 520
Aprintingsystemhandlesthetasksinvolvedinfirstgettinga
printjobfromanapplication(orthecommandline)throughthe
appropriatefilters(page1032)andintoaqueueforasuitable
printerandthengettingitprinted.Whilehandlingajob,a
printingsystemcankeeptrackofbillinginformationsothatthe
properaccountscanbechargedforprinteruse.Whenaprinter
fails,theprintingsystemcanredirectjobstoother,similar
printers.
Introduction
LPDandLPR
Traditionally,UNIXhadtwoprintingsystems:theBSDLine
PrinterDaemon(LPD)andtheSystemVLinePrintersystem
(LPR).Linuxadoptedthosesystemsatfirst,andbothUNIXand
Linuxhaveseenmodificationstoandreplacementsforthese
systems.TodayCUPSisthedefaultprintingsystemunderRed
HatLinux.
CUPS
CUPS(CommonUNIXPrintingSystem)isacross-platformprint
serverbuiltaroundIPP(InternetPrintingProtocol),whichis
itselfbasedonHTTP.CUPSprovidesanumberofprinterdrivers
andcanprintseveraldifferenttypesoffiles,including
PostScript.BecauseitisbuiltonIPPandwrittentobeportable,
CUPSrunsundermanyoperatingsystems,includingLinuxand
Windows.OtherUNIXvariants,includingMacOSX,useCUPS,
andrecentversionsofWindowsincludetheabilitytoprintto
IPPprinters,makingCUPSanidealsolutionforprintingina
heterogeneousenvironment.CUPSprovidesSystemVandBSD
commandlineinterfacesand,inadditiontoIPP,supports
LPD/LPR,HTTP,SMB,andJetDirect(socket)protocols,among
others.
IPP
TheIPPproject(www.pwg.org/ipp)beganin1996,whenNovell
andseveralothercompaniesdecidedtodesignaprotocolfor
printingovertheInternet.TheIPPenablesusersto
Determinethecapabilitiesofaprinter.
Submitjobstoaprinter.
Determinethestatusofaprinter.
Determinethestatusofaprintjob.
Cancelaprintjob.
IPPisaclient/serverprotocolinwhichtheserversidecanbea
printserveroranetwork-capablestand-aloneprinter.
Printersandqueues
Onamoderncomputingsystem,whenyou"sendajobtothe
printer,"youactuallyaddthejobtothelistofjobswaitingtheir
turntobeprintedonaprinter.Thelistiscalledaprintqueueor
simplyaqueue.Thephraseconfiguring(orsettingup)aprinter
isoftenusedtomeanconfiguringa(print)queue.Thischapter
usesthesephrasesinterchangeably.
Prerequisites
Installthefollowingpackages:
cups
system-config-printer(optional)
kdebase(optional,provideskprinter)
RunchkconfigtocauseCUPS(thecupsddaemon)tostartwhen
thesystemgoesintomultiusermode:
#/sbin/chkconfigcupson
StartCUPS:
#/etc/rc.d/init.d/cupsstart
TousetheWebinterfacetoCUPS,youneedanXserveranda
Webbrowser.
MoreInformation
Local
CUPSDocumentationWiththeCUPSWebinterfaceup(page
512),pointalocalbrowserat
localhost:631/documentation.html.
Web
www.linuxprinting.orgInformationonprintersandprinting
underLinux;hostsasupportdatabasewithdetailsaboutmany
printers,includingnotesanddriverinformation;alsoforums,
articles,andaHOWTOdocumentonprinting.
CUPShomepagewww.cups.org
IPPinformationwww.pwg.org/ipp
HOWTO
SMBHOWTOhasasectiontitled"SharingaWindowsPrinter
withLinuxMachines."
Notes
SELinux
WhenSELinuxissettouseatargetedpolicy,CUPSisprotected
bySELinux.Youcandisablethisprotectionifnecessary.For
moreinformationreferto"SettingtheTargetedPolicywith
system-config-securitylevel"onpage402.
JumpStartI:ConfiguringaLocalPrinterUsing
system-config-printer
ThisJumpStartconfiguresaprinterthatisconnecteddirectlyto
thelocalsystem.Thefastestwaytoaddanewprinteristouse
system-config-printer.TodisplaythePrinterconfigurationwindow
(Figure14-1),entersystem-config-printeronacommand
line.FromKDEselectMainmenu:Administration Printing
orfromGNOMEselectSystem:Administration Printing.
Figure14-1.ThemainPrinterconfiguration
window
Browsedqueues
IfthewordsBrowsedqueuesappearinthePrinter
configurationwindow,clicktheadjacenttriangletodisplayalist
ofqueuesthatCUPShasfound.Iftheprinteryouwanttoaddis
listedhere,youaredone.Tomakeitthedefaultprinter,
highlightit,clickDefaultandthenApplyonthetoolbar,and
closethewindow.Iftheprinteryouwanttoaddisnotlisted,
continuewiththenextparagraph.
FromthePrinterconfigurationwindow(Figure14-1),clickNew
onthetoolbartoopentheAddanewprintqueuewizard.Click
ForwardtodisplaytheQueuenamewindow(Figure14-2).
Enteranameforandashortdescriptionoftheprinter.The
nameisashortidentifierthatstartswithaletteranddoesnot
containanySPACEs.Theoptionaldescriptioncanbeashort
sentence.ClickForward.
Figure14-2.TheQueuenamewindow
[Viewfullsizeimage]
Thenextwindow,Queuetype,asksyoutospecifytheprinter
connection(Figure14-3).Bydefault,theLocally-connected
queuetypeisselectedinthecomboboxatthetopofthe
window.
Figure14-3.TheQueuetypewindow
[Viewfullsizeimage]
MostprintersconnecttoaparallelorUSBport,althougholder
printersmayconnecttoaserialport.Thedefaultlistinthebox
inthemiddleofthewindowliststhesystem'sparallelports.
UnderLinux,aparallelportisidentifiedas/dev/lpn,wheren
isthenumberthatidentifiestheport.Thefirstparallelport
(LPT1underWindows)is/dev/lp0.Unlessthelocalsystem
hasseveralparallelports,theprinterisprobablyconnectedto
/dev/lp0.
USBdevicesappearinthe/dev/usbdirectory.USBprinters
appearasstandardparallelprinterswithintheusbdirectory
hierarchy.ThefirstUSBprinterportis/dev/usb/lp0,with
subsequentprintersappearingaslp1,lp2,andsoon,exactly
asparallelportsdo.Thefirstserialport(COM1underDOSor
Windows)is/dev/tty0.
Clicktohighlightthelinethatnamestheporttowhichthe
printeryouareinstallingisconnected.Ifthedeviceisnot
listed,clickCustomdeviceandenterthepathnameofthe
deviceas/dev/xxxwherexxxisthenameofthedevicein
the/devdirectory.ClickForward.
ThewizarddisplaysthePrintermodelwindow(Figure14-4).
Specifyingtheprintermodelisatwo-stepprocess:Firstclick
thebarthathasthewordsGeneric(clicktoselect
manufacturer)onit;thewizarddisplaysalongpop-upmenu
ofmanufacturers.Movethemousepointeroverthemenuuntil
themanufactureroftheprinterishighlighted;thenclick.The
wizardreplacesthewordsinthebarwiththenameofthe
manufactureranddisplaysthatmanufacturer'sknownprinter
modelsintheframebelowthebar.Scrollthroughthesemodels
andclicktheprinterthatisattachedtothesystem.ClickNotes
todisplaynotesontheselectedprinterfromtheLinuxPrinting
Database.
Figure14-4.ThePrintermodelwindow
[Viewfullsizeimage]
Iftheprinterisnotlisted,checkwhetheritcanemulateanother
printer(ifithasanemulationmode).Ifitcan,checkwhether
theprinteritcanemulateislistedandsetitupthatway.Ifall
elsefails,reselectGenericinthebarandchooseageneric
printerfromthelistinthebox.ChoosePostScriptPrinterif
yourprinterisPostScriptcapable.Ifthereisnomatch,select
TextOnlyPrinter;youwillnotbeabletoprintgraphics,but
youshouldbeabletoprinttext.Ifyouareusingawinprinter,
selectGDIPrinterfromthelistofgenericprinters.
ClickForwardtodisplaytheFinish,andcreatethenewprint
queuewindow.Thewizardhasnotsavedanyinformationupto
thispoint;clickCanceltoaborttheprocessorclickFinishto
createthenewprintqueue.
Nextthewizardasksifyouwanttoprintatestpage;dosoto
ensurethattheconfigurationwassuccessful.Printingthetest
pageautomaticallycommitstheconfigurationchanges.Ifyou
donotprintatestpage,clickApplyonthetoolbartocommit
thechanges.
Ifyouhavemorethanoneprintqueueandwanttosetupthe
newprintqueueasthedefault,highlighttheprintqueueand
clickDefaultonthetoolbar.
JumpStartII:ConfiguringaRemotePrinter
UsingCUPS
ThisJumpStartusestheWebinterfacetoCUPStoconfigure
either(1)aprinterthatisconnectedtoadifferentUNIX/Linux
systemthatprovidesIPPsupportoranLPD/LPRqueueor(2)a
printerthatisconnecteddirectlytothenetwork.
IftheprinteryouareconfiguringisonanolderLinuxsystemor
anotherUNIX-likeoperatingsystemthatdoesnotrunCUPS,
thesystemisprobablyrunningLPD/LPR.Newerversionsof
LinuxandUNIXvariantsthatsupportCUPS(includingMacOS
X)supportIPP.Mostdevicesthatconnectprintersdirectlytoa
networksupportLPR/LPDandmaysupportIPP.
Printersconnecteddirectlytoanetworkarefunctionally
equivalenttoprintersconnectedtoasystemrunningaprint
server:Theylistenonthesameportsassystemsrunningprint
serversandqueuejobs.
ConnecttotheWebinterfacetoCUPSbypointingaWeb
browseratlocalhost:631onthesystemyouareconfiguring
theprinteron(Figure14-5).
Figure14-5.CUPSWebinterface:mainpage
[Viewfullsizeimage]
ClickPrintersonthenavigationbaratthetopofthepage.If
theprinteryouwanttoaddisdisplayedinthewindow,youare
done.Youmayneedtousesystem-config-printerasdescribedin
JumpStartI(page505)toestablishitasthedefaultprinter.
Tip:Theprinteryouwanttoaddmay
alreadybesetup
FollowJumpStartI(page505)throughthe
paragraphlabeled"Browsedqueues"(page506)to
seewhetherthelocalsystemalreadyrecognizesthe
printeryouwanttoadd.Alternativelyyoucan
continuewiththissectionaprinterthatisrecognized
willappearwhenyouclickPrintersonthe
navigationbarasdescribedshortly.
Iftheprinteryouwanttoaddisnotdisplayed,clickAdd
PrintertodisplaytheAddNewPrinterpage(Figure14-6).If
youarepromptedforausernameandpassword,enterroot
andtherootpasswordonthelocalsystem.TheNamefield
holdsthenameoftheprinter;itmuststartwithaletterandnot
containanySPACEs.FillintheLocationandDescriptionfields
withtextthatwillhelpusersidentifytheprinter;thenclick
Continue.
Figure14-6.CUPSWebinterface:AddNew
Printerpage
[Viewfullsizeimage]
Thenextpageasksyoutoselectthedevicethattheprinteris
attachedto.ClickthedownarrowattherightoftheDevice
comboboxtodisplaythelistofprinterdevices.SelectInternet
PrintingProtocol(ipp)orLPD/LPRHostorPrinter,
dependingonwhattheprinterisattachedto.Select
AppSocket/HPJetDirectforanHPJetDirect-compatible
networkprinter.ClickContinue.
Tip:ClickAdministrationtomodifya
printer
Youmaynotbeabletomodifyaprinterwhenyou
clickPrintersfromthenavigationbarbecauseyou
maynotberunningwithrootprivileges.Whenyou
clickAdministrationonthenavigationbar,the
CUPSinterfacepromptsforausernameand
password.Enterrootandtherootpasswordtogive
yourselfrootprivileges.Withtheseprivilegesyou
canmodifylocalprinters,althoughyoumaynotbe
abletomodifyremoteprinters.
ThenextpageasksfortheURI(locationonthenetwork)ofthe
printer.ForanLPDprinter,usetheform
lpd://hostname/queue;foranIPPprinter,useipp://host-
name/ipp;foranHPJetDirect-compatiblenetworkprinter,use
socket://hostname.Replacehostnamewiththenameofthe
hostthattheprinterisattachedtoorthenameoftheprinter
foranetworkprinter.YoucanspecifyanIPaddressinsteadof
hostname.Replacequeuewiththenameofthequeueonthe
remotesystem.EntertheURIoftheprinterandclick
Continue.
NextisthefirstoftwoModel/Driverpages(Figure14-7).
HighlightthebrandofprinterandclickContinue.Iftheprinter
isPostScriptcapablebutisnotlisted,selectPostscript.Ifthe
printerisnotPostScriptcapableandisnotlisted,checkwhether
theprintersupportsPCL;ifitdoes,selectanother,similarPCL
printer.Ifallelsefails,determinewhichlistedprinterismost
similartotheoneyouareconfiguringandspecifythatprinter.
Youcanalsotryconfiguringtheprinterusingsystem-config-printer
(page505),whichoffersadifferentchoiceofmodels.
Figure14-7.CUPSWebinterface:Model/Driver
page
[Viewfullsizeimage]
Thefinalstepinthisprocessistocompletethesecond
Model/Driverpage.Selectthemodeloftheprinterfromthe
scrollablelistandclickContinue.Iftheprinterwasconfigured
properly,CUPSdisplaysamessagesayingthattheprinterwas
addedsuccessfully.Clickthenameoftheprinteronthispageor
clickPrintersatthetopofthepagetodisplaythePrinterpage
(Figure14-8).Onceyouhavesetuptheprinter,itisagood
ideatoprintatestpage.
Figure14-8.CUPSWebinterface:Printerpage
[Viewfullsizeimage]
TraditionalUNIXPrinting
BeforetheadventofGUIsandWYSIWYG(page1064)word
processors,UNIXuserswouldcreatedocumentsusinganeditor
suchasviandatypesettingmarkuplanguagesuchasTeXor
nroff/troff,converttheresultingfilestoPostScriptusingan
interpreter,andsendthePostScriptfilestotheprinterusinglp
(SystemV)orlpr(BSD).RedHatLinuximplementsbothBSD
andSystemVcommandlineprintingutilitiesforcompatibility:
Theseutilitiesarenowwrappersaroundtheequivalent
functionalityinCUPSratherthancorecomponentsofthe
printingsystem.Thecorrespondingutilitiesarefunctionally
equivalent;usewhicheveryouprefer(Table14-1).
Table14-1.BSDandSystemVcommandlineutilities
BSD/SysV Purpose
lpr/lp Sendsjob(s)totheprinter.
lpq/lpstat Displaysthestatusoftheprintqueue.
lprm/cancel Removesjob(s)fromtheprintqueue.
Fromthecommandline,youcanprintatextorPostScriptfile
usinglp:
$lpmemo.txt
requestidisMainPrinter-25(1file(s))
Theprecedingcommandaddsmemo.txttotheprintqueueof
thedefaultprinterasjob25.Whenthisprinterisavailable,it
printsthefile.
Youcanspecifyaprinterusingthedoption:
$lp-dcolorprintergraph.ps
requestidisColorPrinter-26(1file(s))
ThePoptiontolprisequivalenttothedoptiontolp.
Withoutanargument,lp(andlpr)sendsitsstandardinputto
theprinter:
$catmemo2.txt|lp
requestidisMainPrinter-27(1file(s))
Thelpqandlpstatcommandsdisplayinformationabouttheprint
queue:
$lpstat
MainPrinter-25zach13312SunFeb2618:28:382006
ColorPrinter-26zach75776SunFeb2618:28:482006
MainPrinter-27zach8192SunFeb2618:28:572006
Usecancelorlprmtoremovejobsfromtheprintqueue.Onlythe
ownerofaprintjoborrootcanremoveajob.
$cancel27
$lpstat
MainPrinter-25zach13312SunFeb2618:28:382006
ColorPrinter-26zach75776SunFeb2618:28:482006
Workingasroot,givethecommandcancelaorlprmto
removealljobsfromtheprintqueues.
ConfiguringPrintersUsingCUPS
YoucanusetheWebinterfaceorthecommandlineinterfaceto
CUPStomanageprintersandqueues.
TheCUPSWebInterface
CUPS,whichwasdesignedforInternetprinting,providesaWeb
interfacetoconfigureprinters.Toconnecttothisinterface,
pointaWebbrowserrunningonthelocalsystemat
localhost:631.
SettingUpandModifyingaPrinter
"JumpStartII:ConfiguringaRemotePrinterUsingCUPS"(page
508)discusseshowtosetuparemoteprinterusingCUPS.The
procedureforsettingupalocalprinterissimilar.Themajor
differenceisthesecondstep:specifyingthedevicethatthe
printerisconnectedto.
AlocalprinterisgenerallyconnectedtoUSBPort#1or
ParallelPort#1.Afteryouspecifyoneofthesedevices,the
Webinterfacedisplaysthepageonwhichyouspecifythebrand
oftheprinter;youdonotspecifyaURIforalocalprinter.Ifyou
aresettingupaserialprinter,youwillneedtospecify
characteristicsoftheprinter,includingitsbaudrate.Afterthese
steps,theprocedureisthesameasexplainedinJumpStartII.
Tomodifyaprinter,firstclickPrintersfromtheWebinterface
navigationbarandthenclicktheModifyPrinterbutton
adjacenttotheprinteryouwanttomodify.TheWebinterface
takesyouthroughthesamestepsaswhenyouaresettingupa
newprinter.IftheWebinterfacedoesnotallowyoutomodifya
printer,clickAdministrationinsteadofPrintersonthe
navigationbar.Onceyousupplytheusernamerootandthe
rootpassword,clickManagePrintersandcontinuewiththe
nextparagraph.
ClicktheStopPrinterbuttontopausetheprinter.Clickthe
RejectJobsbuttontopreventjobsfrombeingaddedtothe
printer'squeue.
Jobs
ClickJobsonthenavigationbartodisplaytheJobspage
(Figure14-9),whichlistsjobsintheprintqueues.Fromthis
pageyoucanhold(pause),release(unpause),andcancelprint
jobs.ClickShowCompleteJobstodisplayalistofrecently
completedjobs.Insomecases,youcanrestartcompletedjobs
fromthispage.
Figure14-9.CUPSWebinterface:Jobspage
[Viewfullsizeimage]
Classes
CUPSallowsyoutoputsimilarprintersintoagroupcalleda
class.Aprintercanbelongtomorethanoneclass.Aprintjob
senttoaclasswillbeprintedonthefirstavailableprinterinthe
class.Forexample,youmaybeabletodivideyourprintjobs
intoblack-and-whitejobsandcolorjobs.Ifmorethanone
printercanfulfilleachoftheseroles,youcanallowusersto
selectaprintermanually,oryoucandefinetwoprinterclasses
(black-and-whiteandcolor)andhaveuserssendtheirjobstoa
certainclassofprinters.
Tip:Planforthefuture
Ifyouexpecttoaddprinterstothenetwork,you
maywanttoconfigureclassescontainingthe
existingprinterswhenyousetupthenetwork.You
canthenaddprinterslaterwithouthavingtochange
printerconfigurationsonclientsystems.
Addingprinterstoaclassisatwo-stepprocess.First,youneed
todefineaclass.Second,youneedtoaddexistingprintersto
theclass.Todefineaclass,firstclickClassesonthenavigation
baratthetopofthepageandthenclickAddClass.Toclients,
aclassofprintersappearsasasingleprinter;foreachclass,
youneedtospecifyaname,location,anddescription.Onceyou
havedefinedaclass,youcanaddprinterstotheclass.Repeat
thisprocessforeachclassyouwanttodefine.
CUPSontheCommandLine
InadditiontousingtheWebinterface,youcancontrolCUPS
andmanageprintqueuesfromthecommandline.Thissection
detailsutilitiesthatenableyoutomanageprintersandprint
queuesandestablishprintingquotas.
lpinfo:DisplaysAvailableDrivers
PPDfiles
Thelpinfoutilityprovidesinformationabouttheprinterdrivers
andinterfacesavailabletoCUPS.Themoptiondisplaysthelist
ofavailablePostScriptPrinterDefinition(PPD)files/drivers.
$/usr/sbin/lpinfo-m|head
rawRawQueue
foomatic-db-ppds/Brother/BR7025_2_GPL.ppd.gzBrotherDCP-7025BR-Script3
foomatic-db-ppds/Brother/BR8020_2_GPL.ppd.gzBrotherDCP-8020BR-Script3
foomatic-db-ppds/Brother/BR8025_2_GPL.ppd.gzBrotherDCP-8025DBR-Script3
foomatic-db-ppds/Brother/BR8040_2_GPL.ppd.gzBrotherDCP-8040BR-Script3
foomatic-db-ppds/Brother/BR8045_2_GPL.ppd.gzBrotherDCP-8045DBR-Script3
foomatic-db-ppds/Brother/BRHL14_1_GPL.ppd.gzBrotherHL-1450BR-Script2
foomatic-db-ppds/Brother/BRHL14_2_GPL.ppd.gzBrotherHL-1470NBR-Script2
foomatic-db-ppds/Brother/BRHL16_2_GPL.ppd.gzBrotherHL-1650/70NBR-Script3
foomatic-db-ppds/Brother/BRHL18_2_GPL.ppd.gzBrotherHL-1850/70NBR-Script3
CUPSusesURIs(page1061)toidentifyprinterportsbytype
andlocation,justasaWebbrowseridentifiesdocumentsby
protocolandlocation.AparallelporthasaURIwiththeformat
parallel:/dev/lp0;aremoteLPDprinterusestheformat
lpd://192.168.0.101.Withthevoption,lpinfoprovidesalist
ofavailableconnections:
$/usr/sbin/lpinfo-v
networksocket
networkbeh
directhal
directhp:/no_device_found
networkhttp
networkipp
networklpd
directparallel:/dev/lp0
directscsi
serialserial:/dev/ttyS0?baud=115200
...
directusb:/dev/usb/lp0
directusb:/dev/usb/lp1
...
networksmb
Thevoptiontolpinfodoesnotdisplayeverypossiblenetwork
addressforthesocket,HTTP,IPP,LPD,andSMBprotocols
becausetherearemorethan4billionoftheseaddressesinthe
IPv4addressspace.
lpadmin:ConfiguresPrinters
Thelpadminutilitycanaddandremoveprintersfromthe
system,modifyprinterconfigurations,andmanageprinter
classes.Ithasthreemajoroptions:d(setthedefaultprinter),
x(removeaprinter),andp(addormodifyaprinter).Thefirst
twooptionsaresimple;examplesareshownafterthenext
section.Eachoftheoptionstakesanargumentthatisthename
ofaprinter.Thenameoftheprintermuststartwithaletterand
cannotcontainSPACEs.
AddingorModifyingaPrinter
Youaddaprinterormodifyanexistingprinterbygivinga
commandinthefollowingformat:
#/usr/sbin/lpadminpprinteroptions
Hereprinteristhenameoftheprinterandoptionsisa
combinationofoptionsfromthefollowinglist:
cclass
Addstheprintertotheclassclass,creatingtheclassif
necessary.
Dinfo
Theinfoisastringthatdescribestheprinterforusers.This
stringhasnomeaningtothesystem.Encloseinfowithin
quotationmarksifitcontainsSPACEs.
E
EnablestheprinterandinstructsCUPStoacceptjobsintoits
printqueue.
Lloc
Thelocisastringthatphysicallylocatestheprinterforusers
(office,building,floor,andsoon).Thisstringhasnomeaningto
thesystem.Encloselocwithinquotationmarksifitcontains
SPACEs.
mmodel
ThemodelisthenameofthePPDfile(page514)that
describestheprinter.Uselpinfomtodisplayalistofallofthe
installedPPDfiles.Ifyouhaveamanufacturer-providedPPD
file,copyitto/usr/share/cups/model.UsethePoptionto
specifythepathnameofthefile.Specifyingm
postscript.ppd.gz,forexample,isthesameasspecifyingP
/usr/share/cups/model/postscript.ppd.gz.
Pfile
ThefileistheabsolutepathnameofthePPDfile(page514)
thatholdstheprinterdriver.Seemforanalternativewayto
specifyaPPDfile.
rclass
Removestheprinterfromtheclassclass.Thisoptionremoves
theclassif,afterremovingtheprinter,theclasswouldbeleft
empty.
vURI
TheURIisthedevicetowhichtheprinterisattached.Use
lpinfovtolistpossibledevices.
ExamplelpadminCommands
Ataminimum,youneedtoprovideadeviceandamodelwhen
youaddaprintertothesystem.Thefollowingcommandadds
anEpsonStylusColorprintertothesystemandenablesitfor
use.Theprinterisconnectedlocallytothefirstparallelportand
isnamedColorPrinter.
#lpadmin-pColorPrinter-E-vparallel:/dev/lp0-mstcolor.ppd.gz
Theprinterinformationgeneratedbytheprecedingcommandis
storedinthe/etc/cups/printers.conffile.
#cat/etc/cups/printers.conf
#PrinterconfigurationfileforCUPSv1.1.23
#WrittenbycupsdonFri27Jan200605:00:32PMPST
<PrinterColorPrinter>
InfoColorPrinter
DeviceURIparallel:/dev/lp0
StateIdle
AcceptingYes
JobSheetsnonenone
QuotaPeriod0
PageLimit0
KLimit0
AutodetectedNo
</Printer>
Theprinterdriverinformationfromthe
/usr/share/cups/model/stcolor.ppd.gzfileis
uncompressedandcopiedto/etc/cups/ppd.Theresultingfile
isgiventheprinter'sname:
/etc/cups/ppd/ColorPrinter.ppd.
Youcanmodifyaprinterconfigurationwithlpadminusingthe
sameoptionsthatyouusedtoaddit.Whenyouspecifythe
nameofanexistingprinter,lpadminmodifiestheprinterrather
thancreatinganewone.
ThenextcommandconfiguresanHPLaserJet-compatible
printerwithaJetDirectinterfacethatisconnecteddirectlyto
theLANat192.168.1.103andnamesthisprinterHPLJ.
SpecifyingsocketintheprotocolpartoftheURIinstructsCUPS
tousetheJetDirectprotocol,aproprietaryprotocoldeveloped
byHPforprintersconnecteddirectlytoanetwork.
#lpadmin-pHPLJ-E-vsocket://192.168.1.103-mlaserjet.ppd.gz
Thelpstatutilitywiththedoptiondisplaysthenameofthe
defaultprinter:
$lpstat-d
systemdefaultdestination:MainPrinter
CUPSautomaticallymakesthefirstprinteryoudefinedthe
defaultprinter.ThefollowingcommandmakesHPLJthedefault
printer:
#lpadmin-dHPLJ
Thefollowingcommandremovestheconfigurationforthe
ColorPrinterprinter:
#lpadmin-xColorPrinter
PrintingQuotas
CUPSprovidesrudimentaryprintingquotas.Youcandefinetwo
formsofquotas:pagecountandfilesize.Filesizequotasare
almostmeaninglessbecauseasmallPostScriptfilecantakea
longtimetointerpretandcanrequirealotmoreinktoprint
thanalargeone.Pagequotasaremoreuseful,althoughtheir
implementationisflawed.Todeterminethenumberofpagesin
adocument,CUPSexaminesthePostScriptinput.Ifajobis
submittedintheprinter'snativelanguage,suchasPCL,CUPS
bypassesthisaccountingmechanism.Also,ifmpageisusedto
createaPostScriptfilewithmultiplepagesprintedoneach
sheet,CUPScountseachpageintheoriginaldocument,rather
thaneachsheetofpaperitprintson.
Usethejob-quota-periodandeitherjob-page-limitorjob-
k-limittoestablishaquotaforeachuseronagivenprinter.
Thejob-quota-periodoptionspecifiesthenumberofseconds
thatthequotaremainsvalid.Thefollowingcommand
establishesaquotaof20pagesperdayperuserfortheprinter
namedHPLJ:
$lpadmin-pHPLJ-ojob-quota-period=86400-ojob-page-limit=20
Thejob-k-limitoptionworkssimilarlybutdefinesafilesize
limitinkilobytes.Thelimitisthetotalnumberofkilobytesthat
eachusercanprintoverthequotaperiod.Onceauserhas
exceededherquota,shewillnotbeallowedtoprintuntilthe
nextquotaperiod.
ManagingPrintQueues
Whenaprinterisoperatingnormally,itacceptsjobsintoits
printqueueandprintsthemintheordertheyarereceived.Two
factorsdeterminehowaprinterhandlesajob:iftheprinteris
acceptingjobsandifitisenabled.Table14-2showswhat
happensineachofthefourcombinationsofthetwofactors.
Table14-2.Printerstatus
Enabled Disabled
Accepting
Jobs
Acceptsnewjobsintothe
queue.
Printsjobsfromthequeue.
Acceptsnewjobsintothe
queue.
Doesnotprintjobsfrom
thequeueuntiltheprinter
isenabled.
Rejecting
Jobs
Rejectsnewjobs.
Printsjobsfromthequeue.
Rejectsnewjobs.
Doesnotprintjobsfrom
thequeueuntiltheprinter
isenabled.
Theutilitiesthatchangethesefactorsaredisable,enable,reject,
andaccept.Eachutilitytakesthenameofaprinterasan
argument.Thefollowingcommandsfirstdisableandthen
enabletheprinternamedHPLJ:
#/usr/bin/disableHPLJ
#/usr/bin/enableHPLJ
ThenextcommandscauseHPLJtorejectandthenacceptjobs:
#/usr/sbin/rejectHPLJ
#/usr/sbin/acceptHPLJ
Theenableanddisableutilitiesarelocatedin/usr/bin,while
rejectandacceptarelocatedin/usr/sbin.Dependingonhowthe
PATHenvironmentvariable(page292)isset,youmayneedto
specifyabsolutepathnamesfordisable,reject,andaccept.Because
enableisabashbuiltin(page225),youalwaysneedtospecify
theabsolutepathnameofthisutility.Youmaywanttocreate
aliases(page318)forthesecommandstomakethemeasierto
use.
SharingCUPSPrinters
IPPisdesignedforremoteprinting.Bydefault,CUPSbindsto
localhostandacceptsconnectionsfromthelocalsystemonly.
ToallowothersystemstoconnecttoCUPSonthelocalsystem,
youmustinstructCUPStobindtoanIPaddressthattheother
computerscanreach.TheListendirectiveintheCUPS
configurationfile,/etc/cups/cupsd.conf,specifieswhichIP
addressCUPSbindstoandacceptsrequestson.TheListen
directivehasthefollowingformat:
ListenIP:port
whereIPistheIPaddressthatCUPSacceptsconnectionson
andportistheportnumberthatCUPSlistensonfor
connectionsonIP.CUPStypicallyusesport631.Forexample,
thefollowingdirectivecausesCUPStolistenonIPaddress
192.168.0.10,port631:
Listen192.168.0.10:631
Afteryouchangecupsd.conf,youneedtorestarttheCUPS
daemon:
#/sbin/servicecupsrestart
Stoppingcups:[OK]
Startingcups:[OK]
OnceyourestarttheCUPSdaemon,remotesystemscanprint
onthelocalsystem'sprintersusingtheIPaddressandport
numberspecifiedwiththeListendirective.Makesurethe
system'sfirewall(page768)allowsLANuserstoconnecttoport
631onthelocalsystemanddoesnotallowsystemsoutsidethe
LANtoconnecttothisport.Youmayalsoneedtomodifythe
SELinuxpolicy(page402)dependingonthesystemsetup.
Alternatively,youcanuseCUPS'saccesscontrollisttopermit
onlyselectedmachinestoconnecttolocalprinters.Anaccess
controllistisdefinedinsidea<Location>container.The
followingexampleallowsonlythesystematIP192.168.1.101
andthelocalsystemtoprinttothespecifiedprinter:
<Location/printers>
OrderDeny,Allow
Allowfrom192.168.1.101
Allowfrom@LOCAL
</Location>
The/printersindicatesthatthiscontainerreferstoalllocal
printers.Alternatively,youcancontrolaccessonaper-printer
basisbyspecifying/printers/name,wherenameisthe
printername,orbyspecifying/printers/path.ppd,where
path.ppdisthefullpathnameofthePPDfile(page514)used
bytheprinter.
TheOrderDeny,Allowlinedeniesprintrequestsbydefault
andallowsrequestsonlyfromspecifiedaddresses.Specifying
OrderAllow,Denyallowsprintrequestsbydefaultanddenies
requestsfromspecifiedaddresses.
AllowfromspecifiestheIPaddressesthatCUPSaccepts
connectionsfrom.UseDenyfromwithOrderAllow,Denyto
specifyIPaddressesthatCUPSwillnotacceptconnections
from.
The@LOCALmacrospecifiesthelocalsystem:Itacceptjobs
fromanyaddressthatresolvestothelocalsystem.Specifying
127.0.0.1inplaceof@LOCALwouldworkaslongasno
applicationtriedtoprinttotheprintserverusingitsexternalIP
address.Donotusethemachine'sexternalIPaddress.Most
processesusetheloop-backdevice(127.0.0.1)toconnectto
theprinter,andtheloopbackdevicedoesnotallowconnections
toanyIPotherthanitself.Youcanalsousedomainnames,
includingwildcards,andIPrangeswitheitherwildcardsor
netmasksinAllowfromandDenyfromdirectives.
TheKDEPrintingManager
KDEincludesaprintingabstractionlayer(kprinter)that
providestheprintdialogboxforKDEapplicationsandautility
formanagingprinters(Figure14-10).TodisplaythePrinting
Managerwindow,enterkcmshellprintmgronacommand
line.FromKDEselectMainmenu:ControlCenter
Peripherals Printers.Youcanusetherelatedkprinterutility
toprintfiles.
Figure14-10.TheKDEPrintingManager
[Viewfullsizeimage]
Thekprinterabstractionlayerisnotastand-aloneprogram
anddoesnotreplaceCUPS.Rather,kprinterisaninterface
betweenanapplicationorausersubmittingaprintjobandthe
printingsystem.KDE'sPrintingManagerprovidesmuchofthe
samefunctionalityasCUPSandcanuseCUPSasaprinting
mechanism.Withproperpermissions,thePrintingManager
performsthefollowingtasks:
StartsprintjobsYoucanstartaprintjobwiththePrinting
Manager,aswellasfromacommandlineorwithinan
application.
ControlsprintjobsThePrintingManagercandisplay
informationoneachofyourprintjobs.Fromthese
windows,youcancancelprintjobs(evenwhentheyhave
startedprinting),holdandreleaseprintjobs,andmove
printjobstodifferentqueues(aslongastheyhavenot
startedprinting).Youcanalsosendaprintjobasafaxor
saveitasaPDForPostScriptfile.
WorkswithprintersYoucanadd,remove,andmodify
printersandtheirproperties.
WorkswithmultipleprintingsystemsThePrinting
ManagerworkswithCUPS,LPRng,RLPR,PDQ,andother
printingsystems.
WorkswithfiltersThePrintingManagerallowsyouto
importexistingprintingfilters(page1032)ortoinstallnew
ones.
RefertotheKDEPrintHandbook(clickHelpfromthekprinter
window)formoreinformation.
IntegrationwithWindows
ThissectionexplainshowtouseLinuxprintersfromWindows
computersandhowtouseWindowsprintersfromLinux
systems.
PrintingfromWindows
ThissectionassumesthatSamba(page695)isinstalledand
workingontheLinuxsystemthatcontrolstheprinteryouwant
tousefromWindows.Sambamustbesetupsothatthe
WindowsuserwhowillbeprintingismappedtoaLinuxuser
(includingmappingtheWindowsguestusertotheLinuxuser
nobody).MakesurethattheseusershaveSambapasswords.
Referto"SambaUsers,UserMaps,andPasswords"onpage
698.
WindowssupportsprintersharingviaSMB,allowingaprinterto
besharedtransparentlybetweenWindowssystemsusingthe
samemechanismasfilesharing.SambaallowsWindowsusers
touseprintersconnectedtoLinuxsystemsjustastheywould
useanyothersharedprinters.BecauseallLinuxprinters
traditionallyappeartobePostScriptprinters,theLinuxprint
serverappearstoshareaPostScriptprinter.Windowsdoesnot
includeagenericPostScriptprinterdriver.Instead,Windows
usersmustselectaprinterdriverforaPostScriptprinter.The
AppleColorLaserWriterdriverisagoodchoice.
WhenyouuserpmtoinstallSamba,itcreatesadirectory
named/var/spool/sambathatisownedbyrootandthat
anyonecanreadfromandwriteto.Thestickybit(page1057)
issetforthisdirectory,allowingaWindowsuserwhostartsa
printjobasaLinuxusertobeabletodeletethatjob,but
denyinguserstheabilitytodeleteprintjobsofotherusers.
Makesurethisdirectoryisinplaceandhastheproper
ownershipandpermissions:
$ls-ld/var/spool/samba
drwxrwxrwt2rootroot4096Feb2412:29/var/spool/samba
Putthefollowingtwolinesinthe[global]sectionofthe
/etc/samba/smb.conffile:
[global]
...
printing=cups
printcapname=cups
Theprinter'sshareislistedinthe[printers]sectionin
smb.conf.Inthefollowingexample,thepathisthepath
Sambausesasaspooldirectoryandisnotanormalshare
path.Thesettingsallowanyone,includingguest,tousethe
printer.SettinguseclientdrivertoyescausesWindows
systemstousetheirowndrivers.Notsettingthisoption,or
settingittono,cancauseprintingfromWindowsnottowork.
Makesurethe[printers]sectioninsmb.confhasthe
followingentries:
[printers]
comment=AllPrinters
path=/var/spool/samba
printeradmin=root
guestok=yes
printable=yes
useclientdriver=yes
browseable=no
Ideallyeachuserwhoplanstoprintshouldhaveanaccount.
Whenmultipleuserssharethesameaccount(forexample,the
nobodyaccount),theseuserscandeleteoneanother'sprint
jobs.
ModernversionsofWindows(2000andlater)supportIPPand,
asaresult,cancommunicatedirectlywithCUPS.IPPiseasier
tomanageandcanbemademoresecurethanusingSambato
printfromWindows.Tousethisfeature,youmusthaveCUPS
configuredontheLinuxprintservertoallowremoteIPP
printing;youalsoneedtocreateanewprinterontheWindows
systemthatpointstotheIPaddressoftheLinuxprintserver.
ThedetailsinvolvedinconfiguringaWindowsmachineare
beyondthescopeofthisbook.Youcanusetestparm(page714)
andtestprnstocheckthesyntaxoftheSambasetup.
PrintingtoWindows
CUPSviewsaprinteronaWindowsmachineexactlythesame
wayitviewsanyotherprinter.TheonlydifferenceistheURI
youneedtospecifywhenconnectingit.Toconfigureaprinter
connectedtoaWindowsmachine,gotothePrinterspageinthe
CUPSWebinterfaceandselectAddPrinter,asyouwouldfora
localprinter.
Whenyouareaskedtoselectthedevice,chooseWindows
PrinterviaSAMBA.EntertheURIoftheprinterinthe
followingformat:smb://windows_system/printer_name.
Onceyouhaveaddedtheprinter,youcanuseitasyouwould
anyotherprinter.
ChapterSummary
AprintingsystemsuchasCUPSsetsupprinters.Italsomoves
printjobsfromanapplicationorthecommandlinethroughthe
appropriatefiltersandintoaqueueforasuitableprinterand
thenprintsthosejobs.
CUPSisacross-platformprintserverbuiltaroundtheIPP
printingprotocol.CUPShandlessettingupandsendingjobs
throughprintqueues.TheeasiestwaytoworkwithCUPSisvia
theWebinterface,whichyoucanaccessbypointingaWeb
browseratlocalhost:631onthesystemtheprinteris
connectedto.FromtheWebinterface,youcanconfigureprint
queuesandmodifyprintjobsinthequeues.
YoucanusethetraditionalUNIXcommandsfromacommand
linetosendjobstoaprinter(lpr/lp),displayaprintqueue
(lpq/lpstat),andremovejobsfromaprintqueue(lprm/cancel).In
addition,CUPSprovidesthelpinfoandlpadminutilitiesto
configureprintersfromthecommandline.
SambaenablesyoutoprintonaLinuxprinterfromaWindows
system,andviceversa.
Exercises
1. Whichcommandscanyouusefromacommandlinetosendafiletothedefault
printer?
2. Whichcommandwouldyougivetocancelallprintjobsonthesystem?
3. Whichcommandslistyouroutstandingprintjobs?
4. WhatisthepurposeofsharingaLinuxprinterusingSamba?
5. NamethreeprintingprotocolsthatCUPSsupports.WhichistheCUPSnative
protocol?
AdvancedExercises
6. WhichcommandliststheinstalledprinterdriversavailabletoCUPS?
7. Howwouldyousendatextfiletoaprinterconnectedtothefirstparallelport
withoutusingaprintqueue?Whyisdoingthisnotagoodidea?
8.
AssumeyouhaveaUSBprinterwithamanufacturer-suppliedPostScriptprinter
definitionfilenamednewprinter.ppd.Whichcommandwouldyouusetoaddthis
printertothesystemonthefirstUSBportwiththenameUSBPrinter?
9. Howwouldyoudefineaquotathatwouldalloweachusertoprintupto50pages
perweektotheprinternamedLaserJet?
10.
Defineasetofaccesscontrolrulesfora<Location>containerinside
/etc/cups/cupsd.confthatwouldallowanyonetoprinttoallprintersaslongas
theywereeitheronthelocalmachineorinthemydomain.comdomain.
15.RebuildingtheLinuxKernel
INTHISCHAPTER
LocatingtheSourceCode 526
InstallingtheSourceCode 527
ConfiguringandCompilingtheLinuxKernel 529
InstallingtheKernelandAssociatedFiles 532
BootLoader 533
dmesg:DisplaysKernelMessages 535
OnceyouhaveinstalledRedHatEnterpriseLinuxorFedora
Core,youmaywanttoreconfigureandrebuildtheLinuxkernel.
RedHatLinuxcomeswithaprebuiltkernelthatsimplifiesthe
installationprocess.Thiskernelmaynotbeproperlyconfigured
forallofyoursystem'sfeatures,however.Byreconfiguringand
rebuildingthekernel,youcancreateonethatiscustomizedfor
yoursystemandyouruniqueneeds.
BecauserecentreleasesoftheLinuxkernelaremodular,youdo
notusuallyneedtorebuildthekernel.Instead,youcan
dynamicallychangemanythingsthatusedtorequirerebuilding
thekernel.Twowaystomakethesechangesarebyusingboot
optionsorbymodifying/etc/sysctl.conf,whichisusedby
sysctlwhenthesystemisbooted.
Youcanalsoappendastringtothekernellinein
/boot/grub/grub.confortoitssymboliclink,
/etc/grub.conf.Forexample,norelocatepreventsthe
substitutionofCPU-specificoptimizationsandacpi=off
preventsacpid(theadvancedconfigurationandpower
interfacedaemon)fromstarting.
Tip:Maybeyoujustneedtoinstallanew
Linuxkernelbinary
Referto"InstallingaLinuxKernelBinary"onpage
490whenyouwanttoinstallaLinuxkernelbinary
thatyoudonotneedtoconfigureorbuild.
sysctl
Thesysctlutilitymodifieskernelparameterswhilethesystemis
running.Thisutilitytakesadvantageofthefacilitiesof
/proc/sys,whichdefinestheparametersthatsysctlcanmodify.
Thecommandsysctladisplaysacompletelistofsysctl
parameters.Anexampleofdisplayingandchangingthe
domainnamekernelparameterfollows.Thequotationmarks
arenotrequiredinthisexample,butyoumustquoteany
charactersthatwouldotherwisebeinterpretedbytheshell.
#/sbin/sysctlkernel.domainname
kernel.domainname=tcorp.com
#/sbin/sysctl-wkernel.domainname="testing.com"
kernel.domainname=testing.com
Caution:HavethefirstinstallationCDor
theinstallationDVDhandywhenyou
rebuildthekernel
WhenyourebuildtheLinuxkerneltoinstallanew
versionortochangetheconfigurationoftheexisting
version,makesurethatyouhavethefirst
installationCDortheinstallationDVDhandy.You
canalsousetherescueCD;seepage40.These
disksallowyoutorebootthesystem,evenwhenyou
havedestroyedthesystemsoftwarecompletely.
HavingthisCDorDVDcanmakethedifference
betweenmomentarypanicandafull-scalenervous
breakdown.Referto"RescueMode"onpage397for
instructionsonbringingthesystemupinrescue
mode.
PreparingtheSourceCode
Beforeyoucanstartrebuildingthekernel,youmustlocate,
install,andcleanthesourcecode.Ifyouwanttousecodethat
hasnotbeencustomized(patched)byRedHat,visitkernel.org.
LocatingtheSourceCode
Whenyouhavethekernelsourceonthesystem,the/usr/src
directorywilllooksimilartothefollowing:
$ls-l/usr/src
total20
lrwxrwxrwx1rootroot17Jan2718:25linux->linux-2.6.15.i686
drwxr-xr-x21rootroot4096Jan2722:12linux-2.6.15.i686
drwxr-xr-x8rootroot4096Jan2718:20redhat
Intheprecedingexample,thenamelinux-2.6.15.i686means
thatthedirectorycontainsversion2.6oftheLinuxkernel,
release15,andissetupforaPentiumPro(P6core)
architecture.
The/usr/srcdirectoryisthetraditionallocationforthekernel
source.Alsocheckwhetherthekernelcodeappearsin
/usr/src/redhat,asthatiswhereitisinstalledbydefault.If
itisthere,seestep4onpage528.
Ifthesourcecodeispresentonthesystem,skipto"Cleaning
theSourceTree"onpage529.
InstallingtheSourceCode
Whenthesourceisnotpresentonthesystem,youneedto
installit.
FEDORA
Beforeyoustart,installrpmbuild.Youwillneedthisprogramto
unpackandapplypatchestothesourcefiles.Therpmbuildutility
ispartofthefedora-rpmdevtoolspackage.Youcanusepirut
(page483)toinstallthispackage(thepackageisanoptional
packageinDeveloperTools)oryoucanissuethefollowingyum
command.
Installrpmbuild
#yuminstallfedora-rpmdevtools
Withrpmbuildinstalled,followthesestepstoinstallthekernel
sourcecode:
1. TodownloadthesourcecodefortheFedoraCore5kernel,pointa
browserat
download.fedora.redhat.com/pub/fedora/linux/core/5/SRPMS
IfyouwantthesourcecodeforaversionotherthantheFedora
Core5kernel,substitutethereleasenumberofthekernelyou
wantfor5intheprecedingURL.
Downloadtherpmfileforthekernelsourcecode.Itwillhavea
namesimilartokernel-2.6.15-1.1955_FC5.src.rpm.Thesrc
indicatesthatthepackagecontainssourcefiles.Firefoxwithits
defaultsetupwilldownloadthefileto~/Desktop.
Alternatively,youcanuseyumdownloadertodownloadthekernelfor
thelocalsystem.Seepage482forinstructions.
2. Workingasroot,userpmtoinstallthepackageyoujust
downloaded.Youneedeithertocdtothedirectorythatholdsthe
rpmfileortospecifythepathnameoftherpmfileinthefollowing
command:
#rpm-Uvhkernel*rpm
3. Theprecedingcommandinstallsthekernelspecificationfileas
/usr/src/redhat/SPECS/kernel-2.6.spec.Thisfileholdsthe
instructionsthatrpmbuildusestounpackthekernelsourcefiles
andapplypatchestothosefiles.Changedirectoriesto
/usr/src/redhat/SPECSandrunrpmbuild:
#cd/usr/src/redhat/SPECS
#rpmbuild-bp--target$(arch)kernel-2.6.spec
Thiscommandtakeafewminutestorunandgeneratesalotof
output.
4. Traditionallythesourceforthekernelthatthesystemisrunning
iskeptin/usr/src/linux.Thefollowingcommandsmovethe
sourcetothe/usr/srcdirectoryandcreateasymboliclinkto
linuxthere.Thisexampleshowsthenamesofthekernel
directoriesaskernel-2.6.15andlinux-2.6.15.i686.Thenames
onthesystemyouareworkingonwillbeslightlydifferent.
#cd/usr/src/redhat/BUILD/kernel-2.6.15
#ls
Config.mklinux-2.6.15.i686vanillaxen
#mvlinux-2.6.15.i686/usr/src
#cd/usr/src
#ln-s/usr/src/linux-2.6.15.i686/usr/src/linux
Afteryougivethesecommands,thepatchedkernelsourceis
locatedin/usr/src/linux.Therestofthischapterassumes
thatthekernelsourceisinthislocation.
RHEL
InstallingthekernelsourcecodeonaRHELsystemissimilarto
installingitonFEDORA.Reviewtheprecedingprocedureasyou
readthissectionforabetterunderstandingofwhateachstep
does.
Beforeyoustart,useup2date(page494)toinstalltwopackages
thatyouwillneedtoinstallthekernel:
#up2dateredhat-rpm-configrpm-build
Downloadthekernelsourcecode:
#up2date--get-sourcekernel
Userpmtoinstallthekernelsourcecode:
#rpm-ivh/var/spool/up2date/kernel*.src.rpm
Afteryouinstallthecode,unpackitandapplythepatches:
#cd/usr/src/redhat/SPECS
#rpmbuild-bp--target$(arch)kernel-2.6.spec
Finally,movethesourcetreetoitsclassiclocation.Seestep4,
substitutingthenamesofthekerneldirectoriesontheRHEL
systemforthoseintheexample.
Tip:Nowtheworkingdirectoryis
/usr/src/linux
Allcommandsinthissectiononbuildingakernelare
givenrelativetothetop-leveldirectorythatholds
thekernelsource.Traditionallythisdirectoryis
/usr/src/linux.Makesurethatthisdirectoryis
yourworkingdirectorybeforeproceeding.If
necessary,linkthedirectoryholdingthekernel
sourcein/usr/srcto/usr/src/linuxasexplained
instep4.
ReadtheDocumentation
Thekernelpackageincludesthelatestdocumentation,someof
whichmaynotbeavailableinotherdocuments.Reviewthe
READMEfileandtherelevantfilesintheDocumentation
directory.ReadtheLinuxKernel-HOWTOforanexcellent,
detailed,genericguidetoinstallingandconfiguringtheLinux
kernel.
ConfiguringandCompilingtheLinuxKernel
Thissectiondescribeshowtoconfigurethekerneltomeetyour
needsandhowtocompileit.
CleaningtheSourceTree
Ifyouwanttosaveanexistingconfigurationfile
(/usr/src/linux/.configure),copyittoanotherdirectory
(suchasyourhomedirectory)orrenameitbeforeyouproceed,
becausethenextcommandwillremoveit.Purgethesource
tree(allsubdirectoriesandfileswithin/usr/src/linux)ofall
configurationandpotentiallystale*.ofilesbygivingthe
followingcommand:
$makemrproper
ConfiguringtheLinuxKernel
BeforeyoucancompilethecodeandcreateaLinuxkernel,you
mustdecideandspecifywhichfeaturesyouwantthekernelto
support.Youcanconfigurethekerneltosupportmostfeatures
intwoways:bybuildingthefeatureintothekernelorby
specifyingthefeatureasaloadablekernelmodulepage531,
whichisloadedintothekernelonlyasneeded.Indeciding
whichmethodtouse,youmustweighthesizeofthekernel
againstthetimeittakestoloadamodule.Makethekernelas
smallaspossiblewhileminimizinghowoftenmoduleshaveto
beloaded.DonotmaketheSCSIdrivermodularunlessyou
haveareasontodoso.
Theconfigsdirectoryprovidessampleconfigurationfilesfor
variousprocessors,multipleprocessors,andconfigurations.You
maywanttolookatthesefilesbeforeyougetstartedoreven
useoneofthemasyourstartingpoint.Touseoneofthese
files,copyitfromtheconfigsdirectorytothelinuxdirectory
andrenameit.config.
ThreestandardcommandsareusedtoconfiguretheLinux
kernel:
$makeconfig
$makemenuconfig
$makexconfig
ThemakexconfigcommandusesQt(www.trolltech.com),
whichisnormallyinstalledwithKDEorGNOMEunderFEDORA.
IfyouprefertouseGTK+(www.gtk.org)anditisinstalledon
thelocalsystem,givethecommandmakegconfig.
UnderRHELyoumayneedtoinstalltheqt-develpackage.
Givethecommandup2dateqt-develtoinstallthispackage
andseveralpackagesthatitisdependenton.
Eachcommandasksthesamequestionsandproducesthe
sameresult,giventhesameresponses.Thefirstandsecond
commandsworkincharacter-basedenvironments;thesecond
andthirdcommandsworkingraphicalenvironments.Formost
administratorsinmostsituations,thethird(graphical)method
istheeasiesttouse(Figures15-1and15-2).Thefiguresshow
thewindowsdisplayedbyFEDORA;RHELwindowslookdifferent
butperformthesamefunction.
Figure15-1.Theqconfwindowasdisplayedby
makexconfigonFedora
[Viewfullsizeimage]
Figure15-2.TheqconfPowerManagement
supportsubmenu
[Viewfullsizeimage]
Themakexconfigcommanddisplaystheqconfwindow.You
canviewtheqconfwindowinthreeconfigurations:single,split,
orfullview.Chooseaviewbyclickingoneofthethreeiconsto
therightofthefloppydisketteonthetoolbar.Figure15-1
showsthedefaultsplitview.Inthisview,theleftframeshows
theoptionsandthetop-rightviewliststhefeaturesforeach
option.Thebottom-rightviewdescribesthehighlightedoption
orfeature.Figure15-2showsthefullview.
Inanyview,youclicktheboxesandcirclesnexttothechoices
andsubchoices.Anemptybox/circleindicatesthefeatureis
disabled,acheckmarkindicatesitistobeincludedinthe
kernel,andadotmeansitistobecompiledasamodule.Select
Menubar:Option ShowAllOptionstodisplayalloptions
andfeatures.
Gothroughtheoptionsandmarkthefeaturesasyouwouldlike
themtobeconfiguredinthenewkernel.Atanytimeduringthe
configurationprocess,youcanstorethecurrentlydefined
configurationtoafile,loadaconfigurationfromafile,orexit
withorwithoutsavingyourchanges.SeetheselectionsinFile
ontheMenubar.Whenyouaredone,selectMenubar:File
Saveandclosethewindow.
EXTRAVERSIONNumber
Topreventoverwritingexistingkernelfilesandtoidentify
variouscompilationsofthekernel,youcanusethe
EXTRAVERSIONvariableinMakefile.Thisvariableisinitially
settoprep.Whatevervalueyouassigntothisvariableis
placedattheendofthekernelnameandreleasenumberto
identifythekernel.Youcanmakenoteofpatchesappliedtothe
kernelinthisstringtohelppeopletrackdownproblemslater
on.
CompilingtheLinuxKernel
Beforecompilingthekernel,makesure,onceagain,thatno
filesareinthesourcetreefrompreviouswork:
$makeclean
Thengivethefollowingcommandtocompilethekernel:
$makebzImage
CHKinclude/linux/version.h
UPDinclude/linux/version.h
SYMLINKinclude/asm->include/asm-i386
HOSTCCscripts/basic/fixdep
HOSTCCscripts/basic/split-include
HOSTCCscripts/basic/docproc
...
UsingLoadableKernelModules
Aloadablekernelmodule(page1041)(sometimescalleda
moduleorloadablemodule)isanobjectfilepartofthe
kernelthatislinkedintothekernelatruntime.Modulesare
compiledseparatelyfromthekernelandcanbeinsertedinto
andremovedfromarunningkernelatalmostanytimeexcept
whenthemoduleisbeingused.Thisabilitygivesthekernelthe
flexibilitytobeassmallaspossibleatanygiventime.Modules
areagoodwaytocodesomekernelfeatures,includingdrivers
thatarenotusedcontinually(suchasatapedriver).
Tip:Modulefilenameextensionshave
changed
FilenamesofmodulesintheLinux2.4andearlier
kernelsendedin.o.Startingwiththe2.6kernel
(introducedinFedoraCore2andRedHatEnterprise
LInuxversion4),modulefilenamesendin.ko.
Whenyouconfigurethekerneltosupportloadablemodules,
youneedtobuildandinstallthemodules.Givethefollowing
commandtocompilethemodulesthatyouspecifiedwhenyou
configuredthekernel:
$makemodules
Compilingthemodulestypicallytakeslongerthancompilingthe
kernel.Thenextcommandinstallsthemodulesinthe
/lib/modules/kernel-versionEXTRAVERSIONdirectory.
Runthiscommandasrootevenifyoudidnotbuildany
modules:
#makemodules_install
Table15-1listssomeofthetoolsavailabletohelpyouwork
withmodules.Refertothecorrespondingmanpagesforoptions
andmoreinformation.
Table15-1.Toolsforworkingwithmodules
Tool/utility Function
depmod Workswithdependenciesformodules.
insmod Loadsmodulesinarunningkernel.
lsmod Listsinformationaboutallloadedmodules.
modinfo Listsinformationaboutamodule.
modprobe Loads,unloads,andreportsonmodules.Whenitloads
amodule,italsoloadsdependencies.
rmmod Unloadsmodulesfromarunningkernel.
InstallingtheKernelandAssociatedFiles
Thenextstepistocopythecompiledkernelandassociated
filestotheappropriatedirectory,usuallyeitherroot(/)or
/boot.Whenyouhaveabootpartition,thefilesarekeptin
therootofthispartition(/boot).Withoutabootpartition,the
filesarekeptintherootdirectory.Runthefollowingcommand
asroottoinstallthenewkernelfilesintheproperdirectory:
#makeinstall
Rebooting
RebootthecomputerbyselectingLogOutfromtheMainmenu
ortheDesktopmenuunderKDEandthenchoosingRestart
ComputerorbyselectingShutDownfromtheSystemmenu
underGNOMEandthenchoosingReboot.Ifyouareworkingat
theconsole,pressCONTROL-ALT-DEL.Youcanalsogivea
rebootcommandfromanycharacter-basedterminalor
terminalemulator.
BootLoader
Abootloaderisaverysmallprogramthatisusedinthe
bootstrap(page1022)process,whichbringsacomputerfrom
offorresettoafullyfunctionalstate.Thebootloader
frequentlyresidesonthestartingsectorsofaharddiskcalled
theMBR(MasterBootRecord).
TheBIOS(page1021),storedinanEEPROM(page1030)on
thesystem'smotherboard,gainscontrolofasystemwhenyou
turnonorresetthecomputer.Aftertestingthehardware,the
BIOStransferscontroltotheMBR,whichusuallypassescontrol
tothepartitionbootrecord.Thistransferofcontrolstartsthe
bootloader,whichisresponsibleforlocatingtheoperating
systemkernel(keptinthe/or/bootdirectory),loadingthat
kernelintomemory,andstartingitrunning.Referto"Booting
theSystem"onpage403formoreinformationonwhat
happensfromthispointforward.
Youcanplacethe/bootdirectoryonaverysmallfilesystem
thatislocatednearthebeginningoftheharddrive,wherethe
BIOScanaccessit.Withthissetup,theroot(/)filesystemcan
beanywhereonanyharddrivethatLinuxcanaccessandthat
perhapstheBIOScannot.
grub:TheLinuxLoader
Thenamegrub(seethegrubinfopageand
www.gnu.org/software/grub)standsforGrandUnifiedBoot
Loader.AproductoftheGNUproject,thegrubloaderconforms
tothemultibootspecification(page1044),whichallowsitto
loadmanyfreeoperatingsystemsdirectlyaswellastochain
load(page1024)proprietaryoperatingsystems.Thegrubloader
canrecognizevarioustypesoffilesystemsandkernel
executableformats,allowingittoloadanarbitraryoperating
system.Youmustspecifythekernel'sfilenameandlocation
(driveandpartition)sothatgrubknowswheretofindthe
kernel.Youcanpassthisinformationtogrubviaeitherthe
commandlineorthemenuinterface.Whenyoubootthe
system,grubdisplaysamenuofchoicesthatisgeneratedbythe
/boot/grub/grub.conffile(orseeitssymboliclink,
/etc/grub.conf).Atthispointyoucanmodifythemenu,
choosewhichoperatingsystemtoboot,ordonothingandallow
grubtobootthedefaultsystem.Whenyouinstallgrubatthe
timeyouinstallLinux,theinstallationprogramconfiguresgrub
automatically,soyoudonothaveto.
The/boot/grub/grub.conffileisthedefaultgrub
configurationfile.Thegrub.conffileinthefollowingexampleis
fromasystemthathaditskernelreplaced(therearetwo
versionsofvmlinuzandinitrd).Thesystemhasaseparate
bootpartitionsothatallkernelandinitrd(forsystemsusing
loadablemodules;seepage531)imagepathsarerelativeto
/boot(seetheNOTICEinthefile).Withoutaseparateboot
partition,thebootfilesresideintherootpartition(/)sothat
kernelandinitrdpathsarerelativeto/.
ThefilestartswithcommentsthatAnaconda,thegraphical
installer,putsthere,followedbyfourassignments.Thedefault
isthesectionnumberofthedefaultbootspecification.This
numberingstartswith0.Theexampleincludestwoboot
specifications:Thefirst,numbered0,isforthe2.6.15-
1.1881_FC5kernel;thesecond,numbered1,isforthe
2.6.15-1.1878_FC5kernel.Thetimeoutisthenumberof
secondsthatgrubwaitsafterithaspromptedyouforaboot
specificationbeforeitbootsthesystemwiththedefaultboot
specification.Thesplashimageisthegrubmenuinterface
backgroundthatyouseewhenyoubootthesystem.Whenyou
specifyhiddenmenu,grubbootsthedefaultentryanddoesnot
displaythemenuinterfaceunlessyoupressESCAPEwhilethe
systemisbooting.
$cat/etc/grub.conf
#grub.confgeneratedbyanaconda
#
#Notethatyoudonothavetorerungrubaftermakingchangestothisfile
#NOTICE:Youhavea/bootpartition.Thismeansthat
#allkernelandinitrdpathsarerelativeto/boot/,eg.
#root(hd0,0)
#kernel/vmlinuz-versionroroot=/dev/hda2
#initrd/initrd-version.img
#boot=/dev/hda
default=0
timeout=5
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
titleFedoraCore(2.6.15-1.1881_FC5)
root(hd0,0)
kernel/vmlinuz-2.6.15-1.1881_FC5roroot=LABEL=/1rhgbquiet
initrd/initrd-2.6.15-1.1881_FC5.img
titleFedoraCore(2.6.15-1.1878_FC5)
root(hd0,0)
kernel/vmlinuz-2.6.15-1.1878_FC5roroot=LABEL=/1rhgbquiet
initrd/initrd-2.6.15-1.1878_FC5.img
Followingthehiddenmenuassignmentinthepreceding
examplearetwobootspecifications,differentiatedbythetitle
linesasexplainedpreviously.Thethreelinesfollowingthetitle
lineineachspecificationspecifythelocationoftheroot(drive
0,partition0),kernel,andinitrdimages.Inthiscase,
becausethereisa/bootpartition,thepathnamesarerelative
to/boot.Forthedefaultbootspecification(thefirstone,
numbered0),theabsolutepathnameofthekernelis
/boot/vmlinuz-2.6.15-1.1881_FC5,whichisspecifiedwith
theoptionsroroot=LABEL=/1rhgbquiet.Theseoptionstell
grubthatitistobemountedreadonlyandthatroot(/)is
mountedonthedevicelabeled/1in/etc/fstab(page469).
Therhgb(RedHatgraphicalboot)softwaregeneratesa
graphicaldisplaythattellsyouwhatishappeningasthesystem
boots.Thequietoptionproduceslessdebuggingoutputsoitis
easiertotellwhatishappening.Youspecifytheinitrd(initialize
RAMdisk,page1051)imageinamannersimilartothekernel.
Substitutethelocalkernelandinitrdnamesandversion
numbersfortheonesintheexample.Makesurethatwhenyou
installanewkernelmanually,itstitlelineisdifferentfromthe
othersingrub.conf.
LOADLIN:ADOS-BasedLinuxLoader
TheLOADLINloader,aDOSutilitythatloadsLinuxfromDOS
andsomeversionsofWindows,canloadbigkernels(bzImage)
andRAMdiskimages(initrd).Referto
elserv.ffm.fgan.de/~lermen,whereyoucanfindtheLOADLIN
UsersGuideandotherinformation.Seealsothe
Loadlin+Win95/98/MEmini-HOWTO.
dmesg:DisplaysKernelMessages
Thedmesgutilitydisplaysthekernel-ringbuffer,wherethe
kernelstoresmessages.Whenthesystemboots,thekernelfills
thisbufferwithmessagesrelatedtohardwareandmodule
initialization.Messagesinthekernel-ringbufferareoftenuseful
fordiagnosingsystemproblems.Whenyourundmesg,it
displaysalotofinformation.Itisfrequentlyeasiertopipethe
outputofdmesgthroughlessorgreptofindwhatyouarelooking
for.Forexample,ifyoufindthatyourharddisksareperforming
poorly,youcanusedmesgtocheckthattheyarerunninginDMA
mode:
$dmesg|grepDMA
...
ide0:BM-DMAat0xf000-0xf007,BIOSsettings:hda:DMA,hdb:DMA
ide1:BM-DMAat0xf008-0xf00f,BIOSsettings:hdc:DMA,hdd:DMA
...
TheprecedinglinestellyouwhichmodeeachIDEdeviceis
operatingin.IfyouarehavingproblemswiththeEthernet
connection,searchthedmesglogforeth:
$dmesg|grepeth
forcedeth.c:ReverseEngineerednForceethernetdriver.Version0.49.
eth0:forcedeth.c:subsystem:0147b:1c00boundto0000:00:04.0
eth0:noIPv6routerspresent
Ifeverythingisworkingproperly,dmesgdisplaysthehardware
configurationinformationforeachnetworkcard.Ifyouhave
configuredasystemserviceincorrectly,thedmesglogquickly
fillsupwitherrors;itisagoodplacetostartwhendiagnosing
faults.
ChapterSummary
YoucanbuildaLinuxkernelfromthesourcecode.Sometimes
youdonotneedtobuildakernel;youcandynamicallychange
manythingsbyusingbootoptionsin/etc/grub.conforby
modifying/etc/sysctl.conf.
BeforeyoucanbuildaLinuxkernel,youmusthavethekernel
sourcefilesonthesystem.Thesefilesarelocatedin
/usr/src/linux.Onceyouhavethesourcefiles,youneedto
cleanthesourcetree,configurethekernel,compilethekernel
andtheloadablemodules,andinstallthekernelandloadable
modules.
Thegrubbootloaderisaverysmallprogramthatisusedinthe
processofbringingthesystemup.Youmustconfiguretheboot
loadersothatitrecognizesthenewkernel.
Thedmesgutilitydisplaysthekernel-ringbuffer,wherethe
kernelstoresmessages.Youcanusethisutilitytohelp
diagnoseboot-timeproblems.
Exercises
1. Whatisthepurposeofthekernel?
2. Howwouldyoudisplayalistofallloadedmodulesinthecurrentkernel?
3. Whichcommandwouldyougivetoupgradethekernelfromanrpmfile,andhowis
thisdifferentfromupgradingotherpackages?
4. Howwouldyoudisplayinformationfromthekernelabouttheharddiskonthefirst
IDEchannel?
5. ThenoreplacementkernelargumenttellsthekernelnottouseCPU-specific
sectionsofcode.Howwouldyouusethisargument?
6. Whatisabootloader?
AdvancedExercises
7. WhatistheEXTRAVERSIONvariable?Whereisitusedandwhatisitusedfor?
8. YouhavejustinstalledanAdaptecSCSIcard.Howcanyoufindoutwhetherithas
beenrecognizedandwhichentryin/devrepresentsit?
9. Whenyouinstallanexperimentalkernelfortesting,howdoyouinstructgrubnotto
loaditbydefault?
10. Howwouldyouobtainalistofallnetwork-relatedkernelparameters?
16.AdministrationTasks
INTHISCHAPTER
ConfiguringUserandGroupAccounts 538
BackingUpFiles 540
SystemReports 548
KeepingUsersInformed 551
SolvingProblems 553
SpeedingUptheSystem 554
KeepingtheSystemSecure 556
logrotate:ManagesLogFiles 559
DiskQuotaSystem 561
syslogd:LogsSystemMessages 562
Thesystemadministratorhasmanyresponsibilities.This
chapterdiscussestasksnotcoveredinChapter11,including
configuringuserandgroupaccounts,backingupfiles,
schedulingtasks,generalproblemsolving,andusingthe
systemlogdaemon,syslogd.
ConfiguringUserandGroupAccounts
Morethanausernameisrequiredforausertobeabletologin
anduseasystem.Ausermusthavethenecessaryfiles,
directories,permissions,andusuallyapasswordtologin.Ata
minimumausermusthaveanentryinthe/etc/passwdand
/etc/shadowfilesandahomedirectory.Thefollowing
sectionsdescribeseveralwaysyoucanworkwithuser
accounts.Refertopage373andtheNIS-HOWTOwhenyou
wanttorunNIStomanagethepasswddatabase.
system-config-users:ManagesUserAccounts
Thesystem-config-usersutilitydisplaystheUserManagerwindow
andenablesyoutoadd,delete,andmodifysystemusersand
groups.TodisplaytheUserManagerwindow,entersystem-
config-usersonacommandline.FromKDEselectMain
menu:Administration UsersandGroupsorfromGNOME
selectSystem:Administration UsersandGroups.This
windowhastwotabs:UsersandGroups,whereeachtab
displaysinformationappropriatetoitsname.Figure16-1shows
theUserstab.
Figure16-1.TheUserManagerwindow,Userstab
[Viewfullsizeimage]
Searchfilter
TheSearchfilter,locatedjustbelowthetoolbar,selectsusersor
groupswhosenamesmatchthestring,whichcaninclude
wildcards,thatyouenterintheSearchfiltertextbox.The
stringmatchesthebeginningofaname.Forexample,*nob
matchesnobodyandnfsnobody,whereasnobmatchesonly
nobody.Afteryouenterthestring,clickApplyfilterorpress
RETURN.Ifyouhaveonlyafewusers,youwillnotneedtouse
theSearchfilter.
Addingauser
Tocreateanewuser,clicktheAddUserbuttononthetoolbar.
TheUserManagerdisplaystheCreateNewUserwindow,which
gathersmuchofthesameinformationastheUserDatatabof
theUserPropertieswindow(Figure16-2).Entertheinformation
forthenewuserandclickOK.Onceyoucreateauser,youcan
modifytheusertoadd/change/removeinformation.
Figure16-2.TheUserPropertieswindow,User
Datatab
Modifyingauser
Tomodifyauser,highlighttheuserintheUserManagerwindow
andclickPropertiesonthetoolbar;theutilitydisplaysthe
UserPropertieswindow(Figure16-2).
TheUserPropertieswindowhasfourtabs:UserData,Account
Info,PasswordInfo,andGroups.TheUserDatatabholdsbasic
userinformationsuchasnameandpassword.TheAccountInfo
taballowsyoutospecifyanexpirationdatefortheaccountand
tolocktheaccountsotheusercannotlogin.ThePasswordInfo
taballowsyoutoturnonpasswordexpirationandspecify
variousrelatedparameters.IntheGroupstab,youcanspecify
thegroupsthattheuserisamemberof.
Workingwithgroups
ClicktheGroupstabintheUserManagerwindowtoworkwith
groups.Tocreateagroup,clickAddGrouponthetoolbarand
specifythenameofthegroup.Tochangethenameofagroup
ortoaddorremoveusersfromagroup,highlightthegroup
andclickPropertiesonthetoolbar.Clicktheappropriatetab,
makethechangesyouwant,andclickOK.Seepage451for
moreinformationongroups.
Help
TheUserManagerprovidesextensivehelp.Toaccessit,click
Helponthetoolbar.
Whenyouaredoneworkingwithusersandgroups,closethe
window.
useradd:AddsaUserAccount
Theuseraddutility(andthelinktoit,namedadduser)addsanew
useraccounttothesystem.Bydefault,useraddassignsthenext
highestunuseduserIDtoanewaccountandspecifiesbashas
theuser'sloginshell.Thefollowingexamplecreatestheuser's
homedirectory(in/home),specifiestheuser'sgroupID,and
putstheuser'sfullnameinthecommentfield:
#useradd-g500-c"AlexWatson"alex
Basedonthe/etc/login.defsfile,thesystemcreatesahome
directoryforthenewuser.Whenuseraddcreatesahome
directory,itcopiesthecontentsof/etc/skel,whichcontains
bashandotherstartupfiles,tothatdirectory.Formore
informationonaddingandmodifyinguserinformation,seethe
useraddandusermodmanpages.Onceyouhaveaddedauser,use
passwdtogivetheuserapassword.
userdel:RemovesaUserAccount
Ifappropriate,backupthefilesbelongingtotheuserbefore
deletingthem.Theuserdelutilitydeletesuseraccounts.The
followingcommandremovesalex'saccount,hishome
directory,andallhisfiles:
#userdel-ralex
Toturnoffauser'saccounttemporarily,youcanuseusermodto
changetheexpirationdatefortheaccount.Becauseitspecifies
thathisaccountexpiredinthepast(December31,2005),the
followingcommandlinepreventsalexfromloggingin:
#usermod-e"12/31/05"alex
groupadd:AddsaGroup
Justasuseraddaddsanewusertothesystem,groupaddaddsa
newgroupbyaddinganentryforitin/etc/group(page451).
Thefollowingexamplecreatesanewgroupnamedrtfm:
#groupadd-g1024rtfm
UnlessyouusethegoptiontoassignagroupID,thesystem
picksthenextavailablesequentialnumbergreaterthan500.
TheooptionallowsthegroupIDtobenonuniqueifyouwantto
havemultiplenamesforthesamegroupID.
Theanalogueofuserdelforgroupsisgroupdel,whichtakesa
groupnameasanargument.Youcanalsousegroupmodto
changethenameorgroupIDofagroup,asinthefollowing
examples:
#groupmod-g1025rtfm
#groupmod-nmanualsrtfm
Thefirstexamplegivesthepreviouslycreatedrtfmgroupa
newgroupIDnumber.Thesecondexamplerenamesthertfm
groupmanuals.
Caution:GroupIDcautions
Thegroupmodutilitydoesnotchangegroupnumbers
in/etc/passwdwhenyourenumberagroup.You
mustedit/etc/passwdandchangetheentries
yourself.Ifyouchangethenumberofagroup,files
thatareassociatedwiththegroupwillnolongerbe
associatedwiththegroup.Instead,theymaybe
associatedwithnogrouporwithanothergroupwith
theoldgroupIDnumber.
BackingUpFiles
Oneofthemostneglectedtasksofsystemadministrationis
makingbackupcopiesoffilesonaregularbasis.Thebackup
copiesarevitalinthreeinstances:whenthesystem
malfunctionsandfilesarelost,whenacatastrophicdisaster
(fire,earthquake,andsoon)occurs,andwhenauserorthe
systemadministratordeletesorcorruptsafilebyaccident.
EvenwhenyousetupRAID(page31),youstillneedtobackup
files.AlthoughRAIDprovidesfaulttolerance(helpfulinthe
eventofdiskfailure),itdoesnothelpwhenacatastrophic
disasteroccursorwhenafileiscorruptedoraccidentally
removed.Itisagoodideatohaveawrittenbackuppolicyand
tokeepcopiesofbackupsoffsite(inanotherbuilding,athome,
oratacompletelydifferentfacilityorcampus)inafireproof
vaultorsafe.
Thetimetostartthinkingaboutbackupsiswhenyoupartition
thedisk.Referto"PartitioningaDisk"onpage29.Makesure
thecapacityofthebackupdeviceandyourpartitionsizesare
comparable.Althoughyoucanbackupapartitionontomultiple
volumes,itiseasiernottoandmucheasiertorestoredata
fromasinglevolume.
Youmustbackupfilesystemsonaregularbasis.Backupfiles
areusuallykeptonmagnetictapeorsomeotherremovable
media.Exactlyhowoftenyoushouldbackupwhichfiles
dependsonthesystemandyourneeds.Usethiscriterionwhen
determiningabackupschedule:Ifthesystemcrashes,how
muchworkareyouwillingtolose?Ideallyyouwouldbackupall
filesonthesystemeveryfewminutessoyouwouldneverlose
morethanafewminutesofwork.
Ofcourse,thereisatradeoff:Howoftenareyouwillingtoback
upthefiles?Thebackupproceduretypicallyslowsdownthe
systemforotherusers,takesacertainamountofyourtime,
andrequiresthatyouhaveandstorethemedia(tapeordisk)
holdingthebackup.Avoidbackingupanactivefilesystem;the
resultsmaybeinconsistent,andrestoringfromthebackupmay
beimpossible.Thisrequirementisafunctionofthebackup
programandthefilesystemyouarebackingup.
Anotherquestioniswhentorunthebackup.Unlessyouplanto
kickusersoffandbringthesystemdowntosingle-usermode
(notaveryuser-friendlypractice),youwanttoperformthis
taskwhenthemachineisatitsquietest.Dependingontheuse
ofthesystem,sometimeinthemiddleofthenightcanwork
well.Thenthebackupisleastlikelytoaffectusers,andthefiles
arenotlikelytochangeastheyarebeingreadforbackup.
Afullbackupmakescopiesofallfiles,regardlessofwhenthey
werecreatedoraccessed.Anincrementalbackupmakescopies
ofthosefilesthathavebeencreatedormodifiedsincethelast
(usuallyfull)backup.
Themorepeopleusingthesystem,themoreoftenyoushould
backupthefilesystems.Onepopularscheduleistoperforman
incrementalbackuponeortwotimesadayandafullbackup
oneortwotimesaweek.
ChoosingaBackupMedium
Ifthelocalsystemisconnectedtoanetwork,youcanwrite
yourbackupstoatapedriveonanothersystem.Thistechnique
isoftenusedwithnetworkedcomputerstoavoidthecostof
havingatapedriveoneachcomputerinthenetworkandto
simplifymanagementofbackingupmanycomputersina
network.Mostlikelyyouwanttouseatapesystemfor
backups.Becausetapedrivesholdmanygigabytesofdata,
usingtapesimplifiesthetaskofbackingupthesystem,making
itmorelikelythatyouwilltakecareofthisimportanttask
regularly.OtheroptionsforholdingbackupsarewritableCDs,
DVDs,andremovableharddisks.Thesedevices,althoughnot
ascost-effectiveorabletostoreasmuchinformationastape
systems,offerconvenienceandimprovedperformanceover
usingtapes.
BackupUtilities
Anumberofutilitieshelpyoubackupthesystem,andmost
workwithanymedia.MostLinuxbackuputilitiesarebasedon
oneofthearchiveprogramstarorcpioandaugmentthesebasic
programswithbookkeepingsupportformanagingbackups
conveniently.
Youcanuseanyofthetar,cpio,ordump/restoreutilitiesto
constructfullorpartialbackupsofthesystem.Eachutility
constructsalargefilethatcontains,orarchives,otherfiles.In
additiontofilecontents,anarchiveincludesheaderinformation
foreachfileitholds.Thisheaderinformationcanbeusedwhen
extractingfilesfromthearchivetorestorefilepermissionsand
modificationdates.Anarchivefilecanbesavedtodisk,written
totape,orshippedacrossthenetworkwhileitisbeingcreated.
Inadditiontohelpingyoubackupthesystem,theseprograms
offeraconvenientwaytobundlefilesfordistributiontoother
sites.Thetarprogramisoftenusedforthispurpose,andsome
softwarepackagesavailableontheInternetarebundledastar
archivefiles.
Theamanda(AdvancedMarylandAutomaticNetworkDisk
Archiver,www.amanda.org)utility,oneofthemorepopular
backupsystems,usesdumportarandtakesadvantageofSamba
tobackupWindowssystems.TheamandautilitybacksupaLAN
ofheterogeneoushoststoasingletapedrive.Youcanuseyum
toinstallamanda;refertotheamandamanpagefordetails.
tar:ArchivesFiles
Thetar(tapearchive)utilitystoresandretrievesfilesfroman
archiveandcancompressthearchivetoconservespace.Ifyou
donotspecifyanarchivedevice,taruses/dev/rmt0(which
maynotexistonthelocalsystem).Withthefoption,taruses
theargumenttofasthenameofthearchivedevice.Youcan
usethisoptiontorefertoadeviceonanothersystemonthe
network.Althoughtarhasmanyoptions,youneedonlyafewin
mostsituations.Thefollowingcommanddisplaysacompletelist
ofoptions:
#tarhelp|less
Mostoptionsfortarcanbegiveneitherinashortform(asingle
letter)orasadescriptiveword.Descriptive-wordoptionsare
precededbytwohyphens,asinhelp.Single-letteroptionscan
becombinedintoasinglecommandlineargumentanddonot
needtobeprecededbyahyphen(forconsistencywithother
utilities,itisgoodpracticetousethehyphenanyway).
Althoughthefollowingtwocommandslookquitedifferent,they
specifythesametaroptionsinthesameorder.Thefirstversion
combinessingle-letteroptionsintoasinglecommandline
argument;thesecondversionusesdescriptivewordsforthe
sameoptions:
#tarztvf/dev/st0
#targziplistverbosefile/dev/st0
Bothcommandstelltartogeneratea(v,verbose)tableof
contents(t,list)fromthetapeon/dev/st0(f,file),usinggzip
(z,gzip)todecompressthefiles.UnliketheoriginalUNIXtar
utility,theGNUversionstripstheleading/fromabsolute
pathnames.
TheoptionsinTable16-1tellthetarprogramwhattodo.You
mustincludeexactlyoneoftheseoptionsinatarcommand.
Table16-1.Thetarutility
Option Effect
append(r) Appendsfilestoanarchive
catenate(A) Addsoneormorearchivestotheendofan
existingarchive
create(c) Createsanewarchive
delete Deletesfilesinanarchive(notontapes)
dereference(h) Followssymboliclinks
diff(d) Comparesfilesinanarchivewithdiskfiles
extract(x) Extractsfilesfromanarchive
help Displaysahelplistoftaroptions
list(t) Liststhefilesinanarchive
update(u) Liketheroption,butthefileisnotappendedifa
newerversionisalreadyinthearchive
Thec,t,andxoptionsareusedmostfrequently.Youcanuse
manyotheroptionstochangehowtaroperates.Thejoption,
forexample,compressesordecompressesthefilebyfilteringit
throughbzip2(page140).
cpio:ArchivesFiles
Thecpio(copyin/out)programissimilartotarbutcanuse
archivefilesinavarietyofformats,includingtheoneusedby
tar.Normallycpioreadsthenamesofthefilestoinsertintothe
archivefromstandardinputandproducesthearchivefileas
standardoutput.Whenextractingfilesfromanarchive,cpio
readsthearchiveasstandardinput.
Aswithtar,someoptionscanbegiveninbothashort,single-
letterformandamoredescriptivewordform.However,unlike
tar,thesyntaxofthetwoformsdifferswhentheoptionmustbe
followedbyadditionalinformation.Intheshortform,youmust
includeaSPACEbetweentheoptionandtheadditional
information;withthewordform,youmustseparatethetwo
withanequalsignandnoSPACEs.
Runningcpiowithhelpdisplaysafulllistofoptions.
PerformingaSimpleBackup
Whenyoupreparetomakeamajorchangetoasystem,such
asreplacingadiskdriveorupdatingtheLinuxkernel,itisa
goodideatoarchivesomeorallofthefilessoyoucanrestore
anythatbecomedamagedifsomethinggoeswrong.Forthis
typeofbackup,tarorcpioworkswell.Forexample,ifyouhavea
SCSItapedriveasdevice/dev/st0thatiscapableofholding
allthefilesonasingletape,youcanusethefollowing
commandstoconstructabackuptapeoftheentiresystem:
#cd/
#tarcf/dev/st0.
Allofthecommandsinthissectionstartbyusingcdtochange
totherootdirectorysoyouaresuretobackuptheentire
system.Thetarcommandthencreatesanarchive(c)onthe
device/dev/st0(f).Ifyouwouldliketocompressthearchive,
replacetheprecedingtarcommandwiththefollowingcommand,
whichusesjtocallbzip2:
#tarcjf/dev/st0.
Youcanbackupthesystemwithacombinationoffindandcpio.
ThefollowingcommandscreateanoutputfileandsettheI/O
blocksizeto5120bytes(thedefaultis512bytes):
#cd/
#find.depth|cpiooB>/dev/st0
Thenextcommandrestoresthefilesinthe/homedirectory
fromtheprecedingbackup.Theoptionsextractfilesfroman
archive(i)inverbosemode,keepingthemodificationtimesand
creatingdirectoriesasneeded.
#cd/
#cpioivmd/home/\*</dev/st0
Tip:Excludesomedirectoriesfroma
backup
Inpractice,youwilllikelywanttoexcludesome
directoriesfromthebackupprocess.Forexample,
notbackingup/tmpor/var/tmp(oritslink,
/usr/tmp)cansaveroominthearchive.Also,do
notbackupthefilesin/proc.Becausethe/proc
filesystemisnotadiskfilesystembutratheraway
fortheLinuxkerneltoprovideinformationaboutthe
operatingsystemandsystemmemory,youneednot
backup/proc;youcannotrestoreitlater.Youdo
notneedtobackupfilesystemsthataremounted
fromdisksonothersystemsinthenetwork.Donot
backupFIFOs;theresultsareunpredictable.Ifyou
planonusingasimplemethod,similartothosejust
discussed,createafilenamingthedirectoriesto
excludefromthebackup,andusetheappropriate
optionwiththearchiveprogramtoreadthefile.
Althoughallofthearchiveprogramsworkwellforsuchsimple
backups,utilitiessuchasamandaprovidemoresophisticated
backupandrestoresystems.Forexample,todetermine
whetherafileisinanarchive,youmustreadtheentirearchive.
Ifthearchiveissplitacrossseveraltapes,thisprocessis
particularlytiresome.Moresophisticatedutilities,including
amanda,assistyouinseveralways,includingkeepingatableof
contentsofthefilesinabackup.
dump,restore:BackUpandRestoreFilesystems
Thedumputility,whichfirstappearedinUNIXversion6,backs
upeitheranentirefilesystemoronlythosefilesthathave
changedsincethelastdump.Therestoreutilityrestoresanentire
filesystem,anindividualfile,oradirectoryhierarchy.Youwill
getthebestresultsifyouperformabackuponaquiescent
systemsothatthefilesarenotchangingasyoumakethe
backup.
Thenextcommandbacksupallfiles(includingdirectoriesand
specialfiles)ontheroot(/)partitiontoSCSItape0.
Frequentlythereisalinktotheactivetapedrive,named
/dev/tape,whichyoucanuseinplaceoftheactualentryin
the/devdirectory.
#dump-0uf/dev/st0/
Theoptionspecifiesthattheentirefilesystemistobebacked
up(afullbackup).Therearetendumplevels:09.Zeroisthe
highest(mostcomplete)levelandalwaysbacksuptheentire
filesystem.Eachadditionallevelisincrementalwithrespectto
thelevelaboveit.Forexample,1isincrementalto0andbacks
uponlyfilesthathavechangedsincethelastlevel0dump;2is
incrementalto1andbacksuponlyfilesthathavechanged
sincethelastlevel1dump;andsoon.Youcanconstructavery
flexiblescheduleusingthisscheme.Youdonotneedtouse
sequentialnumbersforbackuplevels.Youcanperformalevel0
dump,followedbylevel2and5dumps.
Theuoptionupdatesthe/etc/dumpdatesfile(page450)
withfilesystem,date,anddumplevelinformationforusebythe
nextincrementaldump.Thefoptionanditsargumentwritethe
backuptothedevicenamed/dev/st0.
Thefollowingcommandmakesapartialbackupcontainingall
filesthathavechangedsincethelastlevel0dump.Thefirst
argumentisa1,specifyingalevel1dump:
#dump-1uf/dev/st0/
Torestoreanentirefilesystemfromatape,firstrestorethe
mostrecentcomplete(level0)backup.Performthisoperation
carefullybecauserestorecanoverwritetheexistingfilesystem.
WhenyouareloggedinasSuperuser,cdtothedirectorythe
filesystemismountedonandgivethiscommand:
#restore-if/dev/st0
Theioptioninvokesaninteractivemodethatallowsyouto
choosewhichfilesanddirectoriestorestore.Aswithdump,thef
optionspecifiesthenameofthedevicethatthebackupmedium
ismountedon.Whenrestorefinishes,loadthenextlower-level
(higher-number)dumptapeandissuethesamerestore
command.Ifmultipleincrementaldumpshavebeenmadeata
particularlevel,alwaysrestorewiththemostrecentone.You
donotneedtoinvokerestorewithspecialargumentstorestore
anincrementaldump;itwillrestorewhateverappearsonthe
tape.
Youcanalsouserestoretoextractindividualfilesfromatapeby
usingthexoptionandspecifyingthefilenamesonthe
commandline.Wheneveryourestoreafile,therestoredfilewill
appearintheworkingdirectory.Beforerestoringfiles,make
sureyouareworkinginthecorrectdirectory.Thefollowing
commandsrestoretheetc/xinetd.conffilefromthetapeon
/dev/st0.Thefilenameofthedumpedfiledoesnotbeginwith
/becausealldumpedpathnamesarerelativetothefilesystem
thatyoudumpedinthiscase/.Becausetherestorecommandis
givenfromthe/directory,thefilewillberestoredtoitsoriginal
locationof/etc/xinetd.conf:
#cd/
#restore-xf/dev/st0etc/xinetd.conf
Ifyouusethexoptionwithoutspecifyingafileordirectory
nametoextract,theentiredumpedfilesystemisextracted.Use
theroptiontorestoreanentirefilesystemwithoutusingthe
interactiveinterface.Thefollowingcommandrestoresthe
filesystemfromthetapeon/dev/st0totheworkingdirectory
withoutinteraction:
#restore-rf/dev/st0
Youcanalsousedumpandrestoretoaccessatapedriveon
anothersystem.Specifythefile/directoryashost:file,where
hostisthehostnameofthesystemthetapedriveisonand
fileisthefile/directoryyouwanttodump/restore.
Occasionally,restoremaypromptyouwiththefollowing
message:
Youhavenotreadanyvolumesyet.
Unlessyouknowwhichvolumeyourfile(s)areonyoushouldstart
withthelastvolumeandworktowardsthefirst.
Specifynextvolume#:
Enter1(one)inresponsetothisprompt.Ifthefilesystem
spansmorethanonetapeordisk,thispromptallowsyouto
switchtapes.
Attheendofthedump,youwillreceiveanotherprompt:
setowner/modefor'.'?[yn]
Answerytothispromptwhenyouarerestoringentire
filesystemsorfilesthathavebeenaccidentallyremoved.Doing
sowillrestoretheappropriatepermissionstothefilesand
directoriesbeingrestored.Answernifyouarerestoringadump
toadirectoryotherthantheoneitwasdumpedfrom.The
workingdirectorypermissionsandownerwillthenbesetto
thoseofthepersondoingtherestore(typicallyroot).
Variousdevicenamescanaccessthe/dev/st0device.Each
nameaccessesadifferentminordevicenumberthatcontrols
someaspectofhowthetapedriveisused.Afteryoucompletea
dumpwhenyouuse/dev/st0,thetapedriveautomatically
rewindsthetapetothebeginning.UsethenonrewindingSCSI
tapedevice(/dev/nst0)tokeepthetapefromrewindingon
completion.Thisfeatureallowsyoutobackupmultiple
filesystemstoonevolume.Followingisanexampleofbacking
upasystemwherethe/home,/usr,and/vardirectories
resideondifferentfilesystems:
#dump-0uf/dev/nst0/home
#dump-0uf/dev/nst0/usr
#dump-0uf/dev/st0/var
Theprecedingexampleusesthenonrewindingdeviceforthe
firsttwodumps.Ifyouusetherewindingdevice,thetape
rewindsaftereachdump,andyouareleftwithonlythelast
dumponthetape.
Youcanusemt(magnetictape),whichispartofthemt-st
package,tomanipulatefilesonamultivolumedumptape.The
followingmtcommandpositionsthetape(fsf2instructsmtto
skipforwardpasttwofiles,leavingthetapeatthestartofthe
thirdfile).Therestorecommandrestoresthe/varfilesystem
fromthepreviousexample:
#mt-f/dev/st0fsf2
#restorerf/dev/st0
SchedulingTasks
Itisagoodpracticetoschedulecertainroutinetaskstorun
automatically.Forexample,youmaywanttoremoveoldcore
filesonceaweek,summarizeaccountingdatadaily,androtate
systemlogfilesmonthly.
crondandcrontab:ScheduleRoutineTasks
Usingcrontab,youcansubmitalistofcommandsinaformat
thatcanbereadandexecutedbycrond.WorkingasSuperuser,
youcanputcommandsinoneofthe/etc/cron.*directoriesto
berunatintervalsspecifiedbythedirectoryname,suchas
cron.daily.
WhenSELinuxissettouseatargetedpolicy,itprotectsthe
crondaemon.Youcandisablethisprotectionifnecessary.For
moreinformationreferto"SettingtheTargetedPolicywith
system-config-securitylevel"onpage402.
Tip:cronstopsfornoone;tryanacron
Thecronddaemonassumesthesystemisalways
running.Asimilarutility,anacron,doesnotmakethat
assumptionandiswellsuitedtoportableandhome
computersthatarefrequentlyturnedoff.Theanacron
utilitytakesitsinstructionsfromthe
/etc/anacrontabfileunlessyouspecifyotherwise.
Refertotheanacronandanacrontabmanpagesformore
information.
at:RunsOccasionalTasks
Likethecronutility,atallowsyoutorunajobsometimeinthe
future.Unlikecron,atrunsajobonlyonce.Forinstance,youcan
scheduleanatjobthatwillrebootthesystemat3AM(whenall
usersareprobablyloggedoff):
#at3am
at>reboot
at>CONTROL-D<EOT>
job1at2006-02-0103:00
Itisalsopossibletorunanatjobfromwithinanatjob.For
instance,anatjobmightcheckfornewpatchesevery18days,
somethingthatwouldbemoredifficultwithcron.
kcron:SchedulesTasks
ThekcronutilityprovidesaGUItocron,allowingyoutocreate
andmodifycrontabfiles.Schedulingtaskswithkcronisa
matterofclickingbuttons(Figure16-3).
Figure16-3.ThekcronTaskScheduler
[Viewfullsizeimage]
Runkcronwhenyouareloggedinasyourselftoviewandmodify
yourpersonalcrontabfile.Whenyourunkcronasroot,you
canmodifyanycrontabfileonthesystem.Atfirst,kcron
displaysawindowthatlistsTasksandVariables,and,whenyou
arerunningasroot,Users.TheDescriptioncolumnofthis
windowisverywideanddoesnotfitinthewindow.Usethe
right-leftscrollbartoviewitscontents.Ifyouarerunningas
root,youneedtodouble-clickausertodisplaytheTasks
folder.Tocreateanewcrontabentry,highlightTasks,and
selectNewfromEditonthemenubar(orfromtheright-click
menu).Tomodifyanentry,highlighttheentry,andselect
ModifyfromEditonthemenubar.Intheresultingwindow,
enterthenameoftheprogramyouwanttorunintheProgram
textbox,andclickbuttonsorplacecheckmarkscorresponding
tothedatesandtimesyouwanttoruntheprogram.Unlessyou
redirectit,outputfromaprogramthatcronrunsismailedto
you.
SystemReports
Manyutilitiesreportononethingoranother.Thewho,finger,ls,ps,andotherutilitiesgenerate
simpleend-userreports.Insomecases,thesereportscanhelpwithsystemadministration.
Thissectiondescribesutilitiesthatgeneratemorein-depthreportsthatcanusuallyprovide
moreassistancewithsystemadministrationtasks.Linuxhasmanyotherreportutilities,
including(fromthesysstatpackage)sar(systemactivityreport),iostat(input/outputandCPU
statistics),andmpstat(processorstatistics);(fromthenet-toolspackage)netstat(network
report);and(fromthenfs-utilspackage)nfsstat(NFSstatistics).
vmstat:ReportsVirtualMemoryStatistics
Thevmstatutility(procpspackage)generatesvirtualmemoryinformationalongwith(limited)
diskandCPUactivitydata.Thefollowingexampleshowsvirtualmemorystatisticsin3-
secondintervalsforseveniterations(fromthearguments37).Thefirstlinecoversthetime
sincethesystemwaslastbooted;therestofthelinescovertheperiodsincetheprevious
line.
$vmstat37
procs-----------memory-------------swap-------io------system------cpu----
rbswpdfreebuffcachesisobiboincsussyidwa
0206843283392421991600430105105213424868
020654632341602488400048977683114223705095
030623528342242790800050568237109417804095
02060317634576298936003416141116125504096
020575912347923256160045167267114723104096
1205490323516435146400442977112021004096
020523432354483763760041736577113523404095
Thefollowinglistexplainsthecolumnheadsdisplayedbyvmstat.
procs
r
b
Processinformation
Numberofwaiting,runnableprocesses
Numberofblockedprocesses(inuninterruptablesleep)
memory
swpd
free
cpu
us
sy
id
wa
top:ListsProcessesUsingtheMostResources
Thetoputilityisausefulsupplementtops.Atitssimplest,top
displayssysteminformationatthetopandthemostCPU-
intensiveprocessesbelowthesysteminformation.Thetoputility
updatesitselfperiodically;typeqtoquit.Althoughyoucanuse
commandlineoptions,theinteractivecommandsareoften
morehelpful.RefertoTable16-2andtothetopmanpagefor
moreinformation.
$top
top-21:30:26up18min,2users,loadaverage:0.95,0.30,0.14
Tasks:63total,4running,58sleeping,1stopped,0zombie
Cpu(s):30.9%us,22.9%sy,0.0%ni,0.0%id,45.2%wa,1.0%hi,0.0%si
Mem:1036820ktotal,1032276kused,4544kfree,40908kbuffers
Swap:2048276ktotal,0kused,2048276kfree,846744kcached
PIDUSERPRNIVIRTRESSHRS%CPU%MEMTIME+COMMAND
1285root250927268921312R29.30.70:00.88bzip2
1276root18030488601372R3.70.10:05.25cp
7root150000S0.70.00:00.27pdflush
6root150000S0.30.00:00.11pdflush
8root150000S0.30.00:00.06kswapd0
300root150000S0.30.00:00.24kjournald
1064mgs2160814422766808S0.30.20:00.69sshd
1224root160496413603944S0.30.10:00.03bash
1275mgs216028409361784R0.30.10:00.15top
1284root15027366681416S0.30.10:00.01tar
1root16026245201312S0.00.10:06.51init
Table16-2.top:interactivecommands
Command Function
ASortsprocessesbyage(newestfirst).
hor?DisplaysaHelpscreen.
kPromptsforaPIDnumberandtypeofsignalandsendsthe
processthatsignal.Defaultstosignal15(SIGTERM);
specify9(SIGKILL)onlywhen15doesnotwork.
MSortsprocessesbymemoryusage.
PSortsprocessesbyCPUusage(default).
qQuits.
sPromptsfortimebetweenupdatesinseconds.Use0for
continuousupdates.
SPACE Updatesthedisplayimmediately.
TSortstasksbytime.
WWritesastartupfilenamed~/.toprcsothatnexttimeyou
starttop,itusesthesameparametersitiscurrentlyusing.
KeepingUsersInformed
Oneofyourprimaryresponsibilitiesasasystemadministrator
iscommunicatingwithsystemusers.Youneedtomake
announcements,suchaswhenthesystemwillbedownfor
maintenance,whenaclassonsomenewsoftwarewillbeheld,
andhowuserscanaccessthenewsystemprinter.Youcaneven
starttofilltheroleofasmalllocalnewspaper,lettingusers
knowaboutnewemployees,RIFs,births,thecompanypicnic,
andsoon.
Differentcommunicationshavedifferentpriorities.Forexample,
informationaboutthecompanypicnicintwomonthsisnotas
timesensitiveasthefactthatyouarebringingthesystem
downin5minutes.Tomeetthesedifferingneeds,Linux
providesdifferentwaysofcommunicating.Themostcommon
methodsaredescribedandcontrastedinthefollowinglist.Allof
thesemethodsaregenerallyavailabletoeveryone,exceptfor
themessageoftheday,whichistypicallyreservedfor
Superuser.
write
Usethewriteutility(page150)tocommunicatewithauserwho
isloggedinonthelocalsystem.Youmightuseit,forexample,
toaskausertostoprunningaprogramthatisboggingdown
thesystem;theusermightreplythathewillbedonein3
minutes.Userscanalsousewritetoaskthesystem
administratortomountatapeorrestoreafile.KDEandGNOME
openanewwindowwhentheyreceiveamessage.
wall
Thewall(writeall)utilityeffectivelycommunicatesimmediately
withalluserswhoareloggedin.Itworkssimilarlytowrite,
exceptthatuserscannotusewalltowritebacktoonlyyou.Use
wallwhenyouareabouttobringthesystemdownorarein
anothercrisissituation.Userswhoarenotloggedinwillnotget
themessage.
UsewallwhileyouareSuperuseronlyinacrisissituation;it
interruptsanythinganyoneisdoing.
Email
Emailisusefulforcommunicatinglessurgentinformationto
oneormoresystemsand/orremoteusers.Whenyousend
mail,youhavetobewillingtowaitforeachusertoreadit.The
emailutilitiesareusefulforremindingusersthattheyare
forgettingtologout,theirbillsarepastdue,ortheyareusing
toomuchdiskspace.
Userscaneasilymakepermanentrecordsofmessagesthey
receiveviaemail,asopposedtomessagesreceivedviawrite,so
theycankeeptrackofimportantdetails.Itwouldbe
appropriatetouseemailtoinformusersaboutanew,complex
procedure,soeachusercouldkeepacopyoftheinformation
forreference.
Messageoftheday
Usersseethemessageofthedayeachtimetheyloginina
textualenvironment.Youcaneditthe/etc/motdfiletochange
thismessageasnecessary.Themessageofthedaycanalert
userstoupcomingperiodicmaintenance,newsystemfeatures,
orachangeinprocedures.
CreatingProblems
Evenexperiencedsystemadministratorsmakemistakes;new
systemadministratorsjustmakemoremistakes.Althoughyou
canimproveyouroddsofavoidingproblemsbycarefully
readingandfollowingthedocumentationprovidedwith
software,manythingscanstillgowrong.Acomprehensivelist
isnotpossible,nomatterhowlong,asnewandexcitingways
tocreateproblemsarediscoveredeveryday.Afewofthemore
commontechniquesaredescribedhere.
FailingtoPerformRegularBackups
Fewfeelingsaremorepainfultoasystemadministratorthan
realizingthatimportantinformationislostforever.Ifyour
systemsupportsmultipleusers,havingarecentbackupmaybe
youronlyprotectionfromapubliclynching.Ifitisasingle-user
system,havingarecentbackupcertainlykeepsyouhappier
whenyouloseaharddisk.
NotReadingandFollowingInstructions
Softwaredevelopersprovidedocumentationforareason.Even
whenyouhaveinstalledasoftwarepackagebefore,carefully
readtheinstructionsagain.Theymayhavechanged,oryou
maysimplyrememberthemincorrectly.Softwarechangesmore
quicklythanbooksarerevised,sonobookshouldbetakenas
offeringfoolproofadvice.Instead,lookforthelatest
documentationonline.
FailingtoAskforHelpWhenInstructionsAre
NotClear
Ifsomethingdoesnotseemtomakesense,trytofindoutwhat
doesmakesensedonotguess.Referto"Help"onpage977.
DeletingorMistypingaCriticalFile
Onesurewaytogiveyourselfnightmaresistoexecutethe
command
##rmrf/etc donotdothis
PerhapsnoothercommandrendersaLinuxsystemuselessso
quickly.Theonlyrecourseistorebootintorescuemode(page
397)usingthefirstinstallationCDandrestorethemissingfiles
fromarecentbackup.Althoughthisexampledepictsan
extremecase,manyfilesarecriticaltoproperoperationofa
system.Deletingoneofthesefilesormistypinginformationin
oneofthemisalmostcertaintocauseproblems.Ifyoudirectly
edit/etc/passwd,forexample,enteringthewrong
informationinafieldcanmakeitimpossibleforoneormore
userstologin.Donotusermrfwithanargumentthat
includeswildcardcharacters;dopauseaftertypingthe
command,andreaditbeforeyoupressRETURN.Check
everythingyoudocarefully,andmakeacopyofacriticalfile
beforeyoueditit.
Caution:Becarefulwhenusinga
wildcardcharacterwithrm
Whenyoumustuseawildcardcharacter,suchas*,
inanargumenttoanrmcommand,firstuseecho
withthesameargumenttoseeexactlywhichfiles
youwillbedeleting.Thischeckisespecially
importantwhenyouareworkingasroot.
SolvingProblems
Asthesystemadministrator,itisyourresponsibilitytokeepthe
systemsecureandrunningsmoothly.Whenauserishavinga
problem,itusuallyfallstotheadministratortohelptheuserget
backontrack.Thissectionsuggestswaystokeepusershappy
andthesystemfunctioningatpeakperformance.
HelpingWhenaUserCannotLogIn
Whenauserhastroublelogginginonthesystem,thesource
maybeausererrororaproblemwiththesystemsoftwareor
hardware.Thefollowingstepscanhelpdeterminewherethe
problemis:
Determinewhetheronlythatoneuseroronlythatone
user'sterminal/workstationhasaproblemorwhetherthe
problemismorewidespread.
Checkthattheuser'sCapsLockkeyisnoton.
Makesuretheuser'shomedirectoryexistsandcorresponds
tothatuser'sentryinthe/etc/passwdfile.Verifythatthe
userownshisorherhomedirectoryandstartupfilesand
thattheyarereadable(and,inthecaseofthehome
directory,executable).Confirmthattheentryfortheuser's
loginshellinthe/etc/passwdfileisvalid(thatis,the
entryisaccurateandtheshellexistsasspecified).
Changetheuser'spasswordifthereisachancethatheor
shehasforgottenthecorrectpassword.
Checktheuser'sstartupfiles(.profile,.login,.bashrc,
andsoon).Theusermayhaveeditedoneofthesefilesand
introducedasyntaxerrorthatpreventslogin.
Checktheterminalormonitordatacablefromwhereit
plugsintotheterminaltowhereitplugsintothecomputer
(orasfarasyoucanfollowit).Tryturningtheterminalor
monitoroffandthenturningitbackon.
Whentheproblemappearstobewidespread,check
whetheryoucanloginfromthesystemconsole.Ifyoucan,
makesurethatthesystemisinmultiusermode.Ifyou
cannotlogin,thesystemmayhavecrashed;rebootitand
performanynecessaryrecoverysteps(thesystemusually
doesquiteabitautomatically).
Checkthatthe/etc/inittabfileissetuptostartmingettyat
runlevels25.
Checkthe/var/log/messagesfile.Thisfileaccumulates
systemerrors,messagesfromdaemonprocesses,and
otherimportantinformation.Itmayindicatethecauseor
moresymptomsofaproblem.Also,checkthesystem
console.Occasionallymessagesaboutsystemproblemsthat
arenotwrittento/var/log/messages(forinstance,afull
disk)aredisplayedonthesystemconsole.
Iftheuserislogginginoveranetworkconnection,run
system-config-services(page406)tomakesurethattheservice
theuseristryingtouse(suchastelnetorssh)isenabled.
Usedftocheckforfullfilesystems.Ifthe/tmpfilesystem
ortheuser'shomedirectoryisfull,loginsometimesfailsin
unexpectedways.Insomecasesyoumaybeabletologin
toatextualenvironmentbutnotagraphicalone.When
applicationsthatstartwhentheuserlogsincannotcreate
temporaryfilesorcannotupdatefilesintheuser'shome
directory,theloginprocessitselfmayterminate.
SpeedingUptheSystem
Whenthesystemisrunningslowlyfornoapparentreason,
perhapsaprocessdidnotexitwhenauserloggedout.
Symptomsofthisproblemincludepoorresponsetimeanda
systemload,asshownbyworuptime,thatisgreaterthan1.0.
Runningtop(page550)isanexcellentwaytoquicklyfindrogue
processes.Usepseftolistallprocesses.Onethingtolookfor
inpsefoutputisalargenumberintheTIMEcolumn.For
example,ifaFirefoxprocesshasaTIMEfieldover100.0,this
processhaslikelyrunamok.However,iftheuserisdoingalot
ofJavaworkandhasnotloggedoutforalongtime,thisvalue
maybenormal.LookattheSTIMEfieldtoseewhenthe
processwasstarted.Iftheprocesshasbeenrunningforlonger
thantheuserhasbeenloggedin,itisagoodcandidatetobe
killed.
Whenausergetsstuckandleavesherterminalunattended
withoutnotifyinganyone,itisconvenienttokill(page395)all
processesownedbythatuser.Iftheuserisrunningawindow
system,suchasGNOMEorKDEontheconsole,killthewindow
managerprocess.Managerprocessestolookforinclude
startkde,gnome-session,oranotherprocessnamethatends
inwm.Usuallythewindowmanageriseitherthefirstorthe
lastthingtoberun,andexitingfromthewindowmanagerlogs
theuserout.Ifkillingthewindowmanagerdoesnotwork,try
killingtheXserverprocessitself.Thisprocessistypicallylisted
as/usr/bin/Xorg.Ifthatfails,youcankillallprocesses
ownedbyauserbygivingthecommandkill11,or
equivalentlykillTERM1whileyouareloggedinasthatuser.
Using1(one)inplaceoftheprocessIDtellskillthatitshould
sendthesignaltoallprocessesthatareownedbythatuser.For
example,asrootyoucouldgivethefollowingcommand:
#sujenny-c'kill-TERM-1'
Ifthisdoesnotkillallprocesses(sometimesTERMdoesnotkill
aprocess),youcanusetheKILLsignal.Thefollowinglinewill
definitelykillallprocessesownedbyJennyandwillnotbe
friendlyaboutit:
#sujenny-c'kill-KILL-1'
(Ifyoudonotusesujennyc,thesamecommandbringsthe
systemdown.)
lsof:FindsOpenFiles
Thelsof(lsopenfiles)utilitylocatesopenfiles.Itsoptions
displayonlycertainprocesses,onlycertainfiledescriptorsofa
process,oronlycertainnetworkconnections(network
connectionsusefiledescriptorsjustasnormalfilesdoandlsof
canshowtheseaswell).Onceyouhaveidentifiedasuspect
processusingpsef,givethefollowingcommand:
#lsof-sppid
ReplacepidwiththeprocessIDofthesuspectprocess;lsof
displaysalistoffiledescriptorsthatprocesspidhasopen.Thes
optiondisplaysthesizesofallopenfiles.Thissizeinformation
ishelpfulindeterminingwhethertheprocesshasaverylarge
fileopen.Ifitdoes,contacttheowneroftheprocessor,if
necessary,killtheprocess.Thernoptionredisplaystheoutput
oflsofeverynseconds.
KeepingaMachineLog
AmachinelogthatincludestheinformationshowninTable16-3
(nextpage)canhelpyoufindandfixsystemproblems.Note
thetimeanddateforeachentryinthelog.Avoidthe
temptationtokeepthelogonlyonthecomputeritwillbemost
usefultoyouwhenthesystemisdown.Anothergoodideaisto
keeparecordofallemailaboutuserproblems.Onestrategyis
tosavethismailtoaseparatefileorfolderasyoureadit.
Anotherapproachistosetupamailaliasthatuserscansend
mailtowhentheyhaveproblems.Thisaliascanthenforward
mailtoyouandalsostoreacopyinanarchivefile.Followingis
anexampleofanentryinthe/etc/aliasesfile(page633)that
setsupthistypeofalias:
trouble:admin,/var/spool/mail/admin.archive
Table16-3.Machinelog
Entry Function
Hardware
modifications
Keeptrackofthesystemhardwareconfiguration:which
devicesholdwhichpartitions,themodelofthenewNIC
youadded,andsoon.
System
software
modifications
KeeptrackoftheoptionsusedwhenbuildingLinux.
Printsuchfilesas/usr/src/linux/.config(Linux
kernelconfiguration)andtheX11configurationfile
/etc/X11/xorg.conf.Thefilehierarchyunder
/etc/sysconfigcontainsvaluableinformationabout
networkconfiguration,amongotherthings.
Hardware
malfunctions
Keepasaccuratealistaspossibleofanyproblemswith
thesystem.Makenoteofanyerrormessagesor
numbersthatthesystemdisplaysonthesystem
consoleandidentifywhatusersweredoingwhenthe
problemoccurred.
User
complaints
Makealistofallreasonablecomplaintsmadeby
knowledgeableusers(forexample,"machineis
abnormallyslow").
Emailsenttothetroublealiaswillbeforwardedtotheadmin
userandalsostoredinthefile/var/mail/admin.archive.
KeepingtheSystemSecure
Nosystemwithdial-inlinesorpublicaccesstoterminalsis
absolutelysecure.Youcanmakeasystemassecureaspossible
bychangingtheSuperuserpasswordfrequentlyandchoosing
passwordsthataredifficulttoguess.Donottellanyonewho
doesnotabsolutelyneedtoknowtheSuperuserpassword.You
canalsoencouragesystemuserstochoosedifficultpasswords
andtochangethemperiodically.
Bydefault,passwordsonRedHatLinuxuseMD5(page1042)
hashing,whichmakesthemmoredifficulttobreakthan
passwordsencryptedwithDES(page990).Itmakeslittle
differencehowwellencryptedyourpasswordisifyoumakeit
easyforsomeonetofindoutorguesswhatitis.
Apasswordthatisdifficulttoguessisonethatsomeoneelse
wouldnotbelikelytothinkyouwouldhavechosen.Donotuse
wordsfromthedictionary(spelledforwardorbackward);
namesofrelatives,pets,orfriends;orwordsfromaforeign
language.Agoodstrategyistochooseacoupleofshortwords,
includesomepunctuation(forexample,puta^between
them),mixthecase,andreplacesomeofthelettersinthe
wordswithnumbers.Ifitwerenotprintedinthisbook,an
exampleofagoodpasswordwouldbeC&yGram5
(candygrams).Ideallyyouwouldusearandomcombinationof
ASCIIcharacters,butthatwouldbedifficulttoremember.
Youcanuseoneofseveralexcellentpassword-cracking
programstofinduserswhohavechosenpoorpasswords.These
programsworkbyrepeatedlyencryptingwordsfrom
dictionaries,phrases,names,andothersources.Ifthe
encryptedpasswordmatchestheoutputoftheprogram,then
theprogramhasfoundthepasswordoftheuser.Aprogram
thatcrackspasswordsiscrack.Itandmanyotherprogramsand
securitytipsareavailablefromCERT(www.cert.org),whichwas
originallycalledtheComputerEmergencyResponseTeam.
Specificallylookatwww.cert.org/tech_tips.
MakesurethatnooneexceptSuperusercanwritetofiles
containingprogramsthatareownedbyrootandruninsetuid
mode(forexample,mailandsu).Alsomakesurethatusersdo
nottransferprogramsthatruninsetuidmodeandareowned
byrootontothesystembymeansofmountingtapesordisks.
Theseprogramscanbeusedtocircumventsystemsecurity.
Onetechniquethatpreventsusersfromhavingsetuidfilesisto
usethenosuidflagtomount,whichyoucansetintheflags
sectioninthefstabfile.Referto"fstab:KeepsTrackof
Filesystems"onpage469.
TheBIOSinmanymachinesgivesyousomedegreeof
protectionfromanunauthorizedpersonmodifyingtheBIOSor
rebootingthesystem.WhenyousetuptheBIOS,lookfora
sectionnamedSecurity.YoucanprobablyaddaBIOS
password.IfyoudependontheBIOSpassword,lockthe
computercase.ItisusuallyasimplemattertoresettheBIOS
passwordbyusingajumperonthemotherboard.
LogFilesandMailforroot
Usersfrequentlyemailrootandpostmastertocommunicate
withthesystemadministrator.Ifyoudonotforwardroot'smail
toyourself(/etc/aliasesonpage633),remembertocheck
root'smailperiodically.Youwillnotreceiveremindersabout
mailthatarrivesforrootwhenyouusesutoperformsystem
administrationtasks.However,afteryouusesutobecomeroot,
youcangivethecommandmailuroottolookatroot'smail.
Reviewthesystemlogfilesregularlyforevidenceofproblems.
Twoimportantfilesare/var/log/messages,wherethe
operatingsystemandsomeapplicationsrecorderrors,and
/var/log/maillog,whichcontainserrorsfromthemail
system.
Thelogwatchutility(/usr/sbin/logwatchpointstothePerl
scriptnamed/usr/share/logwatch/scripts/logwatch.pl)is
areportwriterthatsendsemailreportsonlogfiles.Bydefault,
thisscriptisrundaily(/etc/cron.daily/0logwatchpointsto
thesamePerlscript)andemailsitsoutputtoroot.Refertothe
logwatchmanpageandtothescriptitselfformoreinformation.
MonitoringDiskUsage
Soonerorlateryouwillprobablystarttorunoutofdiskspace.
Donotfillupadisk;Linuxcanwritetofilessignificantlyfaster
ifatleast5to30percentofthediskspaceinagivenfilesystem
remainsfree.Usingmorethanthemaximumoptimaldiskspace
inafilesystemcandegradesystemperformance.
Fragmentation
Asafilesystembecomesfull,itcanbecomefragmented.Thisis
similartotheDOSconceptoffragmentationbutisnotnearlyas
pronouncedandistypicallyrareonmodernLinuxfilesystems;
bydesignLinuxfilesystemsareresistanttofragmentation.Keep
filesystemsfromrunningnearfullcapacity,andyoumaynever
needtoworryaboutfragmentation.Ifthereisnospaceona
filesystem,youcannotwritetoitatall.
Tocheckforfilesystemfragmentation,unmountthefilesystem
andrunfsckonit.Theoutputoffsckincludesapercent
fragmentationfigureforthefilesystem.Youcandefragmenta
filesystembybackingitup,usingmkfs(page419)tomakea
clean,emptyimage,andthenrestoringthefilesystem.Which
utilityyouusetodothebackupandrestoredump/restore,tar,cpio,
orathird-partybackupprogramisirrelevant.
Reports
Linuxprovidesseveralprogramsthatreportonwhoisusing
howmuchdiskspaceonwhichfilesystems.Refertothedu,
quota,anddfmanpagesandthesizeoptioninthefindutilityman
page.Inadditiontotheseutilities,youcanusethediskquota
systemtomanagediskspace.
Fourstrategiestoincreasetheamountoffreespaceona
filesystemaretocompressfiles,deletefiles,growLVM-based
filesystems,andcondensedirectories.Thissectioncontains
someideasonwaystomaintainafilesystemsothatitdoesnot
becomeoverloaded.
Filesthatgrowquickly
Somefiles,suchaslogfilesandtemporaryfiles,growover
time.Coredumpfiles,forexample,takeupsubstantialspace
andarerarelyneeded.Also,usersoccasionallyrunprograms
thataccidentallygeneratehugefiles.Asthesystem
administrator,youmustreviewthesefilesperiodicallysothat
theydonotgetoutofhand.
Ifafilesystemisrunningoutofspacequickly(thatis,overa
periodofanhourratherthanweeksormonths),firstfigureout
whyitisrunningoutofspace.Useapsefcommandto
determinewhetherauserhascreatedarunawayprocessthat
iscreatingahugefile.Whenevaluatingtheoutputofps,look
foraprocessthathasconsumedalargeamountofCPUtime.If
suchaprocessisrunningandcreatingalargefile,thefilewill
continuetogrowasyoufreeupspace.Ifyouremovethehuge
file,thespaceitoccupiedwillnotbefreeduntiltheprocess
terminates,soyouneedtokilltheprocess.Trytocontactthe
userrunningtheprocess,andasktheusertokillit.Ifyou
cannotcontacttheuser,loginasrootandkilltheprocess
yourself.Refertokillonpage395formoreinformation.
Youcanalsotruncatealargelogfileratherthanremovingit,
althoughyoucanbetterdealwiththisrecurringsituationwith
logrotate(discussedinthenextsection).Forexample,ifthe
/var/log/messagesfilehasbecomeverylargebecausea
systemdaemonismisconfigured,youcanuse/dev/nullto
truncateit:
#cp/dev/null/var/log/messages
or
#cat/dev/null>/var/log/messages
or,withoutspawninganewprocess,
#:>/var/log/messages
Ifyouremove/var/log/messages,youhavetorestartthe
syslogddaemon.Ifyoudonotrestartsyslogd,thespaceon
thefilesystemisnotreleased.
Whennosingleprocessisconsumingthediskspacebut
capacityhasinsteadbeenusedupgradually,locateunneeded
filesanddeletethem.Youcanarchivethesefilesbyusingcpio,
dump,ortarbeforeyoudeletethem.Youcansafelyremovemost
filesnamedcorethathavenotbeenaccessedforseveraldays.
Thefollowingcommandlineperformsthisfunctionwithout
removingnecessaryfilesnamedcore(suchas/dev/core):
[Viewfullwidth]
#find/-typef-namecore|xargsfile|grep'Bcorefile'|sed's/:ELF.
rm-f
Thefindcommandlistsallordinaryfilesnamedcoreandsends
itsoutputtoxargs,whichrunsfileoneachofthefilesinthelist.
ThefileutilitydisplaysastringthatincludesBcorefileforfiles
createdastheresultofacoredump.Thesefilesneedtobe
removed.Thegrepcommandfiltersoutfromfilelinesthatdo
notcontainthisstring.Finallysedremoveseverythingfollowing
thecolonsothatallthatisleftonthelineisthepathnameof
thecorefile;xargsremovesthefile.
Tofreeupmorediskspace,lookthroughthe/tmpand
/var/tmpdirectoriesforoldtemporaryfilesandremovethem.
Keeptrackofdiskusagein/var/mail,/var/spool,and
/var/log.
logrotate:ManagesLogFiles
Ratherthandeletingortruncatinglogfiles,youmaywantto
keepthesefilesforawhileincaseyouneedtorefertothem.
Thelogrotateutilityhelpsyoumanagesystemlog(andother)
filesautomaticallybyrotating(page1053),compressing,
mailing,andremovingeachasyouspecify.Thelogrotateutilityis
controlledbythe/etc/logrotate.conffile,whichsetsdefault
valuesandcanoptionallyspecifyfilestoberotated.Typically,
logrotate.confhasanincludestatementthatpointstoutility-
specificspecificationfilesin/etc/logrotate.d.Followingisthe
defaultlogrotate.conffile:
$cat/etc/logrotate.conf
#see"manlogrotate"fordetails
#rotatelogfilesweekly
weekly
#keep4weeksworthofbacklogs
rotate4
#createnew(empty)logfilesafterrotatingoldones
create
#uncommentthisifyouwantyourlogfilescompressed
#compress
#RPMpackagesdroplogrotationinformationintothisdirectory
include/etc/logrotate.d
#nopackagesownwtmp--we'llrotatethemhere
/var/log/wtmp{
monthly
create0664rootutmp
rotate1
}
#system-specificlogsmaybealsobeconfiguredhere.
Thelogrotate.conffilesetsdefaultvaluesforcommon
parameters.Wheneverlogrotatereadsanothervalueforoneof
theseparameters,itresetsthedefaultvalue.Youhaveachoice
ofrotatingfilesdaily,weekly,ormonthly.Thenumber
followingtherotatekeywordspecifiesthenumberofrotated
logfilesthatyouwanttokeep.Thecreatekeywordcauses
logrotatetocreateanewlogfilewiththesamenameand
attributesasthenewlyrotatedlogfile.Thecompresskeyword
(commentedoutinthedefaultfile)causeslogfilestobe
compressedusinggzip.Theincludekeywordspecifiesthe
standard/etc/logrotate.ddirectoryforprogram-specific
logrotatespecificationfiles.Whenyouinstallaprogramusingrpm
(page487)oranrpm-basedutilitysuchasyum(page476),rpm
putsthelogrotatespecificationfileinthisdirectory.
Thelastsetofinstructionsinlogrotate.conftakescareofthe
/var/log/wtmplogfile(wtmpholdsloginrecords;youcan
viewthisfilewiththecommandwho/var/log/wtmp).The
keywordmonthlyoverridesthedefaultvalueofweeklyfor
thisutilityonly(becausethevalueiswithinbrackets).The
createkeywordisfollowedbytheargumentsestablishingthe
permissions,owner,andgroupforthenewfile.Finallyrotate
establishesthatonerotatedlogfileshouldbekept.
The/etc/logrotate.d/cupsfileisanexampleofautility-
specificlogrotatespecificationfile:
$cat/etc/logrotate.d/cups
/var/log/cups/*_log{
missingok
notifempty
sharedscripts
postrotate
/etc/init.d/cupscondrestart>/dev/null2>&1||true
endscript
}
Thisfile,whichisincorporatedin/etc/logrotate.dbecauseof
theincludestatementinlogrotate.conf,workswitheachof
thefilesin/var/log/cupsthathasafilenamethatendsin
_log(*_log).Themissingokkeywordmeansthatnoerror
willbeissuedwhenthefileismissing.Thenotifempty
keywordcauseslogrotatenottorotatethelogfileifitisempty,
overridingthedefaultactionofrotatingemptylogfiles.The
sharedscriptskeywordcauseslogrotatetoexecutethe
command(s)intheprerotateandpostrotatesectionsone
timeonlynotonetimeforeachlogthatisrotated.Althoughit
doesnotappearinthisexample,thecopytruncatekeyword
causeslogrotatetotruncatetheoriginallogfileimmediatelyafter
itcopiesit.Thiskeywordisusefulforprogramsthatcannotbe
instructedtocloseandreopentheirlogfilesbecausetheymight
continuewritingtotheoriginalfileevenafterithasbeen
moved.Thelogrotateutilityexecutesthecommandsbetween
prerotateandendscriptbeforetherotationbegins.Similarly,
commandsbetweenpostrotateandendscriptareexecuted
aftertherotationiscomplete.
Thelogrotateutilityhasmanykeywords,manyofwhichtake
argumentsandhavesideeffects.Refertothelogrotatemanpage
fordetails.
RemovingUnusedSpacefromDirectories
Adirectorythatcontainstoomanyfilenamesisinefficient.The
pointatwhichadirectoryonanext2orext3filesystem
becomesinefficientvaries,dependingpartlyonthelengthof
thefilenamesitcontains.Keepdirectoriesrelativelysmall.
Havingfewerthanseveralhundredfiles(ordirectories)ina
directoryisgenerallyagoodidea,andhavingmorethan
severalthousandisgenerallyabadidea.Additionally,Linux
usesacachingmechanismforfrequentlyaccessedfilesto
speedtheprocessoflocatinganinodefromafilename.This
cachingmechanismworksonlyonfilenamesofupto30
charactersinlength,soavoidgivingextremelylongfilenames
tofrequentlyaccessedfiles.
Whenadirectorybecomestoolarge,youcanusuallybreakit
intoseveralsmallerdirectoriesbymovingitscontentstothose
newdirectories.Makesurethatyouremovetheoriginal
directoryonceyouhavemovedallofitscontents.
BecauseLinuxdirectoriesdonotshrinkautomatically,removing
afilefromadirectorydoesnotshrinkthedirectory,even
thoughitfreesupspaceonthedisk.Toremoveunusedspace
andmakeadirectorysmaller,youmustcopyormoveallthe
filestoanewdirectoryandremovetheoriginaldirectory.
Thefollowingprocedureremovesunuseddirectoryspace.First
removeallunneededfilesfromthelargedirectory.Thencreate
anew,emptydirectory.Nextmoveorcopyallremainingfiles
fromtheoldlargedirectorytothenewemptydirectory.
Remembertocopyhiddenfiles.Finally,deletetheolddirectory
andrenamethenewdirectory.
#mkdir/home/alex/new
#mv/home/alex/large/*/home/alex/large/.[A-z]*/home/alex/new
#rmdir/home/alex/large
#mv/home/alex/new/home/alex/large
Optional:DiskQuotaSystem
Thediskquotasystemlimitsthediskspaceandnumberoffilesownedby
individualusers.Youcanchoosetolimiteachuser'sdiskspace,thenumberof
fileseachusercanown,orboth.Eachresourcethatislimitedhastwolimits.The
lowerlimit,orquota,canbeexceededbytheuser,althoughawarningisgiven
eachtimetheuserlogsinwhenheisabovethequota.Afteracertainnumberof
warnings(setbythesystemadministrator),thesystemwillbehaveasiftheuser
hadreachedtheupperlimit.Oncetheupperlimitisreachedortheuserhas
receivedthespecifiednumberofwarnings,theuserwillnotbeallowedtocreate
anymorefilesoruseanymorediskspace.Theuser'sonlyrecourseatthatpoint
istoremovesomefiles.
Userscanreviewtheirusageandlimitswiththequotautility.Superusercanuse
quotatoobtaininformationaboutanyuser.
Firstyoumustdecidewhichfilesystemstolimitandhowtoallocatespaceamong
users.Typicallyonlyfilesystemsthatcontainusers'homedirectories,suchas
/home,arelimited.Usetheedquotautilitytosetthequotas,andthenusequotaon
tostartthequotasystem.Youwillprobablywanttoputaquotaoncommandinto
theappropriateinitscriptsothatthequotasystemwillbeenabledwhenyou
bringupthesystem(page404).Unmountingafilesystemautomaticallydisables
thequotasystemforthatfilesystem.
syslogd:LogsSystemMessages
TraditionallyUNIXprogramssentlogmessagestostandard
error.Ifamorepermanentlogwasrequired,theoutputwas
redirectedtoafile.Becauseofthelimitationsofthisapproach,
4.3BSDintroducedthesystemlogdaemon(syslogd)nowused
byLinux.Thisdaemonlistensforlogmessagesandstoresthem
inthe/var/loghierarchy.Inadditiontoprovidinglogging
facilities,syslogdallowsasinglemachinetoserveasalog
repositoryforanetworkandallowsarbitraryprogramsto
processspecificlogmessages.
syslog.conf
The/etc/syslog.conffilestoresconfigurationinformationfor
syslogd.Eachlineinthisfilecontainsoneormoreselectors
andanaction,separatedbywhitespace.Theselectorsdefine
theoriginandtypeofthemessages;theactionspecifieshow
syslogdistoprocessthemessage.Samplelinesfrom
syslog.conffollow(a#indicatesacomment):
#Logallkernelmessagestotheconsole.
kern.*/dev/console
#Logallthemailmessagesinoneplace.
mail.*/var/log/maillog
#Logcronstuff
cron.*/var/log/cron
#Everybodygetsemergencymessages
*.emerg*
#Savebootmessagesalsotoboot.log
local7.*/var/log/boot.log
Selectors
Aselectorissplitintotwoparts,afacilityandapriority,which
areseparatedbyaperiod.Thefacilityindicatestheoriginofthe
message.Forexample,kernmessagescomefromthekernel
andmailmessagescomefromthemailsubsystem.Followingis
alistoffacilitynamesusedbysyslogdandthesystemsthat
generatethesemessages:
auth Authorizationandsecuritysystemsincludinglogin
authpriv Sameasauth,butshouldbeloggedtoasecure
location
cron cron
daemon Systemandnetworkdaemonswithouttheirown
categories
kern Kernel
lpr Printingsubsystem
mail Mailsubsystem
news Networknewssubsystem
user Defaultfacility;alluserprogramsusethisfacility
uucp TheUNIX-to-UNIXcopyprotocolsubsystem
local0to
local7
Reservedforlocaluse
Thepriorityindicatestheseverityofthemessage.Thefollowing
listoftheprioritynamesandtheconditionstheyrepresentisin
priorityorder:
debug Debugginginformation
info Informationthatdoesnotrequireintervention
notice Conditionsthatmayrequireintervention
warning Warnings
err Errors
crit Criticalconditionssuchashardwarefailures
alert Conditionsthatrequireimmediateattention
emerg Emergencyconditions
Aselectorconsistingofasinglefacilityandpriority,suchas
kern.info,causesthecorrespondingactiontobeappliedto
everymessagefromthatfacilitywiththatpriorityorhigher
(moreurgent).Use.=tospecifyasinglepriority;forexample,
kern.=infoappliestheactiontokernelmessagesofinfo
priority.Anexclamationpointspecifiesthatapriorityisnot
matched,sokern.!infomatcheskernelmessageswitha
prioritylowerthaninfoandkern.!=infomatcheskernel
messageswithapriorityotherthaninfo.
Alinewithmultipleselectors,separatedbysemicolons,applies
theactionifanyoftheselectorsismatched.Eachofthe
selectorsonalinewithmultipleselectorsconstrainsthematch,
withsubsequentselectorsfrequentlytighteningtheconstraints.
Forexample,theselectorsmail.info;mail.!errmatchmail
subsystemmessageswithinfo,notice,orwarningpriorities.
Youcanreplaceeitherpartoftheselectorwithanasteriskto
matchanything.Thekeywordnoneineitherpartofthe
selectorindicatesnomatchispossible.Theselector
*.crit;kern.nonematchesallcriticalorhigher-priority
messages,exceptthosefromthekernel.
Actions
Theactionspecifieshowsyslogdprocessesamessagethat
matchestheselector.Thesimplestactionsareordinaryfiles,
whicharespecifiedbytheirabsolutepathnames;syslogd
appendsmessagestothesefiles.Specify/dev/consoleifyou
wantmessagessenttothesystemconsole.Ifyouwanta
hardcopyrecordofmessages,youcanspecifyadevicefilethat
representsadedicatedprinter.
Youcanwriteimportantmessagestoaspecificuser'sterminal
byspecifyingausername,suchasroot,oracomma-separated
listofusernames.Veryimportantmessagescanbewrittento
everylogged-interminalbyusinganasterisk.
Toforwardmessagestosyslogdonaremotesystem,specify
thenameofthesystemprecededby@.Itisagoodideato
forwardcriticalmessagesfromthekerneltoanothersystem
becausethesemessagesoftenprecedeasystemcrashandmay
notbesavedtothelocaldisk.Thefollowinglinefrom
syslog.confsendscriticalkernelmessagestogrape:
kern.crit@grape
Becausesyslogdisnotconfiguredbydefaulttoenablelogging
overthenetwork,youmusteditthe/etc/sysconfig/syslog
fileontheremotesystem(grapeinthiscase)sothatsyslogd
isstartedwiththeroption.Afteryoumodifythesyslogfile,
restartsyslogdusingthesysloginitscript.
ChapterSummary
Thesystem-config-usersutilityaddsnewusersandgroupstothe
systemandmodifiesexistingusers'accounts.Youcanalsouse
theequivalentcommandlinetools(useradd,usermod,userdel,
groupadd,andgroupmod)toworkwithuseraccounts.Backingup
filesonthesystemisacriticalandoftenoverlookedpartof
systemadministration.Linuxincludesthetar,cpio,dump,and
restoreutilitiestobackupandrestorefiles.Youcanalsouse
moresophisticatedpackagessuchasamandaandvarious
commercialproducts.
Thesystemschedulingdaemon,cron,periodicallyexecutes
scheduledtasks.Youcanscheduletasksusingcrontab,at,and
KDE'skcron.Systemreportspresentinformationonthehealth
ofthesystem.Twousefultoolsthatgeneratethesereportsare
vmstat,whichdetailsvirtualmemory,I/O,andCPUstatistics,
andtop,whichreportsonhowthesystemisperformingfrom
momenttomomentandcanhelpyoufigureoutwhatmightbe
slowingitdown.
Anotheraspectofsystemadministrationissolvingproblems.
Linuxincludesseveraltoolsthatcanhelpyoutrackdown
systemproblems.Oneofthemostimportantofthesetoolsis
syslogd,thesystemlogdaemon.Using/etc/syslogd.conf,
youcancontrolwhicherrormessagesappearontheconsole,
whicharesentasemail,andwhichgotooneofseverallog
files.
Exercises
1. Howwouldyoulistalltheprocessesrunningvi?
2. Howwouldyouusekilltocauseaserverprocesstorereaditsconfigurationfiles?
3. Fromthecommandline,howwouldyoucreateausernamedJohnDoewhohas
theusernamejdandwhobelongstogroup65535?
4. Howwouldyounotifytheusersofthesystemthatyouaregoingtorebootthe
systemin10minutes?
5.
Giveacommandthatwillcreatealevel0dumpofthe/usrfilesystemonthefirst
tapedeviceonthesystem.Whichcommandwouldyouusetotakeadvantageofa
drivethatsupportscompression?Whichcommandwouldplacealevel3dumpof
the/varfilesystemimmediatelyafterthelevel0dumponthetape?
AdvancedExercises
6. Ifthesystemislessresponsivethannormal,whatisagoodfirststepinfiguring
outwheretheproblemis?
7. AprocessstoresitsPIDinafilenamedprocess.pid.Writeacommandlinethat
willterminatetheprocess.
8.
Workingasroot,youareplanningtodeletesomefilesbutwanttomakesurethat
thewildcardexpressionyouwilluseiscorrect.Suggesttwowaysyoucouldmake
surethatyoudeletedthecorrectfiles.
9.
Createacronfilethatwillregularlyperformthefollowingbackups:
a. Performsalevel0backuponcepermonth.
b. Performsalevel2dumponedayperweek.
c. Performsalevel5dumpeverydaythatneitheralevel0noralevel2dump
isperformed.
Intheworstcase,howmanyrestoreswouldyouhavetoperformtorecoverafile
thatwasdumpedusingtheprecedingschedule?
17.ConfiguringaLAN
INTHISCHAPTER
SettingUptheHardware 568
GatewaysandRouters 569
NIC:NetworkInterfaceCard 569
ConfiguringtheSystems 570
system-config-network:ConfigurestheHardware 571
iwconfig:ConfiguresaWirelessNIC 572
SettingUpServers 574
Networksallowcomputerstocommunicateandshare
resources.Alocalareanetwork(LAN)connectscomputersat
onesite,suchasanoffice,home,orlibrary,andcanallowthe
connectedcomputerstoshareanInternetconnectionanda
printer.Ofcourse,oneofthemostimportantreasonstosetup
aLANistoallowsystemstocommunicatewhileusersenjoy
multiplayergames.
ThischaptercoversthetwoaspectsofconfiguringaLAN:
settingupthehardwareandconfiguringthesoftware.This
chapterisnotnecessarilyorganizedintheorderyouwill
performthetasksinvolvedinsettingupaparticularLAN:Read
thechapterthrough,figureouthowyouwillsetupyourLAN,
andthenreadthepartsofthechapterintheorderappropriate
toyoursetup.
SettingUptheHardware
Eachsystem,ornode,onaLANmusthaveanetworkinterface
card(NIC).NICscanbeconnectedtothenetworkwithcables
orradiowaves(wireless);ineithercase,eachsystemmust
connecttoacentralhub.Ifthenetworkisconnectedtoanother
network,suchastheInternet,itmustalsohavearouter,or
gateway.Theroutercanbeeitheroneofthesystemsonthe
LANoradedicatedpieceofhardware.
ConnectingtheComputers
AmodernEthernet-basedLANhasaconnectionbetweeneach
computerandacentralhub.Twokindsofhubsexist:passive
(sometimesjustcalledahub)andswitching(calledaswitch).A
passivehubsimplyconnectsallsystemstogetherandshares
thenetworkbandwidthamongthesystems.Aswitchinghub
putseachsystemonitsownnetworkwiththeswitchandroutes
packetsbetweenthosenetworks,providingeachsystemwith
thefullnetworkbandwidth.
InthesimplenetworkshowninFigure17-1,fourcomputersare
connectedtoasinglehub.Assumingthehubispassive,when
computers1and2arecommunicatingatthesametimeas
computers3and4,eachconversationislimitedtoamaximum
ofhalfthenetworkbandwidth.Ifthehubwereaswitch,each
conversationcouldusethefullnetworkbandwidth.
Figure17-1.Asimplenetwork
Usuallyhubsarelessexpensivethanswitches.Ifyouplanto
usethenetworkforsharinganInternetconnectionandlightfile
sharing,ahubislikelytobefastenough.Ifsystemsonthe
networkwillexchangefilesregularly,aswitchmaybemore
appropriate.Referto"Ethernet"onpage347foradiscussionof
switches,hubs,andcables.
EachcomputeronaLANmustbeconnectedtothehub.Ifyou
areusingusemorethanonehub,connecttheportlabeled
uplinkononetoanormalportonanother.
Wirelessaccesspoint(WAP)
Awirelessaccesspoint(WAP)connectsawirelessnetworktoa
wiredone.TypicallyaWAPactsasatransparentbridge,
forwardingpacketsbetweenthetwonetworksasiftheywere
one.IfyouconnectmultipleWAPsindifferentlocationstothe
samewirednetwork,wirelessclientscanroamtransparently
betweentheWAPs.
Wirelessnetworksdonotrequireahub,althoughaWAPcan
optionallyfillasimilarrole.Inawirelessnetwork,the
bandwidthissharedamongallnodeswithinrangeofone
another;themaximumspeedislimitedbytheslowestnode.
GatewaysandRouters
IftheLANyouaresettingupisconnectedtoanothernetwork,
suchastheInternet,youneedarouter,sometimescalleda
gateway.Aroutercanperformseveralfunctions,themost
commonofwhichisallowingseveralsystemstoshareasingle
InternetconnectionandIPaddress(NAT,page764).Whena
routerusesNAT,thepacketsfromeachsystemontheLAN
appeartocomefromasingleIPaddress;returnpacketsare
passedbacktothecorrectsystem.
Youhaveseveralchoicesforrouters:
Asimplehardwarerouterisrelativelycheapanddoesmost
thingsrequiredbyasmallnetwork.
YoucansetupaRedHatLinuxsystemasarouter.The
Linuxkernelcanuseiptables(page763)toroutepackets
betweennetworkadapters.
YoucanuseaLinuxdistributiontailoredforuseasarouter.
Forexample,SmoothWall(www.smoothwall.org)providesa
browser-basedconfigurationinthestyleofahardware
router.
NIC:NetworkInterfaceCard
Eachsystem'sNICmaybeaseparateEthernetcard(wiredor
wireless)oritmaybebuiltintothemotherboard.
SupportedNICs
LinuxsupportsmostwiredEthernetNICs.FewerwirelessNICs
aresupported.See"MoreInformation"onpage575for
references.
UnsupportedwirelessNICs
IfawirelessnetworkcardisnotsupportedunderLinuxdirectly,
youmaybeabletogetittoworkwithNdisWrapper
(ndiswrapper.sourceforge.net),whichusesWin32drivers.
NdisWrapperisakernelmodulethatprovidesasubsetofthe
WindowsnetworkdriverAPI.NoRedHatpackagecontainsthis
program.
Wirelessbridge
AnalternativetoawirelessNICisawirelessbridge.Awireless
bridgeforwardspacketsbetweenwiredandwirelessinterfaces,
eliminatingtheneedforwirelessdrivers.Thissimpledevicehas
anEthernetportthatplugsintoaNICandan802.11(wireless)
controller.Whilecarryingabridgearoundisusuallynotfeasible
formobileusers,itisaneasywaytomigrateadesktop
computertoawirelessconfiguration.
Mode
Wirelessnetworksoperateineitheradhocorinfrastructure
mode.Inadhocmode,individualnodesinthenetwork
communicatedirectlywitheachother.Ininfrastructuremode,
nodescommunicateviaaWAP(page569).Infrastructuremode
isgenerallymorereliableifthewirelessLANcommunicateswith
awiredLAN.
IfyoudonotwanttouseaWAP,itmaybepossibletosetupa
WLANcardsoitactsasaWAP;consulttheNIC/driver
documentationformoreinformation.
ConfiguringtheSystems
kudzu
Oncethehardwareisinplace,youneedtoconfigureeach
systemsothatitknowsabouttheNICthatconnectsittothe
network.Normallykudzu,theRedHatutilitythatdetectsand
configuresnewhardware,givesthesystemtheinformationit
needsabouttheNIC.ThekudzuutilityprobestheNICwhenyou
installRedHatLinuxorthefirsttimeyoubootthesystemafter
youinstallaNIC.
Youcanusesystem-config-network(discussedinthenextsection)
toaugmenttheinformationkudzucollectsandtoactivatethe
NIC.Whenitpromptsyouforinformation,kudzuallowsyouto
specifyonlyonenameserver.Itisagoodideatospecifyatleast
twoorthreenameservers;youcanusesystem-config-networkto
addadditionalnameservers.
Systeminformation
InadditiontoinformationabouttheNIC,eachsystemneeds
thefollowinginformation:
Thesystem'sIPaddress
Thenetmask(subnetmask)forthesystem'saddress
(pages357and423)
TheIPaddressofthegateway
TheIPaddressesofthenameservers(DNSaddresses)
Thesystem'shostname(setwhenyouinstallRedHat
Linux)
IfyousetupaDHCPserver(page431)todistributenetwork
configurationinformationtosystemsontheLAN,youdonot
needtospecifytheprecedinginformationoneachsystem;you
justspecifythatthesystemisusingDHCPtoobtainthis
information.Youneedtospecifythisinformationwhenyouset
uptheDHCPserver.
Privateaddressspace
WhenyousetupaLAN,theIPaddressesofthesystemsonthe
LANaregenerallynotmadepublicontheInternet.Some
specialIPaddresses,partoftheprivateaddressspacedefined
byIANA(page1036),arereservedforprivateuseandare
appropriatetouseonaLAN(Table17-1).Unlessyouhavebeen
assignedIPaddressesforthesystemsontheLAN,choose
addressesfromtheprivateaddressspace.
Table17-1.PrivateIPranges(definedinRFC1918)
RangeofIPaddresses FromIPaddress ToIPaddress
10.0.0.0/8 10.0.0.1 10.255.255.254
172.16.0.0/12 172.16.0.1 172.31.255.254
192.168.0.0/16 192.168.0.1 192.168.255.254
system-config-network:ConfigurestheHardware
Thesystem-config-networkutilityconfiguresnetworkhardware.To
displaytheNetworkConfigurationwindow(Figure17-2),enter
system-config-networkonacommandline.FromKDEselect
Mainmenu:System Administration Networkorfrom
GNOMEselectSystem:Administration Network.The
NetworkConfigurationwindowhastabstospecifyhosts
(/etc/hosts,page452)andDNSservers(/etc/resolv.conf,
page455),aswellastoconfigurenetworkhardwareandlogical
devicesassociatedwiththehardware.
Figure17-2.TheNetworkConfigurationwindow,
Devicestab
Addingadevice
Normallykudzuidentifiesandaddsnewhardwaretothesystem.
Youcanthenusesystem-config-networktoedittheconfiguration
information.IfyouneedtoaddaNICtothesystemmanually,
clicktheDevicestab;thenclickNewonthetoolbar.Theutility
displaystheSelectDeviceTypewindow(Figure17-3).
Figure17-3.TheSelectDeviceTypewindow
TheSelectDeviceTypewindowcansetupsixtypesof
connections(mostofwhichdonotpertaintosettingupaLAN):
Ethernet(page347),ISDN(page1038),modem,tokenring
(page1060),wireless,andxDSL(page1064).ISDN,modem,
wireless,andxDSLarePPP(Point-to-PointProtocol)
connections.PPPisaseriallineprotocolthatestablishesa
connectionbetweentwosystems,puttingthemonthesame
network.Itiscapableofhandlingseveralprotocols,themost
commonofwhichisTCP/IP,whichprovidescompressionfor
increasedefficiency.Thetwosystemscanthenrunssh,X,or
anyothernetworkapplicationbetweenthem.Ethernetand
tokenringareusedtoconnecttoLANs.
Choosethetypeofconnectionyouwanttoestablishandclick
Forward.Someselectionsprobeforinformationatthispoint.
Youcanacceptentriesinthetextboxesthatarefilledininthe
followingwindow.Fillinblanktextboxesasappropriate.When
youhavefinishedsettingupthedevice,clickApply.TheSelect
DeviceTypewindowcloses,andtheNetworkConfiguration
windowdisplaysthedeviceyoujustadded.Followthe
instructionsinthenextparagraphtoedittheconfiguration
information.Ifyouarefinished,clicktheDevicestab,highlight
thenewdevice,clickMenubar:File Save,andclick
Activatetobringthenewdeviceonline.
Editingadevice
TheNetworkConfigurationwindow(Figure17-2)hasfourtabs,
twoofwhichpertaintohardwaredevicesandtwoofwhich
relatetothesystem.TheHoststabmodifiesthe/etc/hosts
file(page452)andtheDNStabmodifiesthesystem's
hostnameandthe/etc/resolv.conffile(page455).Make
changesinthesetabsasnecessary.
Tomodifytheconfigurationofnetworkhardware,suchasa
NIC,clicktheHardwaretab,highlightthedescriptionofthe
hardware,andclickEditonthetoolbar.Theutilitydisplaysthe
NetworkAdaptersConfigurationwindow.Inthiswindow,you
canchangethenameofthedevice(eth0,eth1,andsoon)
andtheresourcesituses.Typicallyyouwillchangeonlythe
name.ClickOKtoacceptthechangesandclosethewindow.
Tomodifythedevicerepresentedbyapieceofhardware,click
theDevicestab,highlightthedevice,andclickEditonthe
toolbar.Theutilitydisplaysawindowappropriatetothedevice
youareediting.Forexample,ifyouareworkingwithan
EthernetNIC,system-config-networkdisplaystheEthernetDevice
window(Figure17-4).
Figure17-4.TheEthernetDevicewindow
[Viewfullsizeimage]
Fromthiswindow,youcansetupthedevicetouseDHCPor
manuallyspecifythenecessaryIPaddresses.TheHardware
Devicetaballowsyoutoassociatethedevicewithapieceof
hardwareandspecifyaMACaddress(page1041).Whenyou
arefinishedmakingchanges,clickOK,clicktheDevicestab,
highlightthenewdevice,andclickMenubar:File Save.
Activatethedeviceifnecessary.
iwconfig:ConfiguresaWirelessNIC
YoucanconfigureawirelessNICusingeithersystem-config-network
(page571)oriwconfig.Theiwconfigutilityisbasedonifconfigand
configureselementsofawirelessNICnotsupportedbyifconfig,
suchassettingupMastermodeandbindingacardtoaWAP.
Themostcommonparametersyouwillchangewithiwconfigare
theencryptionkey,themode,andthenameofthenetwork.
Mostdevicessupportaminimumof40-bitWiredEquivalent
Privacy(WEP)encryption.Theencryptionkeyisdefinedbya
stringof10hexadecimaldigits.Thecontentsofthestringare
arbitrary,butmustbethesameonallnodes:
#iwconfigeth1key19FEB47A5B
ThealgorithmusedbyWEPisknowntobeflawed;usingitdoes
notgivemuchprotection.Ifyourequireprivacy,usean
encryptedprotocol,suchasSSHorHTTPS.Ifyouhavedifficulty
connecting,disableencryptiononallnodes:
#iwconfigeth1keyoff
Themodedefineswhetheryouareconnectingtoanadhocor
aninfrastructurenetwork.NormallyyoucansetmodetoAuto,
whichselectsthecorrectmodeautomatically:
#iwconfigeth1modeAuto
TheexceptionisifyouwanttousetheNICasaWAP,inwhich
caseyouneedtosetmodetoMaster:
#iwconfigeth1modeMaster
NotallwirelessNICsarecapableofactingasmasters.
ThenetworknameisdefinedbytheESSID(ExtendedService
SetID),anarbitrarystring.WiththeESSIDset(itmustbethe
sameoneverynode,includingtheWAP),youshouldbeableto
roambetweenanysetofnodeswiththesamenetworkname:
#iwconfigeth1essid"MyWirelessNetwork"
Seetheiwconfigmanpageformoreinformation.
SettingUpServers
SettinguplocalclientsandserverscanmakeaLANeasierto
useandmoreuseful.Thefollowinglistbrieflydescribessomeof
thesetoolsandreferencesthepagesthatdescribethemin
detail.
NISNIScanprovideauniformloginregardlessofwhich
systemyouloginon.TheNISauthenticationserveris
coveredonpage663andtheclientonpage659.NISis
oftencombinedwithhomedirectoriesmountedusingNFS.
NFSNFSallowsyoutosharedirectoryhierarchies.Sharing
directoriesusingNFSrequiresthattheserverexportthe
directoryhierarchy(page684)andtheclientsmountthe
hierarchy(page676).
UsingNFS,youcanstoreallhomedirectoriesonone
systemandmountthemfromothersystemsasneeded.
ThisconfigurationworkswellwithNISloginauthentication.
Withthissetup,itcanbeconvenienttocreateaworld-
writabledirectoryforexample/home/sharedwhichusers
canusetoexchangefiles.Ifyousetthestickybit(page
1057)onthisdirectory(chmod1777/home/shared),
userscandeleteonlyfilestheycreated.Ifyoudonotset
thestickybit,anyusercandeleteanyfile.
OpenSSHOpenSSHtoolsincludessh(logsinonaremote
system,page585)andscp(copiesfilesto/fromaremote
system,page588).Youcanalsosetupautomaticlogins
withOpenSSH:Ifyousetupasharedhomedirectorywith
NFS,eachuser's~/.sshdirectory(page581)isthesame
oneachsystem;auserwhosetsupapersonal
authenticationkey(page592)willbeabletouseOpenSSH
toolsbetweensystemswithoutenteringapassword.See
page591forinformationonhowtosetupanOpenSSH
server.Youcanjustusethesshandscpclients;youdonot
havetosetthemup.
DNScacheSettingupalocalcachecanreducethetraffic
betweentheLANandtheoutsideworldandcanimprove
responsetimes.Formoreinformationreferto"JumpStartI:
SettingUpaDNSCache"onpage733.
DHCPDHCPenablesaclientsystemtoretrievenetwork
configurationinformationfromaservereachtimeit
connectstoanetwork.Seepage431formoreinformation.
SambaSambaallowsLinuxsystemstoparticipateina
Windowsnetwork,sharingdirectoriesandprinters,and
accessingthosesharedbyWindowssystems.Samba
includesaspecialshareforaccessingusers'home
directories.Formoreinformationreferto"The[homes]
Share:SharingUsers'HomeDirectories"onpage711.
YoucanalsouseSambatosetupashareddirectorysimilarto
theonedescribedunder"NFS."ToshareaLinuxdirectorywith
Windowscomputers,placethefollowingcodein
/etc/smb.conf(page706):
[public]
comment=Publicfilespace
path=/home/shared
readonly=no
public=yes
browseable=yes
AnyWindowsusercanaccessthisshare;itcanbeusedto
exchangefilesbetweenusersandbetweenLinuxandWindows
systems.
ChapterSummary
Alocalareanetwork(LAN)connectscomputersatonesiteand
canallowtheconnectedcomputerstoshareanInternet
connectionandaprinter.Eachsystem,ornode,onaLANmust
haveanetworkinterfacecard(NIC).NICscanbeconnectedto
thenetworkviacablesorradiowaves(wireless).
AnEthernet-basedLANhasaconnectionbetweeneach
computerandacentralhub.Twokindsofhubsexist:passive
(sometimesjustcalledahub)andswitching(faster,calleda
switch).Awirelessaccesspoint(WAP)connectsawireless
networktoawiredone.IftheLANyouaresettingupis
connectedtoanothernetwork,suchastheInternet,youneeda
router(gateway).Aroutercanperformseveralfunctions,the
mostcommonofwhichisallowingseveralsystemstosharea
singleInternetconnectionandIPaddress,calledNAT.
YoucanconfiguretheLANtouseNISasaloginserversothat
youdonothavetosetupaccountsoneachsystem.Youcan
useNFS,whichallowsyoutomountremotedirectory
hierarchies,tosetupauniversalhomedirectory.Sambaisan
importantpartofmanyLANs:ItallowsLinuxsystemsto
participateinaWindowsnetwork,sharingdirectoriesand
printers,andaccessingthosesharedbyWindowssystems.
Exercises
1. Whatadvantagedoesaswitchhaveoverapassivehub?
2. Whichserverwouldyousetuptoallowuserstologinwiththesameusername
andpasswordonallcomputersonaLAN?
3. Nametwoserversthatallowyoutosharedirectoriesbetweensystems.
4. WhatisaWAPandwhatdoesitdo?
5. Whatisacommonfunctionofarouter?Whatisthisfunctioncalled?
6. Whatdoesawirelessbridgedo?
7. Whatiskudzu?WhatdoesitdowhenyouinstallanewNIC?
8. Whatistheprivateaddressspace?Whenwouldyouuseaprivateaddress?
AdvancedExercises
9. Ifyousetasystem'ssubnetmaskto255.255.255.0,howmanycomputerscan
youputonthenetworkwithoutusingarouter?
10. WhichfilestoresinformationaboutwhichDNSserversthesystemuses?
PartV:UsingClientsandSettingUpServers
Chapter18OpenSSH:SecureNetworkCommunication
Chapter19FTP:TransferringFilesAcrossaNetwork
Chapter20sendmail:SettingUpMailClients,Servers,and
More
Chapter21NIS:NetworkInformationService
Chapter22NFS:SharingFilesystems
Chapter23Samba:IntegratingLinuxandWindows
Chapter24DNS/BIND:TrackingDomainNamesand
Addresses
Chapter25iptables:SettingUpaFirewall
Chapter26Apache(httpd):SettingUpaWebServer
18.OpenSSH:SecureNetwork
Communication
INTHISCHAPTER
AboutOpenSSH 580
OpenSSHClients 583
JumpStart:Usingsshandscp 583
sshd:OpenSSHServer 591
JumpStart:StartingthesshdDaemon 591
AuthorizedKeys:AutomaticLogin 592
Troubleshooting 595
Tunneling/PortForwarding 596
OpenSSHisasuiteofsecurenetworkconnectivitytoolsthat
replacestelnet,rcp,rsh/rshd,rlogin/rlogind,andftp/ftpd.Unlike
thetoolsitreplaces,OpenSSHtoolsencryptalltraffic,including
passwords.Inthiswaytheythwartmalicioususerswhowould
eavesdrop,hijackconnections,andstealpasswords.
ThischaptercoversthefollowingOpenSSHtools:
scpCopiesfilesto/fromanothersystem
sftpCopiesfilesto/fromothersystems(asecure
replacementforftp)
sshRunsacommandonorlogsinonanothersystem
sshdTheOpenSSHdaemon(runsontheserver)
ssh-keygenCreatesRSAorDSAhost/userauthenticationkeys
Introduction
Usingpublickeyencryption(page989),OpenSSHprovidestwo
levelsofauthentication:serverandclient/user.Firsttheclient
verifiesthatitisconnectedtothecorrectserver.ThenOpenSSH
encryptscommunicationbetweenthesystems.Onceasecure,
encryptedconnectionhasbeenestablished,OpenSSHmakes
surethattheuserisauthorizedtologinonorcopyfiles
from/totheserver.Afterverifyingthesystemanduser,
OpenSSHallowsdifferentservicestobepassedthroughthe
connection.Theseservicesincludeinteractiveshellsessions
(ssh),remotecommandexecution(sshandscp),X11
client/serverconnections,andTCP/IPporttunneling.
SSH1versusSSH2
SSHprotocolversion2(SSH2)isacompleterewriteofSSH
protocolversion1(SSH1)thatoffersimprovedsecurity,
performance,andportability.Thetwoprotocolsarenot
compatible.BecauseSSH1isbeingrapidlysupplantedbySSH2
andbecauseSSH1isvulnerabletoaman-in-the-middleattack
(footnote3onpage992),thischapterdoesnotdiscussSSH1.
Becauseversion2isfloating-pointintensive,version1does
haveaplaceonsystemswithoutFPUs(floating-pointunitsor
accelerators),suchasold486SXsystems.Asinitiallyinstalled,
theOpenSSHtoolssuppliedwithRedHatLinuxsupportboth
protocols;youneedrunonlyoneservertocommunicatewith
systemsusingeitherprotocol.
ssh
Thesshutilityallowsyoutologinonaremotesystemovera
network.Youmightchoosetousearemotesystemtoaccessa
special-purposeapplicationortouseadevicethatisavailable
onlyonthatsystem,oryoumightusearemotesystem
becauseyouknowthatitisfasterornotasbusyasthelocal
computer.Whiletraveling,manybusiness-peopleusesshona
laptoptologinonasystematcompanyheadquarters.Froma
GUIyoucanuseseveralsystemssimultaneouslybyloggingin
oneachfromadifferentterminalemulatorwindow.
X11forwarding
WithX11forwardingturnedon,asitiswhenyouinstallRedHat
Linux,itisasimplemattertorunanX11programoveranssh
connection:RunsshfromaterminalemulatorrunningonaGUI
andgiveanX11commandsuchasxclock;thegraphicaloutput
appearsonthelocaldisplay.Formoreinformationreferto
"ForwardingX11"onpage596.
AboutOpenSSH
ThissectiondiscussesconfigurationfilesusedbyOpenSSH
clientsandservers,describeshowOpenSSHworks,and
highlightsadditionalOpenSSHresources.
Files
OpenSSHclientsandserversrelyonmanyfiles.Globalfilesare
keptin/etc/sshanduserfilesin~/.ssh.Inthedescriptionof
eachfile,thefirstwordindicateswhethertheclientorthe
serverusesthefile.
Caution:rhostauthenticationisasecurity
risk
AlthoughOpenSSHcangetauthentication
informationfrom/etc/hosts.equiv,
/etc/shosts.equiv,~/.rhosts,and~/.shosts,
thischapterdoesnotcovertheuseofthesefiles
becausetheyaresecurityrisks.Thedefaultsettings
inthe/etc/ssh/sshd_configconfigurationfile
preventtheiruse.
/etc/ssh:GlobalFiles
Globalfileslistedinthissectionaffectallusersbutcanbe
overriddenbyfilesinauser's~/.sshdirectory.
moduli
clientandserverContainskeyexchangeinformationthat
OpenSSHusestoestablishasecureconnection.Donotmodify
thisfile.
ssh_config
clientTheglobalOpenSSHconfigurationfile(page589).Entries
herecanbeoverriddenbyentriesinauser's~/.ssh/config
file.
sshd_config
serverTheconfigurationfileforsshd(page593).
ssh_host_dsa_key,ssh_host_dsa_key.pub
serverSSHprotocolversion2DSAhostkeys.Bothfilesshould
beownedbyroot.Thessh_host_dsa_key.pubpublicfile
shouldbereadablebyanyonebutwritableonlybyitsowner
(644permissions).Thessh_host_dsa_keyprivatefileshould
notbereadableorwritablebyanyoneexceptitsowner(600
permissions).
ssh_host_rsa_key,ssh_host_rsa_key.pub
serverSSHprotocolversion2RSAhostkeys.Bothfilesshould
beownedbyroot.Thessh_host_rsa_key.pubpublicfile
shouldbereadablebyanyonebutwritableonlybyitsowner
(644permissions).Thessh_host_rsa_keyprivatefileshould
notbereadableorwritablebyanyoneexceptitsowner(600
permissions).
ssh_known_hosts
clientContainspublicRSA(bydefault)keysofhoststhatusers
onthelocalsystemcanconnectto.Thisfilecontains
informationsimilarto~/.ssh/known_hosts,exceptitisset
upbytheadministratorandisavailabletoallusers.Thisfile
shouldbeownedbyrootandshouldbereadablebyanyonebut
writableonlybyitsowner(644permissions).
sshrc
serverContainsinitializationroutines.If~/.ssh/rcisnot
present,thisscriptrunsafter~/.ssh/environmentandbefore
theuser'sshellstarts.
~/.ssh:UserFiles
OpenSSHcreatesthe~/.sshdirectoryandtheknown_hosts
filethereinautomaticallywhenyouconnecttoaremotesystem.
authorized_keys
serverEnablesyoutologinonorcopyfilesfrom/toanother
systemwithoutsupplyingapassword(page592).Noone
excepttheownershouldbeabletowritetothisfile.
config
clientAuser'sprivateOpenSSHconfigurationfile(page589).
Entrieshereoverridethosein/etc/ssh/ssh_config.
environment
serverContainscommandsthatareexecutedwhenauserlogs
inwithssh.Similarinfunctionto~/.bashrcforalocalbash
shell.
id_dsa,id_dsa.pub
clientUserauthenticationDSAkeysgeneratedbyssh-keygen
(page592).Bothfilesshouldbeownedbytheuserinwhose
homedirectorytheyappear.Theid_dsa.pubpublicfileshould
bereadablebyanyonebutwritableonlybyitsowner(644
permissions).Theid_dsaprivatefileshouldnotbereadableor
writablebyanyoneexceptitsowner(600permissions).
id_rsa,id_rsa.pub
clientUserauthenticationRSAkeysgeneratedbyssh-keygen
(page592).Bothfilesshouldbeownedbytheuserinwhose
homedirectorytheyappear.Theid_rsa.pubpublicfileshould
bereadablebyanyonebutwritableonlybyitsowner(644
permissions).Theid_rsaprivatefileshouldnotbereadableor
writablebyanyoneexceptitsowner(600permissions).
known_hosts
clientContainspublicRSAkeys(bydefault)ofhoststhatthe
userhasconnectedto.OpenSSHautomaticallyaddsentries
eachtimetheuserconnectstoanewserver(page584).Refer
to"HostKeyAlgorithms"(page590)forinformationonusing
DSAkeys.
rc
serverContainsinitializationroutines.Thisscriptrunsafter
environmentandbeforetheuser'sshellstarts.Ifthisfileis
notpresent,OpenSSHruns/etc/ssh/sshrc;ifthatfiledoes
notexist,OpenSSHrunsxauth.
HowOpenSSHWorks
WhenOpenSSHstarts,itfirstestablishesanencrypted
connectionandthenauthenticatestheuser.Oncethesetwo
tasksarecompleted,OpenSSHallowsthetwosystemstosend
informationbackandforth.
OpenSSHusestwokeypairstonegotiateanencryptedsession:
ahostkeypairandasessionkeypair.Thehostkeypairisaset
ofpublic/privatekeysthatisestablishedthefirsttimethe
serversystemrunssshd(page592),typicallythefirsttimethe
systemboots.Thesessionkeypairisasetofpublic/private
keysthatchangeshourly.
ThefirsttimeanOpenSSHclientconnectswithanOpenSSH
server,youareaskedtoverifythatitisconnectedtothecorrect
server(see"First-timeauthentication"onpage584).After
verification,theclientmakesacopyoftheserver'spublichost
key.Onsubsequentconnections,theclientcomparesthekey
providedbytheserverwiththekeyitstored.Althoughthistest
isnotfoolproof,thenextoneisquitesecure.
Theclientthengeneratesarandomkey,whichitencryptswith
boththeserver'spublichostkeyandthesessionkey.Theclient
sendsthisencryptedkeytotheserver.Theserver,inturn,uses
itsprivatekeystodecrypttheencryptedkey.Thisprocess
createsakeythatisknownonlytotheclientandserverandis
usedtoencrypttherestofthesession.
MoreInformation
Localmanpagesssh,scp,ssh-keygen,ssh_config,sshd,sshd_config
Web
OpenSSHhomepagewww.openssh.comSearchtldp.orgforssh
forvariousHOWTOsandotherdocuments.
Books
ImplementingSSH:StrategiesforOptimizingtheSecureShell
byDwivedi;JohnWiley&Sons(October2003)SSH,The
SecureShell:TheDefinitiveGuidebyBarrett&Silverman;
O'Reilly&Associates(February2001)
OpenSSHClients
Thissectioncoverssettingupandusingthessh,scp,andsftp
clients.
Prerequisites
Installthefollowingpackages:
openssh
openssh-clients
TherearenostartupcommandsforOpenSSHclients.
JumpStart:Usingsshandscp
Thesshandscpclientsdonotrequiresetupbeyondinstallingthe
requisitepackages,althoughyoucancreateandeditfilesthat
facilitatetheiruse.Torunasecureshellonorsecurelycopya
fileto/fromaremotesystem,thefollowingcriteriamustbe
met:TheremotesystemmustberunningtheOpenSSH
daemon(sshd),youmusthaveanaccountontheremote
system,andtheservermustpositivelyidentifyitselftothe
client.Thefollowingexampleshowsauserlogginginongrape
aszachandthengivinganexitcommandtoreturntotheshell
onthelocalsystem:
$sshzach@grape
zach@grape'spassword:
[zach@grapezach]$exit
Connectiontograpeclosed.
$
Youcanomituser@(zach@intheprecedingexample)from
thecommandlineifyouwanttologinasyourselfandyouhave
thesameusernameonbothsystems.Thefirsttimeyou
connecttoaremoteOpenSSHserver,sshorscpasksyouto
confirmthatyouareconnectedtotherightsystem.Referto
"First-timeauthentication"onpage584.
Thefollowingexamplecopiesty1fromtheworkingdirectoryon
thelocalsystemtoZach'shomedirectoryongrape:
$scpty1zach@grape:
zach@grape'spassword:
ty1100%|*****************************|131100:00
Setup
ThissectiondescribeshowtosetupOpenSSHontheclient
side.
RecommendedSettings
X11forwarding
TheconfigurationfilesprovidedbyRedHatestablishamostly
securesystemandmayormaynotmeetyourneeds.The
importantOpenSSHdefaultvaluethattheRedHatconfiguration
filesoverrideisForwardX11Trusted,whichissettoyesinthe
RedHat/etc/ssh/ssh_configconfigurationfile(page595).
Seepage596formoreinformationonX11forwarding.
ServerAuthentication/KnownHosts
known_hosts,ssh_known_hosts
Twofileslistthehoststhelocalsystemhasconnectedtoand
positivelyidentified:~/.ssh/known_hosts(user)and
/etc/ssh/ssh_known_hosts(global).Nooneexceptthe
owner(rootinthecaseofthesecondfile)shouldbeableto
writetoeitherofthesefiles.Nooneexcepttheownershould
haveanyaccesstoa~/.sshdirectory.
First-timeauthentication
WhenyouconnecttoanOpenSSHserverforthefirsttime,the
OpenSSHclientpromptsyoutoconfirmthatyouareconnected
totherightsystem.Thischeckingcanhelppreventaman-in-
the-middleattack(footnote3onpage992):
Theauthenticityofhost'grape(192.168.0.3)'can'tbeestablished.
RSAkeyfingerprintisc9:03:c1:9d:c2:91:55:50:e8:19:2b:f4:36:ef:73:78.
Areyousureyouwanttocontinueconnecting(yes/no)?
Warning:Permanentlyadded'grape,192.168.0.3'(RSA)tothelistof
knownhosts.
Beforeyourespondtotheprecedingquery,makesureyouare
logginginonthecorrectsystemandnotonanimposter.Ifyou
arenotsure,atelephonecalltosomeonewhologsinonthat
systemlocallycanhelpverifythatyouareontheintended
system.Whenyouansweryes(youmustspellitout),the
clientappendstheserver'spublichostkey(thesinglelinein
the/etc/ssh/ssh_host_rsa_key.pubor
/etc/ssh/ssh_host_dsa_key.pubfileontheserver)tothe
user's~/.ssh/known_hostsfileonthelocalclient,creating
the~/.sshdirectoryifnecessary.Sothatitcankeeptrackof
whichlineinknown_hostsappliestowhichserver,OpenSSH
prependsthenameoftheserverandtheserver'sIPaddress
(bydefault)totheline.
WhenyousubsequentlyuseOpenSSHtoconnecttothatserver,
theclientverifiesthatitisconnectedtothecorrectserverby
comparingthiskeytotheonetheserversupplies.
known_hostsfile
Theknown_hostsfileusesoneverylonglinetoidentifyeach
hostitkeepstrackof.EachlinestartswiththehostnameandIP
addressofthesystemthelinecorrespondsto,followedbythe
typeofencryptionbeingusedandtheserver'spublichostkey.
Thefollowingline(itisonelogicallinewrappedontofour
physicallines)fromknown_hostsisusedtoconnecttogrape
at192.168.0.3usingRSA(page1053)encryption:
$cat~/.ssh/known_hosts
grape,192.168.0.3ssh-rsaAAAAB3NzaC1yc2EAAAABIwAAAIEArinPGsaLUtnSL4V7b
T51ksF7KoScsIk7wqm+2sJEC43rxVNS5+MO/O64UXp5qQOHBmeLCCFCsIJg8xseuVkg9iwO
BKKOdlZdBNVqFS7tnJdBQTFf+ofPIDDip8w6ftHOdM8hZ/diQq5gXqMH+Mpac31pQXAxXgY
SP8NYIgb3X18=
OpenSSHautomaticallystoreskeysfromserversithas
connectedtoinuser-privatefiles(~/.ssh/known_hosts).
Thesefilesworkonlyfortheuserwhosedirectorytheyappear
in.Workingasrootandusingatexteditor,youcancopylines
fromauser'sprivatelistofknownhoststothepubliclistin
/etc/ssh/ssh_known_hoststomakeaserverknown
globallyonthelocalsystem.
If,afteraremotesystem'spublickeyisstoredinoneofthe
knownhostsfiles,theremotesystemsuppliesadifferent
fingerprintwhenthesystemsconnect,OpenSSHdisplaysthe
followingmessageanddoesnotcompletetheconnection:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@WARNING:REMOTEHOSTIDENTIFICATIONHASCHANGED!@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ITISPOSSIBLETHATSOMEONEISDOINGSOMETHINGNASTY!
Someonecouldbeeavesdroppingonyourightnow(man-in-the-middleattack)!
ItisalsopossiblethattheRSAhostkeyhasjustbeenchanged.
ThefingerprintfortheRSAkeysentbytheremotehostis
f1:6f:ea:87:bb:1b:df:cd:e3:45:24:60:d3:25:b1:0a.
Pleasecontactyoursystemadministrator.
Addcorrecthostkeyin/home/sam/.ssh/known_hoststogetridofthismessage.
Offendingkeyin/home/sam/.ssh/known_hosts:1
RSAhostkeyforgrapehaschangedandyouhaverequestedstrictchecking.
Hostkeyverificationfailed.
Ifyouseethismessage,youmaybethesubjectofaman-in-
the-middleattack.Itismorelikely,however,thatsomethingon
theremotesystemhaschanged,causingittosupplyanew
fingerprint.Checkwiththeremotesystem'sadministrator.Ifall
iswell,removetheoffendingkeyfromthespecifiedfile(the
thirdlinefromthebottomintheprecedingexamplepointsto
thelineyouneedtoremove)andtryconnectingagain.Youwill
seethefirst-timeauthentication(page584)againasOpenSSH
verifiesthatyouareconnectingtothecorrectsystem.Follow
thesamestepsaswhenyouinitiallyconnectedtotheremote
host.
ssh:ConnectstoorExecutesCommandsona
RemoteSystem
Theformatofansshcommandlineis
ssh[options][user@]host[command]
wherehost,thenameoftheOpenSSHserveryouwantto
connectto,istheonlyrequiredargument.Thehostcanbea
localsystemname,anFQDNofasystemontheInternet,oran
IPaddress.Givethecommandsshhosttologinontheremote
systemhostwiththesameusernamethatyouareusingonthe
localsystem.Includeuser@whenyouwanttologinwitha
usernameotherthantheoneyouareusingonthelocalsystem.
Dependingonhowthingsaresetup,youmayneedtosupply
yourpassword.
Openingaremoteshell
Withoutcommand,sshlogsyouinonhost.Theremotesystem
displaysashellpromptandyoucanruncommandsonhost.
Givethecommandexittoclosetheconnectiontohostand
returntothelocalsystem'sprompt:
[bravo]$sshspeedy
alex@speedy'spassword:
Lastlogin:SatSep1606:51:59frombravo
Havealotoffun...
Youhavenewmail.
[speedy]$
...
[speedy]$exit
Connectiontospeedyclosed.
[bravo]$
Runningaremotecommand
Whenyouincludecommand,sshlogsinonhost,executes
command,closestheconnectiontohost,andreturnscontrol
tothelocalsystem.Theremotesystemneverdisplaysa
prompt.
Thefollowingexamplerunslsinthememosdirectoryonthe
remotesystemspeedy.Theexampleassumesthattheuser
runningthecommand(Alex)hasaloginonspeedyandthat
thememosdirectoryisinAlex'shomedirectoryonspeedy:
[bravo]$sshspeedylsmemos
alex@speedy'spassword:
memo.0921
memo.draft
[bravo]$
Forthenextexample,assumeafilenamedmemo.newisin
theworkingdirectoryonthelocalsystem(bravo).Youcannot
rememberwhetherthisfilecontainscertainchangesorwhether
youmadethesechangestothefilenamedmemo.drafton
speedy.Youcouldcopymemo.drafttothelocalsystemand
rundiff(page135)onthetwofiles,butthenyouwouldhave
threesimilarcopiesofthefilespreadacrosstwosystems.If
youarenotcarefulaboutremovingtheoldcopieswhenyouare
done,youmayjustbecomeconfusedagaininafewdays.
Insteadofcopyingthefile,youcanusessh:
[bravo]$sshspeedycatmemos/memo.draft|diffmemos.new
Whenyourunssh,standardoutputofthecommandrunonthe
remotesystemispassedtothelocalshellasthoughthe
commandhadbeenruninplaceonthelocalsystem.Aswithall
shellcommands,youmustquotespecialcharactersthatyoudo
notwantthelocalsystemtointerpret.Inthepreceding
example,theoutputofthecatcommandonspeedyissent
throughapipeonbravotodiff(runningonbravo),which
comparesthelocalfilememos.newtostandardinput().The
followingcommandlinehasthesameeffectbutcausesdiffto
runontheremotesystem:
[bravo]$catmemos.new|sshspeedydiffmemos/memo.draft
Standardoutputfromdiffontheremotesystemissenttothe
localshell,whichdisplaysitonthescreen(becauseitisnot
redirected).
Options
Thissectiondescribessomeoftheoptionsyoucanusewithssh.
C
(compression)Enablescompression.(Inthecommercial
versionofssh,Cdisablescompressionand+Cenables
compression.)
f
(notforeground)Sendssshtothebackgroundafteraskingfor
apasswordandbeforeexecutingthecommand.Usefulwhen
youwanttorunthecommandinthebackgroundbutmust
supplyapassword.Impliesn.
L
Forwardsaportonthelocalclienttoaremotesystem.For
moreinformationreferto"Tunneling/PortForwarding"onpage
596.
luser
(login)Attemptstologinasuser.
n
(null)Redirectsstandardinputtosshtocomefrom/dev/null.
Requiredwhenrunningsshinthebackground.
ooption
(option)Specifiesoptionintheformatusedinconfiguration
files(page589).
p
(port)Specifiestheportontheremotehostthatthe
connectionismadeto.Usingthehostdeclaration(page590)in
theconfigurationfile,youcanspecifyadifferentportforeach
systemyouconnectto.
R
Forwardsaportontheremotesystemtothelocalclient.For
moreinformationreferto"Tunneling/PortForwarding"onpage
596.
t
(tty)Allocatesapseudo-ttytothesshprocessontheremote
system.Withoutthisoption,whenyourunacommandona
remotesystem,sshdoesnotallocateatty(terminal)tothe
process.Instead,sshattachesstandardinputandstandard
outputoftheremoteprocesstothesshsessionthatisnormally,
butnotalways,whatyouwant.Thisoptionforcessshtoallocate
attyontheremotesystemsoprogramsthatrequireattywill
work.
v
(verbose)Displaysdebuggingmessagesabouttheconnection
andtransfer.Usefulifthingsarenotgoingasexpected.
X
(X11)TurnsonnontrustedX11forwarding.Thisoptionisnot
necessaryifyouturnonX11nontrustedforwardinginthe
configurationfile.Formoreinformationreferto"Forwarding
X11"onpage596.
x
(X11)TurnsoffX11forwarding.
Y
(X11trusted)TurnsontrustedX11forwarding.Thisoptionis
notnecessaryifyouturnontrustedX11forwardinginthe
configurationfile.Formoreinformationreferto"Forwarding
X11"onpage596.
scp:CopiesFilesfrom/toaRemoteSystem
Thescp(securecopy)utilitycopiesanordinaryordirectoryfile
fromonesystemtoanotheronanetwork.Thisutilityusesssh
totransferfilesandemploysthesameauthentication
mechanismasssh;thusitprovidesthesamesecurityasssh.The
scputilityasksyouforapasswordwhenoneisrequired.The
formatofanscpcommandis
scp[[user@]from-host:]source-file[[user@]to-host:]
[destination-file]
wherefrom-hostisthenameofthesystemyouarecopying
filesfromandto-hostisthesystemyouarecopyingto.The
from-hostandto-hostargumentscanbelocalsystemnames,
FQDNs(page1032)ofsystemsontheInternet,orIP
addresses.Whenyoudonotspecifyahost,scpassumesthe
localsystem.Theuseroneithersystemdefaultstotheuseron
thelocalsystemwhoisgivingthecommand;youcanspecifya
differentuserwithuser@.Thescputilitycancopybetweentwo
remotesystems.
Thesource-fileisthefileyouarecopying,andthe
destination-fileistheresultingcopy.Makesurethatyouhave
readpermissionforthefileyouarecopyingandwrite
permissionforthedirectoryyouarecopyingitinto.Youcan
specifyplainordirectoryfilesasrelativeorabsolute
pathnames.(Arelativepathnameisrelativetothespecifiedor
implicituser'shomedirectory.)Whenthesource-fileisa
directory,youmustusetheroptiontocopyitscontents.When
thedestination-fileisadirectory,eachofthesourcefiles
maintainsitssimplefilename.Whenthedestination-fileis
missing,scpassumestheuser'shomedirectory.
Samhasanalternateusername,sls,ongrape.Inthefollowing
example,Samusesscptocopymemo.txtfromthehome
directoryofhisslsaccountongrapetotheallmemos
directoryintheworkingdirectoryonthelocalsystem.If
allmemoswasnotthenameofadirectory,memo.txtwould
becopiedtoafilenamedallmemosintheworkingdirectory.
$scpsls@grape:memo.txtallmemos
sls@grape'spassword:
memo.txt100%|*****************************|1466400:00
Asthetransferprogresses,thepercentandnumberofbytes
transferredincreaseandthetimeremainingdecreases.The
asterisksprovideavisualrepresentationoftheprogressofthe
transfer.
Inthenextexample,Sam,whileworkingfrompeach,copies
thesamefileasinthepreviousexampletothedirectorynamed
oldinSam'shomedirectoryonspeedy.Forthisexampleto
work,Sammustbeabletousesshtologinonspeedyfrom
grapewithoutusingapassword.Formoreinformationreferto
"AuthorizedKeys:AutomaticLogin"onpage592.
$[sam@peach]scpsls@grape:memo.txtspeedy:old
sam@grape'spassword:
Options
Thissectiondescribessomeoftheoptionsyoucanusewithscp.
C
(compression)Enablescompression.
ooption
(option)Specifiesoptionintheformatusedinconfiguration
files(discussedshortly).
Pport
(port)Connectstoportportontheremotehost.
p
(preserve)Preservesthemodificationandaccesstimesaswell
asthemodesoftheoriginalfile.
q
(quiet)Doesnotdisplaytheprogressmeter.
r
(recursive)Recursivelycopiesadirectoryhierarchy.
v
(verbose)Displaysdebuggingmessagesabouttheconnection
andtransfer.Usefulifthingsarenotgoingasexpected.
sftp:ASecureFTPClient
AspartofOpenSSH,RedHatLinuxprovidessftp,asecure
alternativetoftp(page601).Functionallythesameasftp,sftp
mapsftpcommandsintoOpenSSHcommands.Youcanreplace
ftpwithsftpwhenyouarelogginginonaserverthatisrunning
theOpenSSHdaemon,sshd.Onceyouareconnectedtoa
systemwithsftp,givethecommand?todisplayalistof
commands.Forsecurecommunication,usesftporscptoperform
allfiletransfersrequiringauthentication.Refertothesftpman
pageformoreinformation.
~/.ssh/configand/etc/ssh/ssh_config
ConfigurationFiles
ItisrarelynecessarytomodifyOpenSSHclientconfiguration
files.Foragivenusertheremaybetwoconfigurationfiles:
~/.ssh/config(user)and/etc/ssh/ssh_config(global).
Thesefilesarereadinthisorderand,foragivenparameter,the
firstonefoundistheonethatisused.Ausercanoverridea
globalparametersettingbysettingthesameparameterinhis
userconfigurationfile.Parametersgivenonthesshorscp
commandlinetakeprecedenceoverparameterssetineitherof
thesefiles.
Auser's~/.ssh/configfilemustbeownedbytheuser(the
ownerofthe~/directory)andmustnotbewritablebyanyone
excepttheowner;ifitis,theclientwillexitwithanerror
message.Thisfileistypicallysettomode600asthereisno
reasonforanyoneexceptitsownertobeabletoreadit.
Linesintheconfigurationfilescontaindeclarationsthatstart
withakeyword,whichisnotcasesensitive,followedby
whitespace,andendwithcase-sensitivearguments.
YoucanusetheHostkeywordtocausedeclarationstoapplyto
aspecificsystem.AHostdeclarationappliestoallthelines
betweenitandthenextHostdeclaration.Youcanuse*and?
wildcardswithinahostname.
Hosthostnames
Specifiesthatthefollowingdeclarations,untilthenextHost
declaration,applytohostnamesonly.Thehostnamesshould
beinthesameformyouwoulduseonacommandlineandcan
contain?and*wildcards.Asingle*specifiesallhosts.
CheckHostIPyes|no
UsesanIPaddressinadditiontoahostnametoidentifya
systemintheknown_hostsfilewhensettoyes(default).Set
tonotouseahostnameonly.
ForwardX11yes|no
Whensettoyes,automaticallyforwardsX11connectionsover
asecurechannelinnontrustedmodeandsetstheDISPLAY
shellvariable.Alternatively,youcanuseXonthecommandline
toredirectX11connectionsinnontrustedmode.Thedefault
valueforthisparameterisno.ForX11forwardingtowork,
X11Forwardingmustalsobesettoyesinthe
/etc/sshd_configfileontheserver(page595).Formore
informationreferto"ForwardingX11"onpage596.
ForwardX11Trustedyes|no
Whensettoyes,automaticallyforwardsX11connectionsover
asecurechannelintrustedmodeandsetstheDISPLAYshell
variable.Alternatively,youcanuseYonthecommandlineto
redirectX11connectionsintrustedmode.Thedefaultvaluefor
thisparameterisnobutRedHatLinuxsetsittoyes.ForX11
forwardingtowork,X11Forwardingmustalsobesettoyesin
the/etc/sshd_configfileontheserver(page595).Formore
informationreferto"ForwardingX11"onpage596.
HostbasedAuthenticationyes|no
Triesrhostsauthenticationwhensettoyes.Foramoresecure
system,settono(default).
HostKeyAlgorithmsalgorithms
Thealgorithmsisacomma-separatedlistofalgorithmsthat
theclientusesinorderofpreference.Choosealgorithmsfrom
ssh-rsaorssh-dss(defaultisssh-rsa,ssh-dss).
TCPKeepAliveyes|no
Periodicallycheckswhetheraconnectionisalivewhensetto
yes(default).Thischeckingcausesthesshorscpconnectionto
bedroppedwhentheservercrashesortheconnectiondiesfor
anotherreason,evenifitisonlytemporary.Settingthis
parametertonocausestheclientnottocheckwhetherthe
connectionisalive.
ThisdeclarationusestheTCPkeepaliveoption,whichisnot
encryptedandissusceptibletoIPspoofing(page1038).Refer
to"ClientAliveInterval"onpage594foraserver-based
nonspoofablealternative.
StrictHostKeyCheckingyes|no|ask
DetermineswhetherandhowOpenSSHaddshostkeystoa
user'sknown_hostsfile.Settoask(default)toaskwhether
toaddahostkeywhenconnectingtoanewsystem,settono
toaddahostkeyautomatically,andsettoyestorequirethat
hostkeysbeaddedmanually.Theyesandaskarguments
causeOpenSSHtorefusetoconnecttoasystemwhosehost
keyhaschanged.Foramoresecuresystem,settoyesorask.
Username
Specifiesausernametousewhenlogginginonasystem.
SpecifysystemswiththeHostdeclaration.Thisoptionmeans
thatyoudonothavetoenterausernameonthecommandline
whenyouareusingausernamethatdiffersfromyour
usernameonthelocalsystem.
sshd:OpenSSHServer
ThissectiondiscusseshowtosetupanOpenSSHserver.
Prerequisites
Installthefollowingpackages:
openssh
openssh-server
Runchkconfigtocausesshdtostartwhenthesystementers
multiusermode:
#/sbin/chkconfigsshdon
See"StartingsshdfortheFirstTime"(page592)for
informationonstartingtheserverforthefirsttime.
Notes
Firewall
AnOpenSSHservernormallyusesTCPport22.IftheOpenSSH
serversystemisrunningafirewall,youneedtoopenthisport.
UsingtheRedHatgraphicalfirewalltool(page768),selectSSH
fromtheTrustedServicesframetoopenthisport.Formore
generalinformationseeChapter25,whichdetailsiptables.
SELinux
WhenSELinuxissettouseatargetedpolicy,sshdisprotected
bySELinux.Youcandisablethisprotectionifnecessary.For
moreinformationreferto"SettingtheTargetedPolicywith
system-config-securitylevel"onpage402.
JumpStart:StartingthesshdDaemon
Installtherequisitepackagesandstartthesshddaemonas
describedfollowing.Lookin/var/log/securetomakesure
everythingisworkingproperly.
RecommendedSettings
TheconfigurationfilesprovidedbyRedHatestablishamostly
securesystemandmayormaynotmeetyourneeds.TheRed
Hat/etc/ssh/sshd_configfileturnsonX11forwarding(page
596).Foramoresecuresystem,youcansetPermitRootLogin
tono,therebyremovingaknown-name,privilegedaccountthat
isexposedtotheoutsideworldwithonlypasswordprotection.
StartingsshdfortheFirstTime
WhenyoustartthesshdOpenSSHdaemonforthefirsttime,
generallywhenyoufirstbootthesystemafterinstallation,it
automaticallycreateshostkeyfiles(page581)in/etc/ssh:
#/sbin/servicesshdstart
GeneratingSSH1RSAhostkey:[OK]
GeneratingSSH2RSAhostkey:[OK]
GeneratingSSH2DSAhostkey:[OK]
Startingsshd:[OK]
OpenSSHusesthefilesitcreatestoidentifytheserver.
AuthorizedKeys:AutomaticLogin
YoucanconfigureOpenSSHsoyoudonothavetoentera
passwordeachtimeyouconnecttoaremotesystem.Toset
thingsup,youneedtogenerateapersonalauthenticationkey,
placethepublicpartofthekeyontheremoteserver,andkeep
theprivatepartofthekeyonthelocalclient.Whenyou
connect,theremotesystemissuesachallengebasedonthe
publicpartofthekey.Theprivatepartofthekeyisrequiredto
respondproperlytothechallenge.Ifthelocalsystemprovides
theappropriateresponse,theremotesystemlogsyouin.
Thefirststepinsettingupanautomaticloginistogenerate
yourpersonalauthenticationkeys.Checkwhetherthese
authenticationkeysalreadyexist:Lookin~/.sshforeither
id_dsaandid_dsa.puborid_rsaandid_rsa.pub.Ifoneof
thesepairsoffilesispresent,skipthenextstep(donotcreate
anewkey).
Thessh-keygenutilitycreatesthepublicandprivatepartsofan
RSAkey:
ssh-keygen
$ssh-keygen-trsa
Generatingpublic/privatersakeypair.
Enterfileinwhichtosavethekey(/home/sam/.ssh/id_rsa):
Createddirectory'/home/sam/.ssh'.
Enterpassphrase(emptyfornopassphrase):RETURN
Entersamepassphraseagain:RETURN
Youridentificationhasbeensavedin/home/sam/.ssh/id_rsa.
Yourpublickeyhasbeensavedin/home/sam/.ssh/id_rsa.pub.
Thekeyfingerprintis:
f2:eb:c8:fe:ed:fd:32:98:e8:24:5a:76:1d:0e:fd:1dsam@peach
ReplacersawithdsatogenerateDSAkeys.Inthisexample,
theuserpressedRETURNinresponsetoeachquery.Youhave
theoptionofspecifyingapassphrase(1030charactersisa
goodlength)toencrypttheprivatepartofthekey.Thereisno
waytorecoveralostpassphrase.Seethefollowingsecuritytip
formoreinformationaboutthepassphrase.
Thessh-keygenutilitygeneratestwokeys:aprivatekeyor
identificationin~/.ssh/id_rsaandapublickeyin
~/.ssh/id_rsa.pub.Nooneexcepttheownershouldbeable
towritetoeitherofthesefiles.Onlytheownershouldbeable
toreadfromtheprivatekeyfile.
authorized_keys
Toenableyoutologinonorcopyfilesfrom/toanothersystem
withoutsupplyingapassword,firstcreatea~/.sshdirectory
withpermissionssetto700ontheremotesystem.Nextcopy
~/.ssh/id_rsa.pubonthelocalsystemtoafilenamed
~/.ssh/authorized_keysontheremotesystem.Noone
excepttheownershouldbeabletoreadfromorwritetothis
file.Nowwhenyourunsshorscptoaccesstheremotesystem,
youdonothavetosupplyapassword.Tomakethesystem
evenmoresecure,youcandisablepasswordauthenticationby
settingPasswordAuthenticationtonoin/etc/sshd_config.
Security:Whenyouencryptyour
personalkey
Theprivatepartofthekeyiskeptinafilethatonly
youcanread.Ifamalicioususercompromiseseither
youraccountortherootaccountonthelocal
system,thatuserthenhasaccesstoyouraccount
ontheremotesystembecauseshecanreadthe
privatepartofyourpersonalkey.
Encryptingtheprivatepartofyourpersonalkey
protectsthekeyand,therefore,restrictsaccessto
theremotesystemshouldsomeonecompromise
yourlocalaccount.However,ifyouencryptyour
personalkey,youmustsupplythepassphraseyou
usedtoencryptthekeyeachtimeyouusethekey,
negatingthebenefitofnothavingtotypea
passwordwhenlogginginontheremotesystem.
Also,mostpassphrasesthatyoucanremembercan
becrackedquitequicklybyapowerfulcomputer.
Abetterideaistostoretheprivatekeysona
removablemedium,suchasaUSBflashdrive,and
haveyour~/.sshdirectoryasthemountpointfor
thefilesystemstoredonthisdrive.
CommandLineOptions
Commandlineoptionsoverridedeclarationsintheconfiguration
files.Followingaredescriptionsofsomeofthemoreuseful
sshdoptions.
d
(debug)Setsdebugmodewhereinsshdsendsdebugging
messagestothesystemlogandtheserverstaysinthe
foreground.Youcanspecifythisoptionuptothreetimesto
increasetheverbosityoftheoutput.Seealsoe.(Thesshclient
usesvfordebugging;seepage587.)
e
(error)Sendsoutputtostandarderror,nottothesystemlog.
Usefulwithd.
ffile
(file)Specifiesthefilewiththepathnamefileasthedefault
configurationfileinsteadof/etc/ssh/sshd_config.
t
(test)Checkstheconfigurationfilesyntaxandthesanityofthe
keyfiles.
D
(noDetach)Keepssshdintheforeground.Usefulfor
debugging;impliedbyd.
/etc/ssh/sshd_configConfigurationFile
The/etc/ssh/sshd_configconfigurationfilecontainsone-line
declarationsthatstartwithakeyword,whichisnotcase
sensitive,followedbywhitespace,andendwithcase-sensitive
arguments.
AllowUsersuserlist
TheuserlistisaSPACE-separatedlistofusernamesthat
specifiesuserswhoareallowedtologinusingsshd.Thislist
caninclude*and?wildcards.Youcanspecifyauserasuser
oruser@host.Ifyouusethesecondformat,makesurethat
youspecifythehostasreturnedbyhostname.Withoutthis
declaration,anyuserwhocanloginlocallycanloginusingan
OpenSSHclient.
ClientAliveCountMaxn
Thenspecifiesthenumberofclient-alivemessagesthatcanbe
sentwithoutreceivingaresponsebeforesshddisconnectsfrom
theclient.SeeClientAliveInterval.Defaultis3.
ClientAliveIntervaln
Sendsamessagethroughtheencryptedchannelaftern
secondsofnotreceivingamessagefromtheclient.See
ClientAliveCountMax.Defaultis0,meaningthatnomessages
aresent.
Thisdeclarationpassesmessagesovertheencryptedchannel
andisnotsusceptibletoIPspoofing(page1038).Itdiffers
fromTCPKeepAlive,whichusestheTCPkeepaliveoptionandis
susceptibletoIPspoofing.
HostbasedAuthenticationyes|no
Triesrhostsauthenticationwhensettoyes.Foramoresecure
system,settono(default).
IgnoreRhostsyes|no
Ignores.rhostsand.shostsfilesforauthentication.Doesnot
affecttheuseof/etc/hosts.equivand
/etc/ssh/shosts.equivfilesforauthentication.Foramore
securesystem,settoyes(default).
LoginGraceTimen
Waitsnsecondsforausertologinontheserverbefore
disconnecting.Avalueof0meansthereisnotimelimit.The
defaultis120.
LogLevelval
Specifieshowdetailedthelogmessagesare.Choosevalfrom
QUIET,FATAL,ERROR,INFO,andVERBOSE.Thedefaultis
INFO.
PasswordAuthentication
Permitsausertouseapasswordforauthentication.Defaultis
yes.
PermitEmptyPasswords
Permitsausertologintoanaccountthathasanempty
password.Defaultisno.
PermitRootLogin
PermitsroottologinusinganOpenSSHclient.Foramore
securesystem,settono.Thedefaultisyes.
StrictModesyes|no
Checksmodesandownershipofuser'shomedirectoryandfiles.
Loginfailsifthedirectoriesand/orfilescanbewrittentoby
anyone.Forsecurity,settoyes(default).
TCPKeepAliveyes|no
Periodicallycheckswhetheraconnectionisalivewhensetto
yes(default).Checkingcausesthesshorscpconnectiontobe
droppedwhentheclientcrashesortheconnectiondiesfor
anotherreason,evenifitisonlytemporary.Settingthis
parametertonocausestheservernottocheckwhetherthe
connectionisalive.
ThisdeclarationusestheTCPkeepaliveoption,whichisnot
encryptedandissusceptibletoIPspoofing(page1038).Refer
toClientAliveInterval(page594)foranonspoofablealternative.
X11Forwardingyes|no
AllowsX11forwardingwhensettoyes.Thedefaultisno,but
RedHatLinuxsetsX11Forwardingtoyes.ForX11forwarding
towork,theForwardX11declarationortheForwardX11Trusted
declarationmustalsobesettoyesineitherthe
~/.ssh/configor/etc/ssh/ssh_configclientconfiguration
file(page590).Formoreinformationreferto"ForwardingX11"
onpage596.
Troubleshooting
Logfiles
Thereareseveralplacestolookforclueswhenyouhavea
problemconnectingwithsshorscp.Firstlookforsshdentriesin
/var/log/secureand/var/log/messagesontheserver.
Followingaremessagesyoumayseewhenyouareusingan
AllowUsersdeclarationbuthavenotincludedtheuserwhois
tryingtologin(page593):
#grepsshd/var/log/secure
grapesshd[16]:UsersamnotallowedbecausenotlistedinAllowUsers
grapesshd[16]:Failedpasswordforillegalusersamfrom192.168.0.6port59276ssh2
ThenextmessagesoriginatewithPAM(page438)andindicate
thattheuserisnotknowntothesystem:
#grepsshd/var/log/messages
grapesshd(pam_unix)[2817]:checkpass;userunknown
grapesshd(pam_unix)[2817]:authenticationfailure;logname=uid=0
euid=0tty=NODEVsshruser=rhost=peach.sobell.com
Debugtheclient
Ifentriesinthesefilesdonothelpsolvetheproblem,try
connectingwiththevoption(eithersshorscptheresultsshould
bethesame).OpenSSHdisplaysalotofmessagesandoneof
themmayhelpyoufigureoutwhattheproblemis.
$ssh-vgrape
OpenSSH_4.2p1,OpenSSL0.9.8a11Oct2005
debug1:Readingconfigurationdata/etc/ssh/ssh_config
debug1:Applyingoptionsfor*
debug1:Connectingtogrape[192.168.0.3]port22.
debug1:Connectionestablished.
debug1:identityfile/home/sam/.ssh/identitytype-1
debug1:identityfile/home/sam/.ssh/id_rsatype1
...
debug1:Host'grape'isknownandmatchestheRSAhostkey.
debug1:Foundkeyin/home/sam/.ssh/known_hosts:2
debug1:ssh_rsa_verify:signaturecorrect
...
debug1:Authenticationsthatcancontinue:publickey,password,keyboard-interactive
debug1:Tryingprivatekey:/home/sam/.ssh/id_dsa
debug1:Nextauthenticationmethod:keyboard-interactive
debug1:Authenticationsthatcancontinue:publickey,password,keyboard-interactive
debug1:Nextauthenticationmethod:password
sam@grape'spassword:
Debugtheserver
Youcandebugfromtheserversidebyrunningsshdwiththe
deoptions.Theserverwillrunintheforegroundanditsdisplay
mayhelpyousolvetheproblem.
Tunneling/PortForwarding
Thesshutilityallowsyoutoforwardaport(portforwarding,
page1049)throughtheencryptedconnectionitestablishes.
Becausethedatasentacrosstheforwardedportusesthe
encryptedsshconnectionasitsdatalinklayer(page351),the
termtunneling(page1061)isappliedtothistypeof
connection:"Theconnectionistunneledthroughssh."Youcan
secureprotocolsincludingPOP,X,IMAP,andWWWbytunneling
themthroughssh.
ForwardingX11
ThesshutilitymakesiteasytotunneltheX11protocol.ForX11
tunnelingtowork,youmustenableitonboththeserverand
theclient.Ontheserver,youenableX11forwardingbysetting
theX11Forwardingdeclarationtoyesinthe
/etc/ssh/sshd_configfile(page595).
Trustedclients
InthepasttherewasonlyonewayforaclienttoenableX11
forwarding;todaytherearetwoways.Previously,whenyou
enabledX11forwarding(bysettingForwardX11toyesina
configurationfileorbyusingtheXoptiononthesshcommand
line)onaclient,theclientconnectedasatrustedclient,which
meantthattheclienttrustedtheserver,andwasgivenfull
accesstotheX11display.WithfullaccesstotheX11display,in
somesituationsaclientmaybeabletomodifyotherclientsof
theXdisplay.Makeasecureconnectiononlywhenyoutrustthe
remotesystem.(Youdonotwantsomeonetamperingwithyour
client.)Ifthisconceptisconfusing,seethetip"TherolesofX
clientandservermaybecounterintuitive"onpage235.
Nontrustedclients
AsofFedoraCore3andRHELversion4(OpenSSH3.8and
later),ansshclientcanconnecttoansshserverasatrusted
clientorasanontrustedclient.Anontrustedclientisgiven
limitedaccesstotheX11displayandcannotmodifyother
clientsoftheXdisplay.
Fewclientsworkproperlywhentheyareruninnontrusted
mode.IfyouarerunninganXclientinnontrustedmodeand
youencounterproblems,tryrunningintrustedmode(assuming
youtrusttheremotesystem).RedHatLinuxsetsupsshclients
torunintrustedmodebydefault.
Runningssh
Whenyoustartansshclient,youcanusetheYoption(page
587)onthecommandlinetostarttheclientintrustedmode.
ThisoptionperformsthesamefunctionastheXoptiondidin
earlierversionsofssh.OryoucansettheForwardX11trusted
declarationtoyesinauser's~/.ssh/configconfigurationfile
(page590)or,workingasroot,youcansetForwardX11trusted
toyesintheglobal/etc/ssh/ssh_configfile(page590)to
enabletrustedX11tunneling.
TousenontrustedtunnelingyoucanusetheXoption(page
587)orsettheForwardX11declarationtoyesinoneofthe
configurationfiles(page590).
WithX11forwardingturnedon,sshtunnelstheX11protocol,
settingtheDISPLAYenvironmentvariableonthesystemit
connectstoandforwardingtherequiredport.Youmusthave
theDISPLAYvariableset.Typicallyyouwillberunningfroma
GUI,whichusuallymeansthatyouareusingsshonaterminal
emulatortoconnecttoaremotesystem.WhenyougiveanX11
commandfromansshprompt,OpenSSHcreatesanewsecure
channelthatcarriestheX11data.Thegraphicaloutputfrom
theX11programappearsonyourscreen.
[peach]$sshspeedy
[speedy]$echo$DISPLAY
localhost:10.0
Bydefault,sshusesXWindowSystemdisplaynumbers10and
higher(portnumbers6010andhigher)forforwardedX
sessions.Onceyouconnecttoaremotesystemusingssh,you
cangiveacommandtorunanXapplication.Theapplication
willthenrunontheremotesystemwithitsdisplayappearing
onthelocalsystem,sothatitappearstorunlocally.
Portforwarding
YoucanforwardarbitraryportsusingtheLandRoptions.The
Loptionforwardsalocalporttoaremotesystem,sothata
programthattriestoconnecttotheforwardedportonthelocal
systemtransparentlyconnectstotheremotesystem.TheR
optiondoesthereverse:Itforwardsremoteportstothelocal
system.TheNoption,whichpreventssshfromexecuting
remotecommands,isgenerallyusedwithLandR.Whenyou
specifyN,sshworksonlyasaprivatenetworktoforwardports.
Ansshcommandlineusingoneoftheseoptionshasthe
followingformat:
$sshNL|Rlocal-port:remote-host:remote-porttarget
wherelocal-portisthenumberofthelocalportthatisbeing
forwardedtoorfromremote-host,remote-hostisthename
orIPaddressofthesystemthatlocal-portgetsforwardedto
orfrom,remote-portisthenumberoftheportonremote-
hostthatisbeingforwardedfromortothelocalsystem,and
targetisthenameorIPaddressofthesystemsshconnectsto.
Asanexample,assumethatthereisaPOPmailclientonthe
localsystemandthatthePOPserverisonaremotenetwork,
onasystemnamedpophost.POPisnotasecureprotocol;
passwordsaresentincleartexteachtimetheclientconnectsto
theserver.YoucanmakeitmoresecurebytunnelingPOP
throughssh(POP-3connectsonport110;port1550isan
arbitraryportonthelocalsystem):
$ssh-N-L1550:pophost:110pophost
Aftergivingtheprecedingcommand,youcanpointthePOP
clientatlocalhost:1550,andtheconnectionbetweenthe
clientandtheserverwillbeencrypted.(Whenyousetupan
accountonthePOPclient,specifythelocationoftheserveras
localhost,port1550;detailsvarywithdifferentmailclients.)
Inthisexample,remote-hostandtargetarethesame
system.
Firewalls
Thesystemspecifiedforportforwarding(remote-host)does
nothavetobethesameasthedestinationofthesshconnection
(target).Asanexample,assumethePOPserverisbehinda
firewallandyoucannotconnecttoitviassh.Ifyoucanconnect
tothefirewallviatheInternetusingssh,youcanencryptthe
partoftheconnectionovertheInternet:
$ssh-N-L1550:pophost:110firewall
Hereremote-host,thesystemreceivingtheportforwarding,is
pophost,andtarget,thesystemthatsshconnectsto,is
firewall.
Youcanalsousesshwhenyouarebehindafirewall(thatis
runningsshd)andwanttoforwardaportintoyoursystem
withoutmodifyingthefirewallsettings:
$ssh-R1678:localhost:80firewall
Theprecedingcommandforwardsconnectionsfromtheoutside
toport1678onthefirewalltothelocalWebserver.Forwarding
connectionsinthismannerallowsyoutouseaWebbrowserto
connecttoport1678onthefirewallinordertoconnecttothe
Webserveronthelocalsystem.Thissetupwouldbeusefulif
youranaWebmailprogram(page644)onthelocalsystem
becauseitwouldallowyoutocheckyourmailfromanywhere
usinganInternetconnection.
Compression
Compression,whichisenabledwiththeCoption,canspeedup
communicationoveralow-bandwidthconnection.Thisoptionis
commonlyusedwithportforwarding.Compressioncanincrease
latencytoanextentthatmaynotbedesirableforanXsession
forwardedoverahigh-bandwidthconnection.
ChapterSummary
OpenSSHisasuiteofsecurenetworkconnectivitytoolsthat
encryptsalltraffic,includingpasswords,therebythwarting
malicioususerswhomightotherwiseeavesdrop,hijack
connections,andstealpasswords.Thecomponentsdiscussedin
thischapteraresshd(theserverdaemon),ssh(runsa
commandonorlogsinonanothersystem),scp(copiesfiles
to/fromanothersystem),sftp(securelyreplacesftp),andssh-
keygen(createsauthenticationkeys).
Toensuresecurecommunications,whenanOpenSSHclient
opensaconnection,itfirstverifiesthatitisconnectedtothe
correctserver.ThenOpenSSHencryptscommunicationbetween
thesystems.FinallyOpenSSHmakessurethattheuseris
authorizedtologinonorcopyfilesfrom/totheserver.
OpenSSHalsoenablessecureX11forwarding.Withthisfeature,
youcanrunsecurelyagraphicalprogramonaremotesystem
andhavethedisplayappearonthelocalsystem.
Exercises
1. Whatisthedifferencebetweenthescpandsftputilities?
2. Howcanyouusesshtofindoutwhoisloggedinonaremotesystem?
3. Howwouldyouusescptocopyyour~/.bashrcfilefrombravotothelocal
system?
4. Howwouldyouusesshtorunxtermonbravoandshowthedisplayonthelocal
system?
5. WhatproblemcanenablingcompressionpresentwhenusingsshtorunremoteX11
applicationsonalocaldisplay?
6.
WhenyoutrytoconnecttoanothersystemusinganOpenSSHclientandyouseea
messagewarningyouthattheremotehostidentificationhaschanged,whathas
happened?Whatshouldyoudo?
AdvancedExercises
7. Whichscpcommandwouldyouusetocopyyourhomedirectoryfrombravotothe
localsystem?
8. Whichsinglecommandcouldyougivetologinasrootontheremotesystem
namedbravo,ifbravohasremoterootloginsdisabled?
9. Howcouldyouusesshtocomparethecontentsofthe~/memosdirectorieson
bravoandthelocalsystem?
19.FTP:TransferringFilesAcrossa
Network
INTHISCHAPTER
FTPClient 603
JumpStart:DownloadingFilesUsingftp 604
AnonymousFTP 607
AutomaticLogin 607
BinaryVersusASCIITransferMode 608
FTPServer(vsftpd) 612
JumpStart:StartingavsftpdServer 613
vsftpd.conf:ThevsftpdConfigurationFile 614
FileTransferProtocolisamethodofdownloadingfilesfromand
uploadingfilestoanothersystemusingTCP/IPoveranetwork.
FileTransferProtocolisthenameofaclient/serverprotocol
(FTP)andaclientutility(ftp)thatinvokestheprotocol.In
additiontotheoriginalftputility,therearemanytextualand
graphicalFTPclientprograms,includingmostbrowsers,that
runundermanydifferentoperatingsystems.Therearealso
manyFTPserverprograms.
Introduction
Firstimplementedunder4.2BSD,FTPhasplayedanessential
roleinthepropagationofLinux;thisprotocol/programis
frequentlyusedtodistributefreesoftware.ThetermFTPsite
referstoanFTPserverthatisconnectedtoanetwork,usually
theInternet.FTPsitescanbepublic,allowinganonymoususers
tologinanddownloadsoftwareanddocumentation.In
contrast,privateFTPsitesrequireyoutologinwithausername
andpassword.Somesitesallowyoutouploadprograms.
ftpandvsftpd
AlthoughmostFTPclientsaresimilar,theserversdifferquitea
bit.Thischapterdescribestheftpclientwithreferencestosftp,a
secureFTPclient.ItalsocoverstheFTPserverthatRedHat
usesinternallyandoffersaspartofitsdistribution,vsftpd
(verysecureFTP).
Security
FTPisnotasecureprotocol.Allusernamesandpasswords
exchangedinsettingupanFTPconnectionaresentincleartext,
dataexchangedoveranFTPconnectionisnotencrypted,and
theconnectionissubjecttohijacking.FTPisbestusedfor
downloadingpublicfiles.Inmostcases,theOpenSSHclients,
ssh(page585),scp(page588),andsftp(page589),offersecure
alternativestoFTP.
Security:UseFTPonlytodownload
publicinformation
FTPisnotsecure.YoucanusescpforalmostallFTP
functionsotherthanallowinganonymoususersto
downloadinformation.Becausescpusesan
encryptedconnection,userpasswordsanddata
cannotbesniffed.Seepage585formore
informationonscp.
Thevsftpdserverdoesnotmakeusernames,passwords,data,
andconnectionsmoresecure.Thevsftpdserverissecurein
thatamalicioususerfindsitmoredifficulttocompromise
directlythesystemrunningit,evenifvsftpdispoorly
implemented.Onefeaturethatmakesvsftpdmoresecurethan
ftpdisthatitdoesnotrunwithrootprivileges.Seealso
"Security"onpage613
ftputility
TheftputilityisauserinterfacetoFileTransferProtocol(FTP),
thestandardprotocolusedtotransferfilesbetweensystems
thatcancommunicateoveranetwork.
sftputility
PartoftheOpenSSHsuite,sftpisasecurealternativetoftp.See
page589formoreinformation.
FTPconnections
FTPusestwoconnections:oneforcontrol(youestablishthis
connectionwhenyouloginonanFTPserver)andonefordata
transfer(FTPsetsupthisconnectionwhenyouaskittotransfer
afile).AnFTPserverlistensforincomingconnectionsonport
21bydefaultandhandlesuserauthenticationandfile
exchange.
Passiveversusactiveconnections
AclientcanaskanFTPservertoestablisheitheraPASV
(passivethedefault)oraPORT(active)connectionfordata
transfer.Someserversarelimitedtoonlyonetypeof
connection.ThedifferencebetweenapassiveandanactiveFTP
connectionliesinwhethertheclientorserverinitiatesthedata
connection.Inpassivemode,theclientinitiatestheconnection
totheserver(onport20bydefault);inactivemode,theserver
initiatestheconnection(thereisnodefaultport;see
"ConnectionParameters"onpage622fortheparametersthat
determinewhichportsareused).Neitherisinherentlymore
securethantheother.Passiveconnectionsaremorecommon
becauseaclientbehindaNAT(page764)canconnecttoa
passiveserveranditissimplertoprogramascalablepassive
server.
Theparametersthatcontrolthetypeofconnectionthata
MoreInformation
Local
Typehelpor?atanftp>prompttodisplayalistof
commands.Followthe?withaSPACEandanftpcommandto
displayinformationaboutthatcommand.
Files/usr/share/doc/vsftpd*
manpagesftp,netrc,vsftpd.conf
Web
vsftpdhomepagevsftpd.beasts.org
HOWTO
FTPmini-HOWTO
FTPClient
ftp
RedHatsuppliesseveralFTPclientsincludingftp(anolder
versionoftheBSDftputility).Thissectiondiscussesftpbecause
mostotherFTPclientsprovideasupersetofftpcommands.
sftp
PartoftheOpenSSHsuite,sftpisasecurealternativetoftp.See
page589formoreinformation.
gftp
Thegftputility(gftppackage)isagraphicalclientthatworks
withFTP,SSH,andHTTPservers.Thisclienthasmanyuseful
features,includingtheabilitytoresumeaninterruptedfile
transfer.Seethegftpmanpageformoreinformation.
ncftp
Thencftputility(ncftppackage)isatextualclientthatoffers
manymorefeaturesthanftp,includingfilenamecompletionand
commandlineediting.Seethencftpmanpagefordetails.
Prerequisites
TheftpandsftputilitiesareinstalledonmostRedHatsystems.
Youcancheckfortheirpresencebygivingeitherofthese
utilities'namesascommands:
$ftp
ftp>quit
$sftp
usage:sftp[-1Cv][-Bbuffer_size][-bbatchfile][-Fssh_config]
[-ossh_option][-Psftp_server_path][-Rnum_requests]
[-Sprogram][-ssubsystem|sftp_server]host
sftp[[user@]host[:file[file]]]
sftp[[user@]host[:dir[/]]]
sftp-bbatchfile[user@]host
Installtheftporopenssh-clients(containssftp)packageif
needed.
JumpStart:DownloadingFilesUsingftp
ThisJumpStartsectionisbrokenintotwoparts:adescriptionof
thebasiccommandsandatutorialsessionthatshowsauser
workingwithftp.
BasicCommands
Givethecommand
$ftphostname
wherehostnameisthenameoftheFTPserveryouwantto
connectto.Ifyouhaveanaccountontheserver,loginwith
yourusernameandpassword.Ifitisapublicsystem,loginas
theuseranonymous(orftp)andgiveyouremailaddressas
yourpassword.Usethelsandcdftpcommandsontheserver
asyouwouldusethecorrespondingutilitiesfromashell.The
commandgetfilecopiesfilefromtheservertothelocal
system,putfilecopiesfilefromthelocalsystemtotheserver,
statusdisplaysinformationabouttheFTPconnection,andhelp
displaysalistofcommands.
Theprecedinginstructions,exceptforstatus,alsoworkfrom
sftpandncftp.
TutorialSession
FollowingaretwoftpsessionswhereinAlextransfersfilesfrom
andtoavsftpdservernamedbravo.WhenAlexgivesthe
commandftpbravo,thelocalftpclientconnectstotheserver,
whichasksforausernameandpassword.Becauseheislogged
inonhislocalsystemasalex,ftpsuggeststhatAlexloginon
bravoasalex.Tologinasalex,hecouldjustpressRETURN.
Becausehisusernameonbravoiswatson,however,hetypes
watsoninresponsetotheName(bravo:alex):prompt.Alex
respondstothePassword:promptwithhisnormalsystem
password,andthevsftpdservergreetshimandinformshim
thatitisUsingbinarymodetotransferfiles.Withftpin
binarymode,AlexcantransferASCIIandbinaryfiles(page
608).
Connectandlogin
$ftpbravo
Connectedtobravo.
220(vsFTPd2.0.4)
530PleaseloginwithUSERandPASS.
530PleaseloginwithUSERandPASS.
KERBEROS_V4rejectedasanauthenticationtype
Name(bravo:alex):watson
331Pleasespecifythepassword.
Password:
230Loginsuccessful.
RemotesystemtypeisUNIX.
Usingbinarymodetotransferfiles.
ftp>
Afterloggingin,Alexusestheftplscommandtoseewhatisin
hisremoteworkingdirectory,whichishishomedirectoryon
bravo.Thenhecdstothememosdirectoryanddisplaysthe
filesthere.
lsandcd
ftp>ls
227EnteringPassiveMode(192,168,0,6,79,105)
150Herecomesthedirectorylisting.
drwxr-xr-x25005004096Oct1023:52expenses
drwxr-xr-x25005004096Oct1023:59memos
drwxrwxr-x225005004096Oct1023:32tech
226DirectorysendOK.
ftp>cdmemos
250Directorysuccessfullychanged.
ftp>ls
227EnteringPassiveMode(192,168,0,6,114,210)
150Herecomesthedirectorylisting.
-rw-r--r--15005004770Oct1023:58memo.0514
-rw-r--r--15005007134Oct1023:58memo.0628
-rw-r--r--15005009453Oct1023:58memo.0905
-rw-r--r--15005003466Oct1023:59memo.0921
-rw-r--r--15005001945Oct1023:59memo.1102
226DirectorysendOK.
NextAlexusestheftpgetcommandtocopymemo.1102from
theservertothelocalsystem.Binarymodeensuresthathewill
getagoodcopyofthefileregardlessofwhetheritisbinaryor
ASCII.Theserverconfirmsthatthisfilewascopiedsuccessfully
andreportsonthesizeofthefileandhowlongittooktocopy.
Alexthencopiesthelocalfilememo.1114totheremote
system.Thefileiscopiedintohisremoteworkingdirectory,
memos.
getandput
ftp>getmemo.1102
local:memo.1102remote:memo.1102
227EnteringPassiveMode(192,168,0,6,194,214)
150OpeningBINARYmodedataconnectionformemo.1102(1945bytes).
226FilesendOK.
1945bytesreceivedin7.1e-05secs(2.7e+04Kbytes/sec)
ftp>putmemo.1114
local:memo.1114remote:memo.1114
227EnteringPassiveMode(192,168,0,6,174,97)
150Oktosenddata.
226FilereceiveOK.
1945bytessentin2.8e-05secs(6.8e+04Kbytes/sec)
NowAlexdecideshewantstocopyallthefilesinthememo
directoryonbravotoanewdirectoryonhislocalsystem.He
givesanlscommandtomakesurehewillcopytherightfiles,
butftphastimedout.Insteadofexitingfromftpandgiving
anotherftpcommandfromtheshell,hegivesftpanopen
bravocommandtoreconnecttotheserver.Afterloggingin,he
usestheftpcdcommandtochangedirectoriestomemoson
theserver.
Timeoutandopen
ftp>ls
Nocontrolconnectionforcommand:Badfiledescriptor
Passivemoderefused.Turningoffpassivemode.
Nocontrolconnectionforcommand:Badfiledescriptor
ftp>openbravo
Connectedtobravo(192.168.0.6).
220(vsFTPd1.1.3)
...
ftp>cdmemos
250Directorysuccessfullychanged.
Localcd(lcd)
Atthispoint,Alexrealizeshehasnotcreatedthenewdirectory
toholdthefileshewantstodownload.Givinganftpmkdir
commandwouldcreateanewdirectoryontheserver,butAlex
wantsanewdirectoryonhislocalsystem.Heusesan
exclamationpoint(!)followedbyamkdirmemos.hold
commandtoinvokeashellandrunmkdironthelocalsystem,
creatingadirectorynamedmemos.holdinhisworking
directoryonthelocalsystem.(Youcandisplaythenameof
yourworkingdirectoryonthelocalsystemwith!pwd.)Next,
becauseAlexwantstocopyfilesfromtheservertothe
memos.holddirectoryonhislocalsystem,hehastochange
hisworkingdirectoryonthelocalsystem.Givingthecommand
!cdmemos.holdwillnotaccomplishwhatAlexwantstodo
becausetheexclamationpointwillspawnanewshellonthe
localsystemandthecdcommandwouldbeeffectiveonlyinthe
newshell,whichisnottheshellthatftpisrunningunder.For
thissituation,ftpprovidesthelcd(localcd)command,which
changestheworkingdirectoryforftpandreportsonthenew
localworkingdirectory:
ftp>!mkdirmemos.hold
ftp>lcdmemos.hold
Localdirectorynow/home/alex/memos.hold
Alexusestheftpmget(multipleget)commandfollowedbythe
asterisk(*)wildcardtocopyallfilesfromtheremotememos
directorytothememos.holddirectoryonthelocalsystem.
Whenftppromptshimforthefirstfile,Alexrealizesthathe
forgottoturnoffprompts,soherespondswithnandpresses
CONTROL-Ctostopcopyingfilesinresponsetothesecond
prompt.Theservercheckswhetherhewantstocontinuewith
hismgetcommand.
NextAlexgivestheftppromptcommand,whichtogglesthe
promptaction(turnsitoffifitisonandturnsitonifitisoff).
Nowwhenhegivesamget*command,ftpcopiesallthefiles
withoutpromptinghim.Aftergettingthedesiredfiles,Alex
givesaquitcommandtoclosetheconnectionwiththeserver,
exitfromftp,andreturntothelocalshellprompt.
mgetandprompt
ftp>mget*
mgetmemo.0514?n
mgetmemo.0628?CONTROL-C
Continuewithmget?n
ftp>prompt
Interactivemodeoff.
ftp>mget*
local:memo.0514remote:memo.0514
227EnteringPassiveMode(192,168,0,6,53,55)
150OpeningBINARYmodedataconnectionformemo.0514(4770bytes).
226FilesendOK.
4770bytesreceivedin8.8e-05secs(5.3e+04Kbytes/sec)
local:memo.0628remote:memo.0628
227EnteringPassiveMode(192,168,0,6,65,102)
150OpeningBINARYmodedataconnectionformemo.0628(7134bytes).
226FilesendOK.
...
150OpeningBINARYmodedataconnectionformemo.1114(1945bytes).
226FilesendOK.
1945bytesreceivedin3.9e-05secs(4.9e+04Kbytes/sec)
ftp>quit
221Goodbye.
Notes
ALinuxsystemrunningftpcanexchangefileswithanyofthe
manyoperatingsystemsthatsupportFTP.Manysitesoffer
archivesoffreeinformationonanFTPserver,althoughfor
manyitisjustanalternativetoaneasier-to-accessWebsite
(see,forexample,ftp://ftp.ibiblio.org/pub/Linuxand
http://www.ibiblio.org/pub/Linux).Mostbrowserscanconnect
toanddownloadfilesfromFTPservers.
Theftputilitymakesnoassumptionsaboutfilesystemnamingor
structurebecauseyoucanuseftptoexchangefileswithnon-
UNIX/Linuxsystems(whichmayusedifferentfilenaming
conventions).
AnonymousFTP
Manysystemsmostnotablythosefromwhichyoucandownload
freesoftwareallowyoutologinasanonymous.Mostsystems
thatsupportanonymousloginsacceptthenameftpasan
easier-to-spellandquicker-to-entersynonymforanonymous.
Ananonymoususerisusuallyrestrictedtoaportionofa
filesystemsetasidetoholdfilesthataretobesharedwith
remoteusers.Whenyouloginasananonymoususer,the
serverpromptsyoutoenterapassword.Althoughany
passwordmaybeaccepted,byconventionyouareexpectedto
supplyyouremailaddress.Manysystemsthatpermit
anonymousaccessstoreinterestingfilesinthepubdirectory.
Mostbrowsers,suchasFirefox,loginonananonymousFTP
siteandtransferafilewhenyouclickonthefilename.
AutomaticLogin
Youcanstoreserver-specificFTPusernameandpassword
informationsothatyoudonothavetoenteriteachtimeyou
visitanFTPsite.Eachlineof~/.netrcidentifiesaserver.When
youconnecttoanFTPserver,ftpreadsthe~/.netrcfileto
determinewhetheryouhaveanautomaticloginsetupforthat
server.Theformatofalinein~/.netrcis
machineserverloginusernamepasswordpasswd
whereserveristhenameoftheserver,usernameisyour
username,andpasswdisyourpasswordonserver.Replace
machinewithdefaultonthelastlineofthefiletospecifya
usernameandpasswordforsystemsnotlistedin~/.netrc.The
defaultlineisusefulforlogginginonanonymousservers.A
sample~/.netrcfilefollows:
$cat~/.netrc
machinebravologinalexpasswordmypassword
defaultloginanonymouspasswordalex@tcorp.com
Toprotecttheaccountinformationin.netrc,makeitreadable
byonlytheuserwhosehomedirectoryitappearsin.Referto
thenetrcmanpageformoreinformation.
BinaryVersusASCIITransferMode
ThevsftpdFTPservercanbutdoesnotalwaysprovidetwo
modestotransferfiles.Binarymodetransfersalwayscopyan
exact,byte-for-byteimageofafileandneverchangeline
endings.Transferallbinaryfilesusingbinarymode.Unlessyou
needtoconvertlineendings,usebinarymodetotransferASCII
filesaswell.
ASCIIfiles,suchastextorprogramsourcecode,whencreated
underLinuxwithatexteditorsuchasvi,useasingleNEWLINE
character(CONTROL-J,writtenas\n)tomarktheendofeach
line.Otheroperatingsystemsmarktheendsoflinesdifferently.
WindowsmarkstheendofeachsuchlinewithaRETURN
(CONTROL-M,writtenas\r)followedbyaNEWLINE(two
characters).MacintoshusesaRETURNbyitself.These
descriptionsdonotapplytofilescreatedbywordprocessors
suchasWordorOpenOfficebecausethoseprogramsgenerate
binaryfiles.
ThevsftpdFTPservercanmapLinuxlineendingstoWindows
lineendingsasyouuploadfilesandWindowslineendingsto
Linuxlineendingsasyoudownloadfiles.Althoughyoucould
arguethatthesefeaturesshouldbeontheclientandnotthe
server,theyareincorporatedinvsftpd,wheretheASCII
downloadfeaturecanbeasecurityrisk.
TouseASCIImodeonanFTPserverthatallowsit,givean
asciicommand(page610)afteryouloginandsetcrtoON
(thedefault,page610).Iftheserverdoesnotallowyouto
changelineendingsasyoutransferafile,youcanusethe
unix2dos(page139)ordos2unix(page139)utilitybeforeorafter
youtransferafileinbinarymode.
Security
Whenrunagainstaverylargefile,theftpsizecommand,which
displaysthesizeofafile,consumesalotofserverresources
andcanbeusedtoinitiateaDoSattack(page1030).To
enhancesecurity,bydefaultvsftpdtransferseveryfilein
binarymode,evenwhenitappearstobeusingASCIImode.On
theserverside,youcanenablerealASCIImodetransfersby
settingtheascii_upload_enableand
ascii_download_enableparameters(page619)toYES.With
theserversettoallowASCIItransfers,theclientcontrols
whetherlineendingsaremappedbyusingtheascii,binary,
andcrcommands(page610).
ftpSpecifics
Thissectioncoversthedetailsofusingftp.
Format
Anftpcommandlinehasthefollowingformat:
ftp[options][ftp-server]
whereoptionsisoneormoreoptionsfromthelistinthenext
sectionandftp-serveristhenameornetworkaddressofthe
FTPserverthatyouwanttoexchangefileswith.Ifyoudonot
specifyanftp-server,youwillneedtousetheftpopen
commandtoconnecttoaserveronceftpisrunning.
CommandLineOptions
g
(globbing)Turnsoffglobbing.Seeglob(page610).
i
(interactive)Turnsoffpromptsduringfiletransferswithmget
(page610)andmput(page610).Seealsoprompt(page
611).
n
(noautomaticlogin)Disablesautomaticlogins(page607).
v
(verbose)Tellsyoumoreabouthowftpisworking.Responses
fromtheremotecomputeraredisplayed,andftpreports
informationonhowquicklyfilesaretransferred.Seealso
verbose(page612).
ftpCommands
Theftputilityisinteractive:Afteryoustartftp,itpromptsyouto
entercommandstosetparametersortransferfiles.Youcan
abbreviatecommandsaslongastheabbreviationsareunique.
Enteraquestionmark(?)inresponsetotheftp>promptto
displayalistofcommands.Followthequestionmarkbya
SPACEandacommandtodisplayabriefdescriptionofwhatthe
commanddoes:
ftp>?mget
mgetgetmultiplefiles
ShellCommand
![command]
Withoutcommand,escapesto(spawns)ashellonthelocal
system.UseCONTROL-Dorexittoreturntoftpwhenyouare
finishedusingthelocalshell.Followtheexclamationpointwith
commandtoexecutethatcommandonly;ftpdisplaysanftp>
promptwhenexecutionofthecommandfinishes.Becausethe
shellthatftpspawnswiththiscommandisachildoftheshell
thatisrunningftp,nochangesyoumakeinthisshellare
preservedwhenyoureturntoftp.Specifically,whenyouwantto
copyfilestoalocaldirectoryotherthanthedirectorythatyou
startedftpfrom,youneedtousetheftplcdcommandto
changeyourlocalworkingdirectory:Issuingacdcommandin
thespawnedshellwillnotmakethechangeyoudesire.See
"Localcd(lcd)"onpage606foranexample.
TransferFiles
Inthefollowingdescriptions,remote-fileandlocal-filecanbe
pathnames.
appendlocal-file[remote-file]
Appendslocal-filetothefileofthesamenameontheremote
systemortoremote-fileifspecified.
getremote-file[local-file]
Copiesremote-filetothelocalsystemunderthenamelocal-
file.Withoutlocal-file,ftpusesremote-fileasthefilenameon
thelocalsystem.
mgetremote-file-list
(multipleget)Copiesseveralfilestothelocalsystem,each
maintainingitsoriginalfilename.Youcannametheremotefiles
literallyorusewildcards(seeglob).Useprompt(page611)to
turnoffpromptsduringtransfers.
mputlocal-file-list
(multipleput)Copiesseveralfilestotheserver,each
maintainingitsoriginalfilename.Youcannamethelocalfiles
literallyorusewildcards(seeglob).Useprompt(page611)to
turnoffpromptsduringtransfers.
newerremote-file[local-file]
Ifthemodificationtimeofremote-fileismorerecentthanthat
oflocal-fileoriflocal-filedoesnotexist,copiesremote-file
tothelocalsystemunderthenamelocal-file.Withoutlocal-
file,ftpusesremote-fileasthefilenameonthelocalsystem.
Similartoget,butdoesnotoverwriteanewerfilewithanolder
one.
putlocal-file[remote-file]
Copieslocal-filetotheremotesystemunderthename
remote-file.Withoutremote-file,ftpuseslocal-fileasthe
filenameontheremotesystem.
regetremote-file[local-file]
Iflocal-fileexistsandissmallerthanremote-file,assumes
thatapreviousgetoflocal-filewasinterruptedandcontinues
fromwherethepreviousgetleftoff.Thiscommandcansave
timewhenagetofalargefilefailspartwaythroughthe
transfer.
Status
ascii
SetsthefiletransfertypetoASCII.Thecrcommandmustbe
ONforasciitowork(page608).
binary
Setsthefiletransfertypetobinary(page608).
bye
Closestheconnectiontotheserverandterminatesftp.Sameas
quit.
case
Togglesanddisplayscasemappingstatus.DefaultisOFF.When
ON,forgetandmgetcommands,mapsfilenamesthatareall
uppercaseontheservertoalllower-caseonthelocalsystem.
close
Closestheconnectiontotheserverwithoutexitingfromftp.
cr
(carriageRETURN)Togglesanddisplays(carriage)RETURN
strippingstatus.Effectiveonlywhenthefiletransfertypeis
ascii.SetcrtoON(default)toremoveRETURNcharactersfrom
RETURN/LINEFEEDlineterminationsequencesusedby
Windows,yieldingthestandardLinuxlineterminationof
LINEFEED.SetcrtoOFFtoleavelineendingsunmapped(page
608).
debug[n]
Toggles/setsanddisplaysdebuggingstatus/level,wherenis
thedebugginglevel.OFFor0(zero)isthedefault.Whenn>0,
displayseachcommandftpsendstotheserver.
glob
Togglesanddisplaysfilenameexpansion(page221)statusfor
mdelete(page611),mget(page610),andmput(page610)
commands.
hash
Togglesanddisplayspoundsign(#,alsocalledahashmark)
displaystatus.WhenON,ftpdisplaysonepoundsignforeach
1024-bytedatablockittransfers.
open[hostname]
Specifieshostnameasthenameoftheservertoconnectto.
Withouthostname,promptsforthenameoftheserver.Useful
whenaconnectiontimesoutorotherwisefails.
passive
Togglesbetweenactive(PORTthedefault)andpassive(PASV)
transfermodesanddisplaysthetransfermode.Formore
informationreferto"Passiveversusactiveconnections"onpage
602.
prompt
Togglesanddisplaysthepromptstatus.WhenON(default),
mdelete(page611),mget(page610),andmput(page610)
askforverificationbeforetransferringeachfile.SettoOFFto
turnofftheseprompts.
quit
Closestheconnectiontotheserverandterminatesftp.Sameas
bye.
umask[nnn]
Changestheumask(page420)appliedtofilescreatedonthe
servertonnn.Withoutnnn,displaystheumask.
user[username][password]
Promptsfororacceptstheusernameandpasswordthat
enableyoutologinontheserver.Whenyoucallitwiththen
option,ftppromptsyouforausernameandpassword
automatically.Formoreinformationreferto"AutomaticLogin"
onpage607.
Directories
cdremote-directory
Changestheworkingdirectoryontheservertoremote-
directory.
cdup
Changestheworkingdirectoryontheservertotheparentof
theworkingdirectory.
lcd[local_directory]
(localchangedirectory)Changestheworkingdirectoryon
thelocalsystemtolocal_directory.Withoutanargument,this
commandchangestheworkingdirectoryonthelocalsystemto
yourhomedirectory(justasthecdshellbuiltindoeswithoutan
argument).See"Localcd(lcd)"onpage606foranexample.
Files
chmodmoderemote-file
Changestheaccesspermissionsofremote-fileontheserver
tomode.Seechmodonpage182formoreinformationonhow
tospecifythemode.
deleteremote-file
Removesremote-filefromtheserver.
mdeleteremote-file-list
(multipledelete)Deletesthefilesspecifiedbyremote-file-
listfromtheserver.
DisplayInformation
dir[remote-directory][file]
Displaysalistingofremote-directoryfromtheserver.When
youdonotspecifyremote-directory,displaystheworking
directory.Whenyouspecifyfile,thelistingissavedonthelocal
systeminafilenamedfile.
help[command]
Displaysinformationaboutcommand.Withoutcommand,
displaysalistoflocalftpcommands.
ls[remote-directory][file]
Similartodirbutproducesamoreconciselistingfromsome
servers.Whenyouspecifyfile,thelistingissavedonthelocal
systeminafilenamedfile.
pwd
Displaysthepathnameoftheworkingdirectoryontheserver.
Use!pwdtodisplaythepathnameofthelocalworking
directory.
status
Displaysftpconnectionandstatusinformation.
verbose
Togglesanddisplaysverbosemode,whichdisplaysresponses
fromtheserverandreportsonhowquicklyfilesaretransferred.
Sameasspecifyingthevoptiononthecommandline.
FTPServer(vsftpd)
ThissectiondiscussesthevsftpdserverassuppliedbyRed
Hat.
Prerequisites
Installthefollowingpackage:
vsftpd
Runchkconfigtocausevsftpdtostartwhenthesystementers
multiusermode.
#/sbin/chkconfigvsftpdon
Startvsftpd:
#/sbin/servicevsftpdstart
Ifyouchangethevsftpd.confconfigurationfile,youneedto
restartvsftpd.
Notes
Thevsftpdservercanruninnormalmode(thexinetddaemon
[page425]callsvsftpdeachtimeaclienttriestomakea
connection)oritcanruninstand-alonemode(vsftpdrunsasa
daemonandhandlesconnectionsdirectly).
Stand-alonemode
Althoughbydefaultvsftpdrunsinnormalmode,RedHatsets
ituptoruninstand-alonemodebysettingthelisten
parameter(page615)toYESinthevsftpd.conffile.UnderRed
HatLinux,withvsftpdrunninginstand-alonemode,youstart
andstoptheserverusingserviceandthevsftpdinitscript.
Normalmode
Youmustinstallanxinetdcontrolfile(page425)ifyouwantto
runvsftpdinnormalmode.Asamplefilecanbefoundat
/usr/share/doc/vsftpd*/vsftpd.xinetd.Copythesample
filetothe/etc/xinetd.ddirectory,renameitvsftpd,andedit
thefiletochangethedisableparametertono.Withthelisten
parameterinvsftpd.confsettoNO,xinetdwilltakecareof
startingvsftpdasneeded.
Security
Thesafestpolicyisnottoallowuserstoauthenticateagainst
FTP:UseFTPforanonymousaccessonly.Ifyoudoallowlocal
userstoauthenticateanduploadfilestotheserver,besureto
putlocalusersinachrootjail(page616).BecauseFTPsends
usernamesandpasswordsincleartext,amalicioususercan
easilysniff(page1056)them.Withausernameandpassword,
thesameusercanimpersonatealocaluser,uploadaTrojan
horse(page1060),andcompromisethesystem.
Firewall
AnFTPservernormallyusesTCPport21.IftheFTPserver
systemisrunningafirewall,youneedtoopenthisport.Using
theRedHatgraphicalfirewalltool(page768),selectFTPfrom
theTrustedServicesframetoopenthisport.Formoregeneral
informationseeChapter25,whichdetailsiptables.
SELinux
WhenSELinuxissettouseatargetedpolicy,FTPisprotected
bySELinux.Youcandisablethisprotectionifnecessary.For
moreinformationreferto"SettingtheTargetedPolicywith
system-config-securitylevel"onpage402.
JumpStart:StartingavsftpdServer
Bydefault,underRedHatLinuxvsftpdallowslocaland
anonymoususerstologinontheserveranddoesnotsetupa
guestaccount.Whensomeonelogsinasananonymoususer,
thatpersonisworkinginthe/var/ftpdirectory.Youdonot
havetoconfigureanything.
TestingtheSetup
Makesurevsftpdisworkingbylogginginfromthesystem
runningtheserver.Youcanrefertotheserveraslocalhostor
byusingitshostnameonthecommandline.Loginas
anonymous;useanypassword.
$ftplocalhost
Connectedtolocalhost.localdomain.
220(vsFTPd2.0.4)
530PleaseloginwithUSERandPASS.
530PleaseloginwithUSERandPASS.
KERBEROS_V4rejectedasanauthenticationtype
Name(bravo:alex):anonymous
331Pleasespecifythepassword.
Password:
230Loginsuccessful.
RemotesystemtypeisUNIX.
Usingbinarymodetotransferfiles.
ftp>quit
221Goodbye.
Ifyouarenotabletoconnecttotheserver,firstmakesurethe
serverisrunning:
$/sbin/servicevsftpdstatus
vsftpd(pid3091)isrunning...
Nextcheckthatpermissionson/var/ftp,orthehome
directoryofftpasspecifiedin/etc/passwd,aresetto755.If
theftpusercanwriteto/var/ftp,connectionswillfail.
#ls-ld/var/ftp
drwxr-xr-x4rootroot4096Aug2723:54/var/ftp
Onceyouareabletologinfromthelocalsystem,loginfrom
anothersystemeitheroneontheLANoranothersystemwith
accesstotheserver.Onthecommandline,usethehostname
fromwithintheLANortheFQDN(page1032)fromoutsidethe
LAN.Thedialogshouldappearthesameasintheprevious
example.Ifyoucannotloginfromasystemthatisnotonyour
LAN,useping(page365)totesttheconnectionandmakesure
thefirewallissetuptoallowFTPaccess.See"FTPconnections"
onpage602foradiscussionofactiveandpassivemodesand
theportsthateachmodeuses.
vsftpd.conf:ThevsftpdConfigurationFile
Theconfigurationfileforvsftpd,/etc/vsftpd/vsftpd.conf,
listsBoolean,numeric,andstringname-valuepairsof
configurationparameters,calleddirectives.Eachname-value
pairisjoinedbyanequalsignwithnoSPACEsoneitherside.
RedHatLinuxprovidesawell-commented
/etc/vsftpd/vsftpd.conffilethatchangesmanyofthe
compiled-indefaults.Thissectioncoversmostoftheoptions,
notingtheirdefaultvaluesandtheirvaluesasspecifiedinthe
vsftpd.conffilesuppliedwithRedHatLinux.
SetBooleanoptionstoYESorNOandnumericoptionstoa
nonnegativeinteger.Octalnumbers,whichareusefulforsetting
umaskoptions,musthavealeading0(zero).Numberswithouta
leadingzeroaretreatedasbase10numbers.Followingare
examplesfromvsftpd.confofsettingeachtypeofoption:
anonymous_enable=YES
local_umask=022
xferlog_file=/var/log/vsftpd.log
Descriptionsofthedirectivesarebrokenintothefollowing
groups:
Stand-alonemode(page615)
Loggingin(page615)
Workingdirectoryandthechrootjail(page616)
Downloadinganduploadingfiles(page618)
Messages(page620)
Display(page620)
Logs(page621)
Connectionparameters(page622)
Stand-AloneMode
Referto"Notes"onpage607foradiscussionofnormaland
stand-alonemodes.Thissectiondescribestheparametersthat
affectstand-alonemode.
listen
YESrunsvsftpdinstand-alonemode;NOrunsitinnormal
mode.
Default:NO
RedHat:YES
listen_address
Instand-alonemode,specifiestheIPaddressofthelocal
interfacethatvsftpdlistensonforincomingconnections.When
notset,vsftpdusesthedefaultnetworkinterface.
Default:none
listen_port
Instand-alonemode,specifiestheportthatvsftpdlistenson
forincomingconnections.
Default:21
max_clients
Instand-alonemode,specifiesthemaximumnumberofclients.
Zero(0)indicatesunlimitedclients.
Default:0
max_per_ip
Instand-alonemode,specifiesthemaximumnumberofclients
fromthesameIPaddress.Zero(0)indicatesunlimitedclients
fromthesameIPaddress.
Default:0
LoggingIn
Threeclassesofuserscanloginonavsftpdserver:
anonymous,local,andguest.Theguestuserisrarelyusedand
isnotcoveredinthischapter.Localusersloginwiththeir
systemusernameandpassword.Anonymoususersloginwith
anonymousorftp,usingtheiremailaddressasapassword.
Youcancontrolwhethereachoftheseclassesofuserscanlog
inontheserverandwhattheycandooncetheylogin.Youcan
alsospecifywhatalocalusercandoonaper-userbasis;refer
touser_config_dironpage624.
LocalUsers
userlist_enable
The/etc/vsftpd/user_listfile(page624),oranotherfile
specifiedbyuserlist_file,containsalistofzeroormoreusers.
YESconsultsthislistandtakesactionbasedonuserlist_deny,
eithergrantingordenyingusersinthelistpermissiontologin
ontheserver.Topreventthetransmissionofcleartext
passwords,accessisdeniedimmediatelyaftertheuserenters
herusername.NOdoesnotconsultthelist.Foramoresecure
system,settoNO.
Default:NO
RedHat:YES
userlist_deny
YESpreventsuserslistedin/etc/vsftpd/user_list(page624)
fromlogginginontheserver.NOallowsonlyuserslistedin
/etc/vsftpd/user_listtologinontheserver.Use
userlist_filetochangethenameofthefilethatthisparameter
consults.Thisparameterischeckedonlywhenuserlist_enable
issettoYES.
Default:YES
userlist_file
Thenameofthefileconsultedwhenuserlist_enableissetto
YES.
Default:/etc/vsftpd/user_list
local_enable
YESpermitslocalusers(userslistedin/etc/passwd)tologin
ontheserver.
Default:NO
RedHat:YES
AnonymousUsers
anonymous_enable
YESallowsanonymouslogins.
Default:YES
no_anon_password
YESskipsaskinganonymoususersforpasswords.
Default:NO
deny_email_enable
YEScheckswhetherthepassword(emailaddress)thatan
anonymoususerentersislistedin
/etc/vsftpd/banned_emailsorotherfilespecifiedby
banned_email_file.Ifitis,theuserisnotallowedtologinon
thesystem.NOdoesnotperformthischeck.Usingiptables(page
763)toblockspecifichostsisgenerallymoreproductivethan
usingthisparameter.
Default:NO
banned_email_file
Thenameofthefileconsultedwhendeny_email_enableis
settoYES.
Default:/etc/vsftpd/banned_emails
WorkingDirectoryandthechrootJail
Whenauserlogsinonavsftpdserver,standardfilesystem
accesspermissionscontrolwhichdirectoriesandfilestheuser
canaccessandhowtheusercanaccessthem.Threebasic
parameterscontrolauserwhoisloggedinonavsftpdserver:
UserID(UID)
Initialworkingdirectory
Rootdirectory
Bydefault,thevsftpdserversetstheuserIDofalocaluserto
thatuser'susernameandsetstheuserIDofananonymous
usertoftp.Alocaluserstartsinherhomedirectoryandan
anonymoususerstartsin/var/ftp.
Bydefault,anonymoususersareplacedinachrootjailfor
security;localusersarenot.Forexample,whenananonymous
userlogsinonavsftpdserver,hishomedirectoryis/var/ftp.
Allthatusersees,however,isthathishomedirectoryis/.The
userseesthedirectoryat/var/ftp/uploadas/upload.The
usercannotsee,orworkwith,forexample,the/home,
/usr/local,or/tmpdirectories.Theuserisinachrootjail.For
moreinformationreferto"SettingUpachrootJail"onpage428.
Youcanusethechroot_local_useroptiontoputeachlocal
userinachrootjailwhoserootistheuser'shomedirectory.You
canusechroot_list_enabletoputselectedlocalusersinchroot
jails.
chroot_list_enable
Uponlogin,YEScheckswhetheralocaluserislistedin
/etc/vsftpd/chroot_list(page624)oranotherfilespecified
bychroot_list_file.
Whenauserisinthelistandchroot_local_userissettoNO,
theuserisputinachrootjailinhishomedirectory.Onlyusers
listedin/etc/vsftpd/chroot_listareputinchrootjails.
Whenauserisinthelistandchroot_local_userissettoYES,
thatuserisnotputinachrootjail.Usersnotlistedin
/etc/vsftpd/chroot_listareputinchrootjails.
Default:NO
chroot_local_user
Seechroot_list_enable.SettoNOforamoreopensystem,
butremembertoaddnewuserstothechroot_list_fileas
neededwhenyouadduserstothesystem.SettoYESfora
moresecuresystem.Newusersareautomaticallyrestricted
unlessyouaddthemtochroot_list_file.
Default:NO
chroot_list_file
Thenameofthefileconsultedwhenchroot_list_enableisset
toYES.
Default:/etc/vsftpd/chroot_list
passwd_chroot_enable
YESenablesyoutochangethelocationofthechrootjailthatthe
chroot_list_enableandchroot_local_usersettingsimpose
onalocaluser.
Thelocationofthechrootjailcanbemovedupthedirectory
structurebyincludinga/./withinthehomedirectorystringfor
thatuserin/etc/passwd.Thischangehasnoeffectonthe
standardsystemlogin,justasacd.commandhasnoeffecton
theworkingdirectory.
Forexample,changingthehomedirectoryfieldin
/etc/passwd(page454)forSamfrom/home/samto
/home/./samallowsSamtocdto/homeafterloggingin
usingvsftpd.Giventheproperpermissions,Samcannowview
filesandpossiblycollaboratewithanotheruser.
Default:NO
secure_chroot_dir
Thenameofanemptydirectorythatisnotwritablebytheuser
ftp.Thevsftpdserverusesthisdirectoryasasecurechrootjail
whentheuserdoesnotneedaccesstothefilesystem.
Default:/usr/share/empty
local_root
Afteralocaluserlogsinontheserver,thisdirectorybecomes
theuser'sworkingdirectory.Noerrorresultsifthespecified
directorydoesnotexist.
Default:none
DownloadingandUploadingFiles
Bydefault,anyuserwhetherlocaloranonymouscandownload
filesfromthevsftpdserver,assumingproperfilesystemaccess
andpermissions.Youmustchangewrite_enablefromNO
(default)toYEStopermitlocaluserstouploadfiles.Bydefault,
local_umaskissetto022,givinguploadedfiles644
permissions(page180).
Security
Referto"Security"onpage613forinformationonthesecurity
holethatiscreatedwhenyouallowlocaluserstouploadfiles.
Thefollowingactionssetupvsftpdtoallowanonymoususers
touploadfiles:
1. Setwrite_enable(page619)toYES.
2. Createadirectoryunder/var/ftpthatananonymoususer
canwritetobutnotreadfrom(mode333).Youdonotwant
amalicioususertobeabletosee,download,modify,and
uploadafilethatanotheruseroriginallyuploaded.The
followingcommandscreatea/var/ftp/uploadsdirectory
thatanyonecanwritetobutnoonecanreadfrom:
#mkdir/var/ftp/uploads
#chmod333/var/ftp/uploads
Becauseofthesecurityrisk,vsftpdpreventsanonymous
connectionswhenananonymoususer(ftp)canwriteto
/var/ftp.
3. Setanon_upload_enable(page619)toYES.
4. Seetheotheroptionsinthissection.
Download/UploadforLocalUsers
local_umask
Theumask(page420)settingforlocalusers.
Default:077
RedHat:022
file_open_mode
Uploadedfilepermissionsforlocalusers.Theumask(page420)
isappliedtothisvalue.Changeto0777tomakeuploadedfiles
executable.
Default:0666
write_enable
YESpermitsuserstocreateanddeletefilesanddirectories
(assumingappropriatefilesystempermissions).NOprevents
usersfrommakingchangestothefilesystem.
Default:NO
RedHat:YES
AnonymousUsers
anon_mkdir_write_enable
YESpermitsananonymoususertocreatenewdirectorieswhen
write_enable=YESandtheanonymoususerhaspermissionto
writetotheparentdirectory.
Default:NO
anon_other_write_enable
YESgrantsananonymoususerwritepermissioninadditionto
thepermissionsgrantedbyanon_mkdir_write_enableand
anon_upload_enable.Forexample,YESallowsananonymous
usertodeleteandrenamefiles,assumingpermissiontowrite
totheparentdirectory.Notrecommendedforsecuresites.
Default:NO
anon_root
Afterananonymoususerlogsinontheserver,thisdirectory
becomestheuser'sworkingdirectory.Noerrorresultsifthe
specifieddirectorydoesnotexist.
Default:none
anon_umask
Theumask(page420)settingforanonymoususers.Thedefault
settinggivesonlyanonymoususersaccesstofilesuploadedby
anonymoususers;setto022togiveeveryonereadaccessto
thesefiles.
Default:077
anon_upload_enable
YESallowsanonymoususerstouploadfileswhen
write_enable=YESandtheanonymoususerhaspermissionto
writetothedirectory.
Default:NO
anon_world_readable_only
YESlimitsthefilesthatausercandownloadtothosethatare
readablebytheownerofthefile,membersofthegroupthefile
isassociatedwith,andothers.Itmaynotbedesirabletoallow
oneanonymoususertodownloadafilethatanother
anonymoususeruploaded.SettingthisparametertoYEScan
avoidthisscenario.
Default:YES
ascii_download_enable
YESallowsausertodownloadfilesusingASCIImode.Setting
thisparametertoYEScancreateasecurityrisk(page608).
Default:NO
ascii_upload_enable
YESallowsausertouploadfilesusingASCIImode(page608).
Default:NO
chown_uploads
YEScausesfilesuploadedbyanonymoususerstobeownedby
root(oranotheruserspecifiedbychown_username).
Default:NO
chown_username
Seechown_uploads.
Default:root
ftp_username
Theusernameofanonymoususers.
Default:ftp
nopriv_user
Thenameoftheuserwithminimalprivileges,asusedby
vsftpd.Toenhancesecurity,becauseotherprogramsuse
nobody,replacenobodywiththenameofadedicateduser
suchasftp.
Default:nobody
Messages
Youcanreplacethestandardgreetingbannerthatvsftpd
displayswhenauserlogsinonthesystem(banner_fileand
ftpd_banner).Youcanalsodisplayamessageeachtimea
userentersadirectory(dirmessage_enableand
message_file).Whenyousetdirmessage_enable=YES,
eachtimeauserentersadirectoryusingcd,vsftpddisplays
thecontentsofthefileinthatdirectorynamed.message(or
otherfilespecifiedbymessage_file).
dirmessage_enable
YESdisplays.messageoranotherfilespecifiedby
message_fileasanftpuserentersanewdirectorybygivinga
cdcommand.
Default:NO
RedHat:YES
message_file
Seedirmessage_enable.
Default:.message
banner_file
Theabsolutepathnameofthefilethatisdisplayedwhenauser
connectstotheserver.Overridesftpd_banner.
Default:none
ftpd_banner
Thisstringoverridesthestandardvsftpdgreetingbanner
displayedwhenauserconnectstotheserver.
Default:none;usesstandardvsftpdbanner
Display
Thissectiondescribesparametersthatcanimprovesecurityand
performancebycontrollinghowvsftpddisplaysinformation.
hide_ids
YESlistsallusersandgroupsindirectorylistingsasftp.NO
liststherealowners.
Default:NO
setproctitle_enable
NOcausespstodisplaytheprocessrunningvsftpdasvsftpd.
YEScausespstodisplaywhatvsftpdiscurrentlydoing
(uploadingandsoon).SettoNOtoprovideamoresecure
system.
Default:NO
text_userdb_names
NOimprovesperformancebydisplayingnumericUIDsandGIDs
indirectorylistings.YESdisplaysnames.
Default:NO
use_localtime
NOcausesls,mls,andmodtimeFTPcommandstodisplay
UTC(page1062);YEScausesthesecommandstodisplaythe
localtime.
Default:NO
ls_recurse_enable
YESpermitsuserstogivelsRcommands.Settingthis
parametertoYESmayposeasecurityriskbecausegivinganls
Rcommandatthetopofalargedirectoryhierarchycan
consumealotofsystemresources.
Default:NO
Logs
Bydefault,loggingisturnedoff.However,thevsftpd.conffile
distributedwithRedHatLinuxturnsiton.Thissectiondescribes
parametersthatcontrolthedetailsandlocationsoflogs.
log_ftp_protocol
YESlogsFTPrequestsandresponses,providedthat
xferlog_std_formatissettoNO.
Default:NO
xferlog_enable
YESmaintainsatransferlogin/var/log/vsftpd.log(or
anotherfilespecifiedbyxferlog_file).NOdoesnotcreatea
log.
Default:NO
RedHat:YES
xferlog_std_format
YEScausesatransferlog(notcoveringconnections)tobe
writteninstandardxferlogformat,asusedbywu-ftpd,aslong
asxferlog_fileisexplicitlyset.Thedefaultvsftpdlogformat
ismorereadablethanxferlogformat,butitcannotbe
processedbyprogramsthatgeneratestatisticalsummariesof
xferlogfiles.SearchforxferlogontheInternetformore
information.
Default:NO
RedHat:YES
xferlog_file
See
xferlog_enableandxferlog_std_format.
Default:
/var/log/vsftpd.log
ConnectionParameters
Youcanallowclientstoestablishpassiveand/oractive
connections(page602).Settingtimeoutsandmaximum
transferratescanimproveserversecurityandperformance.
Thissectiondescribesparametersthatcontrolthetypesof
connectionsthataclientcanestablish,thelengthoftime
vsftpdwillwaitwhileestablishingaconnection,andthespeeds
ofconnectionsfordifferenttypesofusers.
Passive(PASV)Connections
pasv_enable
NOpreventstheuseofPASVconnections.
Default:YES
pasv_promiscuous
NOcausesPASVtoperformasecuritycheckthatensuresthat
thedataandcontrolconnectionsoriginatefromasingleIP
address.YESdisablesthischeck;itisnotrecommendedfora
securesystem.
Default:NO
pasv_max_port
ThehighestportnumberthatvsftpdwillallocateforaPASV
dataconnection;usefulinsettingupafirewall.
Default:0(useanyport)
pasv_min_port
ThelowestportnumberthatvsftpdwillallocateforaPASV
dataconnection;usefulinsettingupafirewall.
Default:0(useanyport)
pasv_address
SpecifiesanIPaddressotherthantheoneusedbytheclientto
contacttheserver.
Default:none;theaddressistheoneusedbytheclient
Active(PORT)Connections
port_enable
NOpreventstheuseofPORTconnections.
Default:YES
port_promiscuous
NOcausesPORTtoperformasecuritycheckthatensuresthat
outgoingdataconnectionsconnectonlytotheclient.YES
disablesthischeck;itisnotrecommendedforasecuresystem.
Default:NO
connect_from_port_20
YESspecifiesport20(ftp-data,aprivilegedport)ontheserver
forPORTconnections,asrequiredbysomeclients.NOallows
vsftpdtorunwithfewerprivileges(onanonprivilegedport).
Default:NO
RedHat:YES
ftp_data_port
Withconnect_from_port_20settoNO,specifiestheportthat
vsftpdusesforPORTconnections.
Default:20
Timeouts
accept_timeout
Thenumberofsecondstheserverwaitsforaclienttoestablish
aPASVdataconnection.
Default:60
connect_timeout
Thenumberofsecondstheserverwaitsforaclienttorespond
toaPORTdataconnection.
Default:60
data_connection_timeout
Thenumberofsecondstheserverwaitsforastalleddata
transfertoresumebeforedisconnecting.
Default:300
idle_session_timeout
ThenumberofsecondstheserverwaitsbetweenFTP
commandsbeforedisconnecting.
Default:300
local_max_rate
Forlocalusers,themaximumdatatransferrateinbytesper
second.Zero(0)indicatesnolimit.
Default:0
anon_max_rate
Foranonymoususers,themaximumdatatransferrateinbytes
persecond.Zeroindicatesnolimit.
Default:0
one_process_model
YESestablishesoneprocessperconnection,whichimproves
performancebutdegradessecurity.NOallowsmultiple
processesperconnection.NOisrecommendedforamore
securesystem.
Default:NO
Miscellaneous
Thissectiondescribesparametersnotdiscussedelsewhere.
pam_service_name
ThenameofthePAMserviceusedbyvsftpd.
Default:ftp
RedHat:vsftpd
tcp_wrappers
YEScausesincomingconnectionstousetcp_wrappers(page
427)ifvsftpdwascompiledwithtcp_wrapperssupport.
Whentcp_wrapperssetstheenvironmentvariable
VSFTPD_LOAD_CONF,vsftpdloadstheconfigurationfile
specifiedbythisvariable,allowingper-IPconfiguration.
Default:NO
RedHat:YES
user_config_dir
Specifiesadirectorythatcontainsfilesnamedforlocalusers.
Eachofthesefiles,whichmimicvsftpd.conf,contains
parametersthatoverride,onaper-userbasis,default
parametersandparametersspecifiedinvsftpd.conf.For
example,assumethatuser_config_dirissetto
/etc/vsftpd/user_conf.Ifthedefaultconfigurationfile,
/etc/vsftpd/vsftpd.conf,setsidlesession_timeout=300
andSam'sindividualconfigurationfile,
/etc/vsftpd/user_conf/sam,sets
idlesession_timeout=1200,allusers'sessions,exceptfor
Sam's,willtimeoutafter300secondsofinactivity.Sam's
sessionswilltimeoutafter1,200seconds.
Default:none
Files
Inadditionto/etc/vsftpd/vsftpd.conf,thefollowingfiles
controlthefunctioningofvsftpd.Thedirectoryhierarchythat
user_config_dirpointstoisnotincludedinthislistasithas
nodefaultname.
/etc/vsftpd/ftpusers
Listsusers,oneperline,whoareneverallowedtologinonthe
FTPserver,regardlessofhowuserlist_enable(page615)is
setandregardlessoftheuserslistedintheuser_listfile.The
defaultfilelistsroot,bin,daemon,andothers.
/etc/vsftpd/user_list
Listseithertheonlyuserswhocanloginontheserverorthe
userswhoarenotallowedtologinontheserver.The
userlist_enable(page615)optionmustbesettoYESfor
vsftpdtoexaminethelistofusersinthisfile.Setting
userlist_enabletoYESanduserlist_deny(page615)toYES
(ornotsettingit)preventslistedusersfromlogginginonthe
server.Settinguserlist_enabletoYESanduserlist_denyto
NOpermitsonlythelisteduserstologinontheserver.
/etc/vsftpd/chroot_list
Dependingonthechroot_list_enable(page617)and
chroot_local_user(page617)settings,thisfilelistseither
userswhoareforcedintoachrootjailintheirhomedirectories
oruserswhoarenotplacedinachrootjail.
/var/log/vsftpd.log
Logfile.Formoreinformationreferto"Logs"onpage621.
ChapterSummary
FTPisaprotocolfordownloadingfilesfromanduploadingfiles
toanothersystemoveranetwork.FTPisthenameofbotha
client/serverprotocol(FTP)andaclientutility(ftp)thatinvokes
thisprotocol.BecauseFTPisnotasecureprotocol,itshouldbe
usedonlytodownloadpublicinformation.Youcanrunthe
vsftpdFTPserverintherestrictedenvironmentofachrootjail
tomakeitsignificantlylesslikelythatamalicioususercan
compromisethesystem.
ManyserversandclientsimplementtheFTPprotocol.Theftp
utilityistheoriginalclientimplementation;sftpisasecure
implementationthatusesOpenSSHfacilitiestoencryptthe
connection.ThevsftpddaemonisasecureFTPserver;itbetter
protectstheserverfrommalicioususersthandootherFTP
servers.
PublicFTPserversallowyoutologinasanonymousorftp.By
convention,yousupplyyouremailaddressasapasswordwhen
youloginasananonymoususer.Publicserversfrequentlyhave
interestingfilesinthepubdirectory.
FTPprovidestwomodesoftransferringfiles:binaryandASCII.
Itissafetousebinarymodetotransferalltypesoffiles,
includingASCIIfiles.IfyoutransferabinaryfileusingASCII
mode,thetransferwillfail.
Exercises
1.
WhatchangesdoesFTPmaketoanASCIIfilewhenyoudownloaditinASCIImode
toaWindowsmachinefromaLinuxserver?Whatchangesaremadewhenyou
downloadthefiletoaMac?
2. WhathappensifyoutransferanexecutableprogramfileinASCIImode?
3. Whenwouldftpbeabetterchoicethansftp?
4. Howwouldyoupreventlocalusersfromlogginginonavsftpdserverusingtheir
systemusernameandpassword?
5. Whatadvantagedoessftphaveoverftp?
6. Whatisthedifferencebetweencdandlcdinftp?
AdvancedExercises
7. WhymightyouhaveproblemsconnectingtoanFTPserverinPORTmode?
8. Whyisitadvantageoustorunvsftpdinachrootjail?
9.
Afterdownloadingafile,youfindthatitdoesnotmatchtheMD5checksum
provided.Downloadingthefileagaingivesthesameincorrectchecksum.What
haveyoudonewrongandhowwouldyoufixit?
10. Howwouldyouconfigurevsftpdtorunthroughxinetd,andwhatwouldbethe
mainadvantageofthisapproach?
20.sendmail:SettingUpMailClients,
Servers,andMore
INTHISCHAPTER
JumpStartI:ConfiguringsendmailonaClient 630
JumpStartII:ConfiguringsendmailonaServer 631
HowsendmailWorks 632
Configuringsendmail 635
SpamAssassin 640
Webmail 644
MailingLists 646
SettingUpanIMAPorPOP3Server 647
SettingUpKMail 648
AuthenticatedRelaying 650
Sendingandreceivingemailrequirethreepiecesofsoftware.At
eachend,thereisaclient,calledanMUA(MailUserAgent),
whichisabridgebetweenauserandthemailsystem.Common
MUAsaremutt,KMail,Thunderbird,andOutlook.Whenyousend
anemail,theMUAhandsittoanMTA(aMailTransferAgent
suchassendmail),whichtransfersittothedestinationserver.
Atthedestination,anMDA(aMailDeliveryAgentsuchas
procmail)putsthemailintherecipient'smailboxfile.OnLinux
systems,theMUAonthereceivingsystemeitherreadsthe
mailboxfileorretrievesmailfromaremoteMUAorMTA,such
asanISP'sSMTP(mail)server,usingPOP(PostOfficeProtocol)
orIMAP(InternetMessageAccessProtocol).
MostLinuxMUAsexpectalocalcopyofsendmailtodeliver
outgoingemail.Onsomesystems,includingthosewithadialup
connectiontotheInternet,sendmailrelaysemailtoanISP's
mailserver.BecausesendmailusesSMTP(SimpleMailTransfer
Protocol)todeliveremail,sendmailisoftenreferredtoasan
SMTPserver.
InthedefaultRedHatLinuxsetup,thesendmailMTAuses
procmailasthelocalMDA.Inturn,procmailwritesemailto
theendoftherecipient'smailboxfile.Youcanalsouse
procmailtosortemailaccordingtoasetofrules,eitherona
per-userbasisorglobally.Theglobalfilteringfunctionisuseful
forsystemwidefilteringtodetectspamandforothertasks,but
theper-userfeatureislargelysuperfluousonamodernsystem.
TraditionalUNIXMUAsweresimpleprogramsthatcouldnot
filtermailandthusdelegatedthisfunctiontoMDAssuchas
procmail.ModernMUAs,bycontrast,incorporatethis
functionality.
Tip:Youdonotneedtosetupsendmailto
sendandreceiveemail
MostMUAscanusePOPorIMAPforreceivingemail.
TheseprotocolsdonotrequireanMTAsuchas
sendmail.Asaconsequence,youdonotneedto
installorconfiguresendmail(oranotherMTA)to
receiveemail.YoustillneedSMTPtosendemail.
However,theSMTPservercanbeataremote
location,suchasyourISP,soyoudonotneedto
concernyourselfwithit.
Introduction
WhenthenetworkthatwastoevolveintotheInternetwasfirst
setup,itconnectedafewcomputers,eachservingalarge
numberofusersandrunningseveralservices.Eachcomputer
wascapableofsendingandreceivingemailandhadaunique
hostname,whichwasusedasadestinationforemail.
TodaytheInternethasalargenumberoftransientclients.
BecausetheseclientsdonothavefixedIPaddressesor
hostnames,theycannotreceiveemaildirectly.Usersonthese
systemsusuallymaintainanaccountonanemailserverrunby
theiremployeroranISP,andtheycollectemailfromthis
accountusingPOPorIMAP.Unlessyouownadomainthatyou
wanttoreceiveemailat,youwillnotneedtosetupsendmail
asanincomingSMTPserver.
Youcansetupsendmailonaclientsystemsothatitsimply
relaysoutboundmailtoanSMTPserver.Thisconfigurationis
requiredbyorganizationsthatusefirewallstopreventemail
frombeingsentoutontheInternetfromanysystemotherthan
thecompany'sofficialmailservers.Asapartialdefenseagainst
spreadingviruses,someISPsblockoutboundport25toprevent
theircustomersfromsendingemaildirectlytoaremote
computer.ThisconfigurationisrequiredbytheseISPs.
Youcanalsosetupsendmailasanoutboundserverthatdoes
notuseanISPasarelay.Inthisconfiguration,sendmail
connectsdirectlytotheSMTPserversforthedomainsreceiving
theemail.AnISPsetupasarelayisconfiguredthisway.
Youcansetupsendmailtoacceptemailforaregistered
domainnameasspecifiedinthedomain'sDNSMXrecord(page
726).However,mostmailclients(MUAs)donotinteractdirectly
withsendmailtoreceiveemail.Instead,theyusePOPor
IMAPprotocolsthatincludefeaturesformanagingmailfolders,
leavingmessagesontheserver,andreadingonlythesubjectof
anemailwithoutdownloadingtheentiremessage.Ifyouwant
tocollectyouremailfromasystemotherthantheonerunning
theincomingmailserver,youmayneedtosetupaPOPor
IMAPserver,asdiscussedonpage647.
Prerequisites
Installthefollowingpackages:
sendmail(required)
sendmail-cf(requiredtoconfiguresendmail)
squirrelmail(optional;providesWebmail,page644)
spamassassin(optional;providesspamfiltering,page
640)
mailman(optional;providesmailinglistsupport,page
646)
dovecot(optional;providesIMAPandPOPincomingmail
serverdaemons)
Runchkconfigtocausesendmailtostartwhenthesystemgoes
multiuser(bydefault,sendmaildoesnotruninsingle-user
mode):
#/sbin/chkconfigsendmailon
Startsendmail.Becausesendmailisnormallyrunning,you
needtorestartittocausesendmailtorereaditsconfiguration
files.Thefollowingrestartcommandworksevenwhen
sendmailisnotrunningitjustfailstoshutdownsendmail:
#/sbin/servicesendmailrestart
Shuttingdownsendmail:[OK]
Shuttingdownsm-client:[OK]
Startingsendmail:[OK]
Startingsm-client:[OK]
RunchkconfigtocausetheSpamAssassindaemon,spamd,to
startwhenthesystementersmultiusermode(SpamAssassinis
normallyinstalledinthisconfiguration):
#/sbin/chkconfigspamassassinon
Aswithsendmail,SpamAssassinisnormallyrunning.Restartit
tocausespamdtorereaditsconfigurationfiles:
#/sbin/servicespamassassinrestart
Stoppingspamd:[OK]
Startingspamd:[OK]
TheIMAPandPOPprotocolsareimplementedasseveral
daemons.Seepage647forinformationonthesedaemonsand
howtostartthem.
Notes
Firewall
AnSMTPservernormallyusesTCPport25.IftheSMTPserver
systemisrunningafirewall,youneedtoopenthisport.Using
theRedHatgraphicalfirewalltool(page768),selectMail
(SMTP)fromtheTrustedServicesframetoopenthisport.For
moregeneralinformationseeChapter25,whichdetailsiptables.
cyrus
ThischaptercoverstheIMAPandPOP3serversincludedinthe
dovecotpackage.RedHatLinuxalsoprovidesIMAPandPOP3
serversinthecyrus-imapdpackage.
MoreInformation
Web
sendmailwww.sendmail.org
IMAPwww.imap.org
IMAPandPOP3www.dovecot.org
IMAPandPOP3cyrusimap.web.cmu.edu
SquirrelMailwww.squirrelmail.org
Postfixwww.postfix.org/docs.html(alternativeMTA,page652)
JumpStartI:ConfiguringsendmailonaClient
Tip:Youmaynotneedtoconfigure
sendmailtosendemail
Withsendmailrunning,givethecommand
describedunderunder"Test"onpage631.Aslong
assendmailcanconnecttoport25outbound,you
shouldnotneedtosetupsendmailtouseanSMTP
relayasdescribedinthissection.Ifyoureceivethe
mailsentbythetest,youcanskipthissection.
ThisJumpStartconfiguresanoutboundsendmailserver.This
server
UsesaremoteSMTPservertypicallyanISPtorelay
outboundemailtoitsdestination(anSMTPrelay).
SendstotheSMTPserveremailoriginatingfromthelocal
systemonly.Itdoesnotforwardemailoriginatingfrom
othersystems.
Doesnothandleinboundemail.Asisfrequentlythecase,
youneedtousePOPorIMAPtoreceiveemail.
Tosetupthisserver,youmustedit/etc/mail/sendmail.mc
andrestartsendmail.
Changesendmail.mc
Thednlatthestartofthefollowinglineinsendmail.mc
indicatesthatthislineisacomment:
dnldefine('SMART_HOST','smtp.your.provider')
TospecifyaremoteSMTPserver,youmustopensendmail.mc
inaneditorandchangetheprecedingline,deletingdnlfrom
thebeginningofthelineandreplacingsmtp.your.provider
withtheFQDNofyourISP'sSMTPserver(obtainthisname
fromyourISP).Becarefulnottoalterthebackticks(')andthe
singlequotationmarks(')inthisline.IfyourISP'sSMTPserver
isatsmtp.myisp.com,youwouldchangethelineto
define('SMART_HOST','smtp.myisp.com')
Tip:Donotalterthebackticks(')orthe
singlequotationmarks(')
Becarefulnottoalterthebackticks(')orthesingle
quotationmarks(')inanylineinsendmail.mc.
Thesesymbolscontrolthewaythem4preprocessor
convertssendmail.mctosendmail.cf;sendmail
willnotworkproperlyifyoudonotpreservethese
symbols.
Restartsendmail
Whenyourestartit,sendmailregeneratesthe
sendmail.cffilefromthesendmail.mcfileyou
edited:
#/sbin/servicesendmailrestart
Test
Testsendmailwiththefollowingcommand:
$echo"mysendmailtest"|/usr/sbin/sendmailuser@remote.host
Replaceuser@remote.hostwithanemailaddresson
anothersystemwhereyoureceiveemail.Youneed
tosendemailtoaremotesystemtomakesurethat
sendmailisrelayingyouremail.
JumpStartII:ConfiguringsendmailonaServer
Ifyouwanttoreceiveinboundemailsenttoaregistered
domainthatyouown,youneedtosetupsendmailasan
incomingmailserver.ThisJumpStartdescribeshowtosetup
suchaserver.Thisserver
Acceptsoutboundemailfromthelocalsystemonly.
Deliversoutboundemaildirectlytotherecipient'ssystem,
withoutusingarelay.
Acceptsinboundemailfromanysystem.
Thisserverdoesnotrelayoutboundemailoriginatingonother
systems.Referto"access:SetsUpaRelayHost"onpage638if
youwantthelocalsystemtoactasarelay.Forthis
configurationtowork,youmustbeabletomakeoutbound
connectionsfromandreceiveinboundconnectionstoport25.
Thelineinsendmail.mcthatlimitssendmailtoaccepting
inboundemailfromthelocalsystemonlyis
DAEMON_OPTIONS('Port=smtp,Addr=127.0.0.1,Name=MTA')dnl
Toallowsendmailtoacceptinboundemailfromothersystems,
removetheparameterAddr=127.0.0.1,fromthepreceding
line:
DAEMON_OPTIONS('Port=smtp,Name=MTA')dnl
Bydefault,sendmaildoesnotusearemoteSMTPserverto
relayemail,sothereisnothingtochangetocausesendmailto
sendemaildirectlytorecipients'systems.(JumpStartIsetupa
SMART_HOSTtorelayemail.)
Onceyouhaverestartedsendmail,itwillacceptmail
addressedtothelocalsystem,aslongasaDNSMXrecord
(page726)pointsatthelocalsystem.Ifyouarenotrunninga
DNSserver,youmustaskyourISPtosetupanMXrecord.
HowsendmailWorks
Outboundemail
Whenyousendemail,theMUApassestheemailtosendmail,
whichcreatesinthe/var/spool/mqueue(mailqueue)
directorytwofilesthatholdthemessagewhilesendmail
processesit.Tocreateauniquefilenameforaparticularpiece
ofemail,sendmailgeneratesarandomstringandusesthat
stringinfilenamespertainingtotheemail.Thesendmail
daemonstoresthebodyofthemessageinafilenameddf
(datafile)followedbythegeneratedstring.Itstoresthe
headersandotherinformationinafilenamedqf(queuefile)
followedbythegeneratedstring.
Ifadeliveryerroroccurs,sendmailcreatesatemporarycopy
ofthemessagethatitstoresinafilewhosenamestartswithtf
(temporaryfile)andlogserrorsinafilewhosenamestartsxf.
Onceanemailhasbeensentsuccessfully,sendmailremoves
allfilespertainingtothatemailfrom/var/spool/mqueue.
Incomingemail
Bydefault,theMDAstoresincomingmessagesinusers'filesin
themailspooldirectory,/var/spool/mail,inmboxformat.
Withinthisdirectory,eachuserhasamailfilenamedwiththe
user'susername.Mailremainsinthesefilesuntilitiscollected,
typicallybyanMUA.OnceanMUAcollectsthemailfromthe
mailspool,theMUAstoresthemailasdirectedbytheuser,
usuallyintheuser'shomedirectoryhierarchy.
mboxversusmaildir
Themboxformatstoresallmessagesforauserinasinglefile.
Topreventcorruption,thefilemustbelockedwhileaprocessis
addingmessagestoordeletingmessagesfromthefile;you
cannotdeleteamessageatthesametimetheMTAisadding
messages.Acompetingformat,maildir,storeseachmessage
inaseparatefile.Thisformatdoesnotuselocks,allowingan
MUAtoreadanddeletemessagesatthesametimeasnewmail
isdelivered.Inaddition,themaildirformatisbetterableto
handlelargermailboxes.Thedownsideisthatthemaildir
formataddsoverheadwhenyouareusingaprotocolsuchas
IMAPtocheckmessages.Thedovecotpackagesupportsboth
mboxandmaildirformats.Qmail(page652),asendmail
alternative,usesmaildir-formatmailboxes.
Maillogs
Thesendmaildaemonstoreslogmessagesin
/var/log/maillog.Othermailservers,suchasthedovecot
imap-loginandpop3-logindaemons,mayalsolog
informationtothisfile.Followingisasamplelogentry:
/var/log/maillog
#cat/var/log/maillog
...
Mar316:25:33MACHINENAMEsendmail[7225]:i23GPXvm007224:
to=<user@localhost.localdomain>,ctladdr=<root@localhost.localdomain>
(0/0),delay=00:00:00,xdelay=00:00:00,mailer=local,pri=30514,
dsn=2.0.0,stat=Sent
Eachlogentrystartswithatimestamp,thenameofthesystem
sendingtheemail,thenameofthemailserver(sendmail),
andauniqueidentificationnumber.Theaddressoftherecipient
followstheto=labelandtheaddressofthesenderfollows
ctladdr=.Additionalfieldsprovidethenameofthemailerand
thetimeittooktosendthemessage.Ifamessageissent
correctly,thestat=labelisfollowedbySent.
AmessageismarkedSentwhensendmailsendsit;Sentdoes
notindicatethatthemessagehasbeendelivered.Ifamessage
isnotdeliveredbecauseanerroroccurredfartherdownthe
line,thesenderusuallyreceivesanemailsayingthatitwasnot
deliveredandgivingareasonwhy.
Ifyousendandreceivealotofemail,themaillogfilecangrow
quitelarge.Thesysloglogrotate(page559)entryissetupto
archiveandrotatethemaillogfilesregularly.
AliasesandForwarding
Threefilescanforwardemail:.forward(page634),aliases
(discussednext),andvirtusertable(page640).Table20-1on
page640comparesthethreefiles.
Table20-1.Comparisonofforwardingtechniques
.forward aliases virtusertable
Controlledby nonrootuser root root
Forwardsemail
addressedto
nonrootuser Anyrealor
virtualuseron
thelocalsystem
Anyrealor
virtualuseron
anydomain
recognizedby
sendmail
Orderof
precedence
Third Second First
/etc/aliases
Mostofthetimewhenyousendemail,itgoestoaspecific
person;therecipient,user@system,mapstoaspecific,real
useronthespecifiedsystem.Sometimesyoumaywantemail
togotoaclassofusersandnottoaspecificrecipient.
Examplesofclassesofusersincludepostmaster,webmaster,
root,andtech_support.Differentusersmayreceivethis
emailatdifferenttimesortheemailmaybeansweredbya
groupofusers.Youcanusethe/etc/aliasesfiletomap
inboundaddressestolocalusers,files,commands,andremote
addresses.
Eachlinein/etc/aliasescontainsthenameofalocal
pseudouser,followedbyacolon,whitespace,andacomma-
separatedlistofdestinations.Thedefaultinstallationincludesa
numberofaliasesthatredirectmessagesforcertain
pseudouserstoroot.Thesehavetheform
system:root
Sendingmessagestotherootaccountisagoodwayofmaking
themeasytoreview.However,becauseroot'semailisrarely
checked,youmaywanttosendcopiestoarealuser.The
followinglineforwardsmailsenttoabuseonthelocalsystem
torootandalex:
abuse:root,alex
Youcancreatesimplemailinglistswiththistypeofalias.For
example,thefollowingaliassendscopiesofallemailsentto
adminonthelocalsystemtoseveralusers,includingZach,
whoisonadifferentsystem:
admin:sam,helen,mark,zach@tcorp.com
Youcandirectemailtoafilebyspecifyinganabsolute
pathnameinplaceofadestinationaddress.Thefollowingalias,
whichisquitepopularamonglessconscientioussystem
administrators,redirectsemailsenttocomplaintsto
/dev/null(page448),wheretheydisappear:
complaints:/dev/null
Youcanalsosendemailtostandardinputofacommandby
precedingthecommandwithapipecharacter(|).This
techniqueiscommonlyusedwithmailinglistsoftwaresuchas
Mailman(page646).Foreachlistitmaintains,Mailmanhas
entries,suchasthefollowingentryformylist,inthealiases
file:
mylist:"|/usr/lib/mailman/mail/mailmanpostmylist"
newaliases
Afteryouedit/etc/aliases,youmusteitherrunnewaliasesas
rootorrestartsendmailtorecreatethealiases.dbfilethat
sendmailreads.
praliases
Youcanusepraliasestolistaliasescurrentlyloadedby
sendmail:
#/usr/sbin/praliases|head-5
postmaster:root
daemon:root
adm:root
lp:root
shutdown:root
~/.forward
Systemwidealiasesareusefulinmanycases,butnonroot
userscannotmakeorchangethem.Sometimesyoumaywant
toforwardyourownmail:Maybeyouwantmailfromseveral
systemstogotooneaddressorperhapsyoujustwantto
forwardyourmailwhileyouareworkingatanotherofficefora
week.The~/.forwardfileallowsordinaryuserstoforward
theiremail.
Linesina.forwardfilearethesameastherightcolumnofthe
aliasesfileexplainedpreviously:Destinationsarelistedone
perlineandcanbealocaluser,aremoteemailaddress,a
filename,oracommandprecededbyapipecharacter(|).
Mailthatyouforwarddoesnotgotoyourlocalmailbox.Ifyou
wanttoforwardmailandkeepacopyinyourlocalmailbox,you
mustspecifyyourlocalusernameprecededbyabackslashto
preventaninfiniteloop.ThefollowingexamplesendsSam's
emailtohimselfonthelocalsystemandonthesystemat
tcorp.com:
$cat~sam/.forward
sams@tcorp.com
\sam
RelatedPrograms
sendmail
Thesendmailpackageincludesseveralprograms.Theprimary
program,sendmail,readsfromstandardinputandsendsan
emailtotherecipientspecifiedbyitsargument.Youcanuse
sendmailfromthecommandlinetocheckthatthemail
deliverysystemisworkingandtoemailtheoutputofscripts.
Seepage631foranexample.
mailq
Themailqutilitydisplaysthestatusoftheoutgoingmailqueue
andnormallyreportstherearenomessagesinthequeue.
Messagesinthequeueusuallyindicateaproblemwiththelocal
orremotesendmailconfigurationoranetworkproblem.
#/usr/bin/mailq
/var/spool/mqueueisempty
Totalrequests:0
mailstats
Themailstatsutilityreportsonthenumberandsizesofmessages
sendmailhassentandreceivedsincethedateitdisplayson
thefirstline:
#/usr/sbin/mailstats
StatisticsfromSatDec2416:02:342005
Mmsgsfrbytes_frommsgstobytes_tomsgsrejmsgsdisMailer
000K17181103904K00prog
43683864216614K1364561568314K206160esmtp
922615126101362K47902512776528K45900local
============================================================
T59453730317976K63266214448746K252060
C694638499700146185
Intheprecedingoutput,eachmailerisidentifiedbythefirst
column,whichdisplaysthemailernumber,andbythelast
column,whichdisplaysthenameofthemailer.Thesecond
throughfifthcolumnsdisplaythenumberandtotalsizesof
messagessentandreceivedbythemailer.Thesixthand
seventhcolumnsdisplaythenumberofmessagesrejectedand
discardedrespectively.TherowthatstartswithTliststhe
columntotals,andtherowthatstartswithCliststhenumberof
TCPconnections.
Configuringsendmail
Thesendmailconfigurationfilesresidein/etc/mail,where
theprimaryconfigurationfileissendmail.cf.Thisdirectory
containsothertextconfigurationfiles,suchasaccess,
mailertable,andvirtusertable.Thesendmaildaemondoes
notreadthesefilesbutinsteadreadsthecorresponding*.db
filesinthesamedirectory.
makemap
Youcanusemakemaporgivethecommandmakefromthe
/etc/maildirectorytogeneratethe*.dbfiles,althoughthis
stepisnotusuallynecessary.Thesendmailinitscript
automaticallygeneratesthesefileswhenyoustartorrestart
sendmail:
#/sbin/servicesendmailrestart
Thesendmail.mcandsendmail.cfFiles
Thissendmail.cffileisnotintendedtobeeditedbyhandand
containsalargewarningtothiseffect:
$cat/etc/mail/sendmail.cf
...
######################################################################
#####
#####DONOTEDITTHISFILE!Onlyeditthesource.mcfile.
#####
######################################################################
...
Editingsendmail.mcandGeneratingsendmail.cf
Thesendmail.cffileisgeneratedfromsendmail.mcusingthe
m4macroprocessor.Itcanbehelpfultouseatexteditorthat
supportssyntaxhighlighting,suchasvim,toeditsendmail.mc.
dnl
Manyofthelinesinsendmail.mcstartwithdnl,whichstands
fordeletetonewline;thistokencausesm4todeletefromthe
dnltotheendoftheline(thenextNEWLINEcharacter).
Becausem4ignoresanythingonalineafteradnlinstruction,
youcanusednltointroducecomments;itworksthesameway
as#doesinashellscript.
Manyofthelinesinsendmail.mcendwithdnl.Because
NEWLINEsimmediatelyfollowthesednls,thesednlsare
superfluous;youcanremovethemifyoulike.
Afteryoueditsendmail.mc,youneedtoregenerate
sendmail.cftomakeyourchangestakeeffect.Whenyou
restartsendmail,thesendmailinitscriptregenerates
sendmail.cf.
Aboutsendmail.mc
Linesnearthebeginningofsendmail.mcprovidebasic
configurationinformation:
divert(-1)dnl
include('/usr/share/sendmail-cf/m4/cf.m4')dnl
VERSIONID('setupforRedHatLinux')dnl
OSTYPE('linux')dnl
Thelinethatstartswithdiverttellsm4todiscardextraneous
outputitmaygeneratewhenprocessingthisfile.
Theincludestatementtellsm4wheretofindthemacro
definitionfilethatitwillusetoprocesstherestofthisfile;it
pointstothefilenamedcf.m4.Thecf.m4filecontainsother
includestatementsthatincludepartsofthesendmail
configurationrulesets.
TheVERSIONIDstatementdefinesastringthatindicatesthe
versionofthisconfiguration.Youcanchangethisstringto
includeabriefcommentaboutchangesyouhavemadetothis
fileorotherinformation.Thevalueofthisstringisnot
significanttosendmail.
DonotchangetheOSTYPEstatementunlessyouaremigrating
asendmail.mcfilefromanotheroperatingsystem.
Otherstatementsyoumaywanttochangeareexplainedinthe
followingsectionsandinthesendmaildocumentation.
Tip:Quotingm4strings
Them4macroprocessor,whichconverts
sendmail.mctosendmail.cf,requiresstringstobe
precededbyabacktick(')andclosedwithasingle
quotationmark(').
Masquerading
Typicallyyouwantyouremailtoappeartocomefromtheuser
andthedomainwhereyoureceiveemail;sometimesthe
outboundserverisinadifferentdomainthantheinbound
server.Youcancausesendmailtoalteroutboundmessagesso
thattheyappeartocomefromauserand/ordomainotherthan
theonetheyaresentfrom:Inotherwords,youmasquerade
(page1042)themessage.
Severallinesinsendmail.mcpertaintothistypeof
masquerading.EachiscommentedoutinthefilethatRedHat
distributes:
dnlMASQUERADE_AS('mydomain.com')dnl
dnlMASQUERADE_DOMAIN(localhost)dnl
dnlFEATURE(masquerade_entire_domain)dnl
TheMASQUERADE_ASstatementcausesemailthatyousend
fromthelocalsystemtoappeartocomefromthespecified
domain(mydomain.cominthecommented-outlineinthe
distributedfile).Removetheleadingdnlandchange
mydomain.comtothedomainnamethatyouwantmailto
appeartocomefrom.
TheMASQUERADE_DOMAINstatementcausesemailfromthe
specifiedsystemordomaintobemasqueraded,justaslocal
emailis.Thatis,emailfromthesystemspecifiedinthis
statementistreatedasthoughitcamefromthelocalsystem:It
ischangedsothatitappearstocomefromthedomainspecified
intheMASQUERADE_ASstatement.Removetheleadingdnl
andchangelocalhosttothenameofthesystemordomain
thatsendstheemailthatyouwanttomasquerade.Ifthename
youspecifyhasaleadingperiod,itspecifiesadomain.Ifthere
isnoleadingperiod,thenamespecifiesasystemorhost.The
sendmail.mcfilecanincludeasmanyMASQUERADE_DOMAIN
statementsasnecessary.
Themasquerade_entire_domainfeaturestatementcauses
sendmailalsotomasqueradesubdomainsofthedomain
specifiedintheMASQUERADE_DOMAINstatement.Removethe
leadingdnltomasqueradeentiredomains.
AcceptingEmailfromUnknownHosts
AsconfiguredbyRedHat,sendmailacceptsemailfrom
domainsthatitcannotresolve(andthatmaynotexist).Toturn
thisfeatureoffandcutdowntheamountofspamyoureceive,
adddnltothebeginningofthefollowingline:
FEATURE('accept_unresolvable_domains')dnl
Whenthisfeatureisoff,sendmailusesDNStolookupthe
domainsofallemailitreceives.Ifitcannotresolvethedomain,
itrejectstheemail.
SettingUpaBackupServer
Youcansetupabackupmailservertoholdemailwhenthe
primarymailserverexperiencesproblems.Formaximum
coverage,thebackupservershouldbeonadifferentconnection
totheInternetfromtheprimaryserver.
Settingupabackupserveriseasy.Justremovetheleadingdnl
fromthefollowinglineinthebackupmailserver's
sendmail.mcfile:
dnlFEATURE('relay_based_on_MX')dnl
DNSMXrecords(page726)specifywhereemailforadomain
shouldbesent.YoucanhavemultipleMXrecordsforadomain,
eachpointingtoadifferentmailserver.Whenadomainhas
multipleMXrecords,eachrecordusuallyhasadifferent
priority;thepriorityisspecifiedbyatwo-digitnumber,where
lowernumbersspecifyhigherpriorities.
Whenattemptingtodeliveremail,anMTAfirsttriestodeliver
emailtothehighest-priorityserver.Ifthatdeliveryattempt
fails,ittriestodelivertoalower-priorityserver.Ifyouactivate
therelay_based_on_MXfeatureandpointalow-priorityMX
recordatasecondarymailserver,themailserverwillaccept
emailforthedomain.Themailserverwillthenforwardemailto
theserveridentifiedbythehighest-priorityMXrecordforthe
domainwhenthatserverbecomesavailable.
OtherFilesin/etc/mail
The/etc/maildirectoryholdsmostofthefilesthatcontrol
sendmail.Thissectiondiscussesthreeofthosefiles:
mailertable,access,andvirtusertable.
mailertable:ForwardsEmailfromOneDomaintoAnother
Whenyourunamailserver,youmaywanttosendmail
destinedforonedomaintoadifferentlocation.Thesendmail
daemonusesthe/etc/mail/mailertablefileforthispurpose.
Eachlineinmailertableholdsthenameofadomainanda
destinationmailerseparatedbywhitespace;whensendmail
receivesemailforthespecifieddomain,itforwardsittothe
mailerspecifiedonthesameline.RedHatenablesthisfeature
bydefault:Putanentryinthemailertablefileandrestart
sendmailtouseit.
Thefollowinglineinmailertableforwardsemailsentto
tcorp.comtothemaileratbravo.com:
$cat/etc/mail/mailertable
tcorp.comsmtp:[bravo.com]
Thesquarebracketsintheexampleinstructsendmailnotto
useMXrecordsbutrathertosendemaildirectlytotheSMTP
server.Withoutthebrackets,emailcouldenteraninfiniteloop.
Aperiodinfrontofadomainnameactsasawildcardand
causesthenametomatchanydomainthatendsinthe
specifiedname.Forexample,.tcorp.commatches
sales.tcorp.com,mktg.tcrop.com,andsoon.
Thesendmailinitscriptregeneratesmailertable.dbfrom
mailertableeachtimeyourunit,aswhenyourestart
sendmail.
access:SetsUpaRelayHost
OnaLAN,youmaywanttosetupasingleservertoprocess
outboundmail,keepinglocalmailinsidethenetwork.Asystem
thatprocessesoutboundmailforothersystemsiscalledarelay
host.The/etc/mail/accessfilespecifieswhichsystemsthe
localserverrelaysemailfor.AsconfiguredbyRedHat,thisfile
listsonlythelocalsystem:
$cat/etc/mail/access
...
#bydefaultweallowrelayingfromlocalhost...
localhost.localdomainRELAY
localhostRELAY
127.0.0.1RELAY
YoucanaddsystemstothelistinaccessbyaddinganIP
addressfollowedbywhitespaceandthewordRELAY.The
followinglineaddsthe192.168.subnettothelistofhoststhat
thelocalsystemrelaysmailfor:
192.168.RELAY
Thesendmailinitscriptregeneratesaccess.dbfromaccess
eachtimeyourunit,aswhenyourestartsendmail.
virtusertable:ServesEmailtoMultipleDomains
WhentheDNSMXrecordsaresetupproperly,asinglesystem
canserveemailtomultipledomains.Onasystemthatserves
mailtomanydomains,youneedawaytosorttheincoming
mailsothatitgoestotherightplaces.Thevirtusertablefile
canforwardinboundemailaddressedtodifferentdomains
(aliasescannotdothis).
AssendmailisconfiguredbyRedHat,virtusertableis
enabled.Youneedtoputforwardinginstructionsinthe
/etc/mail/virtusertablefileandrestartsendmailtoserve
thespecifieddomains.Thevirtusertablefileissimilartothe
aliasesfile(page633),excepttheleftcolumncontainsfull
emailaddresses,notjustlocalones.Eachlineinvirtusertable
startswiththeaddressthattheemailwassentto,followedby
whitespaceandtheaddresssendmailwillforwardtheemailto.
Aswithaliases,thedestinationcanbealocaluser,anemail
address,afile,orapipesymbol(|),followedbyacommand.
Thefollowinglinefromvirtusertableforwardsmailaddressed
tozach@tcorp.comtozcs,alocaluser:
zach@tcorp.comzcs
Youcanalsoforwardemailforausertoaremoteemail
address:
sams@bravo.comsams@tcorp.com
Youcanforwardallemaildestinedforadomaintoanother
domainwithoutspecifyingeachuserindividually.Toforward
emailforeveryuseratbravo.comtotcorp.com,specify
@bravo.comasthefirstaddressontheline.Whensendmail
forwardsemail,itreplacesthe%1inthedestinationaddress
withthenameoftherecipient.Thenextlineforwardsallemail
addressedtobravo.comtotcorp.com,keepingtheoriginal
recipients'names:
@bravo.com%1@tcorp.com
Finallyyoucanspecifythatemailintendedforaspecificuser
shouldberejectedbyusingtheerrornamespaceinthe
destination.Thenextexamplebouncesemailaddressedto
spam@tcorp.comwiththemessage5.7.0:550Invalid
address:
spam@tcorp.comerror:5.7.0:550Invalidaddress
.forward,aliases,andvirtusertable
The.forward(page634),aliases(page633),and
virtusertablefilesalldothesamething:Theyforwardemail
addressedtooneusertoanotheruser.Theycanalsoredirect
emailtoafileortoserveasinputtoaprogram.Thedifference
betweenthemisscopeandownership;seeTable20-1.
AdditionalEmailTools
ThissectioncoversSpamAssassin,Webmail,andmailinglists.
Inaddition,itdiscusseshowtosetupIMAPandPOP3servers
andaKMailclient.
SpamAssassin
Spamormorecorrectly,UCE(unsolicitedcommercial
email)accountsformorethanthree-quartersofallemail.
SpamAssassinevaluateseachpieceofincomingemailand
assignsitanumberthatindicatesthelikelihoodthattheemail
isspam.Thehigherthenumber,themorelikelythattheemail
isspam.Youcanfilteremailbasedonitsrating.SpamAssassin
iseffectiveasinstalled,butyoucanmodifyitsconfiguration
filestomakeitbetterfityourneeds.
HowSpamAssassinworks
YoucansetupSpamAssassin(spamassassinpackage)ona
mailserversothatitratesallinboundemailbeforeitissentto
users.Alternatively,individualuserscanrunitfromtheirmail
clients.Eitherway,youruntheSpamAssassinspamddaemon
andfilteremailthroughthisdaemonusingthespamcclient.
SpamAssassinusesseveraltechniquestoidentifyspam:
HeaderanalysisChecksfortricksthatpeoplewhosend
spamusetomakeyouthinkemailislegitimate
TextanalysisChecksthebodyofanemailfor
characteristicsofspam
BlacklistsChecksvariousliststoseeifthesenderisknown
forsendingspam
DatabaseChecksthesignatureofthemessageagainst
Vipul'sRazor(razor.sourceforge.net),aspam-tracking
database
Withspamdrunning,youcanseehowspamcworksbysending
asimplestringtoit:
$echo"hithere"|spamc
X-Spam-Flag:YES
X-Spam-Checker-Version:SpamAssassin3.1.0(2005-09-13)onpbnj
X-Spam-Level:*****
X-Spam-Status:Yes,score=5.7required=5.0tests=EMPTY_MESSAGE,MISSING_HB_SEP,
MISSING_HEADERS,MISSING_SUBJECT,NO_RECEIVED,NO_RELAYS,TO_CC_NONE
autolearn=noversion=3.1.0
X-Spam-Report:
*-0.0NO_RELAYSInformational:messagewasnotrelayedviaSMTP
*2.5MISSING_HB_SEPMissingblanklinebetweenmessageheaderandbody
*0.2MISSING_HEADERSMissingTo:header
*1.3MISSING_SUBJECTMissingSubject:header
*1.5EMPTY_MESSAGEMessageappearstobeemptywithnoSubject:text
*-0.0NO_RECEIVEDInformational:messagehasnoReceivedheaders
*0.1TO_CC_NONENoTo:orCc:header
hithere
Subject:[SPAM]
X-Spam-Prev-Subject:(nonexistent)
Ofcourse,SpamAssassincomplainsbecausethestring
yougaveitdidnotcontainstandardemailheaders.The
logicallinethatstartswithX-Spam-Statuscontainsthe
heartofthereportonthestringhithere.Firstitsays
Yes(itconsidersthemessagetobespam).SpamAssassin
usesaratingsystemthatassignsanumberofhitstoa
pieceofemail.Iftheemailreceivesmorethanthe
requirednumberofhits(5.0bydefault),SpamAssassin
marksitasspam.Thestringfailedformanyreasonsthat
areenumeratedonthisstatusline.Thereasonsare
detailedinthefollowingX-Spam-Report.Thefollowing
listingisfromarealpieceofspamprocessedby
SpamAssassin.Itreceived24.5hits,indicatingthatitis
almostcertainlyspam.
X-Spam-Status:Yes,hits=24.5required=5.0
tests=DATE_IN_FUTURE_06_12,INVALID_DATE_TZ_ABSURD,
MSGID_OE_SPAM_4ZERO,MSGID_OUTLOOK_TIME,
MSGID_SPAMSIGN_ZEROES,RCVD_IN_DSBL,RCVD_IN_NJABL,
RCVD_IN_UNCONFIRMED_DSBL,REMOVE_PAGE,VACATION_SCAM,
X_NJABL_OPEN_PROXY
version=2.55
X-Spam-Level:************************
X-Spam-Checker-Version:SpamAssassin2.55(1.174.2.19-2003-05-19-exp)
X-Spam-Report:Thismailisprobablyspam.Theoriginalmessagehasbeenattached
alongwiththisreport,soyoucanrecognizeorblocksimilarunwanted
mailinfuture.Seehttp://spamassassin.org/tag/formoredetails.
Contentpreview:ParadiseSEXIslandAwaits!Tropical1weekvacations
whereanythinggoes!WehavelotsofWOMEN,SEX,ALCOHOL,ETC!Every
man'sdreamawaitsonthisislandofpleasure.[...]
Contentanalysisdetails:(24.50points,5required)
MSGID_SPAMSIGN_ZEROES(4.3points)Message-Idgeneratedbyspamtool(zeroesvariant)
INVALID_DATE_TZ_ABSURD(4.3points)InvalidDate:header(timezonedoesnotexist)
MSGID_OE_SPAM_4ZERO(3.5points)Message-Idgeneratedbyspamtool(4-zeroesvariant)
VACATION_SCAM(1.9points)BODY:VacationOffers
REMOVE_PAGE(0.3points)URI:URLofpagecalled"remove"
MSGID_OUTLOOK_TIME(4.4points)Message-Idisfake(inOutlookExpressformat)
DATE_IN_FUTURE_06_12(1.3points)Date:is6to12hoursafterReceived:date
RCVD_IN_NJABL(0.9points)RBL:Receivedviaarelayindnsbl.njabl.org
[RBLcheck:found94.99.190.200.dnsbl.njabl.org.]
RCVD_IN_UNCONFIRMED_DSBL(0.5points)RBL:Receivedviaarelayinunconfirmed.dsbl.org
[RBLcheck:found94.99.190.200.unconfirmed.dsbl.org.]
X_NJABL_OPEN_PROXY(0.5points)RBL:NJABL:senderisproxy/relay/formmail/spam-source
RCVD_IN_DSBL(2.6points)RBL:Receivedviaarelayinlist.dsbl.org
[RBLcheck:found211.157.63.200.list.dsbl.org.]
X-Spam-Flag:YES
Subject:[SPAM]re:statement
BecauseSpamAssassinconsideredtheprecedingemailtobe
spam,itmodifiedtheSubjectlinebyadding[SPAM]atthe
beginningoftheline.
Configuration
Edit/etc/mail/spamassassin/local.cftoconfigure
SpamAssassinglobally.Userscanoverridetheglobaloptions
andaddtheirownoptionsin~/.spamassassin/user_prefs.
Youcanputtheoptionsdiscussedinthissectionineitherof
thesefiles.Useperldoctodisplaytheconfigurationdocument
thatlistsalltheoptions:
Documentation
$perldocMail::SpamAssassin::Conf
Asshownintheprecedingexample,SpamAssassinrewritesthe
Subjectlineofemailthatitratesasspam.The
rewrite_subjectkeywordintheconfigurationfilescontrols
thisbehavior.A1followingthiskeywordindicatesthat
SpamAssassinwillrewriteSubjectlines.Changethe1toa0
(zero)toturnoffthisbehavior:
rewrite_subject0
Therequired_hitskeywordspecifiestheminimumnumberof
hitsapieceofemailmustreceivebeforeSpamAssassin
considersittobespam.Thedefaultis5.0.Withahigher
number,SpamAssassinmarksfewerpiecesofemailasspam.
required_hits5.00
Sometimesmailfromaddressesthatshouldbemarkedasspam
isnot,ormailfromaddressesthatshouldnotbemarkedas
spamis.Usethewhitelist_fromkeywordtospecifyaddresses
thatshouldneverbemarkedasspamandblacklist_fromto
specifyaddressesthatshouldalwaysbemarkedasspam:
whitelist_fromsams@tcorp.com
blacklist_fromspammer.net
Youcanspecifymultipleaddresses,separatedbySPACEs,on
thewhitelist_fromandblacklist_fromlines.Eachaddress
canincludewildcards.Youcanalsousemultiplelines.
UsingSpamAssassinwithaMailServer
ToaddSpamAssassinheaderstoeachemailthatarrivesonthe
system,youneedtoconfigureyourMDAtopipeemailthrough
thespamc.Thefirststepistomakesureyouhaveprocmail
configuredasyourMDA.Thefirstofthefollowinglinesin
sendmail.mcspecifiestheprocmailcommand,itspath,and
flags.TheMAILERlinedefinesprocmailasthemailer.You
shouldnothavetochangeeitheroftheselines.
FEATURE(local_procmail,'','procmail-t-Y-a$h-d$u')dnl
MAILER(procmail)dnl
Theprocmailconfigurationfile,/etc/procmailrc,maynot
existontheserver.Ifthefiledoesnotexist,createitsothatit
isownedbyrootandhas644permissionsandthefollowing
contents.Ifitdoesexist,appendthelasttwolinesfromthe
followingfiletoit:
$cat/etc/procmailrc
DROPPRIVS=yes
:0fw
|/usr/bin/spamc
Thefirstlineofthisfileensuresthatprocmailrunswiththe
leastpossibleprivileges.Thenexttwolinesimplementarule
thatpipeseachuser'sincomingemailthroughspamc.The:0
tellsprocmailthatarulefollows.Thefflagindicatesafilter;
thewflagcausesprocmailtowaitforthefiltertocomplete
andchecktheexitcode.Thelastlinespecifiesthe
/usr/bin/spamcfileasthefilter.
Withtheprecedingchangesinplace,allemailthatcomesinto
thesystempassesthroughSpamAssassin,whichratesit
accordingtotheoptionsintheglobalconfigurationfile.For
userswhohavehomedirectoriesontheserversystem,
SpamAssassinallowsusers'configurationfilestooverridethe
globalfile.
WhenyourunSpamAssassinonaserver,youtypicallywantto
ratetheemailmoreconservativelysothatfewerpiecesofgood
emailaremarkedasspam.Settingrequired_hitsintherange
of610isgenerallyappropriate.Also,youdonotwantto
removeanyemailautomaticallybecauseyoucouldpreventa
userfromgettingapieceofnonspamemail.Whentheserver
marksemailaspossiblybeingspam,userscanmanuallyor
automaticallyfilterthespamanddecidewhattodowithit.
UsingSpamAssassinwithaMailClient
WiththeSpamAssassin(spamd)daemonrunningandthe
configurationfilessetup,youarereadytohaveSpamAssassin
filteryouremail.Todoso,youneedtosetuptworulesinyour
mailclient:Thefirstpasseseachpieceofemailthrough
SpamAssassinusingspamc(page640)andthesecondfilters
emailbasedonwhethertheX-Spam-FlaglinehasaYESorNO
onit.
Ingeneral,youdonotwanttopassverylargepiecesofemail
throughSpamAssassin.Thefollowingexample,whichuses
KMail,passesmessagessmallerthan200,000bytesthrough
SpamAssassin.Thefirstfilterrule(Figure20-1)processesall
messageswherethesizeislessthan200,000bytes.Therule
pipesmessagesthrough/usr/bin/spamc.Thisruleusesnice
toconservesystemresources.TheAdvancedtabspecifiesthat
theruleisappliedtoincomingmessagesandfilteringdoesnot
stopifthemessagematchesthisrule.
Figure20-1.Thefirstrulepassesmessages
throughSpamAssassin
[Viewfullsizeimage]
ThefirstruleaddsanX-Spam-Flaglinetoeachpieceofemailit
processes.Thesecondrulechecksthevalueoftheflagonthis
line.IftheX-Spam-FlaglinecontainsYES,thesecondrule
movestheemailtoafoldernamedspam(Figure20-2).
BecausetheIfthisfiltermatches,stopprocessinghere
boxischeckedintheAdvancedtab,KMaildoesnotfurther
processmessagesmarkedasspam.Messagesnotmarkedas
spamcanbeprocessedbyotherrules.
Figure20-2.ThesecondrulecheckstheX-Spam-
Flag
[Viewfullsizeimage]
SELinux
WhenSELinuxissettouseatargetedpolicy,theSpamAssassin
daemon,spamd,isprotectedbySELinux.Youcandisablethis
protectionifnecessary.Formoreinformationreferto"Setting
theTargetedPolicywithsystem-config-securitylevel"onpage402.
Webmail
Traditionallyyoureademailusingadedicatedemailclientsuch
asKMail.RecentlyithasbecomemorecommontouseaWeb
applicationtoreademail.Ifyouhaveanemailaccountwitha
commercialprovidersuchasGmail,HotMail,orYahoo!Mail,you
useaWebbrowsertoreademail.Emailreadinthismanneris
calledWebmail.Unlikeemailyoureadonadedicatedclient,
youcanreadWebmailfromanywhereyoucanopenabrowser
ontheInternet:YoucancheckyouremailfromanInternetcafe
orafriend'scomputer,forexample.
SquirrelMail(squirrelmailpackage)providesWebmail
services;theSquirrelMailfilesresidein
/usr/share/squirrelmail.IfyouwanttorunSquirrelMail,you
mustrunIMAP(page647)becauseSquirrelMailusesIMAPto
receiveandauthenticateemail.YoumustalsorunApache
(Chapter26)soausercanuseabrowsertoconnectto
SquirrelMail.
SquirrelMailismodular:Youcaneasilyaddfunctionalityusing
plugins.Therearepluginsthatallowyoutoshareacalendar
andpluginsthatgiveyoutheabilitytochangepasswordsusing
theWebmailinterface.Seethepluginssectionofthe
SquirrelMailWebsiteformoreinformation.
CreatethefollowinglinktomakeSquirrelMailaccessiblefrom
theWeb:
#ln-s/usr/share/squirrelmail/var/www/html/mail
Withthislinkinplace,youcanpointaWebbrowserat
http://localhost/mailtodisplaytheSquirrelMailloginpage
(Figure20-3).
Figure20-3.SquirrelMailloginpage
[Viewfullsizeimage]
Nextusetheconf.plscriptin
/usr/share/squirrelmail/configtoconfigureSquirrelMail:
#cd/usr/share/squirrelmail/config
#./conf.pl
SquirrelMailConfiguration:Read:config_default.php(1.4.0)
---------------------------------------------------------
MainMenu--
1.OrganizationPreferences
2.ServerSettings
3.FolderDefaults
4.GeneralOptions
5.Themes
6.AddressBooks
7.MessageoftheDay(MOTD)
8.Plugins
9.Database
10.Languages
D.Setpre-definedsettingsforspecificIMAPservers
CTurncoloron
SSavedata
QQuit
Command>>
TheonlyitemthatyoumustsettogetSquirrelMailtoworkis
theserver'sdomainname(fromtheServerSettingspage).
SquirrelMailprovidesseveralthemes;ifyoudonotliketheway
SquirrelMaillooks,chooseanotherthemefromtheThemes
page.
MailingLists
Amailinglistcanbeanassetifyouregularlysendemailtothe
samelargegroupofpeople.Amailinglistprovidesseveral
advantagesoverlistingnumerousrecipientsintheToorCcfield
ofanemailorsendingthesameemailindividuallytomany
people:
AnonymityNoneoftherecipientsoftheemailcanseethe
addressesoftheotherrecipients.
ArchivingEmailsenttothelistisstoredinacentral
locationwherelistmembersorthepublic,asspecifiedby
thelistadministrator,canbrowsethroughit.
AccesscontrolYoucaneasilyspecifywhocansendemail
tothelist.
ConsistencyWhenyousendmailtoagroupofpeople
usingToorCc,itisalltooeasytoleavepeoplewhowantto
beonthelistoffandtoleavepeoplewhowanttobeoffthe
liston.
EfficiencyAmailinglistapplicationspreadsemail
transmissionsovertimesoitdoesnotoverloadthemail
server.
Mailmanprovidesmailinglistsupport.ThebulkofMailman
residesin/usr/lib/mailman.Theconfigurationfileis
/etc/mailman/mm_cfg.py,whichisalinkto
/usr/lib/mailman/Mailman/mm_cfg.py.Beforeyoucan
useMailman,youneedtoreplacefqdninthetwofollowing
linesinmm_cfg.pywiththenameofthelocaldomainenclosed
withinsinglequotationmarks:
DEFAULT_URL_HOST=fqdn
DEFAULT_EMAIL_HOST=fqdn
Aftermakingthesechanges,createanewmailinglistwiththe
newlistutility:
#/usr/lib/mailman/bin/newlist
Enterthenameofthelist:painting_class
Entertheemailofthepersonrunningthelist:helen@tcorp.com
Initialpainting_classpassword:
Tofinishcreatingyourmailinglist,youmustedityour/etc/aliases(or
equivalent)filebyaddingthefollowinglines,andpossiblyrunningthe
'newaliases'program:
##painting_classmailinglist
painting_class:"|/usr/lib/mailman/mail/mailmanpostpainting_class"
painting_class-admin:"|/usr/lib/mailman/mail/mailmanadminpainting_class"
painting_class-bounces:"|/usr/lib/mailman/mail/mailmanbouncespainting_class"
painting_class-confirm:"|/usr/lib/mailman/mail/mailmanconfirmpainting_class"
painting_class-join:"|/usr/lib/mailman/mail/mailmanjoinpainting_class"
painting_class-leave:"|/usr/lib/mailman/mail/mailmanleavepainting_class"
painting_class-owner:"|/usr/lib/mailman/mail/mailmanownerpainting_class"
painting_class-request:"|/usr/lib/mailman/mail/mailmanrequestpainting_class"
painting_class-subscribe:"|/usr/lib/mailman/mail/mailmansubscribepainting_class"
painting_class-unsubscribe:"|/usr/lib/mailman/mail/mailmanunsubscribepainting_class"
Hitentertonotifypainting_classowner...
Beforethelistcanreceiveemail,youneedtocopythelines
generatedbynewlisttotheendof/etc/aliases(page633)and
runnewaliases.
MailmanincludesaWebconfigurationinterfacethatyoucan
enablebyconfiguringaWebservertorunthescriptsin
/usr/lib/mailman/cgi-bin.Refertothefile
/etc/httpd/conf.d/mailman.confforasampleentrythat
youcanputin/etc/httpd/conf/httpd.conf(page794)toset
upthisinterface(pipermailisthearchivemanagerthatMailman
uses).
SettingUpanIMAPorPOP3Server
Twoprotocolsallowuserstoretrieveemailremotely:IMAP
(InternetMessageAccessProtocol)andPOP(PostOffice
Protocol).Thedovecotpackage(www.dovecot.org)includes
theimap-loginandpop3-logindaemonsthatimplement
theseprotocols.Typicallyyoudonothavetomodifythe
dovecotconfigurationfile(/etc/dovecot.conf).See
/usr/share/doc/dovecot*formoreinformation.
Thedovecotself-signedcertificate
Thefollowingcommandsgenerateandinstalltheself-signed
certificatesthatdovecotrequires:
FEDORA
#exportSSLDIR=/etc/pki/dovecot
#cd/etc/pki/dovecot
#/usr/share/doc/dovecot-1.0/examples/mkcert.sh
RHEL
Firstedit/usr/share/doc/dovecot*/dovecot-openssl.cnf
asnecessary.Typicallynochangesareneeded.Thengivethe
followingcommandstogenerateandinstalltheself-signed
certificatesthatdovecotrequires:
#mkdir-p/etc/ssl/certs/etc/ssl/private
#cd/usr/share/doc/dovecot*
#shmkcert.sh
Themkcert.shscriptwritesthecertificatestothedirectories
youcreatedwiththefirstcommand.
RHEL+FEDORA
Runchkconfigtocausethedovecotdaemonstostartwhenthe
systementersmultiusermode:
#/sbin/chkconfigdovecoton
Startthedaemonswiththefollowingcommand:
#/sbin/servicedovecotstart
StartingDovecotImap:[OK]
DespitedovecotreportingthatitstartedtheIMAPserveronly,
italsostartsthePOP3server.
SettingUpKMail
KMailisthegraphicalemailclientforKDEthatiscompatible
withtheMIME,SMTP,POP3,andIMAPstandards.Tostart
KMail,givethecommandkmailfromaterminalemulator
windoworfromaRunCommandwindow(pressALT-F2toopen
thiswindow).YoucanalsochooseInternet KMailfromthe
KDEmainmenu.YoucanrunKMailfromanydesktop
environment,includingGNOME.Figure20-4showstheinitial
KMailwindow.
Figure20-4.TheinitialKMailwindow
[Viewfullsizeimage]
WhenyoustartKMailforthefirsttime,ittakesyouthroughthe
stepsnecessarytoconfigureit.Alternatively,youcanconfigure
KMailbyselectingConfigureKMailfromtheSettingsmenuon
themenubartodisplaytheConfigureKMailwindow(Figure20-
5).Thiswindowhasbuttonsalongtheleftside;clickthe
buttonstodisplaydifferentconfigurationpagesontheright.
Figure20-5.TheConfigureKMailwindow
[Viewfullsizeimage]
Identity
KMailsetsupaminimalidentityforyou.ClicktheIdentities
buttontodisplaytheIdentitiespage.Fromthispageyoucan
createnewidentitiesandmodifyexistingones,suchasthe
defaultidentitythatKMailcreatedforyou.Youcanspecifyyour
emailaddress,areply-toaddress(ifitdiffersfromyouremail
address),asignaturethatKMailautomaticallyappendstoyour
outgoingemailmessages,andmore.
Help
KMailprovideshelpinsettingupKMailtosendandreceive
email.ClicktheHelpbuttonatthelower-leftcornerofany
KMailwindowtodisplaytheappropriatepageoftheonline
ConfigureKMailmanual(partoftheKDEHelpCenter).
Accounts
Onceyouhaveanidentity,youneedtosetupincomingand
outgoingaccounts.ClicktheAccountsbuttontodisplaythe
Accountspagewhereyoucansetupaccountsforsendingand
receivingmessages.Thispagehastwotabs:Sendingand
Receiving.
Outgoingaccount
ClicktheSendingtabontheAccountspagetodisplaythe
outgoingaccounts.Theoutgoingaccountdefaultstosendmail
onthelocalsystem.Ifyouusethelocalsendmail,youneedto
configureitasexplainedin"JumpStartI:Configuringsendmailon
aClient"onpage630.IfyouareusingSMTP,youneedto
removethesendmailaccountandaddanSMTPaccount.Todo
so,highlightthesendmailaccountandclickRemove;then
clickAddtodisplaytheAddTransportwindowwhereyoucan
selectsendmailorSMTP.
Incomingaccount
ClicktheReceivingtabontheAccountspagetodisplaythe
incomingaccounts;thereisnodefaultincomingaccount.Click
AddtodisplaytheAddAccountwindowwhereyoucanselecta
typeofaccountsuchasLocalmailbox,POP3,orIMAP.Ifyou
receivemailbothlocallyandfromanISP,youneedtosetup
twoaccounts.ForaPOP3orIMAPaccountyouneedtospecify
theserver(host)andyourusernameandpasswordonthe
server.IfyouwantKMailtocheckformailperiodically,turnon
EnableintervalmailcheckingandspecifyhowoftenKMail
shouldcheckformail.
Youdonothavetochangeanysettingsonotherpages.
Followingisasummaryofwhatyouwillfindoneachofthe
ConfigureKMailpages:
IdentitiesSpecifyoneormoreemailidentitiesincludinga
nameandemailaddressintheGeneraltab,asignaturein
theSignaturetab,anduseofPGPorGnuPG(page992)and
yourOpenPGPkeyintheCryptographytab.
AccountsSpecifyoutgoingandincomingemailaccounts.
AppearanceSpecifyhowKMaillooks,includingfonts,
colors,layout,andheaders.
ComposerSpecifywhatoutgoingmessageslooklikeand
whichheadersareincludedwhenyoureplytoorforwarda
message.
SecuritySpecifysecurityfeaturesincludingwhetheryou
wanttoreceiveHTMLmessagesinHTMLorplaintext.
ReceivingHTMLmessagesinHTMLcanmakeasystemless
secure.
MiscSpecifyKMailoptionsincludingwhichwarningsyou
receive,howmessagesyoureadaremarked,andwhat
happenswhenyouexitfromKMail.
KMailhasalotofoptionsandfeatures.UsetheHelpbuttonto
getassistance.ItiseasytosetupKMailforbasicuse.Asyou
becomemorecomfortableusingit,youcanconfigureKMailtoa
greaterextenttotakecareofmoretasksforyou.
AuthenticatedRelaying
Ifyoutravelwithaportablecomputersuchasalaptop,you
mayconnecttotheInternetthroughadifferentconnectionat
eachlocationwhereyouwork.Perhapsyoutravelforwork,or
maybeyoujustbringyourlaptophomeatnight.
Thissectiondoesnotapplyifyoualwaysdialintothenetwork
throughyourISP.Inthatcase,youarealwaysconnectedto
yourISP'snetworkanditisasthoughyounevermovedyour
computer.
Onalaptopyoudonotusealocalinstanceofsendmailto
sendemail.InsteadyouuseSMTPtoconnecttoanISPortoa
company'sSMTPserver,whichrelaystheoutgoingmail.To
avoidrelayingemailforanyone,includingmalicioususerswho
wouldsendspam,SMTPserversrestrictwhotheyrelayemail
for,basedonIPaddress.Byimplementingauthenticated
relaying,youcancausetheSMTPservertoauthenticate,based
onuseridentification.Inaddition,SMTPcanencrypt
communicationwhenyousendmailfromyouremailclientand
usetheSMTPserver.
Anauthenticatedrelayprovidestheseadvantagesoveraplain
connection:
YoucansendemailfromanyInternetconnection.
Thesecureconnectionmakesitmoredifficulttointercept
emailasittraversestheInternet.
Theoutgoingmailserverrequiresauthentication,
preventingitfrombeingusedforspam.
YousetupauthenticatedrelayingbycreatinganSSLcertificate
orusinganexistingone,enablingSSLinsendmail,andtelling
youremailclienttoconnecttotheSMTPserverusingSSL.If
youhaveanSSLcertificatefromacompanysuchasVerisign,
youcanskipthenextsection,inwhichyoucreateaself-signed
certificate.
CreatingaSelf-SignedCertificateforsendmail
FEDORA
ThedefaultlocationforSSLcertificatesis/etc/pki/tls/certs
(PKIstandsforpublickeyinfrastructure).Workingasroot,use
mkdirtocreatethisdirectoryifnecessaryandthenusethe
Makefileinthisdirectorytogeneratetherequiredcertificates.
Apacheusesasimilarprocedureforcreatingacertificate(page
822).
#cd/etc/pki/tls/certs
#makesendmail.pem
...
Generatinga1024bitRSAprivatekey
........................++++++
.......................++++++
writingnewprivatekeyto'/tmp/openssl.q15963'
-----
Youareabouttobeaskedtoenterinformationthatwillbeincorporated
intoyourcertificaterequest.
WhatyouareabouttoenteriswhatiscalledaDistinguishedNameoraDN.
Therearequiteafewfieldsbutyoucanleavesomeblank
Forsomefieldstherewillbeadefaultvalue,
Ifyouenter'.',thefieldwillbeleftblank.
-----
CountryName(2lettercode)[GB]:US
StateorProvinceName(fullname)[Berkshire]:California
LocalityName(eg,city)[Newbury]:SanFrancisco
OrganizationName(eg,company)[MyCompanyLtd]:SobellAssociatesInc.
OrganizationalUnitName(eg,section)[]:
CommonName(eg,yournameoryourserver'shostname)[]:
EmailAddress[]:mgs@sobell.com
Youcanenteranyinformationyouwishinthecertificate.
RHEL
ThedefaultlocationforSSLcertificatesis
/usr/share/ssl/certs.Beforegivingthemake
sendmail.pemcommandasexplainedabove,usemkdirto
createthisdirectoryifnecessaryandthencdtoit.
EnablingSSLinsendmail
Onceyouhaveacertificate,instructsendmailtouseitby
addingthefollowinglinestosendmail.mc:
define('confAUTH_OPTIONS','Ap')
TRUST_AUTH_MECH('EXTERNALDIGEST-MD5CRAM-MD5LOGINPLAIN')
define('confAUTH_MECHANISMS','EXTERNALGSSAPIDIGEST-MD5CRAM-MD5LOGINPLAIN')
Thefirstoftheselinestellssendmailtoallowauthenticated
userstorelay.Thenexttwolinesspecifytheauthentication
mechanisms.
ThefirstoptionforconfAUTH_OPTIONS,A,instructssendmail
tousetheAUTHparameterwhensendingmailonlyif
authenticationsucceeded.Thesecondoption,P,instructs
sendmail,forconnectionsthatarenotsecure,nottoallow
authenticationmethodsthatcouldbecrackedbyapacket
sniffer.
Nowaddthefollowinglinestosendmail.mctotellsendmail
wherethecertificateis:
define('CERT_DIR','/etc/pki/tls/certs')
define('confCACERT_PATH','CERT_DIR')
define('confCACERT','CERT_DIR/sendmail.pem')
define('confSERVER_CERT','CERT_DIR/sendmail.pem')
define('confSERVER_KEY','CERT_DIR/sendmail.pem')
define('confCLIENT_CERT','CERT_DIR/sendmail.pem')
define('confCLIENT_KEY','CERT_DIR/sendmail.pem')
Encryptedconnectionsaremadeinoneoftwoways:SSL
(simpler)orTLS.SSLrequiresadedicatedportandhasthe
clientandtheservernegotiateasecureconnectionand
continuethetransactionasiftheconnectionwerenot
encrypted.TLShastheclientconnecttotheserverusingan
insecureconnectionandthenissueaSTARTTLScommandto
negotiateasecureconnection.TLSrunsoverthesameportas
anunencryptedconnection.Becausemanyclientssupportonly
SSL,itisagoodideatoinstructsendmailtolistenonthe
SMTPSport.Thefinallinethatyouaddtosendmail.mc
instructssendmailtolistenontheSSLport:
DAEMON_OPTIONS('Port=smtps,Name=TLSMTA,M=s')
EnablingSSLintheMailClient
EnablingSSLinamailclientisusuallyquitesimple.For
example,KMailprovidesSettings ConfigureKMail
Accounts Receiving Add/Modify Extrasthatallows
youtochoosethetypeofencryptionyouwanttouse:None,
SSL,orTLS.
Alternativestosendmail
Overtheyears,sendmailhasgrowntobeenormously
complex.Itscomplexitymakesitchallengingtoconfigureifyou
wanttosetupsomethingmorethanasimplemailserver.Its
sizeandcomplexityalsoaddtoitsvulnerability.Foroptimal
security,makesureyourunthelatestversionofsendmailand
alwayskeepsendmailup-to-date.Youmightconsiderusing
oneofthefollowingalternatives.
Postfix
Postfix(postfixpackage)isanalternativeMTA.Postfix
attemptstobefastandeasytoadminister,whilealsobeing
sendmailcompatibleenoughtonotupsetsendmailusers.
Postfixhasagoodreputationforeaseofuseandsecurityandis
adrop-inreplacementforsendmail.DocumentationforPostfix
canbefoundatwww.postfix.org/docs.html.
Qmail
QmailisadirectcompetitorofPostfixandhasthesame
objectives.Bydefault,Qmailstoresemailusingthemaildir
formatasopposedtothemboxformatthatotherMTAsuse
(page632).TheQmailWebsiteiswww.qmail.org.
ChapterSummary
ThesendmaildaemonisanMTA(MailTransferAgent).When
yousendamessage,sendmailworkswithothersoftwareto
getittotheproperrecipients.Youcansetupsendmailto
relayemailtoanSMTPserverthatsendstheemailontoits
ultimatedestinationoryoucanhavesendmailsendemail
directlytotheSMTPserversforthedomainsreceivingthe
email.Bydefault,sendmailstoresincomingmessagesinthe
mailspooldirectory,/var/spool/mail.
Thefilethatcontrolsmanyaspectsofhowsendmailworksis
sendmail.cf.Ifyoueditsendmail.mc,whenyourestart
sendmail,thesendmailinitscriptgeneratessendmail.cf.
Thesystemadministratorcanusethe/etc/aliasesfileand
ordinaryuserscanuse~/.forwardfilestorerouteemailto
oneormorelocalorremoteaddresses,tofiles,orasinputto
programs.
YoucanuseaprogramsuchasSpamAssassintogradeand
markemailastothelikelihoodofitbeingspam.Youcanthen
decidewhattodowiththemarkedemail:Youcanlookateach
pieceofpotentialspamanddecidewheretoputit,oryoucan
haveyourMUAautomaticallyputpotentialspaminaspecial
mailboxforspam.
OtherprogramsthatcanhelpwithemailincludeSquirrelMail,
whichprovidesWebmailservices,andMailman,whichprovides
mailinglistsupport.
Exercises
1. Bydefault,emailaddressedtosystemgoestoroot.Howwouldyoualsosavea
copyin/var/logs/systemmail?
2. HowwouldMaxstoreacopyofhisemailin~/mboxandsendacopyto
max@bravo.com?
3.
IfyourfirewallallowedonlythemachinewiththeIPaddress192.168.1.1tosend
emailoutsidethenetwork,howwouldyouinstructyourlocalcopyofsendmailto
usethisserverasarelay?
4. Whatdoesdnlstandforinthem4macrolanguage?Whatarednlcommandsused
for?
5.
SpamAssassinisinstalledonyourmailserver,withthethresholdsettoan
unusuallylowvalueof3,resultinginalotoffalsepositives.Whatrulecouldyou
givetoyourmailclienttoallowittoidentifyspamwithascoreof5orhigher?
6. DescribethesoftwareandprotocolsusedwhenMaxsendsanemailtoSamona
remoteLinuxsystem.
AdvancedExercises
7.
Yourcompany'scurrentmailserverrunsonacommercialUNIXserver,andyouare
planningtomigrateittoLinux.Aftercopyingtheconfigurationfilesacrosstothe
Linuxsystem,youfindthatitdoesnotwork.Whatmightyouhaveforgottento
change?
8.
Assumeyouhaveascriptthatsendsitsoutputtostandardoutput.Howwouldyou
modifythescripttosendtheoutputinanemailtoauserspecifiedbythefirst
argumentonthecommandline?(Youmayassumethatthedataisstoredin
$RESULT.)
9. GiveasimplewayofreadingyouremailthatdoesnotinvolvetheuseofanMUA.
10. Ifyouaccidentallydeletethe/etc/aliasesfile,howcouldyoueasilyre-createit
(assumingthatyouhadnotrestartedsendmail)?
21.NIS:NetworkInformationService
INTHISCHAPTER
HowNISWorks 656
SettingUpanNISClient 659
yppasswd:ChangesNISPasswords 662
SettingUpanNISServer 663
yppasswdd:TheNISPasswordUpdateDaemon 669
NIS(NetworkInformationService)simplifiesthemaintenance
ofcommonadministrativefilesbykeepingtheminacentral
databaseandhavingclientscontactthedatabaseserverto
retrieveinformationfromthedatabase.DevelopedbySun
Microsystems,NISisanexampleoftheclient/serverparadigm.
JustasDNSaddressestheproblemofkeepingmultiplecopies
of/etc/hostsfilesup-to-date,NISdealswiththeissueof
keepingsystem-independentconfigurationfiles(suchas
/etc/passwd)current.Mostnetworkstodayare
heterogeneous(page1035);eventhoughtheyrundifferent
varietiesofUNIXorLinux,theyhavecertaincommon
attributes,suchasapasswdfile.
IntroductiontoNIS
AprimarygoalofaLANadministratoristomakethenetwork
transparenttousers.Oneaspectofthistransparencyis
presentinguserswithsimilarenvironments,includingusername
andpassword,whentheyloginondifferentmachines.From
theadministrator'sperspective,theinformationthatsupportsa
user'senvironmentshouldnotbereplicatedbutrathershould
bekeptinacentrallocationanddistributedasrequested.NIS
simplifiesthistask.
AswithDNS,usersneednotbeawarethatNISismanaging
systemconfigurationfiles.SettingupandmaintainingNIS
databasesaretasksforthesystemadministrator;individual
usersandusersonsingle-userLinuxsystemsrarelyneedto
workdirectlywithNIS.
YellowPages
NISusedtobecalledtheYellowPages,andsomepeoplestill
refertoitbythisname.Sunrenamedtheservicebecause
anothercorporationholdsthetrademarktothatname.The
namesofNISutilitiesandfiles,however,arereminiscentofthe
oldname:ypcatdisplaysandypmatchsearchesanNISfile,and
theserverdaemonisnamedypserv.
HowNISWorks
NISdomain
NISmakesacommonsetofinformationavailabletosystems
onanetwork.Thenetwork,referredtoasanNISdomain,is
characterizedbyeachsystemhavingthesameNISdomain
name(differentthana(DNS)domainname[page1030]).
Technically,anNISdomainisasetofNISmaps,ordatabase
files.
Masterandslaveservers
EachNISdomainmusthaveexactlyonemasterserver;larger
networksmayhaveslaveservers.Eachslaveserverholdsa
copyoftheNISdatabasefromthemaster.Theneedforslave
serversisbasedonthesizeoftheNISdomainandthe
reliabilityofthesystemsandnetwork.Asystemcanbelongto
onlyoneNISdomainatatime.
Whenaclientdeterminesthataserverisdownorisnot
respondingfastenough,itselectsanotherserver,asspecifiedin
theconfigurationfile.Ifitcannotreachaserver,ypbind
terminateswithanerror.
nsswitch.conf
WhetherasystemusesNIS,DNS,localfiles,oracombination
asthesourceofcertaininformation,andinwhatorder,is
determinedby/etc/nsswitch.conf(page435).Whenitneeds
informationfromtheNISdatabase,aclientrequeststhe
informationfromtheNISserver.Forexample,whenauser
attemptstologin,theclientsystemmayauthenticatetheuser
withnameandpasswordinformationfromtheNISserver.
Youcanconfigurensswitch.conftocause/etc/passwdto
overrideNISpasswordinformationforthelocalsystem.When
youdonotexporttherootaccounttoNIS(andyoushould
not),thissetupallowsyoutohaveauniquerootpasswordfor
eachsystem.
Sourcefiles
UnderRedHatLinux,NISderivestheinformationitofferssuch
asusernames,passwords,andlocalsystemnamesandIP
addressesfromlocalASCIIconfigurationfilessuchas
/etc/passwdand/etc/hosts.Thesefilesarecalledsource
filesormasterfiles.(Someadministratorsavoidconfusionby
usingdifferentfilesforlocalconfigurationandNISsource
information.)AnNISservercanincludeinformationfromas
manyofthefollowingsourcefilesasisappropriate:
/etc/group Definesgroupsandtheirmembers
/etc/gshadow Providesshadowpasswordsforgroups
/etc/hosts MapslocalsystemsandIPaddresses
/etc/passwd Listsuserinformation
/etc/printcap Listsprinterinformation
/etc/rpc MapsRPCprogramnamesandnumbers
/etc/services Mapssystemservicenamesandportnumbers
/etc/shadow Providesshadowpasswordsforusers
TheinformationthatNISoffersisbasedonfilesthatchange
fromtimetotime;NISisresponsibleformakingthischanging
informationavailableinatimelymannertoallsystemsinthe
NISdomain.
NISmaps
BeforeNIScanstoretheinformationcontainedinasourcefile,
itmustbeconvertedtoadbm(page1028)formatfilecalleda
map.Eachmapisindexedononefield(column).Records
(rows)fromamapcanberetrievedbyspecifyingavaluefrom
theindexedfield.Somefilesgeneratetwomaps,eachindexed
onadifferentfield.Forexample,the/etc/passwdfile
generatestwomaps:oneindexedbyusername,theother
indexedbyUID.Thesemapsarenamedpasswd.bynameand
passwd.byuid.
Optional
NISmapscorrespondtoClibraryfunctions.Thegetpwnam()andgetpwuid()
functionsobtainusernameandUIDinformationfrom/etc/passwdonnon-NIS
systems.OnNISsystems,thesefunctionsplaceRPCcallstotheNISserverina
processthatistransparenttotheapplicationcallingthefunction.
Mapnames
ThenamesofthemapsthatNISusescorrespondtothefilesin
the/var/yp/nisdomainnamedirectoryonthemasterserver,
wherenisdomainnameisthenameoftheNISdomain:
$ls/var/yp/mgs
group.bygidmail.aliasesprotocols.bynameservices.byname
group.bynamenetid.bynameprotocols.bynumberservices.byservicename
hosts.byaddrpasswd.bynamerpc.bynameypservers
hosts.bynamepasswd.byuidrpc.bynumber
Mapnicknames
TomakeiteasiertorefertoNISmaps,youcanassign
nicknamestomaps.The/var/yp/nicknamesfilecontainsa
listofcommonlyusednicknames.Viewthenicknamesfileor
givethecommandypcatxtodisplaythelistofnicknames:
$cat/var/yp/nicknames
passwdpasswd.byname
groupgroup.byname
networksnetworks.byaddr
hostshosts.byname
protocolsprotocols.bynumber
servicesservices.byname
aliasesmail.aliases
ethersethers.byname
Eachlineinnicknamescontainsanicknamefollowedby
whitespaceandthenameofthemapthenicknamerefersto.
Youcanadd,remove,ormodifynicknamesbychangingthe
nicknamesfile.
Displayingmaps
TheypcatandypmatchutilitiesdisplayinformationfromtheNIS
maps.Usingthenicknamepasswd,thefollowingcommand
displaystheinformationcontainedinthepasswd.byname
map:
$ypcatpasswd
mark:$1$X4JAzD0.$c.64fRCLPvQNSmq9qrfYv/:500:500:MarkSobell:/home/mark:/bin/bash
...
Bydefault,NISstorespasswordsonlyforuserswithUIDsless
than500(seeMINUID,onpage666).Thusypcatdoesnot
displaylinesforroot,bin,andothersystementries.Youcan
displaypasswordinformationforasingleuserwithypmatch:
$ypmatchmarkpasswd
mark:$1$X4JAzD0.$c.64fRCLPvQNSmq9qrfYv/:500:500:MarkSobell:/home/mark:/bin/bash
Youcanretrievethesameinformationbyfilteringtheoutputof
ypcatthroughgrep,butypmatchismoreefficientbecauseit
searchesthemapdirectly,usingasingleprocess.Theypmatch
utilityworksonthekeyforthemaponly.Tomatchmembersof
thegrouporotherfieldsnotinamap,suchastheGECOS
(page1033)fieldinpasswd,youneedtouseypcatwithgrep:
$ypcatpasswd|grep-isobell
mark:$1$X4JAzD0.$c.64fRCLP9qrfYv/:500:500:MarkSobell:/home/mark:/bin/bash
Terminology
Thischapterusesthefollowingdefinitions:
NISsourcefilesTheASCIIfilesthatNISobtainsinformation
from
NISmapsThedbm-formatfilescreatedfromNISsourcefiles
NISdatabaseThecollectionofNISmaps
MoreInformation
Local
manpagesdomainname,makedbm,netgroup,revnetgroup,ypbind,
ypcat,ypinit,ypmatch,yppasswd,yppoll,yppush,ypset,ypserv,
ypserv.conf,ypwhich,ypxfr,ypxfrd(Someoftheseareinstalled
onlywhenyouinstallypserv,whichisneededwhenyourunan
NISserver[page663].)
Web
www.linux-nis.org
SettingUpanNISClient
ThissectiondiscusseshowtosetupanNISclientonthelocal
system.
Prerequisites
Installthefollowingpackages:
yp-tools
ypbind
Runchkconfigtocauseypbindtostartwhenthesystementers
multiusermode:
#/sbin/chkconfigypbindon
Afteryouhaveconfiguredypbind,startitwithservice:
#/sbin/serviceypbindstart
BindingtotheNISdomain:[OK]
ListeningforanNISdomainserver.
Notes
IfthereisnoNISserverforthelocalsystem'sNISdomain,you
needtosetoneup(page663).IfthereisanNISserver,you
needtoknowthenameoftheNISdomainthesystembelongs
toand(optionally)thenameorIPaddressofoneormoreNIS
serversfortheNISdomain.
AnNISclientcanrunonthesamesystemasanNISserver.
SELinux
WhenSELinuxissettouseatargetedpolicy,NISisprotected
bySELinux.Youcandisablethisprotectionifnecessary.For
moreinformationreferto"SettingtheTargetedPolicywith
system-config-securitylevel"onpage402.
Step-by-StepSetup
Thissectionliststhestepsinvolvedinsettingupandstartingan
NISclient.
SpecifyingtheSystem'sNISDomainName
Specifythesystem'sNISdomainnameinthe
/etc/sysconfig/networkfilebyaddingthefollowingline:
NISDOMAIN=nisdomainname
wherenisdomainnameisthenameoftheNISdomainthatthe
localsystembelongsto.Theypbindandypservinitscripts
executethenetworkfilesothatthenameofthesystem'sNIS
domainissetjustbeforeitisneeded.Youcanusethe
nisdomainnameutilitytosetorviewtheNISdomainname,but
settingitinthismannerdoesnotmaintainthenamewhenthe
systemisrebooted:
Tip:ADNSdomainnameisdifferent
fromanNISdomainname
TheDNSdomainnameisusedthroughoutthe
Internettorefertoagroupofsystems.DNSmaps
thesenamestoIPaddressestoenablesystemsto
communicatewithoneanother.
TheNISdomainnameisusedstrictlytoidentify
systemsthatshareanNISserverandisnormally
notseenorusedbyusersandotherprograms.
SomeadministratorsuseonenameasbothaDNS
domainnameandanNISdomainname,although
thispracticecandegradesecurity.
#nisdomainname
(none)
#nisdomainnamemgs
#nisdomainname
mgs
Caution:Toavoidconfusion,use
nisdomainname,notdomainname
Thedomainnameandnisdomainnameutilitiesdothesame
thing:Theydisplayorsetthesystem'sNISdomain
name.Usenisdomainnametoavoidconfusionwhenyou
arealsoworkingwithDNSdomainnames.
Caution:Youmustsetthelocalsystem's
NISdomainname
Ifyoudonotsetthelocalsystem'sNISdomain
name,whenyoustartypbind,itsendsamessageto
syslogd(page562)andquits.
Edit/etc/yp.conftoSpecifyanNISServer
Edit/etc/yp.conftospecifyoneormoreNISservers(masters
and/orslaves).Asexplainedbycommentsinthefile,youcan
useoneofthreeformatstospecifyeachserver:
domainnisdomainserverserver_name
domainnisdomainbroadcast(donotuse)
ypserverserver_name
wherenisdomainisthenameoftheNISdomainthatthelocal
(client)systembelongstoandserver_nameisthehostname
oftheNISserverthatthelocalsystemqueries.Thesecond
formatislesssecurethanthefirstandthirdformatsbecauseit
exposesthesystemtorogueserversbybroadcastingarequest
foraservertoidentifyitself.
Youcanusemultiplelinestospecifymultipleserversforoneor
moredomains.Specifyingmultipleserversforasingledomain
allowsthesystemtochangetoanotherserverwhenitscurrent
serverisslowordown.
WhenyouspecifymorethanoneNISdomain,youmustsetthe
system'sNISdomainnamebeforestartingypbindsotheclient
queriestheproperserver.SpecifyingtheNISdomainnamein
/etc/sysconfig/networkbeforerunningtheypbindinit
scripttakescareofthisissue.See"SpecifyingtheSystem'sNIS
DomainName"onpage659.
Startypbind
TheRedHatLinuxypbinddaemonisypbind-mtrenamedthat
is,anewer,multithreadedversionoftheolderypbinddaemon.
Usechkconfigtocauseypbindtostarteachtimethesystem
entersmultiusermodeandservicetostartypbindimmediately.
Formoreinformationreferto"Prerequisites"onpage659.
TestingtheSetup
Afterstartingypbind,usenisdomainnametomakesurethe
correctNISdomainnameisset.Referto"Specifyingthe
System'sNISDomainName"onpage659ifyouneedtosetthe
NISdomainname.Nextcheckthatthesystemissetupto
connecttotheproperserver.Thenameoftheserverissetin
/etc/yp.conf(page660).
$ypwhich
peach
MakesuretheNISserverisupandrunning(replaceserverwith
thenameoftheserverthatypwhichreturned):
$/usr/sbin/rpcinfo-userverypserv
program100004version1readyandwaiting
program100004version2readyandwaiting
Afterstartingypbind,checkthatithasregisteredwith
portmap:
$/usr/sbin/rpcinfo-ulocalhostypbind
program100007version1readyandwaiting
program100007version2readyandwaiting
Ifrpcinfodoesnotreportthatypbindisreadyandwaiting,
checkthatypbindisrunning:
$/sbin/serviceypbindstatus
ypbind(pid28689)isrunning...
IfNISisstillnotworkingproperly,usetheinitscripttostop
ypbind.Startitagainwithdebuggingturnedon:
#/sbin/serviceypbindstop
ShuttingdownNISservices:[OK]
#/sbin/ypbind-debug
...
Thedebugoptionkeepsypbindintheforegroundandcauses
ittosenderrormessagesanddebuggingoutputtostandard
error.
yppasswd:ChangesNISPasswords
Theyppasswdutilitynottobeconfusedwiththeyppasswdd
daemon(twod's;seepage669)thatrunsontheNIS
serverreplacesthefunctionalityofpasswdonclientswhenyou
areusingNISforpasswords.Wherepasswdchangespassword
informationinthe/etc/shadowfileonthelocalsystem,
yppasswdchangespasswordinformationinthe/etc/shadowfile
ontheNISmasterserverandintheNISshadow.byname
map.Optionally,yppasswdcanalsochangeuserinformationin
the/etc/passwdfileandpasswd.bynamemap.
Theyppasswdutilitychangesthewayyouloginonallsystemsin
theNISdomainthatuseNIStoauthenticatepasswords.The
yppasswdutilitycannotchangerootandsystempasswords;by
default,NISdoesnotstorepasswordsofuserswithUIDsless
than500.Youhavetousepasswdtochangetheseusers'
passwordslocally.
Touseyppasswd,theyppasswdddaemonmustberunningon
theNISmasterserver.
passwdversusyppasswd
WhenauserwhoisauthenticatedusingNISpasswordsruns
passwdtochangeherpassword,allappearstoworkproperly,yet
theuser'spasswordisnotchanged:Theuserneedstouse
yppasswd.Therootandsystemaccounts,incontrast,mustuse
passwdtochangetheirpasswords.Acommonsolutiontothis
problemisfirsttorenamepasswd,forexample,torootpasswd,and
thentochangeitspermissionssoonlyrootcanexecuteit.[1]
Second,createalinktoyppasswdnamedpasswd:
[1]Thepasswdutilityhassetuidpermissionwithexecutepermissionforallusers.If,after
changingitsnameandpermissions,youwanttorestoreitsoriginalnameand
permissions,firstchangeitsnameandthengivethecommandchmod4511
/usr/bin/passwd.
#ls-l/usr/bin/passwd
-r-s--x--x1rootroot16336Feb132006/usr/bin/passwd
#mv/usr/bin/passwd/usr/bin/rootpasswd
#chmod700/usr/bin/rootpasswd
#ln-s/usr/bin/yppasswd/usr/bin/passwd
#ls-l/usr/bin/{yppasswd,passwd,rootpasswd}
lrwxrwxrwx1rootroot17Oct815:32/usr/bin/passwd->/usr/bin/yppasswd
-rwx------1rootroot16336Feb132006/usr/bin/rootpasswd
-r-xr-xr-x3rootroot18544Jan252006/usr/bin/yppasswd
Withthissetup,anonrootuserchanginghispasswordusing
passwdwillrunyppasswd,whichisappropriate.Ifrootora
systemaccountuserrunspasswd(reallyyppasswd),yppasswd
displaysanerrorthatwillideallyremindtheadministratorto
runrootpasswd.
ModifyingUserInformation
AslongasyppasswddisrunningontheNISmasterserver,a
usercanuseyppasswdfromanNISclienttochangeherNIS
passwordandrootcanchangeanyuser'spassword(except
thatofrootorasystemaccountuser).Ausercanalsouse
yppasswdtochangehisloginshellandGECOS(page1033)
informationiftheyppasswdddaemonissetuptopermitthese
changes.Referto"yppasswdd:TheNISPasswordUpdate
Daemon"onpage669forinformationonhowtoconfigure
yppasswddtopermituserstochangethesefields.Usethel
optionwithyppasswdtochangetheloginshell.Useftochange
GECOSinformation:
$yppasswd-f
ChangingNISaccountinformationformarkonpeach.
Pleaseenterpassword:
Changingfullnameformarkonpeach.
Toacceptthedefault,simplypressreturn.Toenteranempty
field,typetheword"none".
Name[MSobell]:MarkGSobell
Location[]:SF
OfficePhone[]:
HomePhone[]:
TheGECOSinformationhasbeenchangedonpeach.
$ypmatchmarkpasswd
mark:$1$X49qrfYv/:500:500:MarkGSobell,SF:/home/mark:/bin/bash
AddingandRemovingUsers
ThereareseveralwaystoaddandremoveusersfromtheNIS
passwdmap.Theeasiestapproachistokeepthe
/etc/passwdfileontheNISmasterserversynchronizedwith
thepasswdmap.Youcankeepthesefilessynchronizedby
makingchangestothepasswdfileusingstandardtoolssuch
aspasswdandrunningypinittoupdatethemap(page668).
SettingUpanNISServer
ThissectiondiscusseshowtosetupanNISserver.
Prerequisites
DecideonanNISdomainname.SomesitesusetheirDNS
domainnameastheNISdomainname.Choosingadifferent
nameismoresecure.
Installthefollowingpackage:
ypserv
Runchkconfigtocauseypservtostartwhenthesystementers
multiusermode:
#/sbin/chkconfigypservon
Onthemasterserveronly,runchkconfigtocausethemap
server,ypxfrd(page668),tostartwhenthesystementers
multiusermode:
#/sbin/chkconfigypxfrdon
Inaddition,onthemasterserveronly,runchkconfigtocausethe
NISpasswordupdatedaemon,yppasswdd(page669),tostart
whenthesystementersmultiusermode:
#/sbin/chkconfigyppasswddon
Afterconfiguringypserv,startitwiththeypservinitscript:
#/sbin/serviceypservstart
StartingYPserverservices:
Nextstarttheypxfrddaemon(page668)onthesystem
runningthemasterserver:
#/sbin/serviceypxfrdstart
StartingYPmapserver:[OK]
Nowstarttheyppasswdddaemon(page669)onthemaster
server:
#/sbin/serviceyppasswddstart
StartingYPpasswdservice:[OK]
Notes
AnNISclientcanrunonthesamesystemasanNISserver.
Theremustbeonlyonemasterserverforeachdomain.
YoucanrunmultipleNISdomainservers(fordifferentdomains)
onasinglesystem.
AnNISserverservestheNISdomainslistedin/var/yp.Fora
moresecuresystem,removethemapsdirectoriesfrom
/var/ypwhendisablinganNISserver.
SELinux
WhenSELinuxissettouseatargetedpolicy,NISisprotected
bySELinux.Youcandisablethisprotectionifnecessary.For
moreinformationreferto"SettingtheTargetedPolicywith
system-config-securitylevel"onpage402.
Step-by-StepSetup
Thissectionliststhestepsinvolvedinsettingupandstartingan
NISserver.
SpecifytheSystem'sNISDomainName
Specifythesystem'sNISdomainnamebyaddingthefollowing
linetothe/etc/sysconfig/networkfile:
NISDOMAIN=nisdomainname
wherenisdomainnameisthenameoftheNISdomainthatthe
localsystembelongsto.Formoreinformationreferto
"SpecifyingtheSystem'sNISDomainName"onpage659.
Edit/etc/ypserv.conftoConfiguretheNISServer
The/etc/ypserv.conffile,whichholdsNISserver
configurationinformation,specifiesoptionsandaccessrules.
Optionrulesspecifyserveroptionsandhavethefollowing
format:
option:value
Options
Followingisalistofoptionsandtheirdefaultvalues:
files
Specifiesthemaximumnumberofmapfilesthatypserv
caches.Setto0toturnoffcaching.Defaultis30.
trusted_master
Onaslaveserver,thename/IPaddressofthemasterserver
thatnewmapswillacceptedbefrom.Defaultisnomaster
server,meaningnonewmapsareaccepted.
xfer_check_port
YES(default)requiresthemasterservertorunonaprivileged
port(page1049).NOallowsittorunonanyport.
AccessRules
Accessrules,whichspecifywhichhostsanddomainscanaccess
whichmaps,havethefollowingformat:
host:domain:map:security
wherehostanddomainspecifytheIPaddressandNISdomain
thisruleappliesto;mapisthenameofthemapthatthisrule
appliesto;andsecurityiseithernone(alwaysallowaccess),
port(allowaccessfromaprivilegedport),ordeny(neverallow
access).
Thefollowinglinesappearintheypserv.conffilesuppliedwith
RedHatLinux:
$cat/etc/ypserv.conf
...
#Noteverybodyshouldseetheshadowpasswords,notsecure,since
#underMSDOGeverbodyisrootandcanaccessports<1024!!!
*:*:shadow.byname:port
*:*:passwd.adjunct.byname:port
...
Theselinesrestricttheshadow.bynameand
passwd.adjunct.byname(thepasswdmapwithshadow
[asterisk]entries)mapstoaccessfromportsnumberedless
than1024.Asthecommentpointsout,however,anyoneusing
aDOSorearlyWindowssystemonthenetworkcanreadthe
mapsbecausetheycanaccessportsnumberedlessthan1024.
ThefollowingexampledescribesaLANwithsomeaddresses
thatyouwanttograntNISaccessfromandsomethatyoudo
not;perhapsyouhaveawirelesssegmentorsomepublic
networkconnectionsthatyoudonotwanttoexposetoNIS.
YoucanlistthesystemsoranIPsubnetthatyouwanttogrant
accesstoinypserv.conf.AnyonelogginginonanotherIP
addresswillthenbedeniedNISservices.Thefollowingline
fromypserv.confgrantsaccesstoanyonelogginginfroman
IPaddressintherangeof192.168.0.1to192.168.0.255
(specifiedas192.168.0.1withasubnetmask[page423]of
/24):
$cat/etc/ypserv.conf
...
192.168.0.1/24:*:*:none
Create/var/yp/securenetstoEnhanceSecurity
Toenhancesystemsecurity,createthe/var/yp/securenets
file,whichpreventsunauthorizedsystemsfromsendingRPC
requeststotheNISserverandretrievingNISmaps.Notably
securenetspreventsunauthorizedusersfromretrievingthe
shadowmap,whichcontainsencryptedpasswords.When
securenetsdoesnotexistorisempty,anNISserveraccepts
requestsfromanysystem.
EachlineofsecurenetslistsanetmaskandIPaddress.NIS
acceptsrequestsfromsystemswhoseIPaddressesare
specifiedinsecurenetsandignoresandlogsrequestsfrom
otheraddresses.Youmustincludethe(local)serversystemas
localhost(127.0.0.1)insecurenets.Asimplesecurenetsfile
follows:
$cat/var/yp/securenets
#youmustacceptrequestsfromlocalhost
255.255.255.255127.0.0.1
#
#acceptrequestsfromIPaddresses192.168.0.1-192.168.0.62
255.255.255.192192.168.0.0
#
#acceptrequestsfromIPaddressesstartingwith192.168.14
255.255.255.0192.168.14.0
Edit/var/yp/MakefiletoSpecifyMaps
Themakeutility(page842),controlledby/var/yp/Makefile,
usesmakedbmtocreatetheNISmapsthatholdtheinformation
thatNISdistributes.Whenyourunypinitonthemasterserver,
ypinitcallsmake:Youdonotneedtorunmakemanually.
Edit/var/yp/Makefiletosetoptionsandspecifywhichmaps
tocreate.Thefollowingsectionsdiscuss/var/yp/Makefilein
moredetail.
Variables
Followingisalistofvariablesyoucansetin
/var/yp/Makefile.ThevaluesfollowingthewordsRedHat
arethevaluessetinthefiledistributedbyRedHat.
B
Donotchange.
RedHat:notset
NOPUSH
Specifiesthatypservisnottocopy(push)mapstoslave
servers.SettoTRUEifyoudonothaveanyslaveNISservers;
settoFALSEtocauseNIStocopymapstoslaveservers.
RedHat:TRUE
MINUID,MINGID
SpecifiesthelowestUIDandGIDnumberstoincludeinNIS
maps.Inthe/etc/passwdand/etc/groupfiles,lowerID
numbersbelongtorootandsystemaccountsandgroups.To
enhancesecurity,NISdoesnotdistributepasswordandgroup
informationabouttheseusersandgroups.SetMINUIDtothe
lowestUIDnumberyouwanttoincludeintheNISmapsand
setMINGIDtothelowestGIDnumberyouwanttoinclude.
RedHat:500/500
NFSNOBODYUID,NFSNOBODYGID
SpecifiestheUIDandGIDoftheusernamednfsnobody.NIS
doesnotexportvaluesforthisuser.Setto0toexportmapsfor
nfsnobody.
RedHat:65534/65534
MERGE_PASSWD,MERGE_GROUP
TRUEmergesthe/etc/shadowand/etc/passwdfilesand
the/etc/gshadowand/etc/groupfilesinthepasswdand
groupmaps,enablingshadowuserpasswordsandgroup
passwords.
RedHat:TRUE/TRUE
FileLocations
Thenextsectionsof/var/yp/Makefilespecifythestandard
filelocations;youdonotnormallyneedtochangethem.This
partofthemakefileisbrokenintothefollowinggroups:
CommandsLocatesgawkandmakeandsetsavalueforumask
(page420)
SourcedirectoriesLocatesdirectoriesthatcontainNISsource
files
NISsourcefilesLocatesNISsourcefilesusedtobuildtheNIS
database
ServersLocatesthefilethatlistsNISservers
Theall:Target
Theall:targetin/var/yp/Makefilespecifiesthemapsthat
makeistobuildforNIS:
all:passwdgrouphostsrpcservicesnetidprotocolsmail\
#netgrpshadowpublickeynetworksethersbootparamsprintcap\
#amd.homeauto.masterauto.homeauto.localpasswd.adjunct\
#timezonelocalenetmasks
Thefirstlineoftheall:targetliststhemapsthatmakebuildsby
default.Thislinestartswiththewordall,followedbyacolon
(:)andaTAB.Becauseeachofthefirstthreelinesoftheall:
targetendswithabackslash,eachofthefourphysicallinesin
theall:targetispartofonelonglogicalline.Thelastthree
physicallinesarecommentedout.Uncommentlinesanddelete
ormovemapnamesuntilthelistmatchesyourneeds.
Asyourneedschange,youcanedittheall:targetinMakefile
andrunmakeinthe/var/ypdirectorytomodifythelistof
mapsthatNISdistributes.
StarttheServers
Startthemasterserverandthentheslaveserversafter
completingtheprecedingsteps.Usechkconfigtocauseypserv
tostarteachtimethesystementersmultiusermodeandservice
tostartypservimmediately.Formoreinformationreferto
"Prerequisites"onpage663.
ypxfrd:themapserver
TheypxfrddaemonspeedsuptheprocessofcopyinglargeNIS
databasesfromserverstoslaves.Itallowsslavestocopythe
maps,therebyavoidingtheneedforeachslavetocopytheraw
dataandthencompilethemaps.WhenanNISslavereceivesa
messagefromtheserverstatingthatthereisanewmap,it
startsypxfr,whichreadsthemapfromtheserver.
Theypxfrddaemonrunsonthemasterserveronly;itisnot
necessarytorunitonslaveservers.Usechkconfigtocause
ypxfrdtostarteachtimethesystementersmultiusermode
andservicetostartypxfrdimmediately.Formoreinformation
referto"Prerequisites"onpage663.
ypinit:BuildsorImportstheMaps
TheypinitutilitybuildsorimportsandtheninstallstheNIS
database.Onthemasterserver,ypinitgathersinformationfrom
thepasswd,group,hosts,networks,services,protocols,
netgroup,andrpcfilesin/etcandbuildsthedatabase.Ona
slaveserver,ypinitcopiesthedatabasefromthemasterserver.
Youmustrunypinitbygivingitsabsolutepathname
(/usr/lib/yp/ypinit).Usethemoptiontocreatethedomain
subdirectoryunder/var/ypandbuildthemapsthatgoiniton
themasterserver;usethesmasteroptiononslaveserversto
importmapsfrommaster(themasterserver).Inthefollowing
example,ypinitasksforthenamesofeachoftheslaveservers;
italreadyhasthenameofthemasterserverbecausethis
commandisrunonthatsystem(peachintheexample).
TerminatethelistwithCONTROL-Donalinebyitself.Afteryou
respondtothequeryaboutthelistofserversbeingcorrect,
ypinitbuildstheypserversmapandcallsmakewith
/var/yp/Makefile,whichbuildsthemapsspecifiedin
Makefile.
#/usr/lib/yp/ypinit-m
Atthispoint,wehavetoconstructalistofthehostswhichwillrunNIS
servers.peachisinthelistofNISserverhosts.Pleasecontinuetoadd
thenamesfortheotherhosts,oneperline.Whenyouaredonewiththe
list,typea<controlD>.
nexthosttoadd:peach
nexthosttoadd:speedy
nexthosttoadd:CONTROL-D
ThecurrentlistofNISserverslookslikethis:
peach
speedy
Isthiscorrect?[y/n:y]y
Weneedafewminutestobuildthedatabases...
Building/var/yp/mgs/ypservers...
Running/var/yp/Makefile...
gmake[1]:Enteringdirectory`/var/yp/mgs'
Updatingpasswd.byname...
Updatingpasswd.byuid...
Updatinggroup.byname...
Updatinggroup.bygid...
Updatinghosts.byname...
Updatinghosts.byaddr...
Updatingrpc.byname...
Updatingrpc.bynumber...
Updatingservices.byname...
Updatingservices.byservicename...
Updatingnetid.byname...
Updatingprotocols.bynumber...
Updatingprotocols.byname...
Updatingmail.aliases...
gmake[1]:Leavingdirectory`/var/yp/mgs'
peachhasbeensetupasaNISmasterserver.
Nowyoucanrunypinit-speachonallslaveserver.
Testing
Fromtheserver,checkthatypservisconnectedtoportmap:
#rpcinfo-p|grepypserv
1000042udp849ypserv
1000041udp849ypserv
1000042tcp852ypserv
1000041tcp852ypserv
Againfromtheserversystem,makesuretheNISserverisup
andrunning:
$/usr/sbin/rpcinfo-ulocalhostypserv
program100004version1readyandwaiting
program100004version2readyandwaiting
Iftheserverisnotworkingproperly,useservicetostopypserv.
Startitagainwithdebuggingturnedon:
#/sbin/serviceypservstop
StoppingYPserverservices:
#/usr/sbin/ypserv--debug
...
Thedebugoptionkeepsypservintheforegroundandcauses
ittosenderrormessagesanddebuggingoutputtostandard
error.
yppasswdd:TheNISPasswordUpdateDaemon
TheNISpasswordupdatedaemon,yppasswdd,runsonlyon
themasterserver;itisnotnecessarytorunitonslaveservers.
(Ifthemasterserverisdownandyoutrytochangeyour
passwordfromaclient,yougetanerrormessage.)Whena
userrunsyppasswd(page662)onaclient,yppasswdexchanges
informationwiththeyppasswdddaemontoupdatetheuser's
password(andoptionallyother)informationintheNISshadow
(andoptionallypasswd)mapandinthe/etc/shadow(and
optionally/etc/passwd)fileontheNISmasterserver.
Passwordchangerequestsaresenttosyslogd(page562).
Startyppasswdd
Usechkconfigtocauseyppasswddtostarteachtimethe
systementersmultiusermodeandservicetostartyppasswdd
immediately.Formoreinformationreferto"Prerequisites"on
page663.
AllowGECOSandLoginShellModification
Bydefault,yppasswdddoesnotallowuserstochangeGECOS
(page1033)informationortheloginshellwhentheyrun
yppasswd.Youcanallowuserstochangethisinformationwith
optionsonthecommandlinewhenyoustartyppasswddor,
moreconveniently,bymodifyingthe
/etc/sysconfig/yppasswddconfigurationfile.Theechfn
optiontoyppasswddallowsuserstochangetheirGECOS
information;echshallowsuserstochangetheirloginshell.
Whenyousettheoptionsinthe/etc/sysconfig/yppasswdd
file,theyaresetautomaticallyeachtimetheyppasswddinit
fileisrun.
$cat/etc/sysconfig/yppasswdd
...
YPPASSWDD_ARGS="-echfn-echsh"
ChapterSummary
NIS(NetworkInformationService)simplifiesthemanagement
ofcommonadministrativefilesbymaintainingtheminacentral
databaseandhavingclientscontactthedatabaseserverto
retrieveinformationfromthedatabase.ThenetworkthatNIS
servesiscalledanNISdomain.EachNISdomainhasone
masterserver;largernetworksmayhaveslaveservers.
NISderivestheinformationitoffersfromlocalconfiguration
files,suchas/etc/passwdand/etc/hosts.Thesefilesare
calledsourcefilesormasterfiles.BeforeNIScanstorethe
informationcontainedinasourcefile,itmustbeconvertedto
dbm-formatfiles,calledmaps.Theypcatandypmatchutilities
displayinformationfromNISmaps.
Theyppasswdutilityreplacesthefunctionalityofpasswdonclients
whenyouareusingNIStoauthenticatepasswords.The
/etc/ypserv.conffile,whichholdsNISserverconfiguration
information,specifiesoptionsandaccessrulesfortheNIS
server.Toenhancesystemsecurity,youcancreatea
/var/yp>/securenetsfile,whichpreventsunauthorized
systemsfromsendingRPCrequeststotheNISserverand
retrievingNISmaps.
Exercises
1. Whatisthedifferencebetweenthepasswdandyppasswdutilities?
2. HowwouldyoupreventNISfromexportingtherootuserandothersystemusers
toclients?
3. HowwouldyoumakeNISuserinformationoverridelocaluserinformationonclient
systems?
4. Whydoesthe/etc/passwdfileneedtwoNISmaps?
AdvancedExercises
5. HowcanyouuseNIStomirrorthefunctionalityofaprivateDNSserverforasmall
network?WhyshouldNISnotbeusedthiswayonalargenetwork?
6. HowcanyoufindoutiftheworkingdirectoryisthehomedirectoryofanNISuser?
7. WhatadvantagedoesNISprovidewhenyouuseitwithNFS?
8. SuggestawaytoimplementNISmapssotheycanbeindexedonmorethanone
field.
22.NFS:SharingFilesystems
INTHISCHAPTER
SettingUpanNFSClient 676
JumpStart:MountingaRemoteDirectoryHierarchy 676
ImprovingPerformance 680
SettingUpanNFSServer 682
JumpStart:ConfiguringanNFSServerUsingsystem-config-nfs 683
ExportingaDirectoryHierarchy 684
automount:AutomaticallyMountsDirectoryHierarchies 690
TheNFS(NetworkFilesystem)protocol,aUNIXdefacto
standardoriginallydevelopedbySunMicrosystems,allowsa
servertoshareselectedlocaldirectoryhierarchieswithclient
systemsonaheterogeneousnetwork.NFSrunsonUNIX,DOS,
Windows,VMS,Linux,andmore.Filesontheremotecomputer
(thefileserver)appearasiftheyarepresentonthelocal
system(theclient).Thephysicallocationofafileisirrelevantto
anNFSuser.
NFSreducesstorageneedsandsystemadministration
workload.Asanexample,eachsysteminacompany
traditionallyholdsitsowncopyofanapplicationprogram.To
upgradetheprogram,theadministratorneedstoupgradeiton
eachsystem.NFSallowsyoutostoreacopyofaprogramona
singlesystemandgiveotherusersaccesstoitoverthe
network.Thisscenariominimizesstoragerequirementsby
reducingthenumberoflocationsthatneedtomaintainthe
samedata.Inadditiontoboostingefficiency,NFSgivesusers
onthenetworkaccesstothesamedata(notjustapplication
programs),therebyimprovingdataconsistencyandreliability.
Byconsolidatingdata,NFSreducesadministrativeoverheadand
providesaconveniencetousers.
Introduction
Figure22-1showstheflowofdatafromaclienttoaserverina
typicalNFSclient/serversetup.AnNFSdirectoryhierarchy
appearstousersandapplicationprogramsasjustanother
directoryhierarchy.Bylookingatit,youcannottellthatagiven
directoryholdsaremotelymountedNFSdirectoryhierarchyand
notalocalext3filesystem.TheNFSservertranslates
commandsfromtheclientintooperationsontheserver's
filesystem.
Figure22-1.FlowofdatainatypicalNFS
client/serversetup
[Viewfullsizeimage]
Disklesssystems
Inmanycomputerfacilities,userfilesarestoredonacentral
fileserverequippedwithmanylarge-capacitydiskdrivesand
devicesthatquicklyandeasilymakebackupcopiesofthedata.
Adisklesssystembootsfromafileserver(netboots,discussed
next),aCD,orafloppydisketteandloadssystemsoftware
fromafileserver.TheLinuxTerminalServerProject(LTSP.org)
Websitesaysitall:"Linuxmakesagreatplatformfordeploying
disklessworkstationsthatbootfromanetworkserver.TheLTSP
isallaboutrunningthinclientcomputersinaLinux
environment."Becauseadisklessworkstationdoesnotrequire
alotofcomputingpower,youcangiveolder,retiredcomputers
asecondlifebyusingthemasdisklesssystems.
Netboot/PXE
Youcannetboot(page1044)systemsthatareappropriatelyset
up.RedHatLinuxincludesthePXE(PrebootExecution
Environment)serverpackagefornetbootingIntelsystems.
Oldersystemssometimesusetftp(TrivialFileTransferProtocol)
fornetbooting.Non-Intelarchitectureshavehistoricallyincluded
netbootcapabilities,whichRedHatLinuxalsosupports.Youcan
buildtheLinuxkernelsothatitmountsroot(/)usingNFS.
Giventhemanywaystosetupasystem,theoneyouchoose
dependsonwhatyouwanttodo.SeetheRemote-Bootmini-
HOWTOformoreinformation.
Datalesssystems
AnothertypeofLinuxsystemisadatalesssystem,inwhichthe
clienthasadiskbutstoresnouserdata(onlyLinuxandthe
applicationsarekeptonthedisk).Settingupthistypeof
systemisamatterofchoosingwhichdirectoryhierarchiesare
mountedremotely.
df:showswheredirectoryhierarchiesaremounted
Thedfutilitydisplaysalistofthedirectoryhierarchiesavailable
onthesystem,alongwiththeamountofdiskspace,freeand
used,oneach.Theh(human)optionmakestheoutputmore
intelligible.Directoryhierarchynamesthatareprependedwith
hostname:areavailablethroughNFS.
[bravo]$cd;pwd
/speedy.home/jenny
[bravo]$df-h
FilesystemSizeUsedAvailUse%Mountedon
/dev/hda1981M287M645M31%/
/dev/hda620G2.7G16G15%/usr
/dev/hda79.7G384M8.8G5%/home
grape:/gc1985M92M844M10%/grape.gc1
grape:/gc53.9G3.0G738M81%/grape.gc5
speedy:/home3.9G2.4G1.4G64%/speedy.home
Intheprecedingexample,Jenny'shomedirectory,
/home/jenny,isontheremotesystemspeedy.UsingNFS,
the/homefilesystemonspeedyismountedonbravo;to
makeiteasytorecognize,itismountedas/speedy.home.
The/gc1and/gc5filesystemsongrapearemountedon
bravoas/grape.gc1and/grape.gc5,respectively.
YoucanusetheToptiontodftoaddaTypecolumntothe
display.ThefollowingcommandusestnfstodisplayNFS
filesystemsonly:
[grape]$df-htnfs
FilesystemSizeUsedAvailUse%Mountedon
grape:/gc1985M92M844M10%/grape.gc1
grape:/gc53.9G3.0G738M81%/grape.gc5
speedy:/home3.9G2.4G1.4G64%/speedy.home
Errors
Sometimesyoumayloseaccesstoremotefiles.Forexample,a
networkproblemoraremotesystemcrashmaymakethese
filestemporarilyunavailable.Whenyoutrytoaccessaremote
fileinthesecircumstances,yougetanerrormessage,suchas
NFSserverspeedynotresponding.Whenthelocalsystem
cancontacttheremoteserveragain,youseeanothermessage,
suchasNFSserverspeedyOK.Settingupastablenetwork
andserver(ornotusingNFS)isthebestdefenseagainstthese
kindsofproblems.
Security
NFSisbasedonthetrusted-hostparadigm(page362)and
thereforehasallthesecurityshortcomingsthatplagueother
servicesbasedonthisparadigm.Inaddition,NFSisnot
encrypted.Becauseoftheseissues,youshouldimplementNFS
onasingleLANsegmentonly,whereyoucanbe(reasonably)
surethatsystemsonaLANsegmentarewhattheyclaimtobe.
MakesureafirewallblocksNFStrafficfromoutsidetheLANand
neveruseNFSovertheInternet.
Toimprovesecurity,makesureUIDsandGIDsarethesameon
theserverandclients(page687).
SettingUpanNFSClient
ThissectioncoverssettingupanNFSclient,mountingremote
directoryhierarchies,andimprovingNFSperformance.
Prerequisites
Installthefollowingpackages:
nfs-utils
system-config-nfs(optional)
Theportmaputility(partoftheportmappackage;referto"RPC
NetworkServices"onpage377)mustberunningtoenable
reliablefilelocking.
TherearenodaemonstostartforNFSclients.
JumpStart:MountingaRemoteDirectory
Hierarchy
TosetupanNFSclient,mounttheremotedirectoryhierarchy
thesamewayyoumountalocaldirectoryhierarchy(page
466).Thefollowingsectionsdetailthisprocess.
mount:MountsaRemoteDirectoryHierarchy
Thefollowingexamplesshowtwowaystomountaremote
directoryhierarchy,assumingthatspeedyisonthesame
networkasthelocalsystemandissharing/homeand
/exportwiththelocalsystem.The/exportdirectoryon
speedyholdstwodirectoryhierarchiesthatyouwantto
mount:/export/progsand/export/oracle.
Theexamplemountsspeedy's/homedirectoryon
/speedy.homeonthelocalsystem,/export/progson
/apps,and/export/oracleon/oracle.
Firstusemkdirtocreatethedirectoriesthatarethemount
pointsfortheremotedirectoryhierarchies:
#mkdir/speedy.home/apps/oracle
Youcanmountanydirectoryfromanexporteddirectory
hierarchy.Inthisexample,speedyexports/exportandthe
localsystemmounts/export/progsand/export/oracle.
Thefollowingcommandsmanuallymountthedirectory
hierarchiesonetime:
#mountspeedy:/home/speedy.home
#mount-oro,nosuidspeedy:/export/progs/apps
#mount-orospeedy:/export/oracle/oracle
Ifyoureceivetheerrormount:RPC:Programnot
registered,itmaymeanNFSisnotrunningontheserver.
Bydefault,directoryhierarchiesaremountedread-write,
assumingtheNFSserverisexportingthemwithread-write
permissions.Thefirstoftheprecedingcommandsmountsthe
/homedirectoryhierarchyfromspeedyonthelocaldirectory
/speedy.home.Thesecondandthirdcommandsusetheoro
optiontoforceareadonlymount.Thesecondcommandadds
thenosuidoption,whichforcessetuid(page183)executables
inthemounteddirectoryhierarchytorunwithregular
permissionsonthelocalsystem.
nosuidoption
Ifauserhastheabilitytorunasetuidprogram,thatuserhas
thepowerofSuperuser.Thisabilityshouldbelimited.Unless
youknowthatauserwillneedtorunaprogramwithsetuid
permissionsfromamounteddirectoryhierarchy,alwaysmount
adirectoryhierarchywiththenosuidoption.Forexample,you
wouldneedtomountadirectoryhierarchywithsetuidprivileges
whenadisklessworkstationhasitsrootpartitionmounted
usingNFS.
nodevoption
Mountingadevicefilecreatesanotherpotentialsecurityhole.
Althoughthebestpolicyisnottomountuntrustworthy
directoryhierarchies,itisnotalwayspossibletoimplementthis
policy.Unlessauserneedstouseadeviceonamounted
directoryhierarchy,mountdirectoryhierarchieswiththenodev
option,whichpreventscharacterandblockspecialfiles(page
463)onthemounteddirectoryhierarchyfrombeingusedas
devices.
fstabfile
Ifyoumountdirectoryhierarchiesfrequently,youcanadd
entriesforthedirectoryhierarchiestothe/etc/fstabfile(page
681).(Alternatively,youcanuseautomount;seepage690.)
Thefollowing/etc/fstabentriesautomaticallymountthesame
directoryhierarchiesasinthepreviousexampleatthesame
timeasthesystemmountsthelocalfilesystems:
$cat/etc/fstab
...
speedy:/home/speedy.homenfs-00
speedy:/export/progs/appsnfsr,nosuid00
speedy:/export/oracle/oraclenfsr00
AfilethatismountedusingNFSisalwaystypenfsonthelocal
system,regardlessofwhattypeitisontheremotesystem.
TypicallyyoudonotrunfsckonorbackupanNFSdirectory
hierarchy.Theentriesinthethird,fifth,andsixthcolumnsof
fstabareusuallynfs(filesystemtype),0(donotbackupthis
directoryhierarchywithdump[page545]),and0(donotrun
fsck[page470]onthisdirectoryhierarchy).Theoptionsfor
mountinganNFSdirectoryhierarchydifferfromthosefor
mountinganext3orothertypeoffilesystem.Seethenext
sectionfordetails.
umount:UnmountsaRemoteDirectoryHierarchy
Useumounttounmountaremotedirectoryhierarchythesame
wayyouwouldunmountalocalfilesystem(page469).
mount:MountsaDirectoryHierarchy
Themountutility(page466)associatesadirectoryhierarchy
withamountpoint(adirectory).Youcanusemounttomountan
NFS(remote)directoryhierarchy.Thissectiondescribessome
mountoptions.Itlistsdefaultoptionsfirst,followedbynon-
defaultoptions(enclosedinparentheses).Youcanusethese
optionsonthecommandlineorin/etc/fstab(page681).For
acompletelistofoptions,refertothemountandnfsmanpages.
AttributeCaching
Fileattributes,whicharestoredinafile'sinode(page460),
provideinformationaboutafile,suchasfilemodificationtime,
size,links,andowner.Fileattributesdonotincludethedata
storedinafile.Typicallyfileattributesdonotchangeveryoften
foranordinaryfile;theychangeevenlessoftenforadirectory
file.Eventhesizeattributedoesnotchangewitheverywrite
instruction:WhenaclientiswritingtoanNFS-mountedfile,
severalwriteinstructionsmaybegivenbeforethedatais
actuallytransferredtotheserver.Inaddition,manyfile
accesses,suchasthatperformedbyls,arereadonlyoperations
anddonotchangethefile'sattributesoritscontents.Thusa
clientcancacheattributesandavoidcostlynetworkreads.
Thekernelusesthemodificationtimeofthefiletodetermine
whenitscacheisout-of-date.Ifthetimetheattributecache
wassavedislaterthanthemodificationtimeofthefileitself,
thedatainthecacheiscurrent.TheattributecacheofanNFS-
mountedfilemustbeperiodicallyrefreshedfromtheserverto
determinewhetheranotherprocesshasmodifiedthefile.This
periodisspecifiedasaminimumandmaximumnumberof
secondsforordinaryanddirectoryfiles.Followingisalistof
optionsthataffectattributecaching:
ac(noac)
(attributecache)Permitsattributecaching(default).The
noacoptiondisablesattributecaching.Althoughnoacslows
theserver,itavoidsstaleattributeswhentwoNFSclients
activelywritetoacommondirectoryhierarchy.
acdirmax=n
(attributecachedirectoryfilemaximum)Thenisthe
numberofseconds,atamaximum,thatNFSwaitsbefore
refreshingdirectoryfileattributes(defaultis60seconds).
acdirmin=n
(attributecachedirectoryfileminimum)Thenisthe
numberofseconds,ataminimum,thatNFSwaitsbefore
refreshingdirectoryfileattributes(defaultis30seconds).
acregmax=n
(attributecacheregularfilemaximum)Thenisthenumber
ofseconds,atamaximum,thatNFSwaitsbeforerefreshing
regularfileattributes(defaultis60seconds).
acregmin=n
(attributecacheregularfileminimum)Thenisthenumber
ofseconds,ataminimum,thatNFSwaitsbeforerefreshing
regularfileattributes(defaultis3seconds).
actimeo=n
(attributecachetimeout)Setsacregmin,acregmax,
acdirmin,andacdirmaxtonseconds(withoutthisoption,
eachindividualoptiontakesonitsassignedordefaultvalue).
ErrorHandling
ThefollowingoptionscontrolwhatNFSdoeswhentheserver
doesnotrespondorwhenanI/Oerroroccurs.Toallowfora
mountpointlocatedonamounteddevice,amissingmount
pointistreatedasatimeout.
fg(bg)
(foreground)RetriesfailedNFSmountattemptsinthe
foreground(default).Thebg(background)optionretriesfailed
NFSmountattemptsinthebackground.
hard(soft)
Displaysservernotrespondingontheconsoleonamajor
timeoutandkeepsretrying(default).Thesoftoptionreportsan
I/Oerrortothecallingprogramonamajortimeout.Ingeneral,
itisnotadvisabletousesoft.Asthemountmanpagesaysof
soft,"Usuallyitjustcauseslotsoftrouble."Formore
informationreferto"ImprovingPerformance"onpage680.
nointr(intr)
(nointerrupt)Doesnotallowasignaltointerruptafile
operationonahard-mounteddirectoryhierarchywhenamajor
timeoutoccurs(default).Theintroptionallowsthistypeof
interrupt.
retrans=n
(retransmissionvalue)Afternminortimeouts,NFS
generatesamajortimeout(defaultis3).Amajortimeout
abortstheoperationordisplaysservernotrespondingonthe
console,dependingonwhetherhardorsoftisset.
retry=n
(retryvalue)ThenumberofminutesthatNFSretriesamount
operationbeforegivingup(defaultis10,000).
timeo=n
(timeoutvalue)Thenisthenumberoftenthsofasecond
thatNFSwaitsbeforeretransmittingfollowinganRPC,orminor,
timeout(defaultis7).Thevalueisincreasedateachtimeoutto
amaximumof60secondsoruntilamajortimeoutoccurs(see
retrans).Onabusynetwork,incaseofaslowserver,orwhen
therequestpassesthroughmultiplerouters/gateways,
increasingthisvaluemayimproveperformance.
MiscellaneousOptions
Followingareadditionalusefuloptions:
lock(nolock)
PermitsNFSlocking(default).ThenolockoptiondisablesNFS
locking(doesnotstartthelockddaemon)andisusefulwith
olderserversthatdonotsupportNFSlocking.
mounthost=name
Thenameofthehostrunningmountd,theNFSmount
daemon.
mountport=n
Theportusedbymountd.
nodev
(nodevice)Causesmounteddevicefilesnottofunctionas
devices(page677).
port=n
TheportusedtoconnecttotheNFSserver(defaultsto2049if
theNFSdaemonisnotregisteredwithportmap).Whenn=0
(default),NFSqueriesportmapontheservertodeterminethe
port.
rsize=n
(readblocksize)Thenumberofbytesreadatonetimefrom
anNFSserver.Thedefaultblocksizeis4096.Referto
"ImprovingPerformance."
wsize=n
(writeblocksize)Thenumberofbyteswrittenatonetimeto
anNFSserver.Thedefaultblocksizeis4096.Referto
"ImprovingPerformance".
tcp
UseTCPinplaceofthedefaultUDPprotocolforanNFSmount.
Thisoptionmayimproveperformanceonacongestednetwork;
however,someNFSserverssupportUDPonly.
udp
UsethedefaultUDPprotocolforanNFSmount.
ImprovingPerformance
hard/soft
SeveralparameterscanaffecttheperformanceofNFS,
especiallyoverslowconnectionssuchasalinewithalotof
trafficoronecontrolledbyamodem.Ifyouhaveaslow
connection,makesurehard(page679)isset(thisisthe
default)sothattimeoutsdonotabortprogramexecution.
Blocksize
OneoftheeasiestwaystoimproveNFSperformanceisto
increasetheblocksizethatis,thenumberofbytesNFS
transfersatatime.Thedefaultof4096islowforafast
connectionusingmodernhardware.Tryincreasingrsize[page
756]andwsizeto8192orhigher.Experimentuntilyoufind
theoptimalblocksize.Unmountandmountthedirectory
hierarchyeachtimeyouchangeanoption.SeetheNFSHOWTO
formoreinformationontestingdifferentblocksizes.
Timeouts
NFSwaitstheamountoftimespecifiedbythetimeo(timeout,
page679)optionforaresponsetoatransmission.Ifitdoesnot
receivearesponseinthisamountoftime,itsendsanother
transmission.Thesecondtransmissionusesbandwidththat,
overaslowconnection,mayslowthingsdownfurther.Youmay
beabletoincreaseperformancebyincreasingtimeo.
Thedefaultvalueoftimeoisseven-tenthsofasecond(700
milliseconds).Afteratimeout,NFSdoublesthetimeitwaitsto
1400milliseconds.Oneachtimeoutitdoublestheamountof
timeitwaitstoamaximumof60seconds.Youcantestthe
speedofaconnectionwiththesizepacketsyouaresending
(rsizeandwsize)byusingpingwiththes(size)option:
$ping-s4096speedy
PINGspeedy.tcorp.com(192.168.0.1)4096(4124)bytesofdata.
4104bytesfromspeedy.tcorp.com(192.168.0.1):icmp_seq=0ttl=64time=1.43ms
4104bytesfromspeedy.tcorp.com(192.168.0.1):icmp_seq=1ttl=64time=1.17ms
4104bytesfromspeedy.tcorp.com(192.168.0.1):icmp_seq=2ttl=64time=1.17ms
...
4104bytesfromspeedy.tcorp.com(192.168.0.1):icmp_seq=26ttl=64time=1.16ms
4104bytesfromspeedy.tcorp.com(192.168.0.1):icmp_seq=27ttl=64time=1.16ms
4104bytesfromspeedy.tcorp.com(192.168.0.1):icmp_seq=28ttl=64time=1.16ms
4104bytesfromspeedy.tcorp.com(192.168.0.1):icmp_seq=29ttl=64time=1.26ms
---speedy.tcorp.compingstatistics---
30packetstransmitted,30received,0%packetloss,time29281ms
rttmin/avg/max/mdev=1.154/1.192/1.431/0.067ms
TheprecedingexampleusesRedHatLinux'sdefaultpacketsize
of4096bytesandshowsafastaveragepacketround-triptime
ofslightlymorethan1millisecond.Overamodemline,youcan
expecttimesofseveralseconds.Iftheconnectionisdealing
withothertraffic,thetimewillbelonger.Runthetestduringa
periodofheavytraffic.Tryincreasingtimeotothreeorfour
timestheaverageround-triptime(toallowforunusuallybad
networkconditions,aswhentheconnectionismade)andsee
whetherperformanceimproves.Rememberthatthetimeo
valueisgivenintenthsofasecond(100milliseconds=one-
tenthofasecond).
/etc/fstab:MountsDirectoryHierarchies
Automatically
The/etc/fstabfile(page469)listsdirectoryhierarchiesthat
thesystemmountsautomaticallyasitcomesup.Youcanuse
theoptionsdiscussedintheprecedingsectiononthecommand
lineorinthefstabfile.
Thefirstexamplelinefromfstabmountsgrape's/gc1
filesystemonthe/grape.gc1mountpoint:
grape:/gc1/grape.gc1nfsrsize=8192,wsize=819200
Amountpointshouldbeanempty,localdirectory.(Filesina
mountpointarehiddenwhenadirectoryhierarchyismounted
onit.)ThetypeofafilesystemmountedusingNFSisalways
nfs,regardlessofitstypeonthelocalsystem.Youcanincrease
thersizeandwsizeoptionstoimproveperformance.Referto
"ImprovingPerformance"onpage680.
Thenextexamplefromfstabmountsafilesystemfrom
speedy:
speedy:/export/speedy.exportnfstimeo=50,hard00
Becausethelocalsystemconnectstospeedyoveraslow
connection,timeoisincreasedto5seconds(50tenthsofa
second).Referto"Timeouts"onpage680.Inaddition,hardis
settomakesurethatNFSkeepstryingtocommunicatewith
theserverafteramajortimeout.Referto"hard/soft"onpage
680.
Thefinalexamplefromfstabshowsaremote-mountedhome
directory.Becausespeedyisalocalserverandisconnectedvia
areliable,high-speedconnection,timeoisdecreasedandrsize
andwsizeareincreasedsubstantially:
speedy:/export/home/homenfstimeo=4,rsize=16384,wsize=1638400
SettingUpanNFSServer
Prerequisites
Installthefollowingpackage:
nfs-utils
Runchkconfigtocausenfstostartwhenthesystementers
multiusermode:
#/sbin/chkconfignfson
Startnfs:
#/etc/rc.d/init.d/nfsstart
Thenfsinitscriptstartsmountd,nfsd,andrquotad.
Theportmaputility(partoftheportmappackage;referto"RPC
NetworkServices"onpage377)mustberunningtoenable
reliablefilelocking.
Notes
SELinux
WhenSELinuxissettouseatargetedpolicy,NFSisprotected
bySELinux.Youcandisablethisprotectionifnecessary.For
moreinformationreferto"SettingtheTargetedPolicywith
system-config-securitylevel"onpage402.
Firewall
Ifthesystemisrunningafirewall,yougenerallyneedtoopen
TCPport111forportmap,TCPports1013and1016for
mountd,andTCPport2049fornfs.Iftheseportsdonotallow
NFSaccess,userpcinfop(page423)todeterminetheTCP
portsthatthelocalserverusesfortheseservicesandthen
openthoseports.ForinformationonusingtheRedHatLinux
graphicalfirewalltool,see"Openingotherports"onpage768.
Formoregeneralinformation,seeChapter25,whichdetails
iptables.
JumpStart:ConfiguringanNFSServerUsing
system-config-nfs
TodisplaytheNFSServerConfigurationwindow(Figure22-2),
enterthecommandsystem-config-nfs.FromKDEselectMain
menu:Administration ServerSettings NFSorfrom
GNOMEselectSystem:Administration ServerSettings
NFS.Fromthiswindowyoucangeneratean/etc/exportsfile,
whichisalmostallthereistosettingupanNFSserver.Ifthe
systemisrunningafirewall,see"Notes"inthepreceding
section.Thesystem-config-nfsutilityallowsyoutospecifywhich
directoryhierarchiesaresharedandhowtheyaresharedusing
NFS.Eachexportedhierarchyiscalledashare.
Figure22-2.NFSServerConfigurationwindow
Toaddashare,clickAddonthetoolbar.Tomodifyashare,
highlighttheshareandclickPropertiesonthetoolbar.Clicking
AdddisplaystheAddNFSSharewindow,whileclicking
PropertiesdisplaystheEditNFSSharewindow.These
windowsareidenticalexceptfortheirtitles.
TheAdd/EditNFSSharewindowhasthreetabs:Basic,General
Options,andUserAccess.OntheBasictab(Figure22-3)you
canspecifythepathnameoftherootoftheshareddirectory
hierarchy,thenamesorIPaddressesofthesystems(hosts)
thatthehierarchywillbesharedwith,andwhetherusersfrom
thespecifiedsystemswillbeabletowritetothesharedfiles.
Figure22-3.EditNFSSharewindow
Theselectionsintheothertwotabscorrespondtooptionsthat
youcanspecifyinthe/etc/exportsfile.Followingisalistof
thecheckboxdescriptionsinthesetabsandtheoptioneach
correspondsto:
GeneralOptionstab
Allowconnectionsfromports1023andhigher:insecure(page
686)
Allowinsecurefilelocking:no_auth_nlmorinsecure_locks
(page686)
Disablesubtreechecking:no_subtree_check(page686)
Syncwriteoperationsonrequest:sync(page686)
Forcesyncofwriteoperationsimmediately:no_wdelay(page
686)
Hidefilesystemsbeneath:nohide(page686)
Exportonlyifmounted:mountpoint(page686)
UserAccesstab
Treatremoterootuseraslocalroot:no_root_squash(page
687)
Treatallclientusersasanonymoususers:all_squash(page
688)
LocaluserIDforanonymoususers:anonuid(page688)
LocalgroupIDforanonymoususers:anongid(page688)
Aftermakingthechangesyouwant,clickOKtoclosethe
Add/EditNFSSharewindowandclickOKagaintoclosetheNFS
ServerConfigurationwindow.Thereisnoneedtorestartany
daemons.
ExportingaDirectoryHierarchy
Exportingadirectoryhierarchymakesthedirectoryhierarchy
availableformountingbydesignatedsystemsviaanetwork.
"Exported"doesnotmean"mounted":Whenadirectory
hierarchyisexported,itisplacedinthelistofdirectory
hierarchiesthatcanbemountedbyothersystems.Anexported
directoryhierarchymaybemounted(ornot)atanygiventime.
Aserverholdsthreelistsofexporteddirectoryhierarchies:
/etc/exportsAccesscontrollistforexporteddirectory
hierarchies(discussedinthenextsection).Thesystem
administratorcanmodifythisfilebyeditingitorbyrunning
system-config-nfs.
/var/lib/nfs/xtabAccesscontrollistforexported
directoryhierarchies.Initializedfrom/etc/exportswhen
thesystemisbroughtup.Readbymountdwhenaclient
askstomountadirectoryhierarchy.Modifiedbyexportfs
(page688)asdirectoryhierarchiesaremountedand
unmountedbyNFS.
Kernel'sexporttableListofactiveexporteddirectory
hierarchies.Thekernelobtainsthisinformationfrom
/var/lib/nfs/xtab.Youcandisplaythistablebygiving
thecommandcat/proc/fs/nfs/exports.
Tip:Exportingsymboliclinksanddevice
files
Whenyouexportadirectoryhierarchythatcontains
asymboliclink,makesuretheobjectofthelinkis
availableontheclient(remote)system.Iftheobject
ofthelinkdoesnotexistonaclientsystem,you
mustexportandmountitalongwiththeexported
link.Otherwise,thelinkwillnotpointtothefileit
pointstoontheserver.
AdevicefilereferstoaLinuxkernelinterface.When
youexportadevicefile,youexportthatinterface.If
theclientsystemdoesnothavethesametypeof
device,theexporteddevicewillnotwork.Froma
client,youcanusemount'snodevoption(page677)
topreventdevicefilesonmounteddirectory
hierarchiesfrombeingusedasdevices.
Amountedfilesystemwithamountpointwithinanexported
filesystemwillnotbeexportedwiththeexportedfilesystem.
Youneedtoexplicitlyexporteachfilesystemthatyouwant
exported,evenifitresideswithinanalreadyexported
filesystem.Forexample,whenyouhavetwofilesystems,
/opt/appsand/opt/apps/oracle,residingontwopartitions
toexport,youmustexporteachexplicitly,eventhoughoracle
isasubdirectoryofapps.Mostothersubdirectoriesandfiles
areexportedautomatically.
/etc/exports:HoldsaListofExportedDirectoryHierarchies
The/etc/exportsfileistheaccesscontrollistforexported
directoryhierarchiesthatNFSclientscanmount;itistheonly
fileyouneedtoedittosetupanNFSserver.Theexportsfile
controlsthefollowingaspects:
Whichclientscanaccessfilesontheserver
Whichdirectoryhierarchiesontheservereachclientcan
access
Howeachclientcanaccesseachdirectoryhierarchy
Howclientusernamesaremappedtoserverusernames
VariousNFSparameters
Eachlineintheexportsfilehasthefollowingformat:
export-pointclient1(options)[client2(options)...]
whereexport-pointistheabsolutepathnameoftheroot
directoryofthedirectoryhierarchytobeexported,client1-nis
thenameofoneormoreclientsorisoneormoreIPaddresses,
separatedbySPACEs,thatareallowedtomounttheexport-
point.Theoptions,whicharedescribedinthenextsection,
applytotheprecedingclient.
Eitheryoucanusesystem-config-nfs(page683)tomakechanges
toexportsoryoucaneditthisfiledirectly.Thefollowingsimple
exportsfilegivesgrapereadandwriteaccessandgives
speedyreadonlyaccesstothefilesin/home:
#cat/etc/exports
/homegrape(rw,sync)
/homespeedy(ro,sync)
Ineachcase,accessisimplicitlygrantedforallsubdirectories.
Forhistoricalreasons,exportfscomplainswhenyoudonot
specifyeithersyncorasync.YoucanuseIPaddressesand
includemorethanonesystemonaline:
#cat/etc/exports
/homegrape(rw,sync)speedy(ro,sync)192.168.0.22(rw,sync)
GeneralOptions
Thissectionlistsdefaultoptionsfirst,followedbynon-default
options(enclosedinparentheses).Refertotheexportsman
pageformoreinformation.
auth_nlm(no_auth_nlm)orsecure_locks
(insecure_locks)
Causestheservertorequireauthenticationoflockrequests
(usingtheNLM[NFSLockManager]protocol).Use
no_auth_nlmforolderclientswhenyoufindthatonlyfiles
thatanyonecanreadcanbelocked.
mountpoint[=path]
Allowsadirectorytobeexportedonlyifithasbeenmounted.
Thisoptionpreventsamountpointthatdoesnothavea
directoryhierarchymountedonitfrombeingexportedand
preventstheunderlyingmountpointfrombeingexported.Also
mp.
nohide(hide)
Whenaserverexportstwodirectoryhierarchies,oneofwhichis
mountedontheother,aclienthastomountbothdirectory
hierarchiesexplicitlytoaccessboth.Whenthesecond(child)
directoryhierarchyisnotexplicitlymounted,itsmountpoint
appearsasanemptydirectoryandthedirectoryhierarchyis
hidden.Thenohideoptioncausestheunderlyingsecond
directoryhierarchytoappearwhenitisnotexplicitlymounted,
butthisoptiondoesnotworkinallcases.
ro(rw)
(readonly)PermitsonlyreadrequestsonanNFSdirectory
hierarchy.Userwtopermitreadandwriterequests.
secure(insecure)
RequiresthatNFSrequestsoriginateonaprivilegedport(page
1049)sothataprogramwithoutrootpermissionscannot
mountadirectoryhierarchy.Thisoptiondoesnotguaranteea
secureconnection.
subtree_check(no_subtree_check)
Checkssubtreesforvalidfiles.Assumethatyouhavean
exporteddirectoryhierarchythathasitsrootbelowtherootof
thefilesystemthatholdsit(thatis,anexportedsubdirectoryof
afilesystem).WhentheNFSserverreceivesarequestforafile
inthatdirectoryhierarchy,itperformsasubtreecheckto
confirmthefileisintheexporteddirectoryhierarchy.
Subtreecheckingcancauseproblemswithfilesthatare
renamedwhileopenedand,whenno_root_squashisused,
filesthatonlyrootcanaccess.Theno_subtree_checkoption
disablessubtreecheckingandcanimprovereliabilityinsome
cases.
Forexample,youmayneedtodisablesubtreecheckingfor
homedirectories.Homedirectoriesarefrequentlysubtrees(of
/home),arewrittentooften,andcanhavefileswithinthem
frequentlyrenamed.Youwouldprobablynotneedtodisable
subtreecheckingfordirectoryhierarchiesthatcontainfilesthat
aremostlyread,suchas/usr.
sync(async)
(synchronize)Specifiesthattheserveristoreplytorequests
onlyafterdiskchangesmadebytherequestarewrittentodisk.
Theasyncoptionspecifiesthattheserverdoesnothaveto
waitforinformationtobewrittentodiskandcanimprove
performance,albeitatthecostofpossibledatacorruptionifthe
servercrashesortheconnectionisinterrupted.
Becausethedefaultchangedwithrelease1.0.0ofnfs-utils,
exportfsdisplaysawarningwhenyoudonotspecifyeithersync
orasync.
wdelay(no_wdelay)
(writedelay)Causestheservertodelaycommittingwrite
requestswhenitanticipatesthatanother,relatedrequest
follows,therebyimprovingperformancebycommittingmultiple
writerequestswithinasingleoperation.Theno_wdelayoption
doesnotdelaycommittingwriterequestsandcanimprove
performancewhentheserverreceivesmultiple,small,
unrelatedrequests.
UserIDMappingOptions
EachuserhasaUIDnumberandaprimaryGIDnumberonthe
localsystem.Thelocal/etc/passwdand/etc/groupfiles
mapthesenumberstonames.Whenausermakesarequestof
anNFSserver,theserverusesthesenumberstoidentifythe
userontheremotesystem,raisingseveralissues:
TheusermaynothavethesameIDnumbersonboth
systemsandmaythereforehaveowneraccesstofilesof
anotheruser(see"NISandNFS"forasolution).
Youmaynotwanttherootuserontheclientsystemto
haveowneraccesstoroot-ownedfilesontheserver.
Youmaynotwantaremoteusertohaveowneraccessto
someimportantsystemfilesthatarenotownedbyroot
(suchasthoseownedbybin).
Security:CriticalfilesinNFS-mounted
directoriesshouldbeownedbyroot
Despitethemappingdonebytheroot-squashoption,
therootuseronaclientsystemcanusesutoassume
theidentityofanyuseronthesystemandthen
accessthatuser'sfilesontheserver.Thus,without
resortingtoall-squash,youcanprotectonlyfiles
ownedbyrootonanNFSserver.Makesurethat
rootandnotbinoranotheruserownsandistheonly
userwhocanmodifyordeleteallcriticalfileswithin
anyNFS-mounteddirectoryhierarchy.
Takingthisprecautiondoesnotcompletelyprotect
againstanattackerwithrootprivileges,butitcan
helpprotectasystemfromlessexperienced
malicioususers.
Owneraccessmeansthattheremoteusercanexecute,
remove,orworsemodifythefile.NFSgivesyoutwowaystodeal
withthesecases:
Youcanusetheroot_squashoptiontomaptheIDnumber
oftherootuseronaclienttothenfsnobodyuseronthe
server.
Youcanusetheall-squashoptiontomapallNFSuserson
theclienttonfsnobodyontheserver.
The/etc/passwdfileshowsthatnfsnobodyhasaUIDand
GIDof65534.Youcanusetheanonuidandanongidoptions
tooverridethesevalues.
NISandNFS
WhenyouuseNIS(page655)foruserauthorization,users
automaticallyhavethesameUIDsonbothsystems.Ifyouare
usingNFSonalargenetwork,itisagoodideatousea
directoryservicesuchasLDAP(page1040)orNISfor
authorization.Withoutsuchaservice,youmustsynchronizethe
passwdfilesonallthesystemsmanually.
root_squash(no_root_squash)
Mapsrequestsfromrootonaremotesystemsothatthey
appeartocomefromtheUIDfornfsnobody,anunprivileged
useronthelocalsystem,orasspecifiedbyanonuid.Doesnot
affectothersensitiveUIDssuchasbin.Theno_root_squash
optionturnsoffthismappingsothatrequestsfromrootappear
tocomefromroot.
no_all_squash(all_squash)
Doesnotchangethemappingofusersmakingrequestsofthe
NFSserver.Theall_squashoptionmapsrequestsfromall
users,notjustroot,onremotesystemstoappeartocome
fromtheUIDfornfsnobody,anunprivilegeduseronthelocal
system,orasspecifiedbyanonuid.Thisoptionisusefulfor
controllingaccesstoexportedpublicFTP,news,andother
directories.
anonuid=unandanongid=gn
SettheUIDortheGIDoftheanonymousaccounttounorgn,
respectively.NFSusestheseaccountswhenitdoesnot
recognizeanincomingUIDorGIDandwheninstructedtodoso
byroot_squashorall_squash.
showmount:DisplaysNFSStatusInformation
Withoutanyoptions,theshowmountutilitydisplaysalistof
systemsthatareallowedtomountlocaldirectories.Todisplay
informationforaremotesystem,givethenameoftheremote
systemasanargument.Youtypicallyuseshowmounttodisplaya
listofdirectoryhierarchiesthataserverisexporting.The
informationthatshowmountprovidesmaynotbecomplete,
however,becauseitdependsonmountdandtruststhat
remoteserversarereportingaccurately.
Inthefollowingexample,bravoandgrapecanmountlocal
directories,butyoudonotknowwhichones:
#/usr/sbin/showmount
Hostsonlocalhost:
bravo.tcorp.com
grape.tcorp.com
IfshowmountdisplaysanerrorsuchasRPC:Programnot
registered,NFSisnotrunningontheserver.StartNFSonthe
serverwiththenfsinitscript(page682).
a
(all)Tellswhichdirectoriesaremountedbywhichremote
systems.Thisinformationisstoredin/etc/exports.
#/usr/sbin/showmount-a
Allmountpointsonlocalhost:
bravo.tcorp.com:/home
grape.tcorp.com:/home
e
(exports)Displaysalistofexporteddirectories.
#/usr/sbin/showmount-e
Exportlistforlocalhost:
/homebravo.tcorp.com,grape.tcorp.com
exportfs:MaintainstheListofExportedDirectory
Hierarchies
Theexportfsutilitymaintainsthekernel'slistofexported
directoryhierarchies.Withoutchanging/etc/exports,exportfs
canaddtoorremovefromthelistofexporteddirectory
hierarchies.Anexportfscommandhasthefollowingformat:
/usr/sbin/exportfs[options][client:dir...]
whereoptionsisoneormoreoptions(asdetailedinthenext
section),clientisthenameofthesystemthatdirisexported
to,anddiristheabsolutepathnameofthedirectoryattheroot
ofthedirectoryhierarchybeingexported.
Thesystemexecutesthefollowingcommandwhenitcomesup
(itisinthenfsinitscript).Thiscommandreexportstheentries
in/etc/exportsandremovesinvalidentriesfrom
/var/lib/nfs/xtab(page684)sothat/var/lib/nfs/xtabis
synchronizedwith/etc/exports:
#exportfs-r
Replacetherwithatoexportonlytheentriesin
/etc/exports.Removeanexporteddirectoryhierarchywith
theuoption;removeallexporteddirectoryhierarchieswiththe
uaoptions.
Options
a
(all)Exportsdirectoryhierarchiesspecifiedin/etc/exports.
Thisoptiondoesnotunexportentriesyouhaveremovedfrom
exports(thatis,itdoesnotremoveinvalidentriesfrom
/var/lib/nfs/xtab);usertoperformthistask.
i
(ignore)Ignores/etc/exports;useswhatisspecifiedonthe
commandlineonly.
o
(options)Specifiesoptions.Youcanspecifyoptionsfollowingo
thesamewayyoudointheexportsfile.Forexample,
exportfsiorospeedy:/home/samexports/home/samon
thelocalsystemtospeedyforreadonlyaccess.
r
(reexport)Reexportstheentriesin/etc/exportsand
removesinvalidentriesfrom/var/lib/nfs/xtabsothat
/var/lib/nfs/xtabissynchronizedwith/etc/exports.
u
(unexport)Makesanexporteddirectoryhierarchynolonger
exported.Ifadirectoryhierarchyismountedwhenyou
unexportit,youwillseethemessageStaleNFSfilehandleif
youtrytoaccessthedirectoryhierarchyfromtheremote
system.
v
(verbose)Providesmoreinformation.Displaysexportoptions
whenyouuseexportfstodisplayexportinformation.
TestingtheServerSetup
Fromtheserver,runthenfsinitscriptwithanargumentof
status.Ifalliswell,thesystemdisplayssomethingsimilarto
thefollowing:
#/sbin/servicenfsstatus
rpc.mountd(pid15795)isrunning...
nfsd(pid1581315812158111581015809158081580715806)isrunning...
rpc.rquotad(pid15784)isrunning...
Next,fromtheserver,userpcinfotomakesureNFSisregistered
withportmap:
$/usr/sbin/rpcinfo-plocalhost|grepnfs
1000032udp2049nfs
1000033udp2049nfs
Repeattheprecedingcommandfromtheclient,replacing
localhostwiththenameoftheserver.Theresultsshouldbe
thesame.
Finally,trymountingdirectoryhierarchiesfromremotesystems
andverifyaccess.
automount:AutomaticallyMountsDirectory
Hierarchies
Withdistributedcomputing,whenyouloginonanysystemon
thenetwork,allofyourfiles,includingstartupscripts,are
available.Inadistributedcomputingenvironment,allsystems
arecommonlyabletomountalldirectoryhierarchiesonall
servers:Whicheversystemyouloginon,yourhomedirectory
iswaitingforyou.
Asanexample,assumethat/home/alexisaremotedirectory
hierarchythatismountedondemand.Whenyouissuethe
commandls/home/alex,autofsgoestowork:Itlooksinthe
/etc/auto.homemap,findsthatalexisakeythatsaysto
mountbravo:/export/home/alex,andmountstheremote
directoryhierarchy.Oncethedirectoryhierarchyismounted,ls
displaysthelistoffilesyouwanttosee.Ifyougivethe
commandls/homeafterthismountingsequence,lsshows
thatalexispresentwithinthe/homedirectory.Thedfutility
showsthatalexismountedfrombravo.
Prerequisites
Installthefollowingpackage:
autofs
Runchkconfigtocauseautofstostartwhenthesystementers
multiusermode:
#/sbin/chkconfigautofson
Anautofsdirectoryhierarchyislikeanyotherdirectory
hierarchy,butremainsunmounteduntilitisneeded,atwhich
timethesystemmountsitautomatically(demandmounting).
Thesystemunmountsanautofsdirectoryhierarchywhenitis
nolongerneededbydefaultafterfiveminutesofinactivity.
Automaticallymounteddirectoryhierarchiesareanimportant
partofadministratingalargecollectionofsystemsina
consistentway.Theautomountdaemonisparticularlyuseful
whenaninstallationincludesalargenumberofserversora
largenumberofdirectoryhierarchies.Italsohelpstoremove
serverserverdependencies(discussednext).
Whenyoubootasystemthatusestraditionalfstab-based
mountsandanNFSserverisdown,thesystemcantakealong
timetocomeupasitwaitsfortheservertotimeout.Similarly,
whenyouhavetwoservers,eachmountingdirectory
hierarchiesfromtheother,andbothsystemsaredown,both
mayhangastheyarebroughtupandeachtriestomounta
directoryhierarchyfromtheother.Thissituationiscalleda
serverserverdependency.Theautomountfacilitygetsaround
theseissuesbymountingadirectoryhierarchyfromanother
systemonlywhenaprocesstriestoaccessit.
Whenaprocessattemptstoaccessoneofthedirectorieswithin
anunmountedautofsdirectoryhierarchy,thekernelnotifies
theautomountdaemon,whichmountsthedirectoryhierarchy.
Youhavetogiveacommand,suchascd/home/alex,that
accessestheautofsmountpoint(inthiscase/home/alex)so
astocreatethedemandthatcausesautomounttomountthe
autofsdirectoryhierarchysoyoucanseeit.Beforeyouissue
thecdcommand,alexdoesnotappeartobein/home.
Themainfilethatcontrolsthebehaviorofautomountis
/etc/auto.master.Asimpleexamplefollows:
#cat/etc/auto.master
/free1/etc/auto.misc--timeout60
/free2/etc/auto.misc2--timeout60
Theauto.masterfilehasthreecolumns.Thefirstcolumn
namestheparentoftheautofsmountpointthelocationwhere
theautofsdirectoryhierarchyistobemounted(/free1and
/free2intheexamplearenotmountpointsbutwillholdthe
mountpointswhenthedirectoryhierarchiesaremounted).The
secondcolumnnamesthefiles,calledmapfiles,thatstore
supplementalconfigurationinformation.Theoptionalthird
columnholdsmountoptionsformapentriesthatdonotspecify
anoption.
Althoughthemapfilescanhaveanynames,oneistraditionally
namedauto.misc.Followingarethetwomapfilesspecifiedin
auto.master:
#cat/etc/auto.misc
sam-fstype=ext3:/dev/hda8
#cat/etc/auto.misc2
helen-fstype=ext3:/dev/hda9
Thefirstcolumnofamapfileholdstherelativeautofsmount
point(samandhelen).Thismountpointisappendedtothe
correspondingautofsmountpointfromcolumn1ofthe
auto.masterfiletocreatetheabsoluteautofsmountpoint.In
thisexample,sam(fromauto.misc)isappendedto/free1
(fromauto.master)tomake/free1/sam.Thesecondcolumn
holdstheoptions,andthethirdcolumnshowstheserverand
directoryhierarchytobemounted.Thisexampleshowslocal
drives;foranNFS-mounteddevice,thehostnameoftheremote
systemwouldappearbeforethecolon(forexample,
grape:/home/sam).
Beforethenewsetupcanwork,youmustcreatedirectoriesfor
theparentsofthemountpoints(/free1and/free2inthe
precedingexample)andstart(orrestart)theautomount
daemonusingtheautofsinitscript.Thefollowingcommand
displaysinformationaboutconfiguredandactiveautofsmount
points:
#/sbin/serviceautofsstatus
ChapterSummary
NFSallowsaservertoshareselectedlocaldirectoryhierarchies
withclientsystemsonaheterogeneousnetwork,reducing
storageneedsandadministrativeoverhead.NFSdefinesa
client/serverrelationshipinwhichaserverprovidesdirectory
hierarchiesthatclientscanmount.
Ontheserver,the/etc/exportsfileliststhedirectory
hierarchiesthatthesystemexports.Eachlineinexportslists
thesystemsthatareallowedtomountthehierarchyand
specifiestheoptionsforeachhierarchy(readonly,read-write,
andsoon).GiveanexportfsrcommandtocauseNFSto
rereadthisfile.
Fromaclient,youcangiveamountcommandtomountan
exportedNFSdirectoryhierarchy.Alternativelyyoucanputan
entryin/etc/fstabtohavethesystemautomaticallymount
thedirectoryhierarchywhenitcomesup.
Automaticallymounteddirectoryhierarchieshelpmanagelarge
groupsofsystemswithmanyserversandfilesystemsina
consistentwayandcanhelpremoveserverserver
dependencies.Theautomountdaemonautomaticallymounts
autofsdirectoryhierarchieswhentheyareneededand
unmountsthemwhentheyarenolongerneeded.
Exercises
1. ListthreereasonstouseNFS.
2.
Whichcommandwouldyougivetomountonthelocalsystemthe/home
directoryhierarchythatresidesonthefileservernamedbravo?Assumethe
mounteddirectoryhierarchywillappearas/bravo.homeonthelocalsystem.
Howwouldyoumountthesamedirectoryhierarchyifitresidedonthefileserverat
192.168.1.1?Howwouldyouunmount/home?
3. Howwouldyoulistthemountpointsontheremotesystemnamedbravothatthe
localsystemnamedgrapecanmount?
4. WhichcommandlineliststhecurrentlymountedNFSdirectoryhierarchies?
5. Whatdoesthe/etc/fstabfiledo?
6. Fromaserver,howwouldyouallowreadonlyaccessto/optforanysystemin
example.com?
AdvancedExercises
7. Whenisitagoodideatodisableattributecaching?
8. Describethedifferencebetweentheroot_squashandtheall_squashoptionsin
/etc/exports.
9. Whydoesthesecureoptionin/etc/exportsnotreallyprovideanysecurity?
10. SomedisklessworkstationsuseNFSasswapspace.Whyisthisuseful?Whatisthe
downside?
11. NFSmapsclientuserstousersontheserver.Explainwhythismappingisa
securityrisk.
12. Whatdoesthemountnosuidoptiondo?Whywouldyouwanttodothis?
23.Samba:IntegratingLinuxand
Windows
INTHISCHAPTER
AboutSamba 697
JumpStart:ConfiguringaSambaServerUsingsystem-config-
samba
699
swat:ConfiguresaSambaServer 701
ManuallyConfiguringaSambaServer 705
AccessingLinuxSharesfromWindows 711
AccessingWindowsSharesfromLinux 712
Troubleshooting 714
SambaisafreesuiteofprogramsthatenablesUNIX-like
operatingsystems,includingLinux,Solaris,FreeBSD,andMac
OSX,toworkwithotheroperatingsystems,suchasOS/2and
Windows,asbothaserverandaclient.
Asaserver,SambasharesLinuxfilesandprinterswithWindows
systems.Asaclient,SambagivesLinuxusersaccesstofileson
Windowssystems.Itsabilitytosharefilesacrossoperating
systemsmakesSambaanidealtoolinaheterogeneous
computingenvironment.
Introduction
ThischapterstartsbyprovidingalistofSambatoolsfollowed
bysomebasicinformation.TheJumpStartsectiondiscusses
howtosetupaSambaserverusingsystem-config-samba,a
minimalGUI.Thenextsectioncovershowtouseswat,aWeb-
basedadvancedconfigurationtool,tosetupaSambaserver.
ThefinalserversectiondiscusseshowtosetupaSambaserver
byhand,usingatexteditortomanuallyeditthefilesthat
controlSamba.Thenexttwosections,"AccessingLinuxShares
fromWindows"(page711)and"AccessingWindowsShares
fromLinux"(page712),explainhowtoworkwithLinuxand
Windowsfilesandprinters.Thefinalsectionofthechapter,
"Troubleshooting"(page714),offerstipsonwhattodowhen
youhaveaproblemsettinguporusingSamba.
Table23-1liststheutilitiesanddaemonsthatmakeupthe
Sambasuiteofprograms.
Table23-1.Sambautilitiesanddaemons
Utilityor
daemon Function
net ThisutilityhasthesamesyntaxastheDOSnet
commandand,overtime,willeventuallyreplace
otherSambautilitiessuchassmbpasswd.
nmbd TheNetBIOS(page1044)nameserverprogram,run
asadaemonbydefault.ProvidesNetBIOSoverIP
namingservicesforSambaclients.Alsoprovides
browsing(asintheWindowsNetworkNeighborhood
orMyNetworkPlacesview)support.
nmblookup MakesNetBIOS(page1044)namequeries(page
715).
smbclient DisplayssharesonaSambaserversuchasa
Windowsmachine(page713).
smbd TheSambaprogram,runasadaemonbydefault.
ProvidesfileandprintservicesforSambaclients.
smbpasswd ChangesWindowsNTpasswordhashesonSamba
andWindowsNTservers(page698).
smbstatus Displaysinformationaboutcurrentsmbd
connections.
smbtree Displaysahierarchicaldiagramofavailableshares
(page712).
swat SambaWebAdministrationTool.Agraphicaleditor
forthesmb.conffile(page701).
testparm Checkssyntaxofthesmb.conffile(page714).
testprns Checksprinternamesintheprintcapfile.
AboutSamba
Thissectioncoversthepackagesyouneedtoinstalltorun
Samba,sourcesofmoreinformationonSamba,andusersand
passwordsunderSamba.
Prerequisites
Installthefollowingpackages:
samba
samba-client
samba-common
system-config-samba(optional)
samba-swat(optional,butagoodidea)
Runchkconfigtocausesmbtostartwhenthesystementers
multiusermode:
#/sbin/chkconfigsmbon
Startsmb:
#/sbin/servicesmbstart
Ifyouwanttouseswat,modify/etc/xinetd.d/swat,as
explainedin"swat:ConfiguresaSambaServer"onpage701,
andrestartxinetd:
#/sbin/servicexinetdrestart
MoreInformation
Local
Samba/swathomepagehaslinkstolocalSambadocumentation
(page701)Documentation/usr/share/doc/samba-*
Web
Sambawww.samba.org(mailinglists,documentation,
downloads,andmore)CIFSwww.samba.org/cifs
HOWTO
UnofficialSambaHOWTOhr.uoregon.edu/davidrl/samba.html
SambaHOWTOCollectionPointabrowseratthefollowing
pathnameonthelocalsystem(afterreplacingthe*withthe
value,suchas3.0.21b,fromthelocalfilesystem):
/usr/share/doc/samba-*/htmldocs/index.html
Notes
Firewall
TheSambaservernormallyusesUDPports137and138and
TCPports139and445.IftheSambaserversystemisrunning
afirewall,youneedtoopentheseports.UsingtheRedHat
graphicalfirewalltool(page768),selectSambafromthe
TrustedServicesframetoopentheseports.Formoregeneral
information,seeChapter25,whichdetailsiptables.
SELinux
WhenSELinuxissettouseatargetedpolicy,Sambais
protectedbySELinux.Youcandisablethisprotectionif
necessary.Formoreinformationreferto"SettingtheTargeted
Policywithsystem-config-securitylevel"onpage402.
Share
UnderSamba,anexporteddirectoryhierarchyiscalledashare.
Samba
ThenameSambaisderivedfromSMB(page1055),the
protocolthatisthenativemethodoffileandprintersharingfor
Windows.
SambaUsers,UserMaps,andPasswords
ForaWindowsusertogainaccesstoSambaservicesonaLinux
system,theusermustprovideaWindowsusernameanda
Sambapassword.Insomecases,Windowssuppliesthe
usernameandpasswordforyou.Itisalsopossibleto
authenticateusingothermethods.Forexample,Sambacanuse
LDAP(page1040)orPAM(page438)insteadofthedefault
passwordfile.RefertotheSambadocumentationformore
informationonauthenticationmethods.
Usernames
ThesuppliedusernamemustbethesameasaLinuxusername
ormustmaptoaLinuxusername.Sambakeepstheusername
mapsin/etc/samba/smbusers.Userswiththesame
usernameonLinuxandSambadonotneedtoappearinthis
file,buttheystillneedaSambapassword.
WhenyouinstallSamba,smbusershastwoentries:
$cat/etc/samba/smbusers
#Unix_name=SMB_name1SMB_name2...
root=administratoradmin
nobody=guestpcguestsmbguest
ThefirstentrymapsthetwoWindowsusernames
(administratorandadmin)totheLinuxusernameroot.The
secondentrymapsthreeWindowsusernames,includingguest,
totheLinuxusernamenobody:WhenaWindowsuser
attemptstologinontheSambaserverasguest,Samba
authenticatestheLinuxusernamednobody.
Passwords
SambausesSambapasswordsnotLinuxpasswordsto
authenticateusers.Bydefault,Sambakeepspasswordsin
/etc/samba/smbpasswd.AsSambaisinstalled,
authenticationforrootornobodywouldfailbecauseSambais
installedwithoutpasswords:Thesmbpasswdfiledoesnot
exist.
Eachoftheconfigurationtechniquesdescribedinthischapter
allowsyoutoadduserstosmbusersandpasswordsto
smbpasswd.Youcanalwaysusesmbpasswdasdiscussedlater
inthissectiontoaddandchangepasswordsinsmbpasswd.
Note
WhenyouattempttoconnectfromWindowstoaSambaserver,
WindowspresentsyourWindowsusernameandpasswordto
Samba.IfyourWindowsusernameisthesameasormapsto
yourLinuxusername,andifyourWindowsandSamba
passwordsarethesame,youdonothavetoenterausername
orpasswordtoconnecttotheSambaserver.
Example
Youcanaddthefollowinglinetosmbuserstomapthe
WindowsusernamesamtotheLinuxusernamesls:
sls=sam
Youcanaddapasswordforslstosmbpasswdwiththe
followingcommand:
#smbpasswd-asls
NewSMBpassword:
RetypenewSMBpassword:
Addedusersls.
NowwhenSamusestheusernamesamtologinontheSamba
server,Sambamapssamtoslsandlooksupslsin
smbpasswd.AssumingSamprovidesthecorrectpassword,he
logsinontheSambaserverassls.
JumpStart:ConfiguringaSambaServerUsing
system-config-samba
Thesystem-config-sambautilitycansetuponlybasicfeaturesofa
Sambaserver.Itis,however,thebesttooltouseifyouarenot
familiarwithSambaandyouwanttosetupasimpleSamba
serverquickly.Thesystem-config-sambautilityperformsthreebasic
functions:configuringtheserver,configuringusers,andsetting
upshares(directoryhierarchies)thatareexportedtothe
Windowsmachines.
Tip:Makeacopyofsmb.conf
Asinstalled,the/etc/samba/smb.conffilehas
extensivecomments(page705).Thesystem-config-
sambautilityoverwritesthisfile.Makeacopyof
smb.confforsafekeepingbeforeyourunthisutility
forthefirsttime.
TodisplaytheSambaServerConfigurationwindow(Figure23-
1),entersystem-config-sambaonacommandline.From
KDEselectMainmenu:System SambaorfromGNOME
selectSystem:Administration ServerSettings Samba.
Figure23-1.SambaServerConfigurationwindow
[Viewfullsizeimage]
SelectMenubar:Preferences ServerSettingstodisplay
theServerSettingswindowBasictab(Figure23-2,nextpage).
ChangetheworkgrouptotheoneinuseontheWindows
machines.Changethedescriptionoftheserverifyoulike.Click
theSecuritytabandmakesureAuthenticationModeissetto
User;youdonotneedtospecifyanAuthenticationServerora
KerberosRealm.IfyouareusingWindows98orlater,set
EncryptPasswordstoYes.Whenyouspecifyausernameinthe
GuestAccount,anyonelogginginontheSambaserveras
guestmapstothatuser'sID.Typicallytheguestaccount
mapstotheUIDoftheLinuxusernamednobody.ClickOK.
Figure23-2.ServerSettingswindow,Basictab
Sambausers
SelectMenubar:Preferences SambaUserstodisplaythe
SambaUserswindow(Figure23-3).Iftheuseryouwanttolog
inasisnotalreadyspecifiedinthiswindow,clickAddUser.
Whenyouhavetheproperpermissions,theCreateNewSamba
UserwindowdisplaysacomboboxnexttoUnixUsernamethat
allowsyoutoselectaLinuxuser;otherwise,yourusernameis
displayedastheUnixUsername.TheWindowsUsernameisthe
WindowsusernamethatyouwanttomaptothespecifiedLinux
(UNIX)username.TheSambaPasswordisthepasswordthis
userorWindowsenterstogainaccesstotheSambaserver.
Figure23-3.SambaUserswindow
IfSamhasaccountsnamedsamonboththeWindowsand
Linuxsystems,youwouldselectsamfromtheUnixUsername
combobox,entersamintheWindowsUsernametextbox,and
enterSam'sWindowspasswordinthetwoSambaPassword
textboxes.ClickOKtoclosetheCreateNewSambaUser
windowandclickOKtoclosetheSambaUserswindow.
Tip:AddingaSambapasswordforthe
Linuxusernobody
Becausetheusernobodyexistsinsmbuserswhen
youinstallSamba,youcannotaddtheusernobody,
norcanyouaddapasswordfornobodyfromsystem-
config-samba.Instead,youmustusesmbpasswdfrom
thecommandlineasfollows:
#smbpasswd-anobody
NewSMBpassword:
RetypenewSMBpassword:
Normallytheusernobodydoesnothavea
passwordbecauseitistheguestlogin.Press
RETURN(withouttypinganycharacters)inresponse
toeachoftheSMBpasswordpromptstoadd
nobodytotheSambapasswordfilewithouta
password.
Linuxshares
Nextyouneedtoaddashare,whichisthedirectoryhierarchy
youexportfromtheLinuxsystemtotheWindowssystem.Click
AddShareonthetoolbartodisplaytheBasictabintheCreate
SambaSharewindow(Figure23-4).IntheDirectorytextbox,
entertheabsolutepathnameofthedirectoryyouwanttoshare
(/tmpisaneasydirectorytopracticewith).Enteradescription
ifyoulike.ItcanbeusefultoentertheLinuxhostnameandthe
pathnameofthedirectoryyouaresharinghere.Specify
Writableifyouwanttobeabletowritetothedirectoryfromthe
Windowsmachine;Visibleallowsthesharetobeseenfromthe
Windowsmachine.ClicktheAccesstabandspecifywhetheryou
wanttolimitaccesstospecifiedusersorwhetheryouwantto
allowanyonetoaccessthisshare.ClickOK.ClosetheSamba
ServerConfigurationwindow.
Figure23-4.CreateSambaSharewindow,Basic
tab
swat:ConfiguresaSambaServer
Tip:Makeacopyofsmb.conf
Asinstalled,the/etc/samba/smb.conffile
containsextensivecomments(page705).Theswat
utilityoverwritesthisfile.Makeacopyofsmb.conf
forsafekeepingbeforeyourunthisutilityforthe
firsttime.
Theswat(SambaWebAdministrationTool)utilityisabrowser-
basedgraphicaleditorforthesmb.conffile.Itispartofthe
samba-swatpackage.Foreachoftheconfigurable
parameters,itprovideshelplinks,defaultvalues,andatext
boxtochangethevalue.Theswatutilityisawell-designedtool
inthatitremainstruetothelinesinthesmb.conffileyouedit:
Youcanuseandlearnfromswat,sothatmakingthetransition
tousingatexteditortomodifysmb.confwillbe
straightforward.
Theswatutilityisrunfromxinetd(page425).Beforeyoucan
runswat,youneedtoedit/etc/xinetd.d/swat(asdiscussed
next):
$cat/etc/xinetd.d/swat
#Default:off
#description:SWATistheSambaWebAdminTool.Useswat\
#toconfigureyourSambaserver.TouseSWAT,\
#connecttoport901withyourfavoritewebbrowser.
serviceswat
{
port=901
socket_type=stream
wait=no
only_from=127.0.0.1
user=root
server=/usr/sbin/swat
log_on_failure+=USERID
disable=yes
}
Firstyoumustturnswatonbychangingtheyesthatfollows
disable=tono.Ifyouwanttoaccessswatfromotherthanthe
localsystem,addthenamesorIPaddressesoftheother
systemsyouwanttoaccessswatfromonthelinethatstarts
withonly_from.SeparatethesystemnamesorIPaddresses
withSPACEs.Ifyouwanttoaccessswatonlyfromthelocal
system,givingthecommandchkconfigswatonisaneasier
wayofmakingthischange.Thenrestartxinetdsothatit
rereadsitsconfigurationfiles:
#/sbin/servicexinetdrestart
Stoppingxinetd:[OK]
Startingxinetd:[OK]
Aftermakingthesechangesandrestartingxinetd,youshould
beabletorunswat.Fromthelocalsystem,openabrowser,
entereitherhttp://127.0.0.1:901orhttp://localhost:901
inthelocationbar,andentertheusernamerootandtheroot
passwordinresponsetoswat'srequestforausernameand
password.Fromaremotesystem,replace127.0.0.1withthe
IPaddressoftheserver(butseetheadjacentsecuritytip).Ifa
firewallisrunningonthelocalsystemandyouwanttoaccess
swatfromaremotesystem,openTCPport901(page768).
Security:Donotallowremoteaccessto
swat
Donotallowaccesstoswatfromaremotesystemon
aninsecurenetwork.Whenyoudosoandlogin,
yourpasswordissentincleartextoverwhatever
connectionyouareusingandcaneasilybesniffed.
ThebrowserdisplaysthelocalSamba/swathomepage(Figure
23-5).ThispageincludeslinkstolocalSambadocumentation
andthefollowingbuttons:
Figure23-5.Thelocalswathomepage
[Viewfullsizeimage]
HOME
LinkstolocalSambadocumentation.Whenyouclicktheword
Samba(notthelogo,buttheonejustbeforetheword
DocumentationintheHOMEwindow),swatdisplaystheSamba
manpage,whichdefineseachSambaprogram.
GLOBALS
Editsglobalvariables(parameters)insmb.conf.
SHARES
Editsshareinformationinsmb.conf.
PRINTERS
Editsprinterinformationinsmb.conf.
WIZARD
Rewritesthesmb.conffile,removingallcommentlinesand
linesthatspecifydefaultvalues.
STATUS
Showstheactiveconnections,activeshares,andopenfiles.
Stopsandrestartssmbdandnmbd.
VIEW
Displaysasubsetoralloftheconfigurationparametersas
determinedbydefaultvaluesandsettingsinsmb.conf.
PASSWORD
Managespasswords.
ItisquiteeasytoestablishabasicSambasetupsothatyou
canseeaLinuxdirectoryfromaWindowssystem(Windows3.1
orlater).Moreworkisrequiredtosetupasecureconnectionor
onewithspecialfeatures.Thefollowingexamplecreatesabasic
setupbasedonthesamplesmb.conffilethatisincludedwith
RedHatLinux.
swatHelpanddefaults
Eachofthevariables/parametersinswathasalinknamedHelp
nexttoit.IfyouclickHelp,anewbrowserwindowcontaining
anexplanationoftheparameterappears.Each
variable/parameteralsohasaSetDefaultbuttonthatyoucan
clicktoresetthevariable/parametertoitsdefaultvalue.
Forthisexample,donotclickanyoftheSetDefaultbuttons.
MakesuretoclickCommitChangesatthetopofeachpage
afteryoufinishmakingchangesonapagebutbeforeyouclick
amenubuttonatthetopofthewindow.Otherwise,swatwillnot
keepyourchanges.
FirstclickGLOBALSatthetopoftheSamba/swathomepage.
Leaveeverythingatitscurrentsettingwiththreeexceptions:
workgroup,hostsallow,andhostsdeny.Setworkgroupto
theworkgroupusedontheWindowssystems.(Ifyoufollowed
theprecedingJumpStart,theworkgroupisalreadyset.)Scroll
tothebottomoftheSecurityOptionsandsethostsallowto
thenamesorIPaddressesofmachinesthatyouwanttobe
abletoaccessthelocalsystem'ssharesandprinters(including
localhost[127.0.0.1]).SeparatetheentrieswithSPACEsor
commas.Seepage707formoreinformationonvariousways
youcansethostsallow.SethostsdenytoALL.Click
CommitChanges(nearthetopofthepage)whenyouare
donewiththeGLOBALSpage.
Tip:Ifyoucannolongeruseswat
Ifyoucannolongeruseswat,youprobablychanged
thehostsallowsettingincorrectly.Inthiscase,you
needtoedit/etc/samba/smb.confandfixthe
linewiththewordshostsallowinit:
#grephostssmb.conf
hostsallow=127.0.0.1,192.168.0.8
hostsdeny=ALL
Theprecedingentriesallowaccessfromthelocal
systemandfrom192.168.0.8only.
SHARESpage
NextclickSHARESatthetopofthepage.Threebuttonsand
twotextboxesappearinadditiontothetwoChangeViewTo
buttons(Figure23-6).IntheboxadjacenttotheCreateShare
button,enterthenameyouwanttoassigntotheshareyouare
settingup.Thisnamecanbeanythingyouwant;itisthename
thatWindowsdisplaysandauserselectswhenworkingwiththe
share.ClickCreateShare.Whenyouwanttomodifyan
existingshare,bringupthenameoftheshareinthecombo
boxadjacenttoChooseShare,andclickChooseShare.
EitheroftheseactionsexpandstheShareParameterswindow
sothatitdisplaysinformationabouttheselectedshare.
Figure23-6.ShareParameterspage
[Viewfullsizeimage]
Leaveeverythingatitsdefaultsettingexceptpath,which
specifiestheabsolutepathnameonthelocalLinuxsystemof
theshare,andoptionallycomment,whichyoucanuseto
specifytheLinuxsystemanddirectorythatthissharepointsto.
Thevaluesforhostsallowandhostsdenyaretakenfromthe
globalvariablesthatyousetpreviously.ClickCommitChanges
whenyouaredonewiththeSHARESpage.Ifyouwanttosee
howmanyparameterstherereallyare,clickAdvancednear
thetopofthepage.
Now,fromaWindowsmachine,youshouldbeabletoaccess
theshareyoujustcreated(page711).
Tip:YoudonotneedtorestartSamba
whenyouchangesmb.conf
Sambarereadsitsconfigurationfileseachtimea
clientconnects.Unlessyouchangethesecurity
parameter(page708),youdonotneedtorestart
Sambawhenyouchangesmb.conf.
ManuallyConfiguringaSambaServer
The/etc/samba/smb.conffilecontrolsmostaspectsofhow
Sambaworksandisdividedintosections.Eachsectionbegins
withalinethatstartswithanopenbracket([),includessome
text,andendswithaclosebracket(]).Thetextwithinthe
bracketsidentifiesthesection.Typicalsectionsare
[globals] Definesglobalparameters
[printers] Definesprinters
[homes] Definessharesinthehomesdirectory
[share
name]
Definesashare(youcanhavemorethanoneofthese
sections)
smb.confcomments
AsinstalledonaRedHatLinuxsystem,the
/etc/samba/smb.confsampleconfigurationfilecontains
extensivecommentsandcommented-outexamples.Comment
linesinsmb.confcanstartwitheitherapoundsign(#)ora
semicolon(;).Thesamplefileusespoundsignstobeginlines
thatareintendedtoremainascommentsandsemicolonsto
beginlinesthatyoumaywanttomimicoruseasisby
removingthesemicolons.Thefollowingsegmentofsmb.conf
containstwolinesoftruecommentsandsevenlinesbeginning
withsemicolonsthatyoumaywanttouncommentandmake
changesto:
#Aprivatedirectory,usableonlybyfred.Notethatfredrequires
#writeaccesstothedirectory.
;[fredsdir]
;comment=Fred'sService
;path=/usr/somewhere/private
;validusers=fred
;public=no
;writable=yes
;printable=no
Assumingtheglobalparametersinsmb.confaresetproperly,
youneedtoaddashareforaWindowssystemtobeableto
accessadirectoryonthelocalLinuxsystem.Addthefollowing
simplesharetotheendofthesmb.conffiletoenableauser
onaWindowssystemtobeabletoreadfromandwritetothe
local/tmpdirectory:
[tmp]
comment=temporarydirectory
path=/tmp
writable=yes
guestok=yes
ThenameoftheshareunderWindowsistmp;thepathunder
Linuxis/tmp.AnyWindowsuser,includingguest,whocanlog
inonSamba,canreadfromandwritetothisdirectory,
assumingthattheuser'sLinuxpermissionsallowit.TheLinux
permissionsthatapplytoaWindowsuserusingSambaarethe
permissionsthatapplytotheLinuxuserthattheWindowsuser
mapsto.
Parametersinthesmbd.confFile
Thethesmb.confmanpageandtheHelpfeatureofswatlistall
theparametersyoucansetinsmb.conf.Thefollowingsections
identifysomeoftheparametersyouarelikelytowantto
change.
GlobalParameters
interfaces
ASPACE-separatedlistofthenetworksthatSambauses.
Specifyasinterfacenames(suchaseth0)orasIPaddress/net
maskpairs(page423).
Default:allactiveinterfacesexcept127.0.0.1
serverstring
ThestringthatisdisplayedinvariousplacesontheWindows
machine.Withinthestring,Sambareplaces%vwiththe
Sambaversionnumberand%hwiththehostname.
Default:Samba%v
RedHat:SambaServer
workgroup
Theworkgroupthattheserverbelongsto.Settothesame
workgroupastheWindowsclientsthatusetheserver.This
parametercontrolsthedomainnamethatSambauseswhen
security(page708)issettoDOMAIN.
Default:WORKGROUP
RedHat:MYGROUP
SecurityParameters
encryptpasswords
YESacceptsonlyencryptedpasswordsfromclients.Windows
98andWindowsNT4.0ServicePack3andlateruseencrypted
passwordsbydefault.Thisparameterusessmbpasswdto
authenticatepasswordsunlessyousetsecuritytoSERVERor
DOMAIN,inwhichcaseSambaauthenticatesusinganother
server.
Default:YES
Sambadefaultstostoringencryptedpasswordsinthe
smbpasswdfileifyoudonotsetuppassdb(apassword
database).Storingpasswordsinthesmbpasswdfileis
sensibleonserverswithfewerthan250users.Forhigh-load
servers,consulttheSambaHOWTOcollectionforinformation
aboutconfiguringadatabasebackend.
guestaccount
Theusernamethatisassignedtouserslogginginasguestor
mappedtoguest;applicableonlywhenguestok(page711)is
settoYES.Thisusernameshouldbepresentin/etc/passwd
butshouldnotbeabletologinonthesystem.Typicallyguest
accountisassignedavalueofnobodybecausetheuser
nobodycanaccessonlyfilesthatanyusercanaccess.Ifyou
areusingthenobodyaccountforotherpurposesontheLinux
system,setthisvariabletoanameotherthannobody.
Default:nobody
hostsallow
Analogoustothe/etc/hosts.allowfile(page427),this
parameterspecifieshoststhatareallowedtoconnecttothe
server.Overrideshostsspecifiedinhostsdeny.Agood
strategyistospecifyALLinhostsdenyandtospecifythe
hostsyouwanttograntaccesstointhisfile.Specifyhostsin
thesamemannerasinhosts.allow.
Default:none(allhostspermittedaccess)
hostsdeny
Analogoustothe/etc/hosts.denyfile(page427),this
parameterspecifieshoststhatarenotallowedtoconnecttothe
server.Overriddenbyhostsspecifiedinhostsallow.Ifyou
specifyALLinthisfile,remembertoincludethelocalsystem
(127.0.0.1)inhostsallow.Specifyhostsinthesamemanner
asinhosts.deny.
Default:none(nohostsexcluded)
maptoguest
Defineswhenafailedloginismappedtotheguestaccount.
UsefulonlywhensecurityisnotsettoSHARE.
Never:Allowsguesttologinonlywhentheuserexplicitly
providesguestastheusernameandablankpassword.
BadUser:Treatsanyattempttologinasauserwhodoesnot
existasaguestlogin.Thisparameterisasecurityriskbecause
itallowsamalicioususertoretrievealistofusersonthe
systemquickly.
BadPassword:Silentlylogsinasguestanyuserwho
incorrectlyentershisorherpassword.Thisparametermay
confuseauserwhenshemistypesherpasswordandis
unknowinglyloggedinasguestbecauseshewillsuddenlysee
fewersharesthansheisusedto.
Default:Never
passwdchat
ThechatscriptthatSambausestoconversewiththepasswd
program.Ifthisscriptisnotfollowed,Sambadoesnotchange
thepassword.Usedonlywhenunixpasswordsyncissetto
YES.
Default:*new*password*%n\n*new*password*
%n\n*changed*
passwdprogram
TheprogramSambausestosetLinuxpasswords.Samba
replaces%uwiththeuser'susername.
Default:/usr/bin/passwd%u
security
Specifiesifandhowclientstransferuserandpassword
informationtotheserver.Chooseoneofthefollowing:
USER:CausesSambatorequireausernameand
passwordfromusersorWindowswhenlogginginonthe
Sambaserver.Withthissettingyoucanuse
usernamemaptomapusernamestoothernames
encryptpasswords(page706)toencryptpasswords
(recommended)
guestaccount(page707)tomapuserstotheguest
account
SHARE:CausesSambanottoauthenticateclientsona
per-userbasis.Instead,Sambausesthesystemfoundin
Windows9x,inwhicheachsharecanhaveanindividual
passwordforeitherreadorfullaccess.Thisoptionisnot
compatiblewithmorerecentversionsofWindows.
SERVER:CausesSambatouseanotherSMBserverto
validateusernamesandpasswords.Failingremote
validation,thelocalSambaservertriestovalidateas
thoughsecurityweresettoUSER.
DOMAIN:Sambapassesanencryptedpasswordtoa
WindowsNTdomaincontrollerforvalidation.
ADS:InstructsSambatouseanActiveDirectoryserver
forauthentication,allowingaSambaservertoparticipate
asanativeActiveDirectorymember.(ActiveDirectoryis
thecentralizedinformationsystemthatWindows2000
andlateruse.ItreplacesWindowsDomains,whichwas
usedbyWindowsNTandearlier.)
Default:USER
unixpasswordsync
YEScausesSambatochangeauser'sLinuxpasswordwhenthe
associateduserchangestheencryptedSambapassword.
Default:NO
updateencrypted
YESallowsuserstomigratefromcleartextpasswordsto
encryptedpasswordswithoutlogginginontheserverandusing
smbpasswd.Tomigrateusers,settoYESandsetencrypt
passwordstoNO.Aseachuserlogsinontheserverwitha
cleartextLinuxpassword,smbpasswdencryptsandstoresthe
passwordin/etc/samba/smbpasswd.SettoNOandset
encryptpasswordstoYESafterallusershavebeen
converted.
Default:NO
usernamemap
Thenameofthefilethatmapsusernamesfromaclientto
usernamesontheserver.Eachlineofthemapfilestartswitha
serverusername,followedbyaSPACE,anequalsign,another
SPACE,andoneormoreSPACE-separatedclientusernames.An
asterisk(*)ontheclientsidematchesanyclientusername.This
filefrequentlymapsWindowsusernamestoLinuxusernames
and/ormapsmultipleWindowsusernamestoasingleLinux
usernametofacilitatefilesharing.Asamplemapfileisshown
here:
$cat/etc/samba/smbusers
#Unix_name=SMB_name1SMB_name2...
root=administratoradmin
nobody=guest
sam=sams
Default:nomap
RedHat/etc/samba/smbusers
LoggingParameters
logfile
ThenameoftheSambalogfile.Sambareplaces%mwiththe
nameoftheclientsystem,allowingyoutogenerateaseparate
logfileforeachclient.
Default:none
RedHat:/var/log/samba/%m.log
loglevel
Setstheloglevel,with0(zero)beingoffandhighernumbers
beingmoreverbose.
Default:0(off)
maxlogsize
Anintegerspecifyingthemaximumsizeofthelogfilein
kilobytes.A0(zero)specifiesnolimit.Whenafilereachesthis
size,Sambaappendsa.oldtothefilenameandstartsanew
log,deletinganyoldlogfile.
Default:5000
RedHat:50
BrowserParameters
Thedomainmasterbrowseristhesystemthatisresponsiblefor
maintainingthelistofmachinesonanetworkusedwhen
browsingaWindowsNetworkNeighborhoodorMyNetwork
Places.SMB(page1055)usesweightedelectionsevery1115
minutestodeterminewhichmachinewillbethedomainmaster
browser.
WhetheraSambaserverwinsthiselectiondependsontwo
parameters:First,settingdomainmastertoYESinstructsthe
Sambaservertoentertheelection.Second,theoslevel
determineshowmuchweighttheSambaserver'svotereceives.
Settingoslevelto2shouldcausetheSambaservertowin
againstanyWindows9xmachines.NTServerseriesdomain
controllers,includingWindows2000,XP,and2003,useanos
levelof32.Themaximumsettingforoslevelis255,although
settingitto65shouldensurethattheSambaserverwins.
domainmaster
YEScausesnmbdtoattempttobethedomainmasterbrowser.
Ifadomainmasterbrowserexists,thenlocalmasterbrowsers
willforwardcopiesoftheirbrowseliststoit.Ifthereisno
domainmasterbrowser,thenbrowsequeriesmaynotbeable
tocrosssubnetboundaries.AWindowsPDC(PrimaryDomain
Controller)willalwaystrytobecomethedomainmasterand
maybehaveinunexpectedwaysifitfails.Refertothe
precedingdiscussion.
Default:AUTO
localmaster
YEScausesnmbdtoenterelectionsforthelocalmaster
browseronasubnet.Alocalmasterbrowserstoresacacheof
theNetBIOS(page1044)namesofentitiesonthelocalsubnet,
allowingbrowsing.Windowsmachinesautomaticallyenter
elections;forbrowsingtowork,thenetworkmusthaveatleast
oneWindowsmachineoroneSambaserverwithlocalmaster
settoYES.ItispoorpracticetosetlocalmastertoNO.Ifyou
donotwantacomputertoactasalocalmaster,setitsoslevel
toalowernumber,allowingittobeusedasthelocalmasterif
allelsefails.
Default:YES
oslevel
AnintegerthatcontrolshowmuchSambaadvertisesitselffor
browserelectionsandhowlikelynmbdistobecomethelocal
masterbrowserforitsworkgroup.Ahighernumberincreases
thechancesofthelocalserverbecomingthelocalmaster
browser.Refertothediscussionatthebeginningofthissection.
Default:20
preferredmaster
YESforcesnmbdtoholdanelectionforlocalmasterandenters
thelocalsystemwithaslightadvantage.Withdomainmaster
settoYES,thisparameterhelpsensurethatthelocalSamba
serverbecomesthedomainmaster.Settingthisparameterto
YESonmorethanoneservercausestheserverstocompeteto
becomemaster,generatingalotofnetworktrafficand
sometimesleadingtounpredictableresults.AWindowsPDC
(PrimaryDomainController)automaticallyactsasifthis
parameterisset.
Default:AUTO
CommunicationParameters
dnsproxy
WhenactingasaWINSserver(page1063),YEScausesnmbd
touseDNSifNetBIOS(page1044)resolutionfails.
Default:YES
RedHat:NO
socketoptions
Tunesthenetworkparametersusedwhenexchangingdatawith
aclient.TheRedHatLinuxsettingisappropriateinmostcases.
Default:TCP_NODELAY
RedHat:TCP_NODELAYSO_RCVBUF=8192SO_SNDBUF=8192
winsserver
TheIPaddressoftheWINSserverthatnmbdshouldregister
with.
Default:notenabled
winssupport
YESspecifiesthatnmbdactasaWINSserver.
Default:NO
ShareParameters
Eachofthefollowingparameterscanappearmanytimesin
smb.conf,onceineachsharedefinition.
available
YESspecifiestheshareasactive.SetthisparametertoNOto
disabletheshare,butcontinueloggingrequestsforit.
Default:YES
browseable
Determineswhetherthesharecanbebrowsed,forexample,in
WindowsMyNetworkPlaces.
Default:YES
RedHat:NO
comment
Adescriptionoftheshare,shownwhenbrowsingthenetwork
fromWindows.
Default:none
RedHat:varies
guestok
Allowsauserwhologsinasguesttoaccessthisshare.
Default:NO
path
Thepathofthedirectorythatisbeingshared.
Default:none
RedHat:various
readonly
Doesnotallowwriteaccess.
Default:YES
The[homes]Share:SharingUsers'Home
Directories
FrequentlyuserswanttosharetheirLinuxhomedirectories
withaWindowsmachine.Tomakethistaskeasier,Samba
providesthe[homes]share.Whenyoudefinethisshare,each
user'shomedirectoryissharedwiththespecifiedparameters.
Inmostcases,thefollowingparametersareadequate:
[homes]
comment=HomeDirectories
browseable=no
writable=yes
Thesesettingspreventusersotherthantheownersfrom
browsinghomedirectories,whileallowinglogged-inownersfull
access.
SELinux
IfthesystemisrunningSELinuxwithatargetedpolicyandyou
wanttoallowuserstosharetheirhomedirectoriesasexplained
inthissection,youmustturnontheSELinuxsettingSamba
AllowSambatoshareusershomedirectoriesasdisplayed
bysystem-config-securitylevel(page402).
AccessingLinuxSharesfromWindows
BrowsingShares
ToaccessashareonaSambaserverfromWindows,openMy
ComputerorExplorerontheWindowssystemand,inthe
Addresstextbox,enter\\followedbytheNetBIOSname(or
justthehostnameifyouhavenotassignedadifferentNetBIOS
name)oftheSambaserver.Windowsthendisplaysthe
directoriesthattheLinuxsystemissharing.Toviewtheshares
ontheLinuxsystemnamedbravo,forexample,youwould
enter\\bravo.Fromthiswindow,youcanviewandbrowse
thesharesavailableontheLinuxsystem.Ifyousetashareso
thatitisnotbrowseable,youneedtoenterthepathofthe
shareusingtheformat\\servername\sharename.
MappingaShare
AnotherwaytoaccessashareonaSambaserverisby
mappingashare.OpenMyComputerorExploreronthe
WindowssystemandclickMapNetworkDrivefromoneofthe
drop-downmenusonthemenubar(foundontheToolsmenu
onWindowsXP).WindowsdisplaystheMapNetworkDrive
window.SelectanunusedWindowsdriveletterfromtheDrive
comboboxandentertheWindowspathtotheshareyoujust
created.(Whenyouusesystem-config-sambatocreateashare,the
sharehasthesamenameasthenameofthedirectoryyouare
sharing.)Theformatofthewindowspathis
\\hostname\sharename.Forexample,tomap/tmpon
bravotoWindowsdriveJ,assumingtheshareisnamedtmp
ontheLinuxsystem,selectJintheDrivecombobox,enter
\\bravo\tmpintheFoldertextbox,andclickFinish.You
AccessingWindowsSharesfromLinux
Asaclient,Sambaenablesyoutoviewandworkwithfilesona
WindowssystemfromaLinuxsystem.Thissectiondiscusses
severalwaysofaccessingWindowsfilesfromLinux.
smbtree:DisplaysWindowsShares
Thesmbtreeutilitydisplaysahierarchicaldiagramofavailable
shares.Whenyourunsmbtree,itpromptsyouforapassword;do
notenterapasswordifyouwanttobrowsesharesthatare
visibletotheguestuser.Thepasswordallowsyoutoview
restrictedshares,suchasauser'shomedirectoryinthe
[homes]share.Followingissampleoutputfromsmbtree:
$smbtree
Password:
MGS
\\PBpbSamba
\\PB\markHomeDirectories
\\PB\MainPrinterMainPrinter
\\PB\ADMIN$IPCService(pbSamba)
\\PB\IPC$IPCService(pbSamba)
\\PB\tmpmgstemp
Intheprecedingoutput,MGSisthenameoftheworkgroup,
PBisthenameoftheWindowsmachine,markandtmpare
directoryshares,andMainPrinterisasharedprinter.
Workgroupandmachinenamesarealwaysshownincapitals.
Refertothesmbtreemanpageformoreinformation.
smbclient:ConnectstoWindowsShares
Thesmbclientutilityfunctionssimilarlytoftp(page601)and
connectstoaWindowsshare;however,smbclientusesLinux-
styleforwardslashes(/)aspathseparatorsratherthan
Windows-stylebackslashes(\).Thenextexampleconnectsto
oneofthesharesdisplayedintheprecedingexample:
$smbclient//PB/mark
Password:
Domain=[PB]OS=[Unix]Server=[Samba3.0.10-1.fc2]
smb:\>ls
.D0WedFeb2215:10:032006
..D0MonFeb612:40:172006
.kdeDH0TueFeb722:24:172006
.xemacsDH0MonFeb610:12:452006
.bash_logoutH24TueOct2506:15:042005
.bash_profileH191TueOct2506:15:042005
.bashrcH124TueOct2506:15:042005
...
Youcanusemostftpcommandsfromsmbclient.Referto"Tutorial
Session"onpage604forsomeexamplesorgivethecommand
helptodisplayalistofcommands.
BrowsingWindowsNetworks
BrowsingWindowssharesusingsmbtreeandsmbclientisquite
awkwardcomparedwiththeeaseofbrowsinganetworkfrom
Windows;GnomeandKDEprovidemoreuser-friendly
alternatives.FromeitherKonquerororNautilus(theKDEand
Gnomefilemanagers),entersmb:/inthelocationbarto
browsetheWindowssharesonthenetwork.
BothKonquerorandNautilususevirtualfilesystemadd-ons,
whicharepartoftherespectivedesktopenvironmentsandnot
partofthenativeLinuxsystem.Asaconsequence,onlynative
GnomeorKDEapplicationscanopenfilesonremoteshares;
normalLinuxprogramscannot.Forexample,geditandkeditwill
beabletoopenfilesonremoteshares,whileOpenOffice,
mplayer,andxeditcannot.
MountingWindowsShares
Themountutility(page466)withatcifsoptionmountsa
WindowsshareasifitwereaLinuxdirectoryhierarchy.See
page1024formoreinformationontheCIFSprotocol.When
youmountaWindowsshare,youcanwritetothefilesonthe
share;youcannotwritetofilesonashareusingsmbclient.
AmountcommandthatmountsaWindowssharehasthe
followingsyntax:
#mount-tcifs//host/sharedir
wherehostisthenameofthesystemthattheshareison,
shareisthenameoftheWindowssharethatyouwantto
mount,anddiristheabsolutepathnameoftheLinuxdirectory
thatyouaremountingtheshareon(themountpoint).
Thefollowingcommand,whenrunasroot,mountsonthe
/sharedirectorytheshareusedintheprecedingexample.If
youomitthepasswordargument(whichyoumaywanttodo
forsecurityreasons),mountpromptsforit.
#mount-tcifs//PB/mark/share-ousername=mark,password=pizza
#ls/share
Desktopmansmbconfsmb.confsmbout
httpd.confNVIDIA-Linux-x86-1.0-5336-pkg1.runsmbholdx
Youcanusetheuid,file_mode,anddir_modemountoptions
withtypecifsfilesystemstoestablishownershipand
permissionsofmountedfiles.
#mount-tcifs//PB/mark/share-ousername=mark,uid=mark,file_mode=0644,dir_mode=0755
Permissionsmustbeexpressedasoctalnumbersprecededbya
zero.Formoreinformationrefertothemount.cifsmanpage.
Troubleshooting
Sambaprovidesthreeutilitiesthatcanhelpyoutroubleshoota
connection:ThesmbstatusutilitydisplaysareportonopenSamba
connections;testparmchecksthesyntaxof
/etc/samba/smb.confanddisplaysitscontents;andtestprns
checksthevalidityofthenameofaprinter.
Thefollowingstepscanhelpyounarrowdowntheproblem
whenyoucannotgetSambatowork.
1. Restartthesmbdandnmbddaemons.Makesurethelast
twolinesofoutputendwithOK.
#/sbin/servicesmbrestart
ShuttingdownSMBservices:[OK]
ShuttingdownNMBservices:[OK]
StartingSMBservices:[OK]
StartingNMBservices:[OK]
testparm
2. Runtestparmtocheckthatthesmb.conffileissyntactically
correct:
$testparm
Loadsmbconfigfilesfrom/etc/samba/smb.conf
Processingsection"[homes]"
Processingsection"[printers]"
Processingsection"[tmp]"
LoadedservicesfileOK.
Serverrole:ROLE_STANDALONE
Pressentertoseeadumpofyourservicedefinitions
...
Ifyoumisspellakeywordinsmb.conf,yougetanerror
suchasthefollowing:
#testparm
Loadsmbconfigfilesfrom/etc/samba/smb.conf
Unknownparameterencountered:"workgruop"
Ignoringunknownparameter"workgruop"
...
ping
3. Useping(page365)frombothsidesoftheconnectionto
makesurethenetworkisup.
netview
4. FromaWindowscommandprompt,usenetviewtodisplaya
listofsharesavailablefromtheserver(pbinthis
example):
C:>netview\\pb
Sharedresourcesat\\pb
pbSamba
SharenameTypeUsedasComment
--------------------------------------------------------------------
MainPrinterPrintMainPrinter
markDisk(UNC)HomeDirectories
tmpDiskmgstemp
Thecommandcompletedsuccessfully.
netuse
5. TrytomapthedrivefromaWindowscommandprompt.
Thefollowingcommandattemptstomounttheshare
namedtmponpbasdriveX:
C:>netusex:\\pb\tmp
Thecommandcompletedsuccessfully.
nmblookup
6. Fromtheserver,querythenmbdserver,usingthespecial
name__SAMBA__fortheserver'sNetBIOSname.Thed2
optionturnsthedebuggeronatlevel2,whichgeneratesa
moderateamountofoutput:
$nmblookup-d2-Bpb__SAMBA__
addedinterfaceip=192.168.0.10bcast=192.168.0.255
nmask=255.255.255.0
querying__SAMBA__on192.168.0.10
Gotapositivenamequeryresponsefrom192.168.0.10(192.168.0.10)
192.168.0.10__SAMBA__<00>
nmblookup
7. Fromtheserver,querythenmbdserverfortheclient's
NetBIOSname.(ThemachinenamedjamistheWindows
client.)
$nmblookup-Bjam\*
querying*on192.168.0.9
192.168.0.9*<00>
OmittheBjamoptiontoqueryforallNetBIOSnames.
smbclient
8. Fromtheserver,usesmbclientwiththeLoptiontogenerate
alistofsharesofferedbytheserver:
$smbclient-Lpb
Password:
Domain=[PB]OS=[Unix]Server=[Samba3.0.10-1.fc2]
SharenameTypeComment
--------------------
tmpDiskmgstemp
IPC$IPCIPCService(pbSamba)
ADMIN$IPCIPCService(pbSamba)
MainPrinterPrinterMainPrinter
markDiskHomeDirectories
Domain=[PB]OS=[Unix]Server=[Samba3.0.10-1.fc2]
ServerComment
----------------
WorkgroupMaster
----------------
MGSTUNAER
nmblookup
9. Toqueryforthemasterbrowserfromtheserver,run
nmblookupwiththeMoptionfollowedbythenameofthe
workgroup:
$nmblookup-MMGS
queryingMGSon192.168.0.255
192.168.0.8MGS<1d>
ChapterSummary
SambaisasuiteofprogramsthatenablesLinuxandWindows
tosharedirectoriesandprinters.Adirectoryorprinterthatis
sharedbetweenLinuxandWindowssystemsiscalledashare.
ToaccessashareonaLinuxsystem,aWindowsusermust
supplyausernameandpassword.Usernamesmustcorrespond
toLinuxusernameseitherdirectlyorasmappedbythe
/etc/samba/smbusersfile.Sambapasswordsaregenerated
bysmbpasswdandkeptin/etc/samba/smbpasswd.
ThemainSambaconfigurationfileis/etc/samba/smb.conf,
whichyoucaneditusingatexteditor,swat(aWeb-based
administrationutility),orsystem-config-samba(aminimal-
configurationGUI).Theswatutilityisapowerfulconfiguration
toolthatprovidesintegratedonlinedocumentationandclickable
defaultvaluestohelpyousetupSamba.
FromaWindowsmachine,youcanaccessashareonaLinux
SambaserverbyopeningMyComputerorExplorerand,inthe
Addresstextbox,entering\\followedbythenameofthe
server.Windowsdisplaysthesharesontheserverandyoucan
workwiththemasthoughtheywereWindowsfiles.
FromaLinuxsystem,youcanuseanyofseveralSambatools
toaccessWindowsshares.Thesetoolsincludesmbtree(displays
shares),smbclient(similartoftp),andmountwiththetcifsoption
(mountsshares).Inaddition,youcanentersmb:/inthe
locationbarofKonquerororNautilusandbrowsetheshares.
Exercises
1. WhichtwodaemonsarepartoftheSambasuite?Whatdoeseachdo?
2. WhatstepsarerequiredformappingaWindowsusertoaLinuxuser?
3. Howwouldyouallowaccesstoswatonlyfrommachinesonthe192.168.1.0/8
subnet?
4. Whatisthepurposeofthe[homes]share?
AdvancedExercises
5. DescribehowSamba'shandlingofusersdiffersfromthatofNFS.
6.
Whichconfigurationchangeswouldyouneedtoapplytoroutersifyouwantedto
allowSMB/CIFSbrowsingacrossmultiplesubnetswithoutconfiguringmaster
browsers?
7. Howcouldyouuseswatsecurelyfromaremotelocation?
8. WINSresolutionallowshoststodefinetheirownnames.Suggestawaytouse
Sambatoassignnamesfromacentralizedlist.
24.DNS/BIND:TrackingDomainNames
andAddresses
INTHISCHAPTER
JumpStartI:SettingUpaDNSCache 733
JumpStartII:SettingUpaDomainUsingsystem-config-bind
(FEDORA)
734
SettingUpBIND 739
Troubleshooting 751
AFull-FunctionedNameserver 752
ASlaveServer 756
ASplitHorizonServer 757
DNS(DomainNameSystem)mapsdomainnamestoIP
addresses,andviceversa.Itreducestheneedforhumansto
workwithIPaddresses,which,withtheintroductionofIPv6,
arecomplex.TheDNSspecificationdefinesasecure,general-
purposedatabasethatholdsInternethostinformation.Italso
specifiesaprotocolthatisusedtoexchangethisinformation.
Further,DNSdefineslibraryroutinesthatimplementthe
protocol.Finally,DNSprovidesameansforroutingemail.
UnderDNS,nameserversworkwithclients,calledresolvers,to
distributehostinformationintheformofresourcerecordsina
timelymannerasneeded.
ThischapterdescribesBIND(BerkeleyInternetNameDomain)
version9,apopularopen-sourceimplementationofDNS.Part
oftheRedHatLinuxdistribution,BINDincludestheDNSserver
daemon(named),aDNSresolverlibrary,andtoolsforworking
withDNS.AlthoughDNScanbeusedforprivatenetworks,this
chaptercoversDNSasusedbytheInternet.
IntroductiontoDNS
YounormallyuseDNSwhenyoudisplayaWebpage.For
example,todisplayRedHat'shomepage,youenteritsname,
www.redhat.com,inabrowserandthebrowserdisplaysthe
pageyouwant.YouneverenterorseetheIPaddressforthe
displayedpage.However,withouttheIPaddress,thebrowser
couldnotdisplaythepage.DNSworksbehindthescenesto
findtheIPaddresswhenyouenterthenameinthebrowser.
TheDNSdatabaseis
Hierarchical,sothatitprovidesquickresponsesto
queries:DNShasaroot,branches,andnodes.
Distributed,sothatitoffersfastaccesstoservers.The
DNSdatabaseisspreadacrossthousandsofsystems
worldwide;eachsystemisreferredtoasaDNSserver(ora
domainserverornameserver).
Replicated,toenhancereliability.Becausemanysystems
holdthesameinformation,whensomesystemsfail,DNS
doesnotstopfunctioning.
Asimplemented,DNSis
Secure,sothatyourbrowseroremailisdirectedtothe
correctlocation.
Flexible,sothatitcanadapttonewnames,deleted
names,andnameswhoseinformationchanges.
Fast,sothatInternetconnectionsarenotdelayedbyslow
DNSlookups.
History
ThemappingthatDNSdoeswasoriginallydonestaticallyina
/etc/hostsfile(page452)oneachsystemonanetwork.
SmallLANsstillmakeuseofthisfile.Asnetworksspecifically
theInternetgrew,adynamicmappingsystemwasrequired.
DNSwasspecifiedin1983andBINDbecamepartofBSDin
1985.
Security
BINDisbyfarthemostpopularimplementationofaDNS.
However,recentlyconcernsaboutitssecurityhavearisen.You
maywanttorunBINDinsideachrootjail(page750)orunder
SELinux(page400)andusetransactionsignatures(TSIG,page
748)toimprovesecurity.
hostanddig
Thehostanddigutilities(page368)queryDNSservers.Thehost
utilityissimpler,iseasiertouse,andreturnslessinformation
thandig.ThischapterusesbothtoolstoexploreDNS.
Nodes,Domains,andSubdomains
EachnodeinthehierarchicalDNSdatabaseiscalledadomain
andislabeledwitha(domain)name.AswiththeLinuxfile
structure,thenodeatthetopoftheDNShierarchyiscalledthe
rootnodeorrootdomain.WhiletheLinuxfilestructure
separatesthenodes(directoryandordinaryfiles)withslashes
(/)andlabelstherootnode(directory)withaslash,theDNS
structureusesperiods(Figure24-1).
Figure24-1.TheDNSdomainstructure
[Viewfullsizeimage]
YoureadanabsolutepathnameinaLinuxfilesystemfromleft
toright:Itstartswiththerootdirectory(/)attheleftand,as
youreadtotheright,describesthepathtothefilebeing
identified(forexample,/var/named/named.ca).Unlikea
Linuxpathname,youreadaDNSdomainnamefromrightto
left:Itstartswiththerootdomainattheright(representedby
aperiod[.])and,asyoureadtotheleft,worksitswaydown
throughthetop-levelandsecond-leveldomainstoasubdomain
orhost.Frequentlythenameoftherootdomain(theperiodat
theright)isomittedfromadomainname.Thetermdomain
refersbothtoasinglenodeintheDNSdomainstructureandto
acatenated,period-separatedlist(path)ofdomainnamesthat
describesthelocationofadomain.
FQDN
Afullyqualifieddomainname(FQDN)istheDNSequivalentof
afilesystem'sabsolutepathname:Itisapointerthatpositively
locatesadomainontheInternet.Justasyou(andLinux)can
identifyanabsolutepathnamebyitsleadingslash(/)that
namestherootdirectory,soanFQDNcanbeidentifiedbyits
trailingperiod(.)thatnamestherootdomain(Figure24-2).
Figure24-2.Afullyqualifieddomainname
(FQDN)
Resolver
Theresolvercomprisestheroutinesthatturnanunqualified
domainnameintoanFQDNthatispassedtoDNStobemapped
toanIPaddress.Theresolvercanappendseveraldomains,one
atatime,toanunqualifieddomainname,producingseveral
FQDNsthatitpasses,oneatatime,toDNS.ForeachFQDN,
DNSreportssuccess(itfoundtheFQDNandisreturningthe
correspondingIPaddress)orfailure(theFQDNdoesnotexist).
Theresolveralwaysappendstherootdomain(.)toan
unqualifieddomainnamefirst,allowingyoutotype
www.redhat.cominsteadofwww.redhat.com.(including
thetrailingperiod)inabrowser.Youcanspecifyotherdomains
fortheresolvertotryiftherootdomainfails.Putthedomain
names,intheorderyouwantthemtried,afterthesearch
keywordin/etc/resolv.conf(page455).Forexample,ifyour
searchdomainsincluderedhat.com.,thenthedomainsrhn
andrhn.redhat.com.resolvetothesameaddress.
Subdomains
Eachnodeinthedomainhierarchyisadomain.Eachdomain
thathasaparent(thatis,everydomainexcepttheroot
domain)isalsoasubdomain,regardlessofwhetherithas
children.Allsubdomainscanresolvetohostseventhosewith
children.Forexample,theredhat.com.domainresolvestothe
hostthatservestheRedHatWebsite,withoutpreventingits
childrendomainssuchasfedora.redhat.com.fromresolving.
TheleftmostpartofanFQDNisoftencalledthehostname.
Hostnames
Inthepast,hostnamescouldcontainonlycharactersfromthe
setaz,AZ,09,and.AsofMarch2004,however,hostnames
canincludevariousaccents,umlauts,andsoon
(www.switch.ch/id/idn).DNSconsidersuppercaseand
lowercaseletterstobethesame(itisnotcasesensitive),so
www.sobell.comisthesameasWWW.sObEll.coM.
Zones
Foradministrativepurposes,domainsaregroupedintozones
thatextenddownwardfromadomain(Figure24-3).Asingle
DNSserverisresponsiblefor(holdstheinformationrequiredto
resolve)alldomainswithinazone.TheDNSserverforazone
alsoholdspointerstoDNSserversthatareresponsibleforthe
zonesimmediatelybelowthezoneitisresponsiblefor.
Informationaboutzonesoriginatesinzonefiles,onezoneper
file.
Figure24-3.DNSstructureshowingzones
[Viewfullsizeimage]
Rootdomain
Thehighestzone,theonecontainingtherootdomain,doesnot
containanyhosts.Instead,thisdomaindelegatestotheDNS
serversforthetop-leveldomains(Figure24-1,page721).
Authority
EachzonehasatleastoneauthoritativeDNSserver.Thisserver
holdsallinformationaboutthezone.ADNSqueryreturns
informationaboutadomainandspecifieswhichDNSserveris
authoritativeforthatdomain.
DNSemploysahierarchicalstructuretokeeptrackofnames
andauthority.Atthetoporrootofthestructureistheroot
domain,whichemploys13authoritativenameservers.These
aretheonlyserversthatareauthoritativefortherootandtop-
leveldomains.
Delegationofauthority
WhenreferringtoDNS,thetermdelegationmeansdelegation
ofauthority.ICANN(InternetCorporationforAssignedNames
andNumbers,www.icann.org)delegatesauthoritytotheroot
andtop-leveldomains.Inotherwords,ICANNsayswhich
serversareauthoritativeforthesedomains.Authorityis
delegatedtoeachdomainbelowthetop-leveldomainsbythe
authoritativeserveratthenext-higher-leveldomain.ICANNis
notauthoritativeformostsecond-leveldomains.Forexample,
RedHatisauthoritativefortheredhat.comdomain.This
schemeofdelegatingauthorityallowsforlocalcontrolover
segmentsoftheDNSdatabasewhilemakingallsegments
availabletothepublic.
Queries
Iterativequery
TherearetwotypesofDNSqueries:iterativeandrecursive.[1]
AniterativequerysendsadomainnametoaDNSserverand
askstheservertoreturneithertheIPaddressofthedomainor
thenameoftheDNSserverthatisauthoritativeforthedomain
oroneofitsparents:Theserverdoesnotqueryotherservers
whenseekingananswer.Nameserverstypicallysendeachother
iterativequeries.
[1]Thereisathirdtypeofquerythatisnotcoveredinthisbook:inverse.Aninversequery
providesadomainnamegivenaresourcerecord.Reversenameresolution(page729),
notaninversequery,isusedtoqueryforadomainnamegivenanIPaddress.
Recursivequery
ArecursivequerysendsadomainnametoaDNSserverand
askstheservertoreturntheIPaddressofthedomain:The
servermayneedtoqueryotherserverstogettheanswer.Both
typesofqueriescanfail,inwhichcasetheserverreturnsa
messagesayingitisunabletolocatethedomain.
Whenaclient,suchasabrowser,needstheIPaddressthat
correspondstoadomainname,theclientqueriesaresolver.
MostresolversarequitesimpleandrequireaDNSservertodo
mostofthework:Thatis,theysendrecursivequeries.The
resolvercommunicateswithasingleDNSserver,whichcan
performmultipleiterativequeriesinresponsetotheresolver's
recursivequery.
AllDNSserversmustansweriterativequeries.DNSserverscan
alsobesetuptoanswerrecursivequeries.ADNSserverthatis
notsetuptoanswerrecursivequeriestreatsarecursivequery
asthoughitisaniterativequery.
InFigure24-4,theresolveronaclientsystemistryingto
discovertheaddressoftheserverftp.site1.example.com.on
thenetworkwiththeDNSlayoutshowninFigure24-3onpage
723.Theresolverontheclientsendsarecursivequerytoits
primaryDNSserver.Thisserverinterrogatestherootserver
andoneadditionalserverforeachzoneuntilitreceivesan
answer,whichitreturnstotheresolverontheclient.In
practice,thequerywouldnotstartwiththerootserverbecause
mostserversusuallyhavethelocationoftheauthoritative
nameserverforthecom.domainstoredincache(memory).
Figure24-4.Arecursivequerythatstartsseveral
iterativequeriestofindtheanswer
[Viewfullsizeimage]
Servers
TherearethreemaintypesofDNSservers:primary(master),
secondary(slave),andcaching-only.
Aprimarymasterserver,alsocalledaprimaryserveror
masterserver,istheauthoritativeserverthatholdsthe
mastercopyofzonedata.Itcopiesinformationfromthe
zoneormasterfile,alocalfilethattheserveradministrator
maintains.Forsecurityandefficiency,aprimarymaster
servershouldprovideiterativeanswersonly.Aprimary
masterserverthatprovidesrecursiveanswersismore
easilysubvertedbyaDoSattack(page1030)thanonethat
providesiterativeanswersonly.
Slaveservers,alsocalledsecondaryservers,are
authoritativeandcopyzoneinformationfromtheprimary
masterserveroranotherslaveserver.Onsomesystems,
wheninformationontheprimarymasterserverchanges,
theprimarymasterserversendsamessagetotheslave
servers.Whenaslavereceivessuchamessage,itusesa
processcalledzonetransfertocopythenewzone
informationfromthemasterservertoitself.
DNScaches,alsocalledcaching-onlyservers,arenot
authoritative.Theseserversstoreanswerstoprevious
queriesincache(memory).WhenaDNScachereceivesa
query,itanswersitfromcacheifitcan.IftheDNScache
doesnothavetheanswerincache,itforwardsthequeryto
anauthoritativeserver.
Itispossiblebutforreasonsofsecuritynotrecommendedforthe
sameservertobetheprimarymasterserver(authoritative)for
somezonesandaDNScacheforothers.Whenthesameserver
actsasbothaDNScacheandamasterserver,ifamalicious
localuserormalfunctioningresolveronthelocalnetworkfloods
theDNScachewithmoretrafficthanitcanhandle(aDoS
attack),usersmaybepreventedfromaccessingthepublic
serversthattheprimarymasterserverhandles.Conversely,if
theauthoritativeserveriscompromised,theattackercan
subvertalltrafficleavingthenetwork.
ResourceRecords
Informationaboutnodes(domains)intheDNSdatabaseis
storedinresourcerecords.Resourcerecordsarekeptinzone
files(page741).Thezonethataresourcerecordpertainstois
definedbythezonefilethatcontainstheresourcerecord.The
zoneisnamedinthenamed.conffile(page739)that
referencesthezonefile.
Aresourcerecordhasthefollowingfields:
NameThedomainnameorIPaddress
TTLTimetolive(notinallresourcerecords;seepage
1060)
ClassAlwaysINforInternet(theonlyclassthatDNS
supports)
TypeRecordtype(discussedinthenextsection)
DataVarieswithrecordtype
IftheNamefieldismissing,theresourcerecordinheritsthe
namefromthepreviousresourcerecordinthesamefile.
Cachedresourcerecordsbecomeout-of-datewhenthe
informationintherecordchangesontheauthoritativeserver.
TheTTLfieldindicatesthemaximumtimeaservermaykeepa
recordincachebeforecheckingwhetheraneweroneis
available.Typically,theTTLisontheorderofdays.ATTLof0
meansthattheresourcerecordshouldnotbecached.
Morethan30typesofresourcerecordsexist,rangingfrom
commontypes,suchasaddressrecordsthatstoretheaddress
ofahost,tothosethatcontaingeographicalinformation.The
followingparagraphsdescribethetypesofresourcerecordsyou
aremostlikelytoencounter.
A
IPv4AddressMapsadomainnametotheIPv4addressofa
host.Theremustbeatleastoneaddressrecordforeach
domain;multipleaddressrecordscanpointtothesameIP
address.TheNamefieldholdsthedomainname,whichis
assumedtobeinthesamezoneasthedomain.TheDatafield
holdstheIPaddressassociatedwiththename.Thefollowing
addressresourcerecordmapsthensdomaininthezoneto
192.168.0.1:
nsINA192.168.0.1
AAAA
IPv6AddressMapsadomainnametotheIPv6addressofa
host.Thefollowingaddressresourcerecordmapsthens
domaininthezonetoanIPv6address:
nsINAAAA2001:630:d0:131:a00:20ff:feb5:ef1e
CNAME
CanonicalNameMapsanaliasornicknametoadomain
name.TheNamefieldholdsthealiasornickname;theData
fieldholdstheofficialorcanonicalname.CNAMEisusefulfor
specifyinganeasy-to-remembernameormultiplenamesfor
thesamedomain.Itisalsousefulwhenasystemchanges
namesorIPaddresses.Inthiscasethealiascanpointtothe
realnamethatmustresolvetoanIPaddress.
WhenaqueryreturnsaCNAME,aclientorDNStoolperformsa
DNSlookuponthedomainnamereturnedwiththeCNAME.Itis
acceptabletoprovidemultiplelevelsofCNAMErecords.The
followingresourcerecordmapsftpinthezoneto
www.sam.net.:
ftpINCNAMEwww.sam.net.
MX
MailExchangeSpecifiesadestinationformailaddressedto
thedomain.MXrecordsmustalwayspointtoA(orAAAA)
records.TheNamefieldholdsthedomainname,whichis
assumedtobeinthezone;theDatafieldholdsthenameofa
mailserverprecededbyitspriority.UnlikeArecords,MX
recordscontainaprioritynumberthatallowsmaildelivery
agentstofallbacktoabackupserverincasetheprimary
serverisdown.Severalmailserverscanberankedinpriority
order,wherethelowestnumberhasthehighestpriority.DNS
selectsrandomlyfromamongmailserverswiththesame
priority.Thefollowingresourcerecordsforwardmailsentto
speedyinthezonefirsttomailinthezoneandthen,ifthat
fails,tomail.sam.net..ThevalueofspeedyintheNamefield
onthesecondlineisimplicit.
speedyMX10mail
MX20mail.sam.net.
NS
NameserverSpecifiesthenameofthesystemthatprovides
domainservice(DNSrecords)forthedomain.TheNamefield
holdsthedomainname;theDatafieldholdsthenameofthe
DNSserver.EachdomainmusthaveatleastoneNSrecord.
DNSserversdonotneedtoresideinthedomainand,infact,it
isbetterifatleastonedoesnot.Thesystemnamensis
frequentlyusedtospecifyanameserver,butthisnameisnot
requiredanddoesnothaveanysignificancebeyondassisting
humansinidentifyinganameserver.Thefollowingresource
recordspecifiesns.max.net.asanameserverforpeachinthe
zone:
peachNSns.max.net.
PTR
PointerMapsanIPaddresstoadomainnameandisusedfor
reversenameresolution.TheNamefieldholdstheIPaddress;
theDatafieldholdsthedomainname.DonotusePTRresource
recordswithaliases.Thefollowingresourcerecordmaps3ina
reversezone(forexample,3inthe0.168.192.in-addr.arpa
zoneis192.168.0.3)tograpeinthezone:
3INPTRgrape
Formoreinformationreferto"ReverseNameResolution"on
page729.
SOA
StartofAuthorityDesignatesthestartofazone.Eachzone
musthaveexactlyoneSOArecord.Anauthoritativeserver
maintainstheSOArecordforthezoneitisauthoritativefor.
AllzonefilesmusthaveoneSOAresourcerecord,whichmust
bethefirstresourcerecordinthefile.TheNamefieldholdsthe
nameofthedomainatthestartofthezone.TheDatafield
holdsthenameofthehostthedatawascreatedon,theemail
addressofthepersonresponsibleforthezone,andthe
followinginformationenclosedwithinparentheses(theopening
parenthesismustappearonthefirstphysicallineofanSOA
record):
serialAvalueintherange12,147,483,647.Achangeinthis
numberindicatesthatthezonedatahaschanged.By
convention,thisfieldissettothestringyyyymmddnn(year,
month,day,changenumber).Alongwiththedate,thefinaltwo
digitsthatis,thechangenumbershouldbeincrementedeach
timeyouchangetheSOArecord.
refreshTheelapsedtimeafterwhichtheprimarymaster
servernotifiesslave(secondary)serverstorefreshtherecord;
thetimebetweenupdates.
retryThetimetowaitafterarefreshfailsbeforetryingto
refreshagain.
expiryTheelapsedtimeafterwhichthezoneisnolonger
authoritativeandtherootserversmustbequeried.Theexpiry
appliestoslaveserversonly.
minimumThenegativecachingTTL,whichistheamountof
timethatanonexistentdomainerror(NXDOMAIN)canbeheld
inaslaveserver'scache.AnegativecachingTTListhesameas
anormalTTLexceptthatitappliestodomainsthatdonotexist
ratherthantodomainsthatdoexist.
The$TTLdirective(page742)specifiesthedefaultzoneTTL
(themaximumamountoftimethatdatastaysinaslave
server'scache).Jointly,thedefaultzoneTTLandthenegative
cachingTTLencompassalltypesofrepliestheservercan
generate.
ThefollowingtwoSOAresourcerecordsareequivalent:
@INSOAns.zach.net.mgs@sobell.com.(20051112478H2H4W1D)
@INSOAns.zach.net.mgs@sobell.com.(
2005111247;serial
8H;refresh
2H;retry
4W;expire
1D);minimum
Thesecondformatismorereadablebecauseofitslayoutand
thecomments.Theatsymbol(@)atthestartoftheSOA
resourcerecordstandsforthezonename,alsocalledthe
origin,asspecifiedinthenamed.conffile.Becausethe
named.conffilespecifiesthezonenametobezach.net,you
couldrewritethefirstlineasfollows:
zach.net.INSOAns.zach.net.mgs@sobell.com.(
Thehostutilityreturnssomethingclosertothefirstformatwith
eachofthetimesspecifiedinseconds:
$host-tsoazach.net
zach.net.SOAns.zach.net.mgs\@sobell.com.03111288007200241920086400
TXT
TextAssociatesacharacterstringwithadomain.TheName
fieldholdsthedomainname.Thedatafieldcancontainupto
256charactersandmustbeenclosedwithinquotationmarks.
TXTrecordscancontainanyarbitrarytextvalue.Aswellas
generalinformation,theycanbeusedforthingssuchaspublic
keydistribution.FollowingisaTXTresourcerecordthat
specifiesacompanyname:
zach.netINTXT"SobellAssociatesInc."
DNSQueryandResponse
Query
ADNSqueryhasthreeparts:
1. NameDomainname,FQDN,orIPaddressforreversename
resolution
2. TypeTypeofrecordrequested(page725)
3. ClassAlwaysINforInternetclass
Cache
MostDNSserversstoreincachememorythequeryresponses
fromotherDNSservers.WhenaDNSserverreceivesaquery,it
firsttriestoresolvethequeryfromitscache.Failingthat,the
servermayqueryotherserverstogetananswer.
BecauseDNSusescache,whenyoumakeachangetoaDNS
record,thechangetakestimesometimesamatterofdaysto
propagatethroughtheDNShierarchy.
Response
ADNSmessagethatissentinresponsetoaqueryhasthe
followingstructure:
HeaderrecordInformationaboutthismessage
QueryrecordRepeatsthequery
AnswerrecordsResourcerecordsthatanswerthequery
AuthorityrecordsResourcerecordsforserversthathave
authorityfortheanswers
AdditionalrecordsAdditionalresourcerecords,suchasNS
records
Thedigutilitydoesnotconsult/etc/nsswitch.conf(page435)
todeterminewhichservertoquery.Thefollowingexampleuses
digtoqueryaDNSserver:
$digfedora.redhat.com
...
;;QUESTIONSECTION:
;fedora.redhat.com.INA
;;ANSWERSECTION:
fedora.redhat.com.600INCNAMEwww.redhat.com.
www.redhat.com.330INA209.132.177.50
;;AUTHORITYSECTION:
redhat.com.409INNSns1.redhat.com.
redhat.com.409INNSns2.redhat.com.
redhat.com.409INNSns3.redhat.com.
;;ADDITIONALSECTION:
ns1.redhat.com.300INA66.187.233.210
ns2.redhat.com.600INA66.187.224.210
ns3.redhat.com.600INA66.187.229.10
...
ReverseNameResolution
Inadditiontonormalorforwardnameresolution,DNSprovides
reversenameresolution,alsoreferredtoasinversemappingor
reversemapping,sothatyoucanlookupdomainnamesgiven
anIPaddress.BecauseresourcerecordsintheforwardDNS
databaseareindexedhierarchicallybydomainname,DNS
cannotperformanefficientsearchbyIPaddressonthis
database.
DNSimplementsreversenameresolutionbymeansofaspecial
domainnamedin-addr.arpa(IPv4)orip6.arpa(IPv6).
ResourcerecordsinthesedomainshaveNamefieldsthathold
IPaddresses;therecordsareindexedhierarchicallybyIP
address.TheDatafieldsholdtheFQDNthatcorrespondstothe
IPaddress.
Reversenameresolutioncanverifythatsomeoneiswhohe
saysheisoratleastisfromthedomainhesaysheisfrom.In
general,itallowsaservertoretrieveandrecordthedomain
namesoftheclientsitprovidesservicesto.Forexample,
legitimatemailcontainsthedomainofthesenderandtheIP
addressofthesendingmachine.Amailservercanverifythe
stateddomainofasenderbycheckingthedomainassociated
withtheIPaddress.Reversenameresolutionisalsousedby
anonymousFTPserverstoverifythatadomainspecifiedinan
emailaddressusedasapasswordislegitimate.
Forexample,todeterminethedomainnamethatcorresponds
toanIPaddressof209.132.177.110,aresolverwouldquery
DNSforinformationaboutthedomainnamed
110.177.132.209.in-addr.arpa(Figure24-5,nextpage).
Figure24-5.Reversenameresolutionandthein-
addr.arpadomain
ThefollowingexampleusesdigtoqueryDNSfortheIPaddress
thatcorrespondstorhn.redhat.com,whichis209.132.177.110.
Thesecondcommandlineusesthedigutilitytoquerythesame
IPaddress,reversed,andappendedwith.in-addr.arpa:
110.177.132.209.in-addr.arpatodisplayaPTRresourcerecord
(page727).Thedataportionoftheresultantresourcerecordis
thedomainnamefromtheoriginalquery:rhn.redhat.com.
$digrhn.redhat.com
...
;;QUESTIONSECTION:
;rhn.redhat.com.INA
;;ANSWERSECTION:
rhn.redhat.com.60INA209.132.177.110
...
$dig110.177.132.209.in-addr.arpaPTR
...
;;QUESTIONSECTION:
;110.177.132.209.in-addr.arpa.INPTR
;;ANSWERSECTION:
110.177.132.209.in-addr.arpa.600INPTRrhn.redhat.com.
...
InsteadofreformattingtheIPaddressasinthepreceding
example,youcanusethexoptiontodigtoperformareverse
query:
$dig-x209.132.177.110
...
;;QUESTIONSECTION:
;110.177.132.209.in-addr.arpa.INPTR
;;ANSWERSECTION:
110.177.132.209.in-addr.arpa.456INPTRrhn.redhat.com.
...
Oryoucanjustusehost:
$host209.132.177.110
110.177.132.209.in-addr.arpadomainnamepointerrhn.redhat.com.
AboutDNS
ThissectiondiscusseshowDNSworksandprovidesresources
foradditionalinformationonDNS.
HowDNSWorks
ApplicationprogramsdonotissueDNSqueriesdirectlybut
ratherusethegethostbyname()systemcall.Howthesystem
comesupwiththecorrespondingIPaddressistransparentto
thecallingprogram.Thegethostbyname()callexaminesthe
hostslinein/etc/nsswitch.conffile(page435)todetermine
whichfilesitshouldexamineand/orwhichservicesitshould
queryandinwhatordertoobtaintheIPaddresscorresponding
toadomainname.WhenitneedstoqueryDNS,thelocal
system(i.e.,theDNSclient)queriestheDNSdatabaseby
callingtheresolverlibraryonthelocalsystem.Thiscallreturns
therequiredinformationtotheapplicationprogram.
Prerequisites
Installthefollowingpackages:
bind
bind-utils
bind-config(FEDORA,optional,usedtosetupacaching-
onlynameserver;seethefollowingcautionboxforan
importantnote)
caching-nameserver(RHEL,optional,usedtosetupa
caching-onlynameserver)
system-config-bind(FEDORA,optional)
bind-chroot(optional,usedtosetupBINDtorunina
chrootjail)
Runchkconfigtocausenamedtostartwhenthesystementers
multiusermode:
#/sbin/chkconfignamedon
Afteryouhaveconfigurednamed,startitwithservice:
#/sbin/servicenamedstart
Startingnamed:[OK]
Caution:Removecaching-nameserver
andinstallbind-config
ThereleasedversionofFedoraCore5,includingthe
versionontheDVDenclosedwiththisbook,includes
thecaching-nameserverpackage.
ShortlyafterFedoraCore5wasreleased,the
caching-nameserverpackagewasreplacedbythe
bind-configpackage.
Tofollowtheexamplesinthischapter,youmust
removethecaching-nameserverpackageand
installthebind-configpackage.Thefollowing
commandsuseyum(page478)toaccomplishthese
tasks.Inaddition,itmaybehelpfultoremoveor
rename/etc/named.confasshownbelow.
#yumremovecaching-nameserver
...
#yuminstallbind-config
...
#mv/etc/named.conf/etc/named.conf.old
Ifyoucannotordonotwanttoreplacethe
caching-nameserverpackage,readthepartsof
thischapterthatarelabeledRHELandthatdescribe
thenamed.caching-nameserver.conffile.
RHELincludesthecaching-nameserverpackage.
MoreInformation
DNSforRocketScientistsisanexcellentsitethatmakesgood
useoflinkstopresentinformationonDNSinaverydigestible
form.
Local
BindAdministratorReferenceManual
/usr/share/doc/bind*/arm/Bv9ARM.htmlorseethetip
"UsingthisJumpStart"onpage735.
Web
DNSforRocketScientistswww.zytrax.com/books/dns
BINDwww.isc.org/products/BIND
DNSsecuritywww.sans.org/rr/papers/index.php?id=1069
HOWTO
DNSHOWTO
Book
DNS&BIND,fourthedition,byAlbitz&Liu,O'Reilly&
Associates(April2001)
Notes
Firewall
ThenamedservernormallyacceptsqueriesonTCPandUDP
port53.Iftheserversystemisrunningafirewall,youneedto
opentheseports.ForinformationonusingtheRedHat
graphicalfirewalltool,see"OpeningOtherPorts"onpage768.
Formoregeneralinformation,seeChapter25,whichdetails
iptables.
SELinux
AccordingtotheRedHatnamedmanpage,thedefaultRedHat
SELinuxpolicyfornamedisverysecureandpreventsknown
BINDsecurityvulnerabilitiesfrombeingexploited.Thissetup
hassomelimitations,however.Refertothenamedmanpage
formoreinformation.
IfthesystemisrunningSELinuxwithatargetedpolicyandyou
wanttomodifytheSELinuxnamedsettings,youmustturnon
oneormoreoftheSELinuxsettingsundertheNameService
sectionasdisplayedbysystem-config-securitylevel(page402).
chrootjail
Thebind-chrootpackagesetsupnamedtoruninachrootjail.
Withthispackageinstalled,allfilesthatcontrolBINDare
locatedwithinthisjail.Inthiscasethefilenamesusedinthis
chapteraresymboliclinkstothefilesinthechrootjail.Seepage
750formoreinformation.
namedoptions
Seethecommentsinthe/etc/sysconfig/namedfilefor
informationaboutnamedoptionsthatyoucansetthere.One
ofthemostimportantoftheseoptionssetsthevalueofthe
ROOTDIRvariablethatcontrolsthelocationofthechrootjail
(page750)thatBINDrunsin.
named.conf(FEDORA)
Traditionally,namedlooksforconfigurationinformationinthe
/etc/named.conffile.Thecaching-onlynameserver,whichis
partofthebind-configpackage,placesnamedconfiguration
informationin/etc/named.caching-nameserver.conf.
Forthecaching-onlynameservertoworkwithoutanysetup,
andsothatnamedwillworknormallyifyoucreatea
/etc/named.conffile,theRedHatLinuxnamedinitscript
(/etc/rc.d/init.d/named)firstlooksforconfiguration
informationin/etc/named.conf.Ifthatfiledoesnotexist,it
looksforconfigurationinformationin/etc/named.caching-
nameserver.conf.
JumpStartI:SettingUpaDNSCache
Asexplainedearlier,aDNScacheisabridgebetweenaresolver
andauthoritativeDNSservers:Itisnotauthoritative;itsimply
storestheresultsofitsqueriesinmemory.MostISPsprovidea
DNScachefortheuseoftheircustomers.Settingupalocal
cachecanreducethetrafficbetweentheLANandtheoutside
worldandcanimproveresponsetimes.Whileitispossibleto
setupaDNScacheoneachsystemonaLAN,settingupa
singleDNScacheonaLANpreventsmultiplesystemsonthe
LANfromhavingtoqueryaremoteserverforthesame
information.
AfterinstallingBIND,includingthebind-configpackage(see
thecautionboxonpage732),youhavemostofacaching-only
nameserverreadytorun.Referto"ADNSCache"(page742)
foranexplanationofwhichfilesthisnameserverusesandhow
itworks.BeforeyoustarttheDNScache,putthefollowingline
in/etc/resolv.conf(page455),beforeanyothernameserver
lines:
nameserver127.0.0.1
Thislinetellstheresolvertousethelocalsystem(localhostor
127.0.0.1)astheprimarynameserver.Toexperimentwith
usingthelocalsystemastheonlynameserver,commentout
othernameserverlinesinresolv.confbyprecedingeachwitha
poundsign(#).
Finally,startthenameddaemonusingserviceasexplainedin
the"Prerequisites"section(page731).Referto
"Troubleshooting"onpage751forwaystocheckthattheDNS
cacheisworking.Oncenamedisrunning,youcanseethe
effectofthecachebyusingdigtolookuptheIPaddressof
www.redhat.com,aremotesystem:
$digwww.redhat.com
;<<>>DiG9.3.2<<>>www.redhat.com
;;globaloptions:printcmd
;;Gotanswer:
;;->>HEADER<<-opcode:QUERY,status:NOERROR,id:38263
;;flags:qrrdra;QUERY:1,ANSWER:1,AUTHORITY:3,ADDITIONAL:0
;;QUESTIONSECTION:
;www.redhat.com.INA
;;ANSWERSECTION:
www.redhat.com.60INA209.132.177.50
;;AUTHORITYSECTION:
redhat.com.600INNSns1.redhat.com.
redhat.com.600INNSns2.redhat.com.
redhat.com.600INNSns3.redhat.com.
;;Querytime:496msec
;;SERVER:127.0.0.1#53(127.0.0.1)
;;WHEN:WedMar2918:55:372006
;;MSGSIZErcvd:102
Thefourthlinefromthebottomshowsthatthequerytook496
milliseconds(aboutone-halfofasecond).Whenyourunthe
samequeryagain,itrunsmorequicklybecausetheDNScache
hassavedtheinformationinmemory:
$digwww.redhat.com
...
;;Querytime:2msec
;;SERVER:127.0.0.1#53(127.0.0.1)
;;WHEN:WedMar2918:55:432006
;;MSGSIZErcvd:102
JumpStartII:SettingUpaDomainUsing
system-config-bind(FEDORA)
TodisplaytheBINDConfigurationGUIwindow,entersystem-
config-bindonacommandline(Figure24-6).FromKDEselect
Mainmenu:Administration ServerSettings Domain
NameSystemorfromGNOMEselectSystem:
Administration ServerSettings DomainName
System.
Figure24-6.TheBINDConfigurationGUIwindow
[Viewfullsizeimage]
If/etc/named.confdoesnotexist,system-config-binddisplaysa
dialogboxthatinformsyouthatitisinstallingadefault
configuration.ClickOK.
Notes
The/etc/named.caching-nameserver.conffile,whichis
installedwiththeFEDORAbind-configpackage,isnot
recognizedbysystem-config-bindasanamedconfigurationfile.
See"named.conf"onpage733formoreinformationaboutthis
file.
Tip:UsingthisJumpStart
Thesystem-config-bindutilityisacomplextoolthatyou
mayfindhelpfulforsettingupBIND.Runthisutility
andclickHelp Manualonthemenubartodisplay
theRedHatmanualforthisutility.ClickHelp ISC
ARMtodisplaytheBIND9AdministratorReference
Manual.Youmaywanttoexperimentwiththisutility
afteryouhavesetuponeoftheserversdescribedat
theendofthischapter,asitsconfiguration
informationmaymakemoresenseafteryougo
throughtheprocessofmanuallyconfiguringBIND.
Thissectionexplainshowtousesystem-config-bindbut
doesnotgointodetailaboutwhateachofthefiles
andsettingsdoes;thatinformationiscovered
elsewhereinthischapter.
Eachzonefilethatsystem-config-bindcreateshasafilename
extensionof.db.
Becausethewindowsdisplayedbysystem-config-bindcontainalot
ofinformation,youmayfindithelpfultoexpandormaximize
thesewindowssothatyoucanviewtheinformationmore
easily.
Thesystem-config-bindutilitycreatesfilesinthe
/var/named/chrootdirectoryhierarchysothatyoucanrun
namedinachrootjail.Seepage750formoreinformation.
UsingtheBINDConfigurationGUIWindow
Right-clickonanobject(line)intheBINDConfigurationGUI
windowtodisplayapop-upcontextmenu.Thismenualways
hasanEditselection,whichdisplaysawindowinwhichyoucan
editinformationpertainingtotheobjectyouclickedon.Youcan
displaythesamewindowbydouble-clickingontheobjectorby
highlightingtheobjectandclickingPropertiesontheIcon
menu.Thispop-upmenualsoalwayshasanAddselectionthat
displaysasubmenuwithchoicesappropriatetotheobjectyou
areworkingwith.Figure24-7(nextpage)showsthepop-up
menufortheDNSServerobjectalongwiththeAddsubmenu.
Figure24-7.TheBINDConfigurationGUIwindow
witharight-clickmenu
[Viewfullsizeimage]
IntheBINDConfigurationGUIwindow,atriangleattheleftend
ofalineindicatesthattheobjectholdsotherobjects.Clicka
trianglesothatitpointsdowntoexpandanentry.Clickitso
thatitpointstotherighttocollapseanentry.
SettingUpaDomainServer
HighlightDNSServerintheBINDConfigurationGUIwindow
andclickNew Zoneonthetoolbar(orright-clickandselect
Add Zone)toaddanewzone(page722)anditsassociated
nameserver.Inresponse,system-config-binddisplaysthefirstNew
Zonewindow(Figure24-8),whichallowsyoutospecify
informationaboutthezoneyouaresettingup.
Figure24-8.ThefirstNewZonewindow
WiththeClasscomboboxdisplayingINInternet,clickOK
underthisbox.
NextselecttheorigintypefromthecomboboxunderOrigin
Type.ThemostcommonchoicesareForwardorIPV4Reverse.
ClickOKunderthisbox.Assumingyouselectedaforwardzone,
theForwardZoneOrigintextboxreplacestheorigintype
information.Enterthedomainnameofthezone,includinga
trailingperiod,inthetextbox.
Finallyselectthetypeofzoneyouwanttosetupbyclickingthe
comboboxintheZoneTypeframe.Youcanselectfrommaster,
slave,forward,hint,andothertypesofzones.Referto
"Servers"page724andtypeonpage741forinformationon
typesofzones.
AfteryoumakeyourselectionsandclickOK,system-config-bind
displaysthesecondNewZonewindow(Figure24-9).This
windowenablesyoutosetupSOAinformationforthezone.
Referto"SOA"onpage727forinformationaboutthefieldsin
theSOArecord,includingtheserialnumberandthevarious
times(refreshintervals).Inthiswindow,theauthoritative
(primary)nameserver(page724)defaultstothelocalsystem
andtheemailaddressofthepersonresponsibleforthezone
defaultstorootonthelocalsystem.Ifyouenternamesthatdo
notendwithaperiodinthesetextboxes,system-config-bind
appendsthedomainnameofthezonetothenameyouhave
entered.Changethevaluesinthiswindowasnecessary.All
zonefilesthatsystem-config-bindcreateshaveafilename
extensionof.dbbydefault.Thedefaultfilenameforthezone
fileisthenameofthedomainyouaresettingupwithan
extensionof.db.ClickOKtoclosethewindowwhenyouare
donemakingchanges.
Figure24-9.ThesecondNewZonewindow
Afteryouaddanewzone,theinformationaboutthiszone
appearsintheBINDConfigurationGUIwindow(Figure24-6,
page735).ClickSaveonthetoolbartosavethechangesyou
madebeforeyouclosethewindow.
Toviewinformationaboutthenewzone,youcanbyexpandthe
objectthatholdsthenameofthenewzone.Youcanfurther
expandtheZoneAuthorityInformationandNameServer
objectsthatappearwhenyouexpandthenewzoneobject.
Right-clickanyobjecttoaddtoormodifytheinformationinthe
objectortodeletetheobject.
AddingResourceRecords
Youcanaddanyofanextensivelistofresourcerecordstoa
domain.Right-clickontheobjectrepresentingthedomainyou
justaddedtodisplayapop-upmenu.Slidethemousepointer
overAddtodisplaythedomainAddmenu(Figure24-10).The
uppercaselettersattheleftendofeachselectionspecifythe
typeofresourcerecord(page725)thattheselectionaddsto
thedomain.Followingaresomeofthechoicesavailableonthis
menu:
•AIPv4Addressrecord(page726)
•CNAME Aliasrecord(page726)
•MX MailExchangerecord(page726)
•NS Nameserverrecord(page726)
•TXT Textrecord(page728)
Figure24-10.ThedomainAdddrop-downmenu
[Viewfullsizeimage]
Toaddareversezone(aPTRrecord[page727]),addanew
zoneasbefore,butthistimeselectIPv4(orIPv6)Reverseas
theorigintype.Formoreinformationreferto"ReverseName
Resolution"onpage729.
ClickSavewhenyouaredone,closetheBINDConfiguration
GUIwindow,andstartthenameddaemonasexplainedon
page731.
SettingUpBIND
Thissectiondiscussesthe/etc/named.conffile,zonefiles,
implementationofaDNScache,andrunningDNSinsideachroot
jail.
named.conf:ThenamedConfigurationFile
Configurationinformationfornamed,includingzonenames
andthenamesandlocationsofzonefiles,iskeptin
/etc/named.conf.Bydefault,thezonefilesarekeptin
/var/named.Ifyouarerunningnamedinachrootjail,these
filesarekeptin/var/named/chroot/var/named(page
750).
RHELAsamplenamed.confconfigurationfileisincludedwith
thecaching-nameserverpackage.
FEDORAAsampleconfigurationfile,namednamed.caching-
nameserver.conf,isincludedwiththebind-configpackage.
Seethecautionboxonpage732and"named.conf"onpage
733forinformationaboutthisfileanditsrelationshipto
named.conf.Ifyouwanttomakechangestothisfile,copyit
tonamed.confandthenmakechangestothecopy.Thisway
yourchangeswillnotbeoverwrittenwhenthecaching-
nameserverpackageisupdated.
IP-list
Inthedescriptionsinthissection,IP-listisasemicolon-
separatedlistofIPaddresses,eachoptionallyfollowedbya
slashandsubnetmasklength(page423).Youcanprefixan
IP-listwithanexclamationpoint(!)tonegateit.Builtinnames
thatyoucanuseinIP-listincludeany,none,andlocalhost.
Youmustenclosebuiltinnameswithindoublequotationmarks.
Comments
Withinnamed.conf,youcanspecifyacommentbyprecedingit
withapoundsign(#)asinaPerlorshellprogram,precedingit
withadoubleslash(//)asinaC++program,orenclosingit
between/*and*/asinaCprogram.
OptionsSection
Optionstatementscanappearwithintwosectionsof
named.conf:OptionsandZone.Optionstatementswithinthe
Optionssectionapplyglobally.Whenanoptionstatement
appearsinaZonesection,theoptionappliestothezoneand
overridesanycorrespondingglobaloptionwithinthatzone.An
Optionssectionstartswiththekeywordoptionsandcontinues
withbracessurroundingthestatements.Followingisalistof
someoptionstatements.Statementsthatcanappearonlyinan
Optionssectionaresonoted.
allow-query{IP-list}
AllowsqueriesfromIP-listonly.Withoutthisoption,theserver
respondstoallqueries.
allow-recursion{IP-list}
Specifiessystemsthatthisserverwillperformrecursivequeries
(page723)for.ForsystemsnotinIP-list,theserverperforms
iterativequeriesonly.Withoutthisoption,theserverperforms
recursivequeriesforanysystem.Thisstatementmaybe
overriddenbytherecursionstatement.
allow-transfer{IP-list}
Specifiessystemsthatareallowedtoperformzonetransfers
fromthisserver.SpecifyanIP-listof"none"(includethe
quotationmarks)topreventzonetransfers.
directorypath
Specifiestheabsolutepathnameofthedirectorycontainingthe
zonefiles;underRedHatLinux,thisdirectoryisinitially
/var/named.Filenamesspecifiedinthisnamed.conffileare
relativetothisdirectory.Optionssectiononly.
forwardONLY|FIRST
ONLYforwardsallqueriesandfailsifitdoesnotreceivean
answer.FIRSTforwardsallqueriesand,ifaquerydoesnot
receiveananswer,attemptstofindananswerusingadditional
queries.Validwiththeforwardersstatementonly.
forwarders{IP[port][;...]}
SpecifiesIPaddressesandoptionallyportnumbersthatqueries
areforwardedto.Seetheforwardstatement.
notifyYES|NO
YESsendsamessagetoslaveserversforthezonewhenzone
informationchanges.Masterserversonly.
recursionYES|NO
YES(default)providesrecursivequeries(page723)iftheclient
requests.NOprovidesiterativequeriesonly(page723).An
answerisalwaysreturnedifitappearsintheserver'scache.
Thisstatementoverridestheallow-recursionstatement.
Optionssectiononly.
ZoneSection
AZonesectiondefinesazoneandcanincludeanyofthe
statementslistedfortheOptionssectionexceptasnoted.A
Zonesectionisintroducedbythekeywordzone,thenameof
thezoneenclosedwithindoublequotationmarks,andtheclass
(alwaysIN).ThebodyoftheZonesectionconsistsofapairof
bracessurroundingoneormorezonestatements.Seethe
listingofnamed.rfc1912.zonesonpage743forexamplesof
Zonesections.Followingisalistofsomezonestatements:
allow-update{IP-list}
Specifiessystemsthatareallowedtoupdatethiszone
dynamically.Thisstatementmaybeusefulwhenhostinga
masterDNSserverforadomainownedbysomeoneotherthan
thelocaladministratorbecauseitallowsaremoteuserto
updatetheDNSentrywithoutgrantingtheuseraccesstothe
server.
filefilename
Specifiesthezonefile,thefilethatspecifiesthecharacteristics
ofthezone.Thefilenameisrelativetothedirectoryspecified
bythedirectorystatementintheOptionssection.Thefile
statementismandatoryformasterandhintzonesandisagood
ideaforslavezones(seetype).
masters(IP-list)
Specifiessystemsthataslavezonecanusetoupdatezone
files.Slavezonesonly.
typeztype
Specifiesthetypeofzonethatthissectiondefines.Specify
ztypefromthefollowinglist:
forwardSpecifiesaforwardzone,whichforwardsqueries
directedtothiszone.Seetheforwardand/orforwarders
statementsintheOptionssection.
hintSpecifiesahintzone.Ahintzonelistsrootserversthat
thelocalserverquerieswhenitstartsandwhenitcannot
findananswerinitscache.
masterSpecifiesthelocalsystemasaprimarymaster
server(page724)forthiszone.
slaveSpecifiesthelocalsystemasaslaveserver(page
724)forthiszone.
ZoneFiles
Zonefilesdefinezonecharacteristics.Thenameofthezoneis
typicallyspecifiedinnamed.conf(ornamed.caching-
nameserver.conf).Contrastedwithnamed.conf,zonefiles
useperiodsattheendsofdomainnames.Seepage745for
samplezonefiles.Toimprovesecurity,masterandhintzone
filesshouldbekeptin/var/named,whichisownedbyroot
andisnotwritablebyprocessesrunningwithaUIDofnamed.
Slavezonefilesshouldbekeptin/var/named/slaves,which
isownedbynamedandiswritablebyprocessesrunningwitha
UIDofnamed.ThisconfigurationenablesSELinuxtooffer
bettersecurity.Whenyousetupachrootjail,theslaves
directoryisnotputinthejail.Bothofthesesetupsensurethat
masterandhintzonefilescannotbeupdatedbydynamicDNS
updatesorbyzonetransfers.Seethenamedmanpagefor
moreinformation.
TimeFormats
AlltimesinBINDfilesaregiveninseconds,unlesstheyare
followedbyoneoftheseletters(uppercaseorlowercase):S
(seconds),M(minutes),H(hours),D(days),orW(weeks).You
cancombineformats:Thetime2h25m30smeans2hours,25
minutes,and30secondsandisthesameas8,730seconds.
DomainQualification
Anunqualifieddomaininazonefileisassumedtobeinthe
currentzone(thezonebeingdefinedbythezonefileand
namedbythenamed.conffilethatreferstothezonefile).The
namezachinthezonefileformyzone.com,forexample,
wouldbeexpandedtotheFQDNzach.myzone.com..Usean
FQDN(includethetrailingperiod)tospecifyadomainthatis
notinthecurrentzone.Anynamethatdoesnotendwitha
periodisregardedasasubdomainofthecurrentzone.
ZoneName
Withinazonefile,an@isreplacedwiththezonenameas
specifiedbythenamed.conffilethatreferstothezonefile.
Thezonenameisalsousedtocompleteunqualifieddomain
names.Thezonenameisalsoreferredtoastheorigin.See
"$ORIGIN,"inthenextsection.
ZoneFileDirectives
Thefollowingdirectivescanappearwithinazonefile.Each
directiveisidentifiedbyaleadingdollarsign.The$TTLdirective
ismandatoryandmustbethefirstentryinazonefile.
$TTL
Definesthedefaulttimetoliveforallresourcerecordsinthe
zone.Thisdirectivemustappearinazonefilebeforeany
resourcerecordsthatitappliesto.Anyresourcerecordcan
includeaTTLvaluetooverridethisvalue,exceptforthe
resourcerecordintherootzone(.).
$ORIGIN
Changesthezonenamefromthatspecifiedinthenamed.conf
file.Thisname,orthezonenameifthisdirectivedoesnot
appearinthezonefile,replacesan@signintheNamefieldof
aresourcerecord.
$INCLUDE
Includesafileasthoughitwerepartofthezonefile.Thescope
ofan$ORIGINdirectivewithinanincludedfileistheincluded
file.Thatis,an$ORIGINdirectivewithinanincludedfiledoes
notaffectthefilethatholdsthe$INCLUDEdirective.
ADNSCache
YouinstallaDNScache,alsocalledaresolving,caching
nameserver,whenyouinstallthebind-configpackage(seethe
cautionboxonpage732).Thesection"JumpStartI:SettingUp
aDNSCache"(page733)explainshowtorunthisserver.This
sectionexplainshowthefilesRedHatLinuxprovidesimplement
thisserver.
named.caching-nameserver.conf:ThenamedConfiguration
File(FEDORA)
Seethecautionboxonpage732formoreinformationabout
thisfile.Thedefaultnamed.caching-nameserver.conffileis
shownhere:
#cat/etc/named.caching-nameserver.conf
//
//named.caching-nameserver.conf
//
//ProvidedbyRedHatbind-configpackagetoconfigurethe
//ISCBINDnamed(8)DNSserverasacachingonlynameserver
//(asalocalhostDNSresolveronly).
//
//DONOTEDITTHISFILE-usesystem-config-bindoraneditor
//tocreatenamed.conf-editstothisfilewillbeloston
//bind-configpackageupgrade.
//
options{
listen-onport53{127.0.0.1;};
listen-on-v6port53{::1;};
directory"/var/named";
dump-file"/var/named/data/cache_dump.db";
statistics-file"/var/named/data/named_stats.txt";
memstatistics-file"/var/named/data/named_mem_stats.txt";
query-sourceport53;
query-source-v6port53;
allow-query{localhost;};
};
logging{
channeldefault_debug{
file"data/named.run";
severitydynamic;
};
};
viewlocalhost_resolver{
match-clients{localhost;};
match-destinations{localhost;};
recursionyes;
include"/etc/named.rfc1912.zones";
};
Optionssection
ThefirsttwolinesoftheOptionssectioninstructnamedto
listenonport53(thedefaultnamedport)onthelocalsystem
forincomingqueries.Thedirectorystatementspecifiesthe
directorythatallrelativepathnamesinthisfilearerelativeto.
Specifically,thefilesnamedintheZonesections(ofthe
includednamed.rfc1912.zonesfile)areinthe/var/named
directory.Ifyouarerunningnamedinachrootjail,this
directoryislocatedunder/var/named/chroot(page750).
Thefilealsospecifiesthelocationsofthedump-file(cache
dump),statistics-file(statisticsfile),andmemstatistics-file
(memorystatisticsfile).Thequery-sourcestatementspecifies
the(addressand)portfromwhichtheserverissuesqueries.
Theallow-querystatementspecifiestheIPaddressesthatare
allowedtoquerytheserver.Thisfilespecifiesthatonly
localhostcanquerytheserver.
Loggingsection
TheLoggingsectioncausesdebuggingmessagestobesentto
data/named.run.Formoreinformationreferto"Logging"on
page753
Viewsection
ThesingleViewsectionspecifiesthatthisserverrespondto
queriesfromthelocalsystem(localhost)andperform
recursivequeries.Theincludestatementincludesthe
/etc/named.rfc1912.zonesfile(discussedinthenext
section)asthoughitwerepresentintheViewsection.Formore
informationreferto"Viewsections"onpage757.
named.rfc1912.zones:TheZoneConfigurationFile
(FEDORA)
Asexplainedintheprevioussection,thenamed.caching-
nameserver.conffileincorporatesthe
/etc/named.rfc1912.zonesfilebynamingitinaninclude
statement:
#cat/etc/named.rfc1912.zones
//named.rfc1912.zones:
//
//ProvidedbyRedHatbind-configpackage
//
//ISCBINDnamedzoneconfigurationforzonesrecommendedby
//RFC1912section4.1:localhostTLDsandaddresszones
//
zone"."IN{
typehint;
file"named.ca";
};
zone"localdomain"IN{
typemaster;
file"localdomain.zone";
allow-update{none;};
};
zone"localhost"IN{
typemaster;
file"localhost.zone";
allow-update{none;};
};
zone"0.0.127.in-addr.arpa"IN{
typemaster;
file"named.local";
allow-update{none;};
};
zone"0.0.0.0.0.0.0.....0.0.0.0.0.0.0.0.0.ip6.arpa"IN{
typemaster;
file"named.ip6.local";
allow-update{none;};
};
zone"255.in-addr.arpa"IN{
typemaster;
file"named.broadcast";
allow-update{none;};
};
zone"0.in-addr.arpa"IN{
typemaster;
file"named.zero";
allow-update{none;};
};
Zonesections
ThisfileholdssevenZonesections,eachofwhichhasan
allow-updatestatementthatspecifiesdynamicupdatesofthe
zonearenotallowed.Allfilenamesinthisfilearerelativetothe
directorystatementintheOptionssectionofnamed.caching-
nameserver.conf.
.(Thenameofthezoneisaperiod.)Thehintzone.
Specifiesthatwhentheserverstartsorwhenitdoesnot
knowwhichservertoquery,itshouldlookinthe
/var/named/named.ca(castandsforcache)filetofind
theaddressesofauthoritativeserversfortherootdomain.
localdomainSpecifiesthatlocalhost.localdomainpoints
to127.0.0.1,preventingthelocalserverfromlooking
upstreamforthisinformation.
localhostSetsupthenormalserveronthelocalsystem.
0.0.127.in-addr.arpaSetsupIPv4reversename
resolution.
0.0...0.0.ip6.arpaSetsupIPv6reversenameresolution.
255.in-addr.arpaSpecifiesthatIPaddressesthatstart
with255havetheirreverselookuphandledbythelocal
server,preventingthelocalserverfromlookingupstream
forthisinformation.
0.in-addr.arpaSpecifiesthatIPaddressesthatstartwith0
havetheirreverselookuphandledbythelocalserver,
preventingthelocalserverfromlookingupstreamforthis
information.
ZoneFiles
Therearesevenzonefilesin/var/named,eachcorresponding
tooneoftheZonesectionsinnamed.rfc1912.zones.This
sectiondescribesthreeofthesezonefiles.
Therootzone:named.ca
Thehintzonefile,named.ca,isacopyof
ftp.internic.net/domain/named.cache,whichdoesnotchange
frequently.Thenamed.cafilespecifiesauthoritativeserversfor
therootdomain.TheDNSserverinitializesitscachefromthis
fileandcandetermineanauthoritativeserverforanydomain
fromthisinformation.
Therootzoneisrequiredonlyforserversthatanswerrecursive
queries:Ifaserverrespondstorecursivequeries,itneedsto
performaseriesofiterativequeriesstartingattherootdomain.
Withouttherootdomainhintfile,itwouldnotknowthelocation
oftherootdomainservers.
$cat/var/named/named.ca
;Thisfileholdstheinformationonrootnameserversneededto
;initializecacheofInternetdomainnameservers
;(e.g.referencethisfileinthe"cache.<file>"
;configurationfileofBINDdomainnameservers).
;
;ThisfileismadeavailablebyInterNIC
;underanonymousFTPas
;file/domain/named.cache
;onserverFTP.INTERNIC.NET
;-OR-RS.INTERNIC.NET
;
;lastupdate:Jan29,2004
;relatedversionofrootzone:2004012900
;
;
;formerlyNS.INTERNIC.NET
;
.3600000INNSA.ROOT-SERVERS.NET.
A.ROOT-SERVERS.NET.3600000A198.41.0.4
;
;formerlyNS1.ISI.EDU
;
.3600000NSB.ROOT-SERVERS.NET.
B.ROOT-SERVERS.NET.3600000A192.228.79.201
;
;formerlyC.PSI.NET
;
.3600000NSC.ROOT-SERVERS.NET.
C.ROOT-SERVERS.NET.3600000A192.33.4.12
;
...
;EndofFile
localhost.zone
Thelocalhost.zonezonefiledefinesthelocalhostzone,the
normalserveronthelocalsystem.Itstartswitha$TTL
directiveandholdsthreeresourcerecords:SOA,NS,andA.The
$TTLdirectiveinthefollowingfilespecifiesthatthedefaulttime
tolivefortheresourcerecordsspecifiedinthisfileis86,400
seconds(24hours):
#cat/var/named/localhost.zone
$TTL86400
@INSOA@root(
42;serial(d.adams)
3H;refresh
15M;retry
1W;expiry
1D);minimum
INNS@
INA127.0.0.1
INAAAA::1
Asexplainedearlier,the@atthestartoftheSOAresource
recordstandsfortheorigin(thenameofthezone),whichis
localhost.ThelastthreelinesintheprecedingfilearetheNS
resourcerecordthatspecifiesthenameserverforthezoneas
localhost(@),theAresourcerecordthatspecifiestheIPv4
addressofthehostas127.0.0.1,andtheAAAAresourcerecord
thatspecifiestheIPv6addressofthehostas::1.Because
thesethreerecordshaveblankNamefields,eachinheritsthis
valuefromtheprecedingresourcerecordinthiscase,@.
named.local
Thenamed.localzonefileprovidesinformationaboutthe
0.0.127.in-addr.arpareverselookupzone.Itfollowsthesame
patternasthelocalhostzonefile,exceptthatinsteadoftheA
resourcerecord,thisfilehasaPTRrecordthatprovidesthe
namethatthezoneassociateswiththeIPaddress.ThePTR
resourcerecordspecifiesthename1,whichequatesthesystem
ataddress1inthezone(0.0.127.in-addr.arpa)withthename
localhost,whichhasanIPaddressof127.0.0.1:
$cat/var/named/named.local
$TTL86400
@INSOAlocalhost.root.localhost.(
1997022700;Serial
28800;Refresh
14400;Retry
3600000;Expire
86400);Minimum
INNSlocalhost.
1INPTRlocalhost.
Theotherzonefilesperformsimilarfunctionsasdescribed
under"Zonesections"onpage744.Onceyoustartnamed
(page731),youcanusethetestsdescribedunder
"Troubleshooting"onpage751tomakesuretheserveris
working.
Thenamed.confConfigurationFile(RHEL)
Thenamed.conffileholdsthesamezonesasthe
named.caching-nameserver.conffiledescribedinthe
previoussection.ThecommentsintheOptionssectionofthe
named.conffilearedatedanddonotapplyinmostcases.In
addition,thenamed.conffilehasaControlssectionandan
Includesectionthatincludesthefile/etc/rndc.key.
Controlssection
TheControlssectioncontainstwostatementsthatsetuprndc
control:inetandkeys.Theinetstatementopensacontrol
channelon127.0.0.1,allowinglocal,non-privilegedusersto
managethenameserver.Thekeysstatementallowsakeyto
bedefinedsoastosecurerndccommunications.
include/rndc
Therndc(RemoteNameDaemonControl)utilityallowsthe
systemadministratortocontrolBINDremotely(fromthelocal
oraremotesystem).Youcanuserndctostartandstopthe
daemon,forcethedaemontorereadtheconfigurationfiles,and
viewdiagnosticinformation.Seetherndcmanpageformore
information.
TheIncludesectionofnamed.confonthenameserver
incorporatesthe/etc/rndc.keyfileasthoughitappeared
withinnamed.conf.Byputtingtherndckeyinformationinafile
keptseparatefromthenamed.conffile,therndckey
informationcanbekeptprivateusingfilepermissions,whilethe
named.conffilecanbereadbyanyone.Therndckeyisa
secretsharedbetweenthenameserverandtheremotecontrol
program.The/etc/rndc.keyfilemustalsobeincludedinthe
/etc/rndc.conffileonthecontrollingsystem.Ifyouwishto
userndconasystemotherthanthelocalone,youmustcopy
rndc.keytotheremotesystemandaddtheremotehosttothe
Controlssectioninthenamed.conffileontheserver.
DNSGlueRecords
Itiscommonpracticetoputthenameserverforazoneinside
thezoneitserves.Forexample,youmightputthenameserver
forthezonestartingatsite1.example.com(Figure24-3,page
723)inns.site1.example.com.WhenaDNScachetriesto
resolvewww.site1.example.com,theauthoritativeserverfor
example.comgivesittheNSrecordpointingto
ns.site1.example.com.Inanattempttoresolve
ns.site1.example.com,theDNScacheagainqueriesthe
authoritativeserverforexample.com,whichpointsbackto
ns.site1.example.com.Thisloopdoesnotallow
ns.site1.example.comtoberesolved.
Thesimplestsolutiontothisproblemisnottoallowany
nameservertoresideinsidethezoneitpointsto.Becauseevery
zoneisachildoftherootzone,thissolutionmeansthatevery
domainwouldbeservedbytherootserverandwouldnotscale
atall.Abettersolutionisgluerecords.AgluerecordisanA
recordforanameserverthatisreturnedinadditiontotheNS
recordwhenanNSqueryisperformed.BecausetheArecord
providesanIPaddressforthenameserver,itdoesnotneedto
beresolvedanddoesnotcreatetheproblematicloop.
Thenameserversetupforredhat.comillustratestheuseofglue
records.WhenyouqueryforNSrecordsforredhat.com,DNS
returnsthreeNSrecords.Inaddition,itreturnsthreeArecords
thatprovidetheIPaddressesforthehoststhattheNSrecords
pointto:
$dig-tNSredhat.com
...
;;QUESTIONSECTION:
;redhat.com.INNS
;;ANSWERSECTION:
redhat.com.28INNSns2.redhat.com.
redhat.com.28INNSns3.redhat.com.
redhat.com.28INNSns1.redhat.com.
;;ADDITIONALSECTION:
ns1.redhat.com.5633INA66.187.233.210
ns2.redhat.com.151369INA66.187.224.210
ns3.redhat.com.80180INA66.187.229.10
...
YoucancreateagluerecordbyprovidinganArecordforthe
nameserverinsidethedelegatingdomain'szonefile:
site1.example.comINNSns.site1.example.com
ns.site1.example.comINA1.2.3.4
TSIGs:TransactionSignatures
InteractionbetweenDNScomponentsisbasedonthe
queryresponsemodel:Onepartqueriesanotherandreceivesa
reply.Traditionallyaserverdetermineswhetherandhowto
replytoaquerybasedontheIPclient'saddress.IPspoofing
(page1038)isrelativelyeasytocarryout,makingthis
situationlessthanideal.RecentversionsofBINDsupport
transactionsignatures(TSIGs),whichallowtwosystemsto
establishatrustrelationshipbyusingasharedsecretkey.
TSIGsprovideanadditionallayerofauthenticationbetween
masterandslaveserversforazone.Whenaslaveserveris
locatedatadifferentsitethanthemasterserver(asitshould
be),amaliciouspersonoperatingarouterbetweenthesites
canspooftheIPaddressofthemasterserverandchangethe
DNSdataontheslave(aman-in-the-middlescenario).With
TSIGs,thispersonwouldneedtoknowthesecretkeyto
changetheDNSdataontheslave.
CreatingaSecretKey
Asecretkeyisanencodedstringofupto512bits.Thednssec-
keygenutility,includedwithBIND,generatesthiskey.The
followingcommandgeneratesa512-bitrandomkeyusingMD5,
aone-wayhashfunction(page1046):
$/usr/sbin/dnssec-keygen-ahmac-md5-b512-nHOSTkeyname
Kkeyname.+157+47586
Intheprecedingcommand,replacekeynamewithsomething
uniqueyetmeaningful.Thiscommandcreatesakeyinafile
whosenameissimilartoKkeyname.+157+47586.private,
wherekeynameisreplacedbythenameofthekey,+157
indicatesthealgorithmused,and+47586isahashofthekey.
Ifyourunthesamecommandagain,thehashpartwillbe
different.Thekeyfileisnotuseddirectly.Usecatwithan
argumentoftheprivatefilenametodisplaythealgorithmand
keyinformationyouwillneedinthenextstep:
$catKkeyname.+157+47586.private
Private-key-format:v1.2
Algorithm:157(HMAC_MD5)
Key:uNPDouqVwR7fvo/zFyjkqKbQhcTd6Prm...
UsingtheSharedSecret
Thenextstepistotellthenameserversaboutthesharedsecret
byinsertingthefollowingcodeinthe/etc/named.conffileon
bothservers.Thiscodeisatop-levelsectioninnamed.conf;
insertitfollowingtheOptionssection:
keykeyname{
algorithm"hmac-md5";
secret"uNPDouqVwR7fvo/zFyjkqKbQhcTd6Prm...";
};
Thekeynameisthenameofthekeyyoucreated.The
algorithmisthestringthatappearswithinparenthesesinthe
outputfromcat.ThesecretisthestringthatfollowsKey:inthe
precedingoutput.Youmustencloseeachstringwithindouble
quotationmarks.Becarefulwhenyoucopythekey;althoughit
islong,donotbreakitintomultiplelines.
Becausekeynamesareunique,youcaninsertanynumberof
keysectionsintonamed.conf.Tokeepthekeyasecret,make
sureusersotherthanrootcannotreadit:Eithergive
named.confpermissionssuchthatnooneexceptroothas
accesstoitorputthekeyinafilethatonlyrootcanreadand
incorporateitinnamed.confusinganincludestatement.
Oncebothserversknowaboutthekey,usetheserver
statementinnamed.conftotellthemwhentouseit:
server1.2.3.4{
#1.2.3.4istheIPaddressoftheotherserverusingthiskey
keys{
"keyname";
};
};
Eachservermusthaveaserversection,eachcontainingtheIP
addressoftheotherserver.Theserverswillnowcommunicate
witheachotheronlyiftheyfirstauthenticateeachotherusing
thesecretkey.
RunningBINDinachrootJail
Toincreasesecurity,youcanrunBINDinachrootjail.Seepage
428forinformationaboutthesecurityadvantagesofandways
tosetupachrootjail.SeealsothenoteaboutSELinuxonpage
732andthenamedmanpageforinformationaboutBIND,
SELinux,andchrootjails.Thebind-chrootpackage,whichsets
upBINDtoruninachrootjail,createsadirectorynamed
/var/named/chrootthattakestheplaceoftherootdirectory
(/)forallBINDfiles.Withthispackageinstalled,allfilesthat
controlBINDarelocatedwithinthischrootjailandthefilenames
usedinthischapteraresymboliclinkstothefilesinthechroot
jail:
#ls-l/var/named/etc/named
.../etc/named.caching-nameserver.conf->/var/named/chroot//etc/named.caching
nameserver.conf
.../etc/named.rfc1912.zones->/var/named/chroot//etc/named.rfc1912.zones
/var/named:
total52
...chroot
...data
...localdomain.zone->/var/named/chroot//var/named/localdomain.zone
...localhost.zone->/var/named/chroot//var/named/localhost.zone
...named.broadcast->/var/named/chroot//var/named/named.broadcast
...named.ca->/var/named/chroot//var/named/named.ca
...named.ip6.local->/var/named/chroot//var/named/named.ip6.local
...named.local->/var/named/chroot//var/named/named.local
...named.zero->/var/named/chroot//var/named/named.zero
...slaves
Withthebind-chrootpackageinstalled,theROOTDIRshell
variableissetto/var/named/chrootinthe
/etc/sysconfig/namedfile,whichisexecutedbythenamed
initscript.
Troubleshooting
WhenyoustartaDNScache,the/var/log/messagesfile
containslinessimilartothefollowing.OthertypesofDNS
serversdisplaysimilarmessages.
#cat/var/log/messages
...
18:45:18peachnamed[10003]:startingBIND9.3.2-unamed-t/var/named/chroot
18:45:18peachnamed[10003]:found1CPU,using1workerthread
18:45:18peachnamed[10003]:loadingconfigurationfrom'/etc/named.conf'
18:45:18peachnamed[10003]:listeningonIPv6interfacelo,::1#53
18:45:18peachnamed[10003]:listeningonIPv4interfacelo,127.0.0.1#53
18:45:18peachnamed[10003]:commandchannellisteningon127.0.0.1#953
18:45:18peachnamed[10003]:commandchannellisteningon::1#953
18:45:18peachnamed[10003]:zone0.in-addr.arpa/IN/localhost_resolver:loadedserial42
18:45:18peachnamed[10003]:zone0.0.127.in-addr.arpa/IN/localhost_resolver:loaded
serial1997022700
18:45:18peachnamed[10003]:zone255.in-addr.arpa/IN/localhost_resolver:loadedserial42
18:45:18peachnamed[10003]:zone0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.
0.0.0.ip6.arpa/IN/localhost_resolver:loadedserial1997022700
18:45:18peachnamed[10003]:zonelocaldomain/IN/localhost_resolver:loadedserial42
18:45:18peachnamed[10003]:zonelocalhost/IN/localhost_resolver:loadedserial42
18:45:18peachnamed[10003]:running
Withanargumentofstatus,thenamedinitscriptdisplays
usefulinformation:
#/sbin/servicenamedstatus
numberofzones:6
debuglevel:0
xfersrunning:0
xfersdeferred:0
soaqueriesinprogress:0
queryloggingisOFF
recursiveclients:0/1000
tcpclients:0/100
serverisupandrunning
WhenyoucreateorupdateDNSinformation,youcanusedigor
hosttotestthattheserverworksthewayyouplanned.The
mostusefulpartoftheoutputfromdigisusuallytheanswer
section,whichgivesthenameserver'sreplytoyourquery:
$digexample.com
...
;;ANSWERSECTION:
example.com.172800INA192.0.34.166
...
Theprecedingoutputshowsthattheexample.com.domain
hasasingleArecordandthatrecordpointsto192.0.34.166.
TheTTLofthisrecord,whichtellsyouhowlongtherecordcan
beheldincache,is172,800seconds(2days).Youcanalsouse
digtoqueryotherrecordtypesbyusingtoptionfollowedbythe
typeofrecordyouwanttoqueryfor(tworkswithhost,too):
$dig-tMXredhat.com
...
;;ANSWERSECTION:
redhat.com.600INMX10mx1.redhat.com.
redhat.com.600INMX10mx3.redhat.com.
redhat.com.600INMX20mx2.redhat.com.
...
Ifyouqueryforadomainthatdoesnotexist,digreturnsthe
SOArecordfortheauthoritysectionofthehighest-leveldomain
inyourquerythatdoesexist:
$digdomaindoesnotexist.info
...
;;AUTHORITYSECTION:
info.7200INSOAtld1.ultradns.net.domadmin.ultradns.net....
...
Becauseittellsyouthelastzonethatwasqueriedcorrectly,this
informationcanbeusefulintracingfaults.
TSIGs
IftwoserversusingTSIGs(page748)failtocommunicate,
checkthatthetimeisthesameonbothservers.TheTSIG
authenticationmechanismisdependentonthecurrenttime.If
theclocksonthetwoserversarenotsynchronized,TSIGwill
fail.ConsidersettingupNTP(page1046)ontheserversto
preventthisproblem.
AFull-FunctionedNameserver
BecausetheIPaddressesusedinthisexamplearepartofthe
privateaddressspace(page1049)youcancopytheexample
andruntheserverwithoutaffectingglobalDNS.Also,to
preventcontaminationoftheglobalDNS,eachzonehasthe
notifyoptionsettoNO.Whenyoubuildanameserverthatis
integratedwiththeInternet,youwillwanttouseIPaddresses
thatareuniquetoyourinstallation.Youmaywanttochange
thesettingsofthenotifystatements.
named.conf
Thenamed.conffileinthisexamplelimitstheIPaddresses
thatnamedanswersqueriesfromandsetsuplogging:
$cat/etc/named.conf
options{
directory"/var/named";
allow-query{127.0.0.1;192.168.0.0/24;};};
zone"."IN{
typehint;
file"named.ca";};
zone"0.168.192.in-addr.arpa"IN{
typemaster;
file"named.local";
notifyNO;
};
zone"sam.net"IN{
typemaster;
file"sam.net";
notifyNO;
};
logging{
channel"misc"{
file"/var/log/bind/misc.log"versions4size4m;
print-timeYES;
print-severityYES;
print-categoryYES;
};
channel"query"{
file"/var/log/bind/query.log"versions4size4m;
print-timeYES;
print-severityNO;
print-categoryNO;
};
categorydefault{
"misc";
};
categoryqueries{
"query";
};
};
Theallow-querystatementintheOptionssectionspecifiesthe
IPaddressesofthesystemsthattheserverwillanswerqueries
from.Youmustincludethelocalsystemas127.0.0.1ifitwillbe
queryingtheserver.Thezonethatthisserverisauthoritative
forissam.net;thezonefileforsam.netis
/var/named/sam.net.
Logging
LoggingisturnedonbytheLoggingsection.Thissectionopens
twologgingchannels:onethatlogsinformationto
/var/log/bind/misc.logandonethatlogsinformationto
/var/log/bind/query.log.Whenoneoftheselogsgrowsto4
megabytes(size4minthefilestatement),itisrenamedby
appending.1toitsfilenameandanewlogisstarted.The
numbersattheendsofother,similarlynamedlogsare
incremented.Anylogthatwouldhavealargernumberthan
thatspecifiedbytheversionsclause(4intheexample)is
removed.Seelogrotate(page559)foranotherwaytomaintain
logfiles.Theprintstatementsdeterminewhetherthetime,
severity,andcategoryoftheinformationaresenttothelog;
specifyeachasYESorNO.Thecategorydetermineswhat
informationisloggedtothechannel.Intheexample,default
informationissenttothemiscchannelandqueriesaresentto
thequerychannel.Refertothenamed.confmanpagefor
morechoices.
named.local
Theoriginforthereversezonefile(named.local)is
0.168.192.in-addr.arpa(asspecifiedintheZonesectionthat
referstothisfileinnamed.conf).FollowingtheSOAandNS
resourcerecords,thefirstthreePTRresourcerecordsequate
address1inthesubnet0.168.192.in-addr.arpa(192.168.0.1)
withthenamesgw.sam.net.,www.sam.net.,and
ftp.sam.net.,respectively.ThenextthreePTRresource
recordsequate192.168.0.3withmark.sam.net.,192.168.0.4
withmail.sam.net.,and192.168.0.6withns.sam.net..
$catnamed.local
;zone"0.168.192.in-addr.arpa"
;
$TTL3D
@INSOAns.sam.net.mgs@sobell.com.(
2005110501;serial
8H;refresh
2H;retry
4W;expire
1D);minimum
INNSns.sam.net.
1INPTRgw.sam.net.
1INPTRwww.sam.net.
1INPTRftp.sam.net.
3INPTRmark.sam.net.
4INPTRmail.sam.net.
6INPTRns.sam.net.
sam.net
Thezonefileforsam.nettakesadvantageofmanyBIND
featuresandincludesTXT(page728),CNAME(page726),and
MX(page726)resourcerecords.Whenyouqueryforresource
records,namedreturnstheTXTresourcerecordalongwiththe
recordsyourequested.ThefirstofthetwoNSrecordsspecifies
anunqualifiedname(ns)towhichBINDappendsthezone
name(sam.net),yieldinganFQDNofns.sam.net.Thesecond
nameserverisspecifiedwithanFQDNnamethatBINDdoesnot
alter.TheMXrecordsspecifymailserversinasimilarmanner
andincludeaprioritynumberatthestartofthedatafield;
lowernumbersindicatepreferredservers.
$catsam.net
;zone"sam.net"
;
$TTL3D
@INSOAns.sam.net.mgs@sobell.com.(
200511051;serial
8H;refresh
2H;retry
4W;expire
1D);minimum
TXT"SobellAssociatesInc."
NSns;Nameserveraddress(unqualified)
NSns.max.net.;Nameserveraddress(qualified)
MX10mail;Mailexchange(primary/unqualified)
MX20mail.max.net.;Mailexchange(2nd/qualified)
localhostINA127.0.0.1
wwwINCNAMEns
ftpINCNAMEns
gwINA192.168.0.1
TXT"Router"
nsINA192.168.0.6
MX10mail
MX20mail.max.net.
markINA192.168.0.3
MX10mail
MX20mail.max.net.
TXT"MGS"
mailINA192.168.0.4
MX10mail
MX20mail.max.net.
SomeresourcerecordshaveavalueintheNamefield;those
withoutanameinheritthenamefromthepreviousresource
record.Inasimilarmanner,thepreviousresourcerecordmay
haveaninheritednamevalue,andsoon.Thefiveresource
recordsfollowingtheSOAresourcerecordinheritthe@,or
zonename,fromtheSOAresourcerecord.Theseresource
recordspertaintothezoneasawhole.Inthepreceding
example,thefirstTXTresourcerecordinheritsitsnamefrom
theSOAresourcerecord;itistheTXTresourcerecordforthe
sam.netzone(givethecommandhosttTXTsam.netto
displaytheTXTresourcerecord).
Followingthesefiveresourcerecordsareresourcerecordsthat
pertaintoadomainwithinthezone.Forexample,theMX
resourcerecordsthatfollowtheAresourcerecordwiththe
Namefieldsettomarkareresourcerecordsforthe
mark.sam.net.domain.
TheAresourcerecordforlocalhostisfollowedbytwoCNAME
resourcerecordsthatspecifywww(.sam.net.)and
ftp(.sam.net.)asaliasesforthenameserverns.sam.net..For
example,auserconnectingtoftp.sam.netwillconnectto
192.168.0.6.Theresourcerecordsnamedgw,ns,mark,and
mailareresourcerecordsfordomainswithinthesam.netzone.
Logfiles
Beforerestartingnamed,createthedirectoryforthelogfiles
andgiveitpermissionsandownershipasshownbelow.Ifyou
arerunningnamedinachrootjail,createthebinddirectoryin
/var/named/chroot/var/log.
#mkdir/var/log/bind
#chmod744/var/log/bind
#chownnamed/var/log/bind
#ls-ld/var/log/bind
drwxr--r--2namedroot4096Nov519:41/var/log/bind
Withthelogdirectoryinplace,named.confin/etc(orin
/var/named/chroot/etcifyouarerunningnamedinachroot
jail),andthenamed.ca,named.local,andsam.netzonefiles
in/var/named(orin/var/named/chroot/var/namedif
youarerunningnamedinachrootjail),restartnamedand
checkthelogfiles.Thefile/var/log/messagesshouldshow
somethinglikethefollowing:
#cat/var/log/messages
...
19:25:48peachnamed[22416]:startingBIND9.3.2-unamed-t/var/named/chroot
19:25:48peachnamed[22416]:found1CPU,using1workerthread
19:25:48peachnamed[22416]:loadingconfigurationfrom'/etc/named.conf'
19:25:48peachnamed[22416]:listeningonIPv4interfacelo,127.0.0.1#53
19:25:48peachnamed[22416]:listeningonIPv4interfaceeth0,192.168.0.10#53
19:25:48peachnamed[22416]:commandchannellisteningon127.0.0.1#953
19:25:48peachnamed[22416]:commandchannellisteningon::1#953
Themisc.logfilemayshowerrorsthatdonotappearinthe
messagesfile:
#cat/var/log/bind/misc.log
19:25:48.077general:info:zone0.168.192.in-addr.arpa/IN:loadedserial2005110501
19:25:48.079general:info:zonesam.net/IN:loadedserial200511051
19:25:48.097general:notice:running
ASlaveServer
Tosetupaslaveserver,copythe/etc/named.conffilefrom
themasterservertotheslaveserver,replacingthetype
masterstatementwithtypeslave.Removeanyzonesthatthe
slaveserverwillnotbeactingasaslavefor,includingtheroot
(.)zone,iftheslaveserverwillnotrespondtorecursive
queries.Createthe/var/log/binddirectoryforlogfilesas
explainedattheendoftheprevioussection.
notifystatement
Slaveserverscopyzoneinformationfromtheprimarymaster
serveroranotherslaveserver.Thenotifystatementspecifies
whetheryouwantamasterservertonotifyslaveserverswhen
informationonthemasterserverchanges.Setthe(global)
valueofnotifyintheOptionssectionorsetitwithinaZone
section,whichoverridesaglobalsettingforagivenzone.The
formatis
notifyYES|NO|EXPLICIT
YEScausesthemasterservertonotifyallslaveslistedinNS
resourcerecordsforthezoneaswellasserversatIPaddresses
listedinanalso-notifystatement.Whenyousetnotifyto
EXPLICIT,theservernotifiesserverslistedinthealso-notify
statementonly.NOturnsoffnotification.
Whenyoustartnamed,itcopiesthezonefilesto
/var/named.IfyouspecifynotifyYESonthemasterserver,
thezonefilesontheslaveserverwillbeupdatedeachtimeyou
changetheserialfieldoftheSOAresourcerecordinazone.
Youmustmanuallydistributechangestothe
/etc/named.conffile.
ASplitHorizonServer
AssumeyouwanttosetupaLANthatprovidesallitssystems
andservicestolocalusersoninternalsystems,whichmaybe
behindafirewall,andonlycertainpublicservicessuchasWeb,
FTP,andmailtoInternet(public)users.Asplithorizon(also
calledDMZ)DNSservertakescareofthissituationbytreating
queriesfrominternalsystemsdifferentlyfromqueriesfrom
publicsystems(systemsontheInternet).
Viewsections
BIND9introducedViewsectionsinnamed.conf.Viewsections
facilitatetheimplementationofasplitDNSserver.Eachview
providesadifferentperspectiveoftheDNSnamespacetoa
groupofclients.WhenthereisnoViewsection,allzones
specifiedinnamed.confarepartoftheimplicitdefaultview.
AssumethatanofficehasseveralsystemsonaLANandpublic
Web,FTP,DNS,andmailservers.Thesingleconnectiontothe
InternetisNATed(page1044)sothatitissharedbythelocal
systemsandtheservers.Thegatewaysystemtheone
connecteddirectlytotheInternetisarouter,firewall,and
server.ThisscenariotakesadvantageoftheViewsectionsin
named.confandsupportsseparatesecondarynameserversfor
localandpublicusers.Althoughpublicusersneedaccesstothe
DNSserverastheauthorityonthedomainthatsupportsthe
servers,theydonotrequiretheDNSservertosupport
recursivequeries.Notsupportingrecursionforpublicusers
limitstheloadontheDNSserverandtheInternetconnection.
Forsecurityreasons,publicusersmustnothaveaccessto
informationaboutlocalsystemsotherthantheservers.Local
usersshouldhaveaccesstoinformationaboutlocalsystems
andshouldbeabletousetheDNSserverrecursively.
Figure24-11showsthattheserverrespondsdifferentlyto
queriesfromtheLANandtheInternet.
Figure24-11.AsplithorizonDNSserver
[Viewfullsizeimage]
Theiptablesutility(page763)controlswhichportsonwhich
systemsusersoninternalandexternalsystemscanaccess.
DNScontrolswhichsystemsareadvertisedtowhichusers.
Thenamed.conffilehasfoursections:Options,twoView
sections,andLogging.TheOptionssectionspecifiesthatthe
zonefilesareinthe/var/nameddirectory.TheViewsections
specifythecharacteristicsandzonesthataresolverisgiven
accessto,whichdependontheresolver'saddress.Onezoneis
forusebytheLAN/localusersandtheotherbyInternet/public
users.TheLoggingsectionsetsupthemisc2.logfilefor
defaultmessages.
Thereareseveralwaystospecifywhichclientsseeaview.The
followingnamed.conffileusesmatch-clientsstatements:
$cat/etc/named.conf
options{
directory"/var/named";
};//endoptions
view"local"IN{//startlocalview
match-clients{127.0.0.1;192.168.0.0/24;};
recursionYES;
zone"zach.net"IN{
typemaster;
file"local.net";
notifyYES;
};
zone"0.168.192.in-addr.arpa"IN{
typemaster;
file"named.local";
notifyYES;
};
zone"."IN{
typehint;
file"named.ca";
};
};//endlocalview
view"public"IN{//startpublicview
match-clients{"all";};
recursionNO;
zone"zach.net"IN{
typemaster;
file"public.net";
notifyYES;
};
zone"0.168.192.in-addr.arpa"IN{
typemaster;
file"named.public";
notifyYES;
};
zone"."IN{
typehint;
file"named.ca";
};
};//endpublicview
logging{
channel"misc"{
file"/var/log/bind/misc2.log"versions2size1m;
print-timeYES;
print-severityYES;
print-categoryYES;
};
categorydefault{
"misc";
};
};//endlogging
TheorderingofViewsectionswithinnamed.confiscritical:
Theviewthatispresentedtoaclientisthefirstviewthatthe
clientmatches.Theprecedingnamed.conffileholdstwoView
sections:oneforlocalusersandoneforpublicusers,inthat
order.Localusersaredefinedtobethoseonthe
192.168.0.0/24subnetorlocalhost(127.0.0.1);publicusers
aredefinedtobeanyusers.Ifyoureversedtheorderofthe
Viewsections,allusersincludinglocaluserswouldgettheview
intendedforthepublicandnouserswouldseethelocalview.
ManystatementsfromtheOptionssectioncanbeusedwithin
Viewsections,wheretheyoverridestatementsinthe(global)
Optionssection.Therecursionstatement,whichcanappear
withinanOptionssection,appearsineachViewsection.This
named.conffilesetsupaserverthatprovidesrecursive
answerstoqueriesthatoriginatelocallyanditerativeanswers
toqueriesfromthepublic.Thissetupprovidesquick,complete
answerstolocalusers,limitingthenetworkandprocessor
bandwidththatisdevotedtootheruserswhilestillproviding
authoritativenameserviceforthelocalservers.
Tomakenamed.confeasiertounderstandandmaintain,zones
indifferentViewsectionscanhavethesamenamewhilehaving
differentzonefiles.BoththelocalandpublicViewsectionsin
theexamplehavezonesnamedzach.net:Thepubliczach.net
zonefileisnamedpublic.net,whilethelocaloneisnamed
local.net.
TheLoggingsectionisdescribedonpage753.
Thezonefilesdefiningzach.netaresimilartotheonesinthe
previousexamples;thepublicfileisasubsetofthelocalone.
FollowingtheSOAresourcerecordinbothfilesisaTXT,twoNS,
andtwoMXresourcerecords.NextarethreeCNAMEresource
recordsthatdirectqueriesaddressedtowww.zach.net,
ftp.zach.net,andmail.zach.nettothesystemnamed
ns.zach.net.Thenextfourresourcerecordsspecifytwo
nameserveraddressesandtwomailserversforthens.zach.net
domain.
Thefinalfourresourcerecordsappearinthelocalzach.net
zonefileandnotinthepubliczonefile;theyareaddress(A)
resourcerecordsforlocalsystems.Insteadofkeepingthis
informationin/etc/hostsfilesoneachsystem,youcankeepit
ontheDNSserver,whereitcanbeupdatedeasily.Whenyou
useDNSinsteadof/etc/hosts,youmustchangethehosts
linein/etc/nsswitch.conf(page435).
$catlocal.net
;zach.netlocalzonefile
;
$TTL3D
@INSOAns.zach.net.mgs@sobell.com.(
200511118;serial
8H;refresh
2H;retry
4W;expire
1D);minimum
INTXT"SobellAssociatesInc."
INNSns;Nameserveraddress(unqualified)
INNSns.speedy.net.;Nameserveraddress(qualified)
INMX10mail;Mailexchange(primary/unqualified)
INMX20mail.max.net.;Mailexchange(2nd/qualified)
wwwINCNAMEns
ftpINCNAMEns
mailINCNAMEns
nsINA192.168.0.1
INA192.168.0.6
INMX10mail
INMX20mail.max.net.
speedyINA192.168.0.1
grapeINA192.168.0.3
potatoINA192.168.0.4
peachINA192.168.0.6
Thepublicversionofthezach.netzonefilefollows:
$catpublic.net
;zach.netpubliczonefile
;
$TTL3D
@INSOAns.zach.net.mgs@sobell.com.(
200511118;serial
8H;refresh
2H;retry
4W;expire
1D);minimum
INTXT"SobellAssociatesInc."
INNSns;Nameserveraddress(unqualified)
INNSns.speedy.net.;Nameserveraddress(qualified)
INMX10mail;Mailexchange(primary/unqualified)
INMX20mail.max.net.;Mailexchange(2nd/qualified)
wwwINCNAMEns
ftpINCNAMEns
mailINCNAMEns
nsINA192.168.0.1
INA192.168.0.6
INMX10mail
INMX20mail.max.net.
Therearetworeversezonefiles,eachofwhichstartswithSOA
andNSresourcerecordsfollowedbyPTRresourcerecordsfor
eachofthenamesoftheservers.Thelocalversionofthisfile
alsoliststhenamesofthelocalsystems:
$catnamed.local
;"0.168.192.in-addr.arpa"reversezonefile
;
$TTL3D
@INSOAns.zach.net.mgs@sobell.com.(
2005110501;serial
8H;refresh
2H;retry
4W;expire
1D);minimum
INNSns.zach.net.
INNSns.speedy.net.
1INPTRgw.zach.net.
1INPTRwww.zach.net.
1INPTRftp.zach.net.
1INPTRmail.zach.net.
1INPTRspeedy.zach.net.
3INPTRgrape.zach.net.
4INPTRpotato.zach.net.
6INPTRpeach.zach.net.
ChapterSummary
DNS,whichmapsdomainnamestoIPaddresses,andvice
versa,isimplementedasahierarchical,distributed,and
replicateddatabaseontheInternet.AlthoughBIND,which
implementsDNS,hassecurityissues,youcanimproveits
securitybyrunningitinsideachrootjailandusingtransaction
signatures(TSIGs)andSELinux.
WhenaprogramonthelocalsystemneedstolookupanIP
addressthatcorrespondstoadomainname,itcallsthe
resolver.TheresolverqueriesthelocalDNScache,ifavailable,
andthenqueriesDNSserversontheLANorInternet.Thereare
twotypesofqueries:iterativeandrecursive.Whenaserver
respondstoaniterativequery,itreturnswhateverinformation
ithasathand;itdoesnotqueryotherservers.Recursive
queriescauseaservertoqueryotherserversifnecessaryto
respondwithananswer.
Therearethreetypesofservers.Masterservers,whichholdthe
mastercopyofzonedata,areauthoritativeforazone.Slave
serversarealsoauthoritativeandcopytheirdatafromamaster
serverorotherslaveservers.DNScachesarenotauthoritative
andeitheranswerqueriesfromcacheorforwardqueriesto
anotherserver.
TheDNSdatabaseholdsresourcerecordsfordomains.Many
typesofresourcerecordsexist,includingA(address),MX(mail
exchange),NS(nameserver),PTR(pointerforperforming
reversenameresolution),andSOA(startofauthority,which
describesthezone).
Exercises
1. Whatkindofserverrespondstorecursivequeries?
2. WhatkindofDNSrecordislikelytobereturnedwhenaWebbrowsertriesto
resolvethedomainpartofaURI?
3. WhatareMXresourcerecordsfor?
4. HowwouldyoufindtheIPaddressofexample.comfromthecommandline?
5.
HowwouldyouinstructaLinuxsystemtousethelocalnetwork'sDNScache,
locatedat192.168.1.254,ortheISP'sDNScache,locatedon1.2.3.4,iftheLAN
nameserverisunavailable?
6. HowwouldyouinstructaDNSservertorespondonlytoqueriesfromthe
137.44.*IPrange?
7. HowmightaresolverattempttofindtheIPaddressoftheexampledomain?
AdvancedExercises
8. Howwouldyousetupaprivatedomainnamehierarchythatdoesnotincludeany
oftheofficialInterNIC-assigneddomainnames?
9. WhichpartofDNSismostvulnerabletoanattackfromamalicioususerandwhy?
10.
ItisoftenirritatingtohavetowaitforDNSrecordstoupdatearoundtheworld
whenyouchangeDNSentries.YoucouldpreventthisdelaybysettingtheTTLtoa
smallnumber.WhyissettingtheTTLtoasmallnumberabadidea?
11. OutlineamethodbywhichDNScouldbeusedtosupportencryption.
25.iptables:SettingUpaFirewall
INTHISCHAPTER
HowiptablesWorks 764
Rules,matches,targets,andchains 764
Networkpacket 765
Jumpsandtargets 766
JumpStart:BuildingaFirewallUsingsystem-config-
securitylevel
768
AnatomyofaniptablesCommand 769
BuildingaSetofRules 770
system-config-securitylevel:GeneratesaSetofRules 777
SharinganInternetConnectionUsingNAT 779
Theiptablesutilitybuildsandmanipulatesnetworkpacket
filteringrulesintheLinuxkernel.Youcanuseiptablestocreatea
firewallthatprotectsasystemfrommalicioususersandtoset
upNAT(NetworkAddressTranslation,page1044),whichcan
allowmultiplesystemstoshareasingleInternetconnection.
Theiptablesutilityisflexibleandextensible,allowingyoutoset
upbothsimpleandcomplexnetworkpacketfilteringsolutions.
Itprovidesconnectiontracking(statefulpacketfiltering),
allowingyoutohandlepacketsbasedonthestateoftheir
connection.Forexample,youcansetuprulesthatreject
inboundpacketstryingtoopenanewconnectionandaccept
inboundpacketsthatareresponsestolocallyinitiated
connections.Featuresnotincludedinthebaseiptablespackage
areavailableaspatchesviathepatch-o-maticprogram.
Someoftheconceptsrequiredtofullyunderstandiptablesare
beyondthescopeofthisbook.Althoughyoucanuseiptablesat
severaldifferentlevels,thischapterpresentsonlythe
fundamentals.Thereare,however,somesectionsofthis
chapterthatdelveintoareasthatmayrequireadditional
understandingorexplanation.Ifaconceptisnotclear,referto
oneoftheresourcesin"MoreInformation"onpage766.
HowiptablesWorks
netfilterandiptables
Thefunctionalityfrequentlyreferredtoasiptablesisactually
composedoftwocomponents:netfilterandiptables.Runningin
kernelspace(page1039),thenetfiltercomponentisasetof
tablesthatholdrulesthatthekernelusestocontrolnetwork
packetfiltering.Runninginuserspace(page1062),theiptables
utilitysetsup,maintains,anddisplaystherulesstoredby
netfilter.
Rules,matches,targets,andchains
Arulecomprisesoneormorecriteria(matchesorclassifiers)
andasingleaction(atarget).If,whenaruleisappliedtoa
networkpacket,thepacketmatchesallofthecriteria,the
actionisappliedtothepacket.Rulesarestoredinchains.Each
ruleinachainisapplied,inorder,toapacket,untilamatchis
found.Ifthereisnomatch,thechain'spolicy,ordefaultaction,
isappliedtothepacket(page771).
History
Inthekernel,iptablesreplacestheearlieripchainsasamethodof
filteringnetworkpacketsandprovidesmultiplechainsfor
increasedfiltrationflexibility.Theiptablesutilityalsoprovides
statefulpacketinspection(page766).
Examplerules
Asanexampleofhowruleswork,assumethatachainhastwo
rules(Figure25-1).Thefirstruletestswhetherapacket's
destinationisport23(FTP)anddropsthepacketifitis.The
secondruletestswhetherapacketwasreceivedfromtheIP
address192.168.1.1andaltersthepacket'sdestinationifit
was.Whenapacketisprocessedbytheexamplechain,the
kernelappliesthefirstruleinthechaintoseeifthepacket
arrivedonport23.Iftheanswerisyes,thepacketisdropped
andthatistheendofprocessingforthatpacket.Iftheanswer
isno,thekernelappliesthesecondruleinthechaintoseeif
thepacketcamefromthespecifiedIPaddress.Ifyes,the
destinationinthepacket'sheaderischangedandthemodified
packetissentonitsway.Ifno,thepacketissentonwithout
beingchanged.
Figure25-1.Exampleofhowruleswork
Chainsarecollectedinthreetables:Filter,NAT,andMangle.
Eachofthetableshasbuiltinchains(describednext).Youcan
createadditional,user-definedchainsinFilter,thedefaulttable.
Filter
Thedefaulttable.ThistableismostlyusedtoDROPorACCEPT
packetsbasedontheircontent;itdoesnotalterpackets.Builtin
chainsareINPUT,FORWARD,andOUTPUT.Alluser-defined
chainsgointhistable.
NAT
TheNetworkAddressTranslationtable.Packetsthatcreatenew
connectionsareroutedthroughthistable,whichisused
exclusivelytotranslatethesourceordestinationfieldofthe
packet.BuiltinchainsarePREROUTING,OUTPUT,and
POSTROUTING.UsethistablewithDNAT,SNAT,and
MASQUERADEtargetsonly.
DNAT(destinationNAT)altersthedestinationIPaddressof
thefirstinboundpacketinaconnectionsoitisreroutedto
anotherhost.Subsequentpacketsintheconnectionare
automaticallyDNATed.Usefulforredirectingpacketsfrom
theInternetthatareboundforafirewalloraNATedserver
(page782).
SNAT(sourceNAT)altersthesourceIPaddressofthefirst
outboundpacketinaconnectionsothatitappearstocome
fromafixedIPaddressforexample,afirewallorrouter.
Subsequentpacketsintheconnectionareautomatically
SNATed.RepliestoSNATedpacketsareautomaticallyde-
SNATedsotheygobacktotheoriginalsender.SNATis
usefulforhidingLANaddressesfromsystemsoutsidethe
LANandusingasingleIPaddresstoservemultiplelocal
hosts.SeealsoMASQUERADE(next).
MASQUERADEdiffersfromSNATonlyinthatitchecksfor
anIPaddresstoapplytoeachoutboundpacket,makingit
suitableforusewithdynamicIPaddressessuchasthose
providedbyDHCP(page431).MASQUERADEisslightly
slowerthanSNAT.
Mangle
UsedexclusivelytoaltertheTOS(typeofservice),TTL(timeto
live),andMARKfieldsinapacket.Builtinchainsare
PREROUTINGandOUTPUT.
Networkpacket
Whenapacketfromthenetworkentersthekernel'snetwork
protocolstack,itisgivensomebasicsanitytests,including
checksumverification.Afterpassingthesetests,thepacket
goesthroughthePREROUTINGchain,whereitsdestination
addressmaybechanged(Figure25-2).
Figure25-2.Filteringapacketinthekernel
Nextthepacketisroutedbasedonitsdestinationaddress.Ifit
isboundforthelocalsystem,itfirstgoesthroughtheINPUT
chain,whereitcanbefiltered(accepted,dropped,orsentto
anotherchain)oraltered.Ifthepacketisnotaddressedtothe
localsystem(thelocalsystemisforwardingthepacket),itgoes
throughtheFORWARDandPOSTROUTINGchains,whereitcan
againbefilteredoraltered.
PacketsthatarecreatedlocallypassthroughtheOUTPUTand
POSTROUTINGchains,wheretheycanbefilteredoraltered
beforebeingsenttothenetwork.
State
Theconnectiontrackingmachine(sometimescalledthestate
machine)providesinformationonthestateofapacket,
allowingyoutodefinerulesthatmatchcriteriabasedonthe
stateoftheconnectionthepacketispartof.Forexample,when
aconnectionisopened,thefirstpacketispartofaNEW
connection,whereassubsequentpacketsarepartofan
ESTABLISHEDconnection.Connectiontrackingishandledby
theconntrackmodule.
TheOUTPUTchainhandlesconnectiontrackingforlocally
generatedpackets.ThePREROUTINGchainhandlesconnection
trackingforallotherpackets.Formoreinformationreferto
"State"onpage774.
Beforetheadventofconnectiontracking,itwassometimes
necessarytoopenmanyorallnonprivilegedportstomakesure
thatyouacceptedallRETURNandRELATEDtraffic.Because
connectiontrackingallowsyoutoidentifythesekindsoftraffic,
youcankeepmanymoreportsclosedtogeneraltraffic,thereby
increasingsystemsecurity.
Jumpsandtargets
Ajumportargetspecifiestheactionthekerneltakesifapacket
matchesallthematchcriteriafortherulebeingprocessed
(page775).
Aboutiptables
Thissectioncontainsinformationaboutiptables:resourcesto
consultformoreinformationonthisutility,prerequisitesfor
runningiptables,andnotes.
MoreInformation
Web
Documentation,HOWTOs,FAQs,patch-o-matic,security
informationwww.netfilter.orgTutorial
www.faqs.org/docs/iptablesScriptsandmore
www.linuxguruz.com/iptables
HOWTO
KernelAnalysis-HOWTOIPMasqueradeHOWTO(containsuseful
scripts)NetfilterExtensionsHOWTOatnetfilter.organd
www.iptables.org/documentation/HOWTO/netfilter-extensions-
HOWTO.html
Book
TCPIllustratedbyW.RichardStevens,Addison-Wesley,
December1993
Prerequisites
Installthefollowingpackage:
iptables
Runchkconfigtocauseiptablestostartwhenthesystemcomes
up:
#/sbin/chkconfigiptableson
Toensuremaximumprotection,theiptablesinitscriptstarts
packetfilteringbyrunningiptablesverysoonafterthesystem
entersrunlevels25;incontrast,thisscriptdoesnotstoppacket
filteringalmostuntilthesystemleavesrunlevels0,1,and6.
Seepage404formoreinformationoninitscripts.
Notes
TheiptablesutilitydiffersfrommostotherLinuxutilitiesinits
setupanduse.WhereasotherLinuxutilitiessuchasApache,
vsftpd,andsshdreadthedatathatcontrolstheiroperation
fromaconfigurationfile,iptablesrequiresyoutogiveaseriesof
iptablescommandstobuildasetofpacketfilteringrulesthatare
keptinthekernel.
Therearetwowaystosetupthesamesetofruleseachtime
youbringthesystemup.First,youcanputiptablescommandsin
ascriptandrunthatscripteachtimethesystemboots.Youcan
callthisscriptfrom/etc/rc.d/rc.local.
Second,youcanputtheargumentstotheiptablescommands
youwanttoexecutein/etc/sysconfig/iptables.Thesystem-
config-securitylevelutility(page777)andtheAnacondainstaller
(page47)bothusethistechnique,buildingsetsofrulesand
storingthecorrespondingiptablescommandargumentsin
/etc/sysconfig/iptables.Thecommandserviceiptables
savestorestheiptablesrulescurrentlyineffecttothisfile.If
youusethe/etc/sysconfig/iptablesfileinthismanner,be
awarethatsystem-config-securitylevelandserviceiptablessave
overwritethisfile.
Forinformationoncopyingpacketfilteringrulestoandfromthe
kernel,referto"CopyingRulestoandfromtheKernel"onpage
776.YoucanruniptableswiththeLoptionoryoucanrun
serviceiptablesstatustodisplaythepacketfilteringrulesthe
kernelisusing.
Theiptablesinitscriptexecutesthe
/etc/sysconfig/iptables-configfile.Refertothecomments
inthisfileforoptionsyoucansetinit.
Resettingiptables
Ifyouencounterproblemsrelatedtothefirewallrules,youcan
returnpacketprocessingrulesinthekerneltotheirdefault
statewithoutrebootingbygivingthefollowingcommands:
#iptables--flush&&iptables--delete-chain
Thesecommandsflushallchainsanddeleteanyuser-defined
chains,leavingthesystemwithoutafirewall.Inanemergency
youcangivethefollowingcommandtounloadalliptables
modulesfromthekernelandsetapolicyofDROPforalltables:
#/sbin/serviceiptablespanic
JumpStart:BuildingaFirewallUsingsystem-
config-securitylevel
Torunthisutility,entersystem-config-securitylevelona
commandline.FromKDEselectMainmenu:Administration
SecurityLevelandFirewallorfromGNOMEselect
System:Administration SecurityLevelandFirewall.The
system-config-securitylevelutilitybuildsanextremelysimplefirewall
butstruggleswithcomplexsetups.Thesystem-config-securitylevel
utilitydisplaystheSecurityLevelConfigurationwindow(Figure
25-3),whichhastwotabs.TheSELinuxtabisdiscussedon
page402andtheFirewallOptionstabisdiscussedhere.
Figure25-3.SecurityLevelConfigurationwindow,
FirewallOptionstab
FromtheFirewallcombobox,selectEnabled.Thefirewall
automaticallyallowspacketsthatoriginatelocallythroughto
theoutside(generallytheInternet)andallowsresponsesto
thosepacketsbackin.
OpeningTrustedservices
Clickthecheckboxesnexttotheservicesthatthelocalsystem
provides.Theseboxessetupafirewallthatallowsthelocal
systemtofunctionasoneormoreofthefollowingtypesof
servers:FTP,mail(SMTP),SSH,Samba,SecureWWW(HTTPS),
TELNET,andWWW(HTTP).
Openingotherports
Enterotherportsyouwanttoopenbyclickingthetrianglenext
toOtherportsandthenclickingAddtoopentheAddPort
window.Thiswindowallowsyoutospecifyaporttoopenand
theprotocolthateachportuses(TCPorUDP).
Caution:Openedportsarenot
maintainedwhenyoudisablethefirewall
Whenyouenableafirewallusingsystem-config-
securitylevel,specifyTrustedservicesand/oropen
Otherports,andthendisablethefirewall,the
systemdoesnotmaintainthelistofservicesand
portsyouspecified.Whenyoureenablethefirewall,
youneedtospecifytheservicesandportsagain.
Seepage776forinformationonhowyoucansave
andreloadalistofrules.
ClickOK,andsystem-config-securitylevelsetsupandturnsonthe
firewall.Formoreinformationreferto"system-config-securitylevel:
GeneratesaSetofRules"onpage777.
AnatomyofaniptablesCommand
Commandline
Thissectionliststhecomponentsofaniptablescommandline
thatfollowthenameoftheutility,iptables.Exceptasnoted,the
iptablesutilityisnotsensitivetothepositionofargumentsonthe
commandline.Theexamplesinthischapterreflectagenerally
acceptedsyntaxthatallowscommandstobeeasilyread,
understood,andmaintained.Notallcommandshaveall
components.
Manytokensonaniptablescommandlinehavetwoforms:a
shortform,consistingofasingleletterprecededbyasingle
hyphen,andalongform,consistingofawordprecededbytwo
hyphens.Mostscriptsusetheshortformsforbrevity;lines
usingthelongformscangetunwieldy.Thefollowingiptables
commandlinesareequivalentandareusedasexamplesinthis
section:
#iptables--appendFORWARD--in-interfaceeth1--out-interfaceeth0--jumpACCEPT
#iptables-AFORWARD-ieth1-oeth0-jACCEPT
Table
Specifiesthenameofthetablethecommandoperateson:
Filter,NAT,orMangle.Youcanspecifyatablenameinany
iptablescommand.Whenyoudonotspecifyatablename,the
commandoperatesontheFiltertable.Mostoftheexamplesin
thischapterdonotspecifytablenamesand,therefore,workon
theFiltertable.Specifyatableasttablenameortable
tablename.
Command
Tellsiptableswhattodowiththerestofthecommandlinefor
example,addordeletearule,displayrules,oraddachain.The
examplecommands,Aandappend,appendtherulespecified
bythecommandlinetothespecifiedtableandchain.Seepage
771foralistofcommands.
Chain
Specifiesthenameofthechainthatthisrulebelongstoorthat
thiscommandworkson.ThechainisINPUT,OUTPUT,
FORWARD,PREROUTING,POSTROUTING,orthenameofa
user-definedchain.Specifyachainbyputtingthenameofthe
chainonthecommandlinewithoutanyprecedinghyphens.The
examplesatthebeginningofthissectionworkwiththe
FORWARDchain.
Therearetwokindsofmatchcriteria:packetmatchcriteria,
whichmatchanetworkpacket,andrulematchcriteria,which
matchanexistingrule.
Rulespecifications
Packetmatchcriteriaidentifynetworkpacketsandimplement
rulesthattakeactiononpacketsthatmatchthecriteria.The
combinationofpacketmatchcriteriaandanactioniscalleda
rulespecification.Rulespecificationsformthebasisforpacket
filtering.Thefirstexampleatthebeginningofthissectionuses
thein-interfaceeth1out-interfaceeth0rulematchcriteria.
Thesecondexampleusestheshortformofthesamecriteria:i
eth1oeth0.Bothoftheserulesforwardpacketsthatcomein
ondeviceeth1andgooutondeviceeth0.
Rulematchcriteria
Rulematchcriteriaidentifyexistingrules.Aniptablescommand
canmodify,remove,orpositionanewruleadjacenttoarule
specifiedbyarulematchcriterion.Therearetwowaysto
identifyanexistingrule:Youcanusethesamerulespecification
thatwasusedtocreatetheruleoryoucanusetherule's
ordinalnumber,calledarulenumber.Rulenumbersbeginwith
1,signifyingthefirstruleinachain,andcanbedisplayedwith
iptablesL(orline-numbers).Thefirstcommandbelow
deletestherulelistedatthebeginningofthissection;the
secondreplacesrulenumber3intheINPUTchainwitharule
thatrejectsallpacketsfromIPaddress192.168.0.10:
#iptables--delete-AFORWARD-ieth1-oeth0-jACCEPT
#iptables-RINPUT3--source192.168.0.10--jumpREJECT
Ajumportargetspecifieswhatactionthekerneltakeson
packetsthatmatchallmatchcriteriaforarule.Specifyajump
ortargetasjtargetorjumptarget.Theexamplesatthe
beginningofthissectionspecifytheACCEPTtargetusingthe
followingcommands:jumpACCEPTandjACCEPT.
Jumps
Ajumptransferscontroltoadifferentchainwithinthesame
table.Thefollowingcommandadds(append)aruletothe
INPUTchainthattransferspacketsthatusetheTCPprotocol
(protocoltcp)toauser-definedchainnamedtcp_rules
(jumptcp_rules):
#iptables--appendINPUT--protocoltcp--jumptcp_rules
Whenthepacketfinishestraversingthetcp_ruleschain,
assumingithasnotbeendroppedorrejected,itcontinues
traversingtheINPUTchainfromtherulefollowingtheoneit
jumpedfrom.
Targets
Atargetspecifiesanactionthekerneltakesonthepacket;the
simplestactionsareACCEPT,DROP,andREJECT.Thefollowing
commandaddsaruletotheFORWARDchainthatrejects
packetscomingfromtheFTPport(/etc/services,thefile
iptablesconsultstodeterminewhichporttouse,showsthatFTP
BuildingaSetofRules
Tospecifyatable,itiscommonpracticetoputthetable
declarationonthecommandlineimmediatelyfollowing
iptables.Forexample,thefollowingcommandflushes(deletes
alltherulesfrom)theNATtable:
#iptables-tNAT-F
Commands
Followingisalistofiptablescommands:
append
AAddsrule(s)specifiedbyrule-specificationstotheendof
chain.Whenapacketmatchesoneoftherule-specifications,
targetprocessesit.
iptablesAchainrule-specificationsjumptarget
delete
DRemovesoneormorerulesfromchain,asspecifiedbythe
rule-numbersorrule-specifications.
iptablesDchainrule-numbers|rule-specifications
insert
IAddsrule(s)specifiedbyrule-specificationsandtargetto
thelocationinchainspecifiedbyrule-number.Ifyoudonot
specifyrule-number,itdefaultsto1,theheadofthechain.
iptablesIchainrule-numberrule-
specificationsjumptarget
replace
RReplacesrulenumberrule-numberinchainwithrule-
specificationandtarget.Thecommandfailsifrule-number
orrule-specificationresolvestomorethanoneaddress.
iptablesRchainrule-numberrule-
specificationjumptarget
list
LDisplaystherulesinchain.Omitchaintodisplayrulesforall
chains.Useline-numberstodisplayrulenumbersorselect
otherdisplaycriteriafromthelistonpage772.
iptablesL[chain]display-criteria
flush
FDeletesallrulesfromchain.Omitchaintodeleteallrules
fromallchains.
iptablesF[chain]
zero
ZChangetozerothevalueofallpacketandbytecountersin
chainorinallchainswhenyoudonotspecifychain.Usewith
Ltodisplaythecountersbeforeclearingthem.
iptablesZ[L][chain]
delete-chain
XRemovestheuser-definedchainnamedchain.Ifyoudonot
specifychain,removesalluser-definedchains.Youcannot
deleteachainthatatargetpointsto.
iptablesXchain
policy
PSetsthedefaulttargetorpolicybuiltin-targetforthebuiltin
chainbuiltin-chain.Thispolicyisappliedtopacketsthatdo
notmatchanyruleinthechain.Ifachaindoesnothavea
policy,unmatchedpacketsareACCEPTed.
iptablesPbuiltin-chainbuiltin-target
rename-chain
EChangesthenameofthechainoldtonew.
iptablesEoldnew
help
hDisplaysasummaryofiptablescommandsyntax.
iptablesh
Followamatchextensionprotocolwithhtodisplayoptionsyou
canusewiththatprotocol.Formoreinformationreferto"Help
withextensions"onpage773.
PacketMatchCriteria
Thefollowingcriteriamatchnetworkpackets.Whenyou
precedeacriterionwithanexclamationpoint(!),therule
matchespacketsthatdonotmatchthecriterion.
protocol[!]proto
pMatchesifthepacketusestheprotoprotocol.Thiscriterion
isamatchextension(page773).
source[!]address[/mask]
sorsrcMatchesifthepacketcamefromaddress.The
addresscanbeanameorIPaddress.Seepage423for
formatsoftheoptionalmask(onlywithanIPaddress).
destination[!]address[/mask]
dordstMatchesifthepacketisgoingtoaddress.The
addresscanbeanameorIPaddress.Seepage423for
formatsoftheoptionalmask(onlywithanIPaddress).
in-interface[!]iface[+]
iFortheINPUT,FORWARD,andPREROUTINGchains,matches
ififaceisthenameoftheinterfacethepacketwasreceived
from.Appendaplussign(+)toifacetomatchanyinterface
whosenamebeginswithiface.Whenyoudonotspecifyin-
interface,therulematchespacketscomingfromanyinterface.
out-interface[!]iface[+]
oFortheFORWARD,OUTPUT,andPOSTROUTINGchains,
matchesififaceistheinterfacethepacketwillbesentto.
Appendaplussign(+)toifacetomatchanyinterfacewhose
namebeginswithiface.Whenyoudonotspecifyout-
interface,therulematchespacketsgoingtoanyinterface.
[!]fragment
fMatchesthesecondandsubsequentfragmentsoffragmented
packets.Becausethesepacketsdonotcontainsourceor
destinationinformation,theydonotmatchanyotherrules.
DisplayCriteria
Thefollowingcriteriadisplayinformation.Allpacketsmatch
thesecriteria.
verbose
vDisplaysadditionaloutput.
numeric
nDisplaysIPaddressesandportnumbersasnumbers,not
names.
exact
xUsewithLtodisplayexactpacketandbytecountsinsteadof
roundedvalues.
line-numbers
Displaylinenumberswhenlistingrules.Thelinenumbersare
alsotherulenumbersthatyoucanuseinrulematchcriteria
(page770).
MatchExtensions
Rulespecification(packetmatchcriteria)extensions,called
matchextensions,addmatchesbasedonprotocolsandstateto
thematchesdescribedpreviously.Eachoftheprotocol
extensionsiskeptinamodulethatmustbeloadedbeforethat
matchextensioncanbeused.Thecommandthatloadsthe
modulemustappearinthesamerulespecificationas,andto
theleftof,thecommandthatusesthemodule.Therearetwo
typesofmatchextensions:implicitandexplicit.
ImplicitMatchExtensions
Helpwithextensions
Implicitextensionsareloaded(somewhat)automaticallywhen
youuseaprotocolcommand(following).Eachprotocolhasits
ownextensions.Followtheprotocolwithhtodisplayextensions
youcanusewiththatprotocol.Forexample,thefollowing
commanddisplaysTCPextensionsattheendoftheHelp
output:
#iptables-ptcp-h
...
TCPv1.3.5options:
--tcp-flags[!]maskcompmatchwhenTCPflags&mask==comp
(Flags:SYNACKFINRSTURGPSHALLNONE)
[!]--synmatchwhenonlySYNflagset
(equivalentto--tcp-flagsSYN,RST,ACKSYN)
--source-port[!]port[:port]
--sport...
matchsourceport(s)
--destination-port[!]port[:port]
--dport...
matchdestinationport(s)
--tcp-option[!]numbermatchifTCPoptionset
Thissectiondoesnotdescribeallextensions.Useh,as
describedintheprecedingexample,todisplayacompletelist.
protocol[!]proto
pLoadstheprotomoduleandmatchesifthepacketusesthe
protoprotocol.Theprotocanbeanameornumberfrom
/etc/protocols,includingtcp,udp,andicmp(page1036).
Specifyingallor0(zero)matchesanyofallprotocolsandis
thesameasnotincludingthismatchinarule.
ThefollowingcriterialoadtheTCPmoduleandmatchTCP
protocolpacketscomingfromport22(sshpackets):
--protocoltcp--source-port22
Thefollowingcommandexpandstheprecedingmatchtocause
thekerneltodropallincomingsshpackets.Thiscommanduses
ssh,whichiptableslooksupin/etc/services,inplaceof22:
#iptables--protocoltcp--source-portssh--jumpDROP
TCP
Theextensionsinthissectionareloadedwhenyouspecify
protocoltcp.
destination-port[!][port][:port]]
dportMatchesadestinationportnumberorservicename(see
/etc/services).Youcanalsospecifyarangeofportnumbers.
Specifically,:portspecifiesports0throughport,andport:
specifiesportsportthrough65535.
source-port[!][port][:port]]
sportMatchesasourceportnumberorservicename(see
/etc/services).Youcanalsospecifyarangeofportnumbers.
Specifically,:portspecifiesports0throughport,andport:
specifiesportsportthrough65535.
[!]syn
MatchespacketswiththeSYNbitsetandtheACKandFINbits
cleared.Thismatchextensionisshorthandfortcp-flags
SYN,RST,ACKSYN.
tcp-flags[!]maskcomp
DefinesTCPflagsettingsthatconstituteamatch.Validflagsare
SYN,ACK,FIN,RST,URG,PSH,ALL,andNONE.Themaskisa
comma-separatedlistofflagstobeexamined;compisa
comma-separatedsubsetofmaskthatspecifiestheflagsthat
mustbesetforamatchtooccur.Flagsnotspecifiedinmask
mustbeunset.
tcp-option[!]n
MatchesaTCPoptionwithadecimalvalueofn.
UDP
Whenyouspecifyprotocoludp,youcanspecifyasource
and/ordestinationportinthesamemannerasdescribedearlier
under"TCP."
ICMP
Theextensioninthissectionisloadedwhenyouspecify
protocolicmp.ICMP(page1036)packetscarrymessages
only.
icmp-type[!]name
MatcheswhenthepacketisanICMPpacketoftypename.The
namecanbeanumericICMPtypeoroneofthenames
returnedby
#iptables-picmp-h
ExplicitMatchExtensions
Explicitmatchextensionsdifferfromimplicitmatchextensions
inthatyoumustuseamormatchoptiontospecifyamodule
beforeyoucanusetheextension.Manyexplicitmatch
extensionmodulesareavailable;thissectioncoversstate,one
ofthemostimportant.
State
Thestateextensionmatchescriteriabasedonthestateofthe
connectionthepacketispartof(page766).
statestate
Matchesapacketwhosestateisdefinedbystate,acomma-
separatedlistofstatesfromthefollowinglist:
ESTABLISHEDAnypacket,withinaspecificconnection,
followingtheexchangeofpacketsinbothdirectionsforthat
connection.
INVALIDAstatelessorunidentifiablepacket.
NEWThefirstpacketwithinaspecificconnection,typically
aSYNpacket.
RELATEDAnypacketsexchangedinaconnectionspawned
fromanESTABLISHEDconnection.Forexample,anFTP
dataconnectionmightberelatedtotheFTPcontrol
connection.(Youneedtheip_conntrack_ftpmodulefor
FTPconnectiontracking.)
Thefollowingcommandloadsthestateextensionand
establishesarulethatmatchesanddropsbothinvalidpackets
andpacketsfromnewconnections:
#iptables--matchstate--stateINVALID,NEW--jumpDROP
Targets
Alltargetsarebuiltin;therearenouser-definedtargets.This
sectionlistssomeofthetargetsavailablewithiptables.
Applicabletargetoptionsarelistedfollowingeachtarget.
ACCEPT
Continuesprocessingthepacket.
DNAT
DestinationNetworkAddressTranslationRewritesthe
destinationaddressofthepacket(page765).
to-destinationip[-ip][:port-port]
SameasSNATwithto-source,exceptthatitchangesthe
destinationaddressesofpacketstothespecifiedaddress(es)
andport(s)andisvalidonlyinthePREROUTINGorOUTPUT
chainsoftheNATtableandanyuser-definedchainscalledfrom
thosechains.ThefollowingcommandaddstothePREROUTING
chainoftheNATtablearulethatchangesthedestinationinthe
headersofTCPpacketswithadestinationof66.187.232.50to
192.168.0.10:
#iptables-tNAT-APREROUTING-ptcp-d66.187.232.50-jDNAT--to-destination192.168.0.10
DROP
Endsthepacket'slifewithoutnotice.
LOG
Turnsonloggingforthepacketbeingprocessed.Thekernel
usessyslogd(page562)toprocessoutputgeneratedbythis
target.LOGisanonterminatingtarget;processingcontinues
withthenextrule.UsetworulestoLOGpacketsthatyou
REJECT,oneeachwiththetargetsLOGandREJECT,withthe
samematchingcriteria.
log-leveln
Specifieslogginglevelnaspersyslog.conf(page562).
log-prefixstring
Prefixeslogentrieswithstring,whichcanbeupto14
characterslong.
log-tcp-options
LogsoptionsfromtheTCPpacketheader.
log-ip-options
LogsoptionsfromtheIPpacketheader.
MASQUERADE
SimilartoSNATwithto-source,exceptthattheIPinformation
isgrabbedfromtheinterfaceonthespecifiedport.Foruseon
systemswithdynamicallyassignedIPaddresses,suchasthose
thatuseDHCP,includingmostdial-uplines.Validonlyinrules
inthePOSTROUTINGchainoftheNATtable.
to-portsport[-port]
Specifiestheportfortheinterfaceyouwanttomasquerade.
Forgetsconnectionswhentheinterfacegoesdown,asis
appropriatefordial-uplines.YoumustspecifytheTCPorUDP
protocol(protocoltcporudp)withthistarget.
REJECT
SimilartoDROP,exceptthatitnotifiesthesendingsystemthat
thepacketwasblocked.
reject-withtype
Returnstheerrortypetotheoriginatingsystem.Thetypecan
beanyofthefollowing,allofwhichreturntheappropriateICMP
(page1036)error:icmp-net-unreachable,icmp-host-
unreachable,icmp-port-unreachable,icmp-proto-
unreachable,icmp-net-prohibited,oricmp-host-
prohibited.Youcanspecifytypeasecho-replyfromrules
thatrequireanICMPping(page365)packettoreturnaping
reply.Youcanspecifytcp-resetfromrulesinorcalledfromthe
INPUTchaintoreturnaTCPRSTpacket.Thisparameterisvalid
intheINPUT,FORWARD,andOUTPUTchainsanduser-defined
chainscalledfromthesechains.
RETURN
Stopstraversingthischainandreturnsthepackettothecalling
chain.
SNAT
SourceNetworkAddressTranslationRewritesthesource
addressofthepacket.AppropriateforhostsonaLANthat
shareanInternetconnection.
to-sourceip[-ip][:port-port]
AltersthesourceIPaddressofanoutboundpacket,andthe
sourceIPaddressesofallfuturepacketsinthisconnection,to
ip.Skipsadditionalrules,ifany.Returningpacketsare
automaticallyde-SNATedsotheyreturntotheoriginatinghost.
ValidonlyinthePOSTROUTINGchainoftheNATtable.
WhenyouspecifyarangeofIPaddresses(ip-ip)oruse
multipleto-sourcetargets,iptablesassignstheaddressesina
round-robinfashion,cyclingthroughtheaddresses,onefor
eachnewconnection.
WhentherulespecifiestheTCPorUDPprotocol(ptcporp
udp),youcanspecifyarangeofports.Whenyoudonot
specifyarangeofports,therulematchesallports.Every
connectiononaNATedsubnetmusthaveauniqueIPaddress
andportcombination.IftwocomputersonaNATedsubnettry
tousethesameport,thekernelmapsoneoftheportsto
another(unused)one.Portslessthan512aremappedtoother
portslessthan512,portsfrom512to1024aremappedto
otherportsfrom512to1024,andportsabove1024are
mappedtootherportsabove1024.
CopyingRulestoandfromtheKernel
Theiptables-saveutilitycopiespacketfilteringrulesfromthe
kerneltostandardoutputsoyoucansavetheminafile.The
iptables-restoreutilitycopiesrulesfromstandardinput,aswritten
byiptables-save,tothekernel.Sampleoutputfromiptables-save
follows:
#iptables-save
#Generatedbyiptables-savev1.3.5onTueMar720:52:042006
*filter
:INPUTACCEPT[0:0]
:FORWARDACCEPT[0:0]
:OUTPUTACCEPT[4779:2823599]
:RH-Firewall-1-INPUT-[0:0]
-AINPUT-jRH-Firewall-1-INPUT
-AFORWARD-jRH-Firewall-1-INPUT
-ARH-Firewall-1-INPUT-ilo-jACCEPT
...
COMMIT
Mostofthelinesthatiptables-savewritesareiptablescommand
lineswithouttheiptablesatthebeginning.Linesthatbegin
withapoundsign(#)arecomments.Linesthatbeginwithan
asteriskarenamesoftablesthatthefollowingcommandswork
on;allofthecommandsintheprecedingexampleworkonthe
Filtertable.TheCOMMITlinemustappearattheendofall
commandsforatable;itexecutestheprecedingcommands.
Linesthatbeginwithcolonsspecifychainsinthefollowing
format:
:chainpolicy[packets:bytes]
wherechainisthenameofthechain,policyisthepolicy
(defaulttarget)forthechain,andpacketsandbytesarethe
packetandbytecounters,respectively.Thesquarebrackets
mustappearintheline;theydonotindicateoptional
parameters.Refertothenextsectionandvisit
system-config-securitylevel:GeneratesaSetof
Rules
Thissectiondescribesthesetofrulesgeneratedbysystem-config-
securitylevel(page768)whenyouaskittocreateafirewallwith
onlysshrunningasatrustedserviceandnootherports
specified.Thesystem-config-securitylevelutilitywritestherulesin
theformatusedbyiptables-save(seetheprecedingsection)to
the/etc/sysconfig/iptablesfile,whichisreadbythe
iptablesinitscriptsothatthefirewallisimplementedeach
timethesystemboots.Seethetiponpage769aboutdisabling
thefirewallusingthisutility.
Inthefollowinglisting,*filterindicatesthatthecommands
appearingafteritworkontheFiltertable.Thefirstlinethat
beginswithacolonspecifiesthatthepolicyfortheINPUTchain
intheFiltertableisACCEPT.FORWARDandOUTPUTchainsare
specifiedsimilarly.Becausethecountersforallthechainsare
zero,thecounterswillberesettozeroeachtimethesystem
bootsandinitializesiptablesfromthisfile.
Thesystem-config-securitylevelutilitycreatesauser-definedchain
namedRH-Firewall-1-INPUT.Nopolicyisspecifiedbecause
user-definedchainscannothavepolicies.
#cat/etc/sysconfig/iptables
#Firewallconfigurationwrittenbysystem-config-securitylevel
#Manualcustomizationofthisfileisnotrecommended.
*filter
:INPUTACCEPT[0:0]
:FORWARDACCEPT[0:0]
:OUTPUTACCEPT[0:0]
:RH-Firewall-1-INPUT-[0:0]
-AINPUT-jRH-Firewall-1-INPUT
-AFORWARD-jRH-Firewall-1-INPUT
-ARH-Firewall-1-INPUT-ilo-jACCEPT
-ARH-Firewall-1-INPUT-picmp--icmp-typeany-jACCEPT
-ARH-Firewall-1-INPUT-p50-jACCEPT
-ARH-Firewall-1-INPUT-p51-jACCEPT
-ARH-Firewall-1-INPUT-pudp--dport5353-d224.0.0.251-jACCEPT
-ARH-Firewall-1-INPUT-pudp-mudp--dport631-jACCEPT
-ARH-Firewall-1-INPUT-ptcp-mtcp--dport631-jACCEPT
-ARH-Firewall-1-INPUT-mstate--stateESTABLISHED,RELATED-jACCEPT
-ARH-Firewall-1-INPUT-mstate--stateNEW-mtcp-ptcp--dport22-jACCEPT
-ARH-Firewall-1-INPUT-jREJECT--reject-withicmp-host-prohibited
COMMIT
ThefirsttwolinesthatbeginwithAaddrulestotheINPUTand
FORWARDchainsthatcausecontroltotransfertotheRH-
Firewall-1-INPUTchain.Thesubsequentlinesappendrulesto
theRH-Firewall-1-INPUTchain.Followingisadescriptionof
whattherestofthelinesdo.
Thislineacceptspacketsfromthelocalinterface:
-ARH-Firewall-1-INPUT-ilo-jACCEPT
ThislineacceptsallICMPpackets:
-ARH-Firewall-1-INPUT-picmp--icmp-typeany-jACCEPT
Theselinesacceptpacketsthatmatchprotocols50and51,
which/etc/protocolslistsasIPv6-CryptandIPv6-Auth,both
encryptionheadersforIPv6:
-ARH-Firewall-1-INPUT-p50-jACCEPT
-ARH-Firewall-1-INPUT-p51-jACCEPT
ThenextlineacceptsmulticastDNS(www.multicastdns.org)
packets:
-ARH-Firewall-1-INPUT-pudp--dport5353-d224.0.0.251-jACCEPT
TheselinesallowIPP(page504)UDPandTCPpacketsthrough:
-ARH-Firewall-1-INPUT-pudp-mudp--dport631-jACCEPT
-ARH-Firewall-1-INPUT-ptcp-mtcp--dport631-jACCEPT
Thislineusesmtospecifythestatemoduleandaccepts
ESTABLISHEDandRELATEDpackets:
-ARH-Firewall-1-INPUT-mstate--stateESTABLISHED,RELATED-jACCEPT
ThislineallowsTCPpacketsthroughonport22(ssh):
-ARH-Firewall-1-INPUT-mstate--stateNEW-mtcp-ptcp--dport22-jACCEPT
Thislinerejectsallpacketsthathavenotbeenacceptedand
returnsICMPerroricmp-host-prohibitedtothesystemthat
sentthepacket:
-ARH-Firewall-1-INPUT-jREJECT--reject-withicmp-host-prohibited
COMMITexecutestheprecedingcommands.Withthepreceding
rulesloaded,youcanuseiptablestolisttherulesandseethe
defaultsthatiptablesputsinplace:
#iptables-L
ChainINPUT(policyACCEPT)
targetprotoptsourcedestination
RH-Firewall-1-INPUTall--anywhereanywhere
ChainFORWARD(policyACCEPT)
targetprotoptsourcedestination
RH-Firewall-1-INPUTall--anywhereanywhere
ChainOUTPUT(policyACCEPT)
targetprotoptsourcedestination
ChainRH-Firewall-1-INPUT(2references)
targetprotoptsourcedestination
ACCEPTall--anywhereanywhere
ACCEPTicmp--anywhereanywhereicmpany
ACCEPTipv6-crypt--anywhereanywhere
ACCEPTipv6-auth--anywhereanywhere
ACCEPTudp--anywhere224.0.0.251udpdpt:5353
ACCEPTudp--anywhereanywhereudpdpt:ipp
ACCEPTtcp--anywhereanywheretcpdpt:ipp
ACCEPTall--anywhereanywherestateRELATED,ESTABLISHED
ACCEPTtcp--anywhereanywherestateNEWtcpdpt:ssh
REJECTall--anywhereanywherereject-withicmp-host-prohibited
SharinganInternetConnectionUsingNAT
OntheInternettherearemanyscriptsavailablethatsetup
Internetconnectionsharingusingiptables.Eachofthesescripts
boilsdowntothesamefewbasiciptablescommands,albeitwith
minordifferences.Thissectiondiscussesthosefewstatements
toexplainhowaconnectioncanbeshared.Youcanusethe
statementspresentedinthissectionorrefertotheLinuxIP
MasqueradeHOWTOforcompletescripts.The
tldp.org/HOWTO/IP-Masquerade-HOWTO/firewall-
examples.htmlWebpageholdsthesimplestofthesescripts.
Therearetwowaysyoucanshareasingleconnectiontothe
Internet(oneIPaddress).BothinvolvesettingupNATtoalter
addressesinpacketsandthenforwardthem.Thefirstallows
clients(browsers,mailreaders,andsoon)onseveralsystems
onaLANtoshareasingleIPaddresstoconnecttoserverson
theInternet.Thesecondallowsservers(mail,Web,FTP,andso
on)ondifferentsystemsonaLANtoprovidetheirservicesover
asingleconnectiontotheInternet.Youcanuseiptablestosetup
oneorbothoftheseconfigurations.Inbothcases,youneedto
setupasystemthatisarouter:Itmusthavetwonetwork
connectionsoneconnectedtotheInternetandtheothertothe
LAN.
Foroptimalsecurity,useadedicatedsystemasarouter.
Becausedatatransmissionoveraconnectiontothe
Internetevenoverabroadbandconnectionisrelativelyslow,
usingaslower,oldersystemasarouterdoesnotgenerallyslow
downaLAN.Thissetupalsogivesyousomedefenseagainst
intrusionfromtheInternet.AworkstationontheLANcanalso
functionasarouter,butthissetupmeansthatyoumaintain
dataonasystemthatisdirectlyconnectedtotheInternet.The
followingsectionsdiscussthesecurityofeachsetup.
Theexamplesinthissectionassumethatthedevicenamed
eth0connectstotheInterneton10.255.255.255andthat
eth1connectstotheLANon192.168.0.1.Substitutethe
devicesandIPaddressesthatyoursystemsuse.Ifyouusea
modemtoconnecttotheInternet,youneedtosubstituteppp0
(oranotherdevice)foreth0intheexamples.
Fortheexamplesinthissectiontowork,youmustturnonIP
forwarding.Firstgivethefollowingcommandandmakesure
everythingisworking:
#/sbin/sysctl-wnet.ipv4.ip_forward=1
net.ipv4.ip_forward=1
Onceyouknowthatiptablesisworkingcorrectly,changethe0to
a1inthefollowinglinein/etc/sysctl.conftomakethekernel
alwaysperformIPforwarding:
net.ipv4.ip_forward=0
Aftermakingthischange,givethecommand/sbin/sysctlpto
applythechangeandtomakesurethatthereareno
typographicalerrorsintheconfigurationfile.
ConnectingSeveralClientstoaSingleInternet
Connection
Configuringthekerneloftheroutersystemtoallowclientson
multiplelocalsystemsontheLANtoconnecttotheInternet
requiresyoutosetupIPmasquerading,orSNAT(sourceNAT).
IPmasqueradingtranslatesthesourceanddestination
addressesintheheadersofnetworkpacketsthatoriginateon
localsystemsandthepacketsthatremoteserverssendin
responsetothosepackets.Thesepacketsarepartof
connectionsthatoriginateonalocalsystem.Theexamplein
thissectiondoesnothingtopacketsthatarepartofconnections
thatoriginateontheremotesystems(ontheInternet):These
packetscannotgetpasttheroutersystem,whichprovides
somedegreeofsecurity.
Thepointofrewritingthepacketheadersistoallowsystems
withdifferentlocalIPaddressestoshareasingleIPaddresson
theInternet.Theroutersystemtranslatesthesourceororigin
addressofpacketsfromlocalsystemstothatoftheInternet
connection,sothatallpacketspassingfromtheroutertothe
Internetappeartocomefromasinglesystem10.255.255.255
intheexample.Allpacketssentinresponsebyremotesystems
ontheInternettotheroutersystemhavetheaddressofthe
Internetconnection10.255.255.255intheexampleastheir
destinationaddress.Theroutersystemrememberseach
connectionandaltersthedestinationaddressofeachresponse
packettobecomethatofthelocal,originatingsystem.
Theroutersystemisestablishedbyfouriptablescommands,one
ofwhichsetsupalogofmasqueradedconnections.Thefirst
commandputsthefirstruleintheFORWARDchainoftheFilter
(default)table(AFORWARD):
#iptables-AFORWARD-ieth0-oeth1-mstate--stateESTABLISHED,RELATED-jACCEPT
Tomatchthisrule,apacketmustbe
1. Receivedoneth0(cominginfromtheInternet):ieth0.
2. Goingtobesentoutoneth1(goingouttotheLAN):o
eth1.
3. Partofanestablishedconnectionoraconnectionthatis
relatedtoanestablishedconnection:state
ESTABLISHED,RELATED.
Thekernelaccepts(jACCEPT)packetsthatmeetthesethree
criteria.Acceptedpacketspasstothenextappropriatechainor
table.PacketsfromtheInternetthatattempttocreateanew
connectionarenotmatchedandthereforenotacceptedbythis
rule.Packetsthatarenotacceptedpasstothenextruleinthe
FORWARDchain.
ThesecondcommandputsthesecondruleintheFORWARD
chainoftheFiltertable:
#iptables-AFORWARD-ieth1-oeth0-jACCEPT
Tomatchthisrule,apacketmustbe
1. Receivedoneth1(cominginfromtheLAN):ieth1.
2. Goingtobesentoutoneth0(goingouttotheInternet):o
eth0.
Thekernelacceptspacketsthatmeetthesetwocriteria,which
meansthatallpacketsthatoriginatelocallyandaregoingto
theInternetareaccepted.Acceptedpacketspasstothenext
appropriatechain/table.Packetsthatarenotacceptedpassto
thenextruleintheFORWARDchain.
ThethirdcommandputsthethirdruleintheFORWARDchainof
theFiltertable:
#iptables-AFORWARD-jLOG
Becausethisrulehasnomatchcriteria,itactsonallpacketsit
processes.Thisrule'sactionistologpacketsthatis,itlogs
packetsfromtheInternetthatattempttocreateanew
connection.
PacketsthatgettotheendoftheFORWARDchainoftheFilter
tablearedonewiththerulessetupbyiptablesandarehandled
bythelocalTCPstack.PacketsfromtheInternetthatattempt
tocreateanewconnectionontheroutersystemareaccepted
orreturned,dependingonwhethertheservicetheyaretrying
toconnecttoisavailableontheroutersystem.
ThefourthcommandputsthefirstruleinthePOSTROUTING
chainoftheNATtable.Onlypacketsthatareestablishinganew
connectionarepassedtotheNATtable.Onceaconnectionhas
beensetupforSNATorMASQUERADE,theheadersonall
subsequentESTABLISHEDandRELATEDpacketsarealteredthe
samewayasthefirstpacket.Packetsthataresentinresponse
tothesepacketsautomaticallyhavetheirheadersadjustedso
thattheyreturntotheoriginatinglocalsystem.
#iptables-tNAT-APOSTROUTING-oeth0-jMASQUERADE
Tomatchthisrule,apacketmustbe
1. Establishinganewconnection(otherwiseitwouldnothave
cometotheNATtable).
2. Goingtobesentoutoneth0(goingouttotheInternet):o
eth0.
ThekernelMASQUERADEsallpacketsthatmeetthesecriteria.
Inotherwords,alllocallyoriginatingpacketsthatare
establishingnewconnectionshavetheirsourceaddress
changedtotheaddressthatisassociatedwitheth0
(10.255.255.255intheexample).
Followingarethefourcommandstogether:
#iptables-AFORWARD-ieth0-oeth1-mstate--stateESTABLISHED,RELATED-jACCEPT
#iptables-AFORWARD-ieth1-oeth0-jACCEPT
#iptables-AFORWARD-jLOG
#iptables-tNAT-APOSTROUTING-oeth0-jMASQUERADE
Youcanputthesecommandsin/etc/rc.localorinascript
calledbythisfileontheroutersystemtohavethemexecuted
eachtimethesystemboots.Alternatively,youcanputthemin
/etc/sysconfig/iptables,leavingofftheiptablescommandat
thebeginningofeachlineandaddingafinallinewiththeword
COMMITonit.Whenyouputthecommandsintheiptables
file,theyareexecutedbytheiptablesinitscripteachtimeitis
called.Formoreinformationreferto"CopyingRulestoand
fromtheKernel"onpage776.
TolimitthelocalsystemsthatcanconnecttotheInternet,you
canaddas(source)matchcriteriontothelastcommand:
#iptables-tNAT-APOSTROUTING-oeth0-s192.168.0.0-192.168.0.32-jMASQUERADE
Intheprecedingcommand,s192.168.0.0-192.168.0.32
causesonlypacketsfromanIPaddressinthespecifiedrangeto
beMASQUERADEd.
ConnectingSeveralServerstoaSingleInternet
Connection
DNAT(destinationNAT)cansetuprulestoallowclientsfrom
theInternettosendpacketstoserversontheLAN.This
examplesetsupanSMTPmailserveron192.168.1.33andan
HTTP(Web)serveron192.168.1.34.BothprotocolsuseTCP.
SMTPusesport25andHTTPusesport80,sotherulesmatch
TCPpacketswithdestinationportsof25and80.Theexample
assumesthemailserverdoesnotmakeoutgoingconnections
andusesanotherserverontheLANforDNSandmailrelaying.
BothcommandsputrulesinthePREROUTINGchainoftheNAT
table(APREROUTINGtNAT):
#iptables-APREROUTING-tNAT-ptcp--dport25--to-source192.168.0.33:25-jDNAT
#iptables-APREROUTING-tNAT-ptcp--dport80--to-source192.168.0.34:80-jDNAT
Tomatchtheserules,thepacketmustusetheTCPprotocol(p
tcp)andhaveadestinationportof25(firstrule,dport25)or
80(secondrule,dport80).
Theto-sourceisatargetspecifictothePREROUTINGand
OUTPUTchainsoftheNATtable;italtersthedestination
addressandportofmatchedpacketsasspecified.Aswith
MASQUERADEandSNAT,subsequentpacketsinthesameand
relatedconnectionsarealteredappropriately.
Thefactthattheserverscannotoriginateconnectionsmeans
thatneitherservercanbeexploitedtoparticipateinaDDoS
attack(page1028)onsystemsontheInternetandcannotsend
privatedatafromthelocalsystembacktoamalicioususer's
system.
ChapterSummary
Theiptablesutilitycreatesfirewallsintendedtoprevent
unauthorizedaccesstoasystemornetwork.Aniptables
commandsetsupormaintainsinthekernelrulesthatcontrol
theflowofnetworkpackets;rulesarestoredinchains.Each
rulehasacriteriapartandanactionpart,calledatarget.When
thecriteriapartmatchesanetworkpacket,thekernelapplies
theactionfromtheruletothepacket.
Chainsarecollectedinthreetables:Filter,NAT,andMangle.
Filter,thedefaulttable,DROPsorACCEPTspacketsbasedon
theircontent.NAT,theNetworkAddressTranslationtable,
translatesthesourceordestinationfieldofpackets.Mangleis
usedexclusivelytoalterTOS(typeofservice),TTL(timeto
live),andMARKfieldsinapacket.Theconnectiontracking
machine,whichishandledbytheconntrackmodule,defines
rulesthatmatchcriteriabasedonthestateoftheconnectiona
packetispartof.
Inanemergencyyoucangivethefollowingcommandtounload
alliptablesmodulesfromthekernelandsetapolicyofDROPfor
alltables:
#/sbin/serviceiptablespanic
Exercises
1. Howwouldyouremovealliptablesrulesandchains?
2. Howwouldyoulistallcurrentiptablesrules?
3. HowisconfiguringiptablesdifferentfromconfiguringmostLinuxservices?
4. DefineaniptablesrulethatwillrejectincomingconnectionsontheTELNETport.
5. WhatdoesNATstandfor?WhatdoestheNATtabledo?
AdvancedExercises
6. Whatdoestheconntrackmoduledo?
7. Whatdorulematchcriteriado?Whataretheyusedfor?
8. Whatdopacketmatchcriteriado?Whataretheyusedfor?
9. Whichutilitiescopypacketfilteringrulestoandfromthekernel?Howdothey
work?
10. DefinearulethatwillsilentlyblockincomingSMTPconnectionsfromspmr.com.
26.Apache(httpd):SettingUpaWeb
Server
INTHISCHAPTER
JumpStartI:GettingApacheUpandRunning 789
JumpStartII:SettingUpApacheUsingsystem-config-httpd 790
FilesystemLayout 792
DirectivesI:DirectivesYouMayWanttoModifyasYouGet
Started
794
ContextsandContainers 798
TheRedHathttpd.confFile 814
Redirects 817
Multiviews 818
VirtualHosts 818
Troubleshooting 819
TheWorldWideWeb(WWWorWebforshort),isacollectionof
serversthatholdmaterial,calledcontent,thatWebbrowsers
(orjustbrowsers)candisplay.EachoftheserversontheWeb
isconnectedtotheInternet,anetworkofnetworks(an
internetwork).MuchofthecontentontheWebiscodedin
HTML(HypertextMarkupLanguage,page1036).Hypertext,the
codebehindthelinksthatyouclickonaWebpage,allows
browserstodisplayandreacttolinksthatpointtootherWeb
pagesontheInternet.
ApacheisthemostpopularWebserverontheInternettoday.It
isbothrobustandextensible.Theeasewithwhichyoucan
install,configure,andrunitintheLinuxenvironmentmakesit
anobviouschoiceforpublishingcontentontheWorldWide
Web.TheApacheserverandrelatedprojectsaredevelopedand
maintainedbytheApacheSoftwareFoundation(ASF),anotfor-
profitcorporationformedinJune1999.TheASFgrewoutofthe
ApacheGroup,whichwasestablishedin1995todevelopthe
Apacheserver.
Thischapterstartsbyprovidingintroductoryinformationabout
Apache.ThisinformationisfollowedbythefirstJumpStart
section,whichdescribestheminimumstepsneededtoget
Apacheupandrunning.ThesecondJumpStartsectioncovers
theuseoftheRedHatsystem-config-httpdconfigurationscript.
Followingthesesectionsis"FilesystemLayout,"whichtellsyou
wherethevariousApachefilesarelocated.
Configurationdirectives,akeypartofApache,arediscussed
startingonpage794.Thissectionincludescoverageofcontexts
andcontainers,twofeatures/conceptsthatarecriticalto
understandingApache.Thenextsectionexplainsthemain
Apacheconfigurationfile,/etc/httpd/conf/httpd.conf,as
modifiedbyRedHat.Thefinalpagesofthechaptercover
virtualhosts,troubleshooting,andmodulesyoucanusewith
Apache,includingCGIandSSL.
Introduction
ApacheisaserverthatrespondstorequestsfromWeb
browsers,orclients,suchasFirefox,Netscape,lynx,and
InternetExplorer.WhenyouentertheaddressofaWebpage(a
URI,page1061)inaWebbrowser'slocationbar,thebrowser
sendsarequestovertheInternettothe(Apache)serveratthat
address.Inresponse,theserversendstherequestedcontent
backtothebrowser.Thebrowserthendisplaysorplaysthe
content,whichmightbeasong,picture,videoclip,orother
information.
Content
Asidefromadd-onmodulesthatcaninteractwiththecontent,
Apacheremainsoblivioustothecontentitself.Server
administrationandcontentcreationaretwodifferentaspectsof
bringingupaWebsite.Thischapterconcentratesonsettingup
andrunninganApacheserver;itspendslittletimediscussing
contentcreation.
Modules
Apache,liketheLinuxkernel,usesexternalmodulestoincrease
load-timeflexibilityandallowpartsofitscodetoberecompiled
withoutrecompilingthewholeprogram.Ratherthanbeingpart
oftheApachebinary,modulesarestoredasseparatefilesthat
canbeloadedwhenApacheisstarted.
Apacheusesexternalmodules,calleddynamicsharedobjects
(DSOs),forbasicandadvancedfunctions;thereisnotmuchto
Apachewithoutthesemodules.Apachealsousesmodulesto
extenditsfunctionality:Modulescanprocessscriptswrittenin
Perl,PHP,Python,andotherlanguages;useseveraldifferent
methodstoauthenticateusers;facilitatepublishingcontent;
andprocessnontextualcontent,suchasaudio.Thelistof
moduleswrittenbytheApacheGroupandthird-party
developersisalwaysgrowing.Formoreinformationreferto
"Modules"onpage820.
AboutApache
Thissectiondescribesthepackagesyouneedtoinstalland
providesreferencesfortheprogramscoveredinthischapter.
The"Notes"sectiononpage788introducesterminologyand
othertopicsthatwillhelpyoumakebettersenseofthis
chapter."JumpStartI"(page789)getsApacheupandrunning
asquicklyaspossible.
Prerequisites
Minimalinstallation
Installthefollowingpackages:
httpd
apr(Apacheportableruntime)
apr-util
StartingApache
Runchkconfigtocausehttpdtostartwhenthesystementers
multiusermode:
#/sbin/chkconfighttpdon
AfteryouconfigureApache,useservicetostarthttpd:
#/sbin/servicehttpdstart
AfterchangingtheApacheconfiguration,restarthttpdwiththe
followingcommand,whichwillnotdisturbclientsconnectedto
theserver:
#/sbin/servicehttpdgraceful
Optionalpackages
Youcaninstallthefollowingoptionalpackages:
httpd-manualTheApachemanual
webalizerWebserverloganalyzer(page825)
mod_perlEmbeddedPerlscriptinglanguage
mod_pythonEmbeddedPythonscriptinglanguage
mod_sslSecureSocketsLayerextension(page821)
phpEmbeddedPHPscriptinglanguage,includingIMAP&
LDAPsupport
mrtgMRTGtrafficmonitor(page826)
net-snmpandnet-snmp-utilsSNMP,requiredforMRTG
(page826).
MoreInformation
Local
TheApacheReferenceManualandUsers'Guide
/var/www/manualPointabrowserat
http://localhost/manualifhttpdisrunningorat
/var/www/manual/index.htmlifhttpdisnotrunning.The
manualisavailableonlineonlyifthehttpd-manualpackageis
installed.
Web
ApachedocumentationRHELhttpd.apache.org/docs/2.0,
FEDORAhttpd.apache.org/docs/2.2
ApachedirectiveslistRHEL
httpd.apache.org/docs/2.0/mod/directives.html,FEDORA
httpd.apache.org/docs/2.2/mod/directives.html
ApacheSoftwareFoundation(newsletters,mailinglists,
projects,moduleregistry,andmore)www.apache.org
mod_perlperl.apache.org
mod_phpwww.php.net
mod_pythonwww.modpython.org
mod_sslwww.modssl.org
MRTGmrtg.hdl.com/mrtg.html
SNMPnet-snmp.sourceforge.net
SSIRHELhttpd.apache.org/docs/2.0/howto/ssi.html,FEDORA
httpd.apache.org/docs/2.2/howto/ssi.html
webalizerwww.mrunix.net/webalizer
Notes
Terms:Apacheandhttpd
ApacheisthenameofaserverthatservesHTTPandother
content.TheApachedaemonisnamedhttpdbecauseitisan
HTTPserverdaemon.ThischapterusesthetermsApacheand
httpdinterchangeably.
Terms:serverandprocess
AnApacheserveristhesamethingasanApacheprocess.An
Apachechildprocessexiststohandleincomingclientrequests,
henceitisreferredtoasaserver.
Firewall
AnApacheservernormallyusesTCPport80;asecureserver
usesTCPport443.IftheApacheserversystemisrunninga
firewall,youneedtoopenoneorbothoftheseports.Toget
startedyoujustneedtoopenport80(HTTP).UsingtheRed
Hatgraphicalfirewalltool(page768),selectWWW(HTTPD)
and/orSecureWWW(HTTPS)fromtheTrustedservices
frametoopentheseports.Formoregeneralinformation,see
Chapter25,whichdetailsiptables.
SELinux
WhenSELinuxissettouseatargetedpolicy,httpdisprotected
bySELinux.Youcandisablethisprotectionifnecessary.For
moreinformationreferto"SettingtheTargetedPolicywith
system-config-securitylevel"onpage402.
Runningasroot
BecauseApacheservescontentonprivilegedports,youmust
startitasroot.Forsecurityreasons,theprocessesthatApache
spawnsrunastheuserandgroupapache.
Locale
ThehttpddaemonisstartedusingtheClocalebydefault.You
canmodifythisbehavior,forexample,tousetheconfigured
systemlocale,bysettingtheHTTPD_LANGvariableinthe
/etc/sysconfig/httpdfile.
Documentroot
TherootofthedirectoryhierarchythatApacheservescontent
fromiscalledthedocumentroot.AsshippedbyRedHat,the
documentrootis/var/www/html.Youcanusethe
DocumentRootdirective(page796)tochangethelocationof
thedocumentroot.
Modifyingcontent
AsshippedbyRedHat,onlyrootcanaddormodifycontentin
/var/www/html.Toavoidhavingpeopleworkasrootwhen
theyaremanipulatingcontent,createagroup(webwork,for
example),putpeoplewhoneedtoworkwithWebcontentin
thisgroup,andmakethedirectoryhierarchystartingat
/var/www/html(oranotherdocumentroot)writablebythat
group.Inaddition,ifyoumakethedirectoryhierarchysetgid
(chmodg+sfilename),allnewfilescreatedwithinthis
hierarchywillbelongtothegroup,whichfacilitatessharingfiles.
Seepage539formoreinformationaboutworkingwithgroups.
Versions
RHELrunsApacheversion2.0.FEDORArunsversion2.2.
JumpStartI:GettingApacheUpandRunning
TogetApacheupandrunning,modifythe
/etc/httpd/conf/httpd.confconfigurationfile."DirectivesI:
DirectivesYouMayWanttoModifyasYouGetStarted"onpage
794explainsmoreaboutthisfileandexploresotherchanges
youmaywanttomaketoit.
Modifyingthehttpd.confConfigurationFile
Apacherunsasinstalled,butitisagoodideatoaddthethree
linesdescribedinthissectiontothe
/etc/httpd/conf/httpd.confconfigurationfilebeforestarting
Apache.Ifyoudonotaddtheselines,Apacheassignsvalues
thatmaynotworkforyou.
TheServerNamelineestablishesanamefortheserver.Addone
ofthefollowinglinestohttpd.conftosetthenameofthe
servertothedomainnameoftheserveror,ifyoudonothavea
domainname,totheIPaddressoftheserver:
ServerNameexample.com
or
ServerNameIP_address
whereexample.comisthedomainnameoftheserverand
IP_addressistheIPaddressoftheserver.Ifyouarenot
connectedtoanetwork,youcanusethelocal-hostaddress,
127.0.0.1,sothatyoucanstarttheserverandexperimentwith
it.
Whenaclienthastroublegettinginformationfromaserver,the
serverfrequentlydisplaysanerrorpagethatidentifiesthe
problem.Forexample,whenApachecannotfindarequested
page,itdisplaysapagethatsaysError404:NotFound.Each
errorpagehasalinkthattheusercanclicktosendmailtothe
server'sadministrator.ServerSignaturecanspecifythatyou
wantanemaillinkonerrorpagesandServerAdminspecifies
theemailaddressthattheserverdisplaysonerrorpages.Add
thesetwolinestohttpd.conf:
ServerAdminemail_address
ServerSignatureEMail
whereemail_addressistheemailaddressofthepersonwho
needstoknowifpeoplearehavingtroubleusingtheserver.
Makesurethatsomeonechecksthisemailaccountfrequently.
Aftermakingthechangestohttpd.conf,startorrestarthttpd
asexplainedonpage787.
TestingApache
Onceyoustartthehttpddaemon,youcanconfirmthatApache
isworkingcorrectlybypointingabrowseronthelocalsystem
tohttp://localhost/.Fromaremotesystem,pointabrowser
tohttp://followedbytheServerNameyouspecifiedin
httpd.conf.Forexample,youmightuseeitheroftheseURI
formats:http://192.168.0.16orhttp://example.org.The
browsershoulddisplaytheRedHat/Apachetestpage.Thistest
pageisactuallyanerrorpagethatsaysthereisnocontent.For
moreinformationreferto"RedHattestpage"onpage816.
Iftheserverisbehindafirewall,openTCPport80(page788).
IfyouarehavingproblemsgettingApachetowork,see
"Troubleshooting"onpage819.
PuttingYourContentinPlace
PlacethecontentyouwantApachetoservein
/var/www/html.Apacheautomaticallydisplaysthefile
namedindex.htmlinthisdirectory.Workingasroot(orasa
memberofthegroupyousetupforthispurpose[e.g.,
webwork]),givethefollowingcommandtocreatesucha
page:
#cat>/var/www/html/index.html
<html><body><p>Thisismytestpage.</p></body></html>
CONTROL-D
Aftercreatingthisfile,eitherrefreshthebrowserifitisstill
runningorstartitagainandpointitattheserver.Thebrowser
shoulddisplaythepageyoujustcreated.
JumpStartII:SettingUpApacheUsingsystem-
config-httpd
Tip:Makeacopyofhttpd.conf
Asinstalled,the/etc/httpd/conf/httpd.conffile
containsextensivecommentsandissetupas
explainedinthischapter.Thesystem-config-httpdutility
overwritesthisfile.Makeacopyofhttpd.conffor
safekeepingbeforeyourunthisutilityforthefirst
time.
Youcanusethesystem-config-httpdutilitytodisplaytheHTTP
window,whichallowsyoutoeditthe
/etc/httpd/conf/httpd.conffiletosetupApache.Torunthis
utility,entersystem-config-httpdonacommandline.From
KDEselectMainmenu:Administration ServerSettings
HTTPorfromGNOMEselectSystem:Administration
ServerSettings HTTP.
TheHTTPwindowhasfourtabs:Main,VirtualHosts,Server,
andPerformanceTuning.Eachfieldinthesetabs/windows
correspondstoadirectiveinthe/etc/httpd/conf/httpd.conf
file.Thissectiondiscussessomeofthebasicdirectivesyoucan
changewithsystem-config-httpd.FormoreinformationclickHelp
atthebottomoftheHTTPwindow.
Maintab
TheMaintab(Figure26-1)allowsyoutoestablishanFQDN
(page1032)asthenameoftheserver(ServerName,page
796),anemailaddressfortheserveradministrator
(ServerAdmin,page795),andtheportsandaddressesthat
Apachelistensonforrequests(Listen,page795).Highlightan
entryintheAvailableAddressessubwindow,andclickEditto
editthatentryorAddtoaddanewentry.Bothactionsbringup
awindowthatallowsyoutospecifyaportandselectwhether
youwanttolistentoallIPaddressesonthatportorlistentoa
specificaddress.Togetstarted,setupApachetolistentoall
availableaddressesonport80.
Figure26-1.HTTPwindow,Maintab
VirtualHosts
TheVirtualHoststaballowsyoutoestablishdefaultsettingsfor
Apacheandsetupvirtualhosts(page818).ClicktheVirtual
Hoststab,andthenclickEdittoeditthesettingsforthe
highlightedvirtualhostorAddtoaddanewvirtualhost.Both
actionsopentheVirtualHostPropertieswindow,General
Optionstab(Figure26-2).
Figure26-2.VirtualHostPropertieswindow,
GeneralOptionstab
[Viewfullsizeimage]
TheothertabsintheVirtualHostPropertieswindowarePage
Options(Figure26-3),SSL,Logging,Environment,and
Performance.Thiswindowissimilartotheoneyouusedto
establishdefaultsettings,exceptthatitpertainstoaspecific
virtualhostandhasmoretabs.Youdonothavetochangemost
ofthevaluesinthiswindow.ClickOKwhenyouaredone
makingchanges.
Figure26-3.VirtualHostPropertieswindow,
PageOptionstab
[Viewfullsizeimage]
Servertab
UsuallyyoudonotneedtochangethevaluesintheServertab.
Youcanspecifythepathnameofthelockfile(LockFile
directive),thePIDfile(PidFiledirective),andthedirectorythat
Apachestorescoredumpsin(CoreDumpDirectory).Thelower
portionofthetaballowsyoutospecifytheuser(User,page
812)andgroup(Group,page810)thatApacherunsas.
PerformanceTuningtab
TheselectionsinthePerformanceTuningtabcontrolthe
maximumnumberofconnectionsthatApacheallows
(MaxClients,page802),thenumberofsecondsafterwhicha
connectionwilldisconnect(Timeout,page804),themaximum
numberofrequestsApacheallowsperconnection
(MaxRequestsPerChild,page803),andwhethertoallow
persistentconnections(KeepAlivedirective).Initially,thevalues
inthistabdonotneedtobechanged.ClickOKwhenyouare
donemakingchangesandrestarthttpdasdiscussedonpage
787.
FilesystemLayout
Thissectiontellsyouwhereyoucanfindmanyofthefilesyou
mayneedtoworkwithasyousetupandmodifyanApache
server.
Binaries,scripts,andmodules
TheApacheserverandrelatedbinaryfilesarekeptinseveral
directories:
/usr/sbin/httpdTheApacheserver(daemon).
/usr/sbin/apachectlStartsandstopsApache.Thehttpdinit
scriptcallsapachectl.
/usr/bin/htpasswdCreatesandmaintainspasswordfiles
usedbytheApacheauthenticationmodule(page824).
/usr/sbin/rotatelogsRotatesApachelogfilessothefilesdo
notgettoolarge.Seelogrotate(page559)formoreinformation
aboutrotatinglogfiles.
/etc/httpd/modulesHoldsmodulebinaries.Twoofthemost
frequentlyusedmodulebinaryfilesaremod_perl.soand
mod_python.so.Thisdirectoryisasymboliclinkto
/usr/lib/httpd/modules(page820).
Configurationfiles
Apacheconfigurationfilesarekeptinthe/etc/httpd/confand
/etc/httpd/conf.ddirectories.
/etc/httpd/conf/httpd.confHoldsconfigurationdirectives.
ThisfileisthemainApacheconfigurationfile.Thediscussionof
configurationdirectivesstartsonpage794.Referto"TheRed
Hathttpd.confFile"onpage814foradescriptionofthe
httpd.conffile.
/etc/httpd/conf/magicProvidesMIME(page1043)filetype
identification(theMIMEhintsfile).Itisnotnormallychanged.
Seemagicnumber(page1042)formoreinformation.
/etc/httpd/conf/ssl.*RHELHoldsfilesanddirectoriesused
bymod_ssl(page821).
/etc/pki/tls/certsFEDORAHoldsfilesanddirectoriesusedby
mod_ssl(page821).
/etc/httpd/conf.dHoldsconfigurationfilesformodules
includingphpandmod_perl.
Logs
Logsarekeptin/var/log/httpd(thereisasymboliclinkat
/etc/httpd/logs):
/var/log/httpd/access_logLogsrequestsmadetothe
server.
/var/log/httpd/error_logLogsrequestandruntimeserver
errors.
/var/log/httpd/ssl_*_logHoldsmod_ssllogs.
Webdocuments
Webdocuments(includingtheWebpagesdisplayedbyclient
browsers),customerrormessages,andCGIscriptsarekeptin
/var/wwwbydefault:
/var/www/cgi-binHoldsCGIscripts(page821).
/var/www/errorHoldsdefaulterrordocuments.Youcan
modifythesedocumentstoconformtothestyleofyourWeb
site.SeeErrorDocument(page807).
/var/www/iconsHoldsiconsusedtodisplaydirectory
entries.
/var/www/manualHoldstheApacheReferenceManualand
Users'Guide.FEDORAPresentonlyifthehttpd-manual
packageisinstalled.
Documentroot
Bydefault,thedocumentroot(page788)is/var/www/html.
YoucanchangethislocationwiththeDocumentRootdirective
(page796).InadditiontocontentfortheWebpagesthat
Apacheserves,thisdirectorycanhousetheusagedirectory,
whichholdswebalizer(page825)output.
.htaccessfiles
A.htaccessfilecontainsconfigurationdirectivesandcan
appearinanydirectoryinthedocumentroothierarchy.The
locationofa.htaccessfileiscritical:Thedirectivesina
.htaccessfileapplytoallfilesinthehierarchyrootedatthe
directorythatholdsthe.htaccessfile.Youmustusethe
AllowOverridedirective(page813)tocauseApachetoexamine
.htaccessfiles.BasedontheRedHathttpd.conffile,Apache
doesnotanswerrequestsforfileswhosenamesstartwith.ht,
soclientscannotread.htaccessfiles.
ConfigurationDirectives
Configurationdirectives,orsimplydirectives,arelinesina
configurationfilethatcontrolsomeaspectofhowApache
functions.Aconfigurationdirectiveiscomposedofakeyword
followedbyoneormorearguments(values)separatedby
SPACEs.Forexample,thefollowingconfigurationdirectivesets
Timeoutto300(seconds):
Timeout300
YoumustencloseargumentsthatcontainSPACEswithindouble
quotationmarks.Keywordsarenotcasesensitive,but
arguments(pathnames,filenames,andsoon)oftenare.
httpd.conf
ThemostimportantfilethatholdsApacheconfiguration
directivesis,bydefault,/etc/httpd/conf/httpd.conf.This
fileholdsglobaldirectivesthataffectallcontentservedby
Apache.AnIncludedirective(page810)withinhttpd.confcan
incorporatethecontentsofanotherfileasthoughitwerepart
ofhttpd.conf.
.htaccess
Localdirectivescanappearin.htaccessfiles(above).A
.htaccessfilecanappearinanydirectorywithinthedocument
roothierarchy;itaffectsfilesinthedirectoryhierarchyrooted
atthedirectorythe.htaccessfileappearsin.
Pathnames
Whenyouspecifyanabsolutepathnameinaconfiguration
directive,thedirectiveusesthatpathnamewithoutmodifyingit.
Whenyouspecifyarelativepathname,suchasasimple
filenameorthenameofadirectory,Apacheprependstothe
namethevaluespecifiedbytheServerRoot(page809)
directive(/etc/httpdbydefault).
DirectivesI:DirectivesYouMayWanttoModify
asYouGetStarted
Whenitstarts,Apachereadsthe
/etc/httpd/conf/httpd.confconfigurationfile(bydefault)for
instructionsgoverningeveryaspectofhowApacherunsand
deliverscontent.Thehttpd.conffileshippedbyRedHatis
morethan1,000lineslong.Thissectiondetailssomelinesyou
maywanttochangeasyouaregettingstartedwithApache.
Youcanuseeachofthefollowingdirectivesinhttpd.conf;the
Contextlineineachexplanationshowswhichotherfilesthe
directivescanappearin.Contextisexplainedonpage798.The
sectiontitled"DirectivesII:AdvancedDirectives"onpage802
describesmoredirectives.
Listen
Specifiestheport(s)thatApachelistensforrequestson.
Listen[IP-address:]portnumber
whereIP-addressistheIPaddressthatApachelistensonand
portnumberisthenumberoftheportthatApachelistenson
forthegivenIP-address.WhenIP-addressisabsentorisset
to0.0.0.0,Apachelistensonallnetworkinterfaces.Atleastone
Listendirectivemustappearinhttpd.conforApachewillnot
work.
FEDORA
Thefollowingminimaldirectivefromthehttpd.conffilelistens
forrequestsonallinterfacesonport80:
Listen80
RHEL
ThefollowingListendirectivefromhttpd.confisequivalentto
theprecedingone:
Listen0.0.0.0:80
Thenextdirectivechangestheportfromthedefaultvalueof80
to8080:
Listen8080
Whenyouspecifyaportotherthan80,eachrequesttothe
servermustincludeaportnumber(asin
www.example.org:8080)orthekernelwillreturna
ConnectionRefusedmessage.UsemultipleListendirectives
tocauseApachetolistenonmultipleIPaddressesandports.
Forexample,acceptsconnectionsonallnetworkinterfaceson
port80,on192.168.1.1onport8080,andon192.168.1.2on
port443.
Listen80
Listen192.168.1.1:8080
Listen192.168.1.2:443
acceptsconnectionsonallnetworkinterfacesonport80,on
192.168.1.1onport8080,andon192.168.1.2onport443.
Context:serverconfig
Default:none(Apachewillnotstartwithoutthisdirective)
RedHat:Listen80
ServerAdmin
Setstheemailaddressdisplayedonerrorpages.
ServerAdminemail-address
whereemail-addressistheemailaddressoftheperson
responsibleformanagingtheWebcontent.Undermostversions
ofApache,thisaddressappearsonApache-generatederror
pages.However,RedHatLinuxsetsServerSignature(page
810)toOnwhichcausesApachetodisplayinformationabout
theserver,notanemailaddress,onerrorpages.Ifyouwantto
displayanemailaddressonerrorpagessetServerSignatureto
EMail.Makesureemail-addresspointstoanemailaccount
thatsomeonechecksfrequently.Userscanusethisaddressto
gethelpwiththeWebsiteortoinformtheadministratorof
problems.ThereisnodefaultvalueforServerAdmin;ifyoudo
notusethisdirective,thevalueisundefinedandnoemail
addressappearsonerrorpages.
Becausewebmasterisacommonname,youcanuse
webmasteratyourdomainandusethe/etc/aliasesfile
(page633)toforwardmailthatissenttowebmastertothe
personwhoisresponsibleformaintainingtheWebsite.
Contexts:serverconfig,virtualhost
Default:none
RedHat:RHELnone,FEDORAroot@localhost
ServerName
Specifiestheserver'snameandtheportitlistenson.
ServerNameFQDN[:port]
whereFQDNisthefullyqualifieddomainnameorIPaddressof
theserverandportistheoptionalportnumberApachelistens
on.Thedomainnameoftheservermustbeabletoberesolved
byDNSandmaydifferfromthehostnameofthesystem
runningtheserver.IfyoudonotspecifyaServerName,Apache
performsaDNSreversenameresolution(page729)onthe
system'sIPaddressandassignsthatvaluetoServerName.If
thereverselookupfails,Apacheassignsthesystem'sIP
addresstoServerName.
RedHatLinuxprovidesthefollowingServerNametemplatein
thehttpd.conffile:
#ServerNamewww.example.com:80
Copythisline,removethe#,andsubstitutetheFQDNorIP
addressoftheserverinplaceofwww.example.com.Change
the80totheportnumberApachelistensonifitisnotport80.
TheportsspecifiedbyServerNameandListen(page795)must
bethesameifyouwanttheFQDNspecifiedbyServerNametied
totheIPaddressspecifiedbytheListendirective.
ApacheusesServerNametoconstructaURIwhenitredirectsa
client(page817).
Contexts:serverconfig,virtualhost
Default:none
RedHat:none
DocumentRoot
Pointstotherootofthedirectoryhierarchythatholdsthe
server'scontent.
DocumentRootdirname
wheredirnameistheabsolutepathnameofthedirectoryat
therootofthedirectoryhierarchythatholdsthecontent
Apacheserves.Donotuseatrailingslash.Youcanputthe
documentrootwhereveryoulike,aslongastheuserapache
hasreadaccesstotheordinaryfilesandexecuteaccesstothe
directoryfilesinthedirectoryhierarchy.TheFHS(page176)
specifies/srvasthetop-leveldirectoryforthispurpose.The
followingdirectiveputsthedocumentrootat/home/www:
DocumentRoot/home/www
Contexts:serverconfig,virtualhost
Default:/usr/local/apache/htdocs
RedHat:/var/www/html
UserDir
Allowsuserstopublishcontentfromtheirhomedirectories.
UserDirdirname|disabled|enableduser-list
wheredirnameisthenameofadirectorythat,ifitappearsin
alocaluser'shomedirectory,ApachepublishestotheWeb.The
disabledkeywordpreventscontentfrombeingpublishedfrom
users'homedirectories;enabledcausescontenttobe
publishedfromthehomedirectoriesofusersspecifiedinthe
SPACE-separateduser-list.Whenyoudonotspecifya
dirname,Apachepublishescontentto~/public_html.
ApachecancombinetheeffectsofmultipleUserDirdirectives.
Supposeyouhavethefollowingdirectives:
UserDirdisabled
UserDirenableduser1user2user3
UserDirweb
Thefirstdirectiveturnsoffuserpublishingforallusers.The
seconddirectiveenablesuserpublishingforthreeusers.The
thirddirectivemakeswebthenameofthedirectorythat,ifit
appearsinoneofthespecifiedusers'homedirectories,Apache
publishestotheWeb.
Tocauseabrowsertodisplaythecontentpublishedbyauser,
specifyinthelocationbarthenameoftheWebsitefollowedby
a/~andtheuser'susername.Forexample,ifSampublished
contentinthepublic_htmldirectoryinhishomedirectoryand
theURIoftheWebsitewaswww.example.com,youwould
enterhttp://www.example.com/~samtodisplaySam's
Webpage.Todisplayauser'sWebpage,Apachemusthave
executepermission(asuserapache)fortheuser'shome
directoryandthedirectoryholdingthecontent,andread
permissionforthecontentfiles.
RedHatLinuxprovidesthefollowingServerNamedirectiveand
templateinthehttpd.conffile:
UserDirdisable
#UserDirpublic_html
Putapoundsign(#)infrontofthefirstlineandremovethe
poundsignfromthesecondlinetoallowuserstopublish
contentfromdirectoriesnamedpublic_htmlintheirhome
directories.
Contexts:serverconfig,virtualhost
Default:RHELpublic_html,FEDORAnone
RedHat:disabled
DirectoryIndex
Specifieswhichfiletodisplaywhenauserasksforadirectory.
DirectoryIndexfilename[filename...]
wherefilenameisthenameofthefilethatApacheserves.
Thisdirectivespecifiesalistoffilenames.Whenaclient
requestsadirectory,Apacheattemptstofindafileinthe
specifieddirectorywhosenamematchesafileinthelist.When
Apachefindsamatch,itreturnsthatfile.Whenthisdirectiveis
absentorwhennoneofthefilesspecifiedbythisdirective
existsinthespecifieddirectory,Apachedisplaysadirectory
listingasspecifiedbytheIndexOptionsdirective(page807).
FEDORAprovidesthefollowingDirectoryIndexdirectiveinthe
httpd.conffile:
DirectoryIndexindex.phpindex.htmlindex.htmindex.shtml
ThisdirectivecausesApachetoreturnfromthespecified
directorythefilenamedindex.php,index.html,index.htm,
orindex.shtml.
Theindex.phpisthenameofaPHPdocument;index.html
andindex.htmarethenamesofthestandard,defaultHTML
documents;andindex.shtmlisasecureHTMLdocument.If
yousupplyCGIdocuments,youmaywanttoaddtheindex.cgi
valuetothisdirective.Thenameindexisstandardbut
arbitrary.
A.varfilenameextensiondenotesacontent-negotiated
documentthatallowsApachetoservetheApachemanualand
otherdocumentsinoneofseverallanguagesasspecifiedbythe
client.Ifyouarenotprovidingcontentindifferentlanguages,
youcanomitthisfilenameextensionfromtheDirectoryIndex
directive.
Contexts:serverconfig,virtualhost
Default:index.html
RedHat:RHELindex.htmlindex.html.var
FEDORAindex.phpindex.htmlindex.htmindex.shtml
ContextsandContainers
Tomakeitflexibleandeasytocustomize,Apacheuses
configurationdirectives,contexts,andcontainers.Configuration
directiveswerecoveredintheprevioussection.Thissection
discussescontextsandcontainers,whicharecriticalto
managinganApacheserver.
Contexts
Fourlocations,calledcontexts,definewhereaconfiguration
directivecanappear.Thischaptermarkseachconfiguration
directivetoindicatewhichcontext(s)itcanappearin.Table26-
1describeseachofthesecontexts.
Table26-1.Contexts
Context Location(s)directivescanappearin
server
config
Directivecanappearinthehttpd.conffileonly,butnot
inside<VirtualHost>or<Directory>containers(next
section)unlesssomarked
virtualhost Directivecanappearinside<VirtualHost>containersin
thehttpd.conffileonly
directory Directivecanappearinside<Directory>,<Location>,
and<Files>containersinthehttpd.conffileonly
.htaccess Directivecanappearin.htaccessfiles(page794)only
DirectivesinfilesincorporatedbymeansoftheIncludedirective
(page810)arepartofthecontexttheyareincludedinand
mustbeallowedinthatcontext.
Puttingadirectiveinthewrongcontextgeneratesa
configurationerrorandcancauseApachenottoservecontent
correctlyornottostart.
Containers
Containers,orspecialdirectives,aredirectivesthatgroupother
directives.ContainersaredelimitedbyXML-styletags.Three
examplesareshownhere:
<Directory>...</Directory>
<Location>...</Location>
<VirtualHost>...</VirtualHost>
Lookinhttpd.confforexamplesofcontainers.Likeother
directives,containersarelimitedtousewithinspecified
contexts.Thissectiondescribessomeofthemorefrequently
usedcontainers.
<Directory>
Appliesdirectivestodirectorieswithinspecifieddirectory
hierarchies.
<Directorydirectory>...</Directory>
wheredirectoryisanabsolutepathnamespecifyingtherootof
thedirectoryhierarchythatholdsthedirectoriesthedirectives
inthecontainerapplyto.Thedirectorycanincludewildcards;
a*doesnotmatcha/.
A<Directory>containerprovidesthesamefunctionalityasa
.htaccessfile.Whileanadministratorcanusea<Directory>
containerinthehttpd.conffile,regularuserscannot.Regular
userscanuse.htaccessfilestocontrolaccesstotheirown
directories.
Thedirectivesinthe<Directory>containershowninthe
followingexampleapplytothe/var/www/html/corp
directoryhierarchy:TheDenydirectivedeniesaccesstoall
clients,theAllowdirectivegrantsclientsfromthe192.168.10.
subnetaccess,andtheAllowOverridedirective(page813)
enablestheuseof.htaccessfilesinthehierarchy:
<Directory/var/www/html/corp>
Denyfromall
Allowfrom192.168.10.
AllowOverrideAll
</Directory>
Contexts:serverconfig,virtualhost
<Files>
Appliesdirectivestospecifiedordinaryfiles.
<Filesdirectory>...</Files>
wheredirectoryisanabsolutepathnamespecifyingtherootof
thedirectoryhierarchythatholdstheordinaryfilesthe
directivesinthecontainerapplyto.Thedirectorycaninclude
wildcards;a*doesnotmatcha/.Thiscontainerissimilarto
<Directory>butappliestoordinaryfilesandnottodirectories.
Thefollowingdirective,fromtheRedHathttpd.conffile,
deniesaccesstoallfileswhosefilenamesstartwith.ht.The
tilde(~)changeshowApacheinterpretsthefollowingstring.
Withoutatilde,thestringisasimpleshellmatchthatinterprets
shellspecialcharacters(page221).Withatilde,Apache
interpretsthestringasaregularexpression(page967):
<Files~"^\.ht">
Orderallow,deny
Denyfromall
</Files>
Contexts:serverconfig,virtualhost,directory,.htaccess
<IfModule>
Appliesdirectivesifaspecifiedmoduleisloaded.
<IfModule[!]module-name>...</IfModule>
wheremodule-nameisthenameofthemodule(page820)
thatistestedfor.Apacheexecutesthedirectivesinthis
containerifmodule-nameisloadedorwith!ifmodule-name
isnotloaded.
Apachewillnotstartifyouspecifyaconfigurationdirectivethat
isspecifictoamodulethatisnotloaded.
Thefollowing<IfModule>containerfromtheRedHat
httpd.conffiledependsonthemod_mime_magic.cmodule
beingloaded.Ifthismoduleisloaded,Apacherunsthe
MIMEMagicFiledirective,whichtellsthemod_mime_magic.c
modulewhereitshintsfileislocated.
<IfModulemod_mime_magic.c>
MIMEMagicFileconf/magic
</IfModule>
Seepage815foranotherexampleofthe<IfModule>container.
Contexts:serverconfig,virtualhost,directory,.htaccess
<Limit>
Limitsaccess-controldirectivestospecifiedHTTPmethods.
<Limitmethod[method]...>...</Limit>
wheremethodisanHTTPmethod.AnHTTPmethodspecifies
whichactionistobeperformedonaURI.Themostfrequently
usedmethodsareGET,PUT,POST,andOPTIONS;method
namesarecasesensitive.GET,thedefaultmethod,sendsany
dataindicatedbytheURI.PUTstoresdatafromthebody
sectionofthecommunicationatthespecifiedURI.POSTcreates
anewdocumentcontainingthebodyoftherequestatthe
specifiedURI.OPTIONSrequestsinformationaboutthe
capabilityoftheserver.
Thiscontainerbindsagroupofaccess-controldirectivesto
specifiedHTTPmethods:Onlymethodsnamedbythe<Limit>
containerareaffectedbythisgroupofdirectives.
ThefollowingexampledisablesHTTPuploads(PUTs)from
systemsthatarenotinasubdomainofexample.com:
<LimitPUT>
orderdeny,allow
denyfromall
allowfrom.example.com
</Limit>
Caution:Use<LimitExcept>insteadof
<Limit>
Itissafertousethe<LimitExcept>container
insteadofthe<Limit>container,astheformer
protectsagainstarbitrarymethods.Whenyouuse
<Limit>,youmustbecarefultonameexplicitlyall
possiblemethodsthatthegroupofdirectivescould
affect.
Itissaferstillnottoputaccess-controldirectivesin
anycontainer.
Contexts:serverconfig,virtualhost,directory,.htaccess
<LimitExcept>
Limitsaccess-controldirectivestoallexceptspecifiedHTTP
methods.
<LimitExceptmethod[method]...>...</LimitExcept>
wheremethodisanHTTPmethod.See<Limit>fora
discussionofmethods.
Thiscontainercausesagroupofaccess-controldirectivesnotto
beboundtospecifiedHTTPmethods:Methodsnotnamedin
<LimitExcept>areaffectedbythisgroupofdirectives.
Theaccess-controldirectiveswithinthefollowing
<LimitExcept>containeraffectHTTPmethodsotherthanGET
andPOST.Youcouldputthiscontainerina<Directory>
containertolimititsscope:
<LimitExceptGETPOSTOPTIONS>
Orderdeny,allow
Denyfromall
</LimitExcept>
Contexts:serverconfig,virtualhost,directory,.htaccess
<Location>
AppliesdirectivestospecifiedURIs.
<LocationURI>...</Location>
whereURIpointstocontentandspecifiesafileortherootof
thedirectoryhierarchythatthedirectivesinthecontainerapply
to.Whilethe<Directory>containerpointswithinthelocal
filesystem,<Location>pointsoutsidethelocalfilesystem.The
URIcanincludewildcards;a*doesnotmatcha/.
Thefollowing<Location>containerlimitsaccessto
http://server/poptoclientsfromtheexample.netdomain,
whereserveristheFQDNoftheserver:
<Location/pop>
Orderdeny,allow
Denyfromall
Allowfrom.example.net
</Location>
Contexts:serverconfig,virtualhost
Caution:Use<Location>withcare
Usethispowerfulcontainerwithcare.Donotuseit
toreplacethe<Directory>container:Whenseveral
URIspointtothesamelocationinafilesystem,a
clientmaybeabletocircumventthedesiredaccess
controlbyusingaURInotspecifiedbythis
container.
<LocationMatch>
AppliesdirectivestomatchedURIs.
<LocationMatchregexp>...</LocationMatch>
whereregexpisaregularexpressionthatmatchesoneor
moreURIs.Thiscontainerworksthesamewayas<Location>,
exceptthatitappliestoanyURIsthatregexpmatches:
#Disableautoindexfortherootdirectoryandpresenta
#defaultwelcomepageifnootherindexpageispresent.
#
<LocationMatch"^/$">
Options-Indexes
ErrorDocument403/error/noindex.html
</LocationMatch>
Contexts:serverconfig,virtualhost
<VirtualHost>
Appliesdirectivestoaspecifiedvirtualhost.
<VirtualHostaddr[:port][addr[:port]]...>...</VirtualHost>
whereaddrisanFQDNorIPaddressofthevirtualhostand
portistheportthatApachelistensonforthevirtualhost.This
containerholdscommandsthatApacheappliestoavirtualhost.
Foranexampleandmoreinformation,referto"VirtualHosts"
onpage818.
Context:serverconfig
DirectivesII:AdvancedDirectives
Thissectiondiscussesconfigurationdirectivesthatyoumay
wanttouseafteryouhavegainedsomeexperiencewith
Apache.
DirectivesThatControlProcesses
MaxClients
Specifiesthemaximumnumberofchildprocesses.
MaxClientsnum
wherenumisthemaximumnumberofchildprocesses
(servers)Apacherunsatonetime,includingidleprocessesand
thoseservingrequests.WhenApacheisrunningnumprocesses
andtherearenoidleprocesses,ApacheissuesServertoo
busyerrorstonewconnections;itdoesnotstartnewchild
processes.Avalueof150isusuallysufficient,evenfor
moderatelybusysites.
Context:serverconfig
Default:256
RedHat:150
MaxRequestsPerChild
Specifiesthemaximumnumberofrequestsachildprocesscan
serve.
MaxRequestsPerChildnum
wherenumisthemaximumnumberofrequestsachildprocess
(server)canserveduringitslifetime.Afterachildprocess
servesnumrequests,itdoesnotprocessanymorerequests
butdiesafteritfinishesprocessingitscurrentrequests.Atthis
pointadditionalrequestsareprocessedbyotherprocessesfrom
theserverpool.
Setnumto0tonotsetalimitonthenumberofrequestsa
childcanprocess,exceptfortheeffectsofMinSpareServers.By
limitingthelifeofprocesses,thisdirectivecanpreventmemory
leaksfromconsumingtoomuchsystemmemory.However,
settingMaxRequestsPerChildtoasmallvaluecanhurt
performancebycausingApachetocreatenewchildservers
constantly.
Context:serverconfig
Default:10000
RedHat:4000
MaxSpareServers
Specifiesthemaximumnumberofidleprocesses.
MaxSpareServersnum
wherenumisthemaximumnumberofidleprocesses(servers)
Apachekeepsrunningtoserverequestsastheycomein.Do
notsetthisnumbertoohigh,aseachprocessconsumessystem
resources.
Context:serverconfig
Default:10
RedHat:20
MinSpareServers
Specifiestheminimumnumberofidleprocesses.
MinSpareServersnum
wherenumistheminimumnumberofidleprocesses(servers)
Apachekeepsrunningtoserverequestsastheycomein.More
idleprocessesoccupymorecomputerresources;increasethis
valueforbusysitesonly.
Context:serverconfig
Default:5
RedHat:5
StartServers
SpecifiesthenumberofchildprocessesthatApachestartswith.
StartServersnum
wherenumisthenumberofchildprocesses,orservers,that
Apachestartswhenitisbroughtup.Thisvalueissignificant
onlywhenApachestarts;MinSpareServersand
MaxSpareServerscontrolthenumberofidleprocessesonce
Apacheisupandrunning.StartingApachewithmultipleservers
ensuresthatapoolofserversiswaitingtoserverequests
immediately.
Context:serverconfig
Default:5
RedHat:8
NetworkingDirectives
HostnameLookups
SpecifieswhetherApacheputsaclient'shostnameoritsIP
addressinthelogs.
HostnameLookupsOn|Off|Double
On:PerformsDNSreversenameresolution(page729)to
determinethehostnameofeachclientforloggingpurposes.
Off:Logseachclient'sIPaddress.
Double:Toprovidegreatersecurity,performsDNSreverse
nameresolution(page729)todeterminethehostnameofeach
client,performsaforwardDNSlookuptoverifytheoriginalIP
address,andlogsthehostname.
Contexts:serverconfig,virtualhost,directory
Default:Off
RedHat:Off
Tip:Lookupscanconsumealotof
systemresources
UsetheOnandDoubleoptionswithcaution:They
canconsumealotofresourcesonabusysystem.
Youcanuseaprogramsuchaslogresolvetoperform
reversenameresolutionofflineforstatistical
purposes.
Ifyouperformhostnameresolutionoffline,yourun
theriskthatthenamemayhavechanged;you
usuallywantthenamethatwascurrentatthetime
oftherequest.Tominimizethisproblem,perform
thehostnameresolutionassoonaspossibleafter
writingthelog.
Timeout
SpecifiesthetimeApachewaitsfornetworkoperationsto
complete.
Timeoutnum
wherenumisthenumberofsecondsthatApachewaitsfor
networkoperationstofinish.Youcanusuallysetthisdirective
toalowervalue;fiveminutesisalongtimetowaitonabusy
server.TheApachedocumentationsaysthatthedefaultisnot
lower"becausetheremaystillbeoddplacesinthecodewhere
thetimerisnotresetwhenapacketissent."
Context:serverconfig
Default:300
RedHat:120
UseCanonicalName
Specifiesthemethodtheserverusestoidentifyitself.
UseCanonicalNameOn|Off|DNS
On:ApacheusesthevalueoftheServerNamedirective(page
796)asitsidentity.
Off:Apacheusesthenameandportfromtheincomingrequest
asitsidentity.
DNS:ApacheperformsaDNSreversenameresolution(page
729)ontheIPaddressfromtheincomingrequestandusesthe
resultasitsidentity.Rarelyused.
Thisdirectiveisimportantwhenaserverhasmorethanone
nameandneedstoperformaredirect.RedHatsetsthis
directivetoOffbecausetheServerNamedirective(page796)is
commentedout.OnceyousetServerName,change
UseCanonicalNametoOn.Seepage817foradiscussionof
redirectsandthisdirective.
Contexts:serverconfig,virtualhost,directory
Default:RHELOn,FEDORAOff
RedHat:RHELOff,FEDORAOn
LoggingDirectives
ErrorLog
SpecifieswhereApachesendserrormessages.
ErrorLogfilename|syslog[:facility]
wherefilenamespecifiesthenameofthefile,relativeto
ServerRoot(page809),thatApachesendserrormessagesto;
syslogspecifiesthatApachesenderrorstosyslogd(page
562);andfacilityspecifieswhichsyslogdfacilitytouse.The
defaultfacilityislocal7.
Contexts:serverconfig,virtualhost
Default:logs/error_log
RedHat:logs/error_log
LogLevel
SpecifiestheleveloferrormessagesthatApachelogs.
LogLevellevel
wherelevelspecifiesthatApachelogerrorsofthatleveland
higher(moreurgent).Chooselevelfromthefollowinglist,
whichispresentedhereinorderofdecreasingurgencyand
increasingverbosity:
emerg Systemunusablemessages
alert Needforimmediateactionmessages
crit Criticalconditionmessages
error Errorconditionmessages
warn Nonfatalwarningmessages
notice Normalbutsignificantmessages
info Operationalmessagesandrecommendations
debug Messagesforfindingandsolvingproblems
Contexts:serverconfig,virtualhost
Default:warn
RedHat:warn
DirectivesThatControlContent
AddHandler
Createsamappingbetweenfilenameextensionsandabuiltin
Apachehandler.
AddHandlerhandlerextension[extension]...
wherehandleristhenameofabuiltinhandlerandextension
isafilenameextensionthatmapstothehandler.Handlersare
actionsthatarebuiltintoApacheandaredirectlyrelatedto
loadedmodules.Apacheusesahandlerwhenaclientrequests
afilewithaspecifiedfilenameextension.
Forexample,thefollowingAddHandlerdirectivecausesApache
toprocessfilesthathaveafilenameextensionof.cgiwiththe
cgi-scripthandler:
AddHandlercgi-script.cgi
Contexts:serverconfig,virtualhost,directory,.htaccess
Default:none
RedHat:type-mapvar
Alias
MapsaURItoadirectoryorfile.
Aliasaliaspathname
wherealiasmustmatchpartoftheURIthattheclient
requestedtoinvokethealiasandpathnameistheabsolute
pathnameofthetargetofthealias,usuallyadirectory.
Forexample,thefollowingaliascausesApachetoserve
/usr/local/pix/milk.jpgwhenaclientrequests
http://www.example.com/pix/milk.jpg:
Alias/pix/usr/local/pix
Insomecases,youneedtousea<Directory>container(page
799)tograntaccesstoaliasedcontent.
Contexts:serverconfig,virtualhost
Default:None
RedHat:providestwoaliases,onefor/icons/andonefor
/error/
ErrorDocument
SpecifiestheactionApachetakeswhenthespecifiederror
occurs.
ErrorDocumentcodeaction
wherecodeistheerrorcode(page826)thatthisdirective
definesaresponseforandactionisoneofthefollowing:
string:DefinesthemessagethatApachereturnstotheclient.
absolutepathname:Pointstoalocalscriptorothercontent
thatApacheredirectstheclientto.
URI:PointstoanexternalscriptorothercontentthatApache
redirectstheclientto.
Whenyoudonotspecifythisdirectiveforagivenerrorcode,
Apachereturnsahardcodederrormessagewhenthaterror
occurs.Seepage816foranexplanationofhowan
ErrorDocumentdirectivereturnstheRedHattestpagewhen
thesystemisfirstinstalled.
SomeexamplesofErrorDocumentdirectivesfollow:
ErrorDocument403"Sorry,accessisforbidden."
ErrorDocument403/cgi-bin/uh-uh.pl
ErrorDocument403http://errors.example.com/not_allowed.html
Contexts:serverconfig,virtualhost,directory,.htaccess
Default:none;Apachereturnshardcodederrormessages
RedHat:403/error/noindex.html;referto"RedHattestpage"
onpage816.
IndexOptions
SpecifieshowApachedisplaysdirectorylistings.
IndexOptions[±]option[[±]option]...
whereoptioncanbeanycombinationofthefollowing:
DescriptionWidth=n:Setsthewidthofthedescriptioncolumn
toncharacters.Use*inplaceofntoaccommodatethewidest
description.
FancyIndexing:Indirectorylistings,displayscolumnheaders
thatarelinks.Whenyouclickoneoftheselinks,Apachesorts
thedisplaybasedonthecontentofthecolumn.Clickinga
secondtimereversestheorder.
FoldersFirst:Sortsthelistingsothatdirectoriescomebefore
plainfiles.UseonlywithFancyIndexing.
HTMLTable:FEDORADisplaysadirectorylistinginatable.
IconsAreLinks:Makestheiconsclickable.Useonlywith
FancyIndexing.
IconHeight=n:Setstheheightoficonstonpixels.Useonly
withIconWidth.
IconWidth=n:Setsthewidthoficonstonpixels.Useonly
withIconHeight.
IgnoreCase:Ignorescasewhensortingnames.
IgnoreClient:IgnoresoptionstheclientsuppliedintheURI.
NameWidth=n:Setsthewidthofthefilenamecolumnton
characters.Use*inplaceofntoaccommodatethewidest
filename.
ScanHTMLTitles:ExtractsanddisplaystitlesfromHTML
documents.UseonlywithFancyIndexing.Notnormallyused
becauseitisCPUanddiskintensive.
SuppressColumnSorting:Suppressesclickablecolumn
headingsthatcanbeusedforsortingcolumns.Useonlywith
FancyIndexing.
SuppressDescription:Suppressesfiledescriptions.Useonly
withFancyIndexing.
SuppressHTMLPreamble:Suppressesthecontentsofthefile
specifiedbytheHeaderNamedirective,evenifthatfileexists.
SuppressIcon:Suppressesicons.Useonlywith
FancyIndexing.
SuppressLastModified:Suppressesthemodificationdate.Use
onlywithFancyIndexing.
SuppressRules:Suppresseshorizontallines.Useonlywith
FancyIndexing.
SuppressSize:Suppressesfilesizes.Useonlywith
FancyIndexing.
VersionSort:Sortsversionnumbers(infilenames)inanatural
way;characterstrings,exceptforsubstringsofdigits,arenot
affected.
Asanexample,supposeaclientrequestsaURIthatpointstoa
directory(suchashttp://www.example.com/support/)
andnoneofthefilesspecifiedbytheDirectory-Indexdirective
(page797)ispresentinthatdirectory.Ifthedirectory
hierarchyiscontrolledbya.htaccessfileandAllowOverride
(page813)hasbeensettoallowindexing,thenApache
displaysadirectorylistingaccordingtotheoptionsspecifiedby
thisdirective.
Whenthisdirectiveappearsmorethanoncewithinadirectory,
Apachemergestheoptionsfromthedirectives.Use+andto
mergeoptionswithoptionsfromhigher-leveldirectories.
(Unlessyouuse+orwithalloptions,Apachediscardsany
optionssetinhigher-leveldirectories.)Forexample,the
followingdirectivesandcontainerssettheoptionsfor
/custsup/downloadtoVersionSort;Apachediscards
FancyIndexingandIgnoreCaseinthedownloaddirectory
becausethereisno+orbeforeVersionSortinthesecond
<Directory>container:
<Directory/custsup>
IndexOptionsFancyIndexing
IndexOptionsIgnoreCase
</Directory
<Directory/custsup/download>
IndexOptionsVersionSort
</Directory>
Because+appearsbeforeVersionSort,thenextdirectivesand
containerssettheoptionsfor/custsup/downloadto
FancyIndexing,IgnoreCase,andVersionSort:
<Directory/custsup>
IndexOptionsFancyIndexing
IndexOptionsIgnoreCase
</Directory
<Directory/custsup/download>
IndexOptions+VersionSort
</Directory>
Contexts:serverconfig,virtualhost,directory,.htaccess
Default:none;listsonlyfilenames
RedHat:FancyIndexingVersionSortNameWidth=*
ServerRoot
Specifiestherootdirectoryforserverfiles(notcontent).
ServerRootdirectory
wheredirectoryspecifiesthepathnameoftherootdirectory
forfilesthatmakeuptheserver.Apacheprependsdirectoryto
relativepathnamesinhttpd.conf.Thisdirectivedoesnot
specifythelocationofthecontentthatApacheserves;the
DocumentRootdirective(page796)performsthatfunction.Do
notchangethisvalueunlessyoumovetheserverfiles.
Context:serverconfig
Default:/usr/local/apache
RedHat:/etc/httpd
ServerTokens
SpecifiestheserverinformationthatApachereturnstoaclient.
ServerTokensProd|Major|Minor|Min|OS|Full
Prod:Returnstheproductname(Apache).AlsoProductOnly.
Major:Returnsthemajorreleasenumberoftheserver
(Apache/2).
Minor:Returnsthemajorandminorreleasenumbersofthe
server(Apache/2.2).
Minimal:Returnsthecompleteversion(Apache/2.2.0).Also
Min.
OS:Returnsthenameoftheoperatingsystemandthe
completeversion(Apache/2.2.0(RedHatLinux)).Provides
lessinformationthatmighthelpamalicioususerthanFull
does.
Full:SameasOS,plussendsthenamesandversionsofnon-
Apachegroupmodules(Apache/2.2.0(RedHatLinux)
PHP/5.1.2).
Unlessyouwantclientstoknowthedetailsofthesoftwareyou
arerunningforsomereason,setServerTokenstorevealaslittle
aspossible.
Context:serverconfig
Default:Full
RedHat:OS
ServerSignature
Addsalinetoserver-generatedpages.
ServerSignatureOn|Off|EMail
On:Turnsthesignaturelineon.Thesignaturelinecontainsthe
serverversionasspecifiedbytheServerTokensdirective(page
809)andthenamespecifiedbythe<VirtualHost>container
(page802).
Off:Turnsthesignaturelineoff.
EMail:Tothesignatureline,addsamailto:linktotheserver
emailaddress.Thisoptionproducesoutputthatcanattract
spam.SeeServerAdmin(page795)forinformationon
specifyinganemailaddress.
Contexts:serverconfig,virtualhost,directory,.htaccess
Default:Off
RedHat:On
ConfigurationDirectives
Group
SetstheGIDoftheprocessesthatruntheservers.
Group#groupid|groupname
wheregroupidisaGIDvalue,precededbya#,and
groupnameisthenameofagroup.Theprocesses(servers)
thatApachespawnsarerunasthegroupspecifiedbythis
directive.SeetheUserdirective(page812)formore
information.
Context:serverconfig
Default:#1
RedHat:apache
Include
Loadsdirectivesfromfiles.
Includefilename|directory
wherefilenameistherelativepathnameofafilethatcontains
directives.ApacheprependsServerRoot(page809)to
filename.Thedirectivesinfilenameareincludedinthefile
holdingthisdirectiveatthelocationofthedirective.Because
filenamecanincludewildcards,itcanspecifymorethanone
file.
Thedirectoryistherelativepathnamethatspecifiestheroot
ofadirectoryhierarchythatholdsfilescontainingdirectives.
ApacheprependsServerRoottodirectory.Thedirectivesin
ordinaryfilesinthishierarchyareincludedinthefileholding
thisdirectiveatthelocationofthedirective.Thedirectorycan
includewildcards.
WhenyouinstallApacheanditsmodules,rpmputsconfiguration
files,whichhaveafilenameextensionofconf,intheconf.d
directorywithintheServerRootdirectory.TheIncludedirective
intheRedHathttpd.conffileincorporatesmodule
configurationfilesforwhichevermodulesareinstalled.
Contexts:serverconfig,virtualhost,directory
Default:none
RedHat:conf.d/*.conf
LoadModule
Loadsamodule.
LoadModulemodulefilename
wheremoduleisthenameofanexternalDSOmoduleand
filenameistherelativepathnameofthenamedmodule.
ApacheprependsServerRoot(page809)tofilename.Apache
loadstheexternalmodulespecifiedbythisdirective.Formore
informationreferto"Modules"onpage820.
Context:serverconfig
Default:none;nothingisloadedbydefaultifthisdirectiveis
omitted
RedHat:loadsmorethan40modules;refertohttpd.conffor
thelist
Options
Controlsserverfeaturesbydirectory.
Options[±]option[[±]option...]
Thisdirectivecontrolswhichserverfeaturesareenabledfora
directoryhierarchy.Thedirectoryhierarchyisspecifiedbythe
containerthisdirectiveappearsin.A+ortheabsenceofa
turnsanoptiononandaturnsitoff.
Theoptionmaybeoneofthefollowing:
NoneNoneofthefeaturesthisdirectivecancontrolare
enabled.
AllAllofthefeaturesthisdirectivecancontrolareenabled,
exceptforMulti-Views,whichyoumustexplicitlyenable.
ExecCGIApachecanexecuteCGIscripts(page821).
FollowSymLinksApachefollowssymboliclinks.
IncludesPermitsSSIs(server-sideincludes,page821).SSIs
arecontainersembeddedinHTMLpagesthatareevaluatedon
theserverbeforethecontentispassedtotheclient.
IncludesNOEXECThesameasIncludesbutdisablesthe
#execand#execcgicommandsthatarepartofSSIs.Does
notpreventthe#includecommandfromreferencingCGI
scripts.
IndexesGeneratesadirectorylistingifDirectoryIndex(page
797)isnotset.
MultiViewsAllowsmultiviews(page818).
SymLinksIfOwnerMatchThesameasFollowSymLinksbut
followsthelinkonlyifthefileordirectorybeingpointedtohas
thesameownerasthelink.
ThefollowingOptionsdirectivefromtheRedHathttpd.conffile
setstheIndexesandFollowSymLinksoptionsand,becausethe
<Directory>containerspecifiesthe/var/www/htmldirectory
hierarchy(thedocumentroot),affectsallcontent:
<Directory"/var/www/html">
OptionsIndexesFollowSymLinks
...
<Directory>
Context:directory
Default:All
RedHat:None
ScriptAlias
MapsaURItoadirectoryorfileanddeclaresthetargettobea
server(CGI)script.
ScriptAliasaliaspathname
wherealiasmustmatchpartoftheURItheclientrequestedto
invoketheScript-Aliasandpathnameistheabsolute
pathnameofthetargetofthealias,usuallyadirectory.Similar
totheAliasdirective,thisdirectivespecifiesthatthetargetisa
CGIscript(page821).
ThefollowingScriptAliasdirectivefromtheRedHathttpd.conf
filemapsclientrequeststhatinclude/cgi-bin/tothe
/var/www/cgi-bindirectory(andindicatesthatthese
requestswillbetreatedasCGIrequests):
ScriptAlias/cgi-bin/"/var/www/cgi-bin/"
Contexts:serverconfig,virtualhost
Default:none
RedHat:/cgi-bin/"/var/www/cgi-bin"
User
SetstheUIDoftheprocessesthatruntheservers.
User#userid|username
whereuseridisaUIDvalue,precededbya#,andusername
isthenameofalocaluser.Theprocesses(servers)thatApache
spawnsarerunastheuserspecifiedbythisdirective.
Apachemuststartasroottolistenonaprivilegedport.For
reasonsofsecurity,Apache'schildprocesses(servers)runas
nonprivilegedusers.ThedefaultUIDof1doesnotmaptoa
userunderRedHatLinux.Instead,RedHat'shttpdpackage
createsausernamedapacheduringinstallationandsetsUser
tothatuser.
Context:serverconfig
Default:#1
RedHat:apache
Security:DonotsetUsertorootor0
Foramoresecuresystem,donotsetUsertoroot
or0(zero)anddonotallowtheapacheuserto
havewriteaccesstotheDocumentRootdirectory
hierarchy(exceptasneededforstoringdata),
especiallynottoconfigurationfiles.
SecurityDirectives
Allow
Specifieswhichclientscanaccessspecifiedcontent.
AllowfromAll|host[host...]|env=var[env=var...]
Thisdirective,whichmustbewrittenasAllowfrom,grants
accesstoadirectoryhierarchytothespecifiedclients.The
directoryhierarchyisspecifiedbythecontaineror.htaccess
filethisdirectiveappearsin.
All:Servescontenttoanyclient.
host:Servescontenttotheclient(s)specifiedbyhost,which
cantakeseveralforms:hostcanbeanFQDN,apartialdomain
name(suchasexample.com),anIPaddress,apartialIP
address,oranetwork/netmaskpair.
var:Servescontentwhentheenvironmentvariablenamedvar
isset.YoucansetavariablewiththeSetEnvIfdirective.See
theOrderdirective(page814)foranexample.
Contexts:directory,.htaccess
Default:none;defaultbehaviordependsontheOrderdirective
RedHat:All
AllowOverride
Specifiestheclassesofdirectivesthatareallowedin.htaccess
files.
AllowOverrideAll|None|directive-class[directive-class...]
ThisdirectivespecifieswhetherApacheread.htaccessfilesin
thedirectoryhierarchyspecifiedbyitscontainer.IfApachedoes
reads.htaccessfiles,thisdirectivespecifieswhichkindsof
directivesarevalidwithin.htaccessfiles.
None:Ignores.htaccessfiles.
All:Allowsallclassesofdirectivesin.htaccessfiles.
Thedirective-classisoneofthefollowingdirectiveclass
identifiers:
AuthConfig:Classofdirectivesthatcontrolauthorization
(AuthName,AuthType,Require,andsoon).Thisclassisused
mostlyin.htaccessfilestorequireausernameandpassword
toaccessthecontent.Formoreinformationreferto
"AuthenticationModulesand.htaccess"onpage824.
FileInfo:Classofdirectivesthatcontrolsdocumenttypes
(DefaultType,ErrorDocument,SetHandler,andsoon).
Indexes:Classofdirectivesrelatingtodirectoryindexing
(DirectoryIndex,Fancy-Indexing,IndexOptions,andsoon).
Limit:Classofclientaccessdirectives(Allow,Deny,and
Order).
Options:Classofdirectivescontrollingdirectoryfeatures.
Context:directory
Default:All
RedHat:None
Deny
Specifieswhichclientsarenotallowedtoaccessspecified
content.
DenyfromAll|host[host...]|env=var[env=var...]
Thisdirective,whichmustbewrittenasDenyfrom,denies
accesstoadirectoryhierarchytothespecifiedclients.The
directoryhierarchyisspecifiedbythecontaineror.htaccess
filethisdirectiveappearsin.SeetheOrderdirective(page814)
foranexample.
All:Deniescontenttoallclients.
host:Deniescontenttotheclient(s)specifiedbyhost,which
cantakeseveralforms:hostcanbeanFQDN,apartialdomain
name(suchasexample.com),anIPaddress,apartialIP
address,oranetwork/netmaskpair.
var:Deniescontentwhentheenvironmentvariablenamedvar
isset.YoucansetavariablewiththeSetEnvIfdirective.
Contexts:directory,.htaccess
Default:none
RedHat:none
Order
SpecifiesdefaultaccessandtheorderinwhichAllowandDeny
directivesareevaluated.
OrderDeny,Allow|Allow,Deny
Deny,Allow:Allowsaccessbydefault;deniesaccessonlyto
clientsspecifiedinDenydirectives.(FirstevaluatesDeny
directives,thenevaluatesAllowdirectives.)
Allow,Deny:Deniesaccessbydefault;allowsaccessonlyto
clientsspecifiedinAllowdirectives.(FirstevaluatesAllow
directives,thenevaluatesDenydirectives.)
Accessgrantedordeniedbythisdirectiveappliestothe
directoryhierarchyspecifiedbythecontaineror.htaccessfile
thisdirectiveappearsin.
TheremustnotbeSPACEsoneithersideofthecomma.
AlthoughRedHatLinuxhasadefaultofAllow,Deny,which
deniesaccesstoallclientsnotspecifiedbyAllowdirectives,the
nextdirectiveinhttpd.conf,Allowfromall,grantsaccessto
allclients:
Orderallow,deny
Allowfromall
YoucanrestrictaccessbyspecifyingDeny,Allowtodenyall
accessandthenspecifyingonlythoseclientsyouwanttogrant
accesstoinanAllowdirective.Thefollowingdirectivesgrant
accesstoclientsfromtheexample.netdomainonlyandwould
typicallyappearwithina<Directory>container(page799):
Orderdeny,allow
Denyfromall
Allowfrom.example.net
Contexts:directory,.htaccess
Default:Deny,Allow
RedHat:Allow,Deny
TheRedHathttpd.confFile
Thissectionhighlightssomeoftheimportantfeaturesofthe
RedHathttpd.conffile,whichisbasedonthehttpd.conffile
distributedbyApache.Thisheavilycommentedfileisbroken
intothefollowingparts(asisthissection):
1. GlobalEnvironment:Controlstheoverallfunctioningof
theApacheserver.
2. MainServerConfiguration:Configuresthedefaultserver
(asopposedtovirtualhosts)andprovidesdefault
configurationinformationforvirtualhosts.
3. VirtualHosts:Configuresvirtualhosts.Formore
informationreferto"VirtualHosts"onpage818.
Section1:GlobalEnvironment
ServerTokens
TheServerTokensdirective(page809)issettoOS,which
causesApache,whenqueried,toreturnthenameofthe
operatingsystemandthecompleteversionnumberofApache:
ServerTokensOS
ServerRoot
TheServerRootdirective(page809)issetto/etc/httpd,
whichisthepathnamethatApacheprependstorelative
pathnamesinhttpd.conf:
ServerRoot"/etc/httpd"
<IfModule>
Multiprocessingmodules(MPMs)allowyoutochangetheway
Apacheworksbychangingthemodulesituses.The
<IfModule>containers(page800)allowyoutousethesame
httpd.conffilewithdifferentmodules:Thedirectivesinan
<IfModule>containerareexecutedonlyifthespecifiedmodule
isloaded.
Thesectionofhttpd.confthatstartswiththecomment
##Server-PoolSizeRegulation(MPMspecific)
holdstwo<IfModule>containers(page800)thatconfigure
Apache,dependingonwhichmodule,preforkorworker,is
loaded.RedHatshipsApachewiththepreforkmoduleloaded;
thissectiondoesnotdiscussthe<IfModule>containerforthe
workermodule.(Seethecommentsinthe
/etc/sysconfig/httpdfileifyouwanttoloadtheworker
module.)
Theprefork<IfModule>container,shownbelow,holds
directivesthatcontrolthefunctioningofApachewhenitstarts
andasitruns:
<IfModuleprefork.c>
StartServers8
MinSpareServers5
MaxSpareServers20
ServerLimit256
MaxClients256
MaxRequestsPerChild4000
</IfModule>
Listen
FEDORATheListendirective(page795)doesnotspecifyanIP
address.
RHELTheListendirectivespecifiesanIPaddressof0.0.0.0,
whichisthesameasnotspecifyinganIPaddress,soApache
listensonallnetworkinterfaces.
Listen80
LoadModule
TherearequiteafewLoadModuledirectives(page811);these
directivesloadtheApacheDSOmodules(page820).
Include
TheIncludedirective(page810)includesthefilesthatmatch
*.confinthe/etc/httpd/conf.ddirectory,asthoughthey
werepartofhttpd.conf:
Includeconf.d/*.conf
RedHattestpage
WhenyoufirstinstallApache,thereisnoindex.htmlfilein
/var/www/html;whenyoupointabrowseratthelocalWeb
server,Apachegenerateserror403,whichreturnstheRedHat
testpage.Themechanismbywhichthispageisreturnedis
convoluted:TheRedHathttpd.conffileholdsanInclude
directivethatincludesallfilesintheconf.ddirectorythatisin
theServerRootdirectory(page809).Thewelcome.conffilein
thisdirectorycontainsanErrorDocument403directive(page
807)thatredirectsuserswhoreceivethiserrorto
error/noindex.htmlintheDocument-Rootdirectory(page
796).Thenoindex.htmlfileistheRedHattestpagethat
confirmstheserverisworkingbutthereisnocontentto
display.
Section2:MainServerConfiguration
ServerAdmin,ServerName
AsRedHatLinuxisshipped,theServerAdminandServerName
directivesarecommentedout.Changethemtousefulvaluesas
suggestedintheServerAdmin(page795)andServerName
(page796)sections.
DocumentRoot
TheDocumentRootdirective(page796)appearsasfollows:
DocumentRoot"/var/www/html"
Youneedtomodifythisdirectiveonlyifyouwanttoputyour
contentsomewhereotherthan/var/www/html.
<Directory>
Thefollowing<Directory>container(page799)setsupa
restrictiveenvironmentfortheentirelocalfilesystem(specified
by/):
<Directory/>
OptionsFollowSymLinks
AllowOverrideNone
</Directory>
TheOptionsdirective(page811)allowsApachetofollow
symboliclinksbutdisallowsmanyoptions.TheAllowOverride
directive(page813)causesApachetoignore.htaccessfiles.
Youmustexplicitlyenablelessrestrictiveoptionsifyouwant
them,butbeawarethatdoingsocanexposetheroot
filesystemandcompromisesystemsecurity.
Nextanother<Directory>containersetsuplessrestrictive
optionsfortheDocumentRoot(/var/www/html).Thecodein
httpd.confisinterspersedwithmanycomments.Withoutthe
commentsitlookslikethis:
<Directory"/var/www/html">
OptionsIndexesFollowSymLinks
AllowOverrideNone
Orderallow,deny
Allowfromall
</Directory>
TheIndexesoptionintheOptionsdirectiveallowsApacheto
displaydirectorylistings.TheOrder(page814)andAllow(page
812)directivescombinetoallowrequestsfromallclients.This
containerisslightlylessrestrictivethantheprecedingone,
althoughitstilldoesnotallowApachetofollowdirectivesin
.htaccessfiles.
DirectoryIndex
Asexplainedonpage797,theDirectoryIndexdirectivecauses
Apachetoreturnthefilenamedindex.php,index.html,
index.htm,orindex.shtmlfromarequesteddirectory.
BecauseOptionsIndexesisspecifiedinthepreceding
<Directory>container,ifnoneofthesefilesexistsinaqueried
directory,Apachereturnsadirectorylisting:
DirectoryIndexindex.phpindex.htmlindex.htmindex.shtml
Therearemanymoredirectivesinthispartofthehttpd.conf
file.Thecommentsinthefileprovideaguideastowhatthey
do.Thereisnothinghereyouneedtochangeasyougetstarted
usingApache.
Section3:VirtualHosts
Alllinesinthissectionarecommentsorcommented-out
directives.Ifyouwanttosetupvirtualhosts,seepage818.
Redirects
ApachecanrespondtoarequestforaURIbyaskingtheclient
torequestadifferentURI.Thisresponseiscalledaredirect.A
redirectworksbecauseredirectionispartoftheHTTP
implementation:Apachesendstheappropriateresponsecode
andthenewURI,andacompliantbrowserrequeststhenew
location.
TheRedirectdirectivecanestablishanexplicitredirectthat
sendsaclienttoadifferentpagewhenaWebsiteismoved.Or,
whenauserenterstheURIofadirectoryinabrowserbut
leavesoffthetrailingslash,Apachecanautomaticallyredirect
theclienttothesameURIterminatedwithaslash.
UseCanonicalName
TheServerNamedirective(page796),whichestablishesthe
nameoftheserver,andtheUseCanonicalNamedirective(page
805)arebothimportantwhenaserverhasmorethanone
nameandneedstoperformanautomaticredirect.Forexample,
assumetheserverwiththenamezach.example.comandthe
aliaswww.example.comhasServerNamesetto
www.example.com.WhenaclientspecifiesaURIofa
directorybutleavesoffthetrailingslash
(zach.example.com/dir),Apachehastoperformaredirectto
determinetheURIoftherequesteddirectory.When
UseCanonicalNameissettoOn,Apacheusesthevalueof
ServerNameandreturnswww.example.com/dir/.With
UseCanonicalNamesettoOff,Apacheusesthenamefromthe
incomingrequestandreturnszach.example.com/dir/.
Multiviews
Multiviewsisawaytorepresentapageindifferentways,most
commonlyindifferentlanguages.Usingrequestheaders,a
browsercanrequestaspecificlanguagefromaserver.Servers
thatcannothandletheserequestsignorethem.
RHEL
MultiviewsisdemonstratedbytheApachemanual,whichcan
beinstalledlocallyin/var/www/manual(httpd-manual
package).Whenyoupointabrowserto
http://server/manual/index.html,thebrowserdisplaysthe
pageinthebrowser'sdefaultlanguage.Ifyouchangethe
browser'sdefaultlanguagesettingandreloadthepage,the
browserdisplaysthepageinthenewlanguage.Thebrowser
candisplaythepagesindifferentlanguagesbecausetheserver
hasacopyofthepageforeachlanguage.Forexample,thefiles
index.html.enandindex.html.debothexistinthe
/var/www/manualdirectory.
Server-GeneratedDirectoryListings(Indexing)
Whenaclientrequestsadirectory,theApacheconfiguration
determineswhatisreturnedtotheclient.Apachecanreturna
fileasspecifiedbytheDirectoryIndexdirective(page797),a
directorylistingifnofilematchesDirectoryIndexandthe
OptionsIndexesdirective(page811)isset,oranerror
messageifnofilematchesDirectoryIndexandOptionsIndexes
isnotset.
VirtualHosts
Apachesupportsvirtualhosts,whichmeansthatoneinstance
ofApachecanrespondtorequestsdirectedtomultipleIP
addressesorhostnamesasthoughitweremultipleservers.
EachIPaddressorhostnamecanthenprovidedifferentcontent
andbeconfigureddifferently.
Therearetwotypesofvirtualhosts:host-by-nameandhost-
by-IP.Host-by-namereliesontheFQDNtheclientusesinits
requesttoApacheforexample,www.example.comversus
www2.example.com.Host-by-IPexaminestheIPaddressthe
hostresolvesasandrespondsaccordingtothatmatch.
Host-by-nameishandyifthereisonlyoneIPaddress,but
ApachemustsupportmultipleFQDNs.Althoughyoucanuse
host-by-IPifagivenWebserverhasaliases,Apacheshould
servethesamecontentregardlessofwhichnameisused.
Virtualhostsinherittheirconfigurationsfromhttpd.conf
Section1(page815)andSection2(page816).InSection3,
<VirtualHost>containerscreatethevirtualhostsandspecify
directivesthatoverrideinheritedanddefaultvalues.Youcan
specifymanyvirtualhostsforasingleinstanceofApache.
Thefollowing<VirtualHost>containersetsupahost-by-name
forthesitenamedintranet.example.com.Thisvirtualhost
handlesrequeststhataredirectedtointranet.example.com.
<VirtualHostintranet.example.com>
ServerNameintranet.example.com
DocumentRoot/usr/local/www
ErrorLog/var/log/httpd/intra.error_log
CustomLog/var/log/httpd/intra.server_log
<Directory/usr/local/www>
Orderdeny,allow
Denyfromall
Allowfrom192.168.#allowfromprivatesubnetonly
</Directory>
</VirtualHost>
Troubleshooting
Youcanuseserviceandthehttpdinitscripttocheckthesyntax
oftheApacheconfigurationfiles:
#servicehttpdconfigtest
SyntaxOK
Onceyoustartthehttpddaemon,youcanconfirmthatApache
isworkingcorrectlybypointingabrowseronthelocalsystem
athttp://localhost/.Fromaremotesystem,use
http://server/,substitutingthehostnameoftheserverfor
server.Inresponse,ApachedisplaystheRedHattestpage.
Ifthebrowserdoesnotdisplaythetestpage,itwilldisplayone
oftwoerrors:Connectionrefusedoranerrorpage.Ifyouget
aConnectionrefusederror,makesurethatport80isnot
blockedbyafirewall(page788)andcheckthattheserveris
running:
#/sbin/servicehttpdstatus
httpd(pid21406214052140421403214022140113622)isrunning...
Iftheserverisrunning,checkthatyoudidnotspecifyaport
otherthan80inaListendirective.Ifyoudid,theURIyou
specifyinthebrowsermustreflectthisportnumber
(http://localhost:portspecifiesportport).Otherwise,check
theerrorlog(/var/log/httpd/error_log)forinformationon
whatisnotworking.
Toverifythatthebrowserisnotatfault,usetelnettotryto
connecttoport80oftheserver:
$telnetwww.example.com80
Trying192.0.34.166...
Connectedtowww.example.com.
Escapecharacteris'^]'.
CONTROL-]
telnet>quit
Connectionclosed.
IfConnectionrefusedisdisplayed,youhaveverifiedthatyou
cannotgetthroughtotheserver.
Modules
Apacheisaskeletalprogramthatreliesonexternalmodules,
calleddynamicsharedobjects(DSOs),toprovidemostofits
functionality.Thissectionliststhesemodulesanddiscusses
someofthemoreimportantones.Inadditiontothemodules
includedwithRedHatLinux,manyothermodulesareavailable.
Seehttpd.apache.org/modulesformoreinformation.
ModuleList
Followingisalistofsomeofthemodulesthatareavailable
underApache:
access(mod_access.so)Controlsaccessbasedonclient
characteristics.
actions(mod_actions.so)AllowsexecutionofCGIscriptsbased
ontherequestmethod.
alias(mod_alias.so)Allowsoutsidedirectoriestobemappedto
DocumentRoot.
asis(mod_asis.so)Allowssendingfilesthatcontaintheirown
headers.
auth(mod_auth.so)Providesuserauthenticationvia
.htaccess.
auth_anon(mod_auth_anon.so)Providesanonymoususer
accesstorestrictedareas.
auth_dbm(mod_auth_dbm.so)UsesDBMfilesfor
authentication.
auth_digest(mod_auth_digest.so)UsesMD5digestfor
authentication.
autoindex(mod_autoindex.so)Allowsdirectoryindexestobe
generated.
cern_meta(mod_cern_meta.so)AllowstheuseofCERNhttpd
metafilesemantics.
cgi(mod_cgi.so)AllowstheexecutionofCGIscripts.
dav(mod_dav.so)AllowsDistributedAuthoringandVersioning.
dav_fs(mod_dav_fs.so)Providesafilesystemformod_dav.
dir(mod_dir.so)Allowsdirectoryredirectsandlistingsasindex
files.
env(mod_env.so)AllowsCGIscriptstoaccessenvironment
variables.
expires(mod_expires.so)AllowsgenerationofExpiresHTTP
headers.
headers(mod_headers.so)Allowscustomizationofrequest
andresponseheaders.
imap(mod_imap.so)Allowsimagemapstobeprocessedon
theserverside.
include(mod_include.so)Providesserver-sideincludes(SSIs).
info(mod_info.so)Allowstheserverconfigurationtobe
viewed.
log_config(mod_log_config.so)Allowsloggingofrequests
madetotheserver.
mime(mod_mime.so)Allowsassociationoffileextensionswith
content.
mime_magic(mod_mime_magic.so)DeterminesMIMEtypes
offiles.
negotiation(mod_negotiation.so)Allowscontentnegotiation.
proxy(mod_proxy.so)AllowsApachetoactasaproxyserver.
proxy_connect(mod_proxy_connect.so)Allowsconnect
requesthandling.
proxy_ftp(mod_proxy_ftp.so)ProvidesanFTPextension
proxy.
proxy_http(mod_proxy_http.so)ProvidesanHTTPextension
proxy.
rewrite(mod_rewrite.so)Allowson-the-flyURIrewritingbased
onrules.
setenvif(mod_setenvif.so)Setsenvironmentvariablesbased
onarequest.
speling(mod_speling.so)Auto-correctsspellingifthe
requestedURIhasincorrectcapitalizationandonespelling
mistake.
status(mod_status.so)Allowstheserverstatustobequeried
andviewed.
unique_id(mod_unique_id.so)GeneratesauniqueIDforeach
request.
userdir(mod_userdir.so)Allowsuserstohavecontent
directories(public_html).
usertrack(mod_usertrack.so)Allowstrackingofuseractivity
onasite.
vhost_alias(mod_vhost_alias.so)Allowstheconfigurationof
virtualhosting.
mod_cgiandCGIScripts
TheCGI(CommonGatewayInterface)allowsexternal
applicationprogramstointerfacewithWebservers.Any
programcanbeaCGIprogramifitrunsinrealtime(atthe
timeoftherequest)andrelaysitsoutputtotherequesting
client.Variouskindsofscripts,includingshell,Perl,Python,and
PHP,arethemostcommonlyencounteredCGIprograms
becauseascriptcancallaprogramandreformatitsoutputin
HTMLforaclient.
ApachecanhandlerequestsforCGIprogramsinseveral
differentways.ThemostcommonmethodistoputaCGI
programinthecgi-bindirectoryandthenenableitsexecution
fromthatdirectoryonly.Thelocationofthecgi-bindirectory,
asspecifiedbytheScriptAliasdirective(page812),is
/var/www/cgi-bin.Alternatively,anAddHandlerdirective
(page806)canidentifyfilenameextensionsofscripts,suchas
.cgior.pl,withintheregularcontent(forexample,
AddHandlercgi-script.cgi).IfyouuseAddHandler,youmust
alsospecifytheExecCGIoptioninanOptionsdirectivewithin
theappropriate<Directory>container.Themod_cgimodule
mustbeloadedtoaccessandexecuteCGIscripts.
ThefollowingPerlCGIscriptdisplaystheApacheenvironment.
Thisscriptshouldbeusedfordebuggingonlybecauseit
presentsasecurityriskifoutsideclientscanaccessit:
#!/usr/bin/perl
##
##printenv--demoCGIprogramthatprintsitsenvironment
##
print"Content-type:text/plain\n\n";
foreach$var(sort(keys(%ENV))){
$val=$ENV{$var};
$val=~s|\n|\\n|g;
$val=~s|"|\\"|g;
print"${var}=\"${val}\"\n";
}
mod_ssl
SSL(SecureSocketsLayer),whichisimplementedbythe
mod_sslmodule,hastwofunctions:Itallowsaclienttoverify
theidentityofaserveranditenablessecuretwo-way
communicationbetweenaclientandaserver.SSLisusedon
Webpageswithformsthatrequirepasswords,creditcard
numbers,orothersensitivedata.
ApacheusestheHTTPSprotocolnotHTTPforSSL
communication.WhenApacheusesSSL,itlistensonasecond
port(443bydefault)foraconnectionandperformsa
handshakingsequencebeforesendingtherequestedcontentto
theclient.
Serververificationiscriticalforfinancialtransactions.Afterall,
youdonotwanttogiveyourcreditcardnumbertoafraudulent
Websiteposingasaknowncompany.SSLusesacertificateto
positivelyidentifyaserver.Overapublicnetworksuchasthe
Internet,theidentificationisreliableonlyifthecertificate
containsadigitalsignaturefromanauthoritativesourcesuchas
VeriSignorThawte.SSLWebpagesaredenotedbyaURI
beginningwithhttps://.
Dataencryptionpreventsmalicioususersfromeavesdropping
onInternetconnectionsandcopyingpersonalinformation.To
encryptcommunication,SSLsitsbetweenthenetworkandan
applicationandencryptscommunicationbetweentheserver
andtheclient.
SettingUpmod_ssl
The/etc/httpd/conf.d/ssl.conffileconfiguresmod_ssl.The
firstfewdirectivesinthisfileloadthemod_sslmodule,
instructApachetolistenonport443,andsetvarious
parametersforSSLoperation.Aboutathirdofthewaythrough
thefileisasectionlabeledSSLVirtualHostContextthatsets
upvirtualhosts(page818).
A<VirtualHost>containerinssl.confissimilartoonein
httpd.conf.Aswithany<VirtualHost>container,itholds
directivessuchasServerNameandServerAdminthatneedto
beconfigured.Inaddition,itholdssomeSSL-relateddirectives.
UsingaSelf-SignedCertificateforEncryption
IfyourequireSSLforencryptionandnotverificationthatis,if
theclientalreadytruststheserveryoucangenerateandusea
self-signedcertificate,bypassingthetimeandexpenseinvolved
inobtainingadigitallysignedcertificate.Self-signedcertificates
generateawarningwhenyouconnecttotheserver:Most
browsersdisplayadialogboxthatallowsyoutoexamineand
acceptthecertificate.Thesendmaildaemonalsouses
certificates(page650).
Theself-signedcertificatedependsontwofiles:aprivatekey
andthecertificate.Thelocationofeachfileisspecifiedin
/etc/httpd/conf.d/ssl.conf.Thefileshavedifferentnames
andarestoredindifferentlocationsunderFEDORAandRHEL.
FEDORA
#grep'^SSLCertificate'/etc/httpd/conf.d/ssl.conf
SSLCertificateFile/etc/pki/tls/certs/localhost.crt
SSLCertificateKeyFile/etc/pki/tls/private/localhost.key
Togeneratetheprivatekeythattheencryptionrelieson,cdto
/etc/pki/tls/certsandenteramakecommand:
#cd/etc/pki/tls/certs
#makelocalhost.key
umask77;\
/usr/bin/opensslgenrsa-des31024>localhost.key
GeneratingRSAprivatekey,1024bitlongmodulus
...............++++++
.........++++++
eis65537(0x10001)
Enterpassphrase:
Verifying-Enterpassphrase:
Theprecedingcommandgeneratesafilenamedlocalhost.key
thatisprotectedbythepassphraseyouentered:Youwillneed
thispassphrasetostarttheserver.Keeptheserver.keyfile
secret.
Thenextcommandgeneratesthecertificate.Thisprocessuses
theprivatekeyyoujustcreated.Youneedtosupplythesame
passphraseyouenteredwhenyoucreatedtheprivatekey.
#makelocalhost.crt
umask77;\
/usr/bin/opensslreq-utf8-new-keylocalhost.key-x509-days365-out
localhost.crt-set_serial0
Enterpassphraseforlocalhost.key:
Youareabouttobeaskedtoenterinformationthatwillbeincorporated
intoyourcertificaterequest.
WhatyouareabouttoenteriswhatiscalledaDistinguishedNameoraDN.
Therearequiteafewfieldsbutyoucanleavesomeblank
Forsomefieldstherewillbeadefaultvalue,
Ifyouenter'.',thefieldwillbeleftblank.
-----
CountryName(2lettercode)[GB]:US
StateorProvinceName(fullname)[Berkshire]:California
LocalityName(eg,city)[Newbury]:SanFrancisco
OrganizationName(eg,company)[MyCompanyLtd]:SobellAssociatesInc.
OrganizationalUnitName(eg,section)[]:
CommonName(eg,yournameoryourserver'shostname)[]:
EmailAddress[]:mgs@sobell.com
Theanswerstothefirstfivequestionsarearbitrary:Theycan
helpclientsidentifyasitewhentheyexaminethecertificate.
Theanswertothesixthquestion(CommonName)iscritical.
Becausecertificatesaretiedtothenameoftheserver,you
mustentertheserver'sFQDNaccurately.Ifyoumistypethis
information,theservernameandthatofthecertificatewillnot
match.Thebrowserwillthengenerateawarningmessageeach
timeaconnectionismade.
Asspecifiedbyssl.conf,Apachelooksforthefilesinthe
directorythatyoucreatedthemin.Donotmovethesefiles.
AfteryourestartApache,thenewcertificatewillbeinuse.
RHEL
Theprocessofcreatingthekeyandcertificateissimilarunder
RHEL.Thefollowingoutputshowsthelocationofthetwofiles:
#grep'^SSLCertificate'/etc/httpd/conf.d/ssl.conf
SSLCertificateFile/etc/httpd/conf/ssl.crt/server.crt
SSLCertificateKeyFile/etc/httpd/conf/ssl.key/server.key
Togeneratetheprivatekey,cdto/etc/httpd/confandgive
thecommandmakeserver.key.Fromthesamedirectory,give
thecommandmakeserver.crttogeneratethecertificate.
Thesecommandscreatefilesintheworkingdirectory.Next
moveserver.keyintothessl.keydirectory,andserver.crt
intothessl.crtdirectory.AfteryourestartApache,thenew
certificatewillbeinuse.
NotesonCertificates
Althoughtheservernameispartofthecertificate,theSSL
connectionistiedtotheIPaddressoftheserver:Youcan
haveonlyonecertificateperIPaddress.Formultiplevirtual
hoststohaveseparatecertificates,youmustspecifyhost-
by-IPratherthanhost-by-namevirtualhosts(page818).
Aslongastheserverisidentifiedbythenameforwhichthe
certificatewasissued,youcanusethecertificateon
anotherserverand/orIPaddress.
Arootcertificate(rootCA)isthecertificatethatsignsthe
servercertificate.Everybrowsercontainsadatabaseofthe
publickeysfortherootcertificatesofthemajorsigning
authorities,includingVeriSignandThawte.
Itispossibletogeneratearootcertificate(rootCA)and
signallyourservercertificateswiththisrootCA.Regular
clientscanimportthepublickeyoftherootCAsothatthey
recognizeeverycertificatesignedbythatrootCA.This
setupisconvenientforaserverwithmultipleSSL-enabled
virtualhostsandnocommercialcertificates.Formore
informationsee
www.modssl.org/docs/2.8/ssl_faq.html#ToC29.
Youcannotuseaself-signedcertificateifclientsneedto
verifytheidentityoftheserver.
AuthenticationModulesand.htaccess
TorestrictaccesstoaWebpage,Apacheandthirdparties
provideauthenticationmodulesandmethodsthatcanverifya
user'scredentials,suchasausernameandpassword.Some
modulesenableauthenticationagainstvariousdatabases
includingLDAP(page1040)andNIS(page655).
Userauthenticationdirectivesarecommonlyplacedina
.htaccessfile.Abasic.htaccessfilethatusestheApache
defaultauthenticationmodule(mod_auth)follows.Substitute
appropriatevaluesforthelocalserver.
#cat.htaccess
AuthUserFile/var/www/.htpasswd
AuthGroupFile/dev/null
AuthName"Browserdialogboxquery"
AuthTypeBasic
requirevalid-user
The/var/www/.htpasswdisatypicalabsolutepathnameof
a.htpasswdfileandBrowserdialogboxqueryisthestring
thattheuserwillseeaspartofthedialogboxthatrequestsa
usernameandpassword.
Thesecondlineofthepreceding.htaccessfileturnsoffthe
groupfunction.Thefourthlinespecifiestheuserauthentication
typeBasic,whichisimplementedbythedefaultmod_auth
module.ThelastlinetellsApachewhichuserscanaccessthe
protecteddirectory.Theentryvalid-usergrantsaccesstothe
directorytoanyuserwhoisintheApachepasswordfileand
whoentersthecorrectpassword.YoucanalsospecifyApache
usernamesseparatedbySPACEs.
YoucanputtheApachepasswordfileanywhereonthesystem,
aslongasApachecanreadit.Itissafetoputthisfileinthe
samedirectoryasthe.htaccessfilebecause,bydefault,
Apachewillnotansweranyrequestsforfileswhosenamesstart
with.ht.
Thefollowingcommandcreatesa.htpasswdfileforSam:
$htpasswd-c.htpasswdsam
Newpassword:
Re-typenewpassword:
Addingpasswordforusersam
Omitthecoptiontoaddauserortochangeapasswordinan
existing.htpasswdfile.RemembertouseanAllowOverride
directive(page813)topermitApachetoreadthe.htaccess
file.
ScriptingModules
Apachecanprocesscontentbeforeservingittoaclient.In
earlierversionsofApache,onlyCGIscriptscouldprocess
content.Inthecurrentversion,scriptingmodulescanworkwith
scriptsthatareembeddedinHTMLdocuments.
ScriptingmodulesmanipulatecontentbeforeApacheservesit
toaclient.BecausetheyarebuiltintoApache,theyarefast.
Scriptingmodulesareespeciallyefficientatworkingwith
externaldatasourcessuchasrelationaldatabases.Clientscan
passdatatoascriptingmodulethatmodifiestheinformation
thatApacheserves.
ContrastscriptingmoduleswithCGIscriptsthatarerun
externallytoApache:CGIscriptsdonotallowclientinteraction
andareslowbecausetheymustmakeexternalcalls.
RedHatprovidespackagesthatallowyoutoembedPerl,
Python,andPHPcodeinHTMLcontent.PerlandPython,which
aregeneral-purposescriptinglanguages,areencapsulatedfor
usedirectlyinApacheandareimplementedinthemod_perl
andmod_pythonmodules,respectively.
PHP,whichwasdevelopedformanipulatingWebcontent,
outputsHTMLbydefault.Implementedinthemod_php
module,thislanguageiseasytosetup,hasasyntaxsimilarto
PerlandC,andcomeswithalargenumberofWeb-related
functions.
webalizer:AnalyzesWebTraffic
Thewebalizerpackage,whichistypicallyinstalledaspartof
Apache,createsadirectoryat/var/www/usageandacron
file(page547)at/etc/cron.daily/00webalizer.Onceaday,
thecronfilegeneratesusagedataandputsitintheusage
directory;youcanviewthisdatabypointingabrowserat
http://server/usage/,whereserveristhehostnameofthe
server.
The/etc/webalizer.conffilecontrolsthebehaviorofthe
webalizerutility.IfyouchangethelocationoftheDocumentRoot
orlogfiles,youmusteditthisfiletoreflectthosechanges.For
moreinformationonwebalizer,refertothewebalizermanpageand
thesiteslistedunder"MoreInformation"onpage787.
MRTG:MonitorsTrafficLoads
MultiRouterTrafficGrapher(MRTG)isanopen-source
applicationthatgraphsstatisticsavailablethroughSNMP
(SimpleNetworkManagementProtocol).SNMPinformationis
availableonallhigh-endroutersandswitches,aswellason
someothernetworkedequipment,suchasprintersandwireless
accesspoints.Youcanusethenet-snmpandnet-snmp-utils
packagessuppliedbyRedHattoinstallSNMPonasystem.You
alsoneedtoinstallthemrtgpackage.
OnceMRTGandSNMPareinstalledandrunning,youcanview
thereportsathttp://server/mrtg,whereserveristheFQDN
oftheserver.Formoreinformationseethemrtgmanpageand
thesiteslistedunder"MoreInformation"onpage787.
ErrorCodes
FollowingisalistofApacheerrorcodes:
100Continue
101SwitchingProtocols
200OK
201Created
202Accepted
203Non-AuthoritativeInformation
204NoContent
205ResetContent
206PartialContent
300MultipleChoices
301MovedPermanently
302MovedTemporarily
303SeeOther
304NotModified
305UseProxy
400BadRequest
401Unauthorized
402PaymentRequired
403Forbidden
404NotFound
405MethodNotAllowed
406NotAcceptable
407ProxyAuthenticationRequired
408RequestTime-out
409Conflict
410Gone
411LengthRequired
412PreconditionFailed
413RequestEntityTooLarge
414Request-URITooLarge
415UnsupportedMediaType
500InternalServerError
501NotImplemented
502BadGateway
503ServiceUnavailable
504GatewayTime-out
505HTTPVersionnotsupported
ChapterSummary
ApacheisthemostpopularWebserverontheInternettoday.It
isbothrobustandextensible.The
/etc/httpd/conf/httpd.confconfigurationfilecontrolsmany
aspectsofhowApacheruns.TheRedHathttpd.conffile,
whichisbasedonthehttpd.conffiledistributedbyApache,is
heavilycommentedandbrokenintothreeparts:Global
Environment,MainServerConfiguration,andVirtualHosts.You
canusethesystem-config-httpdutilitytomodifyhttpd.conf.
Contenttobeservedmustbeplacedin/var/www/html,
calledthedocumentroot.Apacheautomaticallydisplaysthefile
namedindex.htmlinthisdirectory.
Configurationdirectives,orsimplydirectives,arelinesina
configurationfilethatcontrolsomeaspectofhowApache
functions.Fourlocations,calledcontexts,definewherea
configurationdirectivecanappear:serverconfig,virtual
host,directory,and.htaccess.Containers,orspecial
directives,aredirectivesthatgroupotherdirectives.
TorestrictaccesstoaWebpage,Apacheandthirdparties
provideauthenticationmodulesandmethodsthatcanverifya
user'scredentials,suchasausernameandpassword.Some
modulesenableauthenticationagainstvariousdatabases,
includingLDAPandNIS.
ApachecanrespondtoarequestforaURIbyaskingtheclient
torequestadifferentURI.Thisresponseiscalledaredirect.
Apachecanalsoprocesscontentbeforeservingittoaclient
usingscriptingmodulesthatworkwithscriptsembeddedin
HTMLdocuments.
Apachesupportsvirtualhosts,whichmeansthatoneinstance
ofApachecanrespondtorequestsdirectedtomultipleIP
addressesorhostnamesasthoughitweremultipleservers.
EachIPaddressorhostnamecanprovidedifferentcontentand
beconfigureddifferently.
TheCGI(CommonGatewayInterface)allowsexternal
applicationprogramstointerfacewithWebservers.Any
programcanbeaCGIprogramifitrunsinrealtimeandrelays
itsoutputtotherequestingclient.
SSL(SecureSocketsLayer)hastwofunctions:Itallowsaclient
toverifytheidentityofaserveranditenablessecuretwo-way
communicationbetweenaclientandserver.
Exercises
1. HowwouldyoutellApachethatyourcontentisin/usr/local/www?
2. HowwouldyouinstructanApacheservertolistenonport81insteadofport80?
3. HowwouldyouenableSamtopublishWebpagesfromhis~/websitedirectory
butnotallowanyoneelsetopublishtotheWeb?
4. Apachemustbestartedasroot.Why?Whydoesthisactionnotpresentasecurity
risk?
AdvancedExercises
5.
IfyouarerunningApacheonafirewallsystem,perhapstodisplayaWebfrontend
forfirewallconfiguration,howwouldyoumakesurethatitisaccessibleonlyfrom
insidethelocalnetwork?
6. Whyisitmoreefficienttorunscriptsusingmod_phpormod_perlthanthrough
CGI?
7. WhattwothingsdoesSSLprovideandhowdoesthisdifferifthecertificateisself-
signed?
8.
SomeWebsitesgeneratecontentbyretrievingdatafromadatabaseandinserting
itintoatemplateusingPHPorCGIeachtimethesiteisaccessed.Whyisthis
practiceoftenapooridea?
9.
AssumeyouwanttoprovideWebmailaccessforemployeesonthesameserver
thathoststhecorporateWebsite.TheWebsiteaddressisexample.com,youwant
tousemail.example.comforWebmail,andtheWeb-mailapplicationislocatedin
/var/www/webmail.Describetwowaysyoucansetthisupthisconfiguration.
10.
PartofaWebsiteisaprivateintranetandisaccessedas
http://example.com/intranet.Describehowyouwouldpreventpeopleoutsidethe
companyfromaccessingthissite.Assumethecompanyusesthe192.168.0.0/16
subnetinternally.
27.ProgrammingTools
INTHISCHAPTER
ProgramminginC 832
UsingSharedLibraries 840
make:KeepsaSetofProgramsCurrent 842
DebuggingCPrograms 850
Threads 860
SystemCalls 861
SourceCodeManagement 863
CVS:ConcurrentVersionsSystem 864
Withitsrichsetoflanguagesanddevelopmenttools,theLinux
operatingsystemprovidesanoutstandingenvironmentfor
programming.Cisoneofthemostpopularsystem
programminglanguagestouseinconjunctionwithLinux,in
partbecausetheoperatingsystemitselfiswrittenmostlyinC.
UsingC,programmerscaneasilyaccesssystemservicesusing
functionlibrariesandsystemcalls.Inaddition,avarietyof
helpfultoolscanfacilitatethedevelopmentandmaintenanceof
programs.
ThischapterexplainshowtocompileandlinkCprograms.It
introducestheGNUgdbdebuggerandtoolsthatprovide
feedbackaboutmemory,disk,andCPUresources.Italsocovers
someofthemostusefulsoftwaredevelopmenttools:themake
utilityandCVS(ConcurrentVersionsSystem).Themakeutility
helpsyoukeeptrackofwhichprogrammoduleshavebeen
updatedandhelpsensurethatyouusethelatestversionsofall
programmoduleswhenyoucompileaprogram.CVSisasource
codemanagementsystemthattrackstheversionsoffiles
involvedinaproject.
ProgramminginC
AmajorreasonthattheLinuxsystemprovidesanexcellentC
programmingenvironmentisthatCprogramscaneasilyaccess
theservicesoftheoperatingsystem.Systemcallstheroutines
thatmakeoperatingsystemservicesavailableto
programmerscanbemadefromCprograms.Thesesystemcalls
providesuchservicesascreatingfiles,readingfromandwriting
tofiles,collectinginformationaboutfiles,andsendingsignalsto
processes.WhenyouwriteaCprogram,youcanusesystem
callsinthesamewayyouuseordinaryCprogrammodules,or
functions,thatyouhavewritten.Formoreinformationreferto
"SystemCalls"onpage861.
Severallibrariesoffunctionshavebeendevelopedtosupport
programminginC.Theselibrariesarecollectionsofrelated
functionsthatyoucanusejustasyouuseyourownfunctions
andthesystemcalls.Manyofthelibraryfunctionsaccessbasic
operatingsystemservicesthroughsystemcalls,providingthe
servicesinwaysthatarebettersuitedtotypicalprogramming
tasks.Otherlibraryfunctions,suchasthemathlibrary
functions,servespecialpurposes.
ThischapterdescribestheprocessesofwritingandcompilingC
programs.However,itwillnotteachyoutoprograminC.
CheckingYourCompiler
TheCcompilerincommonuseonLinuxisGNUgcc,which
comesaspartofRedHatLinuxdistributions
(www.gnu.org/software/gcc/gcc.html).Ifitisnotalready
presentonthesystemyouareworkingon,youneedtoinstall
thegccpackage.Givethefollowingcommandtodetermine
whetheryouhaveaccesstothegcccompiler:
$gcc--version
bash:gcc:commandnotfound
Ifyougetaresponseotherthanversioninformation,eitherthe
compilerisnotinstalledoryourPATHvariabledoesnotcontain
thenecessarypathname(usuallygccisinstalledin/usr/bin).
Ifyougetversioninformationfromthegcccommand,theGNU
Ccompilerisinstalled.
Nextmakesurethatthecompilerisfunctioning.Asasimple
test,createafilenamedMakefilewiththefollowinglines.The
linethatstartswithgccmustbeindentedbyusingaTAB,not
SPACEs.
$catMakefile
morning:morning.c
TABgcc-omorningmorning.c
Nowcreateasourcefilenamedmorning.cwiththefollowing
lines:
$catmorning.c
#include<stdio.h>
intmain(intargc,char**argv){
printf("GoodMorning\n");
return0;
}
Compilethefilewiththecommandmakemorning.Whenit
compilessuccessfully,theresultingfilewillbeexecutable;you
canruntheprogrambygivingthecommandmorningor
./morning.Whenyougetoutputfromthisprogram,youknow
thatyouhaveaworkingCcompiler.
$makemorning
gcc-omorningmorning.c
$morning
GoodMorning
ACProgrammingExample
TocreateormodifyaCprogram,youmustuseaneditor,such
asemacsorvim.ThenameoftheCprogramfilemustendin.c.
Enteringthesourcecodeforaprogramissimilartotypinga
memoorshellscript.Althoughemacsandvim"know"thatyou
areeditingaCprogram,othereditorsmaynotknowwhether
yourfileisaCprogram,ashellscript,oranordinarytext
document.Youareresponsibleformakingthecontentsofthe
filesyntacticallysuitablefortheCcompilertoprocess.
Figure27-1(nextpage)illustratesthestructureofasimpleC
programnamedtabs.c.Thefirsttwolinesoftheprogramare
commentsthatdescribewhattheprogramdoes.Thestring/*
identifiesthebeginningofthecomment,andthestring*/
identifiestheendofthecomment;theCcompilerignoresall
charactersbetweenthem.Becauseacommentcanspantwoor
morelines,the*/attheendofthefirstlineandthe/*atthe
beginningofthesecondlinearenotnecessarybutareincluded
forclarity.Asthecommentexplains,theprogramreads
standardinput,convertsTABcharactersintotheappropriate
numberofSPACEs,andwritesthetransformedinputto
standardoutput.LikemanyLinuxutilities,thisprogramisa
filter.
Figure27-1.AsimpleCprogram:tabs.c(Theline
numbersarenotpartofthesourcecode.)
[Viewfullsizeimage]
Thecommentsatthetopoftabs.carefollowedby
preprocessordirectives,whichareinstructionsfortheC
preprocessor.DuringtheinitialphaseofcompilationtheC
preprocessorexpandsthesedirectives,readyingtheprogram
forthelaterstagesofthecompilationprocess.Preprocessor
directivesbeginwiththepoundsign(#)andmayoptionallybe
precededbySPACEandTABcharacters.
Symbolicconstants
Youcanusethe#definepreprocessordirectivetodefine
symbolicconstantsandmacros.Symbolicconstantsarenames
thatyoucanuseinaprograminplaceofconstantvalues.For
example,tabs.cusesa#definepreprocessordirectiveto
associatethesymbolicconstantTABSIZEwiththeconstant8.
ThepreprocessorthenusesTABSIZEinplaceoftheconstant8
asthedistancebetweenTABstops.Byconventionthenamesof
symbolicconstantsconsistofalluppercaseletters.
Bydefiningsymbolicnamesforconstantvalues,youcanmake
aprogrambotheasiertoreadandeasiertomodify.Ifyoulater
decidetochangeaconstant,youneedtochangeonlythe
preprocessordirective;youdonotneedtochangethevalue
everywhereitoccursintheprogram.Ifyoureplacethe#define
directiveforTABSIZEinFigure27-1withthefollowingdirective,
theprogramwillplaceTABstopseveryfourcolumnsratherthan
everyeight:
#defineTABSIZE4
Macros
Asymbolicconstant,whichisatypeofmacro,mapsasymbolic
nametoreplacementtext.Macrosarehandywhenthe
replacementtextisneededatmultiplepointsthroughoutthe
sourcecodeorwhenthedefinitionofthemacroissubjectto
change.Theprocessofsubstitutingthereplacementtextforthe
symbolicnameiscalledmacroexpansion.
Youcanalsouse#definedirectivestodefinemacroswith
arguments.Useofsuchamacroresemblesafunctioncall.
UnlikeCfunctions,however,macrosarereplacedwithCcode
priortocompilationintoobjectfiles.
TheNEXTTABmacrocomputesthedistancetothenextTABstop,
giventhecurrentcolumnpositioncurcol:
#defineNEXTTAB(curcol)(TABSIZE-((curcol)%TABSIZE))
ThisdefinitionusesthesymbolicconstantTABSIZE,whose
definitionmustappearpriortoNEXTTABinthesourcecode.The
macroNEXTTABcouldbeusedintabs.ctoassignavalueto
retvalinthefunctionfindstop:
retval=NEXTTAB(*col);
Headers(includefiles)
Whenmodulesofaprogramuseseveralmacrodefinitions,the
definitionsaretypicallycollectedtogetherinasinglefilecalled
aheaderfileoranincludefile.AlthoughtheCcompilerdoes
notplaceconstraintsonthenamesofheaderfiles,by
conventiontheyendin.h.Thenameoftheheaderfileislisted
inan#includepreprocessordirectiveineachprogramsource
filethatusesanyofthemacros.TheprograminFigure27-1
usesgetcharandputchar,whicharefunctionsdefinedin
stdio.h.Thestdio.hheaderfile,whichdefinesavarietyof
general-purposemacros,isusedbymanyClibraryfunctions.
Theanglebrackets(<and>)thatsurroundstdio.hintabs.c
instructtheCpreprocessortolookfortheheaderfileina
standardlistofdirectories(suchas/usr/include).Toincludea
headerfilefromanotherdirectory,encloseitspathname
betweendoublequotationmarks.Youcanspecifyanabsolute
pathnamewithinthedoublequotationmarksoryoucangivea
relativepathname.Ifyougivearelativepathname,searching
beginswiththeworkingdirectoryandthenmovestothesame
directoriesthataresearchedwhentheheaderfileissurrounded
byanglebrackets.Byconventionheaderfilesthatyousupply
aresurroundedbydoublequotationmarks.
Youcanalsospecifydirectoriestobesearchedforheaderfiles
byusingtheIoptiontotheCcompiler.Assumethatyouwant
tocompiletheprogramderiv.c,whichcontainsthefollowing
preprocessordirective:
#include"eqns.h"
Iftheheaderfileeqns.hislocatedinthesubdirectory
myincludes,youcancompilederiv.cwiththeIoptiontotell
theCpreprocessortolookforeqns.hthere:
$gcc-I./myincludesderiv.c
WhentheCpreprocessorencountersthe#includedirectivein
thederiv.cfile,itwilllookforeqns.hinthemyincludes
subdirectoryoftheworkingdirectory.
Tip:Userelativepathnamesforinclude
files
Usingabsolutepathnamesforincludefilesdoesnot
workifthelocationoftheheaderfilewithinthe
filesystemchanges.Usingrelativepathnamesfor
headerfilesworksaslongasthelocationofthe
headerfilerelativetotheworkingdirectoryremains
thesame.RelativepathnamesalsoworkwiththeI
optiononthegcccommandlineandallowheader
filestobemoved.
Functionprototype
Precedingthedefinitionofthefunctionmainisafunction
prototype.Thisdeclarationtellsthecompilerwhattypea
functionreturns,howmanyargumentsafunctionexpects,and
whatthetypesofthoseargumentsare.Intabs.ctheprototype
forthefunctionfindstopinformsthecompilerthatfindstop
returnstypeintandthatitexpectsasingleargumentoftype
pointertoint:
intfindstop(int*);
Oncethecompilerhasseenthisdeclaration,itcandetectand
flaginconsistenciesinthedefinitionandtheusesofthe
function.Asanexample,supposethatyoureplacedthe
referencetofindstopintabs.cwiththefollowingstatement:
inc=findstop();
Theprototypeforfindstopwouldcausethecompilertodetect
amissingargumentandissueanerrormessage.Youcouldthen
easilyfixtheproblem.Whenafunctionispresentinaseparate
sourcefileorisdefinedafteritisreferencedinasourcefile(as
findstopisintheexample),thefunctionprototypehelpsthe
compilercheckthatthefunctionisbeingcalledproperly.
Withouttheprototype,thecompilerwouldnotissueanerror
messageandtheproblemmightmanifestitselfasunexpected
behaviorduringexecution.Atthislatepoint,findingthebug
mightbedifficultandtime-consuming.
Functions
AlthoughyoucannamemostCfunctionsanythingyouwant,
eachprogrammusthaveexactlyonefunctionnamedmain.
Thefunctionmainisthecontrolmodule:Aprogrambegins
executionwiththefunctionmain,whichtypicallycallsother
functions,whichinturnmaycallstillotherfunctions,andso
forth.Byputtingdifferentoperationsintoseparatefunctions,
youcanmakeaprogrameasiertoreadandmaintain.For
example,theprograminFigure27-1usesthefunction
findstoptocomputethedistancetothenextTABstop.Although
thefewstatementsoffindstopcouldeasilyhavebeenincluded
inthemainfunction,isolatingtheminaseparatefunction
drawsattentiontoakeycomputation.
Functionscanmakebothdevelopmentandmaintenanceofthe
programmoreefficient.Byputtingafrequentlyusedcode
segmentintoafunction,youavoidenteringthesamecodeinto
theprogramoverandoveragain.Whenyoulaterwantto
modifythecode,youneedchangeitonlyonce.
Ifaprogramislongandincludesseveralfunctions,youmay
wanttosplititintotwoormorefiles.Regardlessofitssize,you
maywanttoplacelogicallydistinctpartsofaprogramin
separatefiles.ACprogramcanbesplitintoanynumberof
differentfiles;however,eachfunctionmustbewhollycontained
withinasinglefile.
Tip:Useaheaderfileformultiplesource
files
Whenyouarecreatingaprogramthattakes
advantageofmultiplesourcefiles,put#define
preprocessordirectivesintoaheaderfile.Thenuse
anincludestatementwiththenameoftheheader
fileinanysourcefilethatusesthosedirectives.
CompilingandLinkingaCProgram
Tocompiletabs.candcreateanexecutablefilenameda.out,
givethefollowingcommand:
$gcctabs.c
ThegccutilitycallstheCpreprocessor,theCcompiler,the
assembler,andthelinker.Figure27-2showsthesefour
componentsofthecompilationprocess.TheCpreprocessor
expandsmacrodefinitionsandincludesheaderfiles.The
compilationphasecreatesassemblylanguagecode
correspondingtotheinstructionsinthesourcefile.Nextthe
assemblercreatesmachine-readableobjectcode.Oneobject
fileiscreatedforeachsourcefile.Eachobjectfilehasthesame
nameasthesourcefile,exceptthatthe.cextensionisreplaced
with.o.Aftersuccessfullycompletingallphasesofthe
compilationprocessforaprogram,theCcompilercreatesthe
executablefileandremovesany.ofiles.
Figure27-2.Thecompilationprocess
Duringthefinalphaseofthecompilationprocess,thelinker
searchesspecifiedlibrariesforfunctionstheprogramusesand
combinesobjectmodulesforthosefunctionswiththeprogram's
objectmodules.Bydefault,theCcompilerlinksthestandardC
librarylibc.so(usuallyfoundin/lib),whichcontainsfunctions
thathandleinputandoutputandprovidesmanyothergeneral-
purposecapabilities.Ifyouwantthelinkertosearchother
libraries,youmustusethel(lowercase"l")optiontospecify
thelibrariesonthecommandline.UnlikemostoptionstoLinux
systemutilities,theloptiondoesnotprecedeallfilenameson
thecommandlinebutratherappearsafterthefilenamesofall
modulesthatitappliesto.Inthenextexample,theCcompiler
searchesthemathlibrarylibm.so(usuallyfoundin/lib):
$gcccalc.clm
Theloptionusesabbreviationsforlibrarynames,appending
theletterfollowingltolibandaddinga.soor.aextension.
Themintheexamplestandsforlibm.so.
Usingthesamenamingmechanism,youcanhaveagraphics
librarynamedlibgraphics.a,whichcanbelinkedwiththe
followingcommand:
$gccpgm.c-lgraphics
Whenyouusethisconventiontonamelibraries,gccknowsto
searchforthemin/usr/liband/lib.Youcanalsohavegcc
searchotherdirectoriesbyusingtheLoption:
$gccpgm.c-L.-L/opt/libgraphics/lib/-lgraphics
Theprecedingcommandcausesgcctosearchforlibraryfilesin
theworkingdirectoryandinthe/opt/libgraphics/lib
directorybeforesearchinginthedefaultlocations(typically
/usr/liband/lib).Alibrarymightbeinstalledinoneofthese
speciallocationsifitwerebuiltfromsourceandnotinstalled
usingrpm.Thefinalpartofthecommandlineinstructsthe
linkertosearchforandlinklibgraphics.awiththeexecutable
filecreatedbygcc.
Asthelaststepofthecompilationprocess,thelinkercreatesan
executablefilenameda.outunlessyouspecifyadifferent
filenamewiththeooption.Objectfilesaredeletedafterthe
executableiscreated.
ELFformat
Youmayoccasionallyencounterreferencestothea.outformat,
anoldUNIXbinaryformat.LinuxusestheExecutableand
LinkingFormat(ELF)forbinaries;recentversionsofgccproduce
thisformatnotthea.outformat,despitethefilename.Usethe
fileutility(page135)todisplaytheformatoftheexecutable
thatgccgenerates:
$filea.out
a.out:ELF32-bitLSBexecutable,Intel80386,version1(SYSV),for
GNU/Linux2.6.9,dynamicallylinked(usessharedlibs),forGNU/Linux
2.6.9,notstripped
Inthenextexample,theO3optioncausesgcctousetheC
compileroptimizer.Theoptimizermakesobjectcodemore
efficientsothattheexecutableprogramrunsmorequickly.
Optimizationhasmanyfacets,includinglocatingfrequently
usedvariablesandtakingadvantageofprocessor-specific
features.ThenumberaftertheOindicatesthelevelof
optimization,whereahighernumberspecifiesmore
optimization.Seethegccinfopageforspecifics.Thefollowing
examplealsoshowsthatthe.ofilesarenolongerpresentafter
a.outiscreated:
$ls
acctspay.cacctsrec.cledger.c
$gcc-O3ledger.cacctspay.cacctsrec.c
$ls
a.outacctspay.cacctsrec.cledger.c
Youcanusetheexecutablea.outinthesamewayyouuse
shellscriptsandotherprograms:bytypingitsnameonthe
commandline.TheprograminFigure27-1onpage834
expectstoreadfromstandardinput.Thus,onceyouhave
createdtheexecutablea.out,youcanuseacommandsuchas
thefollowingtorunit:
$./a.out<mymemo
Ifyouwanttosavethea.outfile,youshouldchangeitsname
toamoredescriptiveone.Otherwise,youmightaccidentally
overwriteitduringalatercompilation.
$mva.outaccounting
Tosaveyourselfthetroubleofrenamingana.outfile,youcan
specifythenameoftheexecutablefileonthegcccommand
line.TheooptioncausestheCcompilertogivetheexecutable
thenameyouspecifyratherthana.out.Inthenextexample,
theexecutableisnamedaccounting:
$gcc-oaccountingledger.cacctspay.cacctsrec.c
Ifaccountingdoesnotrequirearguments,youcanrunitwith
thefollowingcommand:
$accounting
Youcansuppressthelinkingphaseofcompilationbyusingthe
coptionwiththegcccommand.Becausethecoptiondoesnot
treatunresolvedexternalreferencesaserrors,itallowsyouto
compileanddebugthesyntaxofthemodulesofaprogramas
youcreatethem.Onceyouhavecompiledanddebuggedallof
themodules,youcanrungccagainwiththeobjectfilesas
argumentstoproduceanexecutableprogram.Inthenext
example,gccproducesthreeobjectfilesbutnoexecutable:
$gcc-cledger.cacctspay.cacctsrec.c
$ls
acctspay.cacctspay.oacctsrec.cacctsrec.oledger.cledger.o
Nowifyourungccagainandnametheobjectfilesonthe
commandline,gccwillproducetheexecutable.Becauseit
recognizesthefilenameextension.o,theCcompilerknowsthat
thefilesneedonlytobelinked.Youcanalsoincludeboth.cand
.ofilesonasinglecommandline:
$gcc-oaccountingledger.oacctspay.cacctsrec.o
TheCcompilerrecognizesthatthe.cfileneedstobe
preprocessedandcompiled,whereasthe.ofilesdonot.TheC
compileralsoacceptsassemblylanguagefilesendingin.sand
assemblesandlinksthem.Thisfeaturemakesiteasytomodify
andrecompileaprogram.
Youcancreateaseriesoffilestodivideaprojectintofunctional
groups.Forinstance,youmightputgraphicsroutinesinone
file,stringfunctionsinanotherfile,anddatabasecallsinathird
file.Havingmultiplefilescanenableseveralengineerstowork
onthesameprojectconcurrentlyandcanspeedupcompilation.
Forexample,ifallfunctionsareinonefileandyouchangeone
ofthefunctions,thecompilermustrecompileallofthe
functionsinthefile.Recompilingtheentireprogrammaytake
considerabletimeevenifyoumadeonlyasmallchange.When
youseparatefunctionsintodifferentfiles,onlythefilethatyou
changemustberecompiled.Forlargeprogramswithmany
sourcefiles(forexample,theCcompileroremacs),thetimelost
byrecompilingonehugefileforeverysmallchangewouldbe
enormous.Formoreinformationreferto"make:KeepsaSetof
ProgramsCurrent"onpage842.
Tip:Whatnottonameaprogram
Donotnameaprogramtestoranyothernameofa
builtinorotherexecutableonthelocalsystem.If
youdo,youwilllikelyexecutethebuiltinorother
programinsteadoftheprogramyouintendtorun.
Usewhich(page144)todeterminewhichprogram
youwillrunwhenyougiveacommand.
UsingSharedLibraries
Mostmodernoperatingsystemsusesharedlibraries,alsocalled
dynamiclibraries.Theselibrariesarenotlinkedintoaprogram
atcompiletimebutratherareloadedwhentheprogramstarts
(orlaterinsomecases).Thenamesoffileshousingshared
librarieshavefilenameextensionsof.so(sharedobject)for
example,libc.so.Usuallylibaaa.soisasymboliclinkto
libaaa.so.x,wherexisasmallnumberrepresentingthe
versionofthelibrary.Manyoftheselibrariesarekeptin
/usr/lib.AtypicalLinuxinstallationhasmorethan300shared
librariesin/usr/lib.Applicationscanhavetheirownshared
libraries.Forexample,thegcccompilermightkeepitslibraries
in/usr/lib/gcc-lib/i386-redhat-linux/3.4.0.
Archivedlibraries
Incontrasttosharedlibrariesaretheolder,staticallylinked
libraries(witha.afilenameextension),alsocalledarchived
libraries.Archivedlibrariesareaddedtotheexecutablefile
duringthelast(linking)phaseofcompilation.Theiradditioncan
makeaprogramrunslightlyfasterthefirsttimeitisrun,albeit
attheexpenseofprogrammaintainabilityandsize.Taken
together,thecombinedsizeofseveralexecutablesthatusea
sharedlibraryandthesizeofthesharedlibraryaresmaller
thanthecombinedsizeofthesameexecutableswithstatic
libraries.Whenarunningprogramhasalreadyloadeda
dynamiclibrary,asecondprogramthatrequiresthesame
dynamiclibrarystartsslightlyfaster.
Reducingmemoryusageandincreasingmaintainabilityarethe
primaryreasonsforusingsharedobjectlibraries;thanksto
theseadvantages,theyhavelargelyreplacedstaticallylinked
librariesasthelibrarytypeofchoice.Considerwhathappens
whenyoudiscoveranerrorinalibrary.Withastaticlibrary,you
mustrelinkeveryprogramthatusesthelibraryoncethelibrary
hasbeenfixedandrecompiled.Incontrast,withadynamic
library,youneedtofixandrecompileonlythelibraryitself.
Sharedobjectlibrariesalsomakedynamicloadingofprogram
librariesontheflypossible(forexample,perl,python,andtcl
extensionsandmodules).Forexample,theApache(HTTP)Web
serverspecifiesmodulesinthehttpd.conffileandloadsthem
asneeded.
ldd
Theldd(listdynamicdependencies)utilitytellsyouwhich
sharedlibrariesaprogramneeds.Thefollowingexampleshows
thatcpuseslibacl,theAccessControlListslibrary;libc,theC
library;libattr,theExtendedAttributeslibrary;andld-linux,
theruntimelinker:
$ldd/bin/cp
linux-gate.so.1=>(0x00ef8000)
libacl.so.1=>/lib/libacl.so.1(0x00c81000)
libselinux.so.1=>/lib/libselinux.so.1(0x00570000)
libc.so.6=>/lib/libc.so.6(0x0027b000)
libattr.so.1=>/lib/libattr.so.1(0x00b92000)
libdl.so.2=>/lib/libdl.so.2(0x003ce000)
libsepol.so.1=>/lib/libsepol.so.1(0x00aed000)
/lib/ld-linux.so.2(0x0025e000)
Runninglddon/usr/bin/gnome-session(aprogramthat
startsagraphicalGNOMEsession)lists69librariesfrom
/usr/liband/lib.
Theprogramthatdoesthedynamicruntimelinking,ld-linux.so,
alwayslooksin/usr/libforlibraries.Theotherdirectoriesthat
ldsearchesvarydependingonhowldissetup.Youcanadd
directoriesforldtolookinbyspecifyingasearchpathat
compile(actuallylink)time,usingtheroptionfollowedbya
colon-separatedlistofdirectories(donotputaSPACEafterr).
Useonlyabsolutepathnamesinthissearchpath.Althoughyou
usethisoptiononthegcccommandline,itispassedtothe
linker(ld).Thegnome-sessiondesktopmanagerwaslikelylinked
withacommandsuchasthefollowing:
gccflagsognome-sessionobjectsr/liblibraries
Thiscommandlineallowsld.so(andldd)tosearch/libin
additiontothestandard/usr/libforthelibrariesneededby
theexecutable.
Thecompilerneedstoseethesharedlibrariesatlinktimeto
confirmthattheneededfunctionsandproceduresarepresent
aspromisedbytheheader(.h)files.UsetheLoptiontotellthe
compile-timelinkertolookinthedirectorymylibforsharedor
staticlibraries:Lmylib.Unlikethesearchpath,Lcanuse
relativepathnamessuchasL../libahandyfeaturewhena
programbuildsitsownsharedlibrary.Thelibrarycanbeinone
locationatbuildtime(L)butinanotherlocationatruntime
afteritisinstalled(rpath).TheSPACEafterLisoptionalandis
usuallyomitted;rmustnotbefollowedbyaSPACE.Youcan
repeattheLandtheroptionsmultipletimesonthelinkline.
FixingBrokenBinaries
Thecommandlinesearchpathisafairlynewidea.Thesearch
pathwastraditionallyspecifiedbyusingthe
LD_LIBRARY_PATHand,morerecently,LD_RUN_PATH
environmentvariables.Thesevariableshavethesameformat
asPATH(page292).ThedirectoriesinLD_LIBRARY_PATH
arenormallysearchedbeforetheusuallibrarylocations.Newer
LinuxreleasesextendthefunctionofLD_LIBRARY_PATHto
specifydirectoriestobesearchedeitherbeforeorafterthe
normallocations.Seetheldmanpagefordetails.The
LD_RUN_PATHvariablebehavessimilarlyto
LD_LIBRARY_PATH.Ifyouuser,however,
LD_LIBRARY_PATHsupersedesanythinginLD_RUN_PATH.
TheuseofLD_LIBRARY_PATHbringsupseveralproblems.
Becauseonlyoneenvironmentvariableexists,itmustbe
sharedamongallprograms.Iftwoprogramshavethesame
nameforalibraryorusedifferent,incompatibleversionsofthe
samelibrary,onlythefirstwillbefound.Asaresultoneofthe
programswillnotrunorevenworsewillnotruncorrectly.
Wrappers
LD_LIBRARY_PATHstillhasitsplaceinthescripts,called
wrappers,thatareusedtofixbrokenbinaries.Supposethatthe
brokenbinarybbusesthesharedlibrarylibbb.so,whichyou
wanttoputin/opt/bb/libandnotin/usr/lib,asthebb
programmerrequested.Thecommandlddbbwilltellyou
whichlibrariesaremissing.
Security:LD_LIBRARY_PATH
Undercertaincircumstancesamalicioususercan
createaTrojanhorsenamedlibc.soandplaceitina
directorythatissearchedbefore/usr/lib(any
directorythatappearsinLD_LIBRARY_PATH
before/usr/lib).Thefakelibcwillthenbeused
insteadofthereallibc.
Thisisnotaproblem:Renamebbtobb.broken,andcreatea
/bin/shwrappernamedbb.
#!/bin/sh
LD_LIBRARY_PATH=/opt/bb/lib
exportLD_LIBRARY_PATH
execbb.broken"$@"
Using$@ratherthan$*preservesSPACEsintheparameters;
seepage922.
Awrappercanalsoallowyoutoinstallprogramsinarbitrary
locations.
CreatingSharedLibraries
Buildingadynamicallyloadablesharedlibraryisnotatrivial
matter:Itinvolvessettingupreentrantfunctioncalls,defininga
libraryentranceroutine,andperformingothertasks.Whenyou
wanttocreateasharedobjectlibrary,youmustcompilethe
sourcefileswiththefPIC(position-independentcode)optionto
gccandlinktheresultingobjectfilesintothelibxx.sofileusing
thesharedxoptionstothelinker(forexample,ldsharedxo
libmylib.so*.o).Thebestresourceforinvestigatingshared
libraryconstructionandusageisexistingcodeontheInternet.
Forexample,youcanlookatthesourcefilesforzlibat
www.gzip.org/zlib.
C++
C++fileshavespecialneeds,andlibraries(sharedornot)often
havetobemadebythecompilerratherthanldorar.Shared
librariescandependonothersharedlibrariesandhavetheir
ownsearchpaths.IfyousetLD_LIBRARY_PATH,addthei
flagtothelinkphasewhencompilingtoignorethecurrent
LD_LIBRARY_PATHoryoumayhaveunexpectedresults.
IdeallyyouwouldnothaveLD_LIBRARY_PATHsetona
globallevelbutwoulduseitonlyinwrappersasneeded.
make:KeepsaSetofProgramsCurrent
Tip:ThissectioncoverstheGNUmake
program
ThissectiondescribestheGNUmakeprogram.Other
maketools(BSNmake,GNUstepmake,Borlandmake,
andsoon)areavailableaswellassimilartoolssuch
asant(theApachebuildtool).Makefilescreatedfor
GNUmakeareoftenincompatiblewithothermake
tools,whichcanbeproblematicifyouaretryingto
compilecodetargetedforanotherplatform.
Inalargeprogramwithmanysourceandheaderfiles,thefiles
typicallydependononeanotherincomplexways.Whenyou
changeafilethatotherfilesdependon,youmustrecompileall
dependentfiles.Forexample,youmighthaveseveralsource
files,allofwhichuseasingleheaderfile.Whenyouchangethe
headerfile,youmustrecompileeachofthesourcefiles.The
headerfilemightdependonotherheaderfiles,andsoforth.
Figure27-3showsasimpleexampleofthesekindsof
dependencyrelationships.Eacharrowinthisfigurepointsfrom
afiletoanotherfilethatdependsonit.
Figure27-3.Dependencygraphforthetarget
form
Whenyouareworkingonalargeprogram,itcanbedifficult,
time-consuming,andtedioustodeterminewhichmodulesneed
toberecompiledbecauseoftheirdependencyrelationships.
Themakeutilityautomatesthisprocess.
Dependencylines:targetfilesandprerequisitefiles
Atitssimplest,makelooksatdependencylinesinafilenamed
makefileorMakefileintheworkingdirectory.Thedependency
linesindicaterelationshipsamongfiles,specifyingatargetfile
thatdependsononeormoreprerequisitefiles.Ifyouhave
modifiedanyoftheprerequisitefilesmorerecentlythantheir
targetfile,makeupdatesthetargetfilebasedonconstruction
commandsthatfollowthedependencyline.Themakeutility
normallystopsifitencountersanerrorduringtheconstruction
process.
Thefilecontainingtheupdatinginformationforthemakeutility
iscalledamakefile.(Seepage832foratrivialexample.)A
simplemakefilehasthefollowingsyntax:
target:prerequisite-list
TABconstruction-commands
Thedependencylineconsistsofthetargetandthe
prerequisite-list,separatedbyacolon.Eachconstruction-
commandsline(youmayhavemorethanone)muststartwith
aTABandmustfollowthedependencyline.Longlinescanbe
continuedbyplacingaBACKSLASH(\)asthelastcharacteronthe
line.
Thetargetisthenameofthefilethatdependsonthefilesin
theprerequisite-list.Theconstruction-commandsare
regularshellcommandsthatconstruct(usuallycompileand/or
link)thetargetfile.Themakeutilityexecutestheconstruction-
commandswhenthemodificationtimeofoneormorefilesin
theprerequisite-listismorerecentthanthatofthetargetfile.
Thefollowingexampleshowsthedependencylineand
constructioncommandsforthefilenamedforminFigure27-3.
Theformfiledependsontheprerequisitessize.oand
length.o.Anappropriategcccommandconstructsthetarget:
form:size.olength.o
TABgcc-oformsize.olength.o
Eachoftheprerequisitesononedependencylinecanbea
targetonanotherdependencyline.Forexample,bothsize.o
andlength.oaretargetsonotherdependencylines.Although
theexampleinFigure27-3illustratesasimplecase,inother
situationsthenestingofdependencyspecificationscancreatea
complexhierarchythatdictatesrelationshipsamongmanyfiles.
Thefollowingmakefile(namedMakefile)correspondstothe
completedependencystructureshowninFigure27-3.The
executablefileformdependsontwoobjectfiles,andeachof
theseobjectfilesdependsonitsrespectivesourcefileanda
headerfile,form.h.Inturn,form.hdependsontwoother
headerfiles.
$catMakefile
form:size.olength.o
gcc-oformsize.olength.o
size.o:size.cform.h
gcc-csize.c
length.o:length.cform.h
gcc-clength.c
form.h:num.htable.h
catnum.htable.h>form.h
Althoughthelastlinewouldnotnormallybeseeninamakefile,
itillustratesthepointthatyoucanputanyshellcommandona
constructionline.Becausetheshellprocessesmakefiles,the
commandlineshouldbeonethatyoucouldenterinresponseto
ashellprompt.
Thefollowingcommandbuildsthedefaulttargetformifanyof
itsprerequisitesaremorerecentthantheircorresponding
targetsorifanyofthetargetsdonotexist:
$make
Thus,ifthefileformhasbeendeleted,makewillrebuildit,
regardlessofthemodificationdatesofitsprerequisitefiles.The
firsttargetinamakefileisthedefaultandisbuiltwhenyoucall
makewithoutanyarguments.
Ifyouwantmaketorebuildatargetotherthanthefirstonein
themakefile,youmustprovidethattargetasanargumentto
make.Thefollowingcommandrebuildsonlyform.hifitdoesnot
existorifitsprerequisitesweremorerecentlymodifiedthan
thetarget:
$makeform.h
ImpliedDependencies
Youcanrelyonimplieddependenciesandconstruction
commandstofacilitatethejobofwritingamakefile.For
instance,ifyoudonotincludeadependencylineforanobject
file,makeassumesthattheobjectfiledependsonacompileror
assemblersourcecodefile.Thus,ifaprerequisiteforatarget
fileisxxx.oandnodependencylineidentifiesxxx.oasa
target,makelooksatthefilenameextensiontodeterminehow
tobuildthe.ofile.Ifitfindsanappropriatesourcefile,make
providesadefaultconstructioncommandlinethatcallsthe
propercompilerortheassemblertocreatetheobjectfile.Table
27-1listssomefilenameextensionsthatmakerecognizesand
thetypeoffilethatcorrespondstoeachfilenameextension.
Table27-1.Filenameextensions
Filenamewithextension Typeoffile
filename.c Cprogramminglanguagesourcecode
filename.C,filename.cc,
filename.cxx,
filename.c++,
filename.cpp
C++programminglanguagesourcecode
filename.f Fortranprogramminglanguagesource
code
filename.h Headerfile
filename.l flex,lexlexicalanalyzergeneratorsource
code
filename.m Objective-Cprogramminglanguage
sourcecode
filename.o Objectmodule
filename.s Assemblercode
filename.sh Shellscript
filename.y bison,yaccparsergeneratorsourcecode
CandC++aretraditionalprogramminglanguagesthatare
availablewithRedHatmanyotherLinuxdistributions.Thebison
andflextoolscreatecommandlanguages.
Inthenextexample,amakefilekeepsthefilenamedcompute
up-to-date.Themakeutilityignoresanylinethatbeginswitha
poundsign(#),sothefirstthreelinesofthefollowingmakefile
arecommentlines.Thefirstdependencylineshowsthat
computedependsontwoobjectfiles:compute.oandcalc.o.
Thecorrespondingconstructionlinegivesthecommandthat
makeneedstoproducecompute.Theseconddependencyline
showsthatcompute.odependsnotonlyonitsCsourcefilebut
alsoonthecompute.hheaderfile.Theconstructionlinefor
compute.ousestheCcompileroptimizer(O3option).The
thirdsetofdependencyandconstructionlinesisnotrequired.
Intheirabsence,makeinfersthatcalc.odependsoncalc.cand
producesthecommandlineneededforthecompilation:
$catMakefile
#
#Makefileforcompute
#
compute:compute.ocalc.o
gcc-ocomputecompute.ocalc.o
compute.o:compute.ccompute.h
gcc-c-O3compute.c
calc.o:calc.c
gcc-ccalc.c
clean:
rm*.o*core**~
Therearenoprerequisitesforclean,thelasttarget.Thistarget
iscommonlyusedtogetridofextraneousfilesthatmaybe
out-of-dateornolongerneeded,suchas.ofiles.
Belowaresomesampleexecutionsofmakebasedonthe
previousmakefile.Asthelscommandshows,compute.o,
calc.o,andcomputearenotup-to-date.Consequentlythe
makecommandrunstheconstructioncommandsthatre-create
them.
$ls-ltr
total22
rwrw1alexpubs311Jun2115:56makefile
rwrw1alexpubs354Jun2116:02calc.o
rwxrwx1alexpubs6337Jun2116:04compute
rwrw1alexpubs49Jun2116:04compute.h
rwrw1alexpubs880Jun2116:04compute.o
rwrw1alexpubs780Jun2118:20compute.c
rwrw1alexpubs179Jun2118:20calc.c
$make
gcc-c-O3compute.c
gcc-ccalc.c
gcc-ocomputecompute.ocalc.o
Ifyourunmakeonceandthenrunitagainwithoutmakingany
changestotheprerequisitefiles,makeindicatesthatthe
programisup-to-dateanddoesnotexecuteanycommands:
$make
make:'compute'isuptodate.
touch
Thenextexampleusesthetouchutilitytochangethe
modificationtimeofaprerequisitefile.Thissimulationshows
whathappenswhenyoualterthefile.Themakeutilityexecutes
onlythecommandsnecessarytobringtheout-of-datetargets
up-to-date:
$touchcalc.c
$make
gcc-ccalc.c
gcc-ocomputecompute.ocalc.o
Inthenextexample,touchchangesthemodificationtimeof
compute.h.Themakeutilityre-createscompute.obecauseit
dependsoncompute.handre-createstheexecutablebecause
itdependsoncompute.o:
$touchcompute.h
$make
gcc-c-O3compute.c
gcc-ocomputecompute.ocalc.o
n
Ifyouwanttoseewhatmakewoulddoifyouranit,runitwith
then(noexecute)option.Thisoptiondisplaysthecommands
thatmakewouldexecutebutitdoesnotexecutethem.
t
Astheseexamplesillustrate,touchisusefulwhenyouwantto
foolmakeeitherintorecompilingprogramsorintonot
recompilingthem.Youcanusetouchtoupdatethemodification
timesofallsourcefilessothatmakeconsidersnothingtobeup-
to-date;makewillthenrecompileeverything.Alternatively,you
canusetouchorthetoptiontomaketotouchallrelevantfiles;
makethenconsiderseverythingtobeup-to-date.Usingtouchin
thismannerisusefulifthemodificationtimesoffileshave
changedyetthefilesremainup-to-date(ascanhappenwhen
youcopyasetoffilesfromonedirectorytoanother).
Thefollowingexampleusesmakenseveraltimestoseewhat
makewoulddoifyougaveamakecommand.Thefirst
commandshowsthatthetarget,compute,isup-to-date.Next
touchmakesthemodificationdatesonall*.cfilesmorerecent
thantheirtargets,andmakenshowswhatmakewoulddoif
youcalleditwithoutthenoption.Themaketcommandthen
bringsalltargetsup-to-date.Thefinalmakencommand
confirmsthatcomputeisup-to-date.
$maken
make:'compute'isuptodate.
$touch*.c
$maken
gcccO3compute.c
gccccalc.c
gccocomputecompute.ocalc.o
$maket
touchcompute.o
touchcalc.o
touchcompute
$maken
make:'compute'isuptodate.
j
Thej(jobs)optionperformsanumberoftasksinparallel;the
numericargumenttojspecifiesthenumberofjobsor
processes.MostmaketaskshitthediskfirstandtheCPU
second,resultinginCPUusagedroppingbetweencompilations.
Onamultiprocessorsystem,youcanreduceCPUusageby
issuingthecommandmakejn,wherenisthenumberofCPUs
plus1.Runningtasksinparallelcansignificantlyreducethe
buildtimeforalargeproject.
Itisagoodideatokeepintermediatefilesaroundwhileyouare
writinganddebuggingaprogramsothatyouneedtorebuild
onlytheonesthatchange.Onceyouaresatisfiedwiththe
programyouhavecreated,youcanusethemakefiletorelease
thediskspaceoccupiedbytheextrafiles.Usingacleantarget
inamakefilemeansthatyoudonothavetorememberallthe
littlepiecesthatcansafelybedeleted.Thenextexamplesimply
removesallobject(.o)filesandallfileswithfilenamesthatend
withatilde(~):
$makeclean
rm*.o*.~
Optional:Macros
Themakeutility'smacrofacilityenablesyoutocreateandusemacroswithina
makefile.Thesyntaxofamacrodefinitionis
ID=list
whereIDisanidentifyingnameandlistisalistoffilenames.Afterthismacro
definition,$(ID)representslistinthemakefile.
WithamacroyoucancompileaprogramwithanyofseveralCcompilersby
makingonlyaminorchangetothemakefile.ByusingtheCCmacroand
replacingalloccurrencesofgccinthemakefileonpage846with$(CC),for
example,youneedtoassignavalueonlytoCCtousethecompilerofyour
choice:
$catMakefile
#
#Makefileforcompute
#
CC=gcc
compute:compute.ocalc.o
$(CC)ocomputecompute.ocalc.o
compute.o:compute.ccompute.h
$(CC)cO3compute.c
calc.o:calc.c
$(CC)ccalc.c
clean:
rm*.o
Thisexampleassumesthatthecompiler/loaderflagsarethesameacross
compilers/loaders.Inamorecomplexsituation,youmayneedtocreatemacros
fortheseflagsorusethedefaultvalues.
Severalcommercial,high-performancecompilersareavailableforLinux.You
couldspecifythecompilerfromthePortlandGroup,pgcc,byreplacingthe
CC=gccassignmentwithCC=pgcc.IfyoudonotassignavaluetotheCC
macro,itdefaultstogccunderLinux.TheCCmacroinvokestheCcompilerwith
onlytheoptionsthatyouspecify.
Severalothermacrodefinitionsarecommonlyused.TheCFLAGSmacrosends
argumentstotheCcompiler,LDFLAGSsendsargumentstothelinker(ld,orgcc
o),andCPPFLAGSsendsargumentstotheCpreprocessorandprogramsthat
useit,includinggcc.TheCOMPILE.cmacroexpandsto$(CC)c$(CFLAGS)
$(CPPFLAGS).TheLINK.cmacroexpandsto$(CC)$(CFLAGS)
$(CPPFLAGS)$(LDFLAGS).
Bydefault,makeinvokestheCcompilerwithoutanyoptions(exceptthecoption
whenitisappropriatetocompilebutnotlinkafile).YoucanusetheCFLAGS
macrodefinitiontocausemaketocalltheCcompilerwithspecificoptions.Inthe
followingsyntax,replaceoptionswiththeoptionsyouwanttouse:
CFLAGS=options
Thefollowingmakefileusesmacrosaswellasimplieddependenciesand
constructions:
#makefile:report,print,printf,printh
#
CC=gcc
CFLAGS=-O3
#commentoutthetwolinesaboveanduncommentthe
#twobelowwhenyouareusingthePortlandGroup'scompiler
#CC=pgcc
#CFLAGS=-fast
FILES=in.cout.cratio.cprocess.ctally.c
OBJECTS=in.oout.oratio.oprocess.otally.o
HEADERS=names.hcompanies.hconventions.h
report:$(OBJECTS)
$(LINK.c)-oreport$(OBJECTS)
ratio.o:$(HEADERS)
process.o:$(HEADERS)
tally.o:$(HEADERS)
print:
pr$(FILES)$(HEADERS)|lpr
printf:
pr$(FILES)|lpr
printh:
pr$(HEADERS)|lpr
Followingthecommentlinesinthisexample,themakefileusestheCFLAGS
macrotocausemakealwaystousetheoptimizer(O3option)whenitinvokesthe
Ccompilerastheresultofanimpliedconstruction.(TheCCandCFLAGS
definitionsforthepgccCcompilerperformthesamefunctionswhentheyare
uncommentedandyouareworkingwithpgcc,exceptthatyouusefastwithpgcc
andO3withgcc.)Aconstructionlineinamakefileoverridesthecorresponding
impliedconstructionline,ifoneexists.Ifyouwanttoapplyamacrotoa
constructioncommand,youmustincludethemacrointhatcommand;see
OBJECTSintheconstructioncommandforthereporttarget.FollowingCFLAGS,
themakefiledefinestheFILES,OBJECTS,andHEADERSmacros.Eachofthese
macrosdefinesalistoffiles.
Thefirstdependencylineintheprecedingexampleshowsthatreportdepends
onthelistoffilesdefinedbyOBJECTS.Thecorrespondingconstructionlineuses
theLINK.cmacrotolinkthefilesdefinedbyOBJECTSandcreateanexecutable
filenamedreport.IfyouspecifyanyLDFLAGS,theyareusedinthisstep.
Thenextthreedependencylinesshowthatthreeobjectfilesdependonthelist
offilesdefinedbyHEADERS.Becausetherearenoconstructionlines,makelooks
forasourcecodefilecorrespondingtoeachobjectfileandcompilesit.These
threedependencylinesensurethattheobjectfilesarerecompiledifanyheader
fileschange.
Youcancombineseveraltargetsononedependencyline,sothesethree
dependencylinescouldhavebeencombinedintooneline:
ratio.oprocess.otally.o:$(HEADERS)
Thethreefinaldependencylinesintheprecedingexamplesendsourceand
headerfilestotheprinter.Theselineshavenothingtodowithcompilingthe
reportfile;noneofthesetargets(print,printf,andprinth)dependson
anything.Whenyoucalloneofthesetargetsfromthecommandline,make
executestheconstructionlinefollowingit.Thefollowingcommandprintsall
sourcefilesdefinedbyFILES:
$makeprintf
Youcanoverridemacrosinamakefilebyspecifyingthemonthecommandline.
Thefollowingcommandaddsdebuggingsymbolstoallobjectfiles:
$makeCFLAGS=-g...
DebuggingCPrograms
TheCcompilerisliberalaboutthekindsofconstructsitallows
inprograms.InkeepingwiththeUNIXphilosophythat"no
newsisgoodnews"andthattheuserknowswhatisbest,gcc,
likemanyotherLinuxutilities,acceptsalmostanyconstruct
thatislogicallypossibleaccordingtothedefinitionofthe
language.Althoughthisapproachgivestheprogrammeragreat
dealofflexibilityandcontrol,itcanmakedebuggingdifficult.
Figure27-4showsbadtabs.c,aflawedversionofthetabs.c
programdiscussedearlier.Itcontainssomeerrorsanddoesnot
runproperly.Thissectionusesthisprogramtoillustratesome
debuggingtechniques.
Figure27-4.Thebadtabs.cprogram(Theline
numbersarenotpartofthesourcecode;the
arrowspointtoerrorsintheprogram.)
[Viewfullsizeimage]
Inthefollowingexample,badtabs.ciscompiledandthenrun
withinputfromthetesttabsfile.Inspectionoftheoutput
showsthattheTABcharacterhasnotbeenreplacedwiththe
propernumberofSPACEs:
$gccobadtabsbadtabs.c
$cattesttabs
abcTABxyz
$badtabs<testtabs
abcxyz
OnewaytodebugaCprogramistoinsertprintstatementsat
criticalpointsthroughoutthesourcecode.Tolearnmoreabout
thebehaviorofbadtabs.cwhenitruns,youcanreplacethe
contentsoftheswitchstatementasfollows:
case'\t':/*cisatab*/
fprintf(stderr,"beforecalltofindstop,posnis%d\n",posn);
inc=findstop(&posn);
fprintf(stderr,"aftercalltofindstop,posnis%d\n",posn);
for(;inc>0;inc--)
putchar('');
break;
case'\n':/*cisanewline*/
fprintf(stderr,"gotanewline\n");
putchar(c);
posn=0;
break;
default:/*cisanythingelse*/
fprintf(stderr,"gotanothercharacter\n");
putchar(c);
posn++;
break;
Thefprintfstatementsinthiscodesendtheirmessagesto
standarderror.Thus,ifyouredirectstandardoutputofthis
program,itwillnotbeinterspersedwiththeoutputsentto
standarderror.Thenextexampledemonstratestheoperationof
thisprogramontheinputfiletesttabs:
$gcc-obadtabsbadtabs.c
$badtabs<testtabs>testspaces
gotanothercharacter
gotanothercharacter
gotanothercharacter
beforecalltofindstop,posnis3
aftercalltofindstop,posnis3
gotanothercharacter
gotanothercharacter
gotanothercharacter
gotanewline
$cattestspaces
abcTABxyz
Thefprintfstatementsprovideadditionalinformationaboutthe
executionoftabs.c.Thevalueofthevariableposnisnot
incrementedinfindstop,asitshouldbe.Thiscluemightbe
enoughtoleadyoutothebugintheprogram.Ifnot,youmight
attemptto"corner"theoffendingcodebyinsertingprint
statementsinfindstop.
Forsimpleprogramsorwhenyouhaveanideaofwhatiswrong
withaprogram,addingprintstatementsthattracethe
executionofthecodecanoftenhelpyoudiscovertheproblem
quickly.Abetterstrategymaybetotakeadvantageofthetools
thatLinuxprovidestohelpyoudebugprograms.
gccCompilerWarningOptions
Thegcccompilerincludesmanyofthefeaturesoflint,theclassic
Cprogramverifier,andthensome.(Thelintutilityisnot
availableunderLinux;usesplint[secureprogramminglint;
www.splint.org]instead.)ThegcccompilercanidentifymanyC
programconstructsthatposepotentialproblems,evenfor
programsthatconformtothelanguage'ssyntaxrules.For
instance,youcanrequestthatthecompilerreportavariable
thatisdeclaredbutnotused,acommentthatisnotproperly
terminated,orafunctionthatreturnsatypenotpermittedin
olderversionsofC.Optionsthatenablethisstrictercompiler
behaviorallbeginwiththeuppercaseletterW(Warning).
AmongtheWoptionsisaclassofwarningsthattypicallyresult
fromprogrammercarelessnessorinexperience(seeTable27-
2).Theconstructsthatgeneratethesewarningsaregenerally
easytofixandeasytoavoid.
Table27-2.gccWoptions
Option Reportsanerrorwhen
Wimplicit Afunctionorparameterisnotexplicitlydeclared
Wreturn-type Afunctionthatisnotvoiddoesnotreturnavalueor
thetypeofafunctiondefaultstoint
Wunused Avariableisdeclaredbutnotused
Wcomment Thecharacters/*,whichnormallybeginacomment,
occurwithinacomment
Wformat Certaininput/outputstatementscontainformat
specificationsthatdonotmatchthearguments
TheWalloptiondisplayswarningsaboutalloftheerrorslisted
inTable27-2,alongwithother,similarerrors.
Theexampleprogrambadtabs.cissyntacticallycorrect:It
compileswithoutgeneratinganerror.However,ifyoucompileit
(ccausesgcctocompilebutnottolink)withtheWalloption,
gccidentifiesseveralproblems.(Warningmessagesdonotstop
theprogramfromcompiling,whereaserrormessagesdo.)
$gcccWallbadtabs.c
badtabs.c:11:warning:returntypedefaultsto'int'
badtabs.c:Infunction'main':
badtabs.c:34:warning:controlreachesendofnonvoidfunction
badtabs.c:46:25:warning:"/*"withincomment
badtabs.c:Infunction'findstop':
badtabs.c:40:warning:unusedvariable'colindex'
badtabs.c:47:warning:controlreachesendofnonvoidfunction
Thefourthwarningmessagereferencesline46,column25.
Inspectionofthecodeforbadtabs.caroundthatlinerevealsa
commentthatisnotproperlyterminated.Thecompilerseesthe
string/*inthefollowinglineasthebeginningofacomment:
/*incrementargument(currentcolumnposition)tonexttabstop*/
However,becausethecharacters*and/attheendoftheline
areseparatedbyaSPACE,theydonotsignifytheendofthe
commenttothecompiler.Insteadthecompilerinterpretsallof
thestatementsincludingthestatementthatincrementsthe
argumentthroughthestring*/attheveryendofthefindstop
functionaspartofthecomment.AfteryouremovetheSPACE
betweenthecharacters*and/,badtabsproducesthecorrect
output.
Thenextfewparagraphsdiscusstheremainingwarning
messages.Althoughmostdonotcauseproblemsinthe
executionofbadtabs,youcangenerallyimproveaprogramby
rewritingthosepartsofthecodethatproducesuchwarnings.
Becausethedefinitionofthefunctionmaindoesnotincludean
explicittype,thecompilerassumestypeint,thedefault.This
resultsinthewarningmessagereferencingline11in
badtabs.c,thetopofthefunctionmain.Anadditionalwarning
isgivenwhenthecompilerencounterstheendofthefunction
main(line34)withoutseeingavaluereturned.
Ifaprogramrunssuccessfully,byconventionitshouldreturna
zerovalue;ifnovalueisreturned,theexitcodeisundefined.
AlthoughmanyCprogramsdonotreturnavalue,thisoversight
cancauseproblemswhentheprogramisexecuted.Whenyou
addthefollowingstatementattheendofthefunctionmainin
badtabs.c,thewarningreferencingline34disappears:
return0;
Line40ofbadtabs.ccontainsthedefinitionforthelocal
variablecolindexinthefunctionfindstop.Awarningmessage
referencesthislinebecausethecolindexvariableisnever
used.Removingitsdeclarationeliminatesthewarningmessage.
Thefinalwarningmessage,referencingline47,resultsfromthe
improperlyterminatedcommentdiscussedearlier.Thecompiler
issuesthewarningmessagebecauseitneverseesareturn
statementinfindstop.(Thecompilerignorescommentedtext.)
Becausethefunctionfindstopreturnstypeint,thecompiler
expectstofindareturnstatementbeforereachingtheendof
thefunction.Thiswarningdisappearswhenthecommentis
properlyterminated.
ManyotherWoptionsareavailablewiththegcccompiler.The
onesnotcoveredintheWallclassoftendealwithportability
differences;modifyingthecodecausingthesewarningsmay
notbeappropriate.Thesewarningsusuallyresultwhen
programsarewrittenindifferentCdialectsorwhenconstructs
maynotworkwellwithother(especiallyolder)Ccompilers.The
pedantic-errorsoptionturnswarningsintoerrors,causinga
buildtofailifitcontainsitemsthatwouldgeneratewarnings.To
learnmoreabouttheseandotherwarningoptions,refertothe
gccinfopage.
SymbolicDebuggers
Manydebuggersareavailabletotackleproblemsthatevade
simplerdebuggingmethodssuchasprintstatementsand
compilerwarningoptions.Thesedebuggersincludegdb,kdbg,
xxgdbmxgdb,ddd,andups,allofwhichareavailableontheWeb
(refertoAppendixB).Suchhigh-levelsymbolicdebuggers
enableyoutoanalyzetheexecutionofaprogramintermsofC
languagestatements.Theyalsoprovidealower-levelviewfor
analyzingtheexecutionofaprogramintermsofthemachine
instructions.Exceptforgdb,eachofthesedebuggersprovidesa
GUI.
Adebuggerenablesyoutomonitorandcontroltheexecutionof
aprogram.Youcanstepthroughaprogramlinebylinewhile
youexaminethestateoftheexecutionenvironment.
Coredumps
Adebuggeralsoallowsyoutoexaminecorefiles(whichare
namedcore).Whenaseriouserroroccursduringtheexecution
ofaprogram,theoperatingsystemcancreateacorefile
containinginformationaboutthestateoftheprogramandthe
systemwhentheerroroccurred.Thisfilecomprisesadumpof
thecomputer'smemory(itwaspreviouslycalledcore
memoryhencethetermcoredump)thatwasbeingusedbythe
program.Toconservediskspace,yoursystemmaynotsave
corefilesautomatically.Youcanusetheulimitbuiltintoallow
corefilestobesaved.Ifyouarerunningbash,thefollowing
commandallowscorefilesofunlimitedsizetobesavedtodisk:
$ulimit-cunlimited
Theoperatingsystemadvisesyouwheneveritdumpscore.You
canuseasymbolicdebuggertoreadinformationfromacore
filetoidentifythelineintheprogramwheretheerroroccurred,
tocheckthevaluesofvariablesatthatpoint,andsoforth.
Becausecorefilestendtobelargeandtakeupdiskspace,be
suretoremovethesefileswhenyounolongerneedthem.
gdb:SymbolicDebugger
ThissectionexplainshowtousetheGNUgdbdebugger.Other
symbolicdebuggersofferadifferentinterfacebutoperateina
similarmanner.Totakefulladvantageofasymbolicdebugger
withaprogram,youmustcompiletheprogramwiththeg
option,whichcausesgcctogenerateadditionalinformationthat
thedebuggeruses.Thisinformationincludesasymboltablea
listofvariablenamesusedintheprogramandtheirassociated
values.Withoutthesymboltableinformation,thedebugger
cannotdisplaythevaluesandtypesofvariables.Ifaprogramis
compiledwithoutthegoption,gdbcannotidentifysourcecode
linesbynumber,asmanygdbcommandsrequire.
Tip:Alwaysuseg
Itisagoodideatousethegoptionevenwhenyou
arereleasingsoftware.Includingdebuggingsymbols
makesabinaryabitlarger.Debuggingsymbolsdo
notmakeaprogramrunmoreslowly,buttheydo
makeitmucheasiertofindproblemsidentifiedby
users.
Tip:Avoidusingoptimizationflagswith
thedebugger
Limittheoptimizationflagsto0or02whenyou
compileaprogramfordebugging.Because
debuggingandoptimizinginherentlyhavedifferent
goals,itmaybebesttoavoidcombiningthetwo
operations.
Tip:Optimizationshouldwork
Turningoptimizationoffcompletelycansometimes
eliminateerrors.Eliminatingerrorsinthisway
shouldnotbeseenasapermanentsolution,
however.Whenoptimizationisnotenabled,the
compilermayautomaticallyinitializevariablesand
performcertainotherchecksforyou,resultingin
morestablecode.Correctcodeshouldwork
correctlywhencompiledwithatleastthe0option
andalmostcertainlywiththe02option.The03
optionoftenincludesexperimentaloptimizations:It
maynotgeneratecorrectcodeinallcases.
Thefollowingexampleusesthegoptionwhencreatingthe
executablefiletabsfromtheCprogramtabs.c,whichwas
discussedatthebeginningofthischapter:
$gcc-gtabs.c-otabs
Inputfortabsiscontainedinthefiletesttabs,whichconsists
ofasingleline:
$cattesttabs
xyzTABabc
Youcannotspecifytheinputfiletotabswhenyoucallthe
debugger.Instead,youmustcallthedebuggerandthenspecify
theinputfilewhenyoustartexecutionwiththeruncommand.
Torunthedebuggeronthesampleexecutable,givethename
oftheexecutablefileonthecommandlinewhenyourungdb.
Youwillseesomeintroductorystatementsaboutgdb,followed
bythegdbprompt[(gdb)].Atthispointthedebuggerisready
toacceptcommands.Thelistcommanddisplaysthefirstten
linesofsourcecode.Asubsequentlistcommanddisplaysthe
nexttenlinesofsourcecode.
$gdbtabs
GNUgdbRedHatLinux(6.3.0.0-1.114rh)
Copyright2004FreeSoftwareFoundation,Inc.
...
(gdb)list
2/*standardoutputwhilemaintainingcolumns*/
3
4#include<stdio.h>
5#defineTABSIZE8
6
7/*prototypeforfunctionfindstop*/
8intfindstop(int*);
9
10intmain()
11{
(gdb)list
12intc;/*characterreadfromstdin*/
13intposn=0;/*columnpositionofcharacter*/
14intinc;/*columnincrementtotabstop*/
15
16while((c=getchar())!=EOF)
17switch(c)
18{
19case'\t':/*cisatab*/
20inc=findstop(&posn);
21for(;inc>0;inc--)
(gdb)
Oneofthemostimportantfeaturesofadebuggerisitsability
torunaprograminacontrolledenvironment.Youcanstopthe
programfromrunningwheneveryouwant.Whileitisstopped,
youcancheckthestateofanargumentorvariable.For
example,youcangivethebreakcommandasourcecodeline
number,anactualmemoryaddress,orafunctionnameasan
argument.Thefollowingcommandtellsgdbtostoptheprocess
wheneverthefunctionfindstopiscalled:
(gdb)breakfindstop
Breakpoint1at0x8048454:filetabs.c,line41.
(gdb)
Thedebuggeracknowledgestherequestbydisplayingthe
breakpointnumber,thehexadecimalmemoryaddressofthe
breakpoint,andthecorrespondingsourcecodelinenumber
(41).Thedebuggernumbersbreakpointsinascendingorderas
youcreatethem,startingwith1.
Aftersettingabreakpointyoucanissuearuncommandto
startexecutionoftabsunderthecontrolofthedebugger.The
runcommandsyntaxallowsyoutouseanglebracketsto
redirectinputandoutput(justastheshellsdo).Inthe
followingexample,thetesttabsfileisspecifiedasinput.When
theprocessstops(atthebreakpoint),youcanusetheprint
commandtocheckthevalueof*col.Thebacktrace(orbt)
commanddisplaysthefunctionstack.Inthisexample,the
currentlyactivefunctionhasbeenassignedthenumber0.The
functionthatcalledfindstop(main)hasbeenassignedthe
number1.
(gdb)run<testtabs
Startingprogram:/home/mark/book/10/tabs<testtabs
Readingsymbolsfromsharedobjectreadfromtargetmemory...done.
LoadedsystemsuppliedDSOat0x28a000
Breakpoint1,findstop(col=0xbf93ae78)attabs.c:41
41retval=(TABSIZE-(*col%TABSIZE));
(gdb)print*col
$1=3
(gdb)backtrace
#0findstop(col=0xbf93ae78)attabs.c:41
#10x080483edinmain()attabs.c:20
(gdb)
Youcanexamineanythinginthecurrentscopevariablesand
argumentsintheactivefunctionaswellasglobalvariables.In
thenextexample,therequesttoexaminethevalueofthe
variableposnatbreakpoint1resultsinanerror.Theerroris
generatedbecausethevariableposnisdefinedlocallyinthe
functionmain,notinthefunctionfindstop.
(gdb)printposn
Nosymbol"posn"incurrentcontext.
Theupcommandchangestheactivefunctiontothecallerof
thecurrentlyactivefunction.Becausemaincallsthefunction
findstop,thefunctionmainbecomestheactivefunctionwhen
yougivetheupcommand.(Thedowncommanddoesthe
inverse.)Theupcommandmaybegivenanintegerargument
specifyingthenumberoflevelsinthefunctionstackto
backtrack,withup1havingthesamemeaningasup.(Youcan
usethebacktracecommandtodeterminewhichargumentto
usewithup.)
(gdb)up
#10x080483edinmain()attabs.c:20
20inc=findstop(&posn);
(gdb)printposn
$2=3
(gdb)print*col
Nosymbol"col"incurrentcontext.
(gdb)
Thecont(continue)commandcausestheprocesstocontinue
runningfromwhereitleftoff.Thetesttabsfilecontainsonly
oneline,sotheprocessfinishesexecutingandtheresults
appearonthescreen.Thedebuggerreportstheexitcodeofthe
program.Acontcommandgivenafteraprogramhasfinished
executingremindsyouthatexecutionoftheprogramis
complete.Thedebuggingsessionisthenendedwithaquit
command.
(gdb)cont
Continuing.
abcxyz
Programexitednormally.
(gdb)cont
Theprogramisnotbeingrun.
(gdb)quit
$
Thegdbdebuggersupportsmanycommandsthataredesigned
tofacilitatedebugging.Typehelpatthe(gdb)prompttogeta
listofthecommandclassesavailableundergdb:
(gdb)help
Listofclassesofcommands:
aliasesAliasesofothercommands
breakpointsMakingprogramstopatcertainpoints
dataExaminingdata
filesSpecifyingandexaminingfiles
internalsMaintenancecommands
obscureObscurefeatures
runningRunningtheprogram
stackExaminingthestack
statusStatusinquiries
supportSupportfacilities
tracepointsTracingofprogramexecutionwithoutstoppingtheprogram
userdefinedUserdefinedcommands
Type"help"followedbyaclassnameforalistofcommandsinthatclass.
Type"help"followedbycommandnameforfulldocumentation.
Commandnameabbreviationsareallowedifunambiguous.
(gdb)
Asexplainedintheinstructionsfollowingthelist,enteringhelp
followedbythenameofacommandclassorcommandname
willdisplayevenmoreinformation.Thefollowinglistingshows
thecommandsintheclassdata:
(gdb)helpdata
Examiningdata.
Listofcommands:
appendAppendtargetcode/datatoalocalfile
callCallafunctionintheprogram
deletedisplayCancelsomeexpressionstobedisplayedwhenprogramstops
deletememDeletememoryregion
disabledisplayDisablesomeexpressionstobedisplayedwhenprogramstops
disablememDisablememoryregion
disassembleDisassembleaspecifiedsectionofmemory
displayPrintvalueofexpressionEXPeachtimetheprogramstops
...
printPrintvalueofexpressionEXP
printobjectAskanObjectiveCobjecttoprintitself
printfPrintf"printfformatstring"
ptypePrintdefinitionoftypeTYPE
restoreRestorethecontentsofFILEtotargetmemory
setEvaluateexpressionEXPandassignresulttovariableVAR
setvariableEvaluateexpressionEXPandassignresulttovariableVAR
undisplayCancelsomeexpressionstobedisplayedwhenprogramstops
whatisPrintdatatypeofexpressionEXP
xExaminememory:x/FMTADDRESS
...
(gdb)
Thefollowingcommandrequestsinformationonthecommand
whatis,whichtakesavariablenameorotherexpressionasan
argument:
(gdb)helpwhatis
PrintdatatypeofexpressionEXP.
GraphicalSymbolicDebuggers
Severalgraphicalinterfacestogdbexist.Forinstance,thexxgdb
graphicalversionofgdbprovidesanumberofwindows,
includingaSourceListingwindow,aCommandwindowthat
containsasetofcommonlyusedcommands,andaDisplay
windowforviewingthevaluesofvariables.Theleftmouse
buttonselectscommandsfromtheCommandwindow.Youcan
clickthedesiredlineintheSourceListingwindowtoseta
breakpoint,andyoucanselectvariablesbyclickingtheminthe
SourceListingwindow.Selectingavariableandclickingprintin
theCommandwindowwilldisplaythevalueofthevariablein
theDisplaywindow.Youcanviewlinesofsourcecodeby
scrolling(andresizing)theSourceListingwindow.
TheGNUddddebugger(www.gnu.org/software/ddd;seeFigure
27-5)alsoprovidesaGUItogdb.Unlikexxgdb,dddcandisplay
complexCstructuresandthelinksbetweenthemingraphical
form.Thisdisplaymakesiteasiertoseeerrorsinthese
structures.Otherwise,thedddinterfaceisverysimilartothatof
xxgdb.
Figure27-5.Theddddebugger
[Viewfullsizeimage]
Unlikexxgdb,ups(ups.sourceforge.net)wasdesignedfromthe
grounduptoworkasagraphicaldebugger;thegraphical
interfacewasnotaddedafterthedebuggerwascomplete.The
resultinginterfaceissimpleyetpowerful.Forexample,ups
automaticallydisplaysthevalueofavariablewhenyouclickit
andprovidesabuilt-inCinterpreterthatallowsyoutoattachC
codetotheprogramyouaredebugging.Becausethisattached
codehasaccesstothevariablesandvaluesintheprogram,you
canuseittoperformsophisticatedchecks,suchasfollowing
anddisplayingthelinksinacomplexdatastructure(page
1028).
Threads
Athreadisasinglesequentialflowofcontrolwithinaprocess.
Threadsarethebasisformultithreadedprograms,inwhich
multipleindependentbutrelatedthreadscooperateto
accomplishalargertask.Threadsarelightweightprocessesthat
reduceschedulingoverheadinseveralways.Themost
significantwayisthatthreadsreducetheneedtoswapinnew
memorysegmentsonacontextswitch,becausethreadsshare
thesamememoryspace.
Multithreadedprogramsgenerallyusereentrantcode(codethat
multiplethreadscanusesimultaneously)andaremostvaluable
whenrunonmultiple-CPUmachines.UnderLinux,
multithreadedservers,suchasNFS,maybeeasiertowriteand
maintainthanmultipleserverprocesses.Whenapplied
judiciously,multithreadingcanalsoserveasalower-overhead
replacementforthetraditionalforkexecidiomforspawning
processes.
FedoraCore5andRedHatEnterpriseLinux5nolongersupport
LinuxThreads(linas.org/linux/threads-faq.html).Insteadthey
supporttheNativePOSIXThreadLibrary(NPTL).NPTL
implementsPOSIXthreadsandimprovesperformanceand
scalabilityoverLinuxThreads.Seetldp.org/FAQ/Threads-FAQ
andpage1012formoreinformationaboutthreads.
Tip:Multiplethreadsarenotalways
better
Ifyouwriteamultithreadedprogramwithnoclear
goalordivisionofeffortforasingle-CPUsystem(for
example,aparallel-serverprocess),theresulting
programwilllikelyrunmoreslowlythana
nonthreadedprogramwouldonthesamesystem.
SystemCalls
TheLinuxkernelhasthreefundamentalresponsibilities:to
controlprocesses,tomanagethefilesystem,andtooperate
peripheraldevices.Asaprogrammeryouhaveaccesstothese
kerneloperationsthroughsystemcallsandlibraryfunctions.
Thissectiondiscussessystemcallsatagenerallevel;adetailed
treatmentisbeyondthescopeofthisbook.
Asthenameimplies,asystemcallinstructsthesystem(kernel)
toperformsomeworkdirectlyonyourbehalf.Therequesttells
thekernelwhatworkneedstobedoneandincludesthe
necessaryarguments.Forexample,asystemcalltoopenafile
includesthenameofthefile.Alibraryroutineislessdirect:It
issuessystemcallsonyourbehalf.Theadvantagesofalibrary
routinearethatitmayinsulateyoufromthelow-leveldetailsof
kerneloperationsandthatithasbeenwrittencarefullytomake
surethatitperformsefficiently.
Forexample,itisstraightforwardtousethestandardI/O
libraryfunctionfprintf()tosendtexttostandardoutputor
standarderror.Withoutthisfunction,youwouldneedtoissue
severalsystemcallstoachievethesameresult.Thecallstothe
libraryroutinesputchar()andgetchar()inFigure27-1on
page834ultimatelyusethewrite()andread()systemcalls
toperformtheI/Ooperations.
strace:TracesSystemCalls
Thestraceutilityisadebuggingtoolthatdisplaysatraceofall
systemcallsmadebyaprocessorprogram.Becauseyoudo
notneedtorecompiletheprogramthatyouwanttotrace,you
canusestraceonbinariesthatyoudonothavesourcefor.
Systemcallsareeventsthattakeplaceattheinterface
(boundary)betweenusercodeandkernelcode.Examiningthis
boundarycanhelpyouisolatebugs,trackdownraceconditions,
andperformsanitychecking.Formoreinformationrefertothe
stracehomepage(www.liacs.nl/~wichert/straceand
sourceforge.net/projects/strace.)
ControllingProcesses
Whenyouenteracommandatashellprompt,theshellprocess
callsthefork()systemcalltocreateacopyofitself(spawna
child)andthenusesanexec()systemcalltooverlaythatcopy
inmemorywithadifferentprogram(thecommandyouaskedit
torun).Table27-3listssystemcallsthataffectprocesses.
Table27-3.Systemcalls:processcontrol
Systemcall Function
fork() Createsacopyofaprocess
exec() Overlaysaprograminmemorywithanotherprogram
getpid() ReturnsthePIDnumberofthecallingprocess
getppid() ReturnsthePIDnumberofthecallingprocess'sparent
process
wait() Causestheparentprocesstowaitforthechildprocess
tofinishrunningbeforeitresumesexecution
exit() Causesaprocesstoexit
nice() Changesthepriorityofaprocess
kill() Sendsasignaltoaprocess
AccessingtheFilesystem
Manyoperationstakeplacewhenaprogramreadsfromor
writestoafile.Becausetheprogramneedstoknowwherethe
fileislocated,thefilenamemustbeconvertedtoaninode
numberonthecorrectfilesystem.Youraccesspermissionsmust
becheckednotonlyforthefileitselfbutalsoforallintervening
directoriesinthepathtothefile.Becausethefileisnotstored
inonecontinuouspieceonthedisk,alldiskblocksthatcontain
piecesofthefilemustbelocated.Theappropriatekerneldevice
drivermustbecalledtocontroltheoperationofthedisk.Once
thefilehasbeenfound,theprogrammayneedtofinda
particularlocationwithinthefileratherthanworkingwithit
sequentiallyfrombeginningtoend.Table27-4listssomeofthe
mostcommonsystemcallsforfilesystemoperations.
Table27-4.Systemcalls:filesystem
Systemcall Function
stat() Getsstatusinformationfromaninode,suchasthe
inodenumber,thedeviceonwhichitislocated,owner
andgroupinformation,andthesizeofthefile
lseek() Movestoapositioninthefile
creat() Createsanewfile
open() Opensanexistingfile
read() Readsafile
write() Writesafile
close() Closesafile
unlink() Unlinksafile(deletesanamereferencetotheinode)
chmod() Changesfileaccesspermissions
chown() Changesfileownership
AccesstoperipheraldevicesonaLinuxsystemishandled
throughthefilesysteminterface.Peripheraldevicesare
representedbyoneormorespecialfiles,usuallylocatedunder
/dev.Whenyoureadfromorwritetooneofthesespecialfiles,
thekernelpassesyourrequesttotheappropriatekerneldevice
driver.Asaresultyoucanusethestandardsystemcallsand
libraryroutinestointeractwiththesedevices;youdonotneed
tolearnanewsetofspecializedfunctions.Thisabilityisoneof
themostpowerfulfeaturesofaLinuxsystembecauseitallows
userstousethesamebasicutilitiesonawiderangeofdevices.
Theavailabilityofstandardsystemcallsandlibraryroutinesis
thekeytotheportabilityofLinuxtools.Forexample,asan
applicationsprogrammer,youcanrelyontheread()and
write()systemcallsworkingthesamewayondifferent
versionsoftheLinuxsystemandondifferenttypesof
computers.Thesystemsprogrammerwhowritesadevicedriver
orportsthekerneltorunonanewcomputer,however,must
understandthedetailsattheirlowestlevel.
SourceCodeManagement
Whenyouworkonaprojectinvolvingmanyfilesthatevolve
overlongperiodsoftime,itcanbedifficulttokeeptrackofthe
differentversionsofthefiles,particularlyifseveralpeopleare
updatingthefiles.Thisproblemcropsupregularlyinlarge
softwaredevelopmentprojects.Sourcecodeanddocumentation
fileschangefrequentlyasyoufixbugs,enhanceprograms,and
releasenewversionsofthesoftware.Thetaskbecomeseven
morecomplexwhenmorethanoneversionofeachfileis
active.Inmanysituationsdevelopersmaybeusingoneversion
ofafilewhileanewerversionisbeingmodified.Inthese
circumstancesyoucaneasilylosetrackoftheversionsand
accidentallyundochangesorduplicateearlierwork.
Tohelpavoidthesekindsofproblems,LinuxincludesCVS
(ConcurrentVersionsSystem;www.nongnu.org/cvs)for
managingandtrackingchangestofiles.AlthoughCVScanbe
usedonanysetoffiles,itismostoftenemployedtomanage
sourcecodeandsoftwaredocumentation.CVSisbasedonRCS
(GNU'sRevisionControlSystem)andisdesignedtocontrolthe
concurrentaccessandmodificationofsourcefilesbymultiple
users.
AgraphicalfrontendtoCVSnamedTkCVS(page872)
simplifiestheuseofCVS,especiallyifyoudonotuseit
frequentlyenoughtomemorizeitsmanycommandsand
options.
CVScontrolswhoisallowedtoupdatefiles.Foreachupdate,
CVSrecordswhomadethechangesandwhythechangeswere
made.BecauseCVSstoresthemostrecentversionofafileand
theinformationneededtore-createallpreviousversions,itis
possibletoregenerateanyversionofafile.
Asetofversionsforseveralfilesmaybegroupedtogetherto
formarelease.Anentirereleasecanbere-createdfromthe
changeinformationstoredwitheachfile.Savingthechanges
forafileratherthansavingacompletecopyofthefilegenerally
conservesalotofdiskspacewellinexcessofthespacerequired
tostoreeachupdateintheCVSfilesthemselves.
ThissectionprovidesanoverviewofCVSandTkCVS.Seethe
CVS-RCS-HOW-TODocumentforLinuxformoreinformation.
CVS:ConcurrentVersionsSystem
CVStreatscollectionsoffilesassingleunits,makingiteasyto
workonlargeprojectsandpermittingmultipleuserstoworkon
thesamefilesimultaneously.CVSalsoprovidesvaluableself-
documentingfeaturesforitsutilities.
BuiltinCVSHelp
CVSusesasingleutility,cvs,forallitsfunctions.Todisplaythe
instructionsforgettinghelp,usethehelpoption:
$cvshelp
Usage:cvs[cvsoptions]command[commandoptionsandarguments]
wherecvsoptionsareq,n,etc.
(specifyhelpoptionsforalistofoptions)
wherecommandisadd,admin,etc.
(specifyhelpcommandsforalistofcommands
orhelpsynonymsforalistofcommandsynonyms)
wherecommandoptionsandargumentsdependonthespecificcommand
(specifyHfollowedbyacommandnameforcommandspecifichelp)
Specifyhelptoreceivethismessage
TheConcurrentVersionsSystem(CVS)isatoolforversioncontrol.
ForCVSupdatesandadditionalinformation,see
theCVShomepageathttp://www.cvshome.org/
Togethelpwithacvscommand,usethehelpoptionfollowed
bythenameofthecommand.Thefollowingexampleshows
helpinformationforthelogcommand:
$cvshelplog
Usage:cvslog[lRhtNb][r[revisions]][ddates][sstates]
[w[logins]][files...]
lLocaldirectoryonly,norecursion.
bOnlylistrevisionsonthedefaultbranch.
hOnlyprintheader.
ROnlyprintnameofRCSfile.
tOnlyprintheaderanddescriptivetext.
NDonotlisttags.
SDonotprintname/headerifnorevisionsselected.d,r,
s,&whavelittleeffectinconjunctionwithb,h,R,and
twithoutthisoption.
r[revisions]Acommaseparatedlistofrevisionstoprint:
rev1:rev2Betweenrev1andrev2,includingrev1andrev2.
rev1::rev2Betweenrev1andrev2,excludingrev1.
rev:revandfollowingrevisionsonthesamebranch.
rev::Afterrevonthesamebranch.
:revrevandpreviousrevisionsonthesamebranch.
::revrevandpreviousrevisionsonthesamebranch.
revJustrev.
branchAllrevisionsonthebranch.
branch.Thelastrevisiononthebranch.
ddatesAsemicolonseparatedlistofdates
(D1<D2forrange,Dforlatestbefore).
sstatesOnlylistrevisionswithspecifiedstates.
w[logins]Onlylistrevisionscheckedinbyspecifiedlogins.
(Specifythehelpglobaloptionforalistofotherhelpoptions)
Optionsforindividualcvscommands(commandoptions)goto
therightoftheindividualcommandnames.Optionstothecvs
utilityitself,suchasthehelpoptiontothelogcommand,goto
theleftofallindividualcommandnames(thatis,theyfollow
thewordcvsonthecommandline).Thetwotypesofoptions
sometimesusethesameletteryetmayhaveanentirely
differentmeaning.
HowCVSStoresRevisionFiles
CVSROOT
WithCVS,revisionfilesarekeptinacommonareacalleda
sourcerepository.TheenvironmentvariableCVSROOTholds
theabsolutepathnameofthisrepository.Thesystem
administratorcantellyouwhatvaluetouseforCVSROOT,or
youcancreateyourownprivaterepositoryandhaveCVSROOT
pointtoit.
Thesourcerepositoryisorganizedasahierarchicalcollectionof
filesanddirectories.CVSdoesnotlimityoutocheckingoutone
fileatatime;youcancheckoutanentiresubdirectory
containingmanyfilestypicallyallthefilesforaparticular
project.AsubdirectoryofCVSROOTthatcanbecheckedoutas
asingleunitiscalledamodule.Severalpeoplecancheckout
andsimultaneouslymodifythefileswithinasinglemodule.
CVSuserstypicallystorethemodulestheyarecurrently
workingoninaspecialdirectory.Ifyouwanttofollowthis
practice,youmustusecdtomakethatspecialdirectorythe
workingdirectorybeforeyoucheckoutamodule.Whenyou
checkoutamodule,CVSreplicatesthemodule'streestructure
intheworkingdirectory.Multipledeveloperscantherefore
checkoutandeditCVSfilessimultaneouslybecausethe
originalsareretainedinthesourcerepository;thefilesinthe
repositoryundergorelativelyinfrequentmodificationina
controlledmanner.
BasicCVSCommands
Althoughmanycvscommandsareavailable,knowledgeofjusta
handfulofcommandsallowsasoftwaredevelopertouseCVS
andtocontributechangestoamodule.Adiscussionofsome
usefulcommandsfollows.Allexamplesassumethatthe
appropriatemoduleshavebeeninstalledintheCVSsource
repository."AddingaModuletotheRepository"(page869)
explainshowtoinstallamodule.
Ofthecommandsdiscussedinthissection,cvscommitisthe
onlyonethatchangesthesourcerepository.Theother
commandsaffectonlythefilesintheworkingdirectory.
Tosimplifyexamplesinthefollowingsections,thepathnameof
theworkingdirectoryisgivenbythevariableCVSWORK;all
modulescanbeassumedtobesubdirectoriesofCVSWORK.
AlthoughthisvariablehasnospecialmeaningtoCVS,youmay
findithelpfultodefinesuchavariableforyourownwork.
CheckingOutFilesfromtheSourceRepository
TocheckoutamodulefromtheCVSsourcerepository,usethe
cvscheckoutcommand.Thefollowingexamplechecksoutthe
Project2module,whichconsistsoffoursourcefiles.Firstuse
cdtomakethedirectoryyouwantthemodulecopiedinto
(CVSWORKinthiscase)theworkingdirectory.Thecvsutility
alwayscopiesintotheworkingdirectory.
$cd$CVSWORK
$ls
Project1
$cvscheckoutProject2
cvscheckout:UpdatingProject2
UProject2/adata.h
UProject2/compute.c
UProject2/randomfile.h
UProject2/shuffle.c
$ls
Project1Project2
$lsProject2
CVSadata.hcompute.crandomfile.hshuffle.c
Thenameofthemodule,Project2,isgivenasanargumentto
cvscheckout.BecausetheProject2directorydoesnot
alreadyexist,cvscreatesitintheworkingdirectoryandplaces
copiesofallsourcefilesfortheProject2moduleintoit:The
nameofthemoduleandthenameofthedirectoryholdingthe
modulearethesame.Thecheckoutcommandpreservesthe
treestructureofthecvsmodule,creatingsubdirectoriesas
needed.
Thesecondlscommandaftercheckoutreveals,inadditionto
thefoursourcefilesforProject2,adirectorynamedCVS.The
CVSsystemusesthisdirectoryforadministrativepurposes;you
donotnormallyaccessit.
Onceyouhaveyourowncopiesofthesourcefiles,youcanedit
themasyouseefit.Youcanchangefileswithinthemodule
evenifotherdevelopersaremodifyingthesamefilesatthe
sametime.
MakingYourChangesAvailabletoOthers
Tocheckinyourchangessothatotheruserscanaccessthem,
youneedtorunthecvscommitcommand.Whenyougivethis
command,cvspromptsyoutoprovideabrieflogmessage
describingthechanges,unlessyouusethemoption.Withthis
option,cvsusesthestringfollowingtheoptionasthelog
message.Thefileorfilesthatyouwanttocommitfollowthe
optionallogmessageonthecommandline:
$cvscommit-m"functionshuffleinserted"compute.c
cvscommit:Up-to-datecheckfailedfor'compute.c'
cvs[commitaborted]:correctaboveerrorsfirst!
Herethecvsutilityreportsanerrorbecausetheversionof
compute.cthatyoumodifiedisnotup-to-date.Thatis,a
newerversionofcompute.chasbeencommittedbysomeone
elsesinceyoulastcheckeditoutofthesourcerepository.After
informingyouoftheproblem,cvsexitswithoutstoringyour
changesinthesourcerepository.
Tomakeyourversionofcompute.ccurrent,youneedtorun
theupdatecommand.Asubsequentcommitwillthensucceed,
andyourchangeswillapplytothelatestrevisioninthesource
repository.
UpdatingYourCopieswithChangesbyOthers
Astheprecedingexampleshows,CVSdoesnotnotifyyouwhen
anotherdeveloperchecksinanewrevisionofafileafteryou
havecheckedoutyourworkingcopy.Youlearnthisfactonly
whenyouattempttocommityourchangestothesource
repository.Toincorporateup-to-daterevisionsofaCVSsource
file,usethecvsupdatecommand:
$cvsupdatecompute.c
RCSfile:/usr/local/src/master/Project2/compute.c,v
retrievingrevision1.9
retrievingrevision1.10
Mergingdifferencesbetween1.9and1.10intocompute.c
Mcompute.c
Herethechangesmadetotheworkingcopyofcompute.c
remainintactbecausetheupdatecommandmergesthelatest
revisioninthesourcerepositorywiththeversionspecifiedon
theupdatecommandline.Theresultofthemergeisnot
alwaysperfect,however.Forthisreason,thecvsupdate
commandinformsyouifitdetectsoverlappingchanges.
AddingNewFilestotheRepository
Youcanusethecvsaddcommandtoschedulenewfilestobe
addedtothesourcerepositoryaspartofthemoduleyouare
workingon.Withthedirectorycontainingthefilesasthe
workingdirectory,givethecvsaddcommand,listingthefiles
youwanttoaddasarguments:
$cd$CVSWORK/Project2
$ls
CVScompute.cshuffle.ctabout2.c
adata.hrandomfile.htabout1.c
$cvsaddtabout[1-2].c
cvsadd:schedulingfile'tabout1.c'foraddition
cvsadd:schedulingfile'tabout2.c'foraddition
cvsadd:use'cvscommit'toaddthesefilespermanently
Thisaddcommandmarksthefilestabout1.candtabout2.c
forentryintotherepository.However,thesefileswillnotbe
availabletootherusersuntilyougiveacommitcommand.This
stagingallowsyoutoprepareseveralfilesbeforeothers
incorporatethechangesintotheirworkingcopieswiththecvs
updatecommand.
RemovingFilesfromtheRepository
Thecvsremovecommandrecordsthefactthatyouwishto
removeafilefromthesourcerepository.Liketheadd
command,itdoesnotaffectthesourcerepository.Todeletea
filefromtherepository,youmustfirstdeleteyourworkingcopy
ofthefile,asthefollowingexampleshows:
$cvsremoveshuffle.c
cvsremove:file'shuffle.c'stillinworkingdirectory
cvsremove:1fileexists;use'rm'toremoveitfirst
$rmshuffle.c
$cvsremoveshuffle.c
cvsremove:scheduling'shuffle.c'forremoval
cvsremove:use'cvscommit'toremovethisfilepermanently
Inthisexample,afterusingrmtodeletetheworkingcopyof
shuffle.c,acvsremovecommandisgiven.Again,youmust
givethecommitcommandbeforethefileisactuallyremoved
fromthesourcerepository.
OtherCVSCommands
Althoughthecommandsdescribedearlieraresufficientformost
workonamodule,youmayfindsomeothercommandstobe
useful.
TaggingaRelease
Youcanapplyacommonlabel,ortag,tothefilesinamodule
astheycurrentlyexist.Onceyouhavetaggedfilesofamodule,
youcanre-createtheminexactlythesameformevenifthey
havebeenmodified,added,ordeletedsincetheyweretagged.
Thisabilityenablesyoutofreezeareleaseyetallows
developmenttocontinueonthenextrelease:
$cvsrtagRelease_1Project1
cvsrtag:TaggingProject1
HeretheProject1modulehasbeentaggedwiththelabel
Release_1.Youcanusethistagwiththecvsexport
commandtoextractthefilesastheyexistedwhentheywere
frozen.
ExtractingaRelease
Thecvsexportcommandletsyouextractfilesastheywere
frozenandtagged:
$cvsexport-rRelease_1-dR1Project1
cvsexport:UpdatingR1
UR1/scm.txt
Thiscommandworkslikethecvscheckoutcommandbutdoes
notcreatetheCVSsupportfiles.Youmustgiveeitherther
optiontoidentifytherelease(asshownabove)oradatewith
theDoption.ThedR1optioninstructscvstoplacethefilesfor
themoduleintothedirectoryR1insteadofusingthemodule
nameasthedirectory.
RemovingWorkingFiles
Whenyouarefinishedmakingchangestothefilesyouhave
checkedoutoftherepository,youmaydecidetoremoveyour
copyofthemodulefromyourworkingdirectory.Onesimple
approachistocdtotheworkingdirectoryandrecursively
removethemodule.Forexample,ifyouwanttoremoveyour
workingcopyofProject2,youcouldgivethefollowing
commands:
$cd$CVSWORK
$rm-rfProject2
Therepositorywillnotbeaffectedbytheremovalofthesefiles.
However,ifyouhadmadechangestothefilesbuthadnotyet
committedthosechanges,thechangeswouldbelostifyou
usedthisapproach.Thecvsreleasecommandishelpfulinthis
situation:
$cd$CVSWORK
$cvsrelease-dProject2
Thereleasecommandalsoremovestheworkingfilesbutfirst
checkseachonetoseewhetherithasbeenmarkedforaddition
intotherepositorybuthasnotyetbeencommitted.Ifthatis
thecase,thereleasecommandwarnsyouandasksyouto
verifyyourintentiontodeletethefile.Youcanfixtheproblem
atthispointifyoulikeandredothereleasecommand.The
releasecommandalsowarnsyouiftherepositoryholdsa
newerversionofthefilethantheonefoundintheworking
directory.Thusyouhavetheopportunitytoupdateandcommit
yourfilebeforedeletingit.(Withoutthedoption,yourworking
fileswillnotbedeletedbutyouwillreceivethesamesequence
ofwarningmessages.)
AddingaModuletotheRepository
ThediscussionofCVStothispointhasassumedthatthe
moduleisalreadypresentintheCVSsourcerepository.Ifyou
wanttoinstalladirectoryhierarchyasanewmoduleinthe
repositoryorupdateanexistingmodulewithanewreleasethat
wasdevelopedelsewhere,gotothedirectorythatholdsthe
filesfortheprojectandrunthecvsimportcommand.The
followingexampleinstallsthefilesforProject1inthesource
repository:
$cvsimport-m"Myfirstproject"Project1ventagreltag
Themoptionallowsyoutoenterabriefdescriptionofthe
moduleonthecommandline.Followingthedescriptionisthe
directoryorthepathnameofthedirectoryunderCVSROOT
thatyouwanttoholdthemodule.Thelasttwofieldsare
symbolicnamesforthevendorbranchandtherelease.
Althoughtheyarenotsignificanthere,theycanbeusefulwhen
releasesofsoftwarearesuppliedbyoutsidesources.
Youcannowusethecvscheckoutcommandtocheckoutthe
Project1module:
$cvscheckoutProject1
CVSAdministration
BeforeyouinstallaCVSrepository,thinkabouthowyouwould
liketoadministerit.Manyinstallationsmaintainasingle
repositoryinwhichseparateprojectsarekeptasseparate
modules.Youmaychoosetohavemorethanonerepository.
TheCVSsystemsupportsasinglerepositorythatisshared
acrossseveralcomputersystemsusingNFS.
InsidearepositoryisamodulenamedCVSROOTthatcontains
administrativefiles(hereCVSROOTisthenameofamodule
andisdifferentfromtheCVSROOTdirectory).Althoughthe
filesinthismodulearenotrequiredtouseCVS,theycan
simplifyaccesstotherepository.
DonotchangeanyfilesintheCVSROOTmodulebyediting
themdirectly.Instead,checkoutthefileyouwanttochange,
editthechecked-outcopy,andthencheckitbackin,justas
youwouldwithfilesinanyothermoduleintherepository.For
example,tocheckoutthemodulesfilefromtheCVSROOT
module,givethefollowingcommand:
$cvscheckoutCVSROOT/modules
ThiscommandcreatesthedirectoryCVSROOTinyourworking
directoryandplacesachecked-outcopyofmodulesinthat
directory.Aftercheckingitout,youcaneditthemodulesfilein
theCVSROOTdirectory:
$cdCVSROOT
$vimmodules
Afteryoueditthemodulesfile,checkitbackintothe
repository:
$cd..
$cvscheckinCVSROOT/modules
OfalltheadministrativefilesintheCVSROOTmodule,the
modulesfileisthemostimportant.Youcanusethisfileto
attachsymbolicnamestomodulesintherepository,allow
accesstosubdirectoriesofamoduleasiftheywerethemselves
modules,andspecifyactionstotakewhencheckingspecific
filesinorout.
Mostrepositoriesstartwithamodulesfilethatallowsyouto
checkoutthemodulesfilewiththefollowingcommand,
insteadoftheoneshownearlier:
$cvscheckoutmodules
WiththeprecedingcommandCVScreatesasubdirectory
namedmoduleswithintheworkingdirectory,insteadofone
namedCVSROOT.Themodulesfileisthencheckedoutinto
thisdirectory.
Thefollowingexampleshowsamodulesfile(thelinesthat
startwith#arecommentlinesand,alongwithblanklines,are
ignoredbyCVS):
#TheCVSmodulesfile
#
#Threedifferentlineformatsarevalid:
#keyaaliases...
#key[options]directory
#key[options]directoryfiles...
#
#Where"options"arecomposedof:
#iprogRun"prog"on"cvscommit"fromtoplevelofmodule.
#oprogRun"prog"on"cvscheckout"ofmodule.
#tprogRun"prog"on"cvsrtag"ofmodule.
#uprogRun"prog"on"cvsupdate"ofmodule.
#ddirPlacemoduleindirectory"dir"insteadofmodulename.
#lTopleveldirectoryonlydonotrecurse.
#
#And"directory"isapathtoadirectoryrelativeto$CVSROOT.
#
#The"a"optionspecifiesanalias.Analiasisinterpretedasif
#everythingontherightofthe"a"hadbeentypedonthecommandline.
#
#
#Youcanencodeamodulewithinamodulebyusingthespecial'&'
#charactertointerposeanothermoduleintothecurrentmodule.This
#canbeusefulforcreatingamodulethatconsistsofmanydirectories
#spreadoutovertheentiresourcerepository.
#Convenientaliases
worlda.
#CVSROOTsupport;runmkmoduleswheneveranythingchanges.
CVSROOTimkmodulesCVSROOT
modulesimkmodulesCVSROOTmodules
loginfoimkmodulesCVSROOTloginfo
commitinfoimkmodulesCVSROOTcommitinfo
rcsinfoimkmodulesCVSROOTrcsinfo
editinfoimkmodulesCVSROOTeditinfo
#Addothermoduleshere...
testgentestgen
testdata1testdata1
testdata2testdata2
testdata3testdata3
testdata4testdata4
testcodetestgen/_code
cvscvs
Thelinesafterthecommentandblanklinesdefinesymbolic
namesformanymodules.Forexample,thefollowingline
definesworldtobeanaliasfortherootoftheCVSrepository:
worlda.
YoucanusesuchnamesinCVScommandsasthenamesof
modules.Forexample,thefollowingcommandchecksoutthe
entirerepository(probablynotagoodidea):
$cvscheckoutworld
Inthesamplemodulesfile,theadministrativefilescontain
definitionsthatattachbothasymbolicnametothefileandan
action(imkmodules)totakewheneachfileischeckedinto
therepository.TheimkmodulesactioncausesCVStorunthe
mkmodulesprogramwhenthefileischeckedin.Thisprogram
ensuresthatacopyofthecheckedinfileexistsinalocation
whereCVScanlocateit.
Followingtheactionisthenameofthesubdirectoryin
CVSROOTthatholdsfilesassociatedwiththesymbolicname.
Anyremainingargumentsonthelinearethenamesofspecific
fileswithinthatdirectory.
ThefollowinglineidentifiesCVSROOTasthenameofthe
moduleinthedirectory$CVSROOT/CVSROOTthatis,forall
theadministrativefilesforCVS:
CVSROOT-imkmodulesCVSROOT
Similarlythefollowinglineassociatesthemodulesmodulewith
themodulesfilewithintheCVSROOTdirectory:
modules-imkmodulesCVSROOTmodules
Nowthefollowingcommandcanfindandcheckoutthe
modulesfile:
$cvscheckoutmodules
Thelastsetoflinesinthesamplemodulesfileassociates
symbolicmodulenameswithdirectoriesandfilesinthe
repository.
UsingTkCVS
Thecvsutilityisusefulenoughthatagraphicalinterface,
TkCVS,hasbeenwrittenforitusingtheTkextensiontotheTcl
programminglanguage(tcl.sourceforge.net).TkCVSispartof
thetkcvspackage.Itprovidesaconvenientpoint-and-click
interfacetoCVS(Figure27-6).Afteryouhavedownloadedand
installedTkCVS(www.twobarleycorns.net/tkcvs.html),youcan
starttheutilitybyusingcdtochangetothedirectoryyouwant
toworkinandthenenteringthefollowingcommand:
$tkcvs&
Figure27-6.TheTkCVSutility
[Viewfullsizeimage]
Alloperationsareavailablethroughthepull-downmenusfound
atthetopofthewindow.Alongthebottomofthewindoware
buttonsforaccessingthemostcommonactions.Adescription
oftheactionboundtoabutton(atooltip,page1060)appears
whenyouallowthemousepointertohoveroverabutton.
Inthemiddleofthewindowisabrowselist.Tomoveintoa
subdirectory,double-clicktheleftmousebuttonwhilethe
mousepointerisonthedirectorynameinthislist.Toeditafile
double-clickthefilename.Toselectmorethanonefile,hold
downtheleftmousebuttonanddragthemousepointeracross
severalnames.Clickingtherightmousebuttonwillmarkall
selectedfiles.Someoftheoperations(suchasviewingthe
revisionlogmessages)willworkonallmarkedfiles.
TheHelppull-downmenuintheupper-rightcornerofthe
windowisanexcellentwaytolearnhowTkCVSworks.For
example,whenyouselecttheHelpmenuitemCVSmodules
file,anexplanationofthelinesthatyoucanaddtotheCVS
modulesfiletobettersupportTkCVSappearsinawindow.If
youchoosenottoaddtheselinestothemodulesfile,some
TkCVScommands,suchasthoseforbrowsingtherepository,
maynotdisplayallavailablemodules.
ChapterSummary
TheoperatingsysteminterfacetoCprogramsandavarietyof
softwaredevelopmenttoolsrendertheLinuxsystemwellsuited
toprogramminginC.TheClibrariesprovidegeneral-purposeC
functionsthatmakeoperatingsystemservicesandother
functionalityavailabletoCprogrammers.ThestandardClibrary
libcisalwaysaccessibletoCprograms,andyoucanspecify
otherlibrariesbyusingtheloptiontothegcccompiler.
YoucanwriteaCprogrambyusingatexteditor,suchasvimor
emacs.Cprogramsalwayshaveafunctionnamedmainand
oftenincludeseveralotherfunctions.Preprocessordirectives
definesymbolicconstantsandmacrosandinstructthe
preprocessortoincludeheaderfiles.
gcc
Whenyouusegcc,itcallstheCpreprocessorfollowedbytheC
compilerandtheassembler.Thecompilercreatesassembly
languagecode,whichtheassemblerusestocreateobject
modules.Thelinkerthencombinestheseobjectmodulesinto
anexecutablefile.YoucanusetheWalloptiontogcctodetect
riskyconstructsonesthatarelegalbutsuggestthepossibilityof
laterproblems.Otheroptionstogcccanhelplocateareasof
yourcodethatmightnotbeportable.
gdb
AlthoughusingprintfstatementsandtheWalloptioncanhelp
inlocatingprogrambugs,itisagoodpracticetocompileC
programsroutinelywiththegoption.Informationthatcanbe
interpretedbygdb,asymbolicdebugger,isthengeneratedas
partoftheexecutablefile.Whenyourunaprogramunderthe
controlofgdb,youcanspecifypointswheregdbshouldpause
theprogramsothatyoucaninquireaboutthevaluesof
variables,displaytheprogramstack,oruseawiderangeof
commandstolearnaboutmanyotheraspectsoftheprogram's
behavior.
make
Themakeutilityusesafilenamedmakefile(orMakefile)that
documentstherelationshipsamongfiles.Itdetermineswhich
modulesofaprogramareout-of-dateandcompilesfilessothat
allmodulesareup-to-date.Thedependencyline,which
specifiestheexactrelationshipsbetweentargetand
prerequisitefiles,isthekeytotheoperationofamakefile.
Followingthedependencylineareconstructioncommandsthat
canbringthetargetup-to-date.Implieddependencies,
constructioncommands,andthemakemacrofacilityare
availabletosimplifythewritingofcomplexmakefiles.
CVS
TheLinuxsystemincludesseveralutilitiesthatassistinkeeping
trackofgroupsoffilesthatundergomultiplerevisions,oftenat
thehandsofmultipledevelopers.Oneofthesesourcecode
managementsystemsisCVS(ConcurrentVersionsSystem).
CVSisbuiltontopofRCSbutprovidesamuchmoreextensive
setofoperationsformanagingdirectoriesoffilesthatmaybe
accessedandmodifiedbymanyusers.Itisagoodchoicefor
managinglarge-scaleprojectsandformaintainingsoftware
releasesthataresenttoandfromothersites.
Exercises
1. WhatfunctiondoeseveryCprogramhave?Whyshouldyousplitlargeprograms
intoseveralfunctions?
2. Whatcommandcouldyougivetocompileprog.candfunc.cintoanexecutable
namedcprog?
3.
ShowtwowaystoinstructtheCpreprocessortoincludetheheaderfile
/usr/include/math.hinyourCprogram.Assumingthatthedeclar.hheaderfile
islocatedinthesubdirectorynamedheadersofyourhomedirectory,describetwo
waystoinstructtheCpreprocessortoincludethisheaderfileinyourCprogram.
4.
Howarethenamesofsystemlibrariesabbreviatedonthegcccommandline?
Wheredoesgccsearchforlibrariesnamedinthismanner?Describehowtospecify
yourownlibraryonthegcccommandline.
5.
Writeamakefilethatreflectsthefollowingrelationships:
a. TheCsourcefilestransactions.candreports.carecompiledtoproducean
executablefilenamedaccts.
b. Bothtransactions.candreports.cincludeaheaderfilenamedaccts.h.
c. Theheaderfileaccts.hiscomposedoftwootherheaderfiles:trans.hand
reps.h.
6. Ifyouretrieveversion4.1ofthefileanswerforeditingandthenattemptto
retrievethesameversionagain,whatwillCVSdo?WhyisCVSsetupthisway?
AdvancedExercises
7.
Modifythebadtabs.cprogram(page851)sothatitexitscleanly(withaspecific
returnvalue).Compiletheprogramandrunitusinggdboranotherdebugger.What
valuesdoesthedebuggerreportwhentheprogramfinishesexecuting?
8.
Forthemakefile
$catMakefile
leads:menu.ousers.oresellers.oprospects.o
gccoleadsmenu.ousers.oresellers.oprospects.o
menu.o:menu.hdialog.hinquiry.h
users.o:menu.hdialog.h
prospects.o:dialog.h
identify:
a. Targets.
b. Constructioncommands.
c. Prerequisites.
9.
RefertoMakefileinexercise8toanswerthefollowingquestions:
a. Ifthetargetleadsisup-to-dateandyouthenchangeusers.c,what
happenswhenyourunmakeagain?Bespecific.
b. Rewritethemakefiletoincludethefollowingmacros:
OBJECTS=menu.ousers.oresellers.oprospects.o
HFILES=menu.hdialog.h
10.
Reviewthemakeinfopagetoanswerthefollowingquestions:
a. Whatdoesthetoptiondo?
b. IfyouhavefilesnamedmakefileandMakefileintheworkingdirectory,
howcanyouinstructmaketouseMakefile?
c. Givetwowaystodefineavariablesothatyoucanuseitinsideamakefile.
11.
Refertothemakefileforcomputeonpage846.
a. Supposethatafileintheworkingdirectoryisnamedclean.Whatisthe
effectofgivingthefollowingcommand?Explain.
$makeclean
b. Thediscussiononpage844statesthatthefollowingcommandisnot
normallyseeninmakefiles:
catnum.htable.h>form.h
Whatistheeffectofremovingthisconstructioncommandfromthemakefile
whileretainingthedependencyline?
c. Theprecedingconstructioncommandworksonlybecausethefileform.his
madeupofnum.handtable.h.Moreoften#includedirectivesinthetarget
definethedependencies.Suggestamoregeneraltechniquethatupdates
form.hwhenevernum.hortable.hhasamorerecentmodificationdate.
28.ProgrammingtheBourneAgainShell
INTHISCHAPTER
ControlStructures 878
FileDescriptors 911
ParametersandVariables 914
ArrayVariables 914
LocalityofVariables 916
SpecialParameters 918
PositionalParameters 920
BuiltinCommands 926
Expressions 940
ShellPrograms 948
ARecursiveShellScript 949
ThequizShellScript 952
Chapter7introducedtheshellsandChapter9wentintodetail
abouttheBourneAgainShell.Thischapterintroducesadditional
BourneAgainShellcommands,builtins,andconceptsthatcarry
shellprogrammingtoapointwhereitcanbeuseful.Thefirst
partofthischaptercoversprogrammingcontrolstructures,
whicharealsoknownascontrolflowconstructs.These
structuresallowyoutowritescriptsthatcanloopover
commandlinearguments,makedecisionsbasedonthevalueof
avariable,setupmenus,andmore.TheBourneAgainShell
usesthesameconstructsfoundinsuchhigh-levelprogramming
languagesasC.
Thenextpartofthischapterdiscussesparametersand
variables,goingintodetailaboutarrayvariables,localversus
globalvariables,specialparameters,andpositionalparameters.
Theexplorationofbuiltincommandscoverstype,whichdisplays
informationaboutacommand,andread,whichallowsyouto
acceptuserinputinashellscript.Thesectionontheexecbuiltin
demonstrateshowexecprovidesanefficientwaytoexecutea
commandbyreplacingaprocessandexplainshowyoucanuse
ittoredirectinputandoutputfromwithinascript.Thenext
sectioncoversthetrapbuiltin,whichprovidesawaytodetect
andrespondtooperatingsystemsignals(suchasthatwhichis
generatedwhenyoupressCONTROL-C).Thediscussionof
builtinsconcludeswithadiscussionofkill,whichcanaborta
process,andgetopts,whichmakesiteasytoparseoptionsfora
shellscript.(Table28-6onpage939listssomeofthemore
commonlyusedbuiltins.)
Nextthechapterexaminesarithmeticandlogicalexpressions
andtheoperatorsthatworkwiththem.Thefinalsectionwalks
throughthedesignandimplementationoftwomajorshell
scripts.
Thischaptercontainsmanyexamplesofshellprograms.
Althoughtheyillustratecertainconcepts,mostuseinformation
fromearlierexamplesaswell.Thisoverlapnotonlyreinforces
youroverallknowledgeofshellprogrammingbutalso
demonstrateshowyoucancombinecommandstosolve
complextasks.Running,modifying,andexperimentingwiththe
examplesinthisbookisagoodwaytobecomecomfortable
withtheunderlyingconcepts.
Tip:Donotnameashellscripttest
Youcanunwittinglycreateaproblemifyougivea
shellscriptthenametestbecauseaLinuxutilityhas
thesamename.DependingonhowthePATH
variableissetupandhowyoucalltheprogram,you
mayrunyourscriptortheutility,leadingto
confusingresults.
Thischapterillustratesconceptswithsimpleexamples,which
arefollowedbymorecomplexonesinsectionsmarked
"Optional."Themorecomplexscriptsillustratetraditionalshell
programmingpracticesandintroducesomeLinuxutilitiesoften
usedinscripts.Youcanskipthesesectionswithoutlossof
continuitythefirsttimeyoureadthechapter.Returntothem
laterwhenyoufeelcomfortablewiththebasicconcepts.
ControlStructures
Thecontrolflowcommandsaltertheorderofexecutionof
commandswithinashellscript.Controlstructuresincludethe
if...then,for...in,while,until,andcasestatements.In
addition,thebreakandcontinuestatementsworkin
conjunctionwiththecontrolstructurestoaltertheorderof
executionofcommandswithinascript.
if...then
Theif...thencontrolstructurehasthefollowingsyntax:
iftest-command
then
commands
fi
Theboldwordsinthesyntaxdescriptionaretheitemsyou
supplytocausethestructuretohavethedesiredeffect.The
nonboldwordsarethekeywordstheshellusestoidentifythe
controlstructure.
testbuiltin
Figure28-1showsthattheifstatementteststhestatus
returnedbythetest-commandandtransferscontrolbasedon
thisstatus.Theendoftheifstructureismarkedbyafi
statement,(ifspelledbackward).Thefollowingscriptprompts
fortwowords,readsthem,andthenusesanifstructureto
executecommandsbasedontheresultreturnedbythetest
builtinwhenitcomparesthetwowords.(Seethetestinfopage
forinformationonthetestutility,whichissimilartothetest
builtin.)Thetestbuiltinreturnsastatusoftrueifthetwowords
arethesameandfalseiftheyarenot.Doublequotationmarks
around$word1and$word2makesurethattestworks
properlyifyouenterastringthatcontainsaSPACEorother
specialcharacter:
$catif1
echo-n"word1:"
readword1
echo-n"word2:"
readword2
iftest"$word1"="$word2"
then
echo"Match"
fi
echo"Endofprogram."
$if1
word1:peach
word2:peach
Match
Endofprogram.
Figure28-1.Anif...thenflowchart
Intheprecedingexamplethetest-commandistest
"$word1"="$word2".Thetestbuiltinreturnsatruestatusif
itsfirstandthirdargumentshavetherelationshipspecifiedby
itssecondargument.Ifthiscommandreturnsatruestatus(=
0),theshellexecutesthecommandsbetweenthethenandfi
statements.Ifthecommandreturnsafalsestatus(not=0),
theshellpassescontroltothestatementfollowingfiwithout
executingthestatementsbetweenthenandfi.Theeffectof
thisifstatementistodisplayMatchifthetwowordsarethe
same.ThescriptalwaysdisplaysEndofprogram.
Builtins
IntheBourneAgainShell,testisabuiltinpartoftheshell.Itis
alsoastand-aloneutilitykeptin/usr/bin/test.Thischapter
discussesanddemonstratesmanyBourneAgainShellbuiltins.
Youusuallyusethebuiltinversionifitisavailableandtheutility
ifitisnot.Eachversionofacommandmayvaryslightlyfrom
oneshelltothenextandfromtheutilitytoanyoftheshell
builtins.Seepage926formoreinformationonshellbuiltins.
Checkingarguments
Thenextprogramusesanifstructureatthebeginningofa
scripttocheckthatyouhavesuppliedatleastoneargumenton
thecommandline.Theeqtestoperatorcomparestwointegers,
wherethe$#specialparameter(page921)takesonthevalue
ofthenumberofcommandlinearguments.Thisstructure
displaysamessageandexitsfromthescriptwithanexitstatus
of1ifyoudonotsupplyatleastoneargument:
$catchkargs
iftest$#-eq0
then
echo"Youmustsupplyatleastoneargument."
exit1
fi
echo"Programrunning."
$chkargs
Youmustsupplyatleastoneargument.
$chkargsabc
Programrunning.
Atestliketheoneshowninchkargsisakeycomponentofany
scriptthatrequiresarguments.Topreventtheuserfrom
receivingmeaninglessorconfusinginformationfromthescript,
thescriptneedstocheckwhethertheuserhassuppliedthe
appropriatearguments.Sometimesthescriptsimplytests
whetherargumentsexist(asinchkargs).Otherscriptstestfor
aspecificnumberorspecifickindsofarguments.
Youcanusetesttoaskaquestionaboutthestatusofafile
argumentortherelationshipbetweentwofilearguments.After
verifyingthatatleastoneargumenthasbeengivenonthe
commandline,thefollowingscripttestswhethertheargument
isthenameofanordinaryfile(notadirectoryorothertypeof
file)intheworkingdirectory.Thetestbuiltinwiththefoption
andthefirstcommandlineargument($1)checkthefile:
$catis_ordfile
iftest$#-eq0
then
echo"Youmustsupplyatleastoneargument."
exit1
fi
iftest-f"$1"
then
echo"$1isanordinaryfileintheworkingdirectory"
else
echo"$1isNOTanordinaryfileintheworkingdirectory"
fi
Youcantestmanyothercharacteristicsofafilewithtestand
variousoptions.Table28-1listssomeoftheseoptions.
Table28-1.Optionstothetestbuiltin
Option Testsfiletoseeifit
dExistsandisadirectoryfile
eExists
fExistsandisanordinaryfile(notadirectory)
rExistsandisreadable
sExistsandhasasizegreaterthan0bytes
wExistsandiswritable
xExistsandisexecutable
Othertestoptionsprovidewaystotestrelationshipsbetween
twofiles,suchaswhetheronefileisnewerthananother.Refer
tolaterexamplesinthischapterformoredetailedinformation.
Tip:Alwaystestthearguments
Tokeeptheexamplesinthisbookshortandfocused
onspecificconcepts,thecodetoverifyargumentsis
oftenomittedorabbreviated.Itisagoodpracticeto
testargumentsinshellprogramsthatotherpeople
willuse.Doingsoresultsinscriptsthatareeasierto
runanddebug.
[]isasynonymfortest
Thefollowingexampleanotherversionofchkargschecksfor
argumentsinawaythatismoretraditionalforLinuxshell
scripts.Theexampleusesthebracket([])synonymfortest.
Ratherthanusingthewordtestinscripts,youcansurroundthe
argumentstotestwithbrackets.Thebracketsmustbe
surroundedbywhitespace(SPACEsorTABs).
$catchkargs2
if[$#-eq0]
then
echo"Usage:chkargs2argument..."1>&2
exit1
fi
echo"Programrunning."
exit0
$chkargs2
Usage:chkargs2arguments
$chkargs2abc
Programrunning.
Usagemessage
Theerrormessagethatchkargs2displaysiscalledausage
messageandusesthe1>&2notationtoredirectitsoutputto
standarderror(page270).Afterissuingtheusagemessage,
chkargs2exitswithanexitstatusof1,indicatingthatanerror
hasoccurred.Theexit0commandattheendofthescript
causeschkargs2toexitwitha0statusaftertheprogramruns
withoutanerror.TheBourneAgainShellreturnsa0statusif
youomitthestatuscode.
Theusagemessageiscommonlyemployedtospecifythetype
andnumberofargumentsthescripttakes.ManyLinuxutilities
provideusagemessagessimilartotheoneinchkargs2.Ifyou
callautilityorotherprogramwiththewrongnumberorkindof
arguments,youwilloftenseeausagemessage.Followingisthe
usagemessagethatcpdisplayswhenyoucallitwithoutany
arguments:
$cp
cp:missingfileargument
Try'cp--help'formoreinformation.
if...then...else
Theintroductionofanelsestatementturnstheifstructureinto
thetwo-waybranchshowninFigure28-2.Theif...then...else
controlstructurehasthefollowingsyntax:
iftest-command
then
commands
else
commands
fi
Figure28-2.Anif...then...elseflowchart
Becauseasemicolon(;)endsacommandjustasaNEWLINE
does,youcanplacethenonthesamelineasifbyprecedingit
withasemicolon.(Becauseifandthenareseparatebuiltins,
theyrequireacommandseparatorbetweenthem;asemicolon
andNEWLINEworkequallywell.)Somepeoplepreferthis
notationforaestheticreasons,whileotherslikeitbecauseit
savesspace:
iftest-command;then
commands
else
commands
fi
Ifthetest-commandreturnsatruestatus,theifstructure
executesthecommandsbetweenthethenandelsestatements
andthendivertscontroltothestatementfollowingfi.Ifthe
test-commandreturnsafalsestatus,theifstructureexecutes
thecommandsfollowingtheelsestatement.
Whenyourunthenextscript,namedout,withargumentsthat
arefilenames,itdisplaysthefilesontheterminal.Ifthefirst
argumentisv(calledanoptioninthiscase),outusesless
(page128)todisplaythefilesonepageatatime.After
determiningthatitwascalledwithatleastoneargument,out
testsitsfirstargumenttoseewhetheritisv.Iftheresultofthe
testistrue(ifthefirstargumentisv),outusestheshiftbuiltin
toshifttheargumentstogetridofthevanddisplaysthefiles
usingless.Iftheresultofthetestisfalse(ifthefirstargument
isnotv),thescriptusescattodisplaythefiles:
$catout
if[$#-eq0]
then
echo"Usage:out[-v]filenames..."1>&2
exit1
fi
if["$1"="-v"]
then
shift
less--"$@"
else
cat--"$@"
fi
Optional
Inouttheargumenttocatandlesstellstheseutilitiesthatnomoreoptionsfollow
onthecommandlineandnottoconsiderleadinghyphens()inthefollowinglist
asindicatingoptions.Thusallowsyoutoviewafilewithanamethatstartswith
ahyphen.Althoughnotcommon,filenamesbeginningwithahyphendo
occasionallyoccur.(Youcancreatesuchafilebyusingthecommandcat>
fname.)TheargumentworkswithallLinuxutilitiesthatusethegetoptsbuiltin
(page936)toparsetheiroptions;itdoesnotworkwithmoreandafewother
utilities.Thisargumentisparticularlyusefulwhenusedinconjunctionwithrmto
removeafilewhosenamestartswithahyphen(rmfname),includinganythat
youcreatewhileexperimentingwiththeargument.
if...then...elif
Theif...then...elifcontrolstructure(Figure28-3)hasthe
followingsyntax:
iftest-command
then
commands
eliftest-command
then
commands
...
else
commands
fi
Figure28-3.Anif...then...elifflowchart
Theelifstatementcombinestheelsestatementandtheif
statementandallowsyoutoconstructanestedsetof
if...then...elsestructures(Figure28-3).Thedifference
betweentheelsestatementandtheelifstatementisthateach
elsestatementmustbepairedwithafistatement,whereas
multiplenestedelifstatementsrequireonlyasingleclosingfi
statement.
Thefollowingexampleshowsanif...then...elifcontrol
structure.Thisshellscriptcomparesthreewordsthattheuser
enters.ThefirstifstatementusestheBooleanoperatorAND
(a)asanargumenttotest.Thetestbuiltinreturnsatruestatus
onlyifthefirstandsecondlogicalcomparisonsaretrue(thatis,
ifword1matchesword2andword2matchesword3).Iftest
returnsatruestatus,thescriptexecutesthecommand
followingthenextthenstatement,passescontroltothe
statementfollowingfi,andterminates:
$catif3
echo-n"word1:"
readword1
echo-n"word2:"
readword2
echo-n"word3:"
readword3
if["$word1"="$word2"-a"$word2"="$word3"]
then
echo"Match:words1,2,&3"
elif["$word1"="$word2"]
then
echo"Match:words1&2"
elif["$word1"="$word3"]
then
echo"Match:words1&3"
elif["$word2"="$word3"]
then
echo"Match:words2&3"
else
echo"Nomatch"
fi
$if3
word1:apple
word2:orange
word3:pear
Nomatch
$if3
word1:apple
word2:orange
word3:apple
Match:words1&3
$if3
word1:apple
word2:apple
word3:apple
Match:words1,2,&3
Ifthethreewordsarenotthesame,thestructurepasses
controltothefirstelif,whichbeginsaseriesofteststoseeif
anypairofwordsisthesame.Asthenestingcontinues,ifany
oneoftheifstatementsissatisfied,thestructurepasses
controltothenextthenstatementandsubsequentlytothe
statementfollowingfi.Eachtimeanelifstatementisnot
satisfied,thestructurepassescontroltothenextelif
statement.Thedoublequotationmarksaroundthearguments
toechothatcontainampersands(&)preventtheshellfrom
interpretingtheampersandsasspecialcharacters.
Optional:ThelnksScript
Thefollowingscript,namedlnks,demonstratestheif...thenandif...then...elif
controlstructures.Thisscriptfindshardlinkstoitsfirstargument,afilename.If
youprovidethenameofadirectoryasthesecondargument,lnkssearchesfor
linksinthatdirectoryandallsubdirectories.Ifyoudonotspecifyadirectory,
lnkssearchestheworkingdirectoryanditssubdirectories.Thisscriptdoesnot
locatesymboliclinks.
$catlnks
#!/bin/bash
#Identifylinkstoafile
#Usage:lnksfile[directory]
if[$#-eq0-o$#-gt2];then
echo"Usage:lnksfile[directory]"1>&2
exit1
fi
if[-d"$1"];then
echo"Firstargumentcannotbeadirectory."1>&2
echo"Usage:lnksfile[directory]"1>&2
exit1
else
file="$1"
fi
if[$#-eq1];then
directory="."
elif[-d"$2"];then
directory="$2"
else
echo"Optionalsecondargumentmustbeadirectory."1>&2
echo"Usage:lnksfile[directory]"1>&2
exit1
fi
#Checkthatfileexistsandisanordinaryfile:
if[!-f"$file"];then
echo"lnks:$filenotfoundorspecialfile"1>&2
exit1
fi
#Checklinkcountonfile
set--$(ls-l"$file")
linkcnt=$2
if["$linkcnt"-eq1];then
echo"lnks:nootherhardlinksto$file"1>&2
exit0
fi
#Gettheinodeofthegivenfile
set$(ls-i"$file")
inode=$1
#Findandprintthefileswiththatinodenumber
echo"lnks:usingfindtosearchforlinks..."1>&2
find"$directory"-xdev-inum$inode-print
Alexhasafilenamedletterinhishomedirectory.Hewantstofindlinkstothis
fileinhisandotherusers'homedirectoryfiletrees.Inthefollowingexample,
Alexcallslnksfromhishomedirectorytoperformthesearch.Thesecond
argumenttolnks,/home,isthepathnameofthedirectoryhewantstostart
thesearchin.Thelnksscriptreportsthat/home/alex/letterand
/home/jenny/draftarelinkstothesamefile:
$lnksletter/home
lnks:usingfindtosearchforlinks...
/home/alex/letter
/home/jenny/draft
Inadditiontotheif...then...elifcontrolstructure,lnksintroducesother
featuresthatarecommonlyusedinshellprograms.Thefollowingdiscussion
describeslnkssectionbysection.
Specifytheshell
Thefirstlineofthelnksscriptuses#!(page274)tospecify
theshellthatwillexecutethescript:
#!/bin/bash
Inthischapterthe#!notationappearsonlyinmorecomplex
examples.Itensuresthatthepropershellexecutesthescript,
evenwhentheuserisrunningadifferentshellorthescriptis
calledfromanothershellscript.
Comments
Thesecondandthirdlinesoflnksarecomments;theshell
ignoresthetextthatfollowsapoundsignuptothenext
NEWLINEcharacter.Thesecommentsinlnksbrieflyidentify
whatthefiledoesandhowtouseit:
#Identifylinkstoafile
#Usage:lnksfile[directory]
Usagemessages
Thefirstifstatementtestswhetherlnkswascalledwithzero
argumentsormorethantwoarguments:
if[$#-eq0-o$#-gt2];then
echo"Usage:lnksfile[directory]"1>&2
exit1
fi
Ifeitheroftheseconditionsistrue,lnkssendsausage
messagetostandarderrorandexitswithastatusof1.The
doublequotationmarksaroundtheusagemessagepreventthe
shellfrominterpretingthebracketsasspecialcharacters.The
bracketsintheusagemessageindicatethatthedirectory
argumentisoptional.
Thesecondifstatementtestswhetherthefirstcommandline
argument($1)isadirectory(thedargumenttotestreturnsa
truevalueifthefileexistsandisadirectory):
if[-d"$1"];then
echo"Firstargumentcannotbeadirectory."1>&2
echo"Usage:lnksfile[directory]"1>&2
exit1
else
file="$1"
fi
Ifthefirstargumentisadirectory,lnksdisplaysausage
messageandexits.Ifitisnotadirectory,lnkssavesthevalue
of$1inthefilevariablebecauselaterinthescriptsetresets
thecommandlinearguments.Ifthevalueof$1isnotsaved
beforethesetcommandisissued,itsvaluewillbelost.
Testthearguments
Thenextsectionoflnksisanif...then...elifstatement:
if[$#-eq1];then
directory="."
elif[-d"$2"];then
directory="$2"
else
echo"Optionalsecondargumentmustbeadirectory."1>&2
echo"Usage:lnksfile[directory]"1>&2
exit1
fi
Thefirsttest-commanddetermineswhethertheuserspecified
asingleargumentonthecommandline.Ifthetest-command
returns0(true),theuser-createdvariablenameddirectoryis
assignedthevalueoftheworkingdirectory(.).Ifthetest-
commandreturnsfalse,theelifstatementtestswhetherthe
secondargumentisadirectory.Ifitisadirectory,the
directoryvariableissetequaltothesecondcommandline
argument,$2.If$2isnotadirectory,lnkssendsausage
messagetostandarderrorandexitswithastatusof1.
Thenextifstatementinlnkstestswhether$filedoesnot
exist.Thistestkeepslnksfromwastingtimelookingforlinks
toanonexistentfile.
Thetestbuiltinwiththethreearguments!,f,and$file
evaluatestotrueifthefile$filedoesnotexist:
[!-f"$file"]
The!operatorprecedingthefargumenttotestnegatesits
result,yieldingfalseifthefile$filedoesexistandisan
ordinaryfile.
Nextlnksusessetandlsltocheckthenumberoflinks$file
has:
#Checklinkcountonfile
set--$(ls-l"$file")
linkcnt=$2
if["$linkcnt"-eq1];then
echo"lnks:nootherhardlinksto$file"1>&2
exit0
fi
Thesetbuiltinusescommandsubstitution(page334)tosetthe
positionalparameterstotheoutputoflsl.Thesecondfieldin
thisoutputisthelinkcount,sotheuser-createdvariable
linkcntissetequalto$2.Theusedwithsetpreventssetfrom
interpretingasanoptionthefirstargumentproducedbylsl
(thefirstargumentistheaccesspermissionsforthefileand
typicallybeginswith).Theifstatementcheckswhether
$linkcntisequalto1;ifitis,lnksdisplaysamessageand
exits.Althoughthismessageisnottrulyanerrormessage,itis
redirectedtostandarderror.Thewaylnkshasbeenwritten,all
informationalmessagesaresenttostandarderror.Onlythe
finalproductoflnksthepathnamesoflinkstothespecifiedfileis
senttostandardoutput,soyoucanredirecttheoutputasyou
please.
Ifthelinkcountisgreaterthanone,lnksgoesontoidentify
theinode(page1037)for$file.Asexplainedonpage193,
comparingtheinodesassociatedwithfilenamesisagoodway
todeterminewhetherthefilenamesarelinkstothesamefile.
Thelnksscriptusessettosetthepositionalparameterstothe
outputoflsi.Thefirstargumenttosetistheinodenumberfor
thefile,sotheuser-createdvariablenamedinodeisassigned
thevalueof$1:
#Gettheinodeofthegivenfile
set$(ls-i"$file")
inode=$1
Finallylnksusesthefindutilitytosearchforfileshavinginode
numbersthatmatch$inode:
#Findandprintthefileswiththatinodenumber
echo"lnks:usingfindtosearchforlinks..."1>&2
find"$directory"-xdev-inum$inode-print
Thefindutilitysearchesforfilesthatmeetthecriteriaspecified
byitsarguments,beginningitssearchwiththedirectory
specifiedbyitsfirstargument($directory)andsearchingall
subdirectories.Theremainingargumentsspecifythatthe
filenamesoffileshavinginodesmatching$inodeshouldbe
senttostandardoutput.Becausefilesindifferentfilesystems
canhavethesameinodenumberandnotbelinked,findmust
searchonlydirectoriesinthesamefilesystemas$directory.
Thexdevargumentpreventsfindfromsearchingdirectorieson
otherfilesystems.Refertopage190formoreinformationabout
filesystemsandlinks.
Theechocommandprecedingthefindcommandinlnks,which
tellstheuserthatfindisrunning,isincludedbecausefind
frequentlytakesalongtimetorun.Becauselnksdoesnot
includeafinalexitstatement,theexitstatusoflnksisthatof
thelastcommanditruns,find.
DebuggingShellScripts
Whenyouarewritingascriptsuchaslnks,itiseasytomake
mistakes.Youcanusetheshell'sxoptiontohelpdebuga
script.Thisoptioncausestheshelltodisplayeachcommand
beforeitrunsthecommand.Tracingascript'sexecutioninthis
waycangiveyouinformationaboutwhereaproblemlies.
Youcanrunlnksasinthepreviousexampleandcausethe
shelltodisplayeachcommandbeforeitisexecuted.Eitherset
thexoptionforthecurrentshell(setx)sothatallscripts
displaycommandsastheyarerunorusethexoptiontoaffect
onlytheshellthatisrunningthescriptcalledbythecommand
line.
$bash-xlnksletter/home
+'['2-eq0-o2-gt2']'
+'['-dletter']'
+file=letter
+'['2-eq1']'
+'['-d/home']'
+directory=/home
+'[''!'-fletter']'
...
PS4
Eachcommandthatthescriptexecutesisprecededbythe
valueofthePS4variableaplussign(+)bydefault,soyoucan
distinguishdebuggingoutputfromscript-producedoutput.You
mustexportPS4ifyousetitintheshellthatcallsthescript.
ThenextcommandsetsPS4to>>>>followedbyaSPACEand
exportsit:
$exportPS4='>>>>'
Youcanalsosetthexoptionoftheshellrunningthescriptby
puttingthefollowingsetcommandatthetopofthescript:
set-x
Putsetxanywhereinthescriptyouwanttoturndebugging
on.Turnthedebuggingoptionoffwithaplussign.
set+x
Thesetoxtraceandset+oxtracecommandsdothesame
thingsassetxandset+x,respectively.
for...in
Thefor...incontrolstructurehasthefollowingsyntax:
forloop-indexinargument-list
do
commands
done
Thefor...instructure(Figure28-4)assignsthevalueofthe
firstargumentintheargument-listtotheloop-indexand
executesthecommandsbetweenthedoanddone
statements.Thedoanddonestatementsmarkthebeginning
andendoftheforloop.
Figure28-4.Afor...inflowchart
Afteritpassescontroltothedonestatement,thestructure
assignsthevalueofthesecondargumentintheargument-list
totheloop-indexandrepeatsthecommands.Thestructure
repeatsthecommandsbetweenthedoanddonestatements
onetimeforeachargumentintheargument-list.Whenthe
structureexhauststheargument-list,itpassescontroltothe
statementfollowingdone.
Thefollowingfor...instructureassignsapplestotheuser-
createdvariablefruitandthendisplaysthevalueoffruit,
whichisapples.Nextthestructureassignsorangestofruit
andrepeatstheprocess.Whenitexhauststheargumentlist,
thestructuretransferscontroltothestatementfollowingdone,
whichdisplaysamessage.
$catfruit
forfruitinapplesorangespearsbananas
do
echo"$fruit"
done
echo"Taskcomplete."
$fruit
apples
oranges
pears
bananas
Taskcomplete.
Thenextscriptliststhenamesofthedirectoryfilesinthe
workingdirectorybyloopingoverallthefiles,usingtestto
determinewhichfilesaredirectories:
$catdirfiles
foriin*
do
if[-d"$i"]
then
echo"$i"
fi
done
Theambiguousfilereferencecharacter*matchesthenamesof
allfiles(excepthiddenfiles)intheworkingdirectory.Priorto
executingtheforloop,theshellexpandsthe*andusesthe
resultinglisttoassignsuccessivevaluestotheindexvariablei.
for
Theforcontrolstructurehasthefollowingsyntax:
forloop-index
do
commands
done
Intheforstructuretheloop-indextakesonthevalueofeach
ofthecommandlinearguments,oneatatime.Itisthesame
asthefor...instructure(Figure28-4)exceptforwhereitgets
valuesfortheloop-index.Theforstructureperformsa
sequenceofcommands,usuallyinvolvingeachargumentin
turn.
Thefollowingshellscriptshowsaforstructuredisplayingeach
commandlineargument.Thefirstlineofthescript,forarg,
impliesforargin"$@",wheretheshellexpands"$@"intoa
listofquotedcommandlinearguments"$1""$2""$3"andso
on.Thebalanceofthescriptcorrespondstothefor...in
structure.
$catfor_test
forarg
do
echo"$arg"
done
$for_testcandygumchocolate
candy
gum
chocolate
Optional:ThewhosScript
Thefollowingscript,namedwhos,demonstratestheusefulnessoftheimplied
"$@"intheforstructure.Yougivewhosoneormoreusers'fullnamesor
usernamesasarguments,andwhosdisplaysinformationabouttheusers.The
whosscriptgetstheinformationitdisplaysfromthefirstandfifthfieldsinthe
/etc/passwdfile.Thefirstfieldalwayscontainsausername,andthefifthfield
typicallycontainstheuser'sfullname.Youcanprovideausernameasan
argumenttowhostoidentifytheuser'snameorprovideanameasan
argumenttoidentifytheusername.Thewhosscriptissimilartothefingerutility,
althoughwhosdeliverslessinformation.
$catwhos
#!/bin/bash
#adaptedfromfinger.shbyLeeSailer
#UNIX/WORLD,III:11,p.67,Fig.2
if[$#-eq0]
then
echo"Usage:whosid..."1>&2
exit1
fi
forid
do
gawk-F:'{print$1,$5}'/etc/passwd|
grep-i"$id"
done
Belowwhosidentifiestheuserwhoseusernameischasandtheuserwhose
nameisMarilouSmith:
$whoschas"MarilouSmith"
chasCharlesCasey
msmithMarilouSmith
Useof"$@"
Thewhosscriptusesaforstatementtoloopthroughthe
commandlinearguments.Inthisscripttheimplieduseof"$@"
intheforloopisparticularlybeneficialbecauseitcausesthe
forlooptotreatanargumentthatcontainsaSPACEasasingle
argument.ThisexamplequotesMarilouSmith,whichcauses
theshelltopassittothescriptasasingleargument.Thenthe
implied"$@"intheforstatementcausestheshellto
regeneratethequotedargumentMarilouSmithsothatitis
againtreatedasasingleargument.
gawk
Foreachcommandlineargument,whossearchesthe
/etc/passwdfile.Insidetheforloopthegawkutilityextracts
thefirst($1)andfifth($5)fieldsfromthelinesin
/etc/passwd.TheF:optioncausesgawktouseacolon(:)as
afieldseparatorwhenitreads/etc/passwd,allowingitto
breakeachlineintofields.Thegawkcommandsetsandusesthe
$1and$5arguments;theyareincludedwithinsinglequotation
marksandarenotinterpretedbytheshell.Donotconfuse
theseargumentswithpositionalparameters,whichcorrespond
tocommandlinearguments.Thefirstandfifthfieldsaresentto
grep(page131)viaapipe.Thegreputilitysearchesfor$id
(whichhastakenonthevalueofacommandlineargument)in
itsinput.Theioptioncausesgreptoignorecaseasitsearches;
grepdisplayseachlineinitsinputthatcontains$id.
|attheendofaline
Aninterestingsyntacticalexceptionthatbashgivesthepipe
symbol(|)appearsonthelinewiththegawkcommand:Youdo
nothavetoquoteaNEWLINEthatimmediatelyfollowsapipe
symbol(thatis,apipesymbolthatisthelastthingonaline)to
keeptheNEWLINEfromexecutingacommand.Trygivingthe
commandwho|andpressingRETURN.Theshelldisplaysa
secondaryprompt.Ifyouthenentersortfollowedbyanother
RETURN,youseeasortedwholist.Thepipeworkseventhough
aNEWLINEfollowsthepipesymbol.
while
Thewhilecontrolstructurehasthefollowingsyntax:
whiletest-command
do
commands
done
Aslongasthetest-command(Figure28-5)returnsatrueexit
status,thewhilestructurecontinuestoexecutetheseriesof
commandsdelimitedbythedoanddonestatements.Before
eachloopthroughthecommands,thestructureexecutesthe
test-command.Whentheexitstatusofthetest-commandis
false,thestructurepassescontroltothestatementafterthe
donestatement.
Figure28-5.Awhileflowchart
testbuiltin
Thefollowingshellscriptfirstinitializesthenumbervariableto
zero.Thetestbuiltinthendetermineswhethernumberisless
than10.Thescriptusestestwiththeltargumenttoperforma
numericaltest.Fornumericalcomparisons,youmustusene
(notequal),eq(equal),gt(greaterthan),ge(greaterthanor
equalto),lt(lessthan),orle(lessthanorequalto).Forstring
comparisonsuse=(equal)or!=(notequal)whenyouare
workingwithtest.Inthisexample,testhasanexitstatusof0
(true)aslongasnumberislessthan10.Aslongastestreturns
true,thestructureexecutesthecommandsbetweenthedoand
donestatements.Seepage879forinformationonthetest
utility,whichisverysimilartothetestbuiltin.
$catcount
#!/bin/bash
number=0
while["$number"-lt10]
do
echo-n"$number"
((number+=1))
done
echo
$count
0123456789
$
Theechocommandfollowingdodisplaysnumber.Then
preventsechofromissuingaNEWLINEfollowingitsoutput.The
nextcommandusesarithmeticevaluation[((...));page940]to
incrementthevalueofnumberby1.Thedonestatement
terminatestheloopandreturnscontroltothewhilestatement
tostarttheloopoveragain.Thefinalechocausescounttosend
aNEWLINEcharactertostandardoutput,sothatthenext
promptoccursintheleftmostcolumnonthedisplay(rather
thanimmediatelyfollowing9).
Optional:Thespell_checkScript
Theaspellutilitychecksthewordsinafileagainstadictionaryofcorrectlyspelled
words.Withtheloption,aspellrunsinlistmode:Inputcomesfromstandard
inputandaspellsendseachpotentiallymisspelledwordtostandardoutput.The
followingcommandproducesalistofpossiblemisspellingsinthefileletter.txt:
$aspell-l<letter.txt
quikly
portible
frendly
Thenextshellscript,namedspell_check,showsanotheruseofawhile
structure.Tofindtheincorrectspellingsinafile,youcanusespell_check,
whichcallsaspelltocheckafileagainstasystemdictionarybutgoesastep
further:Itenablesyoutospecifyalistofcorrectlyspelledwordsandremoves
thesewordsfromtheoutputofaspell.Thisscriptisusefulforremovingwords
thatyouusefrequently,suchasnamesandtechnicalterms,thatarenotina
standarddictionary.Althoughyoucanduplicatethefunctionalityofspell_check
byusingadditionalaspelldictionaries,thescriptisincludedhereforitsinstructive
value.
Thespell_checkscriptrequirestwofilenamearguments:afilecontainingthe
listofcorrectlyspelledwordsandafilethatyouwanttocheck.Thefirstif
statementverifiesthattheuserspecifiedtwoarguments.Thenexttwoif
statementsverifythatbothargumentsarereadablefiles.(Theexclamationpoint
negatesthesenseofthefollowingoperator;theroperatorcausestestto
determinewhetherafileisreadable.Theresultisatestthatdetermines
whetherafileisnotreadable.)
$catspell_check
#!/bin/bash
#removecorrectspellingsfromaspelloutput
if[$#-ne2]
then
echo"Usage:spell_checkfile1file2"1>&2
echo"file1:listofcorrectspellings"1>&2
echo"file2:filetobechecked"1>&2
exit1
fi
if[!-r"$1"]
then
echo"spell_check:$1isnotreadable"1>&2
exit1
fi
if[!-r"$2"]
then
echo"spell_check:$2isnotreadable"1>&2
exit1
fi
aspell-l<"$2"|
whilereadline
do
if!grep"^$line$""$1">/dev/null
then
echo$line
fi
done
Thespell_checkscriptsendstheoutputfromaspell(withtheloptionsothatit
producesalistofmisspelledwordsonstandardoutput)throughapipeto
standardinputofawhilestructure,whichreadsonelineatatime(eachline
hasonewordonit)fromstandardinput.Thetest-command(thatis,read
line)returnsatrueexitstatusaslongasitreceivesalinefromstandardinput.
Insidethewhileloopanifstatement[1]monitorsthereturnvalueofgrep,which
determineswhetherthelinethatwasreadisintheuser'slistofcorrectlyspelled
words.Thepatternthatgrepsearchesfor(thevalueof$line)isprecededand
followedbyspecialcharactersthatspecifythebeginningandendofaline(^
and$,respectively).Thesespecialcharactersensurethatgrepfindsamatchonly
ifthe$linevariablematchesanentirelineinthefileofcorrectlyspelledwords.
(Otherwise,grepwouldmatchastring,suchaspaul,intheoutputofaspellifthe
fileofcorrectlyspelledwordscontainedthewordpaulson.)Thesespecial
characters,togetherwiththevalueofthe$linevariable,formaregular
expression(AppendixA).
Theoutputofgrepisredirectedto/dev/null(page215)becausetheoutputis
notneeded;onlytheexitcodeisimportant.Theifstatementchecksthe
negatedexitstatusofgrep(theleadingexclamationpointnegatesorchangesthe
senseoftheexitstatustruebecomesfalse,andviceversa),whichis0ortrue
(falsewhennegated)whenamatchinglineisfound.Iftheexitstatusisnot0or
false(truewhennegated),thewordwasnotinthefileofcorrectlyspelled
words.Theechobuiltinsendsalistofwordsthatarenotinthefileofcorrectly
spelledwordstostandardoutput.
OnceitdetectstheEOF(endoffile),thereadbuiltinreturnsafalseexitstatus.
Controlthenpassesoutofthewhilestructure,andthescriptterminates.
Beforeyouusespell_check,createafileofcorrectspellingscontainingwords
thatyouusefrequentlybutthatarenotinastandarddictionary.Forexample,if
youworkforacompanynamedBlinkenshipandKlimowski,Attorneys,you
wouldputBlinkenshipandKlimowskiintothefile.Thefollowingexample
showshowspell_checkchecksthespellinginafilenamedmemoandremoves
BlinkenshipandKlimowskifromtheoutputlistofincorrectlyspelledwords:
$aspell-l<memo
Blinkenship
Klimowski
targat
hte
$catword_list
Blinkenship
Klimowski
$spell_checkword_listmemo
targat
hte
Refertotheaspellmanual(inthe/usr/share/doc/aspelldirectoryorat
aspell.net)formoreinformation.
[1]Thisifstatementcanalsobewrittenas
if!grep-qw"$line""$1"
Theqoptionsuppressestheoutputfromgrepsothatonlyanexitcodeisreturned.The
woptioncausesgreptomatchonlyawholeword.
until
Theuntilandwhilestructuresareverysimilar,differingonlyin
thesenseofthetestperformedatthetopoftheloop.Figure
28-6showsthatuntilcontinuestoloopuntilthetest-
commandreturnsatrueexitstatus.Thewhilestructureloops
whilethetest-commandcontinuestoreturnatrueornonerror
condition.Theuntilcontrolstructurehasthefollowingsyntax:
untiltest-command
do
commands
done
Figure28-6.Anuntilflowchart
Thefollowingscriptdemonstratesanuntilstructurethat
includesread.Whentheuserentersthecorrectstringof
characters,thetest-commandissatisfiedandthestructure
passescontroloutoftheloop.
$catuntil1
secretname=jenny
name=noname
echo"Trytoguessthesecretname!"
echo
until["$name"="$secretname"]
do
echo-n"Yourguess:"
readname
done
echo"Verygood."
$until1
Trytoguessthesecretname!
Yourguess:helen
Yourguess:barbara
Yourguess:rachael
Yourguess:jenny
Verygood
Thefollowinglockttyscriptissimilartothelockcommandon
BerkeleyUNIXandtheLockScreenmenuselectioninGNOME.
Thescriptpromptsyouforakey(password)andusesanuntil
controlstructuretolocktheterminal.Theuntilstatement
causesthesystemtoignoreanycharacterstypedatthe
keyboarduntiltheusertypesinthekeyonalinebyitself,
whichunlockstheterminal.Thelockttyscriptcankeeppeople
fromusingyourterminalwhileyouareawayfromitforshort
periodsoftime.Itsavesyoufromhavingtologoutifyouare
concernedaboutotherusersusingyourlogin.
$catlocktty
#!/bin/bash
#UNIX/WORLD,III:4
trap''12318
stty-echo
echo-n"Key:"
readkey_1
echo
echo-n"Again:"
readkey_2
echo
key_3=
if["$key_1"="$key_2"]
then
tputclear
until["$key_3"="$key_2"]
do
readkey_3
done
else
echo"locktty:keysdonotmatch"1>&2
fi
sttyecho
Tip:Forgetyourpasswordforlocktty?
Ifyouforgetyourkey(password),youwillneedto
loginfromanother(virtual)terminalandkillthe
processrunninglocktty.
trapbuiltin
Thetrapbuiltin(page933)atthebeginningofthelockttyscript
stopsauserfrombeingabletoterminatethescriptbysending
itasignal(forexample,bypressingtheinterruptkey).Trapping
signal18meansthatnoonecanuseCONTROL-Z(jobcontrol,a
stopfromatty)todefeatthelock.(SeeTable28-5onpage933
foralistofsignals.)Thesttyechocommandcausesthe
terminalnottodisplaycharacterstypedatthekeyboard,
therebypreventingthekeythattheuserentersfromappearing
onthescreen.Afterturningoffkeyboardecho,thescript
promptstheuserforakey,readsitintotheuser-created
variablekey_1,promptstheusertoenterthesamekeyagain,
andsavesitinkey_2.Thestatementkey_3=createsa
variablewithaNULLvalue.Ifkey_1andkey_2match,
lockttyclearsthescreen(withthetputcommand)andstartsan
untilloop.Theuntilloopkeepsattemptingtoreadfromthe
terminalandassigningtheinputtothekey_3variable.Once
theusertypesinastringthatmatchesoneoftheoriginalkeys
(key_2),theuntilloopterminatesandkeyboardechoisturned
onagain.
breakandcontinue
Youcaninterruptafor,while,oruntilloopbyusingabreak
orcontinuestatement.Thebreakstatementtransferscontrol
tothestatementafterthedonestatement,whichterminates
executionoftheloop.Thecontinuecommandtransferscontrol
tothedonestatement,whichcontinuesexecutionoftheloop.
Thefollowingscriptdemonstratestheuseofthesetwo
statements.Thefor...instructureloopsthroughthevalues
110.Thefirstifstatementexecutesitscommandswhenthe
valueoftheindexislessthanorequalto3($indexle3).The
secondifstatementexecutesitscommandswhenthevalueof
theindexisgreaterthanorequalto8($indexge8).In
betweenthetwoifs,echodisplaysthevalueoftheindex.Forall
valuesuptoandincluding3,thefirstifstatementdisplays
continueandexecutesacontinuestatementthatskipsecho
$indexandthesecondifstatementandcontinueswiththe
nextforstatement.Forthevalueof8,thesecondifstatement
displaysbreakandexecutesabreakstatementthatexitsfrom
theforloop:
$catbrk
forindexin12345678910
do
if[$index-le3];then
echo"continue"
continue
fi
#
echo$index
#
if[$index-ge8];then
echo"break"
break
fi
done
$brk
continue
continue
continue
4
5
6
7
8
break
case
Thecasestructure(Figure28-7,page902)isamultiple-branch
decisionmechanism.Thepathtakenthroughthestructure
dependsonamatchorlackofamatchbetweenthetest-
stringandoneofthepatterns.Thecasecontrolstructurehas
thefollowingsyntax:
casetest-stringin
pattern-1)
commands-1
;;
pattern-2)
commands-2
;;
pattern-3)
commands-3
;;
...
esac
Figure28-7.Acaseflowchart
Thefollowingcasestructureexaminesthecharacterthatthe
userentersasthetest-string.Thisvalueisheldinthevariable
letter.Ifthetest-stringhasavalueofA,thestructure
executesthecommandfollowingthepatternA.Theright
parenthesisispartofthecasecontrolstructure,notpartofthe
pattern.Ifthetest-stringhasavalueofBorC,thestructure
executesthecommandfollowingthematchingpattern.The
asterisk(*)indicatesanystringofcharactersandservesasa
catch-allincasethereisnomatch.Ifnopatternmatchesthe
test-stringandifthereisnocatch-all(*)pattern,control
passestothecommandfollowingtheesacstatement,without
thecasestructuretakinganyaction.
$catcase1
echo-n"EnterA,B,orC:"
readletter
case"$letter"in
A)
echo"YouenteredA"
;;
B)
echo"YouenteredB"
;;
C)
echo"YouenteredC"
;;
*)
echo"YoudidnotenterA,B,orC"
;;
esac
$case1
EnterA,B,orC:B
YouenteredB
Thenextexecutionofcase1showstheuserenteringa
lowercaseb.Becausethetest-stringbdoesnotmatchthe
uppercaseBpattern(oranyotherpatterninthecase
statement),theprogramexecutesthecommandsfollowingthe
catchallpatternanddisplaysamessage:
$case1
EnterA,B,orC:b
YoudidnotenterA,B,orC
Thepatterninthecasestructureisanalogoustoan
ambiguousfilereference.Itcanincludeanyofthespecial
charactersandstringsshowninTable28-2.
Table28-2.Patterns
Pattern Function
*Matchesanystringofcharacters.Useforthedefaultcase.
?Matchesanysinglecharacter.
[...] Definesacharacterclass.Anycharactersenclosedwithin
bracketsaretried,oneatatime,inanattempttomatcha
singlecharacter.Ahyphenbetweentwocharacters
specifiesarangeofcharacters.
|Separatesalternativechoicesthatsatisfyaparticular
branchofthecasestructure.
Thenextscriptacceptsbothuppercaseandlowercaseletters:
$catcase2
echo-n"EnterA,B,orC:"
readletter
case"$letter"in
a|A)
echo"YouenteredA"
;;
b|B)
echo"YouenteredB"
;;
c|C)
echo"YouenteredC"
;;
*)
echo"YoudidnotenterA,B,orC"
;;
esac
$case2
EnterA,B,orC:b
YouenteredB
Optional
Thefollowingexampleshowshowyoucanusethecasestructuretocreatea
simplemenu.Thecommand_menuscriptusesechotopresentmenuitemsand
prompttheuserforaselection.(Theselectcontrolstructure[page907]makes
itmucheasiertocodeamenu.)Thecasestructurethenexecutesthe
appropriateutilitydependingontheuser'sselection.
$catcommand_menu
#!/bin/bash
#menuinterfacetosimplecommands
echo-e"\nCOMMANDMENU\n"
echo"a.Currentdateandtime"
echo"b.Userscurrentlyloggedin"
echo"c.Nameoftheworkingdirectory"
echo-e"d.Contentsoftheworkingdirectory\n"
echo-n"Entera,b,c,ord:"
readanswer
echo
#
case"$answer"in
a)
date
;;
b)
who
;;
c)
pwd
;;
d)
ls
;;
*)
echo"Thereisnoselection:$answer"
;;
esac
$command_menu
COMMANDMENU
a.Currentdateandtime
b.Userscurrentlyloggedin
c.Nameoftheworkingdirectory
d.Contentsoftheworkingdirectory
Entera,b,c,ord:a
WedJan512:31:12PST2005
echoe
Theeoptioncausesechotointerpret\nasaNEWLINE
character.Ifyoudonotincludethisoption,echodoesnotoutput
theextrablanklinesthatmakethemenueasytoreadbut
insteadoutputsthe(literal)two-charactersequence\n.Thee
optioncausesechotointerpretseveralotherbackslash-quoted
characters(Table28-3).Remembertoquote(i.e.,placedouble
quotationmarksaroundthestring)thebackslash-quoted
charactersothattheshelldoesnotinterpretitbutpassesthe
backslashandthecharactertoecho.Seexpg_echo(page327)
forawaytoavoidusingtheeoption.
Table28-3.Specialcharactersinecho(mustusee)
Quoted
character echodisplays
\a Alert(bell)
\b BACKSPACE
\c SuppresstrailingNEWLINE
\f FORMFEED
\n NEWLINE
\r RETURN
\t HorizontalTAB
\v VerticalTAB
\\ Backslash
\nnn ThecharacterwiththeASCIIoctalcodennn;ifnnnisnot
valid,echodisplaysthestringliterally
Youcanalsousethecasecontrolstructuretotakevarious
actionsinascript,dependingonhowmanyargumentsthe
scriptiscalledwith.Thefollowingscript,namedsafedit,usesa
casestructurethatbranchesbasedonthenumberofcommand
linearguments($#).Itsavesabackupcopyofafileyouare
editingwithvim.
$catsafedit
#!/bin/bash
#UNIX/WORLD,IV:11
PATH=/bin:/usr/bin
script=$(basename$0)
case$#in
0)
vim
exit0
;;
1)
if[!-f"$1"]
then
vim"$1"
exit0
fi
if[!-r"$1"-o!-w"$1"]
then
echo"$script:checkpermissionson$1"1>&2
exit1
else
editfile=$1
fi
if[!-w"."]
then
echo"$script:backupcannotbe"\
"createdintheworkingdirectory"1>&2
exit1
fi
;;
*)
echo"Usage:$script[file-to-edit]"1>&2
exit1
;;
esac
tempfile=/tmp/$$.$script
cp$editfile$tempfile
ifvim$editfile
then
mv$tempfilebak.$(basename$editfile)
echo"$script:backupfilecreated"
else
mv$tempfileediterr
echo"$script:editerror--copyof"\
"originalfileisinediterr"1>&2
fi
Ifyoucallsafeditwithoutanyarguments,thecasestructure
executesitsfirstbranchandcallsvimwithoutafilename
argument.Becauseanexistingfileisnotbeingedited,safedit
doesnotcreateabackupfile.Ifyoucallsafeditwithone
argument,itrunsthecommandsinthesecondbranchofthe
casestructureandverifiesthatthefilespecifiedby$1does
notyetexistoristhenameofafileforwhichtheuserhasread
andwritepermission.Thesafeditscriptalsoverifiesthatthe
userhaswritepermissionfortheworkingdirectory.Iftheuser
callssafeditwithmorethanoneargument,thethirdbranchof
thecasestructurepresentsausagemessageandexitswitha
statusof1.
SetPATH
Inadditiontousingacasestructureforbranchingbasedonthe
numberofcommandlinearguments,thesafeditscript
introducesseveralotherfeatures.First,atthebeginningofthe
script,thePATHvariableissettosearch/binand/usr/bin.
SettingPATHinthiswayensuresthatthecommandsexecuted
bythescriptarestandardutilities,whicharekeptinthose
directories.BysettingPATHinsideascript,youcanavoidthe
problemsthatmightoccurifusershavesetPATHtosearch
theirowndirectoriesfirstandhavescriptsorprogramswiththe
samenamesastheutilitiesthescriptcalls.Youcanalsoinclude
absolutepathnameswithinascripttoachievethisend,butthis
practicecanmakeascriptlessportable.
Nameoftheprogram
Inasecondsafeditfeature,thefollowinglinecreatesa
variablenamedscriptandassignsthesimplefilenameofthe
scripttoit:
script=$(basename$0)
Thebasenameutilitysendsthesimplefilenamecomponentofits
argumenttostandardoutput,whichisassignedtothescript
variable,usingcommandsubstitution.The$0holdsthe
commandthescriptwascalledwith(page921).Nomatter
whichofthefollowingcommandstheusercallsthescriptwith,
theoutputofbasenameisthesimplefilenamesafedit:
$/home/alex/bin/safeditmemo
$./safeditmemo
$safeditmemo
Afterthescriptvariableisset,itreplacesthefilenameofthe
scriptinusageanderrormessages.Byusingavariablethatis
derivedfromthecommandthatinvokedthescriptratherthana
filenamethatishardcodedintothescript,youcancreatelinks
tothescriptorrenameit,andtheusageanderrormessages
willstillprovideaccurateinformation.
Namingtemporaryfiles
Athirdsignificantfeatureofsafeditrelatestotheuseofthe
$$variableinthenameofatemporaryfile.Thestatement
followingtheesacstatementcreatesandassignsavaluetothe
tempfilevariable.Thisvariablecontainsthenameofa
temporaryfilethatisstoredinthe/tmpdirectory,asaremany
temporaryfiles.ThetemporaryfilenamebeginswiththePID
numberoftheshellandendswiththenameofthescript.Use
ofthePIDnumberensuresthatthefilenameisunique,and
safeditwillnotattempttooverwriteanexistingfile,asmight
happeniftwopeoplewereusingsafeditatthesametime.The
nameofthescriptisappendedsothat,shouldthefilebeleftin
/tmpforsomereason,youcanfigureoutwhereitcamefrom.
ThePIDnumberisusedinfrontofratherthanafter$scriptin
thefilenamebecauseofthe14-characterlimitplacedon
filenamesbysomeolderversionsofUNIX.Linuxsystemsdonot
havethislimitation.BecausethePIDnumberensuresthe
uniquenessofthefilename,itisplacedfirstsothatitcannotbe
truncated.(Ifthe$scriptcomponentistruncated,thefilename
isstillunique.)Forthesamereason,whenabackupfileis
createdinsidetheifcontrolstructureafewlinesdowninthe
script,thefilenameiscomposedofthestringbak.followedby
thenameofthefilebeingedited.Onanoldersystem,ifbak
wereusedasasuffixratherthanaprefixandtheoriginal
filenamewere14characterslong,.bakmightbelostandthe
originalfilewouldbeoverwritten.Thebasenameutilityextracts
thesimplefilenameof$editfilebeforeitisprefixedwithbak.
Fourth,safeditusesanunusualtest-commandintheif
structure:vim$editfile.Thetest-commandcallsvimtoedit
$editfile.Whenyoufinisheditingthefileandexitfromvim,vim
returnsanexitcode.Theifcontrolstructureusesthatexitcode
todeterminewhichbranchtotake.Iftheeditingsession
completedsuccessfully,vimreturns0andthestatements
followingthethenstatementareexecuted.Ifvimdoesnot
terminatenormally(aswouldoccuriftheuserkilled[page395]
thevimprocess),vimreturnsanonzeroexitstatusandthe
scriptexecutesthestatementsfollowingelse.
select
Theselectcontrolstructureisbasedontheonefoundinthe
KornShell.Itdisplaysamenu,assignsavaluetoavariable
basedontheuser'schoiceofitems,andexecutesaseriesof
commands.Theselectcontrolstructurehasthefollowing
syntax:
selectvarname[inarg...]
do
commands
done
Theselectstructuredisplaysamenuoftheargitems.Ifyou
omitthekeywordinandthelistofarguments,selectusesthe
positionalparametersinplaceoftheargitems.Themenuis
formattedwithnumbersbeforeeachitem.Forexample,a
selectstructurethatbeginswith
selectfruitinapplebananablueberrykiwiorangewatermelonSTOP
displaysthefollowingmenu:
1)apple3)blueberry5)orange7)STOP
2)banana4)kiwi6)watermelon
TheselectstructureusesthevaluesoftheLINESand
COLUMNSvariablestodeterminethesizeofthedisplay.
(LINEShasadefaultvalueof24;COLUMNShasadefault
valueof80.)WithCOLUMNSsetto20,themenulookslike
this:
1)apple
2)banana
3)blueberry
4)kiwi
5)orange
6)watermelon
7)STOP
PS3
AfterdisplayingthemenuselectdisplaysthevalueofPS3,the
specialselectprompt.ThedefaultvalueofPS3is?#butyou
typicallysetPS3toamoremeaningfulvalue.Whenyouentera
validnumber(oneinthemenurange)inresponsetothePS3
prompt,selectsetsvarnametotheargumentcorresponding
tothenumberyouentered.Ifyoumakeaninvalidentry,
varnameissettonull.Eitherwayselectstoresyourresponse
inthekeywordvariableREPLYandthenexecutesthe
commandsbetweendoanddone.IfyoupressRETURN
withoutenteringachoice,theshellredisplaysthemenuandthe
PS3prompt.
TheselectstructurecontinuestoissuethePS3promptand
executethecommandsuntilsomethingcausesitto
exittypicallyabreakorexitstatement.Abreakstatement
exitsfromtheloopandanexitstatementexitsfromthescript.
Thefollowingscriptillustratestheuseofselect:
$catfruit2
#!/bin/bash
PS3="Chooseyourfavoritefruitfromthesepossibilities:"
selectFRUITinapplebananablueberrykiwiorangewatermelonSTOP
do
if["$FRUIT"==""];then
echo-e"Invalidentry.\n"
continue
elif[$FRUIT=STOP];then
echo"Thanksforplaying!"
break
fi
echo"Youchose$FRUITasyourfavorite."
echo-e"Thatischoicenumber$REPLY.\n"
done
$fruit2
1)apple3)blueberry5)orange7)STOP
2)banana4)kiwi6)watermelon
Chooseyourfavoritefruitfromthesepossibilities:3
Youchoseblueberryasyourfavorite.
Thatischoicenumber3.
Chooseyourfavoritefruitfromthesepossibilities:99
Invalidentry.
Chooseyourfavoritefruitfromthesepossibilities:7
Thanksforplaying!
AftersettingthePS3promptandestablishingthemenuwith
theselectstatement,fruit2executesthecommandsbetween
doanddone.Iftheusermakesaninvalidentry,theshellsets
varname($FRUIT)toanullvalue,sofruit2firsttests
whether$FRUITisnull.Ifitis,echodisplaysanerrorand
continuecausestheshelltoredisplaythePS3prompt.Ifthe
entryisvalid,thescripttestswhethertheuserwantstostop.If
so,echodisplaysamessageandbreakexitsfromtheselect
structure(andfromthescript).Iftheuserenteredavalid
responseanddoesnotwanttostop,thescriptdisplaysthe
nameandnumberoftheuser'sresponse.(Seepage904for
informationabouttheeoptiontoecho.)
HereDocument
AHeredocumentallowsyoutoredirectinputtoashellscript
fromwithintheshellscriptitself.AHeredocumentissocalled
becauseitishereimmediatelyaccessibleintheshell
scriptinsteadofthere,perhapsinanotherfile.
Thefollowingscript,namedbirthday,containsaHere
document.Thetwolessthan(<<)symbolsinthefirstline
indicatethataHeredocumentfollows.Oneormorecharacters
thatdelimittheHeredocumentfollowthelessthansymbolsthis
exampleusesaplussign.Whereastheopeningdelimitermust
appearadjacenttothelessthansymbols,theclosingdelimiter
mustbeonalinebyitself.Theshellsendseverythingbetween
thetwodelimiterstotheprocessasstandardinput.Inthe
exampleitisasthoughyouhadredirectedstandardinputto
grepfromafile,exceptthatthefileisembeddedintheshell
script:
$catbirthday
grep-i"$1"<<+
AlexJune22
BarbaraFebruary3
DarleneMay8
HelenMarch13
JennyJanuary23
NancyJune26
+
$birthdayJenny
JennyJanuary23
$birthdayjune
AlexJune22
NancyJune26
Whenyourunbirthday,itlistsalltheHeredocumentlinesthat
containtheargumentyoucalleditwith.Inthiscasethefirst
timebirthdayisrun,itdisplaysJenny'sbirthdaybecauseitis
calledwithanargumentofJenny.Thesecondrundisplaysall
thebirthdaysinJune.Theiargumentcausesgrep'ssearchnot
tobecasesensitive.
Optional
Thenextscript,namedbundle,[2]includesacleveruseofaHeredocument.
Thebundlescriptisanelegantexampleofascriptthatcreatesashellarchive
(shar)file.Thescript,shownfollowing,createsafilethatisitselfashellscript
containingseveralotherfilesaswellasthecodetore-createtheoriginalfiles.
$catbundle
#!/bin/bash
#bundle:groupfilesintodistributionpackage
echo"#Tounbundle,bashthisfile"
fori
do
echo"echo$i1>&2"
echo"cat>$i<<'Endof$i'"
cat$i
echo"Endof$i"
done
Justastheshelldoesnottreatspecialcharactersthatoccurinstandardinputof
ashellscriptasspecial,sotheshelldoesnottreatthespecialcharactersthat
occurbetweenthedelimitersinaHeredocumentasspecial.
Asthefollowingexampleshows,theoutputofbundleisashellscript,whichis
redirectedtoafilenamedboth-files.Itcontainsthecontentsofeachfilegiven
asanargumenttobundle(file1andfile2inthiscase)insideaHeredocument.
Toextracttheoriginalfilesfrombothfiles,yousimplyrunitasanargumentto
abashcommand.BeforeeachHeredocumentisacatcommandthatcausesthe
Heredocumenttobewrittentoanewfilewhenbothfilesisrun:
$catfile1
Thisisafile.
Itcontainstwolines.
$catfile2
Thisisanotherfile.
Itcontains
threelines.
$bundlefile1file2>bothfiles
$catbothfiles
#Tounbundle,bashthisfile
echofile11>&2
cat>file1<<'Endoffile1'
Thisisafile.
Itcontainstwolines.
Endoffile1
echofile21>&2
cat>file2<<'Endoffile2'
Thisisanotherfile.
Itcontains
threelines.
Endoffile2
Inthenextexample,file1andfile2areremovedbeforebothfilesisrun.The
bothfilesscriptechoesthenamesofthefilesitcreatesasitcreatesthem.The
lscommandthenshowsthatbothfileshasre-createdfile1andfile2:
$rmfile1file2
$bashbothfiles
file1
file2
$ls
bothfiles
file1
file2
[2]ThankstoBrianW.KernighanandRobPike,TheUnixProgrammingEnvironment
(EnglewoodCliffs,N.J.:Prentice-Hall,1984),98.Reprintedwithpermission.
FileDescriptors
Asdiscussedonpage270,beforeaprocesscanreadfromor
writetoafileitmustopenthatfile.Whenaprocessopensa
file,Linuxassociatesanumber(calledafiledescriptor)withthe
file.Eachprocesshasitsownsetofopenfilesanditsownfile
descriptors.Afteropeningafile,aprocessreadsfromand
writestothatfilebyreferringtoitsfiledescriptor.Whenitno
longerneedsthefile,theprocessclosesthefile,freeingthefile
descriptor.
AtypicalLinuxprocessstartswiththreeopenfiles:standard
input(filedescriptor0),standardoutput(filedescriptor1),and
standarderror(filedescriptor2).Oftenthosearetheonlyfiles
theprocessneeds.Recallthatyouredirectstandardoutputwith
thesymbol>orthesymbol1>andthatyouredirectstandard
errorwiththesymbol2>.Althoughyoucanredirectotherfile
descriptors,becausefiledescriptorsotherthan0,1,and2do
nothaveanyspecialconventionalmeaning,itisrarelyusefulto
doso.Theexceptionisinprogramsthatyouwriteyourself,in
whichcaseyoucontrolthemeaningofthefiledescriptorsand
cantakeadvantageofredirection.
Openingafiledescriptor
TheBourneAgainShellopensfilesusingtheexecbuiltinas
follows:
execn>outfile
execm<infile
Thefirstlineopensoutfileforoutputandholdsitopen,
associatingitwithfiledescriptorn.Thesecondlineopensinfile
forinputandholdsitopen,associatingitwithfiledescriptorm.
Duplicatingafiledescriptor
The<&tokenduplicatesaninputfiledescriptor;use>&to
duplicateanoutputfiledescriptor.Youcanduplicateafile
descriptorbymakingitrefertothesamefileasanotheropen
filedescriptor,suchasstandardinputoroutput.Usethe
followingformattoopenorredirectfiledescriptornasa
duplicateoffiledescriptorm:
execn<&m
Onceyouhaveopenedafile,youcanuseitforinputand
outputintwodifferentways.First,youcanuseI/Oredirection
onanycommandline,redirectingstandardoutputtoafile
descriptorwith>&norredirectingstandardinputfromafile
descriptorwith<&n.Second,youcanusetheread(page927)
andechobuiltins.Ifyouinvokeothercommands,including
functions(page321),theyinherittheseopenfilesandfile
descriptors.Whenyouhavefinishedusingafile,youcanclose
itwith
execn<&
Whenyouinvoketheshellfunctioninthenextexample,named
mycp,withtwoarguments,itcopiesthefilenamedbythefirst
argumenttothefilenamedbythesecondargument.Ifyou
supplyonlyoneargument,thescriptcopiesthefilenamedby
theargumenttostandardoutput.Ifyouinvokemycpwithno
arguments,itcopiesstandardinputtostandardoutput.
Tip:Afunctionisnotashellscript
Themycpexampleisashellfunction;itwillnot
workasyouexpectifyouexecuteitasashellscript.
(Itwillwork:Thefunctionwillbecreatedinavery
short-livedsubshell,whichisprobablyoflittleuse.)
Youcanenterthisfunctionfromthekeyboard.Ifyou
putthefunctioninafile,youcanrunitasan
argumenttothe.(dot)builtin(page269).Youcan
alsoputthefunctioninastartupfileifyouwantitto
bealwaysavailable(page323).
functionmycp()
{
case$#in
0)
#zeroarguments
#filedescriptor3duplicatesstandardinput
#filedescriptor4duplicatesstandardoutput
exec3<&04<&1
;;
1)
#oneargument
#openthefilenamedbytheargumentforinput
#andassociateitwithfiledescriptor3
#filedescriptor4duplicatesstandardoutput
exec3<$14<&1
;;
2)
#twoarguments
#openthefilenamedbythefirstargumentforinput
#andassociateitwithfiledescriptor3
#openthefilenamedbythesecondargumentforoutput
#andassociateitwithfiledescriptor4
exec3<$14>$2
;;
*)
echo"Usage:mycp[source[dest]]"
return1
;;
esac
#callcatwithinputcomingfromfiledescriptor3
#andoutputgoingtofiledescriptor4
cat<&3>&4
#closefiledescriptors3and4
exec3<&-4<&-
}
Therealworkofthisfunctionisdoneinthelinethatbegins
withcat.Therestofthescriptarrangesforfiledescriptors3and
4,whicharetheinputandoutputofthecatcommand,tobe
associatedwiththeappropriatefiles.
Optional
Thenextprogramtakestwofilenamesonthecommandline,sortsboth,and
sendstheoutputtotemporaryfiles.Theprogramthenmergesthesortedfilesto
standardoutput,precedingeachlinebyanumberthatindicateswhichfileit
camefrom.
$catsortmerg
#!/bin/bash
usage()
{
if[$#-ne2];then
echo"Usage:$0file1file2"2>&1
exit1
fi
}
#Defaulttemporarydirectory
:${TEMPDIR:=/tmp}
#Checkargumentcount
usage"$@"
#Setuptemporaryfilesforsorting
file1=$TEMPDIR/$$.file1
file2=$TEMPDIR/$$.file2
#Sort
sort$1>$file1
sort$2>$file2
#Open$file1and$file2forreading.Usefiledescriptors3and4.
exec3<$file1
exec4<$file2
#Readthefirstlinefromeachfiletofigureouthowtostart.
readLine1<&3
status1=$?
readLine2<&4
status2=$?
#Strategy:whilethereisstillinputleftinbothfiles:
#Outputthelinethatshouldcomefirst.
#Readanewlinefromthefilethatlinecamefrom.
while[$status1-eq0-a$status2-eq0]
do
if[["$Line2">"$Line1"]];then
echo-e"1.\t$Line1"
read-u3Line1
status1=$?
else
echo-e"2.\t$Line2"
read-u4Line2
status2=$?
fi
done
#Nowoneofthefilesisatend-of-file.
#Readfromeachfileuntiltheend.
#Firstfile1:
while[$status1-eq0]
do
echo-e"1.\t$Line1"
readLine1<&3
status1=$?
done
#Nextfile2:
while[[$status2-eq0]]
do
echo-e"2.\t$Line2"
readLine2<&4
status2=$?
done
#Closeandremovebothinputfiles
exec3<&-4<&-
rm-f$file1$file2
exit0
ParametersandVariables
Shellparametersandvariableswereintroducedonpage285.
Thissectionaddstothepreviouscoveragewithadiscussionof
arrayvariables,globalversuslocalvariables,specialand
positionalparameters,andexpandingnullandunsetvariables.
ArrayVariables
TheBourneAgainShellsupportsone-dimensionalarray
variables.Thesubscriptsareintegerswithzero-basedindexing
(i.e.,thefirstelementofthearrayhasthesubscript0).The
followingformatdeclaresandassignsvaluestoanarray:
name=(element1element2...)
ThefollowingexampleassignsfourvaluestothearrayNAMES:
$NAMES=(maxhelensamzach)
Youreferenceasingleelementofanarrayasfollows:
$echo${NAMES[2]}
sam
Thesubscripts[*]and[@]bothextracttheentirearraybut
workdifferentlywhenusedwithindoublequotationmarks.An
@producesanarraythatisaduplicateoftheoriginalarray;an
*producesasingleelementofanarray(oraplainvariable)
thatholdsalltheelementsofthearrayseparatedbythefirst
characterinIFS(normallyaSPACE).Inthefollowingexample,
thearrayAisfilledwiththeelementsoftheNAMESvariable
usingan*,andBisfilledusingan@.Thedeclarebuiltinwith
theaoptiondisplaysthevaluesofthearrays(andremindsyou
thatbashuseszero-basedindexingforarrays):
$A=("${NAMES[*]}")
$B=("${NAMES[@]}")
$declare-a
declare-aA='([0]="maxhelensamzach")'
declare-aB='([0]="max"[1]="helen"[2]="sam"[3]="zach")'
...
declare-aNAMES='([0]="max"[1]="helen"[2]="sam"[3]="zach")'
Fromtheoutputofdeclare,youcanseethatNAMESandBhave
multipleelements.Incontrast,A,whichwasassigneditsvalue
withan*withindoublequotationmarks,hasonlyoneelement:
Ahasallitselementsenclosedbetweendoublequotation
marks.
Inthenextexample,echoattemptstodisplayelement1of
arrayA.NothingisdisplayedbecauseAhasonlyoneelement
andthatelementhasanindexof0.Element0ofarrayAholds
allfournames.Element1ofBholdstheseconditeminthe
arrayandelement0holdsthefirstitem.
$echo${A[1]}
$echo${A[0]}
maxhelensamzach
$echo${B[1]}
helen
$echo${B[0]}
max
Youcanapplythe${#name[*]}operatortoarrayvariables,
returningthenumberofelementsinthearray:
$echo${#NAMES[*]}
4
Thesameoperator,whengiventheindexofanelementofan
arrayinplaceof*,returnsthelengthoftheelement:
$echo${#NAMES[1]}
5
Youcanusesubscriptsontheleftsideofanassignment
statementtoreplaceselectedelementsofthearray:
$NAMES[1]=alex
$echo${NAMES[*]}
maxalexsamzach
LocalityofVariables
Bydefaultvariablesarelocaltotheprocessinwhichtheyare
declared.Thusashellscriptdoesnothaveaccesstovariables
declaredinyourloginshellunlessyouexplicitlymakethe
variablesavailable(global).Underbash,exportmakesavariable
availabletochildprocesses.
Onceyouusetheexportbuiltinwithavariablenameasan
argument,theshellplacesthevalueofthevariableinthe
callingenvironmentofchildprocesses.Thiscallbyvaluegives
eachchildprocessacopyofthevariableforitsownuse.
Thefollowingextest1shellscriptassignsavalueofamerican
tothevariablenamedcheeseandthendisplaysitsfilename
(extest1)andthevalueofcheese.Theextest1scriptthen
callssubtest,whichattemptstodisplaythesameinformation.
Nextsubtestdeclaresacheesevariableanddisplaysitsvalue.
Whensubtestfinishes,itreturnscontroltotheparentprocess,
whichisexecutingextest1.Atthispointextest1again
displaysthevalueoftheoriginalcheesevariable.
$catextest1
cheese=american
echo"extest11:$cheese"
subtest
echo"extest12:$cheese"
$catsubtest
echo"subtest1:$cheese"
cheese=swiss
echo"subtest2:$cheese"
$extest1
extest11:american
subtest1:
subtest2:swiss
extest12:american
Thesubtestscriptneverreceivesthevalueofcheesefrom
extest1,andextest1neverlosesthevalue.Unlikeinthereal
world,achildcanneveraffectitsparent'sattributes.Whena
processattemptstodisplaythevalueofavariablethathasnot
beendeclared,asisthecasewithsubtest,theprocessdisplays
nothing;thevalueofanundeclaredvariableisthatofanull
string.
Thefollowingextest2scriptisthesameasextest1except
thatitusesexporttomakecheeseavailabletothesubtest
script:
$catextest2
exportcheese=american
echo"extest21:$cheese"
subtest
echo"extest22:$cheese"
$extest2
extest21:american
subtest1:american
subtest2:swiss
extest22:american
Herethechildprocessinheritsthevalueofcheeseas
americanand,afterdisplayingthisvalue,changesitscopyto
swiss.Whencontrolisreturnedtotheparent,theparent's
copyofcheeseretainsitsoriginalvalue:american.
Anexportbuiltincanoptionallyincludeanassignment:
exportcheese=american
Theprecedingstatementisequivalenttothefollowingtwo
statements:
cheese=american
exportcheese
Althoughitisrarelydone,youcanexportavariablebeforeyou
assignavaluetoit.Youdonotneedtoexportanalready-
exportedvariableasecondtimeafteryouchangeitsvalue.For
example,youdonotusuallyneedtoexportPATHwhenyou
assignavaluetoitin~/.bash_profilebecauseitistypically
exportedinthe/etc/profileglobalstartupfile.
Functions
Becausefunctionsruninthesameenvironmentastheshell
thatcallsthem,variablesareimplicitlysharedbyashellanda
functionitcalls.
$functionnam(){
>echo$myname
>myname=zach
>}
$myname=sam
$nam
sam
$echo$myname
zach
Intheprecedingexample,themynamevariableissettosam
intheinteractiveshell.Thenthenamfunctioniscalled.It
displaysthevalueofmynameithas(sam)andsetsmyname
tozach.Thefinalechoshowsthat,intheinteractiveshell,the
valueofmynamehasbeenchangedtozach.
Functionlocalvariables
Localvariablesarehelpfulinafunctionwrittenforgeneraluse.
Becausethefunctioniscalledbymanyscriptsthatmaybe
writtenbydifferentprogrammers,youneedtomakesurethat
thenamesofthevariablesusedwithinthefunctiondonot
interactwithvariablesofthesamenameintheprogramsthat
callthefunction.Localvariableseliminatethisproblem.When
usedwithinafunction,thetypesetbuiltindeclaresavariableto
belocaltothefunctionitisdefinedin.
Thenextexampleshowstheuseofalocalvariableina
function.Itusestwovariablesnamedcount.Thefirstis
declaredandassignedavalueof10intheinteractiveshell.Its
valueneverchanges,asechoverifiesaftercount_downisrun.
Theothercountisdeclared,usingtypeset,tobelocaltothe
function.Itsvalue,whichisunknownoutsidethefunction,
rangesfrom4to1,astheechocommandwithinthefunction
confirms.
Theexampleshowsthefunctionbeingenteredfromthe
keyboard;itisnotashellscript.(Seethetip"Afunctionisnot
ashellscript"onpage912).
$functioncount_down(){
>typesetcount
>count=$1
>while[$count-gt0]
>do
>echo"$count..."
>((count=count-1))
>sleep1
>done
>echo"BlastOff."
>}
$count=10
$count_down4
4...
3...
2...
1...
BlastOff\!
$echo$count
10
The((count=count1))assignmentisenclosedbetween
doubleparentheses,whichcausetheshelltoperforman
arithmeticevaluation(page940).Withinthedouble
parenthesesyoucanreferenceshellvariableswithoutthe
leadingdollarsign($).
SpecialParameters
Specialparametersenableyoutoaccessusefulvalues
pertainingtocommandlineargumentsandtheexecutionof
shellcommands.Youreferenceashellspecialparameterby
precedingaspecialcharacterwithadollarsign($).Aswith
positionalparameters,itisnotpossibletomodifythevalueofa
specialparameterbyassignment.
$$:PIDNumber
Theshellstoresinthe$$parameterthePIDnumberofthe
processthatisexecutingit.Inthefollowinginteraction,echo
displaysthevalueofthisvariableandthepsutilityconfirmsits
value.BothcommandsshowthattheshellhasaPIDnumberof
5209:
$echo$$
5209
$ps
PIDTTYTIMECMD
5209pts/100:00:00bash
6015pts/100:00:00ps
Becauseechoisbuiltintotheshell,theshelldoesnothaveto
createanotherprocesswhenyougiveanechocommand.
However,theresultsarethesamewhetherechoisabuiltinor
not,becausetheshellsubstitutesthevalueof$$beforeitforks
anewprocesstorunacommand.Tryusingtheechoutility
(/bin/echo),whichisrunbyanotherprocess,andseewhat
happens.Inthefollowingexample,theshellsubstitutesthe
valueof$$andpassesthatvaluetocpasaprefixfora
filename:
$echo$$
8232
$cpmemo$$.memo
$ls
8232.memomemo
IncorporatingaPIDnumberinafilenameisusefulforcreating
uniquefilenameswhenthemeaningsofthenamesdonot
matter;itisoftenusedinshellscriptsforcreatingnamesof
temporaryfiles.Whentwopeoplearerunningthesameshell
script,theseuniquefilenameskeepthemfrominadvertently
sharingthesametemporaryfile.
Thefollowingexampledemonstratesthattheshellcreatesa
newshellprocesswhenitrunsashellscript.Theid2script
displaysthePIDnumberoftheprocessrunningit(notthe
processthatcalleditthesubstitutionfor$$isperformedbythe
shellthatisforkedtorunid2):
$catid2
echo"$0PID=$$"
$echo$$
8232
$id2
./id2PID=8362
$echo$$
8232
ThefirstechodisplaysthePIDnumberoftheinteractiveshell.
Thenid2displaysitsname($0)andthePIDofthesubshell
thatitisrunningin.ThelastechoshowsthatthePIDnumberof
theinteractiveshellhasnotchanged.
$!
ThevalueofthePIDnumberofthelastprocessthatyouranin
thebackgroundisstoredin$!.Thefollowingexampleexecutes
sleepasabackgroundtaskandusesechotodisplaythevalueof
$!:
$sleep60&
[1]8376
$echo$!
8376
$?:ExitStatus
Whenaprocessstopsexecutingforanyreason,itreturnsan
exitstatustotheparentprocess.Theexitstatusisalsoreferred
toasaconditioncodeorareturncode.The$?variablestores
theexitstatusofthelastcommand.
Byconventionanonzeroexitstatusrepresentsafalsevalue
andmeansthatthecommandfailed.Azeroistrueand
indicatesthatthecommandwassuccessful.Inthefollowing
example,thefirstlscommandsucceedsandthesecondfails:
$lses
es
$echo$?
0
$lsxxx
ls:xxx:Nosuchfileordirectory
$echo$?
1
Youcanspecifytheexitstatusthatashellscriptreturnsby
usingtheexitbuiltin,followedbyanumber,toterminatethe
script.Ifyoudonotuseexitwithanumbertoterminatea
script,theexitstatusofthescriptisthatofthelastcommand
thescriptran.
$cates
echoThisprogramreturnsanexitstatusof7.
exit7
$es
Thisprogramreturnsanexitstatusof7.
$echo$?
7
$echo$?
0
Theesshellscriptdisplaysamessageandterminatesexecution
withanexitcommandthatreturnsanexitstatusof7,theuser-
definedexitstatusinthisscript.Thefirstechothendisplaysthe
valueoftheexitstatusofes.Thesecondechodisplaysthe
valueoftheexitstatusofthefirstecho.Thevalueis0because
thefirstechowassuccessful.
PositionalParameters
Thepositionalparameterscomprisethecommandnameand
commandlinearguments.Theyarecalledpositionalbecause
withinashellscript,yourefertothembytheirpositiononthe
commandline.Onlythesetbuiltin(page924)allowsyouto
changethevaluesofpositionalparameterswithoneexception:
Youcannotchangethevalueofthecommandnamefromwithin
ascript.
$#:NumberofCommandLineArguments
The$#parameterholdsthenumberofargumentsonthe
commandline(positionalparameters),notcountingthe
commanditself:
$catnum_args
echo"Thisscriptwascalledwith$#arguments."
$num_argssammaxzach
Thisscriptwascalledwith3arguments.
$0:NameoftheCallingProgram
Theshellstoresthenameofthecommandyouusedtocalla
programinparameter$0.Thisparameterisnumberedzero
becauseitappearsbeforethefirstargumentonthecommand
line:
$catabc
echo"Thecommandusedtorunthisscriptis$0"
$abc
Thecommandusedtorunthisscriptis./abc
$/home/sam/abc
Thecommandusedtorunthisscriptis/home/sam/abc
Theprecedingshellscriptusesechotoverifythenameofthe
scriptyouareexecuting.Youcanusethebasenameutilityand
commandsubstitutiontoextractanddisplaythesimple
filenameofthecommand:
$catabc2
echo"Thecommandusedtorunthisscriptis$(basename$0)"
$/home/sam/abc2
Thecommandusedtorunthisscriptisabc2
$1$n:CommandLineArguments
Thefirstargumentonthecommandlineisrepresentedby
parameter$1,thesecondargumentby$2,andsoonupto$n.
Forvaluesofnover9,thenumbermustbeenclosedwithin
braces.Forexample,thetwelfthcommandlineargumentis
representedby${12}.Thefollowingscriptdisplayspositional
parametersthatholdcommandlinearguments:
$catdisplay_5args
echoFirst5argumentsare$1$2$3$4$5
$display_5argsjennyalexhelen
First5argumentsarejennyalexhelen
Thedisplay_5argsscriptdisplaysthefirstfivecommandline
arguments.Theshellassignsanullvaluetoeachparameter
thatrepresentsanargumentthatisnotpresentonthe
commandline.Thusthe$4and$5variableshavenullvaluesin
thisexample.
$*
The$*variablerepresentsallthecommandlinearguments,as
thedisplay_allprogramdemonstrates:
$catdisplay_all
echoAllargumentsare$*
$display_allabcdefghijklmnop
Allargumentsareabcdefghijklmnop
Enclosereferencestopositionalparametersbetweendouble
quotationmarks.Thequotationmarksareparticularly
importantwhenyouareusingpositionalparametersas
argumentstocommands.Withoutdoublequotationmarks,a
positionalparameterthatisnotsetorthathasanullvalue
disappears:
$catshowargs
echo"$0wascalledwith$#arguments,thefirstis:$1:."
$showargsabc
./showargswascalledwith3arguments,thefirstis:a:.
$echo$xx
$showargs$xxabc
./showargswascalledwith3arguments,thefirstis:a:.
$showargs"$xx"abc
./showargswascalledwith4arguments,thefirstis::.
Theshowargsscriptdisplaysthenumberofarguments($#)
followedbythevalueofthefirstargumentenclosedbetween
colons.Theprecedingexamplefirstcallsshowargswiththree
simplearguments.Nexttheechocommanddemonstratesthat
the$xxvariable,whichisnotset,hasanullvalue.Inthefinal
twocallstoshowargs,thefirstargumentis$xx.Inthefirst
casethecommandlinebecomesshowargsabc;theshell
passesshowargsthreearguments.Inthesecondcasethe
commandlinebecomesshowargs""abc,whichresultsin
callingshowargswithfourarguments.Thedifferenceinthe
twocallstoshowargsillustratesasubtlepotentialproblem
thatyoushouldkeepinmindwhenusingpositionalparameters
thatmaynotbesetorthatmayhaveanullvalue.
"$*"versus"$@"
The$*and$@parametersworkthesamewayexceptwhen
theyareenclosedwithindoublequotationmarks.Using"$*"
yieldsasingleargument(withSPACEsorthevalueofIFS[page
295]betweenthepositionalparameters),whereas"$@"
producesalistwhereineachpositionalparameterisaseparate
argument.Thisdifferencetypicallymakes"$@"moreuseful
than"$*"inshellscripts.
Thefollowingscriptshelptoexplainthedifferencebetween
thesetwospecialparameters.Inthesecondlineofbothscripts,
thesinglequotationmarkskeeptheshellfrominterpretingthe
enclosedspecialcharacterssotheycanbedisplayedas
themselves.Thebb1scriptshowsthatset"$*"assigns
multipleargumentstothefirstcommandlineparameter:
$catbb1
set"$*"
echo$#parameterswith'"$*"'
echo1:$1
echo2:$2
echo3:$3
$bb1abc
1parameterswith"$*"
1:abc
2:
3:
Thebb2scriptshowsthatset"$@"assignseachargumentto
adifferentcommandlineparameter:
$catbb2
set"$@"
echo$#parameterswith'"$@"'
echo1:$1
echo2:$2
echo3:$3
$bb2abc
3parameterswith"$@"
1:a
2:b
3:c
shift:PromotesCommandLineArguments
Theshiftbuiltinpromoteseachcommandlineargument.The
firstargument(whichwas$1)isdiscarded.Thesecond
argument(whichwas$2)becomesthefirstargument(now
$1),thethirdbecomesthesecond,andsoon.Becauseno
"unshift"commandexists,youcannotbringbackarguments
thathavebeendiscarded.Anoptionalargumenttoshiftspecifies
thenumberofpositionstoshift(andthenumberofarguments
todiscard);thedefaultis1.
Thefollowingdemo_shiftscriptiscalledwiththreearguments.
Doublequotationmarksaroundtheargumentstoechopreserve
thespacingoftheoutput.Theprogramdisplaysthearguments
andshiftsthemrepeatedlyuntiltherearenomorearguments
lefttoshift:
$catdemo_shift
echo"arg1=$1arg2=$2arg3=$3"
shift
echo"arg1=$1arg2=$2arg3=$3"
shift
echo"arg1=$1arg2=$2arg3=$3"
shift
echo"arg1=$1arg2=$2arg3=$3"
shift
$demo_shiftalicehelenjenny
arg1=alicearg2=helenarg3=jenny
arg1=helenarg2=jennyarg3=
arg1=jennyarg2=arg3=
arg1=arg2=arg3=
Repeatedlyusingshiftisaconvenientwaytoloopoverallthe
commandlineargumentsinshellscriptsthatexpectan
arbitrarynumberofarguments.Seepage883forashellscript
thatusesshift.
set:InitializesCommandLineArguments
Whenyoucallthesetbuiltinwithoneormorearguments,it
assignsthevaluesoftheargumentstothepositional
parameters,startingwith$1.Thefollowingscriptusessetto
assignvaluestothepositionalparameters$1,$2,and$3:
$catset_it
setthisisit
echo$3$2$1
$set_it
itisthis
Combiningcommandsubstitution(page334)withthesetbuiltin
isaconvenientwaytogetstandardoutputofacommandina
formthatcanbeeasilymanipulatedinashellscript.The
followingscriptshowshowtousedateandsettoprovidethe
dateinausefulformat.Thefirstcommandshowstheoutputof
date.Thencatdisplaysthecontentsofthedatesetscript.The
firstcommandinthisscriptusescommandsubstitutiontoset
thepositionalparameterstotheoutputofthedateutility.The
nextcommand,echo$*,displaysallpositionalparameters
resultingfromthepreviousset.Subsequentcommandsdisplay
thevaluesofparameters$1,$2,$3,and$4.Thefinal
commanddisplaysthedateinaformatyoucanuseinaletter
orreport:
$date
WedJan523:39:18PST2005
$catdateset
set$(date)
echo$*
echo
echo"Argument1:$1"
echo"Argument2:$2"
echo"Argument3:$3"
echo"Argument6:$6"
echo
echo"$2$3,$6"
$dateset
WedJan523:39:25PST2005
Argument1:Wed
Argument2:Jan
Argument3:5
Argument6:2005
Jan5,2005
Youcanalsousethe+formatargumenttodatetomodifythe
formatofitsoutput.
Whenusedwithoutanyarguments,setdisplaysalistoftheshell
variablesthatareset,includinguser-createdvariablesand
keywordvariables.Underbash,thislististhesameasthat
displayedbydeclareandtypesetwhentheyarecalledwithoutany
arguments.
Thesetbuiltinalsoacceptsoptionsthatletyoucustomizethe
behavioroftheshell.Formoreinformationreferto"set±o:
TurnsShellFeaturesOnandOff"onpage325.
ExpandingNullandUnsetVariables
Theexpression${name}(orjust$nameifitisnot
ambiguous)expandstothevalueofthenamevariable.If
nameisnullornotset,bashexpands${name}toanullstring.
TheBourneAgainShellprovidesthefollowingalternativesto
acceptingtheexpandednullstringasthevalueofthevariable:
Useadefaultvalueforthevariable.
Useadefaultvalueandassignthatvaluetothevariable.
Displayanerror.
Youcanchooseoneofthesealternativesbyusingamodifier
withthevariablename.Inaddition,youcanusesetonounset
(page327)tocausebashtodisplayanerrorandexitfroma
scriptwheneveranunsetvariableisreferenced.
:UsesaDefaultValue
The:modifierusesadefaultvalueinplaceofanullorunset
variablewhileallowinganonnullvariabletorepresentitself:
${name:default}
Theshellinterprets:as"Ifnameisnullorunset,expand
defaultandusetheexpandedvalueinplaceofname;elseuse
name."Thefollowingcommandliststhecontentsofthe
directorynamedbytheLITvariable.IfLITisnullorunset,it
liststhecontentsof/home/alex/literature:
$ls${LIT:-/home/alex/literature}
Thedefaultcanitselfhavevariablereferencesthatare
expanded:
$ls${LIT:-$HOME/literature}
:=AssignsaDefaultValue
The:modifierdoesnotchangethevalueofavariable.Youmay
wanttochangethevalueofanullorunsetvariabletoits
defaultinascript,however.Youcandosowiththe:=modifier:
${name:=default}
Theshellexpandstheexpression${name:=default}inthe
samemannerasitexpands${name:default}butalsosetsthe
valueofnametotheexpandedvalueofdefault.Ifascript
containsalinesuchasthefollowingandLITisunsetornullat
thetimethislineisexecuted,LITisassignedthevalue
/home/alex/literature:
$ls${LIT:=/home/alex/literature}
:builtin
Shellscriptsfrequentlystartwiththe:(colon)builtinfollowed
onthesamelinebythe:=expansionmodifiertosetany
variablesthatmaybenullorunset.The:builtinevaluateseach
tokenintheremainderofthecommandlinebutdoesnot
executeanycommands.Withouttheleadingcolon(:),theshell
evaluatesandattemptstoexecutethe"command"thatresults
fromtheevaluation.
Usethefollowingsyntaxtosetadefaultforanullorunset
variableinashellscript(thereisaSPACEfollowingthefirst
colon):
:${name:=default}
Whenascriptneedsadirectoryfortemporaryfilesandusesthe
valueofTEMPDIRforthenameofthisdirectory,thefollowing
linemakesTEMPDIRdefaultto/tmp:
:${TEMPDIR:=/tmp}
:?DisplaysanErrorMessage
Sometimesascriptneedsthevalueofavariablebutyoucannot
supplyareasonabledefaultatthetimeyouwritethescript.If
thevariableisnullorunset,the:?modifiercausesthescriptto
displayanerrormessageandterminatewithanexitstatusof
1:
${name:?message}
YoumustquotemessageifitcontainsSPACEs.Ifyouomit
message,theshelldisplaysthedefaulterrormessage
(parameternullornotset).Interactiveshellsdonotexit
whenyouuse:?.Inthefollowingcommand,TESTDIRisnot
setsotheshelldisplaysonstandarderrortheexpandedvalue
ofthestringfollowing:?.Inthiscasethestringincludes
commandsubstitutionfordate,withthe%Tformatbeing
followedbythestringerror,variablenotset.
cd${TESTDIR:?$(date+%T)error,variablenotset.}
bash:TESTDIR:16:16:14error,variablenotset.
BuiltinCommands
BuiltincommandswereintroducedinChapter7.Commands
thatarebuiltintoashelldonotforkanewprocesswhenyou
executethem.Thissectiondiscussesthetype,read,exec,trap,kill,
andgetoptsbuiltinsandconcludeswithTable28-6onpage939,
whichlistsmanybashbuiltins.
type:DisplaysInformationAboutaCommand
Thetypebuiltinprovidesinformationaboutacommand:
$typecatechowhoiflt
catishashed(/bin/cat)
echoisashellbuiltin
whois/usr/bin/who
ifisashellkeyword
ltisaliasedto'ls-ltrh|tail'
Theprecedingoutputshowsthefilesthatwouldbeexecutedif
yougavecatorwhoasacommand.Becausecathasalready
beencalledfromthecurrentshell,itisinthehashtable(page
1034)andtypereportsthatcatishashed.Theoutputalso
showsthatacalltoechorunstheechobuiltin,ifisakeyword,
andltisanalias.
read:AcceptsUserInput
Whenyoubeginwritingshellscripts,yousoonrealizethatone
ofthemostcommontasksforuser-createdvariablesisstoring
informationauserentersinresponsetoaprompt.Usingread,
scriptscanacceptinputfromtheuserandstorethatinputin
variables.Thereadbuiltinreadsonelinefromstandardinput
andassignsthewordsonthelinetooneormorevariables:
$catread1
echo-n"Goahead:"
readfirstline
echo"Youentered:$firstline"
$read1
Goahead:Thisisaline.
Youentered:Thisisaline.
Thefirstlineoftheread1scriptusesechotopromptyouto
enteralineoftext.Thenoptionsuppressesthefollowing
NEWLINE,allowingyoutoenteralineoftextonthesameline
astheprompt.Thesecondlinereadsthetextintothevariable
firstline.Thethirdlineverifiestheactionofreadbydisplaying
thevalueoffirstline.Thevariableisquoted(alongwiththe
textstring)inthisexamplebecauseyou,asthescriptwriter,
cannotanticipatewhichcharacterstheusermightenterin
responsetotheprompt.Considerwhatwouldhappenifthe
variablewerenotquotedandtheuserentered*inresponseto
theprompt:
$catread1_no_quote
echo-n"Goahead:"
readfirstline
echoYouentered:$firstline
$read1_no_quote
Goahead:*
Youentered:read1read1_no_quotescript.1
$ls
read1read1_no_quotescript.1
Thelscommandliststhesamewordsasthescript,
demonstratingthattheshellexpandstheasteriskintoalistof
filesintheworkingdirectory.Whenthevariable$firstlineis
surroundedbydoublequotationmarks,theshelldoesnot
expandtheasterisk.Thustheread1scriptbehavescorrectly:
$read1
Goahead:*
Youentered:*
Ifyouwanttheshelltointerpretthespecialmeaningsofspecial
characters,donotusequotationmarks.
REPLY
Thereadbuiltinhasfeaturesthatcanmakeiteasiertouse.
Whenyoudonotspecifyavariabletoreceiveread'sinput,bash
putstheinputintothevariablenamedREPLY.Youcanusethe
poptiontoprompttheuserinsteadofusingaseparateecho
command.Thefollowingread1ascriptperformsexactlythe
sametaskasread1:
$catread1a
read-p"Goahead:"
echo"Youentered:$REPLY"
Theread2scriptpromptsforacommandlineandreadsthe
user'sresponseintothevariablecmd.Thescriptthenattempts
toexecutethecommandlinethatresultsfromtheexpansionof
thecmdvariable:
$catread2
read-p"Enteracommand:"cmd
$cmd
echo"Thanks"
Inthefollowingexample,read2readsacommandlinethat
callstheechobuiltin.Theshellexecutesthecommandandthen
displaysThanks.Nextread2readsacommandlinethat
executesthewhoutility:
$read2
Enteracommand:echoPleasedisplaythismessage.
Pleasedisplaythismessage.
Thanks
$read2
Enteracommand:who
alexpts/4Jun1707:50(:0.0)
scottpts/12Jun1711:54(bravo.example.com)
Thanks
Ifcmddoesnotexpandintoavalidcommandline,theshell
issuesanerrormessage:
$read2
Enteracommand:xxx
./read2:line2:xxx:commandnotfound
Thanks
Theread3scriptreadsvaluesintothreevariables.Theread
builtinassignsoneword(asequenceofnonblankcharacters)to
eachvariable:
$catread3
read-p"Entersomething:"word1word2word3
echo"Word1is:$word1"
echo"Word2is:$word2"
echo"Word3is:$word3"
$read3
Entersomething:thisissomething
Word1is:this
Word2is:is
Word3is:something
Whenyouentermorewordsthanreadhasvariables,readassigns
onewordtoeachvariable,withallleftoverwordsgoingtothe
lastvariable.Bothread1andread2assignedthefirstword
andallleftoverwordstotheonevariabletheyeachhadtowork
with.Inthefollowingexample,readacceptsfivewordsinto
threevariables,assigningthefirstwordtothefirstvariable,the
secondwordtothesecondvariable,andthethirdthroughfifth
wordstothethirdvariable:
$read3
Entersomething:thisissomethingelse,really.
Word1is:this
Word2is:is
Word3is:somethingelse,really.
Table28-4listssomeoftheoptionssupportedbytheread
builtin.
Table28-4.readoptions
Table28-4.readoptions
Option Function
aaname(array) Assignseachwordofinputtoanelementofarray
aname.
ddelim(delimiter) Usesdelimtoterminatetheinputinsteadof
NEWLINE.
e(Readline) Ifinputiscomingfromakeyboard,usetheReadline
Library(page312)togetinput.
nnum(numberof
characters)
Readsnumcharactersandreturns.Assoonasthe
usertypesnumcharacters,readreturns;thereisno
needtopressRETURN.
pprompt(prompt) Displayspromptonstandarderrorwithouta
terminatingNEWLINEbeforereadinginput.Displays
promptonlywheninputcomesfromthekeyboard.
s(silent) Doesnotechocharacters.
un(filedescriptor) Usestheintegernasthefiledescriptorthatread
takesitsinputfrom.
readu4arg1arg2
isequivalentto
readarg1arg2<&4
See"FileDescriptors"(page911)foradiscussionof
redirectionandfiledescriptors.
Thereadbuiltinreturnsanexitstatusof0ifitsuccessfullyreads
anydata.IthasanonzeroexitstatuswhenitreachestheEOF
(endoffile).Thefollowingexamplerunsawhileloopfromthe
commandline.Ittakesitsinputfromthenamesfileand
terminatesafterreadingthelastlinefromnames.
$catnames
AliceJones
RobertSmith
AlicePaulson
JohnQ.Public
$whilereadfirstrest
>do
>echo$rest,$first
>done<names
Jones,Alice
Smith,Robert
Paulson,Alice
Q.Public,John
$
Theplacementoftheredirectionsymbol(<)forthewhile
structureiscritical.Itisimportantthatyouplacetheredirection
symbolatthedonestatementandnotatthecalltoread.
Optional
Eachtimeyouredirectinput,theshellopenstheinputfileandrepositionsthe
readpointeratthestartofthefile:
$readline1<names;echo$line1;readline2<names;echo$line2
AliceJones
AliceJones
Hereeachreadopensnamesandstartsatthebeginningofthenamesfile.In
thefollowingexample,namesisopenedonce,asstandardinputofthesubshell
createdbytheparentheses.Eachreadthenreadssuccessivelinesofstandard
input.
$(readline1;echo$line1;readline2;echo$line2)<names
AliceJones
RobertSmith
Anotherwaytogetthesameeffectistoopentheinputfilewithexecandholdit
open(referto"FileDescriptors"onpage911):
$exec3<names
$read-u3line1;echo$line1;read-u3line2;echo$line2
AliceJones
RobertSmith
$exec3<&-
exec:ExecutesaCommand
Theexecbuiltinhastwoprimarypurposes:torunacommand
withoutcreatinganewprocessandtoredirectafile
descriptorincludingstandardinput,output,orerrorofashell
scriptfromwithinthescript(page911).Whentheshell
executesacommandthatisnotbuiltintotheshell,ittypically
createsanewprocess.Thenewprocessinheritsenvironment
(globalorexported)variablesfromitsparentbutdoesnot
inheritvariablesthatarenotexportedbytheparent.(Formore
informationreferto"LocalityofVariables"onpage916.)In
contrast,execexecutesacommandinplaceof(overlays)the
currentprocess.
execversus.(dot)
Insofarasexecrunsacommandintheenvironmentofthe
originalprocess,itissimilartothe.(dot)command(page
269).However,unlikethe.command,whichcanrunonlyshell
scripts,execcanrunbothscriptsandcompiledprograms.Also,
whereasthe.commandreturnscontroltotheoriginalscript
whenitfinishesrunning,execdoesnot.Finally,the.command
givesthenewprogramaccesstolocalvariables,whereasexec
doesnot.
execrunsacommand
Theexecbuiltinusedforrunningacommandhasthefollowing
syntax:
execcommandarguments
execdoesnotreturncontrol
Becausetheshelldoesnotcreateanewprocesswhenyouuse
exec,thecommandrunsmorequickly.However,becauseexec
doesnotreturncontroltotheoriginalprogram,itcanbeused
onlyasthelastcommandthatyouwanttoruninascript.The
followingscriptshowsthatcontrolisnotreturnedtothescript:
$catexec_demo
who
execdate
echo"Thislineisneverdisplayed."
$exec_demo
jennypts/7May307:05(bravo.example.com)
hlspts/1May306:59(:0.0)
MonMay3011:42:56PDT2005
Thenextexample,amodifiedversionoftheoutscript(page
883),usesexectoexecutethefinalcommandthescriptruns.
Becauseoutrunseithercatorlessandthenterminates,thenew
version,namedout2,usesexecwithbothcatandless:
$catout2
if[$#-eq0]
then
echo"Usage:out2[-v]filenames"1>&2
exit1
fi
if["$1"="-v"]
then
shift
execless"$@"
else
execcat--"$@"
fi
execredirectsinputandoutput
Thesecondmajoruseofexecistoredirectafile
descriptorincludingstandardinput,output,orerrorfromwithina
script.Thenextcommandcausesallsubsequentinputtoa
scriptthatwouldhavecomefromstandardinputtocomefrom
thefilenamedinfile:
exec<infile
Similarlythefollowingcommandredirectsstandardoutputand
standarderrortooutfileanderrfile,respectively:
exec>outfile2>errfile
Whenyouuseexecinthismanner,thecurrentprocessisnot
replacedwithanewprocess,andexeccanbefollowedbyother
commandsinthescript.
/dev/tty
Whenyouredirecttheoutputfromascripttoafile,youmust
makesurethattheuserseesanypromptsthescriptdisplays.
The/dev/ttydeviceisapseudonymforthescreentheuseris
workingon;youcanusethisdevicetorefertotheuser'sscreen
withoutknowingwhichdeviceitis.(Thettyutilitydisplaysthe
nameofthedeviceyouareusing.)Byredirectingtheoutput
fromascriptto/dev/tty,youensurethatpromptsand
messagesgototheuser'sterminal,regardlessofwhich
terminaltheuserisloggedinon.Messagessentto/dev/tty
arealsonotdivertedifstandardoutputandstandarderrorfrom
thescriptareredirected.
Theto_screen1scriptsendsoutputtothreeplaces:standard
output,standarderror,andtheuser'sscreen.Whenitisrun
withstandardoutputandstandarderrorredirected,
to_screen1stilldisplaysthemessagesentto/dev/ttyonthe
user'sscreen.Theoutanderrfilesholdtheoutputsentto
standardoutputandstandarderror.
$catto_screen1
echo"messagetostandardoutput"
echo"messagetostandarderror"1>&2
echo"messagetotheuser">/dev/tty
$to_screen1>out2>err
messagetotheuser
$catout
messagetostandardoutput
$caterr
messagetostandarderror
Thefollowingcommandredirectstheoutputfromascripttothe
user'sscreen:
exec>/dev/tty
Puttingthiscommandatthebeginningofthepreviousscript
changeswheretheoutputgoes.Into_screen2,execredirects
standardoutputtotheuser'sscreensothe>/dev/ttyis
superfluous.Followingtheexeccommand,alloutputsentto
standardoutputgoesto/dev/tty(thescreen).Outputto
standarderrorisnotaffected.
$catto_screen2
exec>/dev/tty
echo"messagetostandardoutput"
echo"messagetostandarderror"1>&2
echo"messagetotheuser">/dev/tty
$to_screen2>out2>err
messagetostandardoutput
messagetotheuser
Onedisadvantageofusingexectoredirecttheoutputto
/dev/ttyisthatallsubsequentoutputisredirectedunlessyou
useexecagaininthescript.
Youcanalsoredirecttheinputtoread(standardinput)sothatit
comesfrom/dev/tty(thekeyboard):
readname</dev/tty
or
exec</dev/tty
trap:CatchesaSignal
Asignalisareporttoaprocessaboutacondition.Linuxuses
signalstoreportinterruptsgeneratedbytheuser(forexample,
pressingtheinterruptkey)aswellasbadsystemcalls,broken
pipes,illegalinstructions,andotherconditions.Thetrapbuiltin
catches,ortraps,oneormoresignals,allowingyoutodirect
theactionsascripttakeswhenitreceivesaspecifiedsignal.
Thisdiscussioncoverssixsignalsthataresignificantwhenyou
workwithshellscripts.Table28-5liststhesesignals,thesignal
numbersthatsystemsoftenascribetothem,andtheconditions
thatusuallygenerateeachsignal.Givethecommandkilll,
trapl,orman7signalforalistofsignalnames.
Table28-5.Signals
Type Name Number Generatingcondition
Notareal
signal
EXIT 0 Exitbecauseofexitcommandorreachingthe
endoftheprogram(notanactualsignalbut
usefulintrap)
Hangup SIGHUP
orHUP
1 Disconnecttheline
Terminal
interrupt
SIGINTor
INT
2 Presstheinterruptkey(usuallyCONTROL-C)
Quit SIGQUIT
orQUIT
3 Pressthequitkey(usuallyCONTROL-SHIFT-|or
CONTROL-SHIFT-\)
Kill SIGKILL
orKILL
9 Thekillcommandwiththe9option(cannotbe
trapped;useonlyasalastresort)
Software
termination
SIGTERM
orTERM
15 Defaultofthekillcommand
Stop SIGTSTP 20 Pressthesuspendkey(usuallyCONTROL-Z)
orTSTP
Debug DEBUG Executescommandsspecifiedinthetrap
statementaftereachcommand(notanactual
signalbutusefulintrap)
Error ERR Executescommandsspecifiedinthetrap
statementaftereachcommandthatreturnsa
nonzeroexitstatus(notanactualsignalbut
usefulintrap)
Whenittrapsasignal,ascripttakeswhateveractionyou
specify:Itcanremovefilesorfinishanyotherprocessingas
needed,displayamessage,terminateexecutionimmediately,
orignorethesignal.Ifyoudonotusetrapinascript,anyofthe
sixactualsignalslistedinTable28-5(notEXIT,DEBUG,orERR)
terminatesthescript.BecauseaprocesscannottrapaKILL
signal,youcanusekillKILL(orkill9)asalastresortto
terminateascriptoranyotherprocess.(Seepage936formore
informationonkill.)
Thetrapcommandhasthefollowingsyntax:
trap['commands'][signal]
Theoptionalcommandspartspecifiesthecommandsthatthe
shellexecuteswhenitcatchesoneofthesignalsspecifiedby
signal.Thesignalcanbeasignalnameornumberfor
example,INTor2.Ifcommandsisnotpresent,trapresetsthe
traptoitsinitialcondition,whichisusuallytoexitfromthe
script.
Thetrapbuiltindoesnotrequiresinglequotationmarksaround
commandsasshownintheprecedingsyntax,butitisagood
practicetousethem.Thesinglequotationmarkscauseshell
variableswithinthecommandstobeexpandedwhenthe
signaloccurs,notwhentheshellevaluatestheargumentsto
trap.Evenifyoudonotuseanyshellvariablesinthe
commands,youneedtoencloseanycommandthattakes
argumentswithineithersingleordoublequotationmarks.
Quotingthecommandscausestheshelltopasstotrapthe
entirecommandasasingleargument.
Afterexecutingthecommands,theshellresumesexecuting
thescriptwhereitleftoff.Ifyouwanttraptopreventascript
fromexitingwhenitreceivesasignalbutnottorunany
commandsexplicitly,youcanspecifyanull(empty)
commandsstring,asshowninthelockttyscript(page899).
Thefollowingcommandtrapssignalnumber15afterwhichthe
scriptcontinues.
trap''15
Thefollowingscriptdemonstrateshowthetrapbuiltincancatch
theterminalinterruptsignal(2).YoucanuseSIGINT,INT,or2
tospecifythissignal.Thescriptreturnsanexitstatusof1:
$catinter
#!/bin/bash
trap'echoPROGRAMINTERRUPTED;exit1'INT
whiletrue
do
echo"Programrunning."
sleep1
done
$inter
Programrunning.
Programrunning.
Programrunning.
CONTROL-C
PROGRAMINTERRUPTED
$
:(null)builtin
Thesecondlineofintersetsupatrapfortheterminalinterrupt
signalusingINT.Whentrapcatchesthesignal,theshell
executesthetwocommandsbetweenthesinglequotation
marksinthetrapcommand.Theechobuiltindisplaysthe
messagePROGRAMINTERRUPTED,exitterminatestheshell
runningthescript,andtheparentshelldisplaysaprompt.Ifexit
werenotthere,theshellwouldreturncontroltothewhileloop
afterdisplayingthemessage.Thewhilelooprepeats
continuouslyuntilthescriptreceivesasignalbecausethetrue
utilityalwaysreturnsatrueexitstatus.Inplaceoftrueyoucan
usethe:(null)builtin,whichiswrittenasacolonandalways
returnsa0(true)status.
Thetrapbuiltinfrequentlyremovestemporaryfileswhenascript
isterminatedprematurelysothatthefilesarenotlefttoclutter
thefilesystem.Thefollowingshellscript,namedaddbanner,
usestwotrapstoremoveatemporaryfilewhenthescript
terminatesnormallyorowingtoahangup,softwareinterrupt,
quit,orsoftwareterminationsignal:
$cataddbanner
#!/bin/bash
script=$(basename$0)
if[!-r"$HOME/banner"]
then
echo"$script:needreadable$HOME/bannerfile"1>&2
exit1
fi
trap'exit1'12315
trap'rm/tmp/$$.$script2>/dev/null'0
forfile
do
if[-r"$file"-a-w"$file"]
then
cat$HOME/banner$file>/tmp/$$.$script
cp/tmp/$$.$script$file
echo"$script:banneraddedto$file"1>&2
else
echo"$script:needreadandwritepermissionfor$file"1>&2
fi
done
Whencalledwithoneormorefilenamearguments,addbanner
loopsthroughthefiles,addingaheadertothetopofeach.This
scriptisusefulwhenyouuseastandardformatatthetopof
yourdocuments,suchasastandardlayoutformemos,orwhen
youwanttoaddastandardheadertoshellscripts.Theheader
iskeptinafilenamed~/banner.Becauseaddbanneruses
theHOMEvariable,whichcontainsthepathnameoftheuser's
homedirectory,thescriptcanbeusedbyseveraluserswithout
modification.IfAlexhadwrittenthescriptwith/home/alexin
placeof$HOMEandthengiventhescripttoJenny,eithershe
wouldhavehadtochangeitoraddbannerwouldhaveused
Alex'sbannerfilewhenJennyranit(assumingJennyhadread
permissionforthefile).
Thefirsttrapinaddbannercausesittoexitwithastatusof1
whenitreceivesahangup,softwareinterrupt(terminal
interruptorquitsignal),orsoftwareterminationsignal.The
secondtrapusesa0inplaceofsignal-number,whichcauses
traptoexecuteitscommandargumentwheneverthescriptexits
becauseitreceivesanexitcommandorreachesitsend.
Togetherthesetrapsremoveatemporaryfilewhetherthescript
terminatesnormallyorprematurely.Standarderrorofthe
secondtrapissentto/dev/nullforcasesinwhichtrapattempts
toremoveanonexistenttemporaryfile.Inthosecasesrmsends
anerrormessagetostandarderror;becausestandarderroris
redirected,theuserdoesnotseethismessage.
Seepage899foranotherexamplethatusestrap.
kill:AbortsaProcess
Thekillbuiltinsendsasignaltoaprocessorjob.Thekill
commandhasthefollowingsyntax:
kill[signal]PID
wheresignalisthesignalnameornumber(forexample,INT
or2)andPIDistheprocessidentificationnumberofthe
processthatistoreceivethesignal.Youcanspecifyajob
number(page219)as%ninplaceofPID.Ifyouomitsignal,
killsendsaTERM(softwaretermination,number15)signal.For
moreinformationonsignalnamesandnumbersseeTable28-5
onpage933.
ThefollowingcommandsendstheTERMsignaltojobnumber
1:
$kill-TERM%1
BecauseTERMisthedefaultsignalforkill,youcanalsogive
thiscommandaskill%1.Givethecommandkilll(lowercase
"l")todisplayalistofsignalnames.
Aprogramthatisinterruptedoftenleavesmattersinan
unpredictablestate:Temporaryfilesmaybeleftbehind(when
theyarenormallyremoved),andpermissionsmaybechanged.
Awell-writtenapplicationtraps,ordetects,signalsandcleans
upbeforeexiting.Mostcarefullywrittenapplicationstrapthe
INT,QUIT,andTERMsignals.
Toterminateaprogram,firsttryINT(pressCONTROL-C,ifthe
jobisintheforeground).Becauseanapplicationcanbewritten
toignorethesesignals,youmayneedtousetheKILLsignal,
whichcannotbetrappedorignored;itisa"surekill.".Formore
informationreferto"kill:SendsaSignaltoaProcess"onpage
395.
getopts:ParsesOptions
Thegetoptsbuiltinparsescommandlinearguments,thereby
makingiteasiertowriteprogramsthatfollowtheLinux
argumentconventions.Thesyntaxforgetoptsis
getoptsoptstringvarname[arg...]
whereoptstringisalistofthevalidoptionletters,varnameis
thevariablethatreceivestheoptionsoneatatime,andargis
theoptionallistofparameterstobeprocessed.Ifargisnot
present,getoptsprocessesthecommandlinearguments.If
optstringstartswithacolon(:),thescripttakescareof
generatingerrormessages;otherwise,getoptsgenerateserror
messages.
ThegetoptsbuiltinusestheOPTIND(optionindex)and
OPTARG(optionargument)variablestostoreoption-related
values.Whenashellscriptstarts,thevalueofOPTINDis1.
Eachtimegetoptslocatesanargument,itincrementsOPTINDto
theindexofthenextoptiontobeprocessed.Iftheoptiontakes
anargument,bashassignsthevalueoftheargumentto
OPTARG.
Toindicatethatanoptiontakesanargument,followthe
correspondingletterinoptstringwithacolon(:).Theoption
stringdxo:lt:rindicatesthatgetoptsshouldsearchford,x,o,l,
t,androptionsandthattheoandtoptionstakearguments.
Usinggetoptsasthetest-commandinawhilecontrolstructure
allowsyoutoloopovertheoptionsoneatatime.Thegetopts
builtincheckstheoptionlistforoptionsthatareinoptstring.
Eachtimethroughtheloop,getoptsstorestheoptionletterit
findsinvarname.
Supposethatyouwanttowriteaprogramthatcantakethree
options:
1. Aboptionindicatesthattheprogramshouldignore
whitespaceatthestartofinputlines.
2. Atoptionfollowedbythenameofadirectoryindicatesthat
theprogramshouldusethatdirectoryfortemporaryfiles.
Otherwise,itshoulduse/tmp.
3. Auoptionindicatesthattheprogramshouldtranslateallits
outputtouppercase.
Inaddition,theprogramshouldignoreallotheroptionsandend
optionprocessingwhenitencounterstwohyphens().
Theproblemistowritetheportionoftheprogramthat
determineswhichoptionstheuserhassupplied.Thefollowing
solutiondoesnotusegetopts:
SKIPBLANKS=
TMPDIR=/tmp
CASE=lower
while[["$1"=-*]]#[[=]]doespatternmatch
do
case$1in
-b)SKIPBLANKS=TRUE;;
-t)if[-d"$2"]
then
TMPDIR=$2
shift
else
echo"$0:-ttakesadirectoryargument.">&2
exit1
fi;;
-u)CASE=upper;;
--)break;;#Stopprocessingoptions
*)echo"$0:Invalidoption$1ignored.">&2;;
esac
shift
done
Thisprogramfragmentusesalooptocheckandshiftarguments
whiletheargumentisnot.Aslongastheargumentisnottwo
hyphens,theprogramcontinuestoloopthroughacase
statementthatchecksforpossibleoptions.Thecaselabel
breaksoutofthewhileloop.The*caselabelrecognizesany
option;itappearsasthelastcaselabeltocatchanyunknown
options,displaysanerrormessage,andallowsprocessingto
continue.Oneachpassthroughtheloop,theprogramdoesa
shifttogettothenextargument.Ifanoptiontakesan
argument,theprogramdoesanextrashifttogetpastthat
argument.
Thefollowingprogramfragmentprocessesthesameoptions,
butusesgetopts:
SKIPBLANKS=
TMPDIR=/tmp
CASE=lower
whilegetopts:bt:uarg
do
case$argin
b)SKIPBLANKS=TRUE;;
t)if[-d"$OPTARG"]
then
TMPDIR=$OPTARG
else
echo"$0:$OPTARGisnotadirectory.">&2
exit1
fi;;
u)CASE=upper;;
:)echo"$0:Mustsupplyanargumentto-$OPTARG.">&2
exit1;;
\?)echo"Invalidoption-$OPTARGignored.">&2;;
esac
done
Inthisversionofthecode,thewhilestructureevaluatesthe
getoptsbuiltineachtimeitcomestothetopoftheloop.The
getoptsbuiltinusestheOPTINDvariabletokeeptrackofthe
indexoftheargumentitistoprocessthenexttimeitiscalled.
Thereisnoneedtocallshiftinthisexample.
Inthegetoptsversionofthescriptthecasepatternsdonotstart
withahyphenbecausethevalueofargisjusttheoptionletter
(getoptsstripsoffthehyphen).Also,getoptsrecognizesastheend
oftheoptions,soyoudonothavetospecifyitexplicitlyasin
thecasestatementinthefirstexample.
Becauseyoutellgetoptswhichoptionsarevalidandwhich
requirearguments,itcandetecterrorsinthecommandlineand
handlethemintwoways.Thisexampleusesaleadingcolonin
optstringtospecifythatyoucheckforandhandleerrorsin
yourcode;whengetoptsfindsaninvalidoption,itsetsvarname
to?andOPTARGtotheoptionletter.Whenitfindsanoption
thatismissinganargument,getoptssetsvarnameto:and
OPTARGtotheoptionlackinganargument.
The\?casepatternspecifiestheactiontotakewhengetopts
detectsaninvalidoption.The:casepatternspecifiestheaction
totakewhengetoptsdetectsamissingoptionargument.Inboth
casesgetoptsdoesnotwriteanyerrormessage;itleavesthat
tasktoyou.
Ifyouomittheleadingcolonfromoptstring,bothaninvalid
optionandamissingoptionargumentcausevarnametobe
assignedthestring?.OPTARGisnotsetandgetoptswritesits
owndiagnosticmessagetostandarderror.Generallythis
methodislessdesirablebecauseyouhavelesscontrolover
whattheuserseeswhenanerrorismade.
Usinggetoptswillnotnecessarilymakeyourprogramsshorter.
Itsprincipaladvantagesarethatitprovidesauniform
programminginterfaceanditenforcesstandardoption
handling.
APartialListofBuiltins
Table28-6listssomeofthebashbuiltins.See"Listingbash
builtins"onpage225forinstructionsonhowtodisplay
completelistsofbuiltins.
Table28-6.bashbuiltins
Builtin Function
:Returns0ortrue(thenullbuiltin;page935)
.(dot) Executesashellscriptaspartofthecurrentprocess(page
269)
bg Putsasuspendedjobinthebackground(page281)
break Exitsfromaloopingcontrolstructure(page900)
cd Changestoanotherworkingdirectory(page174)
continue Startswiththenextiterationofaloopingcontrolstructure
(page900)
echo Displaysitsarguments(page137)
eval Scansandevaluatesthecommandline(page323)
exec Executesashellscriptorprograminplaceofthecurrent
process(page930)
exit Exitsfromthecurrentshell(usuallythesameasCONTROL-
Dfromaninteractiveshell;page920)
export Placesthevalueofavariableinthecallingenvironment
(makesitglobal;page916)
fg Bringsajobfromthebackgroundintotheforeground
(page280)
getopts Parsesargumentstoashellscript(page936)
jobs Displayslistofbackgroundjobs(page280)
kill Sendsasignaltoaprocessorjob(page395)
pwd Displaysthenameoftheworkingdirectory(page170)
read Readsalinefromstandardinput(page927)
readonly Declaresavariabletobereadonly(page289)
set Setsshellflagsorcommandlineargumentvariables;with
noargument,listsallvariables(pages325and924)
shift Promoteseachcommandlineargument(page923)
test Comparesarguments(page879)
times Displaystotaltimesforthecurrentshellanditschildren
trap Trapsasignal(page933)
type Displayshoweachargumentwouldbeinterpretedasa
command(page927)
umask Returnsthevalueofthefile-creationmask(page420)
unset Removesavariableorfunction(page289)
wait Waitsforabackgroundprocesstoterminate
Expressions
Anexpressioniscomposedofconstants,variables,and
operatorsthatcanbeprocessedtoreturnavalue.Thissection
coversarithmetic,logical,andconditionalexpressionsaswellas
operators.Table28-8onpage943liststhebashoperators.
ArithmeticEvaluation
TheBourneAgainShellcanperformarithmeticassignmentsand
evaluatemanydifferenttypesofarithmeticexpressions,all
usingintegers.Theshellperformsarithmeticassignmentsina
numberofways.Oneiswithargumentstotheletbuiltin:
$let"VALUE=VALUE*10+NEW"
Intheprecedingexample,thevariablesVALUEandNEW
containintegervalues.Withinaletstatementyoudonotneed
tousedollarsigns($)infrontofvariablenames.Double
quotationmarksmustencloseasingleargument,orexpression,
thatcontainsSPACEs.BecausemostexpressionscontainSPACEs
andneedtobequoted,bashaccepts((expression))asa
synonymforlet"expression",obviatingtheneedforboth
quotationmarksanddollarsigns:
$((VALUE=VALUE*10+NEW))
Youcanuseeitherformwhereveracommandisallowedand
canremovetheSPACEsifyoulike.Inthefollowingexample,the
asterisk(*)doesnotneedtobequotedbecausetheshelldoes
notperformpathnameexpansionontherightsideofan
assignment(page288):
$letVALUE=VALUE*10+NEW
Becauseeachargumenttoletisevaluatedasaseparate
expression,youcanassignvaluestomorethanonevariableon
asingleline:
$let"COUNT=COUNT+1"VALUE=VALUE*10+NEW
Youneedtousecommastoseparatemultipleassignments
withinasetofdoubleparentheses:
$((COUNT=COUNT+1,VALUE=VALUE*10+NEW))
Tip:Arithmeticevaluationversus
arithmeticexpansion
Arithmeticevaluationdiffersfromarithmetic
expansion.Asexplainedonpage332,arithmetic
expansionusesthesyntax$((expression)),
evaluatesexpression,andreplaces
$((expression))withtheresult.Youcanuse
arithmeticexpansiontodisplaythevalueofan
expressionortoassignthatvaluetoavariable.
Arithmeticevaluationusestheletexpressionor
((expression))syntax,evaluatesexpression,and
returnsastatuscode.Youcanusearithmetic
evaluationtoperformalogicalcomparisonoran
assignment.
Logicalexpressions
Youcanusethe((expression))syntaxforlogicalexpressions,
althoughthattaskisfrequentlyleftto[[expression]].The
nextexampleexpandstheage_checkscript(page332)to
includelogicalarithmeticevaluationinadditiontoarithmetic
expansion:
$catage2
#!/bin/bash
echo-n"Howoldareyou?"
readage
if((30<age&&age<60));then
echo"Wow,in$((60-age))years,you'llbe60!"
else
echo"Youaretooyoungortoooldtoplay."
fi
$age2
Howoldareyou?25
Youaretooyoungortoooldtoplay.
Thetest-statementfortheifstructureevaluatestwological
comparisonsjoinedbyaBooleanANDandreturns0(true)if
theyarebothtrueor1(false)otherwise.
LogicalEvaluation(ConditionalExpressions)
Thesyntaxofaconditionalexpressionis
[[expression]]
whereexpressionisaBoolean(logical)expression.Youmust
precedeavariablenamewithadollarsign($)within
expression.Theresultofexecutingthisbuiltin,likethetest
builtin,isareturnstatus.Theconditionsallowedwithinthe
bracketsarealmostasupersetofthoseacceptedbytest(page
879).WherethetestbuiltinusesaasaBooleanANDoperator,
[[expression]]uses&&.Similarly,wheretestusesoasa
BooleanORoperator,[[expression]]uses||.
Youcanreplacethelinethattestsageintheage2script
(preceding)withthefollowingconditionalexpression.Youmust
surroundthe[[and]]tokenswithwhitespaceoracommand
terminator,andplacedollarsignsbeforethevariables:
if[[30<$age&&$age<60]];then
Youcanalsousetest'srelationaloperatorsgt,ge,lt,le,eq,
andne:
if[[30-lt$age&&$age-lt60]];then
Stringcomparisons
Thetestbuiltintestswhetherstringsareequalorunequal.The
[[expression]]syntaxaddscomparisontestsforstring
operators.The>and<operatorscomparestringsfororder
(forexample,"aa"<"bbb").The=operatortestsforpattern
match,notjustequality:[[string=pattern]]istrueifstring
matchespattern.Thisoperatorisnotsymmetrical;the
patternmustappearontherightsideoftheequalsign.For
example,[[artist=a*]]istrue(=0),whereas[[a*=artist
]]isfalse(=1):
$[[artist=a*]]
$echo$?
0
$[[a*=artist]]
$echo$?
1
Thenextexampleusesacommandlistthatstartswitha
compoundcondition.Theconditionteststhatthedirectorybin
andthefilesrc/myscript.bashexist.Ifthisistrue,cpcopies
src/myscript.bashtobin/myscript.Ifthecopysucceeds,
chmodmakesmyscriptexecutable.Ifanyofthesestepsfails,
echodisplaysamessage.
$[[-dbin&&-fsrc/myscript.bash]]&&cpsrc/myscript.bash\
bin/myscript&&chmod+xbin/myscript||echo"Cannotmake\
executableversionofmyscript"
StringPatternMatching
TheBourneAgainShellprovidesstringpattern-matching
operatorsthatcanmanipulatepathnamesandotherstrings.
Theseoperatorscandeletefromstringsprefixesorsuffixesthat
matchpatterns.ThefouroperatorsarelistedinTable28-7.
Table28-7.Stringoperators
Operator Function
#Removesminimalmatchingprefixes
## Removesmaximalmatchingprefixes
%Removesminimalmatchingsuffixes
%% Removesmaximalmatchingsuffixes
Thesyntaxfortheseoperatorsis
${varnameoppattern}
whereopisoneoftheoperatorslistedinTable28-7and
patternisamatchpatternsimilartothatusedforfilename
generation.Theseoperatorsarecommonlyusedtomanipulate
pathnamessoastoextractorremovecomponentsortochange
suffixes:
$SOURCEFILE=/usr/local/src/prog.c
$echo${SOURCEFILE#/*/}
local/src/prog.c
$echo${SOURCEFILE##/*/}
prog.c
$echo${SOURCEFILE%/*}
/usr/local/src
$echo${SOURCEFILE%%/*}
$echo${SOURCEFILE%.c}
/usr/local/src/prog
$CHOPFIRST=${SOURCEFILE#/*/}
$echo$CHOPFIRST
local/src/prog.c
$NEXT=${CHOPFIRST%%/*}
$echo$NEXT
local
Herethestring-lengthoperator,${#name},isreplacedbythe
numberofcharactersinthevalueofname:
$echo$SOURCEFILE
/usr/local/src/prog.c
$echo${#SOURCEFILE}
21
Operators
Arithmeticexpansionandarithmeticevaluationusethesame
syntax,precedence,andassociativityofexpressionsastheC
language.Table28-8listsoperatorsinorderofdecreasing
precedence(priorityofevaluation);eachgroupofoperatorshas
equalprecedence.Withinanexpressionyoucanuse
parenthesestochangetheorderofevaluation.
Table28-8.Operators
Typeof
operator/operator Function
Post
var++Postincrement
varPostdecrement
Pre
++varPreincrement
varPredecrement
Unary
Unaryminus
+Unaryplus
Negation
!BooleanNOT(logicalnegation)
~Complement(bitwisenegation)
Exponentiation
**Exponent
Multiplication,
division,remainder
*Multiplication
/Division
%Remainder
Addition,subtraction
Subtraction
+Addition
Bitwiseshifts
<<Leftbitwiseshift
>>Rightbitwiseshift
Comparison
<=Lessthanorequal
>=Greaterthanorequal
<Lessthan
>Greaterthan
Equality,inequality
==Equality
!=Inequality
Bitwise
&BitwiseAND
^BitwiseXOR(exclusiveOR)
|BitwiseOR
Boolean(logical)
&&BooleanAND
||BooleanOR
Conditional
evaluation
?:Ternaryoperator
Assignment
=,*=,/=,%=,+=,-=,<<=,>>=,&=,^=,|=Assignment
Comma
,Comma
Pipe
Thepipetokenhashigherprecedencethanoperators.Youcan
usepipesanywhereinacommandthatyoucanusesimple
commands.Forexample,thecommandline
$cmd1|cmd2||cmd3|cmd4&&cmd5|cmd6
isinterpretedasifyouhadtyped
$((cmd1|cmd2)||(cmd3|cmd4))&&(cmd5|cmd6)
Tip:Donotrelyonrulesofprecedence:
useparentheses
Donotrelyontheprecedenceruleswhenyouuse
compoundcommands.Instead,useparenthesesto
explicitlystatetheorderinwhichyouwanttheshell
tointerpretthecommands.
Incrementanddecrementoperators
Thepostincrement,postdecrement,preincrement,and
predecrementoperatorsworkwithvariables.Thepre-
operators,whichappearinfrontofthevariablenameasin
++COUNTandVALUE,firstchangethevalueofthevariable
(++adds1;subtracts1)andthenprovidetheresultforusein
theexpression.Thepost-operatorsappearafterthevariable
nameasinCOUNT++andVALUE;theyfirstprovidethe
unchangedvalueofthevariableforuseintheexpressionand
thenchangethevalueofthevariable.
$N=10
$echo$N
10
$echo$((--N+3))
12
$echo$N
9
$echo$((N++-3))
6
$echo$N
10
Remainder
Theremainderoperator(%)givestheremainderwhenitsfirst
operandisdividedbyitssecond.Forexample,theexpression
$((15%7))hasthevalue1.
Boolean
TheresultofaBooleanoperationiseither0(false)or1(true).
The&&(AND)and||(OR)Booleanoperatorsarecalledshort-
circuitingoperators.Iftheresultofusingoneoftheseoperators
canbedecidedbylookingonlyattheleftoperand,theright
operandisnotevaluated.The&&operatorcausestheshellto
testtheexitstatusofthecommandprecedingit.Ifthe
commandsucceeded,bashexecutesthenextcommand;
otherwise,itskipstheremainingcommandsonthecommand
line.Youcanusethisconstructtoexecutecommands
conditionally:
$mkdirbkup&&cp-rsrcbkup
Thiscompoundcommandcreatesthedirectorybkup.Ifmkdir
succeeds,thecontentsofdirectorysrciscopiedrecursivelyto
bkup.
The||separatoralsocausesbashtotesttheexitstatusofthe
firstcommandbuthastheoppositeeffect:Theremaining
command(s)areexecutedonlyifthefirstonefailed(thatis,
exitedwithnonzerostatus):
$mkdirbkup||echo"mkdirofbkupfailed">>/tmp/log
Theexitstatusofacommandlististheexitstatusofthelast
commandinthelist.Youcangrouplistswithparentheses.For
example,youcouldcombinetheprevioustwoexamplesas
$(mkdirbkup&&cp-rsrcbkup)||echo"mkdirfailed">>/tmp/log
Intheabsenceofparentheses,&&and||haveequal
precedenceandaregroupedfromlefttoright.Thefollowing
examplesusethetrueandfalseutilities.Theseutilitiesdo
nothingandreturntrue(0)andfalse(1)exitstatuses,
respectively:
$false;echo$?
1
The$?variableholdstheexitstatusoftheprecedingcommand
(page920).Thenexttwocommandsyieldanexitstatusof1
(false):
$true||false&&false
$echo$?
1
$(true||false)&&false
$echo$?
1
Similarlythenexttwocommandsyieldanexitstatusof0
(true):
$false&&false||true
$echo$?
0
$(false&&false)||true
$echo$?
0
Because||and&&haveequalprecedence,theparenthesesin
thetwoprecedingpairsofexamplesdonothingtochangethe
orderofoperations.
Becausetheexpressionontherightsideofashort-circuiting
operatormaynevergetexecuted,youmustbecarefulwith
assignmentstatementsinthatlocation.Thefollowingexample
demonstrateswhatcanhappen:
$((N=10,Z=0))
$echo$((N||((Z+=1))))
1
$echo$Z
0
BecausethevalueofNisnonzero,theresultofthe||(OR)
operationis1(true),nomatterwhatthevalueoftherightside
is.Asaconsequence((Z+=1))isneverevaluatedandZisnot
incremented.
Ternary
Theternaryoperator,?:,decideswhichoftwoexpressions
shouldbeevaluated,basedonthevaluereturnedfromathird
expression:
expression1?expression2:expression3
Ifexpression1producesafalse(0)value,expression3is
evaluated;otherwise,expression2isevaluated.Thevalueof
theentireexpressionisthevalueofexpression2or
expression3,dependingonwhichoneisevaluated.If
expression1istrue,expression3isnotevaluated.If
expression1isfalseexpression2isnotevaluated:
$((N=10,Z=0,COUNT=1))
$((T=N>COUNT?++Z:--Z))
$echo$T
1
$echo$Z
1
Assignment
Theassignmentoperators,suchas+=,areshorthand
notations.Forexample,N+=3isthesameas((N=N+3)).
Otherbases
Thefollowingcommandsusethesyntaxbase#ntoassignbase
2(binary)values.Firstv1isassignedavalueof0101(5
decimal)andv2isassignedavalueof0110(6decimal).The
echoutilityverifiesthedecimalvalues.
$((v1=2#0101))
$((v2=2#0110))
$echo"$v1and$v2"
5and6
NextthebitwiseANDoperator(&)selectsthebitsthatareon
inboth5(0101binary)and6(0110binary).Theresultis
binary0100,whichis4decimal.
$echo$((v1&v2))
4
TheBooleanANDoperator(&&)producesaresultof1ifboth
ofitsoperandsarenonzeroandaresultof0otherwise.The
bitwiseinclusiveORoperator(|)selectsthebitsthatareonin
either0101or0110,resultingin0111,whichis7decimal.The
BooleanORoperator(||)producesaresultof1ifeitherofits
operandsisnonzeroandaresultof0otherwise.
$echo$((v1&&v2))
1
$echo$((v1|v2))
7
$echo$((v1||v2))
1
NextthebitwiseexclusiveORoperator(^)selectsthebitsthat
areonineither,butnotboth,oftheoperands0101and0110,
yielding0011,whichis3decimal.TheBooleanNOToperator(!)
producesaresultof1ifitsoperandis0andaresultof0
otherwise.Becausetheexclamationpointin$((!v1))is
enclosedwithindoubleparentheses,itdoesnotneedtobe
escapedtopreventtheshellfrominterpretingtheexclamation
pointasahistoryevent.Thecomparisonoperatorsproducea
resultof1ifthecomparisonistrueandaresultof0otherwise.
$echo$((v1^v2))
3
$echo$((!v1))
0
$echo$((v1<v2))
1
$echo$((v1<v2))
0
ShellPrograms
TheBourneAgainShellhasmanyfeaturesthatmakeitagood
programminglanguage.Thestructuresthatbashprovidesare
notarandomassortment.Rather,theyhavebeenchosento
providemostofthestructuralfeaturesthatareinother
procedurallanguages,suchasCorPascal.Aprocedural
languageprovidestheabilityto
Declare,assign,andmanipulatevariablesandconstant
data.TheBourneAgainShellprovidesstringvariables,
togetherwithpowerfulstringoperators,andinteger
variables,alongwithacompletesetofarithmeticoperators.
Breaklargeproblemsintosmallonesbycreating
subprograms.TheBourneAgainShellallowsyoutocreate
functionsandcallscriptsfromotherscripts.Shellfunctions
canbecalledrecursively;thatis,aBourneAgainShell
functioncancallitself.Youmaynotneedtouserecursion
often,butitmayallowyoutosolvesomeapparently
difficultproblemswithease.
Executestatementsconditionally,usingstatementssuchas
if.
Executestatementsiteratively,usingstatementssuchas
whileandfor.
Transferdatatoandfromtheprogram,communicatingwith
bothdatafilesandusers.
Programminglanguagesimplementthesecapabilitiesin
differentwaysbutwiththesameideasinmind.Whenyouwant
tosolveaproblembywritingaprogram,youmustfirstfigure
outaprocedurethatleadsyoutoasolutionthatis,an
algorithm.Typicallyyoucanimplementthesamealgorithmin
roughlythesamewayindifferentprogramminglanguages,
usingthesamekindsofconstructsineachlanguage.
Chapter9andthischapterhaveintroducednumerousbash
features,manyofwhichareusefulforinteractiveuseaswellas
forshellprogramming.Thissectiondevelopstwocompleteshell
programs,demonstratinghowtocombinesomeofthese
featureseffectively.Theprogramsarepresentedasproblems
foryoutosolvealongwithsamplesolutions.
ARecursiveShellScript
Arecursiveconstructisonethatisdefinedintermsofitself.
Alternatively,youmightsaythatarecursiveprogramisone
thatcancallitself.Thismayseemcircular,butitneednotbe.
Toavoidcircularityarecursivedefinitionmusthaveaspecial
casethatisnotself-referential.Recursiveideasoccurin
everydaylife.Forexample,youcandefineanancestorasyour
mother,yourfather,oroneoftheirancestors.Thisdefinitionis
notcircular;itspecifiesunambiguouslywhoyourancestorsare:
yourmotheroryourfather,oryourmother'smotherorfather
oryourfather'smotherorfather,andsoon.
AnumberofLinuxsystemutilitiescanoperaterecursively.See
theRoptiontothechmod,chown,andcputilitiesforexamples.
Solvethefollowingproblembyusingarecursiveshell
function:
Writeashellfunctionnamedmakepaththat,givenapathname,
createsallcomponentsinthatpathnameasdirectories.Forexample,
thecommandmakepatha/b/c/dshouldcreatedirectoriesa,a/b,
a/b/c,anda/b/c/d.(Themkdirutilitysupportsapoptionthatdoes
exactlythis.Solvetheproblemwithoutusingmkdirp.)
Onealgorithmforarecursivesolutionfollows:
1. Examinethepathargument.Ifitisanullstringorifit
namesanexistingdirectory,donothingandreturn.
2. Ifitisasimplepathcomponent,createit(usingmkdir)and
return.
3. Otherwise,callmakepathusingthepathprefixofthe
originalargument.Thisstepeventuallycreatesallthe
directoriesuptothelastcomponent,whichyoucanthen
createwithmkdir.
Ingeneral,arecursivefunctionmustinvokeitselfwithasimpler
versionoftheproblemthanitwasgivenuntilitisfinallycalled
withasimplecasethatdoesnotneedtocallitself.Followingis
onepossiblesolutionbasedonthisalgorithm:
makepath
#thisisafunction
#enteritatthekeyboard,donotrunitasashellscript
#
functionmakepath()
{
if[[${#1}-eq0||-d"$1"]]
then
return0#Donothing
fi
if[["${1%/*}"="$1"]]
then
mkdir$1
return$?
fi
makepath${1%/*}||return1
mkdir$1
return$?
}
Inthetestforasimplecomponent(theifstatementinthe
middleofthefunction),theleftexpressionistheargument
aftertheshortestsuffixthatstartswitha/characterhasbeen
strippedaway(page942).Ifthereisnosuchcharacter(for
example,if$1isalex),nothingisstrippedoffandthetwo
sidesareequal.Iftheargumentisasimplefilenamepreceded
byaslash,suchas/usr,theexpression${1%/*}evaluates
toanullstring.Tomakethefunctionworkinthiscase,you
musttaketwoprecautions:Puttheleftexpressionwithin
quotationmarksandensurethattherecursivefunctionbehaves
sensiblywhenitispassedanullstringasanargument.In
general,goodprogramsarerobust:Theyshouldbeprepared
forborderline,invalid,ormeaninglessinputandbehave
appropriatelyinsuchcases.
Bygivingthefollowingcommandfromtheshellyouare
workingin,youturnondebuggingtracingsothatyoucan
watchtherecursionwork:
$set-oxtrace
(Givethesamecommand,butreplacethehyphenwithaplus
sign(+)toturndebuggingoff.)Withdebuggingturnedon,the
shelldisplayseachlineinitsexpandedformasitexecutesthe
line.A+precedeseachlineofdebuggingoutput.Inthe
followingexample,thefirstlinethatstartswith+showsthe
shellcallingmakepath.Themakepathfunctioniscalledfrom
thecommandlinewithargumentsofa/b/c.Subsequentlyit
callsitselfwithargumentsofa/bandfinallya.Alltheworkis
done(usingmkdir)aseachcalltomakepathreturns.
$makepatha/b/c
+makepatha/b/c
+[[5-eq0]]
+[[-da/b/c]]
+[[a/b=\a\/\b\/\c]]
+makepatha/b
+[[3-eq0]]
+[[-da/b]]
+[[a=\a\/\b]]
+makepatha
+[[1-eq0]]
+[[-da]]
+[[a=\a]]
+mkdira
+return0
+mkdira/b
+return0
+mkdira/b/c
+return0
Thefunctionworksitswaydowntherecursivepathandbackup
again.
Itisinstructivetoinvokemakepathwithaninvalidpathand
seewhathappens.Thefollowingexample,runwithdebugging
turnedon,triestocreatethepath/a/b,whichrequiresthat
youcreatedirectoryaintherootdirectory.Unlessyouhave
permissiontowritetotherootdirectory,youarenotpermitted
tocreatethisdirectory.
$makepath/a/b
+makepath/a/b
+[[4-eq0]]
+[[-d/a/b]]
+[[/a=\/\a\/\b]]
+makepath/a
+[[2-eq0]]
+[[-d/a]]
+[[''=\/\a]]
+makepath
+[[0-eq0]]
+return0
+mkdir/a
mkdir:cannotcreatedirectory'/a':Permissiondenied
+return1
+return1
Therecursionstopswhenmakepathisdeniedpermissionto
createthe/adirectory.Theerrorreturnispassedalltheway
back,sotheoriginalmakepathexitswithnonzerostatus.
Tip:Uselocalvariableswithrecursive
functions
Theprecedingexampleglossedoverapotential
problemthatyoumayencounterwhenyouusea
recursivefunction.Duringtheexecutionofa
recursivefunction,manyseparateinstancesofthat
functionmaybeactivesimultaneously.Allbutoneof
themarewaitingfortheirchildinvocationto
complete.
Becausefunctionsruninthesameenvironmentas
theshellthatcallsthem,variablesareimplicitly
sharedbyashellandafunctionitcallssothatall
instancesofthefunctionshareasinglecopyofeach
variable.Sharingvariablescangiverisetoside
effectsthatarerarelywhatyouwant.Asarule,you
shouldusetypesettomakeallvariablesofarecursive
functionbelocalvariables.Seepage917formore
information.
ThequizShellScript
Solvethefollowingproblemusingabashscript:
Writeagenericmultiple-choicequizprogram.Theprogramshouldget
itsquestionsfromdatafiles,presentthemtotheuser,andkeeptrack
ofthenumberofcorrectandincorrectanswers.Theusermustbe
abletoexitfromtheprogramatanytimewithasummaryofresults
tothatpoint.
Thedetaileddesignofthisprogramandeventhedetailed
descriptionoftheproblemdependonanumberofchoices:How
willtheprogramknowwhichsubjectsareavailableforquizzes?
Howwilltheuserchooseasubject?Howwilltheprogramknow
whenthequizisover?Shouldtheprogrampresentthesame
questions(foragivensubject)inthesameordereachtime,or
shoulditscramblethem?
Ofcourse,youcanmakemanyperfectlygoodchoicesthat
implementthespecificationoftheproblem.Thefollowing
detailsnarrowtheproblemspecification:
Eachsubjectwillcorrespondtoasubdirectoryofamaster
quizdirectory.Thisdirectorywillbenamedinthe
environmentvariableQUIZDIR,whosedefaultwillbe
~/quiz.Forexample,youcouldhavethefollowing
directoriescorrespondtothesubjectsengineering,art,and
politics:~/quiz/engineering,~/quiz/art,and
~/quiz/politics.Putthequizdirectoryin/usr/gamesif
youwantalluserstohaveaccesstoit(requiresroot
privileges).
Eachsubjectcanhaveseveralquestions.Eachquestionis
representedbyafileinitssubject'sdirectory.
Thefirstlineofeachfilethatrepresentsaquestionisthe
textofthequestion.Ifittakesmorethanoneline,you
mustescapetheNEWLINEwithabackslash.(Thissetup
makesiteasytoreadasinglequestionwiththeread
builtin.)Thesecondlineofthefileisanintegerthat
specifiesthenumberofchoices.Thenextlinesarethe
choicesthemselves.Thelastlineisthecorrectanswer.
Followingisasamplequestionfile:
Whodiscoveredtheprincipleofthelever?
4
Euclid
Archimedes
ThomasEdison
TheLeverBrothers
Archimedes
Theprogrampresentsallthequestionsinasubject
directory.Atanypointtheusercaninterruptthequizwith
CONTROL-C,whereupontheprogramwillsummarizethe
resultssofarandexit.Iftheuserdoesnotinterrupt,the
programsummarizestheresultsandexitswhenithas
askedallquestionsforthechosensubject.
Theprogramscramblesthequestionsinasubjectbefore
presentingthem.
Followingisatop-leveldesignforthisprogram:
1. Initialize.Thisinvolvesanumberofsteps,suchassetting
thecountsofthenumberofquestionsaskedsofarandthe
numberofcorrectandwronganswerstozero.Setsupto
trapCONTROL-C.
2. Presenttheuserwithachoiceofsubjectsandgettheuser's
response.
3. Changetothecorrespondingsubjectdirectory.
4. Determinethequestionstobeasked(thatis,thefilenames
inthatdirectory).Arrangetheminrandomorder.
5. Repeatedlypresentquestionsandaskforanswersuntilthe
quizisoverorisinterruptedbytheuser.
6. Presenttheresultsandexit.
Clearlysomeofthesesteps(suchasstep3)aresimple,
whereasothers(suchasstep4)arecomplexandworthyof
analysisontheirown.Useshellfunctionsforanycomplexstep,
andusethetrapbuiltintohandleauserinterrupt.
Hereisaskeletonversionoftheprogramwithemptyshell
functions:
functioninitialize
{
#Initializesvariables.
}
functionchoose_subj
{
#Writeschoicetostandardoutput.
}
functionscramble
{
#Storesnamesofquestionfiles,scrambled,
#inanarrayvariablenamedquestions.
}
functionask
{
#Readsaquestionfile,asksthequestion,andchecksthe
#answer.Returns1iftheanswerwascorrect,0otherwise.Ifit
#encountersaninvalidquestionfile,exitwithstatus2.
}
functionsummarize
{
#Presentstheuser'sscore.
}
#Mainprogram
initialize#Step1intop-leveldesign
subject=$(choose_subj)#Step2
[[$?-eq0]]||exit2#Ifnovalidchoice,exit
cd$subject||exit2#Step3
echo#Skipaline
scramble#Step4
forquesin${questions[*]};do#Step5
ask$ques
result=$?
((num_ques=num_ques+1))
if[[$result==1]];then
((num_correct+=1))
fi
echo#Skipalinebetweenquestions
sleep${QUIZDELAY:=1}
done
summarize#Step6
exit0
Tomakereadingtheresultsabiteasierfortheuser,asleepcall
appearsinsidethequestionloop.Itdelays$QUIZDELAY
seconds(default=1)betweenquestions.
Nowthetaskistofillinthemissingpiecesoftheprogram.Ina
sensethisprogramisbeingwrittenbackward.Thedetails(the
shellfunctions)comefirstinthefilebutcomelastinthe
developmentprocess.Thiscommonprogrammingpracticeis
calledtop-downdesign.Intop-downdesignyoufillinthebroad
outlineoftheprogramfirstandsupplythedetailslater.Inthis
wayyoubreaktheproblemupintosmallerproblems,eachof
whichyoucanworkonindependently.Shellfunctionsarea
greathelpinusingthetop-downapproach.
Onewaytowritetheinitializefunctionfollows.Thecd
commandcausesQUIZDIRtobetheworkingdirectoryforthe
restofthescriptanddefaultsto~/quizifQUIZDIRisnotset.
functioninitialize()
{
trap'summarize;exit0'INT#Handleuserinterrupts
num_ques=0#Numberofquestionsaskedsofar
num_correct=0#Numberansweredcorrectlysofar
first_time=true#trueuntilfirstquestionisasked
cd${QUIZDIR:=~/quiz}||exit2
}
Bepreparedforthecdcommandtofail.Thedirectorymaybe
unsearchableorconceivablyanotherusermayhaveremovedit.
Theprecedingfunctionexitswithastatuscodeof2ifcdfails.
Thenextfunction,choose_subj,isabitmorecomplicated.It
displaysamenuusingaselectstatement:
functionchoose_subj()
{
subjects=($(ls))
PS3="Chooseasubjectforthequizfromtheprecedinglist:"
selectSubjectin${subjects[*]};do
if[[-z"$Subject"]];then
echo"Nosubjectchosen.Bye.">&2
exit1
fi
echo$Subject
return0
done
}
Thefunctionfirstusesanlscommandandcommand
substitutiontoputalistofsubjectdirectoriesinthesubjects
array.Nexttheselectstructure(page907)presentstheuser
withalistofsubjects(thedirectoriesfoundbyls)andassigns
thechosendirectorynametotheSubjectvariable.Finallythe
functionwritesthenameofthesubjectdirectorytostandard
output.Themainprogramusescommandsubstitutiontoassign
thisvaluetothesubjectvariable[subject=$(choose_subj)].
Thescramblefunctionpresentsanumberofdifficulties.Inthis
solutionitusesanarrayvariable(questions)toholdthe
namesofthequestions.Itscramblestheentriesinanarray
usingtheRANDOMvariable(eachtimeyoureference
RANDOMithasthevalueofa[random]integerbetween0and
32767):
functionscramble()
{
typeset-iindexquescount
questions=($(ls))
quescount=${#questions[*]}#Numberofelements
((index=quescount-1))
while[[$index>0]];do
((target=RANDOM%index))
exchange$target$index
((index-=1))
done
}
Thisfunctioninitializesthearrayvariablequestionstothelist
offilenames(questions)intheworkingdirectory.Thevariable
quescountissettothenumberofsuchfiles.Thenthe
followingalgorithmisused:Letthevariableindexcountdown
fromquescount1(theindexofthelastentryinthearray
variable).Foreachvalueofindex,thefunctionchoosesa
randomvaluetargetbetween0andindex,inclusive.The
command
((target=RANDOM%index))
producesarandomvaluebetween0andindex1bytakingthe
remainder(the%operator)when$RANDOMisdividedby
index.Thefunctionthenexchangestheelementsofquestions
atpositionstargetandindex.Itisconvenienttodothisin
anotherfunctionnamedexchange:
functionexchange()
{
temp_value=${questions[$1]}
questions[$1]=${questions[$2]}
questions[$2]=$temp_value
}
Theaskfunctionalsousestheselectstructure.Itreadsthe
questionfilenamedinitsargumentandusesthecontentsof
thatfiletopresentthequestion,accepttheanswer,and
determinewhethertheansweriscorrect.(Seethecodethat
follows.)
Theaskfunctionusesfiledescriptor3toreadsuccessivelines
fromthequestionfile,whosenamewaspassedasanargument
andisrepresentedby$1inthefunction.Itreadsthequestion
intothequesvariableandthenumberofquestionsinto
num_opts.Thefunctionconstructsthevariablechoicesby
initializingittoanullstringandsuccessivelyappendingthe
nextchoice.ThenitsetsPS3tothevalueofquesandusesa
selectstructuretoprompttheuserwithques.Theselect
structureplacestheuser'sanswerinanswer,andthefunction
thenchecksitagainstthecorrectanswerfromthefile.
Theconstructionofthechoicesvariableisdonewithaneye
towardavoidingapotentialproblem.Supposethatoneanswer
hassomewhitespaceinit.Thenitmightappearastwoormore
argumentsinchoices.Toavoidthisproblem,makesurethat
choicesisanarrayvariable.Theselectstatementdoesthe
restofthework:
quiz
$catquiz
#!/bin/bash
#removethe#onthefollowinglinetoturnondebugging
#set-oxtrace
#==================
functioninitialize()
{
trap'summarize;exit0'INT#Handleuserinterrupts
num_ques=0#Numberofquestionsaskedsofar
num_correct=0#Numberansweredcorrectlysofar
first_time=true#trueuntilfirstquestionisasked
cd${QUIZDIR:=~/quiz}||exit2
}
#==================
functionchoose_subj()
{
subjects=($(ls))
PS3="Chooseasubjectforthequizfromtheprecedinglist:"
selectSubjectin${subjects[*]};do
if[[-z"$Subject"]];then
echo"Nosubjectchosen.Bye.">&2
exit1
fi
echo$Subject
return0
done
}
#==================
functionexchange()
{
temp_value=${questions[$1]}
questions[$1]=${questions[$2]}
questions[$2]=$temp_value
}
#==================
functionscramble()
{
typeset-iindexquescount
questions=($(ls))
quescount=${#questions[*]}#Numberofelements
((index=quescount-1))
while[[$index>0]];do
((target=RANDOM%index))
exchange$target$index
((index-=1))
done
}
#==================
functionask()
{
exec3<$1
read-u3ques||exit2
read-u3num_opts||exit2
index=0
choices=()
while((index<num_opts));do
read-u3next_choice||exit2
choices=("${choices[@]}""$next_choice")
((index+=1))
done
read-u3correct_answer||exit2
exec3<&-
if[[$first_time=true]];then
first_time=false
echo-e"Youmaypresstheinterruptkeyatanytimetoquit.\n"
fi
PS3=$ques""#Make$questhepromptforselect
#andaddsomespacesforlegibility.
selectanswerin"${choices[@]}";do
if[[-z"$answer"]];then
echoNotavalidchoice.Pleasechooseagain.
elif[["$answer"="$correct_answer"]];then
echo"Correct!"
return1
else
echo"No,theansweris$correct_answer."
return0
fi
done
}
#==================
functionsummarize()
{
echo#Skipaline
if((num_ques==0));then
echo"Youdidnotansweranyquestions"
exit0
fi
((percent=num_correct*100/num_ques))
echo"Youanswered$num_correctquestionscorrectly,outof\
$num_questotalquestions."
echo"Yourscoreis$percentpercent."
}
#==================
#Mainprogram
initialize#Step1intop-leveldesign
subject=$(choose_subj)#Step2
[[$?-eq0]]||exit2#Ifnovalidchoice,exit
cd$subject||exit2#Step3
echo#Skipaline
scramble#Step4
forquesin${questions[*]};do#Step5
ask$ques
result=$?
((num_ques=num_ques+1))
if[[$result==1]];then
((num_correct+=1))
fi
echo#Skipalinebetweenquestions
sleep${QUIZDELAY:=1}
done
summarize#Step6
exit0
ChapterSummary
Theshellisaprogramminglanguage.Programswritteninthis
languagearecalledshellscripts,orsimplyscripts.Shellscripts
providethedecisionandloopingcontrolstructurespresentin
high-levelprogramminglanguageswhileallowingeasyaccess
tosystemutilitiesanduserprograms.Shellscriptscanuse
functionstomodularizeandsimplifycomplextasks.
Controlstructures
Thecontrolstructuresthatusedecisionstoselectalternatives
areif...then,if...then...else,andif...then...elif.Thecase
controlstructureprovidesamultiwaybranchandcanbeused
whenyouwanttoexpressalternativesusingasimplepattern-
matchingsyntax.
Theloopingcontrolstructuresarefor...in,for,until,and
while.Thesestructuresperformoneormoretasksrepetitively.
Thebreakandcontinuecontrolstructuresaltercontrolwithin
loops:breaktransferscontroloutofaloop,andcontinue
transferscontrolimmediatelytothetopofaloop.
TheHeredocumentallowsinputtoacommandinashellscript
tocomefromwithinthescriptitself.
Filedescriptors
TheBourneAgainShellprovidestheabilitytomanipulatefile
descriptors.Coupledwiththereadandechobuiltins,file
descriptorsallowshellscriptstohaveasmuchcontrolover
inputandoutputasprogramswritteninlower-levellanguages.
Variables
Youassignattributes,suchasreadonly,tobashvariablesusing
thetypesetbuiltin.TheBourneAgainShellprovidesoperatorsto
performpatternmatchingonvariables,providedefaultvalues
forvariables,andevaluatethelengthofvariables.Thisshell
alsosupportsarrayvariablesandlocalvariablesforfunctions
andprovidesbuilt-inintegerarithmeticcapability,usingthelet
builtinandanexpressionsyntaxsimilartotheCprogramming
language.
Builtins
BourneAgainShellbuiltinsincludetype,read,exec,trap,kill,and
getopts.Thetypebuiltindisplaysinformationaboutacommand,
includingitslocation;readallowsascripttoacceptuserinput.
Theexecbuiltinexecutesacommandwithoutcreatinganew
process.Thenewcommandoverlaysthecurrentprocess,
assumingthesameenvironmentandPIDnumberofthat
process.ThisbuiltinexecutesuserprogramsandotherLinux
commandswhenitisnotnecessarytoreturncontroltothe
callingprocess.
ThetrapbuiltincatchesasignalsentbyLinuxtotheprocess
runningthescriptandallowsyoutospecifyactionstobetaken
uponreceiptofoneormoresignals.Youcanusethisbuiltinto
causeascripttoignorethesignalthatissentwhentheuser
pressestheinterruptkey.
Thekillbuiltinallowsyoutoterminatearunningprogram.The
getoptsbuiltinparsescommandlinearguments,makingiteasier
towriteprogramsthatfollowstandardLinuxconventionsfor
commandlineargumentsandoptions.
Utilitiesinscripts
Inadditiontousingcontrolstructures,builtins,andfunctions,
shellscriptsgenerallycallLinuxutilities.Thefindutility,for
instance,iscommonplaceinshellscriptsthatsearchforfilesin
thesystemhierarchyandcanperformavastrangeoftasks,
fromsimpletocomplex.
Awell-writtenshellscriptadherestostandardprogramming
practices,suchasspecifyingtheshelltoexecutethescripton
thefirstlineofthescript,verifyingthenumberandtypeof
argumentsthatthescriptiscalledwith,displayingastandard
usagemessagetoreportcommandlineerrors,andredirecting
allinformationalmessagestostandarderror.
Expressions
Therearetwobasictypesofexpressions:arithmeticand
logical.Arithmeticexpressionsallowyoutodoarithmeticon
constantsandvariables,yieldinganumericresult.Logical
(Boolean)expressionscompareexpressionsorstrings,ortest
conditionstoyieldatrueorfalseresult.Aswithalldecisions
withinLinuxshellscripts,atruestatusisrepresentedbythe
valuezero;false,byanynonzerovalue.
Exercises
1.
RewritethejournalscriptofChapter9(question5,page340)byadding
commandstoverifythattheuserhaswritepermissionforafilenamedjournal-
fileintheuser'shomedirectory,ifsuchafileexists.Thescriptshouldtake
appropriateactionsifjournal-fileexistsandtheuserdoesnothavewrite
permissiontothefile.Verifythatthemodifiedscriptworks.
2. Thespecialparameter"$@"isreferencedtwiceintheoutscript(page883).
Explainwhatwouldbedifferentiftheparameter"$*"wereusedinitsplace.
3. Writeafilterthattakesalistoffilesasinputandoutputsthebasename(page
906)ofeachfileinthelist.
4.
Writeafunctionthattakesasinglefilenameasanargumentandaddsexecute
permissiontothefilefortheuser.
a. Whenmightsuchafunctionbeuseful?
b. Revisethescriptsothatittakesoneormorefilenamesasargumentsand
addsexecutepermissionfortheuserforeachfileargument.
c. Whatcanyoudotomakethefunctionavailableeverytimeyoulogin?
d. Supposethat,inadditiontohavingthefunctionavailableonsubsequent
loginsessions,youwanttomakethefunctionavailablenowinyourcurrent
shell.Howwouldyoudoso?
5. Whenmightitbenecessaryoradvisabletowriteashellscriptinsteadofashell
function?Giveasmanyreasonsasyoucanthinkof.
6. Writeashellscriptthatdisplaysthenamesofalldirectoryfiles,butnoothertypes
offiles,intheworkingdirectory.
7.
Writeascripttodisplaythetimeevery15seconds.Readthedatemanpageand
displaythetime,usingthe%rfielddescriptor.Clearthewindow(usingtheclear
command)eachtimebeforeyoudisplaythetime.
Enterthefollowingscriptnamedsavefiles,andgiveyourselfexecutepermission
tothefile:
$catsavefiles
#!/bin/bash
8.
echo"Savingfilesincurrentdirectoryinfilesavethem."
exec>savethem
foriin*
do
echo"==================================================="
echo"File:$i"
echo"==================================================="
cat"$i"
done
a. Whaterrormessagedoyougetwhenyouexecutethisscript?Rewritethe
scriptsothattheerrordoesnotoccur,makingsuretheoutputstillgoesto
savethem.
b. Whatmightbeaproblemwithrunningthisscripttwiceinthesame
directory?Discussasolutiontothisproblem.
9.
Readthebashmanorinfopage,trysomeexperiments,andanswerthefollowing
questions:
a. Howdoyouexportafunction?
b. Whatdoesthehashbuiltindo?
c. Whathappensiftheargumenttoexecisnotexecutable?
10.
Usingthefindutility,performthefollowingtasks:
a. Listallfilesintheworkingdirectoryandallsubdirectoriesthathavebeen
modifiedwithinthelastday.
b. Listallfilesthatyouhavereadaccesstoonthesystemthatarelargerthan1
megabyte.
c. Removeallfilesnamedcorefromthedirectorystructurerootedatyour
homedirectory.
d. Listtheinodenumbersofallfilesintheworkingdirectorywhosefilenames
endin.c.
e. Listallfilesthatyouhavereadaccesstoontherootfilesystemthathave
beenmodifiedinthelast30days.
11.
Writeashortscriptthattellsyouwhetherthepermissionsfortwofiles,whose
namesaregivenasargumentstothescript,areidentical.Ifthepermissionsfor
thetwofilesareidentical,outputthecommonpermissionfield.Otherwise,output
eachfilenamefollowedbyitspermissionfield.(Hint:Tryusingthecututility.)
Writeascriptthattakesthenameofadirectoryasanargumentandsearchesthe
12.
filehierarchyrootedatthatdirectoryforzero-lengthfiles.Writethenamesofall
zero-lengthfilestostandardoutput.Ifthereisnooptiononthecommandline,
havethescriptdeletethefileafterdisplayingitsname,askingtheuserfor
confirmation,andreceivingpositiveconfirmation.Af(force)optiononthe
commandlineindicatesthatthescriptshoulddisplaythefilenamebutnotaskfor
confirmationbeforedeletingthefile.
AdvancedExercises
13. Writeascriptthattakesacolon-separatedlistofitemsandoutputstheitems,one
perline,tostandardoutput(withoutthecolons).
14.
Generalizethescriptwritteninexercise13sothatthecharacterseparatingthelist
itemsisgivenasanargumenttothefunction.Ifthisargumentisabsent,the
separatorshoulddefaulttoacolon.
15.
Writeafunctionnamedfunloadthattakesasitssingleargumentthenameofa
filecontainingotherfunctions.Thepurposeoffunloadistomakeallfunctionsin
thenamedfileavailableinthecurrentshell;thatis,funloadloadsthefunctions
fromthenamedfile.Tolocatethefile,funloadsearchesthecolon-separatedlist
ofdirectoriesgivenbytheenvironmentvariableFUNPATH.Assumethatthe
formatofFUNPATHisthesameasPATHandthatsearchingFUNPATHissimilar
totheshell'ssearchofthePATHvariable.
16.
Rewritebundle(page910)sothatthescriptitcreatestakesanoptionallistof
filenamesasarguments.Ifoneormorefilenamesaregivenonthecommandline,
onlythosefilesshouldbere-created;otherwise,allfilesintheshellarchiveshould
bere-created.Forexample,supposethatallfileswiththefilenameextension.c
arebundledintoanarchivenamedsrcshell,andyouwanttounbundlejustthe
filestest1.candtest2.c.Thefollowingcommandwillunbundlejustthesetwo
files:
$bashsrcshelltest1.ctest2.c
17. Whatkindoflinkswillthelnksscript(page886)notfind?Why?
18.
Inprinciple,recursionisnevernecessary.Itcanalwaysbereplacedbyaniterative
construct,suchaswhileoruntil.Rewritemakepath(page950)asa
nonrecursivefunction.Whichversiondoyouprefer?Why?
Listsarecommonlystoredinenvironmentvariablesbyputtingacolon(:)between
eachofthelistelements.(ThevalueofthePATHvariableisagoodexample.)You
canaddanelementtosuchalistbycatenatingthenewelementtothefrontofthe
list,asin
PATH=/opt/bin:$PATH
19.
Iftheelementyouaddisalreadyinthelist,younowhavetwocopiesofitinthe
list.Writeashellfunctionnamedaddenvthattakestwoarguments:(1)thename
ofashellvariableand(2)astringtoprependtothelistthatisthevalueofthe
shellvariableonlyifthatstringisnotalreadyanelementofthelist.Forexample,
thecall
addenvPATH/opt/bin
wouldadd/opt/bintoPATHonlyifthatpathnameisnotalreadyinPATH.Be
surethatyoursolutionworkseveniftheshellvariablestartsoutempty.Alsomake
surethatyoucheckthelistelementscarefully.If/usr/opt/binisinPATHbut
/opt/binisnot,theexamplejustgivenshouldstilladd/opt/bintoPATH.(Hint:
Youmayfindthisexerciseeasiertocompleteifyoufirstwriteafunction
locate_fieldthattellsyouwhetherastringisanelementinthevalueofa
variable.)
20.
Writeafunctionthattakesadirectorynameasanargumentandwritesto
standardoutputthemaximumofthelengthsofallfilenamesinthatdirectory.If
thefunction'sargumentisnotadirectoryname,writeanerrormessageto
standardoutputandexitwithnonzerostatus.
21.
Modifythefunctionyouwroteforexercise20todescendallsubdirectoriesofthe
nameddirectoryrecursivelyandtofindthemaximumlengthofanyfilenamein
thathierarchy.
22.
Writeafunctionthatliststhenumberofordinaryfiles,directories,blockspecial
files,characterspecialfiles,FIFOs,andsymboliclinksintheworkingdirectory.Do
thisintwodifferentways:
a. Usethefirstletteroftheoutputoflsltodetermineafile'stype.
b. Usethefiletypeconditiontestsofthe[[expression]]syntaxtodetermine
afile'stype.
23. Modifythequizprogram(page956)sothatthechoicesforaquestionare
randomlyarranged.
A.RegularExpressions
INTHISAPPENDIX
Characters 968
Delimiters 968
SimpleStrings 968
SpecialCharacters 968
Rules 971
BracketingExpressions 972
TheReplacementString 972
ExtendedRegularExpressions 973
Aregularexpressiondefinesasetofoneormorestringsof
characters.Asimplestringofcharactersisaregularexpression
thatdefinesonestringofcharacters:itself.Amorecomplex
regularexpressionusesletters,numbers,andspecial
characterstodefinemanydifferentstringsofcharacters.A
regularexpressionissaidtomatchanystringitdefines.
Thisappendixdescribestheregularexpressionsusedbyed,vim,
emacs,grep,gawk,sed,andotherutilities.Theregularexpressions
usedinshellambiguousfilereferencesaredifferentandare
describedin"FilenameGeneration/PathnameExpansion"on
Characters
Asusedinthisappendix,acharacterisanycharacterexcepta
NEWLINE.Mostcharactersrepresentthemselveswithina
regularexpression.Aspecialcharacterisonethatdoesnot
representitself.Ifyouneedtouseaspecialcharacterto
representitself,youmustquoteitasexplainedonpage971.
Delimiters
Acharactercalledadelimiterusuallymarksthebeginningand
endofaregularexpression.Thedelimiterisalwaysaspecial
characterfortheregularexpressionitdelimits(thatis,itdoes
notrepresentitselfbutmarksthebeginningandendofthe
expression).Althoughvimpermitstheuseofothercharacters
asadelimiterandgrepdoesnotusedelimitersatall,theregular
expressionsinthisappendixuseaforwardslash(/)asa
delimiter.Insomeunambiguouscases,theseconddelimiteris
notrequired.Forexample,youcansometimesomitthesecond
delimiterwhenitwouldbefollowedimmediatelybyRETURN.
SimpleStrings
Themostbasicregularexpressionisasimplestringthat
containsnospecialcharactersexceptthedelimiters.Asimple
stringmatchesonlyitself(TableA-1).Intheexamplesinthis
appendix,thestringsthatarematchedareunderlinedandlook
likethis.
TableA-1.Simplestrings
Regular
expression Matches Examples
/ring/ ring ring,spring,ringing,
stringing
/Thursday/ Thursday Thursday,Thursday's
/ornot/ ornot ornot,poornothing
SpecialCharacters
Youcanusespecialcharacterswithinaregularexpressionto
causetheregularexpressiontomatchmorethanonestring.A
regularexpressionthatincludesaspecialcharacteralways
matchesthelongestpossiblestring,startingasfartowardthe
beginning(left)ofthelineaspossible.
Periods
Aperiod(.)matchesanycharacter(TableA-2).
TableA-2.Period
Regular
expression Matches Examples
/.alk/ AllstringsconsistingofaSPACE
followedbyanycharacterfollowed
byalk
willtalk,maybalk
/.ing/ Allstringsconsistingofany
characterprecedinging
singsong,ping,
beforeinglenook
Brackets
Brackets([])defineacharacterclass[1]thatmatchesanysingle
characterwithinthebrackets(TableA-3).Ifthefirstcharacter
followingtheleftbracketisacaret(^),thebracketsdefinea
characterclassthatmatchesanysinglecharacternotwithinthe
brackets.Youcanuseahyphentoindicatearangeof
characters.Withinacharacter-classdefinition,backslashesand
asterisks(describedinthefollowingsections)losetheirspecial
meanings.Arightbracket(appearingasamemberofthe
characterclass)canappearonlyasthefirstcharacterfollowing
theleftbracket.Acaretisspecialonlyifitisthefirstcharacter
followingtheleftbracket.Adollarsignisspecialonlyifitis
followedimmediatelybytherightbracket.
[1]GNUdocumentationcallstheseListOperatorsanddefinesCharacterClassoperators
asexpressionsthatmatchapredefinedgroupofcharacters,suchasallnumbers(page
1024).
TableA-3.Brackets
Regular
expression Matches Examples
/[bB]ill/ Memberofthecharacterclassb
andBfollowedbyill
bill,Bill,billed
/t[aeiou].k/ tfollowedbyalowercasevowel,
anycharacter,andak
talkative,stink,
teak,tanker
/#[69]/ #followedbyaSPACEanda
memberofthecharacterclass6
through9
#60,#8:,get#9
/[^azAZ]/ Anycharacterthatisnotaletter
(ASCIIcharactersetonly)
1,7,@,.,},Stop!
Asterisks
Anasteriskcanfollowaregularexpressionthatrepresentsa
singlecharacter(TableA-4).Theasteriskrepresentszeroor
moreoccurrencesofamatchoftheregularexpression.An
asteriskfollowingaperiodmatchesanystringofcharacters.(A
periodmatchesanycharacter,andanasteriskmatcheszeroor
moreoccurrencesoftheprecedingregularexpression.)A
character-classdefinitionfollowedbyanasteriskmatchesany
stringofcharactersthataremembersofthecharacterclass.
TableA-4.Asterisks
Regular
expression Matches Examples
/ab*c/ afollowedbyzeroormoreb's
followedbyac
ac,abc,abbc,
debbcaabbbc
/ab.*c/ abfollowedbyzeroormore
charactersfollowedbyc
abc,abxc,ab45c,
xab756.345xcat
/t.*ing/ tfollowedbyzeroormore
charactersfollowedbying
thing,ting,I
thoughtofgoing
/[azAZ]*/ Astringcomposedonlyofletters
andSPACEs
1.anystringwithout
numbersor
punctuation!
/(.*)/ Aslongastringaspossible
between(and)
Get(this)and
(that);
/([^)]*)/ Theshorteststringpossiblethat
startswith(andendswith)
(this),Get(thisand
that)
CaretsandDollarSigns
Aregularexpressionthatbeginswithacaret(^)canmatcha
stringonlyatthebeginningofaline.Inasimilarmanner,a
dollarsign($)attheendofaregularexpressionmatchesthe
endofaline.Thecaretanddollarsignarecalledanchors
becausetheyforce(anchor)amatchtothebeginningorendof
aline(TableA-5).
TableA-5.Caretsanddollarsigns
Regular
expression Matches Examples
/^T/ ATatthebeginningofaline Thisline...,That
Time...,InTime
/^+[09]/ Aplussignfollowedbyadigitat
thebeginningofaline
+5+45.72,+759
Keepthis...
/:$/ Acolonthatendsaline ...below:
QuotingSpecialCharacters
Youcanquoteanyspecialcharacter(butnotadigitora
parenthesis)byprecedingitwithabackslash(TableA-6).
Quotingaspecialcharactermakesitrepresentitself.
TableA-6.Quotedspecialcharacters
Regular
expression Matches Examples
/end\./ Allstringsthatcontainend
followedbyaperiod
Theend.,send.,
pretend.mail
/\\/ Asinglebackslash \
/\*/ Anasterisk *.c,anasterisk(*)
/\[5\]/ [5] itwasfive[5]
/and\/or/ and/or and/or
Rules
Thefollowingrulesgoverntheapplicationofregular
expressions.
LongestMatchPossible
Aregularexpressionalwaysmatchesthelongestpossible
string,startingasfartowardthebeginningofthelineas
possible.Forexample,giventhestring
This(rug)isnotwhatitoncewas(alongtimeago),isit?
theexpression/Th.*is/matches
This(rug)isnotwhatitoncewas(alongtimeago),is
and/(.*)/matches
(rug)isnotwhatitoncewas(alongtimeago)
However,/([^)]*)/matches
(rug)
Giventhestring
singingsongs,singingmoreandmore
theexpression/s.*ing/matches
singingsongs,singing
and/s.*ingsong/matches
singingsong
EmptyRegularExpressions
Withinsomeutilities,suchasvimandless(butnotgrep),an
emptyregularexpressionrepresentsthelastregularexpression
thatyouused.Forexample,supposeyougivevimthefollowing
Substitutecommand:
:s/mike/robert/
Ifyouthenwanttomakethesamesubstitutionagain,youcan
usethefollowingcommand:
:s//robert/
Alternatively,youcanusethefollowingcommandstosearchfor
thestringmikeandthenmakethesubstitution
/mike/
:s//robert/
Theemptyregularexpression(//)representsthelastregular
expressionyouused(/mike/).
BracketingExpressions
Youcanusequotedparentheses,\(and\),tobracketa
regularexpression.Thestringthatthebracketedregular
expressionmatchescanberecalled,asexplainedin"Quoted
Digit."Aregularexpressiondoesnotattempttomatchquoted
parentheses.Thusaregularexpressionenclosedwithinquoted
parenthesesmatcheswhatthesameregularexpressionwithout
theparentheseswouldmatch.Theexpression/\(rexp\)/
matcheswhat/rexp/wouldmatch;/a\(b*\)c/matches
what/ab*c/wouldmatch.
Youcannestquotedparentheses.Thebracketedexpressions
areidentifiedonlybytheopening\(,sonoambiguityarisesin
identifyingthem.Theexpression/\([az]\([AZ]*\)x\)/
consistsoftwobracketedexpressions,onenestedwithinthe
other.Inthestring3tdMNORx7lu,theprecedingregular
expressionmatchesdMNORx,withthefirstbracketed
expressionmatchingdMNORxandthesecondmatching
MNOR.
TheReplacementString
Thevimandsededitorsuseregularexpressionsassearch
stringswithinSubstitutecommands.Youcanusethe
ampersand(&)andquoteddigits(\n)specialcharactersto
representthematchedstringswithinthecorresponding
replacementstring.
Ampersand
Withinareplacementstring,anampersand(&)takesonthe
valueofthestringthatthesearchstring(regularexpression)
matched.Forexample,thefollowingvimSubstitutecommand
surroundsastringofoneormoredigitswithNN.The
ampersandinthereplacementstringmatcheswhateverstring
ofdigitstheregularexpression(searchstring)matched:
:s/[0-9][0-9]*/NN&NN/
Twocharacter-classdefinitionsarerequiredbecausetheregular
expression[09]*matcheszeroormoreoccurrencesofadigit,
andanycharacterstringconstituteszeroormoreoccurrences
ofadigit.
QuotedDigit
Withinthesearchstring,abracketedregularexpression,\
(xxx\),matcheswhattheregularexpressionwouldhave
matchedwithoutthequotedparentheses,xxx.Withinthe
replacementstring,aquoteddigit,\n,representsthestring
thatthebracketedregularexpression(portionofthesearch
string)beginningwiththenth\(matched.Forexample,you
cantakealistofpeopleintheform
last-name,first-nameinitial
andputitintheform
first-nameinitiallast-name
withthefollowingvimcommand:
:1,$s/\([^,]*\),\(.*\)/\2\1/
Thiscommandaddressesallthelinesinthefile(1,$).The
Substitutecommand(s)usesasearchstringandareplacement
stringdelimitedbyforwardslashes.Thefirstbracketedregular
expressionwithinthesearchstring,\([^,]*\),matcheswhat
thesameunbracketedregularexpression,[^,]*,wouldmatch:
zeroormorecharactersnotcontainingacomma(thelast-
name).Followingthefirstbracketedregularexpressionarea
commaandaSPACEthatmatchthemselves.Thesecond
bracketedexpression,\(.*\),matchesanystringofcharacters
(thefirst-nameandinitial).
Thereplacementstringconsistsofwhatthesecondbracketed
regularexpressionmatched(\2),followedbyaSPACEandwhat
thefirstbracketedregularexpressionmatched(\1).
ExtendedRegularExpressions
Thethreeutilitiesegrep,grepwhenrunwiththeEoption(similar
toegrep),andgawkprovideallthespecialcharactersthatare
includedinordinaryregularexpressions,exceptfor\(and\),
aswellasseveralothers.Thevimeditorincludestheadditional
charactersaswellas\(and\).Patternsusingtheextended
setofspecialcharactersarecalledfullregularexpressionsor
extendedregularexpressions.
Twooftheadditionalspecialcharactersaretheplussign(+)
andthequestionmark(?).Theyaresimilarto*,which
matcheszeroormoreoccurrencesofthepreviouscharacter.
Theplussignmatchesoneormoreoccurrencesoftheprevious
character,whereasthequestionmarkmatcheszeroorone
occurrence.Youcanuseanyoneofthespecialcharacters*,+,
and?followingparentheses,causingthespecialcharacterto
applytothestringsurroundedbytheparentheses.Unlikethe
parenthesesinbracketedregularexpressions,these
parenthesesarenotquoted(TableA-7).
TableA-7.Extendedregularexpressions
Regular
expression Matches Examples
/ab+c/ afollowedbyoneormoreb's
followedbyac
yabcw,abbc57
/ab?c/ afollowedbyzerooroneb
followedbyc
back,abcdef
/(ab)+c/ Oneormoreoccurrencesofthe
stringabfollowedbyc
zabcd,ababc!
/(ab)?c/ Zerooroneoccurrenceofthe
stringabfollowedbyc
xc,abcc
Infullregularexpressions,theverticalbar(|)specialcharacter
isaBooleanORoperator.Withinvim,youmustquotethe
verticalbarbyprecedingitwithabackslashtomakeitspecial
(\|).Averticalbarbetweentworegularexpressionscausesa
matchwithstringsthatmatchthefirstexpression,thesecond
expression,orboth.Youcanusetheverticalbarwith
parenthesestoseparatefromtherestoftheregularexpression
thetwoexpressionsthatarebeingORed(TableA-8).
TableA-8.Fullregularexpressions
Regular
expression Meaning Examples
/ab|ac/ Eitheraborac ab,ac,abac(abac
istwomatchesof
theregular
expression)
/^Exit|^Quit/ LinesthatbeginwithExitorQuit Exit,Quit,NoExit
/(D|N)\.
Jones/
D.JonesorN.Jones P.D.Jones,N.Jones
AppendixSummary
Aregularexpressiondefinesasetofoneormorestringsof
characters.Aregularexpressionissaidtomatchanystringit
defines.
Inaregularexpression,aspecialcharacterisonethatdoesnot
representitself.TableA-9listsspecialcharacters.
TableA-9.Specialcharacters
Character Meaning
.Matchesanysinglecharacter
*Matcheszeroormoreoccurrencesofamatchofthe
precedingcharacter
^Forcesamatchtothebeginningofaline
$Amatchtotheendofaline
\Quotesspecialcharacters
\< Forcesamatchtothebeginningofaword
\> Forcesamatchtotheendofaword
TableA-10listswaysofrepresentingcharacterclassesand
bracketedregularexpressions.
TableA-10.Characterclassesandbracketedregular
expressions
Class Defines
[xyz]Definesacharacterclassthatmatchesx,y,orz
[^xyz]Definesacharacterclassthatmatchesanycharacter
exceptx,y,orz
[xz]Definesacharacterclassthatmatchesanycharacterx
throughzinclusive
\(xyz\) Matcheswhatxyzmatches(abracketedregular
expression)
Inadditiontotheprecedingspecialcharactersandstrings
(excludingquotedparentheses,exceptinvim),thecharactersin
TableA-11arespecialwithinfull,orextended,regular
expressions.
TableA-11.Extendedregularexpressions
Expression Matches
+Matchesoneormoreoccurrencesofthepreceding
character
?Matcheszerooroneoccurrenceofthepreceding
character
(xyz)+ Matchesoneormoreoccurrencesofwhatxyzmatches
(xyz)? Matcheszerooroneoccurrenceofwhatxyzmatches
(xyz)* Matcheszeroormoreoccurrencesofwhatxyzmatches
xyz|abc Matcheseitherwhatxyzorwhatabcmatches(use\|
invim)
(xy|ab)cMatcheseitherwhatxycorwhatabcmatches(use\|
invim)
TableA-12listscharactersthatarespecialwithinareplacement
stringinsedandvim.
TableA-12.Replacementstrings
String Represents
&Representswhattheregularexpression(searchstring)
matched
\n Aquotednumber,n,representswhatthenthbracketed
regularexpressioninthesearchstringmatched
B.Help
INTHISAPPENDIX
SolvingaProblem 978
FindingLinux-RelatedInformation 979
Documentation 979
UsefulLinuxSites 980
LinuxNewsgroups 981
MailingLists 981
Words 982
Software 982
OfficeSuitesandWordProcessors 984
SpecifyingaTerminal 984
Youneednotactasauserorsystemadministratorinisolation.
AlargecommunityofLinuxexpertsiswillingtoassistyouin
learningabout,helpingyousolveproblemswith,andgetting
themostoutofaLinuxsystem.Beforeyouaskforhelp,
however,makesureyouhavedoneeverythingyoucantosolve
theproblemyourself.Nodoubt,someonehasexperiencedthe
sameproblembeforeyouandtheanswertoyourquestioncan
befoundsomewhereontheInternet.Yourjobistofindit.This
appendixlistsresourcesanddescribesmethodsthatcanhelp
youinthattask.
SolvingaProblem
Followingisalistofstepsthatcanhelpyousolveaproblem
withoutaskingsomeoneforhelp.Dependingonyour
understandingofandexperiencewiththehardwareand
softwareinvolved,thesestepsmayleadtoasolution.
1. RedHatLinuxcomeswithextensivedocumentation.Read
thedocumentationonthespecifichardwareorsoftwareyou
arehavingaproblemwith.IfitisaGNUproduct,useinfo;
otherwise,usemantofindlocalinformation.Alsolookin
/usr/share/docfordocumentationonspecifictools.For
moreinformationreferto"GettingtheFacts:WheretoFind
Documentation"onpage102.
2. Whentheprobleminvolvessometypeoferrororother
message,useasearchengine,suchasGoogle
(www.google.com/linux)orGoogleGroups
(groups.google.com),tolookupthemessageonthe
Internet.Ifthemessageislong,pickauniquepartofthe
messagetosearchfor;10to20charactersshouldbe
enough.Enclosethesearchstringwithindoublequotation
marks.
3. CheckwhethertheLinuxDocumentationProject
(www.tldp.org)hasaHOWTOormini-HOWTOonthesubject
inquestion.Searchonkeywordsthatrelatedirectlytothe
productandproblem.ReadtheFAQs.
4. SeeTableB-1forothersourcesofdocumentation.
5. UseGoogleorGoogleGroupstosearchonkeywordsthat
relatedirectlytotheproductandproblem.
6. Whenallelsefails(orperhapsbeforeyoutryanythingelse),
examinethesystemlogsin/var/log.Runningas
Superuser,firstlookattheendofthemessagesfileusing
thefollowingcommand:
#tail-20/var/log/messages
Ifmessagescontainsnothinguseful,runthefollowing
command.Itdisplaysthenamesofthelogfilesin
chronologicalorder,withthemostrecentlymodifiedfiles
appearingatthebottomofthelist:
$ls-ltr/var/log
Iftheprobleminvolvesanetworkconnection,reviewthe
securelogfileonthelocalandremotesystems.Alsolook
atmessagesontheremotesystem.
7. The/var/spooldirectorycontainssubdirectorieswith
usefulinformation:cupsholdstheprintqueues,mailholds
theuser'smailfiles,andsoon.
Ifyouareunabletosolveaproblemyourself,athoughtful
questiontoanappropriatenewsgroup(page981)ormailinglist
(page981)canelicitusefulinformation.
Whenyousendorpostaquestion,makesureyoudescribethe
problemandidentifythelocalsystemcarefully.Includethe
versionnumbersofRedHatLinuxandanysoftwarepackages
thatrelatetotheproblem.Describethehardware,if
appropriate.Forafee,RedHatprovidesmanytypesofsupport.
Theauthor'shomepage(www.sobell.com)containscorrections
tothisbook,answerstoselectedchapterexercises,and
pointerstootherLinuxsites.
FindingLinux-RelatedInformation
RedHatLinuxcomeswithreferencepagesstoredonline.You
canreadthesedocumentsbyusingtheinfo(page106)orman
(page104)utilities.Youcanreadmanandinfopagestoget
moreinformationaboutspecifictopicswhilereadingthisbook
ortodeterminewhichfeaturesareavailablewithLinux.Youcan
searchfortopicsusingapropos(seepage145orgivethe
commandmanapropos).
Documentation
Goodbooksareavailableonvariousaspectsofusingand
managingUNIXsystemsingeneralandLinuxsystemsin
particular.Inaddition,youmayfindthesiteslistedinTableB-1
useful.[1]
[1]Theright-handcolumnsofmostofthetablesinthisappendixshowInternetaddresses
(URLs).Allsiteshaveanimplicithttp://prefixunlessftp://orhttps://isshown.Referto
"URLs(Webaddresses)"onpage18.
TableB-1.Documentation
Site Aboutthesite URL
freedesktop.org Createsstandardsfor
interoperabilitybetweenopen-
sourcedesktopenvironments.
freedesktop.org
GNOME GNOMEhomepage. www.gnome.org
GNUManuals GNUmanuals. www.gnu.org/manual
InternetFAQ
Archives
SearchableFAQarchives. www.faqs.org
info Instructionsforusingtheinfo
utility.
www.gnu.org/software/texinfo/manual/info
KDE
Documentation
KDEdocumentation. kde.org/documentation
KDENews KDEnews. dot.kde.org
TheLinux
Documentation
Project
AllthingsrelatedtoLinux
documentation(inmany
languages):HOWTOs,guides,
FAQs,manpages,and
magazines.Thisisthebest
overallsourceforLinux
documentation.Makesureto
visittheLinkspage.
www.tldp.org
RedHat
Documentation
andSupport
ThissitehasalinktotheRed
HatKnowledgebasethatcan
helpanswerquestions.Italso
haslinkstoonline
documentationforRedHat
productsandtoasupport
guide.
www.redhat.com/apps/support
RFCs Requestforcomments;seeRFC
(page1052).
www.rfc-editor.org
System
Administrators
Guild(SAGE)
SAGEisagroupforsystem
administrators.
www.sage.org
UsefulLinuxSites
SometimesthesiteslistedinTableB-2aresobusythatyou
cannotconnecttothem.Inthiscase,youareusuallygivena
listofalternative,ormirror,sitestotry.
TableB-2.UsefulLinuxSites
TableB-2.UsefulLinuxSites
Site Aboutthesite URL
DistroWatch AsurveyofmanyLinuxdistributions,including
news,reviews,andarticles.
distrowatch.com
GNU GNUProjectWebserver. www.gnu.org
ibiblio Alargelibraryanddigitalarchive.Formerly
Metalab;formerlySunsite.
www.ibiblio.org
www.ibiblio.org/pub/linux
www.ibiblio.org/pub/historic-
linux
LinuxHQ.org Anadministratorandpoweruserresourcesite. www.linuxhq.org
Linux
Standard
Base(LSB)
AgroupdedicatedtostandardizingLinux. www.linuxbase.org
Rpmfind.Net Agoodsourceforrpmfiles,especiallywhenyou
needaspecificversion.
rpmfind.net
Sobell Theauthor'shomepagecontainsusefullinks,
errataforthisbook,codeformanyofthe
examplesinthisbook,andanswerstoselected
exercises.
www.sobell.com
USENIX Alarge,well-establishedUNIXgroup.Thissite
hasmanylinks,includingalistofconferences.
www.usenix.org
X.Org TheXWindowSystemhome. www.x.org
LinuxNewsgroups
Oneofthebestwaysofgettingspecificinformationisthrougha
newsgroup(referto"Usenet"onpage378).Frequentlyyoucan
findtheanswertoaquestionbyreadingpostingstothe
newsgroup.TryusingGoogleGroups(groups.google.com)to
searchthroughnewsgroupstoseewhetherthequestionhas
alreadybeenaskedandanswered.Oropenanewsreader
programandsubscribetoappropriatenewsgroups.If
necessary,youcanpostaquestionforsomeonetoanswer.
Beforeyoudoso,makesureyouarepostingtothecorrect
groupandthatyourquestionhasnotalreadybeenanswered.
Thereisanetiquettetopostingquestionssee
www.catb.org/~esr/faqs/smart-questions.htmlforagoodpaper
byEricS.RaymondandRickMoentitled"HowToAskQuestions
theSmartWay."
Thenewsgroupcomp.os.linux.answersprovidespostingsof
solutionstocommonproblemsandperiodicpostingsofthe
mostup-to-dateversionsoftheFAQandHOWTOdocuments.
Thecomp.os.linux.miscnewsgrouphasanswersto
miscellaneousLinux-relatedquestions.
MailingLists
Subscribingtoamailinglist(page646)allowsyouto
participateinanelectronicdiscussion.Withmostlists,youcan
sendandreceiveemaildedicatedtoaspecifictopictoandfrom
agroupofusers.Moderatedlistsdonottendtostrayasmuch
asunmoderatedlists,assumingthelisthasagoodmoderator.
Thedisadvantageofamoderatedlististhatsomediscussions
maybecutoffwhentheygetinterestingifthemoderator
deemsthatthediscussionhasgoneonfortoolong.Mailinglists
describedasbulletinsarestrictlyunidirectional:Youcannot
postinformationtotheselistsbutcanonlyreceiveperiodic
bulletins.Ifyouhavethesubscriptionaddressforamailinglist
butarenotsurehowtosubscribe,putthewordhelpinthe
bodyand/orheaderofemailthatyousendtotheaddress.You
willusuallyreceiveinstructionsviareturnemail.RedHathosts
severalmailinglists;gotowww.redhat.com/mailman/listinfofor
moreinformation.Youcanalsouseasearchenginetosearch
formailinglistlinux.
Words
Manydictionaries,thesauruses,andglossariesareavailable
online.TableB-3listsafewofthem.
TableB-3.Lookingupwords
Site Aboutthe
site URL
ROGET'S
Thesaurus
Thesaurus humanities.uchicago.edu/forms_unrest/ROGET.html
DICT.org Multiple-
database
searchfor
words
www.dict.org
Dictionary.com Everything
relatedto
words
dictionary.reference.com
DNSGlossary DNS
glossary
www.menandmice.com/online_docs_and_faq/glossary/glossarytoc.htm
FOLDOC(The
FreeOn-Line
Dictionaryof
Computing)
Computer
terms
www.foldoc.org
TheJargon
File
Anonline
versionof
TheNew
Hacker's
Dictionary
www.catb.org/~esr/jargon
Merriam- English www.m-w.com
Webster language
OneLook Multiple-site
wordsearch
withasingle
query
www.onelook.com
Webopedia Commercial
technical
dictionary
www.webopedia.com
Wikipedia Anopen-
source
(user-
contributed)
encyclopedia
project
wikipedia.org
Wordsmyth Dictionary
and
thesaurus
www.wordsmyth.net
Yahoo
Reference
Search
multiple
sourcesat
thesame
time
education.yahoo.com/reference
Software
Therearemanywaystolearnaboutinterestingsoftware
packagesandtheiravailabilityontheInternet.TableB-4lists
sitesthatyoucandownloadsoftwarefrom.Forsecurity-related
programs,refertoTableC-1onpage1002.Anotherwayto
learnaboutsoftwarepackagesisthroughanewsgroup(page
981).
TableB-4.Software
Site Aboutthesite URL
Apt Aptinstalls,
removes,and
updatessystem
software
packages
apt.freshrpms.net
BitTorrent BitTorrent
efficiently
distributeslarge
amountsofstatic
data
www.bittorrent.com
CVS CVS(Concurrent
VersionsSystem)
isaversion
controlsystem
www.nongnu.org/cvs
ddd Thedddutilityis
agraphicalfront
endforcommand
linedebuggers
suchasgdb
www.gnu.org/software/ddd
Firefox Webbrowser www.mozilla.com/firefox
Free
Software
Directory
Categorized,
searchablelists
offreesoftware
directory.fsf.org
Freshmeat Alargeindexof
UNIXandcross-
platformsoftware
andthemes
freshmeat.net
gdb Thegdbutilityis
acommandline
debugger
www.gnu.org/software/gdb
GNOME
Project
Linkstoall
GNOMEprojects
www.gnome.org/projects
IceWALKERS Categorized,
searchablelists
www.icewalkers.com
searchablelists
offreesoftware
kdbg Thekdbgutilityis
agraphicaluser
interfacetogdb
freshmeat.net/projects/kdbg
Linux
Software
Map
Adatabaseof
packageswritten
for,portedto,or
compiledfor
Linux
www.boutell.com/lsm
Mtools Acollectionof
utilitiestoaccess
DOSfloppy
diskettesfrom
Linuxwithout
mountingthe
diskettes
mtools.linux.lu
Network
Calculators
Subnetmask
calculator
www.subnetmask.info
rpmfind.net Searchablelistof
rpmfilesfor
variousLinux
distributionsand
versions
rpmfind.net/linux/RPM
Savannah Centralpointfor
development,
distribution,and
maintenanceof
freesoftware
savannah.gnu.org
SourceForge Adevelopment
Websitewitha
largerepository
ofopen-source
codeand
applications
sourceforge.net
strace Thestraceutilityis
asystemcall
tracedebugging
tool
www.liacs.nl/~wichert/stracesourceforge.net/projects/strace
tool
Thunderbird Mailapplication www.mozilla.com/thunderbird
Tucows-
Linux
Commercial,
categorized,
searchablelistof
software
www.tucows.com/Linux
ups Theupsutilityisa
graphicalsource-
leveldebugger
ups.sourceforge.net
yum Theyumutility
installs,removes,
andupdates
systemsoftware
packages
linux.duke.edu/projects/yumapt.freshrpms.net
OfficeSuitesandWordProcessors
Severalofficesuitesandmanywordprocessorsareavailablefor
Linux.TableB-5listsafewofthem.Ifyouareexchanging
documentswithpeopleusingWindows,makesuretheimport
from/exporttoMSWordfunctionalitycoversyourneeds.
TableB-5.Officesuitesandwordprocessors
Product
name Whatitdoes URL
AbiWord Wordprocessor www.abisource.com
KOffice Integratedsuiteofofficeapplicationsincluding
theKWordwordprocessingprogram
www.koffice.org
OpenOffice Amultiplatformandmultilingualofficesuite www.openoffice.org
www.gnome.org/projects/ooo
SpecifyingaTerminal
Becausevim,emacs,konsole,andotherprogramstakeadvantage
offeaturesthatarespecifictovariouskindsofterminalsand
terminalemulators,youmusttelltheseprogramsthenameof
theterminalyouareusingortheterminalthatyourterminal
emulatorisemulating.Onmanysystemstheterminalnameis
setforyou.Iftheterminalnameisnotspecifiedorisnot
specifiedcorrectly,thecharactersonthescreenwillbegarbled
or,whenyoustartaprogram,theprogramwillaskwhattypeof
terminalyouareusing.
Terminalnamesdescribethefunctionalcharacteristicsofa
terminalorterminalemulatortoprogramsthatrequirethis
information.Althoughterminalnamesarereferredtoaseither
TerminfoorTermcapnames,thedifferencerelatestothe
methodthateachsystemusestostoretheterminal
characteristicsinternally,notthemannerthatyouspecifythe
nameofaterminal.Terminalnamesthatareoftenusedwith
Linuxterminalemulatorsandwithgraphicalmonitorswhilethey
arerunintextmodeincludeansi,linux,vt100,vt102,
vt220,andxterm.
Whenyouarerunningaterminalemulator,youcanspecifythe
typeofterminalyouwanttoemulate.Settheemulatorto
eithervt100orvt220,andthensetTERMtothesamevalue.
Whenyoulogin,youmaybepromptedtoidentifythetypeof
terminalyouareusing:
TERM=(vt100)
Youcanrespondtothispromptinoneoftwoways.Firstyou
canpressRETURNtosetyourterminaltypetothenamein
parentheses.Ifthatnamedoesnotdescribetheterminalyou
areusing,youcanenterthecorrectnameandthenpress
RETURN.
TERM=(vt100)ansi
Youmayalsoreceivethefollowingprompt:
TERM=(unknown)
Thispromptindicatesthatthesystemdoesnotknowwhattype
ofterminalyouareusing.Ifyouplantorunprogramsthat
requirethisinformation,enterthenameoftheterminalor
terminalemulatoryouareusingbeforeyoupressRETURN.
TERM
Ifyoudonotreceiveaprompt,youcangivethefollowing
commandtodisplaythevalueoftheTERMvariableandcheck
whethertheterminaltypehasbeenset:
$echo$TERM
Ifthesystemrespondswiththewrongname,ablankline,oran
errormessage,setorchangetheterminalname.Fromthe
BourneAgainShell(bash),enteracommandsimilartothe
followingtosettheTERMvariablesothatthesystemknows
whichtypeofterminalyouareusing:
exportTERM=name
Replacenamewiththeterminalnamefortheterminalyouare
using,makingsurethatyoudonotputaSPACEbeforeorafter
theequalsign.Ifyoualwaysusethesametypeofterminal,
youcanplacethiscommandinyour~/.bashrcfile(page267),
causingtheshelltosettheterminaltypeeachtimeyoulogin.
Forexample,givethefollowingcommandtosetyourterminal
nametovt100:
$exportTERM=vt100
LANG
Forsomeprogramstodisplayinformationcorrectlyyoumay
needtosettheLANGvariable(page298).Frequentlyyoucan
setthisvariabletoC.Underbashusethecommand
$exportLANG=C
C.Security
INTHISAPPENDIX
Encryption 988
FileSecurity 993
EmailSecurity 993
NetworkSecurity 994
HostSecurity 997
LoginSecurity 998
RemoteAccessSecurity 999
VirusesandWorms 1000
PhysicalSecurity 1000
SecurityResources 1002
Securityisamajorpartofthefoundationofanysystemthatis
nottotallycutofffromothermachinesandusers.Someaspects
ofsecurityhaveaplaceevenonisolatedmachines.Examplesof
thesemeasuresincludeperiodicsystembackups,BIOSor
power-onpasswords,andself-lockingscreensavers.
Asystemthatisconnectedtotheoutsideworldrequiresother
mechanismstosecureit:toolstocheckfiles(tripwire),audit
tools(tiger/cops),secureaccessmethods(kerberos/ssh),services
thatmonitorlogsandmachinestates(swatch/watcher),packet-
filteringandroutingtools(ipfwadm/iptables/ipchains),andmore.
Systemsecurityhasmanydimensions.Thesecurityofyour
systemasawholedependsonthesecurityofindividual
components,suchasyouremail,files,network,login,and
remoteaccesspolicies,aswellasthephysicalsecurityofthe
hostitself.Thesedimensionsfrequentlyoverlap,andtheir
bordersarenotalwaysstaticorclear.Forinstance,email
securityisaffectedbythesecurityoffilesandyournetwork.If
themedium(thenetwork)overwhichyousendandreceive
youremailisnotsecure,thenyoumusttakeextrastepsto
ensurethesecurityofyourmessages.Ifyousaveyoursecure
emailintoafileonyourlocalsystem,thenyourelyonthe
filesystemandhostaccesspoliciesforfilesecurity.Afailurein
anyoneoftheseareascanstartadominoeffect,diminishing
reliabilityandintegrityinotherareasandpotentially
compromisingsystemsecurityasawhole.
Thisshortappendixcannotcoverallfacetsofsystemsecurityin
depth,butitdoesprovideanoverviewofthecomplexityof
settingupandmaintainingasecuresystem.Thisappendix
providessomespecifics,concepts,guidelinestoconsider,and
manypointerstosecurityresources(TableC-1onpage1002).
TableC-1.Securityresources
Tool Whatitdoes Wheretogetit
AIDE AdvancedIntrusionDetection
Environment.Similartotripwire
withextensibleverification
algorithms.
sourceforge.net/projects/aide
bugtraq Amoderatedmailinglistforthe
announcementanddetailed
discussionofallaspectsof
computersecurityvulnerabilities.
www.securityfocus.com/archive/1
CERT ComputerEmergencyResponse
Team.Arepositoryofpapersand
dataaboutmajorsecurityevents
andalistofsecuritytools.
www.cert.org
chkrootkit Checksforsignsofarootkit
indicatingthatthemachinehas
beencompromised.
www.chkrootkit.org
dsniff Sniffingandnetworkaudittool
suite.Free.
naughty.monkey.org/~dugsong/dsniff/
ethereal Networkprotocolanalyzer.Free. www.ethereal.com
freefire Suppliesfreesecuritysolutions
andsupportsdevelopersoffree
securitysolutions.
www.freefire.org
fwtk Firewalltoolkit.Asetofproxies
thatcanbeusedtoconstructa
firewall.
www.fwtk.org
GIAC Asecuritycertificationand
trainingWebsite.
www.giac.org
hping Multipurposenetworkauditing
andpacketanalysistool.Free.
www.hping.org
ISC2Educatesandcertifiesindustry
professionalsandpractitioners
underaninternationalstandard.
www.isc2.org
John JohntheRipper:afast,flexible,
weakpassworddetector.
www.openwall.com/john
Kerberos Complete,securenetwork
authenticationsystem.
web.mit.edu/kerberos/www
L6 Verifiesfileintegrity;similarto
tripwire.
www.pgci.ca/l6.html
LIDS Intrusiondetectionandactive
defensesystem.
www.lids.org
LinuxSecurity.com Asolidnewssitededicatedto
Linuxsecurityissues.
www.linuxsecurity.com
LWN.net Securityalertdatabaseforall
majorLinuxdistributions.
lwn.net/Alerts
MicrosoftSecurity Microsoftsecurityinformation. www.microsoft.com/security
nessus Aplugin-basedremotesecurity
scannerthatcanperformmore
than370securitychecks.Free.
www.nessus.org
netcat Explores,tests,anddiagnoses
networks.
freshmeat.net/projects/netcat
nmap Scanshoststoseewhichports
areavailable.Itcanperform
stealthscans,determine
operatingsystemtype,findopen
ports,andmore.
www.insecure.org/nmap
OPIE Providesone-timepasswordsfor
systemaccess.
inner.net/opie
RBAC RoleBasedAccessControl.
Assignsrolesandprivileges
associatedwiththeroles.
csrc.nist.gov/rbac
RedHatSecurity RedHatsecurityinformation. www.redhat.com/security
SAINT SecurityAdministrator's
IntegratedNetworkTool.
Assessesandanalyzesnetwork
vulnerabilities.Thistoolfollows
satan.
www.wwdsi.com/saint
samhain Afileintegritychecker.HasaGUI
configurator,client/server
capability,andreal-timereporting
capability.
samhain.sourceforge.net
SANS Securitytrainingandcertification. www.sans.org
SARA TheSecurityAuditor'sResearch
Assistantsecurityanalysistool.
www-arc.com/sara
Schneier,Bruce Securityvisionary. www.schneier.com
Secunia Monitorsabroadspectrumof
vulnerabilities.
secunia.com
SecurityFocus Homeforsecuritytools,maillists,
libraries,andcogentanalysis.
www.securityfocus.com
snort AflexibleIDS. www.snort.org
srp SecureRemotePassword.
Upgradescommonprotocols,
suchasTELNETandFTP,touse
securepasswordexchange.
srp.stanford.edu
ssh Asecurersh,ftp,andrlogin
replacementwithencrypted
sessionsandotheroptions.
SuppliedwithRedHatLinux.
www.ssh.orgopenssh.org
swatch APerl-basedlogparserand
analyzer.
swatch.sourceforge.net
Treachery Acollectionoftoolsforsecurity
andauditing.
www.treachery.net/tools
tripwire Checksforpossiblesignsof
intruderactivity.Suppliedwith
RedHatLinux.
www.tripwire.com
Security:Othersourcesofsystem
securityinformation
Dependingonhowimportantsystemsecurityisto
you,youmaywanttopurchaseoneormoreofthe
booksdedicatedtosystemsecurity,visitsomeofthe
Internetsitesthatarededicatedtosecurity,orhire
someonewhoisanexpertinthefield.
Donotrelyonthisappendixasyoursole
sourceofinformationonsystemsecurity.
Encryption
Oneofthebuildingblocksofsecurityisencryption,which
providesameansofscramblingdataforsecuretransmissionto
otherparties.Incryptographicterms,thedataormessageto
beencryptedisreferredtoasplaintext,andtheresulting
encryptedblockoftextasciphertext.Processesexistfor
convertingplaintextintociphertextthroughtheuseofkeys,
whichareessentiallyrandomnumbersofaspecifiedlength
usedtolockandunlockdata.Thisconversionisachievedby
applyingthekeystotheplaintextaccordingtoasetof
mathematicalinstructions,referredtoastheencryption
algorithm.
Developingandanalyzingstrongencryptionsoftwareis
extremelydifficult.Manynuancesexist,manystandardsgovern
encryptionalgorithms,andabackgroundinmathematicsis
requisite.Also,unlessanalgorithmhasundergonepublic
scrutinyforasignificantperiodoftime,itisgenerallynot
consideredsecure;itisoftenimpossibletoknowthatan
algorithmiscompletelysecurebutpossibletoknowthatoneis
notsecure.Timeisthebesttestofanyalgorithm.Also,asolid
algorithmdoesnotguaranteeaneffectiveencryption
mechanism,asthefallibilityofanencryptionschemefrequently
liesinproblemswithitsimplementationanddistribution.
Anencryptionalgorithmusesakeythatisacertainnumberof
bitslong.Eachbityouaddtothelengthofakeyeffectively
doublesthekeyspace(thenumberofcombinationsallowedby
thenumberofbitsinthekey2tothepowerofthelengthofthe
keyinbits[1])andmeansthatitwilltaketwiceaslongforan
attackertodecryptyourmessage(assumingthatthescheme
lacksanyinherentweaknessesorvulnerabilitiestoexploit).
However,itisamistaketocomparealgorithmsbasedonlyon
thenumberofbitsused.Insomecasesanalgorithmthatuses
a64-bitkeycanbemoresecurethananalgorithmthatusesa
128-bitkey.
[1]A2-bitkeywouldhaveakeyspaceof4(22),a3-bitkeywouldhaveakeyspaceof8
(23),andsoon.
Thetwoprimaryclassificationsofencryptionschemesarepublic
keyencryptionandsymmetrickeyencryption.Publickey
encryption,alsocalledasymmetricencryption,usestwokeys:a
publickeyandaprivatekey.Thesekeysareuniquely
associatedwithaspecificindividualuser.Publickeyencryption
schemesareusedmostlytoexchangekeysandsignatures.
Symmetrickeyencryption,alsocalledsymmetricencryptionor
secretkeyencryption,usesonekeythatyouandtheperson
youarecommunicatingwith(hereafterreferredtoasyour
friend)shareasasecret.Symmetrickeyencryptionistypically
usedtoencryptlargeamountsofdata.Publickeyalgorithm
keystypicallyhavealengthof512bitsto2,048bits,whereas
symmetrickeyalgorithmsusekeysintherangeof64bitsto
512bits.
Whenyouarechoosinganencryptionscheme,realizethat
securitycomesataprice.Thereisusuallyatradeoffbetween
resilienceofthecryptosystemandeaseofadministration.
Security:Hardtobreak?Hardtouse!
Themoredifficultanalgorithmistocrack,themore
difficultitistomaintainandtogetpeopletouse
properly.Theparamountlimitationsofmost
respectablecryptosystemslienotinweakalgorithms
butratherinusers'failuretotransmitandstorekeys
inasecuremanner.
Thepracticalityofasecuritysolutionisafargreaterfactorin
encryption,andinsecurityingeneral,thanmostpeoplerealize.
Withenoughtimeandeffort,nearlyeveryalgorithmcanbe
broken.Infact,youcanoftenunearththemathematical
instructionsforawidelyusedalgorithmbyflippingthrougha
cryptographybook,reviewingavendor'sproductspecifications,
orperformingaquicksearchontheInternet.Thechallengeis
toensurethattheeffortrequiredtofollowthetwistsandturns
takenbyanencryptionalgorithmanditsresultingencryption
solutionoutweighstheworthoftheinformationitisprotecting.
Tip:Howmuchtimeandmoneyshould
youspendonencryption?
Whenthecostofobtainingtheinformationexceeds
thevaluerealizedbyitspossession,thesolutionis
aneffectiveone.
PublicKeyEncryption
Tousepublickeyencryption,youmustgeneratetwokeys:a
publickeyandaprivatekey.Youkeeptheprivatekeyfor
yourselfandgivethepublickeytotheworld.Inasimilar
manner,yourfriendswillgenerateapairofkeysandgiveyou
theirpublickeys.Publickeyencryptionismarkedbytwo
distinctfeatures:
1. Whenyouencryptdatawithsomeone'spublickey,onlythat
person'sprivatekeycandecryptit.
2. Whenyouencryptdatawithyourprivatekey,anyoneelse
candecryptitwithyourpublickey.
Youmaywonderwhythesecondpointisuseful:Whywouldyou
wanteverybodyelsetobeabletodecryptsomethingyoujust
encrypted?Theanswerliesinthepurposeoftheencryption.
Althoughencryptionchangestheoriginalmessageinto
unreadableciphertext,itspurposeistoprovideadigital
signature.Ifthemessagecanbeproperlydecryptedwithyour
publickey,onlyyoucouldhaveencrypteditwithyourprivate
key,provingthatthemessageisauthentic.Combiningthese
twomodesofoperationyieldsprivacyandauthenticity.Youcan
signsomethingwithyourprivatekeysothatitisverifiedas
authentic,andthenyoucanencryptitwithyourfriend'spublic
keysothatonlyyourfriendcandecryptit.
Publickeyencryptionhasthreemajorshortcomings:
1. Publickeyencryptionalgorithmsaregenerallymuchslower
thansymmetrickeyalgorithmsandusuallyrequireamuch
largerkeysizeandawaytogeneratelargeprimenumbers
touseascomponentsofthekey,makingthemmore
resourceintensive.
2. Theprivatekeymustbestoredsecurelyanditsintegrity
safeguarded.Ifaperson'sprivatekeyisobtainedby
anotherparty,thatpartycanencrypt,decrypt,andsign
messageswhileimpersonatingtheoriginalownerofthe
key.Iftheprivatekeyislostorbecomescorrupted,any
messagespreviouslyencryptedwithitarealsolost,anda
newkeypairmustbegenerated.
3. Itisdifficulttoauthenticatetheoriginofakeythatis,to
provewhomitoriginallycamefrom.Thisso-calledkey-
distributionproblemistheraisond'êtreforsuchcompanies
asVeriSign(www.verisign.com).
AlgorithmssuchasRSA,Diffie-Hellman,andEl-Gamal
implementpublickeyencryptionmethodology.Todaya512-bit
keyisconsideredbarelyadequateforRSAencryptionandoffers
marginalprotection;1,024-bitkeysareexpectedtowithhold
determinedattackersforseveralmoreyears.Keysthatare
2,048bitslongarenowbecomingcommonplaceandarerated
asespionagestrength.Amathematicalpaperpublishedinlate
2001andreexaminedinspring2002describeshowamachine
canbebuiltforaverylargesumofmoneythatcouldbreak
1,024-bitRSAencryptioninsecondstominutes(thispointis
debatedinanarticleatwww.schneier.com/crypto-gram-
0203.html#6).Althoughthecostofsuchamachineexceedsthe
resourcesavailabletomostindividualsandsmaller
corporations,itiswellwithinthereachoflargecorporationsand
governments.
SymmetricKeyEncryption
Symmetrickeyencryptionisgenerallyfastandsimpleto
deploy.Firstyouandyourfriendagreeonwhichalgorithmto
useandakeythatyouwillshare.Theneitherofyoucan
decryptorencryptafilewiththesamekey.Behindthescenes,
symmetrickeyencryptionalgorithmsaremostoften
implementedasanetworkofblackboxes,whichcaninvolve
hardwarecomponents,software,oracombinationofthetwo.
Eachboximposesareversibletransformationontheplaintext
andpassesitontothenextbox,whereanotherreversible
transformationfurtheraltersthedata.Thesecurityofa
symmetrickeyalgorithmreliesonthedifficultyofdetermining
whichboxeswereusedandthenumberoftimesthedatawas
fedthroughthesetofboxes.Agoodalgorithmwillcyclethe
plaintextthroughagivensetofboxesmanytimesbefore
yieldingtheresult,andtherewillbenoobviousmappingfrom
plaintexttociphertext.
Thedisadvantageofsymmetrickeyencryptionisthatit
dependsheavilyontheavailabilityofasecurechannelthrough
whichtosendthekeytoyourfriend.Forexample,youwould
notuseemailtosendyourkey;ifyouremailisintercepted,a
thirdpartyisinpossessionofyoursecretkey,andyour
encryptionisuseless.Youcouldrelaythekeyoverthephone,
butyourcallcouldbeinterceptedifyourphoneweretappedor
someoneoverheardyourconversation.
Commonimplementationsofsymmetrickeyalgorithmsinclude
DES(DataEncryptionStandard),3-DES(tripleDES),IDEA,
RC5,Blowfish,andAES(AdvancedEncryptionStandard).AESis
thenewFederalInformationProcessingStandard(FIPS-197)
algorithmendorsedforgovernmentaluseandhasbeenselected
toreplaceDESasthedefactoencryptionalgorithm.AESuses
theRijndaelalgorithm(www.rijndael.com),chosenaftera
thoroughevaluationof15candidatealgorithmsbythe
cryptographicresearchcommunity.
Noneoftheaforementionedalgorithmshasundergonemore
scrutinythanDES,whichhasbeeninusesincethelate1970s.
However,theuseofDEShasdrawbacksanditisnolonger
consideredsecure,astheweaknessofits56-bitkeymakesit
unreasonablyeasytobreak.Becauseoftheadvancesin
computingpowerandspeedsinceDESwasdeveloped,the
smallsizeofthisalgorithm'skeyrendersitinadequatefor
operationsrequiringmorethanbasicsecurityforarelatively
shortperiodoftime.Forafewthousanddollars,youcanlink
off-the-shelfcomputersystemssothattheycancrackDESkeys
inafewhours.
The3-DESapplicationofDESisintendedtocombatits
degeneratingresiliencebyrunningtheencryptionthreetimes;
itisprojectedtobesecureforyearstocome.DESisprobably
sufficientforsuchtasksassendingemailtoafriendwhenyou
needittobeconfidentialorsecureforonlyafewdays(for
example,tosendanoticeofameetingthatwilltakeplaceina
fewhours).Itisunlikelythatanyoneissufficientlyinterestedin
youremailtoinvestthetimeandmoneytodecryptit.Because
of3-DES'swideavailabilityandeaseofuse,itisadvisableto
useitinsteadofDES.
EncryptionImplementation
Mostoftoday'scommercialsoftwarepackagesusebothpublic
andsymmetrickeyencryptionalgorithms,takingadvantageof
thestrengthsofeachandavoidingtheirweaknesses.Thepublic
keyalgorithmisusedfirst,asameansofnegotiatinga
randomlygeneratedsecretkeyandprovidingformessage
authenticity.Thenasecretkeyalgorithm,suchas3-DES,IDEA,
AES,orBlowfish,encryptsanddecryptsthedataonbothends
forspeed.Finallyahashalgorithm,suchasDSA(Digital
SignatureAlgorithm),generatesamessagedigestthatprovides
asignaturethatcanalertyoutotampering.Thedigestis
digitallysignedwiththesender'sprivatekey.
GnuPG/PGP
Themostpopularpersonalencryptionpackagesavailabletoday
areGnuPG(GNUPrivacyGuard,alsocalledGPG;
www.gnupg.org)andPGP(PrettyGoodPrivacy;www.pgp.com).
GNUPrivacyGuardwasdesignedasafreereplacementforPGP,
asecuritytoolthatmadeitsdebutduringtheearly1990s.Phil
ZimmermandevelopedPGPasaPublicKeyInfrastructure(PKI),
featuringaconvenientinterface,easeofuseandmanagement,
andthesecurityofdigitalcertificates.Onecriticalcharacteristic
setPGPapartfromthemajorityofcryptosystemsthen
available:PGPfunctionsentirelywithoutcertificationauthorities
(CAs).UntiltheintroductionofPGP,PKIimplementationswere
builtaroundtheconceptofCAsandcentralizedkey
managementcontrols.
PGPandGnuPGrelyonthenotionofaringoftrust:[2]Ifyou
trustsomeoneandthatpersontrustssomeoneelse,theperson
youtrustcanprovideanintroductiontothethirdparty.When
youtrustsomeone,youperformanoperationcalledkey
signing.Bysigningsomeoneelse'skey,youverifythatthe
person'spublickeyisauthenticandsafeforyoutousetosend
email.Whenyousignakey,youareaskedwhetheryoutrust
thispersontointroduceotherkeystoyou.Itiscommon
practicetoassignthistrustbasedonseveralcriteria,including
yourknowledgeofaperson'scharacteroralastingprofessional
relationshipwiththeperson.Thebestpracticeistosign
someone'skeyonlyafteryouhavemetfacetofacetoavert
anychanceofaman-inthe-middle[3]scenario.The
disadvantageofthisschemeisthelackofacentralregistryfor
associatingwithpeopleyoudonotalreadyknow.
[2]Formoreinformation,seethesectionofTheGNUPrivacyHandbook
(www.gnupg.org/docs.html)titled"ValidatingOtherKeysonYourPublicKeyring."
[3]Man-in-the-middle:IfAlexandJennytrytocarryonasecureemailexchangeovera
network,AlexfirstsendsJennyhispublickey.However,supposethatMr.Xsitsbetween
AlexandJennyonthenetworkandinterceptsAlex'spublickey.Mr.Xthensendshisown
publickeytoJenny.JennythensendsherpublickeytoAlex,butonceagainMr.X
interceptsitandsubstituteshisownpublickeyandsendsthattoAlex.Withoutsomekind
ofactiveprotection(apieceofsharedinformation),Mr.X,theman-in-the-middle,can
decryptalltrafficbetweenAlexandJenny,reencryptit,andsenditontotheotherparty.
PGPisavailablewithoutcostforpersonaluse,butits
deploymentinacommercialenvironmentrequiresthepurchase
ofalicense.Thiswasnotalwaysthecase:Soonafterits
introduction,PGPwasavailableonmanybulletinboard
systems,anduserscouldimplementitinanymannerthey
chose.PGPrapidlygainedpopularityinthenetworking
community,whichcapitalizedonitsencryptionandkey
managementcapabilitiesforsecuretransmissionofemail.
Afteratime,attentionturnedtothetworobustcryptographic
algorithms,RSAandIDEA,whichformanintegralpartofPGP's
code.Thesealgorithmsareprivatelyowned.Thewide
distributionofandgrowinguserbaseforPGPsparkedbattles
overpatentviolationandlicenses,resultingintheeventual
restrictionofPGP'suse.
EnterGnuPG,whichsupportsmostofthefeaturesand
implementationsmadeavailablebyPGPandcomplieswiththe
OpenPGPMessageFormatstandard.
BecauseGnuPGdoesnotusethepatentedIDEAalgorithmbut
ratherreliesonBUGS(www.gnu.org/directory/bugs.html),you
canuseitalmostwithoutrestriction:Itisreleasedunderthe
GNUGPL(referto"TheCodeIsFree"onpage4).PGPand
GnuPGareconsideredtobeinterchangeableandinteroperable.
Thecommandsequencesforandinternalworkingsofthesetwo
toolsareverysimilar.
Tip:TheGnuPGsystemincludesthegpg
program
GnuPGisfrequentlyreferredtoasgpg,butgpgis
actuallythemainprogramfortheGnuPGsystem.
GNUoffersagoodintroductiontoprivacy,TheGNUPrivacy
Handbook,whichisavailableinseverallanguagesandlistedat
www.gnupg.org(clickDocumentation Guides).Click
Documentation HOWTOsonthesameWebpagetoview
theGNUPrivacyGuard(GnuPG)MiniHowto,whichsteps
throughthesetupanduseofgpg.And,ofcourse,thereisagpg
infopage.
Inadditiontoencryption,gpgisusefulforauthentication.For
example,youcanuseittoverifythatthepersonwhosigneda
pieceofemailisthepersonwhoactuallysentit.
FileSecurity
Fromanenduser'sperspective,filesecurityisoneofthemost
criticalareasofsecurity.SomefilesecurityisbuiltintoLinux:
chmod(page182)givesyoubasicsecuritycontrol.ACLs(Access
ControlLists)allowformorefine-grainedcontroloffileaccess
permissions.ACLsarepartofSolaris,WindowsNT/2000/XP,
VAX/VMS,andmainframeoperatingsystems.RedHatLinux
supportsACLs(page185).Eventhesetoolsareinsufficient,
however,whenyouraccountiscompromised(forexample,by
someonewatchingyourfingersonthekeyboardasyoutype
yourpassword).Toprovidemaximumfilesecurity,youmust
encryptyourfiles.Thenevensomeonewhoknowsyour
passwordcannotreadyourfiles.(Ofcourse,ifsomeoneknows
yourkey,thatpersoncandecryptyourfilesifheorshecanget
tothem.)
EmailSecurity
Emailsecurityoverlapswithfilesecurityand,asdiscussedlater,
withnetworksecurity.GnuPGisthetoolmostfrequentlyused
foremailsecurity,althoughyoucanalsousePGP.PEM(Privacy
EnhancedMail)isastandardratherthananalgorithmandis
usedlessfrequently.
MTAs(MailTransferAgents)
AnincreasinglycommonplaceMTAisSTARTTLS(StartTransport
LayerSecurity;www.sendmail.org/~ca/email/starttls.html).
TLSitselfusuallyreferstoSSL(SecureSocketsLayer)andhas
becomethedefactomethodforencryptingTCP/IPtrafficonthe
Internet.Thesendmaildaemoncanbebuilttosupport
STARTTLS,andmuchdocumentationexistsonhowtodoso.
STARTTLSenhancementsalsoexistforqmailandpostfixand
otherpopularMTAs.Itisimportanttorecognizethatthis
capabilityprovidesencryptionbetweentwomailserversbutnot
necessarilybetweenyourmachineandthemailserver.Also,the
advantagesofusingTLSarenegatediftheemailmustpass
througharelaythatdoesnotsupportTLS.
MUAs(MailUserAgents)
Manypopularmailuseragents,suchasmutt,elm,andemacs,
includetheabilitytousePGPorGnuPGforencryption.This
approachhasbecomethedefaultwaytoexchangesecure
email.
NetworkSecurity
Networksecurityisavitalcomponentforensuringthesecurity
ofacomputingsite.However,withouttherightinfrastructure,
providingnetworksecurityisdifficult,ifnotimpossible.For
example,ifyourunasharednetworktopology,[4]suchas
Ethernet,andhaveinpubliclocationsjacksthatallowanyone
toplugintothenetworkatwill,howcanyoupreventsomeone
fromplugginginamachineandcapturingallthepackets(page
1047)thattraversethenetwork?[5]Youcannot,soyouhavea
potentialsecurityhole.Anothercommonsecurityholerelatesto
theuseoftelnetforlogins.Becausetelnetsendsandreceives
cleartext,anyone"listeningin"onthelinecaneasilycapture
usernamesandpasswords,compromisingsecurity.
[4]Sharednetworktopology:Anetworkinwhicheachpacketmaybeseenbymachines
otherthanitsdestination."Shared"meansthatthe100megabitspersecondbandwidth
issharedbyallusers.
[5]Donotmakethemistakeofassumingthatyouhavesecurityjustbecauseyouhavea
switch.Switchesaredesignedtoallocatebandwidth,nottoguaranteesecurity.
DonotallowanyunauthenticatedPC(anyPCthatdoesnot
requireuserstosupplyalocalnameandpassword)onyour
network.WithaWindows9xPC,anyuseronthenetworkis
effectivelySuperuserforthefollowingreasons:
APCdoesnotrecognizetheconceptofroot.Allusers,by
default,haveaccesstoandcanwatchthenetwork,capture
packets,andsendpackets.
OnUNIX/Linux,onlySuperusercanputthenetwork
interfaceinpromiscuousmodeandcollectpackets.OnUNIX
andLinux,portsnumberedlessthan1024[6]are
privilegedthatis,normaluserprotocolscannotbindtothese
ports.Thisisanimportantbutregrettablemeansof
securityforsomeprotocols,suchasNIS,NFS,RSH,and
LPD.NormallyadataswitchonyourLANautomatically
protectsyourmachinesfrompeoplesnoopingonyour
networkfordata.Inhigh-loadsituations,switcheshave
beenknowntobehaveunpredictably,directingpacketsto
thewrongports.Certainprogramscanoverloadtheswitch
tablesthatholdinformationaboutwhichmachineison
whichport.Whenthesetablesareoverloaded,theswitch
becomesarepeaterandbroadcastsallpacketstoallports.
Theattackeronthesameswitchasyoucanpotentiallysee
allthetrafficyoursystemsendsandreceives.
[6]Thetermporthasmanymeanings.Hereitisanumberassignedtoaprogram.
Thenumberlinksincomingdatawithaspecificservice.Forexample,port21is
usedbyftptraffic,andport23isusedbytelnet.
NetworkSecuritySolutions
Onesolutiontoshared-networkproblemsistoencrypt
messagesthattravelbetweenmachines.IPSec(Internet
ProtocolSecurityProtocol)providesjustsuchatechnology.
IPSeciscommonlyusedtoestablishasecurepoint-to-point
virtualnetwork(VPN,page1062)thatallowstwohoststo
communicatesecurelyoveraninsecurechannel,suchasthe
Internet.Thisprotocolprovidesintegrity,confidentiality,
authenticity,andflexibilityofimplementationthatsupports
multiplevendors.
IPSecisanamalgamationofprotocols(IPSec=AH+ESP+
IPComp+IKE):
AuthenticationHeader(AH)Acryptographicallysecure,
irreversiblechecksum(page1024)foranentirepacket.AH
guaranteesthatthepacketisauthentic.
EncapsulatingSecurityPayload(ESP)Encryptsapacket
tomakethedataunreadable.
IPPayloadCompression(IPComp)Compressesapacket.
Encryptioncanincreasethesizeofapacket,andIPComp
counteractsthisincreaseinsize.
InternetKeyExchange(IKE)Providesawayforthe
endpointstonegotiateacommonkeysecurely.ForAHto
work,bothendsoftheexchangemustusethesamekeyto
preventa"man-in-the-middle"(seefootnote3onpage
992)fromspoofingtheconnection.
WhileIPSecisanoptionalpartofIPv4,IPv6(page359)
mandatesitsuse.However,itmaybequitesometimebefore
IPv6iswidelyimplemented.Seepage1012forinformation
abouttheimplementationofIPSecintheLinux2.6kernel.
NetworkSecurityGuidelines
Somegeneralguidelinesforestablishingandmaintaininga
securesystemfollow.Thislistisnotcompletebutmeantrather
onlyasaguide.
Fiberopticcableismoresecurethancoppercable.Copperis
subjecttobothactiveandpassiveeavesdropping.With
accesstocoppercable,alladatathiefneedstomonitor
yournetworktrafficisapassivedeviceformeasuring
magneticfields.Incontrast,itismuchmoredifficulttotap
afiberopticcablewithoutinterruptingthesignal.Sites
requiringtopsecuritykeepfiberopticcableinpressurized
conduits,whereachangeinpressuresignalsthatthe
physicalsecurityofthecablehasbeenbreached.
Avoidleavingunusedportsavailableinpublicareas.Ifa
malicioususercanplugalaptopintothenetworkwithout
beingdetected,youareatriskofaserioussecurity
problem.Networkdropsthatwillremainunusedfor
extendedperiodsshouldbedisabledattheswitch,
preventingthemfromacceptingorpassingnetworktraffic.
Manynetworkswitcheshaveprovisionsforbindinga
hardwareaddresstoaportforenhancedsecurity.If
someoneunplugsonemachineandplugsinanother
machinetocapturetraffic,chancesarethatthesecond
machinewillhaveadifferenthardwareaddress.Whenit
detectsadevicewithadifferenthardwareaddress,the
switchcandisabletheport.Eventhissolutionisno
guarantee,however,asthereareprogramsthatenableyou
tochangeormaskthehardwareaddressofanetwork
interface.
Security:Installasmallkerneland
runonlytheprogramsyouneed
Linuxsystemscontainahugenumberof
programsthat,althoughuseful,significantly
reducethesecurityofthehost.Installthe
smallestoperatingsystemkernelthatmeets
yourneeds.ForWebandFTPservers,install
onlytheneededcomponents.Usersusually
requireadditionalpackages.
DonotallowNFSorNISaccessoutsideofyournetwork.
Otherwise,itisasimplematterforamalicioususertosteal
yourentirepasswordmap.DefaultNFSsecurityismarginal
tononexistent(acommonjokeisthatNFSstandsforNo
FileSecurity)sosuchaccessshouldnotbeallowedoutside
yournetworktomachinesthatyoudonottrust.
ExperimentalversionsofNFSforLinuxthatsupportmuch
betterauthenticationalgorithmsarenowbecoming
available.UseIPSec,anexperimentalNFSv4withimproved
authentication,orfirewallstoprovideaccessoutsideofyour
domain.
SupportforVPNconfigurationisoftenbuiltintonew
firewallsorprovidedasaseparateproduct,enablingyour
systemtojoinsecurelywiththoseofyourcustomersor
partners.Ifyoumustallowbusinesspartners,contractors,
orotheroutsidepartiestoaccessyourfiles,considerusing
asecurefilesystem,suchasNFSwithKerberos(page
1039),secureNFS(encryptsauthentication,nottraffic),
NFSoveraVPNsuchasIPSec,orcfs(cryptographic
filesystem).
Specify/usrasreadonly(ro)in/etc/fstab.Followingis
anexampleofsuchaconfiguration.
/dev/hda6/usrext2ro00
Thisapproachmaymakeyourmachinedifficulttoupdate,
sousethistacticwithcare.
Mountfilesystemsotherthan/and/usrnosuidtoprevent
setuidprogramsfromexecutingonthisfilesystem.For
example,
/dev/hda4/varext3nosuid00
/dev/hda5/usr/localext3nosuid00
Useabarrierorfirewallproductbetweenyournetworkand
theInternet.Severalvaluablemailinglistscoverfirewalls,
includingthecomp.security.firewallsnewsgroupandthe
HostSecurity
Yourhostmustbesecure.Simplesecuritystepsinclude
preventingremoteloginsandleavingthe/etc/hosts.equiv
andindividualusers'~/.rhostsfilesempty(ornothavingthem
atall).ComplexsecuritystepsincludeinstallingIPSecforVPNs
betweenhosts.Manycommonsecuritymeasuresfall
somewhereinbetweenthesetwoextremes.Afewofthese
follow.SeeTableC-1onpage1002forrelevantURLs.
Althoughpotentiallytrickytoimplementandmanage,
intrusiondetectionsystems(IDSs)areanexcellentwayto
keepaneyeontheintegrityofadevice.AnIDScanwarn
ofpossibleattemptstosubvertsecurityonthehoston
whichitruns.Thegreat-granddaddyofintrusiondetection
systemsistripwire.Thishost-basedsystemchecks
modificationtimesandintegrityoffilesbyusingstrong
algorithms(cryptographicchecksumsorsignatures)that
candetecteventhemostminormodifications.A
commercialversionoftripwireisalsoavailable.Another
commercialIDSisDragonSquire.Otherfree,popular,and
flexibleIDSsincludesamhainandAIDE.ThelasttwoIDSs
offerevenmorefeaturesandmeansofremaininginvisible
tousersthantripwiredoes.CommercialIDSsthatare
popularinenterpriseenvironmentsincludeCiscoSecure
IDS(formerlyNetRanger),EnterasysDragon,andISS
RealSecure.
KeepFedorasystemsup-to-datebydownloadingand
installingthelatestupdates.Useyumtoupdatethesystem
regularly(page478)orsetupthesystemtoupdateitself
everynightautomatically(page482).Goto
fedora.redhat.com/download/updates.htmlformore
information.
RedHatNetwork(RHN,page498)canautomaticallyor
semiautomaticallykeeponeormoresystemsup-to-date,
preventingthesystemfrombecomingpreytofixedsecurity
bugs.
Complementinghost-basedIDSsarenetwork-basedIDSs.
Thelatterprogramsmonitorthenetworkandnodesonthe
networkandreportsuspiciousoccurrences(attack
signatures)viauser-definedalerts.Thesesignaturescanbe
matchedbasedonknownworms,overflowattacksagainst
programs,orunauthorizedscansofnetworkports.Such
programsassnort,klaxon,andNFRareusedinthiscapacity.
Commercialprograms,suchasDragonSentry,alsofillthis
role.
ProvidedwithRedHatLinuxisPAM,whichallowsyoutoset
updifferentmethodsandlevelsofauthenticationinmany
ways(page438).
Processaccountingagoodsupplementtosystem
securitycanprovideacontinuousrecordofuseractionson
yoursystem.Seetheacctonmanpageformoreinformation.
EmergingstandardsforsuchthingsasRoleBasedAccess
Control(RBAC)allowtighterdelegationofprivilegesalong
definedorganizationalboundaries.Youcandelegatearole
orrolestoeachuserasappropriatetotheaccessrequired.
Generalmailinglistsandarchivesareextremelyuseful
repositoriesofsecurityinformation,statistics,andpapers.
ThemostusefularethebugtraqmailinglistandCERT.[7]
Thebugtraqsiteandemailserviceofferimmediate
notificationsaboutspecificvulnerabilities,whereasCERT
providesnoticeofwidespreadvulnerabilitiesanduseful
techniquestofixthem,aswellaslinkstovendorpatches.
[7]CERTisslowbutusefulasamediumforcoordinationbetweensites.Itactsasa
trackingagencytodocumentthespreadofsecurityproblems.
Thesyslogfacility(providedwithRedHatLinux)candirect
messagesfromsystemdaemonstospecificfilessuchas
thosein/var/log.Onlargergroupsofsystems,youcan
sendallimportantsysloginformationtoasecurehost,where
thathost'sonlyfunctionistostoresyslogdatasothatit
cannotbetamperedwith.Seepage376andthesyslogd
manpageformoreinformation.
LoginSecurity
Withoutasecurehost,goodloginsecuritycannotaddmuch
protection.TableC-1listssomeofthebestloginsecuritytools,
includingreplacementdaemonsfortelnetd,rlogind,and
rshd.Thecurrentchoiceofmostsitesisssh,whichcomesas
bothfreewareandacommerciallysupportedpackagethat
worksonUNIX/Linux,Windows,andMacintoshplatforms.
ThePAMfacility(page438)allowsyoutosetupmultiple
authenticationmethodsforusersinseriesorinparallel.In-
seriesPAMrequiresmultiplemethodsofauthenticationfora
user.In-parallelPAMusesanyoneofanumberofmethodsfor
authentication.
Althoughitisnotthemostpopularchoice,youcanconfigure
yoursystemtotakeadvantageofone-timepasswords.S/Keyis
theoriginalimplementationofone-timepasswordsbyBellcore.
OPIE(one-timepasswordsineverything),whichwasdeveloped
bytheU.S.NavalResearchLabs,isanimprovementoverthe
originalBellcoresystem.Inonepermutationofone-time
passwords,theusergetsapieceofpaperlistingasetofone-
timepasswords.Eachtimeauserlogsin,sheentersa
passwordfromthepieceofpaper.Onceused,apassword
becomesobsolete,andthenextpasswordinthelististheonly
onethatwillwork.Evenifamalicioususercompromisesthe
networkandseesyourpassword,theinformationwillbeofno
usebecausethepasswordcanbeusedonlyonce.Thissetup
makesitverydifficultforsomeonetologinasyoubutdoes
nothingtoprotectthedatayoutypeatthekeyboard.One-time
passwordsareagoodsolutionifyouareatasitewhereno
encryptedloginisavailable.Atrulysecure(orparanoid)site
willcombineone-timepasswordsandencryptedlogins.
Anothertypeofsecureloginthatisbecomingmorecommonis
facilitatedbyatokenorasmartcard.Smartcardsarecredit-
card-likedevicesthatuseachallengeresponsemethodof
authentication.Smartcardandtokenauthenticationrelyon
somethingyouhave(thecard)andsomethingyouknow(a
passphrase,userID,orPIN).Forexample,youmightenter
yourusernameinresponsetotheloginpromptandgeta
passwordprompt.YouwouldthenenteryourPINandthe
numberdisplayedontheaccesstoken.Thetokenhasaunique
serialnumberthatisstoredinadatabaseontheauthentication
server.Thetokenandtheauthenticationserverusethisserial
numberasameansofcomputingachallengeevery30to60
seconds.IfthePINandtokennumberyouentermatchwhat
theyshouldbeascomputedbytheaccessserver,youare
grantedaccesstothesystem.
RemoteAccessSecurity
Issuesandsolutionssurroundingremoteaccesssecurity
overlapwiththosepertainingtologinandhostsecurity.Local
loginsmaybesecurewithsimplyausernameandpassword,
whereasremotelogins(andallremoteaccess)shouldbemade
moresecure.Manybreakinscanbetracedbacktoreusable
passwords.Itisagoodideatouseanencryptedauthentication
client,suchassshorkerberos.Youcanalsousesmartcardsfor
remoteaccessauthentication.
Modempoolscanalsobeanentrypointintoasystem.Most
peopleareawareofhoweasyitistomonitoranetworkline.
However,theymaytakeforgrantedthesecurityofthepublic
switchedtelephonenetwork(PSTN,alsoknownasPOTSplain
oldtelephoneservice).Youmaywanttosetupanencrypted
channelafterdialingintoamodempool.Onewaytodosois
byrunningsshoverPPP.
Therearewaystoimplementstringentmodemauthentication
policiessothatunauthorizedusersarenotabletouseyour
modems.ThemostcommontechniquesarePAP(Password
AuthenticationProtocol),CHAP(ChallengeHandshake
AuthenticationProtocol),andRadius.PAPandCHAPare
relativelyweakwhencomparedwithRadius,sothelatterhas
rapidlygainedinpopularity.Ciscoalsoprovidesamethodof
authenticationcalledTACACS/TACACS+(TerminalAccess
ControllerAccessControlSystem).
Oneormoreoftheseauthenticationtechniquesareavailablein
aRAS(remoteaccessserverinanetworkacomputerthat
providesnetworkaccesstoremoteusersviamodem).Before
purchasingaRAS,checkwhatkindofsecurityitprovidesand
decidewhetherthatlevelofsecuritymeetsyourneeds.
Twoothertechniquesforremoteaccesssecuritycanbebuilt
intoamodem(orRASifithasintegratedmodems).Oneis
callback:Afteryoudialin,yougetapasswordprompt.Once
youtypeinyourpassword,themodemhangsupandcallsyou
backataphonenumberithasstoredinternally.Unfortunately
thistechniqueisnotfoolproof.Somemodemshaveabuilt-in
callbacktablethatholdsabouttenentries,sothisstrategy
worksforsmallsiteswithonlyafewmodems.Ifyouusemore
modems,theRASsoftwaremustprovidethecallback.
ThesecondtechniqueistouseCLID(callerlineID)orANI
(automaticnumberidentification)todecidewhethertoanswer
thecall.Dependingonyourwiringandthelocalphone
company,youmayormaynotbeabletouseANI.ANI
informationisprovidedbeforethecall,whereasCLID
informationisprovidedalongwiththecall.
VirusesandWorms
ExamplesofUNIX/LinuxvirusesincludetheBlissvirus/worm
releasedin1997andtheRST.bvirusdiscoveredinDecember
2001.BotharediscussedindetailinarticlesontheWeb.
Virusesspreadthroughsystemsbyinfectingexecutablefiles.In
thecasesofBlissandRST.b,theLinuxnativeexecutable
format,ELF,wasusedasapropagationvector.
Justafter5PMonNovember2,1988,RobertT.Morris,Jr.,a
graduatestudentatCornellUniversity,releasedthefirstbig
virusontotheInternet.CalledanInternetworm,thisviruswas
designedtopropagatecopiesofitselfovermanymachineson
theInternet.Thewormwasapieceofcodethatexploitedfour
vulnerabilities,includingoneinfinger,togetabuffertooverflow
onasystem.Oncethebufferoverflowed,thecodewasableto
getashellandthenrecompileitselfontheremotemachine.
ThewormspreadaroundtheInternetveryquicklyandwasnot
disabled,despitemanypeople'sefforts,for36hours.
Thechiefcharacteristicofanywormispropagationovera
publicnetwork,suchastheInternet.Aviruspropagatesby
infectingexecutablesonthemachine,whereasawormtendsto
preferexploitingknownsecurityholesinnetworkserversto
gainrootaccessandthentriestoinfectothermachinesinthe
sameway.
UNIX/Linuxfilepermissionshelptoinoculatesystemsagainst
manyviruses.WindowsNTisresistantforsimilarreasons.You
caneasilyprotectyoursystemagainstmanyvirusesandworms
bykeepingyoursystempatchesup-to-date,notexecuting
untrustedbinariesfromtheInternet,limitingyourpathto
includeonlynecessarysystemdirectories,anddoingaslittleas
possiblewhileenabledwithSuperuserprivileges.Youcan
preventadisasterincaseavirusstrikesbybackingupyour
systemfrequently.
PhysicalSecurity
Oftenoverlookedasadefenseagainstintrusion,physical
securitycoversaccesstothecomputeritselfandtotheconsole
orterminalattachedtothemachine.Ifthemachineis
unprotectedinanunlockedroom,thereisverylittlehopefor
physicalsecurity.(Asimpleexampleofphysicalvulnerabilityis
someonewalkingintotheroomwherethecomputeris,
removingtheharddrivefromthecomputer,takingithome,and
analyzingit.)Youcantakecertainstepstoimprovethephysical
securityofyourcomputer.
Keepserversinalockedroomwithlimitedaccess.Akey,a
combination,oraswipecardshouldberequiredtogain
access.Protectwindowsaswellasdoors.Maintainasingle
pointofentry.(Safetycodesmayrequiremultipleexits,but
onlyonemustbeanentry.)
Forpublicmachines,useasecuritysystem,suchasa
fiberopticsecuritysystem,thatcansecurealabfullof
machines.Withsuchasystem,yourunafiberopticcable
througheachmachinesuchthatthemachinecannotbe
removed(oropened)withoutcuttingthecable.Whenthe
cableiscut,analarmgoesoff.Somemachinesforexample,
PCswithplasticcasesaremuchmoredifficulttosecurethan
others.Althoughitisnotaperfectsolution,afiberoptic
securitysystemmayimprovelocalsecurityenoughto
persuadeawould-bethieftogosomewhereelse.
MostmodernPCshaveaBIOSpassword.Youcansetthe
orderinwhichaPCsearchesforabootdevice,preventing
thePCfrombeingbootedfromafloppydiskorCD.Some
BIOSscanpreventthemachinefrombootingaltogether
withoutaproperpassword.ThepasswordprotectstheBIOS
fromunauthorizedmodification.Beware,however:Many
BIOSshavewell-knownbackdoors(page1020).Research
thisissueiftheBIOSpasswordisanimportantfeaturefor
you.Inaddition,youcanblanktheBIOSpasswordby
settingtheclear-CMOSjumperonaPCmotherboard;ifyou
arerelyingonaBIOSpassword,lockthecase.
Runonlyfiberopticcablebetweenbuildings.Thisstrategyis
notonlymoresecurebutalsosaferintheeventoflightning
strikesandisrequiredbymanycommercialbuildingcodes.
Maintainlogsofwhogoesinandoutofsecureareas.Sign-
in/outsheetsareusefulonlyifeveryoneusesthem.
Sometimesaguardiswarranted.Oftenasimpleproximity
badgeorsmartcardcantellwhenanyonehasenteredor
leftanareaandkeeplogsoftheseevents,althoughthese
canbeexpensivetoprocureandinstall.
Anyonewhohasaccesstothephysicalhardwarehasthe
keystothepalace.Someonewithdirectaccesstoa
computersystemcandosuchthingsasswapcomponents
andinsertbootmedia,allofwhicharesecuritythreats.
Avoidhavingactivated,unusednetworkjacksinpublic
places.Suchjacksprovideunnecessaryrisk.
Manymodernswitchescanlockaparticularswitchportso
thatitacceptsonlytrafficfromanNIC(networkinterface
card)withaparticularhardwareaddressandshutsdown
theportifanotheraddressisseen.However,commonly
availableprogramscanenablesomeonetoresetthis
address.
Makeperiodicsecuritysweeps.Checkdoorsforproper
locking.Ifyoumusthavewindows,makesurethattheyare
lockedorarepermanentlysealed.
Wastereceptaclesareoftenasourceofinformationfor
intruders.Havepoliciesforcontainmentanddisposalof
sensitivedocuments.
UseaUPS(uninterruptablepowersupply).Withoutaclean
sourceofpower,yoursystemisvulnerabletocorruption.
AppendixSummary
Securityisinverselyproportionaltousability.Theremustbea
balancebetweenyourusers'requirementstogettheirwork
doneandtheamountofsecuritythatisimplemented.Itisoften
unnecessarytoprovidetopsecurityforasmallbusinesswith
onlyafewemployees.Bycontrast,ifyouworkfora
governmentmilitarycontractor,youareboundtohaveextreme
securityconstraintsandanofficialauditpolicytodetermine
whetheryoursecuritypoliciesarebeingimplementedcorrectly.
Reviewyourownsecurityrequirementsperiodically.Severalof
thetoolsmentionedinthisappendixaredesignedtohelpyou
monitoryoursystem'ssecuritymeasures.Suchtoolsasnessus,
samhain,andSAINTallprovideauditingmechanisms.
Somecompaniesspecializeinsecurityandauditing.Hiringone
ofthemtoexamineyoursitecanbecostlybutmayyield
specificrecommendationsforareasthatyoumayhave
overlookedinyourinitialsetup.Whenyouhiresomeoneto
audityoursecurity,recognizethatyoumaybeprovidingboth
physicalandSuperuseraccesstoyoursystems.Makesurethe
companythatyouhirehasagoodhistory,hasbeeninbusiness
forseveralyears,andhasimpeccablereferences.Checkupon
thecompanyperiodically:Thingschangeovertime.Avoidthe
temptationtohireformersystemcrackersasconsultants.
Securityconsultantsshouldhaveanirreproachableethical
background,oryouwillalwayshavedoubtsabouttheir
intentions.
Yourtotalsecuritypackageisbasedonyourriskassessmentof
yourvulnerabilities.Strengthenthoseareasthataremost
importantforyourbusiness.Forexample,manysitesrelyona
firewalltoprotectthemfromtheInternet,whereasinternal
hostsreceivelittleornosecurityattention.Crackersreferto
thissetupas"thecrunchyoutsidesurroundingthesoftchewy
middle."Yetthisisentirelysufficienttoprotectsomesites.
Performyourownriskassessmentandaddressyourneeds
accordingly.Ifneedbe,hireafull-timesecurityadministrator
whosejobitistodesignandaudityoursecuritypolicies.
D.TheFreeSoftwareDefinition[1]
[1]Thismaterialisatwww.gnu.org/philosophy/free-sw.htmlontheGNUWebsite.
BecauseGNUrequestsaverbatimcopy,linksremaininplace(underlined).Viewthe
documentontheWebtoensureyouarereadingthelatestcopyandtofollowthelinks.
Wemaintainthisfreesoftwaredefinitiontoshowclearlywhat
mustbetrueaboutaparticularsoftwareprogramforittobe
consideredfreesoftware.
"Freesoftware"isamatterofliberty,notprice.Tounderstand
theconcept,youshouldthinkof"free"asin"freespeech,"not
asin"freebeer."
Freesoftwareisamatteroftheusers'freedomtorun,copy,
distribute,study,changeandimprovethesoftware.More
precisely,itreferstofourkindsoffreedom,fortheusersofthe
software:
Thefreedomtoruntheprogram,foranypurpose(freedom
0).
Thefreedomtostudyhowtheprogramworks,andadaptit
toyourneeds(freedom1).Accesstothesourcecodeisa
preconditionforthis.
Thefreedomtoredistributecopiessoyoucanhelpyour
neighbor(freedom2).
Thefreedomtoimprovetheprogram,andreleaseyour
improvementstothepublic,sothatthewholecommunity
benefits(freedom3).Accesstothesourcecodeisa
preconditionforthis.
Aprogramisfreesoftwareifusershaveallofthesefreedoms.
Thus,youshouldbefreetoredistributecopies,eitherwithor
withoutmodifications,eithergratisorchargingafeefor
distribution,toanyoneanywhere.Beingfreetodothesethings
means(amongotherthings)thatyoudonothavetoaskorpay
forpermission.
Youshouldalsohavethefreedomtomakemodificationsand
usethemprivatelyinyourownworkorplay,withouteven
mentioningthattheyexist.Ifyoudopublishyourchanges,you
shouldnotberequiredtonotifyanyoneinparticular,orinany
particularway.
Thefreedomtouseaprogrammeansthefreedomforanykind
ofpersonororganizationtouseitonanykindofcomputer
system,foranykindofoveralljob,andwithoutbeingrequired
tocommunicatesubsequentlywiththedeveloperoranyother
specificentity.
Thefreedomtoredistributecopiesmustincludebinaryor
executableformsoftheprogram,aswellassourcecode,for
bothmodifiedandunmodifiedversions.(Distributingprograms
inrunnableformisnecessaryforconvenientlyinstallablefree
operatingsystems.)Itisokifthereisnowaytoproducea
binaryorexecutableformforacertainprogram(sincesome
languagesdon'tsupportthatfeature),butyoumusthavethe
freedomtoredistributesuchformsshouldyoufindordevelopa
waytomakethem.
Inorderforthefreedomstomakechanges,andtopublish
improvedversions,tobemeaningful,youmusthaveaccessto
thesourcecodeoftheprogram.Therefore,accessibilityof
sourcecodeisanecessaryconditionforfreesoftware.
Oneimportantwaytomodifyaprogramisbymergingin
availablefreesubroutinesandmodules.Iftheprogram'slicense
saysthatyoucannotmergeinanexistingmodule,suchasifit
requiresyoutobethecopyrightholderofanycodeyouadd,
thenthelicenseistoorestrictivetoqualifyasfree.
Inorderforthesefreedomstobereal,theymustbeirrevocable
aslongasyoudonothingwrong;ifthedeveloperofthe
softwarehasthepowertorevokethelicense,withoutyour
doinganythingtogivecause,thesoftwareisnotfree.
However,certainkindsofrulesaboutthemannerofdistributing
freesoftwareareacceptable,whentheydon'tconflictwiththe
centralfreedoms.Forexample,copy-left(verysimplystated)is
therulethatwhenredistributingtheprogram,youcannotadd
restrictionstodenyotherpeoplethecentralfreedoms.Thisrule
doesnotconflictwiththecentralfreedoms;ratheritprotects
them.
Youmayhavepaidmoneytogetcopiesoffreesoftware,oryou
mayhaveobtainedcopiesatnocharge.Butregardlessofhow
yougotyourcopies,youalwayshavethefreedomtocopyand
changethesoftware,eventosellcopies.
"Freesoftware"doesnotmean"non-commercial".Afree
programmustbeavailableforcommercialuse,commercial
development,andcommercialdistribution.Commercial
developmentoffreesoftwareisnolongerunusual;suchfree
commercialsoftwareisveryimportant.
Rulesabouthowtopackageamodifiedversionareacceptable,
iftheydon'tsubstantivelyblockyourfreedomtorelease
modifiedversions,oryourfreedomtomakeandusemodified
versionsprivately.Rulesthat"ifyoumakeyourversion
availableinthisway,youmustmakeitavailableinthatway
also"canbeacceptabletoo,onthesamecondition.(Notethat
sucharulestillleavesyouthechoiceofwhethertopublishyour
versionatall.)Rulesthatrequirereleaseofsourcecodetothe
usersforversionsthatyouputintopublicusearealso
acceptable.Itisalsoacceptableforthelicensetorequirethat,
ifyouhavedistributedamodifiedversionandaprevious
developerasksforacopyofit,youmustsendone,orthatyou
identifyyourselfonyourmodifications.
IntheGNUproject,weuse"copyleft"toprotectthesefreedoms
legallyforeveryone.Butnon-copyleftedfreesoftwarealso
exists.Webelievethereareimportantreasonswhyitisbetter
tousecopyleft,butifyourprogramisnon-copyleftedfree
software,wecanstilluseit.
SeeCategoriesofFreeSoftwareforadescriptionofhow"free
software,""copy-leftedsoftware"andothercategoriesof
softwarerelatetoeachother.
Sometimesgovernmentexportcontrolregulationsandtrade
sanctionscanconstrainyourfreedomtodistributecopiesof
programsinternationally.Softwaredevelopersdonothavethe
powertoeliminateoroverridetheserestrictions,butwhatthey
canandmustdoisrefusetoimposethemasconditionsofuse
oftheprogram.Inthisway,therestrictionswillnotaffect
activitiesandpeopleoutsidethejurisdictionsofthese
governments.
Mostfreesoftwarelicensesarebasedoncopyright,andthere
arelimitsonwhatkindsofrequirementscanbeimposed
throughcopyright.Ifacopyright-basedlicenserespects
freedominthewaysdescribedabove,itisunlikelytohave
someothersortofproblemthatweneveranticipated(though
thisdoeshappenoccasionally).However,somefreesoftware
licensesarebasedoncontracts,andcontractscanimposea
muchlargerrangeofpossiblerestrictions.Thatmeansthereare
manypossiblewayssuchalicensecouldbeunacceptably
restrictiveandnon-free.
Wecan'tpossiblylistallthewaysthatmighthappen.Ifa
contract-basedlicenserestrictstheuserinanunusualwaythat
copyright-basedlicensescannot,andwhichisn'tmentioned
hereaslegitimate,wewillhavetothinkaboutit,andwewill
probablyconcludeitisnon-free.
Whentalkingaboutfreesoftware,itisbesttoavoidusingterms
like"giveaway"or"forfree",becausethosetermsimplythat
theissueisaboutprice,notfreedom.Somecommonterms
suchas"piracy"embodyopinionswehopeyouwon'tendorse.
SeeConfusingWordsandPhrasesthatareWorthAvoidingfora
discussionoftheseterms.Wealsohavealistoftranslationsof
"freesoftware"intovariouslanguages.
Finally,notethatcriteriasuchasthosestatedinthisfree
softwaredefinitionrequirecarefulthoughtfortheir
interpretation.Todecidewhetheraspecificsoftwarelicense
qualifiesasafreesoftwarelicense,wejudgeitbasedonthese
criteriatodeterminewhetheritfitstheirspiritaswellasthe
precisewords.Ifalicenseincludesunconscionablerestrictions,
werejectit,evenifwedidnotanticipatetheissueinthese
criteria.Sometimesalicenserequirementraisesanissuethat
callsforextensivethought,includingdiscussionswithalawyer,
beforewecandecideiftherequirementisacceptable.Whenwe
reachaconclusionaboutanewissue,weoftenupdatethese
criteriatomakeiteasiertoseewhycertainlicensesdoordon't
qualify.
Ifyouareinterestedinwhetheraspecificlicensequalifiesasa
freesoftwarelicense,seeourlistoflicenses.Ifthelicenseyou
areconcernedwithisnotlistedthere,youcanaskusaboutit
bysendingusemailatlicensing@gnu.org.
Ifyouarecontemplatingwritinganewlicense,pleasecontact
theFSFbywritingtothataddress.Theproliferationofdifferent
freesoftwarelicensesmeansincreasedworkforusersin
understandingthelicenses;wemaybeabletohelpyoufindan
existingFreeSoftwarelicensethatmeetsyourneeds.
Ifthatisn'tpossible,ifyoureallyneedanewlicense,withour
helpyoucanensurethatthelicensereallyisaFreeSoftware
licenseandavoidvariouspracticalproblems.
Anothergrouphasstartedusingtheterm"opensource"to
meansomethingclose(butnotidentical)to"freesoftware".We
prefertheterm"freesoftware"because,onceyouhaveheardit
referstofreedomratherthanprice,itcallstomindfreedom.
Theword"open"neverdoesthat.
OtherTextstoRead
Translationsofthispage:
[Català|Chinese(Simplified)|Chinese(Traditional)|Czech|
Dansk|Deutsch|English|Español|Persian/Farsi|Français|
Galego|Hebrew|Hrvatski|BahasaIndonesia|Italiano|
Japanese|Korean|Magyar|Nederlands|Norsk|Polski|
Português|Româna|Russian|Slovinsko|Serbian|Tagalog|
Türkçe]
ReturntotheGNUProjecthomepage.
PleasesendFSF&GNUinquiriestognu@gnu.org.Thereare
alsootherwaystocontacttheFSF.
Pleasesendbrokenlinksandothercorrections(orsuggestions)
towebmasters@gnu.org
PleaseseetheTranslationsREADMEforinformationon
coordinatingandsubmittingtranslationsofthisarticle.
Copyright(C)1996,1997,1998,1999,2000,2001,2002,
2003,2004FreeSoftwareFoundation,Inc.,51FranklinSt,Fifth
Floor,Boston,MA02110,USA
Verbatimcopyinganddistributionofthisentirearticleis
permittedinanymediumwithoutroyaltyprovidedthisnoticeis
preserved.
Updated:$Date:2005/11/2613:16:40$$Author:rms$
E.TheLinux2.6Kernel
TheLinux2.6kernelwasreleasedonDecember17,2003.A
majorreleaseofaLinuxkernelisnotaneverydayoccurrence:
Thelastkernel,Linux2.4,wasreleasedinJanuary2001.This
appendixlistsfeaturesthatarenewtothe2.6kernel.
Linuxkernelrevisionsalternatebetweenstableandunstable
versions:2.4wasthepreviousstableversion,so2.5wasthe
developmentbranch,whichlaterbecame2.6.Foreachofthe
majorrevisions,thereisaseriesofminorrevisions.Usually,
minorrevisionsdonotcontainmajorchanges,althoughone
minorrevisiontothe2.4kernelreplacedtheentirevirtual
memorysubsystem,amajorpartofthekernel.
FedoraCore2andaboveandRedHatEnterpriseLinuxv.4and
aboveincludethe2.6kernel.
Seewww.kniggit.net/wwol26.htmlifyouwantmoreinformation
ontheLinux2.6kernelthanthisappendixprovides.
NativePosixThreadLibrary(NPTL)
Classicallyprogramsstartexecutionatthebeginningofaseries
ofinstructionsandexecutetheminsequence.Whilethis
techniqueworkswellforsimpleprogramsrunningonsingleCPU
systems,itisoftenbettertoallowaprogramtoexecute
differentpartsofitselfsimultaneouslyinparallel.Most
programswithaGUIbenefitfromthisfunctionalityasitcan
preventtheuserinterfacefromfreezingwhiletheprogram
performscomputations.
ThetraditionalwayofwritingparallelcodeunderUNIXisto
executeafork()systemcall(page861),whichcreatesacopy
oftherunningprograminmemoryandstartsitexecutingatthe
samepointastheoriginal.Atthepointfork()iscalled,thetwo
copiesoftheprogramareindistinguishable,exceptforthefact
thattheyreceivedifferentreturnvaluesfromtheirfork()call.
Onedisadvantageofthisapproachisthateachtimefork()is
called,thesystemmustcreateacompletecopyoftheprocess.
Thiscopyingtakesarelativelylongtimeandcausesparallel
applicationstousealotofmemory.(Thisdescriptionisnot
quiteaccurate:Copy-on-writefunctionalityinamodern
operatingsystemcopiesonlythosepartsofmemorythatwould
bedifferent.)
Amoreefficientsolutiontothisproblemistoallowasingle
processtorunmultiplethreads.Athreadexistsinthesame
memoryspaceasotherthreadsandsohasamuchsmaller
overheadthanasingleprogramrunningmultipleprocesses.
Thedisadvantageofthisstrategyisthatmultithreaded
applicationsmustbedesignedmorecarefullyandthustake
moretimetowritethanmultiprocessorones.Operating
systems,suchasSolaris,relyheavilyonthreadstoprovide
scalabilitytoverylargeSMP(symmetricmultiprocessing)
systems.ThenewthreadingsupportintheLinux2.6kernel
usesthesameindustrystandardPOSIXAPIsasSolarisfor
implementingthreadsandprovideshigh-performance
processing.
IPSecurity(IPSec)
IPSecisanetworklayerprotocolsuitethatsecuresInternet
connectionsbyencryptingIPpackets.IPSecisanoptionalpart
ofIPv4(page1038)andarequiredpartofIPv6(page1038).
Seepage995formoreinformationonIPSec.
KernelintegrationofIPSecmeansthatanykernelmoduleor
applicationcanuseIPSecinthesamewaythatitwoulduse
unsecuredIP.
AsynchronousI/O(AIO)
WithoutAIO,whenanapplicationneedstogetdatafroma
hardwaredeviceoranetworkconnection,itcaneitherpollthe
connectionuntilthedatabecomesavailableorspawnathread
fortheconnectionthatwaitsforthedata.Neitherofthese
techniquesisparticularlyefficient.
AsynchronousI/Oallowsthekerneltonotifyanapplication
whenithasdatareadytoberead.Thisfeatureismostusefulto
largeserversbutcanprovidemoderateperformancegainsin
almostanyapplication.
0(1)Scheduler
Oneoftheresponsibilitiesofthekernelistomakesurethat
eachexecutionthreadgetsareasonableamountoftimeonthe
CPU(s).TheschedulingalgorithmusedintheLinux2.4kernel
graduallydecreasedperformanceasmoreprocesseswere
addedandadditionalCPUswerebroughtonline,makingithard
touseLinuxonlargeSMPsystems.The2.6scheduling
algorithmrunsinO(1)time,atermthatindicatesthata
processtakesthesametimetorununderallconditions,making
Linuxbetterabletorunlargenumbersofprocessesandscale
tolargesystems.
OProfile
Itisoftensaidthataprogramspends90percentofitstime
executing10percentofthecode.Programmersuseprofiling
toolstoidentifybottlenecksincodeandtargetthis10percent
foroptimization.OProfileisanadvancedprofilingtoolthat
identifiescommonprogramminginefficiencies.Thankstoits
closerelationshipwiththekernel,OProfileisabletoidentify
hardware-specificefficiencyproblems,suchascachemisses,
whichareoftennotpossibletoidentifyfromsourcecode.
kksymoops
Whensomethinggoeswronginthekernel,itgeneratesanerror
messagecalledanOOPS.Thismessageisanin-jokefromthe
LinuxKernelMailingList,wheredeveloperswouldstartbug
reportswith"Oops,we'vefoundabuginthekernel."AnOOPS
providesdebugginginformationthatcanhelpkerneldevelopers
trackdowntheoffendingcodeorindicatethattheOOPSwas
causedbyhardwarefailure.
Thekksymoopsfunctionalityprovidesdetaileddebugging
information,allowingadevelopertodeterminethelineofcode
inthekernelthatcausedtheOOPS.Whilethisfeaturedoesnot
directlybenefittheenduser,itallowsdeveloperstofindkernel
bugsmorequickly,resultinginamorestablekernel.
ReverseMapVirtualMemory(RMAPVM)
Virtualmemory(VM)allowseachprocesstoexistinitsown
memoryspace.Everytimeaprocessattemptstoaccessa
portionofmemory,thekerneltranslatesthememorylocation
fromanaddressintheprocess'sownaddressspacetoonein
realmemory.Thereversemapenablesthekerneltoperform
thisprocessinreverse:Givenalocationinphysicalmemory,
thekernelcandeterminewhichprocessownsit.Thereverse
mapallowspagestobeunallocatedquickly,givingthesystem
morefreememory,fewerpagefaults,andlessoverheadwhen
quittingaprogram.
HugeTLBFS:TranslationLook-AsideBuffer
Filesystem
Thekernelallocatesmemoryinunitsofpages.Virtualmemory
usesthesepagestomapbetweenthevirtualandrealmemory
addressspaces.OlderversionsoftheLinuxkernelsetthesize
ofthesepagesto4kilobytes.Incaseswherealotofvirtual
memoryisused,suchasinlargedatabaseservers,thissmall
sizecanplaceaheavyloadontheVMsubsystem.HugeTLBFS
allowsformuchlargerpages,whichsignificantlyimproves
performanceunderheavyVMloadconditions.
remap_file_pages
Whenretrievingdatafromorwritingdatatoafile,itiscommon
practicetomapthefileondisktoanareaofmemory.The
systemthentranslatesaccessestothatareaofmemorydirectly
intoaccessestodisk.
Foradditionalflexibility,largedatabasesystemsmapdifferent
partsofafiletodifferentpartsofmemory.Eachmapping
resultsinanadditionalloadonthekernelandVMsubsystems.
Theremap_file_pages()systemcallcanperforma
nonuniformmapping,meaningthatafileneedstobemapped
onlyonce,whichsignificantlyimprovestheperformanceof
largedatabaseservers.
2.6NetworkStackFeatures(IGMPv3,IPv6,and
Others)
TheLinux2.6kernelincludesalargenumberofimprovements
intheareaofnetworking,includingsupportforIPv6(page
1038)andenhancedmulticast(page1044)support.Although
thesefeaturesdonotimmediatelybenefitendusers,theydo
permitthedevelopmentanddeploymentofnetworkservices
thatwillnotrequiresignificantmodificationforintegrationwith
futuretechnologies.
InternetProtocolVirtualServer(IPVS)
IPVSimplementstransportlayerswitchinginsidethekernelfor
loadbalancing.Thisfeatureenablesasinglemachineto
distributeconnectionstoaserverfarm,allowingtransparent
loadbalancing.
AccessControlLists(ACLs)
ThetraditionalUNIXpermissionsystemallowsthree
permissionstobeassignedtoeachfile:controllingaccessby
theowner,byasinglegroup,andbyeveryoneelse.ACLs
providemuchfiner-grainedaccesscontrol.Intheory,ACLscan
increasesecurity.However,theymakesettingcorrect
permissionsmorecomplicated,whichmayencourage
administratorstoestablishweakercontrolsthantheyshould.
4GB-4GBMemorySplit:PhysicalAddress
Extension(PAE)
AlthoughRedHatspeaksofthe4GB-4GBMemorySplitinits
discussionofthe2.6kernel,thisterminologyhasnothingtodo
withthenewkernel.ThememorysplitisaRedHat
enhancementtotheEnterpriseandFedorakernels;itisnot
integratedintothemainsourcetree(itisnotpartofthe2.6
kernel).
The32-bitCPUsarelimitedinthattheycanaddressonly232
bytes(4gigabytes)ofmemory.WiththePentiumPro,Intel
introducedawork-aroundtothislimitationcalledPhysical
AddressExtension(PAE),whichpermitstheoperatingsystem
toaddressupto64gigabytesofmemory.Becausetheyare
limitedtoaddressing4gigabyteseach,32-bitprogramscannot
accessthismuchmemory.ALinuxkernelfromthemaintreeis
abletoallocateupto1gigabyteforthekerneland3gigabytes
foreachuserspace(page1062)process.
ThekernelsshippedwithRedHatLinuxarepatchedtoallowthe
kerneltoallocateupto4gigabytesforitselfand3.7gigabytes
foreachuserspaceprocess.TheselimitationsaffectLinuxon
32-bitarchitecturesonly.A64-bitLinuxkernelona64-bitCPU,
suchasaSPARC64,UltraSparc,Alpha,orOpteron,isableto
accessupto16exabytes(16x260bytes)ofRAM.
SchedulerSupportforHyperThreadedCPUs
TheLinux2.6kernelsupportsIntel'sHyperThreading.The2.6
kerneltreatseachvirtualCPUastheequivalentofaphysical
CPU.
SupportforFilesystemsLargerThan2
Terabytes
TheLinux2.6kernelincludesSGI'sXFSjournalingfilesystem,
whichsupportsfilesystemsofupto9exabytes(9x260bytes).
NewI/OElevators
I/OelevatorscontrolhowlongI/Orequestscanbequeuedto
allowthemtobere-orderedforoptimaldeviceperformance.
TheLinux2.6kernelincludessomeadditionalsettingsthat
allowI/Oelevatorstobetunedforspecifichigh-device-load
situations.
InteractiveSchedulerResponseTuning
ThenewschedulerintheLinux2.6kernelprioritizesI/Obound
processes.Becausemostuserinterfaceprocessesspendmost
oftheirtimewaitingforinputfromtheuser,thistuningshould
resultinamoreresponsivesystemunderhighsystemload.
Glossary
AllentriesmarkedwithFOLDOCarebasedondefinitionsinthe
FreeOnlineDictionaryofComputing(www.foldoc.org),Denis
Howe,editor.Usedwithpermission.
10.0.0.0
Seeprivateaddressspaceonpage1049.
172.16.0.0
Seeprivateaddressspaceonpage1049.
192.168.0.0
Seeprivateaddressspaceonpage1049.
802.11
AfamilyofspecificationsdevelopedbyIEEEforwireless
LANtechnology,including802.11(12megabitsper
second),802.11a(54megabitspersecond),802.11b(11
megabitspersecond),and802.11g(54megabitsper
second).
absolutepathname
Apathnamethatstartswiththerootdirectory(/).An
absolutepathnamelocatesafilewithoutregardtothe
workingdirectory.
access
Incomputerjargon,averbmeaningtouse,readfrom,or
writeto.Toaccessafilemeanstoreadfromorwritetothe
file.
AccessControlList
SeeACL.
accesspermission
Permissiontoreadfrom,writeto,orexecuteafile.Ifyou
havewriteaccesspermissiontoafile,youcanwritetothe
file.Alsoaccessprivilege.
ACL
AccessControlList.Asystemthatperformsafunction
similartofilepermissionsbutwithmuchfiner-graincontrol.
activewindow
Onadesktop,thewindowthatreceivesthecharactersyou
typeonthekeyboard.Sameasfocus,desktop(page1032).
addressmask
Seesubnetmaskonpage1058.
alias
Amechanismofashellthatenablesyoutodefinenew
commands.
alphanumericcharacter
Oneofthecharacters,eitheruppercaseorlowercase,from
AtoZand0to9,inclusive.
ambiguousfilereference
Areferencetoafilethatdoesnotnecessarilyspecifyany
onefilebutcanbeusedtospecifyagroupoffiles.Theshell
expandsanambiguousfilereferenceintoalistoffilenames.
Specialcharactersrepresentsinglecharacters(?),stringsof
zeroormorecharacters(*),andcharacterclasses([])
withinambiguousfilereferences.Anambiguousfile
referenceisatypeofregularexpression(page1052).
anglebracket
Aleftanglebracket(<)andarightanglebracket(>).The
shelluses<toredirectacommand'sstandardinputto
comefromafileand>toredirectthestandardoutput.The
shellusesthecharacters<<tosignifythestartofaHere
documentand>>toappendoutputtoafile.
animate
Whenreferringtoawindowaction,meansthattheactionis
sloweddownsotheusercanviewit.Forexample,when
youminimizeawindow,itcandisappearallatonce(not
animated)oritcanslowlytelescopeintothepanelsoyou
cangetavisualfeelforwhatishappening(animated).
anti-aliasing
Addinggraypixelsattheedgeofadiagonallinetogetrid
ofthejaggedappearanceandtherebymakethelinelook
smoother.Anti-aliasingsometimesmakestypeonascreen
lookbetterandsometimesworse;itworksbestonsmall
andlargefontsandislesseffectiveonfontsfrom8to15
points.Seealsosubpixelhinting(page1058).
API
Applicationprograminterface.Theinterface(calling
conventions)bywhichanapplicationprogramaccessesan
operatingsystemandotherservices.AnAPIisdefinedat
thesourcecodelevelandprovidesalevelofabstraction
betweentheapplicationandthekernel(orotherprivileged
utilities)toensuretheportabilityofthecode.FOLDOC
append
Toaddsomethingtotheendofsomethingelse.Toappend
texttoafilemeanstoaddthetexttotheendofthefile.
Theshelluses>>toappendacommand'soutputtoafile.
applet
Asmallprogramthatrunswithinalargerprogram.
ExamplesareJavaappletsthatruninabrowserandpanel
appletsthatrunfromadesktoppanel.
archive
Afilethatcontainsagroupofsmaller,typicallyrelated,
files.Also,tocreatesuchafile.Thetarandcpioutilitiescan
createandreadarchives.
argument
Anumber,letter,filename,oranotherstringthatgives
someinformationtoacommandandispassedtothe
commandwhenitiscalled.Acommandlineargumentis
anythingonacommandlinefollowingthecommandname
thatispassedtothecommand.Anoptionisakindof
argument.
arithmeticexpression
Agroupofnumbers,operators,andparenthesesthatcan
beevaluated.Whenyouevaluateanarithmeticexpression,
youendupwithanumber.TheBourneAgainShellusesthe
exprcommandtoevaluatearithmeticexpressions;theTC
Shelluses@,andtheZShelluseslet.
array
Anarrangementofelements(numbersorstringsof
characters)inoneormoredimensions.TheBourneAgain,
TC,andZShellsandgawkcanstoreandprocessarrays.
ASCII
AmericanStandardCodeforInformationInterchange.A
codethatusessevenbitstorepresentbothgraphic(letters,
numbers,andpunctuation)andCONTROLcharacters.You
canrepresenttextualinformation,includingprogramsource
codeandEnglishtext,inASCIIcode.BecauseASCIIisa
standard,itisfrequentlyusedwhenexchanginginformation
betweencomputers.Seethefile/usr/pub/asciiorgive
thecommandmanasciitoseealistofASCIIcodes.
ExtensionsoftheASCIIcharactersetuseeightbits.The
seven-bitsetiscommon;theeight-bitextensionsarestill
comingintopopularuse.Theeighthbitissometimes
referredtoasthemetabit.
ASCIIterminal
Atextualterminal.Contrastwithgraphicaldisplay(page
1033).
ASP
Applicationserviceprovider.Acompanythatprovides
applicationsovertheInternet.
asynchronousevent
Aneventthatdoesnotoccurregularlyorsynchronously
withanotherevent.Linuxsystemsignalsareasynchronous;
theycanoccuratanytimebecausetheycanbeinitiatedby
anynumberofnonregularevents.
attachment
Afilethatisattachedto,butisnotpartof,apieceofemail.
Attachmentsarefrequentlyopenedbyprograms(including
yourInternetbrowser)thatarecalledbyyourmailprogram
soyoumaynotbeawarethattheyarenotanintegralpart
ofanemailmessage.
authentication
Theverificationoftheidentityofapersonorprocess.Ina
communicationsystem,authenticationverifiesthata
messagecomesfromitsstatedsource.Methodsof
authenticationonaLinuxsystemincludethe/etc/passwd
and/etc/shadowfiles,LDAP,Kerberos5,andSMB
authentication.FOLDOC
automaticmounting
Awayofdemandmountingdirectoriesfromremotehosts
withouthavingthemhardconfiguredinto/etc/fstab.Also
calledautomounting.
avoided
Anobject,suchasapanel,thatshouldnotnormallybe
coveredbyanotherobject,suchasawindow.
backdoor
Asecurityholedeliberatelyleftinplacebythedesignersor
maintainersofasystem.Themotivationforcreatingsuch
holesisnotalwayssinister;someoperatingsystems,for
example,comeoutoftheboxwithprivilegedaccounts
intendedforusebyfieldservicetechniciansorthevendor's
maintenanceprogrammers.
KenThompson's1983TuringAwardlecturetotheACM
revealedtheexistence,inearlyUNIXversions,ofaback
doorthatmaybethemostfiendishlycleversecurityhackof
alltime.TheCcompilercontainedcodethatwould
recognizewhenthelogincommandwasbeingrecompiled
andwouldinsertsomecoderecognizingapasswordchosen
byThompson,givinghimentrytothesystemwhetheror
notanaccounthadbeencreatedforhim.
Normallysuchabackdoorcouldberemovedbyremovingit
fromthesourcecodeforthecompilerandrecompilingthe
compiler.Buttorecompilethecompiler,youhavetousethe
compiler,soThompsonarrangedthatthecompilerwould
recognizewhenitwascompilingaversionofitself.Itwould
insertintotherecompiledcompilerthecodetoinsertinto
therecompiledloginthecodetoallowThompsonentry,
and,ofcourse,thecodetorecognizeitselfanddothe
wholethingagainthenexttimearound.Havingdonethis
once,hewasthenabletorecompilethecompilerfromthe
originalsources;thehackperpetuateditselfinvisibly,
leavingthebackdoorinplaceandactivebutwithnotrace
inthesources.
Sometimescalledawormhole.Alsotrapdoor.FOLDOC
backgroundprocess
Aprocessthatisnotrunintheforeground.Alsocalleda
detachedprocess,abackgroundprocessisinitiatedbya
commandlinethatendswithanampersand(&).Youdonot
havetowaitforabackgroundprocesstoruntocompletion
beforegivingtheshelladditionalcommands.Ifyouhave
jobcontrol,youcanmovebackgroundprocessestothe
foreground,andviceversa.
basename
Thenameofafilethat,incontrastwithapathname,does
notmentionanyofthedirectoriescontainingthefile(and
thereforedoesnotcontainanyslashes[/]).Forexample,
hostsisthebasenameof/etc/hosts.FOLDOC
baud
Themaximuminformation-carryingcapacityofa
communicationchannelinsymbols(statetransitionsor
leveltransitions)persecond.Itcoincideswithbitsper
secondonlyfortwo-levelmodulationwithnoframingor
stopbits.Asymbolisauniquestateofthecommunication
channel,distinguishablebythereceiverfromallother
possiblestates.Forexample,itmaybeoneoftwovoltage
levelsonawireforadirectdigitalconnection,oritmightbe
thephaseorfrequencyofacarrier.FOLDOC
Baudisoftenmistakenlyusedasasynonymforbitsper
second.
baudrate
Transmissionspeed.Usuallyusedtomeasureterminalor
modemspeed.Commonbaudratesrangefrom110to
38,400baud.Seebaud.
BerkeleyUNIX
OneofthetwomajorversionsoftheUNIXoperating
system.BerkeleyUNIXwasdevelopedattheUniversityof
CaliforniaatBerkeleybytheComputerSystemsResearch
GroupandisoftenreferredtoasBSD(BerkeleySoftware
Distribution).
BIND
BerkeleyInternetNameDomain.Animplementationofa
DNS(page1029)serverdevelopedanddistributedbythe
UniversityofCaliforniaatBerkeley
BIOS
BasicInput/OutputSystem.OnPCs,EEPROM-based(page
1030)systemsoftwarethatprovidesthelowest-level
interfacetoperipheraldevicesandcontrolsthefirststageof
thebootstrap(page1022)process,whichloadsthe
operatingsystem.TheBIOScanbestoredindifferenttypes
ofmemory.Thememorymustbenonvolatilesothatit
remembersthesystemsettingsevenwhenthesystemis
turnedoff.AlsoBIOSROM.Refertopage26forinstructions
onhowtoopentheBIOSscreensformaintenance.
bit
Thesmallestpieceofinformationacomputercanhandle.A
bitisabinarydigit:either1or0(onoroff).
bitdepth
Sameascolordepth(page1025).
bit-mappeddisplay
Agraphicaldisplaydeviceinwhicheachpixelonthescreen
iscontrolledbyanunderlyingrepresentationofzerosand
ones.
blankcharacter
EitheraSPACEoraTABcharacter,alsocalledwhitespace
(page1063).Insomecontexts,NEWLINEsareconsidered
blankcharacters.
block
Asectionofadiskortape(usually1,024byteslongbut
shorterorlongeronsomesystems)thatiswrittenatone
time.
blockdevice
Adiskortapedrive.Ablockdevicestoresinformationin
blocksofcharacters.Ablockdeviceisrepresentedbya
blockdevice(blockspecial)file.Contrastwithcharacter
device(page1024).
blocknumber
DiskandtapeblocksarenumberedsothatLinuxcankeep
trackofthedataonthedevice.
blockingfactor
Thenumberoflogicalblocksthatmakeupaphysicalblock
onatapeordisk.Whenyouwrite1Klogicalblockstoa
tapewithaphysicalblocksizeof30K,theblockingfactoris
30.
Boolean
Thetypeofanexpressionwithtwopossiblevalues:true
andfalse.Also,avariableofBooleantypeorafunctionwith
Booleanargumentsorresult.ThemostcommonBoolean
functionsareAND,OR,andNOT.FOLDOC
boot
Seebootstrap.
bootloader
Averysmallprogramthattakesitsplaceinthebootstrap
processthatbringsacomputerfromofforresettoafully
functionalstate.See"BootLoader"onpage533.
bootstrap
Derivedfrom"Pulloneselfupbyone'sownbootstraps,"the
incrementalprocessofloadinganoperatingsystemkernel
intomemoryandstartingitrunningwithoutanyoutside
assistance.Frequentlyshortenedtoboot.
BourneAgainShell
bash.GNU'scommandinterpreterforUNIX,bashisaPOSIX-
compliantshellwithfullBourneShellsyntaxandsomeC
Shellcommandsbuiltin.TheBourneAgainShellsupports
emacs-stylecommandlineediting,jobcontrol,functions,and
onlinehelp.FOLDOC
BourneShell
sh.ThisUNIXcommandprocessorwasdevelopedbySteve
BourneatAT&TBellLaboratories.
brace
Aleftbrace({)andarightbrace(}).Braceshavespecial
meaningstotheshell.
bracket
Asquarebracket(page1057)orananglebracket(page
1018).
branch
Inatreestructure,abranchconnectsnodes,leaves,and
theroot.TheLinuxfilesystemhierarchyisoften
conceptualizedasanupside-downtree.Thebranches
connectfilesanddirectories.Inasourcecodecontrol
system,suchasSCCSorRCS,abranchoccurswhena
revisionismadetoafileandisnotincludedinsubsequent
revisionstothefile.
bridge
Typicallyatwo-portdeviceoriginallyusedforextending
networksatlayer2(datalink)oftheInternetProtocol
model.
broadcast
Atransmissiontomultiple,unspecifiedrecipients.On
Ethernetabroadcastpacketisaspecialtypeofmulticast
packetthathasaspecialaddressindicatingthatalldevices
thatreceiveitshouldprocessit.Broadcasttrafficexistsat
severallayersofthenetworkstack,includingEthernetand
IP.Broadcasttraffichasonesourcebutindeterminate
destinations(allhostsonthelocalnetwork).
broadcastaddress
Thelastaddressonasubnet(usually255),reservedas
shorthandtomeanallhosts.
broadcastnetwork
Atypeofnetwork,suchasEthernet,inwhichanysystem
cantransmitinformationatanytime,andallsystems
receiveeverymessage.
BSD
SeeBerkeleyUNIXonpage1021.
buffer
Anareaofmemorythatstoresdatauntilitcanbeused.
Whenyouwriteinformationtoafileonadisk,Linuxstores
theinformationinadiskbufferuntilthereisenoughto
writetothediskoruntilthediskisreadytoreceivethe
information.
bug
Anunwantedandunintendedprogramproperty,especially
onethatcausestheprogramtomalfunction.FOLDOC
builtin(command)
Acommandthatisbuiltintoashell.Eachofthethree
majorshellstheBourneAgain,TC,andZShellshasitsown
setofbuiltins.Referto"Builtins"onpage225.
byte
Acomponentinthemachinedatahierarchy,usuallylarger
thanabitandsmallerthanaword;nowmostofteneight
bitsandthesmallestaddressableunitofstorage.Abyte
typicallyholdsonecharacter.FOLDOC
Cprogramminglanguage
Amodernsystemslanguagethathashigh-levelfeaturesfor
efficient,modularprogrammingaswellaslower-level
featuresthatmakeitsuitableforuseasasystems
programminglanguage.Itismachineindependentsothat
carefullywrittenCprogramscanbeeasilytransportedto
runondifferentmachines.MostoftheLinuxoperating
systemiswritteninC,andLinuxprovidesanideal
environmentforprogramminginC.
CShell
csh.TheCShellcommandprocessorwasdevelopedbyBill
JoyforBSDUNIX.ItwasnamedfortheCprogramming
languagebecauseitsprogrammingconstructsaresimilarto
thoseofC.Seeshellonpage1055.
cablemodem
AtypeofmodemthatallowsyoutoaccesstheInternetby
usingyourcabletelevisionconnection.
cache
Holdingrecentlyaccesseddata,asmall,fastmemory
designedtospeedupsubsequentaccesstothesamedata.
Mostoftenappliedtoprocessor-memoryaccessbutalso
usedforalocalcopyofdataaccessibleoveranetwork,
fromaharddisk,andsoon.FOLDOC
callingenvironment
Alistofvariablesandtheirvaluesthatismadeavailableto
acalledprogram.Referto"ExecutingaCommand"onpage
302.
cascadingstylesheet
SeeCSSonpage1027.
cascadingwindows
Anarrangementofwindowssuchthattheyoverlap,
generallywithatleastpartofthetitlebarvisible.Opposite
oftiledwindows(page1060).
casesensitive
Abletodistinguishbetweenuppercaseandlowercase
characters.Unlessyousettheignorecaseparameter,vim
performscase-sensitivesearches.Thegreputilityperforms
case-sensitivesearchesunlessyouusetheioption.
catenate
Tojoinsequentially,orendtoend.TheLinuxcatutility
catenatesfiles:Itdisplaysthemoneaftertheother.Also
concatenate.
chainloading
Thetechniqueusedbyabootloadertoloadunsupported
operatingsystems.Usedforloadingsuchoperatingsystems
asDOSorWindows,itworksbyloadinganotherboot
loader.
character-based
Aprogram,utility,orinterfacethatworksonlywithASCII
(page1019)characters.Thissetofcharactersincludes
somesimplegraphics,suchaslinesandcorners,andcan
displaycoloredcharacters.Itcannotdisplaytruegraphics.
ContrastwithGUI(page1034).
character-basedterminal
Aterminalthatdisplaysonlycharactersandverylimited
graphics.Seecharacter-based.
characterclass
Inaregularexpression,agroupofcharactersthatdefines
whichcharacterscanoccupyasinglecharacterposition.A
character-classdefinitionisusuallysurroundedbysquare
brackets.Thecharacterclassdefinedby[abcr]represents
acharacterpositionthatcanbeoccupiedbya,b,c,orr.
Alsolistoperator.
InPOSIX,usedtorefertosetsofcharacterswithacommon
characteristic,denotedbythenotation[:class:];for
example,[:upper:]denotesthesetofuppercaseletters.
Thisbookusesthetermcharacterclassasexplainedunder
"Brackets"onpage969.
characterdevice
Aterminal,printer,ormodem.Acharacterdevicestoresor
displayscharactersoneatatime.Acharacterdeviceis
representedbyacharacterdevice(characterspecial)file.
Contrastwithblockdevice(page1021).
checksum
Acomputedvaluethatdependsonthecontentsofablock
ofdataandistransmittedorstoredalongwiththedatato
detectcorruptionofthedata.Thereceivingsystem
recomputesthechecksumbasedonthereceiveddataand
comparesthisvaluewiththeonesentwiththedata.Ifthe
twovaluesarethesame,thereceiverhassomeconfidence
thatthedatawasreceivedcorrectly.
Thechecksummaybe8,16,or32bits,orsomeothersize.
Itiscomputedbysummingthebytesorwordsofthedata
block,ignoringoverflow.Thechecksummaybenegatedso
thatthetotalofthedatawordsplusthechecksumiszero.
Internetpacketsusea32-bitchecksum.FOLDOC
childprocess
Aprocessthatiscreatedbyanotherprocess,theparent
process.Everyprocessisachildprocessexceptforthefirst
process,whichisstartedwhenLinuxbeginsexecution.
Whenyourunacommandfromtheshell,theshellspawns
achildprocesstorunthecommand.Seeprocessonpage
1049.
CIDR
ClasslessInter-DomainRouting.Aschemethatallocates
blocksofInternetaddressesinawaythatallows
summarizationintoasmallernumberofroutingtable
entries.ACIDRblockisablockofInternetaddresses
assignedtoanISPbytheInternic.Referto"CIDR:
ClasslessInter-DomainRouting"onpage357.FOLDOC
CIFS
CommonInternetFileSystem.AnInternetfilesystem
protocolbasedonSMB(page1055).CIFSrunsontopof
TCP/IP,usesDNS,andisoptimizedtosupportslowerdial-
upInternetconnections.SMBandCIFSareused
interchangeably.FOLDOC
CIPE
CryptoIPEncapsulation(page1031).Thisprotocol(page
1050)tunnels(page1061)IPpacketswithinencryptedUDP
(page1061)packets,islightweightandsimple,andworks
overdynamicaddresses,NAT(page1044),andSOCKS
(page1056)proxies(page1050).
cipher(cypher)
Acryptographicsystemthatusesakeyto
transpose/substitutecharacterswithinamessage,thekey
itself,orthemessage.
ciphertext
Textthatisencrypted.Contrastwithplaintext(page1048).
Seealso"Encryption"onpage988.
ClasslessInter-DomainRouting
SeeCIDRonpage1024.
cleartext
Textthatisnotencrypted.Alsoplaintext.Contrastwith
ciphertext.Seealso"Encryption"onpage988.
CLI
Commandlineinterface.Seealsocharacter-based(page
1024).
client
Acomputerorprogramthatrequestsoneormoreservices
fromaserver.
CODEC
Coder/decoderorcompressor/decompressor.Ahardware
and/orsoftwaretechnologythatcodesanddecodesdata.
MPEGisapopularCODECforcomputervideo.
colordepth
Thenumberofbitsusedtogenerateapixelusually8,16,
24,or32.Thecolordepthisdirectlyrelatedtothenumber
ofcolorsthatcanbegenerated.Thenumberofcolorsthat
canbegeneratedis2raisedtothecolor-depthpower.Thus
a24-bitvideoadaptercangenerateabout16.7million
colors.
colorquality
Seecolordepth.
combobox
Acombinationofalistandtextentrybox.Ausercaneither
selectanoptionfromaprovidedlistorenterhisown
option.
command
Whatyougivetheshellinresponsetoaprompt.Whenyou
givetheshellacommand,itexecutesautility,another
program,abuiltincommand,orashellscript.Utilitiesare
oftenreferredtoascommands.Whenyouareusingan
interactiveutility,suchasvimormail,youusecommands
thatareappropriatetothatutility.
commandline
Alinecontaininginstructionsandargumentsthatexecutes
acommand.Thistermusuallyreferstoalinethatyouenter
inresponsetoashellpromptonacharacter-basedterminal
orterminalemulator(page93).
commandsubstitution
Replacingacommandwithitsoutput.Theshellsperform
commandsubstitutionwhenyouencloseacommand
between$(and)orbetweenapairofbackticks(''),also
calledgraveaccentmarks.
componentarchitecture
Anotioninobject-orientedprogrammingwhere
"components"ofaprogramarecompletelygeneric.Instead
ofhavingaspecializedsetofmethodsandfields,theyhave
genericmethodsthroughwhichthecomponentcan
advertisethefunctionalityitsupportstothesysteminto
whichitisloaded.Thisstrategyenablescompletely
dynamicloadingofobjects.JavaBeansisanexampleofa
componentarchitecture.FOLDOC
concatenate
Seecatenateonpage1023.
conditioncode
Seeexitstatusonpage1031.
connection-orientedprotocol
Atypeoftransportlayerdatacommunicationservicethat
allowsahosttosenddatainacontinuousstreamto
anotherhost.Thetransportserviceguaranteesthatalldata
willbedeliveredtotheotherendinthesameorderassent
andwithoutduplication.Communicationproceedsthrough
threewell-definedphases:connectionestablishment,data
transfer,andconnectionrelease.Themostcommon
exampleisTCP(page1059).
Alsocalledconnection-basedprotocolandstream-oriented
protocol.Contrastwithconnectionlessprotocoland
datagram(page1028).FOLDOC
connectionlessprotocol
Thedatacommunicationmethodinwhichcommunication
occursbetweenhostswithnoprevioussetup.Packetssent
betweentwohostsmaytakedifferentroutes.Thereisno
guaranteethatpacketswillarriveastransmittedoreven
thattheywillarriveatthedestinationatall.UDP(page
1061)isaconnectionlessprotocol.Alsocalledpacket
switching.Contrastwithcircuitswitchingandconnection-
orientedprotocol.FOLDOC
console
Seesystemconsoleonpage1059.
consoleterminal
Seesystemconsoleonpage1059.
controlcharacter
Acharacterthatisnotagraphiccharacter,suchasaletter,
number,orpunctuationmark.Suchcharactersarecalled
controlcharactersbecausetheyfrequentlyacttocontrola
peripheraldevice.RETURNandFORMFEEDarecontrol
charactersthatcontrolaterminalorprinter.
ThewordCONTROLisshowninthisbookinTHISFONT
becauseitisakeythatappearsonmostterminal
keyboards.ControlcharactersarerepresentedbyASCII
codeslessthan32(decimal).Seealsononprinting
characteronpage1046.
controlstructure
Astatementusedtochangetheorderofexecutionof
commandsinashellscriptorotherprogram.Eachshell
providescontrolstructures(forexample,ifandwhile)as
wellasothercommandsthataltertheorderofexecution
(forexample,exec).Alsocontrolflowcommands.
cookie
Datastoredonaclientsystembyaserver.Theclient
systembrowsersendsthecookiebacktotheservereach
timeitaccessesthatserver.Forexample,acatalog
shoppingservicemaystoreacookieonyoursystemwhen
youplaceyourfirstorder.Whenyoureturntothesite,it
knowswhoyouareandcansupplyyournameandaddress
forsubsequentorders.Youmayconsidercookiestobean
invasionofprivacy.
CPU
Centralprocessingunit.Thepartofacomputerthat
controlsalltheotherparts.TheCPUincludesthecontrol
unitandthearithmeticandlogicunit(ALU).Thecontrol
unitfetchesinstructionsfrommemoryanddecodesthemto
producesignalsthatcontroltheotherpartsofthe
computer.Thesesignalscancausedatatobetransferred
betweenmemoryandALUorperipheralstoperforminput
oroutput.ACPUthatishousedonasinglechipiscalleda
microprocessor.Alsoprocessorandcentralprocessor.
cracker
Anindividualwhoattemptstogainunauthorizedaccesstoa
computersystem.Theseindividualsareoftenmaliciousand
havemanymeansattheirdisposalforbreakingintoa
system.Contrastwithhacker(page1034).FOLDOC
crash
Thesystemsuddenlyandunexpectedlystopsorfails.
Derivedfromtheactionoftheharddiskheadsonthe
surfaceofthediskwhentheairgapbetweenthetwo
collapses.
cryptography
Thepracticeandstudyofencryptionand
decryptionencodingdatasothatonlyaspecificindividualor
machinecandecodeit.Asystemforencryptingand
decryptingdataisacryptosystem.Suchsystemsusually
relyonanalgorithmforcombiningtheoriginaldata
(plaintext)withoneormorekeysnumbersorstringsof
charactersknownonlytothesenderand/orrecipient.The
resultingoutputiscalledciphertext(page1025).
Thesecurityofacryptosystemusuallydependsonthe
secrecyofkeysratherthanonthesupposedsecrecyofan
algorithm.Becauseastrongcryptosystemhasalargerange
ofkeys,itisnotpossibletotryallofthem.Ciphertext
appearsrandomtostandardstatisticaltestsandresists
knownmethodsforbreakingcodes.FOLDOC
.cshrcfile
Inyourhomedirectory,afilethattheTCShellexecutes
eachtimeyouinvokeanewTCShell.Youcanusethisfile
toestablishvariablesandaliases.
CSS
Cascadingstylesheet.Describeshowdocumentsare
presentedonscreenandinprint.Attachingastylesheetto
astructureddocumentcanaffectthewayitlookswithout
addingnewHTML(orother)tagsandwithoutgivingup
deviceindependence.Alsostylesheet.
current(process,line,character,directory,event,andso
on)
Theitemthatisimmediatelyavailable,working,orbeing
used.Thecurrentprocessistheprogramyouarerunning,
thecurrentlineorcharacteristheonethecursorison,and
thecurrentdirectoryistheworkingdirectory.
cursor
Asmalllightedrectangle,underscore,orverticalbarthat
appearsontheterminalscreenandindicateswherethe
nextcharacterwillappear.Differsfromthemousepointer
(page1043).
daemon
Aprogramthatisnotinvokedexplicitlybutliesdormant,
waitingforsomecondition(s)tooccur.Theperpetratorof
theconditionneednotbeawarethatadaemonislurking
(althoughoftenaprogramwillcommitanactiononly
becauseitknowsthatitwillimplicitlyinvokeadaemon).
Fromthemythologicalmeaning,laterrationalizedasthe
acronymDiskAndExecutionMONitor.SeeTable10-4on
page374foralistofdaemons.FOLDOC
datastructure
Aparticularformatforstoring,organizing,workingwith,
andretrievingdata.Frequently,datastructuresare
designedtoworkwithspecificalgorithmsthatfacilitate
thesetasks.Commondatastructuresincludetrees,files,
records,tables,arrays,andsoon.
datagram
Aself-contained,independententityofdatacarrying
sufficientinformationtoberoutedfromthesourcetothe
destinationcomputerwithoutrelianceonearlierexchanges
betweenthissourceanddestinationcomputerandthe
transportingnetwork.UDP(page1061)usesdatagrams;IP
(page1038)usespackets(page1047).Packetsare
indivisibleatthenetworklayer;datagramsarenot.FOLDOC
Seealsoframe(page1033).
dataless
Acomputer,usuallyaworkstation,thatusesalocaldiskto
bootacopyoftheoperatingsystemandaccesssystemfiles
butdoesnotusealocaldisktostoreuserfiles.
dbm
Astandard,simpledatabasemanager.Implementedas
gdbm(GNUdatabasemanager),ituseshashestospeed
searching.Themostcommonversionsofthedbmdatabase
aredbm,ndbm,andgdbm.
DDoSattack
Distributeddenialofserviceattack.ADoSattack(page
1030)frommanysystemsthatdonotbelongtothe
perpetratoroftheattack.
debug
Tocorrectaprogrambyremovingitsbugs(thatis,errors).
default
Somethingthatisselectedwithoutbeingexplicitlyspecified.
Forexample,whenusedwithoutanargument,lsdisplaysa
listofthefilesintheworkingdirectorybydefault.
delta
Asetofchangesmadetoafilethathasbeenencodedby
theSourceCodeControlSystem(SCCS).
denialofservice
SeeDoSattackonpage1030.
dereference
Whenspeakingofsymboliclinks,followthelinkratherthan
workingwiththereferencetothelink.Forexample,theL
ordereferenceoptioncauseslstolisttheentrythata
symboliclinkpointstoratherthanthesymboliclink(the
reference)itself.
desktop
Acollectionofwindows,toolbars,icons,andbuttons,some
orallofwhichappearonyourdisplay.Adesktopcomprises
oneormoreworkspaces(page1064).Referto"Gettingthe
MostfromtheDesktop"onpage85.
desktopmanager
Anicon-andmenu-baseduserinterfacetosystemservices
thatallowsyoutorunapplicationsandusethefilesystem
withoutusingthesystem'scommandlineinterface.
detachedprocess
Seebackgroundprocessonpage1020.
device
Adiskdrive,printer,terminal,plotter,orotherinput/output
unitthatcanbeattachedtothecomputer.Shortfor
peripheraldevice.
devicedriver
PartoftheLinuxkernelthatcontrolsadevice,suchasa
terminal,diskdrive,orprinter.
devicefile
Afilethatrepresentsadevice.Alsospecialfile.
devicefilename
Thepathnameofadevicefile.AllLinuxsystemshavetwo
kindsofdevicefiles:blockandcharacterdevicefiles.Linux
alsohasFIFOs(namedpipes)andsockets.Devicefilesare
traditionallylocatedinthe/devdirectory.
devicenumber
Seemajordevicenumber(page1042)andminordevice
number(page1043).
DHCP
DynamicHostConfigurationProtocol.Aprotocolthat
dynamicallyallocatesIPaddressestocomputersonaLAN.
Referto"DHCP:ConfiguresHosts"onpage431.FOLDOC
directory
Shortfordirectoryfile.Afilethatcontainsalistofother
files.
directoryhierarchy
Adirectory,calledtherootofthedirectoryhierarchy,andall
thedirectoryandordinaryfilesbelowit(itschildren).
directoryservice
Astructuredrepositoryofinformationonpeopleand
resourceswithinanorganization,facilitatingmanagement
andcommunication.FOLDOC
diskpartition
Seepartitiononpage1047.
diskless
Acomputer,usuallyaworkstation,thathasnodiskand
mustcontactanothercomputer(aserver)tobootacopyof
theoperatingsystemandaccessthenecessarysystem
files.
distributedcomputing
Astyleofcomputinginwhichtasksorservicesare
performedbyanetworkofcooperatingsystems,someof
whichmaybespecialized.
DMZ
Demilitarizedzone.Ahostorsmallnetworkthatisaneutral
zonebetweenaLANandtheInternet.ItcanserveWeb
pagesandotherdatatotheInternetandallowlocal
systemsaccesstotheInternetwhilepreventingLANaccess
tounauthorizedInternetusers.EvenifaDMZis
compromised,itholdsnodatathatisprivateandnonethat
cannotbeeasilyreproduced.
DNS
DomainNameService.Adistributedservicethatmanages
thecorrespondenceoffullhostnames(thosethatincludea
domainname)toIPaddressesandothersystem
characteristics.
DNSdomainname
Seedomainname.
documentobjectmodel
SeeDOM.
DOM
DocumentObjectModel.Aplatform-/language-independent
interfacethatenablesaprogramtoupdatethecontent,
structure,andstyleofadocumentdynamically.The
changescanthenbemadepartofthedisplayeddocument.
Gotowww.w3.org/DOMformoreinformation.
domainname
Anameassociatedwithanorganization,orpartofan
organization,tohelpidentifysystemsuniquely.Technically,
thepartoftheFQDN(page1032)totherightofthe
leftmostperiod.Domainnamesareassignedhierarchically.
Thedomainberkeley.edureferstotheUniversityof
CaliforniaatBerkeley,forexample;itispartofthetop-level
edu(education)domain.AlsoDNSdomainname.Different
thanNISdomainname(page1046).
DomainNameService
SeeDNS.
door
Anevolvingfilesystem-basedRPC(page1053)mechanism.
DoSattack
Denialofserviceattack.Anattackthatattemptstomake
thetargethostornetworkunusablebyfloodingitwith
spurioustraffic.
DPMS
DisplayPowerManagementSignaling.Astandardthatcan
extendthelifeofCRTmonitorsandconserveenergy.DPMS
supportsfourmodesforamonitor:Normal,Standby
(powersupplyon,monitorreadytocometodisplayimages
almostinstantly),Suspend(powersupplyoff,monitortakes
uptotensecondstodisplayanimage),andOff.
drag
Tomoveaniconfromonepositionorapplicationtoanother,
usuallyinthecontextofawindowmanager.Themotion
partofdrag-and-drop.
druid
Inrole-playinggames,acharacterthatrepresentsa
magicaluser.RedHatusesthetermdruidattheendsof
namesofprogramsthatguideyouthroughatask-driven
chainofsteps.Otheroperatingsystemscallthesetypesof
programswizards.
DSA
DigitalSignatureAlgorithm.Apublickeycipherusedto
generatedigitalsignatures.
DSL
DigitalSubscriberLine/Loop.Provideshigh-speeddigital
communicationoveraspecialized,conditionedtelephone
line.SeealsoxDSL(page1064).
DynamicHostConfigurationProtocol
SeeDHCPonpage1029.
editor
Autility,suchasvimoremacs,thatcreatesandmodifiestext
files.
EEPROM
Electricallyerasable,programmable,readonlymemory.A
PROM(page1049)thatcanbewrittento.
effectiveuserID
TheuserIDthataprocessappearstohave;usuallythe
sameastheuserID.Forexample,whileyouarerunninga
setuidprogram,theeffectiveuserIDoftheprocessrunning
theprogramisthatoftheowneroftheprogram.
element
Onething;usuallyabasicpartofagroupofthings.An
elementofanumericarrayisoneofthenumbersstoredin
thearray.
emoticon
Seesmileyonpage1055.
encapsulation
Seetunnelingonpage1061.
environment
Seecallingenvironmentonpage1023.
EOF
Endoffile.
EPROM
Erasableprogrammablereadonlymemory.APROM(page
1049)thatcanbewrittentobyapplyingahigherthan
normalvoltage.
escape
Seequoteonpage1050.
Ethernet
AtypeofLAN(page1040)capableoftransferratesashigh
as1,000megabitspersecond.Referto"Ethernet"onpage
347.
event
Anoccurrence,orhappening,ofsignificancetoataskor
programforexample,thecompletionofanasynchronous
input/outputoperation,suchasakeypressormouse
click.FOLDOC
exabyte
260bytesorabout1018bytes.Seealsolargenumber(page
1040).
exitstatus
Thestatusreturnedbyaprocess;eithersuccessful(usually
0)orunsuccessful(usually1).
exploit
Asecurityholeoraninstanceoftakingadvantageofa
securityhole.FOLDOC
expression
Seelogicalexpression(page1041)andarithmetic
expression(page1019).
extranet
Anetworkextensionforasubsetofusers(suchasstudents
ataparticularschoolorengineersworkingforthesame
company).Anextranetlimitsaccesstoprivateinformation
eventhoughittravelsonthepublicInternet.
failsafesession
Asessionthatallowsyoutologinonaminimaldesktopin
caseyourstandardlogindoesnotworkwellenoughto
allowyoutologintofixaloginproblem.
FDDI
FiberDistributedDataInterface.AtypeofLAN(page1040)
designedtotransportdataattherateof100millionbitsper
secondoverfiberopticcable.
file
Acollectionofrelatedinformationreferredtowitha
filenameandfrequentlystoredonadisk.Textfilestypically
containmemos,reports,messages,programsourcecode,
lists,ormanuscripts.Binaryorexecutablefilescontain
utilitiesorprogramsthatyoucanrun.Referto"Directory
FilesandOrdinaryFiles"onpage166.
filename
Thenameofafile.Afilenamereferstoafile.
filenamecompletion
Automaticcompletionofafilenameafteryouspecifya
uniqueprefix.
filenameextension
Thepartofafilenamefollowingaperiod.
filenamegeneration
Whatoccurswhentheshellexpandsambiguousfile
references.Seeambiguousfilereferenceonpage1018.
filesystem
Adatastructure(page1028)thatusuallyresidesonpartof
adisk.AllLinuxsystemshavearootfilesystem,andmany
haveotherfilesystems.Eachfilesystemiscomposedof
somenumberofblocks,dependingonthesizeofthedisk
partitionthathasbeenassignedtothefilesystem.Each
filesystemhasacontrolblock,namedthesuperblock,that
containsinformationaboutthefilesystem.Theotherblocks
inafilesystemareinodes,whichcontaincontrolinformation
aboutindividualfiles,anddatablocks,whichcontainthe
informationinthefiles.
filling
Avariantofmaximizinginwhichwindowedgesarepushed
outasfarastheycangowithoutoverlappinganother
window.
filter
Acommandthatcantakeitsinputfromstandardinputand
senditsoutputtostandardoutput.Afiltertransformsthe
inputstreamofdataandsendsittostandardoutput.Apipe
usuallyconnectsafilter'sinputtostandardoutputofone
command,andasecondpipeconnectsthefilter'soutputto
standardinputofanothercommand.Thegrepandsort
utilitiesarecommonlyusedasfilters.
firewall
Adeviceforpolicy-basedtrafficmanagementusedtokeep
anetworksecure.Afirewallcanbeimplementedinasingle
routerthatfiltersoutunwantedpackets,oritcanrelyona
combinationofrouters,proxyservers,andotherdevices.
Firewallsarewidelyusedtogiveusersaccesstothe
Internetinasecurefashionandtoseparateacompany's
publicWWWserverfromitsinternalnetwork.Theyarealso
employedtokeepinternalnetworksegmentsmoresecure.
Recentlythetermhascometobedefinedmorelooselyto
includeasimplepacketfilterrunningonanendpoint
machine.
Seealsoproxyserveronpage1050.
firmware
Softwarebuiltintoacomputer,ofteninROM(page1053).
Maybeusedaspartofthebootstrap(page1022)
procedure.
focus,desktop
Onadesktop,thewindowthatisactive.Thewindowwith
thedesktopfocusreceivesthecharactersyoutypeonthe
keyboard.Sameasactivewindow(page1018).
footer
Thepartofaformatthatgoesatthebottom(orfoot)ofa
page.Contrastwithheader(page1034).
foregroundprocess
Whenyourunacommandintheforeground,theshellwaits
forthecommandtofinishbeforegivingyouanother
prompt.Youmustwaitforaforegroundprocesstorunto
completionbeforeyoucangivetheshellanothercommand.
Ifyouhavejobcontrol,youcanmovebackground
processestotheforeground,andviceversa.Seejobcontrol
onpage1039.Contrastwithbackgroundprocess(page
1020).
fork
Tocreateaprocess.Whenoneprocesscreatesanother
process,itforksaprocess.Alsospawn.
FQDN
Fullyqualifieddomainname.Thefullnameofasystem,
consistingofitshostnameanditsdomainname,including
thetop-leveldomain.Technicallythenamethat
gethostbyname(2)returnsforthehostnamedby
gethostname(2).Forexample,speedyisahostnameand
speedy.example.comisanFQDN.AnFQDNissufficientto
determineauniqueInternetaddressforamachineonthe
Internet.FOLDOC
frame
Adatalinklayerpacketthatcontains,inadditiontodata,
theheaderandtrailerinformationrequiredbythephysical
medium.Networklayerpacketsareencapsulatedto
becomeframes.FOLDOCSeealsodatagram(page1028)and
packet(page1047).
freelist
Inafilesystem,thelistofblocksthatareavailableforuse.
Informationaboutthefreelistiskeptinthesuperblockof
thefilesystem.
freesoftware
RefertoAppendixD,"TheFreeSoftwareDefinition."
freespace
Theportionofaharddiskthatisnotwithinapartition.A
newharddiskhasnopartitionsandcontainsallfreespace.
fullduplex
Theabilitytoreceiveandtransmitdatasimultaneously.A
networkswitch(page1045)istypicallyafull-duplexdevice.
Contrastwithhalf-duplex(page1034).
fullyqualifieddomainname
SeeFQDNonpage1032.
function
Seeshellfunctiononpage1055.
gateway
Agenerictermforacomputeroraspecialdeviceconnected
tomorethanonedissimilartypeofnetworktopassdata
betweenthem.Unlikearouter,agatewayoftenmust
converttheinformationintoadifferentformatbefore
passingiton.Thehistoricalusageofgatewaytodesignate
arouterisdeprecated.
GCOS
SeeGECOS.
GECOS
GeneralElectricComprehensiveOperatingSystem.For
historicalreasons,theuserinformationfieldinthe
/etc/passwdfileiscalledtheGECOSfield.AlsoGCOS.
giga-
Inthebinarysystem,theprefixgiga-multipliesby230(i.e.,
1,073,741,824).Gigabitandgigabytearecommonusesof
thisprefix.AbbreviatedasG.Seealsolargenumberon
page1040.
glyph
Asymbolthatcommunicatesaspecificpieceofinformation
nonverbally.Asmiley(page1055)isaglyph.
GMT
GreenwichMeanTime.SeeUTConpage1062.
graphicaldisplay
Abitmappedmonitorthatcandisplaygraphicalimages.
ContrastwithASCIIterminal(page1019).
graphicaluserinterface
SeeGUIonpage1034.
group(ofusers)
Acollectionofusers.Groupsareusedasabasisfor
determiningfileaccesspermissions.Ifyouarenotthe
ownerofafileandyoubelongtothegroupthefileis
assignedto,youaresubjecttothegroupaccess
permissionsforthefile.Ausercansimultaneouslybelongto
severalgroups.
group(ofwindows)
Awaytoidentifysimilarwindowssotheycanbedisplayed
andactedonsimilarly.Typicallywindowsstartedbyagiven
applicationbelongtothesamegroup.
groupID
Auniquenumberthatidentifiesasetofusers.Itisstored
inthepasswordandgroupdatabases(/etc/passwdand
/etc/groupfilesortheirNISequivalents).Thegroup
databaseassociatesgroupIDswithgroupnames.
GUI
Graphicaluserinterface.AGUIprovidesawaytointeract
withacomputersystembychoosingitemsfrommenusor
manipulatingpicturesdrawnonadisplayscreeninsteadof
bytypingcommandlines.UnderLinux,theXWindow
Systemprovidesagraphicaldisplayandmouse/keyboard
input.GNOMEandKDEaretwopopulardesktopmanagers
thatrununderX.Contrastwithcharacter-based(page
1024).
hacker
Apersonwhoenjoysexploringthedetailsofprogrammable
systemsandlearninghowtostretchtheircapabilities,as
opposedtousers,whoprefertolearnonlytheminimum
necessary.Onewhoprogramsenthusiastically(even
obsessively)orwhoenjoysprogrammingratherthanjust
theorizingaboutprogramming.FOLDOCContrastwithcracker
(page1027).
half-duplex
Ahalf-duplexdevicecanonlyreceiveortransmitatagiven
moment;itcannotdoboth.Ahub(page1036)istypicallya
half-duplexdevice.Contrastwithfullduplex(page1033).
hardlink
Adirectoryentrythatcontainsthefilenameandinode
numberforafile.Theinodenumberidentifiesthelocation
ofcontrolinformationforthefileonthedisk,whichinturn
identifiesthelocationofthefile'scontentsonthedisk.
Everyfilehasatleastonehardlink,whichlocatesthefilein
adirectory.Whenyouremovethelasthardlinktoafile,
youcannolongeraccessthefile.Seelink(page1040)and
symboliclink(page1058).
hash
Astringthatisgeneratedfromanotherstring.Seeone-way
hashfunctiononpage1046.Whenusedforsecurity,ahash
canprove,almosttoacertainty,thatamessagehasnot
beentamperedwithduringtransmission:Thesender
generatesahashofamessage,encryptsthemessageand
hash,andsendstheencryptedmessageandhashtothe
recipient.Therecipientdecryptsthemessageandhash,
generatesasecondhashfromthemessage,andcompares
thehashthatthesendergeneratedtothenewhash.When
theyarethesame,themessagehasprobablynotbeen
tamperedwith.Ahashcanalsobeusedtocreateanindex
calledahashtable.Alsohashvalue.
hashtable
Anindexcreatedfromhashesoftheitemstobeindexed.
Thehashfunctionmakesithighlyunlikelythattwoitems
willcreatethesamehash.Tolookupanitemintheindex,
createahashoftheitemandsearchforthehash.Because
thehashistypicallyshorterthantheitem,thesearchis
moreefficient.
header
Whenyouareformattingadocument,theheadergoesat
thetop,orhead,ofapage.Inelectronicmailtheheader
identifieswhosentthemessage,whenitwassent,what
thesubjectofthemessageis,andsoforth.
Heredocument
Ashellscriptthattakesitsinputfromthefilethatcontains
thescript.
hesiod
ThenameserverofprojectAthena.Hesiodisanameservice
librarythatisderivedfromBIND(page1021)andleverages
aDNSinfrastructure.
heterogeneous
Consistingofdifferentparts.Aheterogeneousnetwork
includessystemsproducedbydifferentmanufacturers
and/orrunningdifferentoperatingsystems.
hexadecimalnumber
Abase16number.Hexadecimal(orhex)numbersare
composedofthehexadecimaldigits09andAF.SeeTableG-
1.
TableG-1.Decimal,octal,and
hexadecimalnumbers
Decimal Octal Hex Decimal Octal Hex
1 1 1 17 21 11
2 2 2 18 22 12
3 3 3 19 23 13
4 4 4 20 24 14
5 5 5 21 25 15
6 6 6 31 37 1F
7 7 7 32 40 20
8 10 8 33 41 21
9 11 9 64 100 40
10 12 A 96 140 60
11 13 B 100 144 64
12 14 C 128 200 80
13 15 D 254 376 FE
14 16 E 255 377 FF
15 17 F 256 400 100
16 20 10 257 401 101
hiddenfile
Afilewhosefilenamestartswithaperiod.Thesefilesare
calledhiddenbecausethelsutilitydoesnotnormallylist
them.Usetheaoptionoflstolistallfiles,includinghidden
ones.Theshelldoesnotexpandaleadingasterisk(*)inan
ambiguousfilereferencetomatchthefilenameofahidden
file.Alsoinvisiblefile.
hierarchy
Anorganizationwithafewthings,orthingoneatthetopand
withseveralthingsbeloweachotherthing.Aninvertedtree
structure.Examplesincomputingincludeafiletreewhere
eachdirectorymaycontainfilesorotherdirectories,a
hierarchicalnetwork,andaclasshierarchyinobject-
orientedprogramming.FOLDOCReferto"TheHierarchical
Filesystem"onpage166.
history
Ashellmechanismthatenablesyoutomodifyand
reexecuterecentcommands.
homedirectory
Thedirectorythatisyourworkingdirectorywhenyoufirst
login.Thepathnameofthisdirectoryisstoredinthe
HOMEshellvariable.
hover
Toleavethemousepointerstationaryforamomentoveran
object.Inmanycaseshoveringdisplaysatooltip(page
1060).
HTML
HypertextMarkupLanguage.Ahypertextdocumentformat
usedontheWorldWideWeb.Tags,whichareembeddedin
thetext,consistofalessthansign(<),adirective,zeroor
moreparameters,andagreaterthansign(>).Matched
pairsofdirectives,suchas<TITLE>and</TITLE>,delimit
textthatistoappearinaspecialplaceorstyle.FOLDOCFor
moreinformationonHTML,goto
www.htmlhelp.com/faq/html/all.html.
HTTP
HypertextTransferProtocol.Theclient/serverTCP/IP
protocolusedontheWorldWideWebfortheexchangeof
HTMLdocuments.
hub
Amultiportrepeater.Ahubrebroadcastsallpacketsit
receivesonallports.Thistermisfrequentlyusedtoreferto
smallhubsandswitches,regardlessofthedevice's
intelligence.Itisagenerictermforalayer2shared-media
networkingdevice.Todaythetermhubissometimesused
torefertosmallintelligentdevices,althoughthatwasnot
itsoriginalmeaning.Contrastwithnetworkswitch(page
1045).
hypertext
Acollectionofdocuments/nodescontaining(usually
highlightedorunderlined)cross-referencesorlinks,which,
withtheaidofaninteractivebrowserprogram,allowthe
readertomoveeasilyfromonedocumenttoanother.FOLDOC
HypertextMarkupLanguage
SeeHTML.
HypertextTransferProtocol
SeeHTTP.
i/odevice
Input/outputdevice.Seedeviceonpage1028.
IANA
InternetAssignedNumbersAuthority.Agroupthat
maintainsadatabaseofallpermanent,registeredsystem
services(www.iana.org).
ICMP
InternetControlMessageProtocol.Atypeofnetworkpacket
thatcarriesonlymessages,nodata.
icon
InaGUI,asmallpicturerepresentingafile,directory,
action,program,andsoon.Whenyouclickanicon,an
action,suchasopeningawindowandstartingaprogramor
displayingadirectoryorWebsite,takesplace.From
miniaturereligiousstatues.FOLDOC
iconify
Theprocessofchangingawindowintoanicon.Contrast
withrestore(page1052).
ignoredwindow
Astateinwhichawindowhasnodecorationandtherefore
nobuttonsortitlebartocontrolitwith.
indentation
Seeindention.
indention
Theblankspacebetweenthemarginandthebeginningofa
linethatissetinfromthemargin.
inode
Adatastructure(page1028)thatcontainsinformation
aboutafile.Aninodeforafilecontainsthefile'slength,the
timesthefilewaslastaccessedandmodified,thetimethe
inodewaslastmodified,ownerandgroupIDs,access
privileges,numberoflinks,andpointerstothedatablocks
thatcontainthefileitself.Eachdirectoryentryassociatesa
filenamewithaninode.Althoughasinglefilemayhave
severalfilenames(oneforeachlink),ithasonlyoneinode.
input
Informationthatisfedtoaprogramfromaterminalor
otherfile.Seestandardinputonpage1057.
installation
Acomputerataspecificlocation.SomeaspectsoftheLinux
systemareinstallationdependent.Alsosite.
interactive
Aprogramthatallowsongoingdialogwiththeuser.When
yougivecommandsinresponsetoshellprompts,youare
usingtheshellinteractively.Also,whenyougivecommands
toutilities,suchasvimandmail,youareusingtheutilities
interactively.
interface
Themeetingpointoftwosubsystems.Whentwoprograms
worktogether,theirinterfaceincludeseveryaspectofeither
programthattheotherdealswith.Theuserinterface(page
1062)ofaprogramincludeseveryprogramaspecttheuser
comesintocontactwith:thesyntaxandsemanticsinvolved
ininvokingtheprogram,theinputandoutputofthe
program,anditserrorandinformationalmessages.The
shellandeachoftheutilitiesandbuilt-incommandshavea
userinterface.
InternationalOrganizationforStandardization
SeeISOonpage1038.
internet
Alargenetworkthatencompassesother,smallernetworks.
Internet
Thelargestinternetintheworld.TheInternet(uppercase
"I")isamultilevelhierarchycomposedofbackbone
networks(ARPANET,NSFNET,MILNET,andothers),midlevel
networks,andstubnetworks.Theseincludecommercial
(.comor.co),university(.acor.edu),research(.orgor
.net),andmilitary(.mil)networksandspanmanydifferent
physicalnetworksaroundtheworldwithvariousprotocols,
includingtheInternetProtocol(IP).OutsidetheUnited
States,countrycodedomainsarepopular(.us,.es,.mx,
.de,andsoforth),althoughyouwillseethemusedwithin
theUnitedStatesaswell.
InternetProtocol
SeeIP.
Internetserviceprovider
SeeISP.
intranet
Aninhousenetworkdesignedtoserveagroupofpeople
suchasacorporationorschool.Thegeneralpubliconthe
Internetdoesnothaveaccesstotheintranet.Seepage
344.
invisiblefile
Seehiddenfileonpage1035.
IP
InternetProtocol.ThenetworklayerforTCP/IP.IPisabest-
effort,packet-switching,connectionlessprotocol(page
1026)thatprovidespacketrouting,fragmentation,and
reassemblythroughthedatalinklayer.IPv4isslowlygiving
waytoIPv6.FOLDOC
IPaddress
InternetProtocoladdress.Afour-partaddressassociated
withaparticularnetworkconnectionforasystemusingthe
InternetProtocol(IP).Asystemthatisattachedtomultiple
networksthatusetheIPwillhaveadifferentIPaddressfor
eachnetworkinterface.
IPmulticast
Seemulticastonpage1044.
IPspoofing
Atechniqueusedtogainunauthorizedaccesstoa
computer.Thewould-beintrudersendsmessagestothe
targetmachine.ThesemessagescontainanIPaddress
indicatingthatthemessagesarecomingfromatrusted
host(page362).Thetargetmachinerespondstothe
messages,givingtheintruder(privileged)accesstothe
target.
IPC
Interprocesscommunication.Amethodtocommunicate
specificinformationbetweenprograms.
IPv4
IPversion4.SeeIPandIPv6.
IPv6
IPversion6.ThenextgenerationofInternetProtocol,
whichprovidesamuchlargeraddressspace(2128bits
versus232bitsforIPv4)thatisdesignedtoaccommodate
therapidlygrowingnumberofInternetaddressabledevices.
IPv6alsohasbuilt-inautoconfiguration,enhancedsecurity,
bettermulticastsupport,andmanyotherfeatures.
ISDN
IntegratedServicesDigitalNetwork.Asetof
communicationsstandardsthatallowsasinglepairofdigital
orstandardtelephonewirestocarryvoice,data,andvideo
atarateof64kilobitspersecond.
ISO
InternationalOrganizationforStandardization.Avoluntary,
nontreatyorganizationfoundedin1946.Itisresponsiblefor
creatinginternationalstandardsinmanyareas,including
computersandcommunications.Itsmembersarethe
nationalstandardsorganizationsof89countries,including
theAmericanNationalStandardsInstitute.FOLDOC
ISO9660
TheISOstandarddefiningafilesystemforCD-ROMs.
ISP
Internetserviceprovider.ProvidesInternetaccesstoits
customers.
jobcontrol
Afacilitythatenablesyoutomovecommandsfromthe
foregroundtothebackgroundandviceversa.Jobcontrol
enablesyoutostopcommandstemporarily.
journalingfilesystem
Afilesystemthatmaintainsanoncachedlogfile,orjournal,
whichrecordsalltransactionsinvolvingthefilesystem.
Whenatransactioniscomplete,itismarkedascompletein
thelogfile.
Thelogfileresultsingreatlyreducedtimespentrecovering
afilesystemafteracrash,makingitparticularlyvaluablein
systemswherehighavailabilityisanissue.
JPEG
JointPhotographicExpertsGroup.Thiscommitteedesigned
thestandardimage-compressionalgorithm.JPEGis
intendedforcompressingeitherfull-colororgray-scale
digitalimagesofnatural,real-worldscenesanddoesnot
workaswellonnonrealisticimages,suchascartoonsor
linedrawings.Filenameextensions:.jpg,.jpeg.FOLDOC
justify
Toexpandalineoftypeintheprocessofformattingtext.A
justifiedlinehasevenmargins.Alineisjustifiedby
increasingthespacebetweenwordsandsometimes
betweenlettersontheline.
Kerberos
AnMIT-developedsecuritysystemthatauthenticatesusers
andmachines.Itdoesnotprovideauthorizationtoservices
ordatabases;itestablishesidentityatlogon,whichisused
throughoutthesession.Onceyouareauthenticated,you
canopenasmanyterminals,windows,services,orother
networkaccessesasyoulikeuntilyoursessionexpires.
kernel
Thepartoftheoperatingsystemthatallocatesmachine
resources,includingmemory,diskspace,andCPU(page
1026)cycles,toallotherprogramsthatrunonacomputer.
Thekernelincludesthelow-levelhardwareinterfaces
(drivers)andmanagesprocesses(page1049),themeans
bywhichLinuxexecutesprograms.Thekernelisthepartof
theLinuxsystemthatLinusTorvaldsoriginallywrote(see
thebeginningofChapter1).
kernelspace
Thepartofmemory(RAM)wherethekernelresides.Code
runninginkernel-spacehasfullaccesstohardwareandall
otherprocessesinmemory.SeetheKernelAnalysis-
HOWTO.
keybinding
Akeyboardkeyissaidtobeboundtotheactionthat
resultsfrompressingit.Typicallykeysareboundtothe
lettersthatappearonthekeycaps:WhenyoupressA,anA
appearsonthescreen.Keybindingusuallyreferstowhat
happenswhenyoupressacombinationofkeys,oneof
whichisCONTROL,ALT,META,orSHIFT,orwhenyoupress
aseriesofkeys,thefirstofwhichistypicallyESCAPE.
keyboard
Ahardwareinputdeviceconsistingofanumberof
mechanicalbuttons(keys)thattheuserpressestoinput
characterstoacomputer.Bydefaultakeyboardis
connectedtostandardinputofashell.FOLDOC
kilo-
Inthebinarysystem,theprefixkilo-multipliesby210(i.e.,
1,024).Kilobitandkilobytearecommonusesofthisprefix.
Abbreviatedask.
KornShell
ksh.Acommandprocessor,developedbyDavidKornat
AT&TBellLaboratories,thatiscompatiblewiththeBourne
Shellbutincludesmanyextensions.Seealsoshellonpage
1055.
LAN
Localareanetwork.Anetworkthatconnectscomputers
withinalocalizedarea(suchasasinglesite,building,or
department).
largenumber
Gotomathworld.wolfram.com/LargeNumber.htmlfora
comprehensivelist.
LDAP
LightweightDirectoryAccessProtocol.Asimpleprotocolfor
accessingonlinedirectoryservices.LDAPisalightweight
alternativetotheX.500DirectoryAccessProtocol(DAP).It
canbeusedtoaccessinformationaboutpeople,system
users,networkdevices,emaildirectories,andsystems.In
somecases,itcanbeusedasanalternativeforservices
suchasNIS.Givenaname,manymailclientscanuseLDAP
todiscoverthecorrespondingemailaddress.Seedirectory
serviceonpage1029.
leaf
Inatreestructure,theendofabranchthatcannotsupport
otherbranches.WhentheLinuxfilesystemhierarchyis
conceptualizedasatree,filesthatarenotdirectoriesare
leaves.Seenodeonpage1046.
leastprivilege,conceptof
MistakesthatSuperusermakescanbemuchmore
devastatingthanthosemadebyanordinaryuser.Whenyou
areworkingonthecomputer,especiallywhenyouare
workingasthesystemadministrator,alwaysperformany
taskusingtheleastprivilegepossible.Ifyoucanperforma
taskloggedinasanordinaryuser,doso.Ifyoumustbe
loggedinasSuperuser,doasmuchasyoucanasan
ordinaryuser,loginasrootorgiveansuorsudo
commandsothatyouhaveSuperuserprivileges,doas
muchofthetaskthathastobedoneasSuperuser,and
reverttobeinganordinaryuserassoonasyoucan.
Becauseyouaremorelikelytomakeamistakewhenyou
arerushing,thisconceptbecomesmoreimportantwhen
youhavelesstimetoapplyit.
LightweightDirectoryAccessProtocol
SeeLDAP.
link
Apointertoafile.Twokindsoflinksexist:hardlinksand
symbolic(soft)links.Ahardlinkassociatesafilenamewith
aplaceonthediskwherethecontentsofthefileislocated.
Asymboliclinkassociatesafilenamewiththepathnameof
ahardlinktoafile.Seehardlink(page1034)andsymbolic
link(page1058).
Linux-PAM
SeePAMonpage1047.
Linux-PluggableAuthenticationModules
SeePAMonpage1047.
loadablekernelmodule
Seeloadablemodule.
loadablemodule
Aportionoftheoperatingsystemthatcontrolsaspecial
deviceandthatcanbeloadedautomaticallyintoarunning
kernelasneededtoaccessthatdevice.See"Using
LoadableKernelModules"onpage531.
localareanetwork
SeeLANonpage1040.
locale
Thelanguage;date,time,andcurrencyformats;character
sets;andsoforththatpertaintoageopoliticalplaceor
area.Forexample,en_USspecifiesEnglishasspokeninthe
UnitedStatesanddollars;en_UKspecifiesEnglishas
spokenintheUnitedKingdomandpounds.Seethelocale
manpageinsection5ofthesystemmanualformore
information.Alsothelocaleutility.
login
Togainaccesstoacomputersystembyresponding
correctlytothelogin:andPassword:prompts.Alsolog
on,login.
logout
Toendyoursessionbyexitingfromyourloginshell.Also
logoff.
logicalexpression
Acollectionofstringsseparatedbylogicaloperators(>,
>=,=,!=,<=,and<)thatcanbeevaluatedastrueor
false.AlsoBoolean(page1022)expression.
.loginfile
Afileinauser'shomedirectorythattheTCShellexecutes
whenyoulogin.Youcanusethisfiletosetenvironment
variablesandtoruncommandsthatyouwantexecutedat
thebeginningofeachsession.
loginname
Seeusernameonpage1062.
loginshell
Theshellthatyouareusingwhenyoulogin.Theloginshell
canforkotherprocessesthatcanrunothershells,utilities,
andprograms.
.logoutfile
Afileinauser'shomedirectorythattheTCShellexecutes
whenyoulogout,assumingthattheTCShellisyourlogin
shell.Youcanputinthe.logoutfilecommandsthatyou
wantruneachtimeyoulogout.
MACaddress
MediaAccessControladdress.Theuniquehardware
addressofadeviceconnectedtoasharednetworkmedium.
EachEthernetadapterhasagloballyuniqueMACaddressin
ROM.MACaddressesare6byteslong,enabling2566
(about300trillion)possibleaddressesor65,536addresses
foreachpossibleIPv4address.
AMACaddressperformsthesameroleforEthernetthatan
IPaddressperformsforTCP/IP:Itprovidesauniquewayto
identifyahost.
machinecollatingsequence
Thesequenceinwhichthecomputerorderscharacters.The
machinecollatingsequenceaffectstheoutcomeofsorts
andotherproceduresthatputlistsinalphabeticalorder.
ManycomputersuseASCIIcodessotheirmachinecollating
sequencescorrespondtotheorderingoftheASCIIcodes
forcharacters.
macro
Asingleinstructionthataprogramreplacesbyseveral
(usuallymorecomplex)instructions.TheCcompiler
recognizesmacros,whicharedefinedusinga#define
instructiontothepreprocessor.
magicnumber
Amagicnumber,whichoccursinthefirst512bytesofa
binaryfile,isa1-,2-,or4-bytenumericvalueorcharacter
stringthatuniquelyidentifiesthetypeoffile(muchlikea
DOS3-characterfilenameextension).See
/usr/share/magicandthemagicmanpageformore
information.
mainmemory
Randomaccessmemory(RAM),anintegralpartofthe
computer.Althoughdiskstorageissometimesreferredtoas
memory,itisneverreferredtoasmainmemory.
majordevicenumber
Anumberassignedtoaclassofdevices,suchasterminals,
printers,ordiskdrives.Usingthelsutilitywiththeloption
tolistthecontentsofthe/devdirectorydisplaysthemajor
andminordevicenumbersofmanydevices(asmajor,
minor).
MAN
Metropolitanareanetwork.Anetworkthatconnects
computersandLANs(page1040)atmultiplesitesina
smallregionalarea,suchasacity.
masquerade
ToappeartocomefromonedomainorIPaddresswhen
actuallycomingfromanother.Saidofapacket(iptables)or
message(sendmail).SeealsoNATonpage1044.
MD5
MessageDigest5.Aone-wayhashfunction(page1046).
TheSHA1(page1054)algorithmhassupplantedMD5in
manyapplications.
MDA
Maildeliveryagent.Oneofthethreecomponentsofamail
system;theothertwoaretheMTA(page1043)andMUA
(page1044).AnMDAacceptsinboundmailfromanMTA
anddeliversittoalocaluser.
mega-
Inthebinarysystem,theprefixmega-multipliesby220
(i.e.,1,048,576).Megabitandmegabytearecommonuses
ofthisprefix.AbbreviatedasM.
menu
Alistfromwhichtheusermayselectanoperationtobe
performed.Thisselectionisoftenmadewithamouseor
otherpointingdeviceunderaGUIbutmayalsobe
controlledfromthekeyboard.Veryconvenientfor
beginners,menusshowwhichcommandsareavailableand
facilitateexperimentingwithanewprogram,oftenreducing
theneedforuserdocumentation.Experiencedusersusually
preferkeyboardcommands,especiallyforfrequentlyused
operations,becausetheyarefastertouse.FOLDOC
merge
Tocombinetwoorderedlistssothattheresultinglistisstill
inorder.Thesortutilitycanmergefiles.
METAkey
Onthekeyboard,akeythatislabeledMETAorALT.Use
thiskeyasyouwouldtheSHIFTkey.Whileholdingitdown,
pressanotherkey.Theemacseditormakesextensiveuseof
theMETAkey.
metacharacter
Acharacterthathasaspecialmeaningtotheshellor
anotherprograminaparticularcontext.Metacharactersare
usedintheambiguousfilereferencesrecognizedbythe
shellandintheregularexpressionsrecognizedbyseveral
utilities.Youmustquoteametacharacterifyouwanttouse
itwithoutinvokingitsspecialmeaning.Seeregular
character(page1052)andspecialcharacter(page1056).
metadata
Dataaboutdata.Indataprocessing,metadatais
definitionaldatathatprovidesinformationabout,or
documentationof,otherdatamanagedwithinanapplication
orenvironment.
Forexample,metadatacandocumentdataaboutdata
elementsorattributes(name,size,datatype,andsoon),
recordsordatastructures(page1028)(length,fields,
columns,andsoon),anddataitself(whereitislocated,
howitisassociated,whoownsit,andsoon).Metadatacan
includedescriptiveinformationaboutthecontext,quality
andcondition,orcharacteristicsofthedata.FOLDOC
metropolitanareanetwork
SeeMANonpage1042.
MIME
MultipurposeInternetMailExtension.Originallyusedto
describehowspecifictypesoffilesthatwereattachedto
emailweretobehandled.TodayMIMEtypesdescribehowa
fileistobeopenedorworkedwith,basedonitsfilename
extension.
minimize
Seeiconifyonpage1036.
minordevicenumber
Anumberassignedtoaspecificdevicewithinaclassof
devices.Seemajordevicenumberonpage1042.
modem
Modulator/demodulator.Aperipheraldevicethatmodulates
digitaldataintoanalogdatafortransmissionoveravoice-
gradetelephoneline.Anothermodemdemodulatesthedata
attheotherend.
module
Seeloadablemoduleonpage1041.
mount
Tomakeafilesystemaccessibletosystemusers.Whena
filesystemisnotmounted,youcannotreadfromorwriteto
filesitcontains.
mountpoint
Adirectorythatyoumountalocalorremotefilesystem
(page466)on.
mouse
Adeviceyouusetopointtoaparticularlocationona
displayscreen,typicallysoyoucanchooseamenuitem,
drawaline,orhighlightsometext.Youcontrolapointeron
thescreenbyslidingamousearoundonaflatsurface;the
positionofthepointermovesrelativetothemovementof
themouse.Youselectitemsbypressingoneormore
buttonsonthemouse.
mousepointer
InaGUI,amarkerthatmovesincorrespondencewiththe
mouse.ItisusuallyasmallblackXwithawhiteborderor
anarrow.Differsfromthecursor(page1027).
mouseover
Theactionofpassingthemousepointeroveraniconor
otherobjectonthescreen.
MTA
Mailtransferagent.Oneofthethreecomponentsofamail
system;theothertwoaretheMDA(page1042)andMUA
(page1044).AnMTAacceptsmailfromusersandMTAs.
MUA
Mailuseragent.Oneofthethreecomponentsofamail
system;theothertwoaretheMDA(page1042)andMTA
(page1043).AnMUAisanend-usermailprogramsuchas
KMail,mutt,orOutlook.
multibootspecification
Specifiesaninterfacebetweenabootloaderandan
operatingsystem.Withcompliantbootloadersand
operatingsystems,anybootloadershouldbeabletoload
anyoperatingsystem.Theobjectofthisspecificationisto
ensurethatdifferentoperatingsystemswillworkona
singlemachine.Formoreinformation,gotoodin-
os.sourceforge.net/guides/multiboot.html.
multicast
Amulticastpackethasonesourceandmultiple
destinations.Inmulticast,sourcehostsregisterataspecial
addresstotransmitdata.Destinationhostsregisteratthe
sameaddresstoreceivedata.Incontrasttobroadcast
(page1022),whichisLAN-based,multicasttrafficis
designedtoworkacrossroutednetworksonasubscription
basis.Multicastreducesnetworktrafficbytransmittinga
packetonetime,withtherouterattheendofthepath
breakingitapartasneededformultiplerecipients.
multitasking
Acomputersystemthatallowsausertorunmorethanone
jobatatime.Amulti-taskingsystem,suchasLinux,allows
youtorunajobinthebackgroundwhilerunningajobin
theforeground.
multiusersystem
Acomputersystemthatcanbeusedbymorethanone
personatatime.Linuxisamultiuseroperatingsystem.
Contrastwithsingle-usersystem(page1055).
namespace
Asetofnamesinwhichallnamesareunique.FOLDOC
NAT
NetworkAddressTranslation.AschemethatenablesaLAN
touseonesetofIPaddressesinternallyandadifferentset
externally.TheinternalsetisforLAN(private)use.The
externalsetistypicallyusedontheInternetandisInternet
unique.NATprovidessomeprivacybyhidinginternalIP
addressesandallowsmultipleinternaladdressestoconnect
totheInternetthroughasingleexternalIPaddress.See
alsomasqueradeonpage1042.
NBT
NetBIOSoverTCP/IP.AprotocolthatsupportsNetBIOS
servicesinaTCP/IPenvironment.AlsoNetBT.
NetBIOS
NetworkBasicInput/OutputSystem.AnAPI(page1019)
forwritingnetwork-awareapplications.
netboot
Tobootacomputeroverthenetwork(asopposedto
bootingfromalocaldisk).
netiquette
Theconventionsofetiquettethatis,polite
behaviorrecognizedonUsenetandinmailinglists,suchas
not(cross-)postingtoinappropriategroupsandrefraining
fromcommercialadvertisingoutsidethebusinessgroups.
Themostimportantruleofnetiquetteis"Thinkbeforeyou
post."Ifwhatyouintendtopostwillnotmakeapositive
contributiontothenewsgroupandbeofinteresttoseveral
readers,donotpostit.Personalmessagestooneortwo
individualsshouldnotbepostedtonewsgroups;useprivate
emailinstead.FOLDOC
netmask
A32-bitmask(forIPv4),thatshowshowanInternet
addressistobedividedintonetwork,subnet,andhost
parts.Thenetmaskhasonesinthebitpositionsinthe32-
bitaddressthataretobeusedforthenetworkandsubnet
partsandzerosforthehostpart.Themaskshouldcontain
atleastthestandardnetworkportion(asdeterminedbythe
addressclass).Thesubnetfieldshouldbecontiguouswith
thenetworkportion.FOLDOC
networkaddress
Thenetworkportion(netid)ofanIPaddress.ForaclassA
network,itisthefirstbyte,orsegment,oftheIPaddress;
foraclassBnetwork,itisthefirsttwobytes;andfora
classCnetwork,itisthefirstthreebytes.Ineachcasethe
balanceoftheIPaddressisthehostaddress(hostid).
Assignednetworkaddressesaregloballyuniquewithinthe
Internet.Alsonetworknumber.Seealso"HostAddress"on
page353.
NetworkFilesystem
SeeNFS.
NetworkInformationService
SeeNIS.
networknumber
Seenetworkaddress.
networksegment
ApartofanEthernetorothernetworkonwhichall
messagetrafficiscommontoallnodes;thatis,itis
broadcastfromonenodeonthesegmentandreceivedby
allothers.Thiscommonalitynormallyoccursbecausethe
segmentisasinglecontinuousconductor.Communication
betweennodesondifferentsegmentsisviaoneormore
routers.FOLDOC
networkswitch
Aconnectingdeviceinnetworks.Switchesareincreasingly
replacingsharedmediahubsinanefforttoincrease
bandwidth.Forexample,a16-port10BaseThubsharesthe
total10megabitspersecondbandwidthwithall16
attachednodes.Byreplacingthehubwithaswitch,both
senderandreceivercantakeadvantageofthefull10
megabitspersecondcapacity.Eachportontheswitchcan
givefullbandwidthtoasingleserverorclientstationortoa
hubwithseveralstations.Networkswitchreferstoadevice
withintelligence.Contrastwithhub(page1036).
NetworkTimeProtocol
SeeNTPonpage1046.
NFS
NetworkFilesystem.AremotefilesystemdesignedbySun
Microsystems,availableoncomputersfrommostUNIX
systemvendors.
NIC
Networkinterfacecard(orcontroller).Anadaptercircuit
boardinstalledinacomputertoprovideaphysical
connectiontoanetwork.FOLDOC
NIS
NetworkInformationService.Adistributedservicebuilton
ashareddatabasetomanagesystem-independent
information(suchasusernamesandpasswords).
NISdomainname
Anamethatdescribesagroupofsystemsthatshareaset
ofNISfiles.Differentfromdomainname(page1030).
NNTP
NetworkNewsTransferProtocol.Referto"Usenet"onpage
378.
node
Inatreestructure,theendofabranchthatcansupport
otherbranches.WhentheLinuxfilesystemhierarchyis
conceptualizedasatree,directoriesarenodes.Seeleafon
page1040.
nonprintingcharacter
Seecontrolcharacteronpage1026.Alsononprintable
character.
nonvolatilestorage
Astoragedevicewhosecontentsarepreservedwhenits
powerisoff.AlsoNVSandpersistentstorage.Some
examplesareCD-ROM,paperpunchtape,harddisk,ROM
(page1053),PROM(page1049),EPROM(page1031),and
EEPROM(page1030).ContrastwithRAM(page1051).
NTP
NetworkTimeProtocol.BuiltontopofTCP/IP,NTP
maintainsaccuratelocaltimebyreferringtoknown
accurateclocksontheInternet.
nullstring
Astringthatcouldcontaincharactersbutdoesnot.Astring
ofzerolength.
octalnumber
Abase8number.Octalnumbersarecomposedofthedigits
07,inclusive.RefertoTableG-1onpage1035.
one-wayhashfunction
Aone-wayfunctionthattakesavariable-lengthmessage
andproducesafixed-lengthhash.Giventhehash,itis
computationallyinfeasibletofindamessagewiththathash;
infact,youcannotdetermineanyusableinformationabout
amessagewiththathash.Alsomessagedigestfunction.
Seealsohash(page1034).
OpenSSH
AfreeversionoftheSSH(secureshell)protocolsuitethat
replacesTELNET,rlogin,andmorewithsecureprogramsthat
encryptallcommunicationevenpass-wordsoveranetwork.
Referto"OpenSSH:SecureNetworkCommunication"on
page579.
operatingsystem
Acontrolprogramforacomputerthatallocatescomputer
resources,schedulestasks,andprovidestheuserwitha
waytoaccessresources.
option
Acommandlineargumentthatmodifiestheeffectsofa
command.Optionsareusuallyprecededbyhyphensonthe
commandlineandtraditionallyhavesingle-characternames
(suchashorn).Somecommandsallowyoutogroup
optionsfollowingasinglehyphen(forexample,hn).GNU
utilitiesfrequentlyhavetwoargumentsthatdothesame
thing:asingle-characterargumentandalonger,more
descriptiveargumentthatisprecededbytwohyphens
(suchasshow-allandinvert-match).
ordinaryfile
Afilethatisusedtostoreaprogram,text,orotheruser
data.Seedirectory(page1029)anddevicefile(page
1029).
output
Informationthataprogramsendstotheterminalor
anotherfile.Seestandardoutputonpage1057.
P2P
Peer-to-Peer.Anetworkthatdoesnotdividenodesinto
clientsandservers.EachcomputeronaP2Pnetworkcan
fulfilltherolesofclientandserver.Inthecontextofafile-
sharingnetwork,thisabilitymeansthatonceanodehas
downloaded(partof)afile,itcanactasaserver.BitTorrent
implementsaP2Pnetwork.
packet
Aunitofdatasentacrossanetwork.Packetisageneric
termusedtodescribeaunitofdataatanylayeroftheOSI
protocolstack,butitismostcorrectlyusedtodescribe
networkorapplicationlayer(page352)dataunits
("applicationprotocoldataunit,"APDU).FOLDOCSeealso
frame(page1033)anddatagram(page1028).
packetfiltering
Atechniqueusedtoblocknetworktrafficbasedonspecified
criteria,suchastheorigin,destination,ortypeofeach
packet.Seealsofirewall(page1032).
packetsniffer
Aprogramordevicethatmonitorspacketsonanetwork.
Seesniffonpage1056.
pager
Autilitythatallowsyoutoviewafileonescreenatatime
(forexample,lessandmore).
paging
Theprocessbywhichvirtualmemoryismaintainedbythe
operatingsystem.Thecontentsofprocessmemoryis
moved(pagedout)totheswapspace(page1058)as
neededtomakeroomforotherprocesses.
PAM
Linux-PAMorLinux-PluggableAuthenticationModules.
Thesemodulesallowasystemadministratortodetermine
howvariousapplicationsauthenticateusers.Referto"PAM"
onpage438.
parentprocess
Aprocessthatforksotherprocesses.Seeprocess(page
1049)andchildprocess(page1024).
partition
Asectionofa(hard)diskthathasanamesoyoucan
addressitseparatelyfromothersections.Adiskpartition
canholdafilesystemoranotherstructure,suchasthe
swaparea.UnderDOSandWindows,partitions(and
sometimeswholedisks)arelabeledC:,D:,andsoon.Also
diskpartitionandslice.
passiveFTP
AllowsFTPtoworkthroughafirewallbyallowingtheflowof
datatobeinitiatedandcontrolledbytheclientFTPprogram
insteadoftheserver.AlsocalledPASVFTPbecauseituses
theFTPPASVcommand.
passphrase
Astringofwordsandcharactersthatyoutypeinto
authenticateyourself.Apass-phrasediffersfroma
passwordonlyinlength.Apasswordisusuallyshort6to10
characters.Apassphraseisusuallymuchlongerupto100
charactersormore.Thegreaterlengthmakesapassphrase
hardertoguessorreproducethanapasswordand
thereforemoresecure.FOLDOC
password
Topreventunauthorizedaccesstoauser'saccount,an
arbitrarystringofcharacterschosenbytheuserorsystem
administratorandusedtoauthenticatetheuserwhen
attemptingtologin.FOLDOCSeealsopassphrase.
PASVFTP
SeepassiveFTP.
pathname
Alistofdirectoriesseparatedbyslashes(/)andending
withthenameofafile,whichcanbeadirectory.A
pathnameisusedtotraceapaththroughthefilestructure
tolocateoridentifyafile.
pathname,lastelementofa
Thepartofapathnamefollowingthefinal/,orthewhole
filenameifthereisno/.Asimplefilename.Alsobasename.
pathnameelement
Oneofthefilenamesthatformsapathname.
peripheraldevice
Seedeviceonpage1028.
persistent
Datathatisstoredonnonvolatilemedia,suchasahard
disk.
phish
Anattempttotrickusersintorevealingorsharingprivate
information,especiallypasswordsorfinancialinformation.
Themostcommonformisemailpurportingtobefroma
bankorvendorthatrequeststhatauserfilloutaformto
"update"anaccountonaphoneyWebsitedisguisedto
appearlegitimate.Generallysentasspam(page1056).
physicaldevice
Atangibledevice,suchasadiskdrive,thatisphysically
separatefromother,similardevices.
PID
Processidentification,usuallyfollowedbythewordnumber.
LinuxassignsauniquePIDnumberaseachprocessis
initiated.
pipe
Aconnectionbetweenprogramssuchthatstandardoutput
ofoneprogramisconnectedtostandardinputofthenext.
Alsopipeline.
pixel
Thesmallestelementofapicture,typicallyasingledotona
displayscreen.
plaintext
Textthatisnotencrypted.Alsocleartext.Contrastwith
ciphertext(page1025).Seealso"Encryption"onpage988.
PluggableAuthenticationModules
SeePAMonpage1047.
point-to-pointlink
Aconnectionlimitedtotwoendpoints,suchasthe
connectionbetweenapairofmodems.
port
Alogicalchannelorchannelendpointinacommunications
system.TheTCP(page1059)andUDP(page1061)
transportlayerprotocolsusedonEthernetuseport
numberstodistinguishbetweendifferentlogicalchannels
onthesamenetworkinterfaceonthesamecomputer.
The/etc/servicesfile(seethebeginningofthisfilefor
moreinformation)ortheNIS(page1045)services
databasespecifiesauniqueportnumberforeach
applicationprogram.Thenumberlinksincomingdatatothe
correctservice(program).Standard,well-knownportsare
usedbyeveryone:Port80isusedforHTTP(Web)traffic.
Someprotocols,suchasTELNETandHTTP(whichisa
specialformofTELNET),havedefaultportsspecifiedas
mentionedearlierbutcanuseotherportsaswell.FOLDOC
portforwarding
Theprocessbywhichanetworkportononecomputeris
transparentlyconnectedtoaportonanothercomputer.If
portXisforwardedfromsystemAtosystemB,anydata
senttoportXonsystemAissenttosystemB
automatically.Theconnectioncanbebetweendifferent
portsonthetwosystems.Seealsotunneling(page1061).
portmapper
AserverthatconvertsTCP/IPportnumbersintoRPC(page
1053)programnumbers.See"RPCNetworkServices"on
page377.
printablecharacter
Oneofthegraphiccharacters:aletter,number,or
punctuationmark.Contrastwithanonprintable,or
CONTROL,character.Alsoprintingcharacter.
privateaddressspace
IANA(page1036)hasreservedthreeblocksofIPaddresses
forprivateinternetsorLANs:
10.0.0.0-10.255.255.255
172.16.0.0-172.31.255.255
192.168.0.0-192.168.255.255
Youcanusetheseaddresseswithoutcoordinatingwith
anyoneoutsideofyourLAN(youdonothavetoregisterthe
systemnameoraddress).SystemsusingtheseIP
addressescannotcommunicatedirectlywithhostsusingthe
globaladdressspacebutmustgothroughagateway.
Becauseprivateaddresseshavenoglobalmeaning,routing
informationisnotstoredbyDNSsandmostISPsreject
privatelyaddressedpackets.Makesurethatyourrouteris
setupnottoforwardthesepacketsontotheInternet.
privilegedport
Aport(page1048)withanumberlessthan1024.OnLinux
andotherUNIX-likesystems,onlyrootcanbindtoa
privilegedport.AnyuseronWindows98andearlier
Windowssystemscanbindtoanyport.Alsoreservedport.
procedure
Asequenceofinstructionsforperformingaparticulartask.
Mostprogramminglanguages,includingmachine
languages,enableaprogrammertodefineproceduresthat
allowtheprocedurecodetobecalledfrommultipleplaces.
Alsosubroutine.FOLDOC
process
TheexecutionofacommandbyLinux.See"Processes"on
page300.
.profilefile
Astartupfileinauser'shomedirectorythattheBourne
AgainorZShellexecuteswhenyoulogin.TheTCShell
executes.logininstead.Youcanusethe.profilefiletorun
commands,setvariables,anddefinefunctions.
program
Asequenceofexecutablecomputerinstructionscontained
inafile.Linuxutilities,applications,andshellscriptsareall
programs.Wheneveryourunacommandthatisnotbuilt
intoashell,youareexecutingaprogram.
PROM
Programmablereadonlymemory.Akindofnonvolatile
storage.ROM(page1053)thatcanbewrittentousinga
PROMprogrammer.
prompt
Acuefromaprogram,usuallydisplayedonthescreen,
indicatingthatitiswaitingforinput.Theshelldisplaysa
prompt,asdosomeoftheinteractiveutilities,suchasmail.
BydefaulttheBourneAgainandZShellsuseadollarsign
($)asaprompt,andtheTCShellusesapercentsign(%).
protocol
Asetofformalrulesdescribinghowtotransmitdata,
especiallyacrossanetwork.Low-levelprotocolsdefinethe
electricalandphysicalstandards,bitandbyteordering,and
transmission,errordetection,andcorrectionofthebit
stream.High-levelprotocolsdealwithdataformatting,
includingmessagesyntax,terminal-to-computerdialog,
charactersets,andsequencingofmessages.FOLDOC
proxy
Aservicethatisauthorizedtoactforasystemwhilenot
beingpartofthatsystem.Seealsoproxygatewayand
proxyserver.
proxygateway
Acomputerthatseparatesclients(suchasbrowsers)from
theInternet,workingasatrustedagentthataccessesthe
Internetontheirbehalf.Aproxygatewaypassesarequest
fordatafromanInternetservice,suchasHTTPfroma
browser/client,toaremoteserver.Thedatathattheserver
returnsgoesbackthroughtheproxygatewaytothe
requestingservice.Aproxygatewayshouldbetransparent
totheuser.
Aproxygatewayoftenrunsonafirewall(page1032)
systemandactsasabarriertomalicioususers.Ithidesthe
IPaddressesofthelocalcomputersinsidethefirewallfrom
Internetusersoutsidethefirewall.
Youcanconfigurebrowsers,suchasMozilla/Firefoxand
Netscape,touseadifferentproxygatewayortouseno
proxyforeachURLaccessmethodincludingFTP,netnews,
SNMP,HTTPS,andHTTP.Seealsoproxy.
proxyserver
Aproxygatewaythatusuallyincludesacache(page1023)
thatholdsfrequentlyusedWebpagessothatthenext
requestforthatpageisavailablelocally(andtherefore
morequickly).Thetermsproxyserverandproxygateway
arefrequentlyinterchangedsothattheuseofcachedoes
notrestexclusivelywiththeproxyserver.Seealsoproxy.
Python
Asimple,high-level,interpreted,object-oriented,
interactivelanguagethatbridgesthegapbetweenCand
shellprogramming.Suitableforrapidprototypingorasan
extensionlanguageforCapplications,Pythonsupports
packages,modules,classes,user-definedexceptions,a
goodCinterface,anddynamicloadingofCmodules.Ithas
noarbitraryrestrictions.Formoreinformation,see
www.python.orgFOLDOC
quote
Whenyouquoteacharacter,youtakeawayanyspecial
meaningthatithasinthecurrentcontext.Youcanquotea
characterbyprecedingitwithabackslash.Whenyouare
interactingwiththeshell,youcanalsoquoteacharacterby
surroundingitwithsinglequotationmarks.Forexample,
thecommandecho\*orecho'*'dis-plays*.The
commandecho*displaysalistofthefilesintheworking
directory.Seeambiguousfilereference(page1018),
metacharacter(page1042),regularcharacter(page1052),
regularexpression(page1052),andspecialcharacter
(page1056).Seealsoescapeonpage1031.
radiobutton
Oneofagroupofbuttonssimilartothoseusedtoselectthe
stationonaradio.Onlyonebuttoncanbeselectedata
time.
RAID
Redundantarrayofinexpensive/independentdisks.Twoor
more(hard)diskdrivesusedincombinationtoimprove
faulttoleranceandperformance.RAIDcanbeimplemented
inhardwareorsoftware.
RAM
Randomaccessmemory.Akindofvolatilestorage.Adata
storagedeviceforwhichtheorderofaccesstodifferent
locationsdoesnotaffectthespeedofaccess.Contrastwith
aharddiskortapedrive,whichprovidesquickeraccessto
sequentialdatabecauseaccessinganonsequentiallocation
requiresphysicalmovementofthestoragemediumand/or
read/writeheadratherthanjustelectronicswitching.
Contrastwithnonvolatilestorage(page1046).FOLDOC
RAMdisk
RAMthatismadetolooklikeafloppydisketteorharddisk.
ARAMdiskisfrequentlyusedaspartoftheboot(page
1022)process.
RAS
Remoteaccessserver.Inanetwork,acomputerthat
providesaccesstoremoteusersviaanalogmodemorISDN
connections.RASincludesthedial-upprotocolsandaccess
control(authentication).Itmaybearegularfileserverwith
remoteaccesssoftwareoraproprietarysystem,suchas
Shiva'sLANRover.Themodemsmaybeinternalorexternal
tothedevice.
RDF
ResourceDescriptionFramework.BeingdevelopedbyW3C
(themainstandardsbodyfortheWorldWideWeb),a
standardthatspecifiesamechanismforencodingand
transferringmetadata(page1043).RDFdoesnotspecify
whatthemetadatashouldorcanbe.Itcanintegratemany
kindsofapplicationsanddata,usingXMLasaninterchange
syntax.Examplesofthedatathatcanbeintegratedinclude
librarycatalogsandworldwidedirectories;syndicationand
aggregationofnews,software,andcontent;andcollections
ofmusicandphotographs.Gotowww.w3.org/RDFformore
information.
redirection
Theprocessofdirectingstandardinputforaprogramto
comefromafileratherthanfromthekeyboard.Also,
directingstandardoutputorstandarderrortogotoafile
ratherthantothescreen.
reentrant
Codethatcanhavemultiplesimultaneous,interleaved,or
nestedinvocationsthatdonotinterferewithoneanother.
Noninterferenceisimportantforparallelprocessing,
recursiveprogramming,andinterrupthandling.
Itisusuallyeasytoarrangeformultipleinvocations(that
is,callstoasubroutine)toshareonecopyofthecodeand
anyreadonlydata.Forthecodetobereentrant,however,
eachinvocationmustuseitsowncopyofanymodifiable
data(orsynchronizedaccesstoshareddata).Thisgoalis
mostoftenachievedbyusingastackandallocatinglocal
variablesinanewstackframeforeachinvocation.
Alternatively,thecallermaypassinapointertoablockof
memorythatthatinvocationcanuse(usuallyforoutput),or
thecodemayallocatesomememoryonaheap,especiallyif
thedatamustsurviveaftertheroutinereturns.
Reentrantcodeisoftenfoundinsystemsoftware,suchas
operatingsystemsandteleprocessingmonitors.Itisalsoa
crucialcomponentofmultithreadedprograms,wherethe
termthread-safeisoftenusedinsteadofreentrant.FOLDOC
regularcharacter
Acharacterthatalwaysrepresentsitselfinanambiguous
filereferenceoranothertypeofregularexpression.
Contrastwithspecialcharacter.
regularexpression
Astringcomposedofletters,numbers,andspecial
symbolsthatdefinesoneormorestrings.SeeAppendixA.
relativepathname
Apathnamethatstartsfromtheworkingdirectory.Contrast
withabsolutepathname(page1018).
remoteaccessserver
SeeRASonpage1051.
remotefilesystem
Afilesystemonaremotecomputerthathasbeensetupso
thatyoucanaccess(usuallyoveranetwork)itsfilesas
thoughtheywerestoredonyourlocalcomputer'sdisks.An
exampleofaremotefilesystemisNFS.
remoteprocedurecall
SeeRPConpage1053.
resolver
TheTCP/IPlibrarysoftwarethatformatsrequeststobesent
totheDNS(page1029)forhostname-to-Internetaddress
conversion.FOLDOC
ResourceDescriptionFramework
SeeRDFonpage1051.
restore
Theprocessofturninganiconintoawindow.Contrastwith
iconify(page1036)
returncode
Seeexitstatusonpage1031.
RFC
Requestforcomments.Begunin1969,oneofaseriesof
numberedInternetinformationaldocumentsandstandards
widelyfollowedbycommercialsoftwareandfreewareinthe
InternetandUNIX/Linuxcommunities.FewRFCsare
standardsbutallInternetstandardsarerecordedinRFCs.
PerhapsthesinglemostinfluentialRFChasbeenRFC822,
theInternetelectronicmailformatstandard.
TheRFCsareunusualinthattheyarefloatedbytechnical
expertsactingontheirowninitiativeandreviewedbythe
Internetatlargeratherthanbeingformallypromulgated
throughaninstitutionsuchasANSI.Forthisreasonthey
remainknownasRFCs,evenaftertheyareadoptedas
standards.TheRFCtraditionofpragmatic,experience-
driven,after-the-factstandardwritingdonebyindividuals
orsmallworkinggroupshasimportantadvantagesoverthe
moreformal,committee-drivenprocesstypicalofANSIor
ISO.ForacompletelistofRFCs,gotowww.rfc-
editor.org.FOLDOC
roam
Tomoveacomputerbetweenwirelessaccesspoints(page
1063)onawirelessnetworkwithouttheuseror
applicationsbeingawareofthetransition.Movingbetween
accesspointstypicallyresultsinsomepacketloss,although
thislossistransparenttoprogramsthatuseTCP.
ROM
Readonlymemory.Akindofnonvolatilestorage.Adata
storagedevicethatismanufacturedwithfixedcontents.In
general,ROMdescribesanystoragesystemwhosecontents
cannotbealtered,suchasaphonographrecordorprinted
book.Whenusedinreferencetoelectronicsandcomputers,
ROMdescribessemiconductorintegratedcircuitmemories,
ofwhichseveraltypesexist,andCD-ROM.
ROMisnonvolatilestorageitretainsitscontentsevenafter
powerhasbeenremoved.ROMisoftenusedtohold
programsforembeddedsystems,astheseusuallyhavea
fixedpurpose.ROMisalsousedforstorageoftheBIOS
(page1021)inacomputer.ContrastwithRAM(page
1051).FOLDOC
rootdirectory
Theancestorofalldirectoriesandthestartofallabsolute
pathnames.Thenameoftherootdirectoryis/.
rootfilesystem
Thefilesystemthatisavailablewhenthesystemisbrought
upinsingle-usermode.Thenameofthisfilesystemis
always/.Youcannotunmountormounttheroot
filesystem.Youcanremountroottochangeitsmount
options.
rootlogin
UsuallytheusernameofSuperuser(page1058).
root(user)
AnothernameforSuperuser(page1058).
rotate
Whenafile,suchasalogfile,getsindefinitelylarger,you
mustkeepitfromtakinguptoomuchspaceonthedisk.
Becauseyoumayneedtorefertotheinformationinthelog
filesinthenearfuture,itisgenerallynotagoodideato
deletethecontentsofthefileuntilithasaged.Insteadyou
canperiodicallysavethecurrentlogfileunderanewname
andcreateanew,emptyfileasthecurrentlogfile.Youcan
keepaseriesofthesefiles,renamingeachasanewoneis
saved.Youwillthenrotatethefiles.Forexample,youmight
removexyzlog.4,xyzlog.3 xyzlog.4,xyzlog.2
xyzlog.3,xyzlog.1 xyzlog.2,xyzlog xyzlog.1,and
createanewxyzlogfile.Bythetimeyouremove
xyzlog.4,itwillnotcontainanyinformationmorerecent
thanyouwanttoremove.
router
Adevice(oftenacomputer)thatisconnectedtomorethan
onesimilartypeofnetworktopassdatabetweenthem.See
gatewayonpage1033.
RPC
Remoteprocedurecall.Acalltoaprocedure(page1049)
thatactstransparentlyacrossanetwork.Theprocedure
itselfisresponsibleforaccessingandusingthenetwork.
TheRPClibrariesmakesurethatnetworkaccessis
transparenttotheapplication.RPCrunsontopofTCP/IPor
UDP/IP.
RSA
Apublickeyencryption(page989)technologythatisbased
onthelackofanefficientwaytofactorverylargenumbers.
Becauseofthislack,ittakesanextraordinaryamountof
computerprocessingtimeandpowertodeduceanRSAkey.
TheRSAalgorithmisthedefactostandardfordatasent
overtheInternet.
run
Toexecuteaprogram.
runlevel
ThemodethatLinuxisrunningin.Runlevelsincludesingle-
userandmultiuser.SeeTable11-1onpage404fora
completelistofrunlevels.
Samba
AfreesuiteofprogramsthatimplementtheServer
MessageBlock(SMB)protocol.SeeSMB(page1055).
schema
WithinaGUI,apatternthathelpsyouseeandinterpretthe
informationthatispresentedinawindow,makingiteasier
tounderstandnewinformationthatispresentedusingthe
sameschema.
scroll
Tomovelinesonaterminalorwindowupanddownorleft
andright.
scrollbar
Awidgetfoundingraphicaluserinterfacesthatcontrols
(scrolls)whichpartofadocumentisvisibleinthewindow.
Awindowcanhaveahorizontalscrollbar,averticalscrollbar
(morecommon),orboth.FOLDOC
server
Apowerfulcentralizedcomputer(orprogram)designedto
provideinformationtoclients(smallercomputersor
programs)onrequest.
session
Thelifetimeofaprocess.Foradesktop,itisthedesktop
sessionmanager.Foracharacter-basedterminal,itisthe
user'sloginshellprocess.InKDE,itislaunchedbykdeinit.A
sessionmayalsobethesequenceofeventsbetweenwhen
youstartusingaprogram,suchasaneditor,andwhenyou
finish.
setgid
Whenyouexecuteafilethathassetgid(setgroupID)
permission,theprocessexecutingthefiletakesonthe
privilegesofthegroupthefilebelongsto.Thelsutility
showssetgidpermissionasansinthegroup'sexecutable
position.Seealsosetuid.
setuid
Whenyouexecuteafilethathassetuid(setuserID)
permission,theprocessexecutingthefiletakesonthe
privilegesoftheownerofthefile.Asanexample,ifyourun
asetuidprogramthatremovesallthefilesinadirectory,
youcanremovefilesinanyofthefileowner'sdirectories,
evenifyoudonotnormallyhavepermissiontodoso.When
theprogramisownedbyroot,youcanremovefilesinany
directorythatrootcanremovefilesfrom.Thelsutility
showssetuidpermissionasansintheowner'sexecutable
position.Seealsosetgid.
sexillion
IntheBritishsystem,1036.IntheAmericansystem,this
numberisnamedundecil-lion.Seealsolargenumber(page
1040).
SHA1
SecureHashAlgorithm1.TheSHAfamilyisasetof
cryptographichash(page1034)algorithmsthatwere
designedbytheNationalSecurityAgency(NSA).The
secondmemberofthisfamilyisSHA1,asuccessortoMD5
(page1042).Seealsocryptographyonpage1027.
share
Afilesystemhierarchythatissharedwithanothersystem
usingSMB(page1055).AlsoWindowsshare(page1063).
sharednetworktopology
Anetwork,suchasEthernet,inwhicheachpacketmaybe
seenbysystemsotherthanitsdestinationsystem.Shared
meansthatthenetworkbandwidthissharedbyallusers.
shell
ALinuxsystemcommandprocessor.Thethreemajorshells
aretheBourneAgainShell(page1022),theTCShell(page
1059),andtheZShell(page1064).
shellfunction
Aseriesofcommandsthattheshellstoresforexecutionat
alatertime.Shellfunctionsarelikeshellscriptsbutrun
morequicklybecausetheyarestoredinthecomputer's
mainmemoryratherthaninfiles.Also,ashellfunctionis
runintheenvironmentoftheshellthatcallsit(unlikea
shellscript,whichistypicallyruninasubshell).
shellscript
AnASCIIfilecontainingshellcommands.Alsoshell
program.
signal
AverybriefmessagethattheUNIXsystemcansendtoa
process,apartfromtheprocess'sstandardinput.Referto
"trap:CatchesaSignal"onpage933.
simplefilename
Asinglefilenamecontainingnoslashes(/).Asimple
filenameisthesimplestformofpathname.Alsothelast
elementofapathname.Alsobasename(page1021).
single-usersystem
Acomputersystemthatonlyonepersoncanuseatatime.
Contrastwithmultiusersystem(page1044).
SMB
ServerMessageBlock.Developedintheearly1980sby
Intel,Microsoft,andIBM,SMBisaclient/serverprotocol
thatisthenativemethodoffileandprintersharingfor
Windows.Inaddition,SMBcanshareserialportsand
communicationsabstractions,suchasnamedpipesand
mailslots.SMBissimilartoaremoteprocedurecall(RPC,
page1053)thathasbeencustomizedforfilesystemaccess.
AlsoMicrosoftNetworking.FOLDOC
smiley
Acharacter-basedglyph(page1033),typicallyusedin
email,thatconveysanemotion.Thecharacters:-)ina
messageportrayasmileyface(lookatitsideways).
Becauseitcanbedifficulttotellwhenthewriterofan
electronicmessageissayingsomethinginjestorin
seriousness,emailusersoftenuse:-)toindicatehumor.
Thetwooriginalsmileys,designedbyScottFahlman,were
:-)and:-(.Alsoemoticon,smileys,andsmilies.Formore
informationsearchonsmileyontheInternet.
smilies
Seesmiley.
SMTP
SimpleMailTransferProtocol.Aprotocolusedtotransfer
electronicmailbetweencomputers.Itisaserver-to-server
protocol,sootherprotocolsareusedtoaccessthe
messages.TheSMTPdialogusuallyhappensinthe
backgroundunderthecontrolofamessagetransport
systemsuchassendmail.FOLDOC
snap(windows)
Asyoudragawindowtowardanotherwindoworedgeof
theworkspace,itcanmovesuddenlysothatitisadjacent
totheotherwindow/edge.Thusthewindowsnapsinto
position.
sneakernet
Usinghand-carriedmagneticmediatotransferfiles
betweenmachines.
sniff
Tomonitorpacketsonanetwork.Asystemadministrator
canlegitimatelysniffpacketsandamalicioususercansniff
packetstoobtaininformationsuchasuser-namesand
passwords.Seealsopacketsniffer(page1047).
SOCKS
AnetworkingproxyprotocolembodiedinaSOCKSserver,
whichperformsthesamefunctionsasaproxygateway
(page1050)orproxyserver(page1050).SOCKSworksat
theapplicationlevel,requiringthatanapplicationbe
modifiedtoworkwiththeSOCKSprotocol,whereasaproxy
(page1050)makesnodemandsontheapplication.
SOCKSv4doesnotsupportauthenticationorUDPproxy.
SOCKSv5supportsavarietyofauthenticationmethodsand
UDPproxy.
sort
Toputinaspecifiedorder,usuallyalphabeticornumeric.
SPACEcharacter
Acharacterthatappearsastheabsenceofavisible
character.Eventhoughyoucannotseeit,aSPACEisa
printablecharacter.ItisrepresentedbytheASCIIcode32
(decimal).ASPACEcharacterisconsideredablankor
whitespace(page1063).
spam
Postingirrelevantorinappropriatemessagestooneormore
Usenetnewsgroupsormailinglistsindeliberateor
accidentalviolationofnetiquette(page1044).Also,sending
largeamountsofunsolicitedemailindiscriminately.This
emailusuallypromotesaproductorservice.Another
commonpurposeofspamistophish(page1048).Spamis
theelectronicequivalentofjunkmail.FromtheMonty
Python"Spam"song.FOLDOC
sparsefile
Afilethatislargebuttakesuplittlediskspace.Thedatain
asparsefileisnotdense(thusitsname).Examplesof
sparsefilesarecorefilesanddbmfiles.
spawn
Seeforkonpage1032.
specialcharacter
Acharacterthathasaspecialmeaningwhenitoccursinan
ambiguousfilereferenceoranothertypeofregular
expression,unlessitisquoted.Thespecialcharactersmost
commonlyusedwiththeshellare*and?.Also
metacharacter(page1042)andwildcard.
specialfile
Seedevicefileonpage1029.
spinner
InaGUI,atypeoftextbox(page1059)thatholdsa
numberyoucanchangebytypingoveritorusingtheup
anddownarrowsattheendofthebox.
spoofing
SeeIPspoofingonpage1038.
spool
Toplaceitemsinaqueue,eachwaitingitsturnforsome
action.Oftenusedwhenspeakingaboutprinters.Alsoused
todescribethequeue.
SQL
StructuredQueryLanguage.Alanguagethatprovidesa
userinterfacetorelationaldatabasemanagementsystems
(RDBMS).SQL,thedefactostandard,isalsoanISOand
ANSIstandardandisoftenembeddedinother
programminglanguages.FOLDOC
squarebracket
Aleftsquarebracket([)orarightsquarebracket(]).
Thesespecialcharactersdefinecharacterclassesin
ambiguousfilereferencesandotherregularexpressions.
SSHCommunicationsSecurity
ThecompanythatcreatedtheoriginalSSH(secureshell)
protocolsuite(www.ssh.com).LinuxusesOpenSSH(page
1046).
standarderror
Afiletowhichaprogramcansendoutput.Usuallyonly
errormessagesaresenttothisfile.Unlessyouinstructthe
shellotherwise,itdirectsthisoutputtothescreen(thatis,
tothedevicefilethatrepresentsthescreen).
standardinput
Afilefromwhichaprogramcanreceiveinput.Unlessyou
instructtheshellotherwise,itdirectsthisinputsothatit
comesfromthekeyboard(thatis,fromthedevicefilethat
representsthekeyboard).
standardoutput
Afiletowhichaprogramcansendoutput.Unlessyou
instructtheshellotherwise,itdirectsthisoutputtothe
screen(thatis,tothedevicefilethatrepresentsthe
screen).
startupfile
Afilethattheloginshellrunswhenyoulogin.TheBourne
AgainandZShellsrun.profile,andtheTCShellruns
.login.TheTCShellalsoruns.cshrcwheneveranewTC
Shellorasubshellisinvoked.TheZShellrunsan
analogousfilewhosenameisidentifiedbytheENV
variable.
statusline
Thebottom(usuallythetwenty-fourth)lineoftheterminal.
Thevimeditorusesthestatuslinetodisplayinformation
aboutwhatishappeningduringaneditingsession.
stickybit
Anaccesspermissionbitthatcausesanexecutableprogram
toremainontheswapareaofthedisk.Ittakeslesstimeto
loadaprogramthathasitsstickybitsetthanonethatdoes
not.OnlySuperusercansetthestickybit.Ifthestickybitis
setonadirectorythatispubliclywritable,onlytheownerof
afileinthatdirectorycanremovethefile.
streamingtape
Atapethatmovesataconstantspeedpasttheread/write
headsratherthanspeedingupandslowingdown,whichcan
slowtheprocessofwritingtoorreadingfromthetape.A
properblockingfactorhelpsensurethatthetapedevicewill
bekeptstreaming.
streams
Seeconnection-orientedprotocolonpage1026.
string
Asequenceofcharacters.
stylesheet
SeeCSSonpage1027.
subdirectory
Adirectorythatislocatedwithinanotherdirectory.Every
directoryexcepttherootdirectoryisasubdirectory.
subnet
Subnetwork.Aportionofanetwork,whichmaybea
physicallyindependentnetworksegment,thatsharesa
networkaddresswithotherportionsofthenetworkandis
distinguishedbyasubnetnumber.Asubnetistoanetwork
asanetworkistoaninternet.FOLDOC
subnetaddress
ThesubnetportionofanIPaddress.Inasubnetted
network,thehostportionofanIPaddressissplitintoa
subnetportionandahostportionusingasubnetmask(also
addressmask).Seealsosubnetnumber.
subnetmask
AbitmaskusedtoidentifywhichbitsinanIPaddress
correspondtothenetworkaddressandsubnetportionsof
theaddress.Calledasubnetmaskbecausethenetwork
portionoftheaddressisdeterminedbythenumberofbits
thataresetinthemask.Thesubnetmaskhasonesin
positionscorrespondingtothenetworkandsubnetnumbers
andzerosinthehostnumberpositions.Alsoaddressmask.
subnetnumber
ThesubnetportionofanIPaddress.Inasubnetted
network,thehostportionofanIPaddressissplitintoa
subnetportionandahostportionusingasubnetmask.Also
addressmask.Seealsosubnetaddress.
subpixelhinting
Similartoanti-aliasing(page1019)buttakesadvantageof
colorstodotheanti-aliasing.ParticularlyusefulonLCD
screens.
subroutine
Seeprocedureonpage1049.
subshell
Ashellthatisforkedasaduplicateofitsparentshell.When
yourunanexecutablefilethatcontainsashellscriptby
usingitsfilenameonthecommandline,theshellforksa
subshelltorunthescript.Also,commandssurroundedwith
parenthesesareruninasubshell.
superblock
Ablockthatcontainscontrolinformationforafilesystem.
Thesuperblockcontainshousekeepinginformation,suchas
thenumberofinodesinthefilesystemandfreelist
information.
superserver
TheextendedInternetservicesdaemon.Refertoxinetdon
page376.
Superuser
Aprivilegeduserhavingaccesstoanythinganyother
systemuserhasaccesstoandmore.Thesystem
administratormustbeabletobecomeSuperuserto
establishnewaccounts,changepasswords,andperform
otheradministrativetasks.TheusernameofSuperuseris
usuallyroot.Alsorootorrootuser.
swap
Theoperatingsystemmovingaprocessfrommainmemory
toadisk,orviceversa.Swappingaprocesstothedisk
allowsanotherprocesstobeginorcontinueexecution.
Referto"swap"onpage458.
swapspace
Anareaofadisk(thatis,aswapfile)usedtostorethe
portionofaprocess'smemorythathasbeenpagedout.
Underavirtualmemorysystem,theamountofswap
spaceratherthantheamountofphysical
memorydeterminesthemaximumsizeofasingleprocess
andthemaximumtotalsizeofallactiveprocesses.Also
swapareaorswappingarea.FOLDOC
switch
Seenetworkswitchonpage1045.
symboliclink
Adirectoryentrythatpointstothepathnameofanother
file.Inmostcasesasymboliclinktoafilecanbeusedin
thesamewaysahardlinkcanbeused.Unlikeahardlink,a
symboliclinkcanspanfilesystemsandcanconnecttoa
directory.
systemadministrator
Thepersonresponsiblefortheupkeepofthesystem.The
systemadministratorhastheabilitytologinasSuperuser.
SeealsoSuperuser.
systemconsole
Themainsystemterminal,usuallydirectlyconnectedtothe
computerandtheonethatreceivessystemerrormessages.
Alsoconsoleandconsoleterminal.
systemmode
Thedesignationforthestateofthesystemwhileitisdoing
systemwork.Someexamplesaremakingsystemcalls,
runningNFSandautofs,processingnetworktraffic,and
performingkerneloperationsonbehalfofthesystem.
Contrastwithusermode(page1062).
SystemV
OneofthetwomajorversionsoftheUNIXsystem.
TCShell
tcsh.Anenhancedbutcompletelycompatibleversionofthe
BSDUNIXCshell,csh.
TCP
TransmissionControlProtocol.Themostcommontransport
layerprotocolusedontheInternet.Thisconnection-
orientedprotocolisbuiltontopofIP(page1038)andis
nearlyalwaysseeninthecombinationTCP/IP(TCPoverIP).
TCPaddsreliablecommunication,sequencing,andflow
controlandprovidesfull-duplex,process-to-process
connections.UDP(page1061),althoughconnectionless,is
theotherprotocolthatrunsontopofIP.FOLDOC
tera-
Inthebinarysystem,theprefixtera-multipliesby240
(1,099,511,627,776).Terabyteisacommonuseofthis
prefix.AbbreviatedasT.Seealsolargenumberonpage
1040.
termcap
Terminalcapability.The/etc/termcapfilecontainsalistof
varioustypesofterminalsandtheircharacteristics.System
Vreplacedthefunctionofthisfilewiththeterminfosystem.
terminal
Differentiatedfromaworkstation(page1064)byitslackof
intelligence,aterminalconnectstoacomputerthatruns
Linux.AworkstationrunsLinuxonitself.
terminfo
Terminalinformation.The/usr/lib/terminfodirectory
containsmanysubdirectories,eachcontainingseveralfiles.
Eachofthosefilesisnamedforandholdsasummaryofthe
functionalcharacteristicsofaparticularterminal.Visually
orientedtextualprograms,suchasvim,usethesefiles.An
alternativetothetermcapfile.
textbox
InaGUI,aboxyoucantypein.
theme
Definedasanimplicitorrecurrentidea,themeisusedina
GUItodescribealookthatisconsistentforallelementsof
adesktop.Gotothemes.freshmeat.netforexamples.
thicknet
Atypeofcoaxialcable(thick)usedforanEthernetnetwork.
Devicesareattachedtothicknetbytappingthecableat
fixedpoints.
thinnet
Atypeofcoaxialcable(thin)usedforanEthernetnetwork.
Thinnetcableissmallerindiameterandmoreflexiblethan
thicknetcable.Eachdeviceistypicallyattachedtotwo
separatecablesegmentsbyusingaT-shapedconnector;
onesegmentleadstothedeviceaheadofitonthenetwork
andonetothedevicethatfollowsit.
thread-safe
Seereentrantonpage1051.
thumb
Themovablebuttoninthescrollbarthatpositionstheimage
inthewindow.Thesizeofthethumbreflectstheamountof
informationinthebuffer.Alsobubble.
TIFF
TaggedImageFileFormat.Afileformatusedforstill-image
bitmaps,storedintaggedfields.Applicationprogramscan
usethetagstoacceptorignorefields,dependingontheir
capabilities.FOLDOC
tiledwindows
Anarrangementofwindowssuchthatnowindowoverlaps
another.Theoppositeofcascadingwindows(page1023).
timetolive
SeeTTL.
toggle
Toswitchbetweenoneoftwopositions.Forexample,theftp
globcommandtogglestheglobfeature:Givethe
commandonce,anditturnsthefeatureonoroff;givethe
commandagain,anditsetsthefeaturebacktoitsoriginal
state.
token
Abasic,grammaticallyindivisibleunitofalanguage,such
asakeyword,operator,oridentifier.FOLDOC
tokenring
AtypeofLAN(page1040)inwhichcomputersareattached
toaringofcable.Atokenpacketcirculatescontinuously
aroundthering.Acomputercantransmitinformationonly
whenitholdsthetoken.
tooltip
Aminicontexthelpsystemthatyouactivatebyallowing
yourmousepointertohover(page1036)overabutton,
icon,orapplet(suchasthoseonapanel).
transientwindow
Adialogorotherwindowthatisdisplayedforonlyashort
time.
TransmissionControlProtocol
SeeTCPonpage1059.
Trojanhorse
Aprogramthatdoessomethingdestructiveordisruptiveto
yoursystem.Itsactionisnotdocumented,andthesystem
administratorwouldnotapproveofitifshewereawareof
it.See"AvoidingaTrojanHorse"onpage398.
ThetermTrojanhorsewascoinedbyMIT-hacker-turned-
NSA-spookDanEdwards.Itreferstoamalicioussecurity-
breakingprogramthatisdisguisedassomethingbenign,
suchasadirectorylister,archiveutility,game,or(inone
notorious1990caseontheMac)aprogramtofindand
destroyviruses.Similartobackdoor(page1020).FOLDOC
TTL
Timetolive.
1. AllDNSrecordsspecifyhowlongtheyaregood
forusuallyuptoaweekatmost.Thistimeiscalledthe
record'stimetolive.WhenaDNSserveroran
applicationstoresthisrecordincache(page1023),it
decrementstheTTLvalueandremovestherecordfrom
cachewhenthevaluereacheszero.ADNSserver
passesacachedrecordtoanotherserverwiththe
current(decremented)TTLguaranteeingtheproper
TTL,nomatterhowmanyserverstherecordpasses
through.
2. IntheIPheader,afieldthatindicateshowmanymore
hopsthepacketshouldbeallowedtomakebeforebeing
discardedorreturned.
TTY
Teletypewriter.TheterminaldevicethatUNIXwasfirstrun
from.TodayTTYreferstothescreen(orwindow,inthe
caseofaterminalemulator),keyboard,andmousethatare
connectedtoacomputer.ThistermappearsinUNIX,and
Linuxhaskeptthetermforthesakeofconsistencyand
tradition.
tunneling
EncapsulationofprotocolAwithinpacketscarriedby
protocolB,suchthatAtreatsBasthoughitwereadata
linklayer.Tunnelingisusedtotransferdatabetween
administrativedomainsthatuseaprotocolnotsupportedby
theinternetconnectingthosedomains.Itcanalsobeused
toencryptdatasentoverapublicinternet,aswhenyouuse
sshtotunnelaprotocolovertheInternet.FOLDOCSeealsoVPN
(page1062)andportforwarding(page1049).
UDP
UserDatagramProtocol.TheInternetstandardtransport
layerprotocolthatprovidessimplebutunreliabledatagram
services.UDPisaconnectionlessprotocol(page1026)that,
likeTCP(page1059),islayeredontopofIP(page1038).
UnlikeTCP,UDPneitherguaranteesdeliverynorrequiresa
connection.Asaresultitislightweightandefficient,butthe
applicationprogrammusthandleallerrorprocessingand
retransmission.UDPisoftenusedforsendingtime-sensitive
datathatisnotparticularlysensitivetominorloss,suchas
audioandvideodata.FOLDOC
UID
UserID.Anumberthatthepasswddatabaseassociates
withausername.
undecillion
IntheAmericansystem,1036.IntheBritishsystem,this
numberisnamedsexillion.Seealsolargenumber(page
1040).
unicast
Apacketsentfromonehosttoanotherhost.Unicastmeans
onesourceandonedestination.
Unicode
Acharacterencodingstandardthatwasdesignedtocover
allmajormodernwrittenlanguageswitheachcharacter
havingexactlyoneencodingandbeingrepresentedbya
fixednumberofbits.
unmanagedwindow
Seeignoredwindowonpage1036.
URI
UniversalResourceIdentifier.Thegenericsetofallnames
andaddressesthatareshortstringsreferringtoobjects
(typicallyontheInternet).ThemostcommonkindsofURIs
areURLs.FOLDOC
URL
Uniform(wasUniversal)ResourceLocator.Astandardway
ofspecifyingthelocationofanobject,typicallyaWebpage,
ontheInternet.URLsareasubsetofURIs.
usagemessage
Amessagedisplayedbyacommandwhenyoucallthe
commandusingincorrectcommandlinearguments.
UserDatagramProtocol
SeeUDP.
UserID
SeeUID.
userinterface
Seeinterfaceonpage1037.
usermode
Thedesignationforthestateofthesystemwhileitisdoing
userwork,suchasrunningauserprogram(butnotthe
systemcallsmadebytheprogram).Contrastwithsystem
mode(page1059).
username
Thenameyouenterinresponsetothelogin:prompt.
Otherusersuseyourusernamewhentheysendyoumailor
writetoyou.EachusernamehasacorrespondinguserID,
whichisthenumericidentifierfortheuser.Boththe
usernameandtheuserIDarestoredinthepasswd
database(/etc/passwdortheNISequivalent).Alsologin
name.
userspace
Thepartofmemory(RAM)whereapplicationsreside.Code
runninginuserspacecannotaccesshardwaredirectlyand
cannotaccessmemoryallocatedtootherapplications.Also
userland.SeetheKernelAnalysis-HOWTO.
UTC
CoordinatedUniversalTime.UTCistheequivalenttothe
meansolartimeattheprimemeridian(0degrees
longitude).AlsocalledZulutime(Zstandsforlongitude
zero)andGMT(GreenwichMeanTime).
UTF-8
AnencodingthatallowsUnicode(page1061)charactersto
berepresentedusingsequencesof8-bitbytes.
utility
AprogramincludedasastandardpartofLinux.You
typicallyinvokeautilityeitherbygivingacommandin
responsetoashellpromptorbycallingitfromwithina
shellscript.Utilitiesareoftenreferredtoascommands.
Contrastwithbuiltin(command)(page1023).
variable
Anameandanassociatedvalue.Theshellallowsyouto
createvariablesandusetheminshellscripts.Also,the
shellinheritsseveralvariableswhenitisinvoked,andit
maintainsthoseandothervariableswhileitisrunning.
Someshellvariablesestablishcharacteristicsoftheshell
environment;othershavevaluesthatreflectdifferent
aspectsofyourongoinginteractionwiththeshell.
viewport
Sameasworkspace(page1064).
virtualconsole
Additionalconsoles,ordisplays,thatyoucanviewonthe
system,orphysical,console.Seepage113formore
information.
virus
Acracker(page1027)programthatsearchesoutother
programsand"infects"thembyembeddingacopyofitself
inthem,sothattheybecomeTrojanhorses(page1060).
Whentheseprogramsareexecuted,theembeddedvirusis
executedaswell,propagatingthe"infection,"usually
withouttheuser'sknowledge.Byanalogywithbiological
viruses.FOLDOC
VLAN
VirtualLAN.Alogicalgroupingoftwoormorenodesthat
arenotnecessarilyonthesamephysicalnetworksegment
butthatsharethesamenetworknumber.AVLANisoften
associatedwithswitchedEthernet.FOLDOC
VPN
Virtualprivatenetwork.Aprivatenetworkthatexistsona
publicnetwork,suchastheInternet.AVPNisaless
expensivesubstituteforcompany-owned/leasedlinesand
usesencryption(page988)toensureprivacy.Aniceside
effectisthatyoucansendnon-Internetprotocols,suchas
AppleTalk,IPX,orNetBIOS(page1044),overtheVPN
connectionbytunneling(page1061)themthroughtheVPN
IPstream.
W2K
Windows2000ProfessionalorServer.
W3C
WorldWideWebConsortium(www.w3.org).
WAN
Wideareanetwork.AnetworkthatinterconnectsLANs
(page1040)andMANs(page1042),spanningalarge
geographicarea(typicallystatesorcountries).
WAP
Wirelessaccesspoint.Abridgeorrouterbetweenwiredand
wirelessnetworks.WAPstypicallysupportsomeformof
accesscontroltopreventunauthorizedclientsfrom
connectingtothenetwork.
Webring
AcollectionofWebsitesthatprovideinformationona
singletopicorgroupofrelatedtopics.Eachhomepagethat
ispartoftheWebringhasaseriesoflinksthatletyougo
fromsitetosite.
whitespace
AcollectivenameforSPACEsand/orTABsandoccasionally
NEWLINEs.Alsowhitespace.
wideareanetwork
SeeWAN.
widget
Thebasicobjectsofagraphicaluserinterface.Buttons,text
fields,andscrollbarsareexamplesofwidgets.
wildcard
Seemetacharacteronpage1042.
Wi-Fi
WirelessFidelity.Agenerictermthatreferstoanytypeof
802.11(page1018)wirelessnetwork.
window
Onadisplayscreen,aregionthatrunsoriscontrolledbya
particularprogram.
windowmanager
Aprogramthatcontrolshowwindowsappearonadisplay
screenandhowyoumanipulatethem.
Windowsshare
Seeshareonpage1054.
WINS
WindowsInternetNamingService.Theserviceresponsible
formappingNetBIOSnamestoIPaddresses.WINShasthe
samerelationshiptoNetBIOSnamesthatDNShasto
Internetdomainnames.
WINSserver
TheprogramresponsibleforhandlingWINSrequests.This
programcachesnameinformationabouthostsonalocal
networkandresolvesthemtoIPaddresses.
wirelessaccesspoint
SeeWAP.
word
Asequenceofoneormorenonblankcharactersseparated
fromotherwordsbyTABs,SPACEs,orNEWLINEs.Usedto
refertoindividualcommandlinearguments.Invim,aword
issimilartoawordintheEnglishlanguageastringofoneor
morecharactersboundedbyapunctuationmark,a
numeral,aTAB,aSPACE,oraNEWLINE.
Workbuffer
Alocationwherevimstorestextwhileitisbeingedited.The
informationintheWorkbufferisnotwrittentothefileon
thediskuntilyougivetheeditoracommandtowriteit.
workingdirectory
Thedirectorythatyouareassociatedwithatanygiven
time.Therelativepathnamesyouusearerelativetothe
workingdirectory.Alsocurrentdirectory.
workspace
Asubdivisionofadesktop(page1028)thatoccupiesthe
entiredisplay.Referto"GettingtheMostfromtheDesktop"
onpage85.
workstation
Asmallcomputer,typicallydesignedtofitinanofficeand
beusedbyonepersonandusuallyequippedwithabit-
mappedgraphicaldisplay,keyboard,andmouse.
Differentiatedfromaterminal(page1059)byits
intelligence.AworkstationrunsLinuxonitselfwhilea
terminalconnectstoacomputerthatrunsLinux.
worm
Aprogramthatpropagatesitselfoveranetwork,
reproducingitselfasitgoes.Todaythetermhasnegative
connotations,asitisassumedthatonlycrackers(page
1027)writeworms.Comparetovirus(page1062)and
Trojanhorse(page1060).FromTapeworminJohn
Brunner'snovel,TheShockwaveRider,BallantineBooks,
1990(viaXEROXPARC).FOLDOC
WYSIWYG
WhatYouSeeIsWhatYouGet.Agraphicalapplication,
suchasawordprocessor,whosedisplayissimilartoits
printedoutput.
Xserver
TheXserveristhepartoftheXWindowSystemthatruns
themouse,keyboard,anddisplay.(Theapplicationprogram
istheclient.)
Xterminal
AgraphicsterminaldesignedtoruntheXWindowSystem.
XWindowSystem
Adesignandsetoftoolsforwritingflexible,portable
windowingapplications,createdjointlybyresearchersat
MITandseveralleadingcomputermanufacturers.
XDMCP
XDisplayManagerControlProtocol.XDMCPallowsthelogin
servertoacceptrequestsfromnetworkdisplays.XDMCPis
builtintomanyXterminals.
xDSL
DifferenttypesofDSL(page1030)areidentifiedbya
prefix,forexample,ADSL,HDSL,SDSL,andVDSL.
Xinerama
AnextensiontoX.org.Xineramaallowswindowmanagers
andapplicationstousethetwoormorephysicaldisplaysas
onelargevirtualdisplay.RefertotheXinerama-HOWTO.
XML
ExtensibleMarkupLanguage.Auniversalformatfor
structureddocumentsanddataontheWeb.Developedby
W3C(page1063),XMLisapared-downversionofSGML.
Seewww.w3.org/XMLandwww.w3.org/XML/1999/XML-in-
10-points.
XSM
XSessionManager.Thisprogramallowsyoutocreatea
sessionthatincludescertainapplications.Whilethesession
isrunning,youcanperformacheckpoint(savesthe
applicationstate)orashutdown(savesthestateandexits
fromthesession).Whenyoulogbackin,youcanloadyour
sessionsothateverythinginyoursessionisrunningjustas
itwaswhenyouloggedoff.
ZShell
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
!Booleanoperator2nd3rd
!variable
!!toreexecutethepreviousevent
!$lastwordofthepreviousevent
#comment2nd
#prompt
#variable
#!tochooseascriptshell
#defineCpreprocessordirective2nd
#includeCpreprocessordirective
$inregularexpressions
$invariablename
$!variable
$#variable
$$variable2nd
$(...)[SeeCommand,substitution.]
$*variable
$0variable
$?variable
$@variable2nd
${},expandvariable
%jobnumber2nd
&background2nd3rd4th5th6th7th
&bitwiseoperator2nd
&inreplacementstring2nd
&&Booleanoperator2nd3rd4th5th6th
((...))[SeeArithmeticevaluation.]
()commandgrouping
()inshellfunctions
*inregularexpressions
*specialcharacter
*/Ccomment
+infullregularexpressions
.(dot)builtin2nd3rd4th
.directory2nd3rd
.inregularexpressions
..directory2nd3rd
./toexecuteafileintheworkingdirectory2nd
.afilenameextension2nd
.autofsckfile
.bash_historyfile
.bash_loginfile
.bash_logoutfile
.bash_profilefile2nd3rd
.bashrcfile2nd3rd
.bmpfilenameextension
.bz2filenameextension2nd
.Cfilenameextension
.cfilenameextension2nd3rd4th
.c++filenameextension
.ccfilenameextension
.conffilenameextension
.configfile
.cppfilenameextension
.cshrcfile
.cxxfilenameextension
.dbfilenameextension2nd
.ffilenameextension
.forwardfile2nd
.giffilenameextension
.gzfilenameextension2nd
.hfilenameextension2nd
.htaccessfile2nd
.htmfilenameextension
.htmlfilenameextension2nd
.htpasswdfile
.inputrcfile
.jpegfilenameextension2nd
.jpgfilenameextension2nd
.lfilenameextension
.loginfile
.logoutfile
.mfilenameextension
.netrcfile
.ofilenameextension2nd3rd4th
.pdffilenameextension
.pgpkeyfile
.phpfilenameextension
.planfile
.ppdfilenameextension
.profilefile2nd3rd
.projectfile
.psfilenameextension
.repofilenameextension
.rhostsfile2nd
.rpmnewfilenameextension
.sfilenameextension2nd
.shfilenameextension
.shtmlfilenameextension
.sofilenameextension2nd
.sshdirectory
.tar.bz2filenameextension
.tar.gzfilenameextension
.tar.Zfilenameextension2nd
.tbzfilenameextension
.tgzfilenameextension
.tiffilenameextension2nd
.tifffilenameextension2nd
.toprcfile
.torrentfile
.txtfilenameextension2nd
.tzfilenameextension
.varfilenameextension
.yfilenameextension
.Zfilenameextension2nd
/directory(root)2nd3rd
/*Ccomment
/bin
falsefile
/boot
grub/grub.conffile2nd
location
partition2nd3rd
/dev2nd3rd
nst0file
nullfile2nd3rd4th5th6th
ptsfile
randomfile
rmt/0file
specialfiles
st0file
ttyfile
urandomfile
zerofile
/devdirectory
/etc
aliasesfile2nd3rd
anacrontabfile
at.allowfile
at.denyfile
auto_masterfile
bashrcfile2nd
cron.*directories
cron.allowfile
cron.ddirectory
cron.denyfile
crontabfile
cupsdirectory
defaultrouterfile
dhclient.conffile
dhcpd.conffile
dovecot.conffile
dumpdatesfile2nd
exportsfile2nd3rd
fstabfile2nd3rd4th5th
groupfile2nd3rd4th
grub.conffile2nd
hostsfile2nd3rd4th5th
hosts.allowfile2nd3rd
hosts.denyfile2nd3rd
hosts.equivfile2nd
httpddirectory
inittabfile2nd3rd4th5th
issuefile2nd
login.defsfile2nd
logrotate.conffile
logrotate.ddirectory
maildirectory2nd
motdfile2nd3rd4th5th
mtabfile
named.conffile2nd3rd
netgroupfile
nologin.txtfile2nd
nsswitch.conffile2nd3rd4th5th6th
ntp.conffile
optdirectory
pam.conffile
pam.ddirectory2nd3rd4th
passwdfile2nd3rd4th5th6th7th8th9th
printcapfile
profilefile2nd3rd4th
protocolsfile2nd
rc.d
directoryhierarchy2nd
init.d:about
init.d:independentservices
init.d:initscripts
init.d:kudzufile
rcfile
rc.localfile
rc.sysinitfile2nd
rcn.ddirectory
resolv.conffile2nd3rd
rndc.conffile
rndc.keyfile
rpcfile2nd
securettyfile
security/access.conffile
selinux/configfile
servicesfile2nd3rd
shadowfile2nd
share/magicfile
shellsfile
skeldirectory
sshdirectory
sudoersfile
sysconfig
httpdfile2nd
hwconffile
iptablesfile2nd3rd
iptables-configfile
namedfile2nd
networkfile2nd
rhn/up2datefile
selinuxfile
syslogfile
yppasswddfile
sysctl.conffile
syslog.conffile2nd
termcapfile
vsftpd
chroot_listfile
ftpusersfile
user_listfile
X11
xorgfile
xinetd.conffile2nd
xinetd.ddirectory2nd
yp.conffile
ypserv.conffile
yum.conffile
yum.repos.ddirectory2nd
/homedirectory
/homepartition
/lib
gccand
modulesdirectory2nd
securitydirectory2nd
/lost+founddirectory
/mntdirectory
/optdirectory2nd3rd
/proc
contents
filesystem2nd
fs/nfsfile
mountsfile
sysfile
/root
anaconda-ks.cfgfile
install.logfile
/sbin
Superusercommands
/sysdirectory
/tmpdirectory2nd3rd
/usr
bindirectory
docdirectory2nd
gamesdirectory
include
Cpreprocessor
infodirectory
lib
directory
gcc
sharedlibraries
terminfodirectory
local2nd
partition
mandirectory
partition
pub/asciifile
sbin
daemons
Superusercommands
share
magicfile
srcdirectory2nd
/var
ftpdirectory
lib/nfs/xtabfile2nd
log2nd3rd
diskusage
lastlogfile
maillogfile
messagesfile2nd3rd4th5th6th7th8th
securefile2nd3rd
vsftpd.logfile
wtmpfile2nd
logdirectory
maildirectory
nameddirectory2nd
partition
spool
diskusage
maildirectory
mqueuefile
tmpdirectory
www
Apachefiles
htmldirectory2nd3rd
aBooleanoperator
'...'[SeeCommand,substitution.]
0<redirectstandardinput
100BaseTcable
10Base2cable
10BaseTcable
1>redirectstandardoutput
2>redirectstandarderror
3-DESencryption
802.11
:(null)builtin2nd3rd
:=assigndefaultvalue
:=substitutedefaultvalue
:?displayerrormessage
;commandseparator
<redirectstandardinput2nd3rd
<&duplicateinputfiledescriptor
<<Heredocument2nd
>redirectstandardoutput2nd3rd4th5th
>&duplicateoutputfiledescriptor2nd
>>appendstandardoutput2nd
?infullregularexpressions
?specialcharacter
@inanetworkaddress2nd3rd
@variable
@withemail
[[...]][SeealsoConditionalexpression.]
[[...]]builtin
[]characterclass2nd3rd
\escapecharacter2nd3rd
\(inregularexpressions
\)inregularexpressions
\ninreplacementstrings
^bitwiseoperator
^inregularexpressions
^quicksubstitutioncharacter
{expansion
{inashellfunction
|bitwiseoperator
|Booleanoperator
|infullregularexpressions
|pipe2nd3rd
||Booleanoperator2nd3rd4th5th
}expansion
}inashellfunction
~(tilde)expansion2nd3rd
~homedirectory[SeealsoHomedirectory.]
~inpathnames
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
aBooleanoperator
afilenameextension2nd
a.outfile
Abortexecution
Absolutepathname2nd3rd4th
acceptutility
Access
AccessControlList[SeeACL.]
accessfile
Accesspermission2nd3rd
changeusingchmod
defined
directory
displayusingls
execute2nd
group
other
owner
read
write
access.conffile
Accessibility
Account,FTP
acctonutility
ACL2nd3rd4th
accessrules
defaultrules
effectiverightsmask
enabling
acpiddaemon
ActiveViewIndicator,Konqueror
Activewindow2nd
Add
device
softwarepackage2nd
user2nd
addcommand(cvs)
addbannershellscript
Address
IP
class
representation
MAC2nd
mask2nd
network2nd
space,private2nd
adduserutility
adfsfilesystem
Administrator,system[SeeSystem,administrator.]
AdvancedEncryptionStandard[SeeAES
encryption.]
AESencryption
affsfilesystem
AIDEutility2nd3rd
AIM
AlertNotificationTool
Algorithm
Alias
bash
doubleversussinglequotationmarks
email
quotationmarks
recursion
recursiveplunge
singleversusdoublequotationmarks
aliasbuiltin
aliasesfile2nd3rd4th
Alphanumericcharacter
amandautility
Ambiguousfilereference2nd
AmericanNationalStandardsInstitute
Anaconda2nd
anaconda-ks.cfgfile
anacronutility
anacrontabfile
ANDbitwiseoperator2nd
ANDBooleanoperator2nd
Andreessen,Marc
Anglebracket
ANI
Animate
AnonymousFTP2nd
ANSI
ANSIC
ansiterminalname
Answerstoquestions,finding
Antialiasing2nd
Apache
.htaccesscontext
.htaccessfile2nd
.htpasswdfile
<Directory>container2nd
<Files>container
<IfModule>container2nd
<Limit>container
<LimitExcept>container
<Location>container
<LocationMatch>container
<VirtualHost>container2nd
AddHandlerdirective
Aliasdirective
Allowdirective
AllowOverridedirective
authenticationmodules
CGI2nd
CommonGatewayInterface[SeeApache,CGI.]
configurationdirectives[SeeApache,directives.]
containers
content2nd3rd
contexts
Denydirective
directives
controlcontent
controlprocesses
security
directorycontext
directorylistings
DirectoryIndexdirective2nd
documentroot
DocumentRootdirective2nd
DSO2nd
dynamicsharedobjects2nd
errorcodes
ErrorDocumentdirective
ErrorLogdirective
files,wheretofind
filesystemlayout
groupapache
Groupdirective
HostnameLookupsdirective
httpddaemonand
httpddirectory
httpd.conffile2nd3rd
HTTPSprotocol
Includedirective2nd
index.htmfile
index.htmlfile
index.phpfile
index.shtmlfile
indexing
IndexOptionsdirective
JumpStart
Apache,gettingupandrunning
Apache,settingupwithsystem-config-httpd
Listendirective2nd
LoadModuledirective2nd
log
LogLeveldirective
logresolveutility
MaxClientsdirective
MaxRequestsPerChilddirective
MaxSpareServersdirective
MinSpareServersdirective
mod_perlmodule
mod_pythonmodule
mod_sslmodule
modules2nd
moreinformation
MRTG
multiviews
Optionsdirective
Orderdirective
pathname
Perl
PHP
prerequisites
privilegedport
process,defined
public_htmldirectory
Python
RedHattestpage
redirect
rootpermission
ScriptAliasdirective
scriptingmodules
self-signedcertificate
serverconfigcontext
server,defined
ServerAdmindirective2nd3rd
ServerNamedirective2nd3rd
ServerRootdirective2nd
ServerSignaturedirective
ServerTokensdirective2nd
SoftwareFoundation
specialdirectives[SeeApache,containers.]
SSL
StartServersdirective
system-config-httpdutility
terminology
testpage,RedHat
Testing
Timeoutdirective
troubleshooting
UseCanonicalNamedirective2nd
Userdirective
UserDirdirective
Userspublishingcontent
virtualhostcontext
virtualhosts
webalizerutility
wwwdirectory
API
apmutility
apmddaemon
Append
standardoutput2nd
Applet2nd
AppleTalk
Application
programmer
XWindowSystem
aproposutility2nd3rd4th
Archive
library,using
packusingtar
shell
unpackusingtar
Argument2nd3rd
commandline
display
testing
Arithmetic
bash
expansion
expression
Arithmeticevaluation
example2nd3rd
Array
ASCII
terminal
asciifile
ASP
aspellutility2nd
Assemblylanguage2nd
Asteriskspecialcharacter
Asymmetricencryption[SeePublickeyencryption.]
Asynchronouscommunication
Asynchronousevent
atutility2nd3rd
AT&TBellLaboratories2nd
at.allowfile
at.denyfile
atddaemon
Athena,Project
ATMlink
Attachment
authconfigutility
Authenticatedrelaying,email
Authentication
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
Blanguage
Backdoor
Backtick2nd
Background
commandgrouping
defined
desktop
foreground,versus
jobcontrol2nd
PIDstoredin$!
process2nd
runningacommandin
symbol(&)
BACKSLASHescapecharacter2nd3rd
BACKSLASHinreplacementstrings
BACKSPACEkey
Backup
activefilesystem
amanda
cpioutility
dumplevel
failingtoperform
file2nd
full
incremental
media
offsite
policy
simple
tarutility
utilities
badtabs.cprogram
Basename2nd
basenameutility2nd3rd
bash
xoption
<&duplicateinputfiledescriptor
>&duplicateoutputfiledescriptor
alias
arguments
arithmeticevaluation
example2nd3rd
operators
arithmeticexpansion
operators
arrayvariables
attribute
array
export
function
integer2nd
readonly2nd
background
builtin
exec
getopts
typeset
closefile
command
process
substitution
commandline,orderofexpansion
conditionalexpression
example2nd
controlstructure[SeeControl,structure,shell
scripts.]
directorystackmanipulation
editingpreviouscommands2nd
emacscommandlineeditor
eventnumber
expandnullvariable
expandunsetvariable
expression
features
filedescriptor
globbing
historymechanism2nd
makepathshellscript
menu
openfile
operator
bitwise
remainder
short-circuiting
ternary
options[Seebash,features.]
overlay
pathnamecompletion
processsubstitution
programstructures
programming
prompt
PS3prompt
quicksubstitution
quizshellscript
quotationmarkremoval
recursion
redirectionoperators
reexecutingevents2nd
REPLYkeywordvariable
signalnames2nd
specialcharacters
standarderror[SeeStandard,error.]
standardinput[SeeStandard,input.]
standardoutput[SeeStandard,output.]
startupfiles
stringpatternmatching
substitution,quick
symboliclink
ternaryoperator
tildesubstitution
variable[SeealsoVariable.]
array
assigndefaultvalue
BASH_ENV
COLUMNS
displayerrormessage
expansion
LINES
modifier
OPTARG
OPTIND
PS3
REPLY2nd
substitutedefaultvalue
vicommandlineeditor
vimcommandlineeditor
BASH_ENVvariable
bashrcfile
Baud
Baudrate
BCPLlanguage
beagleutility
beagleddaemon
BellLaboratories[SeeAT&TBellLaboratories.]
Berkeley
InternetNameDomain[SeeDNS.]
UNIX2nd3rd
Berners-Lee,Tim
bgbuiltin2nd3rd
bindirectory
Binaryfile
Binaryfiles,fixingbroken
BIND[SeealsoDNS.]
bindbuiltin
Binding,key
BIOS
bootfromCD
security
setup
birthdayshellscript
bisonutility
Bit
bucket2nd
depth
Bit-mappeddisplay
BitTorrent
howitworks
obtainFedoraISOimages
peer
prerequisites
seed
torrent
tracker
using
Bitwiseoperator
&2nd
^
AND2nd
|
Blankcharacter2nd3rd4th
Block
device2nd
number
specialfile
Blockingfactor
Blowfishencryption
bmpfilenameextension
Bookmark
Konqueror
toolbar,Konqueror
Boolean
Booleanoperator
!2nd3rd
&&2nd3rd4th5th6th
a2nd
o
NOT
|
||2nd3rd4th5th
Boot
bootstrap
Linux
loader
loader,grub
netboot
options,kernel
reconfigure
system
bootpartition2nd3rd
Bootstrap
Bottleneck,network
BourneShell(original)[SeealsoshShell.]
Bourne,Steve2nd
Brace
aroundavariable
expansion
shellfunctions
Bracket
characterclass
filenameexpansion
Branch
breakcontrolstructure2nd
Bridge,network
Bringingthesystemdown
Broadcast
about
address
network2nd
packet
unicast,versus
Browser
defined
Firefox
Konqueror
Lynx(textonly)
Mosaic
Mozilla2nd3rd4th5th
BSD[SeeBerkeley,UNIX.]
Buffer
disk
primary
selection
Bug
BugSplat
Bugtraq
Bugzilla
defecttrackingsystem
defined
system
Builtin2nd3rd4th
.(dot)2nd3rd
:(null)2nd3rd
[[...]]
alias
bash,listof
bg2nd3rd
bind
cd2nd3rd4th5th6th
command
commandeditingusingfc
declare2nd
dirs
echo2nd3rd4th5th6th7th8th
eval2nd
exec2nd3rd4th
executionof
exit2nd3rd4th
export2nd3rd4th5th
fc
fg2nd3rd
getopts2nd
history2nd
jobs2nd3rd4th5th
kill2nd3rd4th5th6th7th8th9th10th11th
let2nd
locale
null2nd
popd
pushd
pwd2nd3rd
read2nd3rd4th5th6th
readonly2nd3rd4th
set2nd3rd4th5th6th7th
shift2nd3rd
source
test2nd3rd4th5th6th7th8th
times
tput
trap2nd3rd
type2nd
typeset
ulimit
umask2nd
unalias2nd
unset2nd3rd
utility,versus
wait
bundleshellscript
bunzip2utility2nd
BurninginstallationCDsorDVD
Byte
bz2filenameextension2nd
bzcatutility
bzip2utility2nd3rd
bzip2recoverutility
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
C[SeeCprogramminglanguage.]
Cfilenameextension
cfilenameextension2nd3rd4th
Cprogramminglanguage
#includepreprocessordirective
a.outfile
about2nd
archivedlibrary
assembler
badtabs.cprogram
comments
compiler
phase
using
warningoptions
debugging
functionprototype
functions
getcharfunction
headerfile2nd
includefile2nd
library
getpwnam()function
getpwuid()function
libc.so
libm.so
libwrap.a2nd
linkeditor
macroexpansion
mainfunction
objectfile2nd
optimizer
portability
preprocessor2nd
preprocessordirectives
programming
putcharfunction
sampleprogram
sharedlibrary
staticallylinkedlibrary
stdio.hheaderfile
symbolicdebugger
tabs.cprogram
c++filenameextension
C++programminglanguage
C89programminglanguage
Cable
10Base2
10BaseT
Category5
Category5e
Category62nd
Category7
coaxial
fiberoptic
glass
modem
thicknet
thinnet
twistedpair
unshieldedtwistedpair
UTP
Cache
Cache,DNS[SeeDNS,cache.]
Caching-onlyserver[SeeDNS,cache.]
Callbyvalue
CallerID
Callingenvironment
Callingprogram,nameof
cancelutility
Caretinregularexpressions
Cascadingwindows
casecontrolstructure
Case-sensitive
domainname,not
filename
password
catutility2nd3rd4th5th6th
Category5cable
Category5ecable
Category6cable2nd
Category7cable
Catenate2nd3rd
ccfilenameextension
CD
download,burn,andinstallRedHatLinux
ISOimage
rescue
cdbuiltin2nd3rd4th5th6th
CDPATHvariable
CERN
CERT2nd
CGI
Chainloading
Change
accesspermissionusingchmod
directoriesusingcd
filenameusingmv
passwordusingpasswd
Character
alphanumeric
class2nd
device2nd
escaping
list[SeeCharacter,class.]
quoting
specialfile
typeface
Character-based
terminal
checkoutcommand(cvs)2nd
Checksum
Child
directory2nd
process2nd3rd
chkargsshellscript2nd
chkconfigutility
chkrootkitutility
chmodutility2nd
chmod()systemcall
chown()systemcall
chrootjail
BIND
DNS
FTP
nameddaemon
runningaservicein
securityconsiderations
settingup
using
vsftpd
chroot_listfile(vsftpd)
chshutility
CIDR2nd
CIFS
CIPE
Cipher
Ciphertext2nd
Clark,Jim
Class
character
IPaddress
ClasslessInter-DomainRouting[SeeCIDR.]
Clearscreen
clearutility
Cleartext
CLI
Clickexplained
Click-to-focus
CLID
Client
specifying
Client/servermodel2nd3rd4th5th6th7th8th
Clipboard,KDE
Clipboard,XWindowSystem
Closefiles,bash
close()systemcall
CMOSsetup
Coaxialcable
codafilesystem
Code,reentrant
CODEC
Collatingsequence,machine
Colon(:)builtin
Color
depth
quality
window
GNOME
KDE
COLUMNSvariable
Combobox
Comer,Doug
Command2nd
;separator
argument
builtin2nd3rd
completion
controlflow[SeeControl,structure,shellscripts.]
controlstructure[SeeControl,structure,shell
scripts.]
editingprevious
executionof
export
grouping2nd
interpreter
mode,vim
name
NEWLINEseparator
option
process
reexecutingprevious
repeating
runremotely,ssh
separation
separator2nd
substitution2nd3rd4th
summary
syntax
terminator
usagemessage2nd3rd
Commandline2nd
argument2nd
editing
execution
expansion2nd
interface
option
parse2nd
processing2nd
syntax
token2nd
whitespace
word2nd
command_menushellscript
Comments
Cprograms
makefile
shellscripts
commitcommand(cvs)
CommonUNIXPrintingSystem[SeeCUPS,about.]
Communication
interprocess2nd
network
write
comp.lang.cnewsgroup
comp.os.linux.announcenewsgroup
comp.os.linux.answersnewsgroup2nd
comp.os.linux.miscnewsgroup2nd3rd4th
comp.os.linux.networkingnewsgroup
comp.os.linux.securitynewsgroup
comp.os.linux.setupnewsgroup
comp.security.firewallsnewsgroup
Comparefilesusingdiff
CompilingaCprogram
Completion
command
pathname
ReadlineLibrary
variable
Componentarchitecture
Components,KDE
Compress
bunzip2
bzip22nd3rd
bzip2recover
compress2nd
gzip
OpenSSH
uncompress
unzip
zip
compressutility2nd
ComputerSystemsResearchGroup
Computer,diskless
Computing,distributed2nd
Concatenate[SeeCatenate.]
ConcurrentVersionsSystem[Seecvscommand,
log.]
Conditioncode[SeeExit,status.]
Conditionalexpression
example2nd
conffilenameextension
configfile2nd
configsdirectory
Configure
andBuildSystem
daemon
desktopwindow
monitor
Panelwindow
videocard
configureshellscript
Connection-orientedprotocol2nd
Connectionless,protocol
Console
single-usermode
system
terminal
virtual2nd
consolehelperutility2nd
Content,Apache
Contextmenu
continuecontrolstructure2nd
Control
bar,Nautilus
Center,KDE
character
characters,printer
flow[SeeControl,structure,shellscripts.]
job
structure2nd
break2nd
case
continue2nd
do2nd3rd4th
done2nd3rd4th
elif
elifversusfi
else
esac
fi2nd3rd
fiversuselif
for2nd3rd
for...in2nd
if2nd3rd
if...then
if...then...elif
if...then...else
in
select
shellscripts
then2nd3rd
two-waybranch
until
while2nd3rd
CONTROLkey
CONTROL-Ckey2nd
CONTROL-Dkey2nd3rd
CONTROL-Hkey2nd3rd4th
CONTROL-Lkey2nd
CONTROL-Mkey
CONTROL-Qkey
CONTROL-Rkey
CONTROL-Ukey2nd3rd4th
CONTROL-Vkey2nd
CONTROL-Wkey2nd3rd
CONTROL-Xkey2nd
CONTROL-Zkey2nd
Conventions
book,usedinthis
endlinekey
filenaming
Convertfileto/fromWindowsformat
Cookie
CoordinatedUniversalTime[SeeUTC.]
Copy
buffer
directoryrecursivelyusingmv
directory,shellscript
fileusingcp2nd
Copyleft
Core
dump
memory
corefile2nd3rd
Correcttypingmistakes
countshellscript
cputility2nd3rd
cpversusln
cpdirshellscript
cpioutility2nd
cppfilenameextension
CPU
intensiveprocesses,report
crackutility
Cracker
Crash2nd
Crashflag
creat()systemcall
Create
directoryusingmkdir
fileusingvim
file,null
Creationdate,file,displayusingls
crondirectory
cron.*directories
cron.allowfile
cron.ddirectory
cron.denyfile
cronddaemon2nd
crontabfile
crontabutility2nd
Cryptography[SeealsoEncryption.]
csh
CSRG
CSS2nd
CUPS
about
addingaprinter
commandlineinterface
configuringprinters
JumpStart
configuringaremoteprinter
system-config-printer,configuringalocalprinter
KDEprintingmanager
lpadminutility
lpinfoutility
modifyingaprinter
moreinformation
PPDfiles
prerequisites
printqueue
printingfromWindows
printingquotas
printingtoWindows
sharingprinters
Webinterface
winprinter
cupsdirectory
cupsd.conffile
Current
Currentdirectory[SeeWorkingdirectory.]
Cursor
custom.conffile2nd
Customizethedesktop
Cutandpaste
cututility
cvscommand
add
checkout2nd
commit
export
import
log
release
remove
rtag
update
cvsutility
CVSROOTvariable
cxxfilenameextension
Cycling,window
Cypher
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
Daemon
acpid
apmd
atd
automount2nd3rd
beagled
configure
crond2nd
dhcpcd
dhcpd2nd3rd
ftpd
gated
gateway
gpm
httpd
imap-login
imapd[SeeDaemon,imap-login.]
in.fingerd2nd
inetd
ipop3d[SeeDaemon,pop3-login.]
lockd
lpd2nd
messages2nd3rd4th
mountd2nd
name
named2nd3rd
network2nd
nfsd2nd
nmbd2nd3rd4th
ntpd
pop3-login
portmap2nd3rd
postfix
pppd
prefix
in.
rpc.
printer2nd
procmail
protocol
rexecd
rhnsd
rlogind
routed
routing
rquotad
rshd
sendmail2nd3rd4th5th6th7th
services,providing
smbd2nd3rd
spamd2nd
sshd2nd3rd
statd
Superserver[Seexinetddaemon.]
syslogd2nd3rd4th5th
talkd
telnetd2nd
tftpd
timed
xinetd2nd3rd4th5th
ypbind
ypbind-mt
yppasswdd
ypxfrd
Data
EncryptionStandard[SeeDESencryption.]
sink
structure
Database
authentication
dbm
DNS
gdbm
group
hardware
hosts
hwconf
initializing
LinuxSoftwareMap
locate2nd
magicnumber
ndbm
NIS2nd3rd4th
passwd2nd3rd4th
printcap
RHN
rpm
searchengine
services
SQL
systemservices
terminfo
whatis2nd
Datagram,network2nd
Datalesssystem2nd
dateutility2nd
Date,display
dbfilenameextension2nd
dbmdatabase
dddutility2nd
DDoSattack
Debug
Debugger
ddd
graphicalsymbolic
option
shellscript
symbolic
ups
xxgdb
declarebuiltin2nd
Decorations,window
Decrementoperator
Default
defaultrouterfile
Defecttrackingsystem
Delete
directoryusingrmdir
fileusingrm
key
line
linkusingrm
word
Deletekey
Delimiter,regularexpression
Delta,SCCS
Demandmounting,filesystem
DenialofService[SeeDOS,convertfiles;and;
DDoSattack.]
Dependencyline(make)
depmodutility
Dereference
DESencryption
Descriptor,file
Descriptor,file,duplicate
Design,top-down
Desktop
appearance
background
changing
configure,window
customize
hovering
Iconcontextmenu
icons
KDE,defined
launchingapplications
Mainmenu
manage
manager,choosing
menu
Desktop
Iconcontext
Main
panel
PanelIconmenu
Panelmenu
Post-itnotes
switching
theme2nd
toolbar2nd
tooltips
window,defined
Detachedprocess[SeeBackground,process.]
devdirectory2nd3rd
devfsfilesystem
Device
block2nd
character2nd
driver2nd3rd4th
file2nd
file,export
filename
independence
independentinputandoutput
name
names,dynamic(udev)
nonrewinding
null
number
major2nd
minor2nd
physical
raw
tape
tape,nonrewinding
devptsfilesystem
dfutility
dhclientutility
dhclient.conffile
dhclient.leasesfile
DHCP2nd
client
howitworks
MACaddresses
moreinformation
prerequisites,client
prerequisites,server
protocol
resolv.conffile,and
server
staticIPaddresses
dhcpcddaemon
dhcpddaemon2nd3rd
dhcpd.conffile
Die,process
diffutility2nd
Diffie-Hellmanencryption
digutility2nd3rd4th
Digital
signature
SignatureAlgorithm[SeeDSA.]
Directory2nd3rd4th5th6th
.2nd
..2nd
.ssh
/(root)2nd3rd
/bin
/boot2nd3rd
/dev2nd3rd4th
specialfiles
/etc
cron.*
cron.d
cups
httpd
logrotate.d
mail2nd
opt
pam.d2nd3rd4th
rc.d
rc.d:about
rc.d:init.d2nd
rc.d:rcn.d
skel
ssh
sysconfig
X112nd
X11:about
X11:XFConfig
X11:xorg.conf
xinetd.d2nd
yum.repos.d2nd
/home2nd
/lib
gcc,and
modules2nd
security2nd
/lost+found
/mnt
/opt2nd3rd
/proc
/root
/sbin
Superusercommands
/sys
/tmp2nd3rd
/usr2nd
bin
doc2nd
games
include
info
lib
lib:gcc,and
lib:linking,and
lib:shared
lib:terminfo
local
man
sbin2nd
share
src2nd
/var2nd
ftp
log2nd3rd4th5th
mail
named2nd
spool:diskusage
spool:problemsolving
tmp
www:Apachefiles
www:html2nd3rd
accesspermission
bin2nd
boot2nd3rd
changeusingcd
child2nd
compact
configs
copyrecursivelyusingmv
copy,shellscript
createusingmkdir
cron
cron.*
cron.d
cups
current[SeeDirectory,working,changeusingcd.]
deleteusingrmdir
dev2nd3rd4th
doc2nd
empty
eraseusingrmdir
file2nd
ftp
games
hierarchy
home
home2nd3rd
home
home2nd
versusworking
httpd
important
include2nd
info
init.d
lib2nd3rd4th
link
listusingls
listing
local2nd
log2nd3rd4th5th
logrotate.d
mail2nd3rd4th
makeusingmkdir
man
modules2nd
moveusingmv
named2nd
opt2nd3rd
pam.d2nd3rd4th
parent2nd
pathname2nd
proc
public_html
rc.d
init.d2nd
maintain
rcn.d
removeunusedspace
removeusingrmdir
renameusingmv
root2nd3rd4th
sbin2nd3rd4th
security2nd
service
share
skel
spool
diskusage
problemsolving
src2nd
ssh
stackmanipulation
standard
sysconfig
terminfo
tmp2nd
usr
var
working
changeusingcd
defined
home,versus
relativepathnames
significanceof
with
www
X112nd
xinetd.d2nd
yum.repos.d2nd
~(home)[SeeHomedirectory.]
dirsbuiltin
disableutility
Disk
buffer
capacityplanning
Druid
extendedpartition
filesystem
formatting
fragmentation
freespace2nd
logicalpartition
partition2nd
partitiontable
partition,primaryandsecondary
primarypartition
quotasystem
usage
Volumelabel2nd
Diskette,floppy[SeeFloppydiskette,mount.]
Diskless
system
Display
dateusingdate
endofafileusingtail
fileusingcat
graphical
hiddenfilename
machinename
orderedfileusingsort
resolution,changing
sortedfileusingsort
systemloadusingw
textusingecho
topofafileusinghead
uptimeusingw
userlist
usingfinger
usingw
usingwho
DISPLAYvariable
Distributedcomputing2nd3rd
Distribution,Linux
dmesgutility2nd3rd
DMZ
DNS
$INCLUDE
$ORIGIN
$TTL
A(address)record
AAAA(address)record,IPv6
about2nd
authority
cache2nd3rd
caching-onlyserver[SeeDNS,cache.]
chrootjail
CNAMErecord
database2nd
delegation
digutility2nd3rd4th
domain
defined
qualification
root
FQDN
full-functionednameserver
glue2nd
hintszone
hostutility2nd
howitworks
in-addr.arpadomain
inversemapping[SeeDNS,reversename
resolution.]
ip6.arpadomain
iterativequery
JumpStart
settingupaDNScache
settingupadomainwithsystem-config-bind
log2nd3rd
masterserver
moreinformation
MXrecord2nd
nameddaemon2nd3rd
nameddirectory
named.cafile
named.conffile2nd3rd
nameserver,full-functioned
node[SeeDNS,domain,defined.]
NSrecord
nsswitch.conffile
origin[SeeDNS,zone,name.]
overview
prerequisites
primarymasterserver
PTRrecord
query2nd
recursivequery
resolver
resourcerecord
response
reversemapping[SeeDNS,reversename
resolution.]
reversenameresolution
rndcutility
rootdomain2nd
rootzone
secondaryserver
security
server
caching
master
primarymaster
secondary
slave2nd
splithorizon
typesof
settingup
slaveserver2nd
SOArecord
splithorizonserver
subdomain
system-config-bindutility
timeformat
transactionssignatures[SeeDNS,TSIG.]
troubleshooting
TSIG2nd
TTLvalue
TXTrecord
zone
file2nd
hint
name2nd
root
section,named.conf
docontrolstructure2nd3rd4th
docdirectory2nd
DocumentObjectModel[SeeDOM.]
Documentroot,Apache
Documentation
finding
online
system2nd
Dollarsign
regularexpression,in
variables,usewith
DOM
Domain[SeealsoDNS.]
DNS,defined
in-addr.arpa
ip6.arpa
name2nd
NameService[SeeDNS.]
name,notcase-sensitive
NIS
root
donecontrolstructure2nd3rd4th
Door
DOS
convertfiles
filename
filenameextension
filesystem,mounting
mountingfilesystems
DoSattack
dos2unixutility2nd
Doubleversussinglequotationmarks
dovecotself-signedcertificate
dovecot.conffile
DPMS
Drag
DragonSquireutility
Driver,device2nd
Druid
DSA2nd
DSL2nd
dsniffutility
DSO,Apache
Dualmonitors,specifying
Dual-bootsystem
Dumplevel
dumputility
dumpdatesfile2nd
Duplicatelines,gettingridofusinguniq
Dynamic
devicenames(udev)
HostConfigurationProtocol[SeeDHCP.]
IPaddress
library[SeeShared,library,using.]
sharedobjects,Apache
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
e2labelutility
echobuiltin2nd3rd4th5th6th7th8th
ededitor
Editor
commandline
ed
ex
ReadlineLibrary
vim
edquotautility
Edwards,Dan
EEPROM
EffectiveuserID
egreputility
El-Gamalencryption
Electronicmessage,write
Element
elifcontrolstructure
elsecontrolstructure
emacsmail
Email[SeeMail,networkaddresses.]
Emblems,file,Nautilus
Emoticon
Emptyregularexpression
Emulator
operatingsystem
terminal
enableutility
Encryption
3-DES
AES
algorithm
asymmetric[SeeEncryption,publickey.]
Blowfish
DES
Diffie-Hellman
digitalsignature
DSA
El-Gamal
GnuPG
hostkey
IDEA
implementation
key
man-in-the-middle2nd3rd
MD5
OpenSSH
PEM
PGP
privatekey
publickey
RC5
ringoftrust
RSA2nd
scheme,weaknessesof
secretkey
sessionkey
symmetrickey
Endlinekey
Endoffile[SeeEOF.]
Enquireprogram
Entertextusingvim
Enter-onlyfocus
ENVvariable
Environment
calling
establish
exec
export2nd3rd
variable
EOF2nd3rd
EPROM
Erasekey2nd3rd4th5th
Erasewordkey
Errata
Error
codes,Apache
correcting
message
cannotexecute
conditional
nameofcallingscript
NFSserverxxxnotresponding
notfound
redirectingtostandarderror
standarderror[SeeStandard,error.]
system
usage2nd3rd
shellscript
standard[SeeStandard,error.]
usagemessage2nd3rd
esaccontrolstructure
Escapeacharacter2nd
Escapeanendofline
etherealutility
Ethernetnetwork2nd3rd4th5th
Eumlation,terminal
evalbuiltin2nd
Event
asynchronous
history
modifyingprevious
number2nd
reexecuting
text
wordswithin
XWindowSystem
Evolutionutility2nd
exeditor
Exabyte
Exclamationpoint
execbuiltin2nd3rd4th
exec()systemcall2nd
Execute
access2nd3rd
command2nd
permission
shellscript
Exit
shell,froma
status2nd
exitbuiltin2nd3rd4th
exit()systemcall
Expansion
arithmetic
brace2nd
commandline
filename
macro
nullvariable
orderof2nd
parameter
pathname2nd3rd4th
quotationmarks,double
tilde2nd
unsetvariable
variable
Explicitfocus
Exploit
Export
devicefile
link
variable
exportbuiltin2nd3rd4th5th
exportcommand(cvs)
exportfsutility2nd
exportsfile2nd3rd
Expression
arithmetic
logical
ext2filesystem2nd
ext3filesystem2nd
Extendedmultiusermode
Extendedpartition
Extendedregularexpression
ExtensibleMarkupLanguage[SeeXML.]
Extension,filename[SeeFilename.]
Extratoolbar,Konqueror
Extranet2nd
EXTRAVERSIONnumber,kernel
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
ffilenameextension
Fahlman,Scott
Failsafesession
Failsafeterminal
falsefile
Familytree
fcbuiltin
FCEDITvariable
FDDInetwork
fdformatutility
fdisk[Seepartedutility.]
Features,bash[Seebash,features.]
FedoraCore
BitTorrent,downloadingwith
CDsandDVD2nd3rd
CoreversusRedHatEnterpriseLinux
desktop,initial
DVD
errata
Firstboot
installing
ISOfiles,testing
mirrorsites
RedHatEnterpriseLinux,versus
rescueCD
SELinux
updates2nd
Website
X.org
fgbuiltin2nd3rd
FHS2nd3rd
ficontrolstructure2nd3rd
FiberDistributedDataInterface[SeeFDDInetwork.]
Fiberopticcable
FIFOspecialfile2nd3rd
File
.autofsck
.bash_history
.bash_login
.bash_logout
.bash_profile2nd3rd
.bashrc2nd3rd
.config
.cshrc
.forward2nd
.htaccess2nd
.htpasswd
.inputrc
.login
.logout
.netrc
.pgpkey
.plan
.profile2nd3rd
.project
.rhosts2nd
.toprc
.torrent
/bin/false
/boot/grub/grub.conf2nd
/dev
nst0
null2nd3rd4th5th6th
pts
random
rmt/0
st0
tty
urandom
zero
/etc
aliases2nd3rd
anacrontab
at.allow
at.deny
auto_master
bashrc
cron.allow
cron.deny
crontab
defaultrouter
dhclient.conf
dhcpd.conf
dovecot.conf
dumpdates2nd
exports2nd3rd
fstab2nd3rd4th5th
group2nd3rd
grub.conf2nd
hosts2nd3rd4th5th
hosts.allow2nd3rd
hosts.deny2nd3rd
hosts.equiv2nd
inittab2nd3rd4th5th
issue2nd
login.defs2nd
logrotate.conf
motd2nd3rd4th5th
mtab
named.conf2nd3rd
netgroup
nologin.txt2nd
nsswitch.conf2nd3rd4th5th6th
ntp.conf
pam.conf
pam.d
passwd2nd3rd4th5th6th7th8th
printcap
profile2nd3rd4th
protocols2nd
rc.d:init.d
rc.d:init.d/kudzu
rc.d:rc
rc.d:rc.local
rc.d:rc.sysinit2nd
resolv.conf2nd3rd
rndc.conf
rndc.key
rpc2nd
securetty
security/access.conf
selinux/config
services2nd3rd
shadow2nd
share/magic
shells
sudoers
sysconfig:httpd2nd
sysconfig:hwconf
sysconfig:iptables2nd3rd
sysconfig:iptables-config
sysconfig:named2nd
sysconfig:network2nd
sysconfig:rhn/up2date
sysconfig:selinux
sysconfig:syslog
sysconfig:yppasswdd
sysctl.conf
syslog.conf2nd
termcap
vsftpd:chroot_list
vsftpd:ftpusers
vsftpd:user_list
X11/xorg
xinetd.conf2nd
yp.conf
ypserv.conf
yum.conf
/proc
fs/nfs
mounts
sys
/root
anaconda-ks.cfg
install.log
/usr
include
local
pub/ascii
sbin
share/magic
/var
lib/nfs/xtab2nd
log:lastlog
log:maillog
log:messages2nd3rd4th5th6th7th8th
log:secure2nd3rd
log:vsftpd.log
log:wtmp2nd
spool/mqueue
a.out
access
accesspermission2nd
access.conf
aliases2nd3rd4th
ambiguousreference
anaconda-ks.cfg
anacrontab
archiveusingtar
ascii
at.allow
at.deny
authorized_keys
auto_master
backup2nd
bashrc2nd
binary,fixingbroken
blockspecial
characterspecial
close(bash)
config2nd
configuration,rules
copyusingcp
core2nd3rd
createusingcat
creationdate,displayusingls
cron.allow
cron.deny
crontab
cupsd.conf
custom.conf2nd
defaultrouter
defined
descriptor2nd
duplicate
device2nd3rd
dhclient.conf
dhclient.leases
dhcpd.conf
directory2nd
directoryvs.ordinary
display
beginningofusinghead
endofusingtail
usingcat
dovecot.conf
dumpdates2nd
empty,creatingan
executepermission
exports2nd3rd
false
FIFOspecial2nd3rd
forcefsck
fstab2nd3rd4th5th
ftpusers(vsftpd)
group2nd3rd
groupassignment
group,displayusingls
growing
grub.conf2nd
header2nd
hierarchicalstructure
hosts2nd3rd4th5th
hosts.allow2nd3rd
hosts.deny2nd3rd
hosts.equiv2nd
html2nd3rd
httpd2nd
httpd.conf2nd3rd
hwconf
identifyingusingfile
important
include
index.htm
index.html
index.php
index.shtml
inittab2nd3rd4th5th
install.log
iptables2nd3rd
iptables-config
issue2nd
kdmrc
known_hosts2nd3rd
ks.cfg
large,rotate
lastlog
link
linux-gate.so.1
list
log2nd3rd
login.defs2nd
logrotate.conf
magic2nd
mailertable
maillog2nd
Makefile2nd3rd
makefile2nd
manager
Konqueror2nd
Nautilus
MD5SUM
messageoftheday[Seemotdfile.]
messages2nd3rd4th5th6th7th8th
motd2nd3rd4th5th
mounts
moveusingmv
mqueue
mtab
name[SeeFilename.]
named2nd
namedpipe2nd3rd
named.conf2nd3rd
netgroup
network2nd
nfs
nicknames
nologin.txt2nd
nsswitch.conf2nd3rd4th5th6th
nst0
ntp.conf
null2nd3rd4th5th6th
object2nd
openusingNautilus
open,bash
open,finding
orderusingsort
ordinary2nd
ordinaryvs.directory
owner
displayusingls
packarchiveusingtar
pam.conf
pam.d
passwd2nd3rd4th5th6th7th8th
pathname2nd
permission2nd3rd
permissions,Nautilus
pointerto
PPD
printcap
profile2nd3rd4th
properties,Nautilus
protocols2nd
pts
random
rc
rc.d/init.d/kudzu
rc.local
rc.sysinit2nd
reference,ambiguous2nd
removeusingrm
renameusingmv
resolv.conf2nd3rd
rmt/0
rndc.conf
rndc.key
rotate2nd
rpc2nd
secure2nd3rd
securenets
securetty
security
selinux
sendmail.cf
sendmail.mc2nd
services2nd3rd
SHA1SUM
shadow2nd
shells
size,displayusingls
smb.conf
smbpasswd
smbusers
sortusingsort
sparse
special2nd3rd4th
ssh_config
ssh_known_hosts2nd3rd
sshd_config
st0
standard
startup2nd3rd4th5th
stdio.hCheader
structure
sudoers
symboliclink
sys
sysconfig
hwconf
rhn/up2date
sysctl.conf
syslog
syslog.conf2nd
tar
temporary,nameof
termcap
terminal
text
truncate2nd
tty
typeof,discoverusingls
types,GNOME
typescript
UNIXdomainsocket
urandom
user_list(vsftpd)
virtusertable2nd
vsftpd
chroot_list
ftpusers
user_list
vsftpd.conf
vsftpd.log
window
wtmp2nd
xinetd.conf2nd
xorg
xtab2nd
yp.conf
yppasswdd
ypserv.conf
yum.conf
zero
fileutility2nd3rd
Filename2nd3rd
/
absolute
ambiguousreference[SeeFile,ambiguous
reference.]
basename2nd
case
case-sensitive
changeusingmv
charactersin
choiceof
completion
conventions
defined
device
DOS
extension2nd
a2nd
bmp
bz22nd
C
c2nd3rd4th
c++
cc
conf
cpp
cxx
db2nd
DOS
f
gif
gz2nd
h2nd
htm
html2nd
jpeg2nd
jpg2nd
l
listof
m
MIMEand2nd
o2nd3rd4th
pdf
php
ppd
ps
removea
repo
rpmnew
s2nd
sh
sharedobject
shtml
so2nd
tar.bz2
tar.gz
tar.Z2nd
tbz
tgz
tif2nd
tiff2nd
torrent
txt2nd
tz
var
y
Z2nd
generation2nd3rd
hidden2nd3rd
length2nd3rd4th
period,leading
quoting
reference,ambiguous[SeeFile,ambiguous
reference.]
rootdirectory
simple2nd3rd4th
temporaryfile
typeface
unique2nd
Windows
Fileserver2nd
Filesystem
/proc2nd
active
adfs
affs
autofs2nd
checkintegrityof
coda
copydirectoryrecursivelyusingmv
defined
demandmounting
devfs
devpts
disk
ext22nd
ext32nd
filenamelength2nd
freelist2nd
GFS
hfs
HierarchyStandard
HierarchyStandard,Linux
hpfs
independence
iso9660
journaling2nd3rd4th
minix
mount
automatically
demand
point
remote
msdos
ncpfs
NFS2nd3rd
ntfs
organize
proc2nd3rd4th
qnx4
RAID2nd
reiserfs
remote2nd
repair
romfs
root
smbfs
Standard,Linux2nd
structure2nd
swap2nd
sysv
types,listof
ufs
umsdos
use
vfat
virtual
xfs
Filling
Filter2nd3rd
Find
commandnameusingapropos
inodeusingfindutility2nd
stringusinggrep
findutility2nd
fingerutility2nd3rd4th5th
fingerddaemon[Seein.fingerddaemon.]
Firefox,starting
Firewall2nd[Seealsoiptables.]
buildinga
OpenSSH
toolkit
Firmware
Firstboot
Flag,crash
flexutility
Floppydiskette,mount2nd
Focus
desktop
follows-mouse
strictly-under-mouse
under-mouse
window2nd
Folder[SeeDirectory.]
Font
antialiasing2nd
preferences,GNOME
window,GNOME
Footer
forcontrolstructure2nd3rd
for...incontrolstructure2nd
forcefsckfile
Foreground2nd
backgroundversus
process
Fork
child
process
fork()systemcall2nd3rd4th
Formattingaharddisk,low-level
FQDN2nd3rd4th
Fragmentation,disk
Frame,network2nd
Free
list,filesystem2nd
software,definition
space,disk2nd3rd
StandardsGroup
freedesktop.orggroup
Freefire,securitysolutions
fsckutility2nd3rd4th
FSG
FSSTND2nd
fstabfile2nd3rd4th5th
FTP
about
account
active
anonymous
ASCIItransfermode
automaticlogin
basiccommands
binarytransfermode
chrootjail
client
ftputility2nd
JumpStart
downloadingfilesusingftp
startingavsftpdserver
moreinformation
passive2nd
PASVconnection
PORTconnection
prerequisites
pubdirectory
security2nd3rd
server
tutorial
vsftpdserver
vsftpd.conffile
ftpdirectory
ftputility2nd3rd
ftpddaemon
ftpusersfile
Full
backup
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
gaimutility
gamesdirectory
gateddaemon
Gateway
daemon
network
proxy
router,and
gawk2nd
gcc[SeealsoCprogramminglanguage.]
history
homepage
using
warningoptions
gdbutility2nd
gdbmdatabase
gdmutility2nd
gdmsetuputility
GECOS
GECOSandNIS
Generatefilenames
Genericoperatingsystem
getcharCmacro
gethostbyname()systemcall
getoptsbuiltin2nd
getpid()systemcall
getppid()systemcall
GettingstartedusingKonqueror
gettyutility
GFSfilesystem
GIAC,securitycertificationandtraining
giffilenameextension
Giga-
GlobalFilesystem
Globalvariable2nd
Globbing2nd
Glue,DNS
Glyph
GMT
GNOME2nd
colorwindow
controlcenter
custom.conffile2nd
desktop,about
displaymanager[SeeGNOME,display
manager.]
filetypes
focus,window
fontpreferences
fontwindow
gdmutility2nd
gdmsetuputility
gnome-font-propertiesutility
GTK
Helpwindow
KDE,compared2nd
logginginon
Mainmenu
manager,session
menu
Main
PanelIcon
MIMEtypes
Nautilus
controlbars
emblems,file
file:manager
file:permissions
file:properties
locationbar
menubar
openfile
OpenLocationdialogbox
Sidepane
spatialview
toolbar
traditionalview
Viewpane
PanelIconmenu
runprogramwindow
sessionmanager
switchingdesktops
terminalemulator
titlebar
toolbar
windowfocus
WindowList
WorkspaceSwitcher
gnome-control-centerutility
gnome-font-propertiesutility
gnome-terminalutility
GNU
ConfigureandBuildSystem
gcc
compiler2nd
homepage
gdbutility
GeneralPublicLicense
GnuPGencryption
grubutility
manuals
usagemessage
GnuPGencryption
gopherutility
GPG[SeeGnuPGencryption.]
GPL[SeeGNU,GeneralPublicLicense.]
gpmdaemon
gprofutility
GrandUnifiedBootLoader[Seegrubutility.]
Graphicaldisplay
Graveaccent
greputility2nd3rd4th5th6th7th8th
Group
about
access
add
apache
commands2nd
fileassignedto
ID2nd3rd
nameof,displayusingls
password
userprivate
users
wheel
windows
groupdatabase
groupfile2nd3rd
groupaddutility
groupdelutility
groupmodutility
groupsutility
grubutility
grub.conffile2nd
GTK
GUI
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
hfilenameextension2nd
Hacker
Halfduplex
haltutility2nd3rd
Halt,program
Harddisk[SeeDisk,extendedpartition.]
Hardlink2nd
createusingln
removeusingrm
symboliclink,versus
Hardcodedfilenameinshellscripts
Hardware
database
device
help
Hash
one-way
SHA1algorithm
table
headutility
Header
document
file2nd
Help[SeealsoMoreinformation,system
administration.]
answers,finding
aproposutility
Center(KDE)
documentation
errormessages
getting
GNOME
GNUmanuals
hardware
HOWTOs
infopages
Internet,fromthe
KDEHelpCenter
LinuxDocumentationProject2nd
local
manpages
netnews
RedHatWebsite
supportforums
window(GNOME)
Heredocument2nd3rd
Hesiod
Heterogeneous
Heterogeneousnetwork
Hexadecimalnumber
hfsfilesystem
Hiddenfilename
defined
display
notdisplayedwith?
Hierarchicalfilestructure
Hierarchy
HISTFILESIZEvariable
History
CShellmechanism,classic
event
editing
number
previous:!$lastwordof
previous:modifying
reexecuting
text
wordswithin
mechanism
viewing
worddesignator
historybuiltin2nd
HISTSIZEvariable
Homedirectory2nd3rd
.bash_historyfile
.bash_loginfile
.bash_logoutfile
.bash_profilefile2nd
.bashrcfile2nd
.forwardfile2nd
.inputrcfile
.netrc
.profilefile
.rhosts
.ssh
automount
defined
hiddenfile
passwdand
~,shorthandfor
startupfile
workingdirectory,versus
~,shorthandfor
homepartition
HOMEvariable2nd3rd4th
Host
address
key,OpenSSH
security
specifying
trusted
hostutility2nd
Hostname
about
resolution
settingthesystem
symbolic
hostnameutility2nd
hostsdatabase
hostsfile2nd3rd4th5th
hosts.allowfile2nd3rd
hosts.denyfile2nd3rd
hosts.equivfile2nd
Hover2nd
HOWTOdocuments,finding
hpfsfilesystem
hpingutility
htmfilenameextension
HTML
history
suffix
htmlfile2nd3rd
htmlfilenameextension2nd
HTTP2nd
httpddaemon[SeealsoApache.]
httpddirectory
httpdfile2nd
httpd.conffile2nd3rd
HTTPSprotocol2nd
Hub2nd3rd
Humor2nd3rd
hunk(diff)
HUPsignal
hwconfdatabase
hwconffile
Hypermedia
Hypertext2nd
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
I/Odevice[SeeDevice.]
I/Oslave,KDE
IANA2nd
ICMPpacket2nd
icmp_seq
Icon
contextmenu
desktop
moving
Iconify
ICQ
idutility
IDEAencryption
IDS
about
AIDE
DragonSquire
samhain
tripwire
ifcontrolstructure2nd3rd
if...thencontrolstructure
if...then...elifcontrolstructure
if...then...elsecontrolstructure
IFSvariable
Ignoredwindow
IM
IMAP,email
imap-logindaemon
imapddaemon[Seeimap-logindaemon.]
Implieddependency,make
importcommand,cvs
incontrolstructure
in-addr.arpadomain
in.fingerddaemon2nd
Includedirective
includedirectory2nd
Includefile
Incorrectlogin
Incrementoperator
Incrementalbackup
Indentation[SeeIndention.]
Indention
index.htmfile
index.htmlfile
index.phpfile
index.shtmlfile
Indirectpointer
inetddaemon
Infiniterecursion,alias
infodirectory
infoutility
KDEHelpCenter,fromthe
manual
using
Information[SeeMoreinformation,system
administration.]
Initscript2nd
initutility2nd3rd4th5th6th7th
init.ddirectory
inittabfile2nd3rd4th5th
Inode2nd3rd
alteringusingmv
createanotherreferenceusingln
file
filesystem
linksshellscript
number
Input
focus,changing2nd
mode,vim
standard[SeeStandard,input.]
Input/Outputdevice[SeeDevice.]
INPUTRCvariable
insmodutility
install.logfile
Installation,computer
InstallingRedHatLinux[SeeRedHatLinux,
installing,explained.]
Installingsoftware
InstantMessenger
IntegratedServicesDigitalNetwork[SeeISDN.]
Integrity,filesystem
Interactive
Interface
user2nd
InternalFieldSeparator[SeeIFSvariable.]
InternationalOrganizationforStandardization[See
ISO.]
Internet2nd
AssignedNumbersAuthority[SeeIANA.]
browser
connectionsharing
ControlMessageProtocol[SeeProtocol,ICMP.]
lookupauser
mirrorsite
multipleclientsonasingleconnection
multipleserversonasingleconnection
netiquette
netnews[SeeNetnews,historyof.]
network
PrintingProtocol[SeeIPPprotocol.]
Protocol[SeeIP.]
ProtocolSecurity[SeeIPSec.]
RelayChat
searchengine
serviceprovider[SeeISP.]
services
sharingaconnection
speed
URI
URL2nd
Usenet
internet(smalli)
Internetwork
InterNIC
Interprocesscommunication2nd3rd
Interruptkey2nd
Intranet2nd
Intrusiondetectionsystem[SeeIDS,about.]
Invisiblefile[SeeHiddenfilename.]
IP
address2nd3rd
class,address
IPng
IPv62nd3rd
masquerading2nd3rd
multicast[SeeMulticast.]
NextGeneration
spoofing2nd
version6[SeeIP,IPv6.]
ip6.arpadomain
IPC
ipchainsutility
ipop3ddaemon[Seepop3-logindaemon.]
IPPprotocol
IPSec2nd
iptables
ACCEPTtarget
buildingasetofrules
chainpolicy
chain,about
classifiers[Seeiptables,match.]
commandline
commands
connectiontracking2nd
conntrackmodule
displaycriteria
DNAT
DNATtarget
DROPtarget
Filtertable
howitworks
Internetconnectionsharing
IPmasquerading
iptables-restoreutility
iptables-saveutility
jump
JumpStart,buildingafirewallwithsystem-config-securitylevel
LOGtarget
Mangletable
MASQUERADE2nd
masquerade
match
criteria
extension
extension:explicit
extension:implicit
moreinformation
NATtable
netfilter
networkpacket
non-terminatingtarget
packetmatchcriteria2nd
patch-o-matic
policy
prerequisites
protocolsfile
REJECTtarget
resettingrules
RETURNtarget
RH-Firewall-1-INPUTchain
router
rule
about
defined
matchcriteria
number
saving
specification
sharinganInternetconnection
SNAT2nd3rd
statemachine2nd
system-config-securitylevelutility2nd
target2nd3rd
iptablesfile2nd3rd
iptables-configfile
iptables-restoreutility
iptables-saveutility
IPv62nd
addressrecord,DNS
in2.6kernel
ping6
traceroute6
IRC
is_regfileshellscript
ISC2securitycertification
ISDN2nd
ISO
image
ISO9660filesystem2nd
protocolmodel
ISP
issuefile2nd
iwconfigutility
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
Job
control2nd3rd
bgbuiltin
fgbuiltin
howtouse
jobsbuiltin
number2nd
stopforeground
jobsbuiltin2nd3rd4th5th
JohntheRipperutility
Journalingfilesystem2nd3rd4th
Joy,Bill
JPEG
jpegfilenameextension2nd
jpgfilenameextension2nd
JumpStart
Apache,gettingupandrunning
Apache,settingupwithsystem-config-httpd
buildingafirewallwithsystem-config-securitylevel
configuringaSambaserverwithsystem-config-samba
configuringsendmailonaclient
configuringsendmailonaserver
CUPS,configuringaremoteprinter
DNS,settingupacache
DNS,settingupadomainwithsystem-config-bind
downloadingfilesusingftp
NFSserver,configuringwithsystem-config-nfs
NFS,mountingaremotedirectory
OpenSSH,startingthesshddaemon
OpenSSH,usingsshandscp
startingavsftpdserver
system-config-printer,configuringalocalprinter
Justify
jwhoisutility
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
K&R
kcolorchooserutility
kcronutility
kdbgutility
KDE2nd
activeviewindicator,Konqueror
Bookmarktoolbar,Konqueror
bookmark,Konqueror
browser,Konqueror
clipboard
Colorwindow,Select
components
ControlCenter
desktop2nd
Extratoolbar,Konqueror
FAQ
filemanager,Konqueror2nd
focus,window
gettingstarted,Konqueror
GNOME,compared2nd
HelpCenter
I/Oslaves
kcolorchooserutility
kdbgutility
kdmutility
kfindutility
klipperutility
KNotesutility
konsoleutility
Kparts
linkindicator,Konqueror
Locationtoolbar,Konqueror
locktocurrentlocation,Konqueror
logginginon
Mainmenu
Mainpanel
manager,session
menu
Main
Panel
PanelIcon
menubar
Navigationpanel,Konqueror
pager
PanelIconmenu
Panelmenu
portability
printmgrutility
Qt
RunCommandwindow
Searchbar,Konqueror
searchusingkfind
SelectColorwindow
shortcut,Konqueror
switchingdesktops
taskbar
terminalemulator
titlebar
toolbar
defined
Konqueror2nd
User'sManual
view,Konqueror2nd3rd
WebShortcuts(Konqueror)
windowfocus
workspace(Konqueror)
kdmKDEutility
kdmrcfile
Kerberos2nd3rd
Kernel
/procfilesystem
2.4
2.6features
2TBfilesystem
4GB-4GBmemorysplit
ACL
AIO
asynchronousI/O
BIO
blockI/O
hugeTLBFS
HyperThreadedCPUs
I/Oelevators
IGMPv3
interactiveschedulerresponsetuning
InternetProtocolvirtualserver
IPSec
IPv6
IPVS
kksymoops
nativePosixthreadlibrary
networkstackfeatures
NPTL
O(1)scheduler
OOPS
OProfile
PAE
physicaladdressextension
remap_file_pages
reversemapvirtualmemory
rmapVM
TLBFS
translationlook-asidebufferfilesystem
XFSjournalingfilesystem
2.6release
about
boot
bootoptions
cleaningthesourcetree
compiling
configuring
devicedriver
displaymessagesusingdmesg
dmesgutility
exporttable
EXTRAVERSIONnumber
installbinary
installingcompiled
messages
module[SeealsoLoadablemodule.]
networkpacketfiltering[Seeiptables.]
packetfiltering[Seeiptables.]
parameter
programminginterface
rawdevice
rebuild
responsibilities
sourcecode,installing
sourcecode,locating
specialfiles
systemcalls
kernelspace
Kernighan&Ritchie[SeeK&R.]
Key
BACKSPACE
binding
CONTROL
CONTROL-C2nd
CONTROL-D2nd3rd
CONTROL-H2nd3rd4th
CONTROL-L2nd
CONTROL-M
CONTROL-Q
CONTROL-R
CONTROL-U2nd3rd4th
CONTROL-V2nd
CONTROL-W2nd3rd
CONTROL-X2nd
CONTROL-Z2nd
Delete
encryption
endline
ENTER
erase2nd3rd4th5th
interrupt
kill2nd
linekill2nd
META
NEWLINE2nd3rd
RETURN2nd3rd4th5th
SPACEbar
suspend2nd3rd4th5th
TAB
typeface
worderase
Keyboard
movecursortonextline
system-config-keyboard,configuringwith
Keyword
searchingforusingapropos
variable2nd
kfindutility
Kickstartutility
killbuiltin2nd3rd4th5th6th7th8th9th10th11th
Killkey2nd
Killlinekey2nd
KILLsignal
kill()systemcall
killallutility
kilo-
klipperutility2nd
KMail
KNotesutility,KDE
Knowledgebase,RedHat
known_hostsfile2nd3rd
Konqueror
activeviewindicator
bookmark
Bookmarktoolbar
browser
Extratoolbar
filemanager2nd
gettingstarted
linkindicator
Locationtoolbar
locktocurrentlocation
menubar
Navigationpanel
Searchbar
shortcut
toolbar2nd
view2nd3rd
WebShortcuts
workspace
konsoleutility
KornShell[Seeksh.]
Korn,David2nd
Kparts,KDE
ks.cfgfile
ksh
history
kudzuutility2nd
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
lfilenameextension
L6utility
LAN2nd3rd
comparedtointranet
configuring
example
moreinformation,settingupaLAN
settingup
Language,procedural
Language,usedbythesystem
Largenumber
Lastinfirstoutstack
LastLinemode,vim
lastlogfile
LBX
ldutility
ld-linuxlibrary
ld-linux.soutility
LD_LIBRARY_PATHvariable2nd
LD_RUN_PATHvariable
LDAP
lddutility2nd
Leaf
Leastprivilege2nd
Left-handedmouse2nd
Lengthoffilename2nd
lessutility2nd3rd4th5th
letbuiltin2nd
libdirectory2nd3rd4th
libattrlibrary
libclibrary
libc.solibrary
libm.alibrary
libm.solibrary
Library
archived
dynamic[SeeLibrary,shared.]
ld-linux
libacl
libattr
libc
libc.so
libm.so
shared2nd
staticallylinked
libwrap.alibrary2nd
lidsutility
LIFOstack
LightweightDirectoryAccessProtocol[SeeLDAP.]
Linekillkey2nd
LinePrinterDaemon[Seelpddaemon.]
LINESvariable
Link2nd3rd
createusingln
deleteusingrm
export
hard2nd3rd4th
hardversussymbolic
hypertext
indicator,Konqueror
inode
numberof,displayusingls
point-to-point
removeusingrm2nd
soft[SeeLink,symbolic,versushard.]
symbolic
bashand
createusingln
defined
versushard2nd
symlink[SeeLink,symbolic,versushard.]
linksshellscript
linksutility2nd
lintutility
Linux
2.6kernel[SeeKernel.]
boot
distribution
documentation
DocumentationProject2nd
FilesystemHierarchyStandard2nd
FilesystemStandard2nd
kernel[SeeKernel.]
manual
newsgroup2nd
PAM[SeePAM.]
PluggableAuthenticationModules[SeePAM.]
StandardBase
TerminalServerProject
LinuxSoftwareMapdatabase
linuxterminalname
linux-gate.so.1file
linux.redhat.installnewsgroup2nd
linux.redhat.miscnewsgroup
linux.redhat.rpmnewsgroup
LinuxSecurity.comsecuritynews
Listserver2nd
Listserv2nd
llibacllibrary
lnutility2nd3rd
versuscp
Loadaverage
Load,system,displayusingw
Loadablemodule
Loader,boot[SeeBoot,loader.]
Local
areanetwork[SeeLAN.]
variable2nd3rd
localdirectory2nd
localfile
Locale
localebuiltin
localhost2nd
locatedatabase2nd
locateutility2nd
Locationbar
illustration
Nautilus
Locationtoolbar,Konqueror
Locktocurrentlocation,Konqueror
lockutility
lockddaemon
lockttyshellscript
Log
Apache
display
DNS2nd3rd
email
file,check
file,rotate
files
in[SeeLogin.]
machine
OpenSSH
out2nd
sendmail
syslogddaemon
system
vsftpd
logcommand(cvs)
logdirectory2nd3rd4th5th
Logical
expression
partition
volume[SeeLVM.]
VolumeManager[SeeLVM.]
Login
Chooseasessiondialogbox
descriptionof
failsafesession
GUI
incorrect
name[SeeUsername.]
problems2nd
procedure
prompt2nd
remote2nd
root2nd3rd
screen2nd
security
shell2nd3rd4th
loginutility2nd
login.defsfile2nd
LOGNAMEvariable
Logout
logresolveutility
logrotateutility
logrotate.conffile
logrotate.ddirectory
logwatchutility
Loopbackservice
lost+founddirectory
lputility
lpadminutility
lpddaemon2nd
lpinfoutility
lpqutility2nd
LPRlineprintersystem
lprutility2nd3rd4th
lprmutility2nd
lpstatutility2nd
lsutility2nd3rd4th5th6th7th
LSB
lseek()systemcall
lsmodutility
lsofutility
LV[SeeLVM.]
LVM2nd3rd
LV2nd3rd
PV
VG
LWN.netsecurityalerts
lynxtextbrowser
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
mfilenameextension
m4macroprocessor
MACaddress2nd
Machine
collatingsequence
independence
log
name,display
Macintosh
Macro
Cpreprocessor2nd
expansion
m4,processor
make
processor,m4
magicfile2nd
Magicnumber2nd3rd
magicnumberdatabase
Mail
.forwardfile2nd
acceptingmailfromunknownhosts
accessfile
aliases2nd
aliasesfile
authenticatedrelaying
backupserver
checkroot
communicatewithusers
deliveryagent
forwardingemail
howsendmailworks
IMAP
JumpStart
configuringsendmailonaclient
configuringsendmailonaserver
KMail
listserver2nd
log
maildirectory2nd3rd
mailbox
maildirformat
mailertablefile
mailinglist
maillogfile
Mailman
mailqutility
mailstatsutility
makemaputility
masquerading
mboxformat
MDA2nd
moreinformation
mqueuefile
MTA2nd
security
MUA2nd
security
networkaddresses
newaliasesutility
POP
Postfix
postmaster
praliasesutility
prerequisites
procmaildaemon
Qmail
relayhost
security
about
GnuPG
MTA
MUA
PEMencryption
self-signedcertificate
sendingtoremoteuser
sendmaildaemon2nd3rd4th
sendmail.cffile
sendmail.mcfile2nd
servingmultipledomains
SMTP
spam
SpamAssassin
spamddaemon
SquirrelMail
SSL
useragent
virtusertablefile2nd
Webmail
maildirectory2nd3rd4th
mailutility2nd
MAILvariable2nd
Mailbox
MAILCHECKvariable
maildirformat
mailertablefile
Mailinglist
bugtraq
maillogfile2nd
Mailman
MAILPATHvariable
mailqutility
mailstatsutility
Main
memory
menu
panel,KDE
mainfunction
Mainframecomputer
Maintenance[SeeSystem,administration,Kickstart
utility.]
Majordevicenumber2nd
makeutility2nd3rd4th
makedbmutility
Makefilefile2nd
makefilefile2nd
Makefile,discussion
makemaputility
makewhatisutility2nd
MAN2nd
mandirectory
manpages
manutility2nd3rd
Man-in-the-middle2nd3rd
Manager
session2nd
window
Manuals
GNU2nd
HOWTO
man
reference,finding
system,about
Mapfile
Masquerading
IP2nd3rd
mail
MassachusettsInstituteofTechnology[SeeMIT.]
MasterBootRecord[SeeMBR.]
Masterserver,DNS
mboxformat
MBR
MD5encryption2nd
MD5SUMfile
md5sumutility
MDA2nd
Mega-
Memory
main
paging
test
virtual
memtest86+utility
Menu
context
Desktop2nd
Iconcontext
Main
Panel
PanelIcon
Panel,KDE
shellscript
Menubar
Konqueror
Nautilus
Merge
mesgutility
Message
daemon,from
denyusingmesg
Digest5[SeeEncryption,MD5.]
oftheday[Seemotdfile.]
security
sending
email
wall
write2nd
syslogdirectory
system2nd
truncating
usage2nd3rd4th5th
messagesfile2nd3rd4th5th6th7th8th
METAkey
Metabit
Metacharacter2nd
Metacitywindowmanager
Metadata
Methodoflastresort,kill
Metropolitanareanetwork[SeeMAN.]
Microprocessor
Middlemousebutton
MIME2nd
types,GNOME
mingettyutility2nd3rd
mini-HOWTOdocuments,finding
Minicomputer
Minimizewindow
MINIX
minixfilesystem
Minordevicenumber2nd
Mirrorsite
misc.jobs.offerednewsgroup
Mistake,correcttyping
MIT
Athena,Project
XConsortium
MITM[SeeMan-in-the-middle.]
mkdirutility2nd3rd
mkfifoutility
mkfsutility2nd3rd4th5th
mkswaputility
Modem
cable
Modifyingauser
modinfoutility
modprobeutility
Module[SeealsoLoadablemodule.]
kernel
modulesdirectory2nd
Monitor,configure
Monitors,dual
Moreinformation
Apache
CUPS
DHCP
DNS
email
FTP
iptables
LAN,settingupa
NFS
NIS
OpenSSH
PAM
Samba
security
systemadministration
moreutility2nd3rd
Morris,RobertT.Jr.
MosaicWebbrowser
motdfile2nd3rd4th5th
Mount
automatic2nd
filesystemautomatically
floppydiskette
point2nd3rd4th
remotefilesystem
table
mountutility2nd3rd4th5th6th
mountddaemon2nd
mountsfile
Mouse
about
clickexplained
configure
left-handed2nd
middlebutton
mouseover
pointer
pointer,hover2nd
remapbuttons
right-handed
wheel
windowmanager
Mouseover
Move
directoryusingmkdir
fileusingmv
Mozilla
historyof2nd3rd
netnews
proxy
mqueuefile
MSWindows[SeeWindows,convertfiles.]
MS-DOS[SeeDOS,convertfiles.]
msdosfilesystem
mtutility
MTA2nd
security
mtabfile
MUA2nd
security
Multibootspecification
Multicast2nd
MultipurposeInternetMailExtension[SeeMIME.]
Multitasking2nd3rd
Multithreadedprogram
Multiuser
about
Linuxdesign2nd
mode
extended
initiate
Superuser
mvutility2nd3rd
MXrecord,DNS2nd
mxgdbutility
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
Name
command
daemons
domain[SeeDomain,name.]
login[SeeUsername.]
server2nd
variable
nameddaemon2nd3rd
nameddirectory2nd
namedfile2nd
Namedpipe2nd3rd4th
named.conffile2nd3rd
Namespace
NAT2nd
NationalCenterforSupercomputerApplications
Nautilus
controlbars
file
emblems
manager
openwith
permissions
properties
locationbar
menubar
openfile
OpenLocationdialogbox
Sidepane
spatialview
toolbar
traditionalview
Vewpane
Navigationpanel,Konqueror
NBT
ncpfsfilesystem
ndbmdatabase
nessusutility
netuseutility(Windows)
netutility
netviewutility(Windows)
NetBIOS
Netboot2nd
netcatutility
netgroupfile
Netiquette
Netmask
Netnews
answers,finding
archive,groups.google.com
comp.lang.cnewsgroup
comp.os.linux.announcenewsgroup
comp.os.linux.miscnewsgroup2nd
comp.os.linux.networkingnewsgroup
comp.os.linux.securitynewsgroup
comp.os.linux.setupnewsgroup
comp.security.firewallsnewsgroup
groupstructure
groups
hierarchicalstructureofgroups
historyof
linux.redhat.installnewsgroup2nd
linux.redhat.miscnewsgroup
linux.redhat.rpmnewsgroup
misc.jobs.offerednewsgroup
MozillaNews
NetscapeNews
newsgroups
nnutility
readnewsutility
rec.skiingnewsgroup
rnutility
sci.mednewsgroup
soc.singlesnewsgroup
structureofgroups
talk.politicsnewsgroup
tinutility
xrnutility
xvnewsutility
Netscape
BugSplat
historyof
Navigator
netnews
netstatutility
Network
100BaseTcable
10Base2cable
10BaseTcable
@inanaddress2nd3rd
@withemail
address
@signin2nd3rd
email
mask
space,private2nd
AddressTranslation[SeeNAT.]
boot
bottleneck
broadcast2nd
address
multicast,compared
packet
unicast,compared
broadcastpacket
browser
Category5cable
Category5ecable
Category6cable2nd
Category7cable
class,IPaddress
coaxialcable
connection,testusingping
daemon2nd
datagram2nd
DNS
domainname
dynamicIPaddress
Ethernet2nd3rd4th5th
extranet2nd
FDDI
fiberopticcable
fileserver
Filesystem[SeeNFS.]
firewall
frame2nd
gateway2nd3rd
heterogeneous
hops
hostaddress
hostname,FQDN
hostname,nickname
hub2nd3rd
ICMPpacket
InformationService[SeeNIS.]
interfacecard[SeeNetwork,NIC.]
Internet
intranet
IP
address
addressclass
NextGeneration
localarea[SeeLAN.]
metropolitanarea[SeeMAN.]
multicast2nd
nameserver2nd
netmask
netnews[SeeNetnews,historyof.]
newsgroup
NIC2nd
number[SeeNetwork,address,email.]
packet2nd3rd
packetfiltering[Seealsoiptables.]
packetsniffer
partnernet
passivehub2nd
pingtotest
point-to-pointlink
portforwarding
PPPprotocol
privateaddressspace2nd
privilegedport
protocol
remotefilesystem
resolver
routetrace
router2nd3rd4th5th
router,SmoothWallLinuxdistribution
security
about
guidelines
solutions
segment
services2nd
settingup
SLIPprotocol
sniff
socket
staticIPaddress
subnet2nd
about
address
mask2nd
number
specifying
switch2nd3rd4th
switchinghub[SeeNetwork,hub.]
TCP/IPprotocol
thicknetcable
thinnetcable
TimeProtocol[SeeNTP.]
tokenring
topology,shared
traceroute
transferrate
trustedhosts
tunneling2nd
twistedpaircable
UDP2nd
unicast2nd
unicastvs.broadcast
unshieldedtwistedpaircable
usercommunication
utilities2nd
UTPcable
virtualprivate
VPN2nd
WAN[SeeWAN.]
WAP
Wi-Fi
widearea[SeeWAN.]
wireless
accesspoint2nd
bridge
mode
NIC
networkfile2nd
newaliasesutility
NEWLINEkey2nd3rd
News,Internet[SeeNetnews,historyof.]
Newsgroup
comp.lang.c
comp.os.linux.announce
comp.os.linux.answers2nd
comp.os.linux.misc2nd3rd4th
comp.os.linux.networking
comp.os.linux.security
comp.os.linux.setup
comp.security.firewalls
linux.redhat.install
linux.redhat.misc
linux.redhat.rpm
listof
misc.jobs.offered
rec.skiing
sci.med
soc.singles
talk.politics
NFS2nd3rd
/proc/fs/nfs/exportsfile
all_squashoption
attributecachingoptions
blocksize
client,settingup
daemons
dataflow
errorhandlingoptions
errormessage,NFSserverxxxnotresponding
exchangingfiles
export
devicefile
directoryhierarchy
table,kernel
exportfsutility
exportsfile2nd
filesystem
fstabfile2nd3rd
homedirectories
JumpStart
configuringanNFSserverwithsystem-config-nfs
mountingaremotedirectory
linespeed,testing
miscellaneousoptions
moreinformation
mountafilesystem
mountutility
nfsnobody
NISand
options
all_squash
attributecaching
errorhandling
miscellaneous
root_squash
performance,improving
portmaputility2nd
prerequisites2nd
root_squashoption
security
serverserverdependency
setuid
showmountutility
stop
testing
timeout2nd
umountutility
userIDmapping
xtabfile2nd
nfsfile
nfsddaemon2nd
nfsnobody
NIC2nd3rd4th
nice()systemcall
Nickname,host
nicknamesfile
NIS2nd3rd
addingusers
clientsetup
client,test
database2nd3rd
domain
domainname2nd
GECOS
login
makedbmutility
Makefile
map
displaying
names
nicknames
masterserver
moreinformation
needfor
networkfile
NFSand
nicknamesfile
nisdomainnameutility
passwdutility
prerequisites,client
prerequisites,server
removingusers
rpcinfoutility
securenetsfile
serversetup
serverspecify
slaveserver
sourcefiles
testing
YellowPages
yp.conffile
ypbinddaemon
ypbind-mtdaemon
ypinitutility
yppasswdutility
yppasswdddaemon
ypserv.conffile
ypwhichutility
ypxfrutility
ypxfrddaemon
nisdomainnameutility
nmaputility
nmbddaemon2nd3rd4th
nmblookuputility2nd
nnutility
NNTP2nd
Nonewsisgoodnews
noarch2nd
noclobbervariable
Node
nologinutility
nologin.txtfile2nd
Nonprintingcharacter
Nonrewindingtapedevice
Nonvolatilestorage
Normalmode,vim[Seevim,Commandmode.]
NOTBooleanoperator
nsswitch.conffile2nd3rd4th5th6th
nst0file
ntfsfilesystem
NTP
ntp.conffile
ntpddaemon
Null
builtin(:)2nd
device
string2nd
nullfile2nd3rd4th5th6th
Number
block
device
major
minor
giga-
hexadecimal
job
kilo-
large
magic2nd
mega-
octal
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
oBooleanoperator
ofilenameextension2nd3rd4th
Objectfile2nd
Octalnumber
odutility
OLDPWDvariable
One-timepassword
Onlinedocumentation2nd
Open
file
Group
Locationdialogbox,Nautilus
open()systemcall
OpenOffice
OpenPGPMessageFormat
OpenSSH
.sshdirectory
authentication2nd
authorizedkeys
authorized_keysfile
automaticlogin
clients
compression
configfile
configurationfiles2nd
debugging
diffutility
encryption
files
firewall
globalfiles
hostkey
howitworks
initialconnectionto
JumpStart
startingthesshddaemon
usingsshandscp
knownhosts
known_hostsfile2nd3rd
logfile
moreinformation
NFSsharedhomedirectories,and
portforwarding
prerequisites2nd
protocolversions1and2
publickeyencryption
recommendedsettings2nd
remotecommands
rhostauthentication
scputility
security
serverauthentication
sessionkey
setup
sftputility
shell,remote
sshdirectory
sshutility2nd3rd4th
ssh-keygenutility
ssh_configfile
ssh_known_hostsfile2nd3rd
sshddaemon
sshd_configfile
troubleshooting
tunneling
userfiles
X11forwarding2nd3rd4th
Operatingsystem
generic
proprietary
Operationsmenu,window
Operator
bash
inexpressions
redirection
bitwise
&2nd
^
AND2nd
|
Boolean
!2nd3rd
&&2nd3rd4th5th6th
a2nd
o
NOT
|
||2nd3rd4th5th
decrement
increment
postdecrement
postincrement
predecrement
preincrement
relational
short-circuiting
tableof
OPIEutility2nd
optdirectory2nd3rd
OPTARGvariable
Optimizer,Ccompiler
OPTINDvariable
Option
bash[Seebash,features.]
combining
defined
ORoperator
Orderfileusingsort
Orderofexpansion,commandline
Ordinaryfile2nd
Organizeafilesystem
Otheraccess
outshellscript
Output
append[SeeAppend,standardoutput.]
redirect
standard[SeeStandard,output.]
Overlayashell
Owner
access
file,nameof,displayusingls2nd
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
P2P
Packarchivefileusingtar
Package[SeeSoftware,installing.]
Packet
broadcast
filtering[Seealsoiptables.]
network2nd
sniffer
unicast
Pagebreak
Pager2nd3rd4th
Paging2nd
PAM2nd
features
moreinformation
security,login
stack
pam.conffile
pam.ddirectory2nd3rd4th
Panel
desktop
Iconmenu
menu,KDE
Navigation,Konqueror
Parameter
expansion
positional
shell
special
substitution
Parent
directory2nd
ofallprocesses
process2nd3rd
Parentheses
groupingcommands
shellfunctions
Parse2nd
partedutility
Partition
/boot2nd3rd4th
/home
/usr
/var
disk2nd
DiskDruid
LVM
partedutility
planning
primaryandsecondary
RAID2nd
sizes
Partnernet
PASC
PassiveFTP[SeeFTP,passive.]
Passivehub2nd
Passphrase
passwddatabase2nd3rd4th
passwdfile2nd3rd4th5th6th7th8th
passwdutility2nd3rd4th
Password
breaking
change2nd
criteria
group
hashed
one-time
Samba
security
Superuser
PASVFTP[SeeFTP,passive.]
PATHvariable
inherited
login
Superuser2nd
usage
Path,search
Pathname
absolute2nd3rd
completion
defined
element
expansion2nd3rd4th
lastelementof
relative2nd3rd4th
using
~(tilde)ina
pdffilenameextension
Peer,BitTorrent
Period,leadinginafilename
Peripheraldevice[SeeDevice.]
Permission
access
changeusingchmod
controlof
directory
displayusingls
execute
read
typesof
execute
fileaccess2nd
read
setgid
setuid
setuid,setusingchmod
Persistent
PGPencryption
pgpkeyfile[See.pgpkeyfile.]
Philosophy,UNIX2nd
Phish
phpfilenameextension
Physical
device
security
volume[SeeLVM.]
PID2nd
$!variable,and
$$variable
backgroundprocessand2nd
fg
number12nd
temporaryfile,useinnameof
pidofutility
pinfoutility
pingutility2nd3rd4th
ping6utility
Pipe
commandseparator
defined
endofline,at
filter2nd
introduction
named2nd3rd4th
noclobberand
standarderror,and
symbol
syntaxexception
Pipeline[SeePipe.]
pirututility
Pixel
Plaintext2nd
planfile[See.planfile.]
PluggableAuthenticationModule[SeePAM.]
Plussign
Pointtogivefocus
Point-to-pointlink2nd3rd
Point-to-PointProtocol[SeePPPprotocol.]
Pointertoafile
POP,email
pop3-logindaemon
popdbuiltin
Port2nd
forwarding
forwarding,OpenSSH
privileged2nd
Portability2nd
portmapdaemon2nd3rd
portmaputility2nd
Portmapper
Positionalparameter2nd
POSIX
about
standards
Postdecrementoperator
Postfix
postfixdaemon
Postincrementoperator
Postmaster
PostScriptPrinterDefinition[SeePPDfiles.]
Postscript,braceexpansion
Powermanagement2nd
Power,turnoff
poweroffutility
ppdfilenameextension
PPDfiles
PPID[SeeParent,process.]
PPPprotocol2nd3rd
pppddaemon
praliasesutility
Preamble,braceexpansion
PrebootExecutionEnvironment[SeePXE.]
Predecrementoperator
Preincrementoperator
Preprocessordirective
#define2nd
#include
defined
macro2nd
symbolicconstant2nd
Prerequisites
Apache
automount
BitTorrent
CUPS
DHCPclient
DHCPserver
DNS
FTP
iptables
make
NFS2nd
NISclient
NISserver
Samba
sendmail
vsftpd
PrettyGoodPrivacy[SeePGPencryption.]
Primary
buffer
masterserver,DNS
partition
Print
file
IPPprotocol
queue
Printablecharacter
printcapfile
Printer
capabilitydatabase
configuringwithCUPS
controlcharacters
daemon2nd
lprand
pagebreak
sharing
skiptotopofpage
topofform
using
Printing
CUPS
manager,KDE
quotas
system,about
UNIXtraditional
Windows,from
Windows,to
printmgrutility
PrivacyEnhancedMail[SeeEncryption,PEM.]
Privateaddressspace2nd
Privatekey
Privilege,least2nd
Privilegedport2nd3rd
Probedevices
Problems
hungprogram
login
procfilesystem2nd3rd4th5th
Procedurallanguage
Procedure
Process
background2nd3rd
child2nd3rd
defined2nd
die2nd
first
foreground
fork
ID[SeePID.]
init
kill
parent2nd
parentofall
parent-childrelationship
searchforusingpsandgrep
sleep2nd
spawn[SeeFork.]
spontaneous
start
structure
substitution
wakeup2nd3rd
Processingacommandline
procmaildaemon
procmailutility
profilefile2nd3rd4th
Program[SeealsoBuiltin;Utility.]
badtabs.c
keepingcurrent
runninga
stop
structures
tabs.c
terminate
XWindowSystem
Programmer
applications
systems
Programmingtools
ProjectAthena
projectfile[See.projectfile.]
PROM
Prompt
#
$
%
bash
jobcontroland
login2nd
PS2
PS3
representation
root
secondary
shell2nd
Superuser
Proprietaryoperatingsystem
Protocol
connection-oriented2nd
connectionless
datagram-oriented
defined
DHCP
HTTP
HTTPS2nd
ICMP
IPP
IPSec2nd
ISOmodel
network
NNTP
Point-to-Point
PPP2nd
SLIP
TCP/IP
TELNET
UDP
protocolsfile2nd
Proxy
defined
gateway2nd
server2nd
psfilenameextension
psutility2nd3rd4th5th
PS1variable2nd
PS2variable2nd
PS3variable
PS4variable
Pseudoterminal
pstreeutility
ptsfile
pubdirectory
Publickeyencryption
Publickeyencryption,OpenSSH
PublicLicense,GNU[SeeGNU,GeneralPublic
License.]
public_htmldirectory
pushdbuiltin
putcharCmacro
pwdbuiltin2nd3rd
pwdutility2nd
PWDvariable
PXE
Python
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
Qmail2nd
qnx4filesystem
Qt
Questionmark
Questions,findinganswersto
Quicksubstitution
Quiescent
quotautility
quotaonutility
Quotationmark
double2nd3rd4th
removal
single2nd3rd
singleversusdouble2nd
usagemessage
Quoting
characters2nd
shellvariables
specialcharacters
whitespace
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
Radiobutton
RAID
about2nd
backups,doesnotreplace
RAM
disk
swap,and2nd
Randomaccessmemory[SeeRAM.]
Randombytes,generating
randomfile
Randomnumbergenerator
RANDOMvariable
RAS2nd3rd
Raw
device
mode
rbacutility
rcfile
rcscripts
rc.d
about
directory
init.ddirectory2nd
init.d/kudzufile
rc.localfile
rc.sysinitfile2nd
RC5encryption
rcn.ddirectory
rcputility
RDF
Read
access2nd
userinput
readbuiltin2nd3rd4th5th6th
read()systemcall2nd
ReadlineLibrary2nd
completion
readnewsutility
readonlybuiltin2nd3rd4th
Readonlymemory[SeeROM.]
Readonlyvariable
rebootutility
Reboot,system
RebuildingLinux
rec.skiingnewsgroup
Recursion
defined
example
infinite,alias2nd
Recursiveplunge[SeeRecursion,infinite,alias.]
RedHat
EnterpriseLinuxversusFedoraCore
Knowledgebase
Network[SeeRHN(RedHatNetwork),download
andinstallnewpackages.]
PackageManager[SeeRPM,about.]
securityinformation
RedHatLinux
Anaconda2nd
druid
errata
installing
Anaconda2nd
BIOSsetup
BitTorrent
bootcommands
bootprompt
burningCDsorDVD
CDs,testing
CMOSsetup
configuringthedisplay
configuringtheXWindowSystem
DiskDruid
disksetup
diskspace
displayproblems
download,burn,andinstallCDsetorDVD
dualmonitors
dual-bootsystem
explained
FedoraCoreversusRedHatEnterpriseLinux
firewall
Firstboot
floppydiskette
formatting,low-level
freespace
howitworks
install,typeof
installationtype
Kickstart
low-levelformatting
MD5SUMfile
memorytest
networkconfiguration
networkinstallation
non-CDinstallations
parted
partition
partitionplanning
planning
RedHatEnterpriseLinuxversusFedoraCore
requirements
rescueCD
SHA1SUMfile
source
start
upgrade
upgradingversusinstalling
versusupgrading
virtualconsoles
XWindowSystem
Kickstart
rescueCD
software,add
upgrade[SeeRedHatLinux,installing,
explained.]
Redirect
operators,bash
output
standard
error2nd
input2nd
output2nd3rd
outputandappend
outputanderror
outputofbackgroundjob
outputusingtee
Redirection2nd3rd
Redundantarrayofinexpensivedisks[SeeRAID.]
Reentrantcode2nd
Reexecutingcommands
Refreshscreen
Regularcharacter
Regularexpression2nd
\(...\)bracketexpression
ampersand2nd
anchor
asterisk
bracket
bracketing
caret
delimiter
dollarsign
empty
extended
full
longestmatch
period
quoteddigit
quotingparentheses
quotingspecialcharacters
replacementstring
rulesofuse
simplestring
specialcharacter
specialcharacter,quoting
squarebracket
summary
reiserfsfilesystem
rejectutility
Relationaloperator
Relativepathname2nd3rd4th
releasecommand(cvs)
Release,CVS
Religiousstatue,miniature[SeeIcon.]
Remainderoperator
Remapmousebuttons
Remote
accesssecurity
accessserver[SeeRAS.]
computingandlocaldisplays
filesystem2nd
login
NameDaemonControl[SeeDNS,rndcutility.]
procedurecall[SeeRPC.]
Remove
deviceusingkudzu
directoryusingrmdir
fileusingrm
linkusingrm
softwarepackage2nd
user
variable
removecommand
Rename
directoryusingmv
fileusingmv2nd
Repairfilesystem
Repeatingacommand
Replacementstring2nd3rd
REPLYvariable2nd
repofilenameextension
Reports,system
Requestforcomments[SeeRFC.]
RescueCD
Rescuemode2nd
Reservedport[SeePrivilegedport.]
resetutility
Resizingawindow
Resolution,changingthedisplay
resolv.conffile2nd3rd
Resolver2nd3rd4th
ResourceDescriptionFramework[SeeRDF.]
Resourcerecord,DNS
Respawn
Restore
restoreutility
Returncode[SeeExit,status.]
RETURNkey2nd3rd4th5th
Reversenameresolution,DNS
rexecddaemon
RFC
RHN(RedHatNetwork)
AlertNotificationTool
database
downloadandinstallnewpackages
entitle
rhn-applet-guiutility
rhnsddaemon
server
subscribingto
up2dateutility
up2date-configutility
rhn-applet-guiutility
rhnsddaemon
rhostAuthentication,OpenSSH
Right-handedmouse
Ringoftrust
Ritchie,Dennis
rloginutility
rloginddaemon
rmutility2nd3rd4th5th
rmdirutility
rmmodutility
rmt/0file
rnutility
rndcutility
rndc.conffile
rndc.keyfile
Roam
ROM
romfsfilesystem
Root
directory2nd3rd4th
domain,DNS
filesystem
login2nd3rd
user[SeeSuperuser.]
window
rootuser[SeeSuperuser.]
Rotatefile2nd
routeddaemon
Router
discussion
network2nd3rd
settingupwithiptables
SmoothWallLinuxdistribution
Routingdaemon
RPC2nd3rd
rpcfile2nd
rpcinfoutility2nd
RPM
about
binarypackage
database
install
installkernelbinary
noarch
queryfile
querypackage
rpmutility
RPMS
sourcepackage
SRPMS
uninstall
upgrade
rpmutility
rpmnewfilenameextension
rquotaddaemon
RSAencryption2nd
rshutility2nd
rshddaemon
rtagcommand(cvs)
Run
backgroundcommand
commandscript
commandscripts[Seercscripts.]
Commandwindow,KDE
program
programwindow,GNOME
shellscript
Runlevel
2
3[SeeMultiuser.]
4
5
initdefault,and2nd
tableof
runlevelutility
ruptimeutility
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
sfilenameextension2nd
S/Keyutility
safeditshellscript
saintutility
Samba
[homes]share
about
administration[SeeSamba,swatutility.]
browserparameters
browsingLinuxsharesfromWindows
communicationparameters
daemons
globalparameters
homedirectories,sharing
JumpStart,configuringaSambaserverwithsystem-config-
samba
Linuxshares
accessingfromWindows
settingup
loggingparameters
manualconfiguration
mappingashare
moreinformation
NBT
netuseutility(Windows)
netutility
netviewutility(Windows)
NetBIOS
nmbddaemon2nd3rd
nmblookuputility2nd
password
pingutility
prerequisites
printingfromWindows
printingtoWindows
securityparameters
share
shareparameters
shareddirectory
SMB
smb.conffile
smbclientutility2nd3rd
smbddaemon2nd
smbpasswdfile
smbstatusutility2nd
smbtreeutility2nd
smbusersfile
suiteofprograms
swatutility
system-config-sambautility
testparmutility
testprnsutility2nd
troubleshooting
user
adding
map
name
nobody
utilities
WebAdministrationTool[SeeSamba,swatutility.]
Windows
networks,browsing
share
sharesfromLinux,accessing
shares,connectingto
shares,displaying
shares,mounting
WINS
xinetddaemon
samhainutility2nd
SANSsecuritytrainingandeducation
sarautility
sbindirectory2nd
Scheduling
jobs
routinetasks
Schema
Schneier,Bruce
sci.mednewsgroup
scputility2nd3rd[SeealsoOpenSSH.]
Screen,login
Screen,refresh
scriptutility
Script,init
Script,shell[SeeShellscript.]
Scroll
Scrollbar
Search
beagle
engine
database
defined
finda
index
Webcrawler
keywordusingapropos
path
stringusinggrep
usingkfind
Searchbar,Konqueror
Secondaryprompt
Secondaryserver,DNS
Secretkeyencryption[SeeSymmetrickey
encryption.]
Secuniavulernabilitymonitoring
securefile2nd3rd
SecureSocketsLayer[SeeSSL,email.]
securenetsfile
securettyfile
Security
accesspermission2nd
acctonutility
ACL2nd
AIDEutility2nd3rd
ANI
Apachesecuritydirectives
authentication
automaticnumberidentification
backdoor
BIND[SeeSecurity,DNS.]
BIOS
Bugtraq
callerID
CERT2nd3rd
checksum
chkrootkitutility
chrootjail[Seechrootjail,BIND.]
cipher
ciphertext2nd
cleartext
CLID
cookie
crackutility
cracker
cryptography
cypher
DDoSattack
digitalsignature
DNS2nd
DoSattack
DragonSquireIDS
dsniffutility
email
encryption[SeeEncryption.]
EnhancedLinux[SeeSELinux.]
etherealutility
FedoraCore
file
fingerutility
firewall
Firewalltoolkit
Freefiresolutions
FTP2nd
fwtkutility
GIACcertificationandtraining
hole
host
hostbasedtrust
host,trusted
hosts.equivfile
hpingutility
in.rexecddaemon
Internet,rootaccess
IPspoofing
IPng
IPSec2nd
IPv6
ISC2
JohntheRipperutility
keepthesystemsecure
Kerberos2nd
kill
L6utility
lidsutility
Linuxfeatures
LinuxSecurity.com
lockttyscript
login
account
shell
LWN.net
mailinglist,bugtraq
man-in-the-middle2nd3rd
messages
MITM[SeeMan-in-the-middle.]
moreinformation
MTA
MUA
nessusutility
netcatutility
network
about
guidelines
solutions
NFS
nmaputility
one-timepassword
OpenSSH[SeeOpenSSH.]
OPIEutility2nd
PAM2nd
partition
password2nd3rd
PATHandSuperuser
PATHvariable
physical
plaintext
privutility
RAS
rbacutility
RedHatinformation
remoteaccess
resources
ringoftrust
rloginddaemon
rootaccess,Internet
RSA
rshddaemon
saintutility
samhainutility2nd
SANStrainingandcertification
sarautility
Schneier,Bruce
Secuniavulnerabilitymonitoring
SecurityFocustoolsandlists
SELinux
setgid
setuid2nd3rd
SHA1hashalgorithm
shadowfile
smartcard
snortutility
software,up-to-date
spoofing
srputility
ssh[Seesshutility.]
SSL
STARTTLS2nd
suutility
sudoutility
SuperuserandPATH
Superuserpassword
swatchutility
syslogddaemon
TCPwrappers
telnet
telnetddaemon
TLS
Treachery,tools
tripwireutility2nd
Trojanhorse2nd
trust
trustedhost
up-to-datesoftware
virtualprivatenetwork
virus2nd
VPN
vsftpd
wipingafile
worm2nd3rd
xhost
xinetddaemon[Seexinetddaemon.]
securitydirectory2nd
SecurityFocus,securitytoolsandlists
sedutility
Seed,BitTorrent
Segment,network
selectcontrolstructure
Selectionbuffer
Self-signedcertificate2nd3rd
SELinux
selinuxfile
sendmail[SeealsoMail,networkaddresses.]
sendmaildaemon2nd3rd4th5th6th7th
sendmail,masquerade
sendmail.cffile
sendmail.mcfile2nd
Separatingcommands
Server
DNS
cache
full-functioned
master
primarymaster
secondary
slave
splithorizon
typesof
file
FTP
maillist2nd
MessageBlockProtocol[SeeSamba,SMB.]
name2nd
process
proxy
settingup2nd
vsftpd
X2nd
serviceutility
Service,directory
Services
daemonsproviding
Internet
network
nsswitch.conffile
servicesdatabase
servicesfile2nd3rd
Session
defined
failsafe
key,OpenSSH
manager2nd
sestatusutility
setbuiltin2nd3rd4th5th6th7th
SetgroupID[SeeSetgid.]
SetuserID[SeeSetuid.]
Setgid2nd
root,filesbelongingtothegroup2nd
setserialutility
Setuid2nd3rd
at
crontab
findingfilesusingfind
grantprivileges
mount2nd
NFS
nosuidoptiontomount2nd
root,filesownedby2nd
security
Sexillion
sftputility
shfilenameextension
shShell2nd3rd
SHA1hashalgorithm
SHA1SUMfile
sha1sumutility
Shading,window
shadowfile2nd
sharshellscript
Share
sharedirectory
Shared
library
creating
using
networktopology
object,filenameextension
Shares,addingLinux(Samba)
SharinganInternetconnection
Shell2nd
archive
arithmetic(bash)
callingprogram,nameof
command
grouping2nd
interpreter
separation
substitution2nd
comment
comparingstrings
controlstructure
break
case
continue
do2nd3rd4th
done2nd3rd4th
elif
else
esac
fi2nd
for2nd3rd
for...in2nd
if2nd3rd
if...then
if...then...elif
if...then...else
in
then2nd3rd
until
while2nd
environmentvariable2nd
exitfrom
features
function2nd
jobcontrol
keywordvariable
login2nd3rd4th
nameofthecallingprogram
options[SeeShell,features.]
parameter
positional
special
prompt2nd3rd4th
readonlyvariable
sh2nd
sleep
strings,comparing
user-createdvariable
variable[SeeShellvariable,TERM.]
Shellscript2nd3rd
#comment
#!shelltouse
/dev/ttyforaterminal
addbanner
bash
birthday
bundle
chkargs2nd
command_menu
comment
configure
count
cpdir
create
debug
doublequotationmarks2nd
errormessage2nd
executing2nd
Heredocument
infiniteloop
invocation
is_regfile
links
locktty
makepath
menu
out
PATHusage
quiz
quotein2nd3rd4th
readuserinput
recursion
running
safedit
shar
specifyingashell
spell_check
temporaryfilename2nd
usagemessage2nd3rd
userinput
whos
whoson
SHELLvariable
Shellvariable
$!
$#2nd
$$2nd
$*
$0
$?
$@2nd
BASH_ENV
CDPATH
COLUMNS
CVSROOT
DISPLAY
ENV
FCEDIT
HISTFILESIZE
HISTSIZE
HOME2nd3rd4th
IFS
INPUTRC
keyword
LD_LIBRARY_PATH2nd
LD_RUN_PATH
LINES
LOGNAME
MAIL2nd
MAILCHECK
MAILPATH
naming
noclobber
OLDPWD
OPTARG
OPTIND
PATH
example
keywordshellvariable
login
root
security
PS12nd
PS22nd
PS3
PS4
PWD
quoting
RANDOM
readonly
REPLY2nd
SHELL
TERM2nd3rd
shellsfile
shiftbuiltin2nd3rd
Short-circuitingoperator
Shortcut[SeeLink.]
Shortcut,Konqueror
showmountutility
shtmlfilenameextension
Shutdownsystem
shutdownutility2nd
Sidepane,Nautilus
Signal
defined
hangup
HUP
KILL
kill
listof
names2nd
quit
softwaretermination
TERM
terminalinterrupt
Signature,digital
SiliconGraphics
Simplefilename2nd3rd4th
Singlequotationmark2nd
Singleversusdoublequotationmarks
Single-user
frommultiuser
maintenance
mode,about
Superuser
system
Sizeoffile,displayusingls
skeldirectory
Skiptotopofpage
Slaveserver,DNS2nd
sleepsystemcall
Sleep,shell
Slice[SeePartition,disk.]
SLIPprotocol
Sloppyfocus
Slowsystem
Smartcard
SMB[SeeSamba,SMB.]
smb.conffile
smbclientutility2nd3rd
smbddaemon2nd3rd
smbfsfilesystem
smbpasswdfile
smbstatusutility2nd
smbtreeutility2nd
smbusersfile
Smiley
SmoothWall,Linuxrouterdistribution
SMTP2nd3rd
Snap,window
SNAT
Sneakernet
Sniff
snortutility
sofilenameextension2nd
SOArecord,DNS
soc.singlesnewsgroup
Socket
about
UNIXdomain
SOCKS
Softlink[SeeSymbolic,link.]
Software
add
bug
free,definition
installing
keepup-to-date
package
add
information
remove
terminationsignal
upgrading
Sort
sortutility2nd3rd4th5th
sourcebuiltin
Sourcecodemanagement
Sourcerepository
SPACE2nd
Spam
SpamAssassin
whoisand
spamddaemon2nd
Sparsefile
Spawn[SeeFork.]
Special
character
*
?
[]
defined2nd
filenamegeneration
Heredocument
pathnameexpansion
quoting2nd
regularexpressions
standardinput
file
about2nd
block
character
devicefile
parameters,shell2nd
Speed,Internet
spell_checkshellscript
Spinner
splintutility
Splithorizonserver,DNS
Splitting,word
Spontaneousprocess
Spoofing,IP
Spool
spooldirectory2nd
SQL
Squarebracket
test
SquirrelMail
srcdirectory2nd
srputility
sshdirectory
sshutility2nd3rd4th5th6th7th8th9th10th11th[Seealso
OpenSSH.]
ssh-keygenutility
ssh_configfile
ssh_known_hostsfile2nd3rd
sshddaemon2nd
sshd_configfile
SSL
Apache
email
security
st0file
Stack
defined
directory,manipulation
LIFO
PAM
Stallman,Richard
Stand-alonecomputer
Standard
directoriesandfiles
error2nd3rd4th5th
exec
filedescriptor2nd
shellscript
trap
input2nd
exec
filedescriptor2nd
pipe(|)
redirect
specialcharacter
output2nd
append
exec
filedescriptor2nd
pipe(|)
redirect2nd
Standards
FHS
FreeStandardsGroup
FSG
FSSTND
LinuxFilesystemHierarchyStandard
LinuxStandardBase
LSB
OpenPGPMessageFormat
optionhandling
STARTTLS,security2nd
Startupfile2nd
.bash_loginfile
.bash_logoutfile
.bash_profile2nd
.bashrc2nd3rd
.cshrc
.inputrc
.login
.logout
.profile2nd3rd
.toprc
/etc
bashrc2nd
profile2nd3rd
bash
BASH_ENVvariable
checkforproblems
ENVvariable
startxutility2nd
statutility
stat()systemcall
statddaemon
StaticIPaddress
Staticallylinkedlibrary
Status
exit
line
stdio.hCheaderfile
Stickybit
Stopaprogram
Stoppingajobusingthesuspendkey
straceutility
Streamingtape
Streams[SeeConnection-orientedprotocol.]
String
comparing
doublequotationmarks
findingusinggrep
patternmatching(bash)
Stroustrup,Bjarne
Structure,data
StructuredQueryLanguage[SeeSQL.]
sttyutility2nd
Stylesheet[SeeCSS.]
suutility2nd3rd4th
Subdirectory2nd
Subdomain
Subnet2nd
address
mask2nd
number
specifying
Subpixelhinting
Subroutine[SeeProcedure.]
Subshell2nd3rd
Substitution
command
parameter
sudoutility
sudoersfile
SunMicrosystems2nd3rd
Superblock
Supercomputers
Superserver[Seexinetddaemon.]
Superuser2nd
becoming
defined
explained
multiusermode
password
password,changingauser's
PATHvariable
PATH,andsecurity
powers
privileges
prompt
setuid
single-usermode
suutility
sudoutility
Suspendkey2nd3rd4th5th
SVID[SeeSystem,VInterfaceDefinition.]
Swap2nd
filesystem2nd
RAM,and2nd
space
swaponutility
swatutility
swatchutility
Switch[SeeNetwork,switch.]
switchdeskutility
Switchinghub2nd
sylpheedutility
Symboltable
Symbolic
constant
debugger
hostname
link2nd3rd4th5th
creatingusingln
deletingusingrm
symlink[SeeSymbolic,link.]
Symmetrickeyencryption
syncutility
Syntax,commandline
sysfile
sysconfig
about
hwconffile
rhn/up2datefile
sysctlutility2nd
sysctl.conffile
syslogfile
syslogutility
syslog.conffile2nd
syslogddaemon2nd3rd4th5th
System
administration
atutility
authconfigutility
backupfiles
bug
chkconfigutility
client,specifying
communicatewithusers
configurationfilerules
consolehelperutility2nd
crontabutility
disableutility
dmesgutility2nd
dumputility
e2labelutility
edquotautility
enableutility
exportfsutility
file:backup
file:growing
filesystem:integrity
filesystem:mountremote
filesystem:repair
freespace,disk
fsckutility2nd
gdmsetuputility
group,add
groupaddutility
groupdelutility
groupmodutility
haltutility2nd3rd
host,specifying
hosts.allowfile
hosts.denyfile
initscripts
initutility2nd
KDE
Kickstartutility
killbuiltin2nd
killallutility
kudzuutility
loginproblem
log,machine
logs,display
logwatchutility
lpadminutility
lpinfoutility
lsofutility
memtest86+utility
mkfsutility
moreinformation
mountremotefilesystem
mountutility
mouse,configure
multiusermode
multiuser/graphicalmode
partedutility
password,modify
pidofutility
poweroffutility
problems
psutility2nd3rd4th
quotautility
quotaonutility
rebootutility
rejectutility
reports
rescuemode
restoreutility
rhn-applet-guiutility
rpcinfoutility
rpmutility
runlevels
scheduletasks
SELinux
serviceutility
setuidfiles,finding
shutdownutility
single-usermode2nd
slowsystem
suutility
subnet,specifying
syncutility
syslogddaemon
systemdoesnotboot
telinitutility
tools
toputility
Trojanhorse
troublealias
tune2fsutility2nd
umaskbuiltin
umountutility2nd
unameutility
up2dateutility2nd
up2date-configutility
user:add2nd
user:cannotlogin
user:gettinginformationto
user:modify2nd
user:remove
user:useraddutility
user:userdelutility
user:usermodutility
user:vmstatutility
user:wallutility
user:wgetutility
user:xinetddaemon
administrator2nd
powers2nd
responsibilities
Superuser
boot
bringdown
bringup
bug
call2nd3rd
bad,trapping
C,from
chmod()
chown()
close()
creat()
defined2nd
device,raw
exec()2nd
exit()
filesystemoperations
fork()2nd3rd4th
gethostbyname()
getpid()
getppid()
kill()
lseek()
manualsection
nice()
open()
processcontrol
read()2nd
sleep()
stat()
tracingwithstrace
unlink()
wait()
write()2nd
console2nd3rd
crash
dataless2nd
diskless
doesnotboot
errormessages
initialization,customize
loggingin
logs
maintenance
messages2nd
mode
operation
poweringdown
programmer
reboot2nd
reports
rescuemode
security
shutdown2nd
single-user
system-config-nfsutility
VInterfaceDefinition
VUNIX
well-maintained
systemservicesdatabase
system-config-bindutility
system-config-bootutility
system-config-dateutility
system-config-displayutility
system-config-httpdutility
system-config-keyboardutility
system-config-kickstartutility
system-config-languageutility
system-config-lvmutility
system-config-mouseutility
system-config-netbootutility
system-config-networkutility
system-config-network-cmdutility
system-config-nfsutility
system-config-printerutility
system-config-rootpasswordutility
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
T-1line
T-3line
TABkey
Table,hash
tabs.cprogram
tailutility2nd
talkutility2nd
talk.politicsnewsgroup
talkddaemon
Tanenbaum,Andrew2nd
Tape
archive[Seetarutility.]
device2nd
mtutility
nonrewinding
streaming
tarfile
tarutility2nd3rd4th
tar.bz2filenameextension
tar.gzfilenameextension
tar.Zfilenameextension2nd
Tarball
Targetfile,make
Taskbar,KDE
tbzfilenameextension
TCShell
Tcl/Tk
TCP
TCPwrappers
TCP/IP2nd
tcsh
teeutility
Teletypewriter
telinitutility2nd
telnetutility2nd3rd4th5th6th
telnetddaemon2nd
Temporaryfile
Tera-
TERMsignal
TERMvariable2nd3rd
Termcap
termcapfile
Terminal
ASCII
character-based
console
emulator
GNOME2nd
KDE2nd
telnet
failsafe
file
interruptsignal
name
ansi
linux
vt1002nd
vt102
vt220
xterm
pseudo
ServerProject,Linux
specifying
standardinput
standardoutput
X
Terminateaprogram
Terminfo
terminfodatabase
terminfodirectory
Ternaryoperator2nd
testbuiltin2nd3rd4th5th6th7th8th
testutility
testparmutility
testprnsutility2nd
Text
box
echo
file
tftputility
tftpddaemon
tgzfilenameextension
Theme
Theme,desktop2nd
thencontrolstructure2nd3rd
Thicknet2nd
Thinnet2nd
Thompson,Ken2nd
Thread
reentrantcode
safe[SeeReentrantcode.]
Three-fingersalute
Thumb
tiffilenameextension2nd
tifffilenameextension2nd
Tildeexpansion2nd3rd
Tiledwindows
timebuiltin
Timetolive[SeeTTL.]
timeddaemon
tinutility
Titlebar
TkCVSutility
TLS,security
tmpdirectory2nd
Toggle
Token2nd
Tokenringnetwork
Toolbar
defined
Extra,Konqueror
illustration
Konqueror2nd
Nautilus
Tooltip2nd
Topofform
toputility2nd
Top-downdesign
torrentfilenameextension
Torrent,BitTorrent
torrentinfo-consoleutility
Torvalds,Linus2nd3rd4th5th
touchutility2nd
tputbuiltin
trutility2nd3rd
tracerouteutility
traceroute6utility
Tracker,BitTorrent
Transactionssignatures,DNS[SeeDNS,TSIG.]
Transferrate,network
Transientwindow
TransmissionControlProtocol[SeeTCP.]
TransmissionControlProtocol/InternetProtocol
[SeeTCP/IP.]
TransportLayerSecurity[SeeTLS,security.]
trapbuiltin2nd3rd
Treachery,securitytools
Treestructure
tripwireutility2nd
Trojanhorse2nd3rd
Trolltech
Troubleshooting,DNS
trueutility
Trustedhost
tsetutility
TTL
TTL,DNS
TTY[SeeTeletypewriter.]
ttyfile
ttyutility
tune2fsutility2nd
Tunneling
Tunneling,OpenSSH
Tutorial
FTP
Usingvimtocreateandeditafile
Twistedpaircable
txtfilenameextension2nd
typebuiltin2nd
Typeoffile,displayusingls
Typefaceconventions
typescriptfile
typesetbuiltin2nd
Typo,correcting
tzfilenameextension
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
U.S.LibraryofCongress
UCE[SeeSpam.]
udevutility
UDP2nd
UDP/IP
ufsfilesystem
ufsdumputility
UID
effective
passwdfile,in
ulimitbuiltin
umaskbuiltin2nd3rd
umountutility2nd3rd4th
umsdosfilesystem
unaliasbuiltin2nd
unameutility
uncompressutility
Undecillion
Undeclaredvariable
Unicastpacket2nd
Unicastvs.broadcast
Unicode
uniqutility
Uniquefilename2nd
UniversityofIllinois
UNIX
BourneShell
domainsocket
philosophy
printing,traditional
SystemV2nd
SystemVInterfaceDefinition[SeeSystem,V
InterfaceDefinition.]
unix2dosutility2nd
unlink()systemcall
Unlockview,Konqueror
Unmanagedwindow
Unmountabusyfilesystem
Unpackarchivefileusingtar
unsetbuiltin2nd3rd
Unshieldedtwistedpair[SeeUTPcable.]
untilcontrolstructure
unziputility
up2dateutility2nd
up2date-configutility
updatecommand(cvs)
updatedbutility2nd
Upgrade[SeeRedHat,EnterpriseLinuxversus
FedoraCore.]
Upgradingsoftware
upsutility2nd
uptimeutility
Uptime,displayusingw
urandomfile
URI
URL2nd
Usagemessage2nd3rd4th5th
Usenet2nd
User
accounts,manage
add2nd
authentication
cannotlogin
communication,network
createdvariable2nd
DatagramProtocol[SeeUDP.]
finger
ID[SeeUID.]
interface2nd
map,Samba
mode
modify2nd
name[SeeUsername.]
name,Samba
nfsnobody
nobody,Samba
privategroups
remove
root[SeeSuperuser.]
Samba
Superuser[SeeSuperuser.]
w
who
user_listfile(vsftpd)
useraddutility
userdelutility
usermodutility
Username2nd3rd
Userspace
usrpartition
UTC
Utility
accept
accton
adduser
AIDE2nd3rd
amanda
Anaconda
anacron
apm
apropos2nd3rd4th
aspell2nd
at2nd3rd
authconfig
automount
basename2nd3rd
beagle
bison
BitTorrent[SeeBitTorrent.]
builtinversus
bunzip22nd
bzcat
bzip22nd3rd
bzip2recover
cancel
cat2nd3rd4th5th6th
chkconfig
chkrootkit
chmod2nd
chsh
clear
compress2nd
consolehelper2nd
cp2nd3rd
cpio2nd
crack
crontab2nd
cut
cvs
date2nd
ddd2nd
depmod
df
dhclient
diff2nd
dig2nd3rd4th
disable
dmesg2nd3rd
dos2unix2nd
DragonSquire
dsniff
dump
e2label
edquota
egrep
emacs
enable
ethereal
Evolution2nd
exportfs2nd
fdformat
fdisk[Seepartedutility.]
file2nd3rd
find2nd3rd4th
findusingwhereis
findusingwhich
finger2nd3rd4th5th
flex
fsck2nd3rd4th
ftp2nd3rd4th
fuser
fwtk
gaim
gawk2nd
gcc2nd
gcc(GNU)
gdb2nd
gdm
gdm(GNOME)
gdmsetup
getty
gnome-control-center
gnome-font-properties
gnome-terminal
gopher
gprof
grep2nd3rd4th5th6th7th8th
groupadd
groupdel
groupmod
groups
grub
gunzip
gzip
halt2nd3rd
head
host2nd
hostname2nd
hping
id
info2nd3rd
init2nd3rd4th5th6th7th
insmod
ipchains
iptables
iptables-restore
iptables-save
iwconfig
JohntheRipper
jwhois
kcolorchooser
kcron
kdbg
kdm(KDE)
kerberos2nd
kfind
Kickstart
killall
klipper2nd
konsole
kudzu2nd
L6
ld
ld-linux.so
ldd2nd
less2nd3rd4th5th
lids
links2nd
lint
ln2nd3rd
locate2nd
lock
login2nd
logresolve
logrotate
logwatch
lp
lpadmin
lpinfo
lpq2nd
lpr2nd3rd4th
lprm2nd
lpstat2nd
ls2nd3rd4th5th6th7th
lsmod
lsof
lynx
mail2nd
mailq
mailstats
make2nd3rd4th
makedbm
makemap
makewhatis2nd
man2nd3rd
md5sum
memtest86+
mesg
mingetty2nd3rd
mkdir2nd3rd
mkfifo
mkfs2nd3rd4th5th
mkswap
modinfo
modprobe
more2nd3rd
mount2nd3rd4th5th6th
mt
mv2nd3rd
mxgdb
names,typeface
nessus
net
netuse(Windows)
netview(Windows)
netcat
netstat
network2nd
newaliases
nisdomainname
nmap
nmblookup2nd
nn
nologin
od
OPIE2nd
option
parted
passwd2nd3rd4th
pidof
pinfo
ping2nd3rd4th
ping6
pirut
portmap2nd
poweroff
praliases
printmgr
procmail
ps2nd3rd4th5th
pstree
pwd2nd
qmail
quota
quotaon
rbac
rcp
readnews
reboot
reject
reset
restore
rhn-applet-gui
rlogin
rm2nd3rd4th5th
rmdir
rmmod
rn
rndc
rpcinfo2nd
rpm
rsh2nd
runlevel
ruptime
S/Key
saint
samhain2nd
sara
scp2nd3rd[SeealsoOpenSSH.]
script
sed
service
sestatus
setserial
sftp
sha1sum
showmount
shutdown2nd
smbclient2nd3rd
smbstatus2nd
smbtree2nd
snort
sort2nd3rd4th5th
splint
srp
ssh2nd3rd4th5th6th7th8th9th10th11th[Seealso
OpenSSH.]
ssh-keygen
startx2nd
stat
strace
stty2nd
su2nd3rd4th
sudo
swapon
swat
swatch
switchdesk
sylpheed
sync
sysctl2nd
syslog
system-config-bind
system-config-boot
system-config-date
system-config-display
system-config-httpd
system-config-keyboard
system-config-kickstart
system-config-language
system-config-lvm
system-config-mouse
system-config-netboot
system-config-network
system-config-network-cmd
system-config-nfs
system-config-printer
system-config-rootpassword
system-config-samba
system-config-securitylevel2nd3rd
system-config-services
system-config-soundcard
system-config-users
system-logviewer
system-switch-mail
tail2nd
talk2nd
tar2nd3rd4th
tee
telinit2nd
telnet2nd3rd4th5th6th
test2nd3rd4th5th
testparm
testprns2nd
tftp
tin
TkCVS
top2nd
torrentinfo-console
touch2nd
tr2nd3rd
traceroute
traceroute6
tripwire2nd
true
tset
tty
tune2fs2nd
typeset
udev
ufsdump
umount2nd3rd4th
uname
uncompress
uniq
unix2dos2nd
unzip
up2date2nd
up2date-config
updatedb2nd
ups2nd
uptime
useradd
userdel
usermod
uucp
vimtutor
vmstat
w2nd
wall2nd
wc
webalizer
wget
whatis2nd
whereis2nd
which
who2nd3rd4th5th6th
whois
write2nd3rd
XWindowSystem
xargs
xclock
xev
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
varfilenameextension
varpartition
Variable2nd
braces
completion
defaultvalue,assign
displayerrormessage
environment
expansion2nd
exported
global2nd
keyword
local2nd
modifiers
naming
readonly
remove
shell
substitutedefaultvalue
substitution
undeclared
usercreated2nd
VeriSign
vfatfilesystem
VG[SeeLVM,VG.]
vibashcommandlineeditor
Videocard,configure
Viewpane,Nautilus
View,Konqueror2nd
Viewport[SeeWorkspace.]
vim
bashcommandlineeditor
casesensitivity
Commandmode
correctamistake2nd
createafile
dcommand
ddcommand
deletetext
editafile
endasession
entertext
exitfrom
exit,emergency
gettingstarted
Inputmode2nd
inserttext
LastLinemode
movethecursor
Normalmode[Seevim,Commandmode.]
pagebreak
quit
replacementstring
safeditscript
specialcharacters
starting
terminalspecification
ucommand
undochanges
Workbuffer
xcommand
ZZcommand
vimtutorutility
Virtual
console2nd
filesystem
memory
privatenetwork[SeeVPN.]
virtusertablefile2nd
Virus2nd
VLAN
vmstatutility
Volumegroup[SeeLVM,VG.]
Volumelabel2nd
VPN2nd
vsftpd[SeealsoFTP,account.]
chrootjail
configurationfile
connectionparameters
display
downloadingfiles
files
log
loggingin(users)
messages
PASVconnections
PORTconnections
prerequisites
security
server
stand-alonemode2nd
starting
testing
uploadingfiles
vsftpd.conffile
vsftpd.logfile
vt100terminal2nd
vt102terminal
vt220terminal
Vulcandeathgrip
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
wutility2nd
W2K
W3[SeeWorldWideWeb,about.]
W3C
waitbuiltin
wait()systemcall
Wakeup,process
wallutility2nd
WAN2nd3rd4th5th
WAP2nd
wcutility
Web[SeealsoWorldWideWeb,about.]
crawler
ring
shortcuts,Konqueror
webalizerutility
Webmail
Weissman,Terry
wgetutility
whatisdatabase2nd
whatisutility2nd
wheelgroup
whereisutility2nd
whichutility
whilecontrolstructure2nd3rd4th
Whitespace
commandline
defined
quoting
whoami
whoutility2nd3rd4th5th6th
whoisutility
whosshellscript
whosonshellscript
Wi-Fi
Wideareanetwork[SeeWAN.]
Widget
Wildcard[SeealsoMetacharacter.]
Window
active
cascading
clipboard
ConfigurePanel
contextmenu
cutandpaste
cycling
decorations
defined
file
focus
click-to-focus
enter-onlyfocus
explicitfocus
focus-follows-mouse
focus-strictly-under-mouse
focus-under-mouse
inputfocus
pointtogivefocus
sloppyfocus
ignored
inputfocus2nd
List,GNOME
Locationbar
manager2nd
about
Metacity
menubar
minimize
mousebuttons,remap
Operationsmenu
resizing
root
scrollbar
shading
share[SeeSamba,share.]
snap
thumb
tiled
titlebar
toolbar
transient
typical
unmanaged
Windows
convertfiles
dual-bootsystem
filenamelimitation
integration[SeeSamba.]
netuseutility(Samba)
netviewutility(Samba)
networks,browsingusingSamba
privilegedport
Samba[SeeSamba.]
sharesfromLinux,accessingusingSamba
shares,connectingtousingSamba
shares,displayingusingSamba
shares,mounting
winprinter
WINS
Wipingafile
Wire[SeeCable,Category6.]
Wireless[SeeNetwork,wireless,accesspoint.]
Word
defined2nd3rd
deleting
designator
erasekey
parseacommandline
splitting(bash)
Workbuffer
Workbuffer,vim
Workingdirectory
changeusingcd
defined
executeafilein
PATH
relativepathnamesand
significanceof
versushomedirectory
Workspace
defined
GNOME
Konqueror
Switcher,GNOME
Workstation2nd
WorldWideWeb
about
Berners-Lee,Tim
CERN
Consortium
Enquire
HTML
hypermedia
hypertext
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
X
Consortium
server
terminal2nd
XWindowSystem2nd3rd
application(client)
client
clientandserver
colordepth
displaynumber
DISPLAYvariable
display,accessto
emergencyexit
event
exitingfrom
freedesktop.orggroup
history
IDstring
layers
library
Metacitywindowmanager
mouse
buttons,remap
left-handed
right-handed
wheel
multipleXservers
program
remotecomputingandlocaldisplays
resolution,changing
screennumber
server
serverprocess
setup,system-config-displayutility
stack
starting2nd
utilities
clients
startx
xclock
xhost
xmodmap
windowmanager
Xstack
X.orgversusXFree86
X11forwarding,OpenSSH2nd3rd4th
X11R6.6
X11R7.0
xevutility
XFree86versusX.org
Xinerama
Xlib
X.org
X11directory2nd
X11R6.6
X11R7.0
xargsutility
xclockutility
XDMCP
xDSL
xevutility
xfsfilesystem
xhostutility
Xinerama
xinetddaemon2nd3rd4th5th6th
xinetd.conffile2nd
xinetd.ddirectory2nd
XINU
Xlib
XML
xmodmaputility
xorgfile
Xorgutility
Xremote
xrnutility
XSM
xtabfile2nd
xtermterminalname
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N]
[O][P][Q][R][S][T][U][V][W][X][Y][Z]
yfilenameextension
YellowPages
yp.conffile
ypbinddaemon
ypbind-mtdaemon
ypinitutility
yppasswdutility
yppasswdddaemon
yppasswddfile
ypserv.conffile
ypwhichutility
ypxfrutility
ypxfrddaemon
yum
automaticallyrunning
configurationfile
installoption
removeoption
updateoption
using
yum.conffile
yum.repos.ddirectory