Introducing Basic System Administration - Administration - Linux All-in-One For Dummies, 5th Edition (2014)

Linux All-in-One For Dummies, 5th Edition (2014)

Book V. Administration

 width=

webextras.eps Visit www.dummies.com/extras/linuxaio for great Dummies content online.

Contents at a Glance

Chapter 1: Introducing Basic System Administration

Chapter 2: Managing Users and Groups

Chapter 3: Managing File Systems

Chapter 4: Working with Samba and NFS

Chapter 1. Introducing Basic System Administration

In This Chapter

arrow Introducing the GUI sysadmin tools

arrow Becoming root

arrow Understanding the system startup process

arrow Taking stock of the system configuration files

arrow Viewing system information through the /proc file system

arrow Monitoring system performance

arrow Managing devices

arrow Scheduling jobs

System administration, or sysadmin, refers to whatever has to be done to keep a computer system up and running. The system administrator (the sysadmin) is whoever is in charge of taking care of these tasks.

If you’re running Linux at home or in a small office, you’re most likely the system administrator for your systems. Or maybe you’re the system administrator for an entire LAN full of Linux systems. Regardless of your position or title, this chapter will introduce you to basic system administration procedures and show you how to perform some common tasks.

Taking Stock of System Administration Tasks

So what are system administration tasks? An off-the-cuff reply is anything you have to do to keep the system running well. More accurately, though, a system administrator’s duties include

· Adding and removing user accounts: You have to add new user accounts and remove unnecessary user accounts. If a user forgets the password, you have to change the password.

· Managing the printing system: You have to turn the print queue on or off, check the print queue’s status, and delete print jobs if necessary.

· Installing, configuring, and upgrading the operating system and various utilities: You have to install or upgrade parts of the Linux operating system and other software that are part of the operating system.

· Installing new software: You have to install software that comes in various package formats, such as RPM or DEB. You also have to download and unpack software that comes in source-code form — and then build executable programs from the source code.

· Managing hardware: Sometimes you have to add new hardware and install drivers so the devices work properly.

· Making backups: You have to back up files, whether to a DVD drive, a USB memory stick, an external hard drive, or tape.

· Mounting and unmounting file systems: When you want to access the files on a CD-ROM, for example, you have to mount that CD-ROM’s file system on one of the directories in your Linux file system. You may also have to mount old floppy disks from the archive closet, in both Linux format and DOS format.

· Automating tasks: You have to schedule Linux tasks to take place automatically (at specific times) or periodically (at regular intervals).

· Monitoring the system’s performance: You may want to keep an eye on system performance to see where the processor is spending most of its time and to see the amount of free and used memory in the system.

· Starting and shutting down the system: Although starting the system typically involves nothing more than powering up the PC, you do have to take some care when you shut down your Linux system. If your system is set up for a graphical login screen, you can perform the shutdown operation by choosing a menu item from the login screen. Otherwise, use the shutdown command to stop all programs before turning off your PC’s power switch.

· Monitoring network status: If you have a network presence (whether a LAN, a DSL line, or a cable modem connection), you may want to check the status of various network interfaces and make sure your network connection is up and running.

· Setting up host and network security: You have to make sure that system files are protected and that your system can defend itself against attacks over the network.

· Monitoring security: You have to keep an eye on any intrusions, usually by checking the log files.

That’s a long list of tasks! Not all these items are covered in this chapter, but the rest of this minibook describes most of these tasks. The focus in this chapter is on some of the basics, such as using the GUI tools, explaining how to become root (the superuser), describing the system configuration files, and showing you how to monitor system performance, manage devices, and set up periodic jobs.

Introducing Some GUI Sysadmin Tools

Each Linux distribution comes with GUI tools for performing system administration tasks. The GUI tools prompt you for input and then run the necessary Linux commands to perform the task. Although there are slight differences among them, the tools have become more and more uniform as time has passed.

For example, Figure 1-1 shows the YaST Control Center available in SUSE, and Figure 1-2 shows the System Settings interface in Ubuntu. Aside from YaST having more options, you should notice that there is great similarity between the interfaces.

Figure 1-1: YaST Control Center is your starting point for many sysadmin tasks in SUSE.

The left side of the YaST Control Center shows icons for the categories of tasks you can perform. The right side shows icons for specific tasks in the currently selected category. When you click an icon on the right side of the YaST Control Center, a new YaST window appears and enables you to perform that task.

As you can see from the entries in the YaST Control Center, it is truly meant to be a one-stop-shopping spot for all your sysadmin chores.

Figure 1-3 shows the Settings interface in Fedora and you can see that while the icons differ a bit from those found in the other distributions, most of the major chores an administrator deals with are capable of being addressed from here.

Figure 1-2: The Settings interface in Ubuntu offers many tools similar to those in YaST.

Figure 1-3: The Settings interface in Fedora differs a bit from Ubuntu.

Since YaST is the most complete of the lot, Table 1-1 lists the common tasks found in the Control Center.

Table 1-1 Tasks by Category in the YaST Control Center

This Category

Enables You to Configure or Manage the Following

Software

Online Update, Installation Source, Installation in Xen Environment, Installation into Directory, Media Check, Patch CD Update, Software Management, System Update

Hardware

Bluetooth, CD-ROM Drives, Disk Controller, Graphics Card and Monitor, Hardware Information, IDE DMA Mode, Infrared Device, Joystick, Keyboard Layout, Mouse Model, Printer, Scanner, Sound, TV Card

System

/etc/sysconfig Editor, Boot Loader Configuration, Boot or Rescue, Date and Time, LVM, Language, PCI Device Drivers, Partitioner, Power Management, Powertweak, Profile Manager, System Backup, System Restoration, System Services (run level)

Network Devices

DSL, Fax, ISDN, Modem, Network Card, Phone Answering Machine

Network Services

DHCP Server, DNS Server, DNS Host and Name, HTTP Server, Host Names, Kerberos Client, LDAP Client, Mail Transfer Agent, NFS Client, NFS Server, NIS Client, NIS Server, NTP Client, Network Services (xinetd), Proxy, Remote Administration, Routing, SLP Browser, Samba Client, Samba Server, TFTP Server

Security and Users

Firewall, Group Management, Local Security, User Management

Support

Where you can find documentation and help resources

Miscellaneous

Autoinstallation, Post a Support Query, Vendor Driver CD, View Start-up Log, View System Log

How to Become root

You have to log in as root to perform system administration tasks. The root user is the superuser and the only account with all the privileges needed to do anything in the system.

Common wisdom says you should not normally log in as root. When you’re root, you can easily delete all the files with one misstep — especially when you’re typing commands. For example, you type the command rm *.html to delete all files that have the .html extension. But what if you accidentally press the spacebar after the asterisk (*)? The shell takes the command to be rm * .html and — because * matches any filename — deletes everything in the current directory. Seems implausible until it happens to you!

Using the su - command

If you’re logged in as a normal user, how do you do any system administration chores? Well, you become root for the time being. If you’re working at a terminal window or console, type

su -

Then enter the root password in response to the prompt. From this point, you’re root. Do whatever you have to do. To return to your usual self, type

exit

That’s it! It’s that easy.

 width= By the way, Knoppix has a root user but doesn’t have a root password, so you can become root by simply typing su - at the shell prompt in a terminal window. Also, Ubuntu doesn’t have a root user. To perform any task that requires root privileges in Ubuntu, you must type sudo followed by the command and then provide your normal user password when prompted.

In the Security minibook, the issue will be addressed more, but you can control who can use sudo through configuration files (or the YaST interface, as Figure 1-4 shows).

Figure 1-4: Configuring who can use sudo.

Becoming root for the GUI utilities

Most Linux distributions include GUI utilities to perform system administration chores. If you use any of these GUI utilities to perform a task that requires you to be root, the utility typically pops up a dialog box that prompts you for the root password, as shown in Figure 1-5 (except in Ubuntu, where the GUI tools prompt for your normal user password). Just type the password and press Enter. If you don’t want to use the utility, click Cancel.

Figure 1-5: Type the root password and press Enter to gain root privileges.

Recovering from a forgotten root password

To perform system administration tasks, you have to know the root password. What happens if you forget the root password? Not to worry. You can reset the root password by following these steps:

1. Reboot the PC (select Reboot as you log out of the GUI screen) or power up as usual.

As soon you see the graphical GRUB boot loader screen that shows the names of the operating systems, you can boot. If your system runs the LILO boot loader, press Ctrl+X, type linux single at the boot: prompt, and press Enter. Then proceed to Step 4. If you don’t see the graphical loader screen on reboot, it might not be installed (which can occasionally occur when choosing to install from a Live CD). If this is the case, it is recommended that you reinstall from the CD.

2. If you have more than one operating system installed, use the arrow key to select Linux as your operating system and then press the A key.

GRUB prompts you for commands to add to its default boot command.

3. Press the spacebar, and then type single and press Enter.

Linux starts as usual but runs in a single-user mode that doesn’t require you to log in. After Linux starts, you see the following command-line prompt similar to the following:

sh-3.00#

4. Type the passwd command to change the root password as follows:

sh-3.00# passwd
Changing password for user root.
New password:

5. Type the new root password that you want to use (it doesn’t appear onscreen) and then press Enter.

Linux asks for the password again, like this:

Retype new password:

6. Type the password again and press Enter.

If you enter the same password both times, the passwd command changes the root password.

7. Now type reboot and press Enter to reboot the PC.

After Linux starts, it displays the familiar login screen. Now you can log in as root with the new password.

 width= In SUSE Linux, in Step 3, type single init=/bin/sh (instead of single) and before proceeding to Step 4, at the command-line prompt, type mount / -n -0 remount,rw. Then perform Steps 4 through 6 to change the root password. After changing the password, type mount / -n -o remount,ro. Then continue to Step 7 and reboot the PC.

warning.eps Make sure that your Linux PC is physically secure. As these steps show, anyone who can physically access your Linux PC can simply reboot, set a new root password, and do whatever he or she wants with the system. Another way to protect against resetting the password is to set a GRUB password, which causes GRUB to require a valid password before it boots Linux. Of course, you must then remember to enter the GRUB password every time you boot your system!

Understanding How Linux Boots

Knowing the sequence in which Linux starts processes as it boots is important. You can use this knowledge to start and stop services, such as the web server and Network File System (NFS). The next few sections provide you with an overview of how Linux boots and starts the initial set of processes. These sections also familiarize you with the shell scripts that start various services on a Linux system.

Understanding the init process

When Linux boots, it loads and runs the core operating system program from the hard drive. The core operating system is designed to run other programs. A process named init starts the initial set of processes on your Linux system.

To see the processes currently running on the system, type

ps ax | more

You get an output listing that starts like this:

PID TTY STAT TIME COMMAND
1 ? S 0:22 init [2]

The first column, with the heading PID, shows a number for each process. PID stands for process ID (identification) — a sequential number assigned by the Linux kernel. The first entry in the process list, with a PID of 1, is the init process. It’s the first process, and it starts all other processes in your Linux system. That’s why init is sometimes referred to as the mother of all processes.

What the init process starts depends on

· The run level, an identifier that identifies a system configuration in which only a selected group of processes can exist.

· The contents of the /etc/inittab file, a text file that specifies which processes to start at different run levels.

· A number of shell scripts that are executed at specific run levels. (The scripts are located in the /etc/init.d directory and a number of subdirectories in /etc — these subdirectories have names that begin with rc.)

 width= Most Linux distributions use seven run levels — 0 through 6. The meaning of the run levels differs from one distribution to another. Table 1-2 shows the meanings of the run levels and points out some of the actions specific to Fedora, Debian, SUSE, Ubuntu, and Xandros.

Table 1-2 Run Levels in Linux

Run Level

Meaning

0

Shut down the system.

1

Run in single-user standalone mode (no one else can log in; you work at the text console).

2

Run in multiuser mode (Debian, Ubuntu, and Xandros use run level 2 as the default run level).

3

Run in full multiuser mode (used for text mode login in Fedora and SUSE).

4

Run in full multiuser mode (unused in Fedora and SUSE).

5

Run in full multiuser mode (used as the default run level with graphical login in Fedora and SUSE).

6

Reboot the system.

 width= The current run level together with the contents of the /etc/inittab file control which processes init starts in Linux. The default run level is 2 in Debian, Ubuntu, and Xandros. In Fedora and SUSE, run level 3 is used for text mode login screens and 5 for the graphical login screen. You can change the default run level by editing a line in the /etc/inittab file.

To check the current run level, type the following command in a terminal window:

/sbin/runlevel

In Debian, the runlevel command prints an output like this:

N 2

The first character of the output shows the previous run level (N means no previous run level), and the second character shows the current run level (2). In this case, the system started at run level 2. If you’re in a GUI desktop in Fedora, the runlevel command should show 5 as the current run level.

Examining the /etc/inittab file

The /etc/inittab file is the key to understanding the processes that init starts at various run levels. You can look at the contents of the file by using the more command, as follows:

more /etc/inittab

remember.eps To see the contents of the /etc/inittab file with the more command, you don’t have to log in as root.

To interpret the contents of the /etc/inittab file, follow these steps:

1. Look for the line that contains the phrase initdefault.

Here’s that line from the /etc/inittab file from a Debian system:

id:2:initdefault:

That line shows the default run level. In this case, it’s 2.

2. Find all the lines that specify what init runs at run level 2.

Look for a line that has a 2 between the first two colons (:). Here’s a relevant line in Debian:

l2:2:wait:/etc/init.d/rc 2

This line specifies that init executes the file /etc/init.d/rc with 2 as an argument.

If you look at the file /etc/init.d/rc in a Debian system, you find it’s a shell script. You can study this file to see how it starts various processes for run levels 1 through 5.

technicalstuff.eps Each entry in the /etc/inittab file tells init what to do at one or more run levels — you simply list all run levels at which the process runs. Each inittab entry has four fields — separated by colons — in the following format:

id:runlevels:action:process

Table 1-3 shows what each field means.

Table 1-3 Fields in Each inittab Entry

Field

Meaning

id

A unique one- or two-character identifier. The init process uses this field internally. You can use any identifier you want, as long as you don’t use the same identifier on more than one line.

runlevels

A sequence of zero or more characters, each denoting a run level. For example, if the runlevels field is 12345, that entry applies to each of the run levels 1 through 5. This field is ignored if the action field is set to sysinit, boot, or bootwait.

action

What the init process will do with this entry. If this field is initdefault, for example, init interprets the runlevels field as the default run level. If this field is set to wait, init starts the program or script specified in the process field and waits until that process exits.

process

Name of the script or program that init starts. Some settings of the action field require no process field. For example, when the action field is initdefault, there’s no need for a process field.

Trying a new run level with the init command

To try a new run level, you don’t have to change the default run level in the /etc/inittab file. If you log in as root, you can change the run level (and, consequently, the processes that run in Linux) by typing init followed by the run level.

For example, to put the system in single-user mode, type the following:

init 1

Thus, if you want to try run level 3 without changing the default run level in /etc/inittab file, enter the following command at the shell prompt:

init 3

The system ends all current processes and enters run level 3. By default, the init command waits 20 seconds before stopping all current processes and starting the new processes for run level 3.

tip.eps To switch to run level 3 immediately, type the command init -t0 3. The number after the -t option indicates the number of seconds init waits before changing the run level.

You can also use the telinit command, which is simply a symbolic link (a shortcut) to init. If you make changes to the /etc/inittab file and want init to reload its configuration file, use the command telinit q.

Understanding the Linux startup scripts

The init process runs a number of scripts at system startup. In the following discussions, a Debian system is used as an example, but the basic sequence is similar in other distributions — only the names and locations of the scripts may vary.

 width= If you look at the /etc/inittab file in a Debian system, you find the following lines near the beginning of the file:

# Boot-time system configuration/initialization script.
si::sysinit:/etc/init.d/rcS

The first line is a comment line. The second line causes init to run the /etc/init.d/rcS script — the first Linux startup script that init runs in a Debian system. The rcS script performs many initialization tasks, such as mounting the file systems, setting the clock, configuring the keyboard layout, starting the network, and loading many other driver modules. The rcS script performs these initialization tasks by calling many other scripts and reading configuration files located in the /etc/rcS.d directory.

After executing the /etc/init.d/rcS script, the init process runs the /etc/init.d/rc script with the run level as an argument. For example, for run level 2, the following line in /etc/inittab specifies what init executes:

l2:2:wait:/etc/init.d/rc 2

This example says init executes the command /etc/init.d/rc 2 and waits until that command completes.

The /etc/init.d/rc script is somewhat complicated. Here’s how it works:

· It executes scripts in a directory corresponding to the run level. For example, for run level 2, the /etc/init.d/rc script runs the scripts in the /etc/rc2.d directory.

· In the directory that corresponds with the run level, /etc/init.d/rc looks for all files that begin with K and executes each of them with the stop argument. This argument kills any currently running processes. Then it locates all files that begin with S and executes each file with a start argument. This argument starts the processes needed for the specified run level.

To see it executed at run level 2, type the following command:

ls -l /etc/rc2.d

In the resulting listing, the K scripts — the files whose names begin with K — stop (or kill) servers, whereas the S scripts start servers. The /etc/init.d/rc script executes these files in the order in which they appear in the directory listing.

Manually starting and stopping servers

In Linux, the server startup scripts reside in the /etc/init.d directory. You can manually invoke scripts in this directory to start, stop, or restart specific processes — usually servers. For example, to stop the FTP server (the server program is vsftpd), type the following command:

/etc/init.d/vsftpd stop

If vsftpd is already running and you want to restart it, type the following command:

/etc/init.d/vsftpd restart

You can enhance your system administration skills by familiarizing yourself with the scripts in the /etc/init.d directory. To see its listing, type the following command:

ls /etc/init.d

The script names give you some clue about which server the script can start and stop. For example, the samba script starts and stops the processes required for Samba Windows networking services. At your leisure, you may want to study some of these scripts to see what each one does. You don’t have to understand all the shell programming; the comments help you discover the purpose of each script.

Automatically starting servers at system startup

You want some servers to start automatically every time you boot the system. The exact commands to configure the servers vary from one distribution to another.

 width= In Fedora and SUSE, use the chkconfig command to set up a server to start whenever the system boots into a specific run level. For example, if you start the SSH server, you want the sshd server to start whenever the system starts. You can make that happen by using thechkconfig command. To set sshd to start whenever the system boots into run level 3, 4, or 5, type the following command (while logged in as root):

chkconfig --level 345 sshd on

 width= In Fedora and SUSE, you can also use the chkconfig command to check which servers are turned on or off. For example, to see the complete list of all servers for all run levels, type the following command:

chkconfig --list

 width= In Debian, Ubuntu, and Xandros, you can use the update-rc.d command to enable a server to start automatically at system startup. For example, to set sshd to start automatically at the default run levels, type update-rc.d sshd defaults in a terminal window while logged in as root. You can also specify the exact run levels and the sequence number (the order in which each server starts). To find out more about the update-rc.d command, type man update-rc.d in a terminal window.

Taking Stock of Linux System Configuration Files

Linux includes a host of configuration files. All these files share text files that you can edit with any text editor. To edit these configuration files, you must log in as root. A selection of the most popular configuration files appears in Table 1-4, along with a brief description of each. This table gives you an idea of what types of configuration files a system administrator has to work with. In many cases, Linux includes GUI utility programs to set up many of these configuration files.

Table 1-4 Some Linux Configuration Files

Configuration File

Description

/boot/grub

Location of files for the GRUB boot loader.

/boot/grub/menu.lst

Configuration file for the boot menu that GRUB displays before it boots your system.

/boot/System.map

Map of the Linux kernel (maps kernel addresses into names of functions and variables).

/boot/vmlinuz

The Linux kernel (the operating system’s core).

/etc/apache2/httpd.conf

Configuration file for the Apache web server (Debian).

/etc/apt/sources.list

Configuration file that lists the sources — FTP or websites or CD-ROM — from which the Advanced Packaging Tool (APT) obtains packages (Debian, Ubuntu, and Xandros).

/etc/at.allow

Usernames of users allowed to use the at command to schedule jobs for later execution.

/etc/at.deny

Usernames of users forbidden to use the at command.

/etc/bashrc

System-wide functions and aliases for the bash shell (Fedora).

/etc/bash.bashrc

System-wide functions and aliases for the bash shell (Debian, SUSE, Ubuntu, and Xandros).

/etc/cups/cupsd.conf

Printer configuration file for the Common Unix Printing System (CUPS) scheduler.

/etc/fonts

Directory with font configuration files. (In particular, you can put local font configuration settings in the file /etc/fonts/local.conf.)

/etc/fstab

Information about file systems available for mounting and where each file system is to be mounted.

/etc/group

Information about groups.

/etc/grub.conf

The configuration for the GRUB boot loader in Fedora and SUSE.

/etc/hosts

List of IP numbers and their corresponding hostnames.

/etc/hosts.allow

Hosts allowed to access Internet services on this system.

/etc/hosts.deny

Hosts forbidden to access Internet services on this system.

/etc/httpd/conf/httpd.conf

Configuration file for the Apache web server (Fedora).

/etc/init.d

Directory with scripts to start and stop various servers.

/etc/inittab

Configuration file used by the init process that starts all the other processes.

/etc/issue

File containing a message to be printed before displaying the text mode login prompt (usually the distribution name and the version number).

/etc/lilo.conf

The configuration for the Linux Loader (LILO) — one of the boot loaders that can load the operating system from disk (present only if you use the LILO boot loader).

/etc/login.defs

Default information for creating user accounts, used by the useradd command.

/etc/modprobe.conf

Configuration file for loadable kernel modules, used by the modprobe command (Fedora and SUSE).

/etc/modules.conf

Configuration file for loadable modules (Debian and Xandros).

/etc/mtab

Information about currently mounted file systems.

/etc/passwd

Information about all user accounts. (Actual passwords are stored in /etc/shadow.)

/etc/profile

System-wide environment and startup file for the bash shell.

/etc/profile.d

Directory containing script files (with names that end in .sh) that the /etc/profile script executes.

/etc/init.d/rcS

Linux initialization script in Debian, SUSE, Ubuntu, and Xandros.

/etc/rc.d/rc.sysinit

Linux initialization script in Fedora.

/etc/shadow

Secure file with encrypted passwords for all user accounts (can be read by only root).

/etc/shells

List of all the shells on the system that the user can use.

/etc/skel

Directory that holds initial versions of files such as .bash_profile that copy to a new user’s home directory.

/etc/sysconfig

Linux configuration files (Fedora and SUSE).

/etc/sysctl.conf

Configuration file with kernel parameters that are read in and set by sysctl at system startup.

/etc/termcap

Database of terminal capabilities and options (Fedora and SUSE).

/etc/udev

Directory containing configuration files for udev — the program that provides the ability to dynamically name hot-pluggable devices and create device files in the /dev directory.

/etc/X11

Directory with configuration files for the X Window System (X11) and various display managers such as gdm and xdm.

/etc/X11/xorg.conf

Configuration file for X.Org X11 — the X Window System (Fedora, Ubuntu, and SUSE).

/etc/xinetd.conf

Configuration for the xinetd daemon that starts a number of Internet services on demand.

/etc/yum.conf

Configuration for the Yum package updater and installer (Fedora).

/var/log/apache2

Web server access and error logs (Debian).

/var/log/cron

Log file with messages from the cron process that runs scheduled jobs.

/var/log/boot.msg

File with boot messages (SUSE).

/var/log/dmesg

File with boot messages (Debian, Fedora, Ubuntu, and Xandros).

/var/log/httpd

Web server access and error logs (Fedora).

/var/log/messages

System log.

Monitoring System Performance

When you’re the system administrator, you must keep an eye on how well your Linux system is performing. You can monitor the overall performance of your system by looking at information such as

· Central processing unit (CPU) usage

· Physical memory usage

· Virtual memory (swap-space) usage

· Hard drive usage

Linux comes with a number of utilities that you can use to monitor one or more of these performance parameters. The following sections introduce a few of these utilities and show you how to understand the information presented by said utilities.

Using the top utility

To view the top CPU processes — the ones that use most of the CPU time — you can use the text mode top utility. To start that utility, type top in a terminal window (or text console). The top utility then displays a text screen listing the current processes, arranged in the order of CPU usage, along with various other information, such as memory and swap-space usage. Figure 1-6 shows a typical output from the top utility.

Figure 1-6: You can see the top CPU processes by using the top utility.

tip.eps The top utility updates the display every five seconds. If you keep top running in a window, you can continually monitor the status of your Linux system. To quit top, press Q or Ctrl+C or close the terminal window.

The first five lines of the output screen (see Figure 1-6) provide summary information about the system, as follows:

· The first line shows the current time, how long the system has been up, how many users are logged in, and three load averages — the average number of processes ready to run during the last 1, 5, and 15 minutes.

· The second line lists the total number of processes and the status of these processes.

· The third line shows CPU usage — what percentage of CPU time is used by user processes, what percentage by system (kernel) processes, and during what percentage of time the CPU is idle.

· The fourth line shows how the physical memory is being used — the total amount, how much is used, how much is free, and how much is allocated to buffers (for reading from the hard drive, for example).

· The fifth line shows how the virtual memory (or swap space) is being used — the total amount of swap space, how much is used, how much is free, and how much is being cached.

The table that appears below the summary information (refer to Figure 1-6) lists information about the current processes, arranged in decreasing order by amount of CPU time used. Table 1-5 summarizes the meanings of the column headings in the table that top displays.

Table 1-5 Column Headings in top Utility’s Output

Heading

Meaning

PID

Process ID of the process.

USER

Username under which the process is running.

PR

Priority of the process.

NI

Nice value of the process — the value ranges from –20 (highest priority) to 19 (lowest priority) and the default is 0. (The nice value represents the relative priority of the process: The higher the value, the lower the priority and the nicer the process because it yields to other processes.)

VIRT

Total amount of virtual memory used by the process, in kilobytes.

RES

Total physical memory used by a task (typically shown in kilobytes, but an m suffix indicates megabytes).

SHR

Amount of shared memory used by process.

S

State of the process (S for sleeping, D for uninterruptible sleep, R for running, Z for zombies — processes that should be dead but are still running — or T for stopped).

%CPU

Percentage of CPU time used since last screen update.

%MEM

Percentage of physical memory used by the process.

TIME+

Total CPU time the process has used since it started.

COMMAND

Shortened form of the command that started the process.

Using the uptime command

You can use the uptime command to get a summary of the system’s state. Just type the command like this:

uptime

It displays output similar to the following:

15:03:21 up 32 days, 57 min, 3 users, load average: 0.13, 0.23, 0.27

This output shows the current time, how long the system has been up, the number of users, and (finally) the three load averages — the average number of processes that were ready to run in the past 1, 5, and 15 minutes. Load averages greater than 1 imply that many processes are competing for CPU time simultaneously.

The load averages give you an indication of how busy the system is.

Using the vmstat utility

You can get summary information about the overall system usage with the vmstat utility. To view system usage information averaged over 5-second intervals, type the following command (the second argument indicates the total number of lines of output vmstat displays):

vmstat 5 8

You see output similar to the following listing:

procs -----------memory---------- ---swap-- -----io---- --system-- ----cpu----
r b swpd free buff cache si so bi bo in cs us sy id wa
0 0 31324 4016 18568 136004 1 1 17 16 8 110 33 4 61 1
0 1 31324 2520 15348 139692 0 0 7798 199 1157 377 8 8 6 78
1 0 31324 1584 12936 141480 0 19 5784 105 1099 437 12 5 0 82
2 0 31324 1928 13004 137136 7 0 1586 138 1104 561 43 6 0 51
3 1 31324 1484 13148 132064 0 0 1260 51 1080 427 50 5 0 46
0 0 31324 1804 13240 127976 0 0 1126 46 1082 782 19 5 47 30
0 0 31324 1900 13240 127976 0 0 0 0 1010 211 3 1 96 0
0 0 31324 1916 13248 127976 0 0 0 10 1015 224 3 2 95 0

The first line of output shows the averages since the last reboot. After that, vmstat displays the 5-second average data seven more times, covering the next 35 seconds. The tabular output is grouped as six categories of information, indicated by the fields in the first line of output. The second line shows further details for each of the six major fields. You can interpret these fields by using Table 1-6.

Table 1-6 Meaning of Fields in the vmstat Utility’s Output

Field Name

Description

procs

Number of processes and their types: r = processes waiting to run, b = processes in uninterruptible sleep, w = processes swapped out but ready to run.

memory

Information about physical memory and swap-space usage (all numbers in kilobytes): swpd = virtual memory used, free = free physical memory, buff = memory used as buffers, cache = virtual memory that’s cached.

swap

Amount of swapping (the numbers are in kilobytes per second): si = amount of memory swapped in from disk, so = amount of memory swapped to disk.

io

Information about input and output. (The numbers are in blocks per second, where the block size depends on the disk device.) bi = rate of blocks sent to disk, bo = rate of blocks received from disk.

system

Information about the system: in = number of interrupts per second (including clock interrupts), cs = number of context switches per second — how many times the kernel changed which process was running.

cpu

Percentages of CPU time used: us = percentage of CPU time used by user processes, sy = percentage of CPU time used by system processes, id = percentage of time CPU is idle, wa = time spent waiting for input or output (I/O).

technicalstuff.eps In the vmstat utility’s output, high values in the si and so fields indicate too much swapping. (Swapping refers to the copying of information between physical memory and the virtual memory on the hard drive.) High numbers in the bi and bo fields indicate too much disk activity.

Checking disk performance and disk usage

Linux comes with the /sbin/hdparm program to control IDE or ATAPI hard drives, which are common on most PCs. One feature of the hdparm program is that you can use the -t option to determine the rate at which data is read from the disk into a buffer in memory. For example, here’s the result of typing /sbin/hdparm -t /dev/hda on one system:

/dev/hda:
Timing buffered disk reads: 178 MB in 3.03 seconds = 58.81 MB/sec

The command requires the IDE drive’s device name (/dev/hda for the first hard drive and /dev/hdb for the second hard drive) as an argument. If you have an IDE hard drive, you can try this command to see how fast data is read from your system’s disk drive.

To display the space available in the currently mounted file systems, use the df command. If you want a more readable output from df, type the following command:

df -h

Here’s a typical output from this command:

Filesystem Size Used Avail Use% Mounted on
/dev/hda5 7.1G 3.9G 2.9G 59% /
/dev/hda3 99M 18M 77M 19% /boot
none 125M 0 125M 0% /dev/shm
/dev/scd0 2.6G 2.6G 0 100% /media/cdrecorder

As this example shows, the -h option causes the df command to display the sizes in gigabytes (G) and megabytes (M).

To check the disk space being used by a specific directory, use the du command — you can specify the -h option to view the output in kilobytes (K) and megabytes (M), as shown in the following example:

du -h /var/log

Here’s a typical output of that command:

152K /var/log/cups
4.0K /var/log/vbox
4.0K /var/log/httpd
508K /var/log/gdm
4.0K /var/log/samba
8.0K /var/log/mail
4.0K /var/log/news/OLD
8.0K /var/log/news
4.0K /var/log/squid
2.2M /var/log

The du command displays the disk space used by each directory, and the last line shows the total disk space used by that directory. If you want to see only the total space used by a directory, use the -s option. For example, type du -sh /home to see the space used by the /home directory. The command produces output that looks like this:

89M /home

Viewing System Information with the /proc File System

Your Linux system has a special /proc file system. You can find out many things about your system from this file system. In fact, you can even change kernel parameters through the /proc file system (just by writing to a file in that file system), thereby modifying the system’s behavior.

The /proc file system isn’t a real directory on the hard drive but a collection of data structures in memory, managed by the Linux kernel, that appears to you as a set of directories and files. The purpose of /proc (also called the process file system) is to give you access to information about the Linux kernel as well as to help you find out about all processes currently running on your system.

You can access the /proc file system just as you access any other directory, but you have to know the meaning of various files to interpret the information. Typically, you can use the cat or more commands to view the contents of a file in /proc. The file’s contents provide information about some aspect of the system.

As with any directory, start by looking at a detailed directory listing of /proc. To do so, log in as root and type ls -l /proc in a terminal window. In the output, the first set of directories (indicated by the letter d at the beginning of the line) represents the processes currently running on your system. Each directory that corresponds to a process has the process ID (a number) as its name.

warning.eps Notice also a very large file named /proc/kcore; that file represents the entire physical memory of your system. Although /proc/kcore appears in the listing as a huge file, no single physical file occupies that much space on your hard drive — so don’t try to remove the file to reclaim disk space.

