Documente Academic
Documente Profesional
Documente Cultură
Mohammad Ariful Hyder Associate Professor, Dept. of CSE Dhaka City College, Dhaka.
Unix/Linux History
Unix first version created in Bell Labs-1969 Write Unix system in C language-1973 by Denis
Ritchie AT&T licenses source code for low cost, Trademarkes Unix name, licensees must create new name for their operating systems Many Unix Flavors:, IBM-AIX, Solaris,UnixWare, HP-UX
30 January 2013
Unix Principles
Multiuser, Multitasking
Configuration data stored in text Ability to chain programs together to perform
complex tasks Working with Wide variety of computers High Level of Security
30 January 2013
(gcc, emacs,..)
30 January 2013
30 January 2013
30 January 2013
Linux Origins
Linus Torvalds
Finnish college student in 1991 create Linux kernel Code was made available over the internet for free Coders world wide took part in developing the OS
When Linux Kernel combined with GNU applications, complete free Unix-like OS appears (GNU/Linux OS)
30 January 2013
Why Linux
Linux and GNU software are distributed under the terms of the GNU Public License Agreement (GPL)
Linux is continually being developed by individuals throughout the world Skilled programmers can submit additions and
30 January 2013
Why Linux
Applications are developed that are both free and commercial
Linux is for Intel based platforms, Power PC, Alpha-
Support available
30 January 2013
10
+Name Server
30 January 2013
11
30 January 2013
12
30 January 2013
13
Sector Cylinders
Sectors
Head
30 January 2013
14
1234
MBR
30 January 2013
Partition 1
Partition 2
Partition 3
Partition 4
15
1234
Status Start FS End
A
0000 1BEh 1FEh
2
2001 3501 6001
FAT32
FAT16 EXT2 NTFS
2000
3500 6000 8000
30 January 2013
16
1234
P. P. 2 Type: Extended
P. P. 3 Type: Ext2
P. P. 4 Type: NTFS
P2: Extended D: E: F:
C:
P1: FAT32
M B R
P2: EXT3
C:
30 January 2013
18
Installation Mode
New or Upgrade from where
CD HTTP, FTP, NFS, Hard disk Kickstart
30 January 2013
19
Local Login
Text mode login at Virtual consoles
Multiple non-GUI logins are possible through the use of
virtual consoles There are by default 6 available virtual consoles Available through Ctrl-Alt-F[1-6]
Graphical login
If X is running, it is available as Ctrl-Alt-F7
30 January 2013
20
Running Commands
Command have the following syntax:
command [options] [arguments]
30 January 2013
22
30 January 2013
23
(forward slash) character Each shell and system process has a current directory
30 January 2013
24
contain plain files or other directories Leads to a tree structure for the filesystem Root directory: /
bin
users tmp
rocket cs2204
doug joke.txt
lab1.txt lab2.txt
30 January 2013
25
Changing Directory
pwd displays the absolute path to the current directory
cd changes directories
- To an absolute path:
$ cd /home/issa/work To relative path:$ cd project/docs To a directory one level up: $ cd .. To your directory home: $ cd To your previous working directory: $ cd -
30 January 2013
26
30 January 2013
27
30 January 2013
28
Absolute pathnames
Absolute pathnames begin with a slash (/)
Complete road map to file location Can be used anytime you wish to specify a file name
30 January 2013
29
Relative pathnames
relative pathnames do not begin with a slash (/) Specifies location relative to your current working
30 January 2013
30
pathnames
Separate directories by /
Absolute path
start at root and follow the tree e.g. /users/doug/joke.txt
/
bin users tmp rocket
Relative path
start at working directory .. refers to level above; . refers
doug
to working dir. If /users/doug/cs2204 is working dir, this refer to the same file as previous one
../joke.txt
Unix System Administration & Programming 31
30 January 2013
File names
File names may be up to 255 characters All characters are valid, except the /
It may be unwise to use certain special characters in
30 January 2013
32
destination is a directory
30 January 2013
33
destination is a directory
30 January 2013
35
rm [options] filenames
-i -r -f
30 January 2013
37
and all
30 January 2013
38
30 January 2013
39
30 January 2013
40
30 January 2013
41
slocate
output is based on a file index database, updated only once every day.
Syntax
slocate [pattern] locate [pattern]
Example
locate profile
All file or directory pathnames matching the supplied pattern will be displayed
30 January 2013 Unix System Administration & Programming 42
Examples
man man man man ls -k copy -f profile 5 passwd
30 January 2013
43
Gnome documentation
30 January 2013
44
bash Introduction
Bourne Again shell Developed for GNU project The de facto standard Linux shell Backward compatible with Bourne shell (sh) the original (standard) UNIX shell. Bourne shell (sh) original UNIX shell written by Steven Bourne at AT&T
30 January 2013
45
bash Heritage
Bourne shell (sh) original UNIX shell written by Steven Bourne at AT&T
C shell (csh) written by bill joy at UC Berkeley
Added many features such as command completion,
30 January 2013
46
bash Heritage-2
Bourne Again Shell (bash)
Implements many of the extra features found in csh, ksh
Command line completion Command line editing Command line history Sophisticated prompt control
30 January 2013
47
bash Heritage
C shell (csh) written by bill joy at UC Berkeley
Added many features such as command completion,
30 January 2013
48
bash Heritage-2
Bourne Again Shell (bash)
Implements many of the extra features found in csh, ksh
Command line completion Command line editing Command line history Sophisticated prompt control
30 January 2013
49
File Globbing
Globbing is wildcard expansion:
* matches zero or more characters
? matches any single character [a-z] matches a range of characters [^a-z] matches all except the range
Example
Examaple:
slo<TAB> slocate ls myf<TAB>
30 January 2013
51
history
bash stores a history of commands youve entered, which can be used to repeat commands Use history command to see a list of remembered commands: $ history
Use bang character !
!x execute last command begin with x !2 execute command no 2 !! Execute Last command
30 January 2013 Unix System Administration & Programming 52
History-2
Use the up and down arrow keys to scroll through
<ESC>. Or <ALT-.>
30 January 2013
53
Tilde
Tilde (~)
Refer to your home directory:
$ cat ~/.bashrc
May refer to another users home directory:
$ ls ~issa/.bashrc
30 January 2013
54
Curly braces: { }
A string is created for every pattern inside the braces
30 January 2013
55
substitute output from a command in a command line $ echo Hostname: `hostname` $ echo $(date)
30 January 2013
56
30 January 2013
57
$ (dollar sign) including $() , ` (back tick), command substitution \ (backslash),single character inhibition
30 January 2013
58
30 January 2013
59
30 January 2013
60
30 January 2013
61
Local Variable
Conventionally all upper-case Setting variable value
$ CREDIT=300 $ echo $CREDIT
in the history file on logout COLUMN sets the width of the terminal LINES sets the height of terminals PS1 sets the prompt
30 January 2013
62
Aliases
Aliases let you create shortcuts to command
$ Alias dir=ls laF Use alias to see all set aliases To see alias value: $ alias dir $ alias dir=ls laF
30 January 2013
63
Environment variables
Shell variables exist only in current shell instance
30 January 2013
64
30 January 2013
65
Environment variables
PATH colon separated list of locations where commands can be found which command (not variable) showing path of executable
$which ls Path to command can also be given explicitly $ /bin/ls /etc $ ./myls /etc
30 January 2013
66
Include:
Configure the shell by setting local variables Configure other program through environment variables
Establish aliases
Run program on startup
30 January 2013
67
in) Shells launched from a login shell typically are not login shells Login shells and non-login shells run different startup script
30 January 2013
68
/etc/profile.d
~/.bash_profile
69
30 January 2013
70
/etc/profile.d
Some application-specific startup script in this directory Script called by a for-loop in /etc/profile Script set up variables and run initialization procedures
30 January 2013
71
variables and run initialization procedures Commands that place output to the screen, such as the date command should go in .bash_profile not .bashrc
30 January 2013
72
~/.bash_logout
Execute when exiting a login shell Useful for running programs automatically at logout Example uses:
Make backup of files Delete temporary files Display date and time of logout
30 January 2013
73
vi: the visual editor, standard Linux and Unix editor vim: the vi improved standard Red Hat editor On Red hat operating systems, the vi command invokes vim Derived from earlier Unix editors
ed->ex->vi->vim
30 January 2013
74
displayed
If the file doesnt exists,
30 January 2013
75
Insert mode
Type in new text
Return to command mode with <ESC>
Ex mode
Configuring, exiting, saving Search and replace
30 January 2013
76
command mode
i
insert mode
:
last line mode
30 January 2013
77
Command mode
<esc> takes you from insert mode back to command mode cc change line, dd delete line, yy yank (copy) line
30 January 2013
79
Undoing Changes
u undo most recent change
U undo all changes to current line since the cursor landed on the line
30 January 2013
80
/text search downwards for text ?text search Upwards for text n continue search in the same direction N continue search in the opposite direction
30 January 2013
81
30 January 2013
82
A few tricks
5dd delete 5 line (a number can precede any of the tow character change, delete, yank, or put command
x delete a character
30 January 2013
83
Users
Every user of the system is assigned a unique User ID number
Users names and uid are stored in /etc/passwd
User are assigned a home directory and a program that is run when they log in (usually shell)
Users cannot read, write or execute each others files without permission
30 January 2013
84
Groups
Users are assigned to groups with unique group ID number (gid) gids are stored in /etc/group Each user is given their own private group
They can also be added to other groups to gain
additional access
the group
30 January 2013
85
An unlimited capacity to damage the system! Normal (unprivileged) users potential to do damage is limited
30 January 2013
86
30 January 2013
87
Running programs in this way limits the amount of damage any single program can do to the system
30 January 2013
88
username su - username
30 January 2013
89
30 January 2013
90
execute permissions
30 January 2013
92
30 January 2013
93
Examining Permissions
File permissions may be viewed using ls
$ ls l /bin/login
-rwxr-xr-x 1 root root 19080 Apr 1 18:26 /bin/login
File type and file access permission are symbolized by a 10-character string
30 January 2013
94
Using Categories
File permissions are established for each of three user categories. Each category also has a one-letter symbol:
u - the files owners (user)
30 January 2013
95
files from a directory x : permission to execute a program file or change into a directory and do long listing of the directory - : no permission (in place of the r, w, or x)
30 January 2013
96
Examining Directories
The first character in the long listing distinguish directories (d) from regular files (-)
$ ls l /bin
drwxr-xr-x 2 root root 4096 Apr 1 18:26 /bin/
root
30 January 2013
97
This file can be read, written, and executed by its owner, and read and executed by everyone else
30 January 2013
98
This file can be read and written by people in group teachers, but it cannot be executed.
30 January 2013
99
This file can be read by people outside group teachers, but it cannot be changed or executed
30 January 2013
100
30 January 2013
101
Example
$ chmod 640 myfile
30 January 2013 Unix System Administration & Programming 102
Default Mode
Special Permissions
Special permissions: a fourth permission set (in addition to user/group/other),Applicable in four cases:
SUID (set user ID) for an executable, Processes are
granted access to system resources based on user who owns the file. SGID (set group ID) for an executable, Same with SUID except group is affected. SGID a directory: Files created in that directory will have their group set to the directory's group.
30 January 2013 Unix System Administration & Programming 104
Special Permissions
Sticky bit for a directory, If set on a directory, then a user
may only delete files that he owns or for which he has explicit write permission granted, even when he has write access to the directory. (e.g. /tmp )
30 January 2013
105
SUID Permissions
When you login, your login shell process values are your user ID and group ID
E.g., if you run passwd (owned by root), THE user ID is
your ID, not root; then how can it update /etc/passwd file owned by root ? SUID bit enables this functionality When an executable file with set user ID (SUID) permission is executed, command run with permission of the owner of the command, not executor of the command File permission of /bin/passwd is r-sr-sr-x
30 January 2013 Unix System Administration & Programming 106
30 January 2013
107
Inode
An inode tables contains a list of all files in an ext2 or ext3 filesystem An inode (index nodes) is an entry in the table, containing information about a file (the metadata), including:
File type, permission, link count, UID, GID The files size and various time stamps
One inode is associated with each file. The system uses inodes as the definition of a file.
30 January 2013 Unix System Administration & Programming 108
Directory
The computers reference for a file is the inode number
The human way to reference a file is by file name A directory is a mapping between the human name for the file and the computers inode number
5 4 7 2
30 January 2013 Unix System Administration & Programming
apples home .
oranges
109
cp and inode
The cp command:
allocates a free inode number, placing a new entry in
the inode table Create a directory entry, referencing the file human file name to the inode number Copies data into new file
30 January 2013
110
mv and inode
If the destination of the mv command is on the same file system as the source, the mv command:
Creates a new directory entry, with the news file name Deletes the old directory entry with the old file name
30 January 2013
111
rm and inode
The rm command:
Decrement the link count, thus freeing the inode
number to be reused Places data bocks on the free list Removed the directory entry
Data is not actually removed, but will be overwritten when the data blocks are used by
another file
30 January 2013
112
Syntax
ln s filename [linkname]
30 January 2013
113
Hard links
One physical file on the filesystem Each link references the files inode File is present in the filesystem as long as at least one link remain Cannot span drives or partitions Syntax
ln filename [linkname]
30 January 2013
114
regular file directory symbolic link block special file character special file named pipe socket
30 January 2013
115
free per file system -h display sizes in easier to read units du report disk space usage Report kilobytes used per directory Includes subtotals for each subdirectory -s option only report single directory entry Also takes the -h option
30 January 2013 Unix System Administration & Programming 116
Find command
List files and pathnames matching a specific file name or criteria Syntax
find <dirs> [conditions] [action]
Recurses down in file tree in dirs Optionally executes command on each line of output
30 January 2013
117
commands
30 January 2013
118
Description
Finds files with the given filename Finds files with the size n Finds files that were accessed n minutes ago
-mtime +n
30 January 2013
119
Finding Examples
Example:
find . -print
find all files in the current directory (and all subdirectories) & display the results find . -name *.c -print find all files in the current directory (and all subdirectories) with the extension .c & display the results
30 January 2013
120
Finding Examples
find / -name myfile -print
This command tells the find command to look inside the / directory and every subdirectory to look for a file or directory with the name myfile and to display each match it finds This command tells the find command to look inside the current directory and every subdirectory to look for a file with name begin with foo that have been accessed in the last 10 minutes and to display each match it finds
Unix System Administration & Programming 121
30 January 2013
Finding Examples
Example: (for student)
find . -size +5000k find . -name "*.tmp" -exec rm {} \;
30 January 2013
122
30 January 2013
123
Formatting a floppy
One of the this command depending on which filesystem i want to use :
mkfs t ext2 /dev/fd0 mk2fs /dev/fd0 mkfs t vfat /dev/fd0 mformat a:
30 January 2013
124
Inspecting Archives
Syntax
tar tf archive_name.tar
tar
tvf archive_name.tar
30 January 2013
126
Extracting an Archive
Syntax
tar xvf archive_name.tar
directory
Change to the target directory first
current directory
30 January 2013
127
30 January 2013
128
Compression Utilities
gzip,gunzip
Standard linux compression utility Up to 75% compression for text files
bzip2,bunzip2
newer linux compression utility Generally archives better compression than gzip
30 January 2013
129
Using Compression
Sample compression commands
gzip termcap gzip -v termcap gunzip -c termcap.gz | wc l gunzip termcap
30 January 2013
130
Compressing archives
Often tar archive are compress
tar can compress/uncompress archives Compression switches- use during creation and
extraction
z for gzip compression j for bzip2 compression
30 January 2013
131
file1
tar
.tar
gzip
.tar.gz
subdirectory
30 January 2013
132
Example:
$ tar czvf /dev/fd0 mydir
30 January 2013
133
30 January 2013
134
to be redirected to/from a file Pipes allow standard I/O channels to connected to the input or output of programs
30 January 2013
135
Redirecting Output
In order to study redirecting standard output, and error , we will use the find command.
find /etc name passwd
This command will search for all files named passwd in /etc and its subdirectory
By default both the standard output and standard
30 January 2013
136
If the target file of file redirection with > already exists, the existing file will be overwritten
To append data to an existing file, use >> to redirect
instead of >
30 January 2013
137
30 January 2013
138
Redirecting Both Standard Redirection of standard output and standard error Output and Error
can be performed simultaneously
find /etc name passwd 2> error > result
Each I/O channel can be redirect ed to different files, or the same file:
find /etc name passwd > alloutput 2>&1 Or find /etc name passwd &> alloutput
30 January 2013
139
Redirecting Input
Redirect standard Input with <
Some commands only operate on standard input
tr doesnt accept filenames as arguments- it require its
input to be redirected from somewhere Tr A-Z a-z < .bash_profile This command will translate the uppercase character in bash_profile to lowercase
30 January 2013
140
30 January 2013
tee
Let you tee a pipe: redirect output to a file while still piping it to another program
set | tee set.out | less Output from set command is written to file set.out while
30 January 2013
142
tee
Let writing to output and simultaneously
date | tee file1 file2
Thu Jun 10 11:10:34 CEST 2007 cat file1 Thu Jun 10 11:10:34 CEST 2007 cat file2 Thu Jun 10 11:10:34 CEST 2007 uptime | tee -a file2 11:10:51 up 21 days, 21:21, 57 users, load average: 0.04, 0.16, 0.26 cat file2 Thu Jun 10 11:10:34 CEST 2007 11:10:51 up 21 days, 21:21, 57 users, load average: 0.04, 0.16, 0.26
30 January 2013 Unix System Administration & Programming 143
String Processing Tools head few line (default : 10 head command display first
lines) of text in a file
head /tmp/output.txt
30 January 2013
144
String Processing Tools tail command displaytail few line (default : 10 last
lines) of text in a file
tail
/etc/passwd
String Processing Tools sort Sort text to stout original file unchanged
sort
[option]
file(s)
Common option:
-r -n -f -u -t -k Reverse sort to sort descending Numeric sort Ignore case of characters in strings unique (remove duplicate lines in output) x Use x as field separator pos1 sort from field pos1
Unix System Administration & Programming 147
30 January 2013
$ cat b
fish dog animal Bird
$ sort -r b
fish dog bird animal
30 January 2013 Unix System Administration & Programming 148
$ sort c
50 this line should go first 5412 this line should go last 998 this line should go second 999 this line should go third
30 January 2013
149
$ sort -n
50 this line should go first 998 this line should go second 999 this line should go third 5412 this line should go last
30 January 2013 Unix System Administration & Programming 150
30 January 2013
151
sort | uniq:
$ cat a | sort | uniq
bird dog fish fly
30 January 2013
152
Common option:
-f
cut
Specifies field or column -d Specifies field delimiter (default is TAB) cut f3 d: /etc/passwd -c Cuts by characters cut c2-5 /usr/share/dict/words
30 January 2013 Unix System Administration & Programming 153
cut
$ cat a
the quick brown fox jumped over a quick brown fox
30 January 2013
154
cut
$ cut -c 1-3,5,7- a
theqick brown fox jume over a quick brown fox
30 January 2013
155
Tools
bash_profile to lowercase
with
diff
30 January 2013
157
Interactive spell-checker
aspell
30 January 2013
158
Regular Expressions
You can use and even administer Linux systems
without understanding regular expressions but you will be doing things the hard way Regular expressions are endemic to Unix
vi, ed, sed, and emacs
Awk, Tcl, Perl and Python grep, egrep, fgrep
30 January 2013
159
30 January 2013
utility
The shell is limited to fairly simple metacharacter
substitution (*,?, []) and doesnt really support regex Regex in vi are also fairly limited Regex in sed are not exactly the same as regex in Perl, or Awk, or grep, or egrep
page or other documentation for these utilities to determine which flavor of regex are supported
30 January 2013 Unix System Administration & Programming 161
except a newline For example . will match a z or an e or a ? or even another . w.n will match win, wan, won, wen, wmn, went, and wanton as well as w*n and w9n
30 January 2013 Unix System Administration & Programming 162
operated on by the shell If you habitually do it, you wont have to worry about when it is necessary
30 January 2013
163
abcccccccccccccccccccccccccccccccccccd Note the difference between the * in a regex and the shells usage
In a regex, a * only stands for zero or more occurrences of a single preceding character, In the shell, the * stands for any number of characters that may or may not be different
30 January 2013
164
characters on a line
characters on a line prior to the NEWLINE character Note that well (notice the space at the end) would NOT match well$
^Ken$ would only match a line that started with Ken and then had no other characters on the line
30 January 2013 Unix System Administration & Programming
165
Character Classes [ ]
The square brackets [ ] are used to define character
classes
[aA]wk will match awk or Awk
character class BUT ONLY if it is used within a range, [123] would match the characters -, 1, 2, or 3
30 January 2013 Unix System Administration & Programming 166
e, I, o, or u Used anywhere else within a character class, the ^ simply stands for a ^
30 January 2013
more 8s followed by zero or more 9s, not what we want 8\*9\* will fix this - now the asterisks are treated as regular characters
Unix System Administration & Programming
168
Reading a Regex
If you get in the habit of literally reading a regex, it
beginning of a line A better way to read it is the beginning of a line followed by a capital K followed by an e followed by an n ^corn$ would be read as the beginning of a line followed immediately by a c followed by an o followed by an r followed by an n followed immediately by a NEWLINE
30 January 2013 Unix System Administration & Programming 169
Alternation
Regex also provides an alternation character ( | )
It matches a beginning of line followed by either the characters From or Subject followed by a :
the alternation
At(ten|nine)tion then matches Attention or
Atninetion, not Atten or ninetion as would happen without the parenthesis - Atten|ninetion
30 January 2013 Unix System Administration & Programming 170
Optional Items
The ? (question mark) specifies an optional character, the single character that immediately precedes it
For example, if I am looking for the month of July, it may
be specified a July or Jul I could use (July|Jul) to search or I could use July?
30 January 2013
171
Repetition
The * (asterisk or star) has already been seen to specify zero or more occurrences of the immediately preceding character
+ (plus) means one or more
abc+d will match abcd, abccd, or abccccccd but will
not match abd while abc?d will match abd and abcd but not abccd
30 January 2013
172
Regex Summary
Character Name . [] [^] ^ $ \< \> ? * + {n,m} | () \1, \2,
30 January 2013
Meaning any one character any character listed any character not listed position at start of line position at end of line position at beginning of word position at end of word matches optional preceding character matches zero or more occurrences matches one or more occurrences matches m to n occurrences matches either expression it separates limits scope of | or encloses subexpressions for backreferencing Matches text previously matched within first, second, etc set of parenthesis
173
dot character class negated character class caret dollar backslash less-than backslash greater-than question mark asterisk or star plus sign n to m bar, or parenthesis backreference
grep
grep comes from the ed search command global
regular expression print or g\re\p This was such a useful command that it was written as a standalone utility There are two other variants, egrep and fgrep that comprise the grep family grep is the answer to the moments where you know you want a the file that contains a specific phrase but you cant remember its name
30 January 2013 Unix System Administration & Programming
174
grep Family
Syntax
grep [-hilnw] [-e expression] [filename] egrep [-hiln] [-e expression] [-f filename] [expression] [filename] fgrep [-hilnx] [-e string] [-f filename] [string] [filename] -h - Do not display filenames -i - Ignore case -l - List only filenames containing matching lines -n - Precede each matching line with its line number -w - Search for the expression as a word (grep only) -x - Match whole line only (fgrep only)
30 January 2013 Unix System Administration & Programming 175
Family Differences
grep - uses regular expressions for pattern
matching fgrep - file grep, does not use regular expressions, only matches fixed strings but can get search strings from a file egrep - exponential grep, uses a more powerful set of regular expressions
30 January 2013
176
brackets
30 January 2013
177
Meaning
Normal (nonmeta) character Escape a character Start of Line End of Line Any single character except NEWLINE Any of x, y, z, Range Any single character not listed The nth tagged expression Zero or more r's One or more r's (egrep only) Zero or one r's (egrep only) Concatenation: r1 followed by r2 r1 or r2 (egrep only) Tagged regular expression r (grep only) Regular expression r
30 January 2013
178
grep, fgrep, and egrep Ordinary characters match themselves (NEWLINES and metacharacters excluded) Ordinary strings match themselves grep and egrep Matches literal character m Start of line End of line Any single character Any of x, y, ^, $, or z Any one character other than x, y, ^, $, or z Any single character in given range Any single character not in range zero or more occurrences of regex r Matches r1 followed by r2
Unix System Administration & Programming 179
sed command
sed stream editor A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). Replace some substring with another
$ cat a
bird barks mouse runs
sed command
Replace some characters with others
Replacing b with Q, i with X
$ cat a
bird barks mouse runs
30 January 2013
181
Advanced example
Calculate number of hits per remote host in Apache log file, most active hosts first.
Line format:
159.148.123.123 - - [28/Oct/2004:18:11:36 +0300] "GET /somefolder/file.php HTTP/1.1" 200 127602 "-" "Opera/7.54 (X11; Linux i686; U) [en]"
30 January 2013
182
Advanced example
$ cat access_log | cut -d ' ' -f 1 | sort | uniq -c | sort n r
First, cut out the host part (1st field), sort it get the number of repeated lines before the line (uniq c :
prefix lines by the number of occurrences), sort it numerically, reversed so that largest number comes first
Output:
348698 123485 12313 159.148.111.222 159.148.48.54 80.123.123.4
30 January 2013
183
Processes
Operating systems are about managing resources
Files are about storage (and I/O) resources
Processes are about CPU resources
virtual address space, it receives a share (or time slice) of the CPU Processes and commands are not the same
A simple command (ls) generates a single process complex commands or scripts can invoke several simultaneous executing processes
30 January 2013
184
Process types
Interactive
initiated and controlled by terminal session can accept input from user as it runs can output results to the terminal Linux has job control to manage processes
Daemons
Typically started by init process
30 January 2013
185
and the shell must wait until they complete only one process can be running in the foreground for each user. When a command is entered, thye shell will not process further input until the process is complete and the shell prompt is redisplayed But Remember that Linux is a multi-user system foreground and background relate to user sessions. Hence multiple foreground processes can be running.
30 January 2013
186
some time to run, rather than waiting, it can be run as a background process Once started in the background control returns immediately to the shell. a user can initiate multiple simultaneous background processes with the bash shell following a command with an & places in the background eg makewhatis &
Unix System Administration & Programming 187
30 January 2013
One suspended or background process can be brought to the foreground (fg command)
30 January 2013 Unix System Administration & Programming 188
Ctrl+Z
Ctrl+C %n bg %n fg %n kill
30 January 2013
Compound Commands
List of commands seperated by semi-colons List inside () to run inside a subshell
$ ( cd /usr; du )
30 January 2013
190
Daemons
server process running in the background often started at boot time offer service to other processes examples
ftpd - file transfer process daemon cron daemon - scheduling daemon httpd - web server
30 January 2013
191
Process Attributes
the ps and top commands can be used to look at current processes
PID - process ID : each process has a unique ID PPID parent process ID : The process that start a process
30 January 2013
192
Process Attributes
Displaying process information
ps
CMD bash ps
ps aux or ps auxw options most commonly used ps -ef | grep username top (process monitoring) uptime pstree
30 January 2013 Unix System Administration & Programming 193
Process States
process can be in one of many states
R runnable (on the run queue) S sleeping T - stopped D uninterupptible sleep Z defunt (zombie) process
30 January 2013
194
called the child processes The exec system call them places the image of the new process over the copy before allowing it to be scheduled to run when a process dies (finishes or is killed) it sends a signal to its parent
30 January 2013 Unix System Administration & Programming 195
30 January 2013
196
Process Control
A process is a program in execution. Processes are identified by their process identifier, an
virtual memory space with a new program exit terminates a process A parent may wait for a child process to terminate; wait provides the process id of a terminated child so that the parent can tell which child terminated. wait3 allows the parent to collect performance statistics about the child
process, init. init forks a getty process: initializes terminal line parameters and passes the users login name to login.
login sets the numeric user identifier of the process to
that of the user executes a shell which forks subprocesses for user commands.
30 January 2013 Unix System Administration & Programming 198
Signals
Facility for handling exceptional conditions
similar to software interrupts Most desirable way to end a process is to let it end normaly The interrupt signal, SIGINT, is used to stop a command before that command completes (usually produced by ^C) If all else fail, send a kill signal
30 January 2013
199
Signals
Signal name number SIGTERM 15 Meaning Terminate the process in an orderly way. Interrupt the process. A process can ignore this signal. Interrupt the process. A process can not ignore this signal. For daemons: reread the configuration file.
SIGINT
SIGKILL
2
9
SIGHUP
30 January 2013
200
[-signal] pid(s) kill [-signal] %jobID Send the specified signal to a process Default signal is TERM killall kill -l list all available signal
30 January 2013
201
# is the priority value Once the priority value is raised, a non-privileged user cannot lower it
30 January 2013 Unix System Administration & Programming 202
Login shell
Child
Child
Child
Grandchild
Grandchild
30 January 2013
203
pstree
Kernel threads, not real processes Forked processes for network connections
30 January 2013 Unix System Administration & Programming 204
30 January 2013
205
Scheduling processes-cron
Many aspects of system administration require
checking permissions
Linux provides scheduling mechanism refereed to as cron. Cron has two parts
30 January 2013
206
Cron
the crond Daemon is started at boot time the daemon wakes up every minute to check its table of actions
if their is something to do -> run command
30 January 2013
207
Crontab
Commands can be scheduled by
minute (0 59) Hour ( 0 to 23) Day of the month (1 - 31) Month ( 1 to 12) Day of the week (0=Sunday 6 = sat, or use
mon,tues,wed)
Crontab
Example
01 * * * * command1 # hourly at 1 minute past * 1 * * * command2 # daily at 1 am 04 1 1-5 * * command3 # run at 4 minute past 1 each day
30 January 2013
209
Cron
Under Redhat Linux the cron table is used to execute a set of commands in some special directories
/etc/cron.hourly /etc/cron.daily contains logrotate, makewhatis,slocate,tmpwatch /etc/cron.weekly /etc/cron.monthly You can add you own commands to the appropriate directory, but remember they need to be batch commands as they will run automatically
30 January 2013
210
crontab commands
crontab l List crontab e Edit crontab l > cronfile crontab cronfile administrator can explicitly give permission to specific users or exclude specific user by entering their user identification in :
/etc/cron.d/cron.allow
/etc/cron.d/cron.deny
30 January 2013
211
30 January 2013
212
Shell scripts
Everything that can be called from command line, can also be called from shell script Shell Script is series of commands written in plain text file. Shell script is just like batch file is MS-DOS but have more power than the MS-DOS batch file. Interpreted line by line The same effect when entering the lines one by one in interactive shell
30 January 2013 Unix System Administration & Programming 213
30 January 2013
214
produces
30 January 2013
216
Variables
Sample hello world with variables
#!/bin/bash STR="Hello World!" echo $STR
When assigning, no $ is used When getting the contents use $ No data types string, number, character, all the same No declaring, just assign
30 January 2013 Unix System Administration & Programming 217
Results in calling:
tar cvzf 20071028.tgz /home/issa
30 January 2013 Unix System Administration & Programming 218
30 January 2013
219
Arithmetic expansion
Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:
$((expression))
30 January 2013
220
Control structures
if then for in while until case break and continue
30 January 2013
221
if then
Structure
if test-command then commands fi
Example:
if test $word1 = $word2 then echo Match fi
30 January 2013 Unix System Administration & Programming 222
test
Command test is a built-in command Syntax
test expression [ expression ]
The test command evaluate an expression Returns a condition code indicating that the expression is either
Argument
Expression contains one or more criteria
Logical AND operator to separate two criteria: -a Logical OR operator to separate two criteria: -o Negate any criterion: ! Group criteria with parentheses
Test Criteria
Relop -gt -ge -eq -ne -le -lt Description Greater than Greater than or equal to Equal to Not euqal to Less than or equal to Less than
30 January 2013
224
Example
Create a shell script to check there is at least one parameter
Something like this:
if test $# -eq 0 then echo you must supply at least one arguments exit 1 fi
30 January 2013 Unix System Administration & Programming 225
Test Criteria
Option
-d filename -f filename -r filename -s filename -u filename
-w filename
-x filename
30 January 2013
226
Example
Check weather or not the parameter is a non-zero readable file name
Continue with the previous script and add something
like
if [ -r $filename a s $filename ] then fi
30 January 2013
227
Test Criteria
String testing
Criteria String -n string -z string String1 = string2 String1 != string2 meaning True if string is not the null string True if string has a length greater than zero True if string has a length of zero True if string1 is equal to string2 True if string1 is not equal to string2
30 January 2013
228
Example
Check users confirmation
First, read user input echo -n Please confirm: [Yes | No] read user_input Then, compare it with standard answer yes if [ $user_input = Yes ] then echo Thanks for your confirmation! fi What will happen if no around $user_input and user
ifthenelse
Structure
if test-command then commands else commands fi
You can use semicolon (;) ends a command the same way a NEWLINE does.
if [ ]; then i if [ 5 = 5 ]; then echo "equal"; fi
30 January 2013 Unix System Administration & Programming 230
ifthenelif
Structure
if test-command then commands elif test-command then commands . . . else commands fi
30 January 2013 Unix System Administration & Programming 231
for
Structure
for loop-index do commands done
Automatically takes on the value of each of command
30 January 2013
232
Example
Structure
for loop-index in argument_list do commands done
Example:
for file in * do if [ -d $file ]; then echo $file fi done
30 January 2013 Unix System Administration & Programming 233
Example-2
for i in 1 2 3 4 5 do echo "Welcome $i times" done
30 January 2013
234
Example-3
for (( expr1; expr2; expr3 )) do repeat while expr2 is true done
for (( i = 0 ; i <= 5; i++ do echo "Welcome $i times" done ))
30 January 2013
235
Example-4
You can use for together with file name expansion to do some action for several files
#!/bin/bash for x in *txt; do cat $x done;
30 January 2013
236
while
Structure
while test_command do commands done
Example:
while [ $number lt 10 ] do number=`expr $number + 1` done
30 January 2013 Unix System Administration & Programming 237
until
Structure
until test_command do commands done
Example:
secretname=jenny name=noname until [ $name = $secretname ] do echo Your guess: \c read name done
30 January 2013 Unix System Administration & Programming 238
statement Skip the test statements for the current iteration Continues execution of the loop
30 January 2013 Unix System Administration & Programming
239
Example
for index in 1 2 3 4 5 6 7 8 9 10 do if [ $index le 3 ]; then echo continue continue fi echo $index if [ $index ge 8 ]; then echo break break fi done
30 January 2013
240
case
Structure
case test_string in pattern-1 ) commands_1 ;; pattern-2 ) commands_2 ;; esac
case
Special characters used in patterns
Pattern * ? [] | Matches Matches any string of characters. Matches any single character. Defines a character class. A hyphen specifies a range of characters Separates alternative choices that satisfy a particular branch of the case structure
30 January 2013
242
Example
#!/bin/bash echo \n Command MENU\n echo a. Current data and time echo b. Users currently logged in echo c. Name of the working directory\n echo Enter a,b, or c: \c read answer echo
30 January 2013
243
case $answer in Example-continue a) date ;; b) who ;; c) pwd ;; *) echo There is no selection: $answer ;; esac
30 January 2013
244
Read
read variable1 [variable2 ] Read one line of standard input Assign each word to the corresponding variable, with the leftover words assigned to last variables If only one variable is specified, the entire line will be assigned to that variable.
30 January 2013 Unix System Administration & Programming 245
Built-in: exec
Execute a command:
Syntax: exec command argument Run a command without creating a new process
Run a command in the environment of the original process Exec does not return control to the original program Exec can be the used only with the last command that you want to run in a script Example, run the following command in your current shell, what will happen? $exec who
30 January 2013
246
Built-in: exec
Redirect standard output, input or error of a shell script from within the script
Example: $ more redirect.sh exec > /dev/tty echo "this is a test of redirection"
Just capture the signal, not doing anything with it trap signal_number
1 2 9 15 24
30 January 2013
248
Example
$ cat inter #!/bin/bash trap 'echo PROGRAM INTERRUPTED' 2 while true do echo "programming running." sleep 1 done
30 January 2013
249
eval
exec exit export, unset test
job control change the loop working directory display/read scan and evaluate the command execute a program exit from current shell export/ remove a val or fun compare arguments
30 January 2013
250
set
shift times
trap
type
sends a signal to a process or job sets flag or argument promotes each command line argument displays total times for the current shell traps a signal show whether linux command, build-in, file creation mask waits for a process to terminate. print the value of one or more resource limits
Unix System Administration & Programming 251
functions
A shell function is similar to a shell script
It stores a series of commands for execution at a later time. The shell stores functions in the memory Shell executes a shell function in the same shell that called it.
Where to define
In .profile In your script Or in command line
Remove a function
Use unset built-in
30 January 2013
252
functions
Syntax
function_name() { commands }
30 January 2013
253
Example
$ whoson() >{ > date > echo "users currently logged on" > who } $ whoson Tue Feb 1 23:28:44 EST 2005 users currently logged on issa :0 Jan 31 08:46 issa pts/1 Jan 31 08:54 (:0.0) issa pts/2 Jan 31 09:02 (:0.0)
30 January 2013 Unix System Administration & Programming 254
$ more .profile setenv() { if [ $# -eq 2 ] then eval $1=$2 export $1 else echo "usage: setenv NAME VALUE" 1>&2 fi } $ . .profile $ setenv T_LIBRARY /usr/local/t $ echo $T_LIBRARY /usr/local/t
30 January 2013 Unix System Administration & Programming 255
Example-2
Boot Terminology
Loader:
Program that moves bits from disk (usually)
to memory and then transfers CPU control to the newly loaded bits (executable).
Bootloader / Bootstrap:
Program that loads the first program (the kernel).
Boot Manager:
Program that lets you choose the first program to load.
30 January 2013
256
30 January 2013
257
Bios Initialization
Peripherals detected Boot device selected First boot of boot device read and executed
30 January 2013
258
30 January 2013
259
kernel Initialization
Kernel boot time functions
Device detection Device driver initialization Mounts root filesystem read only Load initial process (init)
30 January 2013
260
init Initialization
init read its config: /etc/inittab
Initial runlevel System initialization script Run level specific script directories Trap certain key sequence Define UPS power fail / restore scripts Spawn gettys on virtual consoles
30 January 2013
261
Startup Sequence
Power-on
LILO/GRUB
Boot loader
Load Kernel
Linux
hardware
rc.sysinit
runlevel 0-6
rc.local
Ready
Initialisation Scripts
30 January 2013 Unix System Administration & Programming 262
Meaning
Runs when system boots Init waits for complete
Powerokwait
Respawn Sysinit Wait
30 January 2013
check root file system quota & turns quotas for groups
and users mount non-root file systems and checks them for repairs turns on swapping (virtual memory subsystem) checks and loads modules (drivers) Set the system clock
Unix System Administration & Programming 264
30 January 2013
stop and start processes. The actual commands are held in /etc/rc.d/init.d directory
30 January 2013 Unix System Administration & Programming 265
links to the actual commands Each command is prefixed with S or K and a number 0099 S prefix means that a process should be started e.g. S10network K prefix means that a process should be stopped (killed) K70syslog The numbers determine the order in which the commands are run from lowest first to highest last
30 January 2013
266
Runlevel 1 /etc/rc.d/rc1.d
single user mode used for maintenance by system administrators when
they need sole control of machine, e.g. reconfiguring hardware installing software
Runlevel 2 /etc/rc.d/rc2.d
Multi-user + networking (minus NFS)
30 January 2013 Unix System Administration & Programming 267
Runlevel 4 /etc/rc.d/rc4.d
not defined ( available for customization)
Runlevel 5 /etc/rc.d/rc5.d
Same as 3 under Redhat this but includes starting X
windows
Runlevel 6 /etc/rc.d/rc6.d
reboot similar to 0 but allow allows option to shutdown (halt)
30 January 2013
or reboot
268
/etc/rc.d/rc.local
Run after the runlevel specific script Common place for custom modification
30 January 2013
269
Shutdown
shutdown allows...
users to be warned the systems is going down the contents of disk caches to be written disk file systems to be marked as having been closed properly
30 January 2013
270
System Reboot
Rebooting rarely fixes problems in Linux
If you feel a reboot is necessary try bringing the system
down to runlevel 1 and then back up to runlevel 3 or 5. this is much faster thn reboot
30 January 2013
271
Controlling services
Utilities to control default service startup
redhat-config services: graphical utility that requires
an X interface ntsysv: usable in virtual consols chkconfig : fast, versatile command line utility that work well and is usable with script
service chkconfig: immediately start and stop xinetd managed services and others
30 January 2013 Unix System Administration & Programming 272
Kernel Modules
Modular kernel components
components that need not be resident in the kernel for
Modules configurable at load time /lib/modules Controlling modules : lsmod, insmod, rmmod Controlling modules intelligently : modprobe, depmod
30 January 2013
273
30 January 2013
274
Provide information on system hardware , networking setting and activity, memory usage The /proc/sys subdirectory allow administrator to modify certain parameters of running kernel, but the modifications are temporary and not saved at system shutdown
30 January 2013 Unix System Administration & Programming 275
30 January 2013
276
30 January 2013
277
System Monitoring
top, gnome-system-monitor display snapshot of processes vmstat report virtual memory stats iostat list information on resource usage, including I/O statistics free -summary of system memory usage
30 January 2013
278
File System
File System is developed for
create/store/load/delete/seek file on media Media example Magnetic Media Tape Floppy disk Hard disk Optical Media Cdrom Dvd
30 January 2013
279
30 January 2013
280
ext2 ( is first introduced in kernel 2.0.x ) reiserfs ( is first introduced in kernel 2.2.x ) ext3 ( is first introduced in kernel 2.4.x )
30 January 2013
281
Windows
NTFS, FAT
Linux
ext2,ext3 Each partitions is mounted under /
Reference Root of each Each partition will partition point be own root Ex. C:, D:, F:
30 January 2013
282
/etc
/boot /dev /usr
/home
/proc /var /lib /tmp
- first of mount point in linux - keep linux default configuration - keep important linux booting files - keep all device files - keep all user binary and X library - keep user home directory - is pseudo file system for tracking running process and state of linux system - keeping mail, log file and printer spooling - contain shared library that is required by system program - contain system temporary file
30 January 2013
283
hda1
/var
/home
hda4
type ex. ext2, ext3, reiserfs, device ex. /dev/hda1, /dev/hdb1, target-dir ex. /, /var, /home, /mnt/cdrom,
30 January 2013
284
hda1,ext3
/var
/home
hda4,ext3
30 January 2013
286
Example
umount /var
30 January 2013
287
30 January 2013
288
Assume we would like to add windows partition (hdb1, FAT32) that linux have to mount at boot time at /mnt/windows
file system = /dev/hdb1
30 January 2013
289
From the previous information, we have to add following line in /etc/fstab files
/dev/hba1 /mnt/windows vfat defaults 0 0
30 January 2013
290
Managing partition
Create Partitions using :
fdisk /dev/hda fdisk -l /dev/hda or cat /proc/partitions
display a report
30 January 2013
291
30 January 2013
292
30 January 2013
293
Packages
In more widespread linux distributions, programs are distributed in binary RPM, DEB or modified TGZ formats RPM (RedHat Package Management) packages are used on RedHat, Mandrake, Suse, Conectiva DEB are used on the open source distribution Debian and its forks Modified TGZ are used on SlackWare
30 January 2013
294
source package
distribution size package size package dependencies installation reproducability installation run-time stability installation system alignment installation time
binary package
the vendor sources plus instructions for automated build and installation. providing binary packages containing the final installation files only.
approaches (including RPM), although often not equally well. Both approaches have each their pros and cons, nevertheless all software distributions focus on one of them.
30 January 2013
295
Dependencies
They keep systems in a consistent state and guarantee the applications to run in the expected way
rpm or dpkg commands have limited dependencies management features
They can report which library a package relies on, but the library can itself rely on other packages
30 January 2013
296
Dependencies - Example
Installing a package mod_test1 : # rpm -Uvh mod_test1-xxx.rpm error: failed dependencies: package-a1 is needed by mod_test1 # rpm -Uvh package-a1-xxxx.rpm error: failed dependencies: package-b2 is needed by package-a1 # rpm -Uvh package-b2-xxxx.rpm And so on
30 January 2013
297
The old-fashioned way of distributing software in Linux/Unix Compatible with all distros Main package manager in Slackware, Gentoo Introduced by RedHat and has been adopted by many other distributions (Fedora, Mandrake, SuSe) . The most popular Linux package format Introduced by Debian distribution
Unix System Administration & Programming 298
30 January 2013
compiled before installed Usually come in .tar.gz or .tar.bz2 archives Typical compilation/installation steps
Unpack the archive:
tar xzvf <package_name>.tar.gz tar xvjf <package_name>.tar.bz2 cd <extracted_dir_name> ./configure make make install
299
Build the source code using the GNU Make utility as follows:
Backup Tools
tar
tar jxvf mytarball.tar.bz2 - Extract files from
30 January 2013
mytarball.tar.bz2 tar zxvf mytarball.tar.gz - Extract files from mytarball.tar.gz -z : Use gzip compression -j : Use bzip2 compression -x : Extract -v : Verbose -f : Use file gzip compression is used for tarballs with the extensions .tar.gz, .tgz, Bzip2 compression which is slightly better but requires more CPU is used in tarballs with the extensions .tar.bz2 and .
Unix System Administration & Programming
300
rpm e <package_name>
rpm U <package_name>.rpm
Package Management
Using RPM
To install or upgrade a package: rpm -Uvh package-1.0.i386.rpm
To remove a package: rpm -e package-1.0
installed:
30 January 2013
302
Example: rpm -q
rpm -q -i telnet
30 January 2013
303
package repositories APT utilities set (apt-get, apt-cache etc.) is provided for managing packages on these repositories Can manage packages in binaries and source format Provides packages inter-dependency auto-resolve Contacts repositories listed in /etc/apt/sources.list file
30 January 2013
Brazilian distribution Conectiva ported the apt system on its linux distribution, which uses rpm packages Apt is now available for all distributions using rpm, also thanks to the SourceForge project apt4rpm (http://apt4rpm.sourceforge.net) Some features of Debian apt are not yet available, like package priority or requests to change configuration files, because of some differences in deb and rpm format
Unix System Administration & Programming 305
30 January 2013
ported to RPM based systems (Conectiva Linux, RedHat, Fedora, SUSE, Scientific Linux ...) Installs the whole software with one command: apt-get install lcg-ui Automatically resolves dependencies for specified packages and downloads required rpms Central configuration file with repositories' URLs (/etc/apt/sources.list or /etc/apt/sources.list.d) Automated or half-automated software upgrades Note! APT requires that there are no broken dependencies in the OS
Unix System Administration & Programming 306
30 January 2013
User administrator
chmod, chown , chgrp useradd username userdel username Also can use adduser groupadd groupname gpasswd -a myuser mygroup groups username chage
chage -M 365 student
30 January 2013
307
Host Configuration
To connect a host to the network, the administrator
30 January 2013
309
Host Configuration
Every operating system stores network configuration
information in files. The /etc/sysconfig directory contains scripts and data files required to configure many system services, including networking in redhat Some of these files specify information about the hosts address and host name Other files specify which network services the host will allow, and which other hosts on the network provide services the host may require.
30 January 2013
310
Configuration Utility
netconfig text based network configuration utility
Only write config files. Does not activate device or changes Used by kudzu when new network card found at boot time
configuration utility
30 January 2013
311
Configuration NIC
Setting IP address : Static or Dynamic Static Configuration: Ifconfig
The ifconfig command is used to bind the IP address, host
name, net mask, broadcast address, and other network configuration parameters to a particular network interface. The ifconfig command is run at boot time by the startup scripts called by the init process. You can use the ifconfig command to examine and/or modify interface parameters while the system is up and running. When issued with the a flag, ifconfig prints the configuration information for all interfaces.
30 January 2013 Unix System Administration & Programming 312
Configuration NIC
Example Ifconfig eth0 inet 192.168.17.23 broadcast 192.168.17.255 Netmask 255.255.255.0 To instructs the kernel to activate the eth0 Ifconfig eth0 up
30 January 2013
313
Configuration NIC
The ifcfg-ifname File
The /etc/sysconfig/network-scripts/ifcfg-ifname files supply
the configuration information for each network interface. These script files contain a series of keywords and values parsed at boot time.
DEVICE="eth0" # The interface name BOOTPROTO="none" # Set to DHCP to use DHCP IPADDR="172.16.205.99" # Hosts static IP address NETWORK=172.16.205.96 # The network number BROADCAST=172.16.205.127 # The broadcast address NETMASK="255.255.255.240" # The netmask ONBOOT="yes" # yes to configure at boot
30 January 2013 Unix System Administration & Programming 314
Host Configuration
The ifup Script
The /etc/sysconfig/network-scripts/ifup script file is invoked at boot time by
init. The script reads the interface files and parses the entries. The information from the entries is used to configure each network interface with the proper values.
time by init. The script reads the interface files and parses the entries. The information from the entries is used to shut down each network interface.
library of functions used by the ifup and ifdown scripts. The functions include code for setting the net mask, host name, broadcast addresses, and gateways. The functions perform operations required to configure an interface up or down.
30 January 2013 Unix System Administration & Programming 315
DHCP
Using DHCP to Assign IP Addresses
A tool that simplifies IP configuration is the Dynamic Host
Configuration Protocol (DHCP). DHCP automatically assigns an IP address to a host at boot time. Hosts that use the DHCP protocol to obtain their network configuration information are typically referred to as DHCP clients. Hosts that supply DHCP configuration information to other hosts are referred to as DHCP servers.
client is to do so when the operating system installation process is invoked. In redhat the daemon is now dhclient which started automatically by /sbin/ifup script.
30 January 2013
316
30 January 2013
317
Default Route
Global default defined in:
/etc/sysconfig/network-scripts/ifcfg-xxx
30 January 2013
318
Static Routes
Static routes defined by interface
Display with:
30 January 2013
319
netstat command
netstat
The netstat program is available under most operating
systems. In general, netstat can display packet counts, and configuration information for your system. Some of the typical uses of netstat include display of input/output packet counts per interface, display of TCP/UDP sockets in use on a host, and display of the routing tables for a host.
30 January 2013
320
Name Resolution
hostname display or set the systems name
Is initially set by rc.sysinit from $hostname variable in /etc/sysconfig/network
30 January 2013
321
Name Resolution
/etc/hosts File
One of the most frequently used network administration files is the
/etc/hosts file Even Windows systems have a version of the hosts file, called lmhosts. The file is a registry of IP addresses and associated host names known to a system. At a minimum, it must contain the loop-back address (127.0.0.1) and the IP address for the host. The hosts file is one of the resources consulted by applications in order to resolve a host name to an IP address when communications are requested. The format of host file entries follows.
IP address 192.168.44.55 Fully.Qualified.Name issa.svuonline.org host_alias issa
322
30 January 2013
30 January 2013
323
DNS Utility
Many useful utilities are included in the bind-utils
nslookup
30 January 2013
324
/etc/services file
The /etc/services file contains a list of network
ports and services that correspond to those ports. For example, port 25 is defined as the SMTP port, whereas port 80 is reserved as the hypertext transport protocol daemon (httpd) port. To add a new service to a host, the administrator must add a port number and service name pair to the /etc/services file.
30 January 2013 Unix System Administration & Programming 325
Network Diagnostics
ping
Network packet loss and latency measurement tool
netstat
multipurpose network information tools
traceroute
The traceroute utility does exactly what its name implies: it
traces the route from point A to point B. This utility can be very useful when trying to determine why two hosts cannot communicate. For example, to trace the route from a specific local host to a distant host, the administrator could invoke the following command.
30 January 2013 Unix System Administration & Programming 326
File Sharing
To share files across the network, Linux uses two primary mechanism:
Network File System (NFS): for sharing with other Linux
and UNIX systems Samba: for sharing files with Windows-based computer
30 January 2013
327
NFS
Linux can be both an NFS client and an NFS server The NFS daemon is mountd /etc/exports control which file systems can be exported
/mnt/export issa.svuonline.org(ro) You have to run exportfs following changes to /etc/exports
or restart the NFS daemon manually client make the mount request with mount
mount issa:/mnt/export /mnt/local The : is the indicator to the mount command that this is NFS mount
Unix System Administration & Programming 328
30 January 2013
Samba
Provide file and print services to SMB/CIFS clients (Server Message Block/Common Internet File System). It is used to integrate windows-machines with Linux servers Can customize configuration per machine basis using
smb.conf file Samba include web-based interface for configuration called swat (Samba Web Administration Tools)
30 January 2013
329
30 January 2013
330
Mail Systems
Mail User Agent: many choices from console or graphic interface Mail Transport Agent: responsible for receiving and delivering message using the Simple Mail Transport Protocol (SMTP)
Accept messages from the user agent
Understand destination address Deliver mail originating on the local machine to the proper
mailboxes if local, or a delivery agent if remote Receive incoming mail from other delivery agents and deliver to local user
30 January 2013 Unix System Administration & Programming 331
Mail Systems
The default mail transport agents is Sendmail, can be difficult to configure, several newer ( qmail, postfix, and exim) sendmail behavior is governed by sendmail.cf file
30 January 2013
332