You are on page 1of 303

This Manual is Compiled / Reprocessed By

Pakistan Computer Bureau


Any intimation about the errors, omissions, or suggestions for its improvement would be highly appreciated

at info@pcb.gov.pk

PAKISTAN COMPUTER BUREAU MINISTRY OF INFORMATION TECHNOLOGY PAKISTAN


November, 2008

Table of Contents
1.Steps to Get You Started 1.1. Is Your Hardware Compatible? 1.2. Do You Have Enough Disk Space? 1.3. Can You Install Using the CD-ROM or DVD 1.3.1. Alternative Boot Methods 1.3.2. Making an Installation Boot CD-ROM 1.4. Preparing for a Hard Drive Installation 2. Installing on Intel and AMD Systems 2.1. The Graphical Installation Program User Interface 2.1.1. A Note about Virtual Consoles 2.2. The Text Mode Installation Program User Interface 2.2.1. Using the Keyboard to Navigate 2.3. Starting the Installation Program 2.3.1. Booting the Installation Program on x86, AMD64, and Intel 64 Systems 2.3.2. Booting the Installation Program on Itanium Systems 2.3.3. Additional Boot Options 2.4. Selecting an Installation Method 2.5. Installing from DVD/CD-ROM 2.5.1. What If the IDE CD-ROM Was Not Found? 2.6. Installing from a Hard Drive 2.7. Welcome to Red Hat Enterprise Linux 2.8. Language Selection 2.9. Keyboard Configuration 2.10. Enter the Installation Number 2.11. Disk Partitioning Setup 2.12. Advanced Storage Options 2.13. Create Default Layout 2.14. Partitioning Your System 2.14.1. Graphical Display of Hard Drive(s) 2.14.2. Disk Druid's Buttons 1 1 1 1 2 2 3 5 5 6 7 9 9 10 11 12 14 15 15 16 17 17 18 19 20 22 24 26 27 28
I

2.14.3. Partition Fields 2.14.4. Recommended Partitioning Scheme 2.14.5. Adding Partitions 2.14.6. Editing Partitions 2.14.7. Deleting a Partition 2.15. x86, AMD64, and Intel 64 Boot Loader Configuration 2.15.1. Advanced Boot Loader Configuration 2.15.2. Rescue Mode 2.15.3. Alternative Boot Loaders 2.15.4. SMP Motherboards and GRUB 2.16. Time Zone Configuration 2.17. Set Root Password 2.18. Package Group Selection 2.19. Preparing to Install 2.19.1. Prepare to Install 2.20. Installing Packages 2.21. Installation Complete 2.22.Itanium Systems Booting Your Machine and PostInstallation Setup 2.22.1. Post-Installation Boot Loader Options 2.22.2. Booting Red Hat Enterprise Linux Automatically 3. Removing Red Hat Enterprise Linux 4. Troubleshooting Installation on an Intel or AMD System 4.1. You are Unable to Boot Red Hat Enterprise Linux 4.1.1. Are You Unable to Boot With Your RAID Card? 4.1.2. Is Your System Displaying Signal 11 Errors? 4.2. Trouble Beginning the Installation 4.2.1. Problems with Booting into the Graphical Installation 4.3. Trouble During the Installation 4.3.1. No devices found to install Red Hat Enterprise Linux Error Message 4.3.2. Saving Traceback Messages Without a Diskette Drive 4.3.3. Trouble with Partition Tables 4.3.4. Using Remaining Space

29 30 33 35 36 36 38 40 41 42 42 43 45 47 47 48 48 49 49 50 53 55 55 55 55 56 56 57 57 57 57 58
II

4.3.5. Other Partitioning Problems 4.3.6. Other Partitioning Problems for Itanium System Users 4.3.7. Are You Seeing Python Errors? 4.4. Problems After Installation 4.4.1. Trouble With the Graphical GRUB Screen on an x86based System? 4.4.2. Booting into a Graphical Environment 4.4.3. Problems with the X Window System (GUI) 4.4.4. Problems with the X Server Crashing and Non-Root Users 4.4.5. Problems When You Try to Log In 4.4.6. Is Your RAM Not Being Recognized? 4.4.7. Your Printer Does Not Work 4.4.8. Problems with Sound Configuration 4.4.9. Apache-based httpd service/Sendmail Hangs During Startup 5. The GRUB Boot Loader 5.1. Boot Loaders and System Architecture 5.2. GRUB 5.2.1. GRUB and the x86 Boot Process 5.2.2. Features of GRUB 5.3. Installing GRUB 5.4. GRUB Terminology 5.4.1. Device Names 5.4.2. File Names and Block lists 5.4.3. The Root File System and GRUB 5.5. GRUB Interfaces 5.5.1. Interfaces Load Order 5.6. GRUB Commands 5.7. GRUB Menu Configuration File 5.7.1. Configuration File Structure 5.7.2. Configuration File Directives 5.8. Changing Run levels at Boot Time 5.9. Additional Resources 5.9.1. Installed Documentation

58 58 59 60 60 61 62 62 63 64 65 65 65 66 66 66 67 68 68 69 69 71 72 72 73 74 76 76 77 79 79 79
III

5.9.2. Useful Websites 6. Swap Space


6.1. What is Swap Space? 6.2. Adding Swap Space 6.2.1. Extending Swap on an LVM2 Logical Volume 6.2.2. Creating an LVM2 Logical Volume for Swap 6.2.3. Creating a Swap File. 6.3. Removing Swap Space 6.3.1. Reducing Swap on an LVM2 Logical Volume 6.3.2. Removing an LVM2 Logical Volume for Swap 6.3.3. Removing a Swap File 6.4. Moving Swap Space 7. Managing Disk Storage 7.1. Standard Partitions using parted 7.1.1. Viewing the Partition Table 7.1.2. Creating a Partition 7.1.3. Removing a Partition 7.1.4. Resizing a Partition 7.2. LVM Partition Management 8. Access Control Lists 8.1. Mounting File Systems 8.1.1. NFS 8.2. Setting Access ACLs 8.3. Setting Default ACLs 8.4. Retrieving ACLs 8.5. Archiving File Systems With ACLs 8.6. Compatibility with Older Systems 8.7. Useful Websites 9. Package Management with RPM 9.1. RPM Design Goals 9.2. Using RPM

79
81 81 82 82 83 83 84 85 85 86 86 87 87 88 89 91 92 92 95 95 96 96 97 97 98 99 99 100 101 102
IV

9.2.1. Finding RPM Packages 9.2.2. Installing 9.2.3. Uninstalling 9.2.4. Upgrading 9.2.5. Freshening 9.2.6. Querying 9.2.7. Verifying 9.3. Checking a Package's Signature 9.3.1. Importing Keys 9.3.2. Verifying Signature of Packages 9.4. Practical and Common Examples of RPM Usage 9.5. Additional Resources 9.5.1. Installed Documentation 9.5.2. Useful Websites 9.5.3. Related Books 10. Network File System (NFS) 10.1. How It Works 10.1.1. Required Services 10.2. NFS Client Configuration 10.2.1. Mounting NFS File Systems using /etc/fstab 10.3. autofs 10.3.1. What's new in autofsversion 5? 10.3.2. autofsConfiguration 10.3.3. autofsCommon Tasks 10.4. Common NFS Mount Options 10.5. Starting and Stopping NFS 10.6. NFS Server Configuration 10.6.1. Exporting or Sharing NFS File Systems 10.6.2. Command Line Configuration 10.6.3. Hostname Formats 10.7. The /etc/exportsConfiguration File 10.7.1. The exportfsCommand 10.8. Securing NFS

102 102 105 105 106 107 108 109 110 110 111 113 113 113 113 114 114 115 116 117 118 119 120 122 127 129 130 131 135 136 137 140 142
V

10.8.1. Host Access 10.8.2. File Permissions 10.9. NFS and portmap 10.9.1. Troubleshooting NFS and portmap 10.10. Using NFS over TCP 10.11. Additional Resources 10.11.1. Installed Documentation 10.11.2. Useful Websites 10.11.3. Related Books 11. Samba 11.1. Introduction to Samba 11.1.1. Samba Features 11.2. Samba Daemons and Related Services 11.2.1. Samba Daemons 12. Date and Time Configuration 12.1. Time and Date Properties 12.2. Network Time Protocol (NTP) Properties 12.3. Time Zone Configuration 13. The X Window System 13.1. The X11R7.1 Release 13.2. Desktop Environments and Window Managers 13.2.1. Desktop Environments 13.2.2. Window Managers 13.3. X Server Configuration Files 13.3.1. xorg.conf 13.4. Fonts 13.4.1. Fontconfig 13.4.2. Core X Font System 13.5. Runlevels and X 13.5.1. Runlevel 3 13.5.2. Runlevel 5 14. X Window System Configuration 14.1. Display Settings

142 144 144 145 146 147 147 148 148 149 149 149 150 150 151 152 154 155 157 157 158 159 159 161 162 172 173 174 177 177 178 180 180
VI

14.2. Display Hardware Settings 14.3. Dual Head Display Settings 15. Users and Groups 15.1. User and Group Configuration 15.1.1. Adding a New User 15.1.2. Modifying User Properties 15.1.3. Adding a New Group 15.1.4. Modifying Group Properties 15.2. User and Group Management Tools 15.2.1. Command Line Configuration 15.2.2. Adding a User 15.2.3. Adding a Group 15.2.4. Password Aging 15.2.5. Explaining the Process 15.3. Standard Users 15.4. Standard Groups 15.5. User Private Groups 15.5.1. Group Directories 16. MySql 16.1. What is SQL 16.2. Why MySQL 16.3. What are databases and why do we need them? 16.4. Downloading MySQL 16.5. Installing MySQL on Linux 16.6. Creating MySQL database on Linux system 16.7. Creating tables 16.8. Using a database 16.9. Creating tables 16.10. MySQL lesson - MySQL tables 16.11. MySQL Table details - describe table command 16.12. Inserting data in MySQL tables 16.13. Querying MySQL tables 16.14. Querying tables with MySQL Select - Another example

181 182 184 184 186 188 189 190 190 191 191 192 192 196 197 199 201 201 204 204 204 204 205 206 207 209 211 212 213 213 214 215 217
VII

16.15. Ordering data 16.16. Limiting data retrieval 16.17. Extracting Subsets 16.18. The DISTINCT keyword 16.19. Finding the minimum and maximum values 16.20. MySQL MIN () - Minimum value 16.21. MySQL MAX () - Maximum value 16.22. Finding the average and sum 16.23. MySQL AVG() - Finding the Average 16.24. Naming Columns 16.25. Counting 16.26. The MySQL GROUP BY clause 16.27. Sorting the data in MySQL 16.28. HAVING clause 16.29. A little more on the MySQL SELECT statement 16.30. MySQL programming - MySQL mathematical Functions 16.31. Updating records 16.32. MySQL Date column type part 1 16.33. Specifying date ranges in MySQL 16.34. MySQL programming - MySQL Date column type part 2 16.35. Null column type 16.36. MySQL manual - MySQL table joins 16.37. Deleting entries from tables 16.38. Dropping tables 16.39. MySQL database Column Types 16.40. MySQL Numeric Column Types 16.41. Column Types part 2

230 233 234 235 237 237 238 238 239 240 240 241 242 244 245 248 254 255 258 259 262 263 265 265 266 266 267 269

Linux System Administrator Training Schedule(Day wise)

VIII

1.1. Is Your Hardware Compatible?


Hardware compatibility is particularly important if you have an older system or a system that you built yourself. Red Hat Enterprise Linux 5 should be compatible with most hardware in systems that were factory built within the last two years. However, hardware specifications change almost daily, so it is difficult to guarantee that your hardware is 100% compatible. The most recent list of supported hardware can be found at: http://hardware.redhat.com/hcl/

1.2. Do You Have Enough Disk Space?


Nearly every modern-day operating system (OS) uses disk partitions, and Red Hat Enterprise Linux is no exception. When you install Red Hat Enterprise Linux, you may have to work with disk partitions. The disk space used by Red Hat Enterprise Linux must be separate from the disk space used by other OSes you may have installed on your system, such as Windows, OS/2, or even a different version of Linux. For x86, AMD64, and Intel 64 systems, at least two partitions (/ and swap) must be dedicated to Red Hat Enterprise Linux. For Itanium systems, at least three partitions (/, /boot/efi/, and swap) must be dedicated to Red Hat Enterprise Linux. Before you start the installation process, you must have enough unpartitioned disk space for the installation of Red Hat Enterprise Linux, or have one or more partitions that may be deleted, thereby freeing up enough disk space to install Red Hat Enterprise Linux.

1.3. Can You Install Using the CD-ROM or DVD?


There are several methods that can be used to install Red Hat Enterprise Linux. Installing from a CD-ROM or DVD requires that you have purchased a Red Hat Enterprise Linux product, you have a Red Hat Enterprise Linux 5.0.0 CD-ROM or DVD, and you have a DVD/CD-ROM drive on a system that supports booting from it. Your BIOS may need to be changed to allow booting from your DVD/CD-ROM drive.

Pakistan Computer Bureau

1.3.1. Alternative Boot Methods


Boot DVD/CD-ROM If you can boot using the DVD/CD-ROM drive, you can create your own CDROM to boot the installation program. This may be useful, for example, if you are performing an installation over a network or from a hard drive. USB pen drive If you cannot boot from the DVD/CD-ROM drive, but you can boot using a USB device, such as a USB pen drive, the following alternative boot method is available: To boot using a USB pen drive, use the dd command to copy the diskboot.img image file from the /images/ directory on the DVD or CD-ROM #1. For example: dd if=diskboot.img of=/dev/sda Your BIOS must support booting from a USB device in order for this boot method to work.

1.3.2. Making an Installation Boot CD-ROM


isolinux (not available for Itanium systems) is used for booting the Red Hat Enterprise Linux installation CD. To create your own CD-ROM to boot the installation program, use the following instructions: Copy the isolinux/ directory from the Red Hat Enterprise Linux DVD or CD #1 into a temporary directory (referred to here as <path-to-workspace>) using the following command: cp -r <path-to-cd>/isolinux/<path-to-workspace> Change directories to the <path-to-workspace> directory you have created: cd <path-to-workspace> Make sure the files you have copied have appropriate permissions: chmod u+w isolinux/*

Pakistan Computer Bureau

Finally, issue the following command to create the ISO image file: mkisofs -o file.iso -b isolinux.bin -c boot.cat -noemul-boot \ -boot-load-size 4 -boot-info-table -R -J -v -T isolinux/ Note
The above command was split into two lines for printing purposes only. When you execute this command, be sure to type it as a single command, all on the same line. Burn the resulting ISO image (named file.iso and located in <path-to-workspace>) to a CD-ROM as you normally would.

1.4. Preparing for a Hard Drive Installation


Note
Hard drive installations only work from ext2, ext3, or FAT file systems. If you have a file system other than those listed here, such as reiserfs, you will not be able to perform a hard drive installation.

Hard drive installations require the use of the ISO (or DVD/CD-ROM) images. An ISO image is a file containing an exact copy of a DVD/CD-ROM image. After placing the required ISO images (the binary Red Hat Enterprise Linux DVD/CD-ROMs) in a directory, choose to install from the hard drive. You can then point the installation program at that directory to perform the installation. To prepare your system for a hard drive installation, you must set the system up in one of the following ways: Using a set of CD-ROMs, or a DVD Create ISO image files from each installation CD-ROM, or from the DVD. For each CD-ROM (once for the DVD), execute the following command on a Linux system: dd if=/dev/cdrom of=/tmp/file-name.iso Using ISO images transfer these images to the system to be installed. Verifying that ISO images are intact before you attempt an installation, helps to avoid problems. To verify the ISO images are intact prior to performing an
Pakistan Computer Bureau

installation, use an md5sum program (many md5sum programs are available for various operating systems). An md5sum program should be available on the same Linux machine as the ISO images. Note
The Red Hat Enterprise Linux installation program has the ability to test the integrity of the installation media. It works with the CD / DVD, hard drive ISO, and NFS ISO installation methods. Red Hat recommends that you test all installation media before starting the installation process, and before reporting any installation-related bugs (many of the bugs reported are actually due to improperly-burned CDs). To use this test, type the following command at the boot: prompt (prepend with elilo for Itanium systems):

linux mediacheck

Pakistan Computer Bureau

This chapter explains how to perform a Red Hat Enterprise Linux installation from the DVD/CD-ROM, using the graphical, mouse-based installation program. The following topics are discussed: Becoming familiar with the installation program's user interface Starting the installation program Selecting an installation method Configuration steps during the installation (language, keyboard, mouse, partitioning, etc.) Finishing the installation

2.1. The Graphical Installation Program User Interface


If you have used a graphical user interface (GUI) before, you are already familiar with this process; use your mouse to navigate the screens, click buttons, or enter text fields. You can also navigate through the installation using the keyboard. The Tab key allows you to move around the screen, the Up and Down arrow keys to scroll through lists, + and - keys expand and collapse lists, while Space and Enter selects or removes from selection a highlighted item. You can also use the Alt-X key command combination as a way of clicking on buttons or making other screen selections, where X is replaced with any underlined letter appearing within that screen. Note
If you are using an x86, AMD64, or Intel 64 system, and you do not wish to use the GUI installation program, the text mode installation program is also available. To start the text mode installation program, use the following command at the boot:

prompt: linux text It is highly recommended that installs be performed using the GUI installation program. The GUI installation program offers the full functionality of the Red Hat Enterprise Linux installation program, including LVM configuration which is not available during a text mode installation. Users who must use the text mode installation program can follow the GUI installation instructions and obtain all needed information.

Pakistan Computer Bureau

Note
If you are using an Itanium system, and you do not wish to use the GUI installation program, the text mode installation program is also available. To start the text mode installation program, type the following command at the EFI Shell prompt:

elilo linux text

2.1.1. A Note about Virtual Consoles