Several files and directories in /proc contain interesting information about your Linux PC. The /proc/cpuinfo file, for example, lists the key characteristics of your system, such as processor type and floating-point processor information. You can view the processor information by typing cat /proc/cpuinfo. For example, here’s what appears when cat /proc/cpuinfo is run on a sample system:

processor : 0
vendor_id : GenuineIntel
cpu family : 15
model : 3
model name : Intel(R) Celeron(R) CPU 2.53GHz
stepping : 3
cpu MHz : 2533.129
cache size : 256 KB
fdiv_bug : no
hlt_bug : no
f00f_bug : no
coma_bug : no
fpu : yes
fpu_exception : yes
cpuid level : 5
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge
mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss
ht tm pbe pni monitor ds_cpl cid
bogomips : 4997.12

This output is from a 2.5-GHz Celeron system. The listing shows many interesting characteristics of the processor. Note the line that starts with fdiv_bug. Remember the infamous Pentium floating-point division bug? The bug is in an instruction called fdiv (for floating-point division). Thus, the fdiv_bug line indicates whether this particular Pentium has the bug.

The last line in the /proc/cpuinfo file shows the BogoMIPS for the processor, as computed by the Linux kernel when it boots. BogoMIPS is something that Linux uses internally to time-delay loops.

Table 1-7 summarizes some of the files in the /proc file system that provide information about your Linux system. You can view some of these files on your system to see what they contain, but note that not all files shown in Table 1-7 are present on your system. The specific contents of the /proc file system depend on the kernel configuration and the driver modules that are loaded (which, in turn, depend on your PC’s hardware configuration).

Table 1-7 Some Files and Directories in /proc

File Name

Content

/proc/acpi

Information about Advanced Configuration and Power Interface (ACPI) — an industry-standard interface for configuration and power management on laptops, desktops, and servers.

/proc/bus

Directory with bus-specific information for each bus type, such as PCI.

/proc/cmdline

The command line used to start the Linux kernel (for example, ro root=LABEL=/ rhgb).

/proc/cpuinfo

Information about the CPU (the microprocessor).

/proc/devices

Available block and character devices in your system.

/proc/dma

Information about DMA (direct memory access) channels that are used.

/proc/driver/rtc

Information about the PC’s real-time clock (RTC).

/proc/filesystems

List of supported file systems.

/proc/ide

Directory containing information about IDE devices.

/proc/interrupts

Information about interrupt request (IRQ) numbers and how they are used.

/proc/ioports

Information about input/output (I/O) port addresses and how they’re used.

/proc/kcore

Image of the physical memory.

/proc/kmsg

Kernel messages.

/proc/loadavg

Load average (average number of processes waiting to run in the last 1, 5, and 15 minutes).

/proc/locks

Current kernel locks (used to ensure that multiple processes don’t write to a file at the same time).

/proc/meminfo

Information about physical memory and swap-space usage.

/proc/misc

Miscellaneous information.

/proc/modules

List of loaded driver modules.

/proc/mounts

List of mounted file systems.

/proc/net

Directory with many subdirectories that contain information about networking.

/proc/partitions

List of partitions known to the Linux kernel.

/proc/pci

Information about PCI devices found on the system.

/proc/scsi

Directory with information about SCSI devices found on the system (present only if you have a SCSI device).

/proc/stat

Overall statistics about the system.

/proc/swaps

Information about the swap space and how much is used.

/proc/sys

Directory with information about the system. You can change kernel parameters by writing to files in this directory. (Using this method to tune system performance requires expertise to do properly.)

/proc/uptime

Information about how long the system has been up.

/proc/version

Kernel version number.

tip.eps You can navigate the /proc file system just as you’d work with any other directories and files in Linux. Use the more or cat commands to view the contents of a file.

Understanding Linux Devices

Linux treats all devices as files and uses a device just as it uses a file — opens it, writes data to it, reads data from it, and closes it when finished. This ability to treat every device as a file is possible because of device drivers, which are special programs that control a particular type of hardware. When the kernel writes data to the device, the device driver does whatever is appropriate for that device. For example, when the kernel writes data to the DVD drive, the DVD device driver puts that data onto the physical medium of the DVD disk.

Thus the device driver isolates the device-specific code from the rest of the kernel and makes a device look like a file. Any application can access a device by opening the file specific to that device.

Device files

Applications can access a device as if it were a file. These files, called device files, appear in the /dev directory in the Linux file system.

If you use the ls command to look at the list of files in the /dev directory, you see several thousand files. These files don’t mean that your system has several thousand devices. The /dev directory has files for all possible types of devices — that’s why the number of device files is so large.

So how does the kernel know which device driver to use when an application opens a specific device file? The answer is in two numbers called the major and minor device numbers. Each device file is mapped to a specific device driver through these numbers.

To see an example of the major and minor device numbers, type the following command in a terminal window:

ls -l /dev/hda

You see a line of output similar to the following:

brw-rw---- 1 root disk 3, 0 Aug 16 14:50 /dev/hda

In this line, the major and minor device numbers appear just before the date. In this case, the major device number is 3 and the minor device number is 0. The kernel selects the device driver for this device file by using the major device number.

You don’t have to know much about device files and device numbers, except to be aware of their existence.

remember.eps In case you’re curious, all the major and minor numbers for devices are assigned according to device type. The Linux Assigned Names And Numbers Authority (LANANA) assigns these numbers. You can see the current device list at www.lanana.org/docs/device-list/devices-2.6+.txt.

Block devices

The first letter in the listing of a device file also provides an important clue. For the /dev/hda device, the first letter is b, which indicates that /dev/hda is a block device — one that can accept or provide data in chunks (typically 512 bytes or 1K). By the way, /dev/hda refers to the first IDE hard drive on your system (the C: drive in Windows). Hard drives and CD-ROM drives are examples of block devices.

Character devices

If the first letter in the listing of a device file is c, the device is a character device — one that can receive and send data one character (one byte) at a time. For example, the serial port and parallel ports are character devices. To see the specific listing of a character device, type the following command in a terminal window:

ls -l /dev/ttyS0

The listing of this device is similar to the following:

crw-rw---- 1 root uucp 4, 64 Aug 16 14:50 /dev/ttyS0

Note that the very first letter is c because /dev/ttyS0 — the first serial port — is a character device.

Network devices

Network devices that enable your system to interact with a network — for example, Ethernet and dial-up Point-to-Point Protocol (PPP) connections — are special because they need no file to correspond to the device. Instead, the kernel uses a special name for the device. For example, Ethernet devices are named eth0 for the first Ethernet card, eth1 for the second one, and so on. PPP connections are named ppp0, ppp1, and so on.

Because network devices aren’t mapped to device files, no files corresponding to these devices are in the /dev directory.

Persistent device naming with udev

Starting with the Linux kernel 2.6, a new approach for handling devices was added, based on the following features:

· sysfs: The kernel provides the sysfs file system, which is mounted on the /sys directory of the file system. The sysfs file system displays all the devices in the system as well as lots of information about each device, including the location of the device on the bus, attributes such as name and serial number, and the major and minor numbers of the device.

· /sbin/hotplug: This program is called whenever a device is added or removed. It can then do whatever is necessary to handle the device.

· /sbin/udev: This program takes care of dynamically named devices based on device characteristics such as serial number, device number on a bus, or a user-assigned name based on a set of rules that are set through the text file/etc/udev/udev.rules.

remember.eps The udev program’s configuration file is /etc/udev/udev.conf. Based on settings in that configuration file, udev creates device nodes automatically in the directory specified by the udev_root parameter. For example, to manage the device nodes in the /devdirectory, udev_root should be defined in /etc/udev/udev.conf as follows:

udev_root="/dev/"

Managing Loadable Driver Modules

To use any device, the Linux kernel must contain the driver. If the driver code is linked into the kernel as a monolithic program (a program in the form of a single, large file), adding a new driver means rebuilding the kernel with the new driver code. Rebuilding the kernel means you have to reboot the PC with the new kernel before you can use the new device driver. Luckily, the Linux kernel uses a modular design that does away with rebooting hassles. Linux device drivers can be created in the form of modules that the kernel can load and unload without having to restart the PC.

remember.eps Driver modules are one type of a broader category of software modules called loadable kernel modules. Other types of kernel modules include code that can support new types of file systems, modules for network protocols, and modules that interpret different formats of executable files.

Loading and unloading modules

You can manage the loadable device driver modules by using a set of commands. You have to log in as root to use some of these commands. Table 1-8 summarizes a few commonly used module commands.

Table 1-8 Commands to Manage Kernel Modules

This Command

Does the Following

insmod

Inserts a module into the kernel.

rmmod

Removes a module from the kernel.

depmod

Determines interdependencies between modules.

ksyms

Displays a list of symbols along with the name of the module that defines the symbol.

lsmod

Lists all currently loaded modules.

modinfo

Displays information about a kernel module.

modprobe

Inserts or removes a module or a set of modules intelligently. (For example, if module A requires B, modprobe automatically loads B when asked to load A.)

If you have to use any of these commands, log in as root or type su - in a terminal window to become root.

To see what modules are currently loaded, type

lsmod

You see a long list of modules. The list that you see will depend on the types of devices installed on your system.

The list displayed by lsmod includes all types of Linux kernel modules, not just device drivers. For example, if you use the Ext3 file system, you typically find two modules — jbd and ext3 — that are part of the Ext3 file system (the latest file system for Linux).

remember.eps Besides lsmod, one commonly used module command is modprobe. Use modprobe when you need to manually load or remove one or more modules. The best thing about modprobe is that you don’t need to worry if a module requires other modules to work. Themodprobe command automatically loads any other module needed by a module. For example, to manually load the sound driver, use the command

modprobe snd-card-0

This command causes modprobe to load everything needed to make sound work.

tip.eps You can use modprobe with the -r option to remove modules. For example, to remove the sound modules, use the following command:

modprobe -r snd-card-0

This command gets rid of all the modules that the modprobe snd-card-0 command had loaded.

Using the /etc/modprobe.conf file

How does the modprobe command know that it needs to load the snd-intel8x0 driver module? The answer’s in the /etc/modprobe.conf configuration file. That file contains a line that tells modprobe what it should load when it sees the module name snd-card-0.

To view the contents of /etc/modprobe.conf, type

cat /etc/modprobe.conf

For example, consider a /etc/modprobe.conf file that contains the following lines:

alias eth0 3c59x
alias snd-card-0 snd-intel8x0
alias usb-controller uhci-hcd

Each line that begins with the keyword alias defines a standard name for an actual driver module. For example, the first line defines 3c59x as the actual driver name for the alias eth0, which stands for the first Ethernet card. Similarly, the second line defines snd-intel8x0 as the module to load when the user uses the name snd-card-0.

The modprobe command consults the /etc/modprobe.conf file to convert an alias to the real name of a driver module. It also consults the /etc/modprobe.conf file for other tasks, such as obtaining parameters for driver modules. For example, you can insert lines that begin with the options keyword to provide values of parameters that a driver may need.

For example, to set the debug-level parameter for the Ethernet driver to 5 (this parameter generates lots of information in /var/log/messages), add the following line to the /etc/modprobe.conf file:

options 3c59x debug=5

This line specifies 5 as the value of the debug parameter in the 3c59x module.

If you want to know the names of the parameters that a module accepts, use the modinfo command. For example, to view information about the 3c59x driver module, type

modinfo 3c59x | more

From the resulting output, it’s possible to tell that debug is the name of the parameter for setting the debug level.

Unfortunately, the information displayed by the modinfo command can be cryptic. The only saving grace is that you may not have to do much more than use a graphical utility to configure the device, and the utility takes care of adding whatever is needed to configuration files, such as/etc/modprobe.conf.

Scheduling Jobs in Linux

As a system administrator, you may have to run some programs automatically at regular intervals or execute one or more commands at a specified time in the future. Your Linux system includes the facilities to schedule jobs to run at any future date or time you want. You can also set up the system to perform a task periodically or just once. Here are some typical tasks you can perform by scheduling jobs on your Linux system:

· Back up the files in the middle of the night

· Download large files in the early morning when the system isn’t busy

· Send yourself messages as reminders of meetings

· Analyze system logs periodically and look for any abnormal activities

You can set up these jobs by using the at command or the crontab facility of Linux. The next few sections introduce these job-scheduling features of Linux.

Scheduling one-time jobs

If you want to run one or more commands at a later time, you can use the at command. The atd daemon — a program designed to process jobs submitted using at — runs your commands at the specified time and mails the output to you.

remember.eps Before you try the at command, you need to know that the following configuration files control which users can schedule tasks using the at command:

· /etc/at.allow contains the names of the users who may submit jobs using the at command.

· /etc/at.deny contains the names of users not allowed to submit jobs using the at command.

If these files aren’t present or if you find an empty /etc/at.deny file, any user can submit jobs by using the at command. The default in Linux is an empty /etc/at.deny file; with this default in place, anyone can use the at command. If you don’t want some users to use at, simply list their usernames in the /etc/at.deny file.

