Tải bản đầy đủ (.pdf) (103 trang)

Red Hat Linux Networking and System Administration Third Edition phần 8 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.63 MB, 103 trang )

Table 28-5 (continued)
COMMAND DESCRIPTION
mkpart Creates a primary, logical, or extended partition by specifying
the starting an ending size in MB.
mkpartfs Creates a primary, logical, or extended partition by specifying
the starting and ending size in MB and then creates a file
system of a specified type on the newly created partition.
move Moves a partition by changing the starting and ending blocks,
specified in MB.
print Displays the current partition table.
quit Exits parted.
resize Resizes a partition by changing the starting and ending blocks,
specified in MB.
rm Deletes a partition.
select Chooses the device to edit.
set Changes or sets flags on a disk partition. Valid flags are boot,
root, swap, hidden, raid, lvm, lba, and palo.
CAUTION Exercise extreme care when using parted or any other partition
editor to resize or manipulate parition tables. The tools themselves usually
work fine and don’t exhibit any unexpected behavior. Nonetheless, it is simple
for operator error to render a disk unbootable with a stray keystroke.
Most of the commands listed in Table 28-5 accept one or more cmd_opts,
which are options that specify the device or partition on which to operate, a
starting and ending value, and a file system type. For complete details, refer to
the parted Info page (info parted); less complete but still useful information
can be found in the parted man page (man parted).
Creating and Manipulating File Systems
mke2fs creates a Linux ext2 or ext3 file system on a disk. Its syntax is:
mke2fs [-c | -l list] [-b size] [-i bytes-per-inode] [-j] [-n]
[-m reserve] [-F] [-q] [-v] [-L label] [-S] device
device indicates the disk partition or other device on which to create the


file system. Specifying -n results in a test run; mke2fs goes through the entire
Configuring the System at the Command Line 685
36_599496 ch28.qxd 8/30/05 7:24 PM Page 685
creation process but does not actually create the file system. Use -q to sup-
press output, for example, when mke2fs is used in a script. Conversely, use
-v to generate verbose output.
To check the disk for bad blocks while creating the file system, specify -c, or
use -l list to read a list of known bad blocks from the file named list. By
default, mke2fs calculates file system block sizes based on the size of the
underlying partition, but you can specify -b size to force a block size of 1024,
2048, or 4096 bytes. Similarly, to override the default inode size, use -i
bytes-per-inode (bytes-per-inode should be no smaller than the block
size defined with -b size). -m reserve instructs mke2fs to set aside
reserve percent of the file system for the root user. If -m reserve is omitted,
the default reserve space is 5 percent. -L label sets the file system’s volume
label, or name, to label.
Normally, mke2fs refuses to run if device is not a block device (a disk of
some sort) or if it is mounted; -F overrides this default. -F is most commonly
used to create a file that can be mounted as a loopback file system. -S, finally,
causes mke2fs to write only the superblocks and the group descriptors and to
ignore the block and inode information. In essence, it attempts to rebuild the
high-level file system structure without affecting the file system contents. It
should be used only as a final attempt to salvage a badly corrupted file system,
and may not work. The manual page recommends running e2fsck immedi-
ately after using -S.
To create and manipulate swap space, use the mkswap, swapon, and
swapoff commands. mkswap initializes a swap area on a device (the usual
method) or a file. swapon enables the swap area for use, and swapoff disables
the swap space. mkswap’s syntax is:
mkswap [-c] device [size]

device identifies the partition or file on which to create the swap area and
size specifies the size, in blocks, of the swap area to create. size is necessary
only if you want a swap area smaller than the available space. If device is a
file, it must already exist and be sized appropriately. -c performs a check for
bad blocks and displays a list of any bad blocks found.
TIP To create a swap file before using mkswap, use the following command:
dd if=/dev/zero of=/some/swap/file bs=1M count=128
Replace /some/swap/file with the file you want to create as a swap file.
To enable the kernel to use swap devices and files, use the swapon com-
mand. Its syntax takes three forms:
686 Chapter 28
36_599496 ch28.qxd 8/30/05 7:24 PM Page 686
swapon -s
swapon -a [-ev]
swapon [-p priority] [-v] device
The first form displays a summary of swap space usage for each active swap
device. The second form, normally used in system startup scripts, uses -a to
activate all swap devices listed in /etc/fstab. If -e is also specified, swapon
ignores devices listed in /etc/fstab that do not exist. The third form acti-
vates the swap area on device, and, if -p priority is also specified, gives
device a higher priority in the swap system than other swap areas. priority
can be any value between 0 and 32,767 (specified as 32767), where higher val-
ues represent higher priorities. -v prints short status messages.
e2fsck checks a file system for possible corruption and repairs any damage
found. e2fsck is an ext2- and ext3-file-system-specific version of the more
general fsck command. Ordinarily, you will use fsck, which is a wrapper
program that invokes a file system-specific version of fsck depending on the
type of file system. For example, if you call fsck on an ext2 or ext3 file system,
it will invoke e2fsck; if you call fsck on a ReiserFS file system, fsck invokes
fsck.reiserfs.

