mount’s syntax is: The -a option mounts all the file systems listed in /etc/fstab subject tothe restriction of using the -t option as explained in the previous paragraphthat are configur
Trang 1fdisk -s partition fdisk [-lu] device
The first form uses the -s option to display the size in (blocks) of the diskpartition specified by partition and then exits The second form operates onthe disk specified by device The -l option lists the disk geometry ofdevice, followed by a columnar list of each partition on device showingeach partition’s boot status, starting and ending cylinders, total size (in 512-byte blocks), and the partition type If device is omitted, fdisk lists the sameinformation based on the contents of the file /proc/partitions The -uoption instructs fdisk to show disk and partition sizes in terms sectors instead
of cylinders Omitting -l (second form) starts an interactive fdisk session ondevice
The parted program manipulates existing partitions You can use it check,create, delete, resize, move, and copy the following partition types:
parted [opts] [dev [cmd [cmd_opts]]]
To force parted to run in interactive or batch (script) mode, opts may be -i
or -s, respectively Interactive mode is the default dev can specify any blockdevice on which partitions can be created, such /dev/hdb or /dev/sdc oreven a floppy disk (/dev/fd0) The parted rubber meets the road with thecmdargument and any associated command options specified in cmd_opts.Table 28-5 lists possible parted commands
Table 28-5 GNU parted Commands COMMAND DESCRIPTION
check Checks a partition.
cp Copies the contents of one partition to another.
help Prints parted usage instructions.
mkfs Creates a file system on a partition.
Trang 2Table 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.
C A U T I O N 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, astarting and ending value, and a file system type For complete details, refer tothe parted Info page (info parted); less complete but still useful informationcan be found in the parted man page (man parted)
Creating and Manipulating File Systems
mke2fscreates 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
deviceindicates the disk partition or other device on which to create thefile system Specifying -n results in a test run; mke2fs goes through the entire
Trang 3creation process but does not actually create the file system Use -q to press output, for example, when mke2fs is used in a script Conversely, use -vto generate verbose output.
sup-To check the disk for bad blocks while creating the file system, specify -c, oruse -l list to read a list of known bad blocks from the file named list Bydefault, mke2fs calculates file system block sizes based on the size of theunderlying 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 -ibytes-per-inode(bytes-per-inode should be no smaller than the blocksize defined with -b size) -m reserve instructs mke2fs to set asidereservepercent 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 volumelabel, or name, to label
Normally, mke2fs refuses to run if device is not a block device (a disk ofsome sort) or if it is mounted; -F overrides this default -F is most commonlyused 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 toignore the block and inode information In essence, it attempts to rebuild thehigh-level file system structure without affecting the file system contents Itshould 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, andswapoffcommands mkswap initializes a swap area on a device (the usualmethod) or a file swapon enables the swap area for use, and swapoff disablesthe swap space mkswap’s syntax is:
mkswap [-c] device [size]
deviceidentifies the partition or file on which to create the swap area andsizespecifies the size, in blocks, of the swap area to create size is necessaryonly if you want a swap area smaller than the available space If device is afile, it must already exist and be sized appropriately -c performs a check forbad blocks and displays a list of any bad blocks found
T I P 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 mand Its syntax takes three forms:
Trang 4com-swapon -s swapon -a [-ev]
swapon [-p priority] [-v] device
The first form displays a summary of swap space usage for each active swapdevice The second form, normally used in system startup scripts, uses -a toactivate all swap devices listed in /etc/fstab If -e is also specified, swaponignores 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, givesdevicea higher priority in the swap system than other swap areas prioritycan be any value between 0 and 32,767 (specified as 32767), where higher val-ues represent higher priorities -v prints short status messages
e2fsckchecks a file system for possible corruption and repairs any damagefound e2fsck is an ext2- and ext3-file-system-specific version of the moregeneral fsck command Ordinarily, you will use fsck, which is a wrapperprogram that invokes a file system-specific version of fsck depending on thetype 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 invokesfsck.reiserfs
e2fsck’s syntax is:
e2fsck [-pcnyfvt] [-b sblock] [-B size] [-l list] device
deviceis the partition (/dev/hda1, for example) to test -b sblock tellse2fsckto use the backup super block located on block number sblock -Bsizespecifies block sizes of size bytes -l list instructs e2fsck to add theblock 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,e2fsckasks for confirmation before repairing file system errors; specifying -pdisables any confirmation prompts, -n automatically answers “No” to allquestions 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 systemthat is marked clean, but using -f forces it to do so -v enables verbose output.-tgenerates a timing report at the end of e2fsck’s operation
If e2fsck discovers problems with one of your file systems that it cannotrepair automatically, you might be able to use the debugfs program to repairthe file system manually
resize2fsmakes it possible to resize ext2 and ext3 file systems withoutdestroying existing data and, in certain cases, without having to use fdisk orparted to resize the partition As with parted, use resize2fs with great careand make sure you have good backups of the data on the file system youintend to resize
Trang 5The symlinks command scans directories for symbolic links, displaysthem on the screen, and repairs broken or otherwise malformed symboliclinks Its syntax is:
symlinks [-cdrstv] dirlist
dirlist is a list of one or more directories to scan for symbolic links -rcauses symlinks to recurse through subdirectories -d deletes dangling links,symbolic links whose target no longer exists -c converts absolute links, linksdefined as an absolute path from /, to relative links, links defined relative tothe 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 dowithout actually changing the file system, specify -t By default, symlinksdoes not show relative links; -v overrides this default
To make an existing file system available, it has to be mounted using themountcommand mount’s syntax is:
The -a option mounts all the file systems listed in /etc/fstab (subject tothe 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 -ofsoptions, listed in /etc/fstab Note that you only have to specifydevice, the device containing the file system, or dir, where in the directoryhierarchy the file system should be attached
Use the third form to mount file systems not listed in /etc/fstab or tooverride 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 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.fsoptionsis a comma-delimited list of one or more of the options listed inTable 28-7
Trang 6hier-N OT E 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)
Trang 7Table 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 muchsimpler, 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 dofor mount, except for -r Of course, the options must be understood in thecontext of unmounting a file system If -r is specified and unmounting a filesystem fails for some reason, umount attempts to mount it in read-only mode
To access swap space, use theswapon and swapoff commands To enablethe kernel to use swap devices and files, use the swapon command Its syntaxtakes three forms:
swapon -s swapon -a [-ev]
swapon [-p priority] [-v] device
Trang 8The first form displays a summary of swap space usage for each active swapdevice The second form, normally used in system startup scripts, uses -a toactivate all swap devices listed in /etc/fstab If -e is also specified, swaponignores devices listed in /etc/fstab that do not exist The third form activatesthe 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 beany 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 aspecific swap area Multiple swap areas may be specified using white spacebetween 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 processHere 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
Trang 9cur-chmodhas two forms because it understands both symbolic and octal tion for file permissions For both forms, file is one or more files on whichpermissions are being changed symbolic_mode uses the symbolic permis-sions notation, while octal_mode expresses the permissions being set usingthe standard octal notation.
nota-C R O S S - R E F E R E N nota-C E 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 beingassigned to file For the chown command, owner identifies the new userbeing assigned as file’s owner The colon (:) enables chmod to changefile’s group ownership The format owner:group changes file’s user andgroup owners to owner and group, respectively The format owner: changesonly file’s owner and is equivalent to chown owner file The format:group leaves the owner untouched but changes file’s group owner togroup(equivalent to chgrp group file)
The lsattr and chattr commands are Linux-specific, providing an 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’ssyntax is:
inter-lsattr [-adRVv] file
fileis the file or directory whose attributes you want to display; multiplewhite 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
fileis the file or directory whose attributes you want to display; multiplewhite space separated file arguments may be specified -R causes lsattr torecurse through subdirectories if file names a subdirectory -v version sets
a version or generation number for file +mode adds mode to file’s attributes;-moderemoves mode from file’s attributes; =mode sets file’s attributes tomode, 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
Trang 10■■ 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 deletedThe stat command displays detailed file or file system status information.Its syntax is:
stat [-l] [-f] [-t] file
filespecifies the file or directory about which you want information Usemultiple white-space-delimited file arguments to specify multiple files If -l isused and file is a link, stat operates on the link’s target (the file that islinked) rather than the link itself Using -f causes stat to display informationabout 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 afile or socket fuser provides this functionality Its syntax is:
fuser [-a | -s] [-n namespace] [-signal] [-kimuv] name
namespecifies the file, file system, or socket to query By default, fuserassumes that name is a filename To query TCP or UDP sockets, use -nnamespace, where namespace is udp for UDP sockets and tcp for TCPsockets (file is the default namespace) -a results in a report for all namesspecified on the command line, even if they are not being accessed by anyprocess -s, on the other hand, causes fuser to run silently You cannot use -swith -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 beprompted for confirmation before killing a process Only use -i with -k -mindicates that name specifies a file system or block device, so fuser lists allprocesses 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)
Trang 11This command used the -u option to display the username (root) runningthe 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
lsofperforms 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]
filespecifies the file or file systems (multiple file arguments are ted) to scan Specifying -c c selects processes executing a command thatbegins with the letter c -f causes file to be interpreted as a file or pathname,+fas a file system name -L suppresses displaying the count of files linked tofile -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 repeatthe display every 15 seconds (or t seconds if t is specified) until none of theselected 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
permit-One of the most common uses of lsof is to find out what file (or files) arepreventing 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 stillopen 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 ismounted on the file system /mnt/floppy:
Now, you can use the kill command to kill the processes that are keepingyou from unmounting /mnt/floppy:
Trang 12Managing Disk Space Usage
Monitoring and controlling disk space usage is another important part of asystem 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
C R O S S - R E F E R E N C E 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 detailand summary information about the amount of disk space free and used,respectively df’s syntax is:
df [-ahklTmx] [-t type] [ sync| nosync] [name]
Trang 13name, 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 (thedefault 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 blocksizes 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 its df’s report to the current file system or the file system to which name refers.-t typelimits the report to file systems of type, and nosync prevents dffrom syncing file systems before generating its report (the default is to sync thedisks to obtain the most accurate report)
lim-dudisplays 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 (thedefault is all mounted file systems) -a displays counts for all files, not justdirectories -b prints all sizes in bytes -c displays a grand total for names -huses 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 of1,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 bydefault -s results in a summary total for each name rather than a detailedreport for each file in name -x limits du’s report to the current file system orthe file system to which name refers -X file causes du to ignore any filematching a pattern contained in file Similarly, use exclude=pattern
to specify a single pattern to ignore max-depth=n, finally, limits the played report to directories (or files, if all specified) within n levels of apath specified by name (all directories and files are evaluated, but the granu-larity of the report is limited to n levels)
dis-Timekeeping
In most situations, maintaining the system date and time is a secondary 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 grainedtime values to govern disk writes, reads, and to maintain logs of their activityshould one or more operations need to be rolled back This section discusses
Trang 14con-key commands for showing, setting, and maintaining the date and time on aRed 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 timeserver
■■ 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 ting the system date and time That is, hwclock, date, and rdate have noinherent 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
set-The hwclock command displays and sets the hardware clock Its syntax is:
hwclock [-a | -r | -s | -u | -w | set date=newdate]
hwclockinvoked 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 hardwareclock with the system time, while -s updates the system time based on thehardware time The following examples first show the current system andhardware time, then update the hardware clock to the system time using the -woption:
Thu 20 Apr 2006 09:22:56 AM EDT -0.498212 seconds
Note that after syncing the hardware clock to the system clock, the hardwareclock gained approximately 13 seconds (of course, some time elapsed whilethe commands were typed) Using hwclock -w or hwclock -s in a systeminitialization script (or, as you will see shortly, using rdate to sync the systemand hardware time to an external time source), enables you to maintain accu-rate and consistent time on your Fedora Core or RHEL system
Trang 15C A U T I O N 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 thelocal time (the default) Yes, you read that correctly The acronym almost alwaysappears 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 toaccount 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.newdatecan be any date in a format accepted by the date command The nextexample 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 cally any common date and time specification to set the date using hwclockand date
practi-The date command displays the current time in a specified format or setsthe 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 tomodification by one of the -d, -f, -r, or -u options By default, date printsthe 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 tained in the file datefile (one per line); and -f reffile prints the dateand time that reffile was last modified The next three examples showdate’s output using these first three options
con-$ 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