· 10 years ago · Dec 14, 2015, 09:54 AM
1Shell configuration files are scripts that execute when a shell starts. The shell type determines which shell configuration files are executed. Shell types include:
2• Login shells run when the system starts and is only using the Text User Interface (TUI) as the user interface.
3• Non-login shells run when the system boots into a Graphical User Interface (GUI) and a user starts a terminal session.
4 The following are the names of the files used when the shell starts:
5Configuration File Description Used by shell type
6~/.bashrc ~/.bashrc stores shell preferences for individual users. non-login
7(login on some distributions)
8/etc/profile /etc/profile stores system-wide configuration commands and is used primarily to set environment variables. login
9~/.bash_profile ~/.bash_profile stores shell preferences for individual users. login
10~/.bash_login ~/.bash_login stores commands that execute when a user logs in. login
11~/.profile ~/.profile stores configuration preferences similar to /etc/profile, but for individual users. login
12~/.bash_logout ~/.bash_logout stores commands that execute when a user logs out. login
13Be aware of the following:
14• Login shells execute the configuration scripts they use in the following order:
151 /etc/profile
162 ~/.bash_profile (If this file is found, the shell does not look for additional configuration script files)
173 ~/.bash_login (If this file is found, the shell does not look for additional configuration script files)
184 ~/.profile (This file only executes in the absence of the preceding two)
19The su -l command switches to a user into a login shell; however, without the -l option, a non-login shell is started.
20
21Shell configuration files are scripts that execute when a shell starts. The shell type determines which shell configuration files are executed. Shell types include:
22• Login shells run when the system starts and is only using the Text User Interface (TUI) as the user interface.
23• Non-login shells run when the system boots into a Graphical User Interface (GUI) and a user starts a terminal session.
24 The following are the names of the files used when the shell starts:
25Configuration File Description Used by shell type
26~/.bashrc ~/.bashrc stores shell preferences for individual users. non-login
27(login on some distributions)
28/etc/profile /etc/profile stores system-wide configuration commands and is used primarily to set environment variables. login
29~/.bash_profile ~/.bash_profile stores shell preferences for individual users. login
30~/.bash_login ~/.bash_login stores commands that execute when a user logs in. login
31~/.profile ~/.profile stores configuration preferences similar to /etc/profile, but for individual users. login
32~/.bash_logout ~/.bash_logout stores commands that execute when a user logs out. login
33Be aware of the following:
34• Login shells execute the configuration scripts they use in the following order:
351 /etc/profile
362 ~/.bash_profile (If this file is found, the shell does not look for additional configuration script files)
373 ~/.bash_login (If this file is found, the shell does not look for additional configuration script files)
384 ~/.profile (This file only executes in the absence of the preceding two)
39The su -l command switches to a user into a login shell; however, without the -l option, a non-login shell is started.
40-----
41
42The Linux shell is the Command Line Interface (CLI) or Text User Interface (TUI) that administrators use to control a Linux operating system. Users and programs use the shell to send commands to the system. A Linux shell, or terminal session, might be opened as needed from an applications menu inside a Graphical User Interface (GUI) session, or the Linux shell might be the sole method used to run the computer.
43You can also use the Ctrl+Alt+F1 key combination to start or switch to the first Linux shell session. It is possible to have multiple shells open at the same time; the key combinations Ctrl+Alt+F2, Ctrl+Alt+F3, through Ctrl+Alt+F6, will each start or switch to the second or third shell, and so on. (The key combination Ctrl+Alt+F7 will switch you back to the GUI session, if one is running.)
44Although most Linux distributions now include a graphical interface, and many administration tools have been converted to a graphical format, many tasks are best performed from the command prompt. In addition, while graphical elements vary between distributions, shell commands are more likely to be consistent between distributions.
45The following table describes many common shell types:
46Shell Type Description
47
48
49bash The Bourne-again shell (bash) is the standard shell used in most Linux computers. It uses commands similar to a UNIX shell. Bash includes features such as:
50• Command completion when pressing the tab key
51• Command history
52• Improved arithmetic functions
53sh The Bourne shell is an earlier version of the Bash shell, and is similar in many ways. Sh is the original shell created by Steve Bourne.
54ksh The Korn shell was developed by David Korn. Ksh has scripting features not found in bash.
55csh The C-shell uses syntax similar to syntax used in the C programming language.
56tcsh The tcsh shell is an improved version of csh. It offers command line editing and completion features not available with csh.
57Despite their differences, all shells share some common characteristics:
58• A Linux system can use multiple shells at the same time.
59• A list of shells is stored in the /etc/shells file.
60• All shells are interfaces with the kernel, separate and distinct from it.
61• Shells are run both interactively by end users and automatically by the computer's processes.
62• Shells can run within one another either interactively when a user starts a second shell from the first shell's command line, or automatically by scripts or programs.
63• Shells use configuration files to establish their operating environments.
64
65
66An environment variable is a setting that the operating system or programs working in the operating system access. Environment variables make up the user environment. Be aware of the following details:
67• The standard for writing variables names (called variable identifiers) is to use upper case (e.g., SHELL and EUID)
68• Changing environmental variables from the defaults result in user-defined variables.
69• A user-defined variable applies only to the current session; export the user-defined variables so they apply to child sessions.
70• Add user-defined variables to the shell configuration files to make them persistent.
71
72The table below lists common environment variables:
73Variable Description
74BASH The location of the bash executable file
75SHELL The user's login shell.
76CPU The type of CPU.
77DISPLAY Location where X Windows output goes.
78ENV The location of the configuration file for the current shell.
79EUID The ID number of the current user.
80HISTFILE The filename where past commands are stored.
81HISTSIZE The number of past commands that HISTFILE stores for the current session.
82HISTFILESIZE The number of past commands that HISTFILE stores for the multiple sessions.
83HOME The absolute path of the user's home directory.
84HOST The name of the computer.
85HOSTNAME HOSTNAME is identical to HOST, but used on certain distributions.
86INFODIR The path to the computer's information pages.
87LOGNAME The user name of the current user.
88MAIL The path to the current user's mailbox file.
89MANPATH The path to the computer's man pages.
90OLDPWD The path of the directory the user was in prior to the current path.
91OSTYPE The type of operating system. Usually this is Linux.
92PATH The directory prefixes used to search for programs and files.
93• Use a colon to separate entries in the PATH variable.
94• Do not include a period (.) in the PATH variable. A period indicates that the working directory is in the path, and this poses a security risk.
95PS1 The characters the shell uses to indicate normal user ($), root user (#) and similar items.
96PWD The path of the current working directory.
97LANG The language the operating system uses.
98PAGER Used by the man command to specify the program in which to display man pages.
99The table below lists the most common environment variable commands:
100Use... To... Examples
101echo $variable View the variable's value. echo $SHELL displays the current shell's path.
102env Display the values for environment variables applied to child sessions.
103set Set shell environment variables. Without options, set displays the set environment variables for the system.
104unset variable Remove an environment variable. unset HOMEDIR removes the HOMEDIR variable.
105VARIABLE=value Create a user-defined environment variable.
106To append information to an environment variable, put the current variable in the command. For example, PATH=$PATH:/bin/additionalpath. HOMEDIR=/projects gives the HOMEDIR variable a value of /projects.
107export variable Export a user-defined variable to make it available to child sessions. export HOMEDIR makes the HOMEDIR user-defined variable available to child sessions.
108PATH=$PATH:/bin/special ; export PATH appends a directory to PATH and immediately exports the variable.
109-----
110An alias is a custom command that performs a specific action. Most distributions have aliases that are invoked at startup; however, an alias can be invoked from the shell. Be aware of the following:
111• Aliases defined with the alias command are not persistent across reboots.
112• Add the alias to /etc/profile or home/user/.bashrc to make them persistent across reboots.
113The following table describes the commands that create and remove aliases.
114Use... To... Example
115alias Display the currently defined aliases on the system.
116alias name Create a custom command that:
117• Adds additional functionality to an existing command.
118• Performs multiple functions.
119When creating the alias, encapsulate the command(s) with quotation marks or apostrophes. alias ls='ls --ignore=*.elf' prevents the ls command from displaying .elf files even if ls -a is used.
120alias securebackup='cp ./*.* /dev/st0/*.*;shred -fuvz ./*' creates a command that copies all files to the storage tape, then shreds the original files.
121alias forcelogout="killall /usr/bin/Xorg" creates a shortcut kills all Xserver processes.
122unalias name Remove an alias. unalias ls removes all aliases specified for the ls command and places it back in its original state.
123unalias forcelogout deletes the forcelogout alias if it exists.
124——
125Administrators often use the following methods to create, send, or gather information on a Linux system:
126Method Description
127Redirection Redirection directs standard input, output, and error streams from and to locations other than the default. Be aware of the following redirection details:
128• By default, the Linux system classifies information with the following file descriptors:
129 Standard input (stdin) comes from the keyboard. In redirection, 0 represents stdin.
130 Standard output (stdout) displays on the monitor. In redirection, 1 represents stdout.
131 Standard errors (stderr) display on the monitor. In redirection, 2 represents stderr.
132• Linux commands use the greater-than symbol (>) to show redirection of output, the less-than symbol arrow (<) to indicate redirection of input, and the double greater-than symbol (>>) to append the output to another file or command.
133• The tee command reads from standard input and writes to standard output and files.
134Piping Piping directs the output of one command into the input of another command. Pipes:
135• Use the pipe symbol (|).
136• Can combine several commands to make a stream.
137The following table shows the results of several redirection and piping commands:
138Example Result
139ls /usr > /tmp/deleteme ls /usr > /tmp/deleteme places the list of files in the /usr directory into a file named /tmp/deleteme.
140ls /nonesuch > /tmp/deleteme ls /nonesuch > /tmp/deleteme does not write anything to a file and sends an error message to the monitor '/nonesuch not found'.
141ls /nonesuch 2 > /tmp/deleteme ls /nonesuch 2 > /tmp/deleteme writes the standard error message to a file named /tmp/deleteme.
142ls /bin /nonesuch > /tmp/deleteme ls /bin /nonesuch > /tmp/deleteme writes the contents of the /bin directory to the /tmp/deleteme file, but sends the error message '/nonesuch not found' to the screen.
143ls /bin /nonesuch > /tmp/deleteme 2>&1 ls /bin /nonesuch > /tmp/deleteme 2>&1 directs the standard output to the /tmp/deleteme file, then directs that the standard error messages be sent to the same place as the standard output. Both the list of files in the /bin directory and the error message are written to the file.
144ls /bin /nonesuch 2>&1 > /tmp/deleteme ls /bin /nonesuch 2>&1 > /tmp/deleteme writes the contents of the /bin directory to the /tmp/deleteme file, but sends the error message '/nonesuch not found' to the screen. This is because standard error messages are directed to the same place that standard output goes, but this is before standard output has been directed to the file.
145ls /bin >> /tmp/deleteme ls /bin >> /tmp/deleteme appends the list of files from the /usr directory on to the end of the /tmp/deleteme file.
146sort < unordered_file.txt > ordered_file.txt sort < unordered_file.txt > ordered_file.txt takes input from the unordered_file.txt file sends it to the sort command, and then writes a new file named ordered_file.txt.
147cat /usr/wordlist1 /usr/wordlist2 | sort Sends the output of the cat command, the contents of wordlist1 and wordlist2, to the input of the sort command. The result is a sorted list of the combined contents of wordlist1 and wordlist2.
148cat /usr/wordlist1 /usr/wordlist2 | mail jdoe Mails the combined list of words in wordlist1 and wordlist2 to the user jdoe.
149ls /bin | sort | mail jdoe Lists the contents of /bin then sorts the combined contents and mails them to jdoe.
150cat /usr/wordlist1 /usr/wordlist2 | sort | tee sortedwordlist Lists the contents of wordlist1 and wordlist2 then sorts the combined contents, then sends the results to the monitor and a file named sortedwordlist.
151cat /usr/wordlist1 | tee log.txt Writes to the standard output and the log.txt file.
152-----
153The xargs command reads items from the standard input and breaks up long lists of arguments into smaller, usable lists. Xargs:
154• Makes it easier to pipe input into commands that take arguments.
155• Overcomes a 128 KB shell command size restriction in older Linux kernels.
156• Commonly takes input from the following commands:
157 find
158 ls
159 locate
160 grep -l
161The following table describes the common xargs options:.
162Use... To... Examples
163-0 Ignore space names in files find / -print0 -name *.odt | xargs -0 rm deletes all .odt files in the file system, even those with spaces in the file names.
164-I variable Replace the initial argument of a command with the argument from the standard input. find / -name '*.jpg' | xargs -I var1 cp var1 /home/user/Pictures finds all the .jpg files on the computer and copies them into the /home/user/Pictures directory
165
166-----
167
168The following table describes several basic commands when managing directories:
169Use... To... Examples
170pwd See the present working directory. Shells open to the home directory of the current user. For example, if a user named Fred opened a shell and typed pwd at the prompt, /home/Fred is displayed.
171cd Change the present working directory. cd directory1 changes to a directory named directory1 if it exists in the present working directory. (This is the relative path.)
172cd /home/Fred/directory1 opens directory1 regardless of the present working directory. (This is the absolute path.)
173cd .. changes to the parent directory.
174cd / changes to the root directory.
175ls Display the contents of a directory. Options include:
176• -a displays all directory contents, including hidden content.
177• -l displays a long listing for directory contents, including the owner, modified date, size, and permissions.
178• -R displays the contents of the directory and all sub-directories.
179• -d displays directories but not files.
180• -r reverses the sort order. ls -al displays the long listing of all the contents in the present working directory.
181ls -d only displays the directories.
182ls -R /etc displays all the contents of the /etc directory and all sub-directories.
183mkdir Create a new directory. Use the -p option to create the directories that do not exist. mkdir work_files creates a directory in the present working directory.
184mkdir /home/Fred/work_files creates a directory at the specified path.
185cp -r
186cp -R Copy directories. Copying leaves the source contents (directories and files) intact. cp -r /temp /home/user copies the entire /temp directory with all of its files, sub-directories, and files in the sub-directories to the /home/user directory.
187mv Move or rename directories (and files). Moving directories erases the source directory and places it in the destination. Options include:
188• -f overwrites directory that already exist in the destination directory.
189• -i prompts before overwriting a directory in the destination directory.
190• -n never overwrites files in the destination directory. mv /temp/station ~/doc/ moves station from the /temp directory to the ~/doc directory.
191rmdir Delete an empty directory. rmdir ~/Fred/work_files deletes the work_files directory provided it is empty.
192rm Remove the directory (and file) inode, but not actually delete the data. Options include:
193• -r deletes directories (and all files) in the directories.
194• -f deletes without prompting. rm -rf /home/user/temp deletes the temp directory with all its sub-directories and files without prompting.
195rm -r /home/user/* deletes all directories and files in the /home/user directory.
196
197-----
198The following table describes several basic commands when managing files:
199Use... To... Examples
200touch Create a blank file if the file does not exist, or to update the file's modification and last accessed times if the file exists. touch myfile makes a blank file named myfile.
201cat Display the contents of the file in the shell. This can include displaying multiple files at once. cat myfile displays the contents of the file myfile.
202cat myfile yourfile displays the contents of the file myfile and yourfile together.
203less Display the file one screen at a time.
204• Use the SpaceBar to scroll to the next screen.
205• Use the Up arrow and Down arrow to scroll up and down.
206• Type q to exit. less bigfile displays the contents of bigfile one screen at a time so it can be read.
207head List the first 10 lines of a specified file, by default. The -n option specifies a specific number of lines. head /home/user/myfile lists the first 10 lines of myfile.
208head -n 20 /home/user/myfile lists the first 20 lines of myfile.
209head -n -35 /home/user/myfile displays all lines in myfile, omitting the last 35 lines.
210tail List the last 10 lines of a specified file, by default. Options include:
211• -n specifies a specific number of lines.
212• -f monitors the file. tail /home/user/myfile lists the last 10 lines of myfile.
213tail -n 20 /home/user/myfile lists the last 20 lines of myfile.
214tail -n -15 /home/user/myfile displays all lines in myfile, omitting the first 15 lines.
215file Show the file type. The file command might often be necessary because Linux does not require file extensions. file uses file signatures in:
216• /usr/share/misc/magic
217• /usr/share/misc/magic.mgc
218• /etc/magic file myfile shows whether myfile is a text, data, xml or other type of file.
219cp Copy files. Copying leaves the source file intact. Options include:
220• -f overwrites files that already exist in the destination directory.
221• -i prompts before overwriting a file in the destination directory. cp /temp/document_ab.txt ~/doc/document.txt copies document_ab.txt from the /temp directory to the ~/doc directory and renames the file to document.txt.
222cp /temp/*.txt ~/doc copies all text files from the /temp directory to the ~/doc directory.
223mv Move or rename files (and directories). Moving files erases the source file and places it in the destination. Options include:
224• -f overwrites files that already exist in the destination directory.
225• -i prompts before overwriting a file in the destination directory.
226• -n never overwrites files in the destination directory. mv /temp/document.txt ~/doc/document.txt moves document.txt from the /temp directory to the ~/doc directory.
227mv /temp/*.txt ~/doc/*.txt copies all text files from the /temp directory to the ~/doc directory.
228rm Remove the file (and directory) inode, but not actually delete the data. The -f option deletes without prompting. rm myfile deletes a file in the current directory named myfile.
229rm /home/user/myfile deletes myfile from the /home/user directory regardless of the current directory.
230rm -f /home/user/temp/* deletes all files in the temp directory without promptings.
231shred Deletes the file and overwrites the file information. shred is useful when deleting files that contain proprietary company information or other sensitive data. Options include:
232• -n specifies the times to overwrite. The default is 25 times.
233• -u deletes the inode.
234• -v display the progress of the file deletion.
235• -z overwrites the filename with zeros. shred -u -z companysecrets.txt deletes the file companysecrets.txt, overwrites the file with random information, then leaves zeros in place of the file.
236lsattr List file attributes.
237• -R recursively list attributes of directories and their contents.
238• -V displays the program version.
239• -a lists all files in directories.
240• -d lists directories like other files, rather than listing their contents.
241• -v lists the file's version/generation number. lsattr /etc/grub/grub.conf lists the attributes of the grub.conf file.
242
243-----
244Links are files that point to another file. When links are accessed, they reference the source file's inode. The inode specifies where a file's data physically exists on a disk. Link types include:
245Type Description
246Hard link A hard link is a duplicate entry in the file system that points to a specific piece of data on the disk drive. A hard link:
247• Creates a duplicate file inode.
248• Is indistinguishable from the original files.
249• Maintains a valid inode for the file data even if the original file is deleted.
250• Has a dash (-) as the first character in the permission string (which is the same for original files). For example, -rwxr-xr-x.
251Symbolic link A symbolic link (also known as a soft link) is a file system entry that points to another file system entry, which in turn points to a valid piece of data. A symbolic link:
252• Has a distinct inode.
253• Can work across volumes and file systems.
254• Is similar to shortcuts in the Windows OS.
255• Has a lower-case L (l) as the first character in the permission string. For example, lrwxrwxrwx indicates a symbolic link.
256The table below describes the commands for creating hard links and symbolic links:
257Use... To... Example
258ln source link_name Create links.
259• ln -s creates a symbolic link to a file.
260• ln -b creates backup of a file.
261• ln -i determines the inode for hard or symbolic links.
262• ln (with no options) creates a hard link between files. ln /home/jsmith/project1 /home/edunford/project1 creates an exact copy of /home/jsmith/project1 in /home/edunford/.
263ln -s /home/jsmith/project1 /home/edunford/project1_ln creates a pointer named /home/edunford/project1_ln that points to /home/jsmith/project1.
264ln -s /home/jsmith/project1 /home/edunford/project1_ln creates a pointer named /home/edunford/project1_ln that points to /home/jsmith/project1.
265ln -i displays the inodes for the contents in the present working directory.
266ln -b /home/jsmith/file1 /bup copies file1 as file1~ in /bup.
267cp source link_name Copy files and create links.
268• cp -l creates hard links rather than copying the files.
269• cp -s creates symbolic links rather than copying the files. cp -l /home/jed/fil1 /home/esam/proj1 creates an exact copy of /home/jed/fil1 in /home/esam/.
270cp -s /home/mkon/text /home/ytew/text_ln creates a symbolic link named /home/ytew/text_ln that points to /home/mkon/text.
271
272-----
273The Filesystem Hierarchy Standard (FHS) governs the unified file system for Linux systems by defining a standard set of directories, subdirectories, and files. FHS is a subset of the Linux Standards Base (LSB) which is an organization and a set of guidelines for promoting a set of standards to increase Linux distribution compatibility.
274Directory Description
275/ The / character represents the root directory of the Linux system. All directories are below the / (root directory) of the system.
276/bin The /bin directory contains binary commands that are available to all users.
277/boot The /boot directory contains the kernel and bootloader files.
278/dev The /dev directory contains device files that represent the devices used by the system, such as a hard drive, mouse, and printer.
279/etc The /etc directory contains configuration files specific to the system.
280/home The /home directory contains by default the user home directories.
281/lib The /lib directory contains shared program libraries and kernel modules.
282/media The /media directory contains the /cdrom and /floppy directories.
283/mnt The /mnt directory is an empty directory, and is often used for temporarily mounted filesystems.
284/opt The /opt directory contains the additional programs on the system.
285/proc The /proc directory contains information about the system state and processes.
286/root The /root directory is the root user's home directory. Do not confuse /root with the root of the system (/).
287/sbin The /sbin directory contains system binary commands.
288/srv The /srv directory contains files for services such as HTTP and FTP servers.
289/sys The /sys directory contains the sysfs virtual filesystem which displays information about devices and drivers.
290/tmp The /tmp directory contains temporary files created by programs during system use.
291/usr The /usr directory contains system commands and utilities.
292/var The /var directory contains data files that change constantly. Standard subdirectories include:
293• /var/mail (holds e-mail in boxes)
294• /var/spool (holds files waiting for processing, such as print jobs or scheduled jobs)
295• /var/www (holds www or proxy cache files)
296
297-----
298Use the following commands to find file locations:
299Use... To... Examples
300find Search through all files based on the file system by name, file size, time created, and other options. Be aware of the following find options:
301• -name locates a file or directory by name in a specific path. When using -name:
302 Enclose name strings in single quotes.
303 Use wildcards for partial names.
304 Use -iname for case insensitive.
305• -user finds files owned by a specific user.
306• -size finds files of a specific size. Use the following options:
307 c for bytes
308 k for kilobytes
309 M for megabytes.
310• -mtime finds files last modified before or after a specified number of days ago.
311• -type [fd] specifies whether to find files or directories.
312• -maxdepth specifies how many levels down to search.
313• -print0 finds filenames with spaces.
314• -o specifies the or parameter when searching with multiple criteria.
315• . (period) specifies the search locations as the current directory and subdirectories. find /user/home -name '*.txt' finds all plain text files in the /user/home directory.
316find / -name '*paper*' looks through the entire directory for any folder or directory name with the term paper in it, such as termpaper.odt or wallpaper.jpg.
317find /user/home -size -300k finds all files in the /user/home directory smaller than 300K.
318find /user/home -size +300k finds all files in the /user/home directory larger than 300K.
319find /user/home -mtime -5 finds all files in the /user/home directory modified within the last five days.
320find / -type f -name '*paper*' finds only files with the string paper in the name.
321find / -type d -name '*paper*' finds only directories with the string paper in the name.
322find -maxdepth 3 / -name '*.txt' finds text files three directory levels down from the root directory.
323find -print0 -name '*.txt' finds myreport.txt and 'my report.txt'. Without the -print0 option, 'my report.txt' is not listed.
324locate To search an index file for specific parameters, locate:
325• Is much faster than find.
326• Searches /var/log/locatedb as the index file.
327• Uses the updatedb command to update the file index. (/etc/updatedb.conf is the configuration file for updatedb)
328• Searches from the root (/) directory if no path is specified.
329• Finds all files that contain the specified string without using wildcards.
330• Does not by default verify that the file exists if its file index is outdated.
331• Does not display files created after the last time the file index was updated.
332• Does not search for files by attribute.
333Be aware of the following locate options:
334• -c counts the number of entries rather than list them.
335• -e lists files only after verifying that they exist.
336• -i ignores case.
337• -l limits the number of files listed.
338• -b searches for the string in only file or directory base names. updatedb updates the index file, /var/log/locatedb.
339locate /user/home paper locates all files with the string paper as any part of the file name or directory path under the /user/home directory.
340locate lib locates all files with the string lib anywhere in the file name or directory path.
341locate -c lib counts the number of files with the string lib. For example 46512.
342locate -e .odt verifies that all .odt files listed in the file index actually exist before it lists them.
343locate -i LibraryFines.csv finds the libraryfines.csv file regardless of case.
344locate -l 25 lib lists only the first 25 files from the file index that contain the string lib.
345locate -b lib displays /var/lib and /user/home/libraryfines.csv but not /var/lib/usbutils/usb.ids
346If the search pattern contains no globbing characters, such as the wildcard character (*), locate behaves as if the pattern begins and ends with a wildcard. For example, searching for paper is the same as searching for *paper*.
347which Display the path to a command and determine whether a package is installed. which ls shows the path to the ls binary (executable) file.
348which photorec shows the path to the photorec binary file if photorec is installed. If the command does not display a path, then the photorec utility is not installed.
349whereis Display the path to the binary files, the manual pages, and the source code. Be aware of the following options:
350• -b lists the path to the binary file (similar to which).
351• -m lists the path to the man page files.
352• -s lists the location of the source code.
353• -u lists entries that do not have source code, binary file, and man page locations.
354When no options are specified, whereis shows all available data. whereis -m -u * lists all entries that have no man page location.
355type Display the category of the command. Possible categories include:
356• A built-in shell command
357• A command that the shell calls
358• An aliased command
359• A function
360If a called command has been used recently, the output says that the command is hashed, which means that it is in the shell's hash table. type cd displays cd is a shell built-in.
361type more displays the path to the binary file for more.
362The term file globbing refers to the use of wildcards (e.g., *, *.*, *.txt) to match specific files.
363
364-----
365Grep searches through file text for specific words or character patterns. The following table describes the grep, egrep, and fgrep commands and lists several of their options:
366Use... To... Examples
367grep Search through files for a specified character string. By default grep is context sensitive and displays the string in the context of the line containing the string.
368• -A number prints a specified number of lines following the matching lines.
369• -a searches binary (executable) files as though they were text files.
370• -B number prints a specified number of lines before the matching lines.
371• -C number prints a specified number of lines of context around the matching lines.
372• -c shows the number of matches of the string for the file.
373• -E uses regular expressions for the text pattern.
374• -e pattern specifies a literal pattern.
375• -f searches for multiple strings using a file that lists the string patterns.
376• -F uses a file as the source for the string patterns.
377• -i ignores the case of the string.
378• -l lists just the names of the files with a match. This is used when search multiple files.
379• -m number shows only a specified number of matches for a file.
380• -n displays the line number of the lines containing the term.
381• -r searches the directory and all sub-directories for files containing the term.
382• -v displays non-matching lines.
383• --include=file_name searches only in files with names that match a specified string.
384• --exclude=file_name searches in files with names that do not match a specified string.
385• -w searches for whole words only. grep -A 3 Midway ~/docs/WWII-report searches WWII-report for the pattern Midway and prints the line and the next three lines.
386grep -a var11 /bin searches all files, including binary files, in the /bin directory for the pattern var11.
387grep -c 3 Midway ~/docs/WWII-report shows only the number of times the pattern Midway is found in the WWII-report file.
388grep -e '--count' ~/docs/doc1 looks for the pattern --count in the doc1 file rather than interpreting it as an option.
389grep -l -r Midway ~/docs shows the name of all files in the /home/user/docs directory that contain the term Midway.
390grep -m 2 battle ~/docs/WWII-report shows only the first two times the term battle is found in the file.
391grep -n -i customVariable1 ~/java/program1.java shows the line numbers of lines that have the term customVariable1 in the program1.java file. This is case insensitive.
392grep -r battle ~/docs/ searches the directory and all sub-directories for the term battle.
393grep -w tank ~/docs/WWII-report searches only for the whole word tank in the file.
394egrep Use regular expressions in the search strings. egrep uses the same options and syntax as grep, and is identical to grep -E. Constructors for egrep regular expressions include:
395• ^ matches terms that occur at the beginning of a line.
396• $ matches terms that occur at the end of a line.
397• \< matches words that begin with the term.
398• \> matches words that end with the term.
399• [asdf] matches any one of the characters in the brackets.
400• [0-9] matches any of the range of numbers 0-9.
401• [^xyz] omits any one of the letters in the list
402• . matches any single character.
403• [asdf]+ matches one or more of the characters in the list.
404• * matches any number, or none of the preceding single character
405• | matches either of the terms.
406• \ displays the literal value of a character used for expressions.
407• () groups expressions. egrep ^FAILURE ~/error_logs matches the term FAILURE when it is at the beginning of the line in error_logs.
408egrep tty7$ ~/.bash_history matches the term tty7 when it is at the end of the line.
409egrep \<are ~/myfile matches all words or strings that begin with are. This includes are, area, and arena.
410egrep \>are ~/myfile matches all words or strings that end with are. This includes are, hare, and aware.
411egrep watche[ds] ~/myfile matches either watched or watches.
412egrep exhibit[0-9] ~/myfile matches exhibit1, exhibit3, or exhibit8.
413egrep [^Xx]mas ~/myfile matches Christmas but not xmas or Xmas.
414egrep .are ~/myfile matches hare and care, but not aware or are.
415egrep file[0-9]+ ~/myfile matches file0, file10, and file15636.
416egrep fil* ~/myfile matches fil, filll, and fillllllllllllllll.
417egrep fil.* ~/myfile matches file, fill, file102, and filings.
418egrep men|women ~/myfile matches men or women.
419egrep Hello\? ~/myfile matches Hello?.
420fgrep When searching for fixed strings, rather than regular expressions, fgrep:
421• Uses the same options grep uses, and has the same syntax.
422• Is identical to grep -F, but searches faster than grep.
423• Interprets the pattern as a list of fixed strings, any of which can be matched. fgrep Midway Nimitz ~/docs/myfile searches myfile for lines containing Midway or Nimitz.
424 -----
425
426Be aware of the following advantages to planning and designing a Linux installation:
427• A plan ensures that the installer knows exactly what should happen during the installation. The plan places all the information in the installer's hands before installation begins.
428• There are fewer variables involved when diagnosing and resolving problems.
429• The plan ensures that there is something concrete to reference if managers add requests after the installation begins. It gives the IT team something to use as a point of reference if the changes require a change in resources or schedule.
430The following table describes general steps in an effective installation design:
431Step Description
432Perform a needs assessment An effective assessment determines the goals of the installation, creates a plan to meet those needs, and measures the results of the plan. This involves:
433• Interviewing managers to determine the goals they want to achieve, what problems they need to solve, the expected results.
434• Writing clear, measureable statements that specifically address the goals.
435• Indentifying the stake holders.
436• Confirming correct authorization.
437• Aligning the installation with current organizational strategy and technology.
438• Verifying funding.
439• Creating a support strategy.
440• Determining the scope:
441 Identify deadlines.
442 Determine the tasks that must be completed.
443 Plan for human resource allocation.
444Pick a distribution Picking a distribution involves:
445• Determining whether the computer should be a server or a workstation. Most distributions can be either, but some are better designed for specific functions and even specific types of servers. For example:
446 The SUSE Linux Enterprise Server is optimized to be used as a server.
447 The SUSE Linux Enterprise Desktop is optimized to be used as a desktop.
448• Determining whether end users will be comfortable with the distribution, or whether configuration changes might be necessary.
449• Determining whether required software is available for the distribution. Make a list of applications and ensure that they are provided on the distribution.
450• Ensuring that the distribution has the necessary support.
451Determine the hardware requirements Some computer hardware is incompatible with some distributions. Ordering hardware without first ensuring that the operating system can actually be installed can lead to a stack of useless hardware. Ensure that:
452• The computer's hardware is on the distribution's hardware compatibility list.
453• The computers have sufficient CPU speed, memory and other system requirements to run the distribution and the installed software.
454• The correct version of the distribution is installed on the computer based on the computer's CPU architecture. These include:
455 x86 for 32 bit CPUs
456 x64 for 64 bit CPUs
457 IA-64 for Itanium CPUs
458 ALPHA for Alpha CPUs
459 PPC for Power PC (Apple) CPUs
460Plan the file system The file system determines how a computer's files are organized on a hard drive. Linux supports several file system types that have different characteristics, including:
461• ext2 has volume integrity features that may take several minutes to run after a system crash.
462• ext3 uses journaling to ensure that only incomplete transactions are checked after a system crash. It is the default file system on most distributions.
463• ReiserFS also uses journaling and also implements additional security features based on its file structure.
464Pick the one that best meets your organization's needs. Considerations include:
465• Maximum volume size
466• Maximum file size
467• File name size
468• Permissions and file security
469• Encryption support
470• Recovery support and speed
471• Backup support
472• Journal support
473Plan the partitions Partition planning is another element of file system planning. An efficient strategy is to create multiple partitions based on the types of files held on the partition and the user access needs to the data. Consider creating separate partitions for the following directories. Set mount options based on the type of files in the directory.
474• / (root) needs to be at least 4 GB, but should be much larger. The partition holding the root directory should be on a primary partition and must be formatted with a Linux filesystem.
475• /home should be a minimum of 5 - 10 GB, or as large as needed to store the user files.
476• /boot should be 100 - 200MB. It needs to be in the first 1024 cylinders of the disk for older BIOS versions.
477• /opt should be at least 1 GB based on the number of applications that will be installed.
478• /tmp should be 1GB. Temporary files are cleaned out by the operating system periodically.
479• /usr should be 5 GB - 16 GB. based on the number of installed packages.
480• /var should be 3 - 10 GB. Make it large enough that log file size does not affect the rest of the computer.
481• /swap should be 1 - 1.5 times larger than the amount of installed RAM. Linux can use either a swap file or a swap partition for the swap area. Whenever possible, create a separate swap partition.
482/etc, /bin, /sbin, /lib, /dev, and /proc must all be on the same partition. These directories have system configuration files that are necessary for Linux to function properly.
483Identify software Determine which software packages need to be installed, and only install those packages. This ensures that system resources are conserved, and that vulnerabilities are limited.
484Identify the users Determine the users who will use the computer. Consider the following:
485• Ensure correct name spelling for the users.
486• Determine whether users log in locally or over the network.
487• Have a list of groups to which the users will belong.
488The root user is always installed. Use this account only when necessary to ensure security.
489Gather network information Gathering network information includes the following types of information:
490• IP address
491• Default gateway
492• Subnet mask
493• Server information for DNS servers, mail servers, and other network servers
494• Network topology information such as domain names
495• Naming conventions for servers and workstations
496• Domain names
497Select an installation source Installation sources include:
498• CD
499• DVD
500• Network share
501Determine whether to install the distribution locally, or over the network as well.
502-----
503
504The following table describes the general steps necessary to install a Linux operating system:
505Step Description
506Start the install In many cases, this step involves booting the computer from installation media. The BIOS may need configuration to boot from the media. Linux installers often offer different installation options, such as:
507• New install
508• Reinstall
509• Upgrade
510• Installation recovery
511• Reduced feature installation
512Select a language The selected language becomes the default language for all users; however, it can be changed later, if necessary.
513Set the system time The system time can be set to local time or Coordinated Universal Time (UTC) time.
514• For networks dispersed over multiple time zones, choosing UTC simplifies administration tasks.
515• Some distributions have options to synchronize the time over the network.
516Format partitions A partition is a logical division of a storage device associated with a hard disk drive. Create the partition structure according to the specifications in your installation plan. Determine the directory structure and file system type for each partition. This may require initializing a hard drive. Partitioning options can include:
517• Use all space makes a single partition from the entire disk drive.
518• Replace existing Linux system(s) re-partitions all the previously installed Linux Operating systems.
519• Shrink partitions reduces the size of an existing partition making room for additional partitions.
520• Use free space creates a partition from unpartitioned space on the disk drive.
521• Create custom layout manually creates partitions according to the specific needs of the system or administrator.
522Keep the following in mind when creating partitions:
523• Initializing a hard drive removes all existing data.
524• A swap partition is required for virtual memory. Swap partitions should be between one to two times as large and the amount of RAM on the computer.
525• Linux computers can only have four partitions, but a single extended partition can be sub-divided into additional partitions.
526• Create separate partitions for the following directories to keep logs or abnormally large user files from taking all disk space, and make recovery of data easier if the operating system crashes.
527 /home (user directories)
528 /opt (installed software)
529 /var (log files)
530The operating system can be reinstalled on the root partition (/) and the others can then be remounted, with no loss to data.
531Select applications and services Installing applications and services depends on the role of the system. Applications and services include the following:
532• The boot loader determines which operating system boots by default if more than one operating system exists on a computer.
533• Package patterns include packages necessary for a specific computer role, such as Graphical Desktop or Web Server.
534• Package repositories are locations on the Internet where software packages are maintained. Specific Linux utilities search and install software automatically from these package repositories.
535Set the root password The secure password for the root user (and any other user) should typically:
536• Include 8 characters or longer (longer passwords are harder to crack).
537• Include the use of numbers and symbols in addition to letters.
538• Do not include a username or a dictionary word (or common variations).
539Specify a host name The name of the computer identifies the computer on a network. A domain may be required.
540Configure network connections Configure the network connections.
541Configure services Occasionally services must be configured based on the role of the system, such as a Web Server.
542Add new users and groups Create user accounts and groups for the users who will use the computer.
543• Installations usually require at least one standard user account.
544• Network login options enable the system to access a server for login information rather than maintaining local authentication information.
545Configure the hardware settings Hardware configuration settings might require appropriate drivers or language settings.
546
547-----
548A locale is a set of files that Linux uses to determine country and language-specific settings for various applications. Locales:
549• Determine the way data displays on a computer. This includes:
550 The language and encoding of the text displayed on screen
551 Character classes
552 Sort order
553 Number formatting
554 Currency type and format
555 Date and time display
556• Use configuration files that are part of the system library and are located in /usr/share/locale on most distributions.
557• Use language codes specified in ISO-639, and country codes specified in ISO-3166.
558• Use the following command format: Language_territory.codset modifier. Examples of locale codes with modifiers include en_GB.UTF-8 and de_DE.euro.
559Environment variables implement the locale codes. For example LANG=en_US.UTF-8 specifies that the computer uses US English with a UTF-8 encoding when displaying information. The following table lists the configurable environment variables.
560Variable name Explanation
561LANG LANG defines all locale settings at once, while allowing further individual customization via the LC_* settings below. When LANG=C, programs display output without passing it through locale translations. This is helpful when the output is being corrupted by the locale, and will help avoid some types of problems, such as when using pipelines and scripts that pass on a program's data to another program in binary form.
562Localization support is the responsibility of the program's author. Many programs only support one language or a small subset of languages.
563LC_CTYPE LC_CTYPE defines the character handling properties for the computer. This determines whether characters are recognized as alphabetical, numeric and so on. This also determines the character set used, if applicable.
564LC_MESSAGES LC_MESSAGES specifies localizations for applications that use a message-based localization scheme.
565LC_COLLATE LC_COLLATE defines the alphabetical ordering of strings, such as the output of sorted directory listings.
566LC_NUMERIC LC_NUMERIC defines formatting for numeric values that are not monetary. It affects things such as the thousands separator and the decimal separator.
567LC_MONETARY LC_MONETARY defines currency units and formatting of currency type and numeric values.
568LC_TIME LC_TIME defines formatting for dates and times.
569LC_PAPER LC_PAPER defines the default paper size.
570LC_NAME LC_NAME specifies personal name format. This includes things like whether the surname comes first or last.
571LC_ADDRESS LC_ADDRESS is used for address formatting.
572LC_TELEPHONE LC_TELEPHONE defines telephone number format.
573LC_MEASUREMENT LC_MEASUREMENT determines what measurement units are used.
574LANGUAGE LANGUAGE is used as an override for LC_MESSAGES.
575LC_ALL LC_ALL is a special variable for overriding all other settings. It sets all locales to the same setting.
576The following table lists and describes the command and options to configure locale settings:
577Use... To...
578locale Display the current locale settings for the computer. Be aware of the following options:
579• charmap displays the character encoding.
580• -a lists all installed locales.
581• -m lists all installed character encoding options.
582iconv Convert encoding from one encoding type to another. Be aware of the following options:
583• -f specifies the old encoding type.
584• -t specifies the new encoding type.
585• -o specifies the input and output file.
586
587-----
588The boot process for a Linux computer includes the following general stages:
589Stage Process
590BIOS In the BIOS stage, BIOS is loaded and the system hardware is identified. The following steps take place:
5911. Power is supplied to the processor. The processor is hard-coded to look at a special memory address for code to execute.
5922. This memory address contains a pointer or jump program which instructs the processor where to find the BIOS program.
5933. The processor loads the BIOS program. The first BIOS process to run is the power on self test (POST).
5944. If the POST is successful, the BIOS identifies other system devices. It uses CMOS settings and information supplied by the devices themselves to identify and configure hardware devices. Plug and Play devices are allocated system resources. The system typically displays information about the keyboard, mouse, and IDE drives in the system. Following this summary, information about devices and system resources is displayed.
5955. The BIOS then searches for a boot sector using the boot order specified in the CMOS.
596Boot loader During the boot loader stage, BIOS gives control to the boot loader program. The following steps take place:
5971. BIOS searches the boot sector which contains a Master Boot Record (MBR).
5982. BIOS loads the primary boot loader code from the MBR.
5993. The primary boot loader does one of the following:
600o It examines the partition table marked as bootable, and then loads the boot sector from that partition. This boot sector contains a secondary boot loader, which locates an OS kernel.
601o It locates an OS kernel directly without using a secondary boot loader.
6024. When the secondary boot loader is in RAM and executing, a splash screen is commonly displayed, and an optional initial RAM disk (i.e., initrd image) is loaded into memory. The initrd image:
603o Has root permissions and can be used to access the actual /root file system regardless of whether it exists on the local computer or an external device. Without the permissions, the computer could not access the file systems without being able to read information that only exists on those file systems.
604o Is used to mount the actual file system and load the kernel into RAM.
6055. With the images ready, the secondary boot loader invokes the kernel image.
606OS Kernel During this stage, the Linux kernel takes over. The kernel:
6071. Resides in the /boot directory.
6082. Initializes the hardware on the system.
6093. Locates and loads the initrd script to access the linuxrc program which configures the operating system.
6104. Dismounts and erases the RAM disk image (initrd image).
6115. Looks for new hardware and loads the drivers.
6126. Mounts the root partition.
6137. Loads and executes the initial (init) process.
614Init By default, /sbin/init is the initial (init) process. If /sbin/init is the initial process, the kernel reads a file called /etc/inittab to determine what other programs to run, such as:
615• Scripts to mount partitions or start system services known as daemons.
616• A console for a login
617• An X Display Manager (XDM) for a graphical login
618The initial program gets the process ID of 1 because it's the first process to run on the system.
619
620
621-----
622
623The Grand Unified Boot Loader (GRUB) is a utility that boots a Linux kernel, or any other operating system. Two major versions of GRUB are currently supported:
624• GRUB Legacy: any version of GRUB prior to version 1.98. GRUB Legacy is no longer in development—only bugfixes are being released for older Linux systems.
625• GRUB2: any version of GRUB version 1.98 or later.
626GRUB Legacy has the following features:
627• Loads in two stages:
628 Stage 1 is the information stored in the master boot record. It holds the location of the boot information.
629 Stage 2 is the operating system software located on the boot partition.
630• Uses a menu to allow the user to select between multiple operating systems.
631• Loads a default operating system after a specified time period.
632• Creates a GRUB root using the /boot directory. The GRUB root contains the installed Stage 2 files.
633• Omits /boot from the path if the /boot directory is in a separate partition.
634• Uses the hd#,# syntax to specify the location of the root file system.
635• Is installed by most distributions. If it was not installed, use the grub-install command from the shell prompt to install GRUB. For example, use grub-install --root-directory=/boot sd1 to install GRUB on the second hard drive.
636• Uses one of the following as the configuration file:
637 /boot/grub/menu.lst
638 /boot/grub/grub.conf
639The following table describes several common options in the configuration file:
640Use... To... Examples
641default Specify the operating system that boots as the default. The value may be the entry number (e.g., 0, 1, 2) or the name of the entry (e.g., Fedora). default=0 boots the first operating system in the menu.
642default=Fedora boots the operating system with Fedora as the title.
643timeout Set the number of seconds GRUB waits before automatically booting the default operating system. timeout=10 waits 10 seconds before booting the default operating system.
644gfxmenu
645splashimage Specify the image file which is displayed for the graphical boot menu. splashimage=(hd0,0)/grub/splash.xpm.gz identifies the default splash image.
646hiddenmenu Disable/Enable the menu that lists the operating system options.
647Adding the pound (#) symbol to this line only prevents the operating systems from being displayed on startup. If the user hits any key before GRUB selects the default operating system, the operating systems are displayed. hiddenmenu disables GRUB from displaying the available operating systems.
648#hiddenmenu displays the available operating systems.
649title Specify the title a user sees in the menu. title Fedora displays an option that is named Fedora.
650root Specifies the location of the root file system. root (hd0,0) specifies the first partition on the first hard drive as the root file system.
651root (hd0,1) specifies the second partition on the first hard drive as the root file system.
652rootnoverify (fd0) specifies the floppy drive as the root file system and that it should be loaded regardless of whether GRUB recognizes it.
653kernel Specifies the kernel for the entry and kernel options. kernel /vmlinuz-2.6.33.3-85.fc13.i686
654initrd Specifies the initial RAM disk (initrd image) file. initrd /initramfs-2.6.33.3-85.fc13.i686.img
655chainloader Specify the number of sectors to be read. chainloader +1 specifies that GRUB should read one sector.
656password Require authentication for the options in the GRUB menu. To create an encrypted password:
6571. In a shell prompt, type grub-md5-crypt.
6582. At the prompt, type and confirm the password, then press return.
6593. Copy the hashed output from the shell.
6604. Type password --md5 hashed_output in the GRUB configuration file. password $3cur3 sets the string $3cur3 as the password.
661password --md5 $1$frLco/$/E4pglv5halSBQadGQgb1 uses the hashed output for the password.
662lock Prevent unauthorized boot of the operating system. When the lock keyword is present for an operating system, the password is required before the user can select and boot an operating system.
663
664-----
665GRUB2, the updated version of the Grand Unified Boot Loader (GRUB) utility, is any version of GRUB 1.98 or later. Earlier versions of GRUB are sometimes known as GRUB Legacy. Be aware of the following details about GRUB2:
666• /boot/grub/grub.cfg is the configuration file for GRUB2. This file:
667 Is similar to GRUB Legacy's /boot/grub/menu.lst or /boot/grub/grub.conf file.
668 Should not be edited directly.
669• Depending on the Linux distribution, the update-grub or grub2-mkconfig command generates the /boot/grub/grub.cfg file. Specifically, these commands use the /etc/default/grub file and the scripts in the /etc/grub.d/ directory to generate the /boot/grub/grub.cfg configuration file.
670• The /etc/grub.d/ directory holds script files that are read when the update-grub command is used.
671Important script files in the /etc/grub.d/ directory include:
672Script File Description
67300_header Sets initial appearance items, such as the graphics mode, default selection, timeout, etc. These settings are typically imported from the /etc/default/grub file.
67405_debian_theme Sets the GRUB2 background image, text colors, selection highlighting, and themes.
67510_linux Identifies kernels on the root device for the operating system in use and creates menu entries.
67630_os-prober Executes os-prober to search for other operating systems (i.e., Windows, Linux, etc.,) and place the results in the GRUB2 menu.
67740_custom Allows for custom menu entries, which are imported directly into /boot/grub/grub.cfg without any changes.
678The /etc/default/grub file is the primary configuration file for changing menu display settings. The following table describes several common options in the configuration file:
679Option Description Examples
680GRUB_DEFAULT Sets the default menu entry. Typical entries include:
681• Numeric (i.e., 0, 1, 2, etc.)
682• Complete menu entry quotation (i.e., "Ubuntu, Linux 2.6.31-9-generic") GRUB_DEFAULT=0 sets the first menu entry as the default.
683GRUB_DEFAULT="Ubuntu, Linux 2.6.31-9-generic" sets a menu entry as the default.
684GRUB_SAVEDEFAULT Automatically sets the last selected OS from the menu as the default OS on the next boot. GRUB_DEFAULT=saved is required for this option to work correctly. GRUB_SAVEDEFAULT=true sets the last selected OS from the menu as the default OS on the next boot.
685GRUB_HIDDEN_TIMEOUT Determines how long a screen without the GRUB 2 menu will be displayed. Options include:
686• 0 immediately boots to the default OS
687• X (an integer value) pauses and shows a blank screen for X seconds. If a user presses any key, the GRUB menu is displayed.
688• (blank) uses the value specified in the GRUB_TIMEOUT entry GRUB_HIDDEN_TIMEOUT=0 immediately boots to the default OS.
689GRUB_HIDDEN_TIMEOUT=3 displays a blank screen for 3 seconds and then boots to the default OS if there is no user interaction.
690GRUB_HIDDEN_TIMEOUT_QUIET Displays a counter (countdown). Options include:
691• true does not display a counter
692• false displays the counter for the duration specified in the GRUB_HIDDEN_TIMEOUT entry GRUB_HIDDEN_TIMEOUT_QUIET=true does not display a counter.
693GRUB_TIMEOUT Determines how long to wait for user interaction before booting into the default operating system. Options include:
694• X (an integer value of 1 or higher) sets the display duration
695• -1 causes the menu to display until the user makes a selection.
696Be aware of the following:
697• The GRUB2 menu is hidden by default unless another OS is detected by the system.
698• If there is no other OS, this line may be commented out unless the user changes it. GRUB_TIMEOUT=4 causes the menu to display for four seconds and then boots into the default operating system.
699GRUB_TIMEOUT=-1 causes the menu to display until the user makes a selection.
700GRUB_CMDLINE_LINUX Adds entries to the end of the 'linux' command line (GRUB Legacy's "kernel" line) for both normal and recovery modes. It is used to pass options to the kernel.
701GRUB_GFXMODE Sets the resolution of the graphical menu (i.e., the menu text size). Multiple resolutions may be specified if they are separated by commas. GRUB_GFXMODE=640x480 sets the resolution to 640 x 480.
702GRUB_INIT_TUNE Plays a single beep just prior to the GRUB2 menu display
703GRUB_BACKGROUND Sets the background image during GRUB2 menu display. The full path should be used. Must be in the PNG, TGA, or JPG/JPEG file formats. GRUB_BACKGROUND=/usr/share/images/back.png displays back.png as the background image.
704GRUB_DISABLE_OS_PROBER Enables/disables the os-prober check of other partitions for operating systems, including Windows, Linux, etc., during execution of the update-grub command. If the os-prober is enabled, operating systems found will be placed in the GRUB2 menu. GRUB_DISABLE_OS_PROBER=true disables the os-prober.
705GRUB_DISABLE_OS_PROBER=false enables the os-prober and will add found operating systems to the GRUB2 menu.
706Use the grub-install -v or grub2-install -v command to determine which version of GRUB is installed.
707
708-----
709Chapter 3.3.3
710A runlevel is a collection of services that define a specific system state. For example, Microsoft Windows has Safe Mode and regular mode which are somewhat equivalent to Linux runlevels. The table below describes the runlevels:
711Runlevel Description
7120 This is the halt state. In runlevel 0, the system has no daemons in memory and is ready to be turned off.
7131 This is single user mode. In single user mode, the system uses only enough daemons to allow a single user to log in, and is often used for maintenance tasks. The user is automatically logged in as the root user.
7142 This is multi-user mode. In multi-user mode, the system allows multiple users to log in. It also provides networking services with the exception of the Network File System.
7153 This is extended multi-user mode. In extended multi-user mode, the system provides multi-user mode support in addition to all network services, including Network File System.
7164 This runlevel is undefined, but can be defined if necessary.
7175 This is graphical mode. In graphical mode, the system provides the same capabilities as in extended user mode. However, the system also supports graphical log ins.
7186 This is the reboot runlevel. In this runlevel, the system re-starts itself.
719During the boot process, the init (initialize) daemon loads all the other daemons that control the system. Init uses the /etc/inittab file to determine the default runlevel, and then starts the appropriate daemons for that runlevel; however, some distributions place code for initiating runlevels in separate files. The table below describes the format of the lines in the /etc/inittab file:
720Field Description
721label: This field organizes the file to allow the init daemon to read it alphabetically.
722runlevel(s): This field specifies the runlevel(s) to which the line corresponds.
723action: This field tells init what action to take (e.g., respawn, wait, boot, bootwait, powerfail, powerwait).
724command This field designates a shell command to execute.
725The following are typical lines in the /etc/inittab file:
726• id:3:initdefault: indicates that init should set the system runlevel at 3 by default.
727• si::sysinit:/etc/rc.d/rc.sysinit indicates that that init should execute the /etc/rc.d/rc.sysinit command prior to entering a runlevel when the system initializes.
728• cmd:123:wait:/sbin/custom runs the special script file (/sbin/custom) for runlevels 1, 2, and 3.
729• l5:5:wait:/etc/init.d/rc 5 determines which script runs when invoking an init command.
730• ca::ctrlaltdel:/sbin/shutdown -r -t 4 now specifies what happens when a user presses Ctrl+Alt+Del.
731The following table describes the commands that determine and change the current runlevel. (The commands require root privileges.)
732Use... To... Examples
733runlevel Display the previous runlevel and the current runlevel, respectively.
734• The previous runlevel is the first number.
735• The current runlevel is the second number.
736• An N as the first number specifies that the current runlevel is the runlevel into which the computer booted.
737• An S specifies that the runlevel is single user mode (i.e., runlevel 1).
738[root@COMP ~]# runlevel
7393 5
740Runlevel is 3 was the previous runlevel; Runlevel 5 is the current runlevel.
741init
742telinit Change the runlevel of the computer. init 0 changes the system to runlevel 0, shutting the system down.
743init s changes the runlevel to 1, which is single-user mode.
744init 3 changes the runlevel to 3, which is extended multi-user mode.
745telinit 3 changes the runlevel to 3.
746telinit 5 changes the runlevel to 5, which is graphical multi-user mode.
747init q
748init Q Have init re-examine the inittab file.
749
750----------
751Kernel options allow customization of Linux boot parameters to permit administrators to fix several problems related to booting. The following table describes common kernel parameters:
752Use... To... Examples
753runlevel_number Boot into a specific runlevel. kernel_parameters 3 starts the computer in runlevel three.
754vga Change monitor display settings. vga=0x307 sets the monitor resolution to 1280x1024 with 256 colors.
755init Change the program that the kernel starts at boot time. init=/bin/bash starts the bash shell at boot time.
756acpi Enable or disable the advanced configuration and power interface (ACPI). acpi=off disables ACPI.
757apm Enable or disable advanced power management (APM). apm=off disables APM.
758To add kernel options while the GRUB menu is displayed:
759• Use the following sequence to insert the options directly into the existing boot options:
7601. Select the operating system.
7612. Press the a key.
7623. Add the kernel boot options to the existing boot options.
763• Use the following sequence to add the options to the options listed in the /boot/grub/grub.conf file:
7641. Select the operating system.
7652. Press the e key.
7663. Select the kernel line.
7674. Press the e key.
7685. Add the kernel boot options to the existing boot options.
769
770----------
771Init script configuration is the process of specifying whether specific daemons start at a specified runlevel. Init scripts:
772• Are configured differently for BSD (SUSE) and System V (Fedora and Red Hat) distributions.
773• Are stored in the following locations:
774 /etc/rc.d/init.d directory (System V distribution)
775 /etc/init.d directory (BSD distribution)
776• Have symbolic links that are stored in subdirectories that correspond to the runlevel under which each script should start.
777• Can be started and stopped manually.
778• Are started at boot using the init script.
779• Have code in the scripts that determine the appropriate runlevels on which the script can operate. Configuration commands use this information to configure the appropriate levels at which scripts can start and stop. This code includes:
780 The default-start line defines the runlevels in which the script starts by default.
781 The required-start line defines services that must be running before this service can start
782 The should-start line defines the services that are recommended to start before this service starts.
783Init script directories also contain other important scripts, including the following:
784• rc (BSD and System V) switches between runlevels.
785• halt (BSD and System V) stops and reboots the computer. It runs when the init 0 or init 6 commands are invoked.
786• boot (BSD) or rc.sysinit (System V) is run by the init process when a computer starts. These scripts perform tasks that include:
787 Loading the kernel module
788 Checking the file system
789 Setting the system clock
790• boot.local (BSD) or rc.local (System V) runs specific tasks at startup as specified by the administrator.
791When using init scripts, keep the following in mind:
792• At boot time, init uses the /etc/inittab file to determine the default runlevel, such as runlevel 5.
793• When a runlevel is specified, init looks at the directory associated with the runlevel to determine what processes to start. The directory for runlevel 5 is named rc5.d. Additional directories named rc0.d through rc6.d specify what processes to start for each runlevel.
794• Each rc directory contains symbolic links that point to a specific init script:
795 Link names starting with an S start a script for the runlevel.
796 Link names starting with a K kill a running process when the computer changes runlevels.
797• Init follows the links and runs the scripts to start or stop processes.
798• Init repeats the process using the appropriate rc directory whenever the runlevel changes.
799Use the following commands to manage daemons and the init scripts:
800Use... To... Examples
801service daemon_name Manage the current state of a daemon. Options include:
802• start starts a daemon that is not currently running
803• stop halts a running daemon.
804• restart stops and restarts a daemon.
805• reload requests that a daemon read and apply its configuration files without stopping.
806• status shows the status of a single daemon or daemons.
807• --status-all shows the status of all daemons.
808As an alternative method, use the absolute path to the daemon script and the option to configure the daemon (e.g., /etc/rc.d/init.d/httpd stop). service atd start starts the atd daemon.
809/etc/rc.d/init.d/httpd start starts the httpd daemon.
810service httpd stop halts the httpd daemon.
811/etc/rc.d/init.d/httpd restart restarts the httpd daemon.
812/etc/init.d/httpd reload implements a new configuration for the httpd daemon without halting the service.
813service httpd reload reloads the httpd daemon.
814/etc/init.d/httpd status shows whether the httpd daemon is running.
815service --status-all shows the status of all daemons.
816insserv Configure default runlevels for a daemon on a BSD distribution. insserv references the INIT INFO script section of each daemon to determine the default runlevels for the daemon and dependent daemons. Be aware of the following options:
817• script_name starts at the runlevels specified in the init block script code.
818• -r keeps a script from starting at any runlevel.
819• -d restores a daemon to the default runlevels defined in the scripts. insserv httpd causes the httpd daemon to start at the runlevels specified in the script.
820insserv -r httpd stops the httpd daemon from starting when a computer boots.
821chkconfig Configure default runlevels for a daemon. Be aware of the following options on a System V distribution:
822• --add adds a new service to be managed by chkconfig, and makes sure the service has a start or kill entry at every runlevel.
823• --del removes a service from chkconfig management, and removes symbolic links to the service from /etc/rc0-6.d.
824• --level specify the level to which a service should belong.
825• --level on|off|reset starts, stops, or resets the named service in the specified runlevel. The on and off options affect levels 2, 3, 4, and 5 when the runlevel is omitted.
826• --list lists of services and their runlevels.
827Be aware of the following options on a BSD distribution:
828• -l lists services and their runlevels.
829• -s specify the level to which a service should belong. chkconfig --add atd starts the atd daemon.
830chkconfig --del ldap removes the ldap daemon.
831chkconfig --level 5 lpd specifies level 5 for the lpd daemon.
832chkconfig --level 345 nfslock off turns the nfslock daemon off in runlevels 3, 4, and 5.
833chkconfig ypxfrd on turns the yp transfer daemon on in levels 2, 3, 4, 5.
834
835----------
836Upstart is a services management system that was introduced to resolve some of the short-comings of the init script configuration process. Upstart was temporarily adopted by several major Linux distributions but was soon abandoned in favor of systemd.
837Most major Linux distributions now ship with systemd as the default services management system—replacing both init and Upstart.
838Upstart
839Upstart is an event-based replacement for the /sbin/init daemon; it will start and stop tasks and services whenever the Linux system enters a specific runlevel, but will also start and stop services upon receiving information that something on the system has changed (known as an event).
840• Upstart runlevels are as follows:
841 0 = halt state
842 1 = single user mode
843 2 = graphical, multi-user mode with networking (Default)
844 3, 4, 5 = same as runlevel 2, but not used
845 6 = reboot (the system restarts itself)
846• A job is a series of instructions that init reads which typically include a program and the name of an event. The Upstart init daemon runs the program when the event is triggered. Jobs are divided into tasks and services.
847 A task is a job that performs its work and returns to a waiting state when it is done.
848 A service is a job that does not normally terminate by itself. The init daemon monitors each service, restarting the service if it fails and killing the service when it is stopped manually or by an event.
849• To run and stop a job manually, use the following commands (these are symbolic links to the initctl command):
850 start starts a daemon that is not currently running
851 stop halts a running daemon.
852 restart stops and restarts a daemon.
853 reload requests that a daemon read and apply its configuration files without stopping.
854 runlevel displays the runlevel information.
855• Traditionally, the default runlevel was encoded in the /etc/inittab file. However, with Upstart, this file is no longer used (it is supported by Upstart, but its use is deprecated).
856• To change the runlevel immediately, use one of the following commands:
857 reboot
858 shutdown
859 telinit
860• Use the DEFAULT_RUNLEVEL environment variable in /etc/init/rc-sysinit.conf to set the default runlevel.
861systemd
862systemd is a replacement for both the /sbin/init daemon and Upstart, and is designed to allow services to be started in parallel at system startup. systemd:
863• Is compatible with SysV and Linux Standards Base (LSB) init runlevel scripts
864• Uses socket and D-Bus activation for starting services
865• Allows you to start daemons on-demand
866• Tracks processes using Linux kernel control groups (known as cgroups in systemd terminology)
867• Supports snapshotting and restoring of the system state
868Be aware of the following systemd terms:
869Terms Description
870systemctl Used to manage services and runlevels. systemctl combines the functionality of both service and chkconfig.
871target units Target units are a new concept introduced by systemd. They are similar to the runlevels used by init but differ in that they are named instead of numbered. They are started using the systemctl command. They can also be customized by combining existing targets. The most important systemd targets include:
872• default.target A symlink to another target file, such as graphical.target, in the /lib/systemd/system directory
873• emergency.target Starts an emergency shell on the console
874• graphical.target Starts a system with network support, in multi-user mode, and with a display manager
875• halt.target Shuts the system down
876• mail-transfer-agent.target Starts a system with all services needed for sending and receiving email
877• multi-user.target Starts a system in multi-user mode with network services
878• reboot.target Reboots the system
879• rescue.target Starts a system in single-user mode without network services
880cgroups Kernel Control Groups (aka cgroups) are used to track processes (instead of process IDs) for systemd. cgroup details include:
881• A cgroup is a collection of processes that are bound together by common criteria.
882• cgroups are hierarchical. They are organized into parent-child relationships; a child group inherits parameters from its parent group.
883• Sending signals to parent processes, such as kill signals, also kills the child processes in the cgroup.
884systemd is compatible with the scripts used by the init runlevel system. The following special targets are provided that map with corresponding runlevels:
885init runlevel systemd target Purpose
8860 runlevel0.target, halt.target, poweroff.target System shutdown
8871, S runlevel1.target, rescue.target Single user mode
8882 runlevel2.target, multi-user.target Local multi-user without remote network
8893 runlevel3.target, multi-user.target Full multi-user with network
8904 runlevel4.target Unused/User defined
8915 runlevel5.target, graphical.target Full multi-user with network and display manager
8926 runlevel6.target, reboot.target System reboot
893
894----------
895Turning off the power without executing the proper shutdown procedure to a computer can result in data loss and filesystem corruption. Linux provides several different shutdown options. The table below shows common commands for shutting down the system.
896Use... To... Examples
897shutdown -h now
898halt
899init 0 Shut the system down immediately.
900• -h specifies that the system halt or poweroff after shutdown.
901• now forces the system to shut down without a delay.
902Any of the three commands shut the system down.
903shutdown -r now
904reboot
905init 6 Shut the system down immediately and reboot.
906Any of the three commands reboot the system.
907shutdown -h time message
908shutdown -r time message Shut the system down in the designated amount of time and send a message. shutdown -h +5 System is going down sends a message and shuts the system down in five minutes.
909shutdown -h 22:00 shuts the system down at 10:00 pm.
910shutdown -r +15 reboots the system in 15 minutes.
911shutdown -r 24:00 System is going down at Midnight sends a message and reboots the system at midnight.
912shutdown -c
913Ctrl+c Terminate the shutdown process.
914shutdown -rf time Reboots the system and skips the fsck utility on reboot. The -f parameter stands for reboot fast. shutdown -rf reboots the system and skips fsck.
915shutdown -r +15 reboots the system in 15 minutes and uses fsck.
916shutdown -k message Sends a warning message, but does not shut down the system down. If used in combination with -h or -r, it will terminate the shutdown process after the message is sent. shutdown -k Please log out of the system sends a message but does not shut the system down.
917shutdown -a Use the /etc/shutdown.allow file to shut down the system.
918The most common use of this switch is to edit the /etc/inittab file and add the -a switch to the CTRL-ALT-DELETE section. When the switch is present, shutdown reads the /etc/shutdown.allow file:
919• If a listed user or root is logged into the system, the system shuts down.
920• If a listed user or root is not logged into the system, shutdown is not allowed.
921• If the /etc/shutdown.allow file does not exist, there are no restrictions on who can shut down the system.
922When using the shutdown command to shut down the computer, the system does the following:
9231. Sends a SIGTERM message to open programs to allow them to close.
9242. Notifies logged on users that the shutdown process has initiated and the length of time before shut down.
9253. Blocks users from logging into the system.
9264. Uses init and /etc/inittab to shut down processes and the system.
927
928----------
929Before configuring the X server, administrators must gather certain information about their hardware, such as:
930• Manufacturer and model number of video board and monitor
931• Video board specifications, including:
932 Amount of memory
933 Maximum resolution
934 Maximum color depth
935 Chipset
936While it's good to know all of these video board specifications, the most important one to know is the video chipset, as this dictates which video driver will be installed.
937• Monitor sync rate (horizontal and vertical)
938Configuration settings are contained in a file in the /etc directory. For the two most common X server implementations, the configuration files are:
939• /etc/X11/xorg.conf (X.org)
940• /etc/X11/XF86Config (XFree86)
941The configuration files include the following sections:
942Section Name Description
943Files The Files section Lists paths to files the server needs. These can include font paths, RGB color database, server modules and so forth.
944ServerFlags The ServerFlags section contains global server options. Many of these are for advanced configuration and debugging.
945Module The Module section specifies which server modules should load.
946InputDevice The InputDevice section has settings that give the properties for input devices. These include driver paths, device names, and options such as keyboard languages.
947Device The Device section holds the information the server needs to use the graphics cards.
948VideoAdaptor The VideoAdaptor section has description for X video.
949Monitor The Monitor section holds monitor specific information such as the sync rate and the refresh rates.
950Mode The Mode section holds settings for using different monitor modes, if necessary.
951Screen The Screen section has configurations for resolution, color depth, and so on.
952ServerLayout The ServerLayout section holds information that binds all input and output devices together to form a complete configuration.
953DRI DRI (Direct Rendering Infrastructure) has specifications for video rendering and 3d acceleration.
954Vendor The Vendor section allows vendors to create vendor-specific configuration settings.
955While administrators can edit the configuration file sections manually, it is recommended to use the configuration utilities that come bundled with the distribution. The following table describes utilities used with the X server:
956X Server Type Utility Description Command
957X.org YaST Yet another Setup Tool (YaST) is used in openSUSE. yast2
958 SaX SaX is a SUSE configuration tool similar to YaST. sax2
959 system-config-display Fedora and Red Hat computers running X.org use this tool for configuring video board, and monitor settings. system-config-display
960 system-config-keyboard Fedora and Red Hat computers running X.org use this tool for configuring keyboard settings. system-config-keyboard
961 system-config-mouse Fedora and Red Hat computers running X.org use this tool for configuring mouse settings. system-config-mouse
962 Xorg Xorg is a command-line tool that creates an initial xorg.conf file. It detects hardware and creates a basic configuration file for it. This tool is used when no graphical environment is present. Xorg -configure
963 xorgconfig Xorgconfig is a command-line tool that scans your hardware and configures it. You can also use it to change settings on hardware devices. This tool is used when no graphical environment is present. xorgconfig
964 xorgcfg Xorgcfg is a graphical tool that can make changes on a computer that has a running graphical environment. xorgcfg
965XFree86 Xconfigurator Xconfigurator sets up the necessary configuration files and file links to use XFree86 on a Red Hat system. Use --hsync and --vsync to set the horizontal and vertical sync settings. Xconfigurator
966 XFree-86 XFree-86 is a command-line tool that creates an initial XF86Config file. It detects hardware and creates a basic configuration file for it. This tool is used when no graphical environment is present. XFree-86 -configure
967 xf86config Xf86config is a command-line tool that scans your hardware and configures it. You can also use it to change settings on hardware devices. This tool is used when no graphical environment is present. xf86config
968 xf86cfg Xf86cfg is a graphical tool that can make changes on a computer that has a running graphical environment. xf86cfg
969 xvidtune Xvidtune enables fine tuning of the monitor settings in XFree86 computers. It is also compatible with and used on X.org Xservers. xvidtune
970When configuring the X server, keep the following in mind:
971• Always test the configuration before implementing it using the testing tools associated with the editing tool.
972• Restart the X server to implement the changes. Use one of the following methods:
973 Restart the computer
974 Log out and in
975 Press Ctrl-Alt-Backspace
976• Type startx in a command line to start an X server if no graphical interface is running.
977• If manual edits to the X server configuration file is unavoidable, make a backup of the old file before making the changes.
978
979-----
980When installing a Linux distribution, the installation utility often installs several window managers, but only one desktop environment. The following steps describe how to configure a new window manager or desktop environment on a System V distribution:
9811. Download the Red Hat Package Manager (RPM) package from the Internet or get the installation files from the distribution medium.
982Ensure that you have the correct package version for the CPU architecture and distribution.
9832. Install the files using the RPM utility.
9843. Log out of the computer. When logging back in, find the tool for selecting installed window managers and desktop environments.
9854. Modify the hidden file to make the new window manager or desktop environment the default, by replacing the $WINDOWMANAGER value with the name of the window manager or desktop environment you want to use.
986o In runlevel 3, modify the hidden file .xinitrc.
987o In runlevel 5, modify one of the following hidden files: .Xsession, .Xdefaults, or .Xclients.
9885. Restart the X server.
989Use the following commands to start a specific application if the system does not have a graphical interface enabled.
990Use... To launch the...
991exec startkde KDE desktop environment
992exec gnome-session Gnome desktop environment
993exec fvwm Flexible Virtual Window Manager
994exec sawfish Sawfish window manager
995exec wmaker Window Manager
996exec twm Tab Window Manager
997
998-----
999The display manager is a modular tool that manages the graphical display on a computer and has functions that provide users with a graphical login prompt to log in to a Linux computer from a remote computer. The main display manager types for Linux are:
1000• X Display Manager (XDM)
1001• Gnome Display Manager (GDM)
1002• KDE Display Manager (KDM)
1003The following table describes different tasks when configuring the display manager:
1004Task Description
1005Select the default display manager Selecting the default display manager depends on the distribution.
1006• Some distributions use a configuration file that is often located at /etc/sysconfig.
1007 The name and often the location of the file vary by distribution; use the grep utility to find a file that has DISPLAYMANAGER text in it.
1008 The entry should look similar to DISPLAYMANAGER="KDM".
1009• Some distributions use a script in the /etc/init.d directory.
1010 The script is named xdm, kdm, or gdm depending on the distribution.
1011 Replace the script to change the display manager.
1012Start or stop the display manager If at runlevel 3, you might need to manually start or stop the display manager. Using a shell prompt, navigate to the /etc/init.d/ directory and use one of the following commands:
1013• [xdm] [kdm] [gdm] start
1014• [xdm] [kdm] [gdm] stop
1015Enable or disable the display manager at startup To permanently enable or disable the display manager at startup, use one of the following commands:
1016• chkconfig [xdm] [kdm] [gdm] on
1017• chkconfig [xdm] [kdm] [gdm] off
1018Change the color depth To change the color depth of the display manager, use a setting in the servers file for the type of display manager in use.
1019• The startx command can change color depth by using the -depth option, followed by the color depth in bits.
1020• Lower color depth conserves video memory for a better resolution (increased color depth can sometimes affect the maximum resolution of older video cards).
1021• For example, to start a session in 16 bit mode, use the following command:
1022startx -depth 16
1023Support X Terminals An X Terminal is a system which typically connects only to an X server and does not have its own local system resources. To support X Terminals, complete the following general steps:
10241. Select and configure a display host to listen connection requests on the XDMCP protocol.
10252. Restart the display manager.
10263. Make sure port 177 is allowed through the firewall.
10274. Specify the computers or domain which can make connection requests to the display host.
1028
1029-----
1030The X Display Manager (XDM) is an X Window system display manager that allows users to log in to a Linux computer locally or from another computer on the network. XDM configuration files are often located at one of the following paths:
1031• /etc/X11/xdm
1032• /usr/X11R6/lib/X11/xdm
1033The following table describes the XDM configuration files:
1034File Description
1035Xresources The Xresources file modifies the look of the login display including colors, border size, and similar functions.
1036• The xlogin*Foreground: line controls the color used to display the foreground.
1037• The xlogin*Background: line controls the color used to display the background.
1038• The xlogin*greetColor: line controls the color used to display the greeting.
1039• The xlogin*failColor: line controls the color used to display the failure message.
1040• The xlogin*login.Font: line controls the font used to display the input typed by the user.
1041• The xlogin*login.greetFont: line controls the font used to display the greeting.
1042• The xlogin*login.promptFont: line controls the font used to display prompts.
1043• The xlogin*login.failFont: line controls the font used to display the message when the authentication fails.
1044• The xlogin*greeting: line changes the greeting that displays when someone logs on to the server.
1045• The xlogin*namePrompt: line displays the string displayed to prompt for a user name.
1046• The xlogin*fail: line controls the message displayed when the authentication fails.
1047Xservers The Xservers file lists the location of the server. When configuring an Xservers file, be aware of the following:
1048• The server can be on the local computer or on a remote computer.
1049• Each specification consists of the following parts:
1050 Display name
1051 Display class
1052 Display type
1053 A command line to start the server (if on a local computer)
1054• A -nolisten tcp flag in the line prevents the X server from listening on TCP ports, and renders it inoperable.
1055• If specifying a remote computer, it must be configured with appropriate permissions.
1056• Use the -bpp parameter to change the color depth. Options include:
1057 8 (256 colors)
1058 16 (65,536 colors)
1059 24 bits (16,777,216 colors)
1060 32 (over 4.2 billion colors) bits.
1061The following command sets the color depth to 24 bits:
1062:0 local /usr/bin/X11/X vt7 -bpp 24
1063xdm-config The xdm-config file lists the names and locations of other configuration files. The file contains a command that defines general permissions and access, such as the following:
1064DisplayManager.requestPort: 177
1065• If the request port is set to 177, XDM listens to incoming XDMCP requests. This is the port on which the display manager protocol usually operates.
1066• If the request port is set to 0, XDM does not listen for incoming requests; this is one way to disable the display manager when using XDM.
1067Xaccess The Xaccess file lists the computers which can make requests to the server using XDM and the computers which can see chooser broadcasts. A chooser broadcast sends out a signal that lets the user see that its display manager is enabled and that it is accepting requests. In the Xaccess file:
1068• An asterisk acts as a wildcard that indicates that every computer has access.
1069• A line that consists of only an asterisk grants all computers access to the login screen.
1070• A line followed with the term CHOOSER BROADCAST defines what computers can see the chooser broadcast.
1071• An exclamation point at the start of the command prohibits a computer from accessing the display manager.
1072The following command set allows access for only those computers listed. Any computer in the acme-u.edu domain can see the chooser broadcast and has access to the login screen. The computer mycomputer.mynetwork.com can access the login screen, but cannot see the chooser access information.
1073*.acme--u.edu
1074mycomputer.mynetwork.com
1075*.acme-u.edu CHOOSER BROADCAST
1076Be aware of the following:
1077• SUSE requires the following configuration changes to the /etc/sysconfig/displaymanager file to enable remote logins:
1078 displaymanager_remote_access="yes"
1079 displaymanager_xsrever_TCP_port_6000_ope="yes"
1080• Because XDM runs as root, it is less secure than the other display managers. If any scripts that XDM uses have security flaws, an attacker could potentially gain root access to the file system.
1081
1082-----
1083The KDE Display Manager (KDM) is the display manager supported by the KDE software organization. KDM:
1084• Offers features such as letting users select a session type and shut down the computer from the login prompt screen.
1085• Uses XDM configuration files, but might use a configuration file named kdmrc. The kdmrc file is typically located in one of the following locations:
1086 /etc/kde/kdm/
1087 /etc/x11/kdm/
1088• Looks to XDM during installation and copies the settings for KDM to use. This is optional.
1089• Has a GUI tool called Kcontrol that can configure most KDM settings.
1090The following table lists the general sections of the kdmrc file and describes the most commonly used options.
1091Sections Options
1092General The general section holds options that affect the overall use of KDM. Be aware of the following:
1093• Xservers specifies a path to the X server definitions file or contain X server definitions.
1094• The format is similar to that used by XDM.
1095XDMCP The XDMCP support section has settings that customize how users access remote computers that use KDM. Be aware of the following:
1096• Enable specifies whether kdm listens to incoming XDM Control Protocol (XDMCP) requests.
1097 The default value is true.
1098 If set to false, KDM does not accept incoming requests.
1099• Port specifies the UDP port number KDM uses to listen for incoming XDMCP requests.
1100 The default is 177.
1101 If set to 0, KDM does not accept incoming requests.
1102• Xaccess contains the path to the Xaccess file.
1103 The Xaccess file lists the computers that can access the server using XDMCP, and the computers that can see the chooser broadcasts. It might also list servers to which the requests are forwarded.
1104 The default path is {kde_confdir}/kdm/Xaccess.
1105Xgreeter The Xgreeter section has options to configure the look and content of the login screen. Be aware of the following:
1106• GreetString holds the string users see when logging in. An empty greeting means none at all. The following character pairs query the computer and show the values for the computer in the string:
1107 %d returns the name of the current display
1108 %h returns the local host name, possibly with the domain name
1109 %n returns the local node name, most probably the host name without the domain name
1110 %s returns the operating system
1111 %r returns the operating system version
1112 %m returns the machine (hardware) type
1113 %% returns the a single %
1114• The default is "Welcome to %s at %n".
1115
1116-----
1117The Gnome Display Manager (GDM) is a tool that manages login functions on a local computer or over a network. GDM:
1118• Lets users select a session type and shut down the computer from the login prompt screen.
1119• Uses /etc/X11/gdm/gdm.conf as its main configuration file. This is often a plain text file, but some distributions might use an XML file.
1120• Has a GUI-based configuration tool called gdmsetup. This tool configures color styles, accessibility, and most GDM other functions.
1121The /etc/X11/gdm/gdm.conf file is divided into sections. The following table lists the sections and describes the most commonly configured options in each section these sections
1122Section Description
1123Xserver definitions The X server definitions section tell GDM about the installed X servers. Be aware of the following options:
1124• Name specifies the name that is displayed to the user; used with chooser broadcasts.
1125• Command contains the path to the server executable file.
1126• Flexible specifies whether the Xserver is an on-demand server that starts when GDM receives multiple login requests.
1127• Chooser specifies whether the server displays a chooser list of all Xservers running on the computer rather than a login screen.
1128To define servers, use the /etc/X11/gdm/gdm.conf file, not the gdmsetup tool.
1129Servers The Servers section has commands for initializing the X servers. The lines can be a path to the X server executable or the name of an Xserver definition. GDM can append additional arguments to the command for the path and server definitions.
1130Security options The security options section has options that can implement increased or decreased security depending on the function of the server. Be aware of the following options:
1131• AllowRoot specifies whether users can log in locally using the root account.
1132• AllowRemoteRoot specifies whether users can log in from a remote computer using the root account.
1133• DisallowTCP specifies whether remote connections are disallowed.
1134• RelaxPermissions specifies user permission levels.
1135 When set to 0 it only allows users to access files and directories they own. The default is 0.
1136 When set to 1, they can access group-owned files and directories.
1137 When set to 2, they can access world-writable files and directories.
1138XDMCP support The XDMCP support section has settings that customize how users access remote computers that use GDM. Be aware of the following options:
1139• Enable specifies whether GDM can listen for XDM Control Protocol (XDMCP) requests on the UDP port specified in the Port option.
1140• HonorIndirect enables chooser broadcasts when set to true.
1141• MaxSessions limits the number of simultaneous sessions.
1142• Port identifies the port that GDM uses to listen for XDMCP requests. The default is 177.
1143XDMCP chooser The XDMCP chooser section has settings that determine whether users can see and select from a list of available servers. Be aware of the following options:
1144• Broadcast enables chooser broadcasts when set to true.
1145• Hosts lists the names of hosts outside of the local network that display on chooser broadcast lists.
1146Greeter The greeter section has options to configure the look and content of the login screen. Be aware of the following options:
1147• ChooserButton places a button on the screen that lets the user see a list of available Xservers.
1148• RemoteWelcome holds the string that users see when they log in remotely.
1149• Welcome holds the string that users see when they log in locally. The following character pairs query the computer and show the values for the computer in the string:
1150 %% returns the '%' character
1151 %d returns the display's hostname
1152 %h returns the fully qualified hostname
1153 %m returns the machine (i.e., processor type)
1154 %n returns the Nodename (i.e., hostname without .domain)
1155 %r returns the operating system version.
1156 %s returns the operating system.
1157GDM provides scripts used to customize the login. The scripts are typically located at /etc/gdm/.
1158• The Init script runs as root when GDM initializes the login display. It lets you initialize the display further, and specify programs to run on the login screen.
1159• The PostLogin script runs just after the user types correct login credentials, but before session setup. Use it to set up the home directory, which must be done before the user starts a session.
1160• The PreSession script runs as the session is starting and some setup has already occurred. Use this script to register the session with utmp/wtmp.
1161• The PostSession script runs after the session ends. Use this script to unregister the session with utmp/wtmp.
1162
1163
1164-----
1165Accessibility options (also known as Assistive Technologies (AT)) allow people with tactile, audible, and visual impairments to use Linux systems.
1166The keyboard accessibility options (also known as AccessX) set options such as filtering out accidental keypresses and using shortcut keys without having to hold down several keys at once. The following table describes keyboard accessibility options:
1167Feature Description
1168Sticky keys Sticky keys cause keyboard modifiers keys (i.e., Ctrl, Alt, or Shift) to "stick" when pressed. This affects the next regular key to be pressed even after the release of the sticky key. This is useful for users how have difficulty pressing multiple keys at the same time.
1169Mouse Keys Mouse keys control the mouse pointer with the number keypad.
1170Slow keys Slow keys require a key to be pressed for a specified time period before acceptance. This is useful for individuals who tend to accidentally press keys.
1171Toggle keys Toggle keys associate sounds when the Caps Lock and/or Num Lock is on.
1172Repeat rate Repeat rate affects how quickly the action associated with the key is repeatedly performed when the key is pressed and held down. For example, if you press-and-hold a character key, the character is typed repeatedly according to the repeat rate.
1173Bounce keys Bounce keys ignore fast key presses of the same key, compensating for when users accidentally press a single key multiple times.
1174Visual accessibility options include the following:
1175Feature Description
1176Onscreen keyboard An onscreen keyboard displays an image of keyboard where a user to use a mouse to select keys as if they were pressed on a real keyboard. The GNOME On-Screen Keyboard (GOK) provides the onscreen keyboard, but also helps users navigate the GNOME desktop with the use of alternative input methods, such as:
1177• Blowing and sipping to activate a pneumatic switch
1178• Blinking an eye or a directed gaze with an eye tracking system
1179• Moving the head
1180• Contracting muscles or moving limbs
1181Mouse gesture A mouse gesture allows users to configure Linux to complete a specified task when the mouse is moved in a certain pattern.
1182Screen reader A screen reader reads the text on a screen including menu and button text. Popular screen readers on Linux systems include the following:
1183• Orca is a free, open source scriptable screen reader which works with the GNOME desktop.
1184• Emacspeak is a free screen reader which is often bundled with text editors.
1185Screen magnifier A screen magnifier creates an enlarged view of the area around the mouse pointer by default.
1186Braille devices Linux can use the following Braille hardware devices:
1187• A Braille display is a special type of computer monitor which creates a tactile display of textual information. Many Linux text-mode applications manage Braille display with no configuration changes.
1188• A Braille Embosser prints a hard copy of a text document using embossed Braille characters.
1189BRLTTY provides a Linux daemon that redirects text-mode output to a Braille device.
1190Desktop themes A desktop theme is a preset package containing graphical appearance details. Desktop themes of an assistive nature include:
1191• A high contrast theme displays the background and text colors to improve readability.
1192• A large print theme displays the text in large print to improve readability.
1193
1194
1195-----
1196The Red Hat Package Manager (RPM) is a utility that installs application packages. RPM:
1197• Runs on SUSE, Red Hat, and Fedora distributions.
1198• Installs and configures pre-compiled, pre-configured applications, and services on the system.
1199• Accesses a library containing thousands of packages where the source code is built, compiled, and ready to be installed on a supported Linux architecture or distribution.
1200• Installs, updates, verifies, queries, and uninstalls packages.
1201• Uses a database stored at /var/lib/rpm that keeps track of all installed packages, their current status, and available updates.
1202• Checks for dependencies on other packages and prompts to install these packages if necessary. A dependency is an application's reliance on another package to perform correctly.
1203RPM uses a standard naming convention. Be aware of the following naming convention details:
1204• The syntax is packagename-version-release.architecture.rpm.
1205• Release numbers might contain distribution data:
1206 fcx is for Fedora
1207 rhlx is for Red Hat
1208 susexxx is for version xxx of SUSE
1209• The architecture type specifies the processor:
1210 i386 is for any Intel 80386 or newer processor.
1211 i586 is for any Intel Pentium I or newer processor.
1212 i686 is for any Intel Pentium II or newer processor.
1213 athlon is for any AMD Athlon processor.
1214 noarch is for any architecture (not architecture specific)
1215• For example, acroread-8.1.3-51.6.i586.rpm means the following:
1216Package Name Version Number Release Architecture
1217acroread 8.1.3 51.6 i586
1218The following table lists and describes several common commands for managing RPM packages:
1219Use... To... Examples
1220rpm Use the Red Hat Package Manager (RPM) to manage packages. Be aware of the following options:
1221• --rebuilddb rebuilds the database indices from the installed package headers.
1222• --initdb creates a new database.
1223• --checksig checks the authenticity of the package. The option checks the package's digital signing key against the package to ensure it has not been altered.
1224• -i installs a package. Use the entire package filename when installing.
1225• -h prints hash marks as the package archive is unpacked.
1226• -v displays a verbose version of the installation.
1227• --test tests a package for uninstalled dependencies without actually installing it.
1228• --nodeps installs the package without checking for dependencies. This is not recommended.
1229• --force install the package regardless of whether, a newer version of the package is already installed, package files overwrite files from previously installed packages, or if the package replaces other installed packages.
1230• -e uninstalls (i.e., erases) a package. To uninstall a package, use the package name, not the file name. If dependencies exist, the dependent packages must first be removed.
1231• -U updates an installed package to the newest version.
1232• -F upgrades the package, but only if an earlier version currently exists on the system.
1233• -q queries the computer for information about installed packages.
1234Use this with -a to list all packages and -l show the files associated with the package.
1235• -V verifies that packages are free from errors by performing an MD5 checksum on the package. RPM only gives output when packages have errors. If errors are present, the command displays the error code and the file name. The error codes are:
1236 S indicates a problem in size of a file.
1237 M indicates a problem with a file's mode.
1238 5 indicates a problem with the MD5 checksum of a file.
1239 D indicates a problem with a file's revision numbers.
1240 L indicates a problem with a file's symbolic link.
1241 U indicates a problem with a file's ownership.
1242 G indicates a problem with a file's group.
1243 T indicates a problem with the modification time of a file.
1244 c indicates the specified file is a configuration file.
1245 '.' in place of a code letter indicates that no error is present in that area. rpm --checksig acroread checks the authenticity of the acroread package.
1246rpm -i BackupPC-3.1.0-3.fc9.src.rpm installs the BackupPC package.
1247rpm -ihv http://rpm.sh-linux.org/rpm-fc9/target-SRPMS/BackupPC-3.1.0-3.fc9.src.rpm installs the specified package directly from the Internet.
1248rpm -i --test dbus-python-0.83.0-2.fc9.src.rpm tests the computer for uninstalled dependencies for the dbus-python package.
1249rpm -i --nodeps dbus-python-0.83.0-2.fc9.src.rpm installs the package but does not check for missing dependencies.
1250rpm -i --force dbus-python-0.83.0-2.fc9.src.rpm installs the package regardless of effects on other packages.
1251rpm -e dbus-python removes the package form the computer.
1252rpm -e --nodeps dbus-python removes the package form the computer but does not check for dependent packages.
1253rpm -U dbus-python-0.83.0-2.fc9.src.rpm removes any version older than the specified version and installs the specified package.
1254rpm -U --replacepkgs dbus-python-0.83.0-2.fc9.src.rpm reinstalls the dbus-python package. This option is for fixing errors.
1255rpm -qa displays a list of all installed packages.
1256rpm -qi BackupPC shows all available information about the BackupPC package.
1257rpm -q --whatrequires gmp lists the packages that are dependent on the gmp package.
1258rpm -ql metacity shows the files associated with the metacity package.
1259rpm -q --provides gmp lists the functions that the gmp package provides.
1260rpm -q --requires gmp lists the functions that the gmp package requires.
1261rpm -q --whatprovides /usr/lib/libstlport_gcc.so shows the package that provides the libstlport_gcc.so file.
1262rpm -V BackupPC verifies the BackupPC package.
1263rpm -Va verifies all installed packages.
1264rpm2cpio Convert RPM packages into a cpio archive. This is useful for extracting files from an RPM package without installing and searching for the specific files. rpm2cpio logrotate-1.0-1.i386.rpm > logrotate.cpio converts the files from the logrotate package into a cpio archive.
1265
1266-----
1267The Yellowdog Updater Modified (YUM) is a robust utility that installs Red Hat Package Manager (RPM) packages. YUM:
1268• Is used on Red Hat, Fedora, and other compatible distributions.
1269• Checks the dependencies of the RPM packages, and automatically installs or updates any dependencies as needed.
1270• Keeps and updates a file that lists all packages in Internet repositories.
1271• Uses /etc/yum.conf as the configuration file. The configuration file contains:
1272 URLs of RPM repositories.
1273 Directories where it saves downloaded packages.
1274 Locations of logs.
1275• Uses /etc/yum.repos.d/ to keep a .repo file for each Internet repository. To change where Linux looks for new or updated packages, add .repo files to this directory.
1276• Uses /var/usr/yum.log as a log file to track when packages are installed, removed, or downloaded.
1277The following table lists and describes several common commands for managing RPM packages:
1278Use... To... Example
1279yum Install RPM packages included their dependencies. Be aware of the following actions and options:
1280• list displays lists of packages.
1281• install installs a package. Use the entire package filename when installing.
1282• list updates displays whether updates are available for packages.
1283• update updates RPM packages.
1284• list available lists packages that are available to install.
1285• search searches all packages for a specified term.
1286• info displays detailed package information.
1287• provides, whatprovides displays what packages are associated with a specific file.
1288• remove, erase uninstalls a package.
1289• -y bypasses confirmation prompts. yum list all shows all packages in the repository and installed on the computer.
1290yum list javahelp2.noarch searches for the javahelp2.noarch package in the repository.
1291yum list *help* lists all packages in the repository that have the string help somewhere in the name.
1292yum list installed mtools.i686 shows whether the mtools.i686 package is installed on the computer.
1293yum install BackupPC-3.1.0-3.fc9.src.rpm installs the BackupPC package and any package dependencies.
1294yum install http://rpm.sh-linux.org/rpm-fc9/target-SRPMS/BackupPC-3.1.0-3.fc9.src.rpm installs the specified package directly from the Internet.
1295yum list update mtools.i686 looks for an update for the mtools.i686 package and updates it if one is available.
1296yum update sssd.i686 updates the sssd.i686 package.
1297yum update updates all installed packages.
1298yum list available shows the available packages.
1299yum search Java searches all package information and descriptions for the term Java.
1300yum info zuff.i686 shows information about the zuff.i686 package.
1301yum whatprovides /etc/updatedb.conf shows what packages are associated with the updatedb.conf file.
1302yum remove kdegames.i686 uninstalls the kdegames.i686 package from your computer.
1303yum -y update updates all packages without requesting confirmation prompts.
1304yumdownloader Download a package without installing it. yumdownloader zuff.i686 downloads the zuff package, but does not install it.
1305createrepo Create a repository list of RPM packages stored locally or on a network. Be aware of the following options:
1306• -g specifies an xml file for the repository.
1307• -x excludes specific file globs. createrepo -g packagefile.xml creates a list of packages using the .xml file
1308
1309-----
1310Debian packages are preconfigured installation packages similar to RPM packages. Debian packages:
1311• Are compatible with distributions that do not use RPMs, including Ubuntu, Knoppix, and Linspire.
1312• Use naming conventions similar to RPM naming conventions, but use a .deb file extension.
1313• Include dependency information.
1314• Are not natively compatible with RPM.
1315The following table lists and describes several common commands for managing Debian packages:
1316Use... To... Examples
1317dpkg Install Debian packages on Debian distributions. Be aware of the following dpkg options:
1318• -i installs a package.
1319• --configure reconfigures an unpacked package.
1320• -r removes the package but does not delete the configuration files.
1321• -P completely uninstall the package including the configuration files.
1322• -p lists information about a currently installed Debian package.
1323• -I (uppercase i) or --info lists information about packages that are not installed.
1324• -l (lowercase L) displays all packages with names that match a specified pattern.
1325• -L shows the installed files for a package.
1326• -S finds a package associated with specified files.
1327• -C searches for packages that have been installed only partially on the system.
1328• B disables packages that have dependencies on the package being removed.
1329• --ignore-depends ignores dependency-checking for specified packages.
1330• -no-act prevents changes from being written.
1331• -G prevents a package from being installed if a newer version of the package already exists on the computer.
1332• -E does not install the package if the same version of the package is already installed.
1333• -R installs the package recursively.
1334The dpkg-reconfigure command reconfigures an already installed package. dpkg -i docbook_4.5-4_all.deb installs the docbook package.
1335dpkg -r docbook removes the docbook package.
1336dpkg -P docbook removes the docbook package and its configuration files.
1337dpkg -i docbook displays information about the package.
1338dpkg -I dwm-tools_26-2_i386.deb displays information about the dwm-tools package.
1339dpkg -l kcheckers* lists all packages that begin with kcheckers.
1340dpkg -L docbook lists all files installed with the docbook package.
1341dpkg -S /usr/share/base-files/motd shows the package associated with the motd file.
1342dpkg -B -r docbook removes the docbook package and disables any package dependant on the docbook package.
1343dpkg -G -i docbook_4.5-4_all.deb installs the docbook package if it is a newer version than a previously installed package.
1344apt-cache Retrieve information about the Debian package database. Be aware of the following apt-cache options:
1345• showpkg displays information about a package in the database.
1346• stats shows the number of packages installed, dependency information, and other package cache statistics.
1347• unmet lists any missing dependencies in the package cache.
1348• depends shows all of the package’s dependencies.
1349• pkgnames displays whether a package is installed on the system. When the package name is left off, the command shows information for all packages on the computer.
1350• search searches for a package in the cache. apt-cache showpkg 3dchess_0.8.1-15_i386.deb shows information about the 3dchess package.
1351apt-cache depends 3dchess_0.8.1-15_i386.deb shows dependency information for the 3dchess package.
1352apt-cache pkgnames 3dchess displays whether the 3dchess package is installed.
1353apt-cache search kde searches for all packages that contain kde anywhere in the name.
1354apt-get Download and install packages. apt-get:
1355• Is similar to the yum utility on an RPM distribution.
1356• Gets its information about the application repositories from the /etc/apt/sources.list file.
1357Be aware of the following apt-get options:
1358• update updates /etc/apt/sources.list with the latest information about available packages.
1359• upgrade upgrades all installed packages to the latest versions in accordance with the information in /etc/apt/sources.list.
1360• dist-upgrade shows all of the package’s dependencies.
1361• install installs a package using the package name. The package name is not the file name. During the install, apt-get retrieves the most recent version of the package.
1362• remove removes a specified package, but leaves the configuration files.
1363• purge removes the package and the configuration files.
1364• source retrieves the latest version of the package. The command accesses the /etc/apt/sources.list file to determine whether the latest package version is installed.
1365• check checks the package database for consistency and errors.
1366• clean removes unneeded package information files and logs. This command is needed when not using the dselect utility to install Debian packages.
1367• autoclean removes information files about packages that can no longer be downloaded.
1368• -d downloads packages without installing them.
1369• -f attempts to fix a computer with unsatisfied dependencies. Use this with apt-get install and apt-get remove.
1370• -m ignores package files that cannot be accessed or located.
1371• -q shows less progress information.
1372• -s simulates package installation without doing an actual install.
1373• -y automatically provides a yes response to yes / no questions in the package installation script. apt-get dist-upgrade 3dchess shows dependency information for the 3dchess package.
1374apt-get install 3dchess_0.8.1-15_i386.deb installs the 3dchess package.
1375apt-get remove 3dchess removes the 3dchess package but leaves the 3dchess configuration files.
1376apt-get purge 3dchess removes the 3dchess package along with the 3dchess configuration files.
1377Before purge was added as a command in the apt-get utility, --purge had to be used as an option with the remove command, for example apt-get remove --purge 3dchess (this older syntax is still supported)
1378apt-get source 3dchess determines whether a newer version of 3dchess is available, and if so, installs it.
1379apt-get -d install 3dchess_0.8.1-15_i386.deb downloads the 3dchess package without installing it.
1380apt-get -f install 3dchess_0.8.1-15_i386.deb tries to fix dependency issues for the 3dchess package.
1381apt-get -m remove 3dchess removes the 3dchess package but ignores missing files.
1382apt-get -q remove 3dchess removes the 3dchess package but shows less of the information during the process.
1383apt-get -s install 3dchess_0.8.1-15_i386.deb tests the installation process of the 3dchess package without installing it.
1384apt-get -y install 3dchess_0.8.1-15_i386.deb installs the 3dchess package and automatically provides a yes answer to any yes/no prompts.
1385aptitude View the list of packages and perform package management tasks such as installing, upgrading, and removing packages in the Advanced Packaging Tool (APT). aptitude is the front-end to APT. It displays a list of software packages and allows the user to interactively pick packages to install or remove.
1386
1387-----
1388Shared libraries are code loaded into memory and reused by several different programs. This allows the program file size to be relatively small, as it will use a shared amount of library code when necessary. In addition, updated code within the shared libraries allows each applicable program to take advantage of the improvements. Shared libraries can create the following software management complications:
1389• Changes in the shared library can be incompatible with some of the programs that use the library.
1390• Programs may not be able to locate the shared library.
1391• A shared library can become inaccessible if it is overwritten or updated. For instance, problems may occur if two different packages that include the same shared library are installed.
1392There a two types of shared libraries:
1393Type Description
1394Dynamic Dynamic libraries are not integrated into the code of the application. Dynamic libraries:
1395• Have a .so or .so.version extension (.so stands for shared object).
1396• Are typically stored in /usr/lib/ and /usr/local/lib/.
1397• Can degrade program load time if the library isn't already in use by another program.
1398• Are similar to Dynamic Link Libraries (DLLs) in Windows.
1399Be aware of the following management programs and files for dynamic libraries:
1400• /lib/ld.so is a program which finds and loads the shared libraries needed by a program. It also prepares the program to run and executes it.
1401• /etc/ld.so.conf is a file which contains a list of colon, space, tab, newline, or comma-separated directories in which to search for libraries. Some lines in the file begin with the include directive which list files that are to be included as if they were part of the main file.
1402• /etc/ld.so.cache is a cached list of libraries found in the directories specified in /etc/ld.so.conf. The system uses this cached list instead of loading /etc/ld.so.conf every time a program runs.
1403Use the following methods for configuring dynamic libraries on a Linux system:
1404• Modify /etc/ld.so.conf to add the path of the libraries.
1405• Use the LD_LIBRARY_PATH environment variable to specify additional directories to search for library files.
1406Static Static libraries are integrated into the code of the application when the code is compiled. Static libraries:
1407• Have an .a filename extension.
1408• Are used when dynamic libraries are not available.
1409• Increase the size of the application.
1410Be aware of the following library management commands:
1411Use... To...
1412ldd Discover which libraries are used by another library (i.e., library dependencies).
1413• When using ldd to track down problems, check the complete dependency chain.
1414• Run ldd as root (recommended).
1415Be aware of the following options:
1416• -v displays all information.
1417• -u displays unused direct dependencies.
1418• --version displays the version number of ldd.
1419ldconfig Reload the library cache every time libraries are added or removed, and update the symbolic links. This creates the necessary links and cache for the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib). Be aware of the following options:
1420• -v summarizes the directories and files it is registering as it reloads the cache.
1421• -N updates symbolic links, but does not update the cache.
1422• -n updates the links contained in the directories specified on the command line.
1423• -X updates the cache but does not update symbolic links.
1424• -f changes the configuration file from /etc/ld.so.conf default.
1425• -C changes the cache location for the /etc/ld.so.cache default.
1426• -r treats a new directory as if were the root directory. This is helpful when you are recovering a badly corrupted system or installing a new OS.
1427• -p displays the current library cache, including all the library directories and their respective libraries.
1428
1429-----
1430User accounts control the ability to log on to a system, access resources, and perform certain actions. Groups provide a means of grouping users for administrative purposes such as assigning permissions to files. Be aware of the following types of users and groups:
1431Type Description
1432Standard user Standard user accounts can log into the system. Standard user accounts:
1433• Have friendly usernames (such as mary or bkaun). An administrator must create the user names.
1434• Have an ID of 500 or more for Fedora, or 1000 or more for SUSE. The ID is automatically assigned by the system when the account is created.
1435System user System user accounts are created by default during the Linux installation and are used by the system for specific roles. System user accounts:
1436• Have names that correspond with their roles, such as ftp and mail.
1437• Cannot be used to log into the system.
1438The root user account is created by default and has a UID of 0; however, it can be used to log into a system and perform tasks.
1439Primary group Primary groups (also called the private group) are created when a standard user is created. Primary groups:
1440• Have the corresponding user as the only member.
1441• Are automatically made the owner of files and directories when they are created.
1442• Are similar to any other group; however, the only difference is that the user account specifically identifies the primary group for each user.
1443Secondary groups Secondary groups are used to manage access to files and directories. Secondary groups:
1444• Have friendly names (such as sales or accounting). An administrator must assign secondary group names.
1445• Receive their membership as assigned by the system administrator.
1446The user and group databases are stored in the following files:
1447File Description
1448/etc/passwd The /etc/passwd file holds user account information. Be aware of the following details:
1449• Each entry identifies a user account.
1450• Each entry contains multiple fields, with each field separated by a colon.
1451The following line is a sample entry in the /etc/passwd file:
1452pclark:x:501:501:Petunia Clark:/home/pclark:/bin/bash
1453The fields within this line are as follows:
14541. User account name.
14552. Password. An x in the field indicates passwords are stored in the /etc/shadow file.
14563. User ID number.
14574. Primary group ID number (also known as the default group ID number). Typically this number matches the UID number.
14585. GECOS field. This field is typically used for a description or the user's full name.
14596. Path to the home directory.
14607. Path to the default shell.
1461/etc/shadow The /etc/shadow file holds passwords and password expiration information for user accounts. Be aware of the following details:
1462• Using the /etc/shadow file to separate usernames from passwords increases the security of the user passwords.
1463• Like the /etc/passwd file, each entry corresponds to a user account and each entry contains multiple fields, with each field separated by a colon.
1464The following line is a sample entry in the /etc/shadow file:
1465pclark:$ab7Y56gu9bs:12567:0:99999:7:::
1466The fields within this line are as follows:
14671. User account name.
14682. Password.
1469o $ preceding the password identifies the password as an encrypted entry.
1470o ! or !! indicates the account is locked and cannot be used to log in.
1471o * indicates a system account entry and cannot be used to log in.
14723. Last change. The date of the most recent password change, measured in the number of days since 1 January 1970.
14734. Minimum password age. The minimum number of days the user must wait before changing the password.
14745. Maximum password age. The maximum number of days between password changes.
14756. Password change warning. The number of days a user is warned before the password must be changed.
14767. Grace logins. The number of days the user can log in without changing the password.
14778. Disable time. The number of days since 1 January 1970, after which the account will be disabled.
1478/etc/group The /etc/group file holds group information including the group name, GID, and group membership information. Be aware of the following details:
1479• Each entry identifies a group.
1480• Each entry contains multiple fields, with each field separated by a colon.
1481The following line is a sample entry in the /etc/group file:
1482sales:x:510:pclark,mmckay,hsamson
1483The fields within this line are as follows:
14841. Group name.
14852. Group password. An x indicates the group passwords are contained in the /etc/gshadow file.
14863. Group ID.
14874. Group members. Contains a comma-separated list of user accounts that are members of the group.
1488/etc/gshadow The /etc/gshadow file holds passwords for groups. Be aware of the following details:
1489• Like the /etc/group file, each line corresponds to a group.
1490• Each line consists of fields separated by colons.
1491The following line is a sample entry in the /etc/gshadow file:
1492sales:!:pclark:pclark,mmckay,hsamson
1493The fields within this line are as follows:
14941. Group name.
14952. Group password. The group password allows users to add themselves as members of the account.
1496o If the field contains a single exclamation point (!), the group account cannot be accessed using the password.
1497o If the field contains a double exclamation point (!!), no password has been assigned to the group account (and it cannot be accessed using the password).
1498o If there is no value, only group members can log in to the group account.
14993. Administrators. Contains a comma-separated list of users who have authorization to administer the account.
15004. Group members. Contains a comma-separated list of user accounts that are members of the group.
1501Be aware of the following details:
1502• User and group account information can also be managed through the following network services. Each service can query network servers for user authentication parameters, such as usernames and passwords.
1503 OpenLDAP is an open source implementation of the Lightweight Directory Access Protocol (LDAP).
1504 Network Information System (NIS) allows many Linux computers to share a set of username and password parameters.
1505 Windows Domain allows access to a central directory database that stores security and user account information.
1506• The pwck command verifies the entries in the /etc/passwd and /etc/shadow files. Errors are displayed on the screen, and entries may be deleted to solve the errors.
1507• The pwconv command synchronizes the entries in the /etc/passwd and /etc/shadow files.
1508
1509-----
1510Be aware of the following configuration files when managing user accounts:
1511File Description
1512/etc/default/useradd The /etc/default/useradd file contains default values used by the useradd utility when creating a user account, including:
1513• Group ID
1514• Home directory
1515• Account expiration
1516• Default shell
1517• Secondary group membership
1518/etc/login.defs The /etc/login.defs file contains:
1519• Values used for the group and user ID numbers.
1520• Parameters for passwords encryption in the shadow file.
1521• Password expiration values for user accounts.
1522/etc/skel The /etc/skel directory contains a set of configuration file templates that are copied into a new user's home directory when it is created, including the following files:
1523• .bashrc
1524• .bash_logout
1525• .bash_profile
1526• .kshrc
1527Although it is possible to edit the /etc/passwd and /etc/shadow files manually to manage user accounts, doing so can disable your system. Instead, use the following commands to manage user accounts:
1528Use... To... Example
1529useradd Create a user account. The following options override the settings as found in /etc/default/useradd:
1530• -c adds a description for the account in the GECOS field of /etc/passwd.
1531• -d assigns an absolute pathname to a custom home directory location.
1532• -D displays the default values specified in the /etc/default/useradd file.
1533• -e specifies the date on which the user account will be disabled.
1534• -f specifies the number of days after a password expires until the account is permanently disabled.
1535• -g defines the primary group membership.
1536• -G defines the secondary group membership.
1537• -M does not create the user's home directory.
1538• -m creates the user's home directory (if it does not exist).
1539• -n, N does not create a group with the same name as the user (Red Hat and Fedora respectively).
1540• -p defines the encrypted password.
1541• -r specifies the user account is a system user.
1542• -s defines the default shell.
1543• -u assigns the user a custom UID. This is useful when assigning ownership of files and directories to a different user. useradd pmaxwell creates the pmaxwell user account.
1544useradd -c "Paul Morril" pmorril creates the pmorril account with a comment.
1545useradd -d /tmpusr/sales1 sales1 creates the sales1 user account with home directory located at /tmpusr/sales1.
1546useradd -u 789 dphilips creates the dphilips account with user ID 789.
1547passwd Assign or change a password for a user.
1548• passwd (without a username or options) changes the current user's password.
1549• Users can change their own passwords. The root user can execute all other passwd commands.
1550Be aware of the following options:
1551• -S username displays the status of the user account.
1552 LK indicates the user account is locked.
1553 PS indicates the user account has a password.
1554• -l disables (locks) an account. This command inserts a !! before the password in the /etc/shadow file, effectively disabling the account.
1555• -u enables (unlocks) an account.
1556• -d removes the password from an account.
1557• -n sets the minimum number of days a password exists before it can be changed.
1558• -x sets the number of days before a user must change the password (password expiration time).
1559• -w sets the number of days before the password expires that the user is warned.
1560• -i sets the number of days following the password expiration that the account will be disabled. passwd jsmith changes the password for the jsmith account.
1561passwd -d removes the password from an account.
1562passwd -d jsmith removes the password from the jsmith account.
1563passwd -x 40 jsmith requires jsmith to change his password every 40 days.
1564passwd -n 10 jsmith means that jsmith cannot change his password for 10 days following the most recent change.
1565passwd -w 2 jsmith means that jsmith will be warned 2 days before his password expires.
1566passwd -i 7 jsmith disables the jsmith account after 7 days if the password is not changed.
1567passwd -l jsmith locks the jsmith account.
1568passwd -u jsmith unlocks the jsmith account.
1569
1570usermod Modify an existing user account. usermod uses several of the same switches as useradd. Be aware of the following switches:
1571• -c changes the description for the account.
1572• -l renames a user account. When renaming the account:
1573 Use -d to rename the home directory.
1574 Use -m to copy all files from the existing home directory to the new home directory.
1575• -L locks the user account. This command inserts a ! before the password in the /etc/shadow file, effectively disabling the account.
1576• -U unlocks the user account. usermod -c "Paul Morril" pmorril changes the comment field for user pmorril.
1577usermod -l esmith -d /home/esmith -m ejones renames the ejones account to esmith, renames the home directory, and moves the old home directory contents to the new location.
1578usermod -s /bin/tsch esmith points the shell for esmith to /bin/tsch.
1579usermod -U esmith unlocks the esmith account.
1580userdel Remove the user from the system. Be aware of the following options:
1581• userdel username (without options) removes the user account.
1582• -r removes the user's home directory.
1583• -f forces the removal of the user account even when the user is logged into the system. userdel pmaxwell deletes the pmaxwell account while leaving the home directory on the hard drive.
1584userdel -r pmorril removes both the account and the home directory.
1585
1586-----
1587Use the following commands and options to manage group accounts and group membership:
1588Use... To... Example
1589groupadd Create a new group. The following options override the settings as found in /etc/login.defs:
1590• -g defines the group ID (GID).
1591• -p defines the group password.
1592• -r creates a system group. groupadd sales creates the sales group.
1593groupmod Modify a group definition. Be aware of the following options:
1594• -n changes the name of a group.
1595• -A adds specified users from the group (SUSE distribution)
1596• -R removes specified users from the group (SUSE distribution) groupmod -n sales2 sales renames the sales group to sales2.
1597groupmod -R rsem sales removes the rsem account from the sales group.
1598groupdel Delete a group. groupdel mktg deletes the mktg group
1599gpasswd Change a group password.
1600• groupname prompts for a new password.
1601• -r removes a group password). gpasswd sales prompts for a new group password
1602newgrp Log in to a new group with the group password. newgrp sales prompts for the password for the sales group before logging in.
1603usermod Modify group membership for the user account. Be aware of the following options:
1604• -g assigns a user to a primary group.
1605• -G assigns a user to a secondary group (or groups). Follow the command with a comma-separated list of groups. If the user already belongs to any secondary groups, the user will be removed from those groups if the groups are not in the list.
1606• -Ga assigns a user to a secondary group (or groups) by appending them to any groups the user already belongs to. Follow the command with a comma-separated list of groups.
1607• -G "" Remove the user from all secondary group memberships. Do not include a space between the quotes. useradd -g pmaxwell pmaxwell assigns primary group membership for user pmaxwell to the pmaxwell group.
1608usermod -G sales,mktg pmorril removes all existing secondary group assignments for pmorril and makes the user account a member of the sales and mktg groups.
1609usermod -Ga acct,prod pmorril keeps existing secondary group assignments for pmorril intact and makes the user account a member of the acct and prod groups.
1610usermod -G "" pmaxwell removes the pmaxwell from all groups.
1611groups Display the primary and secondary group membership for the specified user account. groups pmaxwell displays group membership for the pmaxwell account.
1612The command options listed here are not applicable to every distribution of Linux. Consult the man pages for the options that are supported by the Linux distribution you are using.
1613
1614-----
1615A partition is a logical division of a storage device associated with a hard disk drive. A hard disk drive can have a single partition or multiple partitions. One common partitioning scheme divides a disk into primary and extended partitions.
1616
1617Partition Type Description
1618Primary A primary partition is one that is used to store the operating system. Primary partitions:
1619Can hold operating system boot files.
1620Cannot be further subdivided into logical drives.
1621Can be formatted.
1622There can be a maximum of four primary partitions on a single hard disk drive.
1623Extended An extended partition is an optional partition that does not have an operating system installed on it and thus is not bootable. Extended partitions:
1624Can be further subdivided into an unlimited number of logical drives.
1625Cannot be formatted.
1626There can be a maximum of one extended partition on a single hard disk drive.
1627Use the following tools to create and manage partitions:
1628
1629Use... To...
1630fdisk Launch the fdisk utility and create partitions on a hard disk. fdisk is an interactive utility which requires values and decisions to create partitions. Be aware of the following details:
1631fdisk requests a beginning/ending cylinder or size when creating a partition. The size is indicated using K (Kilobytes), M (Megabytes), or G (Gigabytes).
1632fdisk uses hexadecimal codes to determine the partition type. Common hexadecimal codes include:
16330x82 Linux swap
16340x83 Linux partition
16350x85 Linux extended partition
16360x8e Linux logical partition
1637fdisk -l lists the current partition configuration on the system.
1638Type fdisk device_name at the command prompt to enter the fdisk utility. Be aware of the following options within fdisk:
1639
1640l lists the partition types supported.
1641m opens the help file.
1642n creates a new partition.
1643p displays the partition table for that device.
1644q exits fdisk without saving changes.
1645w writes the partition table to disk (i.e., saves the file) and exits the fdisk utility.
1646d deletes a partition.
1647partprobe Request that the operating system re-read the partition table. The operating system kernel reads the partition table and recognizes the table changes.
1648
1649-----
1650Storage devices in Linux are represented by device files.
1651• Device files are located in the /dev directory.
1652• The /dev directory contains files for all types of devices, even those that don't exist on the system.
1653• Not only do device files represent devices, they indicate how data is transferred to that device.
1654• Devices, like storage devices, that receive data in block transfers by using memory to buffer the transfers are called block devices. Devices that send data transfers character-by-character (like the keyboard) are called character devices.
1655The table below lists and describes the most common device files.
1656Device File Description
1657/dev/sdxn sd files identify hard drives. A letter (beginning with a) follows the sd designation and identifies the ID of the hard drive. At the end is appended a number (beginning with 1) that identifies the partition on the drive. Examples include:
1658• sda2 is the second partition (2) on the hard drive with the lowest ID number (a)
1659• sdc1 is the first partition (1) on the drive with the third lowest ID number (c)
1660• sda1 is the first partition (1) on the hard drive with the lowest ID number (a)
1661• sdb3 is the third partition (3) on the drive with the second lowest ID number (b)
1662• sdc2 is the second partition (2) on the drive with the third lowest ID number (c)
1663• sdd1 is the first partition (1) on the drive with the forth lowest ID number (d)
1664Some systems will use /dev/srx instead.
1665/dev/cdrom This is a special designation used to identify the CD-ROM in the system. In reality, the /dev/cdrom ID is just a symbolic link to the actual device (sr0).
1666/dev/fdn fd files identify floppy drives. Device numbering begins at 0. For example, /dev/fd0 is the first floppy drive.
1667/dev/ttyn tty files identify local terminals on the system. Device numbering begins at 0. Subsequent terminals are represented with files that increment by one (e.g., the file for terminal two is /dev/tty2, and so on).
1668/dev/ttySn ttyS files identify serial ports. Device numbering begins at 0. Files for subsequent serial ports are represented by files that increment by one (e.g., the file for serial port two is /dev/ttyS1, and so on).
1669/dev/lpn lp files identify parallel ports. Device numbering begins at 0. Files for subsequent parallel ports are represented by files that increment by one (e.g., the file for parallel port two is /dev/lp1, and so on).
1670/dev/usb/file_name USB devices have their own subdirectory of files to support up to 127 USB devices.
1671/dev/psaux This file is for the PS/2 mouse port.
1672/dev/stn st files identify SCSI tape devices. Device numbering begins at 0.
1673
1674-----
1675The Logical Volume Manager (LVM) provides an alternative methods to manage partitions on a Linux system. LVM gives a system administrator more flexibility in allocating storage on a system. Important aspects of LVM include:
1676• You can (within certain limits) resize and move logical volumes while they are still mounted and running.
1677• Logical volumes may be identified by using descriptive names (i.e., research or marketing) instead of physical disk names such as /dev/sda and /dev/sdb.
1678The following table describes common LVM commands:
1679Command Description Examples
1680pvcreate Initializes physical volume for later use by the Logical Volume Manager (LVM). pvcreate /dev/sdb creates a physical volume on the second hard disk in the system.
1681pvcreate /dev/sdd creates a physical volume on the fourth hard disk in the system.
1682pvscan Scans all disks for physical volumes and displays the result. pvscan displays all found physical volumes on the system and their associated volume groups.
1683vgcreate Creates a new volume group. vgcreate system /dev/sdb creates a volume group named system on the second hard disk in the system.
1684vgcreate backup /dev/sdd creates a volume group named backup on the fourth hard disk in the system.
1685vgextend Adds one or more initialized physical volumes to an existing volume group to extend it in size. vgextend system /dev/sdc adds the third hard disk in the system to the system volume group.
1686lvcreate Creates a new logical volume in a volume group. Options include:
1687• -L specifies the size. Use the following size suffixes:
1688 K for kilobytes
1689 M for megabytes
1690 G for gigabytes
1691 T for terabytes
1692 P for petabytes
1693 E for exabytes
1694• -n specifies the name lvcreate -L 20G -n data system creates a 20 Gigabyte logical volume, named data, on the system volume group.
1695lvcreate -L 2T -n Storage1 backup creates a 2 Terabyte logical volume, named Storage1, on the backup volume group.
1696lvcreate -L 1T -n Storage2 backup creates a 1 Terabyte logical volume, named Storage2, on the backup volume group.
1697lvscan Scans all known volume groups or all supported LVM block devices in the system for logical volumes and displays the result. lvscan displays all of the logical volumes on the system.
1698lvextend Extends the size of a logical volume. Options include:
1699• -L specifies the new size of volume. Be aware of the following:
1700 -L +size specifies an increase in the size of volume.
1701 The omission of the -L option will increase the size of the logical volume by the amount of free space on physical volume.
1702• logicalvolume specifies which logical volume to extend.
1703• physicalvolume specifies the physical volume to use for the extension. lvextend -L 30G data extends the data logical volume to a total of 30 Gigabytes.
1704lvextend -L +10G data extends the data logical volume by another 10 Gigabytes.
1705lvextend -L +10G data /dev/sde extends the data logical volume by another 10 Gigabytes on the physical volume for /dev/sde.
1706lvextend data /dev/sde extends the data logical to all of the free space on the physical volume for /dev/sde.
1707
1708-----
1709The file system determines how a computer's files are organized on a hard drive. Linux supports many different file system types. The table below describes several common file systems.
1710File System Type Characteristics
1711ext2 The second extended file system supports Access Control Lists to control individual permissions, but it does not support journaling.
1712ext3 By layering it atop the ext2 file system, the third extended file system (ext3) supports journaling, so it has faster startup and recovery times. However, because it is tied to ext2, it doesn't offer the full performance capabilities available through a pure journaling file system. This is the most common Linux file system.
1713ext4 Ext4 is the latest version in the ext file system family. Ext4 can handle files up to 16 terabytes and disk sizes up to 1 exabyte.
1714swap A swap file system is used as virtual memory (the portion of the hard disk used to temporarily store portions of main memory) by the operating system. (A recommended practice is to make the swap file equal in size to the amount of memory on the computer.)
1715reiserfs The Reiser file system (ReiserFS) is a newer Linux file system that calculates and proposes the best options for the file system. Because ReiserFS was independently built from the ground up, its journaling capability is native and more robust, offering a great deal of reliability. It is also more efficient at storing small files than other file systems. However, data corruption can occur if power goes out during disk synchronizations. Also, defragmentation tools are not available for this file system.
1716ntfs Microsoft operating systems use NTFS (New Technology File System). Linux can only read ntfs partitions created using Windows 2000 and later, and can write to NTFS file systems created with MS operating system prior to Windows 2000. However, utilities such as ntfsprogs may enable read/write access on all ntfs partitions.
1717vfat VFAT is a FAT32 filesystem for Linux and does not support journaling. VFAT includes long name support. Support for vfat must be compiled into the kernel for the system to recognize the vfat format.
1718xfs The XFS file system was developed for Silicon Graphics IRIX operating system. An XFS file system is proficient at handling large files, offers smooth data transfers, and provides journaling. It also can reside on a regular disk partition or on a logical volume.
1719A disk partition must be formatted using a file system. The following table describes the commands needed to format a partition.
1720Use... To... Example
1721mkfs Create an ext2, ext3, or fat file system. Mkfs uses the following options:
1722• -t file_system_type determines the file system. File system types include:
1723 ext2 (identical to the mkfs.ext2 command)
1724 ext3 (identical to mkfs.ext3)
1725 ext4 (identical to mkfs.ext4)
1726 msdos (identical to mkfs.msdos)
1727 reiserfs (identical to mkreiserfs)
1728• -b specifies the block size. Supported values are 1024, 2048, or 4096.
1729• -i determines how many inodes are on the partition and uses the same values as -b.
1730• -j appends a journal to an ext2 file system.
1731Without the -b and -i options, mkfs calculates the values automatically. mkfs -t ext2 /dev/sda4 creates an ext2 file system on the fourth partition on the first hard disk drive.
1732mkfs -t ext3 /dev/sda1 creates an ext3 file system on the first partition on the first hard disk drive.
1733mkfs -t ext3 /dev/sdc2 creates an ext3 file system on the second partition on the third hard disk drive.
1734mkfs -t ext4 /dev/sdb1 creates an ext4 file system on the first partition on the second hard disk drive.
1735
1736mkreiserfs Create a ReiserFS. mkreiserfs /dev/sda2 formats the second partition on the first hard disk with the Reiser file system.
1737mkswap Create a swap partition. A swap partition is the location on the hard drive where an operating system writes memory information when it runs out of RAM. Mkswap:
1738• Requires the additional command swapon to activate the swap partition.
1739• Uses the swapoff command to deactivate swap partitions.
1740Swapon and swapoff use the -a option to specify all swap partitions listed in /etc/fstab. mkswap /dev/sda2 formats the second hard drive as the swap partition.
1741swapon /dev/sda2 activates second hard drive as the swap partition.
1742swapon -a activates all swap partitions.
1743swapoff /dev/sda2 deactivates second hard drive as the swap partition.
1744swapoff -a deactivates all swap partitions.
1745mke2fs Create an ext2, ext3, or ext4 file system. Command options include:
1746• -b specifies the block size of the file system in Bytes (valid sizes are 1024, 2048 and 4096 bytes per block)
1747• -j creates the file system with an ext3 journal
1748• -L sets the volume label for the file system
1749• -n displays what mke2fs would do if it created a file system, but does not actually create the file system
1750• -t specify the file system type (i.e., ext2, ext3, ext4, etc.) that is to be created mke2fs /dev/sda2 creates an ext2 file system on the second partition on the first hard disk drive.
1751mke2fs -j /dev/sda1 creates an ext3 file system on the first partition on the first hard disk drive.
1752mke2fs -t ext4 /dev/sdc3 creates an ext4 file system on the third partition on the third hard disk drive.
1753Keep the following in mind when working with file systems:
1754• Linux cannot format an extended partition; however, it can create logical partitions inside an extended partition for formatting.
1755• File systems use an inode (information node) table to store information about files. An inode specifies where a file's data physically exists on a disk. Inodes also contain additional information including:
1756 File size
1757 Modification, access, and creation times
1758 Permissions
1759 Ownership
1760• Each file system has a superblock, which contains information about the file system, such as:
1761 File system type (e.g., ext2 and ext3)
1762 Size (e.g., 10GB and 360GB)
1763 Status
1764• Linux maintains multiple redundant copies of the superblock in every filesystem.
1765
1766-----
1767Mounting is the process of making a device accessible to users through the directory tree. The directory to which the device or partition is attached is called the mount point.
1768• Volumes are represented by files located in the /dev directory; however, volumes must be mounted before use.
1769• A volume is mounted to a directory. When accessing the directory in the file system, you are actually accessing the volume mounted to that directory.
1770• Always mount volumes and other storage devices to empty directories. Mounting a volume to a directory that contains data makes the data inaccessible.
1771• The /mnt and /media directories (depending on the system configuration) are directories that contain mount points specifically for external storage devices (e.g., CD-ROM drives, floppy drives, magnetic tape drives).
1772The following files manage and monitor the mounting of file systems:
1773File Description
1774/etc/fstab The /etc/fstab file identifies volumes to mount each time the system boots. When the system boots, it automatically mounts the volumes identified in the file. The file contains entries with six fields that control how a device is mounted. A common entry is shown below:
1775/dev/hda3 /mnt/disk1 ext3 auto,ro,nosuid,users 0 1
1776The fields in entry are as follows:
1777• Device to mount is the path to the device file or the label that describes the volume.
1778• Mount point specifies where to mount the device. This is the directory to which the device is attached.
1779• file system type specifies the device's file system type.
1780• Options specifies the additional options accepted when mounting the device. Options can be strung together in a comma-separated list. Be aware of the following options:
1781 sync reads all I/O files synchronously. (async disables this function.)
1782 atime updates the timestamp on file's inode. (noatime disables this function.)
1783 auto allows the volume to be mounted automatically. Use the auto parameter typically with floppy devices.
1784 noauto prevents the volume from being mounted automatically. Use this option for removable media.
1785 dev allows block files to be read from the volume. (nodev disables this function.)
1786 exec allows programs and script files to run from the volume. (noexec disables this function.)
1787 owner identifies that only the device owner can mount the volume.
1788 ro mounts the volume read only.
1789 rw mounts the volume read/write.
1790 suid allows the SUID bit to be set on files in the volume. (nosuid disables this function.)
1791 user identifies a specific user who can mount the volume.
1792 nouser allows only the root user to mount the volume.
1793 users allows any user to mount the volume.
1794 defaults uses the following default settings: rw, suid, dev, exec, auto, nouser, and async.
1795• Dump## is used by the dump command when backing up the file system.
1796• Fsck# indicates when to run fsck (file system check) during boot up.
1797 0 = never
1798 1 = only if not unmounted cleanly (Always set for the root partition.)
1799 2 = always
1800/etc/mtab The /etc/mtab file tracks the currently-mounted volumes on the system.
1801/procs/mounts The /procs/mounts file contains entries for all currently-mounted volumes on the system. The /proc file system is a virtual file system that contains current system information, including the mounted file systems.
1802Use the following commands to manage the mounting of file systems:
1803Use... To... Example
1804mount /dev/device /mountpoint Mount a volume or device. Common mount options:
1805• -a mounts all file systems listed in the /etc/fstab file
1806• -r, ro mounts the volume as read only
1807• -w, rw mounts the volume as read/write
1808• -t specifies the volume type (If you mount an ext3 file system without the -t, the system recognizes it as an ext2 file system)
1809• -o loop mounts an ISO file. mount -a reads the /etc/fstab file and mounts all volumes listed (except those with the noauto parameter)
1810mount -rt reiserfs /dev/hdc1 /mnt/reis mounts the hdc1 device with the reiser file system as read only to the /mnt/reis mount point.
1811mount -t iso9660 /dev/cdrom /media/cdrom mounts the CD-ROM device to the /media/cdrom mount point.
1812mount -wt vfat /dev/fd0 /mnt/floppy mounts the fd0 device with the vfat file system as read/write to the floppy mount point.
1813mount View the currently-mounted volumes on the system. This will display the contents of the /etc/mtab file.
1814df View which file systems are mounted to specific mount points.
1815umount /device
1816umount /mountpoint Unmount a volume or device from the system. If disk is busy is displayed when unmounting a device:
1817• Make sure the current working directory is not in that file system.
1818• Close any open files located on that file system. umount /dev/hdc1 unmounts the hdc1 device.
1819umount /mnt/reis unmounts the device on the /mnt/reis mount point.
1820umount /dev/cdrom unmounts the CD-ROM device.
1821umount /mnt/cdrom unmounts the device on the /mnt/cdrom mount point (most likely a CD-ROM device).
1822
1823-----
1824Use the following commands to maintain file system integrity:
1825Use... To... Examples
1826df Display the free space in the partition holding the specified directory. If directory is given, the space available on all currently mounted file systems is shown. Disk space is shown in 1K blocks by default. Common options include:
1827• -h displays the output in get human readable format (bytes, KB, MB, GB).
1828• -i Displays inode information.
1829• -l limits the list to local file systems. df /home lists the free space on the partition that holds the /home directory.
1830du
1831 Display files and file sizes in and below a specified directory. Common options include:
1832• -c lists a total amount of space used in the directory.
1833• -h display the output in human readable format (bytes, KB, MB, GB).
1834• -s lists only the total, not each file. du -c /home/badams lists all files and directories in badams' home directory along with a file size and a total amount of space taken up by the directory.
1835du -c -s /home/badams shows the total amount of space taken up in badams' home directory.
1836lsof Display open files in the file system. lsof gives the following information by default:
1837• The command used to access the file
1838• The process ID
1839• The name of the user who is accessing the file
1840• A file descriptor (these are described in the lsof man pages)
1841• The file node type
1842• Device numbers
1843• The file size
1844• The inode address
1845• The file path
1846Common options include:
1847• +D directory_name recursively lists files in a directory.
1848• -c command_name lists all files for processes that are executing the specified command.
1849• -u user lists open files owned by the specified user.
1850• -g process_ID lists files opened by a specific process. lsof -u user lists files opened by processes that the specified user owns.
1851fuser Display the Process IDs of processes that are accessing a specified file or file system. Common options include:
1852• -a displays all process IDs.
1853• -v displays extended information (verbose mode).
1854• -u appends the username to each process ID.
1855• -m displays process IDs in a specified directory. fuser -v /bin/bash shows the user name and process ID for all users who have an open bash shell.
1856fsck Check and optionally repair one or more Linux file systems. Common options include:
1857• -s serializes fsck when multiple file systems are checked.
1858• -t specifies the type(s) of file system to be checked.
1859• -a automatically repairs the file system without any questions.
1860• -r prompts for confirmation when errors are found and ask permission to fix the errors (only when -a is not specified).
1861Be aware of the following:
1862• The file system must be unmounted before using fsck.
1863• When manually running fsck, use runlevel 1 to ensure that other users do not mount the file system. fsck -t ext3 /dev/sdb1 checks the first partition on the first partition of the second hard drive.
1864e2fsck Check and optionally repair a second extended file system (ext2) or ext2 files systems containing a journal (ext3). Command options include:
1865• -f forces a file system check even when the file system appears clean.
1866• -n opens the file system as read-only and automatically answers all questions as "no".
1867• -p automatically repairs the file system without any questions.
1868• -y automatically answers all questions as "yes".
1869• -b uses an alternative superblock if the primary superblock is corrupt. e2fsck -p /dev/sda1 checks and repairs the first partition of the first hard drive so long as it is partitioned using ext2.
1870debugfs Debug the file system. The command examines and changes the state of an ext2, ext3, or ext4 file system. It allows administrators to unlink directories, change inode blocks find all inodes that point to a block, and several other similar functions. Command options include:
1871• -w specifies the file system should open in read-write mode.
1872• -c specifies the file system should open in catastrophic mode (this is useful for file system with significant corruption.)
1873• -f executes commands in a text file. debugfs /dev/sda1 opens the first partition of the first hard drive and displays a prompt that administrators can use to execute commands for the file system.
1874dumpe2fs Print super block and block information for an ext2, ext3, or ext4 file system. This includes information for each sector on the partition about sector type, block ranges, inode information, free blocks, and similar information. Command options include:
1875• -b prints blocks reserved as bad in the file system.
1876• -h prints only super block information.
1877• -x prints group information block numbers in hexadecimal format. dumpe2fs /dev/sda1 lists information for the first partition of the first hard drive.
1878tune2fs Adjust tunable file system parameters on ext2, ext3, and ext4 file systems. Some of the adjustable parameters include volume label, reserved blocks, inode sizes, and journaling. Tune2fs can also implement access control lists for individual users. Command options include:
1879• -c adjust the number of mounts after which the file system will be checked.
1880• -e remount-ro remounts the file system as read-only.
1881• -l lists the contents of the file system super block.
1882• -o acl enables Posix access control lists.
1883• -j converts ext2 file systems to ext3 file systems. tune2fs -o acl /dev/sdb1 enables access control lists on the first partition of the second hard drive. The drive needs to be remounted.
1884xfs_info Display the XFS file system parameters, such as the block size and inode data structures. This is the same functionality as the xfs_growfs -n command. xfs_info /dev/sdb1 displays file system parameters for the first partition of the second hard drive.
1885xfs_metadump Copy (dump) the metadata from an XFS file system to a file. It does not alter the file system. By default, the file names and extended attribute names are obfuscated before they are dumped. Command options include:
1886• -e stops dumping the file system if there is a read error.
1887• -g displays the dump process.
1888• -o disables obfuscation of file names and extended attributes.
1889Only use xfs_metadump to dump unmounted, read-only mounted, or frozen file systems. xfs_metadump -o /dev/sdb1 /dump copies the file system metadata for the first partition on the second hard drive to the /dump file.
1890
1891-----
1892Disk quotas prevent a user or group from using a disproportionate amount of disk space on a volume. Quota implementations include:
1893• Limiting the number of files and directories a user or group can create.
1894• Limiting the amount of disk space a user or group can use.
1895Quota types include the following:
1896• A soft limit allows the user to extend the limits of the disk quota.
1897• A hard limit is a fixed limit that the user cannot modify.
1898The following table lists the general steps to implement quotas:
1899Step Procedure
1900Install quota package To install the quota package (on a System V system):
19011. Use rpm -qi quota to see if the package is installed.
19022. Use yum install package to install the quota package if required.
1903Edit mount options in /etc/fstab Edit the /etc/fstab file to add the mount options for the filesystem so it can implement quotas:
1904• usrquota implements quotas for users.
1905• grpquota implements quotas for groups.
1906Create quota files Create the aquota.user and aquota.group files in the directory where the partition is mounted.
1907Enable quotas and view a quota report Enable disk quotas, and then generate a disk usage and quota report. The report shows:
1908• How much space to allocate to each user.
1909• How much space is currently in use by each user.
1910• Whether some users are using a significant amount of disk space.
1911Edit quotas Edit a quota for the specified user or group. Be aware of the following when editing the quotas:
1912• Set the soft and hard quotas for blocks. This limits the total amount of disk space per user or group.
1913• Set the hard and soft quotas for inodes. This limits the total number of files and directories per user or group.
1914• Users may exceed soft quotas for a number of days specified in the grace period (seven by default.) When the grace period expires, users cannot create additional files.
1915• Users cannot exceed hard quotas.
1916• When setting block quotas, 1000 blocks is about 1 MB, and 1,000,000 blocks is about 1 GB.
1917• Setting the quota limits to 0 removes all quotas.
1918The table below describes common commands for working with quotas:
1919Use.... To... Examples
1920quotacheck -mavug To create the aquota.user and aquota.group files in the filesystem (after placing the quota entries in /etc/fstab). Common options include:
1921• -m updates the quota database even if other processes are running on the filesystem.
1922• -a updates the quota database.
1923• -v runs the command in verbose mode.
1924• -u and -g run the database updates for users and groups, respectively. quotacheck -mavug /home creates the aquota.user and aquota.group files in the root (/) directory.
1925quotaon Enable quotas for the mounted filesystem.
1926• -a enables all mounted filesystems listed in /etc/mtab.
1927• -v runs the command in verbose mode. quotaon -av / enables quotas for the root (/) directory.
1928quotaoff Disable quotas for the mounted filesystem. quotaoff /home disables quotas for the /home directory.
1929repquota Display a summary of the disc usage and quotas for the specified filesystems, including the specific number of files and used space by user. Common options include:
1930• -v reports all quotas, even if there is no usage.
1931• -n does not resolve user and group names to speed printing time .
1932• -u and -g reports for users and groups, respectively.
1933• -a gives information for all filesystems listed in /etc/mtab. repquota /home -uv creates a user quota report for the /home directory.
1934edquota Open and edit a user's quota, a groups quota, or change the grace period:
1935• -u changes the users quota
1936• -g changes a groups quota
1937• -t changes the grace period edquota -u mtomm opens the quota file for the mtomm user account.
1938quota Display the current user's quota:
1939• -u shows the quota for a user.
1940• -g shows the quota for a group
1941• -v shows current the current usage, the hard quota and the soft quota for blocks and inodes. quota displays the quota report only for the current user account.
1942quota -u dhanson displays the quota report only for the dhanson user account.
1943
1944-----
1945When a user creates a file (or directory), the user and the user's primary group receive ownership for the file (or directory). Only a file owner and the root user can change file ownership or permissions.
1946The table below lists the most common commands for managing file ownership.
1947Use... To... Example
1948ls -l View a long file listing. A long file listing shows the ownership for the files (among other information). drwxr-xr-x 22 root root 4096 Jun 19 15:01 sales
1949(Root is the file owner and the group owner for this example.)
1950chown Change the ownership of a file or directory. Be aware of the following options:
1951• -R changes the ownership of the file recursively throughout the directory tree.
1952• user changes the file ownership only.
1953• user:group change the user and group ownership of the file.
1954• :group changes the group ownership only.
1955• .group changes the group ownership only. chown pmorril /sales/report makes pmorril the user owner of the /sales/report file.
1956chown -R pmorril /sales makes pmorril the owner of all files in the /sales directory (and below).
1957chown pmaxwell:sales /sales/report makes pmaxwell the user owner and sales the group owner of the file.
1958chown :sales -R /sales makes the sales group the owner of all files in the /sales directory.
1959chgrp Change the group owner of a file or directory. chgrp sales /sales/report makes the sales group the group owner of the file.
1960
1961-----
1962Every file has an inode (information node) that stores information about the file, including when the file was last modified, file size, data block location, permissions, and ownership (remember, directories are also files in the Linux system). The portion of the inode that stores permission information is called the mode. The mode has three sections:
1963• User (owner) permissions
1964• Group (group owner) permissions
1965• Other (everyone on the Linux system who is not an owner) permissions
1966There are three types of permissions contained in the mode, each of which is described in the table below.
1967Permission Letter Abbreviation Octal Value Allowed Actions on Files Allowed Actions on Directories
1968Read r 4 Open and read the file List directory contents if the execute permission is also present
1969Write w 2 Open, read, and edit the file Add, delete, and rename files if the execute permission is also present
1970Execute x 1 Execute the file (if it's a program file) or the shell script Enter the directory and work with its contents
1971Permissions are identified with either the letter abbreviation (i.e., r, w, x), or the octal number that corresponds to the permission. The following graphic shows a detailed depiction of how permissions are displayed and how they can be referenced.
1972
1973Be aware of the following facts about the mode:
1974• A d preceding the permissions indicates that the object is a directory.
1975• A dash (-) identifies a file (the example above is for a file).
1976• Permissions are grouped according to user, group, or other permissions.
1977• If a permission has not been assigned, a dash (-) takes its place in order.
1978• When using numbers to represent permissions, add the numbers together within each permission group. Then string the numbers together. For example, the permissions in the graphic above can be represented by the number 764.
1979• The root user has all permissions to files and directories regardless of the mode settings.
1980The table below lists the most common commands for managing permissions:
1981Use... To... Example
1982ls -l View a long file listing. A long file listing shows the permissions for the files (among other information) drwxr-xr-x 22 root root 4096 Jun 19 15:01 sales (This is a directory with 755 as the permissions)
1983chmod Change the permissions for the specified file. Be aware of the following syntax options:
1984• category+permission adds a permission for a user, group, or other (category) to a file.
1985• category-permission removes a permission for a user, group, or other from a file.
1986• category=permission sets the permission equal to the permission specified for the user, group, or other for the file.
1987• decimal_value sets the permissions for the file according to the numbers represented for each mode category.
1988• -R sets the permission(s) recursively. chmod u+x,g+x,o+x myfile adds the execute permission to the file myfile for user, group, and other.
1989chmod g-w,o-w myfile removes the write permission for group and other from the file myfile.
1990chmod u=rwx myfile grants the user read, write, and execute permission for the file myfile.
1991chmod 711 myfile grants the user read, write, and execute permission (7) while group and other both receive execute permission (1) for the file myfile.
1992
1993-----
1994A umask changes (removes) the default file and directory permissions. By default, files receive rw-rw-rw- (666) permissions, and directories receive rwxrwxrwx (777) permissions when they are created. In most cases, the default assignment gives excessive permission to files and directories.
1995The umask identifies which permissions are removed from the default permissions when files and directories are created. The following table shows what happens when the mask is set to a value of 022.
1996Umask Calculcation Files
1997(binary) Directories
1998(binary) Files
1999(letter abbreviation) Directories
2000(letter abbreviation)
2001Default Permission 666 777 rw-rw-rw- rwxrwxrwx
2002Umask (minus) 022 022 ----w--w- ----w--w-
2003Result (equals) 644 755 rw-r--r-- rwxr-xr-x
2004Additional examples of umask calculations are:
2005• A umask of 066 results in file permissions of rw-------- (600) and directory permissions of rwx--x--x (711).
2006• A umask of 033 results in file permissions of rw-r--r-- (644) and directory permissions of rwxr--r-- (744).
2007• A umask of 011 results in no changes to file permissions (the x permission is already removed by default) and directory permissions of rwxrw-rw- (766).
2008The table below lists the commands for managing the umask:
2009Use... To... Example
2010umask View the current umask setting 022 is the typical umask setting.
2011umask number Change the default umask. umask 007 sets the umask to remove nothing from the user or group but to remove all permissions from other.
2012Be aware of the following:
2013• The default umask value may vary depending on the Linux distribution (022 or 0022 is typically the default).
2014• Setting the umask with the umask command is only persistent for the shell session.
2015• To make the umask persistent through shell sessions and reboots, add the umask command to the shell configuration file (depending on the distribution).
2016
2017-----
2018Be aware of the following special permissions:
2019Permission Letter Abbreviation Example Octal Value Description
2020SUID (Set User ID) s in the execute permission position of the user permissions rwsrw-rw- 4 If the SUID bit is set, the program will run with the permissions of the file owner, not with the permissions of the user who runs the program.
2021• The most common use of SUID is to allow users to run a command as the root user.
2022• Users do not become the root user, but rather the command or program runs as if executed by the root user.
2023• Some programs require the SUID bit set for proper functionality.
2024• Be careful in setting the SUID bit as it could give a program too many permissions.
2025SGID (Set Group ID) s in the execute permission position of the group permissions rwxrwsrw- 2 If the SGID bit is set:
2026• On a file, the program will run with the group permissions of the group owner.
2027• On a directory, a newly-created file will receive the same group owner as assigned to the parent directory.
2028Sticky bit t in the execute permission position of the other permissions rwxrw-rwt 1 This marks the file (not directory) in such a way as to prevent the file's deletion from the system by anyone except the file owner. Setting the sticky bit works particularly well with shared files.
2029Use the following commands when managing special permissions:
2030Use... To... Example
2031ls -l View a long file listing. A long file listing shows the permissions for the files (among other information). drwsr-xr-x 22 root root 4096 Jun 19 15:01 sales (This is a script with 4755 as the permissions; it has the SUID set.)
2032chmod Assign a special permission. Be aware of the following syntax options:
2033• decimal_value sets the permissions for the file according to the numbers represented for each mode category.
2034 The special permission precedes the standard octal representation of a set of permissions
2035 Only the first number changes to identify the special permission group settings.
2036• category+permission adds a special permission for a user, group, or other (category) to a file.
2037• category-permission removes a special permission for a user, group, or other from a file. chmod 4421 sets the SUID.
2038chmod u+s sets the SUID.
2039chmod u-s removes the SUID.
2040chmod 2421 sets the SGID.
2041chmod g+s sets the SGID.
2042chmod 1421 sets the sticky bit.
2043chmod u+t sets the sticky bit.
2044chmod u-t removes the sticky bit.
2045chmod 6421 sets both the SUID and SGID.
2046chmod 7421 sets the SUID, GUID, and stickybit.
2047
2048-----
2049The tar (tape archive) utility takes the contents of several files and stores them as a single file. Tar:
2050• Uses the .tar file extension.
2051• Can backup entire directories or file systems.
2052The following table lists several options that tar uses.
2053Use... To... Examples
2054tar Combine multiple files into a single file. Options include:
2055• -c creates a new archive.
2056• -v displays a list of all files being written into the archive.
2057• -f specifies the file to create or unpack. Without this option tar uses standard input and output as the destination.
2058• -x extracts the files. If no destination directory is specified, then tar extracts the files to the current working directory.
2059• -z compresses/decompresses a file using the gzip utility (normally named with a .gz extension).
2060• -j compresses/decompresses a file using the bzip2 utility (normally named with a .bz2 extension).
2061• -C changes to a specific directory to extract the files.
2062• -t lists the contents of an archive. tar -cf /root/tarbackups/oct17backup.tar /home writes a backup of the /home directory to the /root/tarbackups/oct17backup.tar file.
2063tar -cvf /root/tarbackups/oct17backup.tar /home writes a backup of the /home directory to the /root/tarbackups/oct17backup.tar file.
2064tar -cvf /root/tarbackups/oct17backup.tar /home writes a backup of the /home directory to the /root/tarbackups/oct17backup.tar file.
2065tar -xvf /root/tarbackups/oct17backup.tar -C /home extracts the files and decompresses them to the /home directory.
2066gzip Compress a file using gzip. Options include:
2067• -c writes the file to standard output.
2068• -d decompresses the file.
2069• -l displays information about files in an archive.
2070• -r recursively compresses all files in directories and subdirectories.
2071This is the same as the tar -z command. gzip file.tar creates a compressed file and removes the original file.
2072gzip -c file.tar > file.tar.gz creates a tar archive leaving the original file unchanged.
2073gzip -d file.tar.gz uncompresses the tar archive.
2074gunzip Uncompress a file using gunzip. Options include:
2075• -f forces decompression even if the file has multiple links or the corresponding file already exists.
2076• -r decompress all files in a directory tree. gunzip file.tar.gz uncompresses the tar archive.
2077gunzip file.cpio uncompresses the cpio file.
2078bzip2 Compress/decompress a file using bzip2.
2079• -d decompresses the file.
2080• -k keeps the original file unchanged.
2081This is the same as tar -j command. bzip2 file.tar creates a compressed file and removes the original file.
2082bzip2 -k file.tar creates a tar archive leaving the original file unchanged.
2083gzip -d file.tar.gz uncompresses the tar archive.
2084
2085-----
2086Be aware of the following cpio and dd utility details:
2087Use... To... Example
2088cpio Create a cpio archive or extract files from a cpio archive. The cpio command is used as another method to archive files, yet is different from other archive utilities because it only takes files names from standard input. Cpio:
2089• Copies files to an archive (copy-out mode).
2090• Extracts files from an archive (copy-in mode).
2091• Copies files to a different directory tree (copy-pass mode).
2092Cpio uses the following options:
2093• -o creates the archive by invoking copy-out mode.
2094• -v invokes verbose output, showing file names as they're added to the archive.
2095• -i extracts files by invoking copy-in mode.
2096• -u overwrites existing files.
2097• -d extracts directories during an extraction.
2098• -t displays archive contents without extracting files.
2099• -p copies files to a new directory (copy-pass mode).
2100 ls ~/4archive | cpio -ov > filename.cpio creates a cpio archive from the files listed in the ~/4archive directory.
2101cpio -iv < filename.cpio extracts the files from the cpio archive.
2102ls ~/copyme | cpio -pvd ./newdirectory copies files from ~/copyme to ./newdirectory.
2103dd Copy information using records. The dd utility copies information using records instead of files. dd is useful for:
2104• Copying partitions to a single image file.
2105• Copying a master boot record.
2106Parameters for dd include:
2107• if= specifies the input file.
2108• of= specifies the output file.
2109• bs= specifies the block size.
2110• count= specifies the number of blocks to be copied. dd if=/dev/sdb1 of=/root/partition.image copies the entire first partition if the second hard drive to a single file.
2111dd if=/dev/sda of=/root/file.mbr bs=512 count=1 copies the master boot record of the first hard drive to a single file.
2112
2113-----
2114Be aware of the following device categories when managing hardware:
2115Category Description
2116Coldplug Coldplug devices should only be removed or replaced when the power to the computer is off. Attempting to remove these devices while the power is on can damage the computer. Coldplug devices include:
2117• RAM (Random-access Memory) chips
2118• CPU (Central Processing Unit)
2119• Expansion cards, such as Peripheral Component Interconnect (PCI) or PCI Express cards
2120• Hard disk drives
2121Hotplug Hotplug devices can be removed while the computer is on. Linux uses software designed to detect these changes as the devices are added and removed. Hotplug devices include:
2122• USB flash drives
2123• FireWire devices
2124Linux uses the following components to manage devices:
2125Component Description
2126sysfs sysfs is a virtual file system mounted at /sys which exports information about hotplug devices so that other utilities can access the information.
2127Hardware Abstraction Layer (HAL) daemon The Hardware Abstraction Layer (HAL) daemon (hald) provides all applications with data about current hardware. hald runs constantly.
2128Desktop Bus (D-Bus) daemon The Desktop Bus (D-Bus) daemon allows processes to communicate with each other and notify them of new hotplug devices.
2129/udev udev is a virtual file system that dynamically creates device files as devices are added and removed. udev uses:
2130• /etc/udev/udev.conf as the configuration file. The configuration file contains the error reporting level for hotplug device errors.
2131• /etc/udev/rules.d/ to name devices.
2132
2133-----
2134When the system boots, it uses one of the following files to automatically load kernel modules. (The exact file used depends on the implementation.)
2135File Description
2136/etc/modprobe.conf Provides the modprobe utility with default commands for loading modules at boot time. Entries in the file include the following:
2137• install loads a module at boot time.
2138• alias specifies a name as an alias for a module name. This alias can be used with module utilities.
2139• options specifies options used while loading a module, including:
2140 irq for IRQ information
2141 io for I/O port information.
2142/etc/modprobe.d Contains multiple configuration files used by modprobe at boot time if the /etc/modprobe.conf file does not exist.
2143Use the following commands to manage kernel modules manually:
2144Use... To... Example
2145lsmod List all loaded modules. The command formats information from the /proc/modules file. No options are associated with lsmod.
2146cat /proc/modules Use the cat command to list, but not format, the lines of information in the /proc/modules file. This file contains a list of all loaded modules.
2147modinfo See additional information about a module listed using the lsmod command. modinfo mii shows information about the MII Hardware Support Library module.
2148depmod Create a file that lists module dependencies. The file is placed at /lib/modules/kernel_version_number/modules.dep. Read the /etc/modules.conf file to identify modules. It then probes each module to identify dependencies and builds a list of those dependencies. Be aware of the following options:
2149• -a Shows information for all modules.
2150• -n Shows what would happen on the screen rather but does not perform the action.
2151• -v Uses verbose mode. depmod -an performs the probe and display the results on the screen.
2152depmod -v displays all module information to the screen as it updates the modules.dep file.
2153insmod Install modules into the kernel.
2154• insmod does not look for dependencies, and fails if a module has unmet dependencies.
2155• Include the full name of the module, including the .o or .ko extension. insmod mousedev.ko loads the mousedev module.
2156modprobe Load modules into the kernel along with any module dependencies. This utility also runs at startup to load modules into the kernel. The /etc/modprobe.conf file provides modprobe with its configuration rules. Be aware of the following options:
2157• -l lists all loaded modules.
2158• -r removes a module. modprobe reiserfs loads the reiserfs and all of its dependant modules.
2159modprobe -r reiserfs removes the reiserfs module.
2160rmmod Remove a module from the kernel. rmmod:
2161• cannot unload the module if it is in use.
2162• Does not look for dependencies and can cause errors if a module depends on a module that is unloaded. rmmod mousedev removes the mousedev module.
2163
2164-----
2165A device driver is a software component that allows a hardware device to communicate with the operating system of a computer. Drivers allow an operating system to correct interpret and implements the signals that come from the hardware device. The following table describes the two methods Linux uses to implement device drivers:
2166Method Description
2167Loaded as a kernel module A kernel module is software that the kernel accesses only when it is needed. When in use, modules run as if they were part of the kernel and have the same access rights. Modules:
2168• Have an .o or .ko extension.
2169• Are stored in the /lib/modules/kernel_version/kernel/drivers/driver_name directory.
2170• Are linked and unlinked dynamically.
2171Compiled into the kernel When the drivers are compiled into the kernel, it is integrated into the kernel build when the kernel is recompiled. This method requires an administrator to recompile the kernel. Drivers compiled into the kernel:
2172• Should be limited to the hardware needed to boot the computer, such as drivers for the keyboard, mouse, and disk drive.
2173• Increase the size and complexity of the kernel.
2174• Requires considerable configuration expertise.
2175• Consume additional computer resources.
2176The following directories contain information about the hardware that is installed on the computer:
2177Directory Contents
2178/proc The /proc directory contains information about the system state and processes. Its contents are created dynamically. Be aware of the following files and directories in the /proc directory:
2179• cmdline displays the boot options that were given to the kernel at boot time.
2180• cpuinfo has information about the computer's CPU.
2181• devices displays a list of hardware installed on the computer.
2182• dma shows all the direct memory access assignments for the computer. Direct memory access gives hardware devices direct access the computer's memory independent of the CPU.
2183• interrupt lists the interrupt request (IRQ) channels the computer uses. Interrupt requests are signals sent to the CPU that inform it that it needs to process input from a hardware device.
2184• iomem contains a mapping of the memory allocated to each device and the input/output port assignments for the memory.
2185• modules lists the kernel modules that the computer is currently using.
2186• version gives information about the current kernel version.
2187• meminfo displays detailed memory information on the system.
2188• /scsi contains a file or directory for each SCSI device attached to the computer.
2189• /bus contains a file or directory for each USB device attached to the computer.
2190• /ide contains a file for the IDE devices attached to the computer, including the internal hard drives and other devices that attach to an IDE ribbon.
2191Changing the system through the /proc directory should be attempted only by experienced administrators. Be aware of the following facts about changing /proc files:
2192• Not every file can be modified. Some are marked read only and can only be viewed.
2193• Do not use vi to view or modify files in the /proc directory. Instead, use the echo command to redirect commands to the appropriate files, or use other special commands.
2194• Use the cat command or other special commands to view files in the /proc directory and sub-directories.
2195/sys The /sys directory displays information about devices and drivers. Be aware of the following directories in the /sys directory:
2196• /block has an entry for each block device on the computer. Block devices such as flash drives and disk drives use data blocks.
2197• /bus holds a sub-directory for SCSI, USB, PCI, and ISA devices. Each of these sub-directories has an additional directory for devices and drivers that has information for each device and driver in the category.
2198• /class has files for each class of devices on the computer.
2199• /devices lists every device that been discovered on the computer. The directory hierarchy places each device beneath the device to which it is connected.
2200• /module has a sub-directory for each kernel module installed on the computer.
2201Linux also includes utilities that provide extensive information about hardware configurations, including:
2202Use... To... Examples
2203lsusb Display information on all USB devices connected to the computer. This utility uses the following options:
2204• -v shows exhaustive information.
2205• -s bus_name shows information for a specific bus. lsusb -v shows all information about each USB device on the computer.
2206hwinfo Display information about hardware on the computer. Be aware of the following options:
2207• --hardware_item_name probes for a specific hardware item. Common hardware names include:
2208 bluetooth
2209 camera
2210 cdrom
2211 cpu
2212 disk
2213 dsl
2214 monitor
2215 mouse
2216 keyboard
2217 usb
2218• --short shows an abbreviated list of information.
2219• --listmd displays RAID devices. hwinfo --cpu shows information about the computer's CPU.
2220lspci Display information for all PCI devices. Be aware of the following options:
2221• -k shows the kernel drivers that support the device.
2222• -t displays a tree diagram that shows connections between all busses, bridges, and devices. lspci -k shows the devices and the kernel drivers that support them.
2223
2224-----
2225A device driver is a software component that allows a hardware device to communicate with the operating system of a computer. Drivers allow an operating system to correct interpret and implements the signals that come from the hardware device. The following table describes the two methods Linux uses to implement device drivers:
2226Method Description
2227Loaded as a kernel module A kernel module is software that the kernel accesses only when it is needed. When in use, modules run as if they were part of the kernel and have the same access rights. Modules:
2228• Have an .o or .ko extension.
2229• Are stored in the /lib/modules/kernel_version/kernel/drivers/driver_name directory.
2230• Are linked and unlinked dynamically.
2231Compiled into the kernel When the drivers are compiled into the kernel, it is integrated into the kernel build when the kernel is recompiled. This method requires an administrator to recompile the kernel. Drivers compiled into the kernel:
2232• Should be limited to the hardware needed to boot the computer, such as drivers for the keyboard, mouse, and disk drive.
2233• Increase the size and complexity of the kernel.
2234• Requires considerable configuration expertise.
2235• Consume additional computer resources.
2236The following directories contain information about the hardware that is installed on the computer:
2237Directory Contents
2238/proc The /proc directory contains information about the system state and processes. Its contents are created dynamically. Be aware of the following files and directories in the /proc directory:
2239• cmdline displays the boot options that were given to the kernel at boot time.
2240• cpuinfo has information about the computer's CPU.
2241• devices displays a list of hardware installed on the computer.
2242• dma shows all the direct memory access assignments for the computer. Direct memory access gives hardware devices direct access the computer's memory independent of the CPU.
2243• interrupt lists the interrupt request (IRQ) channels the computer uses. Interrupt requests are signals sent to the CPU that inform it that it needs to process input from a hardware device.
2244• iomem contains a mapping of the memory allocated to each device and the input/output port assignments for the memory.
2245• modules lists the kernel modules that the computer is currently using.
2246• version gives information about the current kernel version.
2247• meminfo displays detailed memory information on the system.
2248• /scsi contains a file or directory for each SCSI device attached to the computer.
2249• /bus contains a file or directory for each USB device attached to the computer.
2250• /ide contains a file for the IDE devices attached to the computer, including the internal hard drives and other devices that attach to an IDE ribbon.
2251Changing the system through the /proc directory should be attempted only by experienced administrators. Be aware of the following facts about changing /proc files:
2252• Not every file can be modified. Some are marked read only and can only be viewed.
2253• Do not use vi to view or modify files in the /proc directory. Instead, use the echo command to redirect commands to the appropriate files, or use other special commands.
2254• Use the cat command or other special commands to view files in the /proc directory and sub-directories.
2255/sys The /sys directory displays information about devices and drivers. Be aware of the following directories in the /sys directory:
2256• /block has an entry for each block device on the computer. Block devices such as flash drives and disk drives use data blocks.
2257• /bus holds a sub-directory for SCSI, USB, PCI, and ISA devices. Each of these sub-directories has an additional directory for devices and drivers that has information for each device and driver in the category.
2258• /class has files for each class of devices on the computer.
2259• /devices lists every device that been discovered on the computer. The directory hierarchy places each device beneath the device to which it is connected.
2260• /module has a sub-directory for each kernel module installed on the computer.
2261Linux also includes utilities that provide extensive information about hardware configurations, including:
2262Use... To... Examples
2263lsusb Display information on all USB devices connected to the computer. This utility uses the following options:
2264• -v shows exhaustive information.
2265• -s bus_name shows information for a specific bus. lsusb -v shows all information about each USB device on the computer.
2266hwinfo Display information about hardware on the computer. Be aware of the following options:
2267• --hardware_item_name probes for a specific hardware item. Common hardware names include:
2268 bluetooth
2269 camera
2270 cdrom
2271 cpu
2272 disk
2273 dsl
2274 monitor
2275 mouse
2276 keyboard
2277 usb
2278• --short shows an abbreviated list of information.
2279• --listmd displays RAID devices. hwinfo --cpu shows information about the computer's CPU.
2280lspci Display information for all PCI devices. Be aware of the following options:
2281• -k shows the kernel drivers that support the device.
2282• -t displays a tree diagram that shows connections between all busses, bridges, and devices. lspci -k shows the devices and the kernel drivers that support them.
2283
2284-----
2285When the system boots, it uses one of the following files to automatically load kernel modules. (The exact file used depends on the implementation.)
2286File Description
2287/etc/modprobe.conf Provides the modprobe utility with default commands for loading modules at boot time. Entries in the file include the following:
2288• install loads a module at boot time.
2289• alias specifies a name as an alias for a module name. This alias can be used with module utilities.
2290• options specifies options used while loading a module, including:
2291 irq for IRQ information
2292 io for I/O port information.
2293/etc/modprobe.d Contains multiple configuration files used by modprobe at boot time if the /etc/modprobe.conf file does not exist.
2294Use the following commands to manage kernel modules manually:
2295Use... To... Example
2296lsmod List all loaded modules. The command formats information from the /proc/modules file. No options are associated with lsmod.
2297cat /proc/modules Use the cat command to list, but not format, the lines of information in the /proc/modules file. This file contains a list of all loaded modules.
2298modinfo See additional information about a module listed using the lsmod command. modinfo mii shows information about the MII Hardware Support Library module.
2299depmod Create a file that lists module dependencies. The file is placed at /lib/modules/kernel_version_number/modules.dep. Read the /etc/modules.conf file to identify modules. It then probes each module to identify dependencies and builds a list of those dependencies. Be aware of the following options:
2300• -a Shows information for all modules.
2301• -n Shows what would happen on the screen rather but does not perform the action.
2302• -v Uses verbose mode. depmod -an performs the probe and display the results on the screen.
2303depmod -v displays all module information to the screen as it updates the modules.dep file.
2304insmod Install modules into the kernel.
2305• insmod does not look for dependencies, and fails if a module has unmet dependencies.
2306• Include the full name of the module, including the .o or .ko extension. insmod mousedev.ko loads the mousedev module.
2307modprobe Load modules into the kernel along with any module dependencies. This utility also runs at startup to load modules into the kernel. The /etc/modprobe.conf file provides modprobe with its configuration rules. Be aware of the following options:
2308• -l lists all loaded modules.
2309• -r removes a module. modprobe reiserfs loads the reiserfs and all of its dependant modules.
2310modprobe -r reiserfs removes the reiserfs module.
2311rmmod Remove a module from the kernel. rmmod:
2312• cannot unload the module if it is in use.
2313• Does not look for dependencies and can cause errors if a module depends on a module that is unloaded. rmmod mousedev removes the mousedev module.
2314
2315-----
2316Be aware of the following device categories when managing hardware:
2317Category Description
2318Coldplug Coldplug devices should only be removed or replaced when the power to the computer is off. Attempting to remove these devices while the power is on can damage the computer. Coldplug devices include:
2319• RAM (Random-access Memory) chips
2320• CPU (Central Processing Unit)
2321• Expansion cards, such as Peripheral Component Interconnect (PCI) or PCI Express cards
2322• Hard disk drives
2323Hotplug Hotplug devices can be removed while the computer is on. Linux uses software designed to detect these changes as the devices are added and removed. Hotplug devices include:
2324• USB flash drives
2325• FireWire devices
2326Linux uses the following components to manage devices:
2327Component Description
2328sysfs sysfs is a virtual file system mounted at /sys which exports information about hotplug devices so that other utilities can access the information.
2329Hardware Abstraction Layer (HAL) daemon The Hardware Abstraction Layer (HAL) daemon (hald) provides all applications with data about current hardware. hald runs constantly.
2330Desktop Bus (D-Bus) daemon The Desktop Bus (D-Bus) daemon allows processes to communicate with each other and notify them of new hotplug devices.
2331/udev udev is a virtual file system that dynamically creates device files as devices are added and removed. udev uses:
2332• /etc/udev/udev.conf as the configuration file. The configuration file contains the error reporting level for hotplug device errors.
2333• /etc/udev/rules.d/ to name devices.
2334
2335-----
2336A process refers to a program that is running in memory and in the CPU. Be aware of the following file types which create processes on a Linux system:
2337Type Description
2338Binary executable A binary executable is a program written in a programming language that is compiled into a binary file that the CPU can process.
2339Internal shell commands An internal shell command is a command which is built into the shell. These might include the cd command and the echo command.
2340Shell scripts A script is a command or commands stored in a text file. When the shell reads the file, it executes the commands as if they were entered through the keyboard.
2341Be aware of the following types of processes:
2342Type Description
2343User User processes start when a user executes a program file. For example, a user executes the grep command starts a user process.
2344Daemon Daemon processes (also known as system processes) are started by the operating system usually when it boots, but users can start daemon processes as well. Most daemons provide system services.
2345Processes are all given unique process ID numbers randomly from the list of available numbers. Linux uses the following process identifiers:
2346Type Description
2347Process ID (PID) The process ID (PID) uniquely identifies each process. System-started processes typically have low numbers, while user-started processes have higher numbers.
2348Parent Process ID (PPID) The parent process ID (PPID) identifies the process that spawned (or started) the process. The process that spawned the new process is known as the parent process; whereas the spawned process is known as the child process.
2349Be aware of the following when working with processes:
2350• Init is the first process started by the kernel. Init:
2351 Has a process ID of 1.
2352 Spawns all additional processes the operating system needs at boot time.
2353 Is responsible for spawning additional processes including the login shell.
2354• Forking occurs when a parent process spawns a child process that is identical to the parent. An example of forking is the subshell that the shell creates when a user runs the VI editor.
2355• When a user stops a process, all child processes stop as well unless the user specifies that the child processes remain running. The child processes becomes children of init.
2356• A zombie process is an orphaned process (a process without a parent). Zombie processes:
2357 Typically appear when the parent process fails to kill its child processes properly.
2358 Can linger in the system, consuming resources and PIDs.
2359• Core processes always have the lowest PID numbers and are below 100.
2360• A job is another name for a running process. Processes are often referred to as jobs when dealing with job control commands, such as Ctrl+z which pauses a job.
2361• A single-threaded CPU can run only one process at a time.
2362
2363-----
2364Use the following commands to view processes:
2365Use... To... Example
2366top View an interactive listing of processes organized by processor time. top:
2367• Displays a list of processes is in real-time.
2368• Returns Process ID (PID), uptime, load, CPU status, memory, and priority information for processes.
2369• Lists the most CPU-intensive processes at the top of the output by default.
2370• Is useful when monitoring processes.
2371When using top, be aware of the following options:
2372• Press h to display the help screen.
2373• Press f to add or remove columns from the chart.
2374• Press F to show a list of sortable columns, then press the key of the letter next to the column to be sorted.
2375• Press u to specify processes for a specific user. top -u gshant starts top by monitoring only the gshant user.
2376ps Show the processes associated with the current user and terminal (in ascending order based on the process ID). By default, the ps command displays the following information:
2377• Process ID (PID)
2378• Name of the shell session on which the process is running (TTY)
2379• CPU time the process has used (TIME)
2380• The command used to invoke the process (CMD)
2381Be aware of the following ps options:
2382• -A, e shows all processes.
2383• -a shows processes owned by other users and attached to a terminal (i.e., foreground processes).
2384• -f shows all possible detail for processes.
2385• -u shows processes by user ID.
2386• -l shows the processes in long format, and the process state (under the STAT column). The process states include:
2387 sleeping (S)
2388 running (r)
2389 traced (t) by another process
2390 zombie (Z)
2391• -x shows processes that are not attached to a controlling terminal. Use this option to view daemon processes that begin during system boot. ps -Au jsmith shows all processes owned by the user jsmith.
2392ps elf shows all processes in long format.
2393ps aux shows all processes including zombie processes.
2394
2395-----
2396The following table lists commands you can use to manage and prioritize processes. When a process:
2397• Runs in the foreground, the terminal from which they were invoked is unusable (i.e., no other commands can run from the terminal) until the process terminates.
2398• Runs in the background, the terminal is available for additional commands and utilities.
2399The following table describes ways to move processes between the foreground and the background, and adjust process priorities.
2400Use... To... Examples
2401command & Start a process in the background, leaving the shell available for other commands. When running a process in the background, the shell displays the following information:
2402• The job ID in brackets
2403• The process ID (PID)
2404• The process name, which is often the name of the command used to start the process gedit & starts the gedit process in the background.
2405jobs View the active jobs and see the job ID number.
2406• The job ID number is specific to the terminal session.
2407• Each open terminal has its own set of jobs and job ID numbers.
2408• Jobs from one terminal cannot be managed from a second terminal using job ID numbers.
2409bg Send a job to the background. bg 3 sends the job with job ID 3 to the background.
2410fg Bring a job to the foreground. fg 1 brings the job with job ID 1 to the foreground.
2411Ctrl+z Pause a current job (i.e., send to the background) and give it a job ID number.
2412nice Start a command with a higher or lower priority.
2413• Nice values range from 19 (lowest priority), to -20 (highest priority.) The higher the number, the lower priority the job receives in the system.
2414• Use -n to specify the priority value. If no value is specified, the process starts with -10 as the default.
2415• Zero (0) is the default nice value for processes not executed with the nice command. nice -n 7 gedit starts gedit with a priority that is 7 lower than the default.
2416nice -n -9 gedit starts gedit with a priority that is 9 higher than the default.
2417nice gedit starts gedit with a priority that is 10 lower than the default.
2418renice Assign a new priority to a process that has already started using the PID of the process. The command can contain multiple PIDs separated by a space to give them all the same priority number. The values are identical to the nice command. Be aware of the following options:
2419• -n specifies a priority but is assumed by default.
2420• -u specifies a user.
2421• -g specifies a group.
2422Only root can change the priority of other users and groups or raise a process priority above the default. renice -5 3346 raises the priority of the process with PID 3346 to 5 above the default.
2423renice 7 2266 3902 lowers the priority of both processes to 7 below the default.
2424renice 5 -u userbob lowers the priority of all processes owned by userbob to 5 below the default.
2425nohup & Allow a command or shell script to continue running in the background after logging out from a shell.
2426nohup does not automatically put the command it runs in the background; Use the ampersand (&) symbol to start a process in the background. nohup gedit & starts the gedit process in the background and leaves it running after logging out of the shell.
2427
2428-----
2429Use the following commands to terminate a process that has hung and will not close using its exit function or init script:
2430Use... To... Example
2431kill Terminate a process using a process ID (PID) number and a specific kill signal. Kill signals can be sent using a term or a numeric value. Options include the following:
2432• -SIGHUP, -1 tells the process to shut down and restart. When it restarts, the process will have the same PID it had when the kill signal was sent.
2433• -SIGINT, -2 stops a process as if the Ctrl+c key combination had been used. This option is recommended as the first choice when a process will not stop using its exit function or init script.
2434• -SIGKILL, -9 forces a process to stop when it is unresponsive to other options for exiting or killing it. Running this option does not give the process a chance to clean up any resources, such as memory, that it is using. Resources allocated to the process usually remain allocated to it until it is restarted. This option should be used only as a last resort.
2435• -SIGTERM, -15 stops the process cleanly by giving it a chance to release the resources allocated to it. This is the default signal used by the kill command if no signal is specified. This option can be tried if the -2 option fails to kill the process.
2436• -l lists all of the signals that are available for the kill command. kill -1 6754 shuts down and restarts the process.
2437kill -9 6754 forces the unresponsive process to stop running.
2438kill -SIGKILL 6754 (same as using -9)forces the unresponsive process to stop running.
2439kill 6754 stops the process with PID 6754 using the default SIGTERM signal.
2440killall Terminates processes the same as the kill command, using their command name instead of their PID. This command uses the same signal commands that kill uses. killall atd kills all processes named atd.
2441killall -9 atd uses a hard kill to stop the atd process.
2442
2443-----
2444The at daemon (atd) schedules tasks to occur at a specific time. at:
2445• Is started using a script in the /etc/rc.d/init.d/ or /etc/init.d/ script directory.
2446• Uses configuration files to specify standard user accounts that can and cannot use the at command.
2447 /etc/at.allow specifies users who can use the at command.
2448 /etc/at.deny specifies users who cannot use the at command.
2449• Can read commands from a file or standard input.
2450Be aware of the follow general steps to use the at utility:
24511. Type at time, then press Enter to access the command prompts.
24522. Type one command per line. Press Enter after each command.
24533. Press Ctrl+D to exit the command prompt.
2454The table below lists the most common commands for managing tasks with the at command.
2455Use... To... Examples
2456at time date Schedule the command to run at a specific time and date. Options and syntax include:
2457• today
2458• tomorrow
2459• month #
2460• MMDDYY
2461• MM/DD/YY
2462• DD.MM.YY at 12:12AM starts the command the next time the clock reads 12:12 AM.
2463at 12:12AM September 1 starts the command at 12:12 AM on September 1.
2464at 12:00AM 01/01/2010 starts the command at 12:00 AM on January 1, 2010.
2465at 12:00AM 01012010 starts the command at 12:00 AM on January 1, 2010.
2466at 12:00AM 01.01.2010 starts the command at 12:00 AM on January 1, 2010.
2467at time_of_day Use time of day keywords to run the command. Options are:
2468• Midnight (12:00 AM)
2469• Noon (12:00 PM)
2470• Teatime (4:00 PM) at midnight starts the command the next time the clock reads 12:00 AM.
2471at now Run the command immediately.
2472at now + number time_period Schedule the command to run at the designated time in the future. Use:
2473• minutes
2474• hours
2475• days
2476• months at now + 6 days starts the command 6 days after the time the command is issued.
2477at now + 1 months starts the command 1 month after the time the command is issued.
2478at -f filename time Schedule tasks in a file to run at the designated time (like a shell script, for example). at -f /home/user/myscript now + 3 hours starts the jobs listed in the myscript file in three hours from the time the command is issued.
2479at -l
2480atq List the tasks in the at queue for the current user.
2481• When run as root, atq or at -l lists all the jobs in queue.
2482• When run as a user other than root, at lists only the jobs for the user. atq shows all jobs in the at queue.
2483at -d jobnumber
2484atrm jobnumber Remove jobs from the at queue. Use spaces to separate multiple jobs. at -d 2 3 removes jobs 2 and 3 from the at queue.
2485atrm 4 removes job 4 from the at queue.
2486
2487-----
2488The cron daemon (crond) schedules tasks to run on a regular basis. cron uses the following configuration files:
2489File Description
2490/etc/crontab The /etc/crontab (cron table) file holds entries that direct commands to execute at a specific time. The /etc/crontab file:
2491• Is for custom task schedules that run system wide.
2492• Can only be edited by the root user.
2493crond runs tasks scheduled in the /etc/crontab file as the root user.
2494/etc/cron.timeparameter The cron daemon executes the scripts found in each of the following directories at the specified interval for the whole system:
2495• /etc/cron.hourly
2496• /etc/cron.daily
2497• /etc/cron.weekly
2498• /etc/cron.monthly
2499/var/spool/cron/username Each user has a personal crontab file located at /var/spool/cron/username. The cron daemon only checks the file of the current user.
2500/etc/cron.allow The /etc/cron.allow file includes users who can edit their personal crontab file. If /etc/cron.allow file exists, only users listed in therein are allowed to edit /var/spool/cron/username.
2501/etc/cron.deny The /etc/cron.deny file excludes users from editing their personal crontab file. If /etc/cron.deny file exists, users listed in therein are not allowed to edit /var/spool/cron/username.
2502Each entry /etc/crontab or /var/spool/cron/username has a specific format. The table below illustrates the schedule format for a typical entry and provides additional examples. The asterisk (*) is a wildcard that is equal to any value:
2503Example Minute Hour Day of Month Month Day of Week Command Description
250400 5 * * 6 /bin/tar 00 5 * * 6 /bin/tar This schedule runs the tar utility on the 6th day (Saturday) of the week, at the 5th hour (5am--5pm would be 17) and zero minutes. (Note that the days of the week are numbered 0 through 7, 0 and 7 being equal to Sunday.)
250515 23 25 * * /usr/bin/find 15 23 25 * * /usr/bin/find This schedule runs the find command at 11:15 pm on the 25th of every month.
250600 24 1 1,6 * /bin/rm 00 24 1 1 and 6 * /bin/rm This schedule runs the rm command at midnight on the first days of January and July.
2507Use the following commands to manage cron task scheduling:
2508Use... To... Examples
2509crontab Manage the /var/spool/cron/username crontab file: Be aware of the following options:
2510• -e edits the crontab file in vim for the current user.
2511• -l displays the contents of the crontab file.
2512• -r removes the crontab file.
2513• -u username specifies a user for the -e, -l, and -r options. crontab -e edits the crontab of the current user.
2514crontab -eu username edits the crontab file of the specified user.
2515crontab -l lists the cron jobs for the current user.
2516crontab -lu username lists the cron jobs for the specified user.
2517crontab -r -u username removes the crontab file of the specified user.
2518crontab -r removes the crontab file of the current user.
2519crontab /home/user/cronjobs creates a crontab file using the cronjobs file for the current user.
2520vi /etc/crontab Open and edit the /etc/crontab file in Vim. vi /etc/crontab opens the crontab file in Vim.
2521crontab file Load a crontab job from a file. Write the file using crontab syntax.
2522This overwrites the current crontab. crontab /home/user/cronjobs creates a crontab file using the cronjobs file for the current user.
2523which Display the full path for a command. For many distributions, crontab entries require the complete path to commands. For example, to use /bin/rm instead of only rm. which bash displays the full path for the borne again shell.
2524Be aware of the following details:
2525• Some distributions use separate files in the /etc/cron.d directory in addition to lines in the /etc/crontab file.
2526• The cron daemon (crond) is started using a script in the /etc/rc.d/init.d/ or /etc/init.d/ script directory.
2527
2528-----
2529CUPS (Common Unix Print System) is widely used on nearly every current Linux distribution for managing printers and printing. CUPS has the following components:
2530Component Description
2531Client Clients send files to the print server. When configuring a print system, the client's cupsd daemons automatically listen for broadcast signals from servers, and can connect to those servers.
2532Server Servers broadcast their availability over the network for client connections. Other components of a CUPS print system are maintained on the server. The cupsd daemon runs on the server and handles print functions.
2533Scheduler Schedulers are specialized Web servers that handle IPP print requests. Schedulers:
2534• Run on IP port 631.
2535• Have a built-in Web interface.
2536Queue A queue hold a list of print jobs sent to the server. The path to the queue is /var/spool/cups. Files in /var/spool/cups include:
2537• cprint_job_number represents the print job and filter information.
2538• dprint_job_number represents the stored document.
2539Filter A filter converts print jobs from the default printer description language (PDL) into the languages used and understood by the printer.
2540• By default Linux uses the postscript PDL; however, many printers do not use postscript, so the filter converts the print job into a PDL the printer uses.
2541• Filters are located at /usr/lib/cups/filter.
2542Backend A backend is the interface between the scheduler and the printer. Linux computers have several backends including:
2543• Parallel
2544• Serial
2545• USB
2546When the cupsd daemon starts, it queries each backend about printers attached to the computer. The backends provide the cupsd daemon with printer information including make, model, and capabilities for each connected printer. Backends are located at /usr/lib/cups/backend.
2547Postscript Printer Descriptions (PPD) The Postscript Printer Descriptions (PPD) are files that the cupsd daemon uses to determine printer capabilities. These files are located at /etc/cups/ppd.
2548The following are the steps CUPS uses when processing print jobs.
25491. The client sends the print job to the cupsd daemon on the server.
25502. The daemon creates the files and places them in the queue.
25513. Print jobs pass through the filters and are converted to the appropriate PDL.
25524. The backend sends the print job to the printer.
25535. The backend notifies the cupsd daemon when the job is completed, and the job is removed from the queue.
2554The cupsd daemon is configured using the /etc/cups/cupsd.conf file. Be aware of the following common parameters in /etc/cups/cupsd.conf:
2555Use... To... Example
2556ServerName Specify the name of the server broadcast to cups clients. ServerName printserver.mynetwork.com
2557ServerAdmin Specify an email address for the server administrator ServerAdmin printhelp@mynetwork.com
2558DocumentRoot Specify the directory where the client documentation for CUPS resides. The default is /usr/share/doc/packages/cups. DocumentRoot /usr/share/doc/packages/cups
2559LogLevel Specify the error severity level to be logged. LogLevel warn
2560Listen Specify the network addresses the server uses when listening for print jobs. Listen 192.168.10.1:631 listens for print jobs sent to 192.168.10.1:631.
2561Listen *:631 listens for print jobs sent to any address.
2562Listen localhost:631 listens only for print jobs from the local computer.
2563MaxCopies Limit the number of copies of a document that can be printed for a single print job. The default is 100. MaxCopies 50
2564MaxJobsPerUser Limit the number of active print jobs for a single user. The default is 0, meaning no restriction. MaxJobsPerUser 100
2565User Specify the user who owns the cupsd process. The default is lp. User lp
2566Group Specify the cupsd group. The default is lp. Group lp
2567MaxClients Limit the number of concurrent client connections to the CUPS server. The default is 100. MaxClients 50
2568Browsing Enable server broadcasts. The default is On. Browsing On
2569BrowseAddress Specify the address CUPS servers use to broadcast servers. This must be set for broadcasts to work. The default is no setting. Check this first if CUPS clients do not receive broadcasts. BrowseAddress 192.168.2.255:631
2570BrowseAddress printserver.mynetwork.com:631
2571BrowseInterval Set the time in seconds between broadcasts. The default is 30 seconds. If this is set above 60, Printers might timeout and disappear from the printer list. BrowseInterval 30
2572BrowseOrder Specify whether the server allows or denies print jobs by default, then specifies the order in which the BrowseAllow and BrowseDeny parameters are checked. BrowseOrder allow,deny denies by default, then checks the BrowseAllow parameter, and then the BrowseDeny parameter.
2573BrowseOrder deny,allow allows by default, then checks the BrowseDeny parameter, and then the BrowseAllow parameter.
2574BrowseAllow Specify computers and networks that can send print jobs. BrowseAllow all accepts all print jobs.
2575BrowseAllow 192.168.1.0/255.255.255.0 allows print jobs from the 192.168.1.0 domain with a subnet of 255.255.255.0.
2576BrowseAllow *.mynetwork.com allows print jobs from all computers on the domain.
2577BrowseDeny Specify computers that cannot send print jobs. BrowseDeny all rejects all print jobs. Other options are identical to BrowseAllow.
2578The following table describes the utility used to configure CUPS:
2579Use... To... Example
2580cupsctl Configure the /etc/cups/cupsd.conf file. When used with no options, the command displays current settings. Options include:
2581• --remote-admin enables remote administration of the server.
2582• --share-printers enables the sharing of local printers with other computers.
2583• --remote-printers enables the display of remote printers shared via CUPS.
2584Use --no in front of a command to disable an option. cupsctl displays the settings of the cupsd.conf file.
2585cupsctl --remote-admin enables remote administration of the server.
2586cupsctl --no-share-printers will prevent the sharing of local printers.
2587lppasswd -g sys -a root Create the CUPS root user and password.
2588• CUPS requires a CUPS root user to access the Web administration utility.
2589• The CUPS root user must be a member of the sys group.
2590• CUPS user information resides in the /etc/passwd.md5 file instead of /etc/passwd.
2591Be aware of the following options:
2592• -g [groupname] specifies the group.
2593• -a [username] adds a new user. lppasswd -g sys -a root
2594Enter password:
2595Enter password again:
2596The lines above create the CUPS root user account and password.
2597Keep the following in mind when using CUPS:
2598• Most Linux distributions install CUPS by default; however, if CUPS is not installed, use yum or apt-get to install the CUPS package.
2599• Use the init script to restart CUPS after making configuration changes.
2600• To access the Web-based CUPS administration utility, go to http://localhost:631 or http://127.0.0.1:631.
2601
2602-----
2603The Line Printer Daemon (LPD) is the older print management daemon for Linux systems. Although LPD might be present on older systems, the majority of the LPD commands are now also supported when using CUPS. The following table describes commands associated with LPD and CUPS:
2604Use... To... Examples
2605lpr Send a job to the print queue (putting print jobs into the queue is called spooling). Common lpr options include:
2606• -#n prints n number of copies.
2607• -h prints without using a banner page.
2608• -P printer prints to the named printer.
2609• -r removes the job from the queue after printing.
2610• -w sets the page width of a printable document. lpr mydoc prints the mydoc file to the default queue.
2611lpr -P printer7 mydoc sends the print job to the printer7's print queue.
2612lpr -#33 mydoc prints 33 copies of the prospectus file.
2613lpc View and manage printers and print queues. Subcommands for lpc include:
2614• status shows the current state of a printer.
2615• clean removes all files from a print queue.
2616• restart attempts to restart a printer daemon for a printer. lpc status printer7 displays the current state of printer7.
2617lpc clean all empties the print queues for all printers.
2618lpq Query a print queue. This command displays job numbers and users who own the print jobs. Specify a user name or a job number to see information about specific print jobs or print jobs for a specific user. Common lpq options include:
2619• -a shows the contents of all queues.
2620• -l gives a verbose (long) listing.
2621• -P specifies a specific printer's queue.
2622• -U specifies an alternative username. lpq -P Printer7 shows all print jobs and print job numbers for printer7.
2623lpq -l tjones 56 shows a long listing of user tjones' job number 56.
2624lprm Remove jobs from the print queue. If executed by a regular user, the command removes only that user's jobs; if executed by the superuser, the command removes all print jobs.
2625• -P specifies a printer name.
2626• -U specifies an alternative username. lprm -P printer7 6 removes job number 6 from the print queue of printer7.
2627lprm - removes all jobs from the default printer.
2628lprm removes the current job from the default printer.
2629lpstat See the status of a printer. Options include:
2630• -t shows all information for all printers on the network.
2631• -u specifies a alternative username. lpstat -t shows all information for all printers on the network.
2632lpstat -t printer7 shows all information for printer7.
2633lpstat -t -u jsmith shows all information for all print jobs on the network for the user jsmith.
2634cancel Cancel print jobs. Options include:
2635• -P specifies a printer.
2636• -U specifies a alternative username. cancel 11 cancels print job 11 on the default printer.
2637cancel -P printer7 11 cancels print job 11 on printer7.
2638cancel -P printer7 -U jsmith cancels all print jobs for the user jsmith on printer7.
2639lpoptions Set the default printer. Options include:
2640• -p specifies the default printer for all users.
2641• -l displays current option settings for a printer.
2642Users can use the ~/.lpoptions file to set their own default printer values. Include the single line default printer_name to specify the default printer. lpoptions -p printer7 specifies printer7 as the default printer for all users.
2643lpoptions -l printer7 displays the current option settings for printer7.
2644accept Enable a printer's print queue. accept printer7 enables the print queue for printer7.
2645reject Disable a printer's print queue.
2646This does not clear the print queue. reject printer7 disables the print queue for printer7.
2647disable
2648cupsdisable Keep a printer from printing. Jobs are still added to the queue, and are printed when the printer is re-enabled. disable printer7 keeps printer7 from printing the jobs in its queue.
2649enable
2650cupsenable Activate a disabled printer. enable printer7 activates printer7 and allows it to print jobs in its queue.
2651When using LPD, the configuration file is located at /etc/lpd.perms. The table below describes parameters commonly found in the /etc/lpd.perms file:
2652Parameter Description
2653DEFAULT Use the default setting, which is often accept but can also be set to reject.
2654HOST The host named in the print job.
2655REMOTEHOST The host making the request.
2656REMOTEIP The IP address and subnet mask of the host making the request.
2657REMOTEUSER The user making the request.
2658SAMEHOST The HOST and REMOTEHOST are the same.
2659SAMEUSER The USER and REMOTEUSER are the same.
2660SERVER The request originates on the LPD server itself.
2661SERVICE The SERVICE keyword accepts the following arguments:
2662• C=lpc control request
2663• M=lprm removal request
2664• P=job printing
2665• Q=lpq status request
2666• R=lpr job transfer
2667• S=lpc status request
2668• X=connection request
2669USER The user named in the print job.
2670
2671-----
2672A time zone is a geographic region of the world that has the same standard time. Be aware of the following details:
2673• The time zone ensures that daylight hours fall between certain hours, regardless of the area of the world.
2674• In many areas, daylight savings time (DST) moves clocks ahead by one hour from the standard time zone time during "summer" when there are more daylight hours. Not all locations observe daylight savings time. For example, areas along the equator typically do not because the number of daylight hours does not vary significantly throughout the year.
2675• The local time is the time used in your physical location, adjusting for the time zone and daylight savings time (if used).
2676• As you change your physical location, the local time can also change based on the time zone used in that area.
2677• Time zone names used in the United States (Eastern, Central, Mountain, Pacific) are not part of the official time zone standards, but are useful in comparing time between different parts of the country. In the United States, the time zone names can also reflect whether or not daylight time is in effect.
2678 Eastern Daylight Time (EDT) identifies the Eastern time zone, observing daylight standard time.
2679 Mountain Standard Time (MST) identifies the Mountain time zone, not observing daylight standard time.
2680Linux computers have two clocks. The following table describes them.
2681Clock Description
2682Hardware clock The hardware clock is a clock that is maintained by hardware.
2683• The hardware clock runs independently of any program. The clock does not require the CPU or memory to run.
2684• Soft power from the power supply and the CMOS battery ensures that the clock continues to run even when the computer is turned off.
2685• The hardware clock is sometimes called the real time clock (RTC), BIOS clock, CMOS clock, or time of year (TOY) clock.
2686• The current hardware clock time is stored in the /proc/driver/rtc file.
2687System time System time is the clock that runs within the operating system.
2688• A system clock increments in seconds starting from 12:00 AM on Jan 1, 1970.
2689• By default, when the computer boots, it sets the system time based on the hardware clock.
2690• After the operating system runs, the system time is the only clock used by applications and services.
2691• Changing the system time does not automatically change the hardware clock, although you can change the system time and change the hardware clock to match.
2692• The system clock is the clock that Linux uses for all its functions and applications.
2693Clocks on a Linux computer can use local time or UTC time. The following table describes these and explains how to calculate a UTC offset.
2694Time Description
2695Coordinated Universal Time (UTC) Coordinated Universal Time (UTC), formerly known as Greenwich Mean Time (GMT),is a method of identifying a common time between devices regardless of their physical location in the world.
2696• UTC is adjusted periodically to match the rotation of the earth by adding leap seconds. Leap seconds are required because the official duration of a second does not exactly match the earth's rotation (but is very close).
2697• UTC matches time to the rotation of the earth using a single fixed point in Greenwich, England. A line drawn from north pole to south pole that passes through Greenwich is called the prime meridian.
2698• Most computers use UTC (not local time) when recording timestamps. This ensures that a single method of keeping time is used, regardless of the physical location of the computer.
2699• Time expressed using UTC is identified by adding UTC or Z to the time. For example, 09:30 UTC is the same as 09:30Z or 0930Z.UTC is also called Zulu time.
2700UTC offset The UTC offset identifies the amount of time that local time is ahead of or behind Coordinated Universal Time (UTC).
2701• Local time in each time zone is identified by the UTC offset. For example:
2702 Time zones used in the United States are UTC-05 (Eastern), UTC-06 (Central), UTC-07 (Mountain), and UTC-08 (Pacific), with time being behind UTC.
2703 Time zones used in Europe and Asia are ahead of UTC. For example, time in Germany is UTC+01, and time in Japan is UTC+09.
2704• To convert UTC to local time, add time based on the UTC offset (UTC + offset). For example, if UTC is 06:00:
2705 Local time in New York (UTC-05) would be 01:00 (06:00 + - 5:00 = 1 am).
2706 Local time in Los Angeles (UTC-08) would be 22:00 the previous day (10 pm).
2707 Local time in Japan (UTC+09) would be 15:00 (3 pm).
2708• To convert local time to UTC, subtract time based on the UTC offset (UTC - offset). For example:
2709 If the local time in New York (UTC-05) is 14:00, UTC is 19:00 (14:00 - - 5:00 = 14:00 + 5:00).
2710 If the local time in Japan (UTC+09) is 14:00, UTC is 5:00 (14:00 - + 9:00).
2711• UTC does not change for daylight savings time; however, the offset used by a time zone will change. During daylight savings time, add one hour to the UTC offset. For example:
2712 Standard time in New York is UTC-05; daylight time in New York is UTC-04.
2713 Standard time in Germany is UTC+01; daylight time in Germany is UTC+02.
2714Local time Local time is the current time in a local time zone. It is designated using the number of hours ahead or behind UTC time. For example the local time for the Mountain Time Zone in the United States is UTC -7. The default setting for several hardware clocks in a system BIOS is often local time.
2715The following table describes the tools and files used to determine and change time zone settings.
2716Use... To... Examples
2717/usr/share/zoneinfo View the set of time zone configuration files and directories, with each file identifying a specific time zone.
2718• Files are typically organized in subfolders based on continent (such as Australia) or major country (such as US).
2719• Individual files identify a major city in the time zone (such as Perth) or a specific region (either a division of the country or a country within the continent).
2720• Information in the file identifies the UTC offset and any rules for daylight savings time.
2721• Depending on the distribution, time zone files might be located at /usr/lib/zoneinfo. ls /usr/share/zoneinfo displays the names for time zones that Linux uses. Additional settings are located in the subdirectories.
2722/etc/localtime See the current time zone and change the time zone. The /etc/localtime file identifies the current time zone file used on the system. This is a symbolic link to a timezone file in the /usr/share/zoneinfo directory. Replacing this link changes the timezone. ln -s /usr/share/zoneinfo/time_zone_file /etc/localtime creates a symbolic link to the time zone file that permanently alters the time zone for the current user account.
2723cp -s /usr/share/zoneinfo/time_zone_file /etc/localtime accomplishes the same result as the example above.
2724/etc/timezone See the time zone settings on Debian computers. /etc/timezone identifies the current time zone by region and zone.
2725/etc/sysconfig/clock See the current time zone. The file shows the following line:
2726ZONE=timezone cat /etc/sysconfig/clock
2727ZONE="America/Denver"
2728date To view and manually set the system time. date shows the current local time and the time zone.
2729tzselect Change the value of the time zone (TZ) environment variable.
2730• When executed, the utility prompts you to select a region, then a country, and so on until it has enough information to determine the time zone.
2731• Only the root user can invoke the tzselect utility.
2732Use the tzconfig command on Debian Linux distributions in place of tzselect. To use tzselect:
27331. Type tzselect and press Enter.
27342. Type the number from the list that corresponds to the correct continent or ocean, and press Enter.
27353. Type the number from the list that corresponds to the correct region, and press Enter.
27364. Type the number from the list that corresponds to the correct timezone, and press Enter.
27375. Press 1 to confirm the setting.
2738TZ=time_zone
2739export TZ Change the time zone environment variable. Use the file names in the /usr/share/zoneinfo directory to see the appropriate names for time zones.
2740Environment variable changes are only permanent if they are added to a shell configuration file similar to ~/.bashrc or ~/bash_profile. TZ=America/Denver
2741export TZ
2742
2743-----
2744Applications and services, especially those that are used for security purposes, require accurate time. Be aware of the following details:
2745• Services that communicate with other computers require that the clocks on all computers are synchronized within a small degree of variance.
2746• A timestamp is a record attached to an event or an action that identifies the time when the event took place. Timestamps are used to:
2747 Record when security events, such as logon or system changes, occur.
2748 Identify the correct sequence of events. For example, if a database record is changed from two different computers, the timestamp associated with the changes are used to identify which change took place first (or last).
2749Use the following files and utilities to manage the hardware clock and system time:
2750Use... To... Examples
2751cat /proc/driver/rtc Display the hardware clock time. cat /proc/driver/rtc displays the hardware clock time.
2752hwclock View and set the hardware clock time and synchronize the hardware clock and the system time. Options include:
2753• -a, --adjust adds or subtracts time from the hardware clock to account for systematic drift since the last time the clock was set or adjusted.
2754• -r, --show displays the current hardware clock time. hwclock assumes -r if no options are used.
2755• --set--date sets the hardware clock time and date.
2756• -s, --hctosys sets the system time to the current hardware clock time.
2757• -w, --systohc sets the hardware clock based on the system time.
2758• --localtime sets the hardware clock to local time.
2759• -u, --utc sets the hardware clock to UTC time. hwclock -w sets the hardware clock time to match the system time.
2760hwclock --set --date="2/24/2020 16:45:05" -utc sets the hwclock time to 4:45:05 PM on February 24, 2020 un UTC time.
2761hwclock -s sets the system time to match the hardware clock.
2762hwclock -u sets the hardware clock time to UTC time.
2763/etc/sysconfig/clock Configure the hardware clock to use UTC or local time automatically. the file acts as a configuration file that sets the HWCLOCK setting to control whether the clock uses local or Coordinated Universal Time (UTC):
2764• HWCLOCK -u specifies that the system use UTC.
2765• HWCLOCK --localtime specifies that the system use local time.
2766Managing a large group of computers in different time zones is less complex if HWCLOCK is set to use UTC.
2767ntpdate Set the system time to match the time on a time server on the network. The time provider must be running the time service on UPD port 37. ntpdate 192.168.1.10 sets the time on the local computer to match the time on the time server at 192.168.1.10.
2768date View and manually set the system time.
2769• -d [date] displays the date specified by date. Use now to display the current date.
2770• -s sets the date and time.
2771• -u, --utc specifies UTC time. date -s "11/20/2020 15:48:00" sets the time and date to 3:48:00 PM on November 20, 2020.
2772date -su "11/20/2020 15:48:00" sets the UTC time and date to 3:48:00 PM on November 20, 2020
2773date -d 01jan2014 displays the specified date.
2774date -u shows the current UTC time.
2775
2776-----
2777The Network Time Protocol (NTP) is a method of setting and synchronizing system time between computers. NTP uses a hierarchy of clocks and computers for identifying the current Coordinated Universal Time (UTC). NTP:
2778• Synchronizes time in increments.
2779• Allows computers to be a time consumer and a time provider simultaneously so computers can synchronize hierarchically.
2780• Runs on IP port 123.
2781• Uses strata to define time providers in a hierarchy (levels of time providers):
2782 Stratum 0 devices are accurate clocks (such as atomic clocks) that provide the official UTC.
2783 Stratum 1 devices are attached to the time devices (stratum 0). Stratum 1 devices are referred to as time servers because they provide time to other servers and computers through NTP.
2784 Stratum 2 devices receive their time from stratum 1 devices, and can also provide time to other devices.
2785• Supports up to 256 strata, with lower devices getting time from higher devices and providing time to devices in a lower stratum.
2786• Can be configured to use a pool of time servers at pool.ntp.org.
2787• Uses stepping to quickly make large adjustments to close time discrepancies; usually about once every 60 seconds.
2788• Uses slewing to make smaller incremental time adjustments at a rate of about every 15 - 17 minutes. Slewing occurs when time discrepancies are under 128ms.
2789• Does not adjust times when time discrepancies are larger than 17 Minutes. This is known as insane time.
2790• Tracks of the NTP daemon (ntpd) activity in the /var/log/ntp log.
2791Use the following files and utilities to manage time using the NTP:
2792Use... To... Examples
2793/etc/ntp.conf Configure the time providers on the NTP client.
2794• Each entry in the file begins with server and then the address of the time provider.
2795• The server 127.127.1.0 represents the local host address and sets the system time to the hardware clock if no other time providers are available. server 0.fedora.pool.ntp.org synchronizes the time with the Fedora time server pool.
2796server 192.168.1.10 synchronizes the time with a computer at the specified IP address.
2797server 127.127.1.0 synchronizes the time with the hardware clock on the local computer.
2798ntpdate Update the current time on a computer. ntpdate:
2799• Must be run as root.
2800• Will not function if ntpd is currently running.
2801ntpdate is deprecated; Use ntpd in its place. ntpdate 0.pool.ntp.org updates the system time using a time provider from the NTP pool.
2802ntpd Manage the NTP daemon from the command line. Options include:
2803• -q does a one-time synchronization with a time provider. It is similar to ntpdate.
2804• -g allows the NTP daemon to ignore insane time restrictions for the first synchronization.
2805• -c specifies the name and path of the configuration file. The default is /etc/ntp.conf. ntpd -qg updates the current time on the computer and ignores insane time restrictions.
2806ntpd -c ~/ntp/ntpconfig.txt changes the configuration file that NTP uses to ~/ntp/ntpconfig.txt.
2807rcntp start
2808or
2809service ntpd start Start the NTP daemon.
2810rcntp only works on BSD operating systems. service ntpd start starts the NTP daemon.
2811insserv ntp Configure the NTP daemon to start at boot time (BSD systems only.)
2812ntpq Query the status of the NTP daemon. Use -c to invoke a command. Commands include:
2813• remote specifies the IP address of the current time provider.
2814• refid Specifies the type of time source the time provider is using.
2815• st shows the stratum of the time provider.
2816• when shows the last synchronization time.
2817• poll shows the synchronization interval.
2818• reach lists the last time NTP queried the time provider.
2819• delay displays the network lag time between the time provider and the client. ntpq -c reach shows the last time NTP queried the time provider.
2820ntptrace Display the next stratum up from the time provider.
2821Keep the following in mind when working with NTP:
2822• To see what happens as the NTP daemon starts, use one terminal to start the daemon, and use another terminal with the tail command to view the daemon log at /var/log/ntp.
2823• The time used by the computer is adjusted to account for network delay and other inaccuracies detected in the received time. The amount of error that the algorithm identifies is called the drift. The drift is calculated over time and typically saved on the computer to quickly identify accurate time, compensated by the drift amount.
2824• The computer continues to poll the time servers to ensure that the system time remains synchronized.
2825
2826-----
2827A Mail Transfer Agent (MTA) sends messages between clients on a local system or over the Internet. MTAs:
2828• Receive mail from a Mail User Agent (MUA). An MUA is an email application such as Mozilla Thunderbird or Microsoft Outlook.
2829• Send/receive messages to/from other MTAs using Simple Mail Transfer Protocol (SMTP).
2830• Receive messages from MUAs using Simple Mail Transfer Protocol (SMTP) by default.
2831• Send messages to MUAs using Post Office Protocol 3 (POP3) or Internet Message Access Protocol (IMAP) when sending and receiving messages. IMAP has a few advantages over POP3. IMAP:
2832 Can download the entire message or only the message header.
2833 Allows messages to be kept in the message store.
2834 Allows creation of custom folders.
2835• Are used to relay messages from several daemons, including cron and at, when jobs finish running.
2836The following are several of the most common MTA types on a Linux system:
2837Type Details
2838Sendmail Is an older MTA, but is still widely used. It is somewhat more complex to configure than other MTA's. Sendmail:
2839• Is the default MTA used on many distributions.
2840• Is non-modular (a single program.)
2841• Uses an init script is located at /etc/rc.d/init.d/sendmail.
2842Postfix Is the default MTA on many SUSE distributions. Postfix
2843• Is modular (i.e., made up of multiple programs).
2844• Has simplified configuration mechanisms.
2845qmail Is an additional MTA that is not installed by default on any distribution. Qmail:
2846• Is modular.
2847• Implements several security features.
2848• Has simplified configuration mechanisms.
2849• Implements additional protocols:
2850 Quick Mail Queuing Protocol (QMQP) allows the sharing of email queues among different MTAs.
2851 Quick Mail Transport Protocol (QMTP) is a transmission protocol similar to SMTP, but considered to be faster.
2852Exim Is the default MTA only on a very few distributions. Exim:
2853• Is non-modular.
2854• Has simplified configuration mechanisms.
2855Use the following to manage messages:
2856Utility/File Description Examples
2857mail Sendmail uses the mail command to send and receive messages from the mail server:
2858• To manage messages for the local user from the mail spool, type mail.
2859 Type the number of the message to read a message at the '?' prompt.
2860 Type d and the message number to delete the message at the '?' prompt.
2861 Type q to exit the mail prompt at the '?' prompt.
2862• To send mail to a user on the local network:
28631. Type mail user_name@domain.
28642. Type a subject and press enter.
28653. Type the message, then press return to start a new line.
28664. Press Ctrl+d to send the message.
2867• Use mailq or sendmail -bp to display the mail queue.
2868• Use sendmail -q to deliver all queued mail.
2869• Use sendmail -bd to start the sendmail daemon. mail jdoe sends a mail over the network to the user jdoe.
2870mail jdoe@gmail.com sends an email to the specified email address.
2871? 4 displays message four.
2872? d4 deletes message four.
2873? q exits the mail prompt.
2874mailq displays the mail queue for the current user.
2875/etc/aliases.db /etc/aliases.db is a binary database that stores the aliasing information for sendmail. Be aware of the following details:
2876• The /etc/aliases file contains the list of sendmail email aliases in text format.
2877• Use the newaliases command to create or update /etc/aliases.db from the /etc/aliases file. newaliases is identical to sendmail -bi. root: jdoe sends all mail to root to jdoe's inbox.
2878~/.forward /home/user/.forward forwards messages from the local user to a user specified in the file.
2879• Use this for temporary forwarding.
2880• Type the name of the user or address on a single line.
2881Forwarded email messages do not get saved in the original account. jdoe forwards the mail to the user jdoe over the local network.
2882jdoe@gmail.com forwards the mail to the specified account.
2883/var/spool/mail Each user account on the system has a mail file in the /var/spool/mail directory. When new mail arrives, Linux tacks it onto the end of the recipient's mail file. /var/spool/mail/gshant holds email for the gshant user account.
2884
2885-----
2886Structured Query Language (SQL) is used in most database applications. It provides commands for working with databases and tables, for populating tables with data, and for querying and organizing the data. This lesson uses a MySQL database for demonstration purposes.
2887The following table lists commands used to access and control a MySQL server:
2888Use... To... Examples
2889mysql_install_db Install the system tables and other database items for MySQL.
2890mysqlshow See a list of databases in MySQL.
2891mysqladmin Manage a MySQL database. Options include:
2892• password creates a password.
2893• -u specifies a user.
2894• -h specifies the host for the MySQL server. mysqladmin -u user -h localhost password '123456' creates the user account on the local host with a password of 123456.
2895If the -h option is omitted, the local host is implied.
2896mysql Access the MySQL command line. Options include:
2897• -u specifies a user
2898• -p specifies a password. If used alone, -p prompts for the password in the next line. mysql -u root -p accesses MySQL after prompting for a password.
2899mysql -u root -p123456 Accesses MySQL using the password for root. This command is considered insecure.
2900mysql -u root -p 123456 accesses MySQL after prompting for a password, and attempts to connect to a database named 123456.
2901service mysqld start rcmysql start Start the mysqld daemon for MySQL. service mysqld start starts the MySQL daemon on a System V system.
2902The following list defines several basic database objects:
2903• A database is a group of related data organized using tables and accessed using a database application.
2904• A table is a set of data organized into records (rows), and attributes (columns).
2905• A record is an item or entity in a table with its attributes listed across a row. For example, a record may have a name of 'aspen tree', a height of '3 meters', and a type of 'deciduous'. Records are sometimes called tuples.
2906• Attributes in a table are organized into columns. For example a name attribute might have 'aspen tree' in the first record, 'oak tree' in the second record, and 'white fir' in the third record.
2907• Integers are whole numbers between -2,147,483,648 and 2,147,483,647.
2908• A primary key is an attribute of a record that uniquely identifies it from all other records in the table. For example, a telephone number or a unique ID number can be used as a primary key. Primary keys are used to specify records when querying data from multiple tables.
2909When adding information to a database, certain attributes have specific data types. For example, a field that holds a price in US dollars uses numbers with two decimal points for dollars and cents, and a name uses characters. SQL has several data types available when adding information to tables. The following list describes several common SQL data types.
2910• Character data types allow basic alpha-numeric characters. These use an exact length.
2911• Varchar data types allow alpha-numeric characters of any length up to a maximum specified length.
2912• Decimal data types hold numbers that can have decimal values up to 38 decimal places. The exact number of decimal places is specified.
2913• Float is a numeric data type that allows floating decimals. This stores approximate values.
2914• Time holds hours, minutes, seconds, and fractions of seconds.
2915• Date holds calendar dates.
2916• Enum holds a set of specified values such as 'small', 'medium', and 'large'.
2917Administrators use several commands, also known as keywords, to create, modify, and extract data from databases. The following table lists several of the most commonly-used commands.
2918Use... To... Examples
2919CREATE DATABASE Create a new database. CREATE DATABASE clothing; creates a database named clothing.
2920USE Specify the database to work in. USE clothing; accesses the clothing database.
2921SHOW TABLES Displays a list of tables in a database. SHOW TABLES clothing; lists the tables in the clothing database.
2922CREATE TABLE Add a table to the database and create the attributes for records to be added to the table. CREATE TABLE shirts (invoice CHARACTER(7), type VARCHAR(40), color VARCHAR(20), price DECIMAL(5,2), size ENUM('XS','S','M','L','XL','XXL','XXXL'), location(VARCHAR(50), gender ENUM('male','female','either')); creates a table called shirts; adds attributes for invoice, type, color, price, size, location, and gender; and defines the data types for each attribute.
2923INSERT INTO Add records to the table. A value must be specified for each attribute in the table. To leave an attribute blank, place two commas together. INSERT INTO shirts VALUES 0008103,'t-shirt','green',7.95,'S','warehouse1 13-C-3','etiher'; adds a record for small green t-shirts.
2924INSERT INTO shirts VALUES 0008094,'dress shirt','white',14.49,'L','warehouse1 5-J-1','male'; adds a record for men's large white dress shirts.
2925DESCRIBE See a description of a database object. DESCRIBE shirts; displays information about the shirts table.
2926SELECT Retrieve information from a table. Clauses include:
2927• WHERE filters using data from a specified field.
2928• ORDER BY sorts displayed data based on an attribute name.
2929• GROUP BY determines how information in a list is grouped. SELECT location, price FROM shirt WHERE color='green' AND type='t-shirt' AND size='M' ORDER BY price; shows the location and price of all medium green t-shirts from the shirt table. The results are sorted by price.
2930UPDATE Change the values in a record. UPDATE shirts SET price=11.95 WHERE type='dress shirt' AND size='L' AND gender='male'; changes the price on large men's dress shirts.
2931DELETE FROM Remove records from a table. DELETE FROM shirts WHERE color='pink' AND type='polo' AND gender='male'; deletes records for men's pink polo shirts.
2932ALTER TABLE Add, change or remove attributes from tables. ALTER TABLE shirts ADD COLUMN sleeve ENUM('short','long'); creates a new attribute for sleeve length.
2933ALTER TABLE shirts ALTER COLUMN type style; changes the name of the type attribute to style.
2934ALTER TABLE shirts DROP COLUMN location; deletes the location attribute.
2935DROP TABLE Delete an existing table. DROP TABLE shirts; deletes the shirts table.
2936Keep the following in mind when working with SQL statements:
2937• SQL commands, or keywords, are conventionally written in all caps but are actually not case-sensitive.
2938• Statements must end with semicolons. If a semicolon is omitted, the command terminal assumes that the command will be finished on the next line.
2939• In commands, character values need single quotes, but if number values have single quotes, they are treated like character strings. This makes a difference in sorting and doing actions such as getting the sum of a column. If an attribute only holds numbers, use a data type designed to hold numbers.
2940
2941-----
2942Log files are records of information about kernel and daemon errors. Log files:
2943• Are typically recorded in plain text.
2944• Are typically controlled by the syslogd, rsyslogd, or syslog-mg daemon depending on the distribution.
2945• Can be encrypted or sent to a remote server to keep attackers from altering them.
2946• Are an invaluable resource for troubleshooting a Linux system.
2947By default, many daemons send their log messages to the /dev/log file. The logging daemon (e.g., syslogd) parses the message entries in /dev/log file to the correct log file locations using entries in /etc/syslog.conf (or a similar configuration file that follows the name of the daemon, such as /etc/rsyslog.conf). Entries in the /etc/syslog.conf file have the following syntax:
2948facility.priority destination
2949The following table describes the entry options in the /etc/syslog.conf file:
2950Facility Priority Destination (also known as action)
2951The facility is the daemon that produces the message. Be aware of the following facilities:
2952• authpriv identifies authentication (login) messages
2953• cron identifies messages from the memory-resident scheduler
2954• daemon identifies messages from resident daemons
2955• kern identifies kernel messages
2956• lpr identifies printer messages
2957• news identifies messages from the news system
2958• mail identifies messages from Sendmail
2959• user identifies messages from user-initiated processes and programs, including failed logons
2960• local0-local7 identifies user-defined errors
2961• uucp identifies Unix to Unix copy (UUCP) system messages
2962• syslog identifies messages from the syslog process The priority is level of importance of the message. Be aware of the following priorities (listed high to low):
2963• emerg represents emergency, the computer is unstable
2964• alert represents immediate action
2965• crit represents critical errors
2966• err represents serious errors
2967• warning represents non-critical errors
2968• notice represents normal events that are significant
2969• info represents informational messages
2970• debug represents all messages The destination log file is where the logging daemon sends the log file. Options include:
2971• /var/log/boot.log
2972• /var/log/messages
2973• /var/log/cron
2974• /var/log/maillog
2975• @ipaddress (IP address of remote server receiving log file messages)
2976• user1,user2 (sends messages to the specified user currently logged on to the computer)
2977• * (sends messages to all users currently logged on the computer)
2978• /dev/tty1 (sends messages to virtual console 1)
2979The following are examples of entries in the /etc/syslog.conf file:
2980Example Description
2981cron.* /var/log/cron Sends all cron messages to the /var/log/cron log.
2982*.emerg * Sends all emergency messages to all users on the computer.
2983kern.debug /var/log/kerndebug Sends all kernel messages to the /var/log/kerndebug log.
2984*.* @192.168.10.1 Sends all log messages to a remote server with an IP address of 192.168.10.1.
2985Sending log message to a remote server increases security for log files and centralizes log file locations. To enable a server to receive log file messages:
2986• Set the value of the SYSLOGD_PARAMS parameter to -r in /etc/sysconfig/syslog.
2987• Ensure UDP port 514 is open on the firewall.
2988
2989-----
2990Be aware of the following common log files:
2991File/Directory Contents
2992/var/log/boot.log
2993/var/log/boot.msg Depending on the distribution, the system holds messages generated during the boot process in one of the files.
2994/var/log/faillog
2995/var/log/btmp The faillog or btmp file lists login failures for user accounts on a computer depending on the distribution.
2996/var/log/firewall The firewall file displays messages about firewall actions.
2997/var/log/lastlog The lastlog file holds information about the last time each user logged in (and is used by the utility of the same name).
2998/var/log/maillog The maillog file contains reports on mail server status and messages related to incoming and outgoing mail.
2999/var/log/messages The messages file is the default file for storing system messages. This file may include copies of messages that appear on the console, internal kernel messages, and messages sent by networking programs.
3000/var/log/warn The warn file displays warning messages from many processes by default.
3001/var/log/wtmp The wtmp file keeps track of all users who have logged into and out of the system as well as listing every connection and run-level change.
3002/var/log/dmesg The dmesg file is often called the kernel ring buffer. It reports messages received in the process of configuring devices as the system boots.
3003/var/log/secure The secure file logs any attempts to log in as the root user or attempts to use the su command. This file also contains information on remote logins and failed root user login attempts.
3004/var/log/cron The cron file stores messages related to tasks scheduled with cron. It keeps track of which tasks are run and when they were started.
3005/var/log/sa The /var/log/sa directory stores /sa[n] files, which contain all performance information for the day of the month indicated by [n]. For example, /var/log/sa/sa15 contains performance information for the fifteenth day of the month, and it will be overwritten on the fifteenth day of the next month.
3006/var/log/XFree86.log The XFree86.log file stores X Window System startup messages. Examine this file to identify X Window System configuration status and errors.
3007/var/log/rpmpkgs On Red Hat systems, the rpmpkgs file tracks installed packages. It also records all kernel packages on the system.
3008/tmp/install.log
3009/root/install.log The install.log might be present depending on the distribution. This file records messages related to the installation and can be useful for installation records for a computer.
3010
3011-----
3012By default, most Linux distributions include the logrotate utility to automatically manage, compress, rename, and delete log files based on specific criteria (such as size or date). On most distributions, logrotate:
3013• Automatically runs each week as a cron job to periodically maintain system logs. Old logs are renamed with a numbered extension, and logs are deleted after 4 weeks.
3014• Uses /etc/logrotate.conf as the main configuration file. It contains entries that apply to the whole system.
3015• Uses scripts in /etc/logrotate.d to overwrite the settings in /etc/logrotate.conf.
3016The following table describes the commands found in /etc/logrotate.conf or scripts in /etc/logrotate.d:
3017Use... To... Examples
3018compress Compress old log files using gzip.
3019maxage Remove rotated logs that are older than the specified number of days. maxage 180 deletes every rotated log older than 180 days.
3020dateext Use a daily extension on archived files using file.YYYYMMDD format.
3021rotate Specify the number of times to rotate the log before deleting it. rotate 5 rotates the log file five times and then removes it.
3022size Rotate or remove log files based on file size. Use the following:
3023• sizek to specify the size in kilobytes.
3024• sizeM to specify the size in megabytes.
3025• sizeG to specify the size in gigabytes. size 100M deletes or rotates files larger than 100 megabytes.
3026notifempty Prohibit empty logs from being rotated.
3027missingok Prevent errors from being displayed for missing log files.
3028create Create a log file with a name identical to the one just rotated. The command specifies the mode (permissions) of the file and well as the owner and group for the file. create 744 root root creates a file with read, write, and execute permissions for the owner and read permission for the group and everyone; specifies root as the file owner; and specifies root as the group.
3029postrotate Indicate the start of script commands to be executed after log files are rotated. The term endscript must be used to indicate the end of the script.
3030
3031-----
3032The following table describes commands to view and manage text-based log files:
3033Use... To... Examples
3034cat View the contents of a log file. cat /var/log/messages shows the entire text of the messages log.
3035grep Filter text from a text file. cat /var/log/messages | grep ftp filters the output of the cat command to show only lines that contain the term ftp.
3036tail Show the last 10 lines of a file. Be aware of the following options:
3037• -f displays additions to the log in real time.
3038• -n# option with specifies the number of lines to display. tail /var/log/messages shows the last 10 lines of the messages log.
3039tail -f /var/log/messages continually displays the real-time entries of the messages log.
3040head Show the first 10 lines of a file. head /var/log/messages shows the first 10 lines of the messages log.
3041less
3042more Scroll through individual pages of a file. less /var/log/messages allows scrolling through each page of the file.
3043vi
3044gedit Open text files for editing. vi less /var/log/messages opens the messages log for editing.
3045The following table lists several commands used to view and manage binary log files.
3046Use... To...
3047dmesg View the boot logs and to troubleshoot hardware errors. The dmesg command shows information about all the hardware controlled by the kernel and displays error messages as they occur.
3048dmesg -n # Control which error messages are sent to the console. For example, dmesg -n 1 sends only the most critical errors (0 and 1) to the console. Other messages are still logged in the log files.
3049last Show all users who have logged into and out of the system as well as listing every connection and run-level change (i.e., the contents of the /var/log/wtmp file).
3050faillog
3051lastb Show all failed login attempts on the system (i.e., the contents of the /var/log/btmp file or /var/log/faillog file depending on the distribution).
3052lastlog Show a list of the dates and times for the last login for each user.
3053logger Change the message severity and where logged messages are sent.
3054logrotate Manage, compress, rename, and delete log files based on specific criteria (such as size or date).
3055sar View system statistics. sar is short for System Activity Report. It comes as part of the sysstat (System Statistics) package. When used alone, it returns CPU statistics. Common options include the following:
3056• -A Displays all information.
3057• -b Displays I/O statistics.
3058• -B Displays swap statistics.
3059• -f /var/log/sa filename Displays information from the specified file.
3060
3061-----
3062At its most basic level, a script is a command or commands stored in a file. When the shell reads the file, it executes the commands as if they were typed at the keyboard. When using scripts, remember to do the following:
3063• Specify the shell used to run the script, such as bash, csh, or ksh.
3064• Use comments to explain what the script does.
3065• Assign execute permissions to the script with the script with the chmod command, and use the SUID bit to force the script to run with the permissions of the script owner, not with the permissions of the user who runs the script.
3066• Use exit 0 to end the script.
3067• Use one of the following methods to run the script:
3068 Add the folder that contains the script to the PATH environment variable, then type the script name in the present working directory.
3069 Save the script in a folder that is already in the PATH, such as /usr/bin or /bin, then type the name of the script.
3070 Type the full pathname to the script to run the script from anywhere.
3071 Type ./script_name to run the script in the present working directory. (./ indicates the present working directory.)
3072The following table lists some simple scripting functions.
3073Function Description Examples
3074Specify the shell that runs the script The line that specifies the shell must be the first line in the script. It starts with a number sign and exclamation point (#!) and is followed by the path to the shell executable. #! /bin/bash specifies the script will run in the bash executable.
3075Add comments Comments begin with a number sign (#). The shell ignores these lines when running the script. Comments help one programmer to know how another programmer constructed the script, and help the original programmer recall how the script was constructed.
3076Add commands When a script runs, it executes commands as if they were typed on the command line.
3077Commands can be typed on a single line or separated using semi-colons (;). For example, if a script contains pwd on a single line, when it executes, it displays the current directory. #! /bin/bash
3078ls /home/user/Pictures
3079exit 0
3080This script uses the ls command to list the contents of the /home/user/Pictures directory.
3081Use variables Variables hold values that the script uses when running. These values can be either numbers or test. When the script uses a variable, it uses the value assigned to the variable. Keep the following in mind when using variables:
3082• Linux script variables commonly are written using all capital letters. This helps programmers quickly identify them.
3083• When creating variables, place the equals (=) symbol immediately after the variable with no space. If a space follows the variable name, The script treats it as a command, and tries to execute it.
3084• Use a space after the equals (=) symbol only when you want the variable to be the output of a command.
3085• Use quotes if a variable value has a space in it. It is a good practice to always use quotes when you want a variable to represent a character string. VARIABLE1=Hello assigns VARIABLE1 the value of Hello.
3086VARIABLE1 = Hello causes an error because the script tries to run the command VARIABLE1, which by default does not exist.
3087VARIABLE1="Hello, Mr. Smith" assigns VARIABLE1 the value of Hello, Mr. Smith.
3088VARIABLE1=Hello, Mr. Smith assigns VARIABLE1 the value of Hello, then displays an error because it treats Mr. as a command and tries to execute it.
3089VARIABLE1=pwd assigns VARIABLE1 the value of pwd.
3090VARIABLE1= pwd assigns VARIABLE1 the value of the result of running the pwd command. For example, /home/jdoe.
3091Display information on the screen The echo command displays information on the screen. It can display a literal value or a variable. Keep the following in mind:
3092• It is a good practice to always use quotes when you want a variable to represent a literal value.
3093• Use a dollar ($) symbol to display the value of a variable.
3094• Enclose a command with acute symbols (`) (below the ~ on a standard US keyboard) to display the result of a command.
3095• Use a backslash (\) to display special characters. echo Hello displays Hello on the screen.
3096echo Hello, Mr. Smith. displays Hello, Mr. Smith on the screen.
3097echo "Hello, Mr. Smith." displays Hello, Mr. Smith. on the screen.
3098echo \"Hello, Mr. Smith\" displays "Hello, Mr. Smith." on the screen.
3099echo pwd displays pwd on the screen.
3100echo `pwd` displays the result of running the pwd command. For example, /home/jsmith.
3101echo $VARIABLE1 displays the value of VARIABLE1.
3102echo \$VARIABLE1 displays the literal string $VARIABLE1.
3103Get user input The read command creates a variable and prompts the user to type text. It assigns to the variable the value the user types. By default, the user input is treated as a text string. #! /bin/bash
3104echo "What is your name?"
3105read VARIABLE1
3106echo "Hello," $VARIABLE1"."
3107exit 0
3108The script prints What is your name? on the screen, prompts the user for input, then displays the input in the sentence Hello, <input>.
3109Declare integers or functions in the text The declare -i command is used to change the numeric strings into integers. Use the command in the script before populating variable values.
3110The declare -f command is used to declare functions in a script. A function associates a shortcut (called the function name) with a set of commands. #! /bin/bash
3111NUM1=7
3112NUM2=5
3113TOTAL=$NUM1+$NUM2
3114echo $TOTAL
3115exit 0
3116This script gives an output of the text string 7+5 because the shell treats the variable values as text charters.
3117#! /bin/bash
3118declare -i NUM1
3119declare -i NUM2
3120declare -i TOTAL
3121NUM1=7
3122NUM2=5
3123TOTAL=$NUM1+$NUM2
3124echo $TOTAL
3125exit 0
3126This script gives an output of the integer 12 because the shell treats the variable values as integers.
3127Numeric text strings can also be converted to integers using the following format:
3128echo $[$NUM1+$NUM2] gives an output of 12 regardless of whether the declare command is used.
3129
3130-----
3131In addition to the basic commands, scripts can contain the following types of control structures:
3132• Branching structures let scripts perform different actions based on specific conditions or user input.
3133• Looping structures repeat a specified set of commands according to a specified set of conditions specified in the script.
3134The following table describes the commands and statements used to create control structures:
3135Structure Description Examples
3136Sequences Use the seq command to create a sequence of numbers. Command structure can take any of the following forms:
3137• When using only one number in the command, seq starts at 1 and counts to the specified number.
3138• When two numbers are given in the command, seq begins with the first number and counts up to the second number.
3139• When three numbers are given in the command, seq starts at the first number and counts in increments of the second number up to the third number. seq 10 counts from 1 to 10.
3140seq 5 15 starts at 5 and counts to 15.
3141seq 5 5 100 starts at 5 and counts to 100 in increments of 5. (for example 5, 10, 15, 20...)
3142seq 10 -1 -10 starts at 10 and counts down to -10.
3143Testing conditions The test command is used to evaluate whether a condition is true or false. test is commonly used in conjunction with if, then, else statements in a shell script. test options include:
3144• -d tests whether a directory exists.
3145• -e tests whether a file exists.
3146• -f tests whether a regular file exists.
3147Operands for test include:
3148• = tests whether strings are equivalent.
3149• != tests whether strings are not equivalent.
3150• -o is used to specify that either of the options can be equivalent.
3151• -eq tests whether integers are equivalent.
3152• -ne tests whether integers are not equivalent.
3153• -gt tests whether the first integer is greater than the second.
3154• -lt tests whether the first integer is less than the second. test -f ~/myfile.txt determines whether a file named myfile.txt exists in the user's home directory.
3155test -d ~/bin determines whether a directory named bin exists in the user's home directory.
3156test $NAME = "George Washington" determines whether the value if the $NAME variable is George Washington.
3157test $NAME -o $NAME2 = "George Washington" determines whether the value if either the $NAME or the Name2 variable is George Washington.
3158test $NUM1 -le $NUM2 determines whether the value of the variable NUM1 is less than the value of the variable NUM2.
3159If, then, else statements Use if, then, else statements to evaluate conditions. When using these statements, keep the following in mind:
3160• The if command defines the condition to be evaluated.
3161• The then command specifies the commands to perform if the condition is true.
3162• The else command specifies the commands to perform if the condition is false.
3163• Operands include:
3164 = (equal to)
3165 != (not equal to)
3166 > (greater than)
3167 < (less than)
3168• The if command requires spaces between the conditions and the operand.
3169• The if command also requires spaces between the conditions and the brackets ('[' and ']').
3170• The statements must be closed using the fi command. #! /bin/bash
3171echo "What is your name?"
3172read NAME
3173if [ $NAME = "George" ]
3174 then
3175 echo "That's my name too."
3176 else
3177 echo "Hello" $NAME "I'm George."
3178fi
3179exit 0
3180The script takes the user input and evaluates it to determine whether the user types George. If the user types George, the script responds with That's my name too. Otherwise, the script responds with the statement under the else command.
3181The if statement can also be written using the test command.
3182For example, if test $NAME = "George".
3183Case statements Use the case command to write conditional scripts that have several possible options. When using case commands, keep the following in mind:
3184• Case statements can have an unlimited number of possible options.
3185• When the script evaluates an option as being true, all remaining options are skipped.
3186• Each option can execute several lines of commands. Close each case with two semi-colons.
3187• Case statements must be closed using esac (case spelled backwards.) #! /bin/bash
3188echo "What is your favorite season?"
3189read SEASON
3190case $SEASON in
3191 spring) echo "The thing I like best about spring is the flowers."
3192 ;;
3193 summer) echo "I wish I could go swimming, but being a computer, that might not work out so well."
3194 ;;
3195 fall) echo "Fall leaves, Thanksgiving...what's not to like?"
3196 ;;
3197 autumn) echo "Fall leaves, Thanksgiving...what's not to like?"
3198 ;;
3199 winter) echo "Skiing looks fun, but snowstorms interfere with my reception of the neighbor's WiFi."
3200 ;;
3201 *) echo $SEASON "is not listed in my database as being a season. Choose: spring, summer, fall, autumn, or winter."
3202 ;;
3203esac
3204exit 0
3205The script asks the user about season preferences and has a response for each common answer. The last option is a catch-all for any answer other than those specified in the script.
3206While loops The while loop continuously executes all commands between the do and done statements while a specific condition exists. while loops are useful for repeating an action until a specified value is met. Keep the following in mind when using while loops:
3207• while loops require do and done statements.
3208• while loops can create infinite loops that lock up a terminal. For example, the following statement creates an infinite loop because the condition needed to exit the loop can never be met:
3209while test $VAR != "Done!"; do VAR="Not done yet!"; done
3210• Pressing Ctrl+C sends an interrupt signal to the process to terminate an infinite loop. #! /bin/bash
3211declare -i NUM
3212echo "I'm thinking of a number between 1 and 100."
3213# Give NUM a value to prevent errors.
3214NUM=0
3215while test $NUM -ne 23
3216 do
3217 echo "What is your guess?"
3218 read NUM
3219 if test $NUM -lt 23
3220 then
3221 echo "The number is higher."
3222 fi
3223 if test $NUM -gt 23
3224 then
3225 echo "The number is lower."
3226 fi
3227 done
3228echo "You guessed it."
3229exit 0
3230The script uses a while loop to keep the user guessing numbers until they get the answer. As long as the number is not 23, the if statements keep giving the user clues as to whether the number is higher or lower. As soon as the user types 23, the while loop exits and the final statement displays telling the user that the guess is correct.
3231Until loops An until loop is nearly identical to a while loop, but only opposite:
3232• The while loop executes commands while a condition is true.
3233• The until loop executes commands until a condition is true.
3234The while loop example could be changed into an until loop by changing 6th line to:
3235until test $NUM -eq 23 #! /bin/bash
3236declare -i NUM
3237echo "I'm thinking of a number between 1 and 100."
3238# Give NUM a value to prevent errors.
3239NUM=0
3240until test $NUM -eq 23
3241 do
3242 echo "What is your guess?"
3243 read NUM
3244 if test $NUM -lt 23
3245 then
3246 echo "The number is higher."
3247 fi
3248 if test $NUM -gt 23
3249 then
3250 echo "The number is lower."
3251 fi
3252 done
3253echo "You guessed it."
3254exit 0
3255For loops
3256A for loop is a shell structure that executes a set of commands a set number of times. A for loop:
3257• Is useful when a specific action needs to be done a set number of times.
3258• Executes all commands between the do and done statements. These are required.
3259• Can be used with a list of items with one action being done for each item in the list. #!/bin/bash
3260declare -i NUM
3261echo "Multiplication quiz!!!"
3262echo "Which set of multiplication tables do you want to drill?"
3263read NUM
3264echo "OK. We'll work on 0X"$NUM "through 12X"$NUM"."
3265for LOOP in $(seq 0 12)
3266 do
3267 echo "What is" $NUM "X" $LOOP"?"
3268 read ANSWER
3269 if test $ANSWER -eq $[$NUM*$LOOP]
3270 then
3271 echo "That is correct!"
3272 else
3273 echo "That's not it. The correct answer is" $[$NUM*$LOOP]"."
3274 fi
3275done
3276exit 0
3277The script uses a for loop to ask the correct number of multiplication questions. The loop starts at 0 and loops through from 0 to 12. This ensures that the correct number of questions are asked.
3278The script uses the seq command to create the loop sequence. Other methods to create a for loop include:
3279• for LOOP in 1 2 3 4 5 counts from 1 to 5.
3280• for LOOP in {1..5} counts from 1 to 5.
3281• for LOOP in {0..10..2} counts from 0 to 10 in increments of 2.
3282
3283-----
3284A text stream is any information printed to standard output (usually the screen). For example, the ls command sends the list of files to the screen. The following commands intercept and process the text stream in various manners:
3285Use... To... Example
3286cut Remove characters and fields from lines of text in a text stream or file. The command uses its options to determine whether to cut characters or fields and sends the results to standard output. Be aware of the following options:
3287• -c cuts characters.
3288• -f cuts fields.
3289• -d specifies the character used as the field delimiter. The default is a tab.
3290• -s removes lines that do not have a field delimiter.
3291• -d' ' to specify a space as the field delimiter. For the following example, a file named myfile has the following text:
3292http://www.site1.com
3293http://www.mysite.com
3294http://www.anothersite.com
3295cut -c1-7 myfile takes the first seven characters of each line and sends it to standard output. For the example, this is http://.
3296cut -c8- myfile takes character eight to the end of each line and sends it to standard output. This removes http:// from each line.
3297expand Replace a tab character with a specified number of spaces.
3298• The default is eight spaces.
3299• -t specifies the number of spaces to be used. expand -t 1 myfile replaces each tab character in the file with a single space.
3300fmt Format lines in a file or text stream to a uniform length. This is useful to format files with long lines to fit in a terminal. Be aware of the following options:
3301• -w specifies the number of characters for the width. The default is 75.
3302• -s prevents the command from formatting lines shorter than the specified length. This command is often used with code text to keep lines of code separate. fmt -w 80 myfile sends the contents of myfile to standard output with all lines having a uniform length of 80 characters.
3303join Combine text from two files based on identical fields with text and send the result to standard output. By default, fields are offset by whitespace. Be aware of the following options:
3304• -i ignores case when searching for identical text.
3305• -j specifies the number of the field to use when joining. This specifies both files.
3306• -1 specifies the number of the field from the first listed file to use when joining.
3307• -2 specifies the number of the field from the second listed file to use when joining.
3308• -t specifies the character to use as the field delimiter. File1 has the following text:
33091 Mark Twain
33102 William Shakespeare
33113 John Steinbeck
3312File2 has the following text:
33131 Tom Sawyer
33142 Othello
33153 Of Mice and Men
3316join file1 file2 sends the following text to standard output:
33171 Mark Twain Tom Sawyer
33182 William Shakespeare Othello
33193 John Steinbeck Of Mice and Men
3320join -j 3 -t : fileA fileB joins the files using the third field as the common field, and a colon as the field delimiter.
3321nl Place a line number in front of each line in a text file and send the result to standard output. Be aware of the following options:
3322• -i specifies the increment to use when numbering the lines.
3323• -v specifies the starting number.
3324• -s specifies the text to place between the number and the line. The default is two spaces. nl -s ": " myfile adds the number, a colon, and a space to the front of each line in the file.
3325od Display the contents of any file in octal, decimal, hexadecimal, or character format. Be aware of the following options:
3326• -b specifies an octal dump.
3327• -d specifies a decimal dump.
3328• -x specifies a hexadecimal dump.
3329• -c specifies a character dump. od -c /bin/tar shows the contents of the tar command executable in character format.
3330paste Add the contents of one file to the contents of another file on a line-by-line basis.
3331• The default is a tab.
3332• -d specifies a character to place between the conjoined lines of each file. Only a single character can be specified. paste -d @ file1 file2 conjoins each line of file2 to the end of each line of file1 and places an @ between each line pair.
3333
3334pr Format a text file for printing. By default this command:
3335• Separates files into 66-line pages.
3336• Uses the first five lines to create a header that contains a page number, the time and date, and the path to the file.
3337• Uses the last five lines to create a footer of blank lines.
3338Be aware of the following options:
3339• -d double-spaces the lines.
3340• -h specifies text to replace the file name in the header.
3341• -l specifies the number of lines. The default is 66.
3342• -t prevents the command from creating the header and footer.
3343• -o creates a margin on the left side of the text. pr myfile sends the text to standard output using default settings.
3344pr -d -l 60 -t -o 5 myfile sends the text to standard output using, double spacing, a page length of 60 lines, no headers or footers, and a 5-space margin on the left side.
3345sed Take text or commands from the command line as input and modifies the text document named in the command line. sed is particularly useful under the following circumstances:
3346• When a file is too large to open and edit conveniently in a text editor.
3347• When the series of edits (e.g., adding line spacing, margins, replacing text) is too complex to perform easily in a text editor.
3348• When it is easier to perform a series of global document changes.
3349Be aware of the following flags and options:
3350• s replaces the text behind the first / with the text behind the second /. To save the results of the command, use the > to redirect the output to a new file.
3351• d deletes lines that contain the specified term.
3352• g changes all occurrences of the term in a line.
3353• p prints the modified lines in addition to the standard output.
3354• -n suppresses all printing. The p flag can be used to print the modified lines.
3355• -e allows multiple commands in a sed operation.
3356• -f calls a file filled with editing commands (one command per line) to perform a number of operations at one time instead of doing them individually from the command line. sed 's/Nancy/Nanci/' originalfilename >newfilename replaces every occurrence of "Nancy" with "Nanci."
3357sed -n '/there were no credible/,/transfer assets abroad/p' filename displays only the text of a paragraph beginning with "there were no credible" and ending with "transfer assets abroad."
3358sed -n 56,89p filename displays lines 56 through 89 of the specified file.
3359sed -e 's/J.K.W/James K. Whitworth, Esq./' -e 's/Hillary Stuart/Ms. Mary Edwards' -e s/Johnson, Gabriel, and Hawkins/McPhee, Larkin, Simmons' originalfilename >newfilename allows three substitution commands to occur at the same time.
3360sed -f scriptfilename originalfilename >newfilename treats the scriptfilename file as a script file, running each command against the text in the original file and saving the results to the new file.
3361echo night day night | sed s/night/day/g changes both instances of the term night to day. Without the trailing g flag, only the first instance changes.
3362awk Create reports based on the data you retrieve from files, build databases, or perform mathematical operations against numbers in text files.
3363Be aware of the following patterns and actions:
3364• -f specifies a file containing awk commands to be used.
3365• -F specifies the field delimiter to be used. The default is whitespace.
3366• $# is used to designate fields. For example, $6 is the sixth field in a line.
3367• \t inserts a tab.
3368• \n inserts a newline character
3369• \f inserts a form-feed character
3370• \r inserts a carriage return. awk -F: '{print $1}' /etc/passwd | sort prints a sorted list of the user names in /etc/passwd.
3371ls -l | awk '{print "File name: "$9"\tOwner: "$3"\tModified date and time: "$6"\t"$7"\t"$8}' customizes the ls -l command. From the long listing, it rearranges the ninth field to come first, labels each printed field, omits unwanted fields, and adds a tab between fields.
3372sort Sort each line of text in a file or from a text stream alphabetically. Be aware of the following options:
3373• -b ignores leading blank spaces.
3374• -d uses the first alpha-numeric character and ignores special characters.
3375• -f ignores case.
3376• -M sorts by month.
3377• -n sorts according to the string numeric value.
3378• -r reverses the sort order. ls | sort -r reverses the sort order of files from the ls command.
3379sort -b -d -f myfile sorts each line in myfile and it ignores leading spaces, character case, and special characters.
3380split Split lines of text from a file or a text stream into segments of a specified number of lines. Be aware of the following options:
3381• -l, -number specifies the number of lines per file.
3382• -b splits text into a specified byte size instead of number of lines.
3383• -d uses numeric suffixes rather than alphabetic.
3384• -a specifies the number of characters in the suffix. split -50 -d -a 3 AllNames FiftyNames- splits the AllNames file into individual files containing 50 lines each from the content of the AllNames file. The output is FiftyNames-001, FiftyNames-002, and so on.
3385tr Transpose characters in a text stream. tr only works with character streams. The command uses two character sets.
3386• The first set specifies the characters to be changed.
3387• The second set specifies what they should be changed to.
3388Be aware of the following options:
3389• -c changes all characters except those specified in the first set.
3390• -d deletes characters found in the first set.
3391• -s changes double-characters to single ones.
3392• -t truncates the first set of characters to match the size of the second set. cat myfile | tr a A changes every lower-case a to an upper-case A in the output from myfile.
3393cat myfile | tr abc lmn changes each a to an l, each b to an m, and each c to an n in the output from myfile.
3394cat myfile | tr -d asdf deletes each a, s, d, and ff from the output of myfile.
3395cat myfile | tr -c e f changes every character in the output from my file to an f except for the letter e.
3396cat myfile | tr -s t changes double tt to a single t.
3397cat myfile | tr -t abcde lmn ignores the dd and the e in the first set and only changes a, b, and c. Without the -t option, every c, d, and e, is changed to an n.
3398Use a-m to specify all characters a through m.
3399unexpand Change spaces into a tab. Be aware of the following options:
3400• -a specifies that the command change all occurrences. Without -a, the command only changes leading spaces.
3401• -t specifies the number of spaces to be changed. The default is eight. unexpand -a -t 3,4,5 myfile changes each occurrence of three, four, or five consecutive spaces into a tab using text from myfile.
3402uniq Filter identical lines from a file. The lines must be adjacent. Be aware of the following options:
3403• -d prints only the duplicate lines
3404• -f specifies the number of initial words to skip. Words are delimited by white space.
3405• -s specifies the number of initial characters to skip.
3406• -w specifies the number of characters to compare in each line.
3407• -u leaves out the duplicate lines uniq myfile omits all repeated lines in myfile. It prints the first occurrence only.
3408uniq -d myfile prints only the repeated lines.
3409uniq -u myfile prints only the unique lines.
3410uniq -f 4 myfile skips the first four words when comparing lines.
3411uniq -s 4 myfile skips the first four characters when comparing lines.
3412uniq -w 4 myfile uses only the first four characters when comparing lines.
3413wc Print the number of bytes, characters, lines, or words, or the length of the longest line from the text of a file or text stream. Be aware of the following options:
3414• -c specifies bytes.
3415• -m specifies characters. Character count is often identical to byte count.
3416• -l specifies line count.
3417• -L specifies length of the longest line.
3418• -w specifies word count.
3419When no options are used, the command prints line count, word count, and byte count respectively. wc myfile displays line, word and character count.
3420wc -L myfile displays the length of the longest line in the file.
3421wc -m myfile displays the number of characters in the file.
3422
3423
3424-----
3425A protocol is a set of standards for communication between network hosts. Protocols often provide services, such as e-mail or file transfer. Most protocols are not intended to be used alone, but instead rely on and interact with other dependent or complimentary protocols. A group of protocols that is intended to be used together is called a protocol suite.
3426The Internet Protocol (IP) protocol suite (commonly referred to as TCP/IP) is the most widely used protocol suite today. The following table lists several protocols in the IP protocol suite.
3427Protocol Description
3428Internet Protocol (IP) Internet Protocol (IP) is the main protocol used on the Internet. It is a connectionless protocol that makes routing path decisions. It also handles logical addressing issues through the use of IP addresses.
3429Transmission Control Protocol (TCP) TCP provides services that ensure accurate and timely delivery of network communications between two hosts. TCP is a connection-oriented protocol. TCP provides the following services to ensure message delivery:
3430• Sequencing of data packets
3431• Flow control
3432• Error checking
3433User Datagram Protocol (UDP) UDP is a connectionless protocol. UDP is a host-to-host protocol like TCP. However, it does not include mechanisms for ensuring timely and accurate delivery. Because it has less overhead, it offers fast communications, but at the expense of possible errors or data loss.
3434Internet Control Message Protocol (ICMP) ICMP works closely with IP in providing error and control information, by allowing hosts to exchange packet status information, which helps move the packets through the internetwork. Two common management utilities, ping and traceroute, use ICMP messages to check network connectivity. ICMP also works with IP to send notices when destinations are unreachable, when devices' buffers overflow, the route and hops packets take through the network, and whether devices can communicate across the network.
3435Internet Group Membership Protocol (IGMP) IGMP is a protocol for defining host groups. All group members can receive broadcast messages intended for the group (called multicasts). Multicast groups can be composed of devices within the same network or across networks (connected with a router).
3436HyperText Transfer Protocol (HTTP) HTTP is used by Web browsers and Web servers to exchange files (such as Web pages) through the World Wide Web and intranets. HTTP can be described as an information requesting and responding protocol. It is typically used to request and send Web documents, but is also used as the protocol for communication between agents using different IP protocols.
3437HTTP over SSL (HTTPS) HTTPS is a secure form of HTTP that uses SSL to encrypt data before it is transmitted.
3438Secure Sockets Layer (SSL) SSL secures messages being transmitted on the Internet. It uses RSA for authentication and encryption. Web browsers use SSL (Secure Sockets Layer) to ensure safe Web transactions. URLs that begin with https:// trigger your Web browser to use SSL.
3439Transport Layer Security (TLS) TLS ensures that messages being transmitted on the Internet are private and tamper proof. TLS is implemented through two protocols:
3440• TLS Record--Can provide connection security with encryption (with DES for example).
3441• TLS Handshake--Provides mutual authentication and choice of encryption method.
3442TLS and SSL are similar but not interoperable.
3443File Transfer Protocol (FTP) FTP provides a generic method of transferring files. It can include file security through usernames and passwords, and it allows file transfer between dissimilar computer systems. FTP can transfer both binary and text files, including HTML, to another host. FTP URLs are preceded by ftp:// followed by the DNS name of the FTP server. To log in to an FTP server, use: ftp://username@servername.
3444Trivial File Transfer Protocol (TFTP) TFTP is similar to FTP. It lets you transfer files between a host and an FTP server. However, it provides no user authentication and no error detection. TFTP is often used when transferring files such as video, audio, or images. Because it does not perform error detection, TFTP is faster than FTP, but might be subject to file errors.
3445Secure File Transfer Protocol (SFTP) SFTP is a file transfer protocol that uses Secure Shell (SSH) to secure data transfers. SSH ensures that SFTP transmissions use encrypted commands and data which prevent data from being transmitted over the network in clear text.
3446Secure Copy (SCP) SCP is associated with Unix/Linux networks and used to transfer files between systems. Like SFTP, SCP relies on SSH to ensure that data and passwords are not transmitted over the network in clear text.
3447Simple Mail Transfer Protocol (SMTP) SMTP is used to route electronic mail through the internetwork. SMTP is used:
3448• Between mail servers for sending and relaying mail.
3449• By all e-mail clients to send mail.
3450• By some e-mail client programs, such as Microsoft Outlook, for receiving mail from an Exchange server.
3451Internet Message Access Protocol (IMAP) IMAP is an e-mail retrieval protocol designed to enable users to access their e-mail from various locations without the need to transfer messages or files back and forth between computers. Messages remain on the remote mail server and are not automatically downloaded to a client system. Note: An e-mail client that uses IMAP for receiving mail uses SMTP for sending mail.
3452Post Office Protocol 3 (POP3) POP3 is part of the TCP/IP protocol suite and used to retrieve e-mail from a remote server to a local client over a TCP/IP connection. With POP3, e-mail messages are downloaded to the client. Note: An e-mail client that uses POP3 for receiving mail uses SMTP for sending mail.
3453Dynamic Host Configuration Protocol (DHCP) DHCP is a method for automatically assigning addresses and other configuration parameters to network hosts. Using a DHCP server, hosts receive configuration information at startup, reducing the amount of manual configuration required on each host.
3454Domain Name System (DNS) DNS is a system that is distributed throughout the internetwork to provide address/name resolution. For example, the name www.mydomain.com would be identified with a specific IP address.
3455Network Time Protocol (NTP) NTP is used to communicate time synchronization information between systems on a network.
3456Network News Transport Protocol (NNTP) NNTP is the most widely-used protocol that manages notes posted on Usenet Newsgroups.
3457Lightweight Directory Access Protocol (LDAP) LDAP is used to allow searching and updating of a directory service. The LDAP directory service follows a client/server model. One or more LDAP servers contain the directory data, the LDAP client connects to an LDAP Server to make a directory service request.
3458Simple Network Management Protocol (SNMP) SNMP is a protocol designed for managing complex networks. SNMP lets network hosts exchange configuration and status information. This information can be gathered by management software and used to monitor and manage the network.
3459Remote Terminal Emulation (Telnet) Telnet allows an attached computer to act as a dumb terminal, with data processing taking place on the TCP/IP host computer. It is still widely used to provide connectivity between dissimilar systems. Telnet can also be used to test a service by the use of HTTP commands.
3460Secure Shell (SSH) SSH allows for secure interactive control of remote systems. SSH is a secure and acceptable alternative to Telnet. SSH uses public key cryptography for both connection and authentication.
3461
3462-----
3463Network ports are logical connections, provided by the TCP or UDP protocols. The IP protocol stack uses port numbers to determine what protocol incoming traffic should be directed to. Some characteristics of ports are listed below:
3464• Ports allow a single host with a single IP address to run network services. Each port number identifies a distinct service.
3465• Each host can have over 65,000 ports per IP address.
3466• Port use is regulated by the Internet Corporation for Assigning Names and Numbers (ICANN).
3467 ICANN specifies three categories for ports.
3468• Well known ports range from 0 to 1023 and are assigned to common protocols and services.
3469• Registered ports range from 1024 to 49151 and are assigned by ICANN to a specific service.
3470• Dynamic (also called private or high) ports range from 49,152 to 65,535 and can be used by any service on an ad hoc basis. Ports are assigned when a session is established, and released when the session ends.
3471The following table lists the well known ports that correspond to common Internet services.
3472Port(s) Service
347320 TCP
347421 TCP File Transfer Protocol (FTP)
347522 TCP and UDP Secure Shell (SSH)
347623 TCP Telnet
347725 TCP Simple Mail Transfer Protocol (SMTP)
347853 TCP and UDP Domain Name Server (DNS)
347967 UDP
348068 UDP Dynamic Host Configuration Protocol (DHCP)
348169 UDP Trivial File Transfer Protocol (TFTP)
348280 TCP HyperText Transfer Protocol (HTTP)
3483110 TCP Post Office Protocol (POP3)
3484119 TCP Network News Transport Protocol (NNTP)
3485123 UDP Network Time Protocol (NTP)
3486137 UDP
3487138 UDP
3488139 TCP NetBIOS
3489143 TCP and UDP Internet Message Access Protocol (IMAP4)
3490161 TCP and UDP
3491162 TCP and UDP Simple Network Management Protocol (SNMP)
3492389 TCP and UDP Lightweight Directory Access Protocol
3493443 TCP and UDP HTTP with Secure Sockets Layer (SSL)
3494Be aware of the following:
3495• /etc/services lists all network services on the Linux system, including the port assigned to the service. Most applications reference /etc/services for which service is using a specific TCP/UDP port.
3496• To protect a server, ensure that only the necessary ports are opened. For example, if the server is only being used for e-mail, then shut down ports that correspond to FTP, DNS, and HTTP (among others).
3497
3498-----
3499The following table lists several options for assigning IP addresses.
3500Method Uses
3501Static (manual) assignment Using static addressing, IP configuration information must be manually configured on each host. Use static addressing:
3502• On networks with a very small number of hosts.
3503• On networks that do not change often or that will not grow.
3504• To permanently assign IP addresses to hosts that must have always have the same address (such as printers, servers, or routers).
3505• For hosts that cannot accept an IP address from DHCP.
3506• To reduce DHCP-related traffic.
3507Static addressing is very susceptible to configuration errors and duplicate IP address configuration errors (two hosts that have been assigned the same IP address). Static addressing also disables both APIPA and DHCP capabilities on the host.
3508Dynamic Host Configuration Protocol (DHCP) assignment A DHCP server is a special server configured to pass out IP address and other IP configuration information to network clients.
3509• When a client boots, it contacts the DHCP server for IP configuration information.
3510• The DHCP server is configured with a range of IP addresses it can assign to hosts (Microsoft calls these ranges scopes).
3511• The DHCP server can also be configured to pass out other IP configuration such as the default gateway and DNS server addresses.
3512• The DHCP server ensures that each client has a unique IP address.
3513• The DHCP server can be configured to not assign specific addresses in the range, or to assign a specific address to a specific host.
3514• The DHCP server assigns the IP address and other information to the client. The assignment is called a lease, and includes a lease time that identifies how long the client can use the IP address.
3515• Periodically and when the client reboots, it contacts the DHCP server to renew the lease on the IP address.
3516• The DHCP lease process uses frame-level broadcasts. For this reason, DHCP requests typically do not pass through routers to other subnets. To enable DHCP across subnets:
3517 Enable BootP (DHCP broadcast) requests through the router.
3518 Configure a computer for BootP forwarding to request IP information on behalf of other clients.
3519• You can configure a DHCP server to deliver the same address to a specific host each time it requests an address. Microsoft calls this configuration a reservation.
3520• DHCP is a TCP/IP protocol. Any client configured to use DHCP can get an IP address from any server configured for DHCP, regardless of operating system.
3521Use DHCP for small, medium, or large networks. DHCP requires a DHCP server and minimal configuration.
3522
3523-----
3524Linux uses the following files for network configuration:
3525File or Directory Description
3526/etc/init.d/network
3527/etc/rc.d/init.d/network This script file loads and unloads networking services.
3528/etc/sysconfig/network-scripts This is the network configuration file directory, which contains individual device configuration files named ifcfg-device_name (e.g., ifcfg-eth0). Edit the files in this directory to modify the following settings:
3529• Boot protocol (static, DHCP, or BootP)
3530• Autoconfiguration information
3531• IP Address, mask, and default router (for static configurations)
3532/var/lib/dhcpcd/dhcpclientn
3533/var/lib/dhcpcd/dhclient.leases Depending on the distribution's daemon, one of these files exists to manage DHCP address information.
3534The table below shows common commands for configuring network settings.
3535Use... To... Example
3536service network Start, restart, or stop networking services. service network start starts the network service.
3537service network restart restarts the network service.
3538ifconfig interface parameters Create a static IP configuration for the specified interface. Common ifconfig parameters include:
3539• address sets the IP address
3540• netmask addr sets the subnet mask
3541• up activates the interface
3542• down deactivates the interface
3543• broadcast sets the broadcast address. ifconfig eth0 192.168.1.1 netmask addr 255.255.255.0 configures a static IP address and subnet mask for eth0.
3544ifconfig eth0 up starts the eth0 device.
3545ifup Start a network interface. ifup eth1 starts the eth1 network device.
3546ifdown Stop a network interface. ifdown eth1 stops the eth1 network device.
3547ifconfig
3548ifconfig interface View network interface information. Use the -a option to display the status of all interfaces. ifconfig -a displays the status of all interfaces, even those that are down.
3549
3550-----
3551A router is a device that sends packets from one network to another network. Routers receive packets, read their headers to find addressing information, and send them on to their correct destination on the network or Internet. Routers can forward packets through an internetwork by maintaining routing information in a database called a routing table. Every Linux system maintains a route table in RAM that it uses to determine where to send data on a network. The routing table typically contains the following information:
3552• The address of a known network
3553• The interface or next hop router used to reach the destination network
3554• A cost value (also called a metric) that identifies the desirability of the route to the destination network (using distance, delay, or cost)
3555• A timeout value that identifies when the route expires
3556The default router (also known as gateway router and default gateway router) is a device that performs the act of routing, and enables a host to communicate with other hosts on other networks through the process of routing. The default router IP address:
3557• Must be configured on each host to allow inter-network communication. Without the default router, hosts will only be able to communicate with devices within the same subnet.
3558• Must be on the same subnet as the host computer. Routers have multiple network interface cards attached to multiple networks. When configuring the default router, choose the address on the local subnet.
3559• Is stored in the /etc/sysconfig/network/routes file. Changes to the /etc/sysconfig/network/routes file will not take effect until the network interface is restarted.
3560The table below shows common commands for configuring routing:
3561Use... To... Example
3562route add Add a static route in the routing table.
3563• default gw creates a route for the default router.
3564• -net specifies a network address.
3565• -host specifies a single host on the network.
3566• reject installs a blocking route. route add default gw 192.168.1.1 adds the default router 192.168.1.1.
3567route add -net 15.0.0.0 netmask 255.0.0.0 dev eth0 adds a route to the 15.0.0.0/8 network.
3568route add -host 15.0.0.1 gw 10.0.20.1 adds a static route to the 15.0.0.1 host.
3569route add -net 10.0.0.0 netmask 255.0.0.0 reject installs a rejecting route for the 10.0.0.0/8 network.
3570route del Delete a static route in the routing table. route del -net 172.18.0.0 netmask 255.255.0.0 deletes a route to the 17.18.0.0/16 network
3571route View the routing table and the default gateway address.
3572
3573-----
3574Domain Name Service (DNS) resolves IP addresses to domain names that people can remember. The following table lists the files that administrators use to configure DNS settings on Linux.
3575Use... To... Examples
3576/etc/hosts Provide the system with domain names for IP addresses. The line contains the IP address, fully qualified domain name and aliases for the domain name. This file:
3577• Provides name resolution when DNS is not running (for example during system startup before DNS has started)
3578• Operates with the Network Information Service (NIS) to identify hosts.
3579• Provides information for small networks without a DNS server.
3580Domain names include alphanumeric characters, periods (.), and dashes (-), and must begin and end with alphanumeric characters. 127.0.0.1 fs4.mydomain.com localhost specifies that the IP address 127.0.01 is assigned to fs4.mycomain.com and that the term localhost can be used as an alias to specify the computer.
3581/etc/resolv.conf Provide the system with the name of the network DNS server. Up to three servers can be listed, and the servers are accessed in the order specified. The file also has settings that append fully qualified domain names to computer names nameserver 192.168.1.3 specifies 192.168.1.3 as the IP address of the DNS server.
3582search mydomain.com appends the domain name to computer names that do not have a domain name. For example, linux1 becomes linux1.mydomain.com.
3583/etc/nsswitch.conf Specify whether the computer's host file or the DNS server takes precedence if there is a DNS resolution conflict between the two. hosts: files dns specifies that the hosts file takes precedence over information obtained from a DNS server.
3584/etc/HOSTNAME
3585/etc/sysconfig/network Define the host and domain names. HOSTNAME=fs1 identifies the hostname as fs1.
3586host Find the IP address for a domain name. host www.testout.com displays the IP address for www.testout.com.
3587hostname Display or set the name of the local host for the current session. hostname ls4 sets the hostname for the current session to ls4.
3588
3589-----
3590Good troubleshooting is a process that combines knowledge, experience, and intuition. The following process has proven effective in a variety of situations:
35911. Identify the symptoms and potential causes. Ask the user to describe the problem, check for error messages, and recreate the problem. Identify the affected area and determine how large the problem is. For example, fixes for one client workstation would likely be very different than fixes for an entire network segment.
35922. Establish what has changed. Most often, problems are caused by new hardware or software or changes to the configuration. If necessary, ask questions to discover what might have changed that could have caused the problem.
35933. Create a hypothesis. Review the list of potential causes and select the most probable cause. Look for common errors or solutions that can be tried quickly.
35944. Create an action plan and account for side effects of the proposed plan. The plan might include purchases for hardware or equipment that need approval before proceeding. In addition, the plan might involve taking some services offline for a period of time. Identifying the effects ahead of time helps put measures into place to eliminate or reduce any potential negative consequences.
35955. Implement the fix to the problem, and make sure that the solution has fully fixed the problem and has not caused any other problems. If necessary, implement additional steps to correct the problem if the first solution did not work.
35966. Ensure user satisfaction. This may include educating the user, such as explaining what the problem was, the solution, and how to avoid this problem in the future.
35977. Document the solution and process. In the future, check the documentation to see what has changed or to help remember the solution to common problems.
3598Remember, however, that troubleshooting is a process of both deduction and induction. Experience will show when deviating from this process can save both time and effort.
3599
3600
3601-----
3602When troubleshooting network communications, consider the following:
3603Problem Considerations
3604Physical issues The best way to verify if a connection is valid is to check the link light on both the workstation and the hub. If the link light is unlit, try the following:
3605• Swap the cables. This will help determine whether the cable is the problem.
3606• Try using a different switch or hub port for the connection.
3607• Make sure that the card is properly seated.
3608• Use loopback plugs to test network cards and cable testing devices to test network cables.
3609Interference Interference is caused by electromagnetic fields or radio frequency interference.
3610• For wired cables, make sure wires are not routed next to motors or fluorescent lights that can cause interference.
3611• For wireless devices, make sure there are not other devices in the area transmitting on the same frequency and channel (such as microwaves or cordless phones).
3612• Check to make sure that the cable is not kinked or worn. Cables should be routed through walls or ceilings, not strung across the floor. If a cable must run across the floor, encase the cable to prevent wear and secure the cable in place to prevent tripping accidents. Worn cables might introduce some interference, or simply prevent signals from being sent properly.
3613Network issues If the device and connection to the device appear to be working, check the following:
3614• Check firewalls on both end devices to see if communications are being blocked by a host-based firewall.
3615• Check the service on the target device to make sure that it is running and is properly configured.
3616The following table compares some of the tools for troubleshooting network communication problems:
3617Use... To...
3618ping Verify connectivity between hosts within the network.
3619• Ping the special loopback address of 127.0.0.1. This tests the TCP/IP configuration of the local host. If successful, TCP/IP is correctly configured.
3620• Ping a destination with IP address. If there is no response, try to ping any other host.
3621 If your computer cannot communicate with any other computer, check the network cable, the network interface card, or the IP address configuration on your computer.
3622 If your computer can communicate with computers on the local network, but can't communicate with remote computers (such as the Internet), verify the default gateway configuration on your computer.
3623 If all computers on the local network cannot communicate with any remote computer, troubleshoot the router's connection to the remote network.
3624• Ping by a DNS name. If a ping by IP address works, but a ping by DNS name fails, then there is probably a DNS problem.
3625• Use the -c option to specify how many ICMP echo requests to send to the destination.
3626netstat Display a list of network connections (i.e., sockets), the routing table, and information about the network interface. A socket is an endpoint of a bidirectional communication flow across a computer network. Use the following options for additional information:
3627• -a lists both listening and non-listening ports.
3628• -i displays a table of all network interfaces.
3629• -l lists listening sockets.
3630• -s displays statistics for each protocol.
3631• -r displays the routing table, which includes the IP address of the default gateway.
3632traceroute
3633tracepath Test connectivity between devices, show the path between the two devices. traceroute:
3634• Can help track down which router (known as a hop) in the route is not working correctly.
3635• Displays the Round Trip Time (RTT) for each hop. The RTT is the time difference between when the probe was sent from traceroute and the time the response arrived for each packet.
3636tracepath is similar to traceroute, but does not require super user privileges.
3637nslookup Send a name resolution request. To use nslookup:
36381. Enter nslookup at the shell prompt.
36392. Enter the hostname or IP address, such as 192.168.1.1.
36403. The DNS server should respond with the requested mapping.
36414. Enter exit when finished
3642dig Send a name resolution request and receive extensive information about the hostname or IP address. Consider the following options:
3643• a resolves a record information
3644• ptr resolves a ptr record
3645• cname resolves cname record information
3646• p queries a specific port on the host
3647• in resolves Internet record information
3648• mx resolves mx record information
3649• soa resolves start of authority information
3650
3651-----
3652The root user account is the Linux system superuser, and can perform any task. Some utilities do not work if the administrator is not logged in as the root user. The root account is created during the installation process, and it receives the account number 0 (zero); in contrast, normal (standard) user accounts receive ascending numbers beginning at 500 or 1000 depending on the distribution.
3653To protect the root user account, use the following guidelines:
3654• When performing tasks that require the root user account, use the su command to switch to the root user and execute the command; then use the exit command to revert back to the regular user account.
3655• As a general rule, create a user account that gives sufficient permissions to perform most of the daily tasks. Use this account instead of the root user account when logging in to the system.
3656To give standard user accounts the permissions to execute commands as the root user, use the sudo command coupled with the /etc/sudoers file. Be aware the following facts about the sudo command and the /etc/sudoers file:
3657• When users need to execute the command, they use the sudo command followed by the command they want to execute. Users are prompted for a password to execute the command. This is the current user account password, not the root account password.
3658• Users and the commands they are entitled to execute are specified in the /etc/sudoers file.
3659• The /etc/sudoers file can only be edited using the visudo command.
3660• sudo logs information about the users and the commands they run as well as failed attempts to use sudo in the /var/log/security log.
3661The following table describes the sections used to configure the /etc/sudoers file:
3662Section Description Examples
3663User_Alias User_Alias specifies a set of users who are allowed to execute a specific set of commands using the sudo command. User_Alias INSTALLERS = jsmith, psimms adds the users jsmith and psimms to the INSTALLERS alias. Permissions assigned to this alias are grated to these users.
3664Cmnd_Alias Cmnd_Alias specifies a set of commands that users can execute using the sudo command. Cmnd_Alias INSTALL = /bin/rpm, /usr/bin/up2date, /user/bin/yum assigns the rpm, up2date, and yum commands to the Install alias. Users granted access to the Install alias can execute these commands.
3665Host_Alias Host_Alias specifies a list of computers on which sudo users can perform commands. Host_Alias FILESERVERS = fs1, fs2, fs3 adds the three computers to the alias. Users assigned to this alias can run sudo commands on the three computers.
3666Host_Alias EVERYWHERE = *.mydomain.com creates an alias that grants permissions for all computers on the mydomain network.
3667Runas_Alias Runas_Alias specifies a list of user names that are used when running commands. Usually this is just root. Runas_Alias DATABASE = oracle, sybase specifies that sudo commands are run as the oracle or sybase user.
3668Entries in the /etc/sudoers file use the following syntax:
3669User Host = Runas_User Authentication Command(s)
3670The following table describes the entry options in the /etc/sudoers file:
3671User Host Runas_User Authentication
3672The user is the user identified as one of the following:
3673• Username as found in /etc/passwd
3674• Group name as found in /etc/group
3675• User_Alias as found in /etc/sudoers The host is the system where the commands may run.
3676It is identified through the Host_Alias entry in /etc/sudoers.
3677 The Runas_User is user or group to run the
3678If the Runas_User is omitted, the default is root. The authentication parameter requires a password before using the command. Option are:
3679• PASSWD: requires the user to enter their password as found in the /etc/shadow file for users or /etc/gshadow for groups.
3680• NOPASSWD: no password is required.
3681If the authentication is omitted, the default is PASSWD:.
3682The following are examples of entries in the /etc/sudoers file:
3683Example Description
3684root ALL= (ALL) ALL Allows root, on any computer, as any user, to run any program.
3685%admin ALL = (ALL) ALL Allows the admin group, on any computer, as any user, to run any program.
3686INSTALLERS EVERYWHERE = NOPASSWD: INSTALL Allows the users specified in the INSTALLERS user alias, on the computers specified in the EVERYWHERE host alias, to perform commands specified in the INSTALL command alias. The NOPASSWD: tag allows them to run commands without typing their password.
3687treid ALL= /sbin, /usr/sbin Allows user treid, on any computer, to run any command in the /sbin and /usr/sbin directories.
3688#Defaults targetpw Comments the line out so the root password is not required for the sudo commands.
3689#ALL ALL = (ALL) ALL Comments the line out so that all users do not have permissions for all sudo commands.
3690The following table describes the commands for using the superuser account and switching users:
3691Use... To... Examples
3692su Switch to the root user account. Be aware of the following su options:
3693• su -l user_name switches to the specified user in a login shell.
3694• su user_name (without the dash, but with the username) switches to the user.
3695• su - user_name (with the dash and username) switches to the user and loads the user's environmental variables.
3696• su - (with the dash, but no username) switches to the root user and loads the root user's environmental variables.
3697• su (no dash or username) switches to the root user and but does not load the root user's environmental variables.
3698• -c "command" executes a single command, logging in as the root user.
3699 The command is enclosed in either single or double quotation marks.
3700 Include -l user to execute the command as another user.
3701su requires the password of the user except when switching from root to a normal user. su -l jsomes switches to the jsomes user account with jsomes environment variables.
3702su - switches to the root account using the correct environment variables.
3703su -c "ls /home/rgurate" switches to the root user and executes the ls command on the user rgurate's home directory.
3704exit Return to account from which the su command was typed. When no su command has been typed, exit terminates the shell. When using a computer that uses a shell exclusively, exit logs the user out.
3705[root@ls4 ~]# exit
3706logout
3707[jsomes@ls4 ~]$
3708gnomesu Open graphical applications as the root user.
3709This application only works on the GNOME desktop manager. The KDE desktop manager has a similar utility named kdesu. gnomesu nautilus opens the nautilus file browser as the root user account.
3710logout Log out of the system, while leaving the system powered on. Newer distributions use exit exclusively. logout logs the user out of the shell. It is identical to exit.
3711sudo Execute a command as the root user. To use this command, first type sudo, than type the command as you normally would. sudo yum install python.i686 installs the python package as the root user.
3712visudo Open the /etc/sudoers file for editing. The command opens the VI editor, to edit the file, but checks the file for errors when exiting from VI.
3713
3714-----
3715When considering user security, keep in mind the following:
3716• Users should be trained to use secure passwords. Secure passwords use numbers and letters, and are more than 7 characters in length.
3717• Passwords should expire periodically, but not too often.
3718• Administrators can limit the resources that user can access.
3719The following table describes commands used to promote user security and restrictions:
3720Use... To... Examples
3721chage Set user passwords to expire. Be aware of the following options:
3722• -M sets the maximum number of days before the password expires.
3723• -W sets the number of days before the password expires that a warning message displays.
3724• -m sets the minimum number of days that must pass after a password has been changed before a user can change the password again.
3725Look in the /etc/shadow file to see current limits for users. chage -M 60 -W 10 jsmith sets the password for jsmith to expire after 60 days and gives a warning 10 days before it expires.
3726ulimit Limit computer resources used for applications launched from the shell. Limits can be hard of soft limits. Soft limits can be temporarily exceeded up to the hard limit setting. Users can modify soft limits, but only root can modify hard limits.
3727Options include:
3728• -c limits the size of a core dump file. The value is in blocks.
3729• -f limits the file size of files created using the shell session. The value is in blocks.
3730• -n limits the maximum number of open files.
3731• -t limits the amount of CPU time a process can use. This is set in seconds.
3732• -u limits the number of concurrent processes a user can run.
3733• -d limits the maximum amount of memory a process can use. The value is in kilobytes.
3734• -H sets a hard resource limit.
3735• -S sets a soft resource limit.
3736• -a displays current limits. The default shows soft limits. ulimit -H -f 1024 uses a hard limit to limit the size of files to 1020 KB.
3737ulimit -H -a shows current hard limits.
3738ulimit -a shows the current soft limits.
3739ulimit -S -u 10 sets a soft limit that limits the number of processes that a single user can use to 10.
3740ulimit -t 600 limits CPU time for a process to 10 minutes. This sets both hard and soft limits.
3741ulimit -d unlimited removes all restrictions for process memory usage.
3742Use the /etc/security/limits.conf file to limit resource use for all applications. This file is from the pam_limits module of the Plugable Authentication Modules (PAM) module set. Entries in /etc/security/limits.conf use the following syntax:
3743Entity Type Limit Value
3744The following table describes the entry options in the /etc/security/limits.conf file:
3745Entity Type Limits Value
3746When specifying the Entity:
3747• Specify a single user with a user name.
3748• Use an ampersand (@) to specify a group.
3749• Use an asterisk (*) as a wildcard. For the Type:
3750• Use hard to set a limit that cannot be exceeded.
3751• Use soft to set a limit that can be exceeded temporarily.
3752 Limits include:
3753• core limits the size of core dump files. The value uses kilobytes.
3754• data limits the amount of ram an application can use. The value uses kilobytes.
3755• fsize limits maximum file size. The value uses kilobytes.
3756• nofile limits the number of concurrently open data files.
3757• cpu limits the amount of CPU time a process can use. The value uses minutes.
3758• nproc limits the number of concurrent processes a user can have.
3759• maxlogins limits the number of concurrent logins.
3760• priority sets process priority limits. The value range is from -20 (highest priority) to 19 (lowest priority) with 0 being the default.
3761• rss limits the total amount of memory a user can use. The value uses kilobytes. Values include integers, such as 1, 5, or 3000.
3762The following are examples of entries in the /etc/security/limits.conf file:
3763Example Description
3764jsmith hard fsize 1024 Limits the maximum file size that jsmith can create to 1024 KB.
3765@guests hard maxlogins 3 Limits the number of concurrent logins from the guest group to three.
3766* hard maxlogins 1 Limits concurrent logins from the same user to one.
3767* soft cpu 10 Sets a soft limit of 10 minutes on the amount of CPU time any single process for any user can take.
3768rss hard rss 5000 Limits the total amount of memory available to a single user to 5 MB
3769
3770-----
3771The following table describes the general procedures for increasing network security of a Linux system:
3772Security Task Procedure
3773Remove unneeded software Unneeded software takes disk space and could introduce security flaws. To remove unneeded software:
37741. Run one of the following commands:
3775o Use yum list installed to see installed RPM packages on the computer.
3776o Use dpkg –get-selections to see installed Debian packages on the computer.
37772. Research the function of any unrecognized package to determine whether it is necessary.
37783. Use yum, rpm, or dpkg to uninstall unneeded packages.
3779Check for unneeded network services Unneeded network services waste the computer's resources and might provide attackers with an entry point for an attack. To remove unneeded network services:
37801. Search within the /etc/init.d or /etc/rc.d/init.d directories for unusual or unrecognized scripts.
37812. Use the man command and the Internet to research the scripts' functions and determine whether they can be safely removed or disabled.
37823. Use chkconfig, insserv, or init to disable the script, or use yum, rpm, or dpkg remove the script package entirely.
3783Locate open ports Open ports can provide information about what operating system a computer uses, and might provide entry points, or information about ways to formulate an attack. To locate open ports:
37841. Install the nmap utility (if not already installed).
37852. Use one of the following commands to scan for open ports:
3786o nmap -sT scans for TCP ports
3787o nmap -sU scan for UDP ports
37883. From the results of the scan, determine which ports to close and which services use the ports.
37894. Disable the services using ports.
3790Check network connections Open network connections (i.e., open sockets) on a computer also create a security risk. A socket is an endpoint of a bidirectional communication flow across a computer network. Use the following netstat options to identify the open network connections on the Linux system:
3791• -a lists both listening and non-listening sockets.
3792• -l lists listening sockets.
3793• -s displays statistics for each protocol.
3794• -i displays a table of all network interfaces.
3795
3796-----
3797File auditing involves looking for files that pose a security risk to the computer, including:
3798• Files that have the SUID (Set User ID) permission. With the SUID permission, files will run with the owner permissions, not with the permissions of the user who runs the program.
3799• Files that have the write and execute permissions for others (everyone on the Linux system who is not a user or group owner of the file). If the file is writable by others, anyone can replace the file with a malicious script to create a security risk.
3800The following table lists several file auditing commands:
3801Use... To... Examples
3802find / type f -perm Audit for files that pose a security risk. Be aware of the following options:
3803• -o=x audits for the execute permission for others.
3804• -o=w audits for the write permission for others.
3805• -g=x audits for the execute permissions for group owners.
3806• -u=x audits for the execute permission for the owner.
3807• -u=S audits for the SUID bit.
3808Include the -ls option to display the results with the long listing. find / -type f -perm -o=x -ls
3809find / -type f -perm -g=x -ls
3810find / -type f -perm -u=x,o=w -ls
3811crontab Schedule the auditing task to run on a regular basis.
3812
3813-----
3814Administrators can prevent (i.e., block) users from logging in to a Linux computer while resolving serious issues, and can display a message to users attempting to log in. Login blocking is enabled using the Pluggable Authentication Modules (PAM) module configured in the /etc/pam.d/login file. PAM:
3815• Is a set of modules that enables various authentication systems on a Linux computer.
3816• Can employ modules concurrently. For example, one PAM module can be used to enable biometric logins while another enables standard user/password authentication.
3817The following list describes the tasks necessary to configure login blocking:
3818• Force all users to log out of the system:
38191. Log in directly as the root user.
38202. Use the w command to view all active user accounts.
38213. Use pkill -KILL -u user to force the user to log out for each active user.
3822• Disable the ability to login to the system:
38231. Create the /etc/nologin file.
38242. Add a message to the file to display to users when they attempt to log in.
3825Rename or delete the file to re-enable logins.
3826• Add the following line to the /etc/pam.d/login file to configure the PAM module to verify whether the file /etc/nologin exists:
3827
3828 auth requisite pam_nologin.so
3829If /etc/nologin does exist and the user is not root, authentication fails.
3830
3831-----
3832Xinetd is a super daemon that manages many Internet and network services. Xinetd:
3833• Starts and stops daemons as necessary to provide port security and conserve resources.
3834• Acts based on requests from client computers.
3835• Acts as an intermediary between the user requesting a network service and the actual daemon that performs the service.
3836• Can be configured to grant and deny access to specific services, based on the IP address of the computer making the request. This is known as a TCP wrapper.
3837• Increases server latency, and might not be optimal for servers with very high request volumes.
3838• Must be restarted after configuration changes.
3839Use the following files to configure the xinetd super daemon:
3840File Description
3841/etc/xinetd.conf The /etc/xinetd.conf file configures the xinetd daemon. The default configuration for this file rarely needs adjustment; however, be aware of the following parameters:
3842• instances sets the maximum number of concurrent requests xinetd can support.
3843• log_type configures the location to where xinetd writes logs. The default is the /var/log/secure file.
3844• log_on_success determines whether successful connections are logged.
3845• log_on_failure determines whether failed or disallowed connections are logged.
3846• cps limits the number of connections per second.
3847• includedir/etc/xinetd.d/ sets options for the configuration files in the /etc/xinetd.d/ directory.
3848/etc/xinetd.d The /etc/xinetd.d directory contains a file for each network daemon managed by xinetd. The configuration file determines how xinetd will enable the network daemon. Be aware of the following parameters:
3849• disable enables and disables the daemon.
3850• service names the daemon. The name often comes from the /etc/services file.
3851• socket_type determines whether the socket type is a stream.
3852• wait specifies whether the daemon is single-threaded or multi-threaded Yes specifies single-threaded.
3853• user determines the user under which the daemon runs.
3854• server lists the path to the executable.
3855• log_on_failure defines logging specifications for failed logins.
3856Each enabled daemon requires an exception in the host-based firewall to open the port for that daemon.
3857TCP wrappers (tcpd) use the IP addresses of incoming network packets to allow or deny access to computers or daemons. Xinetd can use TCP wrappers to restrict access to enabled daemons. To use TCP wrappers with xinetd, consider the following steps:
3858Step Description Examples
3859Install/Verify the TCP wrappers package is installed. Ensure that the TCP wrappers package (tcpd) is installed with the rpm -q or dpkg -d commands. rpm -q tcpd uses the rpm utility to determine whether tcpd is installed.
3860dpkg -s tcpd performs the identical function on Debian distributions.
3861Edit the daemon files in /etc/xinetd.d. Edit and save the /etc/xinetd.d daemon file(s) for the daemon(s) as follows:
3862• Comment out the existing server= line with the number/pound (#) symbol.
3863• Add the line server = /usr/sbin/tcpd to send requests through tcpd so it can grant or deny access.
3864• Add the line server_args = daemonpath to provide the tcpd daemon with the location of the path to the executable file of the service.
3865• Set the disable line to no. # server = /usr/bin/rsync tells the computer to treat this line as a comment and ignore it.
3866server = /usr/sbin/tcpd replaces the direct path to the executable with the path to tcpd so the request can be filtered.
3867server_args = /usr/bin/rsync specifies the executable to be started if access is granted.
3868disable = no enables the service through xinetd.d.
3869Restart xinetd. Restart the xinetd to enforce the changes made to the /etc/xinetd.d daemon file(s). service inetd restart restarts the daemon on computers that use the path specified. Some distributions place the daemon in another location.
3870Modify tcpd control files. Modify the following tcpd control files to determine which computers can access the services:
3871• /etc/hosts.deny denies services to the specified host(s) or subnets.
3872• /etc/hosts.allow permits services to the specified host(s) or subnets.
3873Be aware of the following details:
3874• The /etc/hosts.allow file is read first and applied before /etc/hosts.deny.
3875• In each of these files, if tcpd finds a matching rule the search is stopped and all remaining rules are ignored.
3876Both files have the following syntax:
3877• Use service: ipaddresses to specify the host(s).
3878• Use service: subnet to specify a subnet. ALL:192.168.0.0/255.255.255.0 specifies all computers on the 192.168.*.* network. ALL specifies all services. The subnet mask follows the network.
3879ftp:192.168.10.10 specifies ftp access for only the computer with the IP address of 192.168.10.10
3880sshd:192.168. specifies sshd access for all computers on the 192.168.*.* network.
3881sshd:ALL specifies sshd access for all computers.
3882sshd:ALL EXCEPT fs1 specifies sshd access for all computers but fs1.
3883Confirm TCP wrapper configuration Use tcpdchk to test and display any potential or real problems with the TCP wrapper configuration. tcpdchk compares the /etc/hosts.deny and /etc/hosts.allow files against the configuration files.
3884
3885-----
3886Inetd is a super daemon that manages many Internet and network services (similar to xinetd). Inetd performs the same functions as xinetd; however, xinetd has some security features not found in inetd.
3887Inetd uses /etc/inetd.conf as the configuration file for every daemon. Each entry in the file represents how inetd manages the daemon. Entries in /etc/inetd.conf use the following syntax:
3888Daemon Socket Protocol Flag User Executable Arguments
3889The following table describes the configuration parameters for each entry within the /etc/inetd.conf configuration file.
3890Parameter Description
3891Daemon Identifies the daemon being controlled. The name should be as it appears in the /etc/services file
3892Socket Designates the type of connection to expect for the daemon. Socket options include:
3893• stream specifies a reliable connection.
3894• dgram specifies a less reliable connection, but uses fewer resources.
3895• raw specifies a low-level network connection.
3896Protocol Designates whether the protocol is Transmission Control Protocol (TCP) or User Datagram Protocol (UDP).
3897Flag Specifies how the server processes the packets. Use:
3898• wait for UDP connections.
3899• nowait for TCP connections.
3900User Determines the user permissions (read, write, and execute) the daemon will use when accessing the file system. Be aware of the following:
3901• Specify a user with the lowest necessary privileges.
3902• Common choices are root and nobody.
3903• Using group permissions is optional.
3904Executable Identifies the path to the daemon executable. Be aware of the following:
3905• Use internal if the daemon does not have an executable file.
3906• Use the path to the executable for external daemons, such as /usr/bin/ftpd.
3907• If using TCP wrappers, use /usr/sbin/tcpd.
3908Arguments Assigns daemon-specific arguments.
3909If using TCP wrappers, the path to the actual daemon executable must be typed here, such as /usr/bin/ftpd.
3910The following are example entries in the /etc/inetd.conf file:
3911Entry Description
3912ftp stream tcp nowait ftp /usr/sbin/ftpd Inetd daemon will start the ftp daemon when necessary.
3913ftp stream tcp nowait root /usr/sbin/tcpd /usr/bin/ftpd Inetd daemon will use TCP wrappers to control which hosts can start the ftp daemon.
3914
3915
3916
3917-----
3918Encryption is a security technique that encodes information so that only someone with the proper key can decode it. Be aware of the following encryption types:
3919Type Description
3920Symmetric Symmetric key encryption (also known as secret key encryption, pre-shared key or private key encryption) uses only one key to encrypt and decrypt data.
3921• Symmetric encryption is well suited for bulk encryption of less sensitive data because it is less CPU-intensive than other encryption methods.
3922• Before communications begin, both parties must exchange the shared secret key using a secure channel. This is often done manually or with some form of asymmetric key cryptography.
3923• Each pair of communicating entities requires a unique shared key. This means that the number of keys required grows exponentially as the number of communication partners grows. For example, 1,000 users in a system would require the generation of almost 500,000 different keys.
3924• The key space is typically short, ranging from 56-bits to a maximum of 512-bits. (As the number of bits in the key increases, so does the strength of the encryption. However, the greater the number of bits in the key, the more CPU resources are required to perform the encryption.)
3925Asymmetric Asymmetric encryption (also known as public key encryption) uses two keys that are mathematically related. Both keys together are called the key pair.
3926• The public key is made available to anyone; the private key is kept secret.
3927• Use one key to encrypt and the other to decrypt. For example, if data is encrypted with the public key, use the private key to decrypt the data.
3928• The strength of an asymmetric encryption system lies in the secrecy and security of its private keys. If the private key is ever discovered, a new key pair must be generated.
3929• Asymmetric encryption of large amounts of data is slow and requires high CPU usage. Processing speeds are much slower (about 1,000 times slower) than symmetric key encryption.
3930• Asymmetric encryption requires fewer keys than symmetric key encryption, because only two keys per user are required (not a key for every communicating partner).
3931Be aware of the following standards for symmetric and asymmetric encryption:
3932Type Description
3933Symmetric Data Encryption Standard (DES) is a very popular encryption standard created by the National Security Agency. DES can be easily broken.
3934 Triple DES (3DES) is an enhanced version of DES. 3DES applies DES three times, and uses a 168-bit key.
3935 AES (Advanced Encryption Standard) is an improved version of Triple DES that supports encryption key lengths of up to 256 bits.
3936 Blowfish is a keyed, symmetric block cipher that was intended to be free of the problems associated with other algorithms and replace DES. Blowfish uses 64-bit blocks and key lengths anywhere from 32 bits to 448 bits.
3937Asymmetric Rivest, Shamir Adleman (RSA) is based on factoring large numbers into their prime values. It was developed by Rivest, Shamir and Adleman. RSA has key-length ranges from about 512 bit to 8,000 bits (2401 digits).
3938 DSA (Digital Signature Algorithm) is a United States Government encryption standard often used for digital signing. DSA currently supports Secure Hashing Algorithm-1 (SHA-1), which uses key lengths between 160 and 256 bits, or SHA-2, which uses key lengths between 256 and 1024 bits.
3939 The Diffie-Hellman Key Exchange was the first asymmetric algorithm. It was developed by Whitfield Diffie and Martin Hellman. It is a key agreement protocol that generates symmetric keys simultaneously at sender and recipient sites over non-secure channels. The Diffie-Hellman key exchange:
3940• Provides for key distribution and does not provide any cryptographic services.
3941• Is based on calculating discreet logarithms in a finite field.
3942• Is used in many algorithms and standards such as DES.
3943• Is subject to man in the middle attacks and requires strong authentication to validate the end points.
3944
3945-----
3946OpenSSH is a tool that encrypts network traffic over a subnet or Internet. OpenSSH is an open version of Secure Shell (SSH) implemented on many Linux distributions and is similar to other versions of SSH. SSH:
3947• Uses a public and private key pair to encode and transfer a symmetric key that is used during the session. The public key is available to all users. The private key is only on the server and is never shared.
3948• Can use associated key management software and scripts to automate the exchange of public keys.
3949• Allows encryption of other network protocols, such as the X server protocols.
3950• Has two types:
3951 SSH version 1 (SSH1) is an older, less secure version of SSH. SSH1 only supports RSA encryption.
3952 SSH version 2 (SSH2) is the current standard SSH implementation. It can use either DSA or RSA encryption.
3953Computers use the following steps when establishing a session using SSH:
39541. A client running SSH establishes a connection to the server (any computer running SSH daemon (sshd)) over port 22.
39552. The computers determine which SSH version to use based on the specifications in the configuration files. Typically, this is SSH2.
39563. The server sends one of the following public keys from the /etc/ssh/ directory to the client:
3957o ssh_host_key.pub (SSH1 public key)
3958o ssh_host_rsa_key.pub (SSH2 public key when using RSA)
3959o ssh_host_dsa_key.pub (SSH2 public key when using DSA)
39604. When the client receives the public key from the server, it compares the key to the keys it has received and stored in one of the following files:
3961o /etc/ssh/ssh_known_hosts
3962o ~/.ssh/known_hosts
3963If the key is not present in either of these files, then the client prompts the user to accept and store the key.
39645. The server and the client then use the Diffie-Hellman key exchange system to agree on a symmetric key that they use for the rest of the session.
39656. The data is exchanged with symmetric encryption.
3966
3967-----
3968OpenSSH configuration files let administrators customize settings for SSH access and availability. Configuration tasks include:
3969• Configuring SSH servers to determine whether clients can access them and which clients have access.
3970• Configuring SSH clients to use SSH and specify which servers they can access.
3971• Configuring the firewall to allow traffic to pass through the ports that SSH uses. By default, it is port 22.
3972OpenSSH uses the following configuration files:
3973File Description Examples
3974/etc/ssh/sshd_config The /etc/ssh/sshd_config file configures the SSH daemon on the server system. Be aware of the following commonly-needed options for configuring an SSH server:
3975• AllowUsers lists users allowed to use SSH. If an AllowUsers line is used in the file, all users except those listed are denied access by default.
3976• DenyUsers lists users not allowed to use SSH. If a DenyUsers line is used in the file, all users except those listed are granted access by default. A DenyUsers entry overrides an AllowUsers entry.
3977• Protocol specifies which protocols SSH allows when accessing the SSH server.
3978 Protocol 2 is more secure, and is supported on newer distributions. The default is protocol 2.
3979 Protocol 1 is typically used on older systems.
3980• ListenAddress gives the addresses that SSH should use when listening for requests. By default, the server listens on all IP addresses assigned to it. Use this line to specify specific addresses.
3981• Port specifies the port number. The default is 22. Use this line to change the default.
3982• PasswordAuthentication disables password authentication when set to no.
3983• UsePAM enables the Pluggable Authentication Modules (PAM) interface between sshd and the system.
3984• PermitRootLogin specifies whether users can log in as root over SSH.
3985 If set to no, then users must log in using standard credentials, but can use the su command to elevate their privileges.
3986 The default is yes.
3987Restart the sshd daemon to implement changes. AllowUsers jsmith mkimball grants access to the specified users.
3988DenyUsers gedwards fjones denies access to the specified users.
3989Protocol 1,2 allows the server to use either protocol.
3990ListenAddress 192.168.10.10:22 ensures that the server listen only on the IP address specified.
3991port 11111 changes the SSH port from the default port to port 11111.
3992
3993/etc/ssh/ssh_config
3994~/.ssh/config The /etc/ssh/ssh_config file configures OpenSSH for all users on the client system. ~/.ssh/config is a user-specific hidden file which can override the configuration in /etc/ssh/ssh_config file. Both files can be overridden using command line options with the ssh command.
3995Be aware of the following commonly-needed options for configuring an SSH client:
3996• Protocol specifies which protocols SSH allows when accessing the SSH server.
3997• StrictHostKeyChecking determines whether SSH clients can accept keys from SSH servers not previously accessed. The keys of previously accessed servers reside in one of the following directories:
3998 /etc/ssh/ssh_known_hosts
3999 ~/.ssh/known_hosts
4000If this parameter is set to yes, then new keys must be added manually using:
4001cat keyfile.pub >> /etc/ssh/ssh_known_hosts
4002• CheckHostIP verifies that the supplied key matches the IP address of the server when set to yes. This prevents IP spoofing, but might generate warnings or refuse connection if the server changes its keys.
4003• Port specifies the port that SSH uses.
4004• User automatically logs in with the specified user name instead of requesting a username. Protocol 1,2 allows the client to connect using either protocol.
4005StrictHostKeyChecking no automatically adds new host keys to the known hosts files. Other options are yes and ask. Ask is the default.
4006port 11111 changes the SSH port from the default port to port 11111.
4007user jsmith automatically uses jsmith as the user when logging in.
4008The following table lists commands used in conjunction with SSH.
4009Use... To... Examples
4010which Verify if a package is installed on the system. which sshd verifies that the SSH server daemon is installed.
4011which ssh verifies that the SSH client daemon is installed.
4012service sshd Manage the current state of the SSH daemon on the server. Options include:
4013• start starts a daemon that is not currently running
4014• stop halts a running daemon.
4015• restart stops and restarts a daemon.
4016• status shows the status of a single daemon or daemons.
4017As an alternative method, use the absolute path to the daemon script and the option to configure the daemon (e.g., /etc/rc.d/init.d/sshd start) service sshd start starts the ssh daemon.
4018/etc/init.d/sshd start starts the ssh daemon.
4019service sshd status shows whether the sshd daemon is running.
4020/etc/it.d/sshd status shows whether the sshd daemon is running.
4021ssh Make a secure connection from the SSH client to the SSH server. Be aware of the following options:
4022• -l specifies the user account on the server. Without this option, SSH uses the same user account name being used on the client computer.
4023• hostname specifies the SSH server name, and could include a domain name.
4024• commands (optional) runs the command on the remote system but displays the results on the local machine. ssh -l bjones hs1 logs in to the hs1 computer as bjones.
4025ssh -l bjones@hs1 ls -la /var/log logs in to the hs1 computer as bjones, executes the ls -la /var/log command on the remote computer, then closes the connection.
4026scp Encrypt and copy files from a remote system over the network. Be aware of the following options:
4027• username specifies the user account on the remote system.
4028• @hostname:remotefile specifies the remote system and the remote file.
4029• destination/filename specifies where to location and name of the new file. If the new file name is omitted, the file is copied using the original name. scp bjones@hs1:hostfile ~/ copies hostfile from the server to the home directory on the client.
4030scp ~/clientfile bjones@hs2.mydomain.com:/home/bjones/ copies clientfile from the client computer to the home directory of bjones on the server.
4031scp bjones@hs1.mydomain.com:/home/bjones/file1 bjones@hs2.mydomain.com:/home/bjones/ copies file1 from hs1 to hs2.
4032sftp Transfer files securely from ftp servers. Be aware of the following options:
4033• username specifies the user account on the remote system.
4034• @hostname specifies the remote system.
4035After logging in, use the same commands that are used when using ftp. These include:
4036• pwd shows the current directory.
4037• get file_name copies a file from the ftp server.
4038• cdup traverses up a directory
4039• dir displays files in the current directory. sftp bjones@ftp1.mydomain.com connects to the FTP server as bjones.
4040slogin Allows access to a shell on a remote computer. It is identical to the ssh command. This is supported only for backwards compatibility. slogin -l bjones hs1 logs in to the hs1 computer as bjones.
4041
4042-----
4043Secure Shell (SSH) port tunneling encrypts data from non-secure protocols before sending the data over a network. Non-secure protocols, such as email and X server traffic, are commonly tunneled through SSH. The SSH port tunneling process works as follows:
40441. The client sends the non-secure protocol information to the port on the server running the SSH daemon.
40452. The SSH daemon intercepts all traffic sent to that port, encrypts it, and sends it to the SSH client.
40463. The SSH client receives the encrypted traffic, decrypts it, and forwards it to the default port for the client.
40474. The client receives the data on its usual port.
4048The /etc/ssh/sshd_config configures the SSH daemon on the server. Be aware of the following commonly-needed options for configuring an SSH server:
4049• AllowTcpForwarding allows TCP traffic to be sent from the SSH daemon when set to yes.
4050• ForwardX11 specifies that clients to which requests are forwarded are regarded as untrusted, and have restricted access to certain GUI features. The default is no.
4051• ForwardX11Trusted specifies that clients to which requests are forwarded are regarded as trusted, and have unrestricted access to all GUI features. The default is yes.
4052• X11Forwarding is similar to setting ForwardX11Trusted to yes, but is used with older distributions. The default is no.
4053Use the following commands to create an SSH port tunnel:
4054Use... To... Example
4055ssh Set up an SSH tunnel from the client to the server for textual traffic. Be aware of the following options:
4056• -f runs SSH in the background after the password prompt.
4057• -N ensures that SSH does not execute a remote command.
4058• -L specifies the port numbers and server name.
4059• -g overrides configuration file settings and creates a tunnel if needed.
4060• tunnelport specifies the SSH port for the encrypted data. Only the root user can set the SSH port to a privileged port (i.e., port 1024 or lower.)
4061• server specifies the server running the SSH daemon.
4062• port specifies the default port for non-secure protocol. ssh -f -N -L 2345:mail.mydomain.com:110 userbob@mail.mydomain.com sets up an SSH port tunnel for POP3 mail traffic over port 2345.
4063ssh -X Set up an SSH tunnel from the client to the server for X server traffic. Be aware of the following options:
4064• -l specifies the username of the user account on the remote system.
4065• server specifies the server name and domain running the SSH daemon. ssh -X -l mtrance hn3.mydomain.com sets up an SSH port tunnel for X server traffic.
4066Use the following commands to send unencrypted X server traffic between a client and server:
4067Use... To... Example
4068xhost +servername Configure the client to receive unencrypted X server traffic. xhost +hn3.mydomain.com configures the client to accept unencrypted X server traffic from hn3.mydomain.com.
4069DISPLAY=host_name:0.0
4070export DISPLAY
4071 Configure and export the DISPLAY environment variable to send unencrypted X server traffic to the specified client. DISPLAY=hn2:0.0 configures the server to display unencrypted X server traffic on hn2.
4072export DISPLAY exports the DISPLAY environment variable.
4073
4074-----
4075Public key authentication uses a public key instead of a password to log in to a computer. The computer uses the following method to authenticate using a public key:
40761. The client specifies which public key the server uses for authentication, and the server checks to ensure the key has previously been authenticated to the server.
40772. If the key is known to the server, it chooses a random number, encrypts it with the public key, and sends it to the client.
40783. The client decrypts the number with a private key, uses its own public key and random number to create a hash (MD5 checksum). The client sends the hash back to the server.
40794. The server uses the public key and the random number to create its own hash (MD5 checksum) and then checks whether both hash values match.
40805. If the hashes match, the server grants access to the user. If the hashes do not match, the user is prompted to log in using a password.
4081Use the following commands and files for public key management:
4082Use... To... Example
4083/etc/ssh/sshd_config Configure the server to accept public key authentication. Be aware of the following commonly-needed options for configuring an public key authentication on the server:
4084• PubKeyAuthentication enables/disables public key authentication on the server.
4085• AuthorizedKeysFile location specifies the location of the file that contains the public keys. PubKeyAuthentication yes enables public key authentication on the server.
4086AuthorizedKeysFile .ssh/authorized_keys specifies the location of the file that contains the public keys.
4087ssh-keygen Create a key on the client for use when authenticating to a server. Be aware of the following ssh-keygen options:
4088• -t dsa creates a DSA key pair (i.e., id_dsa and id_dsa.pub).
4089• -t rsa creates an RSA key pair (i.e., id_rsa and id_rsa.pub). This is the default. ssh-keygen -t dsa creates a DSA key pair.
4090ssh-keygen -t rsa creates an RSA key pair.
4091ssh-keygen creates an RSA key pair.
4092scp Securely copy the client's public key file to the server. scp ~/.ssh/id_rsa.pub bjones@hs2.mydomain.com:/home/bjones/ copies id_rsa.pub to the home directory of bjones.
4093ssh Log in to the server. ssh -l bjones hs1 logs in to the hs1 computer as bjones.
4094cat Append the public key to the ~/authorized_keys file. Be aware of the following:
4095• Overwriting the file deletes all other keys.
4096• If the same user logs in from multiple clients, the file must have all client keys in it.
4097• Always remove the rsa.pub file after appending it to the ~/authorized_keys file. cat id_rsa.pub >> ~/.ssh/authorized_keys appends the id_rsa.pub file to the end of the authorized_keys file.
4098ssh-agent bash
4099ssh-add To configure the client to automatically provide the private key passphrase when needed so that it does not have to be typed for every new connection to a server.
41001. Use ssh-agent bash to enable passphrase agent.
41012. Use ssh-add to specify the name of the private key to add to the agent. For protocol 2, this is one of the following:
4102o ~/.ssh/id_rsa
4103o ~/.ssh/id_dsa
4104Be aware of the following:
4105• After the ssh-add command, type the passphrase when prompted. The passphrase stays in memory while the user is logged in to the client.
4106• SSH1 uses ssh-add ~/.ssh/identity. ssh-agent bash enables passphrase automation.
4107ssh-add ~/.ssh/id_rsa specifies the id_rsa file as the private key.
4108
4109-----
4110Gnu Privacy Guard (GnuPG) is an encryption tool that encrypts and digitally signs email, and also encrypts documents. GnuPG is an implementation of the Pretty Good Privacy (PGP) protocol. It uses public/private key encryption to secure documents. Be aware of the following commands and files when using GnuPG:
4111Use... To... Example
4112which gpg Determine whether the GnuPG package is installed on the system. [root@:ls4 ~]which gpg
4113user/bin/gpg
4114
4115Shows the GnuPG package is installed on the system.
4116gpg Configure the GnuPG keys and other aspects of GnuPG. Be aware of the following options:
4117• --gen-key creates a key pair.
4118• --export name > gpg.pub creates a public key named gpg.pub.
4119• --import filename adds public keys from other people to the GnuPG key ring.
4120• --list-keys displays all the keys on the key ring.
4121• --out new_encrypted_file --recipient name --armor --encrypt original_file_name encrypts a file for an associate.
4122• --out decrypted_file_name --decrypt encrypted_file_name decrypts a file from an associate.
4123• --clearsign file_name digitally signs a file.
4124• --verify file_name compares the file against all keys in the key ring for a valid signature.
4125• --gen-revoke key-ID creates a key revocation certificate.
4126To revoke a public key on a key server:
41271. Revoke the key on a local system using the key revocation certificate.
41282. Send the revoked key to the key server. gpg --gen-key starts the process of creating a GnuPG key pair.
4129gpg --export jjones@acme.biz > gpg.pub creates a public key that people can use to send email to jjones.
4130gpg --out Secret.txt --recipient jjones@acme.biz --armor --encrypt Report.txt encrypts Report.txt using the private key associated with jjones@acme.biz and creates an encrypted file named Secret.txt.
4131gpg --out Report.txt --decrypt Secret.txt decrypts Secret.txt and creates a file named Report.txt.
4132gpg --clearsign Report creates a file named Report.asc. Report.asc contains the original text along with a PGP signature hash.
4133gpg --verify Report.asc uses the public keys to decrypt the hash signature in the Report.asc file and compare it to the original text. This option tries all public keys on the GnuPG key ring until it finds a match. If a match is found, it verifies whether the text is unchanged.
4134gpg --out revoke.asc --gen-revoke A83B65D9 creates a key revocation certificate for the A83B65D9 key.
4135gpg --import revoke.asc adds the key revocation certificate to a system.
4136
4137-----