e2fsck’s syntax is:
e2fsck [-pcnyfvt] [-b sblock] [-B size] [-l list] device
device is the partition (/dev/hda1, for example) to test. -b sblock tells
e2fsck to use the backup super block located on block number sblock. -B
size specifies block sizes of size bytes. -l list instructs e2fsck to add the
block numbers listed in the file name list to the list of known bad blocks.
Using -c causes e2fsck to identify bad blocks on the disk. Ordinarily,
e2fsck asks for confirmation before repairing file system errors; specifying
-p disables any confirmation prompts, -n automatically answers “No” to all
questions and sets the file system to read-only, and -y automatically answers
“Yes” to all questions. e2fsck’s default behavior is not to check a file system
that is marked clean, but using -f forces it to do so. -v enables verbose output.
-t generates a timing report at the end of e2fsck’s operation.
If e2fsck discovers problems with one of your file systems that it cannot
repair automatically, you might be able to use the debugfs program to repair
the file system manually.
resize2fs makes it possible to resize ext2 and ext3 file systems without
destroying existing data and, in certain cases, without having to use fdisk or
parted to resize the partition. As with parted, use resize2fs with great care
and make sure you have good backups of the data on the file system you
intend to resize.
Configuring the System at the Command Line 687
36_599496 ch28.qxd 8/30/05 7:24 PM Page 687
The symlinks command scans directories for symbolic links, displays
them on the screen, and repairs broken or otherwise malformed symbolic
links. Its syntax is:
symlinks [-cdrstv] dirlist
dirlist is a list of one or more directories to scan for symbolic links. -r
causes symlinks to recurse through subdirectories. -d deletes dangling links,
symbolic links whose target no longer exists. -c converts absolute links, links

defined as an absolute path from /, to relative links, links defined relative to
the directory in which the link is located. -c also removes superfluous / and .
elements in link definitions. -s identifies links with extra / in their defini-
tion and, if -c is also specified, repairs them. To see what symlinks would do
without actually changing the file system, specify -t. By default, symlinks
does not show relative links; -v overrides this default.
To make an existing file system available, it has to be mounted using the
mount command. mount’s syntax is:
mount -a [-fFnrsvw] [-t fstype]
mount [-fnrsvw] [-o fsoptions] device | dir
mount [-fnrsvw] [-t fstype] [-o fsoptions] device dir
The first two forms use the information in /etc/fstab when mounting file
systems. When invoked with no options, mount lists all mounted file systems,
and when you specify only –t, fstype lists all mounted file systems of type
fstype. fstype will be one of devpts, ext2, iso9660, or vfat, but many
other file system types are supported — the complete list of valid types is
available in mount’s manual page.
The -a option mounts all the file systems listed in /etc/fstab (subject to
the restriction of using the -t option as explained in the previous paragraph)
that are configured using the auto mount option. (See Table 28-6.) The sec-
ond form is most commonly used to override the mount options, using -o
fsoptions, listed in /etc/fstab. Note that you only have to specify
device, the device containing the file system, or dir, where in the directory
hierarchy the file system should be attached.
Use the third form to mount file systems not listed in /etc/fstab or to
override information it contains. The third form is also the most widely used.
In general, it attaches the file system on device to the system’s directory hier-
archy at the mount point dir, using a file system type of fstype and the
file system options fsoptions. Table 28-6 lists mount’s global options.
fsoptions is a comma-delimited list of one or more of the options listed in

Table 28-7.
688 Chapter 28
36_599496 ch28.qxd 8/30/05 7:24 PM Page 688
NOTE Because Linux supports so many file systems, this chapter discusses
only a few of the many file systems and file system options. mount’s manual
page contains a complete list of the file systems and their corresponding mount
options that Linux currently supports.
Table 28-6 Global Options for the mount Command
OPTION DESCRIPTION
-a Mounts all file systems, subject to restrictions specified using -t
-F Mounts all file systems (used only with -a) in parallel by
creating new processes for each file system to mount
-f Fakes the mount operation, doing everything but actually
mounting the file system
-h Displays a short usage message
-n Mounts the file system without creating an entry in the mount
table (/etc/mtab)
-o fsoptions Mounts the file system using the file system-specific options
fsoptions
-r Mounts the file system in read-only mode
-s Ignores options specified with -o that are invalid for the given
file system type (the default is to abort the mount operation)
-t fstype Restricts mount’s operation to file system types of type fstype
(first and second forms) or specifies the file system type of the
file system being mounted (third form)
-v Prints informational messages while executing (verbose mode)
-w Mounts the file system in read/write mode
Table 28-7 Common File System Options for the mount Command
OPTION TYPE* DESCRIPTION
async 1 Enables asynchronous system I/O on the file system

auto 1 Enables mounting using the -a option
defaults 1 Enables the default options (rw, suid, dev, exec,
auto, nouser, async) for the file system
dev 1 Enables I/O for device files on the file system
exec 1 Enables execution of binaries on the file system
(continued)
Configuring the System at the Command Line 689
36_599496 ch28.qxd 8/30/05 7:24 PM Page 689
Table 28-7 (continued)
OPTION TYPE* DESCRIPTION
gid=gid 2,3 Assigns the GID gid to all files on the file system
mode=mode 3 Sets the permissions of all files to mode
noauto 1 Disables mounting using the -a option
nodev 1 Disables I/O for device files on the file system
noexec 1 Disables execution of binaries on the file system
nosuid 1 Disables set-UID and set-GID bits on the file system
nouser 1 Permits only root user to mount the file system
ro 1 Mounts the file system in read-only mode
remount 1 Attempts to remount a mounted file system
rw 1 Mounts the file system in read/write mode
suid 1 Enables set-UID and set-GID bits on the file system
sync 1 Enables synchronous file system I/O on the file
system
user 1 Permits nonroot users to mount the file system
uid=uid 2,3 Assigns the UID uid to all files on the file system
1 = All file systems, 2 = devpts, 3 = iso9660
To unmount a file system, use the command umount. Its syntax is much
simpler, thankfully, than mount’s:
umount -a [-nrv] [-t fstype]
umount [-nrv] device | dir

All of umount’s options and arguments have the same meaning as they do
for mount, except for -r. Of course, the options must be understood in the
context of unmounting a file system. If -r is specified and unmounting a file
system fails for some reason, umount attempts to mount it in read-only mode.
To access swap space, use theswapon and swapoff commands. To enable
the kernel to use swap devices and files, use the swapon command. Its syntax
takes three forms:
swapon -s
swapon -a [-ev]
swapon [-p priority] [-v] device
690 Chapter 28
36_599496 ch28.qxd 8/30/05 7:24 PM Page 690
The first form displays a summary of swap space usage for each active swap
device. The second form, normally used in system startup scripts, uses -a to
activate all swap devices listed in /etc/fstab. If -e is also specified, swapon
ignores devices listed in /etc/fstab that do not exist. The third form activates
the swap area on device, and, if -p priority is also specified, gives device
a higher priority in the swap system than other swap areas. priority can be
any value between 0 and 32,767 (specified as 32767), where higher values rep-
resent higher priorities. -v prints short status messages.
To deactivate a swap area, use the swapoff command. Its syntax is simple:
swapoff -a | device
Use -a to deactivate all active swap areas, or use device to deactivate a
specific swap area. Multiple swap areas may be specified using white space
between device identifiers.
Working with Files and Directories
This section reviews the basic call syntax of the following commands:
■■ chmod — Modifies file and directory permission settings
■■ chown — Modifies file and directory user ownership
■■ chgrp — Modifies file and directory group ownership

■■ lsattr — Lists special file attributes on ext2 files
■■ chattr — Modifies special file attributes on ext2 files
■■ stat — Shows detailed file information
■■ fuser — Displays a list of process IDs using a file
■■ lsof — Identifies files opened by a process
Here are the syntax summaries for chmod, chown, and chgrp:
chmod [-cfRv] symbolic_mode file
chmod [-cfRv] octal_mode file
chown [-cfhRv] owner[:[group]] file
chown [-cfhRv] :group file
chgrp [-cfhRv] group file
chmod, chown, and chgrp accept the common options -c, -v, -f, -R, and
file. file is the file or directory to modify, and multiple file arguments can
be specified. -R invokes recursive operation on the subdirectories of the cur-
rent working directory or of a directory specified by file. -v generates a
diagnostic for each file or directory examined. -c generates a diagnostic mes-
sage only when it changes a file. -f cancels all but fatal error messages.
Configuring the System at the Command Line 691
36_599496 ch28.qxd 8/30/05 7:24 PM Page 691
chmod has two forms because it understands both symbolic and octal nota-
tion for file permissions. For both forms, file is one or more files on which
permissions are being changed. symbolic_mode uses the symbolic permis-
sions notation, while octal_mode expresses the permissions being set using
the standard octal notation.
CROSS-REFERENCE For a quick refresher on using symbolic and octal
permissions notation, refer to the chmod manual page.
With the chown and chgrp commands, group is the new group being
assigned to file. For the chown command, owner identifies the new user
being assigned as file’s owner. The colon (:) enables chmod to change
file’s group ownership. The format owner:group changes file’s user and

group owners to owner and group, respectively. The format owner: changes
only file’s owner and is equivalent to chown owner file. The format
:group leaves the owner untouched but changes file’s group owner to
group (equivalent to chgrp group file).
The lsattr and chattr commands are Linux-specific, providing an inter-
face to special file attributes available only on the ext2 and ext3 file systems.
lsattr lists these attributes, and chattr sets or changes them. lsattr’s
syntax is:
lsattr [-adRVv] file
file is the file or directory whose attributes you want to display; multiple
white space separated file arguments may be specified. -a causes the attrib-
utes of all files, such as hidden files, to be listed. -d lists the attributes on direc-
tories, rather than listing the contents of the directories, and -R causes lsattr
to recurse through subdirectories if file names a subdirectory.
chattr’s syntax is:
chattr [-RV] [-v version] +|-|=mode file
file is the file or directory whose attributes you want to display; multiple
white space separated file arguments may be specified. -R causes lsattr to
recurse through subdirectories if file names a subdirectory. -v version sets
a version or generation number for file. +mode adds mode to file’s attributes;
-mode removes mode from file’s attributes; =mode sets file’s attributes to
mode, removing all other special attributes. mode can be one or more of the
following:
■■ A — Do not change file’s time (last access time)
■■ S — Update file synchronously
692 Chapter 28
36_599496 ch28.qxd 8/30/05 7:24 PM Page 692
■■ a — File is append-only
■■ c — Kernel automatically compresses/decompresses file
■■ d — File cannot be dumped with the dump command

■■ I — File is immutable (cannot be changed)
■■ s — File will be deleted securely using a special secure deletion algorithm
■■ u — File cannot be deleted
The stat command displays detailed file or file system status information.
Its syntax is:
stat [-l] [-f] [-t] file
file specifies the file or directory about which you want information. Use
multiple white-space-delimited file arguments to specify multiple files. If -l is
used and file is a link, stat operates on the link’s target (the file that is
linked) rather than the link itself. Using -f causes stat to display information
about file’s file system, not file. Specifying -t results in a shorter (terse)
output format suitable for use in scripts.
Often, an administrator needs to identify the user or process that is using a
file or socket. fuser provides this functionality. Its syntax is:
fuser [-a | -s] [-n namespace] [-signal] [-kimuv] name
name specifies the file, file system, or socket to query. By default, fuser
assumes that name is a filename. To query TCP or UDP sockets, use -n
namespace, where namespace is udp for UDP sockets and tcp for TCP
sockets (file is the default namespace). -a results in a report for all names
specified on the command line, even if they are not being accessed by any
process. -s, on the other hand, causes fuser to run silently. You cannot use
-s with -a, -u, or -v. -k kills processes using name with the signal SIGKILL;
use -signal to specify an alternate signal to send. Use -i (interactive) to be
prompted for confirmation before killing a process. Only use -i with -k. -m
indicates that name specifies a file system or block device, so fuser lists all
processes using files on that file system or block device. -u adds the username
of a process’s owner to its output when listing processes. -v, finally, generates
a verbose, ps-like listing of processes using the specified name.
For example, to see what process and user is using the Berkeley socket file
/tmp/.X11-unix/X0, the following command would do:

# fuser -u /tmp/X11-unix/X0
/tmp/.X11-unix/X0: 3078(root)
Configuring the System at the Command Line 693
36_599496 ch28.qxd 8/30/05 7:24 PM Page 693
This command used the -u option to display the username (root) running
the displayed process (3078). For a more verbose listing, add the -v option:
# fuser -uv /tmp/.X11-unix/X0
USER PID ACCESS COMMAND
/tmp/.X11-unix/X0 root 3078 f X
lsof performs the reverse function from fuser, showing the files open by
a given process or group of processes. A simplified version of its syntax is:
lsof [-LlNRst] [-c c] [+f | -f] [+r | -r [t]] [-S [t]] [file]
file specifies the file or file systems (multiple file arguments are permit-
ted) to scan. Specifying -c c selects processes executing a command that
begins with the letter c. -f causes file to be interpreted as a file or pathname,
+f as a file system name. -L suppresses displaying the count of files linked to
file. -l displays UIDs rather than converting them to login names. Specify-
ing -N includes a list of NFS files in lsof’s output. +r causes lsof to repeat
the display every 15 seconds (or t seconds if t is specified) until none of the
selected files remains open; -r repeats the display indefinitely. -R lists the par-
ent process ID of displayed processes. -S enables lsof to time out after 15 sec-
onds, or after t seconds if t is specified.
One of the most common uses of lsof is to find out what file (or files) are
preventing you from unmounting a file system. As you might have experi-
enced, you cannot unmount a file system when a file that resides on it is still
open. If you attempt to do this, umount complains that the file system is busy.
For example, suppose that you want to unmount /dev/fd0, which is
mounted on the file system /mnt/floppy:
# umount /mnt/floppy
umount: /mnt/floppy: device is busy

umount: /mnt/floppy: device is busy
Nuts. Undeterred, you use the lsof command to determine what files are
open on the /mnt/floppy:
# lsof /mnt/floppy
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
bash 4436 bubba cwd DIR 2,0 1024 2 /mnt/floppy
cat 11442 bubba cwd DIR 2,0 1024 2 /mnt/floppy
cat 11442 bubba 1w REG 2,0 0 12 /mnt/floppy/junk
Now, you can use the kill command to kill the processes that are keeping
you from unmounting /mnt/floppy:
694 Chapter 28
36_599496 ch28.qxd 8/30/05 7:24 PM Page 694
# kill 11442 4436
# lsof /mnt/floppy
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
bash 4436 bubba cwd DIR 2,0 1024 2 /mnt/floppy
The bash shell bubba is running isn’t dead, so use more force:
# kill -KILL 4436
# lsof /mnt/floppy
# umount /mnt/floppy
Managing Disk Space Usage
Monitoring and controlling disk space usage is another important part of a
system administrator’s tasks. The commands covered in this section for man-
aging disk space usage include the following:
■■ df — Shows available (free) disk space on mounted file systems
■■ du — Shows disk space usage for files, directories, and file systems
■■ edquota — Modifies user disk space quota limits
■■ quota — Displays current disk usage and disk usage limits
■■ quotaoff — Disables disk quotas on file systems
■■ quotaon — Enables disk quotas on file systems

■■ quotactl — Manages the quota system
■■ quotastats — Prints statistics about the quota system
■■ repquota — Displays a report summarizing disk quota usage
■■ setquota — Sets disk quotas
■■ quotacheck — Compares disk usage to limits set using the quota
system
CROSS-REFERENCE Implementing and using the quota subsystem is
discussed in detail in Chapter 26. Please refer to that chapter for examples and
illustrations of the quota commands introduced in this section.
The df and du commands perform complementary functions, listing detail
and summary information about the amount of disk space free and used,
respectively. df’s syntax is:
df [-ahklTmx] [-t type] [ sync| nosync] [name]
Configuring the System at the Command Line 695
36_599496 ch28.qxd 8/30/05 7:24 PM Page 695
name, which can contain multiple white space delimited values, is the name
of a file whose file system should be checked, or the file system itself (the
default is all mounted file systems). -a includes empty file systems in the dis-
play, which would ordinarily be omitted. -h uses more familiar display units,
such as GB, MB, or KB, rather than default, blocks. -k causes df to use block
sizes of 1024 bytes, and -m block sizes of 1,048,576 bytes. -l limits df’s report
to local file systems, ignoring, for example, NFS mounted file systems. -x lim-
its df’s report to the current file system or the file system to which name refers.
-t type limits the report to file systems of type, and nosync prevents df
from syncing file systems before generating its report (the default is to sync the
disks to obtain the most accurate report).
du displays information about the disk space used. Its syntax is:
du [-abcDhklmSsx] [-X file] [ exclude=path] [ max-depth=n] [name]
name, which can contain multiple white space delimited values, is the name
of a file whose file system should be checked, or the file system itself (the

default is all mounted file systems). -a displays counts for all files, not just
directories. -b prints all sizes in bytes. -c displays a grand total for names. -h
uses more familiar display units, such as GB, MB, or KB, rather than default,
blocks. -k causes df to use block sizes of 1024 bytes, and -m block sizes of
1,048,576 bytes. -l limits df’s report to local file systems, ignoring, for exam-
ple, NFS mounted file systems. If a file or directory in name includes a sym-
bolic link, -L causes it to be dereferenced to obtain the target’s disk usage,
rather than the link’s usage. -S ignores subdirectories, which are recursed by
default. -s results in a summary total for each name rather than a detailed
report for each file in name. -x limits du’s report to the current file system or
the file system to which name refers. -X file causes du to ignore any file
matching a pattern contained in file. Similarly, use exclude=pattern
to specify a single pattern to ignore. max-depth=n, finally, limits the dis-
played report to directories (or files, if all specified) within n levels of a
path specified by name (all directories and files are evaluated, but the granu-
larity of the report is limited to n levels).
Timekeeping
In most situations, maintaining the system date and time is a secondary con-
cern. In larger networks, however, particularly those with multiple servers,
synchronizing the time across the network is considerably more important.
This is especially true for file and database servers, which use finely grained
time values to govern disk writes, reads, and to maintain logs of their activity
should one or more operations need to be rolled back. This section discusses
696 Chapter 28
36_599496 ch28.qxd 8/30/05 7:24 PM Page 696
key commands for showing, setting, and maintaining the date and time on a
Red Hat system, specifically:
■■ hwclock — Displays and sets the hardware clock
■■ date — Displays and sets the system time and date
■■ rdate — Displays and sets the system clock from a network time

