Linux Foundation Certified System Administrator (LFCS) Exam Preparation Notes
Linux Foundation Certified System Administrator (LFCS) Exam Preparation Notes
Administrator (LFCS)
I would like to thank Toby Meehan, LFCS for proof reading the document and giving some very
helpful suggestions.
Throughout this document I am ably assisted by Luigi Menabrea, Ada Lovelace and Charles
Babbage. All of these individuals were key to the development of the famous analytical engine
of 1830s and 40s fame from which modern computing can trace its origins.
Babbage developed the analytical engine after a number of attempts to build a difference
engine, made to compute values of polynomial functions. The Analytical Engine is the transition
to general purpose computation from mechanised calculators.
Luigi went on to serve as the 7th Prime Minister of Italy from 1867 to 1869. His sketch of “The
Analytical Engine” Invented by Charles Babbage, Esq while a military engineer was translated
by Ada Augusta, Countess of Lovelace in 1842. These notes included additional detail that
Lovelace is now widely recognised as the world's first computer program and therefore Ada is
credited as being the first computer programmer.
Charles Babbage
2 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Table of Contents
1. Local system administration...........................................................................................................5
1.1. Creating backups...............................................................................................................................5
1.2. Managing local users accounts........................................................................................................5
1.3. Managing user accounts...................................................................................................................6
1.4. Managing user account attributes...................................................................................................6
1.5. Creating local user groups..............................................................................................................10
1.6. Managing file permissions..............................................................................................................11
1.7. Managing fstab entries....................................................................................................................15
1.8. Restoring backed up data..............................................................................................................16
1.9. Setting file permissions and ownership.........................................................................................16
1.10. Managing user processes............................................................................................................17
1.11. Managing the startup process and related services.................................................................20
2. Command-line...............................................................................................................................27
2.1. Editing text files on the command line...........................................................................................27
2.2. Manipulating text files from the command line.............................................................................29
3. File-system & Storage..................................................................................................................39
3.1. Archiving and compressing files and directories.........................................................................39
3.2. Logical Volume Manager (LVM)....................................................................................................41
3.3. Assembling partitions as Redundant Array of Independent Disks (RAID) devices................53
3.4. Configuring swap partitions............................................................................................................63
3.5. File attributes....................................................................................................................................65
3.6. Finding files on the file-system.......................................................................................................69
3.7. Formatting file-systems...................................................................................................................73
3.8. Mounting file-systems automatically at boot time........................................................................80
3.9. Mounting networked file-systems..................................................................................................84
3.10. Partitioning storage devices.........................................................................................................91
3.11. Troubleshooting file-system issues.............................................................................................91
4. Local security.................................................................................................................................93
4.1. Accessing the root account............................................................................................................93
4.2. Using sudo to manage access to the root account.....................................................................94
5. Shell scripting................................................................................................................................99
5.1. Basic bash shell scripting...............................................................................................................99
6. Software management...............................................................................................................111
6.1. Installing software packages........................................................................................................111
7. Additional handy tools for exam.................................................................................................113
7.1. Using tmux......................................................................................................................................113
7.2. Calculator........................................................................................................................................114
GNU Free Documentation License................................................................................................115
Diarmuid Ó Briain 3
Linux Foundation Certified System Administrator (LFCS)
The Linux Foundation Certified System Administrator (LFCS) examination is a practical test
based on the command line. Familiarity with the GNU/Linux command line is essential in order
to pass. Establish a Virtual Machine (VM) that you do not mind “breaking” and work with it.
KVM or Oracle VirtualBox are good candidates for this.
4 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ file /home.tgz
home.tgz: gzip compressed data, from Unix, last modified: Tue Oct 21 10:38:46
2014
$ file /home.tbz2
home.tbz2: bzip2 compressed data, block size = 900k
$ file /home.xz
home.xz: XZ compressed data
Diarmuid Ó Briain 5
Linux Foundation Certified System Administrator (LFCS)
$ su alovelace
Password: maths
$ id
uid=1002(alovelace) gid=1002(alovelace) groups=1002(alovelace)
Add Ada Lovelace to the babbage group as a secondary in addition to the primary alovelace
group.
6 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
PAM is a common framework for authentication and security. PAM provides a mechanism for
programs who need to access other programs to centrally authenticate instead of having to
contain the authentication function within itself. PAM gives the system administrator the
flexibility to set authentication policies for the system. A particular PAM module the pam_limits
sets limits on the system resources that can be obtained in a user-session, even uid=0. These
limits are taken by the module from the /etc/security/limits.conf or from individual *.conf files
in the /etc/security/limits.d/. Files are of the format.
* soft core 0
root hard core 100000
* hard rss 10000
@student hard nproc 20
@faculty soft nproc 20
@faculty hard nproc 50
ftp hard nproc 0
• Domain
• Username
• Group (group has the '@' before it as in @ababbage)
• * wildcard
• % group wildcard.
• Type
• hard resource limits set by the superuser and enforced by the Kernel.
• soft resource limits can be moved up or down within the permitted range
permitted by hard limits. These can be thought of as default values.
Diarmuid Ó Briain 7
Linux Foundation Certified System Administrator (LFCS)
• Item
• core - limits the core file size (KB).
• data - maximum data size (KB).
• fsize - maximum filesize (KB).
• memlock - maximum locked-in-memory address space (KB).
• nofile - maximum number of open files.
• stack - maximum stack size (KB).
• cpu - maximum CPU time (minutes).
• nproc - maximum number of processes.
• as - address space limit (KB).
• maxlogins - maximum number of logins for this user except for this with uid=0.
• maxsyslogins - maximum number of all logins on system.
• priority - the priority to run user process with (negative values boost process
priority).
• locks - maximum locked files.
• sigpending - maximum number of pending signals.
• msgqueue - maximum memory used by POSIX message queues (bytes).
• nice - maximum nice priority allowed to raise to values: [-20,19].
• rtprio - maximum realtime priority allowed for non-privileged processes.
• chroot - the directory to chroot the user to.
• Value
Add a limit configuration file for Ada Lovelace limiting her to 50 user processes.
$ ulimit -u
max user processes (-u) 60201
$ sudo -s
# echo -e "alovelace\thard\tnproc\t50" >> /etc/security/limits.d/alovelace.conf
# exit
$ cat /etc/security/limits.d/alovelace.conf
alovelace hard nproc 50
$ ulimit -u
max user processes (-u) 50
8 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Set Ada Lovelace's account expiration date to 1st December 2014, the minimum number of
days before password change to ten and the maximum number of days before password
change to twenty.
Setting the date of last password change to zero forces a password change at the next login.
Diarmuid Ó Briain 9
Linux Foundation Certified System Administrator (LFCS)
The following sequence of attempts to change the password gives some idea of the general
restrictions.
$ su - alovelace
Password:
You are required to change your password immediately (root enforced)
Changing password for alovelace.
(current) UNIX password: maths
Enter new UNIX password: maths
Retype new UNIX password: maths
Password unchanged
Enter new UNIX password: ada
Retype new UNIX password: ada
You must choose a longer password
Enter new UNIX password: ada123
Retype new UNIX password: ada123
Bad: new password is too simple
su: Authentication token manipulation error
$ su - alovelace
Password:
You are required to change your password immediately (root enforced)
Changing password for alovelace.
(current) UNIX password: maths
Enter new UNIX password: multiply
Retype new UNIX password: multiply
alovelace~$ id
uid=1001(alovelace) gid=1001(alovelace) groups=1001(alovelace)
In practice the group password is not that useful. It was conceived to allow a user who does not
have access to a particular group to use the newgrp command to award such a group access.
In this case the group password would be used in response to the system challenge.
10 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Change the permissions on the directory to give the group Read, Write and eXecute (RWX)
permissions.
Create two files, one owned by Luigi Menabrea and the other by Ada Lovelace in the sandbox
directory.
$ ls -la
total 16
drwxrwxr-x 2 lmenabrea babbage 4096 Oct 21 15:55 .
drwxr-xr-x 6 lmenabrea lmenabrea 4096 Oct 21 15:50 ..
-rw-r--r-- 1 lmenabrea lmenabrea 34 Oct 21 15:54 file1.txt
-rw-rw-r-- 1 alovelace alovelace 30 Oct 21 15:55 file2.txt
$ cat file1.txt
This is a Luigi Menabrea file.
$ cat file2.txt
This is an Ada Lovelace file.
Why can Ada Lovelace write in the directory ? Well she is part of the babbage group and as
the directory has RW permissions for the babbage group she has rights to Read and Write
files.
Diarmuid Ó Briain 11
Linux Foundation Certified System Administrator (LFCS)
Adjustable attributes
• A - no atime updates
• a - append only
• C - no copy on write
• c - compressed
• D - synchronous directory updates
• d - no dump
• e - extent format
• i - immutable (Superuser only)
• j - data journalling
• S - synchronous updates
• s - secure deletion
• T - top of directory hierarchy
• t - no tail-merging
• u - undeletable
To demonstrate create a directory and a file and review the associated extended attributes.
Only e is set which indicates that the file is using extents for mapping the blocks on disk.
Remove it and replace it again from the adafile.
$ mkdir adadirectory
$ touch adafile
$ lsattr
-------------e-- ./adadirectory
-------------e-- ./adafile
$ chattr -e adafile
$ lsattr adafile
---------------- adafile
$ chattr +e adafile
$ lsattr adafile
-------------e-- adafile
12 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Now set the immutable attribute on the file. This will prevent deletion or renaming of the file. It
will also prevent all but the superuser from writing data to the file. It can only be set with
superuser privileges.
$ lsattr adafile
----i--------e-- adafile
$ rm adafile
rm: remove write-protected regular file ‘adafile’? yes
rm: cannot remove ‘adafile’: Operation not permitted
$ mv adafile ADAfile
mv: cannot move ‘adafile’ to ‘ADAfile’: Operation not permitted
To securely delete a file where its blocks are zeroed and written back to the disk set the s
attribute.
$ sudo chattr =es adafile
$ lsattr adafile
s------------e-- adafile
Another interesting attribute is the A which tells the filesystem to NOT update the file's atime.
This cuts down on disk access which is good for extending the life of an Solid State Drive
(SSD) or extending the life of a laptop battery. While this can be done with this extended
attribute the more typical method is to mount the filesystem with the noatime option. Note in
the example that once the A is set the Access time remains constant.
$ stat adafile
File: ‘adafile’
Size: 86 Blocks: 8 IO Block: 4096 regular file
Device: fc01h/64513d Inode: 12194930 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/lmenabrea) Gid: ( 1000/lmenabrea)
Access: 2014-11-26 06:36:58.176489751 +0000
Modify: 2014-11-26 06:40:13.100481599 +0000
Change: 2014-11-26 06:46:18.964466297 +0000
Birth: -
$ cat adafile
Ada Lovelace file
$ stat adafile
File: ‘adafile’
Size: 86 Blocks: 8 IO Block: 4096 regular file
Device: fc01h/64513d Inode: 12194930 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/lmenabrea) Gid: ( 1000/lmenabrea)
Access: 2014-11-26 06:46:43.928465253 +0000
Modify: 2014-11-26 06:40:13.100481599 +0000
Change: 2014-11-26 06:46:18.964466297 +0000
Birth: -
$ chattr +A adafile
Diarmuid Ó Briain 13
Linux Foundation Certified System Administrator (LFCS)
$ cat adafile
Ada Lovelace file
$ stat adafile
File: ‘adafile’
Size: 86 Blocks: 8 IO Block: 4096 regular file
Device: fc01h/64513d Inode: 12194930 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/lmenabrea) Gid: ( 1000/lmenabrea)
Access: 2014-11-26 06:46:43.928465253 +0000
Modify: 2014-11-26 06:40:13.100481599 +0000
Change: 2014-11-26 06:47:04.464464394 +0000
Birth: -
The setfacl utility is used to set ACLs for files and directories. ACLs can be added or modified
using the -m switch option. Here are a number of examples. First get the ACL details for the
sandbox directory using the getfacl sister utility.
$ getfacl sandbox
# file: sandbox
# owner: lmenabrea
# group: babbage
user::rwx
group::rwx
other::r-x
14 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ cat /etc/fstab
Diarmuid Ó Briain 15
Linux Foundation Certified System Administrator (LFCS)
$ cd /
$ sudo tar -xzvf /home.tgz
$ cd /
$ sudo tar -xjvf /home.tbz2
$ cd /
$ sudo tar -xJvf /home.xz
$ chmod +x hello.sh
$ ./hello.sh
Hello World
$ chmod -x hello.sh
Change the group of the script to babbage and give it group eXecute permissions.
16 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Note that the owner cannot run the script however Ada Lovelace who belongs to the babbage
group can.
$ ./hello.sh
bash: ./hello.sh: Permission denied
$ su alovelace
Password: maths
sandbox> ./hello.sh
Hello World
$ su alovelace
Password: maths
sandbox> stress --cpu 3
stress: info: [4939] dispatching hogs: 3 cpu, 0 io, 0 vm, 0 hdd
1.10.1. top/htop
Monitor processes using top.
$ top
Diarmuid Ó Briain 17
Linux Foundation Certified System Administrator (LFCS)
$ htop
$ ps -A | grep stress
4939 pts/2 00:00:00 stress
4940 pts/2 00:07:42 stress
4941 pts/2 00:07:42 stress
4942 pts/2 00:07:42 stress
$ pgrep stress
5224
5225
5226
5257
5258
5259
5260
18 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ pgrep stress
5225
5226
5257
5258
5259
5260
$ pgrep stress
1.10.4. nice/renice
nice is a utility for managing scheduling priority of processes. Nice values range from -19 (very
high priority) to 19 (very low priority) with a value of 0 being the default priority. Looking at the
top output, the column marked NI indicated the current nice value of each process.
$ top
$ top
Diarmuid Ó Briain 19
Linux Foundation Certified System Administrator (LFCS)
20 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
1.11.2. Runlevels
Runlevels are sets of system configurations. Runlevels for Debian and Ubuntu systems are:
The default runlevel is 2.
Level Description
0 System halt.
1 Single-User mode.
2 Graphical multi-user plus networking.
3 Same as "2", but not used.
4 Same as "2", but not used.
5 Same as "2", but not used.
6 System reboot.
$ runlevel
N 2
$ sudo reboot
Diarmuid Ó Briain 21
Linux Foundation Certified System Administrator (LFCS)
22 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
1.11.3.1. SysV
SystemV (SysV) is the traditional UNIX/Linux init system. It is essentially a number of process
management scripts grouped into runlevels.
• /etc/init.d contains the actual scripts for each process (service).
• rc0.d - The symbolic links in this directory are executed once when entering runlevel 0 (Halt).
• rc1.d - The symbolic links in this directory are executed once when entering runlevel 1
(Single-User mode).
• rc2.d - The symbolic links in this directory are executed once when entering runlevel 2
(Graphical multi-user plus networking).
• rc3.d - The symbolic links in this directory are executed once when entering runlevel 3
(Same as 2 - Not used).
• rc4.d - The symbolic links in this directory are executed once when entering runlevel 4
(Same as 2 - Not used).
• rc5.d - The symbolic links in this directory are executed once when entering runlevel 5
(Same as 2 - Not used).
• rc6.d - The symbolic links in this directory are executed once when entering runlevel 6
(Same as 2 - Not used).
• rcS.d - The symbolic links in this directory whose names begin with an 'S' are executed once
when booting the system.
The actual scripts are all contained in the /etc/init.d directory. Each of the other rcX.d
directories contain Start and Stop symbolic links to the scripts in /etc/init.d. These scripts are
named either SXX<name> or KXX<name> where:
• S - Start
• K - Stop
• XX - Order number
• <name> - name of script in /etc/init.d
$ file /etc/rc1.d/K20hddtemp
/etc/rc1.d/K20hddtemp: symbolic link to `../init.d/hddtemp'
If a new script is added to /etc/init.d, manual symbolic links can be created in the various
rcX.d directories or a script called update-rc.d can be used to make links to start the service
in runlevels 2345 and to stop the service in runlevels 016.
Diarmuid Ó Briain 23
Linux Foundation Certified System Administrator (LFCS)
Individual scripts can be ran directly from /etc/init.d (or with the service utility described
below). Here is an example stopping the Apache2 Server.
/etc/init.d $ ./apache2
Usage: apache2 {start|stop|graceful-stop|restart|reload|force-reload|start-
htcacheclean|stop-htcacheclean}
24 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
service
Use of the service utility with command options. Typical options in the scripts are:
• start
• stop
• restart
• reload
• status
• list
• show
$ service --status-all
[ + ] acpid
[ - ] anacron
[ + ] apache2
[ + ] atd
[ + ] atop
[ + ] avahi-daemon
[ ? ] binfmt-support
[ + ] bluetooth
[ - ] brltty
[ + ] btsync
[ - ] casper
[ ? ] console-setup
[ ? ] cpufrequtils
$ service apache2
Usage: apache2 {start|stop|graceful-stop|restart|reload|force-reload|start-
htcacheclean|stop-htcacheclean}
Diarmuid Ó Briain 25
Linux Foundation Certified System Administrator (LFCS)
1.11.3.2. Upstart
1.11.3.3. systemd
Use of the systemctl utility with command options. Typical options in the scripts are:
• start
• stop
• restart
• reload
• status
• list
• show
$ systemctl status networking
networking start/running
26 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
2. Command-line
2.1.1. VI
vim is the Vi IMproved, a programmers text editor.
Save and Exit
:q[uit] Quit Vim. This fails when changes have been made.
:wq! Write the current file and exit always.
Inserting Text
a Append text after the cursor [count] times.
A Append text at the end of the line [count] times.
i Insert text before the cursor [count] times.
I Insert text before the first non-blank in the line [count] times.
gI Insert text in column 1 [count] times.
o Begin a new line below the cursor and insert text, repeat [count] times.
O Begin a new line above the cursor and insert text, repeat [count] times.
<ESC> Escape from edit mode.
Deleting text
<Del> Delete [count] characters under and after the cursor.
x Delete [count] characters under and after the cursor.
X Delete [count] characters before the cursor.
d{motion} Delete text that {motion} moves over.
dd Delete [count] lines.
D Delete the characters under the cursor until the end of the line.
Undo|Redo |Repeat
u Undo [count] changes.
:u[ndo] Undo one change.
CTRL-R Redo [count] changes which were undone.
:red[o] Redo one change which was undone.
U Undo all latest changes on one line. {Vi: while not moved off of it}.
. Repeat last change, with count replaced with [count].
Diarmuid Ó Briain 27
Linux Foundation Certified System Administrator (LFCS)
Searching
/{pattern}[/] Search forward for the [count]'th occurrence of {pattern}.
/<CR> Search forward for the [count]'th latest used pattern.
?<CR> Search backward for the [count]'th latest used pattern.
n Repeat the latest "/" or "?" [count] times.
N Repeat the latest "/" or "?" [count] times in opposite direction.
Moving Around
Basic motion commands:
h Move left one character (or left arrow).
l Move Right one character (or right arrow).
k Move up one line (or up arrow).
j Move down one line (or down arrow).
0 To the first character of the line.
<Home> To the first character of the line.
^ To the first non-blank character of the line.
$ To the end of the line.
<End> To the end of the line.
2.1.2. VIm
Follow the sequence below to practice creating and editing a file using vim.
$ vi file3.txt
[Press i] The quick brown fox jumps over the lazy dog. [Press ESC :wq]
$ cat file3.txt
The quick brown fox jumps over the lazy dog.
$ vi file3.txt
The quick brown fox jumps over the lazy dog. [Press o]
[Press CR]
He is then shot by the farmer. [Press ESC :wq]
$ vi file3.txt
The quick brown fox jumps over the lazy dog. [Press j twice (or scroll down to
last line]
$ cat file3.txt
The quick brown fox jumps over the lazy dog.
28 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
2.2.2. nano
Alternatively use GNU nano. Nano is ANOther editor, an enhanced free Pico clone
$ nano file3.txt
• Press Control - X.
• Press Y.
• Confirm filename, Press CR.
$ cat printer.txt
My printer will drive me insane,
I'm always refilling its ink,
it empties my purse,
to make matters worse,
it's usually on the blink!
Diarmuid Ó Briain 29
Linux Foundation Certified System Administrator (LFCS)
2.2.1. tac
The tac command is the inverse of cat. It prints files in reverse.
$ cat users.txt
lmenabrea
cbabbage
alovelace
$ tac users.txt
alovelace
cbabbage
lmenabrea
$ cat printer.txt
My printer will drive me insane,
I'm always refilling its ink,
it empties my purse,
to make matters worse,
it's usually on the blink!
30 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Well in the first output the first lowercase a instance on each line is replaced by an uppercase
A. In the second example the addition of the g or global flag changes every instance of a to A.
What about special characters ? Lets replace ' with “.
To print out lines in a file found by a pattern and suppress the other lines use the -n quiet
option. The p flag indicates print the lines found.
To overwrite (edit) a file sed must be used with the -i option which creates a backup of the file
being edited first. A file extension is provided, in this case .bak.
$ cat printer.txt
My printer will drive me insane,
I'm always refilling its ink,
it empties my purse,
to make matters worse,
it's usually on the blink!
$ cat printer.txt
My scanner will drive me insane,
I'm always refilling its ink,
it empties my purse,
to make matters worse,
it's usually on the blink!
$ cat printer.txt.bak
My printer will drive me insane,
I'm always refilling its ink,
it empties my purse,
to make matters worse,
it's usually on the blink!
Diarmuid Ó Briain 31
Linux Foundation Certified System Administrator (LFCS)
Example to change all white space to a single space, making parsing with other commands
easier.
$ cat printer.txt
My scanner will drive me insane,
I'm always refilling its ink,
it empties my purse,
to make matters worse,
it's usually on the blink!
$ cat printer.txt
My scanner will drive me insane,
I'm always refilling its ink,
it empties my purse,
to make matters worse,
it's usually on the blink!
$ cat printer.txt.bak
My scanner will drive me insane,
I'm always refilling its ink,
it empties my purse,
to make matters worse,
it's usually on the blink!
32 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
2.2.3. grep
The grep utility is a powerful pattern search tool. There are numerous options so only some
common ones are listed here.
Option Meaning
-c Count instead of presenting results
-E Extended regular expression
-H Print the file name for each match
-h Suppress the prefixing of file names on output
-i Ignore case
-l List only filenames that contain matches
-n Prefix output with line number
-r Recursive
-s No messages, suppress error messages
-v Invert match
$ ls /home
alovelace cbabbage lmenabrea
Diarmuid Ó Briain 33
Linux Foundation Certified System Administrator (LFCS)
/etc/group:sudo:x:27:lmenabrea,alovelace
/etc/group:alovelace:x:1002:alovelace
/etc/group:babbage:x:1003:alovelace
/etc/subgid:alovelace:231072:65536
/etc/group-:alovelace:x:1002:alovelace
/etc/group-:babbage:x:1003:alovelace
Recursively search but supress the filename at the beginning of the line.
$ sudo grep -rh alovelace /etc/
alovelace:!::alovelace
babbage:
$6$Lo92oBZTUm/H$qw5oIp55D.uy3E5xnzZpHKlO3R5sjJwxayizt1vqbFmLzkcnVdD3RJUhC6WbwGyaL
shRv6EtofdFDLAbdrp7X/::alovelace
sudo:*::lmenabrea,alovelace
alovelace:!::alovelace
babbage:
$6$Lo92oBZTUm/H$qw5oIp55D.uy3E5xnzZpHKlO3R5sjJwxayizt1vqbFmLzkcnVdD3RJUhC6WbwGyaL
shRv6EtofdFDLAbdrp7X/::alovelace
alovelace:231072:65536
alovelace:x:1002:1003:Ada Lovelace:/home/alovelace:/usr/bin/tcsh
alovelace:231072:65536
alovelace:x:1002:27:Ada Lovelace:/home/alovelace:/usr/bin/tcsh
alovelace:
$6$DnyWC4UQ$8bS26d/yiiRdnlj8PTDD8KQpc.bWrDfMCqDcC1FE6XoUDMMDJ6tyn/ZbghwIiUL57kAvc
PpDd2CoF5bWJl2wA/:0:0:99999:7:::
alovelace:231072:65536
alovelace:
$6$DnyWC4UQ$8bS26d/yiiRdnlj8PTDD8KQpc.bWrDfMCqDcC1FE6XoUDMMDJ6tyn/ZbghwIiUL57kAvc
PpDd2CoF5bWJl2wA/:16369:0:99999:7:::
sudo:x:27:lmenabrea,alovelace
alovelace:x:1002:alovelace
babbage:x:1003:alovelace
alovelace:231072:65536
alovelace:x:1002:alovelace
babbage:x:1003:alovelace
Recursively search files and output only the files that contain matches.
$ sudo grep -rl alovelace /etc/
/etc/gshadow-
/etc/gshadow
/etc/subuid
/etc/passwd
/etc/subgid-
/etc/passwd-
/etc/shadow
/etc/subuid-
/etc/shadow-
/etc/group
/etc/subgid
/etc/group-
Use a regular expression to extract groups where Ada Lovelace is the first listed member.
34 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
2.2.4. cut
The cut command filters out fields or columns. Typical options are:
Option Meaning
-d Define field delimiter (default is tab)
-c list Cut by column position
-f list Cut by field number
$ id
uid=1000(lmenabrea) gid=1000(lmenabrea) groups=1000(lmenabrea),4(adm),6(disk),
24(cdrom),27(sudo),30(dip),46(plugdev),108(lpadmin),110(sambashare)
2.2.5. sort
The sort command is used to sort lines of text files. There are a number of options so here are
just some of the most used.
Option Meaning
-b Ignore leading blanks
-f Ignore case
-r Reverse order
-R Random sort
$ ls /home
alovelace
cbabbage
lmenabrea
$ ls /home | sort -r
lmenabrea
cbabbage
alovelace
2.2.6. tr
The tr translate command translates characters in a file from one form to another.
Option Meaning
-d Delete characters in SET1
-s Squeeze repeats
-t Truncate SET1 to length of SET2
Diarmuid Ó Briain 35
Linux Foundation Certified System Administrator (LFCS)
$ cat printer2.txt
My printer will drive me to drink,
I'm always refilling its paper,
it empties my wallet,
to make matters worse,
it’s usually broken!
Another useful option is the -s or --squeese-repeats. In the example multiple blanks are
replaced by a single blank.
$ cat printer3.txt
My printer will drive me to drink,
I'm always refilling its paper,
it empties my wallet,
Another example removes the horizontal and vertical blanks and then replaces spaces with
tabs.
$ cat printer3.txt
My printer will drive me to drink,
I'm always refilling its paper,
it empties my wallet,
36 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
2.2.7. nl
To write a file to standard output with line numbers added use the nl command.
$ ls /home | nl > users.txt
$ cat users.txt
1 lmenabrea
2 cbabbage
3 alovelace
$ ls /home | nl | sed 's/^[ \t]* //g' | sed 's/\t/ /g' > users_list.txt
$ cat users_list.txt
1 alovelace
2 cbabbage
3 johnny
2.2.8. Join
The join command is used to join lines of two files on a common field. In the example the
common field is the line number, the output links these as shown.
$ cat roles.txt
1 mathematician
2 inventor
3 programmer
2.2.9. uniq
The uniq utility can be used to filter matching lines from input to output. The -c option prefix
lines by the number of occurrences while the -u switch option only prints unique lines. -w can
be used to compare no more than N characters in lines.
$ cat numbers.txt
1 2 5 3 3 4 8 9 7 6 5 4 3 2 5 6 7 8 9 1 2 5 3 3 4 8 9 7 6 5 4 3 2 5 6 7 8 9 1 2 5
3 3 4 8 9 7 6 5 4 3 2 5 6 7 8 9 1 2 5 3 3 4 8 9 7 6 5 4 3 2 5 6 7 8 9 1 2 5 3 3 4
8 9 7 6 5 4 3 2 5 6 7 8 9 1
Diarmuid Ó Briain 37
Linux Foundation Certified System Administrator (LFCS)
2.2.10. awk
awk is a pattern scanning and processing language. This is a whole language in itself so it is
best analise an example.
$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/mint--vg-root 451G 155G 273G 37% /
none 4.0K 0 4.0K 0% /sys/fs/cgroup
udev 3.7G 4.0K 3.7G 1% /dev
tmpfs 756M 1.7M 755M 1% /run
none 5.0M 0 5.0M 0% /run/lock
none 3.7G 27M 3.7G 1% /run/shm
none 100M 20K 100M 1% /run/user
/dev/sda1 236M 77M 147M 35% /boot
$ df -h | awk '/none/'
none 4.0K 0 4.0K 0% /sys/fs/cgroup
none 5.0M 0 5.0M 0% /run/lock
none 3.7G 27M 3.7G 1% /run/shm
none 100M 20K 100M 1% /run/user
38 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ $ file sandbox.tar
sandbox.tar: POSIX tar archive (GNU)
Review a tar archive with the -t or --list option to see a table of contents for the archive.
$ rm -r sandbox
$ ls sandbox
file1.txt file2.txt file3.txt hello.sh
3.1.0.1. Compression
The tar archive can be compressed to reduce file size. For example gzip which reduces the
size of files using Lempel-Ziv coding (LZ77) can be applied to the tarball. tar has the ability to
incorporate compression functions as well as archiving and perform both functions with the
same command.
$ tar sandbox.tar
$ ls -l |grep sandbox.tar
-rw-r--r-- 1 lmenabrea lmenabrea 506 Oct 24 13:49 sandbox.tar.gz
Diarmuid Ó Briain 39
Linux Foundation Certified System Administrator (LFCS)
$ gunzip sandbox.tar.gz
$ ls -l |grep sandbox.tar
-rw-r--r-- 1 lmenabrea lmenabrea 10240 Oct 24 13:49 sandbox.tar
An alternative approach is to use the bzip2 utility which uses the Burrows-Wheeler block
sorting text compression algorithm, and Huffman coding. bzip2 compression is generally
considerably better that the more conventional LZ77/LZ78-based compressors.
$ bzip2 sandbox.tar
$ ls -l |grep sandbox.tar
-rw-r--r-- 1 lmenabrea lmenabrea 507 Oct 24 13:49 sandbox.tar.bz2
The reverse process is similar to what has been seen for gunzip.
$ bunzip2 sandbox.tar.bz2
$ ls -l |grep sandbox.tar
-rw-r--r-- 1 lmenabrea lmenabrea 10240 Oct 24 13:49 sandbox.tar
Fortunately the tar utility offers the ability to both archive and compress in one operation, here
is an example using gzip. Note the file extension for a gzipped archives is either .tar.gz or
simply .tgz. The z switch in the command instructs that the directory be archived and gzipped.
$ ls -l |grep sandbox.tar
-rw-r--r-- 1 lmenabrea lmenabrea 451 Oct 24 13:56 sandbox.tar.gz
$ file sandbox.tar.gz
sandbox.tar.gz: gzip compressed data, from Unix, last modified: Fri Oct 24
13:56:47 2014
A similar process can be achieved for bzip2, the end extension being .tar.bz2 or .tbz2 by
convention. The j switch is used to archive and bzip2.
$ ls -l |grep sandbox.tar
-rw-r--r-- 1 lmenabrea lmenabrea 463 Oct 24 13:56 sandbox.tar.bz2
$ file sandbox.tar.bz2
sandbox.tar.bz2: bzip2 compressed data, block size = 900k
$ ls -l |grep sandbox.tar
-rw-r--r-- 1 lmenabrea lmenabrea 463 Oct 24 13:56 sandbox.tar.bz2
$ file sandbox.tar.xz
Sandbox.xz: XZ compressed data
40 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Comparing the relative sizes of the archive and the three compressed versions. When the
requirement is very fast compression, the gzip was the best option, it has also very small
memory footprint, making it ideal for systems with limited memory. bzip2 creates about 15%
smaller files than gzip on average however it compresses at a slower rate than gzip. For
decompression a similar picture emerges with gzip the fastest. bzip2 is a lot slower taking four
to twelve times more time to decompress than gzip. The newer xz is now showing to be slightly
better performance in terms of compression than the others.
$ ls -l | grep sandbox.tar
-rw-r--r-- 1 dobriain dobriain 27832320 Feb 16 13:40 sandbox.tar
-rw-r--r-- 1 dobriain dobriain 26269531 Feb 16 13:41 sandbox.tar.bz2
-rw-r--r-- 1 dobriain dobriain 26035700 Feb 16 13:40 sandbox.tar.gz
-rw-r--r-- 1 dobriain dobriain 25865068 Feb 16 13:41 sandbox.tar.xz
Referring to the diagram, the physical volumes sdd, sde and sdf are grouped together into a
logical volume vg0. Two logical volumes lv0 and lv1 are created on vg0 thereby allowing the
logical volumes to be numbered and sized without recourse to the size of the individual
physical volumes, save the overall size limitation of their sum.
Diarmuid Ó Briain 41
Linux Foundation Certified System Administrator (LFCS)
To demonstrate a number of additional drives are connected to the server. To view them use
the command lsblk.
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 8G 0 disk
├─sda1 8:1 0 7G 0 part /
├─sda2 8:2 0 1K 0 part
└─sda5 8:5 0 1022M 0 part [SWAP]
sdb 8:16 0 100M 0 disk
sdc 8:32 0 100M 0 disk
sdd 8:48 0 100M 0 disk
sde 8:64 0 250M 0 disk
sdf 8:80 0 150M 0 disk
sr0 11:0 1 1024M 0 rom
Taking the last three (sdd, sde, sdf) create partitions on each of type Linux LVM (id: 8e) using
fdisk.
42 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Perform the same action on the sde and sdf drives. When complete review all three.
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 8G 0 disk
├─sda1 8:1 0 7G 0 part /
├─sda2 8:2 0 1K 0 part
└─sda5 8:5 0 1022M 0 part [SWAP]
sdb 8:16 0 100M 0 disk
sdc 8:32 0 100M 0 disk
sdd 8:48 0 100M 0 disk
└─sdd1 8:49 0 99M 0 part
sde 8:64 0 250M 0 disk
└─sde1 8:65 0 249M 0 part
sdf 8:80 0 150M 0 disk
└─sdf1 8:81 0 149M 0 part
sr0 11:0 1 1024M 0 rom
Diarmuid Ó Briain 43
Linux Foundation Certified System Administrator (LFCS)
Initialise these disks for use by LVM with the pvcreate command.
Create as volume group into which the physical volumes are incorporated.
Now create logical volumes as necessary up to the limits on size imposed by the overall volume
group size. In this way the logical volumes loose the limitations of the physical volumes. Note
the middle command where I attempted to create a logical volume beyond the available space
remaining in the volume group.
$ sudo pvdisplay
--- Physical volume ---
PV Name /dev/sdd1
VG Name vg0
PV Size 99.00 MiB / not usable 3.00 MiB
Allocatable yes
PE Size 4.00 MiB
Total PE 24
Free PE 4
Allocated PE 20
PV UUID rl7d2z-dmUs-8p8I-hrSW-zViM-Di3x-7Bw0gb
44 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ sudo vgdisplay
--- Volume group ---
VG Name vg0
System ID
Format lvm2
Metadata Areas 3
Metadata Sequence No 3
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 2
Open LV 0
Max PV 0
Cur PV 3
Act PV 3
VG Size 492.00 MiB
PE Size 4.00 MiB
Total PE 123
Alloc PE / Size 119 / 476.00 MiB
Free PE / Size 4 / 16.00 MiB
VG UUID DFYG3z-dTyu-9sQq-RMys-T8Rn-n2Vm-kacVte
$ sudo lvdisplay
--- Logical volume ---
LV Path /dev/vg0/lv0
LV Name lv0
VG Name vg0
LV UUID 2cyBm2-0u7C-wBR8-DMjZ-p4lb-gJLW-CmLubL
LV Write Access read/write
LV Creation host, time ubuntu-vm, 2014-12-03 06:57:49 +0000
LV Status available
# open 0
LV Size 300.00 MiB
Current LE 75
Segments 2
Allocation inherit
Read ahead sectors auto
- currently set to 256
Block device 252:0
Diarmuid Ó Briain 45
Linux Foundation Certified System Administrator (LFCS)
or
• /dev/mapper/vg0-lv0
• /dev/mapper/vg0-lv1
Make a filesystem on the logical volumes, create mount points and mount.
$ sudo ls /dev/mapper
control vg0-lv0 vg0-lv1
46 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 6.8G 1.7G 4.8G 27% /
none 4.0K 0 4.0K 0% /sys/fs/cgroup
udev 487M 4.0K 487M 1% /dev
tmpfs 100M 460K 99M 1% /run
none 5.0M 0 5.0M 0% /run/lock
none 498M 0 498M 0% /run/shm
none 100M 0 100M 0% /run/user
/dev/mapper/vg0-lv0 283M 2.1M 262M 1% /mnt/l-vol0
/dev/mapper/vg0-lv1 167M 1.6M 153M 1% /mnt/l-vol1
$ mount | grep lv
/dev/mapper/vg0-lv0 on /mnt/l-vol0 type ext4 (rw)
/dev/mapper/vg0-lv1 on /mnt/l-vol1 type ext4 (rw)
$ sudo -s
# echo -e "\n#Entries for LVM Logical volumes" >> /etc/fstab
# echo "/dev/vg0/lv0 /mnt/l-vol0 ext4 defaults 0 0" >> /etc/fstab
# echo "/dev/vg0/lv1 /mnt/l-vol1 ext4 defaults 0 0" >> /etc/fstab
# exit
$ mount | grep lv
/dev/mapper/vg0-lv0 on /mnt/l-vol0 type ext4 (rw)
/dev/mapper/vg0-lv1 on /mnt/l-vol1 type ext4 (rw)
$ df -h | grep lv
/dev/mapper/vg0-lv0 283M 2.1M 262M 1% /mnt/l-vol0
/dev/mapper/vg0-lv1 167M 1.6M 153M 1% /mnt/l-vol1
Sometimes the logical volumes may not appear in the /dev/mapper device list. This can
usually be rectified by activating the volume group as follows.
or
Diarmuid Ó Briain 47
Linux Foundation Certified System Administrator (LFCS)
48 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ sudo vgdisplay
--- Volume group ---
VG Name vg0
System ID
Format lvm2
Metadata Areas 4
Metadata Sequence No 4
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 2
Open LV 0
Max PV 0
Cur PV 4
Act PV 4
VG Size 588.00 MiB
PE Size 4.00 MiB
Total PE 147
Alloc PE / Size 119 / 476.00 MiB
Free PE / Size 28 / 112.00 MiB
VG UUID GFt0V6-VakN-cASe-FE5Z-0fZp-jKw0-ruhgT2
Diarmuid Ó Briain 49
Linux Foundation Certified System Administrator (LFCS)
Alternative approach would be to use the command below. This defines the actual size the new
logical volume should be.
In a similar mechanism a logical volume can be reduced. Here lv0 is reduced to 100MB.
50 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ sudo -s
# echo "My file" > /mnt/l-vol0/my_file
# sudo cat /mnt/l-vol0/my_file
My file
Confirm the new snapshot by checking for the my_file on the mount.
Diarmuid Ó Briain 51
Linux Foundation Certified System Administrator (LFCS)
52 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Diarmuid Ó Briain 53
Linux Foundation Certified System Administrator (LFCS)
RAID
Description
Type
The data is distributed equally between one or more disks without information on parity
or redundancy, without offering fault tolerance. Data is distributed across the disks to
increase storage volume, if the disk fails physically, the information will be lost and will
0
have to be recovered from backup copies. What does increase is the performance,
depending on the RAID 0 implementation, given that the read and write options will be
divided among the different disks. This is often confused with LVM.
This RAID type creates an exact copy, a mirror on a set of two or more disks in an
array. RAID 1 is useful for the reading performance which can increase lineally with the
number of disks. It also adds fault tolerance where a fault occurs to one of the disks as
1 the same information is available on each. RAID 1 is usually adequate for High
Availability (HA) where resources are needed critically. This configuration also makes
it possible to hot swap disks. If a fault is detected in any of the disks, it can be replaced
without switching off the system.
Unlike earlier RAID types with RAID 2 the data is divided into bits and redundant
codes are used for error correction. It is not widely used as a large number of disks is
2
required, one per system bit plus redundancy bits, so for a 32 bit system 39 disks are
required.
RAID3 uses byte divisions with an additional disk dedicated to the parity of blocks.
3 This is not very widely used type. Depending on the size of the data and the positions,
it does not provide simultaneous accesses.
RAID 4 is similar to RAID 3, however it stripes the data at the block level, instead of
4 byte level, which means that it is possible to service simultaneous requests when only
a single block is requested.
Block level striping is used, distributing the parity among the disks. It is widely used,
5 due to the simple parity scheme and due to the fact that this calculation is implemented
simply by the hardware, with good performance levels.
Block level striping like in RAID 5 with the addition of another parity block, i.e. Block
6
level striping with two parity blocks.
A mirror stripe is a nested RAID level where groups of RAID 0 arrays are used in a
RAID 1 array to create a mirror between them. An advantage is that, in the event of an
01
error, the RAID 0 level used may be rebuilt thanks to the other copy, but if more disks
need to be added, they have to be added to all the RAID 0 groups equally.
Striping of mirrors where groups of RAID 1 arrays are used in a RAID 0 array. In each
10 RAID 1 group if a disk fails there is no loss of data. RAID 10 arrays are used with high
performance databases as they include both fault tolerance and the speed.
54 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
The steps:
• Create partitions on each disk (type fd).
• Creade RAID device with the mdadm.
• Format RAID device.
• Mount RAID device (add to /etc/fstab).
• Capture RAID details to ensure persistence.
• mdadm -s can be used to stop RAID.
Diarmuid Ó Briain 55
Linux Foundation Certified System Administrator (LFCS)
In the example we have four 100 MB drives, /dev/sdb, /dev/sdc, /dev/sdd, /dev/sde.
Use the lsblk command to see the physical layout.
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 8G 0 disk
├─sda1 8:1 0 7G 0 part /
├─sda2 8:2 0 1K 0 part
└─sda5 8:5 0 1022M 0 part [SWAP]
sdb 8:16 0 100M 0 disk
sdc 8:32 0 100M 0 disk
sdd 8:48 0 100M 0 disk
sde 8:64 0 100M 0 disk
sdf 8:80 0 100M 0 disk
sr0 11:0 1 1024M 0 rom
Delete existing partitions on the disks. Here is an example for /dev/sdb, repeat for each of the
disks.
WARNING: Re-reading the partition table failed with error 16: Device or resource
busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.
56 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md0 : active raid5 sde[4] sdd[2] sdc[1] sdb[0]
305664 blocks super 1.2 level 5, 512k chunk, algorithm 2 [4/4] [UUUU]
Layout : left-symmetric
Chunk Size : 512K
Diarmuid Ó Briain 57
Linux Foundation Certified System Administrator (LFCS)
Add users that require access to the drive to the disk group.
$ sudo vi /etc/group
...
disk:x:100:lmenabrea,alovelace
...
Make persistent, such that after a reboot the RAID array will reform. The initramfs needs to be
updated so it contains the /etc/mdadm/mdadm.conf settings during boot.
$ sudo -s
# mount -a
# update-initramfs -u
update-initramfs: Generating /boot/initrd.img-3.13.0-40-generic
# exit
$
$ sudo df -h /mnt/raid5-md0/
Change the ownership and permissions of the new mount such that the group is disk and the
permissions are 775.
$ sudo chown root:disk /mnt/raid5-md0/
$ sudo chmod 775 /mnt/raid5-md0/
58 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Test that members of the disk group can create files on the RAID array partition.
/dev/md0:
Version : 1.2
Creation Time : Fri Dec 12 18:46:33 2014
Raid Level : raid5
Array Size : 305664 (298.55 MiB 313.00 MB)
Used Dev Size : 101888 (99.52 MiB 104.33 MB)
Raid Devices : 4
Total Devices : 4
Persistence : Superblock is persistent
Layout : left-symmetric
Chunk Size : 512K
Diarmuid Ó Briain 59
Linux Foundation Certified System Administrator (LFCS)
Upon reboot review the RAID. Notice that /dev/sdc is marked as removed.
Layout : left-symmetric
Chunk Size : 512K
$ cat /mnt/raid5-md0/testfile
This is a test
Check failed disk. Note that [4/3] [U_UU] replaces [4/4] [UUUU] from the earlier runs of the
command.
$ cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md0 : active raid5 sde[4] sdb[0] sdd[2]
305664 blocks super 1.2 level 5, 512k chunk, algorithm 2 [4/3] [U_UU]
60 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 8G 0 disk
├─sda1 8:1 0 7G 0 part /
├─sda2 8:2 0 1K 0 part
└─sda5 8:5 0 1022M 0 part [SWAP]
sdb 8:16 0 100M 0 disk
└─md0 9:0 0 298.5M 0 raid5 /mnt/raid5-md0
sdc 8:32 0 100M 0 disk
sdd 8:48 0 100M 0 disk
└─md0 9:0 0 298.5M 0 raid5 /mnt/raid5-md0
sde 8:64 0 100M 0 disk
└─md0 9:0 0 298.5M 0 raid5 /mnt/raid5-md0
sdf 8:80 0 100M 0 disk
sr0 11:0 1 1024M 0 rom
$ cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md0 : active raid5 sdf[5] sde[4] sdb[0] sdd[2]
305664 blocks super 1.2 level 5, 512k chunk, algorithm 2 [4/4] [UUUU]
Diarmuid Ó Briain 61
Linux Foundation Certified System Administrator (LFCS)
Layout : left-symmetric
Chunk Size : 512K
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 8G 0 disk
├─sda1 8:1 0 7G 0 part /
├─sda2 8:2 0 1K 0 part
└─sda5 8:5 0 1022M 0 part [SWAP]
sdb 8:16 0 100M 0 disk
└─md0 9:0 0 298.5M 0 raid5 /mnt/raid5-md0
sdc 8:32 0 100M 0 disk
sdd 8:48 0 100M 0 disk
└─md0 9:0 0 298.5M 0 raid5 /mnt/raid5-md0
sde 8:64 0 100M 0 disk
└─md0 9:0 0 298.5M 0 raid5 /mnt/raid5-md0
sdf 8:80 0 100M 0 disk
└─md0 9:0 0 298.5M 0 raid5 /mnt/raid5-md0
sr0 11:0 1 1024M 0 rom
The RAID array is now fully recovered and back working with four disks. Check the data on the
array is intact.
$ cat /mnt/raid5-md0/testfile
This is a test
62 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
(parted) print
Model: SanDisk Ultra (scsi)
Disk /dev/sdb: 16.0GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
(parted) rm 2
Warning: Partition /dev/sdb2 is being used. Are you sure you want to continue?
Yes/No? Yes
Diarmuid Ó Briain 63
Linux Foundation Certified System Administrator (LFCS)
Error: Partition(s) 2 on /dev/sdb have been written, but we have been unable to
inform the kernel of the change, probably because it/they are in use. As a
result, the old partition(s) will remain in use. You should reboot now before
making further changes.
Ignore/Cancel? Ignore
(parted) print
Model: SanDisk Ultra (scsi)
Disk /dev/sdb: 16.0GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
(parted) quit
$ sudo -s
# cat << FSTAB >> /etc/fstab
FSTAB
$ cat /proc/swaps
Filename Type Size Used Priority
/dev/dm-2 partition 7942140 0 -1
/dev/sdb2 partition 6647804 0 -2
64 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
FSTAB
Diarmuid Ó Briain 65
Linux Foundation Certified System Administrator (LFCS)
$ umask
0022
In this case with a mask of 022 the default permissions will be:
Files Directories
777 666
022 022
- -
755 644
• chmod go-w filename - removes write perms for the group as well as others.
66 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Change the permissions on file1.txt to User and Group having Read and Write access and
others with no access.
$ ls -l | grep file1.txt
total 20
-rw-rw---- 1 lmenabrea lmenabrea 34 Oct 21 15:54 file1.txt
For example changing file permissions to 660 will give the user
$ ls -l | grep file2.txt
total 20
-rw-rw---- 1 lmenabrea lmenabrea 34 Oct 21 15:54 file2.txt
The set user ID (setuid) bit allows the specification of which user a certain program is
executed as. This is invaluable when an application that needs to run as another user (i.e.
'root') when launched. An example:
$ ls -l | grep hello.sh
-rwsr-xr-x 1 root root 91 Oct 26 00:54 hello.sh
$ whoami
lmenabrea
$ ./hello.sh
When Luigi Menabrea launched the hello.sh script, it has all of the rights of the root user
despite lmenabrea being the owner of the process. Note the s instead of the x in the user
section. This indicates that the setuid is set.
Diarmuid Ó Briain 67
Linux Foundation Certified System Administrator (LFCS)
The set group ID (setgid) allows for the enforcement of what group ownership a directory, plus
all it's subdirectories and files have. i.e. If the setgid bit is set to babbage on a directory, any
directory or file created below that directory will also have the babbage group ownership. This
allows the setup of shared network folders that are accessible by any member of the group,
and any file below that directory will maintain that group ownership.
$ ls -l | grep more_files
drwxr-sr-x 2 lmenabrea babbage 4096 Oct 27 00:13 more_files
$ whoami
lmenabrea
$ ls -l more_files/
total 4
-rw-r--r-- 1 lmenabrea babbage 14 Oct 27 00:48 file4.txt
The Save Text Attribute bit (sticky bit) is only set on a directory. It specifies that only the
owner of a file can delete their own file within the directory regardless of other permissions. In
the example where more_files has the group babbage and a file created by lmenabrea could
only be deleted by him. So Ada Lovelace who is part of the babbage group cannot delete.
$ ls -l | grep ^d
drwxr-sr-t 2 lmenabrea babbage 4096 Oct 27 00:48 more_files
Note that the other x permission position is replaced by t, the sticky bit.
This is similar to regular permissions with the addition of another digit at the front.
Permissions Description
0 no special bit is set.
1 sticky bit is set.
2 setgid bit is set.
4 setuid bit is set.
68 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
3.6.1. find
find START-POINT TEST PATTERN ACTION
TEST :
-name PATTERN - Search in the file name
-iname PATTERN - Search in the file name but ignore case
-mtime N - Search the modification time N*24 hours ago
-mmin N - Search files modified N minutes ago
ACTION :
-delete - Delete files
-print - Send output to STDOUT
-printf format – Send output to STDOUT formatted
-exec COMMAND - Execute the following command
Looking at a few examples using the find command that demonstrate its use.
Find directories and files recursively from the current directory.
$ find . -print
.
./engineers
./BallingarrySC.png
./for.sh
./Files3
./Files3/hello2.sh
./hello.sh
./Files2
./Files2/Diddly
./Files2/Diddly/diddly2.rand
./Files2/Diddly/diddly.rand
./Files2/diddly2.rand.tar.xz
./bg.png
Diarmuid Ó Briain 69
Linux Foundation Certified System Administrator (LFCS)
70 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
The -exec action takes a command as an argument. All following arguments to find are taken
to be arguments to the command until an argument consisting of ';' is encountered. The string
'{}' is replaced by the current file name being processed everywhere it occurs in the arguments
to the command. Both of these constructions might need to be escaped (with a ' \') or quoted to
protect them from expansion by the shell.
$ find . -type f
./engineers
./BallingarrySC.png
./for.sh
./Files3/hello2.sh
./hello.sh
./Files2/Diddly/diddly2.rand
./Files2/Diddly/diddly.rand
./Files2/diddly2.rand.tar.xz
./bg.png
Diarmuid Ó Briain 71
Linux Foundation Certified System Administrator (LFCS)
Find the files over 50 bytes and tar them in a backup file.
$ ls backup.tar.xz
backup.tar.xz
3.6.2. locate
Using locate is somewhat faster assuming the database it is using is up-to-date. Usually cron
runs the updatedb utility daily which updates a database of filenames in the system. Searching
this database is much faster than searching the actual file-system. The database can be
updated manually with the updatedb command.
$ sudo updatedb
$ locate hello.sh
/home/lmenabrea/Desktop/sandbox/hello.sh
Using GREP to find a string within a file, and list the files containing the string.
dog.
Binary file /home/lmenabrea/Desktop/sandbox.tar matches
72 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ dmesg | tail
[25817.293358] scsi 7:0:0:0: Direct-Access SanDisk Ultra 1.26
PQ: 0 ANSI: 5
[25817.294096] sd 7:0:0:0: Attached scsi generic sg2 type 0
[25817.295497] sd 7:0:0:0: [sdb] 31266816 512-byte logical blocks: (16.0 GB/14.9
GiB)
[25817.297056] sd 7:0:0:0: [sdb] Write Protect is off
[25817.297065] sd 7:0:0:0: [sdb] Mode Sense: 43 00 00 00
[25817.298075] sd 7:0:0:0: [sdb] Write cache: disabled, read cache: enabled,
doesn't support DPO or FUA
[25817.321262] sdb: sdb1
[25817.324918] sd 7:0:0:0: [sdb] Attached SCSI removable disk
[25817.598220] EXT4-fs (sdb1): recovery complete
[25817.599850] EXT4-fs (sdb1): mounted file-system with ordered data mode. Opts:
(null)
Another method to find block devices is with the use of the lsblk command. This command
lists information about all or the specified block devices by reading the information from the
sysfs filesystem.
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 465.8G 0 disk
├─sda1 8:1 0 243M 0 part /boot
├─sda2 8:2 0 1K 0 part
└─sda5 8:5 0 465.5G 0 part
└─sda5_crypt (dm-0) 252:0 0 465.5G 0 crypt
├─mint--vg-root (dm-1) 252:1 0 457.9G 0 lvm /
└─mint--vg-swap_1 (dm-2) 252:2 0 7.6G 0 lvm [SWAP]
sdb 8:16 1 14.6G 0 disk
├─sdb1 8:17 1 7.3G 0 part
└─sdb2 8:18 1 7.3G 0 part
sr0 11:0 1 1024M 0 rom
Note that the USB Stick is /dev/sdb1. Run the fdisk utility to edit the partition table. If the
existing drive was created with GUID Partition Table (GPT) layout of the partition table on the
disk instead of Master Boot Record (MBR) then the gparted or gdisk utility must be used.
WARNING: GPT (GUID Partition Table) detected on '/dev/sdb'! The util fdisk
doesn't support GPT. Use GNU Parted.
Install gparted.
Diarmuid Ó Briain 73
Linux Foundation Certified System Administrator (LFCS)
(parted) print
Model: SanDisk Ultra (scsi)
Disk /dev/sdb: 16.0GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
(parted) rm 1
Warning: Partition /dev/sdb1 is being used. Are you sure you want to continue?
Yes/No? Yes
Error: Partition(s) 1 on /dev/sdb have been written, but we have been unable to
inform the kernel of the change, probably because it/they are in use. As a
result, the old partition(s) will remain in use. You should reboot now before
making further changes.
Ignore/Cancel? Ignore
(parted) quit
Information: You may need to update /etc/fstab.
74 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Umount the partition /dev/sdb1 and reload by removing the USB drive and plugging it back in.
Now print the partition table for /dev/sdb and you will see the table is empty.
(parted) exit
Diarmuid Ó Briain 75
Linux Foundation Certified System Administrator (LFCS)
76 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
An alternative to gparted is to use the gdisk. GPT fdisk (gdisk) is very similar to fdisk. It will
automatically convert an old-style Master Boot Record (MBR) partition table or BSD disklabel
stored without an MBR carrier partition to the newer Globally Unique Identifier (GUID) Partition
Table (GPT) format, or will load a GUID partition table. Apart from the beginning where gdisk
shows the type of partition table existing already the menu is familiar to that seen with fdisk
apart from a couple relating to GPT.
Using Linux Unified Key Setup (LUKS) as the standard for disk encryption on Linux.
luksFormat initialises a LUKS partition and sets the initial passphrase.
WARNING!
========
This will overwrite data on /dev/sdb1 irrevocably.
Diarmuid Ó Briain 77
Linux Foundation Certified System Administrator (LFCS)
luksOpen opens the LUKS device and sets up a mapping to a given name (i.e. secret-disk)
after successful verification of the supplied passphrase.
Create a Crypt key file to store the key, this must have 400 permissions and be owned by
root:root.
The file /etc/crypttab contains descriptive information about encrypted filesystems. crypttab
is only read by programs like cryptdisks_start and cryptdisks_stop.
$ sudo vi /etc/crypttab
Note: The device /dev/sdb contains the encrypted data, which only the cryptsetup commands
can access. /dev/mapper/secret-disk is the device on which operations to access the
decrypted data is used, in the crypttab file the target name is the file only, not the path.
Format LUKS partition by writing zeros to /dev/mapper/secret-disk encrypted device. This
will allocate block data with zeros and ensures that viewed from outside will show this as
random data, it protect against disclosure of any usage patterns.
$ dd if=/dev/zero of=/dev/mapper/secret-disk
78 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ sudo vi /etc/fstab
# Secret Disk
/dev/mapper/secret-disk /mnt/secret ext4 defaults 1 2
$ sudo mount -a
Confirm.
$ df -h | grep secret
/dev/mapper/secret-disk 7.3G 17M 6.9G 1% /mnt/secret
Diarmuid Ó Briain 79
Linux Foundation Certified System Administrator (LFCS)
$ dmesg
[ 7574.595004] usb 1-1.2: new high-speed USB device number 7 using ehci-pci
[ 7574.688531] usb 1-1.2: New USB device found, idVendor=0781, idProduct=556c
[ 7574.688536] usb 1-1.2: New USB device strings: Mfr=1, Product=2,
SerialNumber=3
[ 7574.688539] usb 1-1.2: Product: Ultra
[ 7574.688542] usb 1-1.2: Manufacturer: SanDisk
[ 7574.688544] usb 1-1.2: SerialNumber: 20051535821900D271F3
[ 7574.688966] usb-storage 1-1.2:1.0: USB Mass Storage device detected
[ 7574.689214] scsi7 : usb-storage 1-1.2:1.0
[ 7575.687130] scsi 7:0:0:0: Direct-Access SanDisk Ultra 1.26
PQ: 0 ANSI: 5
[ 7575.687636] sd 7:0:0:0: Attached scsi generic sg2 type 0
[ 7575.689238] sd 7:0:0:0: [sdb] 31266816 512-byte logical blocks: (16.0 GB/14.9
GiB)
[ 7575.690942] sd 7:0:0:0: [sdb] Write Protect is off
[ 7575.690945] sd 7:0:0:0: [sdb] Mode Sense: 43 00 00 00
[ 7575.692903] sd 7:0:0:0: [sdb] Write cache: disabled, read cache: enabled,
doesn't support DPO or FUA
[ 7575.717239] sdb: sdb1 sdb2
[ 7575.721558] sd 7:0:0:0: [sdb] Attached SCSI removable disk
[ 7576.079960] FAT-fs (sdb2): Volume was not properly unmounted. Some data may
be corrupt. Please run fsck.
[ 7576.116953] EXT4-fs (sdb1): recovery complete
[ 7576.125055] EXT4-fs (sdb1): mounted file-system with ordered data mode. Opts:
(null)
This confirms the device is /dev/sdb. Now check the partition table with parted.
Two partitions /dev/sdb1, the ext4 partition and /dev/sdb2 the FAT32 (vfat) partition exist.
Create directories as points in the file system to mount the partitions to.
80 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ sudo -s
# cat << FSTAB >> /etc/fstab
FSTAB
The users option permits users that are part of the disk group to mount and unmount the
drives. The following command appends (-a) the group (-G) disk to the user lmenarea as a
secondary group.
Now mount the two partitions with the mount command, which will read the entries in the
/etc/fstab directory.
$ mount /dev/sdb1
$ mount /dev/sdb2
Create a file on the mounted partition, confirm the file was created. umount the partition and
confirm file is gone. Remount again to see file is back.
$ cat /mnt/ext4fs/ext4-file.txt
This is a test file on the ext4 partition.
$ umount /dev/sdb1
$ ls /mnt/ext4fs/ | grep ext4-file.txt
$ mount /dev/sdb1
$ ls /mnt/ext4fs/ | grep ext4-file.txt
ext4-file.txt
$ cat /mnt/ext4fs/ext4-file.txt
This is a test file on the ext4 partition.
Mounts occurred automatically and the file created on the mounted partition is accessible.
Diarmuid Ó Briain 81
Linux Foundation Certified System Administrator (LFCS)
$ sudo vi /etc/fstab
$ mount /dev/sdb1
3.8.1.1. UUID
An alternative to this is to mount via the partition Universally Unique IDentifier (UUID) which is
a practically unique 128-bit value that identifies devices, partitions etc.. First umount the
partition and then obtain the UUID for /dev/sdb1.
Now add an entry to the /etc/fstab file where the UUID replaced the partition name under the
<file system> label.
$ sudo vi /etc/fstab
# /dev/sdb1
UUID="47e6efef-0119-4f08-a805-305052e0f48f" /mnt/sdb1 ext4 defaults 1 2
82 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
3.8.1.2. LABEL
Another alternative is to use e2label. The e2label command permits the viewing or changing of
the label on an ext2/ext3/ext4 filesystem.
$ sudo vi /etc/fstab
# /dev/sdb1
LABEL="my_sdc1_part" /mnt/sdb1 ext4 defaults 1 2
Diarmuid Ó Briain 83
Linux Foundation Certified System Administrator (LFCS)
linux1:~$ vi /etc/idmapd.conf
...
Domain = obriain.com
...
84 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Option Description
rw Allow both read and write requests on this NFS volume.
sync Reply to requests only after the changes have been committed to stable storage.
no_subtree_check This disables subtree checking, which has mild security implications, but can improve
reliability.
linux1:~$ sudo -s
linux1:~# echo -e "\n# /library access" >> /etc/exports
linux1:~# echo "/library linux.obriain.com(rw,sync,fsid=0,no_subtree_check)"
>> /etc/exports
linux1:~# exportfs -a
linux1:~# exit
linux1:~$ vi /etc/idmapd.conf
...
Domain = obriain.com
...
Diarmuid Ó Briain 85
Linux Foundation Certified System Administrator (LFCS)
linux2:~$ sudo -s
linux2:~# mkdir /mnt/library
linux1:~$ id
NFS Client
linux2:~$ id
86 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Create a file on the NFS Share from the Client, use the user lmenabrea.
Check the file in the /library directory on the Server and create a server side file for test with
the user lmenabrea.
Check the servertestfile on the NFS Client from the lmenabrea user.
The Short Message Block (SMB)/Common Internet File System (CIFS) networking protocol
protocol along with a specific implementation of Lightweight Directory Access Protocol (LDAP)
called Active Directory (AD) is used by Microsoft Windows to provide file and print services for
various Windows clients and supports Microsoft Windows Server domain Primary Domain
Controllers (PDC) and domain members.
Samba is a FOSS implementation of this Microsoft infrastructure and allows for GNU/Linux
Servers and Workstations to participate as part of an Active Directory domain or simply using
SMB as part of the Microsoft Windows Network.
Effectively the Samba Server acts as a Windows LAN Manager Server while the Samba
Workstation acts as a Windows LAN Manager Workstation.
Diarmuid Ó Briain 87
Linux Foundation Certified System Administrator (LFCS)
Samba Password
Samba shares a directory or directories that are owned by a user on the Samba Server. The
Samba password however is different to that used by the server for the user from /etc/passwd
and /etc/shadow. The Samba password is stored in /etc/samba/smbpasswd. In this case
we will share a directory called smbshare in Ada Lovelace's home directory.
Set the SMB Password for Ada Lovelace to allow access to the share.
linux1:~# exit
linux1:~$
88 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
$ testparm
Load smb config files from /etc/samba/smb.conf
rlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)
Processing section "[printers]"
Processing section "[print$]"
Processing section "[smbshare]"
Loaded services file OK.
Server role: ROLE_STANDALONE
Press enter to see a dump of your service definitions
Server Comment
--------- -------
UBUNTU ubuntu server (Samba, Ubuntu)
Workgroup Master
--------- -------
WORKGROUP UBUNTU
Diarmuid Ó Briain 89
Linux Foundation Certified System Administrator (LFCS)
linux2:~$ sudo -s
linux2:~# exit
linux2:~$
linux2:~$ sudo -s
linux2:~$ cd /mnt/smbshare
linux2:~$ ls
SMBtest.txt
90 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Diarmuid Ó Briain 91
Linux Foundation Certified System Administrator (LFCS)
Check the EXT4 file-system on /dev/sdb1 partition. Note the echo $? gives the exit status for
the previous command.
$ fsck.ext4 /dev/sdb1
e2fsck 1.42.9 (4-Feb-2014)
/dev/sdb1: clean, 13/499968 files, 68558/1999872 blocks
$ echo $?
0
Check the FAT32 file-system on /dev/sdb2 partition. echo $? returns an exit status of 0.
$ fsck.vfat /dev/sdb2
fsck.fat 3.0.26 (2014-03-07)
/dev/sdb2: 1 files, 1/1658708 clusters
$ echo $?
0
If a file-system has not been cleanly unmounted, the system detects a dirty bit on the file-
system during the next bootup and starts a check. fsck will detect any errors on the file-system
and attempt to fix. You should not interrupt this repair process. If an empty forcefsck file is
created in the root of the root file-system. file-systems that have > 0 specified in the sixth
column of the /etc/fstab will be checked. 0 means do not check. In the case of the extract of
/etc/fstab below, /dev/sdb1 would be checked, however /dev/sdb2 would not.
92 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
4. Local security
$ whoami
lmenabrea
$ su alovelace
Password: maths
:/home> whoami
alovelace
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/
games
In this case Ada Lovelace will maintain the current directory and the environmental variables of
the original user rather than switching to her own account directory and environment variables.
To switch and change the current directory and environmental variables a - is required. To
demonstrate, note the different $PATH values.
$ whoami
lmenabrea
Change to Ada Lovelace account. Trying with and without the '-' or a '-l' switch. Using either of
these switch options provide an environment similar to what the user would expect had the
user logged in directly. This can be seen by noting the $PATH assigned after login.
$ su alovelace
Password: maths
:~> whoami
alovelace
$ su - alovelace
Password: maths
:~% whoami
alovelace
Diarmuid Ó Briain 93
Linux Foundation Certified System Administrator (LFCS)
To change to the root user with Super User privileges. Again note the difference when a '-' or '-
l' is used.
$ su
Password: root-pass
~ # whoami
root
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/
local/games
# echo $HOME
/root
$ su -
Password: root-pass
~ # whoami
root
~ # echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
~ # echo $HOME
/root
$ cat hello.sh
#!/bin/bash
echo "Hello World"
while :
do
echo "Press [CTRL+C] to stop.."
sleep 1
done
$ ./hello.sh
-bash: ./hello.sh: Permission denied
94 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Now run with sudo, you can see that the process is actually ran by the user root.
$ sudo ./hello.sh
Hello World
Press [CTRL+C] to stop..
Press [CTRL+C] to stop..
Press [CTRL+C] to stop..
Now try running it as alovelace or the group babbage using sudo. In the latter case the script
is ran by lmenabrea and is allowed because the sudo was supplied the group babbage and
lmenabrea is in the sudo group.
Defaults env_reset
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Defaults editor=/usr/bin/vi
Diarmuid Ó Briain 95
Linux Foundation Certified System Administrator (LFCS)
Next it is possible to create aliases. Alias names must always start with a capital letter. For
example:
User_Alias replace the portion of the rule that specifies the [USER], see below.
Host_Alias replace the portion of the rule that specifies the [HOSTS], see below.
Runas_Alias replace the portion of the rule that specifies the [USERS]:[GROUPS], see
below.
Cmnd_Alias replace the portion of the rule that specifies the [COMMANDS], see below.
And finally the actual user or group entries. They follow the format:
So the following means that Ada Lovelace can can on all hosts as all users and as all groups
run all commands. Or in other words Ada Lovelace has been given the same rights as the root
user.
or in this case users defined by the User_Alias SUPERUSERS have sudo rights.
A % symbol before the first field indicates all the users of a group. So to allow members of the
sudo group to execute any command.
In this case all members of the admin group may gain root privileges without a password.
96 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
Finally a line that is required at the end of the /etc/sudoers file to include any files in the
/etc/sudoers.d/ directory.
#includedir /etc/sudoers.d
Changes to the /etc/sudoers file or the addition or editing of files in the /etc/sudoers.d/
directory requires the sudo service to be restarted.
The easiest way to give a user sudo rights is to add them to the sudo group. In this example
Ada Lovelace is added to the sudo group and given sudo privileges. (It is possible to directly
edit the /etc/group file either).
$ sudo -s
# whoami
root
Diarmuid Ó Briain 97
Linux Foundation Certified System Administrator (LFCS)
98 Diarmuid Ó Briain
Linux Foundation Certified System Administrator (LFCS)
5. Shell scripting
5.1.4. Functions
display () {
echo "This is a sample function"
}
#!/bin/bash
ls /lib/modules/`uname -r`
echo; printf '*%.0s' {1..20}; echo
ls /lib/modules/$(uname -r)
echo
Diarmuid Ó Briain 99
Linux Foundation Certified System Administrator (LFCS)
$ ./cmd_sub.sh
build kernel modules.alias.bin modules.builtin.bin modules.dep.bin
modules.order modules.symbols updates
initrd modules.alias modules.builtin modules.dep
modules.devname modules.softdep modules.symbols.bin
********************
build kernel modules.alias.bin modules.builtin.bin modules.dep.bin
modules.order modules.symbols updates
initrd modules.alias modules.builtin modules.dep
modules.devname modules.softdep modules.symbols.bin
$ ./pink.sh
My teddybear is pink
export VAR=value
or
VAR=value ; export VAR
5.1.9. Redirection
$ wc -l syslog.pdf
1721 syslog.pdf
$ wc -l < syslog.pdf
1721
5.1.10. if statement
if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi
i.e.
$ cat if.sh
#!/bin/bash
if [ $number -eq 10 ]
then
echo 'It is 10'
else
echo 'It is not 10'
fi
$ ./if.sh
ENTER A NUMBER: 10
It is 10
$ ./if.sh
ENTER A NUMBER: 11
It is not 10
i.e.
$ cat elif.sh
#!/bin/bash
if [ $number -eq 10 ]
then
echo 'It is 10'
elif [ $number -eq 11 ]
then
echo 'It is 11'
else
echo 'It is not 10 or 11'
fi
$ ./elif.sh
ENTER A NUMBER: 10
It is 10
$ ./elif.sh
ENTER A NUMBER: 11
It is 11
$ ./elif.sh
ENTER A NUMBER: 12
It is not 10 or 11
if [ -f filename ]
Condition Meaning
-e file Check if the file exists.
-d file Check if the file is a directory.
-f file Check if the file is a regular file.
-s file Check if the file is of non-zero size.
-g file Check if the file has sgid set.
-u file Check if the file has suid set.
-r file Check if the file is readable.
-w file Check if the file is writeable.
-x file Check if the file is executable.
Using the $((...)) syntax: This is the built-in shell format. The syntax is as follows:
echo $((x+1))
5.1.14. Strings
Here 0 is the offset in the string (i.e., which character to begin from) where the extraction needs
to start and 1 is the number of characters to be extracted.
${string#*.}
Example:
#!/bin/bash
echo "ENTER a number between 1 & 5"
read numb
case $numb in
1 ) echo "you selected 1";;
2 ) echo "you selected 2";;
3 ) echo "you selected 3";;
4 ) echo "you selected 4";;
5 ) echo "you selected 5";;
* ) echo "you cheated !! ";;
esac
5.1.17.1. for
#!/bin/bash
num=0
end=15
for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
do
num=$(($num+$i))
done
num=0
for i in {1..15}
do
num=$(($num+$i))
done
num=0
Another example, this time reading lines from a file one by one. Note the syntax $'\n'. Normally
bash interprets '\n' as a backslash followed by the letter n. $'\n' is interpreted as a carriage
return.
$ cat engineers
Luigi Menabrea
Ada Lovelace
Charles Babbage
$ cat for_engineers.sh
#!/bin/bash
IFS=$'\n'
unset IFS
$ ./for_engineers.sh
Luigi Menabrea.
Ada Lovelace.
Charles Babbage.
5.1.17.2. while
#!/bin/bash
num=0
end=15
5.1.17.3. until
#!/bin/bash
num=0
end=15
until [ $num -eq $end ]
do
echo "$num is less than $end"
((num++))
done
$ cat lsla.txt
total 16
drwxr-xr-x 2 dobriain dobriain 4096 Dec 31 16:51 .
drwxr-xr-x 4 dobriain dobriain 4096 Dec 31 13:03 ..
-rw-r--r-- 1 dobriain dobriain 0 Dec 31 16:51 lsla.txt
-rw-r--r-- 1 dobriain dobriain 145 Dec 29 21:45 printer.txt
-rw-r--r-- 1 dobriain dobriain 166 Dec 29 21:45 printer.txt.bak
$ ls % 2> lserr.txt
$ cat lserr.txt
ls: cannot access %: No such file or directory
A single chevron > overwrites the file if it already existed. Using a double chevron appends to
the file.
$ cat lserr.txt
ls: cannot access %: No such file or directory
ls: cannot access ^: No such file or directory
A special syntax 2>&1. Looking at a command that generates both stdout and stderr. The
2>&1 syntax redirects the output of stderr into the stdout stream.
$ cat lsld.std
drwxrwxrwt 14 root root 4096 Dec 31 17:05 /tmp
$ cat lsld.err
ls: cannot access /tnn: No such file or directory
$ cat lsld.both
ls: cannot access /tnn: No such file or directory
drwxrwxrwt 14 root root 4096 Dec 31 17:10 /tmp
tee - read from standard input and write to stdout and to a file.
$ cat lsld.all
ls: cannot access /tnn: No such file or directory
drwxrwxrwt 14 root root 4096 Dec 31 17:10 /tmp
ls: cannot access /tnn: No such file or directory
drwxrwxrwt 14 root root 4096 Dec 31 17:05 /tmp
$ mktemp passwdXXXX
passwdU9t3
$ mktemp -d passwdXXXX
passwdSjnH
$ ls -l |grep pass
drwx------ 2 lmenabrea lmenabrea 4096 Oct 1 17:49 passwdSjnH
-rw------- 1 lmenabrea lmenabrea 0 Oct 1 17:49 passwdU9t3
$ echo $RANDOM
394
$ echo $RANDOM
16847
$ echo $RANDOM
7609
$ ls -l ~/Desktop/random.data.1M
-rw-r--r-- 1 lmenabrea lmenabrea 1048576 Oct 1 19:01
/home/lmenabrea/Desktop/random.data.1M
$ cat ~/Desktop/random.data.1M
�RI;�Hl�X0��
�V�Rs.����K��Ї��ٷe���s4ʵ2"�M����EFeb����E����+)��&�}�D��*���
IG������4F��Qw
���#�E��fN�6�y���SO\�`;;
�<}ݦX����"I����FJo�_m�����V�u(v�CG�H 9��X��Kҳ=rdD��`&>�ڋtĺ�4�\��.�\:7k�?
x.�R�O}���+z��X8������c�4�NP���x����55 ݦ�ݦj�E��|}M��4O�r�v�Fk�-��0��
_9��v�`�4=KA�i�����{1�S�{�E ݦ
WV=���Z��_�g���a'$�U�� �B/����n����G��Ô�Ku-�"|�4����@�#ݦ
���
$ cat <<EOM
-------------------------------------
This is line 1 of the message.
This is line 2 of the message.
This is line 3 of the message.
This is line 4 of the message.
This is the last line of the message.
-------------------------------------
EOM
$ cat <<-EOM
-------------------------------------
This is line 1 of the message.
This is line 2 of the message.
This is line 3 of the message.
This is line 4 of the message.
This is the last line of the message.
-------------------------------------
EOM
#!/bin/bash
here_file=$(cat <<EOM
-------------------------------------
This is line 1 of the message.
This is line 2 of the message.
This is line 3 of the message.
This is line 4 of the message.
This is the last line of the message.
-------------------------------------
EOM
)
echo "$here_file"
: <<COMMENT
This will not be processed
by the bash interpretor.
COMMENT
6. Software management
aptget [options] [command] [package …]
6.1.2. Example
Find a package that acts as a sticky note for the desktop and install.
aptcache search <package>
$ xpad
7.2. Calculator
bc is a command-line calculator.
$ bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
34*4
136
23+45
68
10/5
2
66-6
60
quit
0. PREAMBLE
The purpose of this License is to make a manual, textbook, or other functional and useful
document "free" in the sense of freedom: to assure everyone the effective freedom to copy and
redistribute it, with or without modifying it, either commercially or noncommercially.
Secondarily, this License preserves for the author and publisher a way to get credit for their
work, while not being considered responsible for modifications made by others.
This License is a kind of "copyleft", which means that derivative works of the document must
themselves be free in the same sense. It complements the GNU General Public License, which
is a copyleft license designed for free software.
We have designed this License in order to use it for manuals for free software, because free
software needs free documentation: a free program should come with manuals providing the
same freedoms that the software does. But this License is not limited to software manuals; it
can be used for any textual work, regardless of subject matter or whether it is published as a
printed book. We recommend this License principally for works whose purpose is instruction or
reference.
This License applies to any manual or other work, in any medium, that contains a notice placed
by the copyright holder saying it can be distributed under the terms of this License. Such a
notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under
the conditions stated herein. The "Document", below, refers to any such manual or work. Any
member of the public is a licensee, and is addressed as "you". You accept the license if you
copy, modify or distribute the work in a way requiring permission under copyright law.
A "Modified Version" of the Document means any work containing the Document or a portion of
it, either copied verbatim, or with modifications and/or translated into another language.
A "Secondary Section" is a named appendix or a front-matter section of the Document that
deals exclusively with the relationship of the publishers or authors of the Document to the
Document's overall subject (or to related matters) and contains nothing that could fall directly
within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a
Secondary Section may not explain any mathematics.) The relationship could be a matter of
historical connection with the subject or with related matters, or of legal, commercial,
philosophical, ethical or political position regarding them.
The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being
those of Invariant Sections, in the notice that says that the Document is released under this
License. If a section does not fit the above definition of Secondary then it is not allowed to be
designated as Invariant. The Document may contain zero Invariant Sections. If the Document
does not identify any Invariant Sections then there are none.
The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or
Back-Cover Texts, in the notice that says that the Document is released under this License. A
Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.
A "Transparent" copy of the Document means a machine-readable copy, represented in a
format whose specification is available to the general public, that is suitable for revising the
document straightforwardly with generic text editors or (for images composed of pixels) generic
paint programs or (for drawings) some widely available drawing editor, and that is suitable for
input to text formatters or for automatic translation to a variety of formats suitable for input to
text formatters. A copy made in an otherwise Transparent file format whose markup, or
absence of markup, has been arranged to thwart or discourage subsequent modification by
readers is not Transparent. An image format is not Transparent if used for any substantial
amount of text. A copy that is not "Transparent" is called "Opaque".
Examples of suitable formats for Transparent copies include plain ASCII without markup,
Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and
standard-conforming simple HTML, PostScript or PDF designed for human modification.
Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include
proprietary formats that can be read and edited only by proprietary word processors, SGML or
XML for which the DTD and/or processing tools are not generally available, and the machine-
generated HTML, PostScript or PDF produced by some word processors for output purposes
only.
The "Title Page" means, for a printed book, the title page itself, plus such following pages as
are needed to hold, legibly, the material this License requires to appear in the title page. For
works in formats which do not have any title page as such, "Title Page" means the text near the
most prominent appearance of the work's title, preceding the beginning of the body of the text.
The "publisher" means any person or entity that distributes copies of the Document to the
public.
A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely
XYZ or contains XYZ in parentheses following text that translates XYZ in another language.
(Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements",
"Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when
you modify the Document means that it remains a section "Entitled XYZ" according to this
definition.
The Document may include Warranty Disclaimers next to the notice which states that this
License applies to the Document. These Warranty Disclaimers are considered to be included
by reference in this License, but only as regards disclaiming warranties: any other implication
that these Warranty Disclaimers may have is void and has no effect on the meaning of this
License.
2. VERBATIM COPYING
You may copy and distribute the Document in any medium, either commercially or
noncommercially, provided that this License, the copyright notices, and the license notice
saying this License applies to the Document are reproduced in all copies, and that you add no
other conditions whatsoever to those of this License. You may not use technical measures to
obstruct or control the reading or further copying of the copies you make or distribute.
However, you may accept compensation in exchange for copies. If you distribute a large
enough number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and you may publicly
display copies.
3. COPYING IN QUANTITY
If you publish printed copies (or copies in media that commonly have printed covers) of the
Document, numbering more than 100, and the Document's license notice requires Cover Texts,
you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts:
Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers
must also clearly and legibly identify you as the publisher of these copies. The front cover must
present the full title with all words of the title equally prominent and visible. You may add other
material on the covers in addition. Copying with changes limited to the covers, as long as they
preserve the title of the Document and satisfy these conditions, can be treated as verbatim
copying in other respects.
If the required texts for either cover are too voluminous to fit legibly, you should put the first
ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent
pages.
If you publish or distribute Opaque copies of the Document numbering more than 100, you
must either include a machine-readable Transparent copy along with each Opaque copy, or
state in or with each Opaque copy a computer-network location from which the general
network-using public has access to download using public-standard network protocols a
complete Transparent copy of the Document, free of added material. If you use the latter
option, you must take reasonably prudent steps, when you begin distribution of Opaque copies
in quantity, to ensure that this Transparent copy will remain thus accessible at the stated
location until at least one year after the last time you distribute an Opaque copy (directly or
through your agents or retailers) of that edition to the public.
It is requested, but not required, that you contact the authors of the Document well before
redistributing any large number of copies, to give them a chance to provide you with an
updated version of the Document.
4. MODIFICATIONS
You may copy and distribute a Modified Version of the Document under the conditions of
sections 2 and 3 above, provided that you release the Modified Version under precisely this
License, with the Modified Version filling the role of the Document, thus licensing distribution
and modification of the Modified Version to whoever possesses a copy of it. In addition, you
must do these things in the Modified Version:
• A. Use in the Title Page (and on the covers, if any) a title distinct from that of the
Document, and from those of previous versions (which should, if there were any, be
listed in the History section of the Document). You may use the same title as a previous
version if the original publisher of that version gives permission.
• B. List on the Title Page, as authors, one or more persons or entities responsible for
authorship of the modifications in the Modified Version, together with at least five of the
principal authors of the Document (all of its principal authors, if it has fewer than five),
unless they release you from this requirement.
• C. State on the Title page the name of the publisher of the Modified Version, as the
publisher.
• D. Preserve all the copyright notices of the Document.
• E. Add an appropriate copyright notice for your modifications adjacent to the other
copyright notices.
• F. Include, immediately after the copyright notices, a license notice giving the public
permission to use the Modified Version under the terms of this License, in the form
shown in the Addendum below.
• G. Preserve in that license notice the full lists of Invariant Sections and required Cover
Texts given in the Document's license notice.
• H. Include an unaltered copy of this License.
• I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating
at least the title, year, new authors, and publisher of the Modified Version as given on
the Title Page. If there is no section Entitled "History" in the Document, create one
stating the title, year, authors, and publisher of the Document as given on its Title Page,
then add an item describing the Modified Version as stated in the previous sentence.
• J. Preserve the network location, if any, given in the Document for public access to a
Transparent copy of the Document, and likewise the network locations given in the
Document for previous versions it was based on. These may be placed in the "History"
section. You may omit a network location for a work that was published at least four
years before the Document itself, or if the original publisher of the version it refers to
gives permission.
• K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of
the section, and preserve in the section all the substance and tone of each of the
contributor acknowledgements and/or dedications given therein.
• L. Preserve all the Invariant Sections of the Document, unaltered in their text and in
their titles. Section numbers or the equivalent are not considered part of the section
titles.
• M. Delete any section Entitled "Endorsements". Such a section may not be included in
the Modified Version.
• N. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title
with any Invariant Section.
• O. Preserve any Warranty Disclaimers.
If the Modified Version includes new front-matter sections or appendices that qualify as
Secondary Sections and contain no material copied from the Document, you may at your option
designate some or all of these sections as invariant. To do this, add their titles to the list of
Invariant Sections in the Modified Version's license notice. These titles must be distinct from
any other section titles.
You may add a section Entitled "Endorsements", provided it contains nothing but
endorsements of your Modified Version by various parties—for example, statements of peer
review or that the text has been approved by an organization as the authoritative definition of a
standard.
You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25
words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only
one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through
arrangements made by) any one entity. If the Document already includes a cover text for the
same cover, previously added by you or by arrangement made by the same entity you are
acting on behalf of, you may not add another; but you may replace the old one, on explicit
permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License give permission to use
their names for publicity for or to assert or imply endorsement of any Modified Version.
5. COMBINING DOCUMENTS
You may combine the Document with other documents released under this License, under the
terms defined in section 4 above for modified versions, provided that you include in the
combination all of the Invariant Sections of all of the original documents, unmodified, and list
them all as Invariant Sections of your combined work in its license notice, and that you
preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and multiple identical Invariant
Sections may be replaced with a single copy. If there are multiple Invariant Sections with the
same name but different contents, make the title of each such section unique by adding at the
end of it, in parentheses, the name of the original author or publisher of that section if known, or
else a unique number. Make the same adjustment to the section titles in the list of Invariant
Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled "History" in the various original
documents, forming one section Entitled "History"; likewise combine any sections Entitled
"Acknowledgements", and any sections Entitled "Dedications". You must delete all sections
Entitled "Endorsements".
6. COLLECTIONS OF DOCUMENTS
You may make a collection consisting of the Document and other documents released under
this License, and replace the individual copies of this License in the various documents with a
single copy that is included in the collection, provided that you follow the rules of this License
for verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute it individually under
this License, provided you insert a copy of this License into the extracted document, and follow
this License in all other respects regarding verbatim copying of that document.
A compilation of the Document or its derivatives with other separate and independent
documents or works, in or on a volume of a storage or distribution medium, is called an
"aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of
the compilation's users beyond what the individual works permit. When the Document is
included in an aggregate, this License does not apply to the other works in the aggregate which
are not themselves derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if
the Document is less than one half of the entire aggregate, the Document's Cover Texts may
be placed on covers that bracket the Document within the aggregate, or the electronic
equivalent of covers if the Document is in electronic form. Otherwise they must appear on
printed covers that bracket the whole aggregate.
8. TRANSLATION
9. TERMINATION
You may not copy, modify, sublicense, or distribute the Document except as expressly
provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it
is void, and will automatically terminate your rights under this License.
However, if you cease all violation of this License, then your license from a particular copyright
holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder fails to notify you of the
violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the
copyright holder notifies you of the violation by some reasonable means, this is the first time
you have received notice of violation of this License (for any work) from that copyright holder,
and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who
have received copies or rights from you under this License. If your rights have been terminated
and not permanently reinstated, receipt of a copy of some or all of the same material does not
give you any rights to use it.
11. RELICENSING
"Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server
that publishes copyrightable works and also provides prominent facilities for anybody to edit
those works. A public wiki that anybody can edit is an example of such a server. A "Massive
Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable
works thus published on the MMC site.
"CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0 license published by
Creative Commons Corporation, a not-for-profit corporation with a principal place of business
in San Francisco, California, as well as future copyleft versions of that license published by that
same organization.
"Incorporate" means to publish or republish a Document, in whole or in part, as part of another
Document.
An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were
first published under this License somewhere other than this MMC, and subsequently
incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and
(2) were thus incorporated prior to November 1, 2008.
The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on
the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing.