Linux Essentials Full Course
Linux Essentials Full Course
February 9, 2016
Florin Simion
[email protected]
Agenda
Day 1
2. Storage
3. Processes
Day 2
1. Introduction
4. Users
5. Using the shell
6. Shell scripts
Day 3
February 7, 2016
7. Regular expressions
8. Essential system services
9. Package management
10. Hardware devices
11. Booting the system
Quiz
2
Course objectives
February 7, 2016
Target audience
By job duties
February 7, 2016
Approach
February 7, 2016
Introduction
February 7, 2016
http://en.wikipedia.org/wiki/Operating_system
February 7, 2016
http://en.wikipedia.org/wiki/Unix
February 7, 2016
GNU / Linux
www.ibm.com
February 7, 2016
Linux distributions
installation discs
a repository of packages (usually in binary form)
a package management system
regular updates of the applications and kernel, for including
new features
bug fixes
security patches
February 7, 2016
February 7, 2016
Storage
February 7, 2016
Topics
February 7, 2016
Introduction
February 7, 2016
February 7, 2016
retaining information
retrieving information
organizing information
protecting information
software
hardware
February 7, 2016
Block devices
February 7, 2016
Linux devices
Implementations
February 7, 2016
data sinks
virtual terminals
/dev/null
/dev/tty0
Block devices
Transfer characteristics:
high speed
random access (vs. sequential access in char devices)
Transfer operations:
buffered
read
write
seek / skip
February 7, 2016
Partitions
Use cases:
www.howtogeek.com
February 7, 2016
Partition tables
technet.microsoft.com
February 7, 2016
10
February 7, 2016
11
Partitioning tools
fdisk (CLI)
www.hal-pc.com
en.wikipedia.org
gparted.sourceforge.net
February 7, 2016
docs.kde.org
12
fdisk
February 7, 2016
13
Swap partitions
A dedicated partition for holding process data that does not fit in the physical memory (RAM)
February 7, 2016
14
File systems
February 7, 2016
15
File systems
File system
codeidol.com
February 7, 2016
16
February 7, 2016
FAT32
NTFS
February 7, 2016
copy-on write
advanced features: snapshots, online resizing
18
Creating / formatting
Un-mounting
Mounting
initializes the data structures of the file systems (to default values)
Verifying
Tuning
February 7, 2016
# ls /sbin/mkfs*
/sbin/mkfs
/sbin/mkfs.bfs
/sbin/mkfs.cramfs
/sbin/mkfs.ext2
/sbin/mkfs.ext3
/sbin/mkfs.ext4
/sbin/mkfs.minix
February 7, 2016
20
mount point a directory where the root of the file system will be found
the file system will appear to extend downwards from the mount point
Note: the original content of the mount point will no longer be accessible
Mounting methods
etutorials.org
February 7, 2016
21
mount
February 7, 2016
22
/etc/fstab
<type>
<options>
<dump>
<pass>
proc
/proc
proc
defaults
/dev/sda1
/boot
ext4
defaults
/dev/sda2
ext4
errors=remount-ro 0
/dev/sda3
/home
ext4
defaults
/dev/sda5
/var
ext4
defaults
/dev/sda7
/media/storage
ext4
defaults
/dev/scd0
/media/cdrom0
udf,iso9660 user,noauto
/dev/fd0
/media/floppy0
auto
rw,user,noauto
February 7, 2016
23
/etc/fstab
<type>
<options>
<dump>
<pass>
proc
/proc
proc
defaults
/dev/sda1
/boot
ext4
defaults
/dev/sda2
ext4
errors=remount-ro 0
/dev/sda3
/home
ext4
defaults
/dev/sda5
/var
ext4
defaults
/dev/sda7
/media/storage
ext4
defaults
/dev/scd0
/media/cdrom0
udf,iso9660 user,noauto
/dev/fd0
/media/floppy0
auto
rw,user,noauto
February 7, 2016
24
February 7, 2016
swapon -a
25
Usage:
umount device_file
umount mount_point
Examples:
umount /dev/sda3
February 7, 2016
umount /mnt/data
26
df disk free
Usage: df [-h] [-k | -m] [-T]
Example:
# df -hT
Filesystem
Type
Size
/dev/sda2
ext4
16G
707M
16G
tmpfs
tmpfs
3.9G
3.9G
0% /lib/init/rw
udev
tmpfs
3.9G
164K
3.9G
1% /dev
tmpfs
tmpfs
3.9G
3.9G
0% /dev/shm
/dev/sda1
ext4
248M
31M
217M
13% /boot
/dev/sda3
ext4
252G
128G
125G
51% /home
/dev/sda5
ext4
126G
2.3G
124G
2% /var
/dev/sda7
ext4
3.2T
353G
2.9T
February 7, 2016
11% /media/storage
27
du disk usage
Usage: du [-h] [--max-depth=N] [directory]
Example:
# du -h --summarize /home/
127G
February 7, 2016
/home/
28
Note: for checking a file system for errors, it must first be un-mounted!
February 7, 2016
useful for verifying file system parameters (like last mount time, last check time,
creation time etc.)
29
Example:
tune2fs c 10 /dev/sda1
sets the maximum number of mounts before a check is performed
tune2fs C 99 /dev/sda1
modifies the actual number of mounts (to force a check at next reboot)
February 7, 2016
30
Network file systems allow a system to access files stored on a remote machine
February 7, 2016
31
NFS:
Usage:
remote_server:remote_share
mount_point
nfs
options
0 0
172.31.203.13:/space/usrglobal /usr/global
nfs
defaults
0 0
Example:
CIFS:
Usage:
//remote_server:remote_share/
cifs
options
0 0
/media/eng
cifs
defaults
0 0
Example:
//172.31.203.16/eng/
February 7, 2016
mount_point
32
File path a string that uniquely identifies the location of a file or directory within a file system
consists of the file or directory name, preceded by all parent directories, separated by /
Examples:
absolute contains all the directories up to the root (as in previous examples)
relative contains only the directories up to the current directory
Example: if the current directory is /var, the relative path of /var/log/syslog is
log/syslog
February 7, 2016
33
Special paths
February 7, 2016
Description
/bin
/boot
/dev
/etc
/home
/media
/mnt
/opt
/proc
procfs
/root
/sbin
/tmp
temporary files
/usr
February 7, 2016
35
February 7, 2016
I/O patterns
typical use cases
Partition
/boot
/home
many reads
/usr/local
user customizations
/var
frequent writes
/var/log
Files
February 7, 2016
37
cp copy
mv move or rename
rm delete (remove)
February 7, 2016
38
List - ls
February 7, 2016
config-2.6.32-5-amd64
grub
initrd.img-2.6.32-5-amd64
lost+found
System.map-2.6.32-5-amd64
vmlinuz-2.6.32-5-amd64
39
Copy - cp
cp /path/to/file1 /path/to/file2
cp /path/to/file1 /path/to/dir2/
cp r /path/to/dir1/ /path/to/dir2/
February 7, 2016
40
Move / rename - mv
mv /path/to/file1 /path/to/dir2/
mv /path/to/file1 /path/to/dir2/file2
mv /path/to/dir1/ /path/to/dir2/
February 7, 2016
41
Remove - rm
Deletes file
February 7, 2016
42
Directory operations
Change directory - cd
Usage: cd path
path can be absolute or relative
February 7, 2016
43
File types
Regular files
Directories
Symbolic link
Named pipe
Device file
February 7, 2016
block device
character device
44
# ls -l /etc/
drwxr-xr-x 3 root root
4096 Aug 27
2012 acpi
2981 Aug 27
2012 adduser.conf
13 Aug 27
# ls -l /dev/
crw------- 1 root root
254,
8,
February 7, 2016
File
# file /dev/sda
/dev/sda: block special
# file /dev/rtc0
/dev/rtc0: character special
# file /boot/
/boot/: directory
# file /boot/vmlinuz-2.6.32-5-amd64
/boot/vmlinuz-2.6.32-5-amd64: Linux kernel x86 boot executable bzImage,
version 2.6.32-5-amd64 (unknown@Debian), RO-rootFS, swap_dev 0x2, Normal
VGA
# file /etc/fstab
/etc/fstab: ASCII English text
# file /usr/local/bin/networking.sh
/usr/local/bin/networking.sh: Bourne-Again shell script text executable
February 7, 2016
46
Stat
# stat /etc/
File: `/etc/'
Size: 4096
Blocks: 8
IO Block: 4096
Device: 802h/2050d
Inode: 655361
Links: 77
Access: (0755/drwxr-xr-x) Uid: (
0/
root)
Gid: (
Access: 2013-03-03 18:27:20.903396964 +0200
Modify: 2013-02-27 12:04:42.331433296 +0200
Change: 2013-02-27 12:04:42.331433296 +0200
# stat /etc/fstab
File: `/etc/fstab'
Size: 947
Blocks: 8
IO Block: 4096
Device: 802h/2050d
Inode: 655491
Links: 1
Access: (0644/-rw-r--r--) Uid: (
0/
root)
Gid: (
Access: 2013-03-03 15:04:11.959642599 +0200
Modify: 2012-10-27 19:47:08.262392353 +0300
Change: 2012-10-27 19:47:08.297379208 +0300
February 7, 2016
directory
0/
root)
regular file
0/
root)
47
Hard link
Symbolic link
msdn.microsoft.com
February 7, 2016
48
Creating links - ln
February 7, 2016
10 Mar
49
File security
February 7, 2016
50
Owners
Changing the user and group of a file is done with the chown command:
Usage:
chown user:group file
chown [-R] user:group directory/
-R makes the operation recursive
February 7, 2016
51
Permissions
group
others
user
Read
Write
eXecute
February 7, 2016
1 root root
52
Permissions representations
111101100
7
February 7, 2016
literal:
rwxr-xr--
enumeration: u=rwx,g=rx,o=r
53
Example:
we want to add execution right for all entities (user, group, others):
the new permissions will be 755 (or u=rwx,g=rx,o=rx)
(octal form)
February 7, 2016
chmod +x test.sh
54
File-creation mask:
when creating a new file, its permissions are set to (0666 & ~mask)
when creating a new directory, its permissions are set to (0777 & ~mask)
February 7, 2016
55
Processes
February 7, 2016
Topics
February 7, 2016
General concepts
February 7, 2016
What is a process?
February 7, 2016
Process
# ps -p 19024 u
USER
root 19024
0.0
Program
File name
Disk space
# ls -al /bin/ping
-rwsr-xr-x 1 root root 34248 Oct 14
February 7, 2016
2010 /bin/ping
5
# pstree -p
init(1)acpid(1447)
apache2(1734)apache2(904)
apache2(1666)
cron(1841)
dhcpd(1849)
getty(2127)
getty(2128)
mysqld_safe(1491)logger(1603)
mysqld(1602){mysqld}(1605)
{mysqld}(1606)
named(27572){named}(27573)
{named}(27574)
ntpd(1467)
rsyslogd(1378)
sshd(1822)sshd(13837)bash(13843)pstree(24134)
sshd(19004)bash(19007)
udevd(479)
February 7, 2016
Process parallelism
February 7, 2016
Process states
http://elf.cs.pub.ro/so/wiki/cursuri/curs-03
February 7, 2016
Listing processes
February 7, 2016
pstree
pgrep
htop
GUI tools
February 7, 2016
most desktop environments (GNOME, KDE etc.) have their own graphical task
manager
10
procfs
Every process has an entry under /proc, named with its PID:
# ls /proc/
1
10
1016
1017
1022
1023
1028
1029
12
12341
14
14098
15
16
17
1734
...
...
1012
1018
1024
1030
13
1447
1602
18
...
1013
1019
1025
10403
1378
1459
1603
1822
...
1014
1020
1026
10497
13837
1467
1666
1824
...
1015
1021
1027
11
13843
1491
1693
1825
...
February 7, 2016
11
...
cwd
environ
exe
fd /
...
maps
...
stat
status
...
February 7, 2016
12
ps
-p pidlist only display processes with PIDs from the provided list
-u userlist only display processes owned by users from the provided list
-f full format output (verbose)
February 7, 2016
13
ps - examples
PID
1
2
PPID
0
0
C STIME TTY
0 Jan14 ?
0 Jan14 ?
ps aux
# ps aux | head
USER
PID %CPU %MEM
root
1 0.0 0.0
root
2 0.0 0.0
...
TIME CMD
00:00:18 init [2]
00:00:00 [kthreadd]
VSZ
8356
0
RSS TTY
732 ?
0 ?
STAT START
Ss
Jan14
S
Jan14
TIME COMMAND
0:18 init [2]
0:00 [kthreadd]
February 7, 2016
pstree
February 7, 2016
15
pgrep
Process grep
Example:
# pgrep -f -l apache2
1734 /usr/sbin/apache2 -k start
4546 /usr/sbin/apache2 -k start
6938 /usr/sbin/apache2 -k start
February 7, 2016
16
top
summary area: general information about the system (load, uptime, number of
processes etc.)
prompt line: below the summary area, used to write specific commands
columns header: displays the table header and highlights the sort key
task area: displays information about all processes
February 7, 2016
17
top - example
top - 13:48:32 up 12 days, 16:06, 1 user, load average: 0.04, 0.10, 0.04
Tasks: 119 total,
1 running, 118 sleeping,
0 stopped,
0 zombie
Cpu(s): 1.3%us, 0.6%sy, 0.9%ni, 96.5%id, 0.7%wa, 0.0%hi, 0.1%si, 0.0%st
Mem:
8066492k total, 8015136k used,
51356k free,
25492k buffers
Swap:
0k total,
0k used,
0k free, 7530592k cached
PID
8234
7864
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
February 7, 2016
USER
carpalex
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
PR
20
20
20
20
RT
20
RT
RT
20
RT
20
20
20
20
20
20
20
20
Signals
February 7, 2016
19
Killing a process
The command is kill, followed by the PID of the process, for example:
kill 1234
The signal that kill uses by default is SIGTERM, and has the number 15
A more powerful signal is SIGKILL (9). This signal cannot be ignored / blocked.
February 7, 2016
20
pkill works like pgrep, but instead of displaying processes, it kills them
February 7, 2016
example:
pkill -9 u root ping
21
Signals
February 7, 2016
22
February 7, 2016
CTRL+Z SIGSTOP
CTRL+C SIGINT
CTRL+\ - SIGQUIT
23
Foreground and
background
February 7, 2016
24
February 7, 2016
the terminal can be used for entering commands, launching other processes etc.
also called a job
25
example:
a line with the job number (in brackets) and the PID is displayed
the command prompt appears
the process runs in the background
e07a107c8e6019aa4ce82d68370b7527
[1]+
Done
big-file.bin
md5sum big-file.bin
Note: the output of the process is still displayed at the current terminal
February 7, 2016
26
While running a foreground process, entering CTRL+Z has the following effects:
The process is suspended (stops its execution, but does not terminate)
Is forced into background (becomes a job)
# ping google.com
PING google.com (173.194.44.33) 56(84) bytes of data.
64 bytes from 173.194.44.33: icmp_req=1 ttl=56 time=24.4 ms
64 bytes from 173.194.44.33: icmp_req=2 ttl=56 time=23.5 ms
^Z
[1]+
Stopped
ping google.com
February 7, 2016
27
# jobs -l
[1]+
1238 Stopped
ping google.com
[2]-
1976 Running
fg [job_number]
bg [job_number]
February 7, 2016
28
Daemons
run in background
do not have an associated terminal
Note: background jobs do have an associated terminal, but are detached
Properties
a daemon cannot communicate with the user via standard input and standard
output
the user usually controls a daemon via configuration files and startup / shutdown
scripts
a daemon usually writes messages to log files
February 7, 2016
When a terminal is closed, it sends a SIGHUP signal to all its child processes, forcing them to
terminate:
By launching a background job with the nohup command, it will ignore any SIGHUP signal
Notes:
February 7, 2016
30
Priorities
February 7, 2016
31
Process priorities
The nicer a process is, the less likely to be chosen by the scheduler
There are few situations is which an user really needs to renice a process
February 7, 2016
32
User management
February 7, 2016
What is a user?
Non-technically
Technically
Run processes
Own files
February 7, 2016
Login / logout
Change password
Switch to a different user
Users in Linux
February 7, 2016
/etc/passwd
/etc/passwd
Fields:
Username
Password is shadowed?
UID
GID
User alias
Home directory
Default shell
# cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
...
sqa:x:1000:1000:sqa,,,:/home/sqa:/bin/bash
February 7, 2016
Passwords
/etc/shadow
# cat /etc/shadow
root:$6$kIwQNw.e$2KdkqHiORpAvLqX.ggLLGOFgR6vddce7neUOQOnNWpl/66y/NMnIg1ZCgCyfDpi
YXYlLAwyjqQPvHVwVHdkgC/:15098:0:99999:7:::
sqa:$6$/x9znDgL$10DetEzMVQbLLTOp5w2AtleTf2OJt5BmVUX/3SF2OLPWoXNJNZD3jEFHIWf2OsQV
iSE8Um5WVgqoA.vDydbje0:15098:0:99999:7:::
passwd [username]
If username is ommitted, the command takes effect for the current user
February 7, 2016
Creating a user
Using adduser
February 7, 2016
Adduser USERNAME
Interactive script which prompts for most account parameters
Also prompt for password
Exists in Debian-based distributions
Usermod
# cat /etc/passwd
...
sqa:x:1000:1000:sqa,,,:/home/sqa:/bin/bash
# usermod d /localhome/sqa sqa
# cat /etc/passwd
...
sqa:x:1000:1000:sqa,,,:/localhome/sqa:/bin/bash
February 7, 2016
Userdel username
Deluser username
February 7, 2016
Groups
The mappings between GIDs and group names are stored in a file
February 7, 2016
/etc/group
9
/etc/group
Fields:
Group name
GID
List of users belonging to the group
# cat /etc/group
root:x:0:
...
cdrom:x:24:sqa
floppy:x:25:sqa, sqa2
...
Notes:
The list of users belonging to the group is useful only when an user belongs to more
than one group
February 7, 2016
10
Creating a group
Groupadd
Addgroup
Modifying a group
Via /etc/group
Via /etc/group
Groupmod
Deleting a group
February 7, 2016
Via /etc/group
Groupdel
Delgroup
11
Switching users
An user can continue its session as a different user without logging in and logging out
Syntax: su [ - ] [ username ]
February 7, 2016
12
sudo command
The users who have the right to use sudo must be configured by root, in /etc/sudoers
In Ubuntu-based distributions, members of the admin group have the right to use
sudo:
February 7, 2016
13
Centralized authentication
The authentication server can also push user attributes to the local system
Credentials are captured on the local system and sent to the authentication server for
validation
Implementations:
February 7, 2016
14
February 7, 2016
What is a shell?
users
resources in an OS
graphical (GUI):
GNOME Shell, KDE, Unity etc.
Windows Explorer (explorer.exe)
February 7, 2016
examples:
GRUB console
CLI running on the console of an embedded device
MATLAB console
text consoles in games (Quake, Half-Life etc.)
Python, TCL console
February 7, 2016
Accessing a shell
a physical terminal
only found in museums nowadays
a virtual terminal
CTRL+ALT+F1, CTRL+ALT+F2,
a terminal emulator
gnome-terminal, konsole, xterm etc.
a remote connection
over a serial line (using a modem) back to the museum
over TCP/IP: SSH, Telnet
February 7, 2016
Terminal vs shell
http://en.wikipedia.org/wiki/Computer_terminal
February 7, 2016
The prompt is a text displayed by the shell at the beginning of every line
cristi@Router:/usr/bin $
Router /usr/bin #
February 7, 2016
Syntax of a command
February 7, 2016
Internal commands
External commands
February 7, 2016
Shell facilities
Command completion
Command history
Screen control:
February 7, 2016
Variables
Defining a variable
name=value
Referencing a variable
$name
also known as expansion
Environment variables
February 7, 2016
10
Return values
# ping -c 1 google.com
PING google.com (173.194.39.160) 56(84) bytes of data.
64 bytes from bud02s04-in-f0.1e100.net (173.194.39.160): icmp_req=1 ttl=57
time=20.9 ms
--- google.com ping statistics --1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 20.969/20.969/20.969/0.000 ms
# echo $?
0
February 7, 2016
11
Bash operators
Command chaining
Sequence: ;
Parallel execution: &
Conditional execution: &&, ||
Pipelines: |, |&
February 7, 2016
12
Command chaining
Sequence:
Conditional execution: OR
command1 || command2
command2 is executed only if command1 is unsuccessful
February 7, 2016
13
Pipelines
command1 | command2
can be used multiple time, for creating a more complex command (one-liner)
February 7, 2016
14
Redirecting input
Used for commands that read their input from the terminal (stdin)
Example:
February 7, 2016
15
Used when the input of a command should be taken directly from the terminal, rather
that from a file
command <<DELIMITER
first line of text
second line of text
DELIMITER
the text that will be redirected to the command input is between the two
DELIMITER marks
DELIMITER can be any word, but must not exist in the text itself
# sort <<STOP
> bob
> alice
> trudy
> STOP
alice
bob
trudy
February 7, 2016
16
Used when a single string should be redirected to the input of the command
Example:
# wc <<< "ana are mere"
1
February 7, 2016
3 13
17
Used for commands that write output to the terminal (stdout / stderr)
February 7, 2016
18
February 7, 2016
19
Both stdout and stderr can be redirected for the same command:
February 7, 2016
20
Suppressing output
stdout is suppressed
stderr is suppressed
stdout is written to the terminal
February 7, 2016
21
February 7, 2016
22
the output (stdout) of command1 is used as the arguments list for command2
Example:
February 7, 2016
23
Bash substitutions
Bash substitutions:
variable substitution
$variable or ${variable}
command substitution
$(command) or `command`
arithmetic expansion
$((expression))
brace expansion
{expression}
February 7, 2016
24
Variable substitution
$variable
# a=2
# echo $a
2
February 7, 2016
25
Command substitution
$(command) or `command`
February 7, 2016
26
Arithmetic expansion
$((expression))
Examples:
computing a sum
# echo $((1+2))
3
incrementing a variable
# a=10
# a=$(($a+1))
# echo $a
11
February 7, 2016
27
Brace expansion
Enumeration:
Numeric range:
{min..max}
expands to a list with all integers between min and max
# echo {0..10}
0 1 2 3 4 5 6 7 8 9 10
an increment can be optionally specified: {min..max..incr}
ASCII range:
{char1..char2}
expands to a list with all ASCII characters between char1 and char2
# echo {X..d}
X Y Z [
] ^ _ ` a b c d
28
February 7, 2016
29
February 7, 2016
30
Text filters
Colloquial name for commands that process an input text, resulting a modified output
text
February 7, 2016
31
cat, tac, nl
inverted cat
output the lines in reverse order
nl file1 file2
February 7, 2016
32
sort, uniq
sorts the lines read from standard input of from file (if present)
-u unique (suppresses duplicates)
-r reverse sort
-n numeric sort (default is alpha-numeric)
also can perform advanced sorts (by fields, by multiple keys etc.)
uniq
February 7, 2016
33
head, tail
displays only the first N lines from standard output or file (if present)
if N is omitted, 10 is used
February 7, 2016
displays only the last N line from standard output or file (if present)
if N is omitted, 10 is used
34
cut
Example: displaying only the username and home directory from /etc/passwd
use : as delimiter
select columns 1 and 6
35
tr
Transliterate
Character replace:
tr char1 char2
replaces all occurrences of char1 with char2
# echo "root:/root" | tr ":" " "
root /root
tr s char
useful for processing white-spaces
Character delete
February 7, 2016
tr d char
36
wc
Word count
wc l
# cat /etc/passwd | wc -l
28
wc c
wc w
When used without any options, it displays all the numbers above
February 7, 2016
37
Getting help
Built-in help
Manual pages
Info pages
man command
info command
sometimes they are more detailed that manual pages
February 7, 2016
help command
38
Shell scripts
February 7, 2016
Shell scripts
The file is interpreted by the shell, executing the commands one by one
Used for automating complex tasks
More complex than an one-liner
February 7, 2016
If the script is written for a different shell than bash, use the appropriate interpreter
The path to the interpreter must be present on the first line of the script, preceded by
#!:
# cat hello.sh
#!/bin/bash
echo "Hello, World!
chmod +x hello.sh
Run the script just by specifying its name (like when running a command)
./hello.sh
Hello, World!
February 7, 2016
Return value
February 7, 2016
Comments
# cat hello.sh
#!/bin/bash
# This is my first script
echo "Hello, World! # This line prints a message
# Nothing more to do
February 7, 2016
Conditionals - if
if condition1;
then
commands
[ elif condition2;
then
commands ]
[ else
commands ]
fi
February 7, 2016
Test conditions
[ expression ]
test expression
files
strings
numbers
Examples:
February 7, 2016
Example:
sum=0
for i in 1 2 3 4 5 6 7 8 9 10
do
sum=$(($sum+$i))
done
echo $sum
February 7, 2016
Example:
i=1
sum=0
while [ $i le 10 ];
do
sum=$(($sum+Si))
i=$(($i+1))
done
echo $sum
February 7, 2016
Script parameters
The parameters can be accessed from within the script, via special variables:
February 7, 2016
10
Functions
Defining a function:
function name()
{
commands
}
Calling a function:
name;
Function parameters:
February 7, 2016
can be accessed using $1, $2 etc. (just like accessing script parameters)
are not declared in the function header (bash functions do not have formal
parameters)
11
Regular
expressions
February 7, 2016
Regular expressions
Regular expressions
Strings that use a special syntax for performing pattern-matching on an input text
Syntax:
February 7, 2016
Regular expressions are used in many commands for performing various tasks, based
on pattern matching
grep
sed
awk
February 7, 2016
grep
Basic usage:
grep regular_expression
reads lines from standard input
writes to standard output only lines matching regular_expression
February 7, 2016
grep options
grep i
grep v
grep w
grep n
grep r
February 7, 2016
recursive search
grep r regular_expression starting_dir
5
sed
Stream editor
Syntax
sed /pattern/s/to_be_replaced/to_replace/options
pattern
optional
if present, only apply transformation to lines matching pattern
s the transformation to apply (in this case substitute)
to_be_replaced a pattern to search for
to_replace what to replace the searched pattern with
options
various flags that alter the default behavior
the most used: g do not stop after the first match
February 7, 2016
awk
Examples:
print the 3rd field, delimited by a variable number of tabs and/or spaces:
awk F [ \t]+ {print $3;}
February 7, 2016
Essential system
services
February 7, 2016
System services
System service
configuration
via configuration files
status checking
via log files
February 7, 2016
syslog
Task scheduling
Logging
ntpd
cron
February 7, 2016
sshd
implements the SSH protocol
NTP
ntpd
client receive time from an NTP server and adjusting the local time
package: ntp
configuration file: /etc/ntp.conf
script: /etc/init.d/ntp
default configuration
February 7, 2016
/etc/ntp.conf
...
# pool.ntp.org maps to about 1000 low-stratum NTP servers.
# pick a different set every time it starts up.
# pool: <http://www.pool.ntp.org/join.html>
server 0.debian.pool.ntp.org iburst
server 1.debian.pool.ntp.org iburst
server 2.debian.pool.ntp.org iburst
server 3.debian.pool.ntp.org iburst
...
# By default, exchange time with everybody, but don't allow configuration.
restrict -4 default kod notrap nomodify nopeer noquery
restrict -6 default kod notrap nomodify nopeer noquery
...
February 7, 2016
date
date +format
# date +%Y-%m-%d
2013-02-24
February 7, 2016
date s STRING
Logging
rsyslogd
package: rsyslog
configuration files: /etc/rsyslog.conf, /etc/rsyslog.d/
script: /etc/init.d/rsyslog
February 7, 2016
log messages from various systems are centralized on a single syslog server
useful for scalable, centralized monitoring solutions
Facility level
Severity level
February 7, 2016
/etc/rsyslog.conf
-/var/log/syslog
cron.*
/var/log/cron.log
auth,authpriv.*
/var/log/auth.log
daemon.*
-/var/log/daemon.log
kern.*
-/var/log/kern.log
lpr.*
-/var/log/lpr.log
mail.*
-/var/log/mail.log
user.*
-/var/log/user.log
February 7, 2016
Task scheduling
cron
package: cron
configuration file: /etc/crontab, /etc/cron.*
script: /etc/init.d/cron
Configuration:
February 7, 2016
global: /etc/crontab
per-user: accessed with crontab e
10
crontab syntax
# m h dom mon dow user
command
* * *
root
17 *
* * *
root
fields:
minute
hour
day of month
month
day of week
username
command
February 7, 2016
11
SSH
February 7, 2016
package: ssh
configuration files: /etc/ssh/*
script: /etc/init.d/ssh
12
ssh username@hostname
Enable X forwarding
ssh X username@hostname
useful for launching remote graphical applications
February 7, 2016
13
February 7, 2016
14
Package
management
February 7, 2016
Packages
A package contains
February 7, 2016
Package formats
February 7, 2016
.deb packages can be converted from other formats using the alien utility
in case of complex dependencies, the conversion may not work well
Installing a package
Manually
manually install the package with the distribution-specific command (dpkg, rpm
etc.)
February 7, 2016
install the package with the distribution-specific command (apt-get, yum etc.)
all dependencies are resolved and installed automatically
February 7, 2016
APT operations
apt-get update
upgrades packages that have newer versions that the ones locally installed
apt-get upgrade
February 7, 2016
search for a package with the name or description containing the specified word
Hardware devices
February 7, 2016
Device drivers
Inspecting the kernel configuration: /boot/config*
February 7, 2016
lspci
February 7, 2016
lsusb
Example:
# lsusb
Bus 007 Device
Bus 006 Device
Bus 005 Device
Bus 004 Device
Bus 003 Device
Power Supply
Bus 003 Device
Bus 002 Device
Bus 001 Device
February 7, 2016
001:
001:
001:
001:
002:
ID
ID
ID
ID
ID
1d6b:0001
1d6b:0001
1d6b:0001
1d6b:0001
051d:0002
hub
hub
hub
hub
Uninterruptible
lshw
Displays a list of all hardware devices in the system (not just PCI or USB devices)
February 7, 2016
Raw information about the hardware devices can also be found in some virtual file
systems
/sys/
/proc/
/dev/
February 7, 2016
Device drivers
Device driver software that acts as an interface between the hardware and the
operating system
February 7, 2016
Kernel configuration
/boot/config-kernel_version
Example:
CONFIG_RTL8180=m
the driver for the Realtek 8180 NIC is available as a module
February 7, 2016
lsmod
Example:
# lsmod
Module
btrfs
zlib_deflate
crc32c
libcrc32c
ufs
qnx4
hfsplus
hfs
minix
ntfs
vfat
msdos
fat
jfs
xfs
exportfs
reiserfs
ext3
...
February 7, 2016
Size
376157
17746
2560
1074
56522
6194
65350
37567
21213
162972
7900
6202
40070
140201
435849
3186
194300
106854
Used by
0
1 btrfs
1
1 btrfs
0
0
0
0
0
0
0
0
2 vfat,msdos
0
0
1 xfs
0
0
9
modprobe, insmod
modprobe
insmod
February 7, 2016
10
modprobe r, rmmod
modprobe
rmmod
February 7, 2016
11
/etc/modules
modules that should be loaded at boot time can be manually specified here
each line contains a module name
/etc/modprobe.d/blacklist.conf
February 7, 2016
12
Booting the
system
February 7, 2016
Boot sequence
Each step from the boot sequence prepares the system for the next step
Steps:
February 7, 2016
BIOS
MBR
bootloader
kernel
init
runlevel (services)
GRUB
versions:
GRUB 1 obsolete
GRUB 2 current stable version
Roles:
February 7, 2016
GRUB - installing
update-grub
detects the operating systems installed on the system and builds a configuration
file
the configuration file is saved in /boot/grub/grub.cfg
grub-install block_device
Note: GRUB can also be installed on a partition, but that partition has to be marked
bootable
February 7, 2016
GRUB - configuring
re-run update-grub
Examples of parameters:
GRUB_DEFAULT
which entry from the GRUB menu to boot into by default (starts from 0)
GRUB_TIMEOUT
number of seconds to wait for user input before booting into default entry
February 7, 2016
Kernel parameters
Parameters can also be manually altered at boot time, by using the GRUB menu
After the system has booted, the parameters can be accessed using /proc/cmdline:
# cat /proc/cmdline
BOOT_IMAGE=/vmlinuz-2.6.32-5-amd64 root=/dev/sda2 ro console=tty0
February 7, 2016
After the init process is started, the system enters a certain runlevel
A runlevel defines which services should be started and which should remain stopped
February 7, 2016
0 halt (shutdown)
1 single-user mode (no daemons and no networking started)
2-5 multi-user mode (all services and networking started)
6 reboot
For changing the runlevel, use init N, where N is the desired runlevel to switch to
examples:
init 0 shuts the system down
init 6 reboots the system
init 1 stops all services and disables networking (mostly used for debugging
purposes)
February 7, 2016
Initialization scripts
February 7, 2016
Runlevel scripts
Each runlevel has associated scripts which specify which services to run and which to
stop
the scripts are found in /etc/rcN.d/
N is the runlevel number
February 7, 2016
10