The Red Hat Enterprise Linux installation program offers more than the dialog boxes of the installation process. Several kinds of diagnostic messages are available to you, as well as a way to enter commands from a shell prompt. The installation program displays these messages on five virtual consoles, among which you can switch using a single keystroke combination. A virtual console is a shell prompt in a non-graphical environment, accessed from the physical machine, not remotely. Multiple virtual consoles can be accessed simultaneously. These virtual consoles can be helpful if you encounter a problem while installing Red Hat Enterprise Linux. Messages displayed on the installation or system consoles can help pinpoint a problem. Refer to Table 2.1, Console, Keystrokes, and Contents for a listing of the virtual consoles, keystrokes used to switch to them, and their contents. Generally, there is no reason to leave the default console (virtual console #6) for graphical installations unless you are attempting to diagnose installation problems. console 1 2 3 4 5 6 keystrokes ctrl-alt-f1 ctrl-alt-f2 ctrl-alt-f3 ctrl-alt-f4 ctrl-alt-f5 ctrl-alt-f6 Contents installation dialog shell prompt install log (messages from installation system-related messages other messages Graphic Display

Table 2.1. Console, Keystrokes, and Contents

Pakistan Computer Bureau

2.2. The Text Mode Installation Program User Interface


The Red Hat Enterprise Linux text mode installation program uses a screenbased interface that includes most of the on-screen widgets commonly found on graphical user interfaces. Figure 2.1, Installation Program Widgets as seen in Boot Loader Configuration, and Figure 2.2, Installation Program Widgets as seen in Disk Druid, illustrate the screens that appear during the installation process. Note
While text mode installations are not explicitly documented, those using the text mode installation program can easily follow the GUI installation instructions. One thing to note is that manipulation of LVM (Logical Volume Management) disk volumes is only possible in graphical mode. In text mode it is only possible to view and accept the default LVM setup.

Figure 2.1. Installation Program Widgets as seen in Boot Loader Configuration

Pakistan Computer Bureau

Figure 2.2. Installation Program Widgets as seen in Disk Druid

Here is a list of the most important widgets shown in Figure 2.1, Installation Program Widgets as seen in Boot Loader Configuration and Figure 2.2, Installation Program Widgets as seen in Disk Druid: Window Windows (usually referred to as dialogs in this manual) appear on your screen throughout the installation process. At times, one window may overlay another; in these cases, you can only interact with the window on top. When you are finished in that window, it disappears, allowing you to continue working in the window underneath. Checkbox Checkboxes allow you to select or deselect a feature. The box displays either an asterisk (selected) or a space (unselected). When the cursor is within a checkbox, press Space to select or deselect a feature. Text Input Text input lines are regions where you can enter information required by the installation program. When the cursor rests on a text input line, you may enter and/or edit information on that line. Text Widget Text widgets are regions of the screen for the display of text. At times, text widgets may also contain other widgets, such as checkboxes. If a text widget contains more information than can be displayed in the space reserved for it, a scroll bar appears; if you position the cursor within the text widget, you can then use the Up and Down arrow keys to scroll through all the information available. Your current position is shown on the scroll bar by a # character, which moves up and down the scroll bar as you scroll.
Pakistan Computer Bureau 8

Scroll Bar Scroll bars appear on the side or bottom of a window to control which part of a list or document is currently in the window's frame. The scroll bar makes it easy to move to any part of a file. Button Widget Button widgets are the primary method of interacting with the installation program. You progress through the windows of the installation program by navigating these buttons, using the Tab and Enter keys. Buttons can be selected when they are highlighted. Cursor Although not a widget, the cursor is used to select (and interact with) a particular widget. As the cursor is moved from widget to widget, it may cause the widget to change color, or the cursor itself may only appear positioned in or next to the widget.

2.2.1. Using the Keyboard to Navigate


Navigation through the installation dialogs is performed through a simple set of keystrokes. To move the cursor, use the Left, Right, Up, and Down arrow keys. Use Tab, and Shift-Tab to cycle forward or backward through each widget on the screen. Along the bottom, most screens display a summary of available cursor positioning keys. To "press" a button, position the cursor over the button (using Tab, for example) and press Space or Enter. To select an item from a list of items, move the cursor to the item you wish to select and press Enter. To select an item with a checkbox, move the cursor to the checkbox and press Space to select an item. To deselect, press Space a second time. Pressing F12 accepts the current values and proceeds to the next dialog; it is equivalent to pressing the OK button. Caution
Unless a dialog box is waiting for your input, do not press any keys during the installation process (doing so may result in unpredictable behavior).

2.3. Starting the Installation Program


To start, first make sure that you have all necessary resources for the installation. If you have already read through Chapter 1, Steps to Get You Started, and followed the instructions, you should be ready to start the installation process. When you have verified that you are ready to begin, boot the installation program using the Red Hat Enterprise Linux DVD or CD-ROM #1 or any boot media that you have created.

Pakistan Computer Bureau

Note
Occasionally, some hardware components require a driver diskette during the installation. A driver diskette adds support for hardware that is not otherwise supported by the installation program.

2.3.1. Booting the Installation Program on x86, AMD64, and Intel 64 Systems
You can boot the installation program using any one of the following media (depending upon what your system can support): Red Hat Enterprise Linux DVD/CD-ROM Your machine supports a bootable DVD/CD-ROM drive and you have the Red Hat Enterprise Linux CD-ROM set or DVD. Boot CD-ROM Your machine supports a bootable CD-ROM drive and you want to perform network or hard drive installation. USB pen drive Your machine supports booting from a USB device. PXE boot via network Your machine supports booting from the network. This is an advanced installation path. Insert the boot media and reboot the system. Your BIOS settings may need to be changed to allow you to boot from the CD-ROM or USB device. Tip
To change your BIOS settings on an x86, AMD64, or Intel 64 system, watch the instructions provided on your display when your computer first boots. A line of text appears, telling you which key to press to enter the BIOS settings.

Once you have entered your BIOS setup program, find the section where you can alter your boot sequence. The default is often C, A or A, C (depending on whether you boot from your hard drive [C] or a diskette drive [A]). Change this sequence so that the CD-ROM is first in your boot order and that C or A (whichever is your typical boot default) is second. This instructs the computer to first look at the CD-ROM drive for bootable media; if it does not find bootable media on the CD-ROM drive, it then checks your hard drive or diskette drive. Save your changes before exiting the BIOS. For more information, refer to the documentation that came with your system.
Pakistan Computer Bureau 10

After a short delay, a screen containing the boot: prompt should appear. The screen contains information on a variety of boot options. Each boot option also has one or more help screens associated with it. To access a help screen, press the appropriate function key as listed in the line at the bottom of the screen. As you boot the installation program, be aware of two issues: Once the boot: prompt appears, the installation program automatically begins if you take no action within the first minute. To disable this feature, press one of the help screen function keys. If you press a help screen function key, there is a slight delay while the help screen is read from the boot media. Normally, you only need to press Enter to boot. Be sure to watch the boot messages to review if the Linux kernel detects your hardware. If your hardware is properly detected, continue to the next section. If it does not properly detect your hardware, you may need to restart the installation and use one of the boot options provided further.

2.3.2. Booting the Installation Program on Itanium Systems


Your Itanium system should be able to boot the Red Hat Enterprise Linux installation program directly from the Red Hat Enterprise Linux CD #1. If your Itanium cannot boot the installation program from the CD-ROM (or if you want to perform a hard drive, NFS, FTP, or HTTP installation) you must boot from an LS-120 diskette.

2.3.2.1. Booting the Installation Program from the DVD/CD-ROM


To boot from the Red Hat Enterprise Linux CD #1 follow these steps: 1. Remove all media except Red Hat Enterprise Linux CD #1. 2. From the Boot Option menu choose EFI Shell. 3. At the Shell> prompt, change to the file system on the CD-ROM. For example, in the above sample map output, the system partition on the CD-ROM is fs1. To change to the fs1 file system, type fs1: at the prompt. 4. Type elilo linux to boot into the installation program.

2.3.2.2. Booting the Installation Program from an LS-120 Diskette


If your Itanium cannot boot from Red Hat Enterprise Linux CD #1, you must boot from an LS-120 diskette. If you want to perform a hard drive, NFS, FTP, or HTTP installation, you must boot from a boot LS-120 diskette.
Pakistan Computer Bureau 11

You must create an LS-120 boot image file diskette from the boot image file on CD #1: images/boot.img. To create this diskette in Linux, insert a blank LS120 diskette and type the following command at a shell prompt: dd if=boot.img of=/dev/hda bs=180k Replace boot.img with the full path to the boot image file and /dev/hda with the correct device name for the LS-120 diskette drive. If you are not using the Red Hat Enterprise Linux CD, the installation program starts in text mode and you must choose a few basic options for your system. To boot from an LS-120 diskette follow these steps: 1. Insert the LS-120 diskette you made from the boot image file boot.img. If you are performing a local CD-ROM installation but booting off the LS-120 diskette, insert the Red Hat Enterprise Linux CD #1 also. If you are performing a hard drive, NFS, FTP, or HTTP installation, you do not need the CDROM. 2. From the Boot Option menu choose EFI Shell. 3. At the Shell> prompt, change the device to the LS-120 drive by typing the command fs0: using the example map output above. 4. Type elilo linux to boot into the installation program.

2.3.3. Additional Boot Options


While it is easiest to boot using a CD-ROM and perform a graphical installation, sometimes there are installation scenarios where booting in a different manner may be needed. This section discusses additional boot options available for Red Hat Enterprise Linux. For Itanium users: To pass options to the boot loader on an Itanium system, enter the following at the EFI Shell prompt: elilo linux option For x86, AMD64, and Intel 64 users: To pass options to the boot loader on an x86, AMD64, or Intel 64 system, use the instructions as provided in the boot loader option samples below.

Pakistan Computer Bureau

12

To perform a text mode installation, at the installation boot prompt, type: linux text ISO images have an md5sum embedded in them. To test the checksum integrity of an ISO image, at the installation boot prompt, type: linux mediacheck The installation program prompts you to insert a CD or select an ISO image to test, and select OK to perform the checksum operation. This checksum operation can be performed on any Red Hat Enterprise Linux CD and does not have to be performed in a specific order (for example, CD #1 does not have to be the first CD you verify). It is strongly recommended to perform this operation on any Red Hat Enterprise Linux CD that was created from downloaded ISO images. This command works with the CD, DVD, hard drive ISO, and NFS ISO installation methods. Also in the images/ directory is the boot.iso file. This file is an ISO image than can be used to boot the installation program. To use the boot.iso, your computer must be able to boot from its CD-ROM drive, and its BIOS settings must be configured to do so. You must then burn the boot.iso file onto a recordable/rewriteable CD-ROM. If you need to perform the installation in serial mode, type the following command: linux console=<device> For text mode installations, use: linux text console=<device> In the above command, <device> should be the device you are using (such as ttyS0 or ttyS1). For example, linux text console=ttyS0. Text mode installations using a serial terminal work best when the terminal supports UTF-8. Under UNIX and Linux, Kermit supports UTF-8. For Windows, Kermit '95 works well. A Non-UTF-8 capable terminal works as long as only English is used during the installation process. An enhanced serial display can be used by passing the utf8 command as a boot-time option to the installation program. For example: linux console=ttyS0 utf8

Pakistan Computer Bureau

13

2.3.3.1. Kernel Options


Options can also be passed to the kernel. For example, to apply updates for the anaconda installation program from a floppy disk enter: linux updates For text mode installations, use: linux text updates This command will prompt you to insert a floppy diskette containing updates for anaconda. It is not needed if you are performing a network installation and have already placed the updates image contents in rhupdates/ on the server. After entering any options, press Enter to boot using those options. If you need to specify boot options to identify your hardware, please write them down. The boot options are needed during the boot loader configuration portion of the installation.

2.4. Selecting an Installation Method


What type of installation method do you wish to use? The following installation methods are available: DVD/CD-ROM If you have a DVD/CD-ROM drive and the Red Hat Enterprise Linux CD-ROMs or DVD you can use this method. Hard Drive If you have copied the Red Hat Enterprise Linux ISO images to a local hard drive, you can use this method. You need a boot CD-ROM (use the linux askmethod boot option). NFS If you are installing from an NFS server using ISO images or a mirror image of Red Hat Enterprise Linux, you can use this method. You need a boot CDROM (use the linux askmethod boot option). Note that NFS installations may also be performed in GUI mode.

Pakistan Computer Bureau

14

FTP If you are installing directly from an FTP server, use this method. You need a boot CD-ROM (use the linux askmethod boot option). HTTP If you are installing directly from an HTTP (Web) server, use this method. You need a boot CD-ROM (use the linux askmethod boot option).

2.5. Installing from DVD/CD-ROM


To install Red Hat Enterprise Linux from a DVD/CD-ROM, place the DVD or CD #1 in your DVD/CD-ROM drive and boot your system from the DVD/CDROM. The installation program then probes your system and attempts to identify your CD-ROM drive. It starts by looking for an IDE (also known as an ATAPI) CD-ROM drive. Note
To abort the installation process at this time, reboot your machine and then eject the boot media. You can safely cancel the installation at any point before the About to Install screen. Refer to Section 24, Preparing to Install for more information.

If your CD-ROM drive is not detected, and it is a SCSI CD-ROM, the installation program prompts you to choose a SCSI driver. Choose the driver that most closely resembles your adapter. You may specify options for the driver if necessary; however, most drivers detect your SCSI adapter automatically. If the DVD/CD-ROM drive is found and the driver loaded, the installer will present you with the option to perform a media check on the DVD/CD-ROM. This will take some time, and you may opt to skip over this step. However, if you later encounter problems with the installer, you should reboot and perform the media check before calling for support. From the media check dialog, continue to the next stage of the installation process.

2.5.1. What If the IDE CD-ROM Was Not Found?


If you have an IDE (ATAPI) DVD/CD-ROM but the installation program fails to find it and asks you what type of DVD/CD-ROM drive you have, try the following boot command. Restart the installation, and at the boot: prompt enter linux hdX=cdrom. Replace X with one of the following letters, depending on
Pakistan Computer Bureau 15

the interface the unit is connected to, and whether it is configured as master or slave (also known as primary and secondary): a first IDE controller, master b first IDE controller, slave c second IDE controller, master d second IDE controller, slave If you have a third and/or fourth controller, continue assigning letters in alphabetical order, going from controller to controller, and master to slave.

2.6. Installing from a Hard Drive


The Select Partition screen applies only if you are installing from a disk partition (that is, if you selected Hard Drive in the Installation Method dialog). This dialog allows you to name the disk partition and directory from which you are installing Red Hat Enterprise Linux.

Figure 2.3. Selecting Partition Dialog for Hard Drive Installation

Enter the device name of the partition containing the Red Hat Enterprise Linux ISO images. This partition must be formatted with a ext2 or vfat filesystem, and cannot be a logical volume. There is also a field labeled Directory holding images. If the ISO images are in the root (top-level) directory of a partition, enter a /. If the ISO images are located in a subdirectory of a mounted partition, enter the
Pakistan Computer Bureau 16

name of the directory holding the ISO images within that partition. For example, if the partition on which the ISO images is normally mounted as /home/, and the images are in /home/new/, you would enter /new/. After you have identified the disk partition, the Welcome dialog appears.

2.7. Welcome to Red Hat Enterprise Linux


The Welcome screen does not prompt you for any input. From this screen you can access the Release Notes for Red Hat Enterprise Linux 5.0.0 by clicking on the Release Notes button.

Click on the Next button to continue.

2.8. Language Selection


Using your mouse, select a language to use for the installation (refer to Figure 2.8, Language Selection). The language you select here will become the default language for the operating system once it is installed. Selecting the appropriate language also helps target
Pakistan Computer Bureau 17

your time zone configuration later in the installation. The installation program tries to define the appropriate time zone based on what you specify on this screen.

Figure 2.8. Language Selection

Once you select the appropriate language, click Next to continue.

2.9. Keyboard Configuration


Using your mouse, select the correct layout type (for example, U.S. English) for the keyboard you would prefer to use for the installation and as the system default (refer to the figure below). Once you have made your selection, click Next to continue.

Pakistan Computer Bureau

18

Figure 2.9. Keyboard Configuration

Tip
To change your keyboard layout type after you have completed the installation, use the Keyboard Configuration Tool. Type the system-config-keyboard command in a shell prompt to launch the Keyboard Configuration Tool. If you are not root, it prompts you for the root password to continue.

2.10. Enter the Installation Number


Enter your Installation Number (refer to Figure 2.10, Installation Number). This number will determine the package selection set that is available to the installer. If you choose to skip entering the installation number you will be presented with a basic selection of packages to install later on.

Pakistan Computer Bureau

19

Figure 2.10. Installation Number

2.11. Disk Partitioning Setup


Partitioning allows you to divide your hard drive into isolated sections, where each section behaves as its own hard drive. Partitioning is particularly useful if you run multiple operating systems. If you are not sure how you want your system to be partitioned. On this screen you can choose to create the default layout or choose to manual partition using the 'Create custom layout' option of Disk Druid. The first three options allow you to perform an automated installation without having to partition your drive(s) yourself. If you do not feel comfortable with partitioning your system, it is recommended that you do not choose to create a custom layout and instead let the installation program partition for you. You can configure an iSCSI target for installation, or disable a dmraid device from this screen by clicking on the 'Advanced storage configuration' button.

Pakistan Computer Bureau

20

Warning
The Update Agent downloads updated packages to /var/cache/yum/ by default. If you partition the system manually, and create a separate /var/ partition, be sure to create the partition large enough (3.0 GB or more) to download package updates.

Figure 2.11. Disk Partitioning Setup

If you choose to create a custom layout using Disk Druid, refer to Section 18, Partitioning Your System. Warning
If you receive an error after the Disk Partitioning Setup phase of the installation saying something similar to: "The partition table on device hda was unreadable. To create new partitions it must be initialized, causing the loss of ALL DATA on this drive."

You may not have a partition table on that drive or the partition table on the drive may not be recognizable by the partitioning software used in the
Pakistan Computer Bureau

21

installation program. Users who have used programs such as EZ-BIOS have experienced similar problems, causing data to be lost (assuming the data was not backed up before the installation began). No matter what type of installation you are performing, backups of the existing data on your systems should always be made.

2.12. Advanced Storage Options

Figure 2.12. Advanced Storage Options

From this screen you can choose to disable a dmraid device, in which case the individual elements of the dmraid device will appear as separate hard drives. You can also choose to configure an iSCSI (SCSI over TCP/IP) target. To configure an ISCSI target invoke the 'Configure ISCSI Parameters' dialog by selecting 'Add ISCSI target' and clicking on the 'Add Drive' button. Fill in the details for the ISCSI target IP and provide a unique ISCSI initiator name to identify this system. Click the 'Add target' button to attempt connection to the SCSI target using this information.

Pakistan Computer Bureau

22

Figure 2.13. Configure ISCSI Parameters

Please note that you will be able to reattempt with a different ISCSI target IP should you enter it incorrectly, but in order to change the ISCSI initiator name you will need to restart the installation.

Pakistan Computer Bureau

23

2.13. Create Default Layout


Create default layout allows you to have some control concerning what data is removed (if any) from your system. Your options are: Remove all partitions on selected drives and create default layout select this option to remove all partitions on your hard drive(s) (this includes partitions created by other operating systems such as Windows VFAT or NTFS partitions). Caution
If you select this option, all data on the selected hard drive(s) is removed by the installation program. Do not select this option if you have information that you want to keep on the hard drive(s) where you are installing Red Hat Enterprise Linux.

Remove Linux partitions on selected drives and create default layout select this option to remove only Linux partitions (partitions created from a previous Linux installation). This does not remove other partitions you may have on your hard drive(s) (such as VFAT or FAT32 partitions). Use free space on selected drives and create default layout select this option to retain your current data and partitions, assuming you have enough free space available on your hard drive(s).

Pakistan Computer Bureau

24

Figure 2.14. Create Default Layout

Using your mouse, choose the storage drive(s) on which you want Red Hat Enterprise Linux to be installed. If you have two or more drives, you can choose which drive(s) should contain this installation. Unselected drives, and any data on them, are not touched. Caution
It is always a good idea to back up any data that you have on your systems. For example, if you are upgrading or creating a dual-boot system, you should back up any data you wish to keep on your drive(s). Mistakes do happen and can result in the loss of all your data.

Tip
If you have a RAID card, be aware that some BIOSes do not support booting from the RAID card. In cases such as these, the /boot/ partition must be created on a partition outside of the RAID array, such as on a separate hard drive. An internal hard drive is necessary to use for partition creation with problematic RAID cards.

Pakistan Computer Bureau

25

A /boot/ partition is also necessary for software RAID setups. If you have chosen to automatically partition your system, you should select Review and manually edit your /boot/ partition. To review and make any necessary changes to the partitions created by automatic partitioning, select the Review option. After selecting Review and clicking Next to move forward, the partitions created for you in Disk Druid appear. You can make modifications to these partitions if they do not meet your needs. Click Next once you have made your selections to proceed.

2.14. Partitioning Your System


If you chose one of the automatic partitioning options and selected Review, you can either accept the current partition settings (click Next), or modify the setup using Disk Druid, the manual partitioning tool. Note
Please note that in the text mode installation it is not possible to work with LVM (Logical Volumes) beyond viewing the existing setup. LVM can only be set up using the graphical Disk Druid program in a graphical installation.

If you chose to create a custom layout, you must tell the installation program where to install Red Hat Enterprise Linux. This is done by defining mount points for one or more disk partitions in which Red Hat Enterprise Linux is installed. You may also need to create and/or delete partitions at this time. Note
If you have not yet planned how to set up your partitions, At a bare minimum, you need an appropriately-sized root partition, and a swap partition equal to twice the amount of RAM you have on the system. Itanium system users should have a /boot/efi/ partition of approximately 100 MB and of type FAT (VFAT), a swap partition of at least 512 MB, and an appropriately-sized root (/) partition.

Pakistan Computer Bureau

26

Figure 2.15. Partitioning with Disk Druid on x86, AMD64, and Intel 64 Systems

The partitioning tool used by the installation program is Disk Druid. With the exception of certain esoteric situations, Disk Druid can handle the partitioning requirements for a typical installation.

2.14.1. Graphical Display of Hard Drive(s)


Disk Druid offers a graphical representation of your hard drive(s). Using your mouse, click once to highlight a particular field in the graphical display. Double-click to edit an existing partition or to create a partition out of existing free space. Above the display, you can review the Drive name (such as /dev/hda), the Geom (which shows the hard disk's geometry and consists of three numbers representing the number of cylinders, heads, and sectors as reported by the hard disk), and the Model of the hard drive as detected by the installation program.

Pakistan Computer Bureau

27

2.14.2. Disk Druid's Buttons


These buttons control Disk Druid's actions. They are used to change the attributes of a partition (for example the file system type and mount point) and also to create RAID devices. Buttons on this screen are also used to accept the changes you have made, or to exit Disk Druid. For further explanation, take a look at each button in order: New: Used to request a new partition. When selected, a dialog box appears containing fields (such as the mount point and size fields) that must be filled in. Edit: Used to modify attributes of the partition currently selected in the Partitions section. Selecting Edit opens a dialog box. Some or all of the fields can be edited, depending on whether the partition information has already been written to disk. You can also edit free space as represented in the graphical display to create a new partition within that space. Either highlight the free space and then select the Edit button, or double-click on the free space to edit it. To make a RAID device, you must first create (or reuse existing) software RAID partitions. Once you have created two or more software RAID partitions, select Make RAID to join the software RAID partitions into a RAID device. Delete: Used to remove the partition currently highlighted in the Current Disk Partitions section. You will be asked to confirm the deletion of any partition. Reset: Used to restore Disk Druid to its original state. All changes made will be lost if you Reset the partitions. RAID: Used to provide redundancy to any or all disk partitions. It should only be used if you have experience using RAID. To read more about RAID, refer to the Red Hat Enterprise Linux Deployment Guide. To make a RAID device, you must first create software RAID partitions. Once you have created two or more software RAID partitions, select RAID to join the software RAID partitions into a RAID device.

Pakistan Computer Bureau

28

LVM: Allows you to create an LVM logical volume. The role of LVM (Logical Volume Manager) is to present a simple logical view of underlying physical storage space, such as a hard drive(s). LVM manages individual physical disks or to be more precise, the individual partitions present on them. It should only be used if you have experience using LVM. To read more about LVM, refer to the Red Hat Enterprise Linux Deployment Guide. Note, LVM is only available in the graphical installation program. To create an LVM logical volume, you must first create partitions of type physical volume (LVM). Once you have created one or more physical volume (LVM) partitions, select LVM to create an LVM logical volume.

2.14.3. Partition Fields


Above the partition hierarchy are labels which present information about the partitions you are creating. The labels are defined as follows: Device: This field displays the partition's device name. Mount Point/RAID/Volume: A mount point is the location within the directory hierarchy at which a volume exists; the volume is "mounted" at this location. This field indicates where the partition is mounted. If a partition exists, but is not set, then you need to define its mount point. Double-click on the partition or click the Edit button. Type: This field shows the partition's file system type (for example, ext2, ext3, or vfat). Format: This field shows if the partition being created will be formatted. Size (MB): This field shows the partition's size (in MB). Start: This field shows the cylinder on your hard drive where the partition begins. End: This field shows the cylinder on your hard drive where the partition ends. Hide RAID device/LVM Volume Group members: Select this option if you do not want to view any RAID device or LVM Volume Group members that have
Pakistan Computer Bureau

29

been created.

2.14.4. Recommended Partitioning Scheme 2.14.4.1. Itanium systems


Unless you have a reason for doing otherwise, we recommend that you create the following partitions for Itanium systems: A /boot/efi/ partition (100 MB minimum) the partition mounted on /boot/efi/ contains all the installed kernels, the initrd images, and ELILO configuration files. Warning
You must create a /boot/efi/ partition of type VFAT and at least 100 MB in size as the first primary partition.

A swap partition (at least 256 MB) swap partitions are used to support virtual memory. In other words, data is written to a swap partition when there is not enough RAM to store the data your system is processing. If you are unsure about what size swap partition to create, make it twice the amount of RAM on your machine. It must be of type swap. Creation of the proper amount of swap space varies depending on a number of factors including the following (in descending order of importance): The applications running on the machine. The amount of physical RAM installed on the machine. The version of the OS. Swap should equal 2x physical RAM for up to 2 GB of physical RAM, and then an additional 1x physical RAM for any amount above 2 GB, but never less than 32 MB. So, if: M = Amount of RAM in GB, and S = Amount of swap in GB, then

Pakistan Computer Bureau

30

If M < 2 S = M *2 Else S=M + 2 Using this formula, a system with 2 GB of physical RAM would have 4 GB of swap, while one with 3 GB of physical RAM would have 5 GB of swap. Creating a large swap space partition can be especially helpful if you plan to upgrade your RAM at a later time. For systems with really large amounts of RAM (more than 32 GB) you can likely get away with a smaller swap partition (around 1x, or less, of physical RAM). A root partition (3.0 GB - 5.0 GB) this is where "/" (the root directory) is located. In this setup, all files (except those stored in /boot/efi) are on the root partition. A 3.0 GB partition allows you to install a minimal installation, while a 5.0 GB root partition lets you perform a full installation, choosing all package groups. 18.4.2. x86, AMD 64, and Intel@ 64 systems Unless you have a reason for doing otherwise, we recommend that you create the following partitions for x86, AMD64, and Intel 64 systems: A swap partition (at least 256 MB) swap partitions are used to support virtual memory. In other words, data is written to a swap partition when there is not enough RAM to store the data your system is processing. If you are unsure about what size swap partition to create, make it twice the amount of RAM on your machine. It must be of type swap. Creation of the proper amount of swap space varies depending on a number of factors including the following (in descending order of importance): The applications running on the machine. The amount of physical RAM installed on the machine.

Pakistan Computer Bureau

31

The version of the OS. Swap should equal 2x physical RAM for up to 2 GB of physical RAM, and then an additional 1x physical RAM for any amount above 2 GB, but never less than 32 MB. So, if: M = Amount of RAM in GB, and S = Amount of swap in GB, then

If M < 2 S = M *2 Else S = M + 2 Using this formula, a system with 2 GB of physical RAM would have 4 GB of swap, while one with 3 GB of physical RAM would have 5 GB of swap. Creating a large swap space partition can be especially helpful if you plan to upgrade your RAM at a later time. For systems with really large amounts of RAM (more than 32 GB) you can likely get away with a smaller swap partition (around 1x, or less, of physical RAM). A /boot/ partition (100 MB) the partition mounted on /boot/ contains the operating system kernel (which allows your system to boot Red Hat Enterprise Linux), along with files used during the bootstrap process. Due to limitations, creating a native ext3 partition to hold these files is required. For most users, a 100 MB boot partition is sufficient. Tip
If your hard drive is more than 1024 cylinders (and your system was manufactured more than two years ago), you may need to create a /boot/partition if you want the / (root) partition to use all of the remaining space on your hard drive.

Tip
If you have a RAID card, be aware that some BIOSes do not support booting from the RAID card. In cases such as these, the /boot/ partition must be created on a partition

Pakistan Computer Bureau

32

outside of the RAID array, such as on a separate hard drive.

A root partition (3.0 GB - 5.0 GB) this is where "/" (the root directory) is located. In this setup, all files (except those stored in /boot) are on the root partition. A 3.0 GB partition allows you to install a minimal installation, while a 5.0 GB root partition lets you perform a full installation, choosing all package groups. 2.14.5. Adding Partitions To add a new partition, select the New button. A dialog box appears (refer to Figure 2.16, Creating a New Partition). Note
You must dedicate at least one partition for this installation, and optionally more.

Figure 2.16. Creating a New Partition

Pakistan Computer Bureau

33

Mount Point: Enter the partition's mount point. For example, if this partition should be the root partition, enter /; enter /boot for the /boot partition, and so on. You can also use the pull-down menu to choose the correct mount point for your partition. For a swap partition the mount point should not be set setting the filesystem type to swap is sufficient. File System Type: Using the pull-down menu, select the appropriate file system type for this partition. Allowable Drives: This field contains a list of the hard disks installed on your system. If a hard disk's box is highlighted, then a desired partition can be created on that hard disk. If the box is not checked, then the partition will never be created on that hard disk. By using different checkbox settings, you can have Disk Druid place partitions where you need them, or let Disk Druid decide where partitions should go. Size (MB): Enter the size (in megabytes) of the partition. Note, this field starts with 100 MB; unless changed, only a 100 MB partition will be created. Additional Size Options: Choose whether to keep this partition at a fixed size, to allow it to "grow" (fill up the available hard drive space) to a certain point, or to allow it to grow to fill any remaining hard drive space available. If you choose Fill all space up to (MB), you must give size constraints in the field to the right of this option. This allows you to keep a certain amount of space free on your hard drive for future use. Force to be a primary partition: Select whether the partition you are creating should be one of the first four partitions on the hard drive. If unselected, the partition is created as a logical partition. OK: Select OK once you are satisfied with the settings and wish to create the partition. Cancel: Select Cancel if you do not want to create the partition. 2.14.5.1. File System Types Red Hat Enterprise Linux allows you to create different partition types, based on the file system they will use. The following is a brief description of the different
Pakistan Computer Bureau 34

file systems available, and how they can be utilized. ext2 An ext2 file system supports standard Unix file types (regular files, directories, symbolic links, etc). It provides the ability to assign long file names, up to 255 characters. ext3 The ext3 file system is based on the ext2 file system and has one main advantage journaling. Using a journaling file system reduces time spent recovering a file system after a crash as there is no need to fsck the file system. The ext3 file system is selected by default and is highly recommended. physical volume (LVM) Creating one or more physical volume (LVM) partitions allows you to create an LVM logical volume. LVM can improve performance when using physical disks. For more information regarding LVM, refer to the Red Hat Enterprise Linux Deployment Guide. software RAID Creating two or more software RAID partitions allows you to create a RAID device. For more information regarding RAID, refer to the chapter RAID (Redundant Array of Independent Disks) in the Red Hat Enterprise Linux Deployment Guide. Swap Swap partitions are used to support virtual memory. In other words, data is written to a swap partition when there is not enough RAM to store the data your system is processing. Refer to the Red Hat Enterprise Linux Deployment Guide for additional information. Vfat The VFAT file system is a Linux file system that is compatible with Microsoft Windows long filenames on the FAT file system. This file system must be used for the /boot/efi/

2.14.6. Editing Partitions


To edit a partition, select the Edit button or double-click on the existing partition.

Pakistan Computer Bureau

35

Note
If the partition already exists on your disk, you can only change the partition's mount point. To make any other changes, you must delete the partition and recreate it.

2.14.7. Deleting a Partition


To delete a partition, highlight it in the Partitions section and click the Delete button. Confirm the deletion when prompted.

2.15. x86, AMD64, and Intel 64 Boot Loader Configuration


To boot the system without boot media, you usually need to install a boot loader. A boot loader is the first software program that runs when a computer starts. It is responsible for loading and transferring control to the operating system kernel software. The kernel, in turn, initializes the rest of the operating system. GRUB (Grand Unified Bootloader), which is installed by default, is a very powerful boot loader. GRUB can load a variety of free operating systems, as well as proprietary operating systems with chain-loading (the mechanism for loading unsupported operating systems, such as DOS or Windows, by loading another boot loader).

Pakistan Computer Bureau

36

Figure 2.17. Boot Loader Configuration

If you do not want to install GRUB as your boot loader, click Change boot loader, where you can choose not to install a boot loader at all. If you already have a boot loader that can boot Red Hat Enterprise Linux and do not want to overwrite your current boot loader, choose Do not install a boot loader by clicking on the Change boot loader button. Caution
If you choose not to install GRUB for any reason, you will not be able to boot the system directly, and you must use another boot method (such as a commercial boot loader application). Use this option only if you are sure you have another way of booting the system!

Every bootable partition is listed, including partitions used by other operating systems. The partition holding the system's root file system has a Label of Red Hat Enterprise Linux (for GRUB). Other partitions may also have boot labels. To

Pakistan Computer Bureau

37

add or change the boot label for other partitions that have been detected by the installation program, click once on the partition to select it. Once selected, you can change the boot label by clicking the Edit button. Select Default beside the preferred boot partition to choose your default bootable OS. You cannot move forward in the installation unless you choose a default boot image. Note
The Label column lists what you must enter at the boot prompt, in non-graphical boot loaders, in order to boot the desired operating system.

Once you have loaded the GRUB boot screen, use the arrow keys to choose a boot label or type e for edit. You are presented with a list of items in the configuration file for the boot label you have selected. Boot loader passwords provide a security mechanism in an environment where physical access to your server is available. If you are installing a boot loader, you should create a password to protect your system. Without a boot loader password, users with access to your system can pass options to the kernel which can compromise your system security. With a boot loader password in place, the password must first be entered before selecting any non-standard boot options. However, it is still possible for someone with physical access to the machine to boot from a diskette, CD-ROM, or USB media if the BIOS support it. Security plans which include boot loader passwords should also address alternate boot methods. If you choose to use a boot loader password to enhance your system security, be sure to select the checkbox labeled Use a boot loader password. Once selected, enter a password and confirm it. To configure more advanced boot loader options, such as changing the drive order or passing options to the kernel, be sure Configure advanced boot loader options is selected before clicking Next.

2.15.1. Advanced Boot Loader Configuration


Now that you have chosen which boot loader to install, you can also determine

Pakistan Computer Bureau

38

where you want the boot loader to be installed. You may install the boot loader in one of two places: The master boot record (MBR) This is the recommended place to install a boot loader, unless the MBR already starts another operating system loader, such as System Commander. The MBR is a special area on your hard drive that is automatically loaded by your computer's BIOS, and is the earliest point at which the boot loader can take control of the boot process. If you install it in the MBR,when your machine boots, GRUB presents a boot prompt. You can then boot Red Hat Enterprise Linux or any other operating system that you have configured the boot loader to boot. The first sector of your boot partition This is recommended if you are already using another boot loader on your system. In this case, your other boot loader takes control first. You can then configure that boot loader to start GRUB, which then boots Red Hat Enterprise Linux.

Figure 2.18. Boot Loader Installation

Pakistan Computer Bureau

39

Tip
If you have a RAID card, be aware that some BIOSes do not support booting from the RAID card. In cases such as these, the boot loader should not be installed on the MBR of the RAID array. Rather, the boot loader should be installed on the MBR of the same drive as the /boot/ partition was created.

If your system only uses Red Hat Enterprise Linux, you should choose the MBR. Click the Change Drive Order button if you would like to rearrange the drive order or if your BIOS does not return the correct drive order. Changing the drive order may be useful if you have multiple SCSI adapters, or both SCSI and IDE adapters, and you want to boot from the SCSI device. The Force LBA32 (not normally required) option allows you to exceed the 1024 cylinder limit for the /boot/ partition. If you have a system which supports the LBA32 extension for booting operating systems above the 1024 cylinder limit, and you want to place your /boot/ partition above cylinder 1024, you should select this option. Tip
While partitioning your hard drive, keep in mind that the BIOS in some older systems cannot access more than the first 1024 cylinders on a hard drive. If this is the case, leave enough room for the /boot Linux partition on the first 1024 cylinders of your hard drive to boot Linux. The other Linux partitions can be after cylinder 1024.

In parted, 1024 cylinders equals 528MB. For more information, refer to:
http://www.pcguide.com/ref/hdd/bios/size MB504-c.html

To add default options to the boot command, enter them into the Kernel parameters field. Any options you enter are passed to the Linux kernel every time it boots.

2.15.2. Rescue Mode


Rescue mode provides the ability to boot a small Red Hat Enterprise Linux environment entirely from boot media or some other boot method instead of the system's hard drive. There may be times when you are unable to get Red Hat Enterprise Linux running completely enough to access files on your system's
Pakistan Computer Bureau

40

hard drive. Using rescue mode, you can access the files stored on your system's hard drive, even if you cannot actually run Red Hat Enterprise Linux from that hard drive. If you need to use rescue mode, try the following method: Using the CD-ROM to boot an x86, AMD64, or Intel 64 system, type linux rescue at the installation boot prompt. Itanium users should type elilo linux rescue to enter rescue mode.

2.15.3. Alternative Boot Loaders


If you do not wish to use a boot loader, you have several alternatives: LOADLIN You can load Linux from MS-DOS. Unfortunately, this requires a copy of the Linux kernel (and an initial RAM disk, if you have a SCSI adapter) to be available on an MS-DOS partition. The only way to accomplish this is to boot your Red Hat Enterprise Linux system using some other method (for example, from a boot CD-ROM) and then copy the kernel to an MS-DOS partition. LOADLIN is available from ftp://metalab.unc.edu/pub/Linux/system/boot/dualboot/ and associated mirror sites. SYSLINUX: SYSLINUX is an MS-DOS program very similar to LOADLIN. It is also available from ftp://metalab.unc.edu/pub/Linux/system/boot/loaders/ and associated mirror sites. Commercial boot loaders You can load Linux using commercial boot loaders. For example, System Commander and Partition Magic are able to boot Linux (but still require GRUB to be installed in your Linux root partition).

Pakistan Computer Bureau

41

Note
Boot loaders such as LOADLIN and System Commander are considered to be thirdparty boot loaders and are not supported by Red Hat.

2.15.4. SMP Motherboards and GRUB


In previous versions of Red Hat Enterprise Linux there were two different kernel versions, a uniprocessor version and an SMP version. In Red Hat Enterprise Linux 5.0.0 the kernel is SMP-enabled by default and will take advantage of multiple core, hyperthreading, and multiple CPU capabilities when they are present. This same kernel can run on single CPUs with a single core and no hyperthreading.

2.16. Time Zone Configuration


Set your time zone by selecting the city closest to your computer's physical location. Click on the map to zoom in to a particular geographical region of the world. From here there are two ways for you to select your time zone: Using your mouse, click on the interactive map to select a specific city (represented by a yellow dot). A red X appears indicating your selection. You can also scroll through the list at the bottom of the screen to select your time zone. Using your mouse, click

Pakistan Computer Bureau

42

Figure 2.21. Configuring the Time Zone

Select System Clock uses UTC if you know that your system is set to UTC. Tip
To change your time zone configuration after you have completed the installation, use the Time and Date Properties Tool.

Type the system-config-date command in a shell prompt to launch the Time and Date Properties Tool. If you are not root, it prompts you for the root password to continue. To run the Time and Date Properties Tool as a text-based application, use the command timeconfig.

2.17. Set Root Password


Setting up a root account and password is one of the most important steps during your installation. Your root account is similar to the administrator account used on Windows NT machines. The root account is used to install packages, upgrade RPMs, and perform most system maintenance. Logging in as root gives you complete control over your system.

Pakistan Computer Bureau

43

Note
The root user (also known as the superuser) has complete access to the entire system; for this reason, logging in as the root user is best done only to perform system maintenance or administration.

Pakistan Computer Bureau

44

Figure 2.22. Root Password

Use the root account only for system administration. Create a non-root account for your general use and su - to root when you need to fix something quickly. These basic rules minimize the chances of a typo or an incorrect command doing damage to your system. Tip
To become root, type su - at the shell prompt in a terminal window and then press Enter. Then, enter the root password and press Enter.

The installation program prompts you to set a root password2 for your system. You cannot proceed to the next stage of the installation process without entering a root password. The root password must be at least six characters long; the password you type is not echoed to the screen. You must enter the password twice; if the two passwords do not match, the installation program asks you to enter them again.

Pakistan Computer Bureau

45

You should make the root password something you can remember, but not something that is easy for someone else to guess. Your name, your phone number, qwerty, password, root, 123456, and anteater are all examples of bad passwords. Good passwords mix numerals with upper and lower case letters and do not contain dictionary words: Aard387vark or 420BMttNT, for example. Remember that the password is case-sensitive. If you write down your password, keep it in a secure place. However, it is recommended that you do not write down this or any password you create. Note
Do not use one of the example passwords offered in this manual. Using one of these passwords could be considered a security risk.

Tip
To change your root password after you have completed the installation, use the Root Password Tool.

Type the system-config-rootpassword command in a shell prompt to launch the Root Password Tool. If you are not root, it prompts you for the root password to continue.

2.18. Package Group Selection


Now that you have made most of the choices for your installation, you are ready to confirm the default package selection or customize packages for your system. The Package Installation Defaults screen appears and details the default package set for your Red Hat Enterprise Linux installation. This screen varies depending on the version of Red Hat Enterprise Linux you are installing. If you choose to accept the current package list. To customize your package set further, select the Customize now option on the screen. Clicking Next takes you to the Package Group Selection screen. You can select package groups, which group components together according to function (for example, X Window System and Editors), individual packages, or a combination of the two.

Pakistan Computer Bureau

46

Note
Users of Itanium systems who want support for developing or running 32-bit applications are encouraged to select the Compatibility Arch Support and Compatibility Arch Development Support packages to install architecure specific support for their systems.

To select a component, click on the checkbox beside it (refer to Figure 2.23, Package Group Selection).

Figure 2.23. Package Group Selection

Select each component you wish to install. Once a package group has been selected, if optional components are available you can click on Optional packages to view which packages are installed by default, and to add or remove optional packages from that group. If there are no optional components this button will be disabled.

Pakistan Computer Bureau

47

Figure 2.24. Package Group Details

2.19. Preparing to Install 2.19.1. Prepare to Install


A screen preparing you for the installation of Red Hat Enterprise Linux now appears. For your reference, a complete log of your installation can be found in /root/install.log once you reboot your system. Warning
If, for some reason, you would rather not continue with the installation process, this is your last opportunity to safely cancel the process and reboot your machine. Once you press the Next button, partitions are written and packages are installed. If you wish to abort the installation, you should reboot now before any existing information on any hard drive is rewritten.

Pakistan Computer Bureau

48

To cancel this installation process, press your computer's Reset button or use the Control-Alt-Delete key combination to restart your machine.

2.20. Installing Packages


At this point there is nothing left for you to do until all the packages have been installed. How quickly this happens depends on the number of packages you have selected and your computer's speed.

2.21. Installation Complete


Congratulations! Your Red Hat Enterprise Linux installation is now complete! The installation program prompts you to prepare your system for reboot. Remember to remove any installation media if it is not ejected automatically upon reboot. After your computer's normal power-up sequence has completed, the graphical boot loader prompt appears at which you can do any of the following things: Press Enter causes the default boot entry to be booted. Select a boot label, followed by Enter causes the boot loader to boot the operating system corresponding to the boot label. Do nothing after the boot loader's timeout period, (by default, five seconds) the boot loader automatically boots the default boot entry. Do whatever is appropriate to boot Red Hat Enterprise Linux. One or more screens of messages should scroll by. Eventually, a login: prompt or a GUI login screen (if you installed the X Window System and chose to start X automatically) appears. The first time you start your Red Hat Enterprise Linux system in run level 5 (the graphical run level), the Setup Agent is presented, which guides you through the Red Hat Enterprise Linux configuration. Using this tool, you can set your system time and date, install software, register your machine with Red Hat Network, and more. The Setup Agent lets you configure your environment at the beginning, so that you can get started using your Red Hat Enterprise Linux system quickly.

Pakistan Computer Bureau

49

2.22. Itanium Systems Booting Your Machine and Post-Installation Setup


This section describes how to boot your Itanium into Red Hat Enterprise Linux and how to set your EFI console variables so that Red Hat Enterprise Linux is automatically booted when the machine is powered on. After you reboot your system at the end of the installation program, type the following command to boot into Red Hat Enterprise Linux: elilo After you type elilo, the default kernel listed in the /boot/efi/elilo.conf configuration file is loaded. (The first kernel listed in the file is the default.) If you want to load a different kernel, type the label name of the kernel from the file /boot/efi/elilo.conf after the elilo command. For example, to load the kernel named linux, type: elilo linux If you do not know the names of the installed kernels, you can view the /boot/efi/elilo.conf file in EFI with the following instructions: 1. At the Shell> prompt, change devices to the system partition (mounted as /boot/efi in Linux). For example, if fs0 is the system boot partition, type fs0: at the EFI Shell prompt. 2. Type ls at the fs0:\> to make sure you are in the correct partition. 3. Then type: Shell>type elilo.conf This command displays the contents of the configuration file. Each stanza contains a line beginning with label followed by a label name for that kernel. The label name is what you type after elilo to boot the different kernels.

2.22.1. Post-Installation Boot Loader Options


In addition to specifying a kernel to load, you can also enter other boot options such as single for single user mode or mem=1024M to force Red Hat Enterprise
Pakistan Computer Bureau

50

Linux to use 1024 MB of memory. To pass options to the boot loader, enter the following at the EFI Shell prompt (replace linux with the label name of the kernel you want to boot and option with the boot options you want to pass to the kernel): elilo linux option

2.22.2. Booting Red Hat Enterprise Linux Automatically


After installing Red Hat Enterprise Linux you can type elilo and any boot options at the EFI Shell prompt each time you wish to boot your Itanium system. However, if you wish to configure your system to boot into Red Hat Enterprise Linux automatically, you need to configure the EFI Boot Manager. To configure the EFI Boot Manager (may vary slightly depending on your hardware): 1. Boot the Itanium system and choose Boot option maintenance menu from the EFI Boot Manager menu. 2. Choose Add a Boot Option from the Main Menu. 3. Select the system partition that is mounted as /boot/efi/ in Linux. 4. Select the elilo.efi file. 5. At the Enter New Description: prompt, type Red Hat Enterprise Linux 5, or any name that you want to appear on the EFI Boot Manager menu. 6. At the Enter Boot Option Data Type: prompt, enter N for No Boot Option if you do not want to pass options to the ELILO boot loader. This option works for most cases. If you want to pass options to the boot loader, you can configure it in the /boot/efi/elilo.conf configuration file instead. 7. Answer Yes to the Save changes to NVRAM prompt. This returns you to the EFI Boot Maintenance Manager menu. 8. Next, you want to make the Red Hat Enterprise Linux 5 menu item the default. A list of boot options appears. Move the Red Hat Enterprise Linux 5 menu item up to the top of the list by selecting it with the arrow keys and pressing the u key to move it up the list. You can move items down the list by

Pakistan Computer Bureau

51

selecting it and pressing the d key. After changing the boot order, choose Save changes to NVRAM. Choose Exit to return to the Main Menu. 9. Optionally, you can change the boot timeout value by choosing Set Auto Boot TimeOut => Set Timeout Value from the Main Menu. 10. Return to the EFI Boot Manager by selecting Exit.

2.22.2.1. Using a Startup Script


It is recommended that you configure the ELILO Boot Manager to boot Red Hat Enterprise Linux automatically. However, if you require additional commands to be executed before starting the ELILO boot loader, you can create a startup script named startup.nsh. The last command should be elilo to boot into Linux. The startup.nsh script should be in the /boot/efi partition (/boot/efi/startup.nsh) and contain the following text: echo -off your set of commands elilo You can either create this file after booting into Red Hat Enterprise Linux or use the editor built into the EFI shell. To use the EFI shell, at the Shell> prompt, change devices to the system partition (mounted as /boot/efi in Linux). For example, if fs0 is the system boot partition, type fs0: at the EFI Shell prompt. Type ls to make sure you are in the correct partition. Then type edit startup.nsh. Type the contents of the file and save it. The next time the system boots, EFI detects the startup.nsh file and use it to boot the system. To stop EFI from loading the file, type Ctrl-C. This aborts the process, and returns you to the EFI shell prompt.

Pakistan Computer Bureau

52

3.1 Removing Red Hat Enterprise Linux


To uninstall Red Hat Enterprise Linux from your x86-based system, you must remove the Red Hat Enterprise Linux boot loader information from your master boot record (MBR). Note
It is always a good idea to backup any data that you have on your system(s). Mistakes do happen and can result in the loss all of your data.

In DOS and Windows, use the Windows fdisk utility to create a new MBR with the undocumented flag /mbr. This ONLY rewrites the MBR to boot the primary DOS partition. The command should look like the following: fdisk /mbr If you need to remove Linux from a hard drive and have attempted to do this with the default DOS (Windows) fdisk, you will experience the Partitions exist but they do not exist problem. The best way to remove non-DOS partitions is with a tool that understands partitions other than DOS. To begin, insert the Red Hat Enterprise Linux CD #1 and boot your system. Once you have booted off the CD, a boot prompt appears. At the boot prompt, type: linux rescue. This starts the rescue mode program. You are prompted for your keyboard and language requirements. Enter these values as you would during the installation of Red Hat Enterprise Linux. Next, a screen appears telling you that the program attempts to find a Red Hat Enterprise Linux install to rescue. Select Skip on this screen. After selecting Skip, you are given a command prompt where you can access the partitions you would like to remove. First, type the command list-harddrives. This command lists all hard drives on your system that are recognizable by the installation program, as well as their sizes in megabytes.

Pakistan Computer Bureau

53

Warning
Be careful to remove only the necessary Red Hat Enterprise Linux partitions. Removing other partitions could result in data loss or a corrupted system environment.

To remove partitions, use the partitioning utility parted. Start parted, where /dev/had is the device on which to remove the partition: parted /dev/hda Using the print command, view the current partition table to determine the minor number of the partition to remove: print The print command also displays the partition's type (such as linux-swap, ext2, ext3, and so on). Knowing the type of the partition helps you in determining whether to remove the partition. Remove the partition with the command rm. For example, to remove the partition with minor number 3: rm 3 Important
The changes start taking place as soon as you press [Enter], so review the command before committing to it.

After removing the partition, use the print command to confirm that it is removed from the partition table. Once you have removed the Linux partitions and made all of the changes you need to make, type quit to quit parted. After quitting parted, type exit at the boot prompt to exit rescue mode and reboot your system, instead of continuing with the installation. The system should reboot automatically. If it does not, you can reboot your computer using Control-Alt-Delete.

Pakistan Computer Bureau

54

This appendix discusses some common installation problems and their solutions.

4.1. You are Unable to Boot Red Hat Enterprise Linux 4.1.1. Are You Unable to Boot With Your RAID Card?
If you have performed an installation and cannot boot your system properly, you may need to reinstall and create your partitions differently. Some BIOSes do not support booting from RAID cards. At the end of an installation, a text-based screen showing the boot loader prompt (for example, GRUB: ) and a flashing cursor may be all that appears. If this is the case, you must repartition your system. Whether you choose automatic or manual partitioning, you must install your /boot partition outside of the RAID array, such as on a separate hard drive. An internal hard drive is necessary to use for partition creation with problematic RAID cards. You must also install your preferred boot loader (GRUB or LILO) on the MBR of a drive that is outside of the RAID array. This should be the same drive that hosts the /boot/ partition. Once these changes have been made, you should be able to finish your installation and boot the system properly.

4.1.2. Is Your System Displaying Signal 11 Errors?


A signal 11 errors, commonly know as a segmentation fault, means that the program accessed a memory location that was not assigned to it. A signal 11 error may be due to a bug in one of the software programs that is installed, or faulty hardware. If you receive a fatal signal 11 error during your installation, it is probably due to a hardware error in memory on your system's bus. Like other operating systems, Red Hat Enterprise Linux places its own demands on your system's hardware. Some of this hardware may not be able to meet those demands, even if they work properly under another OS.

Pakistan Computer Bureau

55

Ensure that you have the latest installation updates and images from Red Hat. Review the online errata to see if newer versions are available. If the latest images still fail, it may be due to a problem with your hardware. Commonly, these errors are in your memory or CPU-cache. A possible solution for this error is turning off the CPU-cache in the BIOS, if your system supports this. You could also try to swap your memory around in the motherboard slots to check if the problem is either slot or memory related. Another option is to perform a media check on your installation CD-ROMs. The Red Hat Enterprise Linux installation program has the ability to test the integrity of the installation media. It works with the CD, DVD, hard drive ISO, and NFS ISO installation methods. Red Hat recommends that you test all installation media before starting the installation process, and before reporting any installation-related bugs (many of the bugs reported are actually due to improperly-burned CDs). To use this test, type the following command at the boot: or yaboot: prompt (prepend with elilo for Itanium systems): linux mediacheck For more information concerning signal 11 errors, refer to: http://www.bitwizard.nl/sig11/

4.2. Trouble Beginning the Installation 4.2.1. Problems with Booting into the Graphical Installation
There are some video cards that have trouble booting into the graphical installation program. If the installation program does not run using its default settings, it tries to run in a lower resolution mode. If that still fails, the installation program attempts to run in text mode. One possible solution is to try using the resolution= boot option. This option may be most helpful for laptop users. Another solution to try is the driver= option to specify the driver that should be loaded for your video card. If this works, it should be reported as a bug as the installer has failed to autodetect your videocard.

Pakistan Computer Bureau

56

Note
To disable frame buffer support and allow the installation program to run in text mode, try using the nofb boot option. This command may be necessary for accessibility with some screen reading hardware.

4.3. Trouble during the Installation 4.3.1. No devices found to install Red Hat Enterprise Linux Error Message
If you receive an error message stating No devices found to install Red Hat Enterprise Linux, there is probably a SCSI controller that is not being recognized by the installation program. You can also refer to the Red Hat Hardware Compatibility List, available online at: http://hardware.redhat.com/hcl/

4.3.2. Saving Traceback Messages Without a Diskette Drive


If you receive a traceback error message during installation, you can usually save it to a diskette. If you do not have a diskette drive available in your system, you can scp the error message to a remote system. When the traceback dialog appears, the traceback error message is automatically written to a file named /tmp/anacdump.txt. Once the dialog appears, switch over to a new tty (virtual console) by pressing the keys CtrlAlt-F2 and scp the message written to /tmp/anacdump.txt to a known working remote system.

4.3.3. Trouble with Partition Tables


The partition table on device hda was unreadable. To create new partitions it must be initialized, causing the loss of ALL DATA on this drive. you may not have a partition table on that drive or the partition table on the drive may not be recognizable by the partitioning software used in the installation program.
Pakistan Computer Bureau 57

Users who have used programs such as EZ-BIOS have experienced similar problems, causing data to be lost (assuming the data was not backed up before the installation began) that could not be recovered. No matter what type of installation you are performing, backups of the existing data on your systems should always be made.

4.3.4. Using Remaining Space


You have a swap and a / (root) partition created, and you have selected the root partition to use the remaining space, but it does not fill the hard drive. If your hard drive is more than 1024 cylinders, you must create a /boot partition if you want the / (root) partition to use all of the remaining space on your hard drive.

4.3.5. Other Partitioning Problems


If you are using Disk Druid to create partitions, but cannot move to the next screen, you probably have not created all the partitions necessary for Disk Druid's dependencies to be satisfied. You must have the following partitions as a bare minimum: A / (root) partition A <swap> partition of type swap Tip
When defining a partition's type as swap, do not assign it a mount point. Disk Druid automatically assigns the mount point for you.

4.3.6. Other Partitioning Problems for Itanium System Users


If you are using Disk Druid to create partitions, but cannot move to the next screen, you probably have not created all the partitions necessary for Disk Druid's dependencies to be satisfied. You must have the following partitions as a bare minimum:

Pakistan Computer Bureau

58

A /boot/efi/ partition of type VFAT A / (root) partition A <swap> partition of type swap Tip
When defining a partition's type as swap, you do not have to assign it a mount point. Disk Druid automatically assigns the mount point for you.

4.3.7. Are You Seeing Python Errors?


During some upgrades or installations of Red Hat Enterprise Linux, the installation program (also known as anaconda) may fail with a Python or traceback error. This error may occur after the selection of individual packages or while trying to save the upgrade log in the /tmp/directory. The error may look similar to: Traceback (innermost last): File "/var/tmp/anaconda7.1//usr/lib/anaconda/iw/progress_gui.py", line 20, in run rc = self.todo.doInstall () File "/var/tmp/anaconda-7.1//usr/lib/anaconda/todo.py", line 1468, in doInstall self.fstab.savePartitions () File "fstab.py", line 221, in savePartitions sys.exit(0) SystemExit: 0 Local variables in innermost frame: self: <fstab.GuiFstab instance at 8446fe0> sys: <module 'sys' (built-in)> ToDo object: (itodo ToDo p1 (dp2 S'method' p3 (iimage CdromInstallMethod p4 (dp5 S'progressWindow' p6 <failed> This error occurs in some systems where links to /tmp/ are symbolic to other locations or have been changed since creation. These symbolic or changed links are invalid during the installation process, so the installation program cannot

Pakistan Computer Bureau

59

write information and fails.

If you experience such an error, first try to download any available errata for anaconda. Errata can be found at: http://www.redhat.com/support/errata/ The anaconda website may also be a useful reference and can be found online at: http://rhlinux.redhat.com/anaconda/ You can also search for bug reports related to this problem. To search Red Hat's bug tracking system, go to: http://bugzilla.redhat.com/bugzilla/ Finally, if you are still facing problems related to this error, register your product and contact our support team. To register your product, go to: http://www.redhat.com/apps/activate/

4.4. Problems After Installation 4.4.1. Trouble With the Graphical GRUB Screen on an x86-based System?
If you are experiencing problems with GRUB, you may need to disable the graphical boot screen. To do this, become the root user and edit the /boot/grub/grub.conf file. Within the grub.conf file, comment out the line which begins with splashimage by inserting the # character at the beginning of the line. Press Enter to exit the editing mode. Once the boot loader screen has returned, type b to boot the system. Once you reboot, the grub.conf file is reread and any changes you have made take effect. You may re-enable the graphical boot screen by uncommenting (or adding) the above line back into the grub.conf file.
Pakistan Computer Bureau 60

4.4.2. Booting into a Graphical Environment


If you have installed the X Window System but are not seeing a graphical desktop environment once you log into your Red Hat Enterprise Linux system, you can start the X Window System graphical interface using the command startx. Once you enter this command and press Enter, the graphical desktop environment is displayed. Note, however, that this is just a one-time fix and does not change the log in process for future log ins. To set up your system so that you can log in at a graphical login screen, you must edit one file, /etc/inittab, by changing just one number in the runlevel section. When you are finished, reboot the computer. The next time you log in, you are presented with a graphical login prompt. Open a shell prompt. If you are in your user account, become root by typing the su command. Now, type gedit /etc/inittab to edit the file with gedit. The file /etc/inittab opens. Within the first screen, a section of the file which looks like the following appears: # Default runlevel. The runlevels used by RHS are: # 0 - halt (Do NOT set initdefault to this) # 1 - Single user mode # 2 - Multiuser, without NFS (The same as 3, if you do not have networking) # 3 - Full multiuser mode # 4 - unused # 5 - X11 # 6 - reboot (Do NOT set initdefault to this) # id:3:initdefault: To change from a console to a graphical login, you should change the number in the line id:3:initdefault: from a 3 to a 5.

Pakistan Computer Bureau

61

Warning
Change only the number of the default runlevel from 3 to 5.

Your changed line should look like the following: id:5:initdefault: When you are satisfied with your change, save and exit the file using the Ctrl-Q keys. A window appears and asks if you would like to save the changes. Click Save. The next time you log in after rebooting your system, you are presented with a graphical login prompt.

4.4.3. Problems with the X Window System (GUI)


If you are having trouble getting X (the X Window System) to start, you may not have installed it during your installation. If you want X, you can either install the packages from the Red Hat Enterprise Linux CD-ROMs or perform an upgrade. If you elect to upgrade, select the X Window System packages, and choose GNOME, KDE, or both, during the upgrade package selection process.

4.4.4. Problems with the X Server Crashing and Non-Root Users


If you are having trouble with the X server crashing when anyone other than root logs in, you may have a full file system (or, a lack of available hard drive space). To verify that this is the problem you are experiencing, run the following command: df -h The df command should help you diagnose which partition is full. For additional information about df and an explanation of the options available (such as the -h option used in this example), refer to the df man page by typing man df at a shell prompt.

Pakistan Computer Bureau

62

A key indicator is 100% full or a percentage above 90% or 95% on a partition. The /home/ and /tmp/ partitions can sometimes fill up quickly with user files. You can make some room on that partition by removing old files. After you free up some disk space, try running X as the user that was unsuccessful before.

4.4.5. Problems When You Try to Log In


If you did not create a user account in the Setup Agent, log in as root and use the password you assigned to root. If you cannot remember your root password, boot your system as linux single. Itanium users must enter boot commands with elilo followed by the boot command. If you are using an x86-based system and GRUB is your installed boot loader, type e for edit when the GRUB boot screen has loaded. You are presented with a list of items in the configuration file for the boot label you have selected. Choose the line that starts with kernel and type e to edit this boot entry. At the end of the kernel line, add: single Press Enter to exit edit mode. Once the boot loader screen has returned, type b to boot the system. Once you have booted into single user mode and have access to the # prompt, you must type passwd root, which allows you to enter a new password for root. At this point you can type shutdown -r now to reboot the system with the new root password. If you cannot remember your user account password, you must become root. To become root, type su - and enter your root password when prompted. Then, type passwd <username>. This allows you to enter a new password for the specified user account. If the graphical login screen does not appear, check your hardware for compatibility issues. The Hardware Compatibility List can be found at: http://hardware.redhat.com/hcl/

Pakistan Computer Bureau

63

4.4.6. Is Your RAM Not Being Recognized?


Sometimes, the kernel does not recognize all of your memory (RAM). You can check this with the cat /proc/meminfo command. Verify that the displayed quantity is the same as the known amount of RAM in your system. If they are not equal, add the following line to the /boot/grub/grub.conf: mem=xxM Replace xx with the amount of RAM you have in megabytes. In /boot/grub/grub.conf, the above example would look similar to the following: # NOTICE: You have a /boot partition. This means that # all kernel paths are relative to /boot/ default=0 timeout=30 splashimage=(hd0,0)/grub/splash.xpm.gz title Red Hat Enterprise Linux (2.6.9-5.EL) root (hd0,0) kernel /vmlinuz-2.6.9-5.EL ro root=/dev/hda3 mem=128M Once you reboot, the changes made to grub.conf are reflected on your system. Once you have loaded the GRUB boot screen, type e for edit. You are presented with a list of items in the configuration file for the boot label you have selected. Choose the line that starts with kernel and type e to edit this boot entry. At the end of the kernel line, add mem=xxM where xx equals the amount of RAM in your system. Press Enter to exit edit mode. Once the boot loader screen has returned, type b to boot the system. Itanium users must enter boot commands with elilo followed by the boot command. Remember to replace xx with the amount of RAM in your system. Press Enter to boot.
Pakistan Computer Bureau 64

4.4.7. Your Printer Does Not Work


If you are not sure how to set up your printer or are having trouble getting it to work properly, try using the Printer Configuration Tool. Type the system-config-printer command at a shell prompt to launch the Printer Configuration Tool. If you are not root, it prompts you for the root password to continue.

4.4.8. Problems with Sound Configuration


If, for some reason, you do not hear sound and know that you do have a sound card installed, you can run the Sound Card Configuration Tool (systemconfig-soundcard) utility. To use the Sound Card Configuration Tool, choose Main Menu => System =>Administration => Soundcard Detection in GNOME, or Main Menu => Administration =>Soundcard Detection in KDE. A small text box pops up prompting you for your root password. You can also type the system-config-soundcard command at a shell prompt to launch the Sound Card Configuration Tool. If you are not root, it prompts you for the root password to continue. If the Sound Card Configuration Tool does not work (if the sample does not play and you still do not have audio sounds), it is likely that your sound card is not yet supported in Red Hat Enterprise Linux.

4.4.9. Apache-based httpd service/Sendmail Hangs During Startup


If you are having trouble with the Apache-based httpd service or Sendmail hanging at startup, make sure the following line is in the /etc/hosts file: 127.0.0.1 localhost.localdomain localhost

Pakistan Computer Bureau

65

When a computer with Red Hat Enterprise Linux is turned on, the operating system is loaded into memory by a special program called a boot loader. A boot loader usually exists on the system's primary hard drive (or other media device) and has the sole responsibility of loading the Linux kernel with its required files or (in some cases) other operating systems into memory.

5.1. Boot Loaders and System Architecture


Each architecture capable of running Red Hat Enterprise Linux uses a different boot loader. The following table lists the boot loaders available for each architecture: Architecture AMD AMD64 IBMeServerSystem i IBMeServerSystem p IBMSystem z IBMSystem z IntelItanium x86 Boot Loaders GRUB OS/400 YABOOT z/IPL z/IPL ELILO GRUB
Table 5.1. Boot Loaders by Architecture

This chapter discusses commands and configuration options for the GRUB boot loader included with Red Hat Enterprise Linux for the x86 architecture.

5.2. GRUB
The GNU GRand Unified Boot loader (GRUB) is a program which enables the selection of the installed operating system or kernel to be loaded at system boot time. It also allows the user to pass arguments to the kernel.

Pakistan Computer Bureau

66

5.2.1. GRUB and the x86 Boot Process


GRUB loads itself into memory in the following stages: 1. The Stage 1 or primary boot loader is read into memory by the BIOS from the MBR1. The primary boot loader exists on less than 512 bytes of disk space within the MBR and is capable of loading either the Stage 1.5 or Stage 2 boot loader. 2. The Stage 1.5 boot loader is read into memory by the Stage 1 boot loader, if necessary. Some hardware requires an intermediate step to get to the Stage 2 boot loader. This is sometimes true when the /boot/ partition is above the 1024 cylinder head of the hard drive or when using LBA mode. The Stage 1.5 boot loader is found either on the /boot/ partition or on a small part of the MBR and the /boot/ partition. 3. The Stage 2 or secondary boot loader is read into memory. The secondary boot loader displays the GRUB menu and command environment. This interface allows the user to select which kernel or operating system to boot, pass arguments to the kernel, or look at system parameters. 4. The secondary boot loader reads the operating system or kernel as well as the contents of /boot/sysroot/ into memory. Once GRUB determines which operating system or kernel to start, it loads it into memory and transfers control of the machine to that operating system. The method used to boot Red Hat Enterprise Linux is called direct loading because the boot loader loads the operating system directly. There is no intermediary between the boot loader and the kernel. The boot process used by other operating systems may differ. For example, the MicrosoftWindows operating system, as well as other operating systems, are loaded using chain loading. Under this method, the MBR points to the first sector of the partition holding the operating system, where it finds the files necessary to actually boot that operating system. GRUB supports both direct and chain loading boot methods, allowing it to boot almost any operating system.

Pakistan Computer Bureau

67

Warning
During installation, Microsoft's DOS and Windows installation programs completely overwrite the MBR, destroying any existing boot loaders. If creating a dual-boot system, it is best to install the Microsoft operating system first.

5.2.2. Features of GRUB


GRUB contains several features that make it preferable to other boot loaders available for the x86 architecture. Below is a partial list of some of the more important features: GRUB provides a true command-based, pre-OS environment on x86 machines. This feature affords the user maximum flexibility in loading operating systems with specified options or gathering information about the system. For years, many non-x86 architectures have employed pre-OS environments that allow system booting from a command line. GRUB supports Logical Block Addressing (LBA) mode. LBA places the addressing conversion used to find files in the hard drive's firmware, and is used on many IDE and all SCSI hard devices. Before LBA, boot loaders could encounter the 1024-cylinder BIOS limitation, where the BIOS could not find a file after the 1024 cylinder head of the disk. LBA support allows GRUB to boot operating systems from partitions beyond the 1024-cylinder limit, so long as the system BIOS supports LBA mode. Most modern BIOS revisions support LBA mode. GRUB can read ext2 partitions. This functionality allows GRUB to access its configuration file, /boot/grub/grub.conf, every time the system boots, eliminating the need for the user to write a new version of the first stage boot loader to the MBR when configuration changes are made. The only time a user needs to reinstall GRUB on the MBR is if the physical location of the /boot/ partition is moved on the disk.

5.3. Installing GRUB


If GRUB was not installed during the installation process, it can be installed afterward. Once installed, it automatically becomes the default boot loader. Before installing GRUB, make sure to use the latest GRUB package available or

Pakistan Computer Bureau

68

use the GRUB package from the installation CD-ROMs. For instructions on installing packages, refer to the chapter titled Package Management with RPM in the Red Hat Enterprise Linux Deployment Guide. Once the GRUB package is installed, open a root shell prompt and run the command /sbin/grub-install <location>, where <location> is the location that the GRUB Stage 1 boot loader should be installed. For example, the following command installs GRUB to the MBR of the master IDE device on the primary IDE bus: /sbin/grub-install /dev/hda The next time the system boots, the GRUB graphical boot loader menu appears before the kernel loads into memory. Important
If GRUB is installed on a RAID 1 array, the system may become unbootable in the event of disk failure. An unsupported workaround is provided online at the following URL:

http://www.dur.ac.uk/a.d.stribblehill/mirrored_grub.html

5.4. GRUB Terminology


One of the most important things to understand before using GRUB is how the program refers to devices, such as hard drives and partitions. This information is particularly important when configuring GRUB to boot multiple operating systems.

5.4.1. Device Names


When referring to a specific device with GRUB, do so using the following format (note that the parentheses and comma are very important syntactically): (<type-of-device><bios-device-number>,<partition-number>) The <type-of-device> specifies the type of device from which GRUB boots. The two most common options are hd for a hard disk or fd for a 3.5 diskette. A lesser used device type is also available called nd for a network disk. Instructions on configuring GRUB to boot over the network are available online at

Pakistan Computer Bureau

69

http://www.gnu.org/software/grub/manual/. The <bios-device-number> is the BIOS device number. The primary IDE hard drive is numbered 0 and a secondary IDE hard drive is numbered 1. This syntax is roughly equivalent to that used for devices by the kernel. For example, the a in hda for the kernel is analogous to the 0 in hd0 for GRUB, the b in hdb is analogous to the 1 in hd1, and so on. The <partition-number> specifies the number of a partition on a device. Like the <bios-device-number>, most types of partitions are numbered starting at 0. However, BSD partitions are specified using letters, with a corresponding to 0, b corresponding to 1, and so on.
Tip The numbering system for devices under GRUB always begins with 0, not 1. Failing to make this distinction is one of the most common mistakes made by new users.

To give an example, if a system has more than one hard drive, GRUB refers to the first hard drive as (hd0) and the second as (hd1). Likewise, GRUB refers to the first partition on the first drive as (hd0,0) and the third partition on the second hard drive as (hd1,2). In general the following rules apply when naming devices and partitions under GRUB: It does not matter if system hard drives are IDE or SCSI, all hard drives begin with the letters hd. The letters fd are used to specify 3.5 diskettes. To specify an entire device without respect to partitions, leave off the comma and the partition number. This is important when telling GRUB to configure the MBR for a particular disk. For example, (hd0) specifies the MBR on the first device and (hd3) specifies the MBR on the fourth device. If a system has multiple drive devices, it is very important to know how the drive boot order is set in the BIOS. This is a simple task if a system has only IDE or SCSI drives, but if there is a mix of devices, it becomes critical that the type of drive with the boot partition be accessed first.

Pakistan Computer Bureau

70

5.4.2. File Names and Blocklists


When typing commands to GRUB that reference a file, such as a menu list, it is necessary to specify an absolute file path immediately after the device and partition numbers. The following illustrates the structure of such a command: (<device-type><device-number>,<partition-number>)</path/to/file> In this example, replace <device-type> with hd, fd, or nd. Replace <devicenumber> with the integer for the device. Replace </path/to/file> with an absolute path relative to the top-level of the device. It is also possible to specify files to GRUB that do not actually appear in the file system, such as a chain loader that appears in the first few blocks of a partition. To load such files, provide a blocklist that specifies block by block where the file is located in the partition. Since a file is often comprised of several different sets of blocks, blocklists use a special syntax. Each block containing the file is specified by an offset number of blocks, followed by the number of blocks from that offset point. Block offsets are listed sequentially in a comma-delimited list. The following is a sample blocklist: 0+50,100+25,200+1 This sample blocklist specifies a file that starts at the first block on the partition and uses blocks 0 through 49, 100 through 124, and 200. Knowing how to write blocklists is useful when using GRUB to load operating systems which require chain loading. It is possible to leave off the offset number of blocks if starting at block 0. As an example, the chain loading file in the first partition of the first hard drive would have the following name: (hd0,0)+1 The following shows the chainloader command with a similar blocklist designation at the GRUB command line after setting the correct device and partition as root:

Pakistan Computer Bureau

71

chainloader +1

5.4.3. The Root File System and GRUB


The use of the term root file system has a different meaning in regard to GRUB. It is important to remember that GRUB's root file system has nothing to do with the Linux root file system. The GRUB root file system is the top level of the specified device. For example, the image file (hd0,0)/grub/splash.xpm.gz is located within the /grub/ directory at the top-level (or root) of the (hd0,0) partition (which is actually the /boot/ partition for the system). Next, the kernel command is executed with the location of the kernel file as an option. Once the Linux kernel boots, it sets up the root file system that Linux users are familiar with. The original GRUB root file system and its mounts are forgotten; they only existed to boot the kernel file.

5.5. GRUB Interfaces


GRUB features three interfaces which provide different levels of functionality. Each of these interfaces allows users to boot the Linux kernel or another operating system. The interfaces are as follows: Note
The following GRUB interfaces can only be accessed by pressing any key within the three seconds of the GRUB menu bypass screen.

Menu Interface This is the default interface shown when GRUB is configured by the installation program. A menu of operating systems or preconfigured kernels are displayed as a list, ordered by name. Use the arrow keys to select an operating system or kernel version and press the Enter key to boot it. If you do nothing on this screen, then after the time out period expires GRUB will load the default option. Press the e key to enter the entry editor interface or the c key to load a command line interface.

Pakistan Computer Bureau

72

Menu Entry Editor Interface To access the menu entry editor, press the e key from the boot loader menu. The GRUB commands for that entry are displayed here, and users may alter these command lines before booting the operating system by adding a command line (o inserts a new line after the current line and O inserts a new line before it), editing one (e), or deleting one (d). After all changes are made, the b key executes the commands and boots the operating system. The Esc key discards any changes and reloads the standard menu interface. The c key loads the command line interface. Tip
For information about changing runlevels using the GRUB menu entry editor, refer to Section 5.8, Changing Runlevels at Boot Time.

Command Line Interface The command line interface is the most basic GRUB interface, but it is also the one that grants the most control. The command line makes it possible to type any relevant GRUB commands followed by the Enter key to execute them. This interface features some advanced shell-like features, including Tab key completion based on context, and Ctrl key combinations when typing commands, such as Ctrl-a to move to the beginning of a line and Ctrl-e to move to the end of a line. In addition, the arrow, Home, End, and Delete keys work as they do in the bash shell.

5.5.1. Interfaces Load Order


When GRUB loads its second stage boot loader, it first searches for its configuration file. Once found, the menu interface bypass screen is displayed. If a key is pressed within three seconds, GRUB builds a menu list and displays the menu interface. If no key is pressed, the default kernel entry in the GRUB menu is used. If the configuration file cannot be found, or if the configuration file is unreadable, GRUB loads the command line interface, allowing the user to type commands to complete the boot process. If the configuration file is not valid, GRUB prints out the error and asks for input. This helps the user see precisely where the problem occurred. Pressing any key reloads the menu interface, where it is then possible to edit the menu option and

Pakistan Computer Bureau

73

correct the problem based on the error reported by GRUB. If the correction fails, GRUB reports an error and reloads the menu interface.

5.6. GRUB Commands


GRUB allows a number of useful commands in its command line interface. Some of the commands accept options after their name; these options should be separated from the command and other options on that line by space characters. The following is a list of useful commands: Boot Boots the operating system or chain loader that was last loaded. chainloader </path/to/file> Loads the specified file as a chain loader. If the file is located on the first sector of the specified partition, use the blocklist notation, +1, instead of the file name. The following is an example chainloader command: chainloader +1 displaymem Displays the current use of memory, based on information from the BIOS. This is useful to determine how much RAM a system has prior to booting it. initrd </path/to/initrd> Enables users to specify an initial RAM disk to use when booting. An initrd is necessary when the kernel needs certain modules in order to boot properly, such as when the root partition is formatted with the ext3 file system. The following is an example initrd command: initrd /initrd-2.6.8-1.523.img install <stage-1><install-disk><stage-2>pconfig-file Installs GRUB to the system MBR.

<stage-1>

Pakistan Computer Bureau

74

Signifies a device, partition, and file where the first boot loader image can be found, such as (hd0,0)/grub/stage1. <install-disk> Specifies the disk where the stage 1 boot loader should be installed, such (hd0).

as

<stage-2> Passes the stage 2 boot loader location to the stage 1 boot loader, such as (hd0,0)/grub/stage2. p<config-file> This option tells the install command to look for the menu configuration file specified by <config-file>, such as (hd0,0)/grub/grub.conf. Warning
The install command overwrites any information already located on the MBR.

kernel </path/to/kernel><option-1><option-N> ... Specifies the kernel file to load when booting the operating system. Replace </path/to/kernel> with an absolute path from the partition specified by the root command. Replace <option-1> with options for the Linux kernel, such as root=/dev/VolGroup00/LogVol00 to specify the device on which the root partition for the system is located. Multiple options can be passed to the kernel in a space separated list. The following is an example kernel command: kernel /vmlinuz-2.6.8-1.523 ro root=/dev/VolGroup00/LogVol00 The option in the previous example specifies that the root file system for Linux is located on the hda5 partition. root (<device-type><device-number>,<partition>) Configures the root partition for GRUB, such as (hd0,0), and mounts the partition. The following is an example root command: root (hd0,0)

rootnoverify (<device-type><device-number>,<partition>)
Pakistan Computer Bureau 75

Configures the root partition for GRUB, just like the root command, but does not mount the partition. Other commands are also available; type help --all for a full list of commands. For a description of all GRUB commands, refer to the documentation available online at http://www.gnu.org/software/grub/manual/.

5.7. GRUB Menu Configuration File


The configuration file (/boot/grub/grub.conf), which is used to create the list of operating systems to boot in GRUB's menu interface, essentially allows the user to select a pre-set group of commands to execute.

5.7.1. Configuration File Structure


The GRUB menu interface configuration file is /boot/grub/grub.conf. The commands to set the global preferences for the menu interface are placed at the top of the file, followed by stanzas for each operating kernel or operating system listed in the menu. The following is a very basic GRUB menu configuration file designed to boot either Red Hat Enterprise Linux or Microsoft Windows 2000: default=0 timeout=10 splashimage=(hd0,0)/grub/splash.xpm.gz hiddenmenu title Red Hat Enterprise Linux Server (2.6.18-2.el5PAE) root (hd0,0) kernel /boot/vmlinuz-2.6.18-2.el5PAE ro root=LABEL=/1 rhgb quiet initrd /boot/initrd-2.6.182.el5PAE.img # section to load Windows title Windows rootnoverify (hd0,0) chainloader +1 This file configures GRUB to build a menu with Red Hat Enterprise Linux as the default operating system and sets it to autoboot after 10 seconds. Two sections are given, one for each operating system entry, with commands specific to the system disk partition table.

Pakistan Computer Bureau

76

Note
Note that the default is specified as an integer. This refers to the first title line in the GRUB configuration file. For the Windows section to be set as the default in the previous example, change the default=0 to default=1.

5.7.2. Configuration File Directives


The following are directives commonly used in the GRUB menu configuration file: chainloader </path/to/file> Loads the specified file as a chain loader. Replace </path/to/file> with the absolute path to the chain loader. If the file is located on the first sector of the specified partition, use the blocklist notation, +1. color <normal-color><selected-color> Allows specific colors to be used in the menu, where two colors are configured as the foreground and background. Use simple color names such as red/black. For example: color red/black green/blue default=<integer> Replace <integer> with the default entry title number to be loaded if the menu interface times out. fallback=<integer> Replace <integer> with the entry title number to try if the first attempt fails. Hiddenmenu Prevents the GRUB menu interface from being displayed, loading the default entry when the timeout period expires. The user can see the standard GRUB menu by pressing the Esc key. initrd </path/to/initrd> Enables users to specify an initial RAM disk to use when booting. Replace </path/to/initrd> with the absolute path to the initial RAM disk.

Pakistan Computer Bureau

77

kernel </path/to/kernel><option-1><option-N> Specifies the kernel file to load when booting the operating system. Replace </path/to/kernel> with an absolute path from the partition specified by the root directive. Multiple options can be passed to the kernel when it is loaded. password=<password> Prevents a user who does not know the password from editing the entries for this menu option. Optionally, it is possible to specify an alternate menu configuration file after the password=<password> directive. In this case, GRUB restarts the second stage boot loader and uses the specified alternate configuration file to build the menu. If an alternate menu configuration file is left out of the command, a user who knows the password is allowed to edit the current configuration file. For more information about securing GRUB, refer to the chapter titled Workstation Security in the Red Hat Enterprise Linux Deployment Guide. root (<device-type><device-number>,<partition>) Configures the root partition for GRUB, such as (hd0,0), and mounts the partition. rootnoverify (<device-type><device-number>,<partition>) Configures the root partition for GRUB, just like the root command, but does not mount the partition. timeout=<integer> Specifies the interval, in seconds, that GRUB waits before loading the entry designated in the default command. splashimage=<path-to-image> Specifies the location of the splash screen image to be used when GRUB boots. title group-title Specifies a title to be used with a particular group of commands used to load a kernel or operating system. To add human-readable comments to the menu configuration file, begin the line with the hash mark character (#).

Pakistan Computer Bureau

78

5.8. Changing Runlevels at Boot Time


Under Red Hat Enterprise Linux, it is possible to change the default runlevel at boot time. To change the runlevel of a single boot session, use the following instructions: When the GRUB menu bypass screen appears at boot time, press any key to enter the GRUB menu (within the first three seconds). Press the a key to append to the kernel command. Add <space><runlevel> at the end of the boot options line to boot to the desired runlevel. For example, the following entry would initiate a boot process into runlevel 3: grub append> ro root=/dev/VolGroup00/LogVol00 rhgb quiet 3

5.9. Additional Resources


This chapter is only intended as an introduction to GRUB. Consult the following resources to discover more about how GRUB works.

5.9.1. Installed Documentation


/usr/share/doc/grub-<version-number>/ T directory contains good information about using and configuring GRUB, his where <version-number> corresponds to the version of the GRUB package installed. info grub The GRUB info page contains a tutorial, a user reference manual, a programmer reference manual, and a FAQ document about GRUB and its usage.

5.9.2. Useful Websites


http://www.gnu.org/software/grub/ The home page of the GNU GRUB project. This site contains information concerning the state of GRUB development and an FAQ.

Pakistan Computer Bureau

79

http://kbase.redhat.com/faq/FAQ_43_4053.shtm Details booting operating systems other than Linux. http://www.linuxgazette.com/issue64/kohli.html An introductory article discussing the configuration of GRUB on a system from scratch, including an overview of GRUB command line options.

Pakistan Computer Bureau

80

6.1. What is Swap Space?


Its an area on disk that temporarily holds a process memory image. When physical memory demand is sufficiently low, process memory images are brought back into physical memory from the swap area on disk. Having sufficient swap space enables the system to keep some physical memory free at all times. This type of memory management is often referred to as virtual memory and allows the total number of processes to exceed physical memory. Virtual memory enables the execution of a process within physical memory only as needed. Swap space can be a dedicated swap partition (recommended), a swap file, or a combination of swap partitions and swap files. Space allocation criteria should be equal to 2x physical RAM for up to 2 GB of physical RAM, and then an additional 1x physical RAM for any amount above 2 GB, but never less than 32 MB. Simply if, Memory in Ram is 512MB then Swap Space will be 512*2 = 1024MB Or if M = Amount of RAM in GB, and S = Amount of swap in GB, then If M < 2 S = M *2 Else S = M + 2 Using this formula, a system with 2 GB of physical RAM would have 4 GB of swap, while the other with 3 GB of physical RAM would have 5 GB of swap. Creating a large swap space partition can be especially helpful if you plan to upgrade your RAM at a later time. For systems with really large amounts of RAM (more than 32 GB) you can likely get away with a smaller swap partition (around 1x, or less, of physical RAM).

Pakistan Computer Bureau

81

Important
File systems and LVM2 volumes assigned as swap space cannot be in use when being modified. For example, no system processes can be assigned the swap space, as well as no amount of swap should be allocated and used by the kernel. Use the free and cat /proc/swaps commands to verify how much and where swap is in use. The best way to achieve swap space modifications is to boot your system in rescue mode, and then follow the instructions (for each scenario) in the remainder of this chapter. Refer to the Red Hat Enterprise Linux Installation Guide for instructions on booting into rescue mode. When prompted to mount the file system, select Skip.

6.2. Extending / Adding Swap Space


Sometimes it happens that you want to add more swap space even after installation. For example, you may upgrade the amount of RAM in your system from 128 MB to 256 MB, but there is only 256 MB of swap space. It might be advantageous to increase the amount of swap space to 512 MB if you perform memory-intense operations or run applications that require a large amount of memory. It is recommended that you extend an existing logical volume. To extend or add swap space, basically you have three options: create a new swap partition create a new swap file extend swap on an existing LVM2 logical volume

6.2.1. Extending Swap on an LVM2 Logical Volume


In our example we assume /dev/VolGroup00/LogVol01 is the volume you want to extend. To extend an LVM2 swap logical volume please 1. Disable the swapping for the associated logical volume: # swapoff -v /dev/VolGroup00/LogVol01 2. Resize the LVM2 logical volume by 256 MB: # lvm lvresize /dev/VolGroup00/LogVol01 -L +256M
Pakistan Computer Bureau 82

3. Format the new swap space: # mkswap /dev/VolGroup00/LogVol01 4. Enable the extended logical volume: # swapon va 5. Test that the logical volume has been extended properly: # cat /proc/swaps # free

6.2.2. Creating an LVM2 Logical Volume for Swap


In our example we assume /dev/VolGroup00/LogVol02 is the swap volume you want to add. To add a swap volume group please 1. Create the LVM2 logical volume of size 256 MB: # lvm lvcreate VolGroup00 -n LogVol02 -L 256M 2. Format the new swap space: # mkswap /dev/VolGroup00/LogVol02 3. Add the following entry to the /etc/fstab file: /dev/VolGroup00/LogVol02 swap swap defaults 0 0 4. Enable the extended logical volume: # swapon va 5. Test that the logical volume has been extended properly: # cat /proc/swaps # free

Pakistan Computer Bureau

83

6.2.3. Creating a Swap File


To add a swap file: 1. Determine the size of the new swap file in megabytes and multiply by 1024 to determine the number of blocks. For example, the block size of a 64 MB swap file is 65536. 2. At a shell prompt as root, type the following command with count being equal to the desired block size: dd if=/dev/zero of=/swapfile bs=1024 count=65536 3. Setup the swap file with the command: mkswap /swapfile To enable the swap file immediately but not automatically at boot time: swapon /swapfile To enable it at boot time, edit /etc/fstab to include the following entry: /swapfile swap swap defaults 0 0

4.

5.

The next time the system boots, it enables the new swap file. 6. After adding the new swap file and enabling it, verify it is enabled by viewing the output of the command cat /proc/swaps or free.

6.3. Removing Swap Space


Sometimes it can be prudent to reduce swap space after installation. For example, say you downgraded the amount of RAM in your system from 1 GB to 512 MB, but there is 2 GB of swap space still assigned. It might be advantageous to reduce the amount of swap space to 1 GB, since the larger 2 GB could be wasting disk space. You have three options: remove an entire LVM2 logical volume used for swap, remove a swap file, or reduce swap space on an existing LVM2 logical volume.

Pakistan Computer Bureau

84

6.3.1. Reducing Swap on an LVM2 Logical Volume


To reduce an LVM2 swap logical volume (assuming /dev/VolGroup00/LogVol01 is the volume you want to extend): 1. Disable swapping for the associated logical volume: # swapoff -v /dev/VolGroup00/LogVol01 2. Reduce the LVM2 logical volume by 512 MB: # lvm lvreduce /dev/VolGroup00/LogVol01 -L -512M 3. Format the new swap space: # mkswap /dev/VolGroup00/LogVol01 4. Enable the extended logical volume: # swapon va 5. Test that the logical volume has been reduced properly: # cat /proc/swaps # free

6.3.2. Removing an LVM2 Logical Volume for Swap


The swap logical volume cannot be in use (no system locks or processes on the volume). The easiest way to achieve this is to boot your system in rescue mode. Refer to for instructions on booting into rescue mode. When prompted to mount the file system, select Skip. To remove a swap volume group (assuming /dev/VolGroup00/LogVol02) is the swap volume you want to remove: 1. Disable swapping for the associated logical volume:

Pakistan Computer Bureau

85

# swapoff -v /dev/VolGroup00/LogVol02

2. Remove the LVM2 logical volume of size 512 MB: # lvm lvremove /dev/VolGroup00/LogVol02 3. Remove the following entry from the /etc/fstab file: /dev/VolGroup00/LogVol02 swap swap defaults 0 0 4. Test that the logical volume has been extended properly: # cat /proc/swaps # free

6.3.3. Removing a Swap File


To remove a swap file: 1. At a shell prompt as root, execute the following command to disable the swap file (where /swapfile is the swap file): # swapoff -v /swapfile 2. Remove its entry from the /etc/fstab file. 3. Remove the actual file: # rm /swapfile

6.4. Moving Swap Space


To move swap space from one location to another, follow the steps for removing swap space, and then follow the steps for adding swap space.

Pakistan Computer Bureau

86

7.1. Standard Partitions using parted


The utility parted allows users to: View the existing partition table Change the size of existing partitions Add partitions from free space or additional hard drives By default, the parted package is included when installing Red Hat Enterprise Linux. To start parted, log in as root and type the command parted /dev/sda at a shell prompt (where /dev/sda is the device name for the drive you want to configure). A device containing a partition must not be in use if said partition is to be removed or resized. Similarly, when creating a new partition on a device, said device must not be in use. For a device to not be in use, none of the partitions on the device can be mounted, and any swap space on the device must not be enabled. As well, the partition table should not be modified while it is in use because the kernel may not properly recognize the changes. If the partition table does not match the actual state of the mounted partitions, information could be written to the wrong partition, resulting in lost and overwritten data. The easiest way to achieve this is to boot your system in rescue mode. When prompted to mount the file system, select Skip. Alternately, if the drive does not contain any partitions in use (system processes that use or lock the file system from being unmounted), you can unmount them with the umount command and turn off all the swap space on the hard drive with the swapoff command. Table below contains a list of commonly used parted commands. The sections that follow explain some of these commands and arguments in more detail.

Command
check minor-num cp fromto Help mktable label mkfs minor-numfile-systemtype mkpart part-typefstypestart-mbend-mb Mkpartfs part-typefstypestart-mbend-mb Pakistan Computer Bureau

Description
Perform a simple check of the file system Copy file system from one partition to another; from and to are the minor numbers of the partitions Display list of available commands Create a disk label for the partition table Create a file system of type file-system-type Make a partition without creating a new file system Make a partition and create the specified file system 87

move minor-numstart-mbendmb name minor-numname Print Quit rescuestart-mbend-mb resize minor-numstartmbend-mb rm minor-num select device set minor-numflagstate toggle [NUMBER [FLAG] unit UNIT Name the partition for Mac and PC98 Display the partition table Quit parted Rescue a lost partition from start-mb to end-mb Resize the partition from start-mb to endmb Remove the partition Select a different device to configure Set the flag on a partition; state is either on or off Toggle the state of FLAG on partition NUMBER Set the default unit to UNIT

7.1.1. Viewing the Partition Table


After starting parted, use the command print to view the partition table. A table similar to the following appears: Model: ATA ST3160812AS (scsi) Disk /dev/sda: 160GB Sector size (logical/physical): 512B/512B Partition Table: msdos
Number 1 2 3 4 5 6 7 Start 32.3kB 107MB 105GB 107GB 107GB 133GB 133GB End 107MB 105GB 107GB 160GB 133GB 133GB 160GB Size 107MB 105GB 2147MB 52.9GB 26.2GB 107MB 26.6GB Type File system primary ext3 primary ext3 primary linux-swap extended logical ext3 logical ext3 logical Flags boot

root

lvm

The first line contains the disk type, manufacturer, model number and interface, and the second line displays the disk label type. The remaining output below the fourth line shows the partition table. In the partition table, the Minor number is the partition number. For example, the partition with minor number 1 corresponds to /dev/sda1. The Start and End values are in megabytes. Valid Types are metadata, free, primary, extended, or logical. The File system is the file system type, which can be any of the following: ext2 ext3 fat16
Pakistan Computer Bureau 88

fat32 hfs jfs linux-swap ntfs reiserfs hp-ufs sun-ufs xfs If a File system of a device shows no value, this means that its file system type is unknown. The Flags column lists the flags set for the partition. Available flags are boot, root, swap, hidden, raid, lvm, or lba. Tip
To select a different device without having to restart parted, use the select command followed by the device name (for example, /dev/sda). Doing so allows you to view or configure the partition table of a device.

7.1.2. Creating a Partition


Warning
Do not attempt to create a partition on a device that is in use.

Before creating a partition, boot into rescue mode (or unmount any partitions on the device and turn off any swap space on the device). Start parted, where /dev/sda is the device on which to create the partition: parted /dev/sda View the current partition table to determine if there is enough free space: print If there is not enough free space, you can resize an existing partition.

7.1.2.1. Making the Partition


From the partition table, determine the start and end points of the new partition and what partition type it should be. You can only have four primary partitions (with no extended partition) on a device. If you need more than four partitions, you can have three primary partitions, one extended partition, and multiple logical partitions within the extended. For example, to create a primary partition with an ext3 file system from 1024 megabytes until 2048 megabytes on a hard drive type the following command: mkpart primary ext3 1024 2048
Pakistan Computer Bureau 89

Tip
If you use the mkpartfs command instead, the file system is created after the partition is created. However, parted does not support creating an ext3 file system. Thus, if you wish to create an ext3 file system, use mkpart and create the file system with the mkfs command as described later.

The changes start taking place as soon as you press Enter, so review the command before executing to it. After creating the partition, use the print command to confirm that it is in the partition table with the correct partition type, file system type, and size. Also remember the minor number of the new partition so that you can label it. You should also view the output of cat /proc/partitions to make sure the kernel recognizes the new partition.

7.1.2.2. Formating the Partition


The partition still does not have a file system. Create the file system: /sbin/mkfs -t ext3 /dev/sda6 Warning
Formatting the partition permanently destroys any data that currently exists on the partition.

7.1.2.3. Labeling the Partition


Next, give the partition a label. For example, if the new partition is /dev/sda6 and you want to label it /work: e2label /dev/sda6 /work By default, the installation program uses the mount point of the partition as the label to make sure the label is unique. You can use any label you want.

7.1.2.4. Creating the Mount Point


As root, create the mount point: mkdir /work

7.1.2.5. Add to /etc/fstab


As root, edit the /etc/fstab file to include the new partition. The new line should look similar to the following:
Pakistan Computer Bureau 90

LABEL=/work /work ext3 defaults 1 2

The first column should contain LABEL= followed by the label you gave the partition. The second column should contain the mount point for the new partition, and the next column should be the file system type (for example, ext3 or swap). If you need more information about the format, read the man page with the command man fstab. If the fourth column is the word defaults, the partition is mounted at boot time. To mount the partition without rebooting, as root, type the command: mount /work

7.1.3. Removing a Partition


Warning
Do not attempt to remove a partition on a device that is in use.

Before removing a partition, boot into rescue mode (or unmount any partitions on the device and turn off any swap space on the device). Start parted, where /dev/sda is the device on which to remove the partition: parted /dev/sda View the current partition table to determine the minor number of the partition to remove: print Remove the partition with the command rm. For example, to remove the partition with minor number 3: rm 3 The changes start taking place as soon as you press Enter, so review the command before committing to it. After removing the partition, use the print command to confirm that it is removed from the partition table. You should also view the output of cat /proc/partitions to make sure the kernel knows the partition is removed. The last step is to remove it from the /etc/fstab file. Find the line that declares the removed partition, and remove it from the file.

Pakistan Computer Bureau

91

7.1.4. Resizing a Partition


Warning
Do not attempt to resize a partition on a device that is in use.

Before resizing a partition, boot into rescue mode (or unmount any partitions on the device and turn off any swap space on the device). Start parted, where /dev/sda is the device on which to resize the partition: parted /dev/sda View the current partition table to determine the minor number of the partition to resize as well as the start and end points for the partition: print To resize the partition, use the resize command followed by the minor number for the partition, the starting place in megabytes, and the end place in megabytes. For example: resize 3 1024 2048 Warning
A partition cannot be made larger than the space available on the device

After resizing the partition, use the print command to confirm that the partition has been resized correctly, is the correct partition type, and is the correct file system type. After rebooting the system into normal mode, use the command df to make sure the partition was mounted and is recognized with the new size.

7.2. LVM Partition Management


The following commands can be found by issuing lvm help at a command prompt. Command
dumpconfig formats help lvchange lvcreate lvdisplay lvextend lvmchange Pakistan Computer Bureau

Description
Dump the active configuration List the available metadata formats Display the help commands Change the attributes of logical volume(s) Create a logical volume Display information about a logical volume Add space to a logical volume Due to use of the device 92

lvmdiskscan lvmsadc lvmsar lvreduce lvremove lvrename lvresize lvs lvscan pvchange pvcreate pvdata pvdisplay pvmove pvremove pvresize pvs pvscan segtypes vgcfgbackup vgcfgrestore vgchange vgck vgconvert vgcreate vgdisplay vgexport vgextend Pakistan Computer Bureau

mapper, this command has been deprecated List devices that may be used as physical volumes Collect activity data Create activity report Reduce the size of a logical volume Remove logical volume(s) from the system Rename a logical volume Resize a logical volume Display information about logical volumes List all logical volumes in all volume groups Change attributes of physical volume(s) Initialize physical volume(s) for use by LVM Display the on-disk metadata for physical volume(s) Display various attributes of physical volume(s) Move extents from one physical volume to another Remove LVM label(s) from physical volume(s) Resize a physical volume in use by a volume group Display information about physical volumes List all physical volumes List available segment types Backup volume group configuration Restore volume group configuration Change volume group attributes Check the consistency of a volume group Change volume group metadata format Create a volume group Display volume group information Unregister a volume group from the system Add physical volumes to a 93

vgimport vgmerge vgmknodes vgreduce vgremove vgs vgscan vgsplit version

volume group Register exported volume group with system Merge volume groups Create the special files for volume group devices in /dev/ Remove a physical volume from a volume group Remove a volume group Display information about volume groups Search for all volume groups Move physical volumes into a new volume group Display software and driver version information

Pakistan Computer Bureau

94

Files and directories have permission sets for the owner of the file, the group associated with the file, and all other users for the system. However, these permission sets have limitations. For example, different permissions cannot be configured for different users. Thus, Access Control Lists (ACLs) were implemented. The Red Hat Enterprise Linux 5 kernel provides ACL support for the ext3 file system and NFS-exported file systems. ACLs are also recognized on ext3 file systems accessed via Samba. Along with support in the kernel, the acl package is required to implement ACLs. It contains the utilities used to add, modify, remove, and retrieve ACL information. The cp and mv commands copy or move any ACLs associated with files and directories.

8.1. Mounting File Systems


Before using ACLs for a file or directory, the partition for the file or directory must be mounted with ACL support. If it is a local ext3 file system, it can mounted with the following command: mount -t ext3 -o acl <device-name><partition> For example: mount -t ext3 -o acl /dev/VolGroup00/LogVol02 /work Alternatively, if the partition is listed in the /etc/fstab file, the entry for the partition can include the acl option: LABEL=/work /work ext3 acl 1 2 If an ext3 file system is accessed via Samba and ACLs have been enabled for it, the ACLs are recognized because Samba has been compiled with the -with-acl-support option. No special flags are required when accessing or mounting a Samba share.

Pakistan Computer Bureau

95

8.1.1. NFS
By default, if the file system being exported by an NFS server supports ACLs and the NFS client can read ACLs, ACLs are utilized by the client system. To disable ACLs on NFS shares when configuring the server, include the no_acl option in the /etc/exports file. To disable ACLs on an NFS share when mounting it on a client, mount it with the no_acl option via the command line or the /etc/fstab file.

8.2. Setting Access ACLs


There are two types of ACLs: access ACLs and default ACLs. An access ACL is the access control list for a specific file or directory. A default ACL can only be associated with a directory; if a file within the directory does not have an access ACL, it uses the rules of the default ACL for the directory. Default ACLs are optional. ACLs can be configured: Per user Per group Via the effective rights mask For users not in the user group for the file The setfacl utility sets ACLs for files and directories. Use the -m option to add or modify the ACL of a file or directory: setfacl -m <rules><files> Rules (<rules>) must be specified in the following formats. Multiple rules can be specified in the same command if they are separated by commas. u:<uid>:<perms> Sets the access ACL for a user. The user name or UID may be specified. The user may be any valid user on the system. g:<gid>:<perms> Sets the access ACL for a group. The group name or GID may be specified. The group may be any valid group on the system.

Pakistan Computer Bureau

96

m:<perms> Sets the effective rights mask. The mask is the union of all permissions of the owning group and all of the user and group entries. o:<perms> Sets the access ACL for users other than the ones in the group for the file. White space is ignored. Permissions (<perms>) must be a combination of the characters r, w, and x for read, write, and execute. If a file or directory already has an ACL, and the setfacl command is used, the additional rules are added to the existing ACL or the existing rule is modified. For example, to give read and write permissions to user andrius: setfacl -m u:andrius:rw /project/somefile To remove all the permissions for a user, group, or others, use the -x option and do not specify any permission (s): setfacl -x <rules><files> For example, to remove all permissions from the user with UID 500: setfacl -x u:500 /project/somefile

8.3. Setting Default ACLs


To set a default ACL, add d: before the rule and specify a directory instead of a file name. For example, to set the default ACL for the /share/ directory to read and execute for users not in the user group (an access ACL for an individual file can override it): setfacl -m d:o:rx /share

8.4. Retrieving ACLs


To determine the existing ACLs for a file or directory, use the getfacl command. In the example below, the getfacl is used to determine the existing ACLs for a file. getfacl home/john/picture.png

Pakistan Computer Bureau

97

The above command returns the following output: # file: home/john/picture.png # owner: john # group: john user::rwgroup::r-- other::r-If a directory with a default ACL is specified, the default ACL is also displayed as illustrated below. [john@main /]$ getfacl home/sales/# file: home/sales/ # owner: john # group: john user::rw- user:barryg:r-- group::r-- mask::r-other::r-- default:user::rwx default:user:john:rwx default:group::r-x default:mask::rwx default:other::rx

8.5. Archiving File Systems With ACLs


Warning
The tar and dump commands do not backup ACLs.

The star utility is similar to the tar utility in that it can be used to generate archives of files. The star package is required to use this utility. The command line options for Star are as follows Option
-c -n

Description
Creates an archive file. Do not extract the files; use in conjunction with -x to show what extracting the files does. Replaces files in the archive. The files are written to the end of the archive file, replacing any files with the same path and file name. Displays the contents of the archive file. Updates the archive file. The files are written to the end of the archive if they do not exist in the archive or if the files are newer than the files of the same name in the archive. This option only work if the archive is a file or an unblocked tape that may backspace.

-r

-t -u

Pakistan Computer Bureau

98

-x

-help -xhelp -/

-acl

Extracts the files from the archive. If used with -U and a file in the archive is older than the corresponding file on the file system, the file is not extracted. Displays the most important options. Displays the least important options. Do not strip leading slashes from file names when extracting the files from an archive. By default, they are striped when files are extracted. When creating or extracting, archive or restore any ACLs associated with the files and directories.

8.6. Compatibility with Older Systems


If an ACL has been set on any file on a given file system that files system has the ext_attr attribute. This attribute can be seen using the following command: tune2fs -l <filesystem-device> A file system that has acquired the ext_attr attribute can be mounted with older kernels, but those kernels do not enforce any ACLs which have been set. Versions of the e2fsck utility included in version 1.22 and higher of the e2fsprogs package (including the versions in Red Hat Enterprise Linux 2.1 and 4) can check a file system with the ext_attr attribute. Older versions refuse to check it.

8.7. Useful Websites


Refer to the follow resources for more information. http://acl.bestbits.at/ Website for ACLs

Pakistan Computer Bureau

99

The RPM Package Manager (RPM) is an open packaging system, which runs on Red Hat Enterprise Linux as well as other Linux and UNIX systems. Red Hat, Inc. encourages other vendors to use RPM for their own products. RPM is distributed under the terms of the GPL. The utility works only with packages built for processing by the rpm package. For the end user, RPM makes system updates easy. Installing, uninstalling, and upgrading RPM packages can be accomplished with short commands. RPM maintains a database of installed packages and their files, so you can invoke powerful queries and verifications on your system. If you prefer a graphical interface, you can use the Package Management Tool to perform many RPM commands. Important
When installing a package, please ensure it is compatible with your operating system and architecture. This can usually be determined by checking the package name.

During upgrades, RPM handles configuration files carefully, so that you never lose your customizations something that you cannot accomplish with regular .tar, .gz files. For the developer, RPM allows you to take software source code and package it into source and binary packages for end users. This process is quite simple and is driven from a single file and optional patches that you create. This clear delineation between pristine sources and your patches along with build instructions eases the maintenance of the package as new versions of the software are released. Note
Because RPM makes changes to your system, you must be logged in as root to install, remove, or upgrade an RPM package.

Pakistan Computer Bureau

100

9.1. RPM Design Goals


To understand how to use RPM, it can be helpful to understand the design goals of RPM:

Upgradability
With RPM, you can upgrade individual components of your system without completely reinstalling. When you get a new release of an operating system based on RPM (such as Red Hat Enterprise Linux), you do not need to reinstall on your machine (as you do with operating systems based on other packaging systems). RPM allows intelligent, fully-automated, in-place upgrades of your system. Configuration files in packages are preserved across upgrades, so you do not lose your customizations. There is no special upgrade files needed to upgrade a package because the same RPM file is used to install and upgrade the package on your system.

Powerful Querying
RPM is designed to provide powerful querying options. You can do searches through your entire database for packages or just for certain files. You can also easily find out what package a file belongs to and from where the package came. The files an RPM package contains are in a compressed archive, with a custom binary header containing useful information about the package and its contents, allowing you to query individual packages quickly and easily.

System Verification
Another powerful RPM feature is the ability to verify packages. If you are worried that you deleted an important file for some package, you can verify the package. You are then notified of any anomalies, if any at which point, you can reinstall the package if necessary. Any configuration files that you modified are preserved during reinstallation.

Pristine Sources
A crucial design goal was to allow the use of pristine software sources, as distributed by the original authors of the software. With RPM, you have the pristine sources along with any patches that were used, plus complete build instructions. This is an important advantage for several reasons. For instance, if a new version of a program is released, you do not necessarily have to start

Pakistan Computer Bureau

101

from scratch to get it to compile. You can look at the patch to see what you might need to do. All the compiled-in defaults, and all of the changes that were made to get the software to build properly, are easily visible using this technique. The goal of keeping sources pristine may seem important only for developers, but it results in higher quality software for end users, too.

9.2. Using RPM


RPM has five basic modes of operation (not counting package building): installing, uninstalling, upgrading, querying, and verifying. This section contains an overview of each mode.

9.2.1. Finding RPM Packages


Before using any RPM packages, you must know where to find them. An Internet search returns many RPM repositories, but if you are looking for RPM packages built by Red Hat, they can be found at the following locations: The Red Hat Enterprise Linux CD-ROMs The Red Hat Errata Page available at http://www.redhat.com/apps/support/errata/ Red Hat Network

9.2.2. Installing
RPM packages typically have file names like foo-1.0-1.i386.rpm. The file name includes the package name (foo), version (1.0), release (1), and architecture (i386). To install a package, log in as root and type the following command at a shell prompt: rpm -ivh foo-1.0-1.i386.rpm Alternatively, the following command can also be used: rpm -Uvh foo-1.0-1.i386.rpm If the installation is successful, the following output is displayed: Preparing... ########################################### [100%]

Pakistan Computer Bureau

102

1:foo ########################################### [100%] As you can see, RPM prints out the name of the package and then prints a succession of hash marks as a progress meter while the package is installed. The signature of a package is checked automatically when installing or upgrading a package. The signature confirms that the package was signed by an authorized party. For example, if the verification of the signature fails, an error message such as the following is displayed: error: V3 DSA signature: BAD, key ID 0352860f If it is a new, header-only, signature, an error message such as the following is displayed: error: Header V3 DSA signature: BAD, key ID 0352860f If you do not have the appropriate key installed to verify the signature, the message contains the word NOKEY such as: warning: V3 DSA signature: NOKEY, key ID 0352860f Warning
If you are installing a kernel package, you should use rpm -ivh instead.

9.2.2.1. Package Already Installed


If a package of the same name and version is already installed, the following output is displayed: Preparing... ########################################### [100%] package foo-1.0-1 is already installed However, if you want to install the package anyway, you can use the -replacepkgs option, which tells RPM to ignore the error: rpm -ivh --replacepkgs foo-1.0-1.i386.rpm This option is helpful if files installed from the RPM were deleted or if you want the original configuration files from the RPM to be installed.

Pakistan Computer Bureau

103

9.2.2.2. Conflicting Files


If you attempt to install a package that contains a file which has already been installed by another package, the following is displayed: Preparing... ########################################### [100%] file /usr/bin/foo from install of foo-1.0-1 conflicts with file from package bar-2.0.20 To make RPM ignore this error, use the --replacefiles option: rpm -ivh --replacefiles foo-1.0-1.i386.rpm

9.2.2.3. Unresolved Dependency


RPM packages may sometimes depend on other packages, which mean that they require other packages to be installed to run properly. If you try to install a package which has an unresolved dependency, output similar to the following is displayed:
error: Failed dependencies: bar.so.2 is needed by foo-1.01 Suggested resolutions: bar-2.0.20-3.i386.rpm

If you are installing a package from the Red Hat Enterprise Linux CDROM set, it usually suggests the package(s) needed to resolve the dependency. Find the suggested package(s) on the Red Hat Enterprise Linux CDROMs or from Red Hat Network, and add it to the command: rpm -ivh foo-1.0-1.i386.rpm bar-2.0.203.i386.rpm If installation of both packages is successful, output similar to the following is displayed: Preparing... ########################################### [100%] 1:foo ########################################### [ 50%] 2:bar ########################################### [100%] If it does not suggest a package to resolve the dependency, you can try the
Pakistan Computer Bureau 104

redhat provides option to determine which package contains the required file. You need the rpmdb-redhat package installed to use this option. rpm -q --redhatprovides bar.so.2 If the package that contains bar.so.2 is in the installed database from the rpmdbredhat package, the name of the package is displayed: bar-2.0.20-3.i386.rpm To force the installation anyway (which is not recommended since the package may not run correctly), use the --nodeps option.

9.2.3. Uninstalling
Uninstalling a package is just as simple as installing one. Type the following command at a shell prompt: rpm -e foo Note
Notice that we used the package namefoo, not the name of the original package filefoo-1.0-1.i386.rpm. To uninstall a package, replace foo with the actual package name of the original package.

You can encounter a dependency error when uninstalling a package if another installed package depends on the one you are trying to remove. For example:
error: Failed dependencies: foo is needed by (installed) bar-2.0.20-3.i386.rpm

To make RPM ignore this error and uninstall the package anyway (which may break the package dependent on it) use the --nodeps option.

9.2.4. Upgrading
Upgrading a package is similar to installing one. Type the following command at a shell prompt: rpm -Uvh foo-2.0-1.i386.rpm As part of upgrading a package, RPM automatically uninstalls any old versions of the foo package. Note that -U will also install a package even when there are no previous versions of the package installed.

Pakistan Computer Bureau

105

Tip
It is not advisable to use the -U option for installing kernel packages, because RPM replaces the previous kernel package. This does not affect a running system, but if the new kernel is unable to boot during your next restart, there would be no other kernel to boot instead.Using the -i option adds the kernel to your GRUB boot menu (/etc/grub.conf). Similarly, removing an old, unneeded kernel removes the kernel from GRUB.

Because RPM performs intelligent upgrading of packages with configuration files, you may see a message like the following: saving /etc/foo.conf as /etc/foo.conf.rpmsave This message means that changes you made to the configuration file may not be forward compatible with the new configuration file in the package, so RPM saved your original file and installed a new one. You should investigate the differences between the two configuration files and resolve them as soon as possible, to ensure that your system continues to function properly. If you attempt to upgrade to a package with an older version number (that is, if a more updated version of the package is already installed), the output is similar to the following: package foo-2.0-1 (which is newer than foo-1.01) is already installed To force RPM to upgrade anyway, use the --oldpackage option: rpm -Uvh --oldpackage foo-1.0-1.i386.rpm

9.2.5. Freshening
Freshening is similar to upgrading, except that only existent packages are upgraded. Type the following command at a shell prompt: rpm -Fvh foo-1.2-1.i386.rpm RPM's freshen option checks the versions of the packages specified on the command line against the versions of packages that have already been installed on your system. When a newer version of an already-installed package is processed

Pakistan Computer Bureau

106

by RPM's freshen option, it is upgraded to the newer version. However, RPM's freshen option does not install a package if no previously-installed package of the same name exists. This differs from RPM's upgrade option, as an upgrade does install packages whether or not an older version of the package was already installed. Freshening works for single packages or package groups. If you have just downloaded a large number of different packages, and you only want to upgrade those packages that are already installed on your system, freshening does the job. Thus, you do not have to delete any unwanted packages from the group that you downloaded before using RPM. In this case, issue the following command: rpm -Fvh *.rpm RPM automatically upgrades only those packages that are already installed.

9.2.6. Querying
The RPM database stores information about all RPM packages installed in your system. It is stored in the directory /var/lib/rpm/, and is used to query what packages are installed, what versions each package is, and any changes to any files in the package since installation, among others. To query this database, use the -q option. The rpm -q package name command displays the package name, version, and release number of the installed package name. For example, using rpm -q foo to query installed package foo might generate the following output: foo-2.0-1 You can also use the following Package Selection Options with -q to further refine or qualify Your query: -a queries all currently installed packages. -f <filename> queries the RPM database for which package owns <filename>. When specifying a file, specify the absolute path of the file (for example, rpm -f /bin/ls). -p <packagefile> queries the uninstalled package <packagefile>.
Pakistan Computer Bureau 107

There are a number of ways to specify what information to display about queried packages. The following options are used to select the type of information for which you are searching. These are called Information Query Options. -i displays package information including name, description, release, size, build date, install date, vendor, and other miscellaneous information. -l displays the list of files that the package contains. -s displays the state of all the files in the package. -d displays a list of files marked as documentation (man pages, info pages, READMEs, etc.). -c displays a list of files marked as configuration files. These are the files you edit after installation to adapt and customize the package to your system (for example, sendmail.cf, passwd, inittab, etc.).

9.2.7. Verifying
Verifying a package compares information about files installed from a package with the same information from the original package. Among other things, verifying compares the size, MD5 sum, permissions, type, owner, and group of each file. The command rpm -V verifies a package. You can use any of the Package Verify Options listed for querying to specify the packages you wish to verify. A simple use of verifying is rpm -V foo, which verifies that all the files in the foo package are as they were when they were originally installed. For example: To verify a package containing a particular file: rpm -Vf /usr/bin/foo In this example, /usr/bin/foo is the absolute path to the file used to query a package. To verify ALL installed packages throughout the system: rpm -Va

To verify an installed package against an RPM package file:

Pakistan Computer Bureau

108

rpm -Vp foo-1.0-1.i386.rpm This command can be useful if you suspect that your RPM databases are corrupt. If everything verified properly, there is no output. If there are any discrepancies, they are displayed. The format of the output is a string of eight characters (a c denotes a configuration file) and then the file name. Each of the eight characters denotes the result of a comparison of one attribute of the file to the value of that attribute recorded in the RPM database. A single period (.) means the test passed. The following characters denote specific discrepancies: 5 S L T D U G M ? MD5 checksum file size symbolic link file modification time device user group mode (includes permissions and file type) unreadable file

If you see any output, use your best judgment to determine if you should remove the package, reinstall it, or fix the problem in another way.

9.3. Checking a Package's Signature


If you wish to verify that a package has not been corrupted or tampered with, examine only the md5sum by typing the following command at a shell prompt (where <rpm-file> is the file name of the RPM package): rpm -K --nosignature <rpm-file> The message <rpm-file>: md5 OK is displayed. This brief message means that the file was not corrupted by the download. To see a more verbose message, replace -K with -Kvv in the command. On the other hand, how trustworthy is the developer who created the package? If the package is signed with the developer's GnuPG key, you know that the developer really is who they say they are. An RPM package can be signed using Gnu Privacy Guard (or GnuPG), to help you make certain your
Pakistan Computer Bureau

109

downloaded package is trustworthy. GnuPG is a tool for secure communication; it is a complete and free replacement for the encryption technology of PGP, an electronic privacy program. With GnuPG, you can authenticate the validity of documents and encrypt/decrypt data to and from other recipients. GnuPG is capable of decrypting and verifying PGP 5.x files as well. During installation, GnuPG is installed by default. That way you can immediately start using GnuPG to verify any packages that you receive from Red Hat. Before doing so, you must first import Red Hat's public key.

9.3.1. Importing Keys


To verify Red Hat packages, you must import the Red Hat GPG key. To do so, execute the following command at a shell prompt: rpm --import /usr/share/rhn/RPM-GPG-KEY To display a list of all keys installed for RPM verification, execute the command: rpm -qa gpg-pubkey* For the Red Hat key, the output includes: gpg-pubkey-db42a60e-37ea5438 To display details about a specific key, use rpm -qi followed by the output from the previous command: rpm -qi gpg-pubkey-db42a60e-37ea5438

9.3.2. Verifying Signature of Packages


To check the GnuPG signature of an RPM file after importing the builder's GnuPG key, use the following command (replace <rpm-file> with the filename of the RPM package): rpm -K <rpm-file> If all goes well, the following message is displayed: md5 gpg OK. This means that the signature of the package has been verified, and that it is not corrupt.

Pakistan Computer Bureau

110

9.4. Practical and Common Examples of RPM Usage


RPM is a useful tool for both managing your system and diagnosing and fixing problems. The best way to make sense of all of its options is to look at some examples. Perhaps you have deleted some files by accident, but you are not sure what you deleted. To verify your entire system and see what might be missing, you could try the following command: rpm -Va If some files are missing or appear to have been corrupted, you should probably either re-install the package or uninstall and then re-install the package. At some point, you might see a file that you do not recognize. To find out which package owns it, enter: rpm -qf /usr/bin/ggv The output would look like the following: ggv-2.6.0-2 We can combine the above two examples in the following scenario. Say you are having problems with /usr/bin/paste. You would like to verify the package that owns that program, but you do not know which package owns paste. Enter the following command, rpm -Vf /usr/bin/paste and the appropriate package is verified. Do you want to find out more information about a particular program? You can try the following command to locate the documentation which came with the package that owns that program: rpm -qdf /usr/bin/free The output would be similar to the following: /usr/share/doc/procps-3.2.3/BUGS /usr/share/doc/procps-3.2.3/FAQ /usr/share/doc/procps-3.2.3/NEWS /usr/share/doc/procps-3.2.3/TODO /usr/share/man/man1/free.1.gz /usr/share/man/man1/pgrep.1.gz /usr/share/man/man1/pkill.1.gz /usr/share/man/man1/pmap.1.gz /usr/share/man/man1/ps.1.gz /usr/share/man/man1/skill.1.gz /usr/share/man/man1/slabtop.1.gz /usr/share/man/man1/snice.1.gz

Pakistan Computer Bureau

111

/usr/share/man/man1/tload.1.gz /usr/share/man/man1/top.1.gz /usr/share/man/man1/uptime.1.gz /usr/share/man/man1/w.1.gz /usr/share/man/man1/watch.1.gz /usr/share/man/man5/sysctl.conf.5.gz /usr/share/man/man8/sysctl.8.gz /usr/share/man/man8/vmstat.8.gz You may find a new RPM, but you do not know what it does. To find information about it, use the following command: rpm -qip crontabs-1.10-7.noarch.rpm The output would be similar to the following: Name : crontabs Relocations: (not relocatable) Version : 1.10 Vendor: Red Hat, Inc. Release : 7 Build Date: Mon 20 Sep 2004 05:58:10 PM EDT Install Date: (not installed) Build Host: tweety.build.redhat.com Group : System Environment/Base Source RPM: crontabs-1.10-7.src.rpm Size : 1004 License: Public Domain Signature : DSA/SHA1, Wed 05 Jan 2005 06:05:25 PM EST, Key ID 219180cddb42a60e Packager : Red Hat, Inc. <http://bugzilla.redhat.com/bugzilla> Summary : Root crontab files used to schedule the execution of programs. Description : The crontabs package contains root crontab files. Crontab is the program used to install, uninstall, or list the tables used to drive the cron daemon. The cron daemon checks the crontab files to see when particular commands are scheduled to be executed. If commands are scheduled, then it executes them. Perhaps you now want to see what files the crontabs RPM installs. You would enter the following: rpm -qlp crontabs-1.10-5.noarch.rpm The output is similar to the following: /etc/cron.daily /etc/cron.hourly /etc/cron.monthly /etc/cron.weekly /etc/crontab /usr/bin/run-parts These are just a few examples. As you use RPM, you may find more uses for it.
Pakistan Computer Bureau

112

9.5. Additional Resources


RPM is an extremely complex utility with many options and methods for querying, installing, upgrading, and removing packages. Refer to the following resources to learn more about RPM.

9.5.1. Installed Documentation


rpm --help This command displays a quick reference of RPM parameters. man rpm The RPM man page gives more detail about RPM parameters than the rpm--help command.

9.5.2. Useful Websites


http://www.rpm.org/ The RPM website. http://www.redhat.com/mailman/listinfo/rpm-list/ The RPM mailing list is archived here. To subscribe, send mail to <rpm-listrequest@redhat.com> with the word subscribe in the subject line.

9.5.3. Related Books


Red Hat RPM Guide by Eric Foster-Johnson; Wiley, John & Sons, Incorporated This book is a comprehensive guide to RPM, from installing packages to building RPMs.

Pakistan Computer Bureau

113

A Network File System (NFS) allows remote hosts to mount file systems over a network and interact with those file systems as though they are mounted locally. This enables system administrators to consolidate resources onto centralized servers on the network. This chapter focuses on fundamental NFS concepts and supplemental information.

10.1. How It Works


Currently, there are three versions of NFS. NFS version 2 (NFSv2) is older and is widely supported. NFS version 3 (NFSv3) has more features, including 64bit file handles, Safe Async writes and more robust error handling. NFS version 4 (NFSv4) works through firewalls and on the Internet, no longer requires portmapper, supports ACLs, and utilizes stateful operations. Red Hat Enterprise Linux supports NFSv2, NFSv3, and NFSv4 clients, and when mounting a file system via NFS, Red Hat Enterprise Linux uses NFSv3 by default, if the server supports it. All versions of NFS can use Transmission Control Protocol (TCP) running over an IP network, with NFSv4 requiring it. NFSv2 and NFSv3 can use the User Datagram Protocol (UDP) running over an IP network to provide a stateless network connection between the client and server. When using NFSv2 or NFSv3 with UDP, the stateless UDP connection under normal conditions has less Protocol overhead than TCP which can translate into better performance on very clean, non-congested networks. The NFS server sends the client a file handle after the client is authorized to access the shared volume. This file handle is an opaque object stored on the server's side and is passed along with RPC requests from the client. The NFS server can be restarted without affecting the clients and the cookie remains intact. However, because UDP is stateless, if the server goes down unexpectedly, UDP clients continue to saturate the network with requests for the server. For this reason, TCP is the preferred protocol when connecting to an NFS server. NFSv4 has no interaction with portmapper, rpc.mountd, rpc.lockd, and rpc.statd, since protocol support has been incorporated into the v4 protocol. NFSv4 listens on the well known TCP port (20410) which eliminates the need for the portmapper interaction. The mounting and locking protocols have been incorpated into the V4 protocol which eliminates the need for interaction with rpc.mountd and rpc.lockd.
Pakistan Computer Bureau 114

Note
TCP is the default transport protocol for NFS under Red Hat Enterprise Linux. UDP can be used for compatibility purposes as needed, but is not recommended for wide usage. All the RPC/NFS daemon have a '-p' command line option that can set the port, making firewall configuration easier.

After the client is granted access by TCP wrappers, the NFS server refers to its configuration file, /etc/exports, to determine whether the client is allowed to access any of the exported file systems. Once access is granted, all file and directory operations are available to the user. Note f FS to work with a default installation of Red
Red Hat Enterprise Linux with a firewall enabled, IPTables with the default TCP port 20410 must be configured. Without proper IPTables configuration, NFS does not function properly.The NFS initialization script and rpc.nfsd process now allow binding to any specified port during system start up. However, this can be error prone if the port is unavailable or conflicts with another daemon.

10.1.1. Required Services


Red Hat Enterprise Linux uses a combination of kernel-level support and daemon processes to provide NFS file sharing. All NFS versions rely on Remote Procedure Calls (RPC) between clients and servers. RPC services under Linux are controlled by the portmap service. To share or mount NFS file systems, the following services work together, depending on which version of NFS is implemented: nfs (/sbin/service nfs start) starts the NFS server and the appropriate RPC processes to service requests for shared NFS file systems. nfslock (/sbin/service nfslock start) is a mandatory service that starts the appropriate RPC processes to allow NFS clients to lock files on the server. portmap accepts port reservations from local RPC services. These ports are then made available (or advertised) so the corresponding remote RPC services access them. portmap responds to requests for RPC services and sets up connections to the requested RPC service. This is not used with

Pakistan Computer Bureau

115

NFSv4. The following RPC processes facilitate NFS services: rpc.mountd This process receives mount requests from NFS clients and verifies the requested file system is currently exported. This process is started automatically by the nfs service and does not require user configuration. This is not used with NFSv4. rpc.nfsd Allows explicit NFS versions and protocols the server advertises to be defined. It works with the Linux kernel to meet the dynamic demands of NFS clients, such as providing server threads each time an NFS client connects. This process corresponds to the NFS service. rpc.lockd allows NFS clients to lock files on the server. If rpc.lockd is not started, file locking will fail. rpc.lockd implements the Network Lock Manager (NLM) protocol. This process corresponds to the nfslock service. This is not used with NFSv4. rpc.statd This process implements the Network Status Monitor (NSM) RPC protocol which notifies NFS clients when an NFS server is restarted without being gracefully brought down. This process is started automatically by the nfslock service and does not require user configuration. This is not used with NFSv4. rpc.rquotad This process provides user quota information for remote users. This process is started automatically by the NFS service and does not require user configuration. rpc.idmapd This process provides NFSv4 client and server upcalls which map between on-the-wire NFSv4 names (which are strings in the form of user@domain) and local UIDs and GIDs. For idmapd to function with NFSv4, the /etc/idmapd.conf must be configured. This service is required for use with NFSv4.

10.2. NFS Client Configuration


NFS shares are mounted on the client side using the mount command. The format of the command is as follows:

Pakistan Computer Bureau

116

mount -t <nfs-type> -o <options><host>:</remote/export></local/directory> Replace <nfs-type> with either nfs for NFSv2 or NFSv3 servers, or nfs4 for NFSv4 servers. Replace <options> with a comma separated list of options for the NFS file system. Replace <host> with the remote host, </remote/export> with the remote directory being mounted, and </local/directory> with the local directory where the remote file system is to be mounted. If accessing an NFS share by manually issuing the mount command, the file system must be remounted manually after the system is rebooted. Red Hat Enterprise Linux offers two methods for mounting remote file systems automatically at boot time: the /etc/fstab file or the autofs service.

10.2.1. Mounting NFS File Systems using /etc/fstab


An alternate way to mount an NFS share from another machine is to add a line to the /etc/fstab file. The line must state the hostname of the NFS server, the directory on the server being exported, and the directory on the local machine where the NFS share is to be mounted. You must be root to modify the /etc/fstab file. The general syntax for the line in /etc/fstab is as follows: server:/usr/local/pub /pub nfs rsize=81102,wsize=81102,timeo=14,intr The mount point /pub must exist on the client machine before this command can be executed. After adding this line to /etc/fstab on the client system, type the command mount /pub at a shell prompt, and the mount point /pub is mounted from the server. The /etc/fstab file is referenced by the netfs service at boot time, so lines referencing NFS shares have the same effect as manually typing the mount command during the boot process. A sample /etc/fstab line to mount an NFS export looks like the following example: <server>:</remote/export></local/directory><nfstype><options> 0 0

Pakistan Computer Bureau

117

Replace <server> with the hostname, IP address, or fully qualified domain name of the server exporting the file system. Replace </remote/export> with the path to the exported directory.Replace </local/directory> with the local file system on which the exported directory is mounted. This mount point must exist before /etc/fstab is read or the mount fails. eplace <nfs-type> with either nfs for NFSv2 or NFSv3 servers, or nfs4 for NFSv4 servers. Replace <options> with a comma separated list of options for the NFS file system.

10.3. autofs
One drawback to using /etc/fstab is that, regardless of how infrequently a user accesses the NFS mounted file system, the system must dedicate resources to keep the mounted file system in place. This is not a problem with one or two mounts, but when the system is maintaining mounts to many systems at one time, overall system performance can be affected. An alternative to /etc/fstab is to use the kernel-based automount utility. An automounter consists of two components. One is a kernel module that implements a file system, while the other is a user-space daemon that performs all of the other functions. The automount utility can mount and unmount NFS file systems automatically (on demand mounting) therefore saving system resources. The automount utility can be used to mount other file systems including AFS, SMBFS, CIFS and local file systems. autofs uses /etc/auto.master (master map) as its default primary configuration file. This can be changed to use another supported network source and name using the autofs configuration (in /etc/sysconfig/autofs) in conjunction with the Name Service Switch mechanism. An instance of the version 4 daemon was run for each mount point configured in the master map and so it could be run manually from the command line for any given mount point. This is not possible with version 5 because it uses a single daemon to manage all configured mount points, so all automounts must be configured in the master map. This is in line with the usual requirements of other industry standard automounters. Mount point, hostname, exported directory, and options can all be specified in a set of files (or other supported network sources) rather than configuring them manually for each host. Please ensure that you have the autofs package installed if you wish to use this service.

Pakistan Computer Bureau

118

10.3.1. What's new in autofs version 5?


Direct map support Autofs direct maps provide a mechanism to automatically mount file systems at arbitrary points in the file system hierarchy. A direct map is denoted by a mount point of "/-" in the master map. Entries in a direct map contain an absolute path name as a key (instead of the relative path names used in indirect maps). Lazy mount and unmount support Multimount map entries describe a hierarchy of mount points under a single key. A good example of this is the "-hosts" map, commonly used for automounting all exports from a host under "/net/<host>" as a multi-mount map entry. When using the "-hosts" map, an 'ls' of "/net/<host>" will mount autofs trigger mounts for each export from <host> and mount and expire them as they are accessed. This can greatly reduce the number of active mounts needed when accessing a server with a large number of exports. Enhanced LDAP support The Lightweight Directory Access Protocol, or LDAP, support in autofs version 5 has been enhanced in several ways with respect to autofs version 4. The autofs configuration file (/etc/sysconfig/autofs) provides a mechanism to specify the autofs schema that a site implements, thus precluding the need to determine this via trial and error in the application itself. In addition, authenticated binds to the LDAP server are now supported, using most mechanisms supported by the common LDAP server implementations. A new configuration file has been added for this support: /etc/autofs_ldap_auth.conf. The default configuration file is selfdocumenting, and uses an XML format. Proper use of the Name Service Switch (nsswitch) configuration. The Name Service Switch configuration file exists to provide a means of determining from where specific configuration data comes. The reason for this configuration is to allow administrators the flexibility of using the back-end database of choice, while maintaining a uniform software interface to access the data. While the version 4 automounter is becoming increasingly better at handling the name service switch configuration, it is still not complete.
Pakistan Computer Bureau 119

Autofs version 5, on the other hand, is a complete implementation. See the manual page for nsswitch.conf for more information on the supported syntax of this file. Please note that not all NSS databases are valid map sources and the parser will reject ones that are invalid. Valid sources are files, yp, nis, nisplus, ldap and hesiod. Multiple master map entries per autofs mount point One thing that is frequently used but not yet mentioned is the handling of multiple master map entries for the direct mount point "/-". The map keys for each entry are merged and behave as one map. An example is seen in the connectathon test maps for the direct mounts below: /- /tmp/auto_dcthon /- /tmp/auto_test3_direct /- /tmp/auto_test4_direct

10.3.2. autofs Configuration


The primary configuration file for the automounter is /etc/auto.master, also referred to as the master map which may be changed as described in the introduction section above. The master map lists autofs-controlled mount points on the system, and their corresponding configuration files or network sources known as automount maps. The format of the master map is as follows: <mount-point> <map-name> <options> where: mount-point is the autofs mount point e.g /home. map-name is the name of a map source which contains a list of mount points, and the file system location from which those mount points should be mounted. The syntax for a map entry is described below. Options if supplied, will apply to all entries in the given map provided they don't themselves have options specified. This behavior is different from autofs version 4 where the options where cumulative.

Pakistan Computer Bureau

120

This has been changed to meet our primary goal of mixed environment compatibility. The following is a sample /etc/auto.master file: $ cat /etc/auto.master /home /etc/auto.misc The general format of maps is similar to the master map, however the "options" appear between the mount point and the location instead of at the end of the entry as in the master map: <mount-point> [<options>] <location> where: <mount-point> is the autofs mount point. This can be a single directory name for an indirect mount or the full path of the mount point for direct mounts. Each direct and indirect map entry key (<mount-point> above) may be followed by a space separated list of offset directories (sub directory names each beginning with a "/") making them what is known as a mutli-mount entry. <options> if supplied, are the mount options for the map entries that do not specify their own options. <location> is the file system location such as a local file system path (preceded with the Sun map format escape character ":" for map names beginning with "/"), an NFS file system or other valid file system location. The following is a sample map file: $ cat /etc/auto.misc payroll -fstype=nfs personnel:/dev/hda3 sales -fstype=ext3 :/dev/hda4 The first column in a map file indicates the autofs mount point (sales and payroll from the server called personnel). The second column indicates the options for the autofs mount while the third column indicates the source of the mount. Following the above configuration, the autofs mount points will be /home/payroll and /home/sales. The -fstype= option is often omitted and is generally not needed for correct operation.

Pakistan Computer Bureau

121

The automounter will create the directories if they do not exist. If the directories exist before the automounter was started, the automounter will not remove them when it exits. You can start or restart the automount daemon by issuing the following command: $/sbin/service autofs start or $/sbin/service autofs restart Using the above configuration, if a process requires access to an autofs unmounted directory such as /home/payroll/2006/July.sxc, the automount daemon automatically mounts the directory. If a timeout is specified, the directory will automatically be unmounted if the directory is not accessed for the timeout period. You can view the status of the automount daemon by issuing the following command in your terminal: $/sbin/service/autofs status

10.3.3. autofs Common Tasks 10.3.3.1. Overriding or augmenting site configuration files
It can be useful to override site defaults for a specific mount point on a client system. For example, assuming that the automounter maps are stored in NIS and the /etc/nsswitch.conf file has the following directive: automount: files nis

and the NIS auto.master map file contains the following: /home auto.home Also assume the NIS auto.home map contains the following: bethfileserver.example.com:/export/home/beth joe fileserver.example.com:/export/home/joe * fileserver.example.com:/export/home/& and the file map /etc/auto.home does not exist. For the above example, lets assume that the client system needs to mount home directories from a different server. In this case, the client will need to use the following /etc/auto.master map: /home /etc/auto.home2

Pakistan Computer Bureau

122

+auto.master And the /etc/auto.home2 map contains the entry: *labserver.example.com:/export/home/& Because only the first occurrence of a mount point is processed, /home will contain the contents of /etc/auto.home2 instead of the NIS auto.home map. Alternatively, if you just want to augment the site-wide auto.home map with a few entries, create a /etc/auto.home file map, and in it put your new entries and at the end, include the NIS auto.home map. Then the /etc/auto.home file map might look similar to: mydir someserver:/export/mydir +auto.home Given the NIS auto.home map listed above, an ls of /home would now give: $ ls /home beth joe mydir This last example works as expected because autofs knows not to include the contents of a file map of the same name as the one it is reading and so moves on to the next map source in the nsswitch configuration. 10.3.3.2. Using LDAP to Store Automounter Maps LDAP client libraries must be installed on all systems which are to retrieve automounter maps from LDAP. On RHEL 5, the openldap package should be installed automatically as a dependency of the automounter. To configure LDAP access, modify /etc/openldap/ldap.conf. Ensure that BASE and URI are set appropriately for your site. Please also ensure that the schema is set in the configuration. The most recently established schema for storing automount maps in LDAP is described by rfc2307bis. To use this schema it is necessary to set it in the autofs configuration (/etc/sysconfig/autofs) by removing the comment characters from the schema definition. For example: DEFAULT_MAP_OBJECT_CLASS="automountMap"
Pakistan Computer Bureau 123

DEFAULT_ENTRY_OBJECT_CLASS="automount" DEFAULT_MAP_ATTRIBUTE="automountMapName" DEFAULT_ENTRY_ATTRIBUTE="automountKey" DEFAULT_VALUE_ATTRIBUTE="automountInformation" Ensure that these are the only schema entries not commented in the configuration. Please also note that the automountKey replaces the cn attribute in the rfc2307b is schema. An LDIF of a sample configuration is described below: # extended LDIF # # LDAPv3 # base <> with scope subtree # filter: (&(objectclass=automountMap)(automountMapName=auto.mas ter)) # requesting: ALL # # auto.master, example.com dn: automountMapName=auto.master,dc=example,dc=com objectClass: top objectClass: automountMap automountMapName: auto.master # extended LDIF # # LDAPv3 # base <automountMapName=auto.master,dc=example,dc=com> with scope subtree # filter: (objectclass=automount) # requesting: ALL # # /home, auto.master, example.com dn: automountMapName=auto.master,dc=example,dc=com objectClass: automount cn: /home automountKey: /home automountInformation: auto.home # extended LDIF # # LDAPv3 # base <> with scope subtree

Pakistan Computer Bureau

124

# filter: (&(objectclass=automountMap)(automountMapName=auto.hom e)) # requesting: ALL # # auto.home, example.com dn: automountMapName=auto.home,dc=example,dc=com objectClass: automountMap automountMapName: auto.home # extended LDIF # # LDAPv3 # base <automountMapName=auto.home,dc=example,dc=com> with scope subtree # filter: (objectclass=automount) # requesting: ALL # # foo, auto.home, example.com dn: automountKey=foo,automountMapName=auto.home,dc=example ,dc=com objectClass: automount automountKey: foo automountInformation: filer.example.com:/export/foo # /, auto.home, example.com dn: automountKey=/,automountMapName=auto.home,dc=example,d c=com objectClass: automount automountKey: / automountInformation: filer.example.com:/export/&

10.3.3.3. Adapting Autofs v4 Maps To Autofs v5 V4 Multi-map entries


Autofs version 4 introduced the notion of a multi-map entry in the master map. A multi-map entry is of the form: <mount-point> <maptype1> <mapname1> <options1> -<maptype2> <mapname2> <options2> -- ...
Pakistan Computer Bureau 125

Any number of maps can be combined into a single map in this manner. This feature is no longer present in v5. This is because Version 5 supports included maps which can be used to attain the same results. Consider the following multimap example: /home file/etc/auto.home -- nis auto.home This can be replaced by the following configuration for v5: /etc/nsswitch.conf must list: automount: files nis /etc/auto.master should contain: /home auto.home /etc/auto.home should contain: <entries for the home directory> +auto.home In this way, the entries from /etc/auto.home and the nis auto.home map are combined.

Multiple master maps.


In autofs version 4, it is possible to merge the contents of master maps from each source, such as files, nis, hesiod, and LDAP. The version 4 automounter looks for a master map for each of the sources listed in /etc/nsswitch.conf. The map is read if it exists and its contents are merged into one large auto.master map. In version 5, this is no longer the behaviour. Only the first master map found from the list of sources in nsswitch.conf is consulted. If it is desirable to merge the contents of multiple master maps, included maps can be used. Consider the following example: /etc/nsswitch.conf: automount: files nis /etc/auto.master: /home /etc/auto.home +auto.master The above configuration will merge the contents of the file-based auto.master and the NIS-based auto.master. However, because included map entries are only allowed in file maps, there is no way to include

Pakistan Computer Bureau

126

both an NIS auto.master and an LDAP auto.master. This limitation can be overcome by creating a master maps that have a different name in the source. In the example above if we had an LDAP master map named auto.master.ldap we could also add "+auto.master.ldap" to the file based master map and provided that "ldap" is listed as a source in our nsswitch configuration it would also be included. 10.4. Common NFS Mount Options Beyond mounting a file system via NFS on a remote host, other options can be specified at the time of the mount to make it easier to use. These options can be used with manual mount commands, /etc/fstab settings, and autofs. The following are options commonly used for NFS mounts: fsid=num Forces the file handle and file attributes settings on the wire to be num, instead of a number derived from the major and minor number of the block device on the mounted file system. The value 0 has special meaning when used with NFSv4. NFSv4 has a concept of a root of the overall exported file system. The export point exported with fsid=0 is used as this root. hard or soft Specifies whether the program using a file via an NFS connection should stop and wait (hard) for the server to come back online, if the host serving the exported file system is unavailable, or if it should report an error (soft). If hard is specified, the user cannot terminate the process waiting for the NFS communication to resume unless the intr option is also specified. If soft is specified, the user can set an additional timeo=<value> option, where <value> specifies the number of seconds to pass before the error is reported. Note
Using soft mounts is not recommended as they can generate I/O errors in very congested networks or when using a very busy server.

intr Allows NFS requests to be interrupted if the server goes down or cannot be reached.

Pakistan Computer Bureau

127

nfsvers=2 or nfsvers=3 Specifies which version of the NFS protocol to use. This is useful for hosts that run multiple NFS servers. If no version is specified, NFS uses the highest supported version by the kernel and mount command. This option is not supported with NFSv4 and should not be used. noacl Turns off all ACL processing. This may be needed when interfacing with older versions of Red Hat Enterprise Linux, Red Hat Linux, or Solaris, since the most recent ACL technology is not compatible with older systems. nolock Disables file locking. This setting is occasionally required when connecting to older NFS servers. noexec Prevents execution of binaries on mounted file systems. This is useful if the system is mounting a non-Linux file system via NFS containing incompatible binaries. nosuid Disables set-user-identifier or set-group-identifier bits. This prevents remote users from gaining higher privileges by running a setuid program. port=num Specifies the numeric value of the NFS server port. If num is 0 (the default), then mount queries the remote host's portmapper for the port number to use. If the remote host's NFS daemon is not registered with its portmapper, the standard NFS port number of TCP 20410 is used instead. rsize=num and wsize=num These settings speed up NFS communication for reads (rsize) and writes (wsize) by setting a larger data block size, in bytes, to be transferred at one time. Be careful when changing these values; some older Linux kernels and network cards do not work well with larger block sizes. For NFSv2 or NFSv3, the default values for both parameters is set to 81102. For NFSv4, the default values for both parameters is set to 32768. sec=mode Specifies the type of security to utilize when authenticating an NFS connection.

Pakistan Computer Bureau

128

sec=sys is the default setting, which uses local UNIX UIDs and GIDs by means of

AUTH_SYS to authenticate NFS operations.

sec=krb5 uses Kerberos V5 instead of local UNIX UIDs and GIDs to authenticate users. sec=krb5i uses Kerberos V5 for user authentication and performs integrity checking of NFS operations using secure checksums to prevent data tampering. sec=krb5p uses Kerberos V5 for user authentication, integrity checking, and encrypts NFS traffic to prevent traffic sniffing. This is the most secure setting, but it also has the most performance overhead involved. tcp Specifies for the NFS mount to use the TCP protocol. udp Specifies for the NFS mount to use the UDP protocol. Many more options are listed on the mount and nfs man pages.

10.5. Starting and Stopping NFS


To run an NFS server, the portmap service must be running. To verify that portmap is active, type the following command as root: /sbin/service portmap status If the portmap service is running, then the NFS service can be started. To start an NFS server, as root type: /sbin/service nfs start Note
nfslock also has to be started for both the NFS client and server to function properly. To start NFS locking as root type: /sbin/service nfslock start. If NFS is set to start at boot, please ensure that nfslock also starts by running chkconfig --list nfslock. If nfslock is not Pakistan Computer Bureau 129

set to on, this implies that you will need to manually run the /sbin/service nfslock start each time the computer starts. To set nfslock to automatically start on boot, type the following command in a terminal chkconfig nfslock on.

To stop the server, as root, type: /sbin/service nfs stop

The restart option is a shorthand way of stopping and then starting NFS. This is the most efficient way to make configuration changes take effect after editing the configuration file for NFS. To restart the server, as root, type: /sbin/service nfs restart The condrestart (conditional restart) option only starts NFS if it is currently running. This option is useful for scripts, because it does not start the daemon if it is not running. To conditionally restart the server, as root, type: /sbin/service nfs condrestart To reload the NFS server configuration file without restarting the service, as root, type: /sbin/service nfs reload By default, the NFS service does not start automatically at boot time. To configure the NFS to start up at boot time, use an initscript utility, such as /sbin/chkconfig, /usr/sbin/ntsysv, or the Services Configuration Tool program.

10.6. NFS Server Configuration


There are three ways to configure an NFS server under Red Hat Enterprise Linux: using the NFS Server Configuration Tool (system-config-nfs), manually editing its configuration file (/etc/exports), or using the /usr/sbin/exportfs command. To use the NFS Server Configuration Tool, you must be running X Windows, have root privileges, and have the system-config-nfs RPM package installed.

Pakistan Computer Bureau

130

To start the application, click on System => Administration => Server Settings => NFS. You can also type the command system-config-nfs in a terminal. The NFS Server Configuration tool window is illustrated below.

NFS Server Configuration Tool

Based on certain firewall settings, you may need to configure the NFS daemon processes to use specific networking ports. The NFS server settings allows you to specify the ports for each process instead of using the random ports assigned by the portmapper. You can set the NFS Server settings by clicking on the Server Settings button. The figure below illustrates the NFS Server Settings window.

NFS Server Settings

10.6.1. Exporting or Sharing NFS File Systems


Sharing or serving files from an NFS server is known as exporting the directories.
Pakistan Computer Bureau 131

The NFS Server Configuration Tool can be used to configure a system as an NFS server. To add an NFS share, click the Add button. The Basic tab requires the following information: Directory Specify the directory to share, such as /tmp. Host(s) Specify the host(s) with which to share the directory. Basic permissions Specify whether the directory should have readonly or read/write permissions.

Add Share

The General Options tab allows the following options to be configured:

Pakistan Computer Bureau

132

NFS General Options

Allow connections from port 1024 and higher Services started on port numbers less than 1024 must be started as root. Select this option to allow the NFS service to be started by a user other than root. This option corresponds to insecure. Allow insecure file locking Do not require a lock request. This option corresponds to insecure_locks. Disable subtree checking If a subdirectory of a file system is exported, but the entire file system is not exported, the server checks to see if the requested file is in the subdirectory exported. This check is called subtree checking. Select this option to disable subtree checking. If the entire file system is exported, selecting to disable subtree checking can increase the transfer rate. This option corresponds to no_subtree_check. Sync write operations on request Enabled by default, this option does not allow the server to reply to requests before the changes made by the request are written to the disk. This option corresponds to sync. If this is not selected, the

Pakistan Computer Bureau

133

async option is used. Force sync of write operations immediately Do not delay writing to disk. This option corresponds to no_wdelay. Hide filesystems beneath turns the nohide option on or off. When the nohide option is off, nested directories are revealed. The clients can therefore navigate through a filesystem from the parent without noticing any changes. Export only if mounted sets the mountpoint option which allows a directory to be exported only if it has been mounted. Optional Mount Point specifies the path to an optional mount point. Click on the Browse to navigate to the preferred mount point or type the path if known. Set explicit Filesystem ID: sets the fsid=X option. This is mainly used in a clustered setup. Using a consistent filesystem ID in all clusters avoids having stale NFS filehandles.

NFS User Access

The User Access tab allows the following options to be configured:


Pakistan Computer Bureau 134

Treat remote root user as local root By default, the user and group IDs of the root user are both 0. Root squashing maps the user ID 0 and the group ID 0 to the user and group IDs of anonymous so that root on the client does not have root privileges on the NFS server. If this option is selected, root is not mapped to anonymous, and root on a client has root privileges to exported directories. Selecting this option can greatly decrease the security of the system. Do not select it unless it is absolutely necessary. This option corresponds to no_root_squash. Treat all client users as anonymous users If this option is selected, all user and group IDs are mapped to the anonymous user. This option corresponds to all_squash. Specify local user ID for anonymous users If Treat all client users as anonymous users is selected, this option lets you specify a user ID for the anonymous user. This option corresponds to anonuid. Specify local group ID for anonymous users If Treat all client users as anonymous users is selected, this option lets you specify a group ID for the anonymous user. This option corresponds to anongid. To edit an existing NFS share, select the share from the list, and click the Properties button. To delete an existing NFS share, select the share from the list, and click the Delete button. After clicking OK to add, edit, or delete an NFS share from the list, the changes take place immediately the server daemon is restarted and the old configuration file is saved as /etc/exports.bak. The new configuration is written to /etc/exports. The NFS Server Configuration Tool reads and writes directly to the /etc/exports configuration file. Thus, the file can be modified manually after using the tool, and the tool can be used after modifying the file manually (provided the file was modified with correct syntax).

Pakistan Computer Bureau

135

The next this section discusses manually editing /etc/exports and using the /usr/sbin/exportfs command to export NFS file systems.

10.6.2. Command Line Configuration


If you prefer editing configuration files using a text editor or if you do not have the X Window System installed, you can modify the configuration file directly. The /etc/exports file controls what directories the NFS server exports. Its format is as follows: directoryhostname(options) The only option that needs to be specified is one of sync or async (sync is recommended). If sync is specified, the server does not reply to requests before the changes made by the request are written to the disk. For example, /misc/export speedy.example.com(sync) would allow users from speedy.example.com to mount /misc/export with the default read-only permissions, but, /misc/export speedy.example.com(rw,sync) would allow users from speedy.example.com to mount /misc/export with read/write privileges.

NOTE:
Be careful with spaces in the /etc/exports file. If there are no spaces between the hostname and the options in parentheses, the options apply only to the hostname. If there is a space between the hostname and the options, the options apply to the rest of the world. For example, examine the following lines:

/misc/export speedy.example.com(rw,sync) speedy.example.com (rw,sync)

/misc/export

The first line grants users from speedy.example.com read-write access and denies all other users. The second line grants users from speedy.example.com read-only access (the default) and allows the rest of the world read-write access.

Pakistan Computer Bureau

136

Each time you change /etc/exports, you must inform the NFS daemon of the change, or reload the configuration file with the following command: /sbin/service nfs reload

10.6.3. Hostname Formats


The host(s) can be in the following forms: Single machine A fully qualified domain name (that can be resolved by the server), hostname (that can be resolved by the server), or an IP address. Series of machines specified with wildcards Use the * or? character to specify a string match. Wildcards are not to be used with IP addresses; however, they may accidentally work if reverse DNS lookups fail. When specifying wildcards in fully qualified domain names, dots (.) are not included in the wildcard. For example, *.example.com includes one.example.com but does not include one.two.example.com. IP networks Use a.b.c.d/z, where a.b.c.d is the network and z is the number of bits in the netmask (for example 1102.168.0.0/24). Another acceptable format is a.b.c.d/netmask, where a.b.c.d is the network and netmask is the netmask (for example, 1102.168.100.8/255.255.255.0).

Netgroups In the format @group-name, where group-name is the NIS netgroup name.

10.7. The /etc/exports Configuration File


The /etc/exports file controls which file systems are exported to remote hosts and specifies options. Blank lines are ignored, comments can be made by starting a line with the hash mark (#), and long lines can be wrapped with a backslash (\). Each exported file system should be on its own individual line, and any lists of authorized hosts placed after an exported file system must be separated by space characters. Options for each of the hosts must be placed in parentheses directly after the host identifier, without any spaces separating the host and the first parenthesis. Valid host types are gss/krb5gss/krb5i and gss/krb5p. A line for an exported file system has the following structure:
Pakistan Computer Bureau 137

<export><host1>(<options>) <hostN>(<options>)... In this structure, replace <export> with the directory being exported, replace <host1> with the host or network to which the export is being shared, and replace <options> with the options for that host or network. Additional hosts can be specified in a space separated list. The following methods can be used to specify host names: single host Where one particular host is specified with a fully qualified domain name, hostname, or IP address. wildcards Where a * or ? character is used to take into account a grouping of fully qualified domain names that match a particular string of letters. Wildcards should not be used with IP addresses; however, it is possible for them to work accidentally if reverse DNS lookups fail. Be careful when using wildcards with fully qualified domain names, as they tend to be more exact than expected. For example, the use of *.example.com as a wildcard allows sales.example.com to access an exported file system, but not bob.sales.example.com. To match both possibilities both *.example.com and *.*.example.com must be specified. IP networks Allows the matching of hosts based on their IP addresses within a larger network. For example, 1102.168.0.0/28 allows the first 16 IP addresses, from 1102.168.0.0 to 1102.168.0.15, to access the exported file system, but not 1102.168.0.16 and higher. netgroups Permits an NIS netgroup name, written as @<groupname>, to be used. This effectively puts the NIS server in charge of access control for this exported file system, where users can be added and removed from an NIS group without affecting /etc/exports. In its simplest form, the /etc/exports file only specifies the exported directory and the hosts permitted to access it, as in the following example: /exported/directory bob.example.com

Pakistan Computer Bureau

138

In the example, bob.example.com can mount /exported/directory/. Because no options are specified in this example, the following default NFS options take effect: ro Mounts of the exported file system are read-only. Remote hosts are not able to make changes to the data shared on the file system. To allow hosts to make changes to the file system, the read/write (rw) option must be specified. wdelay Causes the NFS server to delay writing to the disk if it suspects another write request is imminent. This can improve performance by reducing the number of times the disk must be accessed by separate write commands, reducing write overhead. The no_wdelay option turns off this feature, but is only available when using the sync option. root_squash Prevents root users connected remotely from having root privileges and assigns them the user ID for the user nfsnobody. This effectively "squashes" the power of the remote root user to the lowest local user, preventing unauthorized alteration of files on the remote server. Alternatively, the no_root_squash option turns off root squashing. To squash every remote user, including root, use the all_squash option. To specify the user and group IDs to use with remote users from a particular host, use the anonuid and anongid options, respectively. In this case, a special user account can be created for remote NFS users to share and specify (anonuid=<uid-value>,anongid=<gid-value>), where <uid-value> is the user ID number and <gid-value> is the group ID number. Important
By default, access control lists (ACLs) are supported by NFS under Red Hat Enterprise Linux. To disable this feature, specify the no_acl option when exporting the file system.

Each default for every exported file system must be explicitly overridden. For example, if the rw option is not specified, then the exported file system is shared as read-only. The following is a sample line from /etc/exports which overrides two default options:

Pakistan Computer Bureau

139

/another/exported/directory 1102.168.0.3(rw,sync)

In this example 1102.168.0.3 can mount /another/exported/directory/ read/write and all transfers to disk are committed to the disk before the write request by the client is completed. Additionally, other options are available where no default value is specified. These include the ability to disable sub-tree checking, allow access from insecure ports, and allow insecure file locks (necessary for certain early NFS client implementations Warning
The format of the /etc/exports file is very precise, particularly in regards to use of the space character. Remember to always separate exported file systems from hosts and hosts from one another with a space character. However, there should be no other space characters in the file except on comment lines. For example, the following two lines do not mean the same thing:

/home bob.example.com(rw) /home bob.example.com (rw) The first line allows only users from bob.example.com read/write access to the /home directory. The second line allows users from bob.example.com to mount the directory as read-only (the default), while the rest of the world can mount it read/write.

10.7.1. The exportfs Command


Every file system being exported to remote users via NFS, as well as the access level for those file systems, are listed in the /etc/exports file. When the nfs service starts, the /usr/sbin/exportfs command launches and reads this file, passes control to rpc.mountd (if NFSv2 or NFSv3) for the actual mounting process, then to rpc.nfsd where the file systems are then available to remote users. When issued manually, the /usr/sbin/exportfs command allows the root user to selectively export or unexport directories without restarting the NFS service. When given the proper options, the /usr/sbin/exportfs command

Pakistan Computer Bureau

140

writes the exported file systems to /var/lib/nfs/xtab. Since rpc.mountd refers to the xtab file when deciding access privileges to a file system, changes to the list of exported file systems take effect immediately. The following is a list of commonly used options available for

/usr/sbin/exportfs: -r Causes all directories listed in /etc/exports to be exported by constructing a new export list in /etc/lib/nfs/xtab. This option effectively refreshes the export list with any changes that have been made to /etc/exports. -a Causes all directories to be exported or unexported, depending on what other options are passed to /usr/sbin/exportfs. If no other options are specified, /usr/sbin/exportfs exports all file systems specified in /etc/exports. -o file-systems Specifies directories to be exported that are not listed in /etc/exports. Replace file-systems with additional file systems to be exported. These file systems must be formatted in the same way they are specified in /etc/exports. -i Ignores /etc/exports; only options given from the command line are used to define exported file systems. -u Unexports all shared directories. The command /usr/sbin/exportfs-ua suspends NFS file sharing while keeping all NFS daemons up. To re-enable NFS sharing, type exportfs -r. -v Verbose operation, where the file systems being exported or unexported are displayed in greater detail when the exportfs command is executed. If no options are passed to the /usr/sbin/exportfs command, it displays a list of currently exported file systems.

10.7.1.1. Using exportfs with NFSv4


The exportfs command is used in maintaining the NFS table of exported file

Pakistan Computer Bureau

141

systems. When typed in a terminal with no arguments, the exportfs command shows all the exported directories. Since NFSv4 no longer utilizes the rpc.mountd protocol as was used in NFSv2 and NFSv3, the mounting of file systems has changed. An NFSv4 client now has the ability to see all of the exports served by the NFSv4 server as a single file system, called the NFSv4 pseudo-file system. On Red Hat Enterprise Linux, the pseudo-file system is identified as a single, real file system, identified at export with the fsid=0 option. For example, the following commands could be executed on an NFSv4 server: mkdir /exports mkdir /exports/opt mkdir /exports/etc mount --bind /usr/local/opt /exports/opt mount --bind /usr/local/etc /exports/etc exportfs -o fsid=0,insecure,no_subtree_check gss/krb5p:/exports exportfs -o rw,nohide,insecure,no_subtree_check gss/krb5p:/exports/opt exportfs -o rw,nohide,insecure,no_subtree_check gss/krb5p:/exports/etc In this example, clients are provided with multiple file systems to mount, by using the --bind option which creates unbreakeable links. Because of the pseudo-file systems feature, NFS version 2, 3 and 4 export configurations are not always compatible. For example, given the following directory tree: /home /home/sam /home/john /home/joe and the export: /home *(rw,fsid=0,sync) Using NFS version 2,3 and 4 the following would work: mount server:/home /mnt/home ls /mnt/home/joe Using v4 the following would work: mount -t nfs4 server:/ /mnt/home ls /mnt/home/joe

Pakistan Computer Bureau

142

The difference being "server:/home" and "server:/". To make the exports configurations compatible for all version, one needs to export (read only) the root filesystem with an fsid=0. The fsid=0 signals the NFS server that this export is the root. / *(ro,fsid=0) /home *(rw,sync,nohide) Now with these exports, both "mount server:/home /mnt/home" and "mount -t nfs server:/home /mnt/home" will work as expected.

10.8. Securing NFS


NFS is well suited for sharing entire file systems with a large number of known hosts in a transparent manner. However, with ease of use comes a variety of potential security problems. The following points should be considered when exporting NFS file systems on a server or mounting them on a client. Doing so minimizes NFS security risks and better protects data on the server.

10.8.1. Host Access


Depending on which version of existing network environment, sections explain the differences NFSv2, NFSv3, and NFSv4. If over other versions of NFS 10.8.1.1. Using NFSv2 or NFSv3 NFS controls who can mount an exported file system based on the host making the mount request, not the user that actually uses the file system. Hosts must be given explicit rights to mount the exported file system. Access control is not possible for users, other than through file and directory permissions. In other words, once a file system is exported via NFS, any user on any remote host connected to the NFS server can access the shared data. To limit the potential risks, administrators often allow read-only access or squash user permissions to a common user and group ID. Unfortunately, these solutions prevent the NFS share NFS you plan to implement, depends on your and your security concerns. The following between implementing security measures with at all possible, use of NFSv4 is recommended

Pakistan Computer Bureau

143

from being used in the way it was originally intended. Additionally, if an attacker gains control of the DNS server used by the system exporting the NFS file system, the system associated with a particular hostname or fully qualified domain name can be pointed to an unauthorized machine. At this point, the unauthorized machine is the system permitted to mount the NFS share, since no username or password information is exchanged to provide additional security for the NFS mount. Wildcards should be used sparingly when exporting directories via NFS as it is possible for the scope of the wildcard to encompass more systems than intended. It is also possible to restrict access to the portmap service via TCP wrappers. Access to ports used by portmap, rpc.mountd, and rpc.nfsd can also be limited by creating firewall rules with iptables.

10.8.1.2. Using NFSv4


The release of NFSv4 brought a revolution to authentication and security to NFS exports. NFSv4 mandates the implementation of the RPCSEC_GSS kernel module, the Kerberos version 5 GSS-API mechanism, SPKM-3, and LIPKEY. With NFSv4, the mandatory security mechanisms are oriented towards authenticating individual users, and not client machines as used in NFSv2 and NFSv3. Note
It is assumed that a Kerberos ticket-granting server (KDC) is installed and configured correctly, prior to configuring an NFSv4 server. Kerberos is a network authentication system which allows clients and servers to authenticate to each other through use of symmetric encryption and a trusted third party, the KDC.

NFSv4 includes ACL support based on the Microsoft Windows NT model, not the POSIX model, because of its features and because it is widely deployed. NFSv2 and NFSv3 do not have support for native ACL attributes. Another important security feature of NFSv4 is its removal of the rpc.mountd daemon. The rpc.mountd daemon presented possible security holes because of the way it dealt with filehandlers. For more information on the RPCSEC_GSS framework, including how rpc.svcgssd and rpc.gssd inter operate, refer to http://www.citi.umich.edu/projects/nfsv4/gssd/.

Pakistan Computer Bureau

144

10.8.2. File Permissions


Once the NFS file system is mounted read/write by a remote host, the only protection each shared file has is its permissions. If two users that share the same user ID value mount the same NFS file system, they can modify each others files. Additionally, anyone logged in as root on the client system can use the su - command to become a user who could access particular files via the NFS share. By default, access control lists (ACLs) are supported by NFS under Red Hat Enterprise Linux. It is not recommended that this feature be disabled. The default behavior when exporting a file system via NFS is to use root squashing. This sets the user ID of anyone accessing the NFS share as the root user on their local machine to a value of the server's nfsnobody account. Never turn off root squashing. If exporting an NFS share as read-only, consider using the all_squash option, which makes every user accessing the exported file system take the user ID of the nfsnobody user.

10.9. NFS and portmap


Note
The following section only applies to NFSv2 or NFSv3 implementations that require the portmap service for backward compatibility.

The portmapper maps RPC services to the ports they are listening on. RPC processes notify portmap when they start, registering the ports they are listening on and the RPC program numbers they expect to serve. The client system then contacts portmap on the server with a particular RPC program number. The portmap service redirects the client to the proper port number so it can communicate with the requested service. Because RPC-based services rely on portmap to make all connections with incoming client requests, portmap must be available before any of these services start. The portmap service uses TCP
Pakistan Computer Bureau 145

wrappers for access control, and access control rules for portmap affect all RPCbased services. Alternatively, it is possible to specify access control rules for each of the NFS RPC daemons. The man pages for rpc.mountd and rpc.statd contain information regarding the precise syntax for these rules.

10.9.1. Troubleshooting NFS and portmap


Because portmap provides coordination between RPC services and the port numbers used to communicate with them, it is useful to view the status of current RPC services using portmap when troubleshooting. The rpcinfo command shows each RPC-based service with port numbers, an RPC program number, a version number, and an IP protocol type (TCP or UDP). To make sure the proper NFS RPC-based services are enabled for portmap, issue the following command as root: rpcinfo -p The following is sample output from this command: program vers proto port 100000 2 tcp 111 portmapper 100000 2 udp 111 portmapper 100021 1 udp 32774 nlockmgr 100021 3 udp 32774 nlockmgr 100021 4 udp 32774 nlockmgr 100021 1 tcp 34437 nlockmgr 100021 3 tcp 34437 nlockmgr 100021 4 tcp 34437 nlockmgr 100011 1 udp 8110 rquotad 100011 2 udp 8110 rquotad 100011 1 tcp 822 rquotad 100011 2 tcp 822 rquotad 100003 2 udp 20410 nfs 100003 3 udp 20410 nfs 100003 2 tcp 20410 nfs 100003 3 tcp 20410 nfs 100005 1 udp 836 mountd 100005 1 tcp 8310 mountd 100005 2 udp 836 mountd 100005 2 tcp 8310 mountd 100005 3 udp 836 mountd 100005 3 tcp 8310 mountd If one of the NFS services does not start up correctly, portmap is unable to map RPC requests from clients for that service to the correct port. In many cases, if NFS is not present in rpcinfo output, restarting NFS causes the service to correctly register with portmap and begin working. Other useful options are available for

Pakistan Computer Bureau

146

the rpcinfo command. Refer to the rpcinfo man page for more information.

10.10. Using NFS over TCP


The default transport protocol for NFSv4 is TCP; however, the Red Hat Enterprise Linux 5 kernel includes support for NFS over UDP. To use NFS over UDP, include the -o udp option to mount when mounting the NFSexported file system on the client system. There are three ways to configure an NFS file system export. On demand via the command line (client side), automatically via the /etc/fstab file (client side), and automatically via autofs configuration files, such as /etc/auto.master and /etc/auto.misc (server side with NIS). For example, on demand via the command line (client side): mount -o udp shadowman.example.com:/misc/export /misc/local When the NFS mount is specified in /etc/fstab (client side): server:/usr/local/pub /pub nfs rsize=81102,wsize=81102,timeo=14,intr,udp When the NFS mount is specified in an autofs configuration file for a NIS server, available for NIS enabled workstations: myproject -rw,soft,intr,rsize=81102,wsize=81102,udp penguin.example.net:/proj52 Since the default is TCP, if the -o udp option is not specified, the NFS-exported file system is accessed via TCP. The advantages of using TCP include the following: Improved connection durability, thus less NFS stale file handles messages. Performance gain on heavily loaded networks because TCP acknowledges every packet, unlike UDP which only acknowledges completion. TCP has better congestion control than UDP. On a very congested network, UDP packets are the first packets that are dropped. This means that if NFS is writing data (in 8K chunks) all of that 8K must be retransmitted over UDP. Because of TCP's reliability, only parts of that 8K data are transmitted at a time.

Pakistan Computer Bureau

147

Error detection. When a TCP connection breaks (due to the server being unavailable) the client stops sending data and restarts the connection process once the server becomes available. With UDP, since it's connection-less, the client continues to pound the network with data until the server reestablishes a connection. The main disadvantage is that there is a very small performance hit due to the overhead associated with the TCP protocol.

10.11. Additional Resources


Administering an NFS server can be a challenge. Many options, including quite a few not mentioned in this chapter, are available for exporting or mounting NFS shares. Consult the following sources for more information.

10.11.1. Installed Documentation


/usr/share/doc/nfs-utils-<version-number>/Replace <versionnumber> with the version number of the NFS package installed. This directory contains a wealth of information about the NFS implementation for Linux, including a look at various NFS configurations and their impact on file transfer performance. man mount Contains a comprehensive look at mount options for both NFS server and client configurations. man fstab Gives details for the format of the /etc/fstab file used to mount file systems at boot-time. man nfs Provides details on NFS-specific file system export and mount options. man exports Shows common options used in the /etc/exports file when exporting NFS file systems.

10.11.2. Useful Websites


http://nfs.sourceforge.net/ The home of the Linux NFS project and a great place for project status updates. http://www.citi.umich.edu/projects/nfsv4/linux/
Pakistan Computer Bureau 148

An NFSv4 for Linux 2.6 kernel resource. http://www.nfsv4.org1 The home of NFS version 4 and all related standards. http://www.vanemery.com/Linux/NFSv4/NFSv4-norpcsec.html Describes the details of NFSv4 with Fedora Core 2, which includes the 2.6 kernel. http://www.nluug.nl/events/sane2000/papers/pawlows ki.pdf An excellent whitepaper on the features and enhancements of the NFS Version 4 protocol. http://wiki.autofs.net The Autofs wiki, discussions, documentation and enhancements.

10.11.3. Related Books


Managing NFS and NIS by Hal Stern, Mike Eisler, and

Ricardo Labiaga; O'Reilly & Associates Makes an excellent reference guide for the many different NFS export and mount options available. NFS Illustrated by Brent Callaghan; Addison-Wesley Publishing Company Provides comparisons of NFS to other network file systems and shows, in detail, how NFS communication occurs.

Pakistan Computer Bureau

149

Samba is an open source implementation of the Server Message Block (SMB) protocol. It allows the networking of Microsoft Windows, Linux, UNIX, and other operating systems together, enabling access to Windows-based file and printer shares. Samba's use of SMB allows it to appear as a Windows server to Windows clients.

11.1. Introduction to Samba


The third major release of Samba, version 3.0.0, introduced numerous improvements from prior versions, including: The ability to join an Active Directory domain by means of LDAP and Kerberos Built in Unicode support for internationalization Support for Microsoft Windows XP Professional client connections to Samba servers without needing local registry hacking Two new documents developed by the Samba.org team, which include a 400+ page reference manual, and a 300+ page implementation and integration manual.

11.1.1. Samba Features


Samba is a powerful and versatile server application. Even seasoned system administrators must know its abilities and limitations before attempting installation and configuration. What Samba can do: Serve directory trees and printers to Linux, UNIX, and Windows clients Assist in network browsing (with or without NetBIOS) Authenticate Windows domain logins Provide Windows Internet Name Service (WINS) name server resolution Act as a Windows NT-style Primary Domain Controller (PDC) Act as a Backup Domain Controller (BDC) for a Samba-based PDC Act as an Active Directory domain member server

Pakistan Computer Bureau

149

Join a Windows NT/2000/2003 PDC What Samba cannot do: Act as a BDC for a Windows PDC (and vice versa) Act as an Active Directory domain controller

11.2. Samba Daemons and Related Services


The following is a brief introduction to the individual Samba daemons and services.

11.2.1. Samba Daemons


Samba is comprised of three daemons (smbd, nmbd, and winbindd). Two services (smb and windbind) control how the daemons are started, stopped, and other service-related features. Each daemon is listed in detail, as well as which specific service has control over it. smbd. The smbd server daemon provides file sharing and printing services to Windows clients. In addition, it is responsible for user authentication, resource locking, and data sharing through the SMB protocol. The default ports on which the server listens for SMB traffic are TCP ports 139 and 445. The smbd daemon is controlled by the smb service. nmbd. The nmbd server daemon understands and replies to NetBIOS name service requests such as those produced by SMB/CIFS in Windows-based systems. These systems include Windows 95/98/ME, Windows NT, Windows 2000, Windows XP, and LanManager clients. It also participates in the browsing protocols that make up the Windows Network Neighborhood view. The default port that the server listens to for NMB traffic is UDP port 137. The nmbd daemon is controlled by the smb service. winbindd. The winbind service resolves user and group information on a server running Windows NT 2000 or Windows Server 2003. This makes Windows
Pakistan Computer Bureau

150

user / group information understandable by UNIX platforms. This is achieved by using Microsoft RPC calls, Pluggable Authentication Modules (PAM), and the Name Service Switch (NSS). This allows Windows NT domain users to appear and operate as UNIX users on a UNIX machine. Though bundled with the Samba distribution, the winbind service is controlled separately from the smb service. The winbindd daemon is controlled by the winbind service and does not require the smb service to be started in order to operate. Winbindd is also used when Samba is an Active Directory member, and may also be used on a Samba domain controller (to implement nested groups and/or interdomain trust). Because winbind is a client-side service used to connect to Windows NT-based servers, further discussion of winbind is beyond the scope of this manual.

Pakistan Computer Bureau

151

The Time and Date Properties Tool allows the user to change the system date and time, to configure the time zone used by the system, and to setup the Network Time Protocol (NTP) daemon to synchronize the system clock with a time server. You must be running the X Window System and have root privileges to use the tool. There are three ways to start the application: From the desktop, go to Applications (the main menu on the panel) => System Settings => Date & Time From the desktop, right-click on the time in the toolbar and select Adjust Date and Time. Type the command system-config-date, system-config-time, or dateconfig at a shell prompt (for example, in an XTerm or a GNOME terminal).

12.1. Time and Date Properties


As shown in Figure 12.1, Time and Date Properties, the first tabbed window that appears is for configuring the system date and time.

Pakistan Computer Bureau

152

Figure 12.1. Time and Date Properties

To change the date, use the arrows to the left and right of the month to change the month, use the arrows to the left and right of the year to change the year, and click on the day of the week to change the day of the week. To change the time, use the up and down arrow buttons beside the Hour, Minute, and Second in the Time section. Clicking the OK button applies any changes made to the date and time, the NTP
Pakistan Computer Bureau 153

daemon settings, and the time zone settings. It also exits the program.

12.2. Network Time Protocol (NTP) Properties


As shown in Figure 12.2, NTP Properties, the second tabbed window that appears is for configuring NTP.

Figure 12.2. NTP Properties

The Network Time Protocol (NTP) daemon synchronizes the system clock with a remote time server or time source. The application allows you to configure an NTP daemon to synchronize your system clock with a remote server. To enable this feature, select Enable Network Time Protocol. This enables the NTP Servers list and other options. You can choose one of the predefined servers, edit a predefined server by clicking the Edit or add a new server name by clicking Add. Your system does not start synchronizing with the NTP server until you click OK. After clicking OK, the configuration is saved and the NTP daemon is started (or restarted if it is already running). Clicking the OK button applies any changes made to the date and time, the NTP

Pakistan Computer Bureau

154

daemon settings, and the time zone settings. It also exits the program.

12.3. Time Zone Configuration


As shown in Figure 12.3, Timezone Properties, the third tabbed window that appears is for configuring the system time zone. To configure the system time zone, click the Time Zone tab. The time zone can be changed by either using the interactive map or by choosing the desired time zone from the list below the map. To use the map, click on the desired region. The map zooms into the region selected, after which you may choose the city specific to your time zone. A red X appears and the time zone selection changes in the list below the map. Alternatively, you can also use the list below the map. In the same way that the map lets you choose a region before choosing a city, the list of time zones is now a treelist, with cities and countries grouped within their specific continents. Nongeographic time zones have also been added to address needs in the scientific community. Click OK to apply the changes and exit the program.

Pakistan Computer Bureau

155

Figure 12.3. Timezone Properties

If your system clock is set to use UTC, select the System clock uses UTC option. UTC stands for the Universal Time, Coordinated, also known as Greenwich Mean Time (GMT).

Pakistan Computer Bureau

156

While the heart of Red Hat Enterprise Linux is the kernel, for many users, the face of the operating system is the graphical environment provided by the X Window System, also called X. Other windowing environments have existed in the UNIX world, including some that predate the release of the X Window System in June 1984. Nonetheless, X has been the default graphical environment for most UNIX-like operating systems, including Red Hat Enterprise Linux, for many years. The graphical environment for Red Hat Enterprise Linux is supplied by the X.Org Foundation, an open source organization created to manage development and strategy for the X Window System and related technologies. X.Org is a largescale, rapidly developing project with hundreds of developers around the world. It features a wide degree of support for a variety of hardware devices and architectures, and can run on a variety of different operating systems and platforms. This release for Red Hat Enterprise Linux specifically includes the X11R7.1 release of the X Window System. The X Window System uses a client-server architecture. The X server (the Xorg binary) listens for connections from X client applications via a network or local loopback interface. The server communicates with the hardware, such as the video card, monitor, keyboard, and mouse. X client applications exist in the user-space, creating a graphical user interface (GUI) for the user and passing user requests to the X server.

13.1. The X11R7.1 Release


Red Hat Enterprise Linux 5.0.0 now uses the X11R7.1 release as the base X Window System, which includes several video driver, EXA, and platform support enhancements over the previous release, among others. In addition, this release also includes several automatic configuration features for the X server. X11R7.1 is the first release to take specific advantage of the modularisation of the X Window System. This modularisaton, which splits X into logically distinct modules, makes it easier for open source developers to contribute code to the system. Important
Red Hat Enterprise Linux no longer provides the XFree86 server packages. Before upgrading a system to the latest version of Red Hat Enterprise Linux, be sure that the system's video card is compatible with the X11R7.1 release by checking the Red Hat Hardware Compatibility List located online at http://hardware.redhat.com/.

Pakistan Computer Bureau

157

In the X11R7.1 release, all libraries, headers, and binaries now live under /usr/ instead of /usr/X11R6. The /etc/X11/ directory contains configuration files for X client and server applications. This includes configuration files for the X server itself, the xfs font server, the X display managers, and many other base components. The configuration file for the newer Fontconfig-based font architecture is still /etc/fonts/fonts.conf. For more on configuring and adding fonts, refer to Section 4, Fonts. Because the X server performs advanced tasks on a wide array of hardware, it requires detailed information about the hardware it works on. The X server automatically detects some of this information; other details must be configured. The installation program installs and configures X automatically, unless the X11R7.1 release packages are not selected for installation. However, if there are any changes to the monitor, video card or other devices managed by the X server, X must be reconfigured. The best way to do this is to use the X Configuration Tool (system-config-display), particularly for devices that are not detected manually. In Red Hat Enterprise Linux's default graphical environment, the X Configuration Tool is available at System (on the panel) => Administration => Display. Changes made with the X Configuration Tool take effect after logging out and logging back in. For more information about X Configuration Tool, refer to X Window System Configuration. In some situations, reconfiguring the X server may require manually editing its configuration file, /etc/X11/xorg.conf. For information about the structure of this file, refer to Section 3, X Server Configuration Files.

13.2. Desktop Environments and Window Managers


Once an X server is running, X client applications can connect to it and create a GUI for the user. A range of GUIs are possible with Red Hat Enterprise Linux, from the rudimentary Tab Window Manager to the highly developed and interactive GNOME desktop environment that most Red Hat Enterprise Linux users are familiar with. To create the latter, more comprehensive GUI, two main classes of X client application must connect to the X server: a desktop environment and a window manager.
Pakistan Computer Bureau 158

13.2.1. Desktop Environments


A desktop environment integrates various X clients to create a common graphical user environment and development platform. Desktop environments have advanced features allowing X clients and other running processes to communicate with one another, while also allowing all applications written to work in that environment to perform advanced tasks, such as drag and drop operations. Red Hat Enterprise Linux provides two desktop environments: GNOME The default desktop environment for Red Hat Enterprise Linux based on the GTK+ 2 graphical toolkit. KDE An alternative desktop environment based on the Qt 3 graphical toolkit. Both GNOME and KDE have advanced productivity applications, such as word processors, spreadsheets, and Web browsers; both also provide tools to customize the look and feel of the GUI. Additionally, if both the GTK+ 2 and the Qt libraries are present, KDE applications can run in GNOME and vice-versa.

13.2.2. Window Managers


Window managers are X client programs which are either part of a desktop environment or, in some cases, stand-alone. Their primary purpose is to control the way graphical windows are positioned, resized, or moved. Window managers also control title bars, window focus behavior, and user-specified key and mouse button bindings. Four window managers are included with Red Hat Enterprise Linux: kwin The KWin window manager is the default window manager for KDE. It is an efficient window manager which supports custom themes. metacity The Metacity window manager is the default window manager for GNOME. It is a simple and efficient window manager which also supports custom themes. To run this window manager, you need to install the metacity package.
Pakistan Computer Bureau 159

Mwm The Motif Window Manager (mwm) is a basic, stand-alone window manager. Since it is designed to be a stand-alone window manager, it should not be used in conjunction with GNOME or KDE. To run this window manager, you need to install the openmotif package. Twm The minimalist Tab Window Manager (twm, which provides the most basic tool set of any of the window managers, can be used either as a stand-alone or with a desktop environment. It is installed as part of the X11R7.1 release. To run any of the aforementioned window managers, you will first need to boot into Runlevel 3. For instructions on how to do this, refer to Section 13.2.2.1, Runlevels. Once you are logged in to Runlevel 3, you will be presented with a terminal prompt, not a graphical environment. To start a window manager, type xinit e <path-to-window-manager> at the prompt. <path-to-window-manager> is the location of the window manager binary file. The binary file can be located by typing which windowmanager-name, where window-manager-name is the name of the window manager you want to run. For example:
user@host# which twm/usr/bin/twm user@host# xinit -e /usr/bin/twm

The first command above returns the absolute path to the twm window manager, the second command starts twm. To exit a window manager, close the last window or press Ctrl-AltBackspace. Once you have exited the window manager, you can log back into Runlevel 5 by typing startx at the prompt.

Pakistan Computer Bureau

160

13.2.2.1. Runlevels
Before you can configure access to services, you must understand Linux runlevels. A runlevel is a state, or mode, that is defined by the services listed in the directory /etc/rc.d/rc<x>.d, where <x> is the number of the runlevel. The following runlevels exist: 0 Halt 1 Single-user mode 2 Not used (user-definable) 3 Full multi-user mode 4 Not used (user-definable) 5 Full multi-user mode (with an X-based login screen) 6 Reboot If you use a text login screen, you are operating in runlevel 3. If you use a graphical login screen, you are operating in runlevel 5. The default runlevel can be changed by modifying the /etc/inittab file, which contains a line near the top of the file similar to the following:
id:5:initdefault:

Change the number in this line to the desired runlevel. The change does not take effect until you reboot the system.

13.3. X Server Configuration Files


The X server is a single binary executable (/usr/bin/Xorg). Associated configuration files are stored in the /etc/X11/ directory (as is a symbolic link X which points to /usr/bin/Xorg). The configuration file for the X server is /etc/X11/xorg.conf. The directory /usr/lib/xorg/modules/ contains X server modules that can be loaded dynamically at runtime. By default, only some modules in /usr/lib/xorg/modules/ are automatically loaded by the X server.

Pakistan Computer Bureau

161

To load optional modules, they must be specified in the X server configuration file, /etc/X11/xorg.conf. For more information about loading modules, refer to Section 3.1.5, Module. When Red Hat Enterprise Linux 5.0.0 is installed, the configuration files for X are created using information gathered about the system hardware during the installation process.

13.3.1. xorg.conf
While there is rarely a need to manually edit the /etc/X11/xorg.conf file, it is useful to understand the various sections and optional parameters available, especially when troubleshooting.

13.3.1.1. The Structure


The /etc/X11/xorg.conf file is comprised of many different sections which address specific aspects of the system hardware. Each section begins with a Section "<section-name>" line (where <section-name> is the title for the section) and ends with an EndSection line. Each section contains lines that include option names and one or more option values. These are sometimes enclosed in double quotes ("). Lines beginning with a hash mark (#) are not read by the X server and are used for human-readable comments. Some options within the /etc/X11/xorg.conf file accept a boolean switch which turns the feature on or off. Acceptable boolean values are: 1, on, true, or yes Turns the option on. 0, off, false, or no Turns the option off. The following are some of the more important sections in the order in which they appear in a typical /etc/X11/xorg.conf file. More detailed information about the X server configuration file can be found in the xorg.conf man page.

Pakistan Computer Bureau

162

13.3.1.2. ServerFlags
The optional ServerFlags section contains miscellaneous global X server settings. Any settings in this section may be overridden by options placed in the ServerLayout section (refer to Section 3.1.3, ServerLayout for details). Each entry within the ServerFlags section is on its own line and begins with the term Option followed by an option enclosed in double quotation marks ("). The following is a sample ServerFlags section:
Section "ServerFlags" Option "DontZap" "true" EndSection

The following lists some of the most useful options: "DontZap" "<boolean>" When the value of <boolean> is set to true, this setting prevents the use of the Ctrl-Alt-Backspace key combination to immediately terminate the X server. "DontZoom" "<boolean>" When the value of <boolean> is set to true, this setting prevents cycling through configured video resolutions using the Ctrl-Alt-Keypad-Plus and Ctrl-Alt-Keypad-Minus key combinations.

13.3.1.3. ServerLayout
The ServerLayout section binds together the input and output devices controlled by the X server. At a minimum, this section must specify one output device and one input device. By default, a monitor (output device) and keyboard (input device) are specified. The following example illustrates a typical ServerLayout section:
Section "ServerLayout" Identifier "Default Layout" Screen 0 "Screen0" 0 0 InputDevice "Mouse0" "CorePointer" InputDevice "Keyboard0" "CoreKeyboard" EndSection

The following entries are commonly used in the ServerLayout section:

Pakistan Computer Bureau

163

Identifier Specifies a unique name for this ServerLayout section. Screen Specifies the name of a Screen section to be used with the X server. More than one Screen option may be present. The following is an example of a typical Screen entry:
Screen 0 "Screen0" 0 0

The first number in this example Screen entry (0) indicates that the first monitor connector or head on the video card uses the configuration specified in the Screen section with the identifier "Screen0". An example of a Screen section with the identifier "Screen0" can be found in Section 13.3.1.9, Screen. If the video card has more than one head, another Screen entry with a different number and a different Screen section identifier is necessary .

The numbers to the right of "Screen0" give the absolute X and Y coordinates for the upper-left corner of the screen (0 0 by default). InputDevice Specifies the name of an Input Device section to be used with the X server. It is advisable that there be at least two InputDevice entries: one for the default mouse and one for the default keyboard. The options CorePointer and CoreKeyboard indicate that these are the primary mouse and keyboard. Option "<option-name>" An optional entry which specifies extra parameters for the section. Any options listed here override those listed in the ServerFlags section. Replace <option-name> with a valid option listed for this section in the xorg.conf main page. It is possible to put more than one ServerLayout section in the /etc/X11/xorg.conf file. By default, the server only reads the first one it encounters, however.

Pakistan Computer Bureau

164

If there is an alternative ServerLayout section, it can be specified as a command line argument when starting an X session.

13.3.1.4. Files
The Files section sets paths for services vital to the X server, such as the font path. This is an optional section, these paths are normally detected automatically. This section may be used to override any automatically detected defaults. The following example illustrates a typical Files section:
Section "Files" RgbPath "/usr/share/X11/rgb.txt" FontPath "unix/:7100" EndSection

The following entries are commonly used in the Files section: RgbPath Specifies the location of the RGB color database. This database defines all valid color names in X and ties them to specific RGB values.

FontPath Specifies where the X server must connect to obtain fonts from the xfs font server. By default, the FontPath is unix/:7100. This tells the X server to obtain font information using UNIX-domain sockets for inter-process communication (IPC) on port 7100. Refer to Section 4, Fonts for more information concerning X and fonts. ModulePath An optional parameter which specifies alternate directories which store X server modules.

Pakistan Computer Bureau

165

13.3.1.5. Module
By default, the X server automatically loads the following modules from the /usr/lib/xorg/modules/ directory: extmod dbe glx freetype type1 record dri The default directory for loading these modules can be changed by specifying a different directory with the optional ModulePath parameter in the Files section. Refer to Section 3.1.4, Files for more information on this section. Adding a Module section to /etc/X11/xorg.conf instructs the X server to load the modules listed in this section instead of the default modules. For example, the following typical Module section: Section "Module" Load "fbdevhw" EndSection instructs the X server to load the fbdevhw instead of the default modules. As such, if you add a Module section to /etc/X11/xorg.conf, you will need to specify any default modules you want to load as well as any extra modules.

Pakistan Computer Bureau

166

13.3.1.6. InputDevice
Each InputDevice section configures one input device for the X server. Systems typically have at least one InputDevice section for the keyboard. It is perfectly normal to have no entry for a mouse, as most mouse settings are automatically detected. The following example illustrates a typical InputDevice section for a keyboard:
Section "InputDevice" Identifier "Keyboard0" Driver "kbd" Option "XkbModel" "pc105" Option "XkbLayout" "us" EndSection

The following entries are commonly used in the InputDevice section: Identifier Specifies a unique name for this InputDevice section. This is a required entry. Driver Specifies the name of the device driver X must load for the device. Option Specifies necessary options pertaining to the device. A mouse may also be specified to override any autodetected defaults for the device. The following options are typically included when adding a mouse in the xorg.conf: Protocol Specifies the protocol used by the mouse, such as IMPS/2. Device Specifies the location of the physical device. Emulate3Buttons Specifies whether to allow a two-button mouse to act like a three-button mouse when both mouse buttons are pressed simultaneously. Consult the xorg.conf man page for a list of valid options for this section.

Pakistan Computer Bureau

167

13.3.1.7. Monitor
Each Monitor section configures one type of monitor used by the system. This is an optional entry as well, as most monitors are now automatically detected. The easiest way to configure a monitor is to configure X during the installation process or by using the X Configuration Tool. For more information about using the X Configuration Tool, refer to X Window System Configuration. This example illustrates a typical Monitor section for a monitor: Section "Monitor" Identifier "Monitor0" VendorName "Monitor Vendor" ModelName "DDC Probed Monitor - ViewSonic G773-2" DisplaySize 320 240 HorizSync 30.0 - 70.0 VertRefresh 50.0 - 180.0 EndSection Warning
Be careful when manually editing values in the Monitor section of /etc/X11/xorg.conf. Inappropriate values can damage or destroy a monitor. Consult the monitor's documentation for a listing of safe operating parameters.

The following are commonly entries used in the Monitor section: Identifier Specifies a unique name for this Monitor section. This is a required entry. VendorName An optional parameter which specifies the vendor of the monitor. ModelName An optional parameter which specifies the monitor's model name. DisplaySize An optional parameter which specifies, in millimeters, the physical size of the monitor's picture area. HorizSync Specifies the range of horizontal sync frequencies compatible with the monitor in kHz. These values help the X server determine the validity of built-in or specified Modeline entries for the monitor.

Pakistan Computer Bureau

168

VertRefresh Specifies the range of vertical refresh frequencies supported by the monitor, in kHz. These values help the X server determine the validity of built in or specified Modeline entries for the monitor. Modeline An optional parameter which specifies additional video modes for the monitor at particular resolutions, with certain horizontal sync and vertical refresh resolutions. Refer to the xorg.conf man page for a more detailed explanation of Modeline entries. Option "<option-name>" An optional entry which specifies extra parameters for the section. Replace <option-name> with a valid option listed for this section in the xorg.conf man page.

13.3.1.8. Device
Each Device section configures one video card on the system. While one Device section is the minimum, additional instances may occur for each video card installed on the machine. The best way to configure a video card is to configure X during the installation process or by using the X Configuration Tool. For more about using the X Configuration Tool, refer to X Window System Configuration. The following example illustrates a typical Device section for a video card: Section "Device" Identifier "Videocard0" Driver "mga" VendorName "Videocard vendor" BoardName "Matrox Millennium G200" VideoRam 8192 Option "dpms" EndSection The following entries are commonly used in the Device section: Identifier Specifies a unique name for this Device section. This is a required entry. Driver Specifies which driver the X server must load to utilize the video card. A list of drivers can be found in

Pakistan Computer Bureau

169

/usr/share/hwdata/videodrivers, which is installed with the hwdata package. VendorName An optional parameter which specifies the vendor of the video card. BoardName An optional parameter which specifies the name of the video card. VideoRam An optional parameter which specifies the amount of RAM available on the video card in kilobytes. This setting is only necessary for video cards the X server cannot probe to detect the amount of video RAM. BusID An entry which specifies the bus location of the video card. On systems with only one video card a BusID entry is optional and may not even be present in the default /etc/X11/xorg.conf file. On systems with more than one video card, however, a BusID entry must be present. Screen An optional entry which specifies which monitor connector or head on the video card the Device section configures. This option is only useful for video cards with multiple heads. If multiple monitors are connected to different heads on the same video card, separate Device sections must exist and each of these sections must have a different Screen value. Values for the Screen entry must be an integer. The first head on the video card has a value of 0. The value for each additional head increments this value by one. Option "<option-name>" An optional entry which specifies extra parameters for the section. Replace <option-name> with a valid option listed for this section in the xorg.conf man page. One of the more common options is "dpms" (for Display Power Management Signaling, a VESA standard), which activates the Service Star energy compliance setting for the monitor.

Pakistan Computer Bureau

170

13.3.1.9. Screen
Each Screen section binds one video card (or video card head) to one monitor by referencing the Device section and the Monitor section for each. While one Screen section is the minimum, additional instances may occur for each video card and monitor combination present on the machine. The following example illustrates a typical Screen section:
Section "Screen" Identifier "Screen0" Device "Videocard0" Monitor "Monitor0" DefaultDepth 16 SubSection "Display" Depth 24 Modes "1280x1024" "1280x960" "1152x864" "1024x768" "800x600" "640x480" EndSubSection SubSection "Display" Depth 16 Modes "1152x864" "1024x768" "800x600" "640x480" EndSubSection EndSection

The following entries are commonly used in the Screen section: Identifier Specifies a unique name for this Screen section. This is a required entry. Device Specifies the unique name of a Device section. This is a required entry. Monitor Specifies the unique name of a Monitor section. This is only required if a specific Monitor section is defined in the xorg.conf file. Normally, monitors are automatically detected. DefaultDepth Specifies the default color depth in bits. In the previous example, 16 (which provides thousands of colors) is the default. Only one DefaultDepth is permitted, although this can be overridden with the Xorg command line option -depth <n>,where <n> is any additional depth specified. SubSection "Display" Specifies the screen modes available at a particular color depth. The Screen section can have multiple Display subsections, which are entirely optional since screen modes are automatically detected. This subsection is normally used to override autodetected modes. Option "<option-name>" An optional entry which specifies extra parameters for the section.
Pakistan Computer Bureau 171

Replace <option-name> with a valid option listed for this section in the xorg.conf man page.

13.3.1.10. DRI
The optional DRI section specifies parameters for the Direct Rendering Infrastructure (DRI). DRI is an interface which allows 3D software applications to take advantage of 3D hardware acceleration capabilities built into most modern video hardware. In addition, DRI can improve 2D performance via hardware acceleration, if supported by the video card driver. This section rarely appears, as the DRI Group and Mode are automatically initialized to default values. If a different Group or Mode is desired, then adding this section to the xorg.conf file will override those defaults. The following example illustrates a typical DRI section: Section "DRI" Group 0 Mode 0666 EndSection Since different video cards use DRI in different ways, do not add to this section without first referring to http://dri.sourceforge.net/.

13.4. Fonts
Red Hat Enterprise Linux uses two subsystems to manage and display fonts under X: Fontconfig and xfs. The newer Fontconfig font subsystem simplifies font management and provides advanced display features, such as anti-aliasing. This system is used automatically for applications programmed using the Qt 3 or GTK+ 2 graphical toolkit. For compatibility, Red Hat Enterprise Linux includes the original font subsystem, called the core X font subsystem. This system, which is over 15 years old, is based around the X Font Server (xfs). This section discusses how to configure fonts for X using both systems.

Pakistan Computer Bureau

172

13.4.1. Fontconfig
The Fontconfig font subsystem allows applications to directly access fonts on the system and use Xft or other rendering mechanisms to render Fontconfig fonts with advanced anti-aliasing. Graphical applications can use the Xft library with Fontconfig to draw text to the screen. Over time, the Fontconfig/Xft font subsystem replaces the core X font subsystem. Important
The Fontconfig font subsystem does not yet work for OpenOffice.org, which uses its own font rendering technology.

It is important to note that Fontconfig uses the etc/fonts/fonts.conf configuration file, which should not be edited by hand. Tip
Due to the transition to the new font system, GTK+ 1.2 applications are not affected by any changes made via the Font Preferences dialog (accessed by selecting System (on the panel) => Preferences => Fonts). For these applications, a font can be configured by adding the following lines to the file .gtkrc.mine: style "user-font" { fontset = "<font-specification>" } widget_class "*" style "user-font"

Replace <font-specification> with a font specification in the style used by traditional X applications, such as -adobe-helvetica-medium-rnormal--*-120-*-*-*-*-*-*. A full list of core fonts can be obtained by running xlsfonts or created interactively using the xfontsel command.

Pakistan Computer Bureau

173

13.4.1.1. Adding Fonts to Fontconfig


Adding new fonts to the Fontconfig subsystem is a straightforward process. 1. To add fonts system-wide, copy the new fonts into the /usr/share/fonts/ directory. It is a good idea to create a new subdirectory, such as local/ or similar, to help distinguish between userinstalled and default fonts. To add fonts for an individual user, copy the new fonts into the .fonts/ directory in the user's home directory. 2. Use the fc-cache command to update the font information cache, as in the following example: fc-cache <path-to-font-directory> In this command, replace <path-to-font-directory> with the directory containing the new fonts (either /usr/share/fonts/local/ or /home/<user>/.fonts/).
Tip Individual users may also install fonts graphically, by typing fonts:/// into theNautilus address bar, and dragging the new font files there. Important If the font file name ends with a .gz extension, it is compressed and cannot be used until uncompressed. To do this, use the gunzip command or double-click the file and drag the font to a directory in Nautilus.

13.4.2. Core X Font System


For compatibility, Red Hat Enterprise Linux provides the core X font subsystem, which uses the X Font Server (xfs) to provide fonts to X client applications. The X server looks for a font server specified in the FontPath directive within the Files section of the /etc/X11/xorg.conf configuration file. Refer to Section 3.1.4, Files for more information about the FontPath entry.

Pakistan Computer Bureau

174

The X server connects to the xfs server on a specified port to acquire font information. For this reason, the xfs service must be running for X to start.

13.4.2.1. xfs Configuration


The /etc/rc.d/init.d/xfs script starts the xfs server. Several options can be configured within its configuration file, /etc/X11/fs/config. The following lists common options: alternate-servers Specifies a list of alternate font servers to be used if this font server is not available. A comma must separate each font server in a list. catalogue Specifies an ordered list of font paths to use. A comma must separate each font path in a list. Use the string :unscaled immediately after the font path to make the unscaled fonts in that path load first. Then specify the entire path again, so that other scaled fonts are also loaded. client-limit Specifies the maximum number of clients the font server services. The default is 10. clone-self Allows the font server to clone a new version of itself when the clientlimit is hit. By default, this option is on. default-point-size Specifies the default point size for any font that does not specify this value. The value for this option is set in decipoints. The default of 120 corresponds to a 12 point font. default-resolutions Specifies a list of resolutions supported by the X server. Each resolution in the list must be separated by a comma.

deferglyphs Specifies whether to defer loading glyphs (the graphic used to visually

Pakistan Computer Bureau

175

represent a font). To disable this feature use none, to enable this feature for all fonts use all, or to turn this feature on only for 16-bit fonts use 16. error-file Specifies the path and file name of a location where xfs errors are logged. no-listen Prevents xfs from listening to particular protocols. By default, this option is set to tcp to prevent xfs from listening on TCP ports for security reasons. Tip
If xfs is used to serve fonts over the network, remove this line.

port Specifies the TCP port that xfs listens on if no-isten does not exist or is commented out. use-syslog Specifies whether to use the system error log.

13.4.2.2. Adding Fonts to xfs


To add fonts to the core X font subsystem (xfs), follow these steps: 1. If it does not already exist, create a directory called /usr/share/fonts/local/ using the following command as root: mkdir /usr/share/fonts/local/ If creating the /usr/share/fonts/local/ directory is necessary, it must be added to the xfs path using the following command as root: chkfontpath --add /usr/share/fonts/local/ 2. Copy the new font file into the /usr/share/fonts/local/ directory 3. Update the font information by issuing the following command as root: ttmkfdir -d /usr/share/fonts/local/ -o /usr/share/fonts/local/fonts.scale 4. Reload the xfs font server configuration file by issuing the following command as root:

Pakistan Computer Bureau

176

service xfs reload

13.5. Runlevels and X


In most cases, the Red Hat Enterprise Linux installer configures a machine to boot into a graphical login environment, known as Runlevel 5. It is possible, however, to boot into a text-only multi-user mode called Runlevel 3 and begin an X session from there. For more information about runlevels, refer to Section 2.2.1, Runlevels. The following subsections review how X starts up in both runlevel 3 and runlevel

13.5.1. Runlevel 3
When in runlevel 3, the best way to start an X session is to log in and type startx. The startx command is a front-end to the xinit command, which launches the X server (Xorg) and connects X client applications to it. Because the user is already logged into the system at runlevel 3, startx does not launch a display manager or authenticate users. Refer to Section 5.2, Runlevel 5 for more information about display managers. When the startx command is executed, it searches for the .xinitrc file in the user's home directory to define the desktop environment and possibly other X client applications to run. If no .xinitrc file is present, it uses the system default /etc/X11/xinit/xinitrc file instead. The default xinitrc script then searches for user-defined files and default system files, including .Xresources, .Xmodmap, and .Xkbmap in the user's home directory, and Xresources, Xmodmap, and Xkbmap in the /etc/X11/ directory. The Xmodmap and Xkbmap files, if they exist, are used by the xmodmap utility to configure the keyboard. The Xresources file is read to assign specific preference values to applications. After setting these options, the xinitrc script executes all scripts located in the /etc/X11/xinit/xinitrc.d/ directory. One important script in this directory is xinput.sh, which configures settings such as the default language.

Pakistan Computer Bureau

177

Next, the xinitrc script attempts to execute .Xclients in the user's home directory and turns to /etc/X11/xinit/Xclients if it cannot be found. The purpose of the Xclients file is to start the desktop environment or, possibly, just a basic window manager. The .Xclients script in the user's home directory starts the user-specified desktop environment in the .Xclients-default file. If .Xclients does not exist in the user's home directory, the standard /etc/X11/xinit/Xclients script attempts to start another desktop environment, trying GNOME first and then KDE followed by twm. When in runlevel 3, the user is returned to a text mode user session after ending an X session.

13.5.2. Runlevel 5
When the system boots into runlevel 5, a special X client application called a display manager is launched. A user must authenticate using the display manager before any desktop environment or window managers are launched. Depending on the desktop environments installed on the system, three different display managers are available to handle user authentication. GNOME The default display manager for Red Hat Enterprise Linux, GNOME allows the user to configure language settings, shutdown, restart or log in to the system. KDE KDE's display manager which allows the user to shutdown, restart or log in to the system. xdm A very basic display manager which only lets the user log in to the system. When booting into runlevel 5, the prefdm script determines the preferred display manager by referencing the /etc/sysconfig/desktop file. A list of options for this file is available in this file: /usr/share/doc/initscripts-<versionnumber>/sysconfig.txt where <version-number> is the version number of the initscripts package.
Pakistan Computer Bureau 178

Each of the display managers reference the /etc/X11/xdm/Xsetup_0 file to set up the login screen. Once the user logs into the system, the /etc/X11/xdm/GiveConsole script runs to assign ownership of the console to the user. Then, the /etc/X11/xdm/Xsession script runs to accomplish many of the tasks normally performed by the xinitrc script when starting X from runlevel 3, including setting system and user resources, as well as running the scripts in the /etc/X11/xinit/xinitrc.d/ directory. Users can specify which desktop environment they want to utilize when they authenticate using the GNOME or KDE display managers by selecting it from the Sessions menu item (accessed by selecting System (on the panel) => Preferences => More Preferences => Sessions). If the desktop environment is not specified in the display manager, the /etc/X11/xdm/Xsession script checks the .xsession and .Xclients files in the user's home directory to decide which desktop environment to load. As a last resort, the /etc/X11/xinit/Xclients file is used to select a desktop environment or window manager to use in the same way as runlevel 3. When the user finishes an X session on the default display (:0) and logs out, the /etc/X11/xdm/TakeConsole script runs and reassigns ownership of the console to the root user. The original display manager, which continues running after the user logged in, takes control by spawning a new display manager. This restarts the X server, displays a new login window, and starts the entire process over again. The user is returned to the display manager after logging out of X from runlevel 5. For more information on how display managers control user authentication, refer to the /usr/share/doc/gdm-<version-number>/README (where <version-number> is the version number for the gdm package installed) and the xdm man page.

Pakistan Computer Bureau

179

During installation, the system's monitor, video card, and display settings are configured. To change any of these settings after installation, use the X Configuration Tool. To start the X Configuration Tool, go to System (on the panel) => Administration => Display, or type the command system-configdisplay at a shell prompt (for example, in an XTerm or GNOME terminal). If the X Window System is not running, a small version of X is started to run the program. After changing any of the settings, log out of the graphical desktop and log back in to enable the changes.

14.1. Display Settings


The Settings tab allows users to change the resolution and color depth. The display of a monitor consists of tiny dots called pixels. The number of pixels displayed at one time is called the resolution. For example, the resolution 1024x768 means that 1024 horizontal pixels and 768 vertical pixels are used. The higher the resolution values, the more images the monitor can display at one time. The color depth of the display determines how many possible colors are displayed. A higher color depth means more contrast between colors.

Pakistan Computer Bureau

180

Figure 14.1. Display Settings

14.2. Display Hardware Settings


When the X Configuration Tool is started, it probes the monitor and video card. If the hardware is probed properly, the information for it is shown on the Hardware tab.

Pakistan Computer Bureau

181

Figure 14.2. Display Hardware Settings

To change the monitor type or any of its settings, click the corresponding Configure button. To change the video card type or any of its settings, click the Configure button beside its settings.

14.3. Dual Head Display Settings


If multiple video cards are installed on the system, dual head monitor support is available and is configured via the Dual head tab.

Pakistan Computer Bureau

182

Figure 14.3. Dual Head Display Settings

To enable use of Dual head, check the Use dual head checkbox. To configure the second monitor type, click the corresponding Configure button. You can also configure the other Dual head settings by using the corresponding drop-down list. For the Desktop layout option, selecting Spanning Desktops allows both monitors to use an enlarged usable workspace. Selecting Individual Desktops shares the mouse and keyboard among the displays, but restricts windows to a single display.

Pakistan Computer Bureau

183

The control of users and groups is a core element of Red Hat Enterprise Linux system administration. Users can be either people (meaning accounts tied to physical users) or accounts which exist for specific applications to use. Groups are logical expressions of organization, tying users together for a common purpose. Users within a group can read, write, or execute files owned by that group. Each user and group has a unique numerical identification number called a userid (UID) and a groupid (GID), respectively. A user who creates a file is also the owner and group owner of that file. The file is assigned separate read, write, and execute permissions for the owner, the group, and everyone else. The file owner can be changed only by the root user, and access permissions can be changed by both the root user and file owner. Red Hat Enterprise Linux also supports access control lists (ACLs) for files and directories which allow permissions for specific users outside of the owner to be set.

15.1. User and Group Configuration


The User Manager allows you to view, modify, add, and delete local users and groups. To use the User Manager, you must be running the X Window System, have root privileges and have the system-config-users RPM package installed. To start the User Manager from the desktop, go to System (on the panel) => Administration => Users & Groups. You can also type the command system-config-users at a shell prompt (for example, in an XT ermora Gnome terminal).

Pakistan Computer Bureau

184

Figure 15.1. User Manager

To view a list of local users on the system, click the Users tab. To view a list of local groups on the system, click the Groups tab. To find a specific user or group, type the first few letters of the name in the Search filter field. Press Enter or click the Apply filter button. The filtered list is displayed. To sort the users or groups, click on the column name. To view a list of local users on the system, click the Users tab. To view a list of local groups on the system, click the Groups tab. To find a specific user or group, type the first few letters of the name in the Search filter field. Press Enter or click the Apply filter button. The filtered list is displayed. To sort the click on the column name, the users or groups are sorted according to the value of that column. Red Hat Enterprise Linux reserves user IDs below 500 for system users. By default, User Manager does not display system users. To view all users, including the system users, go to Edit => Preferences and uncheck
Pakistan Computer Bureau 185

Hide system users and groups from the dialog box.

15.1.1. Adding a New User


To add a new user, click the Add User button. A window as shown in Figure 15.2, New User appears. Type the username and full name for the new user in the appropriate fields. Type the user's password in the Password and Confirm Password fields. The password must be at least six characters. Tip
It is advisable to use a much longer password, as this makes it more difficult for an intruder to guess it and access the account without permission. It is also recommended that the password not be based on a dictionary term; use a combination of letters, numbers and special characters.

Select a login shell. If you are not sure which shell to select, accept the default value of /bin/bash. The default home directory is /home/<username>/. You can change the home directory that is created for the user, or you can choose not to create the home directory by unselecting Create home directory. If you select to create the home directory, default configuration files are copied from the /etc/skel/ directory into the new home directory. Red Hat Enterprise Linux uses a user private group (UPG) scheme. The UPG scheme does not add or change anything in the standard UNIX way of handling groups; it offers a new convention. Whenever you create a new user, by default, a unique group with the same name as the user is created. If you do not want to create this group, unselect Create a private group for the user. To specify a user ID for the user, select Specify user ID manually. If the option is not selected, the next available user ID above 500 is assigned to the new user. Because Red Hat Enterprise Linux reserves user IDs below 500 for system users, it is not advisable to manually assign user IDs 1-499. Click OK to create the user.

Pakistan Computer Bureau

186

To configure more advanced user properties, such as password expiration, modify the user's properties after adding the user.

Pakistan Computer Bureau

187

15.1.2. Modifying User Properties


To view the properties of an existing user, click on the Users tab, select the user from the user list, and click Properties from the menu (or choose File => Properties from the pulldown menu).

Figure 15.3. User Properties

The User Properties window is divided into multiple tabbed pages:

User Data

Shows the basic user information configured when you

added the user. Use this tab to change the user's full name, password, home directory, or login shell.

Account Info

Select Enable account expiration if you

want the account to expire on a certain date. Enter the date in the provided fields. Select Local password is locked to lock the

Pakistan Computer Bureau

188

user account and prevent the user from logging into the system. Password Info Displays the date that the user's password last changed. To force the user to change passwords after a certain number of days, select Enable password expiration and enter a desired value in the Days

before change required: field. The number of days before the user's password expires, the number of days before the user is warned to change passwords, and days before the account becomes inactive can also be changed.

Groups Allows you to view and configure the Primary Group of the

user. As well as other groups that you want the user to be a member of it.

15.1.3. Adding a New Group


To add a new user group, click the Add Group button. Type the name of the new group to create. To specify a group ID for the new group, select Specify group ID manually and select the GID. Note that Red Hat Enterprise Linux also reserves group IDs lower than 500 for system groups.

Figure 15.4. New Group

Click OK to create the group. The new group appears in the group list.

Pakistan Computer Bureau

189

15.1.4. Modifying Group Properties


To view the properties of an existing group, select the group from the group list and click Properties from the menu (or choose File => Properties from the pulldown menu.

Figure 15.5. Group Properties

The Group Users tab displays which users are members of the group. Use this tab to add or remove users from the group. Click OK to save your changes.

15.2. User and Group Management Tools


Managing users and groups can be a tedious task; this is why Red Hat Enterprise Linux provides tools and conventions to make them easier to manage. The easiest way to manage users and groups is through the graphical application, User Manager (system-config-users). For more information on User Manager.

Pakistan Computer Bureau

190

The following command line tools can also be used to manage users and groups:

useradd, usermod, and userdel Industry-standard methods of adding, deleting and modifying user accounts

groupadd, groupmod, and groupdel Industry-standard methods of adding, deleting, and modifying user groups

gpasswd Industry-standard method of administering the /etc/group file


pwck, grpck Tools used for the verification of the password, group, and associated shadow files

pwconv, pwunconv Tools used for the conversion of passwords to shadow passwords and back to standard passwords

15.2.1. Command Line Configuration


If you prefer command line tools or do not have the X Window System installed, use this section to configure users and groups.

15.2.2. Adding a User


To add a user to the system: 1. Issue the useradd command to create a locked user account: useradd <username> 2. Unlock the account by issuing the passwd command to assign a password and set password aging guidelines: passwd <username>

Pakistan Computer Bureau

191

15.2.3. Adding a Group


To add a group to the system, use the command groupadd: groupadd <group-name>

Option
-g<gid>

Description
Group ID for the group, which must be unique and greater than Create a system group with a GID less than 500 When used with -g<gid> and <gid> already exists, groupaddwill choose another unique <gid> for the
Table 15.2. group add Command Line Options

-r -f

15.2.4. Password Aging


For security reasons, it is advisable to require users to change their passwords periodically. This can be done when adding or editing a user on the Password Info tab of the User Manager. To configure password expiration for a user from a shell prompt, use the chage command.

Important Shadow passwords must be enabled to use the chage command.

Pakistan Computer Bureau

192

Option

Description

-m<days>

Specifies the minimum number of days between which the user must change passwords. If the value is 0, the password does not expire. Specifies the maximum number of days for which th password is valid. When the number of days specified by this option plus the number of days specified with the -d option is less than the current day, the user must chang Specifies the number of days since January 1, 1970 the password was changed Specifies the number of inactive days after the password expiration before locking the account. If the value is 0, the account is not locked after the password expires.

-M<days>

-d<days> -I<days>

-E<date>

Specifies the date on which the account is locked, in the format YYYY-MM-DD. Instead of the date, the number of days since January 1, 1970 can also be used. Specifies the number of days before the password expiration date to warn the user.
Table 15.3 chage Command Line Options

-W<days>

Tip
If the chage command is followed directly by a username (with no options), it displays the current password aging values and allows them to be changed.

You can configure a password to expire the first time a user logs in. This forces users to change passwords the first time they log in.

Pakistan Computer Bureau

193

Note
This process will not work if the user logs in using the SSH protocol.
1.

Lock the user password If the user does not exist, use the useradd command to create the user account, but do not give it a password so that it remains locked. If the password is already enabled, lock it with the command:

usermod -L username
2. Force immediate password expiration command: Type

the following

chage -d 0 username This command sets the value for the date the password was last changed to the epoch (January 1, 1970). This value forces immediate password expiration no matter what password aging policy, if any, is in place.
3.

Unlock the account There are two common approaches to this step. The administrator can assign an initial password or assign a null password.

Warning
Do not use the passwd command to set the password as it disables the immediate password expiration just configured.

To assign an initial password, use the following steps:

Start the command line Python interpreter with the python command. It displays the following:

4.1.1-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>

At the prompt, type the following commands. Replace <password> with

the password to encrypt and <salt> with a random combination of at least

Pakistan Computer Bureau

194

2 of the following: any alphanumeric character, the slash (/) character or a dot (.): import crypt; print crypt.crypt("<password>","<salt>") The output is the encrypted password, similar to '12CsGd8FRcMSM'.

Press Ctrl-D to exit the Python interpreter. At the shell, enter the following command (replacing <encrypted-

password> with the encrypted output of the Python interpreter): usermod -p "<encrypted-password>" <username>

Alternatively, you can assign a null password instead of an initial password. To do this, use the following command:

usermod -p "" username Caution


Using a null password, while convenient, is a highly unsecure practice, as any third party can log in first an access the system using the unsecure username. Always make sure that the user is ready to log in before unlocking an account with a null password.

In either case, upon initial log in, the user is prompted for a new password.

Pakistan Computer Bureau

195

15.2.5. Explaining the Process


The following steps illustrate what happens if the command useradd juan is issued on a system that has shadow passwords enabled:
1.

A new line for juan is created in /etc/passwd. The line has the following characteristics:

It begins with the username juan. There is an x for the password field indicating that the system is using shadow passwords.

A UID greater than 499 is created. (Under Red Hat Enterprise Linux, UIDs and GIDs below 500 are reserved for system use.)
2.

A GID greater than 499 is created. The optional GECOS information is left blank. The home directory for juan is set to /home/juan/. The default shell is set to /bin/bash.

A new line for juan is created in /etc/shadow. The line has the following characteristics: begins with the username juan.

It

exclamation points (!!) appear in the password field of the /etc/shadow file, which locks the account.
Two

Note
If an encrypted password is passed using the -p flag, it is placed in the /etc/shadow file on the new line for the user.
The 3.

password is set to never expire.

A new line for a group named juan is created in /etc/group. A group with the same name as a user is called a user private group. For more information on user private groups, refer to

Pakistan Computer Bureau

196

Section 15.1.1, Adding a New User. The line created in /etc/group has the following characteristics:

It begins with the group name juan.

An x appears in the password field indicating that the system is using shadow group passwords. The GID matches the one listed for user juan in /etc/passwd.

4.

A new line for a group named juan is created in /etc/gshadow. The line has the following characteristics: It begins with the group name juan.

An exclamation point (!) appears in the password field of the /etc/gshadow file, which locks the group.
5.

All other fields are blank.

A directory for user juan is created in the /home/ directory. This directory is owned by user juan and group juan. However, it has read, write, and execute privileges only for the user juan. All other permissions are denied.
6.

The files within the /etc/skel/ directory (which contain default user settings) are copied into the new /home/juan/ directory.

At this point, a locked account called juan exists on the system. To activate it, the administrator must next assign a password to the account using the passwd command and, optionally, set password aging guidelines.

15.3. Standard Users


Everything installation. The groupid (GID) in this table is the primary group for the user.

User

UID

GID

Home Directory

Shell

Root

/root

/bin/bash

Pakistan Computer Bureau

197

Bin daemon Adm Lp Sync shutdown Halt Mail News Uucp operator Games gopher ftp nobody Rpm Vcsa Dbus Ntp Canna Nscd Rpc postfix mailman Named amanda postgres Exim Sshd rpcuser nsfnobody Pvm apache Xfs Gdm Htt Mysql

1 2 3 4 5 6 7 8 9 10 11 12 13 14 99 37 69 81 38 39 28 32 89 41 25 33 26 93 74 29 65534 24 48 43 42 100 27

1 2 4 7 0 0 0 12 13 14 0 100 30 50 99 37 69 81 38 39 28 32 89 41 25 6 26 93 74 29 65534 24 48 43 42 101 27

/bin /sbin /var/adm /var/spool/lpd /sbin /sbin /sbin /var/spool/mail /etc/news /var/spool/uucp /root /usr/games /var/gopher /var/ftp / /var/lib/rpm /dev / /etc/ntp /var/lib/canna / / /var/spool/post /var/mailman /var/named var/lib/amanda/ /var/lib/pgsql /var/spool/exim /var/empty/sshd /var/lib/nfs /var/lib/nfs /usr/share/pvm3 /var/www /etc/X11/fs /var/gdm /usr/lib/im /var/lib/mysql

/sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /bin/sync /sbin/shutd /sbin/halt /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /bin/false /bin/bash /bin/bash /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /bin/bash /sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /bin/bash

Pakistan Computer Bureau

198

webalizer mailnull smmsp Squid Ldap netdump Pcap radiusd Radvd quagga Wnn dovecot

67 47 51 23 55 34 77 95 75 92 49 97

67 47 51 23 55 34 77 95 75 92 49 97

/var/www/usage /var/spool/mque /var/spool/mque /var/spool/squi /var/lib/ldap /var/crash /var/arpwatch / / /var/run/quagga /var/lib/wnn /usr/libexec/do

/sbin/nolog /sbin/nolog /sbin/nolog /sbin/nolog /bin/false /bin/bash /sbin/nolog /bin/false /sbin/nolog /sbin/login /sbin/nolog /sbin/nolog

Table 15.4. Standard Users

15.4. Standard Groups


Standard groups configured by an Everything installation. Groups are stored in the /etc/group file. Group Root Bin daemon Sys Adm Tty Disk Lp Mem Kmem Wheel Mail News Uucp Man Games Gopher Dip GID 0 1 2 3 4 5 6 7 8 9 10 12 13 14 15 20 30 40 Members root root, bin, daemon root, bin, daemon root, bin, adm root, adm, daemon root daemon, lp

root mail, postfix, exim news uucp

Pakistan Computer Bureau

199

ftp Lock Nobody Users Rpm Utmp Floppy Vcsa dbus ntp canna rpc postdrop postfix mailman exim named postgres sshd rpcuser apache xfs gdm htt mysql webalizer mailnull smmsp squid ldap netdump pcap quaggavt quagga radvd slocate wnn

50 54 99 100 37 22 19 69 81 38 39 32 90 89 41 93 25 26 74 29 48 43 42 101 27 67 47 51 23 55 34 77 102 92 75 21 49

Pakistan Computer Bureau

200

dovecot radiusd

97 95 Table 15.5. Standard Groups

15.5. User Private Groups


Red Hat Enterprise Linux uses a user private group which makes UNIX groups easier to manage.
A UPG (UPG)

scheme,

is created whenever a new user is added to the system. A UPG has the same name as the user for which it was created and that user is the only member of the UPG. make it safe to set default permissions for a newly created file or directory, allowing both the user and the group of that user to make modifications to the file or directory.
UPGs

The setting which determines what permissions are applied to a newly created file or directory is called a umask and is configured in the /etc/bashrc file. Traditionally on UNIX systems, the umask is set to 022, which allows only the user who created the file or directory to make modifications. Under this scheme, all other users, including members of the creator's group, are not allowed to make any modifications. However, under the UPG scheme, this "group protection" is not necessary since every user has their own private group.

15.5.1. Group Directories


Many IT organizations like to create a group for each major project and then assign people to the group if they need to access that project's files. Using this traditional scheme, managing files has been difficult; when someone creates a file, it is associated with the primary group to which they belong. When a single person works on multiple projects, it is difficult to associate the right files with the right group. Using the UPG scheme, however, groups are automatically assigned to files created within a directory with the setgid bit set. The setgid bit makes managing group projects that share a common directory very simple because any files a user creates within the directory are owned by

Pakistan Computer Bureau

201

the group which owns the directory. Let us say, for example, that a group of people need to work on files in the /usr/share/emacs/site-lisp/ directory. Some people are trusted to modify the directory, but certainly not everyone is trusted. First create an emacs group, as in the following command: /usr/sbin/groupadd emacs To associate the contents of the directory with the emacs group, type: chown -R root.emacs /usr/share/emacs/site-lisp Now, it is possible to add the proper users to the group with the gpasswd command: /usr/bin/gpasswd -a <username> emacs To allow users to create files within the directory, use the following command: chmod 775 /usr/share/emacs/site-lisp When a user creates a new file, it is assigned the group of the user's default private group. Next, set the setgid bit, which assigns everything created in the directory the same group permission as the directory itself (emacs). Use the following command: chmod 2775 /usr/share/emacs/site-lisp At this point, because the default umask of each user is 002, all members of the emacs group can create and edit files in the /usr/share/emacs/site-lisp/ directory without the administrator having to change file permissions every time users write new files. In multiuser environments it is very important to use shadow passwords by the shadow-utils package). Doing so enhances the security of system authentication files. For this reason, the installation program enables shadow passwords by default. The following lists the advantages of shadow passwords have over the
Pakistan Computer Bureau 202
(provided

traditional way of storing Passwords on UNIX-based systems:


Improves

system security by moving encrypted password hashes from the world-readable /etc/passwd file to /etc/shadow, which is readable only by the root user.

Stores information about password aging. Allows the use the /etc/login.defs file to enforce security policies. Most utilities provided by the shadow-utils package work properly whether or not shadow passwords are enabled. However, since password aging information is stored exclusively in the /etc/ shadow file, any commands which create or modify password aging information do not work. The following is a list of commands which do not work without first enabling shadow passwords:

chage gpasswd /usr/sbin/usermod-e or -f options /usr/sbin/useradd-e or -f options

Pakistan Computer Bureau

203

16.1 What is SQL?


The Structured Query Language is used in manipulating data stored in Relational Database Management Systems (RDBMS). SQL provides commands through which data can be extracted, sorted, updated, deleted and inserted. SQL has the full support of ANSI (American National Standards Institute), which has laid down certain rules for the language. SQL can be used with any RDBMS such as MySQL, mSQL, PostgresSQL, Oracle, Microsoft SQL Server, Access, Sybase, Ingres etc. All the important and common SQL statements are supported by these RDBMS, however, each has its own set of proprietary statements and extensions.

16.2 Why MySQL?


Choosing a database system depends on three main factors; the platform on which you work, your finances and what you want to achieve. The reason for choosing MySQL is because of the Linux system and MySQL is free for Linux.

16.3 What are databases and why do we need them?


In simplest terms, databases are store houses of data. Suppose you have an ASCII file that contains the names of your friends and their email addresses. Would you consider this file as a database? Technically, yes! You can add, update and delete data from this file. You may also write a small program (say in Perl or C) to extract, sort and display data on the basis of some search criterion. The need to store data is quite a fundamental to humans. Data storage and representation has been with us for thousands of years. Take the example of cave drawings (graphical data) or charting the course of seasons over the years (this would have helped in knowing the best times to sow or to migrate). Collecting data is important but more significant is the analysis of the data. A case in point is study of the movements of astronomical objects (stars, planets, the moon and the sun). Analysis of this data gave birth to two sciences, Astronomy and Astrology. Astonomy helps us predict tides, eclipses etc. Astrology on the other hand had provided loads of entertainment (!) to avid followers over the years. Coming back to the topic at hand, storing data is of prime importance because we can then analyse the data and extract some Information.

Pakistan Computer Bureau

204

16.4 Downloading MySQL


MySQL is available for Windows, Linux and other Unix variants. The Windows version is a shareware, which must registered after evaluation. we learnt SQL using this version. Later we shifted completely to Linux.... the Linux version is 100% free. You can get MySQL from its web site.

16.4.1 MySQL download - the Windows version


On the download page of MySQL web site, you'll find the links to Windows version. According to the MySQL site the Windows version "contains both the Standard and Max server binaries. It also contains a version of the command-line client which uses the Cygwin library to provide command history and editing".

16.4.2 MySQL download - the Linux version


RPM download is recommend for Linux workstations. (Make sure you download all the RPMs; the MySQL server, client and development RPMs. Note: You need the MySQL client software for this guide. Check MySQL website, it might have a complete RPM package that contains all the RPMS in one download file). If you run Linux as a server, the tarball download might be better. Once you have downloaded MySQL, let's see how to install MySQL on Linux and get it up and running.

16.5 Installing MySQL on Linux


It's simple to install MySQL on Linux using the RPM file.
1.

Become the superuser if you are working in your account. (Type "su" and

the prompt and give the root password).


2. 3.

Change to the directory that has the RPM download. Type the following command at the prompt:

4. rpm -ivh "mysql_file_name.rpm"

Pakistan Computer Bureau

205

Similarly you can also install the MySQL client and MySQL development RPMs if you've downloaded them. Alternatively, you can install the RPMs through GnoRPM (found under System).
5.

Now we'll set a password for the root user. Issue the following at the

prompt.
6. mysqladmin -u root password mysqldata

where mysqldata is the password for the root. (Change this to anything you like). It is now time to test the programs. Typing the following at the prompt starts the mysql client program.
7.

8. mysql -u root -p

The system asks for the the password. Type the root password (mysqldata). If you don't get the prompt for password, it might be because MySQL Server is not running. To start the server, change to /etc/rc.d/init.d/ directory and issue the command ./mysql start (or mysql start depending on the value of the PATH variable on your system). Now invoke mysql client program. Once MySQL client is running, you should get the mysql> prompt. Type the following at this prompt:
9. show databases;
10.

You should now get a display similar to:


+----------------+ | Database |

11. 12. 13. 14. 15. 16. 17.

+----------------+ | mysql | test | |

+----------------+ 2 rows in set (0.00 sec)

Okay, we've successfully installed MySQL on your system. Now let's look at some MySQL basics.

Pakistan Computer Bureau

206

16.6 Creating MySQL database on Linux system


I assume that you are working from your account and not the root. Start a terminal session and become the superuser (Type su at the prompt and then enter the root password). 2. Now we'll access the MySQL server. Type:
1.

3.

mysql -u root -p

The system prompts for the MySQL root password that you set up in Installing MySQL on Linux. (Note: This is not the Linux root password but the MySQL root password). Enter the password, which is not displayed for security reasons. Once you are successfully logged in, the system prints a welcome message and displays the mysql prompt ... something like
Welcome to the MySQL monitor. \g. Your MySQL connection id is 1 to server version: 3.22.32 Type 'help' for help. mysql> Commands end with ; or

4.

Now we are ready for creating the employees database. Issue the

command:
5. create database employees;

(Note: The command ends with a semi-colon) An important point to note is that this database is created by the root and so will not be accessible to any other user unless permitted by the root. Thus, in order to use this database from my account (called manish), I have to set the permissions by issuing the following command:
6.

7.

GRANT ALL ON employees.* TO manish@localhost

IDENTIFIED BY "eagle"

The above command grants my account (manish@localhost) all the permissions on employees database and sets my password to eagle. You

Pakistan Computer Bureau

207

should replace manish with your user name and choose an appropriate password. Close the mysql session by typing quit at the prompt. Exit from superuser and come back to your account. (Type exit). 9. To connect to MySQL from your account, type:
8.

10.

mysql -u user_name -p

Type in the password when prompted. (This password was set by the GRANTS ALL... command above) . The system displays the welcome message once you have successfully logged on to MySQL. Here is how your session should look like:
[manish@localhost manish]$ mysql -u manish -p Enter password: Welcome to the MySQL monitor. \g. Your MySQL connection id is 3 to server version: 3.22.32 Type 'help' for help. mysql> Commands end with ; or

11.

Typing the command SHOW DATABASES; will list all the databases

available on the system. You should get a display similar to:


12. 13. 14. 15. 16. 17. 18. 19. mysql> SHOW DATABASES; +----------------+ | Database |

+----------------+ | employees | mysql | test | | |

+----------------+

Pakistan Computer Bureau

208

20.

3 rows in set (0.00 sec)

21. Enter quit at the mysql> prompt to come out of the mysql client program

16.7 Creating tables


In this section of the mysql training course we will explore the MySQL commands to create database tables and selecting the database. Databases store data in tables. So what are these tables? In simplest terms, tables consist of rows and columns. Each column defines data of a particular type. Rows contain individual records. Consider the following:

Name Manish Sharma John Doe John Wayne Alexander

Age 28 32 48 19

Country India Australia U.S.A. Greece

Email manish@simplygraphix.com j.dow@nowhere.com jw@oldwesterns.com alex@conqueror.com

The table above contains four columns that store the name, age, country and email. Each row contains data for one individual. This is called a record. To find the country and email of Alexander, you'd first pick the name from the first column and and then look in the third and fourth columns of the same row. A database can have many tables; it is tables, that contain the actual data. Hence, we can segregate related (or unrelated) data in different tables. For our employees database we'll have one table that stores company details of the employees. The other table would contain personal information. Let's make the first table. The SQL command for creating tables looks complex when you view it for the first time. Don't worry if you get confused, we'll be discussing this in more detail in later sessions.

CREATE TABLE employee_data ( emp_id int unsigned not null auto_increment primary key, f_name varchar(20),

Pakistan Computer Bureau

209

l_name varchar(20), title varchar(30), age int, yos int, salary int, perks int, email varchar(60) );

Note: In MySQL, commands and column names are not case-sensitive; however, table and database names might be sensitive to case depending on the platform (as in Linux). You can thus, use create table instead of CREATE TABLE. The CREATE TABLE keywords are followed by the name of the table we want to create, employee_data. Each line inside the parenthesis represents one column. These columns store the employee id, first name, last name, title, age, years of service with the company, salary, perks and emails of our employees and are given descriptive names emp_id, f_name, l_name, title, age, yos, salary, perks and email, respectively. Each column name is followed by the column type. Column types define the type of data the column is set to contain. In our example, columns, f_name, l_name, title and email would contain small text strings, so we set the column type to varchar, which means varriable characters. The maximum number of characters for varchar columns is specified by a number enclosed in parenthesis immediately following the column name. Columns age, yos, salary and perks would contain numbers (integers), so we set the column type to int. Our first column (emp_id) contains an employee id. Its column type looks really mean, yeh?. Let's break it down. int: specifies that the column type is an integer (a number). unsigned: determines that the number will be unsigned (positive integer). not null: specifies that the value cannot be null (empty); that is, each row in the column would have a value. auto_increment: When MySQl comes across a column with an auto_increment attribute, it generates a new value that is one greater than the largest value in the column. Thus, we don't need to supply values for this column, MySQL generates it for us! Also, it follows that each value in this column would be unique. (We'll discuss the benefits of having unique values very shortly). primary key: helps in indexing the column that help in faster searches. Each value has to be unique.
Why have a column with unique values?

Our company Bignet has grown tremendously over the past two years. We've recruited thousands. Don't you think there is a fair chance that two employees might have the same name? Now, when that happens, how can

Pakistan Computer Bureau

210

we distinguish the records of these two employees unless we give them unique identification numbers? If we have a column with unique values, we can easily distinguish the two records. The best way to assign unique numbers is to let MySQL do it!

16.8 Using a database


We've already created our employees database. Now let's start the mysql client program and select our database. Once at the mysql prompt, issue the command:
SELECT DATABASE();

The system responds with


mysql> SELECT DATABASE(); +------------+ | DATABASE() | +------------+ | | +------------+ 1 row in set (0.01 sec)

The above shows that no database has been selected. Actually, everytime we work with mysql client, we have to specify which database we plan to use. There are several ways of doing it.
Specifying the database name at the start; type the folowing at the system prompt:

mysql employees (under Windows) mysql employees -u manish -p (under Linux)


Specifying the database with the USE statement at the mysql prompt:

mysql>USE employees;
Specifying the database with \u at the mysql prompt:

mysql>\u employees; It's necessary to specify the database we plan to use, else MySQL will throw an error.

Pakistan Computer Bureau

211

16.9 Creating tables


Once you've selected the employees database, issue the CREATE TABLE command at the mysql prompt.
CREATE TABLE employee_data ( emp_id int unsigned not null auto_increment primary key, f_name varchar(20), l_name varchar(20), title varchar(30), age int, yos int, salary int, perks int, email varchar(60)
);

Note: When you press the enter key after typing the first line, the mysql prompt changes to a ->. This means that mysql understands that the command is not complete and prompts you for additional statements. Remember, each mysql command ends with a semi-colon and each column declaration is separated by a comma. Also, you can type the entire command on one line if you so want. You screen should look similar to:
mysql> CREATE TABLE employee_data -> ( -> emp_id int unsigned not null auto_increment primary key, -> f_name varchar(20), -> l_name varchar(20), -> title varchar(30), -> age int, -> yos int, -> salary int, -> perks int, -> email varchar(60) -> );

Pakistan Computer Bureau

212

Query OK, 0 rows affected (0.01 sec)

Okay, we just made our first table.

16.10 MySQL lesson - MySQL tables


Now that we've created our employee_data table, let's check its listing. Type SHOW TABLES; at the mysql prompt. This should present you with the following display:
mysql> SHOW TABLES; +---------------------+ | Tables in employees | +---------------------+ | employee_data | +---------------------+ 1 row in set (0.00 sec)

16.11 MySQL Table details - describe table command


MySQL provides up with a command that displays the column details of the tables. Issue the following command at the mysql prompt:
DESCRIBE employee_data;

The display would be as follows:


mysql> DESCRIBE employee_data; +--------+------------------+------+-----+---------+---------------+ | Field Extra | Type | | Null | Key | Default |

+--------+------------------+------+-----+---------+---------------+ | emp_id | int(10) unsigned | auto_increment | | f_name | varchar(20) | | YES | PRI | 0 | | NULL | |

Pakistan Computer Bureau

213

| l_name | varchar(20) | | title | | age | | yos | | varchar(30) | int(11) | int(11)

| YES | YES | YES | YES | YES | YES | YES

| | | | | | |

| NULL | NULL | NULL | NULL | NULL | NULL | NULL

| | | | | | |

| salary | int(11) | | perks | | email | | int(11) | varchar(60)

+--------+------------------+------+-----+---------+---------------+ 9 rows in set (0.00 sec)

DESCRIBE lists all the column names along with their column types of the table. Now let's see how we can insert data into our table.

16.12 Inserting data in MySQL tables


Inserting data into tables

The INSERT SQL statement impregnates our table with data. Here is a general form of INSERT.
INSERT into table_name (column1, column2....) values (value1, value2...);

where table_name is the name of the table into which we want to insert data; column1, column2 etc. are column names and value1, value2 etc. are values for the respective columns. This is quite simple, isn't it? The following statement inserts the first record in employee_data table.
INSERT INTO employee_data (f_name, l_name, title, age, yos, salary, perks, email) values ("Manish", "Sharma", "CEO", 28, 4, 200000, 50000, "manish@bignet.com");

Pakistan Computer Bureau

214

As with other MySQL statements, you can enter this command on one line or span it in multiple lines. Some important points:

The table name is employee_data

The values for columns f_name, l_name, title and email are text strings and surrounded with quotes. Values for age, yos, salary and perks are numbers (intergers) and without quotes. You'll notice that we've inserted data in all columns except emp_id. This is because, we leave this job to MySQL, which will check the column for the largest value, increment it by one and insert the new value.

Once you type the above command correctly in the mysql client, it displays a success message.
mysql> INSERT INTO employee_data -> (f_name, l_name, title, age, yos, salary, perks, email) -> values -> ("Manish", "Sharma", "CEO", 28, 4, 200000, -> 50000, "manish@bignet.com"); Query OK, 1 row affected (0.00 sec)

16.13 Querying MySQL tables


Our employee_data table now contains enough data for us to work with. Let us see how we can extract (query) it. Querying involves the use of the MySQL SELECT command. Data is extracted from the table using the SELECT SQL command. Here is the format of a SELECT statement:
SELECT column_names from table_name [WHERE ...conditions];

The conditions part of the statement is optional (we'll go through this later). Basically, you require to know the column names and the table name from which to extract the data. For example, in order to extract the first and last names of all employees, issue the following command.
SELECT f_name, l_name from employee_data;

Pakistan Computer Bureau

215

The statement tells MySQL to list all the rows from columns f_name and l_name.
mysql> SELECT f_name, l_name from employee_data; +---------+------------+ | f_name | Manish | John | Ganesh | Mary | Fred | John | Edward | Alok | Hassan | Paul | Arthur | Kim | Roger | Danny | Mike | Monica | Hal | Joseph | Peter | l_name | Sharma | Hagan | Pillai | Anchor | Kruger | Sakamuro | Nanda | Rajabi | Simon | Hoopla | Hunter | Lewis | Gibson | Harper | Sehgal | Simlai | Irvine | Champion | | | | | | | | | | | | | | | | | | | | | +---------+------------+

| Anamika | Pandit

| MacFarland |

| Shahida | Ali

+---------+------------+ 21 rows in set (0.00 sec)

On close examination, you'll find that the display is in the order in which the data was inserted. Furthermore, the last line indicates the number of rows our table has (21). To display the entire table, we can either enter all the column names or use a simpler form of the SELECT statement.

Pakistan Computer Bureau

216

SELECT * from employee_data;

Some of you might recognize the in the above statement as the wildcard. Though we don't use that term for the character here, it serves a very similar function. The means 'ALL columns'. Thus, the above statement lists all the rows of all columns.
* *

16.14 Querying tables with MySQL Select - Another example


SELECT f_name, l_name, age from employee_data;

Selecting f_name, l_name and age columns would display something like:
mysql> SELECT f_name, l_name, age from employee_data; +---------+------------+------+ | f_name | Manish | John | Ganesh | Mary | Fred | John | Edward | Alok | Hassan | Paul | Arthur | Kim | Roger | Danny | Mike | Monica | Hal | Joseph | l_name | Sharma | Hagan | Pillai | Anchor | Kruger | Sakamuro | Nanda | Rajabi | Simon | Hoopla | Hunter | Lewis | Gibson | Harper | Sehgal | Simlai | Irvine | age | | | | | | | | | | | | | | | | | | | +---------+------------+------+ 28 | 32 | 32 | 27 | 26 | 31 | 34 | 25 | 32 | 33 | 43 | 32 | 32 | 35 | 34 | 36 | 30 | 27 | 27 | 217

| Anamika | Pandit

| MacFarland |

Pakistan Computer Bureau

| Shahida | Ali | Peter | Champion

| |

32 | 36 |

+---------+------------+------+ 21 rows in set (0.00 sec)

16.14.1 Selecting data using conditions


In this section of the MySQL tutorial we'll look at the format of a SELECT statement we met in the last session in detail. We will learn how to use the select statement using the WHERE clause.
SELECT column_names from table_name [WHERE ...conditions];

Now, we know that the conditions are optional (we've seen several examples in the last session... and you would have encountered them in the assignments too). The SELECT statement without conditions lists all the data in the specified columns. The strength of RDBMS lies in letting you retrieve data based on certain specified conditions. In this session we'll look at the SQL Comparison Operators.

16.14.2 The = and! = comparison operators for MySQL Select


SELECT f_name, l_name from employee_data where f_name = 'John'; +--------+------------+ | f_name | l_name | John | John | Hagan | | +--------+------------+ | MacFarland |

+--------+------------+ 2 rows in set (0.00 sec)

This displays the first and last names of all employees whose first names are John. Note that the word John in the condition is surrounded by single quotes. You can also use double quotes. The quotes are important since MySQL will throw an error if they are missing. Also, MySQL comparisions are case insensitive; which means "john", "John" or even "JoHn" would work!

Pakistan Computer Bureau

218

SELECT f_name,l_name from employee_data where title="Programmer"; +--------+------------+ | f_name | l_name | Fred | John | Alok | Kruger | | | | +--------+------------+ | MacFarland | | Nanda

| Edward | Sakamuro

+--------+------------+ 4 rows in set (0.00 sec)

Selects the first and last names of all employees who are programmers.
SELECT f_name, l_name from employee_data where age = 32; +---------+--------+ | f_name | John | Ganesh | Alok | Arthur | Kim | l_name | | Hagan | Nanda | | +---------+--------+ | Pillai | | Hoopla | | Hunter | |

| Shahida | Ali

+---------+--------+ 6 rows in set (0.00 sec)

This lists the first and last names of all empoyees 32 years of age. Remember that the column type of age was int, hence it's not necessary to surround 32 with quotes. This is a subtle difference between text and integer column types. The != means 'not equal to' and is the opposite of the equality operator.

Pakistan Computer Bureau

219

16.14.3 The greater than and lesser than operators


Okay, let's retrieve the first names of all employees who are older than 32.
SELECT f_name, l_name from employee_data where age > 32; +--------+------------+ | f_name | l_name | John | Paul | Roger | Danny | Mike | Peter | +--------+------------+ | MacFarland | | | | | | | | Simon | Lewis | Gibson | Harper | Champion | Hassan | Rajabi

+--------+------------+ 7 rows in set (0.00 sec)

How about employees who draw more than $120000 as salary...


SELECT f_name, l_name from employee_data where salary > 120000; +--------+--------+ | f_name | l_name | +--------+--------+ | Manish | Sharma | +--------+--------+ 1 row in set (0.00 sec)

Now, let's list all employees who have had less than 3 years of service in the company.

SELECT f_name, l_name from employee_data where yos < 3; +--------+----------+ | f_name | l_name | Mary | Anchor | | +--------+----------+

Pakistan Computer Bureau

220

| Edward | Sakamuro | | Paul | Kim | Roger | Danny | Mike | Hal | Simon | Hunter | Lewis | Gibson | Harper | Simlai | | | | | | | | | Arthur | Hoopla

| Joseph | Irvine

+--------+----------+ 10 rows in set (0.00 sec)

16.14.4 The <= and >= operators for selecting MySQL data
Used primarily with integer data, the less than equal (<=) and greater than equal (>=)operators provide additional functionality.
select f_name, l_name, age, salary from employee_data where age >= 33; +--------+------------+------+--------+ | f_name | l_name | John | Paul | Roger | Danny | Mike | Peter | age | salary | 80000 | 90000 | 85000 | 90000 | +--------+------------+------+--------+ | MacFarland | | | | | | | | Simon | Lewis | Gibson | Harper | Champion 34 | 33 | 43 | 34 | | Hassan | Rajabi

35 | 100000 | 36 | 120000 | 36 | 120000 |

+--------+------------+------+--------+ 7 rows in set (0.00 sec)

Selects the names, ages and salaries of employees who are more than or equal to 33 years of age..
select f_name, l_name from employee_data where yos <= 2; +--------+----------+ Pakistan Computer Bureau 221

| f_name | l_name | Mary | Paul | Kim | Roger | Danny | Mike | Hal | Anchor | Simon | Hunter | Lewis | Gibson | Harper | Simlai

| | | | | | | | | |

+--------+----------+ | Edward | Sakamuro | | Arthur | Hoopla

| Joseph | Irvine

+--------+----------+ 10 rows in set (0.00 sec)

Displays employee names who have less than or equal to 2 years of service in the company.

16.14.5 MySQL reference guide - Pattern Matching with text data


We will now learn at how to match text patterns using the where clause and the LIKE operator in this section of the MySQL reference guide. The equal to(=) comparision operator helps is selecting strings that are identical. Thus, to list the names of employees whose first names are John, we can use the following SELECT statement.
select f_name, l_name from employee_data where f_name = "John"; +--------+------------+ | f_name | l_name | John | John | Hagan | | +--------+------------+ | MacFarland |

+--------+------------+ 2 rows in set (0.00 sec)

What if we wanted to display employees whose first names begin with the alphabet J? SQL allows for some pattern matching with string data. Here is how it works.
Pakistan Computer Bureau 222

select f_name, l_name from employee_data where f_name LIKE "J%"; +--------+------------+ | f_name | l_name | John | John | Hagan | | | +--------+------------+ | MacFarland |

| Joseph | Irvine

+--------+------------+ 3 rows in set (0.00 sec)

You'll notice that we've replaced the Equal To sign with LIKE and we've used a percentage sign (%) in the condition. The % sign functions as a wildcard (similar to the usage of * in DOS and Linux systems). It signifies any character. Thus, "J%" means all strings that begin with the alphabet J. Similarly "%S" selects strings that end with S and "%H%", strings that contain the alphabet H. Okay, let's list all the employees that have Senior in their titles.

select f_name, l_name, title from employee_data where title like '%senior%'; +--------+--------+----------------------------+ | f_name | l_name | title | John | Kim | Mike | Hagan | Senior Programmer | | | | +--------+--------+----------------------------+ | Ganesh | Pillai | Senior Programmer | Hunter | Senior Web Designer

| Harper | Senior Marketing Executive |

+--------+--------+----------------------------+ 4 rows in set (0.00 sec)

Listing all employees whose last names end with A is very simple
mysql> select f_name, l_name from employee_data where l_name like '%a'; +--------+--------+ | f_name | l_name | Pakistan Computer Bureau 223

+--------+--------+ | Manish | Sharma | | Alok | Nanda | | Arthur | Hoopla | +--------+--------+ 3 rows in set (0.00 sec)

16.14.6 SQL primer - Logical Operators


In this section of the SQL primer we look at how to select data based on certain conditions presented through MySQL logical operators. SQL conditions can also contain Boolean (logical) operators. They are

AND OR NOT

Their usage is quite simple. Here is a SELECT statement that lists the names of employees who draw more than $70000 but less than $90000.
SELECT f_name, l_name from employee_data where salary > 70000 AND salary < 90000; +--------+------------+ | f_name | l_name | Mary | Fred | John | Paul | Anchor | Kruger | | | | | | | +--------+------------+

| MacFarland | | Simon

| Edward | Sakamuro | Arthur | Hoopla | Joseph | Irvine

+--------+------------+ 7 rows in set (0.00 sec)

Let's display the last names of employees whose last names start with the alphabet S or A.
SELECT l_name from employee_data where

Pakistan Computer Bureau

224

l_name like 'S%' OR l_name like 'A%'; +----------+ | l_name | Sharma | Anchor | Simon | Sehgal | Simlai | Ali | | | | | | | +----------+

| Sakamuro |

+----------+ 7 rows in set (0.00 sec)

Okay here is a more complex example... listing the names and ages of employees whose last names begin with S or P and who are less than 30 years of age.
SELECT f_name, l_name , age from employee_data where (l_name like 'S%' OR l_name like 'A%') AND age < 30; +--------+----------+------+ | f_name | l_name | Manish | Sharma | Mary | Hal | Anchor | Simlai | age | | | | +--------+----------+------+ 28 | 26 | 25 | 27 |

| Edward | Sakamuro |

+--------+----------+------+ 4 rows in set (0.00 sec)

Note the usage of parenthesis in the statement above. The parenthesis are meant to separate the various logical conditions and remove any abiguity. The NOT operator helps in listing all non programmers. (Programmers include Senior programmers, Multimedia Programmers and Programmers).

Pakistan Computer Bureau

225

SELECT f_name, l_name, title from employee_data where title NOT LIKE "%programmer%"; +---------+----------+----------------------------+ | f_name | Manish | Mary | Kim | Roger | Danny | Mike | Monica | Hal | Joseph | Peter | l_name | Sharma | Anchor | Hunter | Lewis | Gibson | Harper | Sehgal | Simlai | Irvine | title | CEO | Web Designer | Web Designer | Senior Web Designer | System Administrator | System Administrator | Marketing Executive | Marketing Executive | Marketing Executive | Customer Service Manager | | | | | | | | | | | | +---------+----------+----------------------------+ | Anamika | Pandit

| Senior Marketing Executive |

| Shahida | Ali

| Champion | Finance Manager

+---------+----------+----------------------------+ 12 rows in set (0.00 sec)

A final example before we proceed to the assignments. Displaying all employees with more than 3 years or service and more than 30 years of age.
select f_name, l_name from employee_data where yos > 3 AND age > 30; +--------+------------+ | f_name | l_name | John | John | Peter | Hagan | | | | +--------+------------+ | Ganesh | Pillai | Champion

| MacFarland |

+--------+------------+ 4 rows in set (0.00 sec)

Pakistan Computer Bureau

226

16.14.7 MySQL - IN and BETWEEN


This section of the tutorial MySQL looks at the In and BETWEEN operators. To list employees who are Web Designers and System Administrators, we use a SELECT statement as
SELECT f_name, l_name, title from -> employee_data where -> title = 'Web Designer' OR -> title = 'System Administrator'; +---------+--------+----------------------+ | f_name | l_name | title | | | +---------+--------+----------------------+ | Anamika | Pandit | Web Designer | Mary | Roger | Danny | Anchor | Web Designer | Lewis

| System Administrator |

| Gibson | System Administrator |

+---------+--------+----------------------+ 4 rows in set (0.01 sec)

SQL also provides an easier method with IN. Its usage is quite simple.
SELECT f_name, l_name, title from -> employee_data where title -> IN ('Web Designer', 'System Administrator'); +---------+--------+----------------------+ | f_name | l_name | title | | | +---------+--------+----------------------+ | Anamika | Pandit | Web Designer | Mary | Roger | Danny | Anchor | Web Designer | Lewis

| System Administrator |

| Gibson | System Administrator |

+---------+--------+----------------------+ 4 rows in set (0.00 sec)

Pakistan Computer Bureau

227

Suffixing NOT to IN will display data that is NOT found IN the condition. The following lists employees who hold titles other than Programmer and Marketing Executive.
SELECT f_name, l_name, title from -> employee_data where title NOT IN -> ('Programmer', 'Marketing Executive'); +---------+----------+----------------------------+ | f_name | Manish | John | Ganesh | Mary | Hassan | Paul | Arthur | Kim | Roger | Danny | Mike | Peter | l_name | Sharma | Hagan | Pillai | Anchor | Rajabi | Simon | Hoopla | Hunter | Lewis | Gibson | Harper | title | CEO | Senior Programmer | Senior Programmer | Web Designer | Web Designer | Multimedia Programmer | Multimedia Programmer | Multimedia Programmer | Senior Web Designer | System Administrator | System Administrator | Customer Service Manager | | | | | | | | | | | | | | +---------+----------+----------------------------+

| Anamika | Pandit

| Senior Marketing Executive |

| Shahida | Ali

| Champion | Finance Manager

+---------+----------+----------------------------+ 14 rows in set (0.00 sec)

BETWEEN is employed to specify integer ranges. Thus instead of age >= 32 AND age <= 40, we can use age BETWEEN 32 and 40.
select f_name, l_name, age from -> employee_data where age BETWEEN -> 32 AND 40; +---------+------------+------+ | f_name | l_name | age | 228

Pakistan Computer Bureau

+---------+------------+------+ | John | Ganesh | John | Alok | Hassan | Arthur | Kim | Roger | Danny | Mike | Peter | Hagan | Pillai | Nanda | Rajabi | Hoopla | Hunter | Lewis | Gibson | Harper | Champion | | | | | | | | | | | 32 | 32 | 34 | 32 | 33 | 32 | 32 | 35 | 34 | 36 | 32 | 36 |

| MacFarland |

| Shahida | Ali

+---------+------------+------+ 12 rows in set (0.00 sec)

You can use NOT with BETWEEN as in the following statement that lists employees who draw salaries less than $90000 and more than $150000.

select f_name, l_name, salary -> from employee_data where salary -> NOT BETWEEN -> 90000 AND 150000; +---------+------------+--------+ | f_name | Manish | Mary | Fred | John | Edward | Alok | Paul | Arthur | l_name | Sharma | Anchor | Kruger | Sakamuro | Nanda | Simon | Hoopla | salary | | 200000 | | | | | | | 85000 | 75000 | 80000 | 75000 | 70000 | 85000 | 75000 | +---------+------------+--------+

| MacFarland |

Pakistan Computer Bureau

229

| Hal | Joseph

| Simlai | Irvine

| | |

70000 | 72000 | 70000 |

| Shahida | Ali

+---------+------------+--------+ 11 rows in set (0.00 sec)

16.15 Ordering data


This section of the online MySQL tutorial looks at how we can change the display order of the data extracted from MySQL tables using the ORDER BY clause of the SELECT statement. The data that we have retrieved so far was always displayed in the order in which it was stored in the table. Actually, SQL allows for sorting of retrieved data with the ORDER BY clause. This clause requires the column name based on which the data will be sorted. Let's see how to display employee names with last names sorted alphabetically (in ascending order).
SELECT l_name, f_name from employee_data ORDER BY l_name; +------------+---------+ | l_name | Ali | Anchor | Champion | Gibson | Hagan | Harper | Hoopla | Hunter | Irvine | Kruger | Lewis | Nanda | Pandit | Pillai | Rajabi | f_name | +------------+---------+ | Shahida | | Mary | Peter | Danny | John | Mike | Arthur | Kim | Joseph | Fred | Roger | Alok | Ganesh | Hassan | | | | | | | | | | | | | | 230

| MacFarland | John

| Anamika |

Pakistan Computer Bureau

| Sakamuro | Sehgal | Sharma | Simlai | Simon

| Edward | Monica | Manish | Hal | Paul

| | | | |

+------------+---------+ 21 rows in set (0.00 sec)

Here are employees sorted by age.


SELECT f_name, l_name, age from employee_data ORDER BY age; +---------+------------+------+ | f_name | Edward | Mary | Hal | Joseph | Manish | Monica | Fred | John | Ganesh | Alok | Arthur | Kim | Hassan | John | Danny | Roger | l_name | Sakamuro | Anchor | Simlai | Irvine | Sharma | Sehgal | Kruger | Hagan | Pillai | Nanda | Hoopla | Hunter | Rajabi | Gibson | Lewis | age | | | | | | | | | | | | | | | | | | +---------+------------+------+ 25 | 26 | 27 | 27 | 27 | 28 | 30 | 31 | 32 | 32 | 32 | 32 | 32 | 32 | 33 | 34 | 34 | 35 |

| Anamika | Pandit

| Shahida | Ali

| MacFarland |

Pakistan Computer Bureau

231

| Mike | Peter | Paul

| Harper | Champion | Simon

| | |

36 | 36 | 43 |

+---------+------------+------+ 21 rows in set (0.00 sec)

The ORDER BY clause can sort in an ASCENDING (ASC) or DESCENDING (DESC) order depending upon the argument supplied. To list employee first names in descending order, we'll use the statement below.
SELECT f_name from employee_data ORDER by f_name DESC; +---------+ | f_name | +---------+ | Shahida | | Roger | Peter | Paul | Monica | Mike | Mary | Manish | Kim | Joseph | John | John | Hassan | Hal | Ganesh | Fred | Edward | Danny | Arthur | | | | | | | | | | | | | | | | | |

| Anamika |

Pakistan Computer Bureau

232

| Alok

+---------+ 21 rows in set (0.00 sec)

Note: The ascending (ASC) order is the default.

16.16 Limiting data retrieval


This section of the online MySQL lesson looks at how to limit the number of records displayed by the SELECT statement. As your tables grow, you'll find a need to display only a subset of data. This can be achieved with the LIMIT clause. For example, to list only the names of first 5 employees in our table, we use LIMIT with 5 as argument.
SELECT f_name, l_name from employee_data LIMIT 5; +---------+--------+ | f_name | Manish | John | Ganesh | Mary | l_name | | Sharma | | Hagan | | Pillai | | Anchor | +---------+--------+

| Anamika | Pandit | +---------+--------+ 5 rows in set (0.01 sec)

These are the first five entries in our table. You can couple LIMIT with ORDER BY. Thus, the following displays the 4 senior most employees.
SELECT f_name, l_name, age from employee_data ORDER BY age DESC LIMIT 4; +--------+----------+------+ | f_name | l_name | age |

Pakistan Computer Bureau

233

+--------+----------+------+ | Paul | Mike | Peter | Roger | Simon | Harper | Lewis | | | 43 | 36 | 36 | 35 |

| Champion |

+--------+----------+------+ 4 rows in set (0.00 sec)

Similarly, we can list the two youngest employees.


SELECT f_name, l_name, age from employee_data ORDER BY age LIMIT 2; +--------+----------+------+ | f_name | l_name | age | +--------+----------+------+ | Edward | Sakamuro | | Mary | Anchor | 25 | 26 |

+--------+----------+------+ 2 rows in set (0.01 sec)

16.17 Extracting Subsets


Limit can also be used to extract a subset of data by providing an additional argument. The general form of this LIMIT is: SELECT (whatever) from table LIMIT starting row, Number to extract;
SELECT f_name, l_name from employee_data LIMIT 6,3; +--------+------------+ | f_name | l_name | John | Alok | +--------+------------+ | MacFarland | | | | Nanda | Edward | Sakamuro

+--------+------------+

Pakistan Computer Bureau

234

3 rows in set (0.00 sec)

This extracts 3 rows starting from the sixth row.

16.18 The DISTINCT keyword


In this section of this manual, we will look at how to select and display records from MySQL tables using the DISTINCT keyword that eliminates the occurences of the same data. To list all titles in our company database, we can throw a statement as:
select title from employee_data; +----------------------------+ | title | CEO | Senior Programmer | Senior Programmer | Web Designer | Web Designer | Programmer | Programmer | Programmer | Programmer | Multimedia Programmer | Multimedia Programmer | Multimedia Programmer | Senior Web Designer | System Administrator | System Administrator | Marketing Executive | Marketing Executive | Marketing Executive | Customer Service Manager | Finance Manager | | | | | | | | | | | | | | | | | | | | | +----------------------------+

| Senior Marketing Executive |

+----------------------------+

Pakistan Computer Bureau

235

21 rows in set (0.00 sec)

You'll notice that the display contains multiple occurences of certain data. The SQL DISTINCT clause lists only unique data. Here is how you use it.
select DISTINCT title from employee_data; +----------------------------+ | title | CEO | Customer Service Manager | Finance Manager | Marketing Executive | Multimedia Programmer | Programmer | Senior Programmer | Senior Web Designer | System Administrator | Web Designer 11 rows in set (0.00 sec) | | | | | | | | | | | +----------------------------+

| Senior Marketing Executive |

+----------------------------+

This shows we have 11 unique titles in the company. Also, you can sort the unique entries using ORDER BY.
select DISTINCT age from employee_data ORDER BY age; +------+ | age | | | | | +------+ 25 | 26 | 27 | 28 |

Pakistan Computer Bureau

236

| | | | | | | |

30 | 31 | 32 | 33 | 34 | 35 | 36 | 43 |

+------+ 12 rows in set (0.00 sec)

is often used with the COUNT aggregate function, which we'll meet in later sessions.
DISTINCT

16.19 Finding the minimum and maximum values


MySQL provides inbuilt functions to find the minimum and maximum values. SQL provides 5 aggregate functions. They are: MIN(): Minimum value MAX(): Maximum value SUM(): The sum of values AVG(): The average values COUNT(): Counts the number of entries We'll look at finding the minimum and maximum values in a column.

16.20 MySQL MIN () - Minimum value


select MIN(salary) from employee_data; +-------------+ | MIN(salary) | +-------------+ | 70000 | +-------------+ 1 row in set (0.00 sec)

Pakistan Computer Bureau

237

16.21 MySQL MAX () - Maximum value


select MAX(salary) from employee_data; +-------------+ | MAX(salary) | +-------------+ | 200000 | +-------------+ 1 row in set (0.00 sec)

16.22 Finding the average and sum 16.22.1 Totalling column values with MySQL SUM
The SUM() aggregate function calculates the total of values in a column. You require to give the column name, which should be placed inside parenthesis. Let's see how much Bignet spends on salaries.
select SUM(salary) from employee_data; +-------------+ | SUM(salary) | +-------------+ | 1997000 | +-------------+ 1 row in set (0.00 sec)

SImilarly, we can display the total perks given to employees.


select SUM(perks) from employee_data; +------------+ | SUM(perks) | +------------+ | 390000 | +------------+ 1 row in set (0.00 sec)

Pakistan Computer Bureau

238

How about finding the total of salaries and perks?


select sum(salary) + sum(perks) from employee_data; +-------------------------+ | sum(salary)+ sum(perks) | +-------------------------+ | 2387000 | +-------------------------+ 1 row in set (0.01 sec)

This shows a hidden gem of the SELECT command. You can add, subtract, multiply or divide values. Actually, you can write full blown arithemetic expressions. Cool!

16.23 MySQL AVG () - Finding the Average


The AVG () aggregate function is employed for calculating averages of data in columns.
select avg(age) from employee_data; +----------+ | avg(age) | +----------+ | 31.6190 | +----------+ 1 row in set (0.00 sec)

This displays the average age of employees in Bignet and the following displays the average salary.
select avg(salary) from employee_data; +-------------+ | avg(salary) | +-------------+ | 95095.2381 | +-------------+ 1 row in set (0.00 sec)

Pakistan Computer Bureau

239

16.24 Naming Columns


MySQL allows you to name the displayed columns. So instead of f_name or l_name etc. you can use more descriptive terms. This is achieved with AS.
select avg(salary) AS 'Average Salary' from employee_data; +----------------+ | Average Salary | +----------------+ | 95095.2381 | +----------------+ 1 row in set (0.00 sec)

Such pseudo names make will the display more clear to users. The important thing to remember here is that if you assign pseudo names that contain spaces, enclose the names in quotes. Here is another example:
select (SUM(perks)/SUM(salary) * 100) AS 'Perk Percentage' from employee_data; +-----------------+ | Perk Percentage | +-----------------+ | 19.53 | +-----------------+ 1 row in set (0.00 sec)

16.25 Counting
The COUNT() aggregate functions counts and displays the total number of entries. For example, to count the total number of entries in the table, issue the command below.
select COUNT(*) from employee_data; +----------+ | COUNT(*) |

Pakistan Computer Bureau

240

+----------+ | 21 | +----------+ 1 row in set (0.00 sec)

As you have learnt, the * sign means "all data" Now, let's count the total number of employees who hold the "Programmer" title.
select COUNT(*) from employee_data where title = 'Programmer'; +----------+ | COUNT(*) | +----------+ | 4 | +----------+ 1 row in set (0.01 sec)

16.26 The MySQL GROUP BY clause


The GROUP BY clause allows us to group similar data. Thus, to list all unique titles in our table we can issue
select title from employee_data GROUP BY title; +----------------------------+ | title | CEO | Customer Service Manager | Finance Manager | Marketing Executive | Multimedia Programmer | Programmer | Senior Programmer | Senior Web Designer | | | | | | | | | +----------------------------+

| Senior Marketing Executive |

Pakistan Computer Bureau

241

| System Administrator | Web Designer 11 rows in set (0.01 sec)

| |

+----------------------------+

You'll notice that this is similar to the usage of DISTINCT, which we encountered in a previous session. Okay, here is how you can count the number of employees with different titles.
select title, count(*) from employee_data GROUP BY title; +----------------------------+----------+ | title | CEO | Customer Service Manager | Finance Manager | Marketing Executive | Multimedia Programmer | Programmer | Senior Programmer | Senior Web Designer | System Administrator | Web Designer 11 rows in set (0.00 sec) | count(*) | | | | | | | | | | | 1 | 1 | 1 | 3 | 3 | 4 | 1 | 2 | 1 | 2 | 2 | +----------------------------+----------+

| Senior Marketing Executive |

+----------------------------+----------+

For the command above, MySQL first groups different titles and then executes count on each group.

16.27 Sorting the data in MySQL


Now, let's find and list the number of employees holding different titles and sort them using ORDER BY.
select title, count(*) AS Number Pakistan Computer Bureau 242

from employee_data GROUP BY title ORDER BY Number; +----------------------------+--------+ | title | CEO | Customer Service Manager | Finance Manager | Senior Web Designer | Senior Programmer | System Administrator | Web Designer | Marketing Executive | Multimedia Programmer | Programmer 11 rows in set (0.00 sec) | Number | | | | | | | | | | | 1 | 1 | 1 | 1 | 1 | 2 | 2 | 2 | 3 | 3 | 4 | +----------------------------+--------+

| Senior Marketing Executive |

+----------------------------+--------+

Pakistan Computer Bureau

243

16.28 HAVING clause


To list the average salary of employees in different departments (titles), we use the GROUP BY clause, as in:
select title, AVG(salary) from employee_data GROUP BY title; +----------------------------+-------------+ | title | CEO | Customer Service Manager | Finance Manager | Marketing Executive | Multimedia Programmer | Programmer | Senior Programmer | Senior Web Designer | System Administrator | Web Designer 11 rows in set (0.00 sec) | AVG(salary) | | 200000.0000 | | | | | 70000.0000 | 77333.3333 | 83333.3333 | 75000.0000 | | 120000.0000 | +----------------------------+-------------+

| Senior Marketing Executive | 120000.0000 | | 115000.0000 | | 110000.0000 | | | 95000.0000 | 87500.0000 |

+----------------------------+-------------+

Now, suppose you want to list only the departments where the average salary is more than $100000, you can't do it, even if you assign a pseudo name to AVG(salary) column. Here, the HAVING clause comes to our rescue.
select title, AVG(salary) from employee_data GROUP BY title HAVING AVG(salary) > 100000; +----------------------------+-------------+ | title | CEO | AVG(salary) | | 200000.0000 | +----------------------------+-------------+

Pakistan Computer Bureau

244

| Finance Manager | Senior Programmer | Senior Web Designer 5 rows in set (0.00 sec)

| 120000.0000 | | 115000.0000 | | 110000.0000 |

| Senior Marketing Executive | 120000.0000 |

+----------------------------+-------------+

16.29 A little more on the MySQL SELECT statement


The MySQL SELECT command is something like a print or write command of other languages. You can ask it to display text strings, numeric data, the results of mathematical expressions etc.

16.29.1 Displaying the MySQL version number


select version(); +-----------+ | version() | +-----------+ | 3.22.32 | +-----------+ 1 row in set (0.00 sec)

16.29.2 Displaying the current date and time


select now(); +---------------------+ | now() | +---------------------+ | 2001-05-31 00:36:24 | +---------------------+ 1 row in set (0.00 sec)

Pakistan Computer Bureau

245

16.29.3 Displaying the current Day, Month and Year


SELECT DAYOFMONTH(CURRENT_DATE); +--------------------------+ | DAYOFMONTH(CURRENT_DATE) | +--------------------------+ | 1 row in set (0.01 sec) SELECT MONTH(CURRENT_DATE); +---------------------+ | MONTH(CURRENT_DATE) | +---------------------+ | 1 | +---------------------+ 1 row in set (0.00 sec) SELECT YEAR(CURRENT_DATE); +--------------------+ | YEAR(CURRENT_DATE) | +--------------------+ | 2001 | +--------------------+ 1 row in set (0.00 sec) 28 | +--------------------------+

16.29.4 Displaying text strings


select 'I Love MySQL'; +--------------+ | I Love MySQL | +--------------+ | I Love MySQL | +--------------+

Pakistan Computer Bureau

246

1 row in set (0.00 sec)

Obviously you can provide pseudo names for these columns using AS.
select 'Manish Sharma' as Name; +---------------+ | Name | +---------------+ | Manish Sharma | +---------------+ 1 row in set (0.00 sec)

16.29.5 Evaluating expressions in MySQL


select ((4 * 4) / 10 ) + 25; +----------------------+ | ((4 * 4) / 10 ) + 25 | +----------------------+ | 26.60 | +----------------------+ 1 row in set (0.00 sec)

16.29.6 Concatenating in MySQL


With SELECT you can concatenate values for display. CONCAT accepts arguments between parenthesis. These can be column names or plain text strings. Text strings have to be surrounded with quotes (single or double).
SELECT CONCAT(f_name, " ", l_name) from employee_data where title = 'Programmer'; +-----------------------------+ | CONCAT(f_name, " ", l_name) | +-----------------------------+ | Fred Kruger |

Pakistan Computer Bureau

247

| John MacFarland | Edward Sakamuro | Alok Nanda 4 rows in set (0.00 sec)

| | |

+-----------------------------+

You can also give descriptive names to these columns using AS.
select CONCAT(f_name, " ", l_name) AS Name from employee_data where title = 'Marketing Executive'; +---------------+ | Name | +---------------+ | Monica Sehgal | | Hal Simlai | | Joseph Irvine | +---------------+ 3 rows in set (0.00 sec)

16.30 MySQL programming - MySQL mathematical Functions


In addition to the four basic arithmetic operations addition (+), Subtraction (), Multiplication (*) and Division (/), MySQL also has the Modulo (%) operator. This calculates the remainder left after division.
select 87 % 9; +--------+ | 87 % 9 | +--------+ | 6 | +--------+ 1 row in set (0.00 sec)

Pakistan Computer Bureau

248

16.30.1 MySQL - MOD(x, y)


Displays the remainder of x divided by y, SImilar to the Modulus operator.
select MOD(37, 13); +-------------+ | MOD(37, 13) | +-------------+ | 11 | +-------------+ 1 row in set (0.00 sec)

16.30.2 MySQL ABS(x)


Calculates the Absolute value of number x. Thus, if x is negative its positive value is returned.
select ABS(-4.05022); +---------------+ | ABS(-4.05022) | +---------------+ | 4.05022 | +---------------+ 1 row in set (0.00 sec) select ABS(4.05022); +--------------+ | ABS(4.05022) | +--------------+ | 4.05022 | +--------------+ 1 row in set (0.00 sec)

Pakistan Computer Bureau

249

16.30.3 SQL SIGN(x)


Returns 1, 0 or -1 when x is positive, zero or negative, respectively.
select SIGN(-34.22); +--------------+ | SIGN(-34.22) | +--------------+ | -1 | +--------------+ 1 row in set (0.00 sec) select SIGN(54.6); +------------+ | SIGN(54.6) | +------------+ | 1 | +------------+ 1 row in set (0.00 sec) select SIGN(0); +---------+ | SIGN(0) | +---------+ | 0 | +---------+ 1 row in set (0.00 sec)

16.30.4 POWER(x,y)
Calculates the value of x raised to the power of y.
select POWER(4,3); +------------+ | POWER(4,3) | +------------+

Pakistan Computer Bureau

250

64.000000 |

+------------+ 1 row in set (0.00 sec)

16.30.5 SQRT(x)
Calculates the square root of x.
select SQRT(3); +----------+ | SQRT(3) | +----------+ | 1.732051 | +----------+ 1 row in set (0.00 sec)

16.30.6 ROUND(x) and ROUND(x,y)


Returns the value of x rounded to the nearest integer. ROUND can also accept an additional argument y that will round x to y decimal places.
select ROUND(14.492); +---------------+ | ROUND(14.492) | +---------------+ | 14 | +---------------+ 1 row in set (0.00 sec) select ROUND(4.5002); +---------------+ | ROUND(4.5002) | +---------------+ | 5 | +---------------+ 1 row in set (0.00 sec)

Pakistan Computer Bureau

251

select ROUND(-12.773); +----------------+ | ROUND(-12.773) | +----------------+ | -13 | +----------------+ 1 row in set (0.00 sec) select ROUND(7.235651, 3); +--------------------+ | ROUND(7.235651, 3) | +--------------------+ | 7.236 | +--------------------+ 1 row in set (0.00 sec)

16.30.7 FLOOR(x)
Returns the largest integer that is less than or equal to x.
select FLOOR(23.544); +---------------+ | FLOOR(23.544) | +---------------+ | 23 | +---------------+ 1 row in set (0.00 sec) select FLOOR(-18.4); +--------------+ | FLOOR(-18.4) | +--------------+ | -19 | +--------------+ 1 row in set (0.00 sec)

Pakistan Computer Bureau

252

16.30.8 CEILING(x)
Returns the smallest integer that is greater than or equal to x.
select CEILING(54.22); +----------------+ | CEILING(54.22) | +----------------+ | 55 | +----------------+ 1 row in set (0.00 sec) select CEILING(-62.23); +-----------------+ | CEILING(-62.23) | +-----------------+ | -62 | +-----------------+ 1 row in set (0.00 sec)

16.30.9 TAN(x), SIN(x) and COS(x)


Calculate the trignometic ratios for angle x (measured in radians).
select SIN(0); +----------+ | SIN(0) | +----------+ | 0.000000 | +----------+ 1 row in set (0.00 sec)

Pakistan Computer Bureau

253

16.31 Updating records


The SQL UPDATE command updates the data in tables. Its format is quite simple.
UPDATE table_name SET column_name1 = value1, column_name2 = value2, column_name3 = value3 ... [WHERE conditions];

Obviously, like other SQL commands, you can type in in one line or multiple lines. Let's look at some examples. Bignet has been doing good business, the CEO increases his salary by $20000 and perks by $5000. His previous salary was $200000 and perks were $50000.
UPDATE employee_data SET salary=220000, perks=55000 WHERE title='CEO'; Query OK, 1 row affected (0.02 sec) Rows matched: 1 Changed: 1 Warnings: 0

You can test this out by listing the data in the table.
select salary, perks from employee_data WHERE title = 'CEO'; +--------+-------+ | salary | perks | +--------+-------+ | 220000 | 55000 | +--------+-------+ 1 row in set (0.00 sec)

Pakistan Computer Bureau

254

Actually, you don't need to know the previous salary explicitly. You can be cheeky and use arithmetic operators. Thus, the following statement would have done the same job without us knowing the original data beforehand.
UPDATE employee_data SET salary = salary + 20000, perks = perks + 5000 WHERE title='CEO'; Query OK, 1 row affected (0.01 sec) Rows matched: 1 Changed: 1 Warnings: 0

Another progressive (???) step Bignet takes is changing the titles of Web Designer to Web Developer.
mysql> update employee_data SET -> title = 'Web Developer' -> WHERE title = 'Web Designer'; Query OK, 2 rows affected (0.00 sec) Rows matched: 2 Changed: 2 Warnings: 0

It's important that you take a long hard look at the condition part in the statement before executing update, else you might update the wrong data. Also, an UPDATE statement without conditions will update all the data in the column in all rows! Be very caferul.

16.32 MySQL Date column type part 1


Till now we've dealt with text (varchar) and numbers (int) data types. To understand date type, we'll explain the following: The details of the table can be displayed with DESCRIBE command.
mysql> DESCRIBE employee_per; +------------+------------------+------+-----+--------+-------+ | Field Extra | | Type | Null | Key | Default |

+------------+------------------+------+-----+--------+-------+

Pakistan Computer Bureau

255

| e_id | | address | | phone | | p_email |

| int(10) unsigned | | varchar(60) | int(11) | varchar(60) | YES | YES | YES | YES | YES | YES | YES | YES

| PRI | 0 | | | | | | | | | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL

| | | | | | | | |

| birth_date | date | | sex | | m_status | | s_name | | children | | enum('M','F') | enum('Y','N') | varchar(40) | int(11)

+------------+------------------+------+-----+--------+-------+ 9 rows in set (0.01 sec)

Notice that column birth_date has date as column type. we've also introduced another column type ENUM, which we'll discuss later. e-id: are employee ids, same as that in table employee_data address: Addresses of employees phone: Phone numbers p_email: Personal email addresses birth_date: Birth dates sex: The sex of the employee, Male or Female m_status: Marital status,Yes or No. s_name: Name of Spouse (NULL if employee is unmarried) children: Number of children (NULL if employee is unmarried) < MySQL of> MySQL dates are ALWAYS represented with the year followed by the month and then the date. Often you'll find dates written as YYYY-MM-DD, where YYYY is 4 digit year, MM is 2 digit month and DD, 2 digit date. We'll look at DATE and related column types in the session on column types.

Pakistan Computer Bureau

256

Operations on Date

Date column type allow for several operations such as sorting, testing conditions using comparision operators etc.
Using = and != operators on dates

select p_email, phone from employee_per where birth_date = '1969-12-31'; +---------------------------+---------+ | p_email | phone | +---------------------------+---------+ | killeratlarge@elmmail.com | 6666666 | +---------------------------+---------+ 1 row in set (0.00 sec)
Note:

MySQL requires the dates to be enclosed in quotes.

Using >= and <= operators

select e_id, birth_date from employee_per where birth_date >= '1970-01-01'; +------+------------+ | e_id | birth_date | +------+------------+ | | | | | | | 1 | 1972-03-16 | 4 | 1972-08-09 | 5 | 1974-10-13 | 8 | 1975-01-12 | 17 | 1970-04-18 | 18 | 1973-10-09 | 19 | 1973-01-20 |

+------+------------+ 7 rows in set (0.00 sec)

Pakistan Computer Bureau

257

16.33 Specifying date ranges in MySQL


select e_id, birth_date from employee_per where birth_date BETWEEN '1969-01-01' AND '1974-01-01'; +------+------------+ | e_id | birth_date | +------+------------+ | | | | | | 1 | 1972-03-16 | 4 | 1972-08-09 | 6 | 1969-12-31 | 17 | 1970-04-18 | 18 | 1973-10-09 | 19 | 1973-01-20 |

+------+------------+ 6 rows in set (0.00 sec) select e_id, birth_date from employee_per where birth_date >= '1969-01-01' AND birth_date <= '1974-01-01'; +------+------------+ | e_id | birth_date | +------+------------+ | | | | | | 1 | 1972-03-16 | 4 | 1972-08-09 | 6 | 1969-12-31 | 17 | 1970-04-18 | 18 | 1973-10-09 | 19 | 1973-01-20 |

+------+------------+

Pakistan Computer Bureau

258

6 rows in set (0.00 sec)

16.34 MySQL programming - MySQL Date column type part 2 16.34.1 Using Date to sort data
select e_id, birth_date from employee_per ORDER BY birth_date; +------+------------+ | e_id | birth_date | +------+------------+ | | | | | | | | | | | | | | | | | | | | | 11 | 1957-11-04 | 16 | 1964-03-06 | 21 | 1964-06-13 | 14 | 1965-04-28 | 15 | 1966-06-23 | 7 | 1966-08-20 | 10 | 1967-07-06 | 20 | 1968-01-25 | 12 | 1968-02-15 | 2 | 1968-04-02 | 9 | 1968-05-19 | 13 | 1968-09-03 | 3 | 1968-09-22 | 6 | 1969-12-31 | 17 | 1970-04-18 | 1 | 1972-03-16 | 4 | 1972-08-09 | 19 | 1973-01-20 | 18 | 1973-10-09 | 5 | 1974-10-13 | 8 | 1975-01-12 |

+------+------------+

Pakistan Computer Bureau

259

16.34.2 Selecting data using Dates


Here is how we can select employees born in March.
select e_id, birth_date from employee_per where MONTH(birth_date) = 3; +------+------------+ | e_id | birth_date | +------+------------+ | | 1 | 1972-03-16 | 16 | 1964-03-06 |

+------+------------+ 2 rows in set (0.00 sec)

Alternatively, we can use month names instead of numbers.


select e_id, birth_date from employee_per where MONTHNAME(birth_date) = 'January'; +------+------------+ | e_id | birth_date | +------+------------+ | | | 8 | 1975-01-12 | 19 | 1973-01-20 | 20 | 1968-01-25 |

+------+------------+ 3 rows in set (0.00 sec)

Be careful when using month names as they are case sensitive. Thus, January will work but JANUARY will not! Similarly, you can select employees born in a specific year or under specific dates. select e_id, birth_date from employee_per where year(birth_date) = 1972;

Pakistan Computer Bureau

260

+------+------------+ | e_id | birth_date | +------+------------+ | | 1 | 1972-03-16 | 4 | 1972-08-09 |

+------+------------+ 2 rows in set (0.00 sec) select e_id, birth_date from employee_per where DAYOFMONTH(birth_date) = 20; +------+------------+ | e_id | birth_date | +------+------------+ | | 7 | 1966-08-20 | 19 | 1973-01-20 |

+------+------------+ 2 rows in set (0.00 sec)

Current dates We had seen in the session on SELECT statement that current date, month and year can be displayed with CURRENT_DATE argument to DAYOFMONTH(), MONTH() and YEAR() clauses, respectively. The same can be used to select data from tables. select e_id, birth_date from employee_per where MONTH(birth_date) = MONTH(CURRENT_DATE); +------+------------+ | e_id | birth_date | +------+------------+ | 8 | 1975-01-12 |

Pakistan Computer Bureau

261

| |

19 | 1973-01-20 | 20 | 1968-01-25 |

+------+------------+ 3 rows in set (0.00 sec)

16.35 Null column type


The NULL column type is special in many ways. To insert a NULL value, just leave the column name from the INSERT statement. Columns have NULL as default unless specified by NOT NULL. You can have null values for integers as well as text or binary data. NULL cannot be compared using arithemetic operators. Comparisions for NULL take place with IS NULL or IS NOT NULL. select e_id, children from employee_per where children IS NOT NULL; +------+----------+ | e_id | children | +------+----------+ | | | | | | | | | | | 2 | 3 | 7 | 9 | 11 | 12 | 13 | 15 | 16 | 17 | 21 | 3 | 2 | 3 | 1 | 4 | 3 | 2 | 3 | 2 | 1 | 2 |

+------+----------+ 11 rows in set (0.00 sec)

The above lists ids and no. of children of all employees who have children.
Pakistan Computer Bureau 262

16.36 MySQL manual - MySQL table joins


Till now, we've used SELECT to retrieve data from only one table. However, we can extract data from two or more tables using a single SELECT statement. The strength of RDBMS lies in allowing us to relate data from one table with data from another. This correlation can only be made if atleast one column in the two tables contain related data. In our example, the columns that contain related data are emp_id of employee_data and e_id of employee_per. Let's conduct a table join and extract the names (from employee_data) and spouse names (from employee_per) of married employee.

select CONCAT(f_name, " ", l_name) AS Name, s_name as 'Spouse Name' from employee_data, employee_per where m_status = 'Y' AND emp_id = e_id; +-----------------+-----------------+ | Name | Manish Sharma | John Hagan | Ganesh Pillai | Anamika Sharma | Alok Nanda | Paul Simon | Arthur Hoopla | Kim Hunter | Danny Gibson | Mike Harper | Monica Sehgal | Peter Champion | Spouse Name | Anamika Sharma | Jane Donner | Sandhya Pillai | Manish Sharma | Manika Nanda | Rina Brighton | Matt Shikari | Betty Cudly | Stella Stevens | Edgar Alan | Ruby Richer | | | | | | | | | | | | | +-----------------+-----------------+

| John MacFarland | Mary Shelly

| Muriel Lovelace |

Pakistan Computer Bureau

263

+-----------------+-----------------+ 13 rows in set (0.00 sec)

The FROM clause takes the names of the two tables from which we plan to extract data. Also, we specify that data has to be retrieved for only those entries where the emp_id and e_id are same. The names of columns in the two tables are unique. However, this may not true always, in which case we can explicitly specify column names along with table name using the dot notation.

select CONCAT(employee_data.f_name, " ", employee_data.l_name) AS Name, employee_per.s_name AS 'Spouse Name' from employee_data, employee_per where employee_per.m_status = 'Y' AND employee_data.emp_id = employee_per.e_id; +-----------------+-----------------+ | Name | Manish Sharma | John Hagan | Ganesh Pillai | Anamika Sharma | Alok Nanda | Paul Simon | Arthur Hoopla | Kim Hunter | Danny Gibson | Mike Harper | Monica Sehgal | Peter Champion | Spouse Name | Anamika Sharma | Jane Donner | Sandhya Pillai | Manish Sharma | Manika Nanda | Rina Brighton | Matt Shikari | Betty Cudly | Stella Stevens | Edgar Alan | Ruby Richer | | | | | | | | | | | | | +-----------------+-----------------+

| John MacFarland | Mary Shelly

| Muriel Lovelace |

+-----------------+-----------------+

Pakistan Computer Bureau

264

13 rows in set (0.00 sec)

16.37 Deleting entries from tables


The SQL delete statement requires the table name and optional conditions. DELETE from table_name [WHERE conditions];
NOTE: If you don't specify any conditions ALL THE DATA IN THE TABLE WILL BE DELETED!!!

One of the Multimedia specialists 'Hasan Rajabi' (employee id 10) leaves the company. We'll delete his entry. DELETE from employee_data WHERE emp_id = 10; Query OK, 1 row affected (0.00 sec)

16.38 Dropping tables


To remove all entries from the table we can issue the DELETE statement without any conditions. DELETE from employee_data; Query OK, 0 rows affected (0.00 sec) However, this does not delete the table. The table still remains, which you can check with SHOW TABLES; mysql> SHOW TABLES; +---------------------+ | Tables in employees | +---------------------+ | employee_data | +---------------------+ 1 rows in set (0.00 sec)

To delete the table, we issue a DROP table command.

Pakistan Computer Bureau

265

DROP TABLE employee_data; Query OK, 0 rows affected (0.01 sec) Now, we won't get this table in SHOW TABLES; listing

16.39 MySQL database Column Types


The three major types of column types used in MySQL are Integer Text Date Choosing a column data type is very important in order to achieve speed, effective storage and retrieval. Hence, we've dedicated two sessions to this topic. Now, I'll be touching only the surface; for a thorough explanation refer the resources in What Next? session.

16.40 MySQL Numeric Column Types


In addition to int (Integer data type), MySQL also has provision for floatingpoint and double precision numbers. Each integer type can take also be UNSIGNED and/or AUTO_INCREMENT. TINYINT: very small numbers; suitable for ages. Actually, we should have used this data type for employee ages and number of children. Can store numbers between 0 to 255 if UNSIGNED clause is applied, else the range is between -128 to 127. SMALLINT: Suitable for numbers between 0 to 65535 (UNSIGNED) or 32768 to 32767. MEDIUMINT: 0 to 16777215 with UNSIGNED clause or -8388608 to 8388607. INT: UNSIGNED integers fall between 0 to 4294967295 or 2147683648 to 2147683647. BIGINT: Huge numbers. (-9223372036854775808 to 9223372036854775807) FLOAT: Floating point numbers (single precision) DOUBLE: Floating point numbers (double precision) DECIMAL:Floating point numbers represented as strings.

Pakistan Computer Bureau

266

16.40.1 Date and time column types


DATE: YYYY-MM-DD (Four digit year followed by two digit month and date) TIME: hh:mm:ss (Hours:Minutes:Seconds) DATETIME: YYYY-MM-DD hh:mm:ss (Date and time separated by a space character) TIMESTAMP: YYYYMMDDhhmmss YEAR: YYYY (4 digit year)

16.41 Column Types part 2 16.41.1 MySQL Text data type


Text can be fixed length (char) or variable length strings. Also, text comparisions can be case sensitive or insensitive depending on the type you choose.

where x can range from 1 to 255. VARCHAR(x): x ranges from 1 - 255 TINYTEXT: small text, case insensitive TEXT: slightly longer text, case insensitive MEDIUMTEXT: medium size text, case insensitive LONGTEXT: really long text, case insensitive TINYBLOB: Blob means a Binary Large OBject. You should use blobs for case sensitive searches. BLOB: slightly larger blob, case sensitive. MEDIUMBLOB: medium sized blobs, case sensitive. LONGBLOB: really huge blobs, case sensitive. ENUM: Enumeration data type have fixed values and the column can take only one value from the given set. The values are placed in parenthesis following ENUM declaration. An example, is the marital status column we encountered in employee_per table.

CHAR(x):

m_status ENUM("Y", "N")

Thus, m_status column will take only Y or N as values. If you specify any other value with the INSERT statement, MYSQL will not return an error, it just inserts a NULLvalue in the column. SET: An extension of ENUM. Values are fixed and placed after the SET declaration; however, SET columns can take multiple values from the values provided. Consider a column with the SET data type as
Pakistan Computer Bureau 267

hobbies SET ("Reading", "Surfing", "Trekking",

"Computing")

You can have 0 or all the four values in the column. INSERT tablename (hobbies) values ("Surfing", "Computing");

Pakistan Computer Bureau

268

Training Schedule Linux System Administrator Training Course Duration: 8 Weeks Working Days: 48
Day 1,2 Steps to Get You Started Is Your Hardware Compatible? Do You Have Enough Disk Space? Can You Install Using the CD-ROM or DVD Alternative Boot Methods Making an Installation Boot CD-ROM Preparing for a Hard Drive Installation Day 3,4,5,6 Installing on Intel and AMD Systems The Graphical Installation Program User Interface A Note about Virtual Consoles The Text Mode Installation Program User Interface Using the Keyboard to Navigate Starting the Installation Program Booting the Installation Program on x86, AMD64, and 64 Systems Booting the Installation Program on Itanium Systems Additional Boot Options Selecting an Installation Method Installing from DVD/CD-ROM What If the IDE CD-ROM Was Not Found? Installing from a Hard Drive Welcome to Red Hat Enterprise Linux Language Selection Keyboard Configuration Enter the Installation Number Disk Partitioning Setup Advanced Storage Options Create Default Layout Partitioning Your System
269

Intel

Graphical Display of Hard Drive(s) Disk Druid's Buttons Partition Fields Recommended Partitioning Scheme Adding Partitions Editing Partitions Deleting a Partition x86, AMD64, and Intel 64 Boot Loader Configuration Advanced Boot Loader Configuration Rescue Mode Alternative Boot Loaders SMP Motherboards and GRUB Time Zone Configuration Set Root Password Package Group Selection Preparing to Install Prepare to Install Installing Packages Installation Complete Itanium Systems - Booting Your Machine and PostInstallation Setup Post-Installation Boot Loader Options Booting Red Hat Enterprise Linux Automatically Day 7 Removing Red Hat Enterprise Linux Day 8,9,10 Troubleshooting Installation on an Intel or AMD System You are Unable to Boot Red Hat Enterprise Linux Are You Unable to Boot With Your RAID Card? Is Your System Displaying Signal 11 Errors? Trouble Beginning the Installation Problems with Booting into the Graphical Installation Trouble During the Installation No devices found to install Red Hat Enterprise Linux Error Message Saving Traceback Messages Without a Diskette Drive
270

Trouble with Partition Tables Using Remaining Space Other Partitioning Problems Other Partitioning Problems for Itanium System Users Are You Seeing Python Errors? Problems After Installation Trouble With the Graphical GRUB Screen on an x86-based System? Booting into a Graphical Environment Problems with the X Window System (GUI) Problems with the X Server Crashing and Non-Root Users Problems When You Try to Log In Is Your RAM Not Being Recognized? Your Printer Does Not Work Problems with Sound Configuration Apache-based httpd service/Sendmail Hangs During Startup Day 11,12,13 The GRUB Boot Loader Boot Loaders and System Architecture GRUB GRUB and the x86 Boot Process Features of GRUB Installing GRUB GRUB Terminology Device Names File Names and Block lists The Root File System and GRUB GRUB Interfaces Interfaces Load Order Commands GRUB Menu Configuration File Configuration File Structure Configuration File Directives Changing Run levels at Boot Time
271

Additional Resources Installed Documentation Useful Websites Day 14,15,16 Swap Space
What is Swap Space? Adding Swap Space Extending Swap on an LVM2 Logical Volume Creating an LVM2 Logical Volume for Swap Creating a Swap File. Removing Swap Space Reducing Swap on an LVM2 Logical Volume Removing an LVM2 Logical Volume for Swap Removing a Swap File Moving Swap Space

Day 17,18,19 Managing Disk Storage


Standard Partitions using parted Viewing the Partition Table Creating a Partition Removing a Partition Resizing a Partition LVM Partition Management

Day 20,21,22 Access Control Lists


Mounting File Systems NFS Setting Access ACLs Setting Default ACLs Retrieving ACLs Archiving File Systems With ACLs Compatibility with Older Systems Useful Websites RPM Design Goals Using RPM
272

Finding RPM Packages Installing Uninstalling Upgrading Freshening Querying Verifying Checking a Package's Signature Importing Keys Verifying Signature of Packages Practical and Common Examples of RPM Usage Additional Resources Installed Documentation Useful Websites Related Books

Day 26,27,28,29 Network File System (NFS)


How It Works Required Services NFS Client Configuration Mounting NFS File Systems using /etc/fstab
autofs

What's new in autofsversion 5?


autofsConfiguration autofsCommon Tasks

Common NFS Mount Options Starting and Stopping NFS NFS Server Configuration Exporting or Sharing NFS File Systems Command Line Configuration Hostname Formats The /etc/exportsConfiguration File The exportfsCommand
273

Securing NFS Host Access File Permissions NFS and portmap Troubleshooting NFS and portmap Using NFS over TCP Additional Resources Installed Documentation Useful Websites Related Books

Day 30,31 Samba


Introduction to Samba Samba Features Samba Daemons and Related Services Samba Daemons

Day 32,33 Date and Time Configuration


Time and Date Properties Network Time Protocol (NTP) Properties Time Zone Configuration

Day 34,35,36 The X Window System


The X11R7.1 Release Desktop Environments and Window Managers Desktop Environments Window Managers X Server Configuration Files
xorg.conf

Fonts Fontconfig Core X Font System Runlevels and X Runlevel 3 Runlevel 5


274

Day 37,38,39 X Window System Configuration


Display Settings Display Hardware Settings Dual Head Display Settings

Day 40,41,42 Users and Groups


User and Group Configuration Adding a New User Modifying User Properties Adding a New Group Modifying Group Properties User and Group Management Tools Command Line Configuration Adding a User Adding a Group Password Aging Explaining the Process Standard Users Standard Groups User Private Groups Group Directories

Day 43,44,45

MySql

What is SQL Why MySQL What are databases and why do we need them? Downloading MySQL Installing MySQL on Linux Creating MySQL database on Linux system Creating tables Using a database Creating tables MySQL lesson - MySQL tables MySQL Table details - describe table command
275

Inserting data in MySQL tables Querying MySQL tables Querying tables with MySQL Select - Another example Ordering data Limiting data retrieval Extracting Subsets The DISTINCT keyword Finding the minimum and maximum values MySQL MIN () - Minimum value MySQL MAX () - Maximum value Finding the average and sum MySQL AVG() - Finding the Average Naming Columns Counting The MySQL GROUP BY clause Sorting the data in MySQL HAVING clause A little more on the MySQL SELECT statement MySQL programming - MySQL mathematical Functions Updating records MySQL Date column type part 1 Specifying date ranges in MySQL MySQL programming - MySQL Date column type part 2 Null column type MySQL manual - MySQL table joins Deleting entries from tables Dropping tables MySQL database Column Types MySQL Numeric Column Types Column Types part 2

Day 46, 47 Course Review & Questions/Answers Session Day 48 Test


276

You might also like