To use at to schedule a one-time job for execution at a later time, follow these steps:

1. Run the at command with the date or time when you want your commands executed.

When you press Enter, the at> prompt appears, as follows:

at 21:30
at>

This method is the simplest way to indicate the time when you want to execute one or more commands — simply specify the time in a 24-hour format. In this case, you want to execute the commands at 9:30 p.m. tonight (or tomorrow, if it’s already past 9:30 p.m.). You can, however, specify the execution time in many different ways. (See Table 1-9 for examples.)

2. At the at> prompt, type the commands you want to execute as if you were typing at the shell prompt. After each command, press Enter and continue with the next command. When you finish entering the commands you want to execute, press Ctrl+D to indicate the end.

Here’s an example that shows how to execute the ps command at a future time:

at> ps
at> <EOT>
job 1 at 2014-12-28 21:30

After you press Ctrl+D, the at command responds with the <EOT> message, a job number, and the date and time when the job will execute.

Table 1-9 Formats for the at Command for the Time of Execution

Command

When the Job Will Run

at now

Immediately

at now + 15 minutes

15 minutes from the current time

at now + 4 hours

4 hours from the current time

at now + 7 days

7 days from the current time

at noon

At noontime today (or tomorrow, if already past noon)

at now next hour

Exactly 60 minutes from now

at now next day

At the same time tomorrow

at 17:00 tomorrow

At 5:00 p.m. tomorrow

at 4:45pm

At 4:45 p.m. today (or tomorrow, if it’s already past 4:45 p.m.)

at 3:00 Dec 28, 2014

At 3:00 a.m. on December 28, 2014

After you enter one or more jobs, you can view the current list of scheduled jobs with the atq command:

atq

The output looks similar to the following:

4 2014-12-28 03:00 a root
5 2014-10-26 21:57 a root
6 2014-10-26 16:45 a root

The first field on each line shows the job number — the same number that the at command displays when you submit the job. The next field shows the year, month, day, and time of execution. The last field shows the jobs pending in the a queue.

If you want to cancel a job, use the atrm command to remove that job from the queue. When removing a job with the atrm command, refer to the job by its number, as follows:

atrm 4

This command deletes job 4 scheduled for 3:00 a.m. December 28, 2014.

tip.eps When a job executes, the output is mailed to you. Type mail at a terminal window to read your mail and to view the output from your jobs.

Scheduling recurring jobs

Although at is good for running commands at a specific time, it’s not useful for running a program automatically at repeated intervals. You have to use crontab to schedule such recurring jobs — for example, if you want to back up your files to tape at midnight every evening.

You schedule recurring jobs by placing job information in a file with a specific format and submitting this file with the crontab command. The cron daemon — crond — checks the job information every minute and executes the recurring jobs at the specified times. Because thecron daemon processes recurring jobs, such jobs are also referred to as cron jobs.

Any output from a cron job is mailed to the user who submits the job. (In the submitted job-information file, you can specify a different recipient for the mailed output.)

Two configuration files control who can schedule cron jobs using crontab:

· /etc/cron.allow contains the names of the users who may submit jobs using the crontab command.

· /etc/cron.deny contains the names of users not allowed to submit jobs using the crontab command.

If the /etc/cron.allow file exists, only users listed in this file can schedule cron jobs. If only the /etc/cron.deny file exists, users listed in this file can’t schedule cron jobs. If neither file exists, the default Linux setup enables any user to submit cron jobs.

To submit a cron job, follow these steps:

1. Prepare a shell script (or an executable program in any programming language) that can perform the recurring task you want to perform.

You can skip this step if you want to execute an existing program periodically.

2. Prepare a text file with information about the times when you want the shell script or program (from Step 1) to execute and then submit this file by using crontab.

You can submit several recurring jobs with a single file. Each line with timing information about a job has a standard format, with six fields — the first five specify when the job runs, and the sixth and subsequent fields constitute the command that runs. For example, here’s a line that executes the myjob shell script in a user’s home directory at five minutes past midnight each day:

5 0 * * * $HOME/myjob

Table 1-10 shows the meaning of the first five fields. Note: An asterisk (*) means all possible values for that field. Also, an entry in any of the first five fields can be a single number, a comma-separated list of numbers, a pair of numbers separated by a hyphen (indicating a range of numbers), or an asterisk.

3. Suppose the text file jobinfo (in the current directory) contains the job information. Submit this information to crontab with the following command:

crontab jobinfo

That’s it! You’re set with the cron job. From now on, the cron job runs at regular intervals (as specified in the job-information file), and you receive mail messages with the output from the job.

To verify that the job is indeed scheduled, type the following command:

crontab -l

The output of the crontab -l command shows the cron jobs currently installed in your name. To remove your cron jobs, type crontab -r.

If you log in as root, you can also set up, examine, and remove cron jobs for any user. To set up cron jobs for a user, use this command:

crontab _u username filename

Here username is the user for whom you install the cron jobs, and filename is the file that contains information about the jobs.

Table 1-10 Format for the Time of Execution in crontab Files

Field Number

Meaning of Field

Acceptable Range of Values*

1

Minute

0–59

2

Hour of the day

0–23

3

Day of the month

0–31

4

Month

1–12 (1 means January, 2 means February, and so on) or the names of months using the first three letters — Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec

5

Day of the week

0–6 (0 means Sunday, 1 means Monday, and so on) or the three-letter abbreviations of weekdays — Sun, Mon, Tue, Wed, Thu, Fri, Sat

Use the following form of crontab command to view the cron jobs for a user:

crontab _u username -l

To remove a user’s cron jobs, use the following command:

crontab -u username -r

Note: The cron daemon also executes the cron jobs listed in the system-wide cron job file /etc/crontab. Here’s a typical /etc/crontab file from a Linux system (type cat /etc/crontab to view the file):

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

The first four lines set up several environment variables for the jobs listed in this file. The MAILTO environment variable specifies the user who receives the mail message with the output from the cron jobs in this file.

The line that begins with # is a comment line. The four lines following the run-parts comment execute the run-parts shell script (located in the /usr/bin directory) at various times with the name of a specific directory as argument. Each of the arguments to run-parts —/etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, and /etc/cron.monthly — are directories. Essentially, run-parts executes all scripts located in the directory that you provide as an argument.

Table 1-11 lists the directories where you can find these scripts and when they execute. You have to look at the scripts in these directories to know what executes at these periodic intervals.

Table 1-11 Script Directories for cron Jobs

Directory Name

Script Executes

/etc/cron.hourly

Every hour

/etc/cron.daily

Each day

/etc/cron.weekly

Weekly

/etc/cron.monthly

Once each month