Curs Linux 2017 PDF
Curs Linux 2017 PDF
1. Installing the OS
User
You and me
Applications
OpenOffice Writer, Mozilla Firefox
Operating System
Kernel – Linux, GNU Hurd
Modules – pcnet32, cdrom, ip_nat, ext3
Shell – bash, sh, csh, zsh
Tools – cp, mv, rm
Hardware
CPU, Memory, GPU, HDD
Kernel
Modules
Each module offers a service to the OS (e.g. memory management, process management)
Modules are dynamically loaded only the necessary modules are loaded at any given
time
Shell
The interface between user/applications and the kernel
Can be a CLI (command line interface), or a GUI (graphical user interface)
Examples:
CLI: Bourne shell (sh), Bourne Again Shell (bash), Korn shell (ksh), C shell (csh)
GUI: Gnome, KDE, CDE, XFCE
Tools
Small applications used for basic functions
cp, rm, mv
C compiler
Assembler
Used directly by the user (at the shell prompt), by more complex programs, or by the shell (shell
script)
Distribution
Operating system (kernel, shell, tools)
Installer
Bootloader
Package manager
Applications – web browser, e-mail client, office suite
Network install
Update vs. fresh install
Basically the same for most distributions (not necessarily in the same order):
Choose language, keyboard, mouse
Create partitioning scheme
Configure bootloader
Select and install software packages
Configure root password and create users
Configure X
Configure network
Other configs (sound, firewall, automatic updates, etc.)
Command shells
Navigation
Programming environment
Graphical shells
Command-line shells:
Sh, ash, bash, csh, dash, fish, ksh, zsh (and many, many more).
Graphic shells:
# for root*
Examples:
$PS1
$SHELL
$PATH
…
Shell variable
Commands can be
Commands not in PATH can be executed with the fully qualified filename
command (Ex. ls )
!! Spoken as bang-bang, this command refers to the most recent command. The
exclamation point is often called bang on Linux and Unix systems.
!n Refer to command n from the history. Use the history command to display these
numbers.
^string1^st Quick substitution . Repeat the last command, replacing the first occurrence of
ring2 string1 with string2.
Key bindings
Ctrl-p - Previous line (also up arrow)
Ctrl-n - Next line (also down arrow)
Ctrl-b - Back one character (also left arrow)
Ctrl-f - Forward one character (also right arrow)
Ctrl-a - Beginning of line
Ctrl-e - End of line
Ctrl-l - Clear the screen, leaving the current line at the top of the screen
Alt-< - Top of history
Alt-> - Bottom of history
Ctrl-d - Delete character from right
Ctrl-k - Delete (kill) text from cursor to end of line
Ctrl-y - Paste (yank) text previously cut (killed)
Alt-d - Delete (kill) word
Ctrl-r-text - Reverse search for text
Ctrl-s-text - Forward search for text
Command substitution
Recursivity
ls [OPTION]... [FILE]...
Filesystem objects
File-naming wildcards
Objects are constantly created, read, modified, copied, moved and deleted:
touch – creates an empty file
mkdir – creates an empty directory
cp – copy one or more files to another location
mv – move or rename files and directories
rm – delete one or more files from filesystem
file – determine file type
ln – create links
Standard I/O – shell capability to control and direct program input, output and error
File descriptors:
Standard Input (stdin/file descriptor 0) – text input stream. By default it is attached to
keyboard.
Standard Output (stdout/file descriptor 1) – text output stream. By default it is attached
to terminal.
Standard Error (stderr/file descriptor 2) – also a text output stream but used exclusively
for errors. By default it is attached to terminal.
backtick (`) not (‘) – shell replaces the content between backticks with the output
Ex. rm `find /home/user/ -name "*~"`
$(command) – same result, easier to read!
tee – read from standard input and write both to one or more files and to standard
output (analogous to a tee junction in a pipe).
Wildcard Description
Match zero or more characters
*
Example: x* matches x, xy, xyz, x.txt, xy.txt, xyz.c,…
Match exactly one character.
?
Example: x? matches files or directories xx, xy, xz, but not x and not xyz.
Match any single character from string. Can also use a range.
[string]
Example: x[yz] matches xy and xz.
x[a-e] matches xa and xc, but not xf or xz.
Match any single character not in string.
[!string]
Example: x[!yz] matches xa and x1 but does not match xy or xz.
Create strings f1, f2, f3, etc. For example, file_{one,two,three} yields the strings file_one, file_two, and
{f1,f2,f3...}
file_three.
Regular expressions:
used by various tools (grep, sed, perl, etc.)
used to search and process text
[] : range of characters
^ : in a range, negates the range
[bc]at
matches bat, cat
does not match hat, Cat
[a-z]ole
matches role, sole, pole
does not match Role
(rat|RAT)
matches rat or RAT
“at”
matches bat, cat, hat
does not match set
[bch]at
matches bat, cat, hat, that
does not match rat
[^bc]at
matches hat, rat
does not match bat, cat
might match at (depending on previous character)!
[Cc]onfidential
matches confidential,Confidential
does not match confident
[Rr][Aa][Tt]
matches rat, Rat, RAT, raT
does not match hat, haT, Hat
tr?oll
matches toll, troll, stroll
does not match stall, trill
tra+p
matches trap, traap, traaaaaaap,…
does not match trip, trp
sto*p
matches stop, stoop, stp
does not match step
^ : beginning of text/line
$ : end of text/line
\:
escapes metacharacters
gives special meaning to some literals
backreferences:
\1,\2… : match the group numbered 1, 2…
the order is determined by opening parentheses
(abc)\1
matches abcabc
does not match abcabd, acabd
(.{2,3})\1
matches abab, abcabc, xyxy, xabxab
does not match abcdabcd, abba
ab\[cd\]\?
matches ab[cd]?
does not match abc, abcd, ab
Position anchors
^, $
Character sets
[], rat, [:alpha:], .at
Quantity modifiers
?, *, {m,n}
# ls
abc abc1
abd
grep abc* *
is expanded to grep abc abc1 abc abc1 abd before execution!
Solution:
grep “abc*” * or
grep ‘abc*’ *
grep –i “linux” *
search for linux, Linux, LINUX, linuX… in all the files in the current directory
display filename and matching line if found
configure - script that creates the correct Makefile for your system
make install - copies the resulting files to the appropriate place in the filesystem
Many of the functions required by programs are linked from system libraries:
disk functions
memory functions
various other functions
Statically linked programs contain the code from the libraries. Such a program stands alone,
requiring no additional code at runtime.
Dynamically linked programs load the necessary code from the libraries as needed.
Dynamically linked libraries are shared among many applications and are thus called shared
libraries
ld.so - looks for dependencies in the executable being loaded and attempts to satisfy
any unresolved links to system-shared libraries.
To add the new library entry to the ld cache, first add its directory to the ld.so.conf
file, which contains directories to be indexed by the ldconfig utility.
ldconfig - Update the ld.so cache file with shared libraries specified on the
command line, in /usr/lib and /lib, and in the directories found in /etc/ld.so.conf.
rpm modes :
rpm -i [options ] (also rpm --install)
rpm -U [options ] (also rpm --upgrade)
rpm -e [options ] (also rpm --uninstall)
rpm -q [options ] (also rpm --query)
rpm -V [options ] (also rpm --verify)
rpm –F [options] (also rpm –-freshen)
Frequently
Option used
Description install and upgrade options:
--force Allows the replacement of existing packages and of files from previously installed packages;
for upgrades, it allows the replacement of a newer package with an older one
-h Prints a string of 50 hash marks (#) during installation as a progress indicator. (--hash)
--nodeps Allows you to install a package without checking for dependencies. (Not a good ideea!)
--test Runs through all the motions except for actually writing files
-v[v] Sets [really] verbose mode.
Option Description
--nodeps Skip dependency checking (not a good idea!)
--test Verify that a package can be uninstalled correctly without breaking
other dependencies prior to making the attempt.
Verify mode - Files from installed packages can be compared against their
expected configuration from the RPM database by using rpm -V.
Option Description
--nofiles Ignores missing files.
--nomd5 Ignores MD5 checksum errors.
--nopgp Ignores PGP checking errors.
Debian RedHat
Package installation dpkg rpm
apt
Package management / updater yum
(apt-get)
GUI Tools synaptic pirut
GUI Updater update-manager pup
Examples:
/dev/hdb1
Primary slave IDE disk, first partition
/dev/sdc5
Third SCSI/SATA disk, first logical partition
MBR supports only 1 byte partition type codes, which are not standardized
collisions
Uses 64bit LBA for storing Sector numbers (2 ZiB max disk size).
Stores a backup header and partition table at the end of the disk.
Decimal Binary
Value SI Value IEC JEDEC
1000 k kilo 1024 Ki kibi K kilo
2 2
1000 M mega 1024 Mi mebi M mega
3 3
1000 G giga 1024 Gi gibi G giga
4 4
1000 T tera 1024 Ti tebi – –
5 5
1000 P peta 1024 Pi pebi – –
6 6
1000 E exa 1024 Ei exbi – –
7 7
1000 Z zetta 1024 Zi zebi – –
8 8
1000 Y yotta 1024 Yi yobi – –
Location Purpose
First 512B Protective MBR - Same as a normal MBR but the 64-byte area
contains a single 0xEE type Primary partition
Next 512B Primary GPT Header
Next 16KiB Primary GPT Table
Last 512B Secondary GPT Header
16KiB before Secondary GPT Table
fdisk –l
There are many other tools for the same purpose (parted, QtParted, diskdruid,
Yast…)
CLI-only or GUI
Dynamic partition resize
# fdisk /dev/sda
It consists of gdisk, sgdisk and cgdisk which are equivalent fdisk (used for MBR disks)
Same as fdisk
# fdisk /dev/sda
GPT fdisk (gdisk) version 0.8.8
Solution - journaling:
record changes before applying them
replay changes if a crash occurs
ReiserFS
Optimized for large numbers of small files
Btrfs
Development began at Oracle
GPL Licensed
inspired by ZFS
NTFS
Preferred filesystem on Windows NT/200x/XP/Vista.
Support for read/write operations is provided by the NTFS-3G driver.
mkfs.fstype <device>
or by using the frontend:
mkfs –t <fstype> <device>
Filenames in Linux
Can contain letters (uppercase and lowercase), numbers, and other characters
Should not contain characters with special meanings: * ? \
Are case-sensitive!!
Special filenames:
. , .. , ~
Wildcards:
? – one character
* - zero or more characters
[] – match a range of characters
b??k
Matches book, back, bark
Does not match bk, brink
b*k
Matches bk, back, book, brink
Does not match blocks,nobook
b[a-e]ck
Matches back, beck, bdck
Does not match bnck, bask
ls (list)
Display all files in a given directory
Frequently used options:
-a (--all) : display all files (including hidden files)
--color : color files depending on their type
-l : display additional information (including permissions)
-R : recursively display the contents of subdirectories
Hardware RAID
Not flexible
Fast
RAID subsystem is independent from host system.
Better performance than Software RAID
Expensive
Built-in RAID controller in hardware
Software RAID
Flexible, cheap
Easy to implement RAID
Implemented in kernel disk (block device) code
Performance dependent on host system (CPU and Memory)
Consumes around 25% of host system processing cycles
But, fast CPU help improve the performance of Software RAID.
File System
RAID Levels
Linear mode Buffer Cache
RAID-0
RAID-1 Software RAID
RAID-4
Device Driver
RAID-5
Etc.
RAID0
Striping
RAID5 (> 3 disks)
RAID1 Striped array with distributed parity
Mirroring
RAID6 (> 4 disks)
RAID4 (> 3 disks) Striped array with dual redundancy
Striped array with a parity device information
RAID1+0
Striped array of mirrored disks
RAID5+1
RAID0+1
Mirroring two RAID5s
Mirroring two RAID0s
RAID5+0
Striped array of RAID5s
An update may involve both the data block and the parity block
Implications
A RAID may be shut down in an inconsistency state
Resynchronization may be required at startup, in the background
Reduced performance
Physical Volume (PV) - a device (HDD) with some administrative data added to it
Physical Extent (PE) - a chunk of storage space located onto a physical volume
(PV)
system
vgremove – remove a VG
vgsplit - splits a VG and creates new VG
vgmerge – used to combine two VGs into a single VG
vgcfgbackup/vgcfgrestore – backup/restore metadata
vgrename – renames an existing VG
vgexport – can move an entire VG to another system.
vgmknodes – recreates a VG directory and LV special files.
MBR /boot
POST – BIOS – Look up Load bootloader Load rest of
Power on Hardware Test boot order Kernel
in memory bootloader
(stage1) (stage2)
Located in the MBR (Master Boot Record) – first 512B of a partitioned HDD
The MBR contains the bootloader and the partition table
Two possibilities:
1. The bootloader:
1. Scans the partition table and locates the partition marked as active
(bootable)
2. Loads the boot sector on that partition and executes it
3. The boot sector contains a secondary bootloader that continues
the process of locating, loading and running the kernel
2. The bootloader locates the OS kernel and executes it directly
(bypassing the secondary bootloader)
/etc/rc.d/
BIOS /etc/inittab
rc3.d
/etc/rc.d/
Linux rc.sysinit RL Specific
GRUB init
Kernel /etc/inittab
/etc/rc.d/rc
Login /etc/rc.d/
Shell rc5.d
/etc/rc.d/
BIOS systemd rc3.d
Systemd
Linux
GRUB init RL Specific
Kernel /etc/
init/*.conf
Login /etc/rc.d/
Shell rc5.d
/etc/grub.conf
Some distributions may use /boot/menu.lst or /boot/grub/grub.conf
timeout=15
splashimage=/grub/bootima
ge.xpm.gz
/boot/grub/grub.cfg
Important changes compared to GRUB Legacy include the following
The title keyword is replaced by menuentry.
The menu title is enclosed in quotation marks.
An opening curly brace ({) follows the menu title, and each entry ends with a closing curly brace
(}).
The set keyword precedes the root keyword, and an equal sign (=) separates root from the
partition specification.
The rootnoverify keyword has been eliminated; you use root instead.
Partitions are numbered starting from 1 rather than from 0. A similar change in disk
numbering is not implemented.
# grub-install <device>
<device> can be specified
As a filename: /dev/hda
As a GRUB disk/partition name: (hd0), (hd0,0)
You may need to run update-grub after updating GRUB 2’s /etc-based configuration files.
Runlevel Description
0 Halt (shutdown)
1, s, S Single-User mode
2 Multiuser. On Debian this is the default runlevel. On Red Hat it is multiuser without networking.
3 Multi-User mode, console logins only. (not used in Debian).
4 Not used.
5 Multi-User mode, with display manager as well as console logins (X11) (not used in Debian)
6 Reboot
BSD Systems
swapper – PID 0
init – PID 1
pagedaemon – PID 2
Unix System V
sched – PID 0 (invisible under RedHat/CentOS)
init – PID 1
/etc/inittab
The "/etc/inittab" file has information on which runlevel to start the system at and lists the
processes to be run at each runlevel.
Each runlevel can be configured by the system administrator.
Each runlevel has its own directory structure where you can define the order in which the services
start.
These directories are located in the /etc directory, under which you have rc1.d, rc2.d, rc3.d…. rc6.d
(coresponding to each runlevel)
Inside each directory are symbolic links that point to master initscripts found in /etc/init.d or
/etc/rc.d/init.d.
The actions of init for each runlevel are derived from Unix System V-style initialization
Hostname
Timezone
Check the hard drives
Mount the hard drives
Remove files from /tmp
Configure network interfaces
Start daemons and network services
init is level-driven – you allocate each service to a runlevel, and services are started up in blocks
based on which runlevel you boot into.
Within the runlevels, the names of the start and stop links govern the timing of the script.
Each /etc/rcx.d directory has a collection of softlinks to the start/stop service scripts in /etc/init.d/.
These look like this:
K20service -> /etc/init.d/service
S35service -> /etc/init.d/service
The numbers control the order, to avoid dependency problems: lower numbers are run first.
init cannot handle hardware that's plugged in after bootup.
init cannot handle networked filesystems which may not be available on boot
init cannot handle daemons which we'd like only to run when the hardware is available
[Unit]
Description
Requires
Wants
Conflicts
Before
After
[Service]
Type=
simple|oneshot|forking|dbus|notify|idle
ExecStart
ExecReload
ExecStop
Restart=
no|on-success|on-failure|on-abort|always
[Install]
Wantedby=
(e.g. Runlevel)
The SysV startup scripts in the runlevel directories are symbolic links back to the
original script.
You can also modify which programs are active in a runlevel by editing the link
filenames.
Numerous utility programs are available to help you manage these links, such
as chkconfig, ntsysv, update-rc.d, and rc-update.
In systemd you can use systemctl command.
Option Explanation
--list list the services and their applicable runlevels
--list <name> view runlevels for a particular service
--level <levels> <name> alter runlevels for a particular service (on, off or reset to
on|off|reset default value)
--add <name> register a service and add appropriate start and stop links
in the runlevel directories.
disable [runlevel] Modifies existing runlevel links to disable the service in the specified
runlevel. If no runlevel is specified, runlevels 2, 3, 4, and 5 are modified.
Command Effect
systemctl start|stop|restart Used to start|stop|restart a service (not reboot persistent)
<service>
systemctl condrestart
Restarts if the service is already running.
<service>
systemctl status <service> Tells whether a service is currently running.
systemctl (or) systemctl list- Used to list the services that can be started or stopped
unit-files --type=<service>
systemctl enable|disable Turn the service on|off, for start at next boot, or other trigger.
<service>
systemctl is-enabled Used to check whether a service is configured to start or not in the current
<service> environment.
Before changing your runlevel you should type initctl reload to have Upstart reread its
configuration files.
exec
script
start on <event>
stop on <event>
task
respawn
See man 5 init for more
control-alt-delete
power-status-changed
startup
runlevel <runlevel>
started <job>
stopped <job>
To make a permanent change, you can edit /etc/inittab and change the default
level (sysvinit ) or use /etc/systemd/system/default.target (systemd)
If you need to bring system up in a different runlevel for one boot you can:
Edit the kernel line in GRUB
Add a parameter after the selected system name in LILO
If you need to switch between runlevels while system is running use „init” command.
The basic user database in a Unix system is the text file, /etc/passwd,
which lists all valid usernames and their associated information.
Each line in the file contains information for a single system account :
Username - The first field on a line is a unique username for the person or service
using the account.
Password - Each username has an associated password. For security reasons, most
systems store user passwords in a separate /etc/shadow file.
UserID - Each username requires a unique user identifier, or UID. The UID is simply a
nonnegative integer.
GroupID - Each username has a default group identifier, or GID. The GID is also a nonnegative integer.
Full name (or other comment) - The user's full name or other information is stored as plain text. This
field may contain spaces.
Home directory - The home directory is the default directory in the filesystem for the user's account.
Default shell - This field specifies the default shell for the user or service, which is the shell that runs when
the user logs in or opens a shell window.
The root account has UID and GID 0, which gives it global privilege on the system.
Groups are similar to users in their administration and are defined in the file
/etc/group
Groups can be assigned to logically tie users together for a common security,
privilege and access purpose.
Like the passwd file, the group file contains colon-separated fields
Account users can use the newgrp command to change their default
group and enter the group password.
Option Description
useradd Define
-C comment [options] user field,
the comment - Create
usually thethe account
user'suser on the
name.
system. Both
-d homedir
system defaults and specified options define how
Use homedir as the user's home directory.
-m
the account is configured.
Create and populate the home directory.
-S shell Use shell as the default for the account.
-D List (and optionally change) system default values
userdel [-r] user - Delete an existing user account. When combined with
the -r option, the user's home directory is deleted.
groupadd group - Add group to the system.
groupmod [option] group - Modify the parameters of group.
groupdel group - Delete group from the system.
passwd [options] username - Interactively set the password for
username.
The other 9 characters are 3 blocks of 3 characters, denoting permissions for owner / group / other users
The permissions are:
r : read
w : write
x : execute
eXecute permission (x) for directories = the right to change to the directory
Write permission (w) for directories = the right to create, delete or rename files in
the directory
Even if the user does not have permissions on the files!
Special permissions
SUID (Set User ID – rwsr-xr-x) – executes a file using the permissions of the file’s owner
SGID (Set Group ID – rwxr-sr-x) – executes a file using the permissions of the file’s
owner group
by specifying the entity and rights that are added (+), withdrawn (-), or applied exactly (=):
# chmod a+x program
# chmod u+rwx,g-rx,o=x program
chattr can add (+), remove (-) or specify exactly the attributes for a file:
# chattr +i important.txt
# chattr =aj data.txt
User ID (UID) and Group ID (GID) - associated with the user who started the
process, determine the rights the process has
Parent process ID (parent PID) - PID of the process that created the process in
question.
If the parent dies, the child is “adopted” by init (PID 1)
Current working directory - the process will read and write files in this directory
unless they are explicitly specified to be elsewhere
Option Description
-b Run in batch mode. This is useful for sending output from top to other programs or to a file. It
executes the number of iterations specified with the -n option and terminate.
-d delay Specify the delay in seconds between screen updates. The default is five seconds.
-i Ignore idle processes, listing only the "interesting" ones taking system resources.
-n num Display num iterations and then exit, instead of running indefinitely.
-q Run with no delay. If the user is the superuser, run with highest possible priority. This option causes top
to update continuously and will probably consume any idle time your CPU had.
-s Run in secure mode.
Option Description
Ctrl-L Screen refresh
h Generate a help screen.
k Kill a process.You will be prompted for the PID of the process and the signal to send it.
n Change the number of processes to show.You will be prompted to enter an integer number.
q Quit the program.
r Change the priority of a process (renice).
s Change the delay in seconds between updates.
signals – numeric integer predefined messages sent to the process either by the
kernel or by a user through interprocess communication
When a process receives a signal (usually sent with „kill” command), it can (or may
be forced) to take action.
There are more than 32 signals defined for normal process use in Linux. Each signal
has a name and a number (the number is sent to the process, the name is only for
convenience)
HUP 1 Hang up. It is used by many daemons to cause the configuration file to be reread.
INT 2 Interrupt; stop running. This signal is sent when you type Ctrl-C.
KILL 9 Kill; stop unconditionally and immediately. Sending this signal is a drastic measure, as it
cannot be ignored by the process. This is the "emergency kill" signal.
TERM 15 Terminate, nicely if possible. This signal is used to ask a process to exit gracefully.
TSTP 20 Stop executing, ready to continue. This signal is sent when you type Ctrl-Z.
CONT 18 Continue execution. This signal is sent to start a process stopped by SIGTSTP or
SIGSTOP. (The shell sends this signal when you use the fg or bg commands after
stopping a process with Ctrl-Z.)
Job control - the ability of the shell (with support of the kernel)
to stop and restart executing commands, as well as place them
in the background
Process priority
the PRI column in top or ps –l
Each process's priority level is constantly and dynamically raised and lowered by the kernel according
to a number of parameters, such as how much system time it has already consumed and its status.
Text files
Receives messages from various sources (applications, remote devices, etc) and
(usually) stores them into files
Identifies:
Which messages should be logged
Where the messages are sent:
files (and other file-like devices, e.g. terminals)
message to user(s)
pipe to a program
another host (over the network)
daemon.* -/var/log/daemon.log
mail.info -/var/log/mail.info
*.=debug -/var/log/debug
*.emerg *
*.* @remote.logging.host
mail.*; *.info |/dev/xconsole
General format:
date/time hostname program: message
Mar 6 21:20:49 thermite sshd[10514]: Failed password for invalid user bureau
from 222.87.204.11 port 41506 ssh2
Mar 6 21:20:53 thermite sshd[10518]: Invalid user jasmin from 222.87.204.11
Mar 6 21:48:19 thermite sshd[11375]: Invalid user ant from 121.14.31.2
Mar 6 21:48:24 thermite sshd[11379]: Invalid user office from 121.14.31.2
logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]
Options:
-f file – log contents of file
-s – also log to stderr
-t – specify custom tag
-p pri – specify priority (and facility)
Job scheduler
Runs jobs at specified date/time(s)
System job:
/etc/crontab
files in /etc/cron.d/
/etc/cron.INTERVAL/ - hourly, daily, weekly…
Must specify the “run as” user
User job:
crontab –e
Final crontabs are stored in /var/spool/cron/crontabs/ (or similar)
cron commands
Min Hr DoM Mth DoW [USER] COMMAND
* = any
*/X = run at intervals of X
Output from the commands (if any) is sent to the owner of the crontab by mail
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
bogd@thermite:~$ crontab -l
man 1 crontab
The crontab program
man 5 crontab
The crontab file format
man cron
root@vm-ubuntu:~# at "13:27"
at> echo "done" > fixed_time.txt
at> <EOT>
job 4 at Thu May 10 13:27:00 2011
root@vm-ubuntu:~# date
Thu Mar 10 13:26:57 EET 2011
root@vm-ubuntu:~# cat fixed_time.txt
cat: fixed_time.txt: No such file or
directory
root@vm-ubuntu:~# date
Thu Mar 10 13:27:00 EET 2011
root@vm-ubuntu:~# cat fixed_time.txt
done
TCP/IP
Data Encoding
Application
Provides services to the users
Application Data
Presentation
Session
Data Transmission
Transport
MAC Port
Sync Bits IP address numbers
Address
To differentiate the segments and datagrams for each application, TCP and UDP
have header fields (port numbers) that can uniquely identify these applications.
The source port number is associated with the originating application on the local
host.
The destination port number is associated with the destination application on the
remote host.
A socket pair, consisting of the source and destination IP addresses and port
numbers, is unique and identifies the conversation between the two hosts.
When services send data using TCP, segments may arrive at their destination
out of order.
Sequence numbers are assigned in the header of each packet and the
segments are reassembled into the original order.
The receiving TCP process places the data from a segment into a receiving
buffer.
Segments are placed in the proper sequence number order and passed to
the Application layer when reassembled.
© 2017 All rights reserved.
UDP
1970 2011
Classful allocation of address space often wasted many addresses, which exhausted
the availability of IPv4 addresses.
Even though this classful system was all but abandoned in the late 1990s, you will see
remnants of it in networks today.
With the classless system, address blocks appropriate to the number of hosts are
assigned to companies or organizations without regard to the unicast class.
192.168.1.2:32001 86.1.1.1:32001
private
public
192.168.1.3:32001 86.1.1.1:32002
192.168.1.4:32001 86.1.1.1:32003
AFRNIC - Africa
APNIC - Asia, Pacific
LACNIC - South America & Caraibe
ARIN- North America
RIPE NCC –Central and Eastern Europe, Middle East
© 2017 All rights reserved.
NETWORKING CONFIGURATION
INTERFACES, CONFIG FILES
hostname [localname]
domainname [nisname]
dnsdomainname
Set or display the current host, domain, or node name of the system.
netstat [options]
Depending on options, netstat displays network connections, routing tables, interface statistics,
masquerade connections, netlink messages, and multicast memberships.
ip - An alternative to the ifconfig, route, and various other commands for many
purposes.
ip [ OPTIONS ] OBJECT { COMMAND | help }
ex. ip route list
Object Description
link Performs actions on network hardware; similar to some ifconfig functions
addr Associates or disassociates a device with an address; similar to ifconfig
addrlabel Displays or adjusts addresses in an IPv6 network
route Displays or adjusts the routing table; similar to some route functions
rule Displays or adjusts firewall table rules; similar to some iptables functions
neigh Displays or adjusts ARP entries
monitor Monitors network for activity
route is used to establish static routes to specific networks or hosts (such as the
default gateway) after an interface is configured.
Option Description
-n Numeric mode; don't resolve hostnames.
-F Display the kernel routing table (the default behavior without add or delete ).
-host | -net Specify that target is a single host or a net. Mutually exclusive.
gw IP packets for target are routed through the gateway, which must be reachable.
When used to display routes, the following routing table columns are printed:
Column Description
Gateway The gateway address. If no gateway is set for the route, an asterisk (*) is displayed by default.
Genmask The netmask for the destination. 255.255.255.255 is used for a host and 0.0.0.0 is used for the
default route.
Route status flags !, D, G, H, R, M, U (reject, dynamic, use gw, target is host, modified, reinstated, up).
Iface The interface to which packets for this route are sent.
Echo
Confirm connectivity using a pair of messages: Echo-Request , Echo-
Reply
Time Exceeded
Sent to the originator of a packet in order to inform it that the
packet’s TTL has reached 0 before reaching the destination
Redirect
Sent to notify the originator of traffic about a better route to a
destination
Create customized datasets on the fly, and call applications (e.g. matlab, sas,
idl, gnuplot) to work on them
The kernel knows how to run a script file by looking at the first line:
#!/bin/bash
also known as “shebang”, “hashbang”, “hashpling”…
notice there are no spaces between the characters!
bogd@thermite:~/curs$ ./script.sh
Hello world
External commands
Variables
Remember:
options
-e -r –I -erl
--exclude-results, --recursive, --long-names
options with parameters
-w 80
--width=80
arguments
file1 file2 file3
All variables are strings, and unset variables default to the empty string
#!/bin/bash
myvar="hello"
echo "My variable is <$myvar>"
echo "Current path is <$PATH>"
echo "Argument 0 is <$0>"
echo "Argument 1 is <$1>"
echo "Argument 2 is <$2>"
bogd@thermite:~/curs$ ./vars.sh 1 2 3
My variable is <hello>
Current path is </usr/local/sbin:/usr/local/bin>
Argument 0 is <./vars.sh>
Argument 1 is <1>
Argument 2 is <2>
bogd@thermite:~/curs$ ~/curs/vars.sh 1 2 3
My variable is <hello>
Current path is </usr/local/sbin:/usr/local/bin>
Argument 0 is </home/bogd/curs/vars.sh>
Argument 1 is <1>
Argument 2 is <2>
“man test” or “info coreutils ‘test invocation’” for a complete list of tests
Syntax:
if EXPR
then
COMMANDS
fi
#!/bin/bash
if [ -e $0 ] #Check my own filename
then
echo "I do indeed exist!"
else
echo "I am not there…"
fi
bogd@thermite:~/curs$ ./test.sh
I do indeed exist!
Syntax:
#!/bin/bash
for file in file1 file2 for1.sh
do
if [ -e $file ]
then
echo "File $file exists!"
else
echo "File $file does not exist!"
fi
done
bogd@thermite:~/curs$ ./for1.sh
File file1 does not exist!
File file2 does not exist!
File for1.sh exists!
Syntax:
while EXPR
do
COMMANDS
done
Defining a function:
function_name() {
COMMANDS
}
Calling a function:
function_name
check_file(){
if [ -e $1 ]
then
echo "Target file $1 exists!"
exit
fi
}
copy_file(){
cp $1 $2
}
Password recommendations:
use strong passwords
change passwords frequently
use shadow passwords
keep passwords secret
use secure remote login
use separate passwords on separate systems
Poor passwords:
names (family/friends/pets), date of birth, telephone numbers, favourite shows, etc.
ANY word that is found in a dictionary!
Strong passwords:
upper/lowercase, punctuation, digits
at least 8 characters!
Suggestion:
“The quick brown fox jumps over the lazy dog!” Tqbfj0tld!
“Trust none of the people around you!” Tn0tp4y!
Password hashes have been moved from the world-readable /etc/passwd to the
more secure /etc/shadow.
Shadow passwords also add support for password aging and account expiration
Shoulder surfing
Worst option:
Direct login as root:
not recommended
no trace in logs as to who actually typed the root password
A little better:
su - , or su –c COMMAND – leaves a trace in the logs
Much better:
sudo COMMAND – runs a single command as superuser
requires the user’s password
/etc/security/limits.conf
Domain:
username
@groupname
* (everyone)
Type:
hard (cannot be exceeded)
soft (can be modified by users)
Item:
core – size of core files
data – size of a program’s data area
cpu – CPU time of a process (minutes)
maxlogins – number of simultaneous logins
priority – default process priority
…
Value:
actual value of the limit
Bash built-in command, only affects bash and programs launched from it!
Files run with the permissions of the owning user (SUID) / owning group (SGID)
Unencrypted traffic
Vulnerable to sniffing
Drawbacks:
extra CPU consumption
/etc/ssh/sshd_config
Options:
Protocol – version of the SSH protocol
PermitRootLogin – whether to accept or not direct root logins
…
man sshd_config
Public/private keys
Public server keys are stored on the client at first connection, and user is warned on
server key change
stored in ~/.ssh/known_hosts
TCP Wrappers
Allow you to use /etc/hosts.allow and /etc/hosts.deny to control access
Requires SSH to be compiled with TCP Wrappers support (or run from a superserver)
Firewalls
Just an example:
iptables -A ssh_filter -m limit --limit 2/minute --limit-burst 3 -j ACCEPT
/etc/nologin
If present, only root can login
SCP (SecureCopy)
Syntax:
Allows you to use a public/private key combination in order to login to another machine