Linux Admin
Linux Admin
Paul Cobbaut
Abstract
This book is meant to be used in an instructor-led training. For self-study, the intent is to read this book next to a working Linux computer so you can immediately do every subject, practicing each command. This book is aimed at novice Linux system administrators (and might be interesting and useful for home users that want to know a bit more about their Linux system). However, this book is not meant as an introduction to Linux desktop applications like text editors, browsers, mail clients, multimedia or office applications. More information and free .pdf available at http://linux-training.be . Feel free to contact the author: Paul Cobbaut: [email protected], http://www.linkedin.com/in/cobbaut Contributors to the Linux Training project are: Serge van Ginderachter: [email protected], build scripts and infrastructure setup Ywein Van den Brande: [email protected], license and legal sections Hendrik De Vloed: [email protected], buildheader.pl script We'd also like to thank our reviewers: Wouter Verhelst: [email protected], http://grep.be Geert Goossens: [email protected], http://www.linkedin.com/in/geertgoossens Elie De Brauwer: [email protected], http://www.de-brauwer.be Christophe Vandeplas: [email protected], http://christophe.vandeplas.com Bert Desmet: [email protected], http://blog.bdesmet.be Rich Yonts: [email protected],
Copyright 2007-2013 Paul Cobbaut Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled 'GNU Free Documentation License'.
Table of Contents
I. process management ......................................................................................... 1 1. introduction to processes ............................................................................ 2 2. process priorities ....................................................................................... 14 3. background jobs ........................................................................................ 21 II. disk management ........................................................................................... 27 4. disk devices ............................................................................................... 28 5. disk partitions ............................................................................................ 41 6. file systems ............................................................................................... 49 7. mounting ................................................................................................... 57 8. introduction to uuid's ................................................................................ 66 9. introduction to raid ................................................................................... 71 10. logical volume management ................................................................... 79 11. iSCSI devices ........................................................................................ 103 III. boot management ....................................................................................... 112 12. bootloader .............................................................................................. 113 13. init and runlevels .................................................................................. 125 IV. system management .................................................................................... 141 14. scheduling ............................................................................................. 142 15. logging .................................................................................................. 149 16. memory management ............................................................................ 160 17. package management ............................................................................ 167 V. network management ................................................................................... 188 18. general networking ................................................................................ 189 19. interface configuration .......................................................................... 198 20. network sniffing .................................................................................... 213 21. binding and bonding ............................................................................. 219 22. ssh client and server ............................................................................. 228 23. introduction to nfs ................................................................................. 240 24. introduction to networking .................................................................... 244 VI. kernel management .................................................................................... 254 25. the Linux kernel .................................................................................... 255 26. library management ............................................................................... 272 VII. backup management ................................................................................. 275 27. backup ................................................................................................... 276 VIII. Appendix ................................................................................................... 285 Index .................................................................................................................... 286
iii
List of Tables
4.1. ide device naming .......................................................................................... 4.2. scsi device naming ......................................................................................... 5.1. primary, extended and logical partitions ........................................................ 5.2. Partition naming ............................................................................................. 10.1. disk partitioning example ............................................................................. 10.2. LVM Example ............................................................................................. 31 31 42 42 80 80
iv
introduction to processes
1.1. terminology
process
A process is compiled source code that is currently running on the system.
PID
All processes have a process id or PID.
PPID
Every process has a parent process (with a PPID). The child process is often started by the parent process.
init
The init process always has process ID 1. The init process is started by the kernel itself so technically it does not have a parent process. init serves as a foster parent for orphaned processes.
kill
When a process stops running, the process dies, when you want a process to die, you kill it.
daemon
Processes that start at system startup and keep running forever are called daemon processes or daemons. These daemons never die.
zombie
When a process is killed, but it still shows up on the system, then the process is referred to as zombie. You cannot kill zombies, because they are already dead.
introduction to processes
pidof
You can find all process id's by name using the pidof command.
root@rhel53 ~# pidof mingetty 2819 2798 2797 2796 2795 2794
Typing exit will end the current process and brings us back to our original values for $$ and $PPID.
[paul@RHEL4b 4812 4224 [paul@RHEL4b exit [paul@RHEL4b 4224 4223 [paul@RHEL4b ~]$ echo $$ $PPID ~]$ exit ~]$ echo $$ $PPID ~]$
introduction to processes
exec
With the exec command, you can execute a process without forking a new process. In the following screenshot a Korn shell (ksh) is started and is being replaced with a bash shell using the exec command. The pid of the bash shell is the same as the pid of the Korn shell. Exiting the child bash shell will get me back to the parent bash, not to the Korn shell (which does not exist anymore).
[paul@RHEL4b ~]$ 4224 [paul@RHEL4b ~]$ $ echo $$ $PPID 5343 4224 $ exec bash [paul@RHEL4b ~]$ 5343 4224 [paul@RHEL4b ~]$ exit [paul@RHEL4b ~]$ 4224 echo $$ # PID of bash ksh # PID of ksh and bash echo $$ $PPID # PID of bash and bash exit echo $$
ps
One of the most common tools on Linux to look at processes is ps. The following screenshot shows the parent child relationship between three bash processes.
[paul@RHEL4b 4224 4223 [paul@RHEL4b [paul@RHEL4b 4866 4224 [paul@RHEL4b [paul@RHEL4b 4884 4866 [paul@RHEL4b PID TTY 4223 ? ~]$ echo $$ $PPID ~]$ bash ~]$ echo $$ $PPID ~]$ bash ~]$ echo $$ $PPID ~]$ ps fx STAT TIME COMMAND S 0:01 sshd: paul@pts/0
introduction to processes
4224 pts/0 4866 pts/0 4884 pts/0 4902 pts/0 [paul@RHEL4b exit [paul@RHEL4b PID TTY 4223 ? 4224 pts/0 4866 pts/0 4903 pts/0 [paul@RHEL4b exit [paul@RHEL4b PID TTY 4223 ? 4224 pts/0 4904 pts/0 [paul@RHEL4b Ss S S R+ ~]$ exit 0:00 0:00 0:00 0:00 \_ -bash \_ bash \_ bash \_ ps fx
~]$ ps fx STAT TIME COMMAND S 0:01 sshd: paul@pts/0 Ss 0:00 \_ -bash S 0:00 \_ bash R+ 0:00 \_ ps fx ~]$ exit ~]$ ps fx STAT TIME COMMAND S 0:01 sshd: paul@pts/0 Ss 0:00 \_ -bash R+ 0:00 \_ ps fx ~]$
On Linux, ps fax is often used. On Solaris ps -ef (which also works on Linux) is common. Here is a partial output from ps fax.
[paul@RHEL4a ~]$ ps fax PID TTY STAT TIME COMMAND 1 ? S 0:00 init [5] ... 3713 5042 5044 5045 5077 ? ? ? pts/1 pts/1 Ss Ss S Ss R+ 0:00 /usr/sbin/sshd 0:00 \_ sshd: paul [priv] 0:00 \_ sshd: paul@pts/1 0:00 \_ -bash 0:00 \_ ps fax
pgrep
Similar to the ps -C, you can also use pgrep to search for a process by its command name.
[paul@RHEL5 ~]$ sleep 1000 & [1] 32558 [paul@RHEL5 ~]$ pgrep sleep 32558 [paul@RHEL5 ~]$ ps -C sleep PID TTY TIME CMD 32558 pts/3 00:00:00 sleep
You can also list the command name of the process with pgrep.
paul@laika:~$ pgrep -l sleep 9661 sleep
introduction to processes
top
Another popular tool on Linux is top. The top tool can order processes according to cpu usage or other properties. You can also kill processes from within top. Press h inside top for help. In case of trouble, top is often the first tool to fire up, since it also provides you memory and swap space information.
introduction to processes
list signals
Running processes can receive signals from each other or from the users. You can have a list of signals by typing kill -l, that is a letter l, not the number 1.
[paul@RHEL4a ~]$ kill -l 1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1 64) SIGRTMAX [paul@RHEL4a ~]$
kill -1 (SIGHUP)
It is common on Linux to use the first signal SIGHUP (or HUP or 1) to tell a process that it should re-read its configuration file. Thus, the kill -1 1 command forces the init process (init always runs with pid 1) to re-read its configuration file.
root@deb503:~# kill -1 1 root@deb503:~#
It is up to the developer of the process to decide whether the process can do this running, or whether it needs to stop and start. It is up to the user to read the documentation of the program. 8
introduction to processes
kill -9 (SIGKILL)
The SIGKILL is different from most other signals in that it is not being sent to the process, but to the Linux kernel. A kill -9 is also called a sure kill. The kernel will shoot down the process. As a developer you have no means to intercept a kill -9 signal.
root@rhel53 ~# kill -9 3342
killall
The killall command will also default to sending a signal 15 to the processes. This command and its SysV counterpart killall5 can by used when shutting down the system. This screenshot shows how Red Hat Enterprise Linux 5.3 uses killall5 when halting the system.
root@rhel53 ~# grep killall /etc/init.d/halt action $"Sending all processes the TERM signal..." /sbin/killall5 -15 action $"Sending all processes the KILL signal..." /sbin/killall5 -9
pkill
You can use the pkill command to kill a process by its command name.
[paul@RHEL5 ~]$ sleep 1000 & [1] 30203 [paul@RHEL5 ~]$ pkill sleep [1]+ Terminated [paul@RHEL5 ~]$
sleep 1000
top
Inside top the k key allows you to select a signal and pid to kill. Below is a partial screenshot of the line just below the summary in top after pressing k. 9
introduction to processes
10
introduction to processes
11
introduction to processes
4. Using your terminal name from above, use ps to find all processes associated with your terminal.
oot@rhel53 ~# ps fax | grep pts/0 2941 ? S 0:00 \_ sshd: paul@pts/0 2942 pts/0 Ss 0:00 \_ -bash 2972 pts/0 S 0:00 \_ su 2973 pts/0 S 0:00 \_ -bash 3808 pts/0 R+ 0:00 \_ ps fax 3809 pts/0 R+ 0:00 \_ grep pts/0
or also
root@rhel53 ~# ps -ef paul 2941 2939 paul 2942 2941 root 2972 2942 root 2973 2972 root 3816 2973 root 3817 2973 | 0 0 0 0 0 0 grep pts/0 17:44 ? 17:44 pts/0 17:45 pts/0 17:45 pts/0 21:25 pts/0 21:25 pts/0
echo $$ should display same number as the one you found 6. What is the parent process id of your shell ?
2972 in the screenshot above, probably different for you
in this example the PPID is from the su - command, but when inside gnome then for example gnome-terminal can be the parent process 7. Start two instances of the sleep 3342 in background. 12
introduction to processes
sleep 3342 & sleep 3342 &
9. Display only those two sleep processes in top. Then quit top.
top -p pidx,pidy (replace pidx pidy with the actual numbers)
13
14
process priorities
pipes (mkfifo)
Processes can communicate with each other via pipes. These pipes can be created with the mkfifo command. The screenshots shows the creation of four distinct pipes (in a new directory).
paul@ubuntu910:~$ mkdir procs paul@ubuntu910:~$ cd procs/ paul@ubuntu910:~/procs$ mkfifo pipe33a pipe33b pipe42a pipe42b paul@ubuntu910:~/procs$ ls -l total 0 prw-r--r-- 1 paul paul 0 2010-04-12 13:21 pipe33a prw-r--r-- 1 paul paul 0 2010-04-12 13:21 pipe33b prw-r--r-- 1 paul paul 0 2010-04-12 13:21 pipe42a prw-r--r-- 1 paul paul 0 2010-04-12 13:21 pipe42b paul@ubuntu910:~/procs$
The commands you see above will create two proj33 processes that use cat to bounce the x character between pipe33a and pipe33b. And ditto for the z character and proj42. 15
process priorities
top
Just running top without options or arguments will display all processes and an overview of innformation. The top of the top screen might look something like this.
top - 13:59:29 up 48 min, 4 users, load average: 1.06, 0.25, 0.14 Tasks: 139 total, 3 running, 136 sleeping, 0 stopped, 0 zombie Cpu(s): 0.3%us, 99.7%sy, 0.0%ni, 0.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 509352k total, 460040k used, 49312k free, 66752k buffers Swap: 746980k total, 0k used, 746980k free, 247324k cached
Notice the cpu idle time (0.0%id) is zero. This is because our cat processes are consuming the whole cpu. Results can vary on systems with four or more cpu cores.
top -p
The top -p 1670,1671,1673,1674 screenshot below shows four processes, all of then using approximately 25 percent of the cpu.
paul@ubuntu910:~$ top -p 1670,1671,1673,1674 PID 1674 1670 1671 1673 USER paul paul paul paul PR 20 20 20 20 NI 0 0 0 0 VIRT 2972 2972 2972 2972 RES 616 616 616 620 SHR 524 524 524 524 S S R S R %CPU %MEM 26.6 0.1 25.0 0.1 24.6 0.1 23.0 0.1 TIME+ 0:11.92 0:23.16 0:23.07 0:11.48 COMMAND proj42 proj33 proj33 proj42
All four processes have an equal priority (PR), and are battling for cpu time. On some systems the Linux kernel might attribute slightly varying priority values, but the result will still be four processes fighting for cpu time.
renice
Since the processes are already running, we need to use the renice command to change their nice value (NI). The screenshot shows how to use renice on both the proj33 processes.
paul@ubuntu910:~$ renice +8 1670 1670: old priority 0, new priority 8 paul@ubuntu910:~$ renice +8 1671 1671: old priority 0, new priority 8
Normal users can attribute a nice value from zero to 20 to processes they own. Only the root user can use negative nice values. Be very careful with negative nice values, since they can make it impossible to use the keyboard or ssh to a system. 16
process priorities
Important to remember is to always make less important processes nice to more important processes. Using negative nice values can have a serere impact on a system's usability.
nice
The nice works identical to the renice but it is used when starting a command. The screenshot shows how to start a script with a nice value of five.
paul@ubuntu910:~$ nice -5 ./backup.sh
17
process priorities
18
process priorities
3. Use top and ps to display information (pid, ppid, priority, nice value, ...) about these two cat processes.
top (probably the top two lines) [paul@rhel53 pipes]$ ps PID TTY TIME 4013 pts/0 00:03:38 4016 pts/0 00:01:07 -C cat CMD cat cat | grep cat | | |
[paul@rhel53 pipes]$ ps fax 4013 pts/0 R 4:00 4016 pts/0 S 1:13 4044 pts/0 S+ 0:00
4. Bounce another character between two other pipes, but this time start the commands nice. Verify that all cat processes are battling for the cpu. (Feel free to fire up two more cats with the remaining pipes).
echo -n y | nice cat - p3 > p4 & nice cat <p4 >p3 &
5. Use ps to verify that the two new cat processes have a nice value. Use the -o and -C options of ps for this.
[paul@rhel53 pipes]$ ps -C cat -o pid,ppid,pri,ni,comm PID PPID PRI NI COMMAND 4013 3947 14 0 cat 4016 3947 21 0 cat 4025 3947 13 10 cat 4026 3947 13 10 cat
6. Use renice te increase the nice value from 10 to 15. Notice the difference with the usual commands.
[paul@rhel53 pipes]$ renice +15 4025 4025: old priority 10, new priority 15 [paul@rhel53 pipes]$ renice +15 4026
19
process priorities
4026: old priority 10, new priority 15 [paul@rhel53 pipes]$ ps -C cat -o pid,ppid,pri,ni,comm PID PPID PRI NI COMMAND 4013 3947 14 0 cat 4016 3947 21 0 cat 4025 3947 9 15 cat 4026 3947 8 15 cat
20
21
background jobs
control-Z
Some processes can be suspended with the Ctrl-Z key combination. This sends a SIGSTOP signal to the Linux kernel, effectively freezing the operation of the process. When doing this in vi(m), then vi(m) goes to the background. The background vi(m) can be seen with the jobs command.
[paul@RHEL4a ~]$ vi procdemo.txt [5]+ Stopped [paul@RHEL4a ~]$ jobs [5]+ Stopped vim procdemo.txt vim procdemo.txt
& ampersand
Processes that are started in background using the & character at the end of the command line are also visible with the jobs command.
[paul@RHEL4a ~]$ find / > allfiles.txt 2> /dev/null & [6] 5230 [paul@RHEL4a ~]$ jobs [5]+ Stopped vim procdemo.txt [6]- Running find / >allfiles.txt 2>/dev/null & [paul@RHEL4a ~]$
jobs -p
An interesting option is jobs -p to see the process id of background processes.
[paul@RHEL4b ~]$ sleep 500 &
22
background jobs
[1] 4902 [paul@RHEL4b [2] 4903 [paul@RHEL4b 4902 4903 [paul@RHEL4b PID TTY 4902 pts/0 4903 pts/0 [paul@RHEL4b
~]$ ps `jobs -p` STAT TIME COMMAND S 0:00 sleep 500 S 0:00 sleep 400 ~]$
fg
Running the fg command will bring a background job to the foreground. The number of the background job to bring forward is the parameter of fg.
[paul@RHEL5 ~]$ jobs [1] Running [2]- Running [3]+ Running [paul@RHEL5 ~]$ fg 3 sleep 2000
bg
Jobs that are suspended in background can be started in background with bg. The bg will send a SIGCONT signal. Below an example of the sleep command (suspended with Ctrl-Z) being reactivated in background with bg.
[paul@RHEL5 ~]$ jobs [paul@RHEL5 ~]$ sleep 5000 & [1] 6702 [paul@RHEL5 ~]$ sleep 3000 [2]+ Stopped [paul@RHEL5 ~]$ [1]- Running [2]+ Stopped [paul@RHEL5 ~]$ [2]+ sleep 3000 [paul@RHEL5 ~]$ [1]- Running [2]+ Running [paul@RHEL5 ~]$ sleep 3000 jobs sleep 5000 & sleep 3000 bg 2 & jobs sleep 5000 & sleep 3000 &
23
background jobs
24
background jobs
4. Start find / > allfiles.txt 2>/dev/null in foreground. Suspend it in background before it finishes.
[paul@rhel53 ~]$ find / > allfiles.txt 2>/dev/null (press ctrl-z) [2]+ Stopped find / > allfiles.txt 2> /dev/null
10. (if time permits, a general review question...) Explain in detail where the numbers come from in the next screenshot. When are the variables replaced by their value ? By which shell ?
25
background jobs
[paul@RHEL4b ~]$ echo $$ $PPID 4224 4223 [paul@RHEL4b ~]$ bash -c "echo $$ $PPID" 4224 4223 [paul@RHEL4b ~]$ bash -c 'echo $$ $PPID' 5059 4224 [paul@RHEL4b ~]$ bash -c `echo $$ $PPID` 4223: 4224: command not found
The current bash shell will replace the $$ and $PPID while scanning the line, and before executing the echo command.
[paul@RHEL4b ~]$ echo $$ $PPID 4224 4223
The variables are now double quoted, but the current bash shell will replace $$ and $PPID while scanning the line, and before executing the bach -c command.
[paul@RHEL4b ~]$ bash -c "echo $$ $PPID" 4224 4223
The variables are now single quoted. The current bash shell will not replace the $$ and the $PPID. The bash -c command will be executed before the variables replaced with their value. This latter bash is the one replacing the $$ and $PPID with their value.
[paul@RHEL4b ~]$ bash -c 'echo $$ $PPID' 5059 4224
With backticks the shell will still replace both variable before the embedded echo is executed. The result of this echo is the two process id's. These are given as commands to bash -c. But two numbers are not commands!
[paul@RHEL4b ~]$ bash -c `echo $$ $PPID` 4223: 4224: command not found
26
This chapter teaches you how to locate and recognise hard disk devices. This prepares you for the next chapter, where we put partitions on these devices.
28
disk devices
4.1. terminology
platter, head, track, cylinder, sector
Data is commonly stored on magnetic or optical disk platters. The platters are rotated (at high speeds). Data is read by heads, which are very close to the surface of the platter, without touching it! The heads are mounted on an arm (sometimes called a comb or a fork). Data is written in concentric circles called tracks. Track zero is (usually) on the outside. The time it takes to position the head over a certain track is called the seek time. Often the platters are stacked on top of each other, hence the set of tracks accessible at a certain position of the comb forms a cylinder. Tracks are divided into 512 byte sectors, with more unused space (gap) between the sectors on the outside of the platter. When you break down the advertised access time of a hard drive, you will notice that most of that time is taken by movement of the heads (about 65%) and rotational latency (about 30%).
block device
Random access hard disk devices have an abstraction layer called block device to enable formatting in fixed-size (usually 512 bytes) blocks. Blocks can be accessed independent of access to other blocks. A block device has the letter b to denote the file type in the output of ls -l.
[root@RHEL4b ~]# ls -l /dev/sda* brw-rw---- 1 root disk 8, 0 Aug brw-rw---- 1 root disk 8, 1 Aug brw-rw---- 1 root disk 8, 2 Aug [root@RHEL4b ~]#
Note that a character device is a constant stream of characters, being denoted by a c in ls -l. Note also that the ISO 9660 standard for cdrom uses a 2048 byte block size. Old hard disks (and floppy disks) use cylinder-head-sector addressing to access a sector on the disk. Most current disks use LBA (Logical Block Addressing).
ide or scsi
Actually, the title should be ata or scsi, since ide is an ata compatible device. Most desktops use ata devices, most servers use scsi. 29
disk devices
ata
An ata controller allows two devices per bus, one master and one slave. Unless your controller and devices support cable select, you have to set this manually with jumpers. With the introduction of sata (serial ata), the original ata was renamed to parallel ata. Optical drives often use atapi, which is an ATA interface using the SCSI communication protocol.
scsi
A scsi controller allows more than two devices. When using SCSI (small computer system interface), each device gets a unique scsi id. The scsi controller also needs a scsi id, do not use this id for a scsi-attached device. Older 8-bit SCSI is now called narrow, whereas 16-bit is wide. When the bus speeds was doubled to 10Mhz, this was known as fast SCSI. Doubling to 20Mhz made it ultra SCSI. Take a look at http://en.wikipedia.org/wiki/SCSI for more SCSI standards.
30
disk devices
It is possible to have only /dev/hda and /dev/hdd. The first one is a single ata hard disk, the second one is the cdrom (by default configured as slave).
31
disk devices
And here an example of sata disks on a laptop with Ubuntu. Remember that sata disks are presented to you with the scsi /dev/sdx notation.
root@laika:~# fdisk -l | grep Disk Disk /dev/sda: 100.0 GB, 100030242816 bytes Disk /dev/sdb: 100.0 GB, 100030242816 bytes
Here is an overview of disks on a RHEL4u3 server with two real 72GB scsi disks. This server is attached to a NAS with four NAS disks of half a terabyte. On the NAS disks, four LVM (/dev/mdx) software RAID devices are configured.
[root@tsvtl1 ~]# fdisk -l | grep Disk Disk /dev/sda: 73.4 GB, 73407488000 bytes Disk /dev/sdb: 73.4 GB, 73407488000 bytes Disk /dev/sdc: 499.0 GB, 499036192768 bytes Disk /dev/sdd: 499.0 GB, 499036192768 bytes Disk /dev/sde: 499.0 GB, 499036192768 bytes Disk /dev/sdf: 499.0 GB, 499036192768 bytes Disk /dev/md0: 271 MB, 271319040 bytes Disk /dev/md2: 21.4 GB, 21476081664 bytes Disk /dev/md3: 21.4 GB, 21467889664 bytes Disk /dev/md1: 21.4 GB, 21476081664 bytes
You can also use fdisk to obtain information about one specific hard disk device.
[root@rhel4 ~]# fdisk -l /dev/sda Disk /dev/sda: 12.8 GB, 12884901888 bytes 255 heads, 63 sectors/track, 1566 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sda1 * /dev/sda2 Start 1 14 End 13 1566 Blocks 104391 12474472+ Id 83 8e System Linux Linux LVM
Later we will use fdisk to do dangerous stuff like creating and deleting partitions.
32
disk devices
/bin/dmesg
Kernel boot messages can be seen after boot with dmesg. Since hard disk devices are detected by the kernel during boot, you can also use dmesg to find information about disk devices.
root@barry:~# dmesg | grep "[hs]d[a-z]" Kernel command line: root=/dev/hda1 ro ide0: BM-DMA at 0xfc00-0xfc07, BIOS settings: hda:DMA, hdb:DMA ide1: BM-DMA at 0xfc08-0xfc0f, BIOS settings: hdc:DMA, hdd:DMA hda: ST360021A, ATA DISK drive hdb: Maxtor 6Y080L0, ATA DISK drive hdc: SONY DVD RW DRU-510A, ATAPI CD/DVD-ROM drive hdd: SONY DVD RW DRU-810A, ATAPI CD/DVD-ROM drive hda: max request size: 128KiB hda: 117231408 sectors (60022 MB) w/2048KiB Cache, CHS=65535/16/63, UDMA hda: hda1 hda2 hdb: max request size: 128KiB hdb: 160086528 sectors (81964 MB) w/2048KiB Cache, CHS=65535/16/63, UDMA hdb: hdb1 hdb2 hdc: ATAPI 32X DVD-ROM DVD-R CD-R/RW drive, 8192kB Cache, UDMA(33) hdd: ATAPI 40X DVD-ROM DVD-R CD-R/RW drive, 2048kB Cache, UDMA(33) ...
Here's another example of dmesg (same computer as above, but with extra 200gb disk now).
paul@barry:~$ dmesg [ 2.624149] hda: [ 2.904150] hdb: [ 3.472148] hdd: | grep -i "ata disk" ST360021A, ATA DISK drive Maxtor 6Y080L0, ATA DISK drive WDC WD2000BB-98DWA0, ATA DISK drive
/sbin/lshw
The lshw tool will list hardware. With the right options lshw can show a lot of information about disks (and partitions). Below a truncated screenshot on Debian 5:
root@debian5:~# aptitude search lshw p lshw - information about hardware configuration p lshw-gtk - information about hardware configuration root@debian5:~# aptitude install lshw ... root@debian5:~# lshw -class volume *-volume:0
33
disk devices
description: EXT3 volume vendor: Linux physical id: 1 bus info: [email protected],1 logical name: /dev/hda1 logical name: / version: 1.0 serial: f327ca8a-8187-48c5-b760-956ec79d414b size: 19GiB capacity: 19GiB capabilities: primary bootable journaled extended_attributes lar\ ge_files huge_files recover ext3 ext2 initialized configuration: created=2009-10-28 12:02:35 filesystem=ext3 ... ...
/sbin/lsscsi
The /sbin/lsscsi will give you a nice readable output of all scsi (and scsi emulated devices). This first screenshot shows lsscsi on a SPARC system.
root@shaka:~# lsscsi [0:0:0:0] disk Adaptec [1:0:0:0] disk SEAGATE root@shaka:~#
RAID5 ST336605FSUN36G
V1.0 0438
/dev/sda /dev/sdb
Here is the same command, but run on a laptop with scsi emulated dvd writer and scsi emulated usb.
paul@laika:~$ lsscsi [0:0:0:0] disk [1:0:0:0] disk [3:0:0:0] cd/dvd [4:0:0:0] disk [4:0:0:1] disk [4:0:0:2] disk [4:0:0:3] disk
HTS721010G9SA00 HTS721010G9SA00 DVD_RW ND-7551A USB Storage-CFC USB Storage-SDC USB Storage-SMC USB Storage-MSC
34
disk devices
/proc/scsi/scsi
Another way to locate scsi devices is via the /proc/scsi/scsi file.
root@shaka:~# cat /proc/scsi/scsi Attached devices: Host: scsi0 Channel: 00 Id: 00 Lun: 00 Vendor: Adaptec Model: RAID5 Type: Direct-Access Host: scsi1 Channel: 00 Id: 00 Lun: 00 Vendor: SEAGATE Model: ST336605FSUN36G Type: Direct-Access root@shaka:~#
Rev: V1.0 ANSI SCSI revision: 02 Rev: 0438 ANSI SCSI revision: 03
Another simple tool is scsiinfo which is a part of scsitools (also not installed by default).
root@debian5:~# scsiinfo -l /dev/sda /dev/sdb /dev/sdc
35
disk devices
36
disk devices
= 0 (off) = 0 (default) = 0 (off) = 1 (on) = 0 (off) = 0 (off) = 256 (on) = 24321/255/63, sectors = 390721968, start = 0
37
disk devices
38
disk devices
2. Use fdisk to find the total size of all hard disk devices on your system.
fdisk -l
3. Stop a virtual machine, add three virtual 1 gigabyte scsi hard disk devices and one virtual 400 megabyte ide hard disk device. If possible, also add another virtual 400 megabyte ide disk.
This exercise happens in the settings of vmware or VirtualBox.
4. Use dmesg to verify that all the new disks are properly detected at boot-up.
See 1.
6. Use fdisk (with grep and /dev/null) to display the total size of the new disks.
root@rhel53 ~# Disk /dev/hda: Disk /dev/hdb: Disk /dev/sda: Disk /dev/sdb: Disk /dev/sdc: fdisk -l 21.4 GB, 1073 MB, 2147 MB, 2147 MB, 2147 MB, 2>/dev/null | grep [MGT]B 21474836480 bytes 1073741824 bytes 2147483648 bytes 2147483648 bytes 2147483648 bytes
8. Look at /proc/scsi/scsi.
root@rhel53 ~# cat /proc/scsi/scsi
39
disk devices
Attached devices: Host: scsi0 Channel: 00 Id: 02 Lun: 00 Vendor: VBOX Model: HARDDISK Type: Direct-Access Host: scsi0 Channel: 00 Id: 03 Lun: 00 Vendor: VBOX Model: HARDDISK Type: Direct-Access Host: scsi0 Channel: 00 Id: 06 Lun: 00 Vendor: VBOX Model: HARDDISK Type: Direct-Access
Rev: 1.0 ANSI SCSI revision: 05 Rev: 1.0 ANSI SCSI revision: 05 Rev: 1.0 ANSI SCSI revision: 05
9. If possible, install lsscsi, lshw and use them to list the disks.
Debian,Ubuntu: aptitude install lsscsi lshw Fedora: yum install lsscsi lshw root@rhel53 ~# lsscsi [0:0:2:0] disk VBOX [0:0:3:0] disk VBOX [0:0:6:0] disk VBOX
40
This chapter continues on the hard disk devices from the previous one. Here we will put partitions on those devices. This chapter prepares you for the next chapter, where we put file systems on our partitions.
41
disk partitions
partition naming
We saw before that hard disk devices are named /dev/hdx or /dev/sdx with x depending on the hardware configuration. Next is the partition number, starting the count at 1. Hence the four (possible) primary partitions are numbered 1 to 4. Logical partition counting always starts at 5. Thus /dev/hda2 is the second partition on the first ATA hard disk device, and /dev/hdb5 is the first logical partition on the second ATA hard disk device. Same for SCSI, /dev/sdb3 is the third partition on the second SCSI disk. Table 5.2. Partition naming partition /dev/hda1 /dev/hda2 /dev/sda5 /dev/sdb6 device first primary partition on /dev/hda second primary or extended partition on /dev/hda first logical drive on /dev/sda second logical on /dev/sdb
42
disk partitions
/proc/partitions
The /proc/partitions file contains a table with major and minor number of partitioned devices, their number of blocks and the device name in /dev. Verify with /proc/ devices to link the major number to the proper device.
paul@RHELv4u4:~$ cat /proc/partitions major minor #blocks name 3 3 8 8 8 8 8 8 253 253 0 64 0 1 2 16 32 48 0 1 524288 734003 8388608 104391 8281507 1048576 1048576 1048576 7176192 1048576 hda hdb sda sda1 sda2 sdb sdc sdd dm-0 dm-1
The major number corresponds to the device type (or driver) and can be found in /proc/devices. In this case 3 corresponds to ide and 8 to sd. The major number determines the device driver to be used with this device. The minor number is a unique identification of an instance of this device type. The devices.txt file in the kernel tree contains a full list of major and minor numbers.
other tools
You might be interested in alternatives to fdisk like parted, cfdisk, sfdisk and gparted. This course mainly uses fdisk to partition hard disks. 43
disk partitions
Disk /dev/sdb: 1073 MB, 1073741824 bytes 255 heads, 63 sectors/track, 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Disk /dev/sdb doesn't contain a valid partition table
44
disk partitions
Device Boot Start End Blocks Id System
We can now issue p again to verify our changes, but they are not yet written to disk. This means we can still cancel this operation! But it looks good, so we use w to write the changes to disk, and then quit the fdisk tool.
Command (m for help): p Disk /dev/sdb: 1073 MB, 1073741824 bytes 255 heads, 63 sectors/track, 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot /dev/sdb1 Start 1 End 14 Blocks Id System 112423+ 83 Linux
Command (m for help): w The partition table has been altered! Calling ioctl() to re-read partition table. Syncing disks. root@RHELv4u2:~#
Disk /dev/sdb: 1073 MB, 1073741824 bytes 255 heads, 63 sectors/track, 130 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot Start End Blocks Id System
45
disk partitions
/dev/sdb1 root@RHELv4u2:~# 1 14 112423+ 83 Linux
The same tool can also be used to wipe out all information about partitions on a disk. This example writes zeroes over the master boot record.
dd if=/dev/zero of=/dev/sda bs=512 count=1
partprobe
Don't forget that after restoring a master boot record with dd, that you need to force the kernel to reread the partition table with partprobe. After running partprobe, the partitions can be used again.
[root@RHEL5 ~]# partprobe [root@RHEL5 ~]#
logical drives
The partition table does not contain information about logical drives. So the dd backup of the mbr only works for primary and extended partitions. To backup the partition table including the logical drives, you can use sfdisk. This example shows how to backup all partition and logical drive information to a file.
sfdisk -d /dev/sda > parttable.sda.sfdisk
The following example copies the mbr and all logical drive info from /dev/sda to / dev/sdb.
sfdisk -d /dev/sda | sfdisk /dev/sdb
46
disk partitions
47
disk partitions
5. Create a 400MB primary partition and two 300MB logical drives on a big disk.
Choose one of the disks you added (this example uses /dev/sdb) fdisk /dev/sdb inside fdisk : n p 1 +400m enter --- n e 2 enter enter --- n l +300m (twice)
7. Compare the output again of fdisk and df. Do both commands display the new partitions ?
The newly created partitions are visible with fdisk. But they are not displayed by df.
8. Create a backup with dd of the mbr that contains your 200MB primary partition.
dd if=/dev/sdc of=bootsector.sdc.dd count=1 bs=512
9. Take a backup of the partition table containing your 400MB primary and 300MB logical drives. Make sure the logical drives are in the backup.
sfdisk -d /dev/sdb > parttable.sdb.sfdisk
48
When you are finished partitioning the hard disk, you can put a file system on each partition. This chapter builds on the partitions from the previous chapter, and prepares you for the next one where we will mount the filesystems.
49
file systems
ext4
Since 2008 the newest incarnation of the ext file system is ext4 is available in the Linux kernel. ext4 support larger files (up to 16 terabyte) and larger file systems than ext3 (and many more features).
50
file systems
vfat
The vfat file system exists in a couple of forms : fat12 for floppy disks, fat16 on msdos, and fat32 for larger disks. The Linux vfat implementation supports all of these, but vfat lacks a lot of features like security and links. fat disks can be read by every operating system, and are used a lot for digital cameras, usb sticks and to exchange data between different OS'ses on a home user's computer.
iso 9660
iso 9660 is the standard format for cdroms. Chances are you will encounter this file system also on your hard disk in the form of images of cdroms (often with the .iso extension). The iso 9660 standard limits filenames to the 8.3 format. The Unix world didn't like this, and thus added the rock ridge extensions, which allows for filenames up to 255 characters and Unix-style file-modes, ownership and symbolic links. Another extensions to iso 9660 is joliet, which adds 64 unicode characters to the filename. The el torito standard extends iso 9660 to be able to boot from CDROM's.
udf
Most optical media today (including cd's and dvd's) use udf, the Universal Disk Format.
swap
All things considered, swap is not a file system. But to use a partition as a swap partition it must be formatted and mounted as swap space.
others...
You might encounter reiserfs on older Linux systems. Maybe you will see Sun's zfs or the open source btrfs. This last one requires a chapter on itself.
/proc/filesystems
The /proc/filesystems file displays a list of supported file systems. When you mount a file system without explicitly defining one, then mount will first try to probe / etc/filesystems and then probe /proc/filesystems for all the filesystems without the nodev label. If /etc/filesystems ends with a line containing only an asterisk (*) then both files are probed.
paul@RHELv4u4:~$ cat /proc/filesystems nodev sysfs
51
file systems
nodev nodev nodev nodev nodev nodev nodev nodev nodev nodev nodev nodev rootfs bdev proc sockfs binfmt_misc usbfs usbdevfs futexfs tmpfs pipefs eventpollfs devpts ext2 nodev ramfs nodev hugetlbfs iso9660 nodev relayfs nodev mqueue nodev selinuxfs ext3 nodev rpc_pipefs nodev vmware-hgfs nodev autofs paul@RHELv4u4:~$
52
file systems
It is time for you to read the manual pages of mkfs and mke2fs. In the example below, you see the creation of an ext2 file system on /dev/sdb1. In real life, you might want to use options like -m0 and -j.
root@RHELv4u2:~# mke2fs /dev/sdb1 mke2fs 1.35 (28-Feb-2004) Filesystem label= OS type: Linux Block size=1024 (log=0) Fragment size=1024 (log=0) 28112 inodes, 112420 blocks 5621 blocks (5.00%) reserved for the super user First data block=1 Maximum filesystem blocks=67371008 14 block groups 8192 blocks per group, 8192 fragments per group 2008 inodes per group Superblock backups stored on blocks: 8193, 24577, 40961, 57345, 73729 Writing inode tables: done Writing superblocks and filesystem accounting information: done This filesystem will be automatically checked every 37 mounts or 180 days, whichever comes first. Use tune2fs -c or -i to override.
This example changes this value to ten percent. You can use tune2fs while the file system is active, even if it is the root file system (as in this example). 53
file systems
[root@rhel4 ~]# tune2fs -m10 /dev/sda1 tune2fs 1.35 (28-Feb-2004) Setting reserved blocks percentage to 10 (10430 blocks) [root@rhel4 ~]# tune2fs -l /dev/sda1 | grep -i "block count" Block count: 104388 Reserved block count: 10430 [root@rhel4 ~]#
The last column in /etc/fstab is used to determine whether a file system should be checked at boot-up.
[paul@RHEL4b ~]$ grep ext /etc/fstab /dev/VolGroup00/LogVol00 / LABEL=/boot /boot [paul@RHEL4b ~]$ ext3 ext3 defaults defaults 1 1 1 2
But after unmounting fsck and e2fsck can be used to check an ext2 file system.
[root@RHEL4b ~]# fsck /boot fsck 1.35 (28-Feb-2004) e2fsck 1.35 (28-Feb-2004) /boot: clean, 44/26104 files, 17598/104388 blocks [root@RHEL4b ~]# fsck -p /boot fsck 1.35 (28-Feb-2004) /boot: clean, 44/26104 files, 17598/104388 blocks [root@RHEL4b ~]# e2fsck -p /dev/sda1 /boot: clean, 44/26104 files, 17598/104388 blocks
54
file systems
55
file systems
3. Create an ext3 filesystem on the 400MB partition and one of the 300MB logical drives.
mke2fs -j /dev/sdb1 (replace sdb1 with the correct partition) mke2fs -j /dev/sdb5 (replace sdb5 with the correct partition)
4. Set the reserved space for root on the logical drive to 0 percent.
tune2fs -m 0 /dev/sdb5
56
Chapter 7. mounting
Table of Contents
7.1. 7.2. 7.3. 7.4. 7.5. 7.6. mounting local file systems ........................................................................... displaying mounted file systems .................................................................... permanent mounts .......................................................................................... securing mounts ............................................................................................. practice: mounting file systems ..................................................................... solution: mounting file systems ..................................................................... 58 59 60 61 63 64
Once you've put a file system on a partition, you can mount it. Mounting a file system makes it available for use, usually as a directory. We say mounting a file system instead of mounting a partition because we will see later that we can also mount file systems that do not exists on partitions.
57
mounting
/bin/mkdir
This example shows how to create a new mount point with mkdir.
root@RHELv4u2:~# mkdir /home/project55
/bin/mount
When the mount point is created, and a file system is present on the partition, then mount can mount the file system on the mount point directory.
root@RHELv4u2:~# mount -t ext2 /dev/sdb1 /home/project55/
/etc/filesystems
Actually the explicit -t ext2 option to set the file system is not always necessary. The mount command is able to automatically detect a lot of file systems. When mounting a file system without specifying explicitly the file system, then mount will first probe /etc/filesystems. Mount will skip lines with the nodev directive.
paul@RHELv4u4:~$ cat /etc/filesystems ext3 ext2 nodev proc nodev devpts iso9660 vfat hfs paul@RHELv4u4:~$
/proc/filesystems
When /etc/filesystems does not exist, or ends with a single * on the last line, then mount will read /proc/filesystems. 58
mounting
/bin/umount
You can unmount a mounted file system using the umount command.
root@pasha:~# umount /home/reet
/bin/mount
The simplest and most common way to view all mounts is by issuing the mount command without any arguments.
root@RHELv4u2:~# mount | grep /dev/sdb /dev/sdb1 on /home/project55 type ext2 (rw)
/proc/mounts
The kernel provides the info in /proc/mounts in file form, but /proc/mounts does not exist as a file on any hard disk. Looking at /proc/mounts is looking at information that comes directly from the kernel.
root@RHELv4u2:~# cat /proc/mounts | grep /dev/sdb /dev/sdb1 /home/project55 ext2 rw 0 0
/etc/mtab
The /etc/mtab file is not updated by the kernel, but is maintained by the mount command. Do not edit /etc/mtab manually.
root@RHELv4u2:~# cat /etc/mtab | grep /dev/sdb /dev/sdb1 /home/project55 ext2 rw 0 0
59
mounting
/bin/df
A more user friendly way to look at mounted file systems is df. The df (diskfree) command has the added benefit of showing you the free space on each mounted disk. Like a lot of Linux commands, df supports the -h switch to make the output more human readable.
root@RHELv4u2:~# df Filesystem 1K-blocks Used Available Use% Mounted on /dev/mapper/VolGroup00-LogVol00 11707972 6366996 4746240 58% / /dev/sda1 101086 9300 86567 10% /boot none 127988 0 127988 0% /dev/shm /dev/sdb1 108865 1550 101694 2% /home/project55 root@RHELv4u2:~# df -h Filesystem Size Used Avail Use% Mounted on /dev/mapper/VolGroup00-LogVol00 12G 6.1G 4.6G 58% / /dev/sda1 99M 9.1M 85M 10% /boot none 125M 0 125M 0% /dev/shm /dev/sdb1 107M 1.6M 100M 2% /home/project55
In the df -h example below you can see the size, free space, used gigabytes and percentage and mount point of a partition.
root@laika:~# df -h | egrep -e "(sdb2|File)" Filesystem Size Used Avail Use% Mounted on /dev/sdb2 92G 83G 8.6G 91% /media/sdb2 root@laika:~#
/bin/du
The du command can summarize disk usage for files and directories. Preventing du to go into subdirectories with the -s option will give you a total for that directory. This option is often used together with -h, so du -sh on a mount point gives the total amount used in that partition.
root@pasha:~# du -sh /home/reet 881G /home/reet
/etc/fstab
This is done using the file system table located in the /etc/fstab file. Below is a sample /etc/fstab file. 60
mounting
root@RHELv4u2:~# cat /etc/fstab /dev/VolGroup00/LogVol00 / LABEL=/boot /boot none /dev/pts none /dev/shm none /proc none /sys /dev/VolGroup00/LogVol01 swap
1 1 0 0 0 0 0
1 2 0 0 0 0 0
By adding the following line, we can automate the mounting of a file system.
/dev/sdb1 /home/project55 ext2 defaults 0 0
mount /mountpoint
Adding an entry to /etc/fstab has the added advantage that you can simplify the mount command. The command in the screenshot below forces mount to look for the partition info in /etc/fstab.
# mount /home/project55
ro
The ro option will mount a file system as read only, preventing anyone from writing.
root@rhel53 ~# mount -t ext2 -o ro /dev/hdb1 /home/project42 root@rhel53 ~# touch /home/project42/testwrite touch: cannot touch `/home/project42/testwrite': Read-only file system
noexec
The noexec option will prevent the execution of binaries and scripts on the mounted file system.
root@rhel53 ~# mount -t ext2 -o noexec /dev/hdb1 /home/project42 root@rhel53 ~# cp /bin/cat /home/project42 root@rhel53 ~# /home/project42/cat /etc/hosts -bash: /home/project42/cat: Permission denied root@rhel53 ~# echo echo hello > /home/project42/helloscript root@rhel53 ~# chmod +x /home/project42/helloscript root@rhel53 ~# /home/project42/helloscript -bash: /home/project42/helloscript: Permission denied
61
mounting
nosuid
The nosuid option will ignore setuid bit set binaries on the mounted file system. Note that you can still set the setuid bit on files.
root@rhel53 ~# mount -o nosuid /dev/hdb1 /home/project42 root@rhel53 ~# cp /bin/sleep /home/project42/ root@rhel53 ~# chmod 4555 /home/project42/sleep root@rhel53 ~# ls -l /home/project42/sleep -r-sr-xr-x 1 root root 19564 Jun 24 17:57 /home/project42/sleep
noacl
To prevent cluttering permissions with acl's, use the noacl option.
root@rhel53 ~# mount -o noacl /dev/hdb1 /home/project42
62
mounting
63
mounting
2. Mount the big 400MB primary partition on /mnt, the copy some files to it (everything in /etc). Then umount, and mount the file system as read only on /srv/ nfs/salesnumbers. Where are the files you copied ?
mount /dev/sdb1 /mnt cp -r /etc /mnt ls -l /mnt umount /mnt ls -l /mnt mkdir -p /srv/nfs/salesnumbers mount /dev/sdb1 /srv/nfs/salesnumbers You see the files in /srv/nfs/salenumbers now... But physically they are on ext3 on partition /dev/sdb1
3. Verify your work with fdisk, df and mount. Also look in /etc/mtab and /proc/ mounts.
fdisk -l df -h mount All three the above commands should show your mounted partitions. grep project22 /etc/mtab grep project22 /proc/mounts
5. What happens when you mount a file system on a directory that contains some files ?
The files are hidden until umount.
6. What happens when you mount two file systems on the same mount point ?
Only the last mounted fs is visible.
7. (optional) Describe the difference between these file searching commands: find, locate, updatedb, whereis, apropos and which.
man is your friend
8. (optional) Perform a file system check on the partition mounted at /srv/nfs/ salesnumbers. 64
mounting
better to unmount first before # fsck /dev/sdb1
65
66
introduction to uuid's
/sbin/vol_id
Below we use the vol_id utility to display the uuid of an ext3 file system.
root@laika:~# vol_id --uuid /dev/sda1 825d4b79-ec40-4390-8a71-9261df8d4c82
/lib/udev/vol_id
Red Hat Enterprise Linux 5 puts vol_id in /lib/udev/vol_id, which is not in the $PATH. The syntax is also a bit different from Debian/Ubuntu.
root@rhel53 ~# /lib/udev/vol_id -u /dev/hda1 48a6a316-9ca9-4214-b5c6-e7b33a77e860
/sbin/tune2fs
We can also use tune2fs to find the uuid of a file system.
[root@RHEL5 ~]# tune2fs -l /dev/sda1 | grep UUID Filesystem UUID: 11cfc8bc-07c0-4c3f-9f64-78422ef1dd5c [root@RHEL5 ~]# /lib/udev/vol_id -u /dev/sda1 11cfc8bc-07c0-4c3f-9f64-78422ef1dd5c
Then we check that it is properly added to /etc/fstab, the uuid replaces the variable devicename /dev/sdc1. 67
introduction to uuid's
Now we can mount the volume using the mount point defined in /etc/fstab.
[root@RHEL5 ~]# mount /home/pro42 [root@RHEL5 ~]# df -h | grep 42 /dev/sdc1 397M 11M 366M
3% /home/pro42
The real test now, is to remove /dev/sdb from the system, reboot the machine and see what happens. After the reboot, the disk previously known as /dev/sdc is now / dev/sdb.
[root@RHEL5 ~]# tune2fs -l /dev/sdb1 | grep UUID Filesystem UUID: 7626d73a-2bb6-4937-90ca-e451025d64e8
And thanks to the uuid in /etc/fstab, the mountpoint is mounted on the same disk as before.
[root@RHEL5 ~]# df -h | grep sdb /dev/sdb1 397M 11M
366M
3% /home/pro42
The screenshot above contains only four lines. The line starting with root= is the continuation of the kernel line.
68
introduction to uuid's
69
introduction to uuid's
2. Use this uuid in /etc/fstab and test that it works with a simple mount.
tail -1 /etc/fstab UUID=60926898-2c78-49b4-a71d-c1d6310c87cc /home/pro42 ext3 defaults 0 0
3. (optional) Test it also by removing a disk (so the device name is changed). You can edit settings in vmware/Virtualbox to remove a hard disk. 4. Display the root= directive in /boot/grub/menu.lst. (We see later in the course how to maintain this file.)
paul@deb503:~$ grep ^[^#] /boot/grub/menu.lst | grep root= kernel /boot/vmlinuz-2.6.26-2-686 root=/dev/hda1 ro selinux=1 quiet kernel /boot/vmlinuz-2.6.26-2-686 root=/dev/hda1 ro selinux=1 single
5. (optional) Replace the /dev/xxx in /boot/grub/menu.lst with a uuid (use an extra stanza for this). Test that it works.
70
71
introduction to raid
jbod
jbod uses two or more disks, and is often called concatenating (spanning, spanned set, or spanned volume). Data is written to the first disk, until it is full. Then data is written to the second disk... The main advantage of jbod (Just a Bunch of Disks) is that you can create larger drives. JBOD offers no redundancy.
raid 1
raid 1 uses exactly two disks, and is often called mirroring (or mirror set, or mirrored volume). All data written to the array is written on each disk. The main advantage of raid 1 is redundancy. The main disadvantage is that you lose at least half of your available disk space (in other words, you at least double the cost).
raid 2, 3 and 4 ?
raid 2 uses bit level striping, raid 3 byte level, and raid 4 is the same as raid 5, but with a dedicated parity disk. This is actually slower than raid 5, because every write would have to write parity to this one (bottleneck) disk. It is unlikely that you will ever see these raid levels in production.
raid 5
raid 5 uses three or more disks, each divided into chunks. Every time chunks are written to the array, one of the disks will receive a parity chunk. Unlike raid 4, the parity chunk will alternate between all disks. The main advantage of this is that raid 5 will allow for full data recovery in case of one hard disk failure.
raid 6
raid 6 is very similar to raid 5, but uses two parity chunks. raid 6 protects against two hard disk failures. Oracle Solaris zfs calls this raidz2 (and also had raidz3 with triple parity). 72
introduction to raid
raid 0+1
raid 0+1 is a mirror(1) of stripes(0). This means you first create two raid 0 stripe sets, and then you set them up as a mirror set. For example, when you have six 100GB disks, then the stripe sets are each 300GB. Combined in a mirror, this makes 300GB total. raid 0+1 will survive one disk failure. It will only survive the second disk failure if this disk is in the same stripe set as the previous failed disk.
raid 1+0
raid 1+0 is a stripe(0) of mirrors(1). For example, when you have six 100GB disks, then you first create three mirrors of 100GB each. You then stripe them together into a 300GB drive. In this example, as long as not all disks in the same mirror fail, it can survive up to three hard disk failures.
raid 50
raid 5+0 is a stripe(0) of raid 5 arrays. Suppose you have nine disks of 100GB, then you can create three raid 5 arrays of 200GB each. You can then combine them into one large stripe set.
many others
There are many other nested raid combinations, like raid 30, 51, 60, 100, 150, ...
73
introduction to raid
fd partition type
The next step is to create a partition of type fd on every disk. The fd type is to set the partition as Linux RAID autodetect. See this (truncated) screenshot:
[root@rhel6c ~]# fdisk /dev/sdd ... Command (m for help): n Command action e extended p primary partition (1-4) p Partition number (1-4): 1 First cylinder (1-1044, default 1): Using default value 1 Last cylinder, +cylinders or +size{K,M,G} (1-1044, default 1044): Using default value 1044 Command (m for help): t Selected partition 1 Hex code (type L to list codes): fd Changed system type of partition 1 to fd (Linux raid autodetect) Command (m for help): w The partition table has been altered! Calling ioctl() to re-read partition table. Syncing disks.
74
introduction to raid
We could use this software raid 5 array in the next topic: lvm.
/proc/mdstat
The status of the raid devices can be seen in /proc/mdstat. This example shows a raid 5 in the process of rebuilding.
[root@rhel6c ~]# cat /proc/mdstat Personalities : [raid6] [raid5] [raid4] md0 : active raid5 sdd1[3] sdc1[1] sdb1[0] 16769664 blocks super 1.2 level 5, 64k chunk, algorithm 2 [3/2] [UU_] [============>........] recovery = 62.8% (5266176/8384832) finish=0\ .3min speed=139200K/sec
mdadm --detail
Use mdadm --detail to get information on a raid device.
[root@rhel6c ~]# mdadm --detail /dev/md0 /dev/md0: Version : 1.2 Creation Time : Sun Jul 17 13:48:41 2011
75
introduction to raid
Raid Level Array Size Used Dev Size Raid Devices Total Devices Persistence Update Time State Active Devices Working Devices Failed Devices Spare Devices : : : : : : : : : : : : raid5 16769664 (15.99 GiB 17.17 GB) 8384832 (8.00 GiB 8.59 GB) 3 3 Superblock is persistent Sun Jul 17 13:49:43 2011 clean 3 3 0 0
Layout : left-symmetric Chunk Size : 64K Name : rhel6c:0 (local to host rhel6c) UUID : c10fd9c3:08f9a25f:be913027:999c8e1f Events : 18 Number 0 1 3 Major 8 8 8 Minor 17 33 49 RaidDevice 0 1 2 State active sync active sync active sync
76
introduction to raid
77
introduction to raid
78
79
In the example above, consider the options when you want to enlarge the space available for /project42. What can you do ? The solution will always force you to unmount the filesystem, take a backup of the data, remove and recreate partitions, and then restore the data and remount the file system.
about lvm
Most lvm implementations support physical storage grouping, logical volume resizing and data migration. Physical storage grouping is a fancy name for grouping multiple physical devices (hard disks) into a logical mass storage device. To enlarge this physical group, hard disks or even single partitions can be added at a later time. The size of lvm volumes on this physical group is independent of the individual size of the components. The total size of the group is the limit. 80
logical volume management One of the nicest features of lvm is the logical volume resizing. You can increase the size of an lvm volume, sometimes even without any downtime. Additionally, you can migrate data away from a failing hard disk device.
81
Note for home users: lvm will work fine when using the complete disk, but another operating system on the same computer will not recognize lvm and will mark the disk as being empty! You can avoid this by creating a partition that spans the whole disk, then run pvcreate on the partition instead of the disk. Then vgcreate creates a volume group using one device. Note that more devices could be added to the volume group.
root@RHEL4:~# vgcreate vg /dev/sdc Volume group "vg" successfully created
The logical volume /dev/vg/lvol0 can now be formatted with ext2, and mounted for normal use.
root@RHELv4u2:~# mke2fs -m0 -j /dev/vg/lvol0 mke2fs 1.35 (28-Feb-2004) Filesystem label= OS type: Linux Block size=1024 (log=0) Fragment size=1024 (log=0) 128016 inodes, 512000 blocks 0 blocks (0.00%) reserved for the super user First data block=1 Maximum filesystem blocks=67633152 63 block groups 8192 blocks per group, 8192 fragments per group 2032 inodes per group Superblock backups stored on blocks: 8193, 24577, 40961, 57345, 73729, 204801, 221185, 401409 Writing inode tables: done Creating journal (8192 blocks): done Writing superblocks and filesystem accounting information: done
82
This filesystem will be automatically checked every 37 mounts or 180 days, whichever comes first. Use tune2fs -c or -i to override. root@RHELv4u2:~# mkdir /home/project10 root@RHELv4u2:~# mount /dev/vg/lvol0 /home/project10/ root@RHELv4u2:~# df -h | grep proj /dev/mapper/vg-lvol0 485M 11M 474M 3% /home/project10
A logical volume is very similar to a partition, it can be formatted with a file system, and can be mounted so users can access it.
83
You already know how to partition a disk, below the first disk is partitioned (in one big primary partition), the second disk is left untouched.
[root@RHEL5 ~]# fdisk -l | grep sd[bc] Disk /dev/sdc doesn't contain a valid partition table Disk /dev/sdb: 1181 MB, 1181115904 bytes /dev/sdb1 1 143 1148616 83 Disk /dev/sdc: 429 MB, 429496320 bytes
Linux
You also know how to prepare disks for lvm with pvcreate, and how to create a volume group with vgcreate. This example adds both the partitioned disk and the untouched disk to the volume group named vg2.
[root@RHEL5 ~]# pvcreate /dev/sdb1 Physical volume "/dev/sdb1" successfully created [root@RHEL5 ~]# pvcreate /dev/sdc Physical volume "/dev/sdc" successfully created [root@RHEL5 ~]# vgcreate vg2 /dev/sdb1 /dev/sdc Volume group "vg2" successfully created
You can use pvdisplay to verify that both the disk and the partition belong to the volume group.
[root@RHEL5 ~]# pvdisplay | grep -B1 vg2 PV Name /dev/sdb1 VG Name vg2 -PV Name /dev/sdc VG Name vg2
And you are familiar both with the lvcreate command to create a small logical volume and the mke2fs command to put ext2 on it.
84
As you see, we end up with a mounted logical volume that according to df is almost 200 megabyte in size.
[root@RHEL5 ~]# mkdir /home/resizetest [root@RHEL5 ~]# mount /dev/vg2/lvol0 /home/resizetest/ [root@RHEL5 ~]# df -h | grep resizetest 194M 5.6M 149M 4% /home/resizetest
But as you can see, there is a small problem: it appears that df is not able to display the extended volume in its full size. This is because the filesystem is only set for the size of the volume before the extension was added.
[root@RHEL5 ~]# df -h | grep resizetest 194M 5.6M 149M
4% /home/resizetest
With lvdisplay however we can see that the volume is indeed extended.
[root@RHEL5 ~]# lvdisplay /dev/vg2/lvol0 | grep Size LV Size 300.00 MB
To finish the extension, you need resize2fs to span the filesystem over the full size of the logical volume.
[root@RHEL5 ~]# resize2fs /dev/vg2/lvol0 resize2fs 1.39 (29-May-2006) Filesystem at /dev/vg2/lvol0 is mounted on /home/resizetest; on-line re\ sizing required Performing an on-line resize of /dev/vg2/lvol0 to 307200 (1k) blocks. The filesystem on /dev/vg2/lvol0 is now 307200 blocks long.
3% /home/resizetest
85
83
Linux
Now we can use pvcreate to create the Physical Volume, followed by pvs to verify the creation.
[root@RHEL5 ~]# pvcreate /dev/sde1 Physical volume "/dev/sde1" successfully created [root@RHEL5 ~]# pvs | grep sde1 /dev/sde1 lvm2 -99.98M 99.98M [root@RHEL5 ~]#
The next step is ti use fdisk to enlarge the partition (actually deleting it and then recreating /dev/sde1 with more cylinders).
[root@RHEL5 ~]# fdisk /dev/sde Command (m for help): p Disk /dev/sde: 858 MB, 858993152 bytes 64 heads, 32 sectors/track, 819 cylinders Units = cylinders of 2048 * 512 = 1048576 bytes Device Boot /dev/sde1 Start 1 End 100 Blocks 102384 Id 83 System Linux
Command (m for help): d Selected partition 1 Command (m for help): n Command action e extended p primary partition (1-4) p Partition number (1-4): Value out of range. Partition number (1-4): 1 First cylinder (1-819, default 1): Using default value 1 Last cylinder or +size or +sizeM or +sizeK (1-819, default 819): 200 Command (m for help): w The partition table has been altered! Calling ioctl() to re-read partition table. Syncing disks. [root@RHEL5 ~]#
86
logical volume management When we now use fdisk and pvs to verify the size of the partition and the Physical Volume, then there is a size difference. LVM is still using the old size.
[root@RHEL5 ~]# fdisk -l 2>/dev/null | grep sde1 /dev/sde1 1 200 204784 [root@RHEL5 ~]# pvs | grep sde1 /dev/sde1 lvm2 -99.98M 99.98M [root@RHEL5 ~]#
83
Linux
Executing pvresize on the Physical Volume will make lvm aware of the size change of the partition. The correct size can be displayed with pvs.
[root@RHEL5 ~]# pvresize /dev/sde1 Physical volume "/dev/sde1" changed 1 physical volume(s) resized / 0 physical volume(s) not resized [root@RHEL5 ~]# pvs | grep sde1 /dev/sde1 lvm2 -199.98M 199.98M [root@RHEL5 ~]#
87
Then we create the Volume Group and verify again with pvs. Notice how the three physical volumes now belong to vg33, and how the size is rounded down (in steps of the extent size, here 4MB).
[root@RHEL5 ~]# vgcreate vg33 /dev/sdb /dev/sdc /dev/sdd Volume group "vg33" successfully created [root@RHEL5 ~]# pvs PV VG Fmt Attr PSize PFree /dev/sda2 VolGroup00 lvm2 a15.88G 0 /dev/sdb vg33 lvm2 a408.00M 408.00M /dev/sdc vg33 lvm2 a408.00M 408.00M /dev/sdd vg33 lvm2 a408.00M 408.00M [root@RHEL5 ~]#
The last step is to create the Logical Volume with lvcreate. Notice the -m 1 switch to create one mirror. Notice also the change in free space in all three Physical Volumes!
[root@RHEL5 ~]# lvcreate --size 300m -n lvmir -m 1 vg33 Logical volume "lvmir" created [root@RHEL5 ~]# pvs PV VG Fmt Attr PSize PFree /dev/sda2 VolGroup00 lvm2 a15.88G 0 /dev/sdb vg33 lvm2 a408.00M 108.00M /dev/sdc vg33 lvm2 a408.00M 108.00M /dev/sdd vg33 lvm2 a408.00M 404.00M
You can see the copy status of the mirror with lvs. It currently shows a 100 percent copy.
[root@RHEL5 ~]# lvs vg33/lvmir LV VG Attr LSize Origin Snap% lvmir vg33 mwi-ao 300.00M
88
You can see with lvs that the snapshot snapLV is indeed a snapshot of bigLV. Moments after taking the snapshot, there are few changes to bigLV (0.02 percent).
[root@RHEL5 ~]# lvs LV VG bigLV vg42 snapLV vg42 [root@RHEL5 ~]#
Attr LSize Origin Snap% Move Log Copy% owi-a- 200.00M swi-a- 100.00M bigLV 0.02
But after using bigLV for a while, more changes are done. This means the snapshot volume has to keep more original data (10.22 percent).
[root@RHEL5 ~]# lvs | grep vg42 bigLV vg42 owi-ao 200.00M snapLV vg42 swi-a- 100.00M bigLV [root@RHEL5 ~]#
10.22
You can now use regular backup tools (dump, tar, cpio, ...) to take a backup of the snapshot Logical Volume. This backup will contain all data as it existed on bigLV at the time the snapshot was taken. When the backup is done, you can remove the snapshot.
[root@RHEL5 ~]# lvremove vg42/snapLV Do you really want to remove active logical volume "snapLV"? [y/n]: y Logical volume "snapLV" successfully removed [root@RHEL5 ~]#
89
pvs
The easiest way to verify whether devices are known to lvm is with the pvs command. The screenshot below shows that only /dev/sda2 is currently known for use with LVM. It shows that /dev/sda2 is part of Volgroup00 and is almost 16GB in size. It also shows /dev/sdc and /dev/sdd as part of vg33. The device /dev/sdb is knwon to lvm, but not linked to any Volume Group.
[root@RHEL5 ~]# pvs PV VG /dev/sda2 VolGroup00 /dev/sdb /dev/sdc vg33 /dev/sdd vg33 [root@RHEL5 ~]#
Attr a-aa-
pvscan
The pvscan command will scan all disks for existing Physical Volumes. The information is similar to pvs, plus you get a line with total sizes.
[root@RHEL5 ~]# pvscan PV /dev/sdc VG vg33 lvm2 [408.00 MB / 408.00 MB free] PV /dev/sdd VG vg33 lvm2 [408.00 MB / 408.00 MB free] PV /dev/sda2 VG VolGroup00 lvm2 [15.88 GB / 0 free] PV /dev/sdb lvm2 [409.60 MB] Total: 4 [17.07 GB] / in use: 3 [16.67 GB] / in no VG: 1 [409.60 MB] [root@RHEL5 ~]#
90
pvdisplay
Use pvdisplay to get more information about physical volumes. You can also use pvdisplay without an argument to display information about all physical (lvm) volumes.
[root@RHEL5 ~]# pvdisplay /dev/sda2 --- Physical volume --PV Name /dev/sda2 VG Name VolGroup00 PV Size 15.90 GB / not usable 20.79 MB Allocatable yes (but full) PE Size (KByte) 32768 Total PE 508 Free PE 0 Allocated PE 508 PV UUID TobYfp-Ggg0-Rf8r-xtLd-5XgN-RSPc-8vkTHD [root@RHEL5 ~]#
91
vgscan
The vgscan command will scan all disks for existing Volume Groups. It will also update the /etc/lvm/.cache file. This file contains a list of all current lvm devices.
[root@RHEL5 ~]# vgscan Reading all physical volumes. This may take a while... Found volume group "VolGroup00" using metadata type lvm2 [root@RHEL5 ~]#
LVM will run the vgscan automatically at boot-up, so if you add hot swap devices, then you will need to run vgscan to update /etc/lvm/.cache with the new devices.
vgdisplay
The vgdisplay command will give you more detailed information about a volume group (or about all volume groups if you omit the argument).
[root@RHEL5 ~]# vgdisplay VolGroup00 --- Volume group --VG Name VolGroup00 System ID Format lvm2 Metadata Areas 1 Metadata Sequence No 3 VG Access read/write VG Status resizable MAX LV 0 Cur LV 2 Open LV 2 Max PV 0 Cur PV 1 Act PV 1 VG Size 15.88 GB PE Size 32.00 MB Total PE 508
92
93
lvscan
The lvscan command will scan all disks for existing Logical Volumes.
[root@RHEL5 ~]# lvscan ACTIVE '/dev/VolGroup00/LogVol00' [14.88 GB] inherit ACTIVE '/dev/VolGroup00/LogVol01' [1.00 GB] inherit [root@RHEL5 ~]#
lvdisplay
More detailed information about logical volumes is available through the lvdisplay(1) command.
[root@RHEL5 ~]# lvdisplay VolGroup00/LogVol01 --- Logical volume --LV Name /dev/VolGroup00/LogVol01 VG Name VolGroup00 LV UUID RnTGK6-xWsi-t530-ksJx-7cax-co5c-A1KlDp LV Write Access read/write LV Status available # open 1 LV Size 1.00 GB Current LE 32 Segments 1 Allocation inherit Read ahead sectors 0 Block device 253:1 [root@RHEL5 ~]#
94
You can also add multiple disks or partitions as target to pvcreate. This example adds three disks to lvm.
[root@RHEL5 ~]# pvcreate /dev/sde /dev/sdf /dev/sdg Physical volume "/dev/sde" successfully created Physical volume "/dev/sdf" successfully created Physical volume "/dev/sdg" successfully created [root@RHEL5 ~]#
pvremove
Use the pvremove command to remove physical volumes from lvm. The devices may not be in use.
[root@RHEL5 Labels on Labels on Labels on [root@RHEL5 ~]# pvremove /dev/sde /dev/sdf /dev/sdg physical volume "/dev/sde" successfully wiped physical volume "/dev/sdf" successfully wiped physical volume "/dev/sdg" successfully wiped ~]#
pvresize
When you used fdisk to resize a partition on a disk, then you must use pvresize to make lvm recognize the new size of the physical volume that represents this partition.
[root@RHEL5 ~]# pvresize /dev/sde1 Physical volume "/dev/sde1" changed 1 physical volume(s) resized / 0 physical volume(s) not resized
95
pvchange
With pvchange you can prevent the allocation of a Physical Volume in a new Volume Group or Logical Volume. This can be useful if you plan to remove a Physical Volume.
[root@RHEL5 ~]# pvchange -xn /dev/sdd Physical volume "/dev/sdd" changed 1 physical volume changed / 0 physical volumes not changed [root@RHEL5 ~]#
To revert your previous decision, this example shows you how te re-enable the Physical Volume to allow allocation.
[root@RHEL5 ~]# pvchange -xy /dev/sdd Physical volume "/dev/sdd" changed 1 physical volume changed / 0 physical volumes not changed [root@RHEL5 ~]#
pvmove
With pvmove you can move Logical Volumes from within a Volume Group to another Physical Volume. This must be done before removing a Physical Volume.
[root@RHEL5 /dev/sdf /dev/sdg [root@RHEL5 /dev/sdf: /dev/sdf: [root@RHEL5 /dev/sdf /dev/sdg ~]# pvs | grep vg1 vg1 lvm2 avg1 lvm2 a~]# pvmove /dev/sdf Moved: 70.1% Moved: 100.0% ~]# pvs | grep vg1 vg1 lvm2 avg1 lvm2 a-
96
vgextend
Use the vgextend command to extend an existing volume group with a physical volume.
[root@RHEL5 ~]# vgextend vg42 /dev/sdg Volume group "vg42" successfully extended [root@RHEL5 ~]#
vgremove
Use the vgremove command to remove volume groups from lvm. The volume groups may not be in use.
[root@RHEL5 ~]# vgremove vg42 Volume group "vg42" successfully removed [root@RHEL5 ~]#
vgreduce
Use the vgreduce command to remove a Physical Volume from the Volume Group. The following example adds Physical Volume /dev/sdg to the vg1 Volume Group using vgextend. And then removes it again using vgreduce.
[root@RHEL5 ~]# pvs | grep sdg /dev/sdg lvm2 -819.20M 819.20M [root@RHEL5 ~]# vgextend vg1 /dev/sdg Volume group "vg1" successfully extended [root@RHEL5 ~]# pvs | grep sdg /dev/sdg vg1 lvm2 a816.00M 816.00M [root@RHEL5 ~]# vgreduce vg1 /dev/sdg Removed "/dev/sdg" from volume group "vg1" [root@RHEL5 ~]# pvs | grep sdg
97
vgchange
Use the vgchange command to change parameters of a Volume Group. This example shows how to prevent Physical Volumes from being added or removed to the Volume Group vg1.
[root@RHEL5 ~]# vgchange -xn vg1 Volume group "vg1" successfully changed [root@RHEL5 ~]# vgextend vg1 /dev/sdg Volume group vg1 is not resizable.
You can also use vgchange to change most other properties of a Volume Group. This example changes the maximum number of Logical Volumes and maximum number of Physical Volumes that vg1 can serve.
[root@RHEL5 ~]# vgdisplay vg1 | grep -i max MAX LV 0 Max PV 0 [root@RHEL5 ~]# vgchange -l16 vg1 Volume group "vg1" successfully changed [root@RHEL5 ~]# vgchange -p8 vg1 Volume group "vg1" successfully changed [root@RHEL5 ~]# vgdisplay vg1 | grep -i max MAX LV 16 Max PV 8
vgmerge
Merging two Volume Groups into one is done with vgmerge. The following example merges vg2 into vg1, keeping all the properties of vg1.
[root@RHEL5 ~]# vgmerge vg1 vg2 Volume group "vg2" successfully merged into "vg1" [root@RHEL5 ~]#
98
As you can see, lvm automatically names the Logical Volume lvol0. The next example creates a 200MB Logical Volume named MyLV in Volume Group vg42.
[root@RHEL5 ~]# lvcreate -L200M -nMyLV vg42 Logical volume "MyLV" created [root@RHEL5 ~]#
The next example does the same thing, but with different syntax.
[root@RHEL5 ~]# lvcreate --size 200M -n MyLV vg42 Logical volume "MyLV" created [root@RHEL5 ~]#
This example creates a Logical Volume that occupies 10 percent of the Volume Group.
[root@RHEL5 ~]# lvcreate -l 10%VG -n MyLV2 vg42 Logical volume "MyLV2" created [root@RHEL5 ~]#
This example creates a Logical Volume that occupies 30 percent of the remaining free space in the Volume Group.
[root@RHEL5 ~]# lvcreate -l 30%FREE -n MyLV3 vg42 Logical volume "MyLV3" created [root@RHEL5 ~]#
lvremove
Use the lvremove command to remove Logical Volumes from a Volume Group. Removing a Logical Volume requires the name of the Volume Group.
[root@RHEL5 ~]# lvremove vg42/MyLV
99
Removing multiple Logical Volumes will request confirmation for each individual volume.
[root@RHEL5 ~]# lvremove vg42/MyLV vg42/MyLV2 vg42/MyLV3 Do you really want to remove active logical volume "MyLV"? [y/n]: y Logical volume "MyLV" successfully removed Do you really want to remove active logical volume "MyLV2"? [y/n]: y Logical volume "MyLV2" successfully removed Do you really want to remove active logical volume "MyLV3"? [y/n]: y Logical volume "MyLV3" successfully removed [root@RHEL5 ~]#
lvextend
Extending the volume is easy with lvextend. This example extends a 200MB Logical Volume with 100 MB.
[root@RHEL5 ~]# lvdisplay /dev/vg2/lvol0 | grep Size LV Size 200.00 MB [root@RHEL5 ~]# lvextend -L +100 /dev/vg2/lvol0 Extending logical volume lvol0 to 300.00 MB Logical volume lvol0 successfully resized [root@RHEL5 ~]# lvdisplay /dev/vg2/lvol0 | grep Size LV Size 300.00 MB
The next example creates a 100MB Logical Volume, and then extends it to 500MB.
[root@RHEL5 ~]# lvcreate --size 100M -n extLV vg42 Logical volume "extLV" created [root@RHEL5 ~]# lvextend -L 500M vg42/extLV Extending logical volume extLV to 500.00 MB Logical volume extLV successfully resized [root@RHEL5 ~]#
lvrename
Renaming a Logical Volume is done with lvrename. This example renames extLV to bigLV in the vg42 Volume Group. 100
[root@RHEL5 ~]# lvrename vg42/extLV vg42/bigLV Renamed "extLV" to "bigLV" in volume group "vg42" [root@RHEL5 ~]#
101
102
This chapter teaches you how to setup an iSCSI target server and an iSCSI initiator client.
103
iSCSI devices
On Debian 6 you will also need aptitude install iscsitarget-dkms for the kernel modules, on Debian 5 this is aptitude install iscsitarget-modules-`uname -a`. Ubuntu includes the kernel modules in the main package. The iSCSI target server is disabled by default, so we enable it.
root@debby6:~# cat /etc/default/iscsitarget ISCSITARGET_ENABLE=false root@debby6:~# vi /etc/default/iscsitarget root@debby6:~# cat /etc/default/iscsitarget ISCSITARGET_ENABLE=true
104
iSCSI devices
We need to declare these three files as iSCSI targets in /etc/iet/ietd.conf (used to be / etc/ietd.conf).
root@debby6:/etc/iet# cp ietd.conf ietd.conf.original root@debby6:/etc/iet# > ietd.conf root@debby6:/etc/iet# vi ietd.conf root@debby6:/etc/iet# cat ietd.conf Target iqn.2010-02.be.linux-training:storage.lun1 IncomingUser isuser hunter2 OutgoingUser Lun 0 Path=/iscsi/lun1.img,Type=fileio Alias LUN1 Target iqn.2010-02.be.linux-training:storage.lun2 IncomingUser isuser hunter2 OutgoingUser Lun 0 Path=/iscsi/lun2.img,Type=fileio Alias LUN2 Target iqn.2010-02.be.linux-training:storage.lun3 IncomingUser isuser hunter2 OutgoingUser Lun 0 Path=/iscsi/lun3.img,Type=fileio Alias LUN3
105
iSCSI devices
. root@debby6:/etc/iet#
106
iSCSI devices
Now we can connect to the Target server and use iscsiadm to discover the devices it offers:
root@ubu1104:/etc/iscsi# iscsiadm -m discovery -t st -p 192.168.1.31 192.168.1.31:3260,1 iqn.2010-02.be.linux-training:storage.lun2 192.168.1.31:3260,1 iqn.2010-02.be.linux-training:storage.lun1 192.168.1.31:3260,1 iqn.2010-02.be.linux-training:storage.lun3
Repeat the above for the other two devices. Restart the initiator service to log in to the target.
root@ubu1104:/etc/iscsi/nodes# /etc/init.d/open-iscsi restart * Disconnecting iSCSI targets * Stopping iSCSI initiator service * Starting iSCSI initiator service iscsid * Setting up iSCSI targets [ OK ] [ OK ] [ OK ]
107
iSCSI devices
Disk Disk Disk Disk Disk Disk Disk identifier: 0x0001983f /dev/sdb: 209 MB, 209715200 bytes identifier: 0x00000000 /dev/sdd: 314 MB, 314572800 bytes identifier: 0x00000000 /dev/sdc: 104 MB, 104857600 bytes identifier: 0x00000000
108
iSCSI devices
109
iSCSI devices
110
iSCSI devices
Now start the iscsitarget daemon and move over to the Initiator. On the Initiator computer: Install open-iscsi and start the daemon. Then use iscsiadm -m discovery -t st -p 'target-ip' to see the iscsi devices on the Target. Edit the files /etc/iscsi/nodes/ as shown in the book. Then restart the iSCSI daemon and rund fdisk -l to see the iSCSI devices.
111
113
bootloader
post
A computer starts booting the moment you turn on the power (no kidding). This first process is called post or power on self test. If all goes well then this leads to the bios. If all goes not so well, then you might hear nothing, or hear beeping, or see an error message on the screen, or maybe see smoke coming out of the computer (burning hardware smells bad!).
bios
All Intel x86 computers will have a basic input/output system or bios to detect, identify and initialize hardware. The bios then goes looking for a boot device. This can be a floppy, hard disk, cdrom, network card or usb drive. During the bios you can see a message on the screen telling you which key (often Del or F2) to press to enter the bios setup.
114
bootloader
openboot
Sun sparc systems start with openboot to test the hardware and to boot the operating system. Bill Callkins explains openboot in his Solaris System Administration books. The details of openboot are not the focus of this course.
boot password
The bios allows you to set a password. Do not forget this password, or you will have to open up the hardware to reset it. You can sometimes set a password to boot the system, and another password to protect the bios from being modified.
boot device
The bios will look for a boot device in the order configured in the bios setup. Usually an operating system on a production server boots of a hard disk.
115
bootloader
bootloader
The mbr is executed by the bios and contains either (a small) bootloader or code to load a bootloader. Looking at the mbr with od can reveal information about the bootloader.
paul@laika:~$ sudo dd if=/dev/sda count=1 bs=16 skip=24 2>/dev/null|od -c 0000000 376 G R U B \0 G e o m \0 H a r d 0000020
There are a variety of bootloaders available, most common on Intel architecture is grub, which is replacing lilo in many places. When installing Linux on sparc architecture, you can choose silo, Itanium systems can use elilo, IBM S/390 and zSeries use z/IPL, Alpha uses milo and PowerPC architectures use yaboot (yet another boot loader). Bootable cd's and dvd's often use syslinux.
kernel
The goal of all this is to load an operating system, or rather the kernel of an operating system. A typical bootloader like grub will copy a kernel from hard disk to memory, and will then hand control of the computer to the kernel (execute the kernel). Once the Linux kernel is loaded, the bootloader turns control over to it. From that moment on, the kernel is in control of the system. After discussing bootloaders, we continue with the init system that starts all the daemons.
12.2. grub
about grub
The most common bootloader on linux systems today is grub. On almost all Intel based systems grub is replacing lilo (the Linux loader). Even Solaris switched to grub on x86 architecture. One of the big advantages of grub over lilo is the capability to change the configuration during boot (by pressing e to edit the boot command line).
/boot/grub/menu.lst
grub's configuration file is called menu.lst and is located in /boot/grub. The screenshot below show the location and size of menu.lst on Debian. 116
bootloader
/boot/grub/grub.conf
Some distributions like Red Hat Enterprise Linux 5 use grub.conf and provide a symbolic link to menu.lst. This is the same file, only the name changed from grub.conf to menu.lst. Notice also in this screenshot that this file is a lot smaller on Red Hat.
[root@RHEL52 grub]# ls -l grub.conf menu.lst -rw------- 1 root root 1346 Jan 21 04:20 grub.conf lrwxrwxrwx 1 root root 11 Oct 11 2008 menu.lst -> ./grub.conf
menu commands
The menu commands always have to be at the top of grub's configuration file.
default
The default command sets a default entry to start. The first entry has number 0.
default 0
fallback
In case the default does not boot, use the fallback entry instead.
fallback 1
timeout
The timeout will wait a number of seconds before booting the default entry.
timeout 5
hiddenmenu
The hiddenmenu will hide the grub menu unless the user presses Esc before the timeout expires. 117
bootloader
hiddenmenu
title
With title we can start a new entry or stanza.
title Debian Lenny
password
You can add a password to prevent interactive selection of a boot environment while grub is running.
password --md5 $1$Ec.id/$T2C2ahI/EG3WRRsmmu/HN/
stanza commands
Every operating system or kernel that you want to boot with grub will have a stanza aka an entry of a couple of lines. Listed here are some of the common stanza commands.
boot
Technically the boot command is only mandatory when running the grub command line. This command does not have any parameters and can only be set as the last command of a stanza.
boot
kernel
The kernel command points to the location of the kernel. To boot Linux this means booting a gzip compressed zImage or bzip2 compressed bzImage. This screenshot shows a typical kernel command used to load a Debian kernel. 118
bootloader
kernel
/boot/vmlinuz-2.6.17-2-686 root=/dev/hda1 ro
initrd
Many Linux installations will need an initial ramdisk at boot time. This can be set in grub with the initrd command. Here a screenshot of Debian 4.0
initrd /boot/initrd.img-2.6.17-2-686
root
The root command accepts the root device as a parameter. The root command will point to the hard disk and partition to use, with hd0 as the first hard disk device and hd1 as the second hard disk device. The same numbering is used for partitions, so hd0,0 is the first partition on the first disk and hd0,1 is the second partition on that disk.
root (hd0,0)
savedefault
The savedefault command can be used together with default saved as a menu command. This combination will set the currently booted stanza as the next default stanza to boot.
default saved timeout 10 title Linux root (hd0,0) kernel /boot/vmlinuz savedefault
119
bootloader
title DOS root (hd0,1) makeactive chainloader +1 savedefault
chainloading
With grub booting, there are two choices: loading an operating system or chainloading another bootloader. The chainloading feature of grub loads the bootsector of a partition (that contains an operating system). Some older operating systems require a primary partition that is set as active. Only one partition can be set active so grub can do this on the fly just before chainloading. This screenshot shows how to set the first primary partition active with grub.
root (hd0,0) makeactive
Chainloading refers to grub loading another operating system's bootloader. The chainloader switch receives one option: the number of sectors to read and boot. For DOS and OS/2 one sector is enough. Note that DOS requires the boot/root partition to be active! Here is a complete example to chainload an old operating system.
title MS-DOS 6.22 root (hd0,1) makeactive chainloader +1
stanza examples
This is a screenshot of a typical Debian 4.0 stanza.
title root kernel initrd Debian GNU/Linux, kernel 2.6.17-2-686 (hd0,0) /boot/vmlinuz-2.6.17-2-686 root=/dev/hda1 ro /boot/initrd.img-2.6.17-2-686
120
bootloader
installing grub
Run the grub-install command to install grub. The command requires a destination for overwriting the boot sector or mbr.
# grub-install /dev/hda
12.3. lilo
Linux loader
lilo used to be the most used Linux bootloader, but is steadily being replaced in x86 with grub.
lilo.conf
Here is an example of a typical lilo.conf file. The delay switch receives a number in tenths of a second. So the delay below is three seconds, not thirty!
boot = /dev/hda delay = 30 image = /boot/vmlinuz root = /dev/hda1 label = Red Hat 5.2 image = /boot/vmlinuz root = /dev/hda2 label = S.U.S.E. 8.0
121
bootloader
other = /dev/hda4 table = /dev/hda label = MS-DOS 6.22
The configration file shows three example stanzas. The first one boots Red Hat from the first partition on the first disk (hda1). The second stanza boots Suse 8.0 from the next partition. The last one loads MS-DOS.
122
bootloader
123
bootloader
Do not forget the initrd file ends in .img . 2. Add a stanza in grub for the 3.0 files. Make sure the title is different.
[root@RHEL5 ~]# grep 3.0 /boot/grub/menu.lst title Red Hat Enterprise Linux Server (3.0) kernel /vmlinuz-3.0 ro root=/dev/VolGroup00/LogVol00 rhgb quiet initrd /initrd-3.0.img
124
125
configuration in /etc/inittab
When /sbin/init is started, it will first read its configuration file /etc/inittab. In that file, it will look for the value of initdefault (3 in the screenshot below).
[paul@rhel4 ~]$ grep ^id /etc/inittab id:3:initdefault:
initdefault
The value found in initdefault indicates the default runlevel. Some Linux distributions have a brief description of runlevels in /etc/inittab, like here on Red Hat Enterprise Linux 4.
# 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 don't have network)
126
Runlevel 0 means the system is shutting down. Runlevel 1 is used for troubleshooting, only the root user can log on, and only at the console. Runlevel 3 is typical for servers, whereas runlevel 5 is typical for desktops (graphical logon). Besides runlevels 0, 1 and 6, the use may vary depending on the distribution. Debian and derived Linux systems have full network and GUI logon on runlevels 2 to 5. So always verify the proper meaning of runlevels on your system.
sysinit script
/etc/rc.d/rc.sysinit
The next line in /etc/inittab in Red Hat and derivatives is the following.
si::sysinit:/etc/rc.d/rc.sysinit
This means that independent of the selected runlevel, init will run the /etc/rc.d/ rc.sysinit script. This script initializes hardware, sets some basic environment, populates /etc/mtab while mounting file systems, starts swap and more.
[paul@rhel ~]$ egrep -e"^# Ini" -e"^# Sta" -e"^# Che" /etc/rc.d/rc.sysinit # Check SELinux status # Initialize hardware # Start the graphical boot, if necessary; /usr may not be mounted yet... # Initialiaze ACPI bits # Check filesystems # Start the graphical boot, if necessary and not done yet. # Check to see if SELinux requires a relabel # Initialize pseudo-random number generator # Start up swapping. # Initialize the serial ports.
That egrep command could also have been written with grep like this :
grep "^# \(Ini\|Sta\|Che\)".
/etc/init.d/rcS
Debian has the following line after initdefault.
si::sysinit:/etc/init.d/rcS
127
init and runlevels The /etc/init.d/rcS script will always run on Debian (independent of the selected runlevel). The script is actually running all scripts in the /etc/rcS.d/ directory in alphabetical order.
root@barry:~# cat /etc/init.d/rcS #! /bin/sh # # rcS # # Call all S??* scripts in /etc/rcS.d/ in numerical/alphabetical order # exec /etc/init.d/rc S
rc scripts
Init will continue to read /etc/inittab and meets this section on Debian Linux.
l0:0:wait:/etc/init.d/rc l1:1:wait:/etc/init.d/rc l2:2:wait:/etc/init.d/rc l3:3:wait:/etc/init.d/rc l4:4:wait:/etc/init.d/rc l5:5:wait:/etc/init.d/rc l6:6:wait:/etc/init.d/rc 0 1 2 3 4 5 6
In both cases, this means that init will start the rc script with the runlevel as the only parameter. Actually /etc/inittab has fields seperated by colons. The second field determines the runlevel in which this line should be executed. So in both cases, only one line of the seven will be executed, depending on the runlevel set by initdefault.
rc directories
When you take a look any of the /etc/rcX.d/ directories, then you will see a lot of (links to) scripts who's name start with either uppercase K or uppercase S.
[root@RHEL52 rc3.d]# ls -l | tail -4 lrwxrwxrwx 1 root root 19 Oct 11 2008 S98haldaemon -> ../init.d/haldaemon lrwxrwxrwx 1 root root 19 Oct 11 2008 S99firstboot -> ../init.d/firstboot
128
The /etc/rcX.d/ directories only contain links to scripts in /etc/init.d/. Links allow for the script to have a different name. When entering a runlevel, all scripts that start with uppercase K or uppercase S will be started in alphabetical order. Those that start with K will be started first, with stop as the only parameter. The remaining scripts with S will be started with start as the only parameter. All this is done by the /etc/rc.d/rc script on Red Hat and by the /etc/init.d/rc script on Debian.
mingetty
mingetty in /etc/inittab
Almost at the end of /etc/inittab there is a section to start and respawn several mingetty daemons.
[root@RHEL4b ~]# grep getty /etc/inittab # Run gettys in standard runlevels 1:2345:respawn:/sbin/mingetty tty1 2:2345:respawn:/sbin/mingetty tty2 3:2345:respawn:/sbin/mingetty tty3 4:2345:respawn:/sbin/mingetty tty4 5:2345:respawn:/sbin/mingetty tty5 6:2345:respawn:/sbin/mingetty tty6
respawning mingetty
The mingetty daemons are started by init and watched until they die (user exits the shell and is logged out). When this happens, the init daemon will respawn a new mingetty. So even if you kill a mingetty daemon, it will be restarted automatically. This example shows that init respawns mingetty daemons. Look at the PID's of the last two mingetty processes.
129
When we kill the last two mingettys, then init will notice this and start them again (with a different PID).
[root@RHEL52 ~]# kill 2411 2412 [root@RHEL52 ~]# ps -C mingetty PID TTY TIME CMD 2407 tty1 00:00:00 mingetty 2408 tty2 00:00:00 mingetty 2409 tty3 00:00:00 mingetty 2410 tty4 00:00:00 mingetty 2821 tty5 00:00:00 mingetty 2824 tty6 00:00:00 mingetty
disabling a mingetty
You can disable a mingetty for a certain tty by removing the runlevel from the second field in its line in /etc/inittab. Don't forget to tell init about the change of its configuration file with kill -1 1. The example below shows how to disable mingetty on tty3 to tty6 in runlevels 4 and 5.
[root@RHEL52 ~]# grep getty /etc/inittab # Run gettys in standard runlevels 1:2345:respawn:/sbin/mingetty tty1 2:2345:respawn:/sbin/mingetty tty2 3:23:respawn:/sbin/mingetty tty3 4:23:respawn:/sbin/mingetty tty4 5:23:respawn:/sbin/mingetty tty5 6:23:respawn:/sbin/mingetty tty6
init and runlevels misunderstanding. "Daemon" is actually a much older form of "demon"; daemons have no particular bias towards good or evil, but rather serve to help define a person's character or personality. The ancient Greeks' concept of a "personal daemon" was similar to the modern concept of a "guardian angel" ....
[ OK ] [ OK ]
You can achieve the same result on RHEL/Fedora with the service command.
[root@RHEL4b ~]# service smb restart Shutting down SMB services: Shutting down NMB services: Starting SMB services: Starting NMB services:
[ [ [ [
OK OK OK OK
] ] ] ]
13.5. chkconfig
The purpose of chkconfig is to relieve system administrators of manually managing all the links and scripts in /etc/init.d and /etc/rcX.d/.
chkconfig --list
Here we use chkconfig to list the status of a service in the different runlevels. You can see that the crond daemon (or service) is only activated in runlevels 2 to 5.
[root@RHEL52 ~]# chkconfig --list crond crond 0:off 1:off 2:on 3:on 4:on 5:on 6:off
When you compare the screenshot above with the one below, you can see that off equals to a K link to the script, whereas on equals to an S link.
131
runlevel configuration
Here you see how to use chkconfig to disable (or enable) a service in a certain runlevel. This screenshot shows how to disable crond in runlevel 3.
[root@RHEL52 ~]# chkconfig --level 3 crond off [root@RHEL52 ~]# chkconfig --list crond crond 0:off 1:off 2:on 3:off 4:on 5:on 6:off
chkconfig configuration
Every script in /etc/init.d/ can have (comment) lines to tell chkconfig what to do with the service. The line with # chkconfig: contains the runlevels in which the service should be started (2345), followed by the priority for start (90) and stop (60).
[root@RHEL52 ~]# head -9 /etc/init.d/crond | tail -5 # chkconfig: 2345 90 60 # description: cron is a standard UNIX program that runs user-specified # programs at periodic scheduled times. vixie cron adds a # number of features to the basic UNIX cron, including better # security and more powerful configuration options.
132
4:off
5:off
6:off
4:on
5:on
6:off
13.6. update-rc.d
about update-rc.d
The Debian equivalent of chkconfig is called update-rc.d. This tool is designed for use in scripts, if you prefer a graphical tool then look at bum. When there are existing links in /etc/rcX.d/ then update-rc.d does not do anything. This is to avoid that post installation scripts using update-rc.d are overwriting changes made by a system administrator.
root@barry:~# update-rc.d cron remove update-rc.d: /etc/init.d/cron exists during rc.d purge (use -f to force)
As you can see in the next screenshot, nothing changed for the cron daemon.
root@barry:~# find /etc/rc0.d/K11cron /etc/rc1.d/K11cron /etc/rc2.d/S89cron /etc/rc3.d/S89cron /etc/rc4.d/S89cron /etc/rc5.d/S89cron /etc/rc6.d/K11cron /etc/rc?.d/ -name '*cron' -exec ls -l {} \;|cut -b44-> ../init.d/cron -> ../init.d/cron -> ../init.d/cron -> ../init.d/cron -> ../init.d/cron -> ../init.d/cron -> ../init.d/cron
removing a service
Here we remove cron from all runlevels. Remember that the proper way to disable a service is to put K scripts oin all runlevels!
root@barry:~# update-rc.d -f cron remove Removing any system startup links for /etc/init.d/cron ... /etc/rc0.d/K11cron /etc/rc1.d/K11cron /etc/rc2.d/S89cron /etc/rc3.d/S89cron /etc/rc4.d/S89cron /etc/rc5.d/S89cron /etc/rc6.d/K11cron root@barry:~# find /etc/rc?.d/ -name '*cron' -exec ls -l {} \;|cut -b44root@barry:~#
133
enable a service
This screenshot shows how to use update-rc.d to enable a service in runlevels 2, 3, 4 and 5 and disable the service in runlevels 0, 1 and 6.
root@barry:~# update-rc.d cron defaults Adding system startup for /etc/init.d/cron ... /etc/rc0.d/K20cron -> ../init.d/cron /etc/rc1.d/K20cron -> ../init.d/cron /etc/rc6.d/K20cron -> ../init.d/cron /etc/rc2.d/S20cron -> ../init.d/cron /etc/rc3.d/S20cron -> ../init.d/cron /etc/rc4.d/S20cron -> ../init.d/cron /etc/rc5.d/S20cron -> ../init.d/cron
customize a service
And here is an example on how to set your custom configuration for the cron daemon.
root@barry:~# update-rc.d -n cron start 11 2 3 4 5 . stop 89 0 1 6 . Adding system startup for /etc/init.d/cron ... /etc/rc0.d/K89cron -> ../init.d/cron /etc/rc1.d/K89cron -> ../init.d/cron /etc/rc6.d/K89cron -> ../init.d/cron /etc/rc2.d/S11cron -> ../init.d/cron /etc/rc3.d/S11cron -> ../init.d/cron /etc/rc4.d/S11cron -> ../init.d/cron /etc/rc5.d/S11cron -> ../init.d/cron
13.7. bum
This screenshot shows bum in advanced mode.
134
13.8. runlevels
display the runlevel
You can see your current runlevel with the runlevel or who -r commands. The runlevel command is typical Linux and will output the previous and the current runlevel. If there was no previous runlevel, then it will mark it with the letter N.
[root@RHEL4b ~]# runlevel N 3
The history of who -r dates back to Seventies Unix, it still works on Linux.
[root@RHEL4b ~]# who -r run-level 3 Jul 28 09:15
last=S
/sbin/shutdown
The shutdown command is used to properly shut down a system. Common switches used with shutdown are -a, -t, -h and -r. The -a switch forces /sbin/shutdown to use /etc/shutdown.allow. The -t switch is used to define the number of seconds between the sending of the TERM signal and the KILL signal. The -h switch halts the system instead of changing to runlevel 1. The -r switch tells /sbin/shutdown to reboot after shutting down. This screenshot shows how to use shutdown with five seconds between TERM and KILL signals.
135
The now is the time argument. This can be +m for the number of minutes to wait before shutting down (with now as an alias for +0. The command will also accept hh:mm instead of +m.
/var/log/wtmp
halt, reboot and poweroff all write to /var/log/wtmp. To look at /var/log/wtmp, we need to use th last.
[root@RHEL52 ~]# last reboot system boot reboot system boot reboot system boot reboot system boot | grep reboot 2.6.18-128.el5 2.6.18-128.el5 2.6.18-128.el5 2.6.18-128.el5
Ctrl-Alt-Del
When rc is finished starting all those scripts, init will continue to read /etc/inittab. The next line is about what to do when the user hits Ctrl-Alt-Delete on the keyboard. Here is what Debian 4.0 does.
root@barry:~# grep -i ctrl /etc/inittab # What to do when CTRL-ALT-DEL is pressed. ca:12345:ctrlaltdel:/sbin/shutdown -t1 -a -r now
Which is very similar to the default Red Hat Enterprise Linux 5.2 action.
[root@RHEL52 ~]# grep -i ctrl /etc/inittab # Trap CTRL-ALT-DELETE ca::ctrlaltdel:/sbin/shutdown -t3 -r now
136
init and runlevels One noticable difference is that Debian forces shutdown to use /etc/shutdown.allow, where Red Hat allows everyone to invoke shutdown pressing Ctrl-Alt-Delete.
It will read commands on what to execute in case of powerfailure, powerok and Ctrl-Alt-Delete. The init process never stops keeping an eye on power failures and that triple key combo.
root@barry:~# grep ^p /etc/inittab pf::powerwait:/etc/init.d/powerfail start pn::powerfailnow:/etc/init.d/powerfail now po::powerokwait:/etc/init.d/powerfail stop
137
138
2. Use the Red Hat Enterprise Linux virtual machine. Go to runlevel 5, display the current and previous runlevel, then go back to runlevel 3.
init 5 (watch the console for the change taking place) runlevel init 3 (again you can follow this on the console)
3. Is the sysinit script on your computers setting or changing the PATH environment variable ? On Red Hat, grep for PATH in /etc/rc.sysinit, on Debian/Ubuntu check /etc/rc.local and /etc/ini.t/rc.local. The answer is probably no, but on RHEL5 the rc.sysinit script does set the HOSTNAME variable.
[root@RHEL5 etc]# grep HOSTNAME rc.sysinit
5. Write a script that acts like a daemon script in /etc/init.d/. It should have a case statement to act on start/stop/restart and status. Test the script! The script could look something like this.
#!/bin/bash # # chkconfig: 345 99 01 # description: pold demo script # # /etc/init.d/pold
139
The touch /var/lock/subsys/pold is mandatory and must be the same filename as the script name, if you want the stop sequence (the K01pold link) to be run. 6. Use chkconfig to setup your script to start in runlevels 3,4 and 5, and to stop in any other runlevel.
chkconfig --add pold
The command above will only work when the # chkconfig: and # description: lines in the pold script are there.
140
Linux administrators use the at to schedule one time jobs. Recurring jobs are better scheduled with cron. The next two sections will discuss both tools.
142
scheduling
In real life you will hopefully be scheduling more useful commands ;-)
atq
It is easy to check when jobs are scheduled with the atq or at -l commands.
root@laika:~# atq 1 Wed Aug 1 22:01:00 2 Wed Aug 1 22:03:00 root@laika:~# at -l 1 Wed Aug 1 22:01:00 2 Wed Aug 1 22:03:00 root@laika:~#
The at command understands English words like tomorrow and teatime to schedule commands the next day and at four in the afternoon.
root@laika:~# at 10:05 tomorrow at> sleep 100 at> <EOT> job 5 at Thu Aug 2 10:05:00 2007 root@laika:~# at teatime tomorrow at> tea at> <EOT> job 6 at Thu Aug 2 16:00:00 2007 root@laika:~# atq 6 Thu Aug 2 16:00:00 2007 a root 5 Thu Aug 2 10:05:00 2007 a root root@laika:~#
atrm
Jobs in the at queue can be removed with atrm. 143
scheduling
root@laika:~# atq 6 Thu Aug 2 5 Thu Aug 2 root@laika:~# atrm root@laika:~# atq 6 Thu Aug 2 root@laika:~#
144
scheduling
14.2. cron
crontab file
The crontab(1) command can be used to maintain the crontab(5) file. Each user can have their own crontab file to schedule jobs at a specific time. This time can be specified with five fields in this order: minute, hour, day of the month, month and day of the week. If a field contains an asterisk (*), then this means all values of that field. The following example means : run script42 eight minutes after two, every day of the month, every month and every day of the week.
8 14 * * * script42
Run script8472 every month on the first of the month at 25 past midnight.
25 0 1 * * script8472
Run this script33 every two minutes on Sunday (both 0 and 7 refer to Sunday).
*/2 * * * 0
Instead of these five fields, you can also type one of these: @reboot, @yearly or @annually, @monthly, @weekly, @daily or @midnight, and @hourly.
crontab command
Users should not edit the crontab file directly, instead they should type crontab -e which will use the editor defined in the EDITOR or VISUAL environment variable. Users can display their cron table with crontab -l.
/etc/crontab
The /etc/crontab file contains entries for when to run hourly/daily/weekly/monthly tasks. It will look similar to this output.
145
scheduling
SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin 20 3 * * * 40 3 * * 7 55 3 1 * * root root root run-parts --report /etc/cron.daily run-parts --report /etc/cron.weekly run-parts --report /etc/cron.monthly
/etc/cron.*
The directories shown in the next screenshot contain the tasks that are run at the times scheduled in /etc/crontab. The /etc/cron.d directory is for special cases, to schedule jobs that require finer control than hourly/daily/weekly/monthly.
paul@laika:~$ ls -ld /etc/cron.* drwxr-xr-x 2 root root 4096 2008-04-11 drwxr-xr-x 2 root root 4096 2008-04-19 drwxr-xr-x 2 root root 4096 2008-04-11 drwxr-xr-x 2 root root 4096 2008-04-11 drwxr-xr-x 2 root root 4096 2008-04-11
146
scheduling
147
scheduling
2. As normal user, use crontab -e to schedule a script to run every four minutes.
paul@rhel55 ~$ crontab -e no crontab for paul - using an empty one crontab: installing new crontab
5. Take a look at the cron files and directories in /etc and understand them. What is the run-parts command doing ?
run-parts runs a script in a directory
148
This chapter has three distinct subjects. First we look at login logging ; how can we find out who is logging in to the system, when and from where. And who is not logging in, who fails at su or ssh. Second we discuss how to configure the syslog daemon, and how to test it with logger. The last part is mostly about rotating logs and mentions the tail -f and watch commands for watching logs.
149
logging
/var/run/utmp (who)
Use the who command to see the /var/run/utmp file. This command is showing you all the currently logged in users. Notice that the utmp file is in /var/run and not in / var/log .
[root@rhel4 ~]# who paul pts/1 sandra pts/2 inge pts/3 els pts/4
14 14 14 14
/var/log/wtmp (last)
The /var/log/wtmp file is updated by the login program. Use last to see the /var/ run/wtmp file.
[root@rhel4a ~]# last | head paul pts/1 192.168.1.45 reboot system boot 2.6.9-42.0.8.ELs nicolas pts/5 pc-dss.telematic stefaan pts/3 pc-sde.telematic nicolas pts/3 pc-nae.telematic nicolas pts/3 pc-nae.telematic dirk pts/5 pc-dss.telematic nicolas pts/3 pc-nae.telematic dimitri pts/5 rhel4 stefaan pts/4 pc-sde.telematic [root@rhel4a ~]#
Wed Wed Wed Wed Wed Wed Wed Wed Wed Wed
Feb Feb Feb Feb Feb Feb Feb Feb Feb Feb
14 14 14 14 14 14 14 14 14 14
18:39 18:21 12:32 12:28 11:36 11:34 10:03 09:45 07:57 07:16
still logged in (01:15) 13:06 (00:33) 12:40 (00:12) 12:21 (00:45) 11:36 (00:01) 12:31 (02:28) 11:34 (01:48) 08:38 (00:40) down (05:50)
The last command can also be used to get a list of last reboots.
[paul@rekkie ~]$ last reboot reboot system boot 2.6.16-rekkie wtmp begins Tue May 30 23:11:45 2006 [paul@rekkie ~]$
(370+08:42)
/var/log/lastlog (lastlog)
Use lastlog to see the /var/log/lastlog file. 150
logging
[root@rhel4a ~]# lastlog | tail tim pts/5 10.170.1.122 rm pts/6 rhel4 henk stefaan pts/3 pc-sde.telematic dirk pts/5 pc-dss.telematic arsene nicolas pts/5 pc-dss.telematic dimitri pts/5 rhel4 bashuserrm pts/7 rhel4 kornuserrm pts/5 rhel4 [root@rhel4a ~]#
Tue Feb Tue Feb **Never Wed Feb Wed Feb **Never Wed Feb Wed Feb Tue Feb Tue Feb
13 09:36:54 13 10:06:56 logged in** 14 12:28:38 14 10:03:11 logged in** 14 12:32:18 14 07:57:19 13 10:35:40 13 10:06:17
+0100 2007 +0100 2007 +0100 2007 +0100 2007 +0100 +0100 +0100 +0100 2007 2007 2007 2007
/var/log/btmp (lastb)
There is also the lastb command to display the /var/log/btmp file. This file is updated by the login program when entering the wrong password, so it contains failed login attempts. Many computers will not have this file, resulting in no logging of failed login attempts.
[root@RHEL4b ~]# lastb lastb: /var/log/btmp: No such file or directory Perhaps this file was removed by the operator to prevent logging lastb\ info. [root@RHEL4b ~]#
The reason given for this is that users sometimes type their password by mistake instead of their login, so this world readable file poses a security risk. You can enable bad login logging by simply creating the file. Doing a chmod o-r /var/log/ btmp improves security.
[root@RHEL4b ~]# touch /var/log/btmp [root@RHEL4b ~]# ll /var/log/btmp -rw-r--r-- 1 root root 0 Jul 30 06:12 /var/log/btmp [root@RHEL4b ~]# chmod o-r /var/log/btmp [root@RHEL4b ~]# lastb btmp begins Mon Jul 30 06:12:19 2007 [root@RHEL4b ~]#
Failed logins via ssh, rlogin or su are not registered in /var/log/btmp. Failed logins via tty are.
[root@RHEL4b ~]# lastb HalvarFl tty3 Maria tty1 Roberto tty1
Mon Jul 30 07:10 - 07:10 Mon Jul 30 07:09 - 07:09 Mon Jul 30 07:09 - 07:09
151
logging
You can enable this yourself, with a custom log file by adding the following line tot syslog.conf.
auth.*,authpriv.* /var/log/customsec.log
152
logging
15.2. syslogd
about syslog
The standard method of logging on Linux is through the syslogd daemon. Syslog was developed by Eric Allman for sendmail, but quickly became a standard among many Unix applications and was much later written as rfc 3164. The syslog daemon can receive messages on udp port 514 from many applications (and appliances), and can append to log files, print, display messages on terminals and forward logs to other syslogd daemons on other machines. The syslogd daemon is configured in / etc/syslog.conf. Each line in the configuration file uses a facility to determine where the message is coming from. It also contains a level for the severity of the message, and an action to decide on what to do with the message.
facilities
The man syslog.conf will explain the different default facilities for certain daemons, such as mail, lpr, news and kern(el) messages. The local0 to local7 facility can be used for appliances (or any networked device that supports syslog). Here is a list of all facilities for syslog.conf version 1.3. The security keyword is deprecated.
auth (security) authpriv cron daemon ftp kern lpr mail mark (internal use only) news syslog user uucp local0-7
levels
The worst severity a message can have is emerg followed by alert and crit. Lowest priority should go to info and debug messages. Specifying a severity will also log all messages with a higher severity. You can prefix the severity with = to obtain only messages that match that severity. You can also specify .none to prevent a specific action from any message from a certain facility. Here is a list of all levels, in ascending order. The keywords warn, error and panic are deprecated. 153
logging
debug info notice warning (warn) err (error) crit alert emerg (panic)
actions
The default action is to send a message to the username listed as action. When the action is prefixed with a / then syslog will send the message to the file (which can be a regular file, but also a printer or terminal). The @ sign prefix will send the message on to another syslog server. Here is a list of all possible actions.
root,user1 * / -/ | @ list of users, separated by comma's message to all logged on users file (can be a printer, a console, a tty, ...) file, but don't sync after every write named pipe other syslog hostname
In addition, you can prefix actions with a - to omit syncing the file after every logging.
configuration
Below a sample configuration of custom local4 messages in /etc/syslog.conf.
local4.crit local4.=crit local4.* /var/log/critandabove /var/log/onlycrit /var/log/alllocal4
[ [ [ [
OK OK OK OK
] ] ] ]
154
logging
15.3. logger
The logger command can be used to generate syslog test messages. You can aslo use it in scripts. An example of testing syslogd with the logger tool.
[root@rhel4a [root@rhel4a [root@rhel4a [root@rhel4a ~]# logger -p local4.debug "l4 debug" ~]# logger -p local4.crit "l4 crit" ~]# logger -p local4.emerg "l4 emerg" ~]#
You can automatically repeat commands by preceding them with the watch command. When executing the following:
[root@rhel6 ~]# watch who
Something similar to this, repeating the output of the who command every two seconds, will appear on the screen.
Every 2.0s: who root paul paul tty1 pts/0 pts/1 Sun Jul 17 15:31:03 2011 2011-07-17 13:28 2011-07-17 13:31 (192.168.1.30) 2011-07-17 15:19 (192.168.1.30)
155
logging
And this screenshot is the resolt of the above configuration, for the logfile from aptitude.
paul@ubu1010:/var/log$ ls -l -rw-r--r-- 1 root root 18298 -rw-r--r-- 1 root root 8163 -rw-r--r-- 1 root root 8163 -rw-r--r-- 1 root root 8163 /var/log/aptitude* 2011-07-17 13:32 /var/log/aptitude 2011-07-01 01:43 /var/log/aptitude.1.gz 2011-06-01 01:43 /var/log/aptitude.2.gz 2011-05-01 01:43 /var/log/aptitude.3.gz
156
logging
157
logging
4. Examine syslog to find the location of the log file containing ssh failed logins.
root@rhel53 ~# grep authpriv /etc/syslog.conf authpriv.* /var/log/secure
Debian/Ubuntu: /var/log/auth.log
5. Configure syslog to put local4.error and above messages in /var/log/l4e.log and local4.info only .info in /var/log/l4i.log. Test that it works with the logger tool!
echo local4.error /var/log/l4e.log >> /etc/syslog.conf echo local4.=info /var/log/l4i.log >> /etc/syslog.conf /etc/init.d/syslog restart logger -p local4.error "l4 error test" logger -p local4.alert "l4 alert test" logger -p local4.info "l4 info test" cat /var/log/l4e.log cat /var/log/l4i.log
6. Configure /var/log/Mysu.log, all the su to root messages should go in that log. Test that it works!
echo authpriv.* /var/log/Mysu.log >> /etc/syslog.conf
logging 7. Send the local5 messages to the syslog server of your neighbour. Test that it works. On RHEL5, edit /etc/sysconfig/syslog to enable remote listening on the server. On Debian/Ubuntu edit /etc/default/syslog or /etc/default/rsyslog.
on the client: logger -p local5.info "test local5 to neighbour"
8. Write a script that executes logger to local4 every 15 seconds (different message). Use tail -f and watch on your local4 log files.
root@rhel53 scripts# cat logloop #!/bin/bash for i in `seq 1 10` do logger -p local4.info "local4.info test number $i" sleep 15 done
root@rhel53 scripts# chmod +x logloop root@rhel53 scripts# ./logloop & [1] 8264 root@rhel53 scripts# tail -f /var/log/local4.all.log Mar 28 13:13:36 rhel53 root: local4.info test number 1 Mar 28 13:13:51 rhel53 root: local4.info test number 2 ...
159
This chapter will tell you how to manage RAM memory and cache. We start with some simple tools to display information about memory: free -om, top and cat /proc/meminfo. We continue with managing swap space, using terms like swapping, paging and virtual memory. The last part is about using vmstat to monitor swap usage.
160
memory management
The first line contains the total amount of physical RAM, the second line is the unused RAM. Buffers is RAM used for buffering files, cached is the amount of RAM used as cache and SwapCached is the amount of swap used as cache. The file gives us much more information outside of the scope of this course.
free
The free tool can display the information provided by /proc/meminfo in a more readable format. The example below displays brief memory information in megabytes.
paul@ubu1010:~$ free -om total used Mem: 3740 3519 Swap: 6234 82 free 221 6152 shared 0 buffers 42 cached 1994
top
The top tool is often used to look at processes consuming most of the cpu, but it also displays memory information on line four and five (which can be toggled by pressing m). Below a screenshot of top on the same ubu1010 from above.
top - 10:44:34 up 16 days, 9:56, 6 users, load average: 0.13, 0.09, 0.12 Tasks: 166 total, 1 running, 165 sleeping, 0 stopped, 0 zombie Cpu(s): 5.1%us, 4.6%sy, 0.6%ni, 88.7%id, 0.8%wa, 0.0%hi, 0.3%si, 0.0%st Mem: 3830176k total, 3613720k used, 216456k free, 45452k buffers Swap: 6384636k total, 84988k used, 6299648k free, 2050948k cached
161
memory management
Size 6384636
Used 84988
Priority -1
The amount of swap space that you need depends heavily on the services that the computer provides.
83
Linux
Now you can see that /proc/swaps displays all swap spaces separately, whereas the free -om command only makes a human readable summary.
root@RHELv4u4:~# cat /proc/swaps Filename /dev/mapper/VolGroup00-LogVol01 /dev/hda1 root@RHELv4u4:~# free -om total used free Mem: 249 245 4 Swap: 1535 0 1535 Type partition partition shared 0 Size Used 1048568 0 524120 0 buffers 125 cached 54 Priority -1 -2
memory management
root@RHELv4u4:~# dd if=/dev/zero of=/smallswapfile bs=1024 count=4096 4096+0 records in 4096+0 records out root@RHELv4u4:~# mkswap /smallswapfile Setting up swapspace version 1, size = 4190 kB root@RHELv4u4:~# swapon /smallswapfile root@RHELv4u4:~# cat /proc/swaps Filename Type Size Used Priority /dev/mapper/VolGroup00-LogVol01 partition 1048568 0 -1 /dev/hda1 partition 524120 0 -2 /smallswapfile file 4088 0 -3
163
memory management
Below a sample vmstat when (in another terminal) root launches a find /. It generates a lot of disk i/o (bi and bo are disk blocks in and out). There is no need for swapping here.
paul@ubu1010:~$ vmstat 2 100 procs ----------memory---------- ---swap-- -----io---- -system-- ----cpu---r b swpd free buff cache si so bi bo in cs us sy id wa 0 0 84984 1999436 53416 269536 0 0 2 5 2 10 6 5 89 1 0 0 84984 1999428 53416 269564 0 0 0 0 1713 2748 4 4 92 0 0 0 84984 1999552 53416 269564 0 0 0 0 1672 1838 4 6 90 0 0 0 84984 1999552 53424 269560 0 0 0 14 1587 2526 5 7 87 2 0 0 84984 1999180 53424 269580 0 0 0 100 1748 2193 4 6 91 0 1 0 84984 1997800 54508 269760 0 0 610 0 1836 3890 17 10 68 4 1 0 84984 1994620 55040 269748 0 0 250 168 1724 4365 19 17 56 9 0 1 84984 1978508 55292 269704 0 0 126 0 1957 2897 19 18 58 4 0 0 84984 1974608 58964 269784 0 0 1826 478 2605 4355 7 7 44 41 0 2 84984 1971260 62268 269728 0 0 1634 756 2257 3865 7 7 47 39
Below a sample vmstat when executing (on RHEL6) a simple memory leaking program. Now you see a lot of memory being swapped (si is 'swapped in').
[paul@rhel6c ~]$ vmstat 2 100 procs r b 0 3 0 2 1 3 1 4 0 4 3 5 ----------memory-------swpd free buff cache 245208 5280 232 1916 263372 4800 72 908 350672 4792 56 992 449584 4788 56 1024 471968 4828 56 1140 505960 4764 56 1136 ---swap-- ----io---- --system-- -----cpu----si so bi bo in cs us sy id wa st 261 0 0 42 27 21 0 1 98 1 0 143840 128 0 1138 462 191 2 10 0 88 0 169280 256 0 1092 360 142 1 13 0 86 0 95880 64 0 606 471 191 2 13 0 85 0 44832 80 0 390 235 90 2 12 0 87 0 68008 16 0 538 286 109 1 12 0 87 0
The code below was used to simulate a memory leak (and force swapping). This code was found on wikipedia without author.
paul@mac:~$ cat memleak.c #include <stdlib.h> int main(void) { while (malloc(50)); return 0; }
164
memory management
165
memory management
3. On a virtual machine, create a swap partition (you might need an extra virtual disk for this).
mkswap /dev/sdd1 ; swapon /dev/sdd1
5. Put all swap spaces in /etc/fstab and activate them. Test with a reboot that they are mounted.
root@computer# tail -2 /etc/fstab /dev/sdd1 swap swap defaults 0 0 /swapfile20mb swap swap defaults 0 0
7. (optional) Display the usage of swap with vmstat and free -s during a memory leak.
166
Most Linux distributions have a package management system with online repositories containing thousands of packages. This makes it very easy to install and remove applications, operating system components, documentation and much more. We discuss the two most used package formats .rpm and .deb and their respective tools. We also briefly discuss the option of obtaining software from outside the repository.
167
package management
17.1. terminology
repository
A lot of software and documentation for your Linux distribution is available as packages in one or more centrally distributed repositories. These packages in such a repository are tested and very easy to install (or remove) with a graphical or command line installer.
.deb packages
Debian, Ubuntu, Mint and all derivatives from Debian and Ubuntu use .deb packages. To manage software on these systems, you can use aptitude or apt-get, both these tools are a front end for dpkg.
.rpm packages
Red Hat, Fedora, CentOS, OpenSUSE, Mandriva, Red Flag and others use .rpm packages. The tools to manage software packages on these systems are yum and rpm.
dependency
Some packages need other packages to function. Tools like apt-get, aptitude and yum will install all dependencies you need. When using dpkg or rpm, or when building from source, you will need to install dependencies yourself.
open source
These repositories contain a lot of independent open source software. Often the source code is customized to integrate better with your distribution. Most distributions also offer this modified source code as a package in one or more source repositories. You are free to go to the project website itself (samba.org, apache.org, github.com, ...) an download the vanilla (= without the custom distribution changes) source code.
168
package management
169
package management
17.2. deb
about deb
Most people use aptitude or apt-get to manage their Debian/Ubuntu family of Linux distributions. Both are a front end for dpkg and are themselves a back end for synaptic and other graphical tools.
dpkg -l
The low level tool to work with .deb packages is dpkg. Here you see how to obtain a list of all installed packages on a Debian server.
root@debian6:~# dpkg -l | wc -l 265
dpkg -l $package
Here is an example on how to get information on an individual packaga. The ii at the beginning means the package is installed.
root@debian6:~# dpkg -l rsync | tail -1 | tr -s ' ' ii rsync 3.0.7-2 fast remote file copy program (like rcp)
dpkg
You could use dpkg -i to install a package and dpkg -r to remove a package, but you'd have to manually keep track of dependencies. Using apt-get or aptitude is much easier.
170
package management
17.3. apt-get
Debian has been using apt-get to manage packages since 1998. Today Debian and many Debian-based distributions still actively support apt-get, though some experts claim aptitude is better at handling dependencies than apt-get. Both commands use the same configuration files and can be used alternately; whenever you see apt-get in documentation, feel free to type aptitude. We will start with apt-get and discuss aptitude in the next section.
apt-get update
When typing apt-get update you are downloading the names, versions and short description of all packages available on all configured repositories for your system. In the example below you can see some repositories at the url be.archive.ubuntu.com because this computer was installed in Belgium. This url can be different for you.
root@ubu1204~# apt-get update Ign http://be.archive.ubuntu.com precise InRelease Ign http://extras.ubuntu.com precise InRelease Ign http://security.ubuntu.com precise-security InRelease Ign http://archive.canonical.com precise InRelease Ign http://be.archive.ubuntu.com precise-updates InRelease ... Hit http://be.archive.ubuntu.com precise-backports/main Translation-en Hit http://be.archive.ubuntu.com precise-backports/multiverse Translation-en Hit http://be.archive.ubuntu.com precise-backports/restricted Translation-en Hit http://be.archive.ubuntu.com precise-backports/universe Translation-en Fetched 13.7 MB in 8s (1682 kB/s) Reading package lists... Done root@mac~#
Run apt-get update every time before performing other package operations.
apt-get upgrade
One of the nicest features of apt-get is that it allows for a secure update of all software currently installed on your computer with just one command.
root@debian6:~# apt-get upgrade Reading package lists... Done Building dependency tree Reading state information... Done 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. root@debian6:~#
The above screenshot shows that all software is updated to the latest version available for my distribution. 171
package management
apt-get clean
apt-get keeps a copy of downloaded packages in /var/cache/apt/archives, as can be seen in this screenshot.
root@ubu1204~# ls /var/cache/apt/archives/ | head accountsservice_0.6.15-2ubuntu9.4_i386.deb apport_2.0.1-0ubuntu14_all.deb apport-gtk_2.0.1-0ubuntu14_all.deb apt_0.8.16~exp12ubuntu10.3_i386.deb apt-transport-https_0.8.16~exp12ubuntu10.3_i386.deb apt-utils_0.8.16~exp12ubuntu10.3_i386.deb bind9-host_1%3a9.8.1.dfsg.P1-4ubuntu0.4_i386.deb chromium-browser_20.0.1132.47~r144678-0ubuntu0.12.04.1_i386.deb chromium-browser-l10n_20.0.1132.47~r144678-0ubuntu0.12.04.1_all.deb chromium-codecs-ffmpeg_20.0.1132.47~r144678-0ubuntu0.12.04.1_i386.deb
Running apt-get clean removes all .deb files from that directory.
root@ubu1204~# apt-get clean root@ubu1204~# ls /var/cache/apt/archives/*.deb ls: cannot access /var/cache/apt/archives/*.deb: No such file or directory
apt-cache search
Use apt-cache search to search for availability of a package. Here we look for rsync.
root@ubu1204~# apt-cache search rsync | grep ^rsync rsync - fast, versatile, remote (and local) file-copying tool rsyncrypto - rsync friendly encryption
apt-get install
You can install one or more applications by appending their name behind apt-get install. The screenshot shows how to install the rsync package.
root@ubu1204~# apt-get install rsync Reading package lists... Done Building dependency tree Reading state information... Done The following NEW packages will be installed: rsync 0 upgraded, 1 newly installed, 0 to remove and 8 not upgraded. Need to get 299 kB of archives. After this operation, 634 kB of additional disk space will be used. Get:1 http://be.archive.ubuntu.com/ubuntu/ precise/main rsync i386 3.0.9-1ubuntu1 [299 k Fetched 299 kB in 0s (740 kB/s) Selecting previously unselected package rsync. (Reading database ... 323649 files and directories currently installed.) Unpacking rsync (from .../rsync_3.0.9-1ubuntu1_i386.deb) ... Processing triggers for man-db ... Processing triggers for ureadahead ... Setting up rsync (3.0.9-1ubuntu1) ... Removing any system startup links for /etc/init.d/rsync ... root@ubu1204~#
172
package management
apt-get remove
You can remove one or more applications by appending their name behind apt-get remove. The screenshot shows how to remove the rsync package.
root@ubu1204~# apt-get remove rsync Reading package lists... Done Building dependency tree Reading state information... Done The following packages will be REMOVED: rsync ubuntu-standard 0 upgraded, 0 newly installed, 2 to remove and 8 not upgraded. After this operation, 692 kB disk space will be freed. Do you want to continue [Y/n]? (Reading database ... 323681 files and directories currently installed.) Removing ubuntu-standard ... Removing rsync ... * Stopping rsync daemon rsync Processing triggers for ureadahead ... Processing triggers for man-db ... root@ubu1204~#
apt-get purge
You can purge one or more applications by appending their name behind aptget purge. Purging will also remove all existing configuration files related to that application. The screenshot shows how to purge the rsync package.
root@ubu1204~# apt-get purge rsync Reading package lists... Done Building dependency tree Reading state information... Done The following packages will be REMOVED: rsync* 0 upgraded, 0 newly installed, 1 to remove and 8 not upgraded. After this operation, 0 B of additional disk space will be used. Do you want to continue [Y/n]? (Reading database ... 323651 files and directories currently installed.) Removing rsync ... Purging configuration files for rsync ... Processing triggers for ureadahead ... root@ubu1204~#
Note that dpkg has no information about a purged package, except that it is uninstalled and no configuration is left on the system.
root@ubu1204~# dpkg -l rsync | tail -1 | tr -s ' ' un rsync <none> (no description available)
173
package management
17.4. aptitude
Most people use aptitude for package management on Debian, Mint and Ubuntu systems. To synchronize with the repositories.
aptitude update
To patch and upgrade all software to the latest version on Ubuntu and Mint.
aptitude safe-upgrade
To search the repositories for applications that contain a certain string in their name or description.
aptitude search $string
To remove an application.
aptitude remove $package
174
package management
17.5. apt
Both apt-get and aptitude use the same configuration information in /etc/apt/. Thus adding a repository for one of them, will automatically add it for both.
/etc/apt/sources.list
The resource list used by apt-get and aptitude is located in /etc/apt/sources.list. This file contains a list of http or ftp sources where packages for the distribution can be downloaded. This is what that list looks like on my Debian server.
root@debian6:~# cat /etc/apt/sources.list deb http://ftp.be.debian.org/debian/ squeeze main deb-src http://ftp.be.debian.org/debian/ squeeze main deb http://security.debian.org/ squeeze/updates main deb-src http://security.debian.org/ squeeze/updates main # squeeze-updates, previously known as 'volatile' deb http://ftp.be.debian.org/debian/ squeeze-updates main deb-src http://ftp.be.debian.org/debian/ squeeze-updates main
There is much more to learn about apt, explore commands like add-apt-repository, apt-key and apropos apt.
175
package management
17.6. rpm
about rpm
The Red Hat package manager can be used on the command line with rpm or in a graphical way going to Applications--System Settings--Add/Remove Applications. Type rpm --help to see some of the options. Software distributed in the rpm format will be named foo-version.platform.rpm .
rpm -qa
To obtain a list of all installed software, use the rpm -qa command.
[root@RHEL52 ~]# rpm -qa | grep samba system-config-samba-1.2.39-1.el5 samba-3.0.28-1.el5_2.1 samba-client-3.0.28-1.el5_2.1 samba-common-3.0.28-1.el5_2.1
rpm -q
To verify whether one package is installed, use rpm -q.
root@RHELv4u4:~# rpm -q gcc gcc-3.4.6-3 root@RHELv4u4:~# rpm -q laika package laika is not installed
rpm -q --redhatprovides
To check whether a package is provided by Red Hat, use the --redhatprovides option.
root@RHELv4u4:~# rpm -q --redhatprovides bash bash-3.0-19.3 root@RHELv4u4:~# rpm -q --redhatprovides gcc gcc-3.4.6-3 root@RHELv4u4:~# rpm -q --redhatprovides laika no package provides laika
rpm -Uvh
To install or upgrade a package, use the -Uvh switches. The -U switch is the same as -i for install, except that older versions of the software are removed. The -vh switches are for nicer output. 176
package management
rpm -e
To remove a package, use the -e switch.
root@RHELv4u4:~# rpm -e gcc-3.4.6-3
rpm -e verifies dependencies, and thus will prevent you from accidentailly erasing packages that are needed by other packages.
[root@RHEL52 ~]# rpm -e gcc-4.1.2-42.el5 error: Failed dependencies: gcc = 4.1.2-42.el5 is needed by (installed) gcc-c++-4.1.2-42.el5.i386 gcc = 4.1.2-42.el5 is needed by (installed) gcc-gfortran-4.1.2-42.el5.i386 gcc is needed by (installed) systemtap-0.6.2-1.el5_2.2.i386
/var/lib/rpm
The rpm database is located at /var/lib/rpm. This database contains all meta information about packages that are installed (via rpm). It keeps track of all files, which enables complete removes of software.
rpm2cpio
We can use rpm2cpio to convert an rpm to a cpio archive.
[root@RHEL53 ~]# file kernel.src.rpm kernel.src.rpm: RPM v3 src PowerPC kernel-2.6.18-92.1.13.el5 [root@RHEL53 ~]# rpm2cpio kernel.src.rpm > kernel.cpio [root@RHEL53 ~]# file kernel.cpio kernel.cpio: ASCII cpio archive (SVR4 with no CRC)
But why would you want to do this ? Perhaps just to see of list of files in the rpm file.
[root@RHEL53 ~]# rpm2cpio kernel.src.rpm | cpio -t | head -5 COPYING.modules Config.mk Module.kabi_i686 Module.kabi_i686PAE Module.kabi_i686xen
177
package management
178
package management
17.7. yum
about yum
The Yellowdog Updater, Modified (yum) is an easier command to work with rpm packages. It is installed by default on Fedora and Red Hat Enterprise Linux since version 5.2.
yum list
Issue yum list available to see a list of available packages. The available parameter is optional.
[root@rhel55 ~]# yum list | wc -l 2471
Issue yum list $package to get all versions (in different repositories) of one package.
[root@rhel55 ~]# yum list samba Loaded plugins: rhnplugin, security Installed Packages samba.i386 3.0.33-3.28.el5 Available Packages samba.i386 3.0.33-3.29.el5_5
installed rhel-i386-server-5
yum search
To search for a package containing a certain string in the description or name use yum search $string.
[root@rhel55 ~]# yum search gcc44 Loaded plugins: rhnplugin, security ========================== Matched: gcc44 =========================== gcc44.i386 : Preview of GCC version 4.4 gcc44-c++.i386 : C++ support for GCC version 4.4 gcc44-gfortran.i386 : Fortran support for GCC 4.4 previe
yum provides
To search for a package containing a certain file (you might need for compiling things) use yum provides $filename.
[root@rhel55 ~]# yum provides /usr/share/man/man1/gzip.1.gz Loaded plugins: rhnplugin, security Importing additional filelist information gzip-1.3.5-9.el5.i386 : The GNU data compression program. Repo : rhel-i386-server-5 Matched from: Filename : /usr/share/man/man1/gzip.1.gz ...
179
package management
yum install
To install an application, use yum install $package. Naturally yum will install all the necessary dependencies.
[root@rhel55 ~]# yum install sudo Loaded plugins: rhnplugin, security Setting up Install Process Resolving Dependencies --> Running transaction check ---> Package sudo.i386 0:1.7.2p1-7.el5_5 set to be updated --> Finished Dependency Resolution Dependencies Resolved ======================================================================= Package Arch Version Repository Size ======================================================================= Installing: sudo i386 1.7.2p1-7.el5_5 rhel-i386-server-5 230 k Transaction Summary ======================================================================= Install 1 Package(s) Upgrade 0 Package(s) Total download size: 230 k Is this ok [y/N]: y Downloading Packages: sudo-1.7.2p1-7.el5_5.i386.rpm Running rpm_check_debug Running Transaction Test Finished Transaction Test Transaction Test Succeeded Running Transaction Installing : sudo Installed: sudo.i386 0:1.7.2p1-7.el5_5 Complete!
| 230 kB
00:00
1/1
yum update
To bring all applications up to date, by downloading and installing them, issue yum update. All software that was installed via yum will be updated to the latest version that is available in the repository.
yum update
If you only want to update one package, use yum update $package.
[root@rhel55 ~]# yum update sudo Loaded plugins: rhnplugin, security Skipping security plugin, no data Setting up Update Process
180
package management
Resolving Dependencies Skipping security plugin, no data --> Running transaction check ---> Package sudo.i386 0:1.7.2p1-7.el5_5 set to be updated --> Finished Dependency Resolution Dependencies Resolved ===================================================================== Package Arch Version Repository Size ===================================================================== Updating: sudo i386 1.7.2p1-7.el5_5 rhel-i386-server-5 230 k Transaction Summary ===================================================================== Install 0 Package(s) Upgrade 1 Package(s) Total download size: 230 k Is this ok [y/N]: y Downloading Packages: sudo-1.7.2p1-7.el5_5.i386.rpm Running rpm_check_debug Running Transaction Test Finished Transaction Test Transaction Test Succeeded Running Transaction Updating : sudo Cleanup : sudo Updated: sudo.i386 0:1.7.2p1-7.el5_5 Complete!
| 230 kB
00:00
1/2 2/2
181
package management
System Tools Text-based Internet Web Server Windows File Server X Software Development X Window System Available Groups: Engineering and Scientific FTP Server Games and Entertainment Java Development KDE (K Desktop Environment) KDE Software Development MySQL Database News Server OpenFabrics Enterprise Distribution PostgreSQL Database Sound and Video Done
To install a set of applications, brought together via a group, use yum groupinstall $groupname.
[root@rhel55 ~]# yum groupinstall 'Sound and video' Loaded plugins: rhnplugin, security Setting up Group Process Package alsa-utils-1.0.17-1.el5.i386 already installed and latest version Package sox-12.18.1-1.i386 already installed and latest version Package 9:mkisofs-2.01-10.7.el5.i386 already installed and latest version Package 9:cdrecord-2.01-10.7.el5.i386 already installed and latest version Package cdrdao-1.2.1-2.i386 already installed and latest version Resolving Dependencies --> Running transaction check ---> Package cdda2wav.i386 9:2.01-10.7.el5 set to be updated ---> Package cdparanoia.i386 0:alpha9.8-27.2 set to be updated ---> Package sound-juicer.i386 0:2.16.0-3.el5 set to be updated --> Processing Dependency: libmusicbrainz >= 2.1.0 for package: sound-juicer --> Processing Dependency: libmusicbrainz.so.4 for package: sound-juicer ---> Package vorbis-tools.i386 1:1.1.1-3.el5 set to be updated --> Processing Dependency: libao >= 0.8.4 for package: vorbis-tools --> Processing Dependency: libao.so.2 for package: vorbis-tools --> Running transaction check ---> Package libao.i386 0:0.8.6-7 set to be updated ---> Package libmusicbrainz.i386 0:2.1.1-4.1 set to be updated --> Finished Dependency Resolution ...
Read the manual page of yum for more information about managing groups in yum.
package management One important flag for yum is enablerepo. Use this command if you want to use a repository that is not enabled by default.
yum $command $foo --enablerepo=$repo
183
package management
17.8. alien
alien is experimental software that converts between rpm and deb package formats (and others). Below an example of how to use alien to convert an rpm package to a deb package.
paul@barry:~$ ls -l netcat* -rw-r--r-- 1 paul paul 123912 2009-06-04 14:58 netcat-0.7.1-1.i386.rpm paul@barry:~$ alien --to-deb netcat-0.7.1-1.i386.rpm netcat_0.7.1-2_i386.deb generated paul@barry:~$ ls -l netcat* -rw-r--r-- 1 paul paul 123912 2009-06-04 14:58 netcat-0.7.1-1.i386.rpm -rw-r--r-- 1 root root 125236 2009-06-04 14:59 netcat_0.7.1-2_i386.deb
In real life, use the netcat tool provided by your distribution, or use the .deb file from their website.
184
package management
You unpack them like with tar xzf, it will create a directory called applicationName-1.2.3
tar xzf $applicationName.tgz
Replace the z with a j when the file ends in .tar.bz2. The tar, gzip and bzip2 commands are explained in detail in the Linux Fundamentals course. If you download a .deb file, then you'll have to use dpkg to install it, .rpm's can be installed with the rpm command.
185
package management
186
package management
3. Use aptitude or yum to search for and install the 'dict', 'samba' and 'wesnoth' applications. Did you find all them all ?
aptitude search wesnoth (Debian, Ubuntu and family) yum search wesnoth (Red Hat and family)
5. If time permits, uninstall Samba from the ubuntu machine, download the latest version from samba.org and install it.
187
While this chapter is not directly about Linux, it does contain general networking concepts that will help you in troubleshooting networks on Linux.
189
general networking
general networking Devices like repeaters and hubs are part of this layer. You cannot use software to 'see' a repeater or hub on the network. The only thing these devices are doing is amplifying electrical signals on cables. Passive hubs are multiport amplifiers that amplify an incoming electrical signal on all other connections. Active hubs do this by reading and retransmitting bits, without interpreting any meaning in those bits. Network technologies like csma/cd and token ring are defined on this layer. This is all we have to say about layer 1 in this book.
layers 5, 6 and 7
The tcp/ip application layer includes layers 5, 6 and 7. Details on the difference between these layers are out of scope of this course.
general networking
[Protocols in Frame: eth:ip:udp:bootp]
Sniffing for ntp (Network Time Protocol) packets gives us this line, which makes us conclude to put ntp next to bootp in the protocol chart below.
[Protocols in Frame: eth:ip:udp:ntp]
Sniffing an arp broadcast makes us put arp next to ip. All these protocols are explained later in this chapter.
[Protocols in Frame: eth:arp]
Below is a protocol chart based on wireshark's knowledge. It contains some very common protocols that are discussed in this book. The chart does not contain all protocols.
192
general networking
multicast
A multicast is destined for a group (of computers).
Some examples of multicast are Realplayer (.sdp files) and ripv2 (a routing protocol).
193
general networking
broadcast
A broadcast is meant for everyone.
Typical example here is the BBC (British Broadcasting Corporation) broadcasting to everyone. In datacommunications a broadcast is most common confined to the lan. Careful, a layer 2 broadcast is very different from a layer 3 broadcast. A layer two broadcast is received by all network cards on the same segment (it does not pass any router), whereas a layer 3 broadcast is received by all hosts in the same ip subnet.
anycast
The root name servers of the internet use anycast. An anycast signal goes the the (geographically) nearest of a well defined group.
With thanks to the nice anonymous wikipedia contributor to put these pictures in the public domain.
194
general networking
18.3. lan-wan-man
The term lan is used for local area networks, as opposed to a wan for wide area networks. The difference between the two is determined by the distance between the computers, and not by the number of computers in a network. Some protocols like atm are designed for use in a wan, others like ethernet are designed for use in a lan.
lan
A lan (Local Area Network) is a local network. This can be one room, or one floor, or even one big building. We say lan as long as computers are close to each other. You can also define a lan when all computers are ethernet connected. A lan can contain multiple smaller lan's. The picture below shows three lan's that together make up one lan.
wan
A wan (Wide Area Network) is a network with a lot of distance between the computers (or hosts). These hosts are often connected by leased lines. A wan does not use ethernet, but protocols like fddi, frame relay, ATM or X.25 to connect computers (and networks). The picture below shows a branch office that is connected through Frame Relay with headquarters.
195
general networking The acronym wan is also used for large surface area networks like the internet. Cisco is known for their wan technology. They make routers that connect many lan networks using wan protocols.
man
A man (Metropolitan Area Network) is something inbetween a lan and a wan, often comprising several buildings on the same campus or in the same city. A man can use fddi or ethernet or other protocols for connectivity.
pan-wpan
Your home network is called a pan (Personal Area Network). A wireless pan is a wpan.
196
general networking
18.5. tcp/ip
history of tcp/ip
In the Sixties development of the tcp/ip protocol stack was started by the US Department of Defense. In the Eighties a lot of commercial enterprises developed their own protocol stack: IBM created sna, Novell had ipx/spx, Microsoft completed netbeui and Apple worked with appletalk. All the efforts from the Eighties failed to survive the Nineties. By the end of the Nineties, almost all computers in the world were able to speak tcp/ip. In my humble opinion, the main reason for the survival of tcp/ip over all the other protocols is its openness. Everyone is free to develop and use the tcp/ip protocol suite.
many protocols
For reliable connections, you use tcp, whereas udp is connectionless but faster. The icmp error messages are used by ping, multicast groups are managed by igmp. These protocols are visible in the protocol field of the ip header, and are listed in the /etc/protocols file.
paul@debian5:~$ grep tcp /etc/protocols tcp 6 TCP # transmission control protocol
many services
Network cards are uniquely identified by their mac address, hosts by their ip address and applications by their port number. Common application level protocols like smtp, http, ssh, telnet and ftp have fixed port numbers. There is a list of port numbers in /etc/services.
paul@ubu1010:~$ grep ssh /etc/services ssh 22/tcp # SSH Remote Login Protocol ssh 22/udp
197
This chapter explains how to configure network interface cards to work with tcp/ip.
198
interface configuration
199
interface configuration
dhcp client
The screenshot below shows that our current Ubuntu 11.04 is configured for dhcp on eth0 (the first network interface card or nic).
root@ubu1104srv:~# cat /etc/network/interfaces # This file describes the network interfaces available on your system # and how to activate them. For more information, see interfaces(5). # The loopback network interface auto lo iface lo inet loopback # The primary network interface auto eth0 iface eth0 inet dhcp
Configuring network cards for dhcp is good practice for clients, but servers usually require a fixed ip address.
fixed ip
The screenshot below shows /etc/network/interfaces configured with a fixed ip address.
root@ubu1104srv:~# cat /etc/network/interfaces # This file describes the network interfaces available on your system # and how to activate them. For more information, see interfaces(5). # The loopback network interface auto lo iface lo inet loopback # The primary network interface auto eth0 iface eth0 inet static address 192.168.33.100 network 192.168.33.0 netmask 255.255.255.0 gateway 192.168.33.1
The screenshot above also shows that you can provide more configuration than just the ip address. See interfaces(5) for help on setting a gateway, netmask or any of the other options. 200
interface configuration
/sbin/ifdown
It is adviced (but not mandatory) to down an interface before changing its configuration. This can be done with the ifdown command. The command will not give any output when downing an interface with a fixed ip address. However ifconfig will no longer show the interface.
root@ubu1104srv:~# ifdown eth0 root@ubu1104srv:~# ifconfig lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:106 errors:0 dropped:0 overruns:0 frame:0 TX packets:106 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:11162 (11.1 KB) TX bytes:11162 (11.1 KB)
/sbin/ifup
Below a screenshot of ifup bringing the eth0 ethernet interface up using dhcp. (Note that this is a Ubuntu 10.10 screenshot, Ubuntu 11.04 omits ifup output by default.)
root@ubu1010srv:/etc/network# ifup eth0 Internet Systems Consortium DHCP Client V3.1.3 Copyright 2004-2009 Internet Systems Consortium. All rights reserved. For info, please visit https://www.isc.org/software/dhcp/ Listening on LPF/eth0/08:00:27:cd:7f:fc Sending on LPF/eth0/08:00:27:cd:7f:fc Sending on Socket/fallback DHCPREQUEST of 192.168.1.34 on eth0 to 255.255.255.255 port 67 DHCPNAK from 192.168.33.100 DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 3 DHCPOFFER of 192.168.33.77 from 192.168.33.100 DHCPREQUEST of 192.168.33.77 on eth0 to 255.255.255.255 port 67 DHCPACK of 192.168.33.77 from 192.168.33.100 bound to 192.168.33.77 -- renewal in 95 seconds. ssh stop/waiting ssh start/running, process 1301 root@ubu1010srv:/etc/network#
The details of dhcp are covered in a separate chapter in the Linux Servers course.
201
interface configuration
There are a dozen more option settable in this file, details can be found in /usr/share/ doc/initscripts-*/sysconfig.txt.
/etc/sysconfig/network-scripts/ifcfgEach network card can be configured individually using the /etc/sysconfig/networkscripts/ifcfg-* files. When you have only one network card, then this will probably be /etc/sysconfig/network-scripts/ifcfg-eth0.
dhcp client
Below a screenshot of /etc/sysconfig/network-scripts/ifcfg-eth0 configured for dhcp (BOOTPROTO="dhcp"). Note also the NM_CONTROLLED paramater to disable control of this nic by Network Manager. This parameter is not explained (not even mentioned) in /usr/share/doc/initscripts-*/sysconfig.txt, but many others are.
[root@rhel6 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE="eth0" HWADDR="08:00:27:DD:0D:5C" NM_CONTROLLED="no" BOOTPROTO="dhcp" ONBOOT="yes"
The BOOTPROTO variable can be set to either dhcp or bootp, anything else will be considered static meaning there should be no protocol used at boot time to set the interface values.
fixed ip
Below a screenshot of a fixed ip configuration in /etc/sysconfig/network-scripts/ ifcfg-eth0.
[root@rhel6 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE="eth0" HWADDR="08:00:27:DD:0D:5C"
202
interface configuration
NM_CONTROLLED="no" BOOTPROTO="none" IPADDR="192.168.1.99" NETMASK="255.255.255.0" GATEWAY="192.168.1.1" ONBOOT="yes"
The HWADDR can be used to make sure that each network card gets the correct name when multiple network cards are present in the computer. It can not be used to assign a mac address to a network card. For this, you need to specify the MACADDR variable. Do not use HWADDR and MACADDR in the same ifcfg-ethx file. The BROADCAST= and NETWORK= parameters from previous RHEL/Fedora versions are obsoleted.
203
interface configuration
19.4. ifconfig
The use of /sbin/ifconfig without any arguments will present you with a list of all active network interface cards, including wireless and the loopback interface. In the screenshot below eth0 has no ip address.
root@ubu1010:~# ifconfig eth0 Link encap:Ethernet HWaddr 00:26:bb:5d:2e:52 UP BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) Interrupt:43 Base address:0xe000 eth1 Link encap:Ethernet HWaddr 00:26:bb:12:7a:5e inet addr:192.168.1.30 Bcast:192.168.1.255 Mask:255.255.255.0 inet6 addr: fe80::226:bbff:fe12:7a5e/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:11141791 errors:202 dropped:0 overruns:0 frame:11580126 TX packets:6473056 errors:3860 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:3476531617 (3.4 GB) TX bytes:2114919475 (2.1 GB) Interrupt:23 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:2879 errors:0 dropped:0 overruns:0 frame:0 TX packets:2879 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:486510 (486.5 KB) TX bytes:486510 (486.5 KB)
You can also use ifconfig to obtain information about just one network card.
[root@rhel6 ~]# ifconfig eth0 eth0 Link encap:Ethernet HWaddr 08:00:27:DD:0D:5C inet addr:192.168.1.99 Bcast:192.168.1.255 Mask:255.255.255.0 inet6 addr: fe80::a00:27ff:fedd:d5c/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:2969 errors:0 dropped:0 overruns:0 frame:0 TX packets:1918 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:335942 (328.0 KiB) TX bytes:190157 (185.7 KiB)
When /sbin is not in the $PATH of a normal user you will have to type the full path, as seen here on Debian.
paul@debian5:~$ /sbin/ifconfig eth3 eth3 Link encap:Ethernet HWaddr 08:00:27:ab:67:30 inet addr:192.168.1.29 Bcast:192.168.1.255 Mask:255.255.255.0 inet6 addr: fe80::a00:27ff:feab:6730/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:27155 errors:0 dropped:0 overruns:0 frame:0 TX packets:30527 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:13095386 (12.4 MiB) TX bytes:25767221 (24.5 MiB)
204
interface configuration
up and down
You can also use ifconfig to bring an interface up or down. The difference with ifup is that ifconfig eth0 up will re-activate the nic keeping its existing (current) configuration, whereas ifup will read the correct file that contains a (possibly new) configuration and use this config file to bring the interface up.
[root@rhel6 ~]# ifconfig eth0 down [root@rhel6 ~]# ifconfig eth0 up [root@rhel6 ~]# ifconfig eth0 eth0 Link encap:Ethernet HWaddr 08:00:27:DD:0D:5C inet addr:192.168.1.99 Bcast:192.168.1.255 Mask:255.255.255.0 inet6 addr: fe80::a00:27ff:fedd:d5c/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:2995 errors:0 dropped:0 overruns:0 frame:0 TX packets:1927 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:339030 (331.0 KiB) TX bytes:191583 (187.0 KiB)
setting ip address
You can temporary set an ip address with ifconfig. This ip address is only valid until the next ifup/ifdown cycle or until the next reboot.
[root@rhel6 ~]# ifconfig eth0 | grep 192 inet addr:192.168.1.99 Bcast:192.168.1.255 Mask:255.255.255.0 [root@rhel6 ~]# ifconfig eth0 192.168.33.42 netmask 255.255.0.0 [root@rhel6 ~]# ifconfig eth0 | grep 192 inet addr:192.168.33.42 Bcast:192.168.255.255 Mask:255.255.0.0 [root@rhel6 ~]# ifdown eth0 && ifup eth0 [root@rhel6 ~]# ifconfig eth0 | grep 192 inet addr:192.168.1.99 Bcast:192.168.1.255 Mask:255.255.255.0
dhclient
Home and client Linux desktops often have /sbin/dhclient running. This is a daemon that enables a network interface to lease an ip configuration from a dhcp server. When your adapter is configured for dhcp or bootp, then /sbin/ifup will start the dhclient daemon. When a lease is renewed, dhclient will override your ifconfig set ip address!
205
interface configuration
19.5. hostname
Every host receives a hostname, often placed in a DNS name space forming the fqdn or Fully Qualified Domain Name. This screenshot shows the hostname command and the configuration of the hostname on Red Hat/Fedora.
[root@rhel6 ~]# grep rhel /etc/sysconfig/network HOSTNAME=rhel6 [root@rhel6 ~]# hostname rhel6
On all Linux distributions you can change the hostname using the hostname $newname command. This is not a permanent change.
[root@rhel6 ~]# hostname server42 [root@rhel6 ~]# hostname server42
On any Linux you can use sysctl to display and set the hostname.
[root@rhel6 ~]# kernel.hostname [root@rhel6 ~]# kernel.hostname [root@rhel6 ~]# kernel.hostname [root@rhel6 ~]# rhel6 sysctl kernel.hostname = server42 sysctl kernel.hostname=rhel6 = rhel6 sysctl kernel.hostname = rhel6 hostname
206
interface configuration
19.6. arp
The ip to mac resolution is handled by the layer two broadcast protocol arp. The arp table can be displayed with the arp tool. The screenshot below shows the list of computers that this computer recently communicated with.
root@barry:~# arp -a ? (192.168.1.191) at 00:0C:29:3B:15:80 [ether] on eth1 agapi (192.168.1.73) at 00:03:BA:09:7F:D2 [ether] on eth1 anya (192.168.1.1) at 00:12:01:E2:87:FB [ether] on eth1 faith (192.168.1.41) at 00:0E:7F:41:0D:EB [ether] on eth1 kiss (192.168.1.49) at 00:D0:E0:91:79:95 [ether] on eth1 laika (192.168.1.40) at 00:90:F5:4E:AE:17 [ether] on eth1 pasha (192.168.1.71) at 00:03:BA:02:C3:82 [ether] on eth1 shaka (192.168.1.72) at 00:03:BA:09:7C:F9 [ether] on eth1 root@barry:~#
Anya is a Cisco Firewall, faith is a laser printer, kiss is a Kiss DP600, laika is a laptop and Agapi, Shaka and Pasha are SPARC servers. The question mark is a Red Hat Enterprise Linux server running on a virtual machine. You can use arp -d to remove an entry from the arp table.
[root@rhel6 ~]# arp Address HWtype HWaddress Flags Mask Iface ubu1010 ether 00:26:bb:12:7a:5e C eth0 anya ether 00:02:cf:aa:68:f0 C eth0 [root@rhel6 ~]# arp -d anya [root@rhel6 ~]# arp Address HWtype HWaddress Flags Mask Iface ubu1010 ether 00:26:bb:12:7a:5e C eth0 anya (incomplete) eth0 [root@rhel6 ~]# ping anya PING anya (192.168.1.1) 56(84) bytes of data. 64 bytes from anya (192.168.1.1): icmp_seq=1 ttl=254 time=10.2 ms ... [root@rhel6 ~]# arp Address HWtype HWaddress Flags Mask Iface ubu1010 ether 00:26:bb:12:7a:5e C eth0 anya ether 00:02:cf:aa:68:f0 C eth0
207
interface configuration
19.7. route
You can see the computer's local routing table with the /sbin/route command (and also with netstat -r ).
root@RHEL4b ~]# netstat -r Kernel IP routing table Destination Gateway Genmask 192.168.1.0 * 255.255.255.0 [root@RHEL4b ~]# route Kernel IP routing table Destination Gateway Genmask 192.168.1.0 * 255.255.255.0 [root@RHEL4b ~]#
Flags U
MSS Window 0 0
It appears this computer does not have a gateway configured, so we use route add default gw to add a default gateway on the fly.
[root@RHEL4b ~]# route add default gw 192.168.1.1 [root@RHEL4b ~]# route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref 192.168.1.0 * 255.255.255.0 U 0 0 default 192.168.1.1 0.0.0.0 UG 0 0 [root@RHEL4b ~]#
Unless you configure the gateway in one of the /etc/ file from the start of this chapter, your computer will forget this gateway after a reboot.
19.8. ping
If you can ping to another host, then tcp/ip is configured.
[root@RHEL4b ~]# ping 192.168.1.5 PING 192.168.1.5 (192.168.1.5) 56(84) 64 bytes from 192.168.1.5: icmp_seq=0 64 bytes from 192.168.1.5: icmp_seq=1 64 bytes from 192.168.1.5: icmp_seq=2 64 bytes from 192.168.1.5: icmp_seq=3 bytes of data. ttl=64 time=1004 ms ttl=64 time=1.19 ms ttl=64 time=0.494 ms ttl=64 time=0.419 ms
--- 192.168.1.5 ping statistics --4 packets transmitted, 4 received, 0% packet loss, time 3009ms rtt min/avg/max/mdev = 0.419/251.574/1004.186/434.520 ms, pipe 2 [root@RHEL4b ~]#
208
interface configuration
This example shows how to use ethtool to switch the bandwidth from 1000Mbit to 100Mbit and back. Note that some time passes before the nic is back to 1000Mbit.
root@laika:~# ethtool Speed: 1000Mb/s root@laika:~# ethtool root@laika:~# ethtool Speed: 100Mb/s root@laika:~# ethtool root@laika:~# ethtool Speed: 1000Mb/s eth0 | grep Speed -s eth0 speed 100 eth0 | grep Speed -s eth0 speed 1000 eth0 | grep Speed
209
interface configuration
210
interface configuration
4. Follow the nic configuration in the book to change your ip address from dhcp client to fixed. Keep the same ip address to avoid conflicts!
Ubuntu/Debian: ifdown eth0 vi /etc/network/interfaces ifup eth0 Redhat/Fedora: ifdown eth0 vi /etc/sysconfig/network-scripts/ifcfg-eth0 ifup eth0
5. Did you also configure the correct gateway in the previous question ? If not, then do this now. 6. Verify that you have a gateway.
paul@debian5:~$ /sbin/route Kernel IP routing table Destination Gateway Genmask 192.168.1.0 * 255.255.255.0 default 192.168.1.1 0.0.0.0
--- 192.168.1.1 ping statistics --3 packets transmitted, 3 received, 0% packet loss, time 2008ms rtt min/avg/max/mdev = 2.283/2.524/2.941/0.296 ms
9. Which ports are used by http, pop3, ssh, telnet, nntp and ftp ?
root@rhel6 ~# grep ^'http ' /etc/services
211
interface configuration
http http root@rhel6 smtp smtp root@rhel6 ssh ssh root@rhel6 telnet telnet root@rhel6 nntp nntp root@rhel6 ftp ftp 80/tcp 80/udp ~# grep 25/tcp 25/udp ~# grep 22/tcp 22/udp ~# grep 23/tcp 23/udp ~# grep 119/tcp 119/udp ~# grep 21/tcp 21/udp www www-http # WorldWideWeb HTTP www www-http # HyperText Transfer Protocol ^'smtp ' /etc/services mail mail ^'ssh ' /etc/services # The Secure Shell (SSH) Protocol # The Secure Shell (SSH) Protocol ^'telnet ' /etc/services
^'nntp ' /etc/services readnews untp readnews untp ^'ftp ' /etc/services fsp fspd
Note that sctp was ommitted from the screenshot. 10. Explain why e-mail and websites are sent over tcp and not udp.
Because tcp is reliable and udp is not.
12. Which ip-addresses did your computer recently have contact with ?
root@rhel6 ~# arp -a ? (192.168.1.1) at 00:02:cf:aa:68:f0 [ether] on eth2 ? (192.168.1.30) at 00:26:bb:12:7a:5e [ether] on eth2 ? (192.168.1.31) at 08:00:27:8e:8a:a8 [ether] on eth2
212
A good network administrator should be able to use a sniffer like wireshark or tcpdump to troubleshoot network problems. A good student will often use a sniffer to learn about networking. This chapter introduces you to network sniffing.
213
network sniffing
20.1. wireshark
installing wireshark
This example shows how to install wireshark on .deb based distributions like Ubuntu and Debian.
aptitude install wireshark
selecting interface
When you first fire up wireshark, you will need to select an interface to sniff. You will see a dialog box that looks similar to this. Choose the interface that you want to sniff.
On some distributions only root is allowed to sniff the network. You might need to use sudo wireshark.
start sniffing
In this example here, we sniffed a ping between two computers. The top pane shows that wireshark recognizes the icmp protocol, and captured all the ping packets between the two computers.
214
network sniffing
use filters
You might get lost in too many packets. A quick solution to see only the packets that are of interest to you is to apply filters. When you type arp and click apply, you will only see arp packets displayed. You can combine two protocols with a logical or between them. The example below shows how to filter only arp and bootp (or dhcp) packets.
This example shows how to filter for dns traffic containing a certain ip address.
215
network sniffing
20.2. tcpdump
Sniffing on the command line can be done with tcpdump. Here are some examples. Using the tcpdump host $ip command displays all traffic with one host (192.168.1.38 in this example).
root@ubuntu910:~# tcpdump host 192.168.1.38 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes
Capturing only ssh (tcp port 22) traffic can be done with tcpdump tcp port $port. This screenshot is cropped to 76 characters for readability in the pdf.
root@deb503:~# tcpdump tcp port 22 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on eth1, link-type EN10MB (Ethernet), capture size 96 bytes 14:22:20.716313 IP deb503.local.37973 > rhel53.local.ssh: P 666050963:66605 14:22:20.719936 IP rhel53.local.ssh > deb503.local.37973: P 1:49(48) ack 48 14:22:20.720922 IP rhel53.local.ssh > deb503.local.37973: P 49:113(64) ack 14:22:20.721321 IP rhel53.local.ssh > deb503.local.37973: P 113:161(48) ack 14:22:20.721820 IP deb503.local.37973 > rhel53.local.ssh: . ack 161 win 200 14:22:20.722492 IP rhel53.local.ssh > deb503.local.37973: P 161:225(64) ack 14:22:20.760602 IP deb503.local.37973 > rhel53.local.ssh: . ack 225 win 200 14:22:23.108106 IP deb503.local.54424 > ubuntu910.local.ssh: P 467252637:46 14:22:23.116804 IP ubuntu910.local.ssh > deb503.local.54424: P 1:81(80) ack 14:22:23.116844 IP deb503.local.54424 > ubuntu910.local.ssh: . ack 81 win 2 ^C 10 packets captured 10 packets received by filter 0 packets dropped by kernel
Same as above, but write the output to a file with the tcpdump -w $filename command.
root@ubuntu910:~# tcpdump -w sshdump.tcpdump tcp port 22 tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes ^C 17 packets captured 17 packets received by filter 0 packets dropped by kernel
216
network sniffing
217
network sniffing
4. Display only the ping echo's in the top pane using a filter.
type 'icmp' (without quotes) in the filter box, and then click 'apply'
5. Now ping to a name (like www.linux-training.be) and try to sniff the DNS query and response. Which DNS server was used ? Was it a tcp or udp query and response ?
First start the sniffer. Enter 'dns' in the filter box and click apply.
root@ubuntu910:~# ping www.linux-training.be PING www.linux-training.be (88.151.243.8) 56(84) bytes of data. 64 bytes from fosfor.openminds.be (88.151.243.8): icmp_seq=1 ttl=58 time=14.9 ms 64 bytes from fosfor.openminds.be (88.151.243.8): icmp_seq=2 ttl=58 time=16.0 ms ^C --- www.linux-training.be ping statistics --2 packets transmitted, 2 received, 0% packet loss, time 1002ms rtt min/avg/max/mdev = 14.984/15.539/16.095/0.569 ms
The details in wireshark will say the DNS query was inside a udp packet.
218
Sometimes a server needs more than one ip address on the same network card, we call this binding ip addresses. Linux can also activate multiple network cards behind the same ip address, this is called bonding. This chapter will teach you how to configure binding and bonding on the most common Linux distributions.
219
220
221
In this demo we decide to bond eth1 and eth2. We will name are bond bond0 and add this entry to modprobe so the kernel can load the bonding module when we bring the interface up.
[root@rhel6 network-scripts]# cat /etc/modprobe.d/bonding.conf alias bond0 bonding
Next we create two files, one for each network card that we will use as slave in bond0.
[root@rhel6 network-scripts]# cat ifcfg-eth1 DEVICE=eth1 BOOTPROTO=none ONBOOT=yes MASTER=bond0 SLAVE=yes USERCTL=no [root@rhel6 network-scripts]# cat ifcfg-eth2 DEVICE=eth2 BOOTPROTO=none ONBOOT=yes MASTER=bond0 SLAVE=yes USERCTL=no
223
In this demo we decide to bond eth1 and eth2. We also need to install the ifenslave package.
debian5:~# aptitude search ifenslave p ifenslave - Attach and detach slave interfaces to a bonding device p ifenslave-2.6 - Attach and detach slave interfaces to a bonding device debian5:~# aptitude install ifenslave Reading package lists... Done ...
Next we update the /etc/network/interfaces file with information about the bond0 interface.
debian5:~# tail -7 /etc/network/interfaces iface bond0 inet static address 192.168.1.42 netmask 255.255.255.0 gateway 192.168.1.1 slaves eth1 eth2 bond-mode active-backup bond_primary eth1
On older version of Debian/Ubuntu you needed to modprobe bonding, but this is no longer required. Use ifup to bring the interface up, then test that it works.
debian5:~# ifup bond0 debian5:~# ifconfig bond0 bond0 Link encap:Ethernet HWaddr 08:00:27:63:9a:95 inet addr:192.168.1.42 Bcast:192.168.1.255 Mask:255.255.255.0 inet6 addr: fe80::a00:27ff:fe63:9a95/64 Scope:Link UP BROADCAST RUNNING MASTER MULTICAST MTU:1500 Metric:1 RX packets:212 errors:0 dropped:0 overruns:0 frame:0 TX packets:39 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:31978 (31.2 KiB) TX bytes:6709 (6.5 KiB)
224
225
226
3. Make sure your neighbour also succeeded in binding an extra ip address before you continue.
ping $extra_ip_neighbour or ssh $extra_ip_neighbour
4. Add an extra network card (or two) to your virtual machine and use the theory to bond two network cards.
Redhat/Fedora: add ifcfg-ethX and ifcfg-bondX files in /etc/sysconfig/network-scripts as shown in the theory and don't forget the modprobe.conf Debian/Ubuntu: expand the /etc/network/interfaces file as shown in the theory and don't forget to install the ifenslave package
227
The secure shell or ssh is a collection of tools using a secure protocol for communications with remote Linux computers. This chapter gives an overview of the most common commands related to the use of the sshd server and the ssh client.
228
/etc/ssh/
Configuration of ssh client and server is done in the /etc/ssh directory. In the next sections we will discuss most of the files found in /etc/ssh/.
229
Imagine Alice and Bob, two people that like to communicate with each other. Using public and private keys they can communicate with encryption and with authentication. When Alice wants to send an encrypted message to Bob, she uses the public key of Bob. Bob shares his public key with Alice, but keeps his private key private! Since Bob is the only one to have Bob's private key, Alice is sure that Bob is the only one that can read the encrypted message. When Bob wants to verify that the message came from Alice, Bob uses the public key of Alice to verify that Alice signed the message with her private key. Since Alice is the only one to have Alice's private key, Bob is sure the message came from Alice.
230
As you can see, the user paul is presented with an rsa authentication fingerprint from the remote system. The user can accepts this bu typing yes. We will see later that an entry will be added to the ~/.ssh/known_hosts file.
paul@ubu1204:~$ ssh [email protected] The authenticity of host '192.168.1.30 (192.168.1.30)' can't be established. RSA key fingerprint is b5:fb:3c:53:50:b4:ab:81:f3:cd:2e:bb:ba:44:d3:75. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.1.30' (RSA) to the list of known hosts. [email protected]'s password: Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.2.0-26-generic-pae i686) * Documentation: https://help.ubuntu.com/
1 package can be updated. 0 updates are security updates. Last login: Wed Jun 6 19:25:57 2012 from 172.28.0.131 admin42@ubuserver:~$
The user can get log out of the remote server by typing exit or by using Ctrl-d.
admin42@ubuserver:~$ exit logout Connection to 192.168.1.30 closed. paul@ubu1204:~$
231
22.4. scp
The scp command works just like cp, but allows the source and destination of the copy to be behind ssh. Here is an example where we copy the /etc/hosts file from the remote server to the home directory of user paul.
paul@ubu1204:~$ scp [email protected]:/etc/hosts /home/paul/serverhosts [email protected]'s password: hosts 100% 809 0.8KB/s 00:00
232
ssh-keygen
The example below shows how Alice uses ssh-keygen to generate a key pair. Alice does not enter a passphrase.
[alice@RHEL5 ~]$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/alice/.ssh/id_rsa): Created directory '/home/alice/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/alice/.ssh/id_rsa. Your public key has been saved in /home/alice/.ssh/id_rsa.pub. The key fingerprint is: 9b:ac:ac:56:c2:98:e5:d9:18:c4:2a:51:72:bb:45:eb alice@RHEL5 [alice@RHEL5 ~]$
~/.ssh
While ssh-keygen generates a public and a private key, it will also create a hidden .ssh directory with proper permissions. If you create the .ssh directory manually, then you need to chmod 700 it! Otherwise ssh will refuse to use the keys (world readable private keys are not secure!). As you can see, the .ssh directory is secure in Alice's home directory.
[alice@RHEL5 ~]$ ls -ld .ssh drwx------ 2 alice alice 4096 May [alice@RHEL5 ~]$ 1 07:38 .ssh
Bob is using Ubuntu at home. He decides to manually create the .ssh directory, so he needs to manually secure it.
bob@laika:~$ bob@laika:~$ drwxr-xr-x 2 bob@laika:~$ bob@laika:~$ mkdir .ssh ls -ld .ssh bob bob 4096 2008-05-14 16:53 .ssh chmod 700 .ssh/
233
The files will be named id_dsa and id_dsa.pub when using dsa instead of rsa.
Be careful when copying a second key! Do not overwrite the first key, instead append the key to the same ~/.ssh/authorized_keys file!
cat id_rsa.pub >> ~/.ssh/authorized_keys
authorized_keys
In your ~/.ssh directory, you can create a file called authorized_keys. This file can contain one or more public keys from people you trust. Those trusted people can use their private keys to prove their identity and gain access to your account via ssh (without password). The example shows Bob's authorized_keys file containing the public key of Alice.
bob@laika:~$ cat .ssh/authorized_keys ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEApCQ9xzyLzJes1sR+hPyqW2vyzt1D4zTLqk\ MDWBR4mMFuUZD/O583I3Lg/Q+JIq0RSksNzaL/BNLDou1jMpBe2Dmf/u22u4KmqlJBfDhe\ yTmGSBzeNYCYRSMq78CT9l9a+y6x/shucwhaILsy8A2XfJ9VCggkVtu7XlWFDL2cum08/0\ mRFwVrfc/uPsAn5XkkTscl4g21mQbnp9wJC40pGSJXXMuFOk8MgCb5ieSnpKFniAKM+tEo\ /vjDGSi3F/bxu691jscrU0VUdIoOSo98HUfEf7jKBRikxGAC7I4HLa+/zX73OIvRFAb2hv\ tUhn6RHrBtUJUjbSGiYeFTLDfcTQ== alice@RHEL5
passwordless ssh
Alice can now use ssh to connect passwordless to Bob's laptop. In combination with ssh's capability to execute commands on the remote host, this can be useful in pipes across different machines.
[alice@RHEL5 ~]$ ssh [email protected] "ls -l .ssh"
234
235
22.8. sshd
The ssh server is called sshd and is provided by the openssh-server package.
root@ubu1204~# dpkg -l openssh-server | tail -1 ii openssh-server 1:5.9p1-5ubuntu1 secure shell (SSH) server,...
22.10. ssh-agent
When generating keys with ssh-keygen, you have the option to enter a passphrase to protect access to the keys. To avoid having to type this passphrase every time, you can add the key to ssh-agent using ssh-add. Most Linux distributions will start the ssh-agent automatically when you log on.
root@ubu1204~# ps -ef | grep ssh-agent paul 2405 2365 0 08:13 ? 00:00:00 /usr/bin/ssh-agent...
This clipped screenshot shows how to use ssh-add to list the keys that are currently added to the ssh-agent
paul@debian5:~$ ssh-add -L ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAvgI+Vx5UrIsusZPl8da8URHGsxG7yivv3/\ ... wMGqa48Kelwom8TGb4Sgcwpp/VO/ldA5m+BGCw== paul@deb503
236
237
2. Verify in the ssh configuration files that only protocol version 2 is allowed.
grep Protocol /etc/ssh/ssh*_config
3. Use ssh to log on to the server, show your current directory and then exit the server.
user@client$ ssh user@server-ip-address user@server$ pwd /home/user user@server$ exit
6. (optional, only works when you have a graphical install of Linux) Install the xeyes package on the server and use ssh to run xeyes on the server, but display it on your client.
on the server: apt-get install xeyes on the client: ssh -X user@server-ip xeyes
7. (optional, same as previous) Create a bookmark in firefox, then quit firefox on client and server. Use ssh -X to run firefox on your display, but on your neighbour's computer. Do you see your neighbour's bookmark ? 8. Use ssh-keygen to create a key pair without passphrase. Setup passwordless ssh between you and your neighbour. (or between your client and your server)
See solution in book "setting up passwordless ssh"
9. Verify that the permissions on the server key files are correct; world readable for the public keys and only root access for the private keys.
ls -l /etc/ssh/ssh_host_*
238
ssh client and server 11. (optional) Protect your keypair with a passphrase, then add this key to the sshagent and test your passwordless ssh to the server.
man ssh-keygen man ssh-agent man ssh-add
239
The network file system (or simply nfs) enables us since the eighties to share a directory with other computers on the network. In this chapter we see how to setup an nfs server and an nfs client computer.
240
introduction to nfs
23.2. rpcinfo
Clients connect to the server using rpc (on Linux this can be managed by the portmap daemon. Look at rpcinfo to verify that nfs and its related services are running.
root@RHELv4u2:~# /etc/init.d/portmap status portmap (pid 1920) is running... root@RHELv4u2:~# rpcinfo -p program vers proto port 100000 2 tcp 111 portmapper 100000 2 udp 111 portmapper 100024 1 udp 32768 status 100024 1 tcp 32769 status root@RHELv4u2:~# service nfs start Starting NFS services: Starting NFS quotas: Starting NFS daemon: Starting NFS mountd:
[ [ [ [
OK OK OK OK
] ] ] ]
241
introduction to nfs
100005 3 udp 100005 3 tcp root@RHELv4u2:~# 1004 1007 mountd mountd
23.4. /etc/exports
Here is a sample /etc/exports to explain the syntax:
paul@laika:~$ cat /etc/exports # Everyone can read this share /mnt/data/iso *(ro) # Only the computers named pasha and barry can readwrite this one /var/www pasha(rw) barry(rw) # same, but without root squashing for barry /var/ftp pasha(rw) barry(rw,no_root_squash) # everyone from the netsec.local domain gets access /var/backup *.netsec.local(rw) # ro for one network, rw for the other /var/upload 192.168.1.0/24(ro) 192.168.5.0/24(rw)
More recent incarnations of nfs require the subtree_check option to be explicitly set (or unset with no_subtree_check). The /etc/exports file then looks like this:
root@debian6 ~# cat /etc/exports # Everyone can read this share /srv/iso *(ro,no_subtree_check) # Only the computers named pasha and barry can readwrite this one /var/www pasha(rw,no_subtree_check) barry(rw,no_subtree_check) # same, but without root squashing for barry /var/ftp pasha(rw,no_subtree_check) barry(rw,no_root_squash,no_subtree_check)
23.5. exportfs
You don't need to restart the nfs server to start exporting your newly created exports. You can use the exportfs -va command to do this. It will write the exported directories to /var/lib/nfs/etab, where they are immediately applied.
root@debian6 ~# exportfs -va
242
introduction to nfs
exporting exporting exporting exporting exporting pasha:/var/ftp barry:/var/ftp pasha:/var/www barry:/var/www *:/srv/iso
Here is another simple example. Suppose the project55 people tell you they only need a couple of CD-ROM images, and you already have them available on an nfs server. You could issue the following command to mount this storage on their /home/ project55 mount point.
root@RHELv4u2:~# mount -t nfs 192.168.1.40:/mnt/data/iso /home/project55/ root@RHELv4u2:~# ls -lh /home/project55/ total 3.6G drwxr-xr-x 2 1000 1000 4.0K Jan 16 17:55 RHELv4u1 drwxr-xr-x 2 1000 1000 4.0K Jan 16 14:14 RHELv4u2 drwxr-xr-x 2 1000 1000 4.0K Jan 16 14:54 RHELv4u3 drwxr-xr-x 2 1000 1000 4.0K Jan 16 11:09 RHELv4u4 -rw-r--r-- 1 root root 1.6G Oct 13 15:22 sled10-vmwarews5-vm.zip root@RHELv4u2:~#
243
244
introduction to networking
[ [ [
OK OK OK
] ] ]
The easy way to configure iptables, is to use a graphical tool like KDE's kmyfirewall or Security Level Configuration Tool. You can find the latter in the graphical menu, somewhere in System Tools - Security, or you can start it by typing system-configsecuritylevel in bash. These tools allow for some basic firewall configuration. You can decide whether to enable or disable the firewall, and what typical standard ports are allowed when the firewall is active. You can even add some custom ports. When you are done, the configuration is written to /etc/sysconfig/iptables on Red Hat.
root@RHELv4u4:~# cat /etc/sysconfig/iptables # Firewall configuration written by system-config-securitylevel # Manual customization of this file is not recommended. *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] :RH-Firewall-1-INPUT - [0:0] -A INPUT -j RH-Firewall-1-INPUT -A FORWARD -j RH-Firewall-1-INPUT -A RH-Firewall-1-INPUT -i lo -j ACCEPT -A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT -A RH-Firewall-1-INPUT -p 50 -j ACCEPT -A RH-Firewall-1-INPUT -p 51 -j ACCEPT -A RH-Firewall-1-INPUT -p udp --dport 5353 -d 224.0.0.251 -j ACCEPT -A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT -A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A RH-F...NPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A RH-F...NPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT -A RH-F...NPUT -m state --state NEW -m tcp -p tcp --dport 21 -j ACCEPT -A RH-F...NPUT -m state --state NEW -m tcp -p tcp --dport 25 -j ACCEPT -A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited COMMIT root@RHELv4u4:~#
To start the service, issue the service iptables start command. You can configure iptables to start at boot time with chkconfig.
root@RHELv4u4:~# service iptables start Applying iptables firewall rules: root@RHELv4u4:~# chkconfig iptables on root@RHELv4u4:~#
OK
245
introduction to networking
One of the nice features of iptables is that it displays extensive status information when queried with the service iptables status command.
root@RHELv4u4:~# service iptables status Table: filter Chain INPUT (policy ACCEPT) target prot opt source destination RH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0 Chain FORWARD (policy ACCEPT) target prot opt source RH-Firewall-1-INPUT all -- 0.0.0.0/0 Chain OUTPUT (policy ACCEPT) target prot opt source Chain RH-Firewall-1-INPUT (2 target prot opt source ACCEPT all -- 0.0.0.0/0 ACCEPT icmp -- 0.0.0.0/0 ACCEPT esp -- 0.0.0.0/0 ACCEPT ah -- 0.0.0.0/0 ACCEPT udp -- 0.0.0.0/0 ACCEPT udp -- 0.0.0.0/0 ACCEPT all -- 0.0.0.0/0 ACCEPT tcp -- 0.0.0.0/0 ACCEPT tcp -- 0.0.0.0/0 ACCEPT tcp -- 0.0.0.0/0 ACCEPT tcp -- 0.0.0.0/0 REJECT all -- 0.0.0.0/0 root@RHELv4u4:~# references) destination 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 224.0.0.251 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0
destination 0.0.0.0/0
destination
udp dpt:5353 udp dpt:631 state RELATED,ESTABLISHED state NEW tcp dpt:22 state NEW tcp dpt:80 state NEW tcp dpt:21 state NEW tcp dpt:25 reject-with icmp-host-prohibited
Mastering firewall configuration requires a decent knowledge of tcp/ip. Good iptables tutorials can be found online here http://iptables-tutorial.frozentux.net/ iptables-tutorial.html and here http://tldp.org/HOWTO/IP-Masquerade-HOWTO/.
246
introduction to networking
0.0.0.0/0
destination 0.0.0.0/0
247
introduction to networking
inetd or xinetd
First verify whether your computer is running inetd or xinetd. This Debian 4.0 Etch is running inetd.
root@barry:~# ps fax | grep inet 3870 ? Ss 0:00 /usr/sbin/inetd
Both daemons have the same functionality (listening to many ports, starting other daemons when they are needed), but they have different configuration files.
xinetd superdaemon
The xinetd daemon is often called a superdaemon because it listens to a lot of incoming connections, and starts other daemons when they are needed. When a connection request is received, xinetd will first check TCP wrappers (/etc/hosts.allow and /etc/hosts.deny) and then give control of the connection to the other daemon. This superdaemon is configured through /etc/xinetd.conf and the files in the directory / etc/xinetd.d. Let's first take a look at /etc/xinetd.conf.
paul@RHELv4u2:~$ cat /etc/xinetd.conf # # Simple configuration file for xinetd # # Some defaults, and include /etc/xinetd.d/ defaults {
248
introduction to networking
instances log_type log_on_success log_on_failure cps } includedir /etc/xinetd.d paul@RHELv4u2:~$ = = = = = 60 SYSLOG authpriv HOST PID HOST 25 30
According to the settings in this file, xinetd can handle 60 client requests at once. It uses the authpriv facility to log the host ip-address and pid of successful daemon spawns. When a service (aka protocol linked to daemon) gets more than 25 cps (connections per second), it holds subsequent requests for 30 seconds. The directory /etc/xinetd.d contains more specific configuration files. Let's also take a look at one of them.
paul@RHELv4u2:~$ ls /etc/xinetd.d amanda chargen-udp echo klogin rexec talk amandaidx cups-lpd echo-udp krb5-telnet rlogin telnet amidxtape daytime eklogin kshell rsh tftp auth daytime-udp finger ktalk rsync time chargen dbskkd-cdb gssftp ntalk swat time-udp paul@RHELv4u2:~$ cat /etc/xinetd.d/swat # default: off # description: SWAT is the Samba Web Admin Tool. Use swat \ # to configure your Samba server. To use SWAT, \ # connect to port 901 with your favorite web browser. service swat { port = 901 socket_type = stream wait = no only_from = 127.0.0.1 user = root server = /usr/sbin/swat log_on_failure += USERID disable = yes } paul@RHELv4u2:~$
The services should be listed in the /etc/services file. Port determines the service port, and must be the same as the port specified in /etc/services. The socket_type should be set to stream for tcp services (and to dgram for udp). The log_on_failure += concats the userid to the log message formatted in /etc/xinetd.conf. The last setting disable can be set to yes or no. Setting this to no means the service is enabled! Check the xinetd and xinetd.conf manual pages for many more configuration options.
inetd superdaemon
This superdaemon has only one configuration file /etc/inetd.conf. Every protocol or daemon that it is listening for, gets one line in this file. 249
introduction to networking
root@barry:~# grep ftp /etc/inetd.conf tftp dgram udp wait nobody /usr/sbin/tcpd /usr/sbin/in.tftpd /boot/tftp root@barry:~#
You can disable a service in inetd.conf above by putting a # at the start of that line. Here an example of the disabled vmware web interface (listening on tcp port 902).
paul@laika:~$ grep vmware /etc/inetd.conf #902 stream tcp nowait root /usr/sbin/vmware-authd vmware-authd
250
introduction to networking
[ [ [ [
OK OK OK OK
] ] ] ]
251
introduction to networking nfs version 4 requires tcp (port 2049) and supports Kerberos user authentication as an option. nfs authentication only takes place when mounting the share. nfs versions 2 and 3 authenticate only the host.
server configuration
nfs is configured in /etc/exports. Here is a sample /etc/exports to explain the syntax. You need some way (NIS domain or LDAP) to synchronize userid's across computers when using nfs a lot. The rootsquash option will change UID 0 to the UID of the nfsnobody user account. The sync option will write writes to disk before completing the client request.
paul@laika:~$ cat /etc/exports # Everyone can read this share /mnt/data/iso *(ro) # Only the computers barry and pasha can readwrite this one /var/www pasha(rw) barry(rw) # same, but without root squashing for barry /var/ftp pasha(rw) barry(rw,no_root_squash) # everyone from the netsec.lan domain gets access /var/backup *.netsec.lan(rw) # ro for one network, rw for the other /var/upload 192.168.1.0/24(ro) 192.168.5.0/24(rw)
You don't need to restart the nfs server to start exporting your newly created exports. You can use the exportfs -va command to do this. It will write the exported directories to /var/lib/nfs/etab, where they are immediately applied.
client configuration
We have seen the mount command and the /etc/fstab file before.
root@RHELv4u2:~# mount -t nfs barry:/mnt/data/iso /home/project55/ root@RHELv4u2:~# cat /etc/fstab | grep nfs barry:/mnt/data/iso /home/iso nfs defaults 0 0 root@RHELv4u2:~#
Here is another simple example. Suppose the project55 people tell you they only need a couple of CD-ROM images, and you already have them available on an nfs server. You could issue the following command to mount this storage on their /home/ project55 mount point.
root@RHELv4u2:~# mount -t nfs 192.168.1.40:/mnt/data/iso /home/project55/ root@RHELv4u2:~# ls -lh /home/project55/ total 3.6G drwxr-xr-x 2 1000 1000 4.0K Jan 16 17:55 RHELv4u1
252
introduction to networking
drwxr-xr-x 2 1000 drwxr-xr-x 2 1000 drwxr-xr-x 2 1000 -rw-r--r-- 1 root root@RHELv4u2:~# 1000 1000 1000 root 4.0K 4.0K 4.0K 1.6G Jan Jan Jan Oct 16 16 16 13 14:14 14:54 11:09 15:22 RHELv4u2 RHELv4u3 RHELv4u4 sled10-vmwarews5-vm.zip
253
uname -r
To see your current Linux kernel version, issue the uname -r command as shown below. This first example shows Linux major version 2.6 and minor version 24. The rest -22generic is specific to the distribution (Ubuntu in this case).
paul@laika:~$ uname -r 2.6.24-22-generic
The same command on Red Hat Enterprise Linux shows an older kernel (2.6.18) with -92.1.17.el5 being specific to the distribution.
[paul@RHEL52 ~]$ uname -r 2.6.18-92.1.17.el5
255
/proc/cmdline
The parameters that were passed to the kernel at boot time are in /proc/cmdline.
paul@RHELv4u4:~$ cat /proc/cmdline ro root=/dev/VolGroup00/LogVol00 rhgb quiet
init=/bin/bash
Normally the kernel invokes init as the first daemon process. Adding init=/bin/bash to the kernel parameters will instead invoke bash (again with root logged on without providing a password).
/var/log/messages
The kernel reports during boot to syslog which writes a lot of kernel actions in /var/ log/messages. Looking at this file reveals when the kernel was started, including all the devices that were detected at boot time.
[root@RHEL53 ~]# grep -A16 "syslogd 1.4.1:" /var/log/messages|cut -b24syslogd 1.4.1: restart. kernel: klogd 1.4.1, log source = /proc/kmsg started. kernel: Linux version 2.6.18-128.el5 ([email protected]... kernel: BIOS-provided physical RAM map: kernel: BIOS-e820: 0000000000000000 - 000000000009f800 (usable) kernel: BIOS-e820: 000000000009f800 - 00000000000a0000 (reserved) kernel: BIOS-e820: 00000000000ca000 - 00000000000cc000 (reserved) kernel: BIOS-e820: 00000000000dc000 - 0000000000100000 (reserved) kernel: BIOS-e820: 0000000000100000 - 000000001fef0000 (usable) kernel: BIOS-e820: 000000001fef0000 - 000000001feff000 (ACPI data) kernel: BIOS-e820: 000000001feff000 - 000000001ff00000 (ACPI NVS) kernel: BIOS-e820: 000000001ff00000 - 0000000020000000 (usable) kernel: BIOS-e820: 00000000fec00000 - 00000000fec10000 (reserved) kernel: BIOS-e820: 00000000fee00000 - 00000000fee01000 (reserved) kernel: BIOS-e820: 00000000fffe0000 - 0000000100000000 (reserved) kernel: 0MB HIGHMEM available. kernel: 512MB LOWMEM available.
This example shows how to use /var/log/messages to see kernel information about /dev/sda.
[root@RHEL53 ~]# grep sda /var/log/messages | cut -b24kernel: SCSI device sda: 41943040 512-byte hdwr sectors (21475 MB) kernel: sda: Write Protect is off
256
dmesg
The dmesg command prints out all the kernel bootup messages (from the last boot).
[root@RHEL53 ~]# dmesg | head Linux version 2.6.18-128.el5 ([email protected]) BIOS-provided physical RAM map: BIOS-e820: 0000000000000000 - 000000000009f800 (usable) BIOS-e820: 000000000009f800 - 00000000000a0000 (reserved) BIOS-e820: 00000000000ca000 - 00000000000cc000 (reserved) BIOS-e820: 00000000000dc000 - 0000000000100000 (reserved) BIOS-e820: 0000000000100000 - 000000001fef0000 (usable) BIOS-e820: 000000001fef0000 - 000000001feff000 (ACPI data) BIOS-e820: 000000001feff000 - 000000001ff00000 (ACPI NVS) BIOS-e820: 000000001ff00000 - 0000000020000000 (usable)
Thus to find information about /dev/sda, using dmesg will yield only kernel messages from the last boot.
[root@RHEL53 ~]# dmesg | grep sda SCSI device sda: 41943040 512-byte hdwr sectors (21475 MB) sda: Write Protect is off sda: Mode Sense: 5d 00 00 00 sda: cache data unavailable sda: assuming drive cache: write through SCSI device sda: 41943040 512-byte hdwr sectors (21475 MB) sda: Write Protect is off sda: Mode Sense: 5d 00 00 00 sda: cache data unavailable sda: assuming drive cache: write through sda: sda1 sda2 sd 0:0:0:0: Attached scsi disk sda EXT3 FS on sda1, internal journal
the Linux kernel Anyone can anonymously use an ftp client to access ftp.kernel.org
paul@laika:~$ ftp ftp.kernel.org Connected to pub3.kernel.org. 220 Welcome to ftp.kernel.org. Name (ftp.kernel.org:paul): anonymous 331 Please specify the password. Password: 230Welcome to the 230230LINUX KERNEL ARCHIVES 230ftp.kernel.org
All the Linux kernel versions are located in the pub/linux/kernel/ directory.
ftp> ls pub/linux/kernel/v* 200 PORT command successful. Consider using PASV. 150 Here comes the directory listing. drwxrwsr-x 2 536 536 4096 Mar 20 2003 v1.0 drwxrwsr-x 2 536 536 20480 Mar 20 2003 v1.1 drwxrwsr-x 2 536 536 8192 Mar 20 2003 v1.2 drwxrwsr-x 2 536 536 40960 Mar 20 2003 v1.3 drwxrwsr-x 3 536 536 16384 Feb 08 2004 v2.0 drwxrwsr-x 2 536 536 53248 Mar 20 2003 v2.1 drwxrwsr-x 3 536 536 12288 Mar 24 2004 v2.2 drwxrwsr-x 2 536 536 24576 Mar 20 2003 v2.3 drwxrwsr-x 5 536 536 28672 Dec 02 08:14 v2.4 drwxrwsr-x 4 536 536 32768 Jul 14 2003 v2.5 drwxrwsr-x 7 536 536 110592 Dec 05 22:36 v2.6 226 Directory send OK. ftp>
/usr/src
On your local computer, the kernel source is located in /usr/src. Note though that the structure inside /usr/src might be different depending on the distribution that you are using. First let's take a look at /usr/src on Debian. There appear to be two versions of the complete Linux source code there. Looking for a specific file (e1000_main.c) with find reveals it's exact location.
paul@barry:~$ ls -l /usr/src/ drwxr-xr-x 20 root root 4096 2006-04-04 22:12 linux-source-2.6.15 drwxr-xr-x 19 root root 4096 2006-07-15 17:32 linux-source-2.6.16 paul@barry:~$ find /usr/src -name e1000_main.c /usr/src/linux-source-2.6.15/drivers/net/e1000/e1000_main.c /usr/src/linux-source-2.6.16/drivers/net/e1000/e1000_main.c
This is very similar to /usr/src on Ubuntu, except there is only one kernel here (and it is newer).
paul@laika:~$ ls -l /usr/src/
258
We will have to dig a little deeper to find the kernel source on Red Hat!
[paul@RHEL52 ~]$ cd /usr/src/redhat/BUILD/ [paul@RHEL52 BUILD]$ find . -name "e1000_main.c" ./kernel-2.6.18/linux-2.6.18.i686/drivers/net/e1000/e1000_main.c
And then use aptitude install to download and install the Debian Linux kernel source code.
root@barry:~# aptitude install linux-source-2.6.24
When the aptitude is finished, you will see a new file named /usr/src/linux-source<version>.tar.bz2
root@barry:/usr/src# ls -lh drwxr-xr-x 20 root root 4.0K 2006-04-04 22:12 linux-source-2.6.15 drwxr-xr-x 19 root root 4.0K 2006-07-15 17:32 linux-source-2.6.16 -rw-r--r-- 1 root root 45M 2008-12-02 10:56 linux-source-2.6.24.tar.bz2
Ubuntu
Ubuntu is based on Debian and also uses aptitude, so the task is very similar. 259
root@laika:~# aptitude search linux-source i linux-source - Linux kernel source with Ubuntu patches v linux-source-2.6 i A linux-source-2.6.24 - Linux kernel source for version 2.6.24 root@laika:~# aptitude install linux-source
When the wget download is finished, you end up with a 60M .rpm file.
[root@RHEL52 total 60M -rw-r--r-- 1 drwxr-xr-x 5 drwxr-xr-x 7 src]# ll root root 60M Dec 5 20:54 kernel-2.6.18-92.1.17.el5.src.rpm root root 4.0K Dec 5 19:23 kernels root root 4.0K Oct 11 13:22 redhat
We will need to perform some more steps before this can be used as kernel source code. First, we issue the rpm -i kernel-2.6.9-42.EL.src.rpm command to install this Red Hat package.
[root@RHEL52 total 60M -rw-r--r-- 1 drwxr-xr-x 5 drwxr-xr-x 7 [root@RHEL52 src]# ll root root 60M Dec 5 20:54 kernel-2.6.18-92.1.17.el5.src.rpm root root 4.0K Dec 5 19:23 kernels root root 4.0K Oct 11 13:22 redhat src]# rpm -i kernel-2.6.18-92.1.17.el5.src.rpm
260
The rpmbuild command put the RHEL Linux kernel source code in /usr/src/redhat/ BUILD/kernel-<version>/.
[root@RHEL52 kernel-2.6.18]# pwd /usr/src/redhat/BUILD/kernel-2.6.18 [root@RHEL52 kernel-2.6.18]# ll total 20K drwxr-xr-x 2 root root 4.0K Dec 6 2007 config -rw-r--r-- 1 root root 3.1K Dec 5 20:58 Config.mk drwxr-xr-x 20 root root 4.0K Dec 5 20:58 linux-2.6.18.i686 drwxr-xr-x 19 root root 4.0K Sep 20 2006 vanilla drwxr-xr-x 8 root root 4.0K Dec 6 2007 xen
initrd
The kernel uses initrd (an initial RAM disk) at boot time. The initrd is mounted before the kernel loads, and can contain additional drivers and modules. It is a compressed cpio archive, so you can look at the contents in this way.
root@RHELv4u4:/boot# mkdir /mnt/initrd root@RHELv4u4:/boot# cp initrd-2.6.9-42.0.3.EL.img TMPinitrd.gz root@RHELv4u4:/boot# gunzip TMPinitrd.gz root@RHELv4u4:/boot# file TMPinitrd TMPinitrd: ASCII cpio archive (SVR4 with no CRC) root@RHELv4u4:/boot# cd /mnt/initrd/ root@RHELv4u4:/mnt/initrd# cpio -i | /boot/TMPinitrd 4985 blocks root@RHELv4u4:/mnt/initrd# ls -l total 76 drwxr-xr-x 2 root root 4096 Feb 5 08:36 bin drwxr-xr-x 2 root root 4096 Feb 5 08:36 dev drwxr-xr-x 4 root root 4096 Feb 5 08:36 etc -rwxr-xr-x 1 root root 1607 Feb 5 08:36 init drwxr-xr-x 2 root root 4096 Feb 5 08:36 lib drwxr-xr-x 2 root root 4096 Feb 5 08:36 loopfs drwxr-xr-x 2 root root 4096 Feb 5 08:36 proc
261
System.map
The System.map contains the symbol table and changes with every kernel compile. The symbol table is also present in /proc/kallsyms (pre 2.6 kernels name this file / proc/ksyms).
root@RHELv4u4:/boot# head System.map-`uname -r` 00000400 A __kernel_vsyscall 0000041a A SYSENTER_RETURN_OFFSET 00000420 A __kernel_sigreturn 00000440 A __kernel_rt_sigreturn c0100000 A _text c0100000 T startup_32 c01000c6 t checkCPUtype c0100147 t is486 c010014e t is386 c010019f t L6 root@RHELv4u4:/boot# head /proc/kallsyms c0100228 t _stext c0100228 t calibrate_delay_direct c0100228 t stext c0100337 t calibrate_delay c01004db t rest_init c0100580 t do_pre_smp_initcalls c0100585 t run_init_process c01005ac t init c0100789 t early_param_test c01007ad t early_setup_test root@RHELv4u4:/boot#
.config
The last file copied to the /boot directory is the kernel configuration used for compilation. This file is not necessary in the /boot directory, but it is common practice to put a copy there. It allows you to recompile a kernel, starting from the same configuration as an existing working one.
/lib/modules
The modules are stored in the /lib/modules/<kernel-version> directory. There is a separate directory for each kernel that was compiled for your system.
paul@laika:~$ ll /lib/modules/ total 12K drwxr-xr-x 7 root root 4.0K 2008-11-10 14:32 2.6.24-16-generic drwxr-xr-x 8 root root 4.0K 2008-12-06 15:39 2.6.24-21-generic drwxr-xr-x 8 root root 4.0K 2008-12-05 12:58 2.6.24-22-generic
<module>.ko
The file containing the modules usually ends in .ko. This screenshot shows the location of the isdn module files.
paul@laika:~$ find /lib/modules -name isdn.ko /lib/modules/2.6.24-21-generic/kernel/drivers/isdn/i4l/isdn.ko /lib/modules/2.6.24-22-generic/kernel/drivers/isdn/i4l/isdn.ko /lib/modules/2.6.24-16-generic/kernel/drivers/isdn/i4l/isdn.ko
lsmod
To see a list of currently loaded modules, use lsmod. You see the name of each loaded module, the size, the use count, and the names of other modules using this one.
[root@RHEL52 ~]# lsmod | head Module Size autofs4 24517 hidp 23105 rfcomm 42457 l2cap 29505 -5 Used by 2 2 0 10 hidp,rfcomm
/proc/modules
/proc/modules lists all modules loaded by the kernel. The output would be too long to display here, so lets grep for the vm module. We see that vmmon and vmnet are both loaded. You can display the same information with lsmod. Actually lsmod only reads and reformats the output of /proc/modules.
paul@laika:~$ cat /proc/modules | grep vm vmnet 36896 13 - Live 0xffffffff88b21000 (P) vmmon 194540 0 - Live 0xffffffff88af0000 (P) paul@laika:~$ lsmod | grep vm vmnet 36896 13 vmmon 194540 0 paul@laika:~$
263
module dependencies
Some modules depend on others. In the following example, you can see that the nfsd module is used by exportfs, lockd and sunrpc.
paul@laika:~$ cat /proc/modules | grep nfsd nfsd 267432 17 - Live 0xffffffff88a40000 exportfs 7808 1 nfsd, Live 0xffffffff88a3d000 lockd 73520 3 nfs,nfsd, Live 0xffffffff88a2a000 sunrpc 185032 12 nfs,nfsd,lockd, Live 0xffffffff889fb000 paul@laika:~$ lsmod | grep nfsd nfsd 267432 17 exportfs 7808 1 nfsd lockd 73520 3 nfs,nfsd sunrpc 185032 12 nfs,nfsd,lockd paul@laika:~$
insmod
Kernel modules can be manually loaded with the insmod command. This is a very simple (and obsolete) way of loading modules. The screenshot shows insmod loading the fat module (for fat file system support).
root@barry:/lib/modules/2.6.17-2-686# /lib/modules/2.6.17-2-686 root@barry:/lib/modules/2.6.17-2-686# root@barry:/lib/modules/2.6.17-2-686# root@barry:/lib/modules/2.6.17-2-686# fat 46588 0 pwd lsmod | grep fat insmod kernel/fs/fat/fat.ko lsmod | grep fat
insmod is not detecting dependencies, so it fails to load the isdn module (because the isdn module depends on the slhc module).
[root@RHEL52 drivers]# pwd /lib/modules/2.6.18-92.1.18.el5/kernel/drivers [root@RHEL52 kernel]# insmod isdn/i4l/isdn.ko insmod: error inserting 'isdn/i4l/isdn.ko': -1 Unknown symbol in module
modinfo
As you can see in the screenshot of modinfo below, the isdn module depends in the slhc module.
[root@RHEL52 drivers]# modinfo isdn/i4l/isdn.ko | head -6 filename: isdn/i4l/isdn.ko license: GPL author: Fritz Elfert
264
modprobe
The big advantage of modprobe over insmod is that modprobe will load all necessary modules, whereas insmod requires manual loading of dependencies. Another advantage is that you don't need to point to the filename with full path. This screenshot shows how modprobe loads the isdn module, automatically loading slhc in background.
[root@RHEL52 [root@RHEL52 [root@RHEL52 isdn slhc [root@RHEL52 kernel]# lsmod | grep isdn kernel]# modprobe isdn kernel]# lsmod | grep isdn 122433 0 10561 1 isdn kernel]#
/lib/modules/<kernel>/modules.dep
Module dependencies are stored in modules.dep.
[root@RHEL52 2.6.18-92.1.18.el5]# pwd /lib/modules/2.6.18-92.1.18.el5 [root@RHEL52 2.6.18-92.1.18.el5]# head -3 modules.dep /lib/modules/2.6.18-92.1.18.el5/kernel/drivers/net/tokenring/3c359.ko: /lib/modules/2.6.18-92.1.18.el5/kernel/drivers/net/pcmcia/3c574_cs.ko: /lib/modules/2.6.18-92.1.18.el5/kernel/drivers/net/pcmcia/3c589_cs.ko:
depmod
The modules.dep file can be updated (recreated) with the depmod command. In this screenshot no modules were added, so depmod generates the same file.
root@barry:/lib/modules/2.6.17-2-686# ls -l modules.dep -rw-r--r-- 1 root root 310676 2008-03-01 16:32 modules.dep root@barry:/lib/modules/2.6.17-2-686# depmod root@barry:/lib/modules/2.6.17-2-686# ls -l modules.dep -rw-r--r-- 1 root root 310676 2008-12-07 13:54 modules.dep
rmmod
Similar to insmod, the rmmod command is rarely used anymore.
265
modprobe -r
Contrary to rmmod, modprobe will automatically remove unneeded modules.
[root@RHELv4u3 [root@RHELv4u3 isdn slhc [root@RHELv4u3 [root@RHELv4u3 [root@RHELv4u3 [root@RHELv4u3 ~]# modprobe isdn ~]# lsmod | grep isdn 133537 0 7233 1 isdn ~]# modprobe -r isdn ~]# lsmod | grep isdn ~]# lsmod | grep slhc ~]#
/etc/modprobe.conf
The /etc/modprobe.conf file and the /etc/modprobe.d directory can contain aliases (used by humans) and options (for dependent modules) for modprobe.
[root@RHEL52 ~]# cat /etc/modprobe.conf alias scsi_hostadapter mptbase alias scsi_hostadapter1 mptspi alias scsi_hostadapter2 ata_piix alias eth0 pcnet32 alias eth2 pcnet32 alias eth1 pcnet32
266
make mrproper
Now clean up the source from any previous installs with make mrproper. If this is your first after downloading the source code, then this is not needed.
[root@RHEL52 linux-2.6.18.i686]# make mrproper CLEAN scripts/basic CLEAN scripts/kconfig CLEAN include/config CLEAN .config .config.old
.config
Now copy a working .config from /boot to our kernel directory. This file contains the configuration that was used for your current working kernel. It determines whether modules are included in compilation or not.
[root@RHEL52 linux-2.6.18.i686]# cp /boot/config-2.6.18-92.1.18.el5 .config
make menuconfig
Now run make menuconfig (or the graphical make xconfig). This tool allows you to select whether to compile stuff as a module (m), as part of the kernel (*), or not at all (smaller kernel size). If you remove too much, your kernel will not work. The configuration will be stored in the hidden .config file.
[root@RHEL52 linux-2.6.18.i686]# make menuconfig
make clean
Issue a make clean to prepare the kernel for compile. make clean will remove most generated files, but keeps your kernel configuration. Running a make mrproper at this point would destroy the .config file that you built with make menuconfig.
[root@RHEL52 linux-2.6.18.i686]# make clean
make bzImage
And then run make bzImage, sit back and relax while the kernel compiles. You can use time make bzImage to know how long it takes to compile, so next time you can go for a short walk. 267
[root@RHEL52 linux-2.6.18.i686]# time make bzImage HOSTCC scripts/basic/fixdep HOSTCC scripts/basic/docproc HOSTCC scripts/kconfig/conf.o HOSTCC scripts/kconfig/kxgettext.o ...
This command will end with telling you the location of the bzImage file (and with time info if you also specified the time command.
Kernel: arch/i386/boot/bzImage is ready real 13m59.573s user 1m22.631s sys 11m51.034s [root@RHEL52 linux-2.6.18.i686]# (#1)
You can already copy this image to /boot with cp arch/i386/boot/bzImage /boot/ vmlinuz-<kernel-version>.
make modules
Now run make modules. It can take 20 to 50 minutes to compile all the modules.
[root@RHEL52 linux-2.6.18.i686]# time make modules CHK include/linux/version.h CHK include/linux/utsrelease.h CC [M] arch/i386/kernel/msr.o CC [M] arch/i386/kernel/cpuid.o CC [M] arch/i386/kernel/microcode.o
make modules_install
To copy all the compiled modules to /lib/modules just run make modules_install (takes about 20 seconds). Here's a screenshot from before the command.
[root@RHEL52 total 20 drwxr-xr-x 6 drwxr-xr-x 6 drwxr-xr-x 6 [root@RHEL52 linux-2.6.18.i686]# ls -l /lib/modules/ root root 4096 Oct 15 13:09 2.6.18-92.1.13.el5 root root 4096 Nov 11 08:51 2.6.18-92.1.17.el5 root root 4096 Dec 6 07:11 2.6.18-92.1.18.el5 linux-2.6.18.i686]# make modules_install
And here is the same directory after. Notice that make modules_install created a new directory for the new kernel.
[root@RHEL52 linux-2.6.18.i686]# ls -l /lib/modules/ total 24
268
/boot
We still need to copy the kernel, the System.map and our configuration file to /boot. Strictly speaking the .config file is not obligatory, but it might help you in future compilations of the kernel.
[root@RHEL52 ]# pwd /usr/src/redhat/BUILD/kernel-2.6.18/linux-2.6.18.i686 [root@RHEL52 ]# cp System.map /boot/System.map-2.6.18-paul2008 [root@RHEL52 ]# cp .config /boot/config-2.6.18-paul2008 [root@RHEL52 ]# cp arch/i386/boot/bzImage /boot/vmlinuz-2.6.18-paul2008
mkinitrd
The kernel often uses an initrd file at bootup. We can use mkinitrd to generate this file. Make sure you use the correct kernel name!
[root@RHEL52 ]# pwd /usr/src/redhat/BUILD/kernel-2.6.18/linux-2.6.18.i686 [root@RHEL52 ]# mkinitrd /boot/initrd-2.6.18-paul2008 2.6.18-paul2008
bootloader
Compilation is now finished, don't forget to create an additional stanza in grub or lilo.
269
Makefile
The make file for this module.
[root@rhel4a kernel_module]# cat Makefile obj-m += hello.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
make
The running of the make command.
[root@rhel4a kernel_module]# make make -C /lib/modules/2.6.9-paul-2/build M=~/kernel_module modules make[1]: Entering dir... `/usr/src/redhat/BUILD/kernel-2.6.9/linux-2.6.9' CC [M] /home/paul/kernel_module/hello.o Building modules, stage 2. MODPOST CC /home/paul/kernel_module/hello.mod.o LD [M] /home/paul/kernel_module/hello.ko make[1]: Leaving dir... `/usr/src/redhat/BUILD/kernel-2.6.9/linux-2.6.9' [root@rhel4a kernel_module]#
15 15 15 15 15 15
270
hello.ko
Use modinfo to verify that it is really a module.
[root@rhel4a kernel_module]# modinfo hello.ko filename: hello.ko vermagic: 2.6.9-paul-2 SMP 686 REGPARM 4KSTACKS gcc-3.4 depends: [root@rhel4a kernel_module]#
271
26.1. introduction
With libraries we are talking about dynamically linked libraries (aka shared objects). These are binaries that contain functions and are not started themselves as programs, but are called by other binaries. Several programs can use the same library. The name of the library file usually starts with lib, followed by the actual name of the library, then the chracters .so and finally a version number.
26.3. ldd
Many programs have dependencies on the installation of certain libraries. You can display these dependencies with ldd. This example shows the dependencies of the su command.
paul@RHEL5 ~$ ldd /bin/su linux-gate.so.1 => (0x003f7000) libpam.so.0 => /lib/libpam.so.0 (0x00d5c000) libpam_misc.so.0 => /lib/libpam_misc.so.0 (0x0073c000) libcrypt.so.1 => /lib/libcrypt.so.1 (0x00aa4000) libdl.so.2 => /lib/libdl.so.2 (0x00800000) libc.so.6 => /lib/libc.so.6 (0x00ec1000) libaudit.so.0 => /lib/libaudit.so.0 (0x0049f000) /lib/ld-linux.so.2 (0x4769c000)
272
library management
26.4. ltrace
The ltrace program allows to see all the calls made to library functions by a program. The example below uses the -c option to get only a summary count (there can be many calls), and the -l option to only show calls in one library file. All this to see what calls are made when executing su - serena as root.
root@deb503:~# ltrace -c -l /lib/libpam.so.0 su - serena serena@deb503:~$ exit logout % time seconds usecs/call calls function ------ ----------- ----------- --------- -------------------70.31 0.014117 14117 1 pam_start 12.36 0.002482 2482 1 pam_open_session 5.17 0.001039 1039 1 pam_acct_mgmt 4.36 0.000876 876 1 pam_end 3.36 0.000675 675 1 pam_close_session 3.22 0.000646 646 1 pam_authenticate 0.48 0.000096 48 2 pam_set_item 0.27 0.000054 54 1 pam_setcred 0.25 0.000050 50 1 pam_getenvlist 0.22 0.000044 44 1 pam_get_item ------ ----------- ----------- --------- -------------------100.00 0.020079 11 total
You can then verify the integrity of all files in this package using debsums.
paul@deb503:~$ debsums e2fslibs /usr/share/doc/e2fslibs/changelog.Debian.gz /usr/share/doc/e2fslibs/copyright /lib/libe2p.so.2.3 /lib/libext2fs.so.2.4 OK OK OK OK
library management
paul@RHEL5 ~$ rpm -qf /lib/libext2fs.so.2.4 e2fsprogs-libs-1.39-8.el5
You can then use rpm -V to verify all files in this package. In the example below the output shows that the Size and the Time stamp of the file have changed since installation.
root@rhel53 ~# rpm -V e2fsprogs-libs prelink: /lib/libext2fs.so.2.4: prelinked file size differs S.?....T /lib/libext2fs.so.2.4
You can then use yum reinstall $package to overwrite the existing library with an original version.
root@rhel53 lib# yum reinstall e2fsprogs-libs Loaded plugins: rhnplugin, security Setting up Reinstall Process Resolving Dependencies --> Running transaction check ---> Package e2fsprogs-libs.i386 0:1.39-23.el5 set to be erased ---> Package e2fsprogs-libs.i386 0:1.39-23.el5 set to be updated --> Finished Dependency Resolution ...
We open the file with vi, but include the strace command with an output file for the trace before vi. This will create a file with all the function calls done by vi.
root@deb503:~# strace -o strace.txt vi 42.txt
The file is read only, but we still change the contents, and use the :w! directive to write to this file. Then we close vi and take a look at the trace log.
root@deb503:~# grep chmod strace.txt chmod("42.txt", 0100600) = -1 ENOENT (No such file or directory) chmod("42.txt", 0100400) = 0 root@deb503:~# ls -l 42.txt -r-------- 1 root root 12 2011-09-26 12:04 42.txt
Notice that vi changed the permissions on the file twice. The trace log is too long to show a complete screenshot in this book.
root@deb503:~# wc -l strace.txt 941 strace.txt
274
SCSI tapes
On the official Linux device list (http://www.lanana.org/docs/device-list/) we find the names for SCSI tapes (major 9 char). SCSI tape devices are located underneath / dev/st and are numbered starting with 0 for the first tape device.
/dev/st0 /dev/st1 /dev/st2 First tape device Second tape device Third tape device
By default, SCSI tapes on linux will use the highest hardware compression that is supported by the tape device. To lower the compression level, append one of the letters l (low), m (medium) or a (auto) to the tape name.
/dev/st0l /dev/st0m /dev/nst2m First low compression tape device First medium compression tape device Third no rewind medium compression tape device
276
backup
IDE tapes
On the official Linux device list (http://www.lanana.org/docs/device-list/) we find the names for IDE tapes (major 37 char). IDE tape devices are located underneath /dev/ht and are numbered starting with 0 for the first tape device. No rewind and compression is similar to SCSI tapes.
/dev/ht0 /dev/nht0 /dev/ht0m First IDE tape device Second no rewind IDE tape device First medium compression IDE tape device
mt
To manage your tapes, use mt (Magnetic Tape). Some examples. To receive information about the status of the tape.
mt -f /dev/st0 status
To rewind a tape...
mt -f /dev/st0 rewind
To erase a tape...
mt -f /dev/st0 erase
27.2. Compression
It can be beneficial to compress files before backup. The two most popular tools for compression of regular files on linux are gzip/gunzip and bzip2/bunzip2. Below you can see gzip in action, notice that it adds the .gz extension to the file.
paul@RHELv4u4:~/test$ ls -l allfiles.tx* -rw-rw-r-- 1 paul paul 8813553 Feb 27 05:38 allfiles.txt paul@RHELv4u4:~/test$ gzip allfiles.txt paul@RHELv4u4:~/test$ ls -l allfiles.tx* -rw-rw-r-- 1 paul paul 931863 Feb 27 05:38 allfiles.txt.gz paul@RHELv4u4:~/test$ gunzip allfiles.txt.gz paul@RHELv4u4:~/test$ ls -l allfiles.tx* -rw-rw-r-- 1 paul paul 8813553 Feb 27 05:38 allfiles.txt paul@RHELv4u4:~/test$
In general, gzip is much faster than bzip2, but the latter one compresses a lot better. Let us compare the two.
paul@RHELv4u4:~/test$ cp allfiles.txt bllfiles.txt
277
backup
paul@RHELv4u4:~/test$ time gzip allfiles.txt real 0m0.050s user 0m0.041s sys 0m0.009s paul@RHELv4u4:~/test$ time bzip2 bllfiles.txt real 0m5.968s user 0m5.794s sys 0m0.076s paul@RHELv4u4:~/test$ ls -l ?llfiles.tx* -rw-rw-r-- 1 paul paul 931863 Feb 27 05:38 allfiles.txt.gz -rw-rw-r-- 1 paul paul 708871 May 12 10:52 bllfiles.txt.bz2 paul@RHELv4u4:~/test$
27.3. tar
The tar utility gets its name from Tape ARchive. This tool will receive and send files to a destination (typically a tape or a regular file). The c option is used to create a tar archive (or tarfile), the f option to name/create the tarfile. The example below takes a backup of /etc into the file /backup/etc.tar .
root@RHELv4u4:~# tar cf /backup/etc.tar /etc root@RHELv4u4:~# ls -l /backup/etc.tar -rw-r--r-- 1 root root 47800320 May 12 11:47 /backup/etc.tar root@RHELv4u4:~#
Compression can be achieved without pipes since tar uses the z flag to compress with gzip, and the j flag to compress with bzip2.
root@RHELv4u4:~# tar czf /backup/etc.tar.gz /etc root@RHELv4u4:~# tar cjf /backup/etc.tar.bz2 /etc root@RHELv4u4:~# ls -l /backup/etc.ta* -rw-r--r-- 1 root root 47800320 May 12 11:47 /backup/etc.tar -rw-r--r-- 1 root root 6077340 May 12 11:48 /backup/etc.tar.bz2 -rw-r--r-- 1 root root 8496607 May 12 11:47 /backup/etc.tar.gz root@RHELv4u4:~#
The t option is used to list the contents of a tar file. Verbose mode is enabled with v (also useful when you want to see the files being archived during archiving).
root@RHELv4u4:~# tar tvf /backup/etc.tar drwxr-xr-x root/root 0 2007-05-12 -rw-r--r-- root/root 2657 2004-09-27 -rw-r--r-- root/root 13136 2006-11-03 drwxr-xr-x root/root 0 2004-11-03 ...
To list a specific file in a tar archive, use the t option, added with the filename (without leading /).
278
backup
root@RHELv4u4:~# tar tvf /backup/etc.tar etc/resolv.conf -rw-r--r-- root/root 77 2007-05-12 08:31:32 etc/resolv.conf root@RHELv4u4:~#
Use the x flag to restore a tar archive, or a single file from the archive. Remember that by default tar will restore the file in the current directory.
root@RHELv4u4:~# tar xvf /backup/etc.tar etc/resolv.conf etc/resolv.conf root@RHELv4u4:~# ls -l /etc/resolv.conf -rw-r--r-- 2 root root 40 May 12 12:05 /etc/resolv.conf root@RHELv4u4:~# ls -l etc/resolv.conf -rw-r--r-- 1 root root 77 May 12 08:31 etc/resolv.conf root@RHELv4u4:~#
You can preserve file permissions with the p flag. And you can exclude directories or file with --exclude.
root ~# tar cpzf /backup/etc_with_perms.tgz /etc root ~# tar cpzf /backup/etc_no_sysconf.tgz /etc --exclude /etc/sysconfig root ~# ls -l /backup/etc_* -rw-r--r-- 1 root root 8434293 May 12 12:48 /backup/etc_no_sysconf.tgz -rw-r--r-- 1 root root 8496591 May 12 12:48 /backup/etc_with_perms.tgz root ~#
You can also create a text file with names of files and directories to archive, and then supply this file to tar with the -T flag.
root@RHELv4u4:~# find /etc -name *.conf > files_to_archive.txt root@RHELv4u4:~# find /home -name *.pdf >> files_to_archive.txt root@RHELv4u4:~# tar cpzf /backup/backup.tgz -T files_to_archive.txt
The tar utility can receive filenames from the find command, with the help of xargs.
find /etc -type f -name "*.conf" | xargs tar czf /backup/confs.tar.gz
You can also use tar to copy a directory, this is more efficient than using cp -r.
(cd /etc; tar -cf - . ) | (cd /backup/copy_of_etc/; tar -xpf - )
Another example of tar, this copies a directory securely over the network.
(cd /etc;tar -cf - . )|(ssh user@srv 'cd /backup/cp_of_etc/; tar -xf - ')
tar can be used together with gzip and copy a file to a remote server through ssh
cat backup.tar | gzip | ssh [email protected] "cat - > backup.tgz"
279
backup Compress the tar backup when it is on the network, but leave it uncompressed at the destination.
cat backup.tar | gzip | ssh [email protected] "gunzip|cat - > backup.tar"
Listing files in a dump archive is done with dump -t, and you can compare files with dump -C. You can omit files from a dump by changing the dump attribute with the chattr command. The d attribute on ext will tell dump to skip the file, even during a full backup. In the following example, /etc/hosts is excluded from dump archives.
chattr +d /etc/hosts
280
backup To restore the complete file system with restore, use the -r option. This can be useful to change the size or block size of a file system. You should have a clean file system mounted and cd'd into it. Like this example shows.
mke2fs /dev/hda3 mount /dev/hda3 /mnt/data cd /mnt/data restore rf /dev/nst0
To extract only one file or directory from a dump, use the -x option.
restore -xf /dev/st0 /etc
27.6. cpio
Different from tar and dump is cpio (Copy Input and Output). It can be used to receive filenames, but copies the actual files. This makes it an easy companion with find! Some examples below. find sends filenames to cpio, which puts the files in an archive.
find /etc -depth -print | cpio -oaV -O archive.cpio
Now pipe it through ssh (backup files to a compressed file on another machine)
find /etc -depth -print|cpio -oaV|gzip -c|ssh server "cat - > etc.cpio.gz"
find sends filenames to cpio | cpio sends files to ssh | ssh sends files to cpio 'cpio extracts files'
find /etc -depth -print | cpio -oaV | ssh user@host 'cpio -imVd'
the same but reversed: copy a dir from the remote host to the local machine
ssh user@host "find path -depth -print | cpio -oaV" | cpio -imVd
27.7. dd
About dd
Some people use dd to create backups. This can be very powerful, but dd backups can only be restored to very similar partitions or devices. There are however a lot of useful things possible with dd. Some examples. 281
backup
Copy files
This example shows how dd can copy files. Copy the file summer.txt to copy_of_summer.txt .
dd if=~/summer.txt of=~/copy_of_summer.txt
backup
27.8. split
The split command is useful to split files into smaller files. This can be useful to fit the file onto multiple instances of a medium too small to contain the complete file. In the example below, a file of size 5000 bytes is split into three smaller files, with maximum 2000 bytes each.
paul@laika:~/test$ ls -l total 8 -rw-r--r-- 1 paul paul 5000 paul@laika:~/test$ split -b paul@laika:~/test$ ls -l total 20 -rw-r--r-- 1 paul paul 5000 -rw-r--r-- 1 paul paul 2000 -rw-r--r-- 1 paul paul 2000 -rw-r--r-- 1 paul paul 1000
backup 5. Use dd and ssh to put a backup of the master boot record on your neighbours computer. 6. (On the real computer) Create and mount an ISO image of the ubuntu cdrom. 7. Combine dd and gzip to create a 'ghost' image of one of your partitions on another partition. 8. Use dd to create a five megabyte file in ~/testsplit and name it biggest. Then split this file in smaller two megabyte parts.
mkdir testsplit dd if=/dev/zero of=~/testsplit/biggest count=5000 bs=1024 split -b 2000000 biggest parts
284
Index
Symbols
/bin/dmesg, 33 /bin/login, 129 /boot/grub/, 116 /boot/grub/grub.conf, 117 /boot/grub/menu.lst, 116 /dev, 43 /dev/hdX, 31 /dev/ht, 277 /dev/nst, 276 /dev/sdb, 68 /dev/sdX, 31 /dev/st, 276 /etc/apt/sources.list, 175 /etc/at.allow, 144 /etc/at.deny, 144 /etc/cron.allow, 145 /etc/cron.d, 146 /etc/cron.deny, 145 /etc/crontab, 146 /etc/exports, 242, 252 /etc/filesystems, 51, 58 /etc/fstab, 54, 60, 67, 163, 243, 252 /etc/hostname, 206 /etc/inetd.conf, 249 /etc/init.d/, 131, 132 /etc/init.d/rc, 129 /etc/init.d/rcS, 128 /etc/inittab, 126, 128, 129 /etc/lvm/.cache, 92 /etc/modprobe.conf, 266 /etc/modprobe.d/, 266 /etc/mtab, 59, 127 /etc/network/interfaces, 200, 221, 224 /etc/passwd, 129 /etc/protocols, 197 /etc/raidtab, 75 /etc/rc.d/rc, 129 /etc/rc.d/rc.sysinit, 127 /etc/rcS.d/, 128 /etc/rcX.d/, 128 /etc/services, 197, 249 /etc/shutdown.allow, 137 /etc/ssh, 229 /etc/ssh/ssh_config, 229
/etc/ssh/sshd_config, 229 /etc/sysconfig/iptables, 245 /etc/sysconfig/network, 202 /etc/sysconfig/network-scripts/, 202 /etc/sysconfig/network-scripts/ifcfg-bond0, 222 /etc/syslog.conf, 153, 154 /etc/xinetd.conf, 248 /etc/xinetd.d, 248 /etc/yum.conf, 182 /etc/yum.repos.d/, 182 /lib, 272 /lib/modules, 263, 268 /lib/modules/<kernel-version>/modules.dep, 265 /proc/cmdline, 256 /proc/devices, 43, 43 /proc/filesystems, 51, 58 /proc/kallsyms, 262 /proc/mdstat, 75 /proc/meminfo, 160, 161 /proc/modules, 263 /proc/mounts, 59 /proc/net/bonding, 222, 224 /proc/partitions, 43 /proc/scsi/scsi, 35 /proc/swaps, 162 /sbin, 204 /sbin/init, 126 /sbin/mingetty, 129 /sbin/telinit, 135 /usr/lib, 272 /usr/share/doc, 202 /usr/src, 258 /var/lib/nfs/etab, 242, 252 /var/lib/rpm, 177 /var/log/auth.log, 152 /var/log/btmp, 150, 151 /var/log/lastlog, 150 /var/log/messages, 256, 271 /var/log/secure, 152 /var/log/wtmp, 136, 150 /var/run/utmp, 150 ./configure, 185 .deb, 167 .rpm, 167 .ssh, 233 ~/.ssh/authorized_keys, 234
286
Index $$, 4 $PPID, 4 chkconfig(8), 131 CHS, 29 Cisco, 196 cpio(1), 177, 281 cron(8), 142 crontab(1), 145 crontab(5), 145 Ctrl-Alt-Delete, 136, 137 Ctrl-Z, 22 cylinder, 29
A
access time, 29 active partition, 120 Alica and Bob, 230 anycast, 194 apt-get(8), 168, 171 aptitude, 273 aptitude(1), 259 aptitude(8), 168, 174 arp(1), 207 arp(protocol), 215 arp table, 207 at(1), 142, 143 ata, 29 atapi, 30 atm, 195 atq(1), 143 atrm(1), 143
D
daemon, 3, 130 dd(1), 46, 115, 162, 281 deb(5), 168 debsums, 273 default(grub), 117, 119 default gateway, 208 depmod(1), 265 device driver, 43 devices.txt, 43 df(1), 60, 60 dhclient(1), 205 dhcp, 202, 215 dhcp client, 200, 205 directory, 50 disk platters, 29 dmesg(1), 33 dmesg(8), 257 dns, 215 DOS, 120 dpkg(8), 168, 170 dpkg -S, 273 dsa, 230 du(1), 60 dump(1), 280
B
badblocks(8), 36 bg(1), 23 Bill Callkins, 115 binding, 220 binding(ip), 219 BIOS, 114 block device, 29 bonding(ip), 219 boot(grub), 118 bootloader, 116 bootp, 202, 215 broadcast, 194 BSD, 114 btrfs, 51 bum(8), 134 bzImage, 118 bzip2(1), 118, 277
E
e2fsck(1), 54 echo(1), 4 egrep, 127 elilo, 116 el torito, 51 Eric Allman, 153 eth0, 200 ethtool(1), 209 Evi Nemeth, 130 exec, 5
C
cable select, 30 Canonical, 126 chainloader, 120 chainloading, 120 character device, 29 chattr(1), 280 chkconfig, 131
287
Index exportfs(1), 242, 252 ext2, 50, 53 ext3, 50 extended partition, 42 ifcfg(1), 220 ifcfg-eth0, 203 ifconfig(1), 204, 205, 220, 221, 222, 224 ifdown(1), 201, 203, 205, 220 ifenslave, 224 ifup(1), 201, 203, 205, 220, 221, 222 igmp, 197 inetd, 248 init, 3, 126, 136 init=/bin/bash, 256 initiator(iSCSI), 104 initng, 126 initrd, 261 initrd(grub), 119 insmod(1), 264, 265 Intel, 114 iptables, 245 iSCSI, 104 iscsiadm, 107 iso9660, 51, 282
F
fallback(grub), 117 fat16, 51 fat32, 51 fd (partition type), 74 fddi, 195 fdisk, 107 fdisk(1), 43, 44, 45, 74 fdisk(8), 32 fg(1), 23 file system, 49 fixed ip, 202 fixed ip address, 200 fork, 5 FQDN, 206 frame relay, 195 free(1), 160, 161 fsck(1), 54 ftp, 248 ftp://ftp.kernel.org, 257
J
jbod, 72 jobs, 22 joliet, 51 journaling, 50
G
gateway, 208 grep, 127, 263 grub, 116, 116, 120 grub-install, 121 gzip(1), 118, 277
K
Kerberos, 241, 252 kernel(grub), 118 kill(1), 3, 8, 8, 130, 130 killall(1), 9 kmyfirewall, 245
H
halt(8), 136 hdparm(8), 37 head (hard disk device), 29 hiddenmenu(grub), 117 hostname, 206 hostname(1), 206 http://www.kernel.org, 257
L
LAN, 195 last(1), 136, 150 lastb(1), 151 lastlog(1), 150 LBA, 29 ldap, 242 ldd, 272 libraries, 272 lilo, 116, 116, 121 lilo.conf, 121 logger(1), 155 logical drive, 42 logical drives, 46 login, 150 288
I
icmp, 197 id_dsa, 234 id_dsa.pub, 234 id_rsa, 234 id_rsa.pub, 234 ide, 43
Index logrotate(1), 156 lsmod, 263 lsmod(1), 263 lsscsi(1), 34 ltrace, 273 lvcreate(1), 82, 84, 99 lvdisplay(1), 85, 94 lvextend(1), 85, 100 LVM, 80 lvmdiskscan(1), 90 lvol0, 99 lvremove(1), 99 lvrename(1), 100 lvs(1), 94 lvscan(1), 94 mount(1), 57, 59, 243, 252 mounting, 57 mount point, 58 mt(1), 277 multicast, 193
N
netstat(1), 208 network file system, 240 nfs, 240, 241 NFS, 251 nice, 17 nice(1), 15 no_subtree_check(nfs), 242 noacl(mount), 62 nodev, 51, 58 noexec(mount), 61 nosuid(mount), 62
M
mac address, 205 major number, 43 make, 270 make(1), 185 make bzImage, 267 make clean, 267 make menuconfig, 267 make modules, 268 make mrproper, 267 make xconfig, 267 MAN, 196 master (hard disk device), 30 master boot record, 46, 115 mbr, 46, 46, 115 MBR, 282 mdadm(1), 75 mingetty, 129 minor number, 43 mirror, 72 mkdir, 58 mke2fs(1), 50, 53, 84 mkfifo, 15 mkfile(1), 162 mkfs(1), 50, 53 mkinitrd(1), 50, 269 mknod(1), 276 mkswap(1), 162 modinfo, 271 modinfo(1), 264 modprobe(1), 265, 266 mount, 58
O
od(1), 116 OpenBoot(Sun), 115 OpenBSD, 229 openssh, 229 openssh-server, 236 OS/2, 120
P
package management, 167 paging, 160 PAN, 196 Parallel ATA, 30 parity(raid), 72 parted(1), 44 partition, 42 partition table, 46, 46 partprobe(1), 46 password(grub), 118 pgrep(1), 6 PID, 3 pidof(1), 4 ping, 197, 208 pipes, 15 pkill(1), 9 portmap, 241, 251 POST, 114 poweroff(8), 136 Power On Self Test, 114 PPID, 3 289
Index primary partition, 42, 115, 120 private key, 230 process, 3 process id, 3 ps, 5 ps -ef, 6 ps fax, 6 public key, 230 pvchange(1), 96 pvcreate(1), 82, 84, 95 pvdisplay(1), 84, 91 pvmove(1), 96 pvremove(1), 95 pvresize(1), 95 pvs(1), 90 pvscan(1), 90 rsh, 229 runlevel, 126 runlevel(1), 135
S
sata, 30 savedefault(grub), 119 scp(1), 234 scsi, 29 scsi_info(1), 35 scsi id, 30 sector, 29 seek time, 29 service(1), 131, 245 setuid, 62 sfdisk(1), 46 shutdown(8), 135 SIGHUP, 8 SIGKILL, 135 SIGTERM, 9, 135 silo, 116 single user mode, 256 slave (hard disk device), 30 SMF, 126 Solaris, 114 SPARC, 115 split(1), 283 ssh, 229 ssh_host_dsa_key, 236 ssh_host_dsa_key.pub, 236 ssh_host_rsa_key, 236 ssh_host_rsa_key.pub, 236 sshd, 236 ssh-keygen, 234 ssh-keygen(1), 233 ssh -X, 235 stanza(grub), 118 strace, 274 striped disk, 72 su, 272 subtree_check(nfs), 242 Sun, 114, 126 swapoff(1), 162 swapon(1), 162 swap partition, 51 swap partition(s), 164 swapping, 160 swap space, 162
R
RAID, 71 raid 1, 72 reboot(8), 136 reiserfs, 51 renice, 16 renice(1), 15 repository, 167, 168 resize2fs(1), 85 respawn(init), 129, 129 restore(1), 280 rfc 3010, 241 rfc 3530, 241 rlogin, 229 rmmod(1), 265 rock ridge, 51 root(grub), 119 root servers(DNS), 194 rootsquash, 242, 252 rotational latency, 29 route(1), 208, 208 router, 196 rpc, 241 RPC, 251 rpcinfo(1), 241, 251 rpm, 176 rpm(8), 168 rpm2cpio(8), 177 rpm -qf, 273 rpm -V, 274 rsa, 230
290
Index swat, 248 sysctl(1), 206 syslog, 256 syslogd, 153 System.map, 262 system-config-securitylevel, 245 System V, 126 vol_id(1), 67
W
WAN, 195 watch(1), 155 who(1), 135, 150 wireshark, 213, 229 WPAN, 196
T
tail(1), 155 tar(1), 185, 278, 279 tcp, 197, 241 tcpdump, 213, 216 telinit(8), 135 telnet, 229, 248 time(1), 267 timeout(grub), 117 title(grub), 118 top, 9 top(1), 7, 160, 161 track, 29 tune2fs(1), 50, 53, 67
X
X.25, 195 x86, 114 xinetd, 248, 248
Y
yaboot, 116 yum, 274 yum(8), 179
Z
z/IPL, 116 zfs, 51 zImage, 118 zombie, 3
U
udf, 51 udp, 197, 241 uname(1), 255 universally unique identifier, 67 update-rc.d, 131 update-rc.d(8), 133 upstart, 126 uuid, 67
V
vanilla, 168 vfat, 51 vgchange(1), 98 vgcreate(1), 82, 84, 97 vgdisplay(1), 92 vgextend(1), 97 vgmerge(1), 98 vgreduce(1), 97 vgremove(1), 97 vgs(1), 92 vgscan(1), 92 vi, 274 virtual memory, 160 vmlinuz, 261 vmstat, 164 291