server
■■ ntpd — Keeps system time synced to one or more time servers
Single-Use Commands
The hwclock, date, and rdate commands are single-use commands for set-
ting the system date and time. That is, hwclock, date, and rdate have no
inherent ability to keep a system’s clock synced. Rather, you run one of them,
the time is set, and you are done. Unless executed from cron or another peri-
odic command scheduling service, none of these commands work to keep sys-
tem time accurate on an ongoing basis.
The hwclock command displays and sets the hardware clock. Its syntax is:
hwclock [-a | -r | -s | -u | -w | set date=newdate]
hwclock invoked by itself or with the -r option displays the current time,
converted to local time, as maintained by the computer’s hardware clock
(often called the RTC, or real-time clock). Specifying -w updates the hardware
clock with the system time, while -s updates the system time based on the
hardware time. The following examples first show the current system and
hardware time, then update the hardware clock to the system time using the
-w option:
# date
Thu Apr 20 09:22:48 EDT 2006
# hwclock
Thu 20 Apr 2006 09:22:49 AM EDT -0.687590 seconds
# hwclock -w
# hwclock
Thu 20 Apr 2006 09:22:56 AM EDT -0.498212 seconds
Note that after syncing the hardware clock to the system clock, the hardware
clock gained approximately 13 seconds (of course, some time elapsed while
the commands were typed). Using hwclock -w or hwclock -s in a system
initialization script (or, as you will see shortly, using rdate to sync the system
and hardware time to an external time source), enables you to maintain accu-

rate and consistent time on your Fedora Core or RHEL system.
Configuring the System at the Command Line 697
36_599496 ch28.qxd 8/30/05 7:24 PM Page 697
CAUTION Updating the system time after the system has booted could cause
unpredictable behavior. Do not use the -s option except early in the system
initialization process.
Use the -u option to tell hwclock that the time stored in the hardware clock
is maintained in UTC (Coordinated Universal Time) format, rather than in the
local time (the default). Yes, you read that correctly. The acronym almost always
appears as UTC, even though it refers to Coordinated Universal Time or Uni-
versal Coordinate Time — just another one of those little Linux/UNIX idiosyn-
crasies. The -a option enables you to adjust the hardware clock’s time to
account for systematic drift in its time. set, finally, sets the hardware clock
to the date and time specified by the newdate argument to the date option.
newdate can be any date in a format accepted by the date command. The next
example shows how to use the set argument to update the system time:
# hwclock set date=”July 8, 2006 7:24 PM”
# hwclock
Sat 08 Jul 2006 07:24:05 PM EDT 0.429153 seconds
As you will see in the discussion of the date command, you can use practi-
cally any common date and time specification to set the date using hwclock
and date.
The date command displays the current time in a specified format or sets
the system time to the specified value. Its syntax comes in two forms:
date [-d datestr] [-f datefile] [-r reffile] [+format]
date [-u] [MMDDhhmm[[CC]YY][.ss]] | -s datespec
The first form displays the time in the format specified by format subject to
modification by one of the -d, -f, -r, or -u options. By default, date prints
the current date and time, but specifying -d datestr prints the date and time
in datestr; -f datefile prints the date and time of the date strings con-

tained in the file datefile (one per line); and -f reffile prints the date
and time that reffile was last modified. The next three examples show
date’s output using these first three options.
$ date -d “July 6, 2006 11:48 AM”
Thu Jul 6 11:48:00 EDT 2006
$ cat datefile
January 1, 2010 00:01:01
December 31, 2010 11:59:59 PM
[root@luther /root]# date -f datefile
Fri Jan 1 00:01:01 MST 2010
Fri Dec 31 23:59:59 MST 2010
$ date -r /boot/vmlinuz
Sat Jul 8 18:57:28 EDT 2006
698 Chapter 28
36_599496 ch28.qxd 8/30/05 7:24 PM Page 698
Note that regardless of how the source or input date is formatted, date’s
output always has the same format. To modify the output format, use the
+format argument. Specify format using one or more of the tokens listed in
Table 28-8.
Table 28-8 Output Format Tokens for the date Command
TOKEN DESCRIPTION
%a Prints the locale’s three-letter abbreviated weekday name (Sun–Sat)
%A Prints the locale’s full weekday name (Sunday–Saturday)
%w Prints the day of the week (0–6, 0 represents Sunday)
%d Prints the day of the month (01–31)
%e Prints the blank padded day of the month (1–31)
%j Prints the day of the year (001–366)
%U Prints the week number of the year, with Sunday as the first day of
the week (00–53)
%V Prints the week number of the year, with Monday as the first day of

the week (01–52)
%W Prints the week number of the year, with Monday as the first day of
the week (00–53)
%b Prints the locale’s three-letter abbreviated month name (Jan–Dec)
%B Prints the locale’s full month name (January–December)
%m Prints the two-digit month (01–12)
%y Prints the last two digits of the year (00–99)
%Y Prints the four-digit year (1970)
%D Prints the date in US format (mm/dd/yy)
%x Prints the locale’s date representation
%S Prints the two-digit second (00–60)
%M Prints the two-digit minute (00–59)
%H Prints the two-digit hour in 24-hour format (00–23)
%I Prints the two-digit hour in 12-hour format (01–12)
%p Prints the locale’s AM or PM
%Z Prints the time zone (for example, EDT) or nothing if no time zone is
determinable
(continued)
Configuring the System at the Command Line 699
36_599496 ch28.qxd 8/30/05 7:24 PM Page 699
Table 28-8 Output Format Tokens for the date Command
TOKEN DESCRIPTION
%T Prints the 24-hour time (hh:mm:ss)
%r Prints the 12-hour time (hh:mm:ss AM|PM)
%X Prints the locale’s time representation (same as %H:%M:%S)
%c Prints the locale’s date and time (Sat Jul 08 12:02:33 EDT 2006)
%s Prints the seconds elapsed since 00:00:00, Jan 1, 1970
%% Prints a literal %
%n Prints a newline
%t Prints a horizontal tab

Here are some examples using +format. The first example prints the four-
digit year, the Julian day, the hour in 24-hour format, the minute, and the sec-
ond, separating each element with a hyphen (-). Note that characters, such as
the hyphen, that are not part of a formatting token (prefixed with %) are inter-
preted literally as part of the output.
$ date +%Y-%j-%H-%M-%S
2006-190-20-44-05
The next example mimics date’s standard output for U.S. locales. Note that
because the format string contains spaces, you have to use strong (‘) or weak
quotes (“) to prevent the shell from interpreting the spaces:
$ date +’%a %b %e %H:%M:%S %Z %Y’
Sun Jul 9 20:49:24 EDT 2006
The final example shows the current date and time using full names for the
month and day using the standard 12-hour time format:
$ date +”%A, %B %d, %Y%n%-I:%M %p”
Sunday, July 09, 2006
8:59 PM
The example also used the %n to insert a newline and the - modifier
between % and I to remove the default padding GNU date inserts into
numeric fields. Again, because the format string used spaces, the string had to
be surrounded with quotes.
700 Chapter 28
36_599496 ch28.qxd 8/30/05 7:24 PM Page 700
Use the second form of the date command to set the system date and time.
Use -u to indicate that the specified date and time are relative to Coordinated
Universal Time. The string MMDDhhmmCCYY.ss defines the time to set. The
pairs of characters, in order, mean:
■■ MM — The month
■■ DD — The day
■■ hh — The hour

■■ mm — The minute
■■ CC — The century (optional)
■■ YY — The year (optional)
■■ ss — The second (optional)
For example, to set the current system date and time to 11:59 p.m. on Decem-
ber 31, 2006, you would execute the command (as root):
# date 123123592006
Sun Dec 31 23:59:00 MST 2006
Fortunately, you can also use more familiar date and time specifications. In
fact, GNU date can interpret most commonly used date and time formats. To
use this type of syntax, use the -s option and place the date in quotes if it con-
tains embedded white space. For example, the following command sets the
current date and time to 5:55:55 a.m. on May 5, 1955:
# date -s “May 5, 1955 5:55:55 am”
Thu May 5 05:55:55 MST 1955
The next command just sets the time, leaving the date untouched:
# date -s “9:33 PM”
Thu May 5 21:33:00 MST 1955
The last example, finally, corrects the date, but, unfortunately, has the side
effect of resetting the time:
# date -s “07/08/2006”
Sat Jul 8 00:00:00 EDT 2006
The rdate command is a simple, effective way to maintain accurate system
and hardware clock time on your system. Its syntax is:
rdate [-sp] host
Configuring the System at the Command Line 701
36_599496 ch28.qxd 8/30/05 7:24 PM Page 701
host indicates the name of the network time server to contact. If -p is spec-
ified, rdate prints the time host returns and, if -s is also specified, the system
time is set to the time host returns. rdate, like hwclock, is best used during

system initialization. rdate needs network connectivity, so it must be exe-
cuted after network has started, perhaps during one of the scripts executed
when starting run level 3.
Using the Network Time Protocol
The Network Time Protocol, or NTP, is a standardized way to keep system
time synchronized across a network. NTP consists of a daemon, ntpd, a con-
figuration file, /etc/ntp.conf, and a set of supporting utilities (ntpdate,
ntpdc, ntptime, and so forth) that, working together, keep your system’s clock
set. NTP is also quite simple to use on Fedora Core and RHEL systems because
Red Hat configured it to sync against their NTP servers, clock.redhat.com.
All you have to do is start it (if it is not already started):
# service ntpd start
To make sure NTP starts at each boot, use chkconfig:
# chkconfig levels 345 ntpd on
# chkconfig levels 0126 ntpd off
Automating Scripts
Admittedly, scripts enable a greater degree of customization, flexibility, and
convenience in performing system administration tasks, but repeatedly typing
script names soon becomes just as tedious and impractical as complete com-
mand line invocations. You can use at and cron to run commands automati-
cally and unattended, enabling you to realize the full power and benefit of the
scripting administrative tasks. Use the at command to schedule scripts you
want to run later and that you want to run only once. Use the cron facility for
programs and scripts that need to run on some sort of regular schedule.
Running One-Shot Jobs with at
The at command provides an interface to the atd daemon’s scheduler. It is
the atd daemon that executes the scripts. Scheduling a job with at is surpris-
ingly simple to do: just type at followed by the time at which you want the
702 Chapter 28
36_599496 ch28.qxd 8/30/05 7:24 PM Page 702

script to run, and then press Enter. For example, the following sequence of
commands schedules the /home/kwall/bin/incrback.sh script to run at
1:05 a.m. tomorrow.
$ at 1:05
warning: commands will be executed using (in order) a) $SHELL b) login
shell c) /bin/sh
at> /home/kwall/bin/incrback.sh
at> <EOT>
job 1 at 2006-04-20 01:05
The at> prompt is a small interactive shell for scheduling commands. The
initial command, at 1:05, used the simplest possible format for specifying
the time. Table 28-9 shows additional options for indicating time to at. Once
you have the at> prompt, enter scripts and other commands just as you
would at the shell prompt. To specify multiple commands, press Enter after
each command, type the next one, press Enter, and so on. Press Ctrl+D after
you have entered all the commands you want. at responds with the <EOT>
sign and then displays a job number (1, in the example) for your commands
and the date and time (April 20, 2006 at 1:05 a.m.) the job will execute.
Table 28-9 Specifying Time with the at Command
COMMAND WHEN THE JOB RUNS
at now Executes the job immediately.
at now + 15 minutes Executes the job 15 minutes from now.
at now + 2 hours Executes the job 2 hours from now.
at now + 10 days Executes the job 10 days from now.
at noon Executes the job at noon today. If it is past noon, the
job executes tomorrow at noon.
at now next hour Executes the job 60 minutes from now.
at 15:00 tomorrow Executes the job at 3:00 p.m. tomorrow.
at 1:05am Executes the job at 1:05 a.m. today (if it is past 1:05
a.m., the job is executed tomorrow at 1:05 a.m.).

at 3:00 Aug 16, 03 At 3:00 a.m. on August 16, 2003.
To view the current list of jobs in atd’s queue, use the atq command. To
remove a job from the queue, use the atrm command. The following com-
mands show the current list of jobs using atq, and then remove them
using atrm.
Configuring the System at the Command Line 703
36_599496 ch28.qxd 8/30/05 7:24 PM Page 703
$ atq
1 2006-04-20 01:05 a kwall
2 2006-04-21 01:05 a kwall
$ atrm 1 2
The first field of atq’s output shows its job number, the same one displayed
when you submitted the job. The rest of the fields are, in order, date and time
the job will execute, the queue (a, in this case), and the user who submitted the
job. Only the root user can see all of the jobs submitted; normal users can see
only their own. Removing a job from the queue is a simple matter of typing
atrm followed by the job number of the job you want to remove, as shown in
the example.
Running Regularly Scheduled Jobs with cron
To run a script automatically at regular intervals, use the cron service. You
schedule repeating jobs using the crontab command, either by placing the
script name and scheduling information in a specially formatted file that
crontab reads, or using crontab interactively. The cron daemon, crond,
takes care of running the job and, as with at, emails its output to you.
To use cron, you need to understand the format of its job file, also called a
crontab (which should not be confused with the crontab command, although
the two are related). Each job in a crontab file is specified on a single line and
each line contains at least six fields. The first five define when the job executes,
and the sixth and subsequent fields name the script or program to run, along
with any arguments the script or program takes. For example, this line exe-

cutes the incrback.sh shell script at 1:05 a.m. each day:
05 01 * * * incrback.sh
Table 28-10 lists the meaning of the first five fields.
Table 28-10 crontab Field Values
FIELD DESCRIPTION VALID VALUES
1 Minute 0–59
2 Hour 0–23
3 Day of month 0–31
4 Month 1–12 (1 is January)
Three letter month abbreviations (Jan, Feb, Mar,
Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
5 Day of week 0–7 (0 and 7 both mean Sunday, 1 is Monday)
Three letter day abbreviations (Sun, Mon, Tue,
Wed, Thu, Fri, Sat)
704 Chapter 28
36_599496 ch28.qxd 8/30/05 7:24 PM Page 704
Entries may be single values, a comma-delimited set of values to specify
multiple days, a range of values separated by a hyphen (-), or any combina-
tion of these three options. An asterisk (*) represents all possible values for
that field. For example, an asterisk in the hour field means a job would execute
every hour of the day.
For example, to run incrback.sh at 4:55 p.m. on the 1st and 15th of Janu-
ary, March, June, and September, the crontab entry would look like one of the
following:
55 16 1,15 1,3,6,9 * incrback.sh
55 16 1,15 Jan,Mar,Jun,Sep * incrback.sh
In this case, the * in the day of the week field is ignored because it is over-
ridden by the other date and time specifications.
The easiest way to schedule a job with cron is to place the crontab entry in a
file, and then invoke the crontab command with the filename as an argument.

So, if one of the crontab entries shown previously was stored in a file named
kwall.crontab, you would submit the job using the following command:
$ crontab kwall.crontab
To verify that the job is indeed scheduled, type crontab -l to list your
crontab entries:
$ crontab -l
# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (/tmp/crontab.2433 installed on Sun Jul 9 17:48:30 2006)
# (Cron version $Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp
$)
55 16 1,15 1,4,6,9 * incrback.sh
To remove all of your cron jobs, type crontab -r. Once you become com-
fortable with the crontab format, you might find it most convenient to use
crontab’s interactive mode. To do so, type crontab -e. The interactive mode
uses the vi editor, so use vi keystrokes to enter, edit, save your changes, and, of
course, to exit the interactive mode.
Summary
In this chapter, you learned the basic commands that every system adminis-
trator must know how to use in a command line environment. You explored a
number of commands for working with users and groups, including adding
and deleting users and groups and how to modify multiple accounts simulta-
neously. You also learned how to obtain useful information about who is
Configuring the System at the Command Line 705
36_599496 ch28.qxd 8/30/05 7:24 PM Page 705
logged in and what they are doing. Managing file systems is also important,
and this chapter discussed commands for creating and checking file systems
and managing disk space usage using quotas. The process administration
commands discussed include commands for identifying which processes are
active, killing processes, and modifying running processes. You also learned
how to use at and cron to run scripts automatically, and got some final tips

and hints on writing, testing, and debugging shell scripts.
706 Chapter 28
36_599496 ch28.qxd 8/30/05 7:24 PM Page 706
707
Administering Users
and Groups
IN THIS CHAPTER
■■ Administering User Accounts
■■ Understanding the Root Account
■■ Implementing Sudo
■■ Using File System Quotas
This chapter discusses the finer points of user and group maintenance on
Fedora Core and RHEL systems. One feature of Red Hat–derived systems that
most confuses newcomers is the user private group scheme. You will also learn
how to add, modify, and delete user accounts and how to use Sudo to give nor-
mal users root capabilities on a limited and monitored basis. The final section
shows you how to implement user and group file system quotas to control and
monitor disk space usage.
Administering User Accounts
Administering users and groups, or, more precisely, administering user and
group accounts, is a fundamental Linux system administration activity. Ordi-
narily, most people understand user accounts as accounts tied to a particular
physical user. However, as you will see later in this chapter, Fedora Core or
RHEL systems also have logical user accounts, user accounts that exist for par-
ticular applications, such as MySQL, or system functions, such as the mail
and bin user accounts.
Other than this distinction between real and logical user accounts, there are
few substantive differences between actual and logical users. In particular, both
actual and logical have user identification numbers (UIDs), numeric values that
CHAPTER

29
37_599496 ch29.qxd 8/30/05 7:20 PM Page 707
the kernel and many applications use instead of the account name. Ordinarily,
each user account has a unique UID (on a given system), but this is not strictly
required.
Because properly managing user and group accounts and assigning and
revoking user and group permissions is so important on any Fedora Core or
RHEL system, this chapter spends a good deal of time examining the com-
mand line and graphical tools for doing so.
The commands covered in this section concern user and group manage-
ment. Commands used for working with users and groups fall into three
broadly defined categories: creating, modifying, and deleting user accounts;
creating, modifying, and deleting group accounts; and displaying current and
historical login and usage information.
Working with User Accounts
One of the most common administrative tasks is working with user and group
accounts. Although some administrators find the traditional command line
tools for managing users and groups tedious or inconvenient to use, this chap-
ter examines them in detail. For those readers who prefer GUI tools, the sec-
tion titled “Using the User Manager” covers the User Manager tool, a GUI
application for creating, modifying, and deleting both users and groups. Table
29-1 lists the commands for adding, modifying, and deleting user accounts.
They are discussed in detail in the following subsections.
You use the following commands most often:
■■ useradd — Create user login accounts
■■ userdel — Delete user login accounts
■■ usermod — Modify user login accounts
■■ passwd — Set or change account passwords
■■ chsh — Set or change a user’s default shell
■■ chage — Modify password expiration information

The User Database Files
To understand the following discussion, you need to know the format of the
user database files, /etc/passwd and /etc/shadow. Each line in both files
consists of colon-separated fields, one line per user. The format of the pass-
word file, /etc/passwd, is:
username:password:uid:gid:gecos:directory:shell
Table 29-1 describes the fields in /etc/passwd.
708 Chapter 29
37_599496 ch29.qxd 8/30/05 7:20 PM Page 708
Table 29-1 Fields in the Password File
FIELD DESCRIPTION
Username The user’s account name on the system
password username’s encrypted password or an x
uid username’s numeric UID (user ID)
gid username’s numeric primary group ID (group ID)
gecos An optional field used for informational purposes that usually
contains username’s full name
home username’s home directory
shell username’s login shell
On Fedora Core and RHEL systems (and almost any Linux systems these
days), the actual password is stored in /etc/shadow, indicated by an x in the
password field in /etc/passwd. Because /etc/passwd is readable by all
users, storing even encrypted passwords in it makes password guessing easier.
/etc/shadow is more secure because it is readable only by programs that run
with root privileges, such as login and passwd. The sidebar “The Shadow
Password System” discusses shadow passwords in more detail.
Strictly speaking, the shell field in /etc/passwd identifies the program
or command to run when a user logs in. If it is empty, /bin/sh is used. If it is
set to a nonexistent executable or /bin/false, the user is unable to log in. In
fact, you can use any command, program, or shell script in the shell field. For

example, you might want to create a shell script that sends email to the secu-
rity administrator if someone attempts to log in using a certain account. As
long as the script ends with a call to /bin/false (or /sbin/nologin), the
user won’t be able to log in.
An entry in /etc/passwd should resemble the following:
marysue:x:502:502:Mary Sue:/home/marysue:/bin/bash
In this entry, username is marysue; password is x, meaning it is stored in
/etc/shadow; uid is 502; gid is 502; gecos is Mary Sue; home is
/home/marysue; and shell is /bin/bash.
NOTE The gecos field is primarily of historical interest. GECOS is an acronym
meaning General Electric Comprehensive Operating System and was renamed to
GCOS when Honeywell purchased General Electric’s large systems division.
Dennis Ritchie, one of the creators of UNIX, writes of it: “Sometimes we sent
printer output or batch jobs to the GCOS machine. The gcos field in the password
file was a place to stash the information for the $IDENT card. Not elegant.”
Administering Users and Groups 709
37_599496 ch29.qxd 8/30/05 7:20 PM Page 709

×