Академический Документы
Профессиональный Документы
Культура Документы
http://very.thoughtful-solutions.info/
Solaris
Fundamentals
Training
Abstract
Operations Group Solaris Fundamentals Training
Share Alike. If you alter, transform, or build upon this work, you
may distribute the resulting work only under a licence identical to
this one.
For any reuse or distribution, you must make clear to others the licence
terms of this work.
Any of these conditions can be waived if you get permission from the
copyright holder.
Your fair use and other rights are in no way affected by the above.
This is a human-readable summary of the Legal Code (the full licence).
Disclaimer
Linking Files.........................................................................................................68
Linking Files : ln..................................................................................................69
Hard links : ln.......................................................................................................70
Symbolic links : ln................................................................................................71
Why create links?.................................................................................................72
Pathname abbreviations .......................................................................................73
Shell Meta-characters...........................................................................................74
* - Asterisk...........................................................................................................75
?- Question Mark..................................................................................................76
[ ] Square Brackets............................................................................................77
` ` - Backticks.......................................................................................................78
Quoting in Shells [ ]........................................................................................79
Escaping in shells [ \ ]..........................................................................................80
Getting Help.............................................................................................................81
Getting help : man................................................................................................82
man : Output.........................................................................................................85
man : example.......................................................................................................88
man page sections.................................................................................................92
manual entries in other sections...........................................................................93
Other useful man options......................................................................................94
Google..................................................................................................................95
Google: Example..................................................................................................96
SunSolve...............................................................................................................97
File Types and Listing .............................................................................................98
Varieties of Files ..................................................................................................99
What sort of file [file].........................................................................................100
Strings in a file [strings].....................................................................................101
Contents of a file [cat]........................................................................................102
Listing contents of files [more]..........................................................................103
Listing contents of files [less].............................................................................104
Top few lines [head]...........................................................................................105
Bottom few lines [tail]........................................................................................106
Fields in a file [cut].............................................................................................107
Counting things [wc]..........................................................................................108
Finding the differences [diff]..............................................................................109
Differences of 3 files [diff3]...............................................................................110
Sorting files and output [sort].............................................................................111
Handling duplicate lines [uniq]..........................................................................112
Redirection.............................................................................................................113
Why ?.................................................................................................................114
Standard Files.....................................................................................................115
Redirection : < > 2> ...........................................................................................116
Redirection : >>..................................................................................................117
Redirection : Merging ........................................................................................118
Redirection: Multiple redirections......................................................................119
Redirection : Examples.......................................................................................120
More redirection: File creation...........................................................................121
Pipelines : |.........................................................................................................122
Pipelines : examples...........................................................................................123
Named Pipes.......................................................................................................124
File Security............................................................................................................125
Security Overview..............................................................................................126
Permissions.........................................................................................................127
Finding the permissions [ls l]...........................................................................128
Types of users.....................................................................................................129
Access Permissions............................................................................................130
How is access decided ?.....................................................................................131
Controlling access [chmod]................................................................................132
Controlling access [chmod]: The modes............................................................133
Octal Modes.......................................................................................................134
Octal Modes : example.......................................................................................135
User ID and Group ID........................................................................................136
Real & Effective User/Group ID........................................................................137
Who am I [id].....................................................................................................138
Ownership..........................................................................................................139
Changing Ownership: chown and chgrp............................................................140
setuid..................................................................................................................141
setgid..................................................................................................................142
setuid and setgid with directories.......................................................................143
Sticky bit.............................................................................................................144
Default Permissions [umask]..............................................................................145
Searching and Translating......................................................................................147
Why?..................................................................................................................148
find : Finding files..............................................................................................149
find : Conditions.................................................................................................150
find : Examples...................................................................................................151
Regular Expressions...........................................................................................152
Regular Expressions : Meta-characters..............................................................153
Regular Expressions: Character Classes.............................................................154
Regular Expressions : Two warnings.................................................................155
Regular Expressions : Examples........................................................................156
Translate [tr].......................................................................................................157
Finding things [grep]..........................................................................................158
Stream Editor [sed].............................................................................................159
sed : Substitution Examples................................................................................160
sed.......................................................................................................................164
Who is using the system ? [who]........................................................................165
Quicker who [w].................................................................................................166
Find a spelling [look]..........................................................................................167
Processes and Control.............................................................................................168
Process Overview...............................................................................................169
Generating Processes..........................................................................................170
Understanding Processes....................................................................................172
Displaying the Processes [ps].............................................................................173
Displaying the Processes [prstat]........................................................................174
prstat : column headings.....................................................................................175
Managing Processes...........................................................................................177
Background a command [ & ]............................................................................178
nohup..................................................................................................................179
Listing the jobs [jobs].........................................................................................180
Foreground a command [fg]...............................................................................181
Killing processes [kill].......................................................................................182
Job Management Commands.............................................................................183
/proc....................................................................................................................184
P.T. Barnum
Introduction
Introduction
What is Unix?
Distributed Computing with Unix
Why Unix?
Unix Philosophy
Unix Major Features
Unix Lore
A Potted History
Unix Flavours
The Evolution of Unix
What is Unix?
What is Unix?
Multi-user, multi-process, multi-access
operating system
Unix
Allows users to run programs, manage their
own files and use devices
terminator
repeater
ethernet segment
router
transceiver
Aims
Aims
Design Goal
... to create a computing environment where they themselves
(the staff of CSRG) could comfor tably and effectively pursue
their ow n work - programming research.
- entails elegance
Why Unix?
Why Unix?
Highly portable, extensible & configurable
- written largely in C
- modular kernel and command set
- configuration soft coded
An open operating system
- vendor independent
Relatively standardised
- IEEE POSIX, X-Open XPG
- Open Software Foundation
Provides a productive development environment
- software tools
- file processing tools
Over 90% of the Unix operating system is written in the C high-level programming
language. This makes the system relatively easy to port to new hardware.
Unix is based on a few simple concepts and is structured in a highly modular
fashion. It has been able to evolve as new technologies become available, but has
remained relatively standardised. Such groups as the IEEE POSIX committee, the
X/Open Forum and the Open Software Foundation (and previously Unix
International) have strived to keep Unix developments open and standardised.
Unix is not tied to any particular vendor, being perhaps the first true open operating
system. Implementations of the system exist on some of the smallest machines in
the world (such as PCs) and also on the biggest machines (such as supercomputers).
Unix Philosophy
Unix Philosophy
Write programs that do one thing and do it well
Major Features
Major Features
Simple, powerful, user interface
Complex commands are made
from simple ones
Hierarchical file system
Consistent file format, the byte stream
Simple, consistent, peripheral interface
Hides machine architecture from user
Unix provides hundreds of commands each designed to do one thing well. Through
a Unix shell (command line interpreter) collections of such commands are
combined to perform complex tasks.
In Unix, files on disk, devices and the input and output of running programs are
considered files. All physical devices have filenames, and behave as ordinary files.
The fundamental component of information in Unix is the byte stream. It allows
files, devices and even programs to be used interchangeably as the source or
destination of data; and thus allows the underlying machine architecture to be
hidden from the user.
Unix Lore
Unix Lore
Intensely loyal defenders acclaim
Unix is an old operating system (though it has changed considerably from its earlier
implementations). It started life as a support environment for a computer game,
and graduated into a teaching and research platform for Universities. As a
consequence, it has acquirednment, to others (especially novice users) the sheer size
and complexity of the command set make it difficult to use.
Potted History
Potted History
1965
1965Bell,GEC
Bell,GECand
andMIT
MITstart
startMULTICS
MULTICS
1969
1969Space
SpaceTravel
Travelconceived
conceived
Unix
Unixbuilt
builton
onPDP-7
PDP-7
1973
1973Unix
Unixcoded
codedininCC
1981
1981BSD
BSD4.1
4.1
1982
1982Unix
UnixSystem
SystemIIIIII
AT&T
AT&Tcombined
combinedseveral
severalvariants
variants
1983
1983UNIX
UNIXSystem
SystemVV
System
SystemIV
IVwas
wasan
aninternal
internalversion
version
Unix started life as the support environment for a Space Traveller game developed
at Bell Laboratories. It was originally coded in PDP assembler, some parts were
developed in B (an interpreted language influenced by BCPL) and later the entire
system was recoded in C. C was developed by Dennis Ritchie for Unix to
overcome the performance limitations of B. Unix was named by Brian Kernighan
as a pun on an earlier system called Multics.
Once Unix had become a stable product within Bell Laboratories, consideration was
given to selling it. However, due to a Consent Decree Bell had signed with the US
Federal government in 1956, it was forbidden to market computer products.
Instead, Bell laboratories (specifically, the Unix Systems Group of AT&T) gave the
system to Universities for educational purposes. Research at the University of
California at Berkeley lead to the development of a variant of the Unix system.
Most commercial flavours of Unix are based upon AT&T system V Unix, or BSD
(Berkeley Software Distribution) 4.x Unix.
Potted History
1983
1983BSD
BSD4.2
4.2
1984
1984SunOS
SunOSderived
derivedfrom
fromBSD
BSD
1985
1985BSD
BSD4.3
4.3
1989
1989SunOS
SunOS44(Solaris
(SolarisI)I)
1991
1991Convergence
Convergenceon
onSVR4
SVR4
1992
1992Solaris
SolarisIIII(SVR4)
(SVR4)
SunOS is Sun Microsystems flavour of Unix. It is based largely upon BSD Unix,
with NFS and NIS network extensions to allow files to be shared and managed
around a network.
In the interest of standardisation, Sun Microsystems, together with a number of
other major workstation manufacturers, have converged on SVR4 Unix. System V
Release 4 incorporates many of the features of earlier System V versions of Unix,
in addition to many other facilities. Suns SVR4 product is Solaris II, and all
preceding SunOS products are now referred to as Solaris I.
Unix Flavours
Unix Flavours
Workstation Unixes
Sun Microsystems
Sun Microsystems
Silicon Graphics
IBM
Hewlett-Packard
SunOS-4 (Solaris I)
SunOS-5 (Solaris II)
AIX-3
HP- UX - 8
Unix
Linux
BSD + SVR3
SVR4
IRIX 4 SVR4
SVR3 + ?
SVR3 + BSD
SVR4
SVR3
SVR4
SVR4
Ultrix
Meikos
BSD + DECnet
SVR3
Key Concepts
Key Concepts
Great is the art of beginning,
but greater is the art of ending
Lazurus Long
processing
output
data
In Unix, everything is a process or a file. No other entities exist, not even disks,
printers, terminals or networks---in Unix all of these things appear as files. The
idea of using file names to represent devices saves introducing another concept.
When a devices file is read or written, Unix ensures that the interactions are
propagated to the particular device which the file represents.
Files are passive entities, unable in themselves to do anything. Processes are active
entities, in some sense they have life. Consider a human as a process, and a
suitcase as data. The suitcase cannot move itself, because it does not have life. A
human must be applied to the suitcase in order for it to move. Likewise a process is
applied to a file in order for it to be processed.
Unix is unusual compared with many operating systems in that process creation is
relatively inexpensive. As a consequence, each command is executed as a single
process. This differs from other systems which often run commands as procedure
or function calls within a central command process.
In Unix, each invocation of a command gives rise to a new process. The process is
created from the commands program file, executes and then dies. It is not unusual
for one command to be executed by one or more users simultaneously, giving rise
to many independent processes (instances) each performing the same task.
Note that the instructions as to what a process should do are stored in a
corresponding program file on disk. When a command is issued, the text of its
program file is used to make the process. The CPU interprets each instruction
within the process to carry out the work.
Organisation of Files
Organisation of Files
Files are organised as an inverted tree
The Unix File System consists
of a single root directory which
contains files.
Files may be data, programs
devices or directories.
This logical file system may be
composed of many physical
devices and networks.
Both process and file entities in Unix are organised as trees. The tree used to hold
files is called the Unix File System (UFS). The tree used to hold processes is
simply called the process tree.
Unix File System
The Unix File System is organised as an inverted tree; the root is at the top, and
branches and leaves in the form of directories and files grow down. A directory is a
special file which can hold other files. Since these files may themselves be
directories, a tree structure is formed.
Unix systems contain only one logical file system. The file system may span
multiple partitions and disks, cross networks and exist in multiple physical forms.
However, the illusion maintained by the operating system, is that the file system is
one, coherent, tree. As a user moves around the file system, Unix ensures that the
physical joins between disks or networks remain hidden.
Since there is only one file system, all users, programs and devices exist in the same
name space. By convention, programs and devices exist in their own subdirectories, and users exist in their own sub-directories.
Organisation of Processes
Organisation of Processes
Processes are organised into a process tree
All processes have a parent
process (save the first) and
may have child processes.
Each command is executed
as a new process, and is the
child of the process which
invoked it.
Unix does not discriminate between the execution of system related programs and
user programs. Both give rise to processes.
The first process in a Unix system is called init and it runs as part of the procedure
of making the machine ready for users. init creates child processes which setup the
machine and ultimately prompt the user to login. Once a user has logged in, a new
child process is created to enable the user to enter commands. This process is
called a shell.
The shell prompts the user to enter a command. For each command that the user
enters, the shell spawns a new processes. The shell is therefore the parent of these
processes. The shell is itself the child of init, since this gave rise to its creation
when the user logged in. Many Unix commands also give rise to child processes,
which may in turn give rise to new generations of processes. Thus a tree of
processes is seen to have been spawned, starting from the great grand parent of all
processes, init.
Login
Login
Multi-user OSs require users to login
- validate username
- associate with account
interactive shells
custom menus
windowing environments
applications
In order to use a Unix machine users must login. In this process the system
determines who the user is (the username), verifies this information (by requesting
a password), and then associates with the user their file and process resources.
Specifically, the user is associated with a sub-directory of the filesystem (their
home directory) and an initial process (usually an interactive shell).
Humans tend to use names to distinguish similar objects, machines tend to prefer
numbers. During the login process the system associates a UID (user identity
number corresponding to the username) and GID (group identity number
corresponding to the users default group) with the user. This is subsequently used
to label all files and processes created by the user.
sh
home
fred
init
cat file
Once a user has successfully logged-in to the system, the user is placed in their
home directory and is given an initial shell from which they may invoke commands.
The home directory
The home directory is simply a sub-directory within the single, logical tree structure
of the Unix file system. Since this structure may be composed of both remote and
local disks, it is likely that the actual physical location of the home directory resides
over the network on a carefully managed file server machine.
Each user usually has their own home directory and uses this to store personal files,
such as programs, letters and data. Home directories may themselves be broken
down into sub-directories, to help organise the users files.
The home directory is said to be the top of the users file tree. Note, however, the
user may still go to any other part of the tree provided they have suitable access
rights.
The Login Shell
The login shell is a process executed on behalf of the user when they login. The
command giving rise to the process may be any Unix command. Often it is an
interactive shell, allowing users to enter their own command. Sometimes it is a
specific application, locking the user within the application and hiding Unix itself.
The login shell is said to be the top of the users process tree. The user may logout
by terminating this process.
process
fred
george
file
file
Users are not first class entities within Unix, only files and processes can claim this
status. Users are simply attributes of files and processes. In Unix, every file and
every processes must be owned by someone and exist in a group.
When users first login their initial process (the shell) and file (their home directory)
belongs to them. Every subsequent file or process created by a user is stamped with
the users identity (UID) and the users current group identity (GID). The UID is
usually unique and has a one-to-one mapping with the users username; the GID is
shared
by users
together.
The GID
provides
In
Unixworking
everything
carries
a UID
anda means
GID by which users can
gain joint access to shared files and commands.
Unix Structure
Unix Structure
more
cat
ksh
ls
kernel
vi
sh
sort
grep
The structure of the Unix system is different from most other large operating
systems. At its centre is a core of functionality known as the kernel. This provides
the system resources, such as the management of process and file trees.
Around the kernel are layered the programs which make up a users perspective of
the operating system. Hundreds of individual commands use the kernel in order to
achieve their tasks. The commands physically reside in the filesystem as program
files. However, once executed they are loaded into the systems memory and
executed as processes.
In the above picture, some of the standard commands are shown around the kernel.
The commands marked sh and ksh are interactive user shells. They are usually
automatically executed when a user logs into the machine and invoke commands on
the users behalf. Its interesting to note, that the shells in themselves are no
different from other programs. Although they form the layer between the user and
the kernel, they reside in the filesystem and are executed as processes.
Kernel Responsibilities
Kernel Responsibilities
sh
who
vi
kernel
The kernel is responsible for providing the resources needed by the programs
wishing to run. There are primarily four resources which the kernel manages.
Process Management
Unix systems are multi-user, multi-process environments. This means that at any
point in time there may be several processes running (between 15 and 60 is not
unusual). Most of the hardware on which Unix is run only has one processor. The
process management part of the kernel is responsible for scheduling each of the
processes
able to calls
run onto
the CPU.hooks
This isinto
referred
as time-slicing or multiSystem
provide
thetokernel
tasking. Provided the kernel can switch from one process to another fast enough
(called a context switch), the illusion to the user is that all of the processes are
running simultaneously.
File System Management
The notion of a tree structure is maintained by the kernel. It allows users to manage
parts of the tree, hides the division between multiple disks and networks, and
protects one users files from another.
Memory & Device Management
Unix employs a virtual memory management policy in which the amount of
memory available to processes is greater than is physically available in RAM. This
is achieved by swapping (or paging) processes from RAM to disk (the swap region
on the disk) when the process is not needed, and swapping it back when it is.
Device Management refers to the maintenance of the file interface to devices.
When users interact with device files, the file like interactions are mapped by the
kernel onto the corresponding device.
V. Brandis
The CDE command line login screen is only accessible from the CDE login
managers options menu, when using a local login session.
Command line login can be achieved remotely using tools such as telnet and ssh.
Usernames
Usernames
Should be at least 6 characters long
Only the first 8 characters are significant
Case sensitive as in all Unix
Spaces are not allowed
Control characters and punctuation are permitted
Most people avoid them
Control-s and control-g are not permitted
A login must exist on the system prior to attempting to log in as that user
Only the Super-User may issue logins
Valid Usernames
Valid Usernames
Valid Entries
Invalid Entries
cowboy
the_black_marauder
>8 characters
marauder
john smith
Contains space
johnny
sarah^g
Contains ctrl-g
johnnyQ
sam
Too short
cee3po
MyLoGiN
its_me
Good Passwords
Good Passwords
Must be at least 6 characters long
Only the first eight characters are significant
Case sensitive
Spaces, punctuation, and control characters are
permitted
(but not control-s and control-g)
Should be different than login name
Must differ from the old password
Before picking a password, it is important to consider security. A good password is easy for you to
remember and hard for someone else to guess.
"since the password protects your work and the entire system from unauthorized and careless
users, and since it is relatively easy for other users (all throughout the networked world no less!) to
move through Unix systems, you should carefully guard your password."
Passwords should be at least six characters long. They can be up to eight characters long, including
numbers and special characters. Using eight characters makes your password more secure. Try not
to use a word in a dictionary or a proper noun because they are so easy to guess just by going
through the dictionary. Personal information, like your social security number, phone number or
birthday is also easy to guess (as you know from all those spy movies you have been seeing).
In particular, do not use your username. Mix letters, numbers, and punctuation. Mix lower and
upper case letters, too. A good way of getting a secure password is to think of a phrase and then
take the initial letters of the words in the phrase, randomly capitalizing and adding punctuation.
License plate combinations also work well, however, dont use your own. Keep several passwords
in mind, so you can change your password regularly (every few months or any time you think
someone else knows it).
Passwords
Passwords
Any user may change their own password with
the passwd command
Super-User cannot decode your password
Though they can be brute force decoded using
crack
Keep in mind that your password is your own. No one else should know it. Do not
share your account with other users by giving your password to them. Depending
on the conditions under which your account was given to you, sharing it may be
like sharing your driver's license, it is often grounds for revocation. Please do not do
it.
Keep your password secure. Do not keep it in a computer file, send it by email,
write it on a post-it note or your white board.
Login Failures
Login Failures
A login failure will generate a login error which
must be acknowledged
If login does not exist
Screen will be cleared and a new login screen
generated
/etc/nologin
File created by super-user to prevent non-root logins, e.g.
during maintenance
Interruptions
Interruptions
To stop a command from executing
Ctrlc
Ctrls
Ctrlq
Ctrld
Ctrlu
Generic Format
login:x:uid:gid:gecos:home directory:shell
login
x
uid
gid
gecos
shell
the username
a place holder for the password, kept in /etc/shadow
a unique number to identify each user
a unique number to identify the users primary group
a comment field used to identify the user
the program executed on completion of the login
NAME
passwd - password file
SYNOPSIS
/etc/passwd
DESCRIPTION
The file /etc/passwd is a local source of information about
users' accounts. The password file can be used in conjunction with other password sources, such as the NIS maps
passwd.byname and passwd.bygid and the NIS+ table passwd.
Programs use the getpwnam(3C) routines to access this information.
Each passwd entry is a single line of the form:
username:password:uid:gid:gcos-field:home-dir:login-shell
Password is generally substituted by an x to show that the actual password is
found in the /etc/shadow file.
Generic format
username:password:lastchg:min:max:warn:inactive:expire:flag
username
password
lastchg
min
max
warn
inactive
expire
flag
NAME
shadow - shadow password file
DESCRIPTION
/etc/shadow is an access-restricted ASCII system file that
stores users' encrypted passwords and related information.
The shadow file can be used in conjunction with other shadow
sources, including the NIS maps passwd.byname and
passwd.byuid and the NIS+ table passwd. Programs use the
getspnam(3C) routines to access this information.
The fields for each user entry are separated by colons. Each
user is separated from the next by a newline. Unlike the
/etc/passwd file, /etc/shadow does not have general read
permission.
Each entry in the shadow file has the form:
username:password:lastchg: min:max:warn: inactive:expire:flag
Generic format
group:x:gid:user-list
group
x
gid
user-list
:
:
:
:
name of group
password placeholder
a unique number to identify the group
list of users belonging to the group
NAME
group - group file
DESCRIPTION
The group file is a local source of group information. The
group file can be used in conjunction with other group
sources, including the NIS maps group.byname and
group.bygid and the NIS+ table group. Programs use the
getgrnam(3C) routines to access this information.
The group file contains a one-line entry for each group
recognized by the system, of the form:
groupname:password:gid:user-list
The password is generally replaced by an x
Summary
Summary
Usernames
6 characters or greater
8 characters are significant
Created in /etc/passwd or name service
Group
Primary gr oup is in /etc/passwd or name ser vice
All groups are in /etc/group or name ser vice
File Hierarchy
File Hierarchy
Just because something
doesnt do what you planned
it to do, doesnt mean its
useless
T. Eddison
Unix employs a tree structure to store files. Starting from an initial top-level
directory (the root directory) sub-directories successively organise information into
categories, and then sub-catagories. There are no limits on the depth to which the
tree structure can grow.
Unix differs from other hierarchical file stores (such as those provided in DOS and
VMS) in that there is only one tree. The single tree structure hides multiple disks,
partitions and even the network when NFS (the Network File System) is employed.
Hierarchical Structure
Hierarchical Structure
Directories are files which hold information on
other files
Directories can be viewed as branches and files
as leaves
Since directories are just other files, they can
also be stored inside directories
The Unix file system is organised into a hierarchical tree structure in which
directories are branches and files leaves. The purpose of directories is to group
together related files. However, since files may themselves be directories, it
follows that directories may contain sub-directories.
Directory Paths
Directory Paths
/
mbox
News
report
format
text
style
letter
book
note
File names
File names
Case sensitive
letters
A-Z or a-z
numbers
0-9
underscore _
period
comma
root
What is a file?
What is a file?
A file consists of
an inode
data
The file hierarchy is provided to offer an logical way of accessing data from
physical media.
Files consist of an inode and the actual data. Each file has an inode.
The inode contains information about the file. For Solaris, this is ususally:
the type of file (regular, directory, device, pipe, link, socket)
the mode of the file (read, write and execute permissions)
the number of hard links to the file
the user id of the file owner
the group id of the group to which the file belongs
dates and times of creation, last modification and last access
pointers to where the data is stored physically on the media
The inode does not contain the name of the file.
Other operating systems and file systems put different information in their inodes.
Varieties of Files
Varieties of Files
Ordinary Files
ASCII text or binary data, formatting left to user
Subclass of ordinary is hidden (name starts with .)
Directory
Directory provides a connection between the names
of the files and the files themselves. They impose a
structure on the file system
Device Files
Often located in the /dev directory
Writing to the device file transfers data to the device.
A directory is a file whose data is a list of file names and the locations of the inodes
that describe those files.
Device files are used to access hardware. They come in two types, block and
character.
current directory
parent director y
trinity% cd ../style
trinity% cd /report/style
trinity% pwd
/report/style
trinity% pwd
/report/style
trinity% cd ..
trinity% pwd
/report
trinity% cd /report/text
trinity% pwd
/report/text
trinity% cd
trinity$ pwd
/report/style
trinity% cd .
trinity% pwd
/report/text
The directories . and .. are convenient names for the current and parent
directories. .. allows path names to traverse back up through the tree.
Use the cd command to change directory and the pwd command to print the
current working directory. Note that cd without any arguments takes the user to
their home directory.
style
text
trinity% ls -l
-rwx------ 1 bill
-rw------- 1 bill
drwx------ 2 bill
drwx------ 2 bill
trinity% ls -F
format* note
style/
text/
trinity% ls /
mbox News report
trinity% ls -aF
./
format*
../
note
style/
text/
trinity% ls ..
mbox News report
trinity% ls /report/style
book letter
100
873
512
512
Mar
Mar
Mar
Mar
21
21
21
21
20:01
17:59
17:58
17:58
format
note
style
text
trinity% ls style
book letter
trinity% ls -d style
style
trinity% ls -ld style
drwx------ 2 greg 512 Mar 21 17:58 style
The ls command is used to display the contents of the specified directory. It takes
a variety of options that affect which files are displayed and the way their
information is formatted.
-l
-a
-g
-d
-F
long listing
all files, including those beginning with .
used with -l for group ownership
the directory file not its contents
show file type
Shell Wildcards
Shell Wildcards
Shell wildcards used for file name expansion
trinity% ls p*
pub pint plastered
trinity% ls /etc/*/m*
/etc/adm/messages
/etc/dp/modem
/etc/openwin/modules
The Unix shell provides wildcard expansion to generate filenames for commands.
To list all filenames that being with p (as above), then * is used to tell the shell to
generate the filenames automatically. The shell searches the specified directory to
find the files.
*
matches zero or more characters
?
matches exactly one character
[ABC] matches either A or B or C
[A-Za-z]
matches any single letter in upper or lower case
Note that wildcard expansion is different in Unix than for DOS. In DOS each
individual utility interprets * and may associate a different meaning to the symbol.
This is not possible in Unix, since the shell interprets the *, generates an argument
list, and then calls the specified command. In the above, echo simple writes to the
display its list of arguments; the list of arguments beginning with p were generated
by the shell prior to invoking echo.
trinity% pwd
/report
trinity% ls -F
format* note
style/
text/
text/
The mkdir command is used to create new directories, and rmdir to remove
directories. In keeping with most Unix commands, the commands may be supplied
as many filename arguments as is required. In the following
mkdir one two three four five six /tmp/seven
six directories are created within the current directory, and a seventh is created
beneath /tmp. Notice, however, that a minimum of one directory must be supplied
to the command.
Using the -p option, mkdir is able to create missing parent directories as needed
mkdir -p first/second/third
will create the missing parent directories first and second if they do not already
exist.
Note that it is not possible to remove a directory with rmdir if it contains other files.
To remove the directory, first remove all the files and sub-directories which it
contains. The powerful (and somewhat dangerous) rm -r command is useful for
this.
Copying Files : cp
Copying Files : cp
cp copies files and directories around the
filesystem
trinity% ls -F
mbox
News/
report/
trinity% ls -F
mbox
News/
report/
trinity% ls -F report/style
book
letter
trinity% cp -r report/style .
trinity% ls -F
mbox
News/
report/ style/
trinity% cp report/style/book .
trinity% ls -F
mbox
News/
report/ book
trinity% ls -F style
book
letter
cp [-ip] f1 f2
cp [-ip] f1 f2 ... fn d
cp -r [-ip] d1 d2
cp is used to copy files and directories around the filesystem. Note that copy means
duplicating the bytes on disk representing the contents of the files being copied.
cp is used with two arguments when copying from one file to another and with
many arguments when copying a collection of files into a directory. In the case of
the latter, the directory must exist and be the last argument. cp may also be used to
copy the contents of one directory to another. In this case the -r (recursive) option
must be supplied. When copying directories, if the target (d2) exists, then the
source (d1) is created within it. A file f1 within d1 may now also be accessed as
d2/d1/f1. If, however, the target does not exist, then it is created and the actual
contents of d1 are copied into it. Therefore, a file f1 within d1, may now also be
accessed as d2/f1.
By default, the copy command overwrites any files which already exist with the
target name. The -i (interactive) option may be used in order to get cp to prompt
prior to overwriting any existing files.
To preserve a files modification time and permission bits, use the -p option. If it is
also necessary to preserve the files ownership, then the cpio command should be
used.
Moving Files : mv
Moving Files : mv
Files and sub-directories can be moved
trinity% ls -F
mbox
News/
report/
trinity% ls -F report/style
book letter
trinity% mv report/style/book .
trinity% ls -F
mbox
News/
report/ book
trinty% ls -F
mbox
News/
report/
trinity% mv report/style .
trinity% ls -F
mbox
News/
report/ style/
trinity% ls -F style
book letter
trinity% ls -F report/style
letter
mv [-i] f1 f2
mv [-i] f1 f2 ... fn d
mv [-i] d1 d2
mv is used to rename files and directories. It does not cause the contents of the file
to be physically moved, only the files name is changed in its directory.
The new name may be a path to another directory, so mv can in fact move a file
from one place to another.
Note that there is no need for a recursive option when moving a directory since files
contained within the directory dont care what it is called. More specifically, the
contents of a directory file are the files stored within it, and mv does not effect file
contents. The -i option may be used if there is a danger of overwriting existing
files.
Deleting Files : rm
Deleting Files : rm
rm deletes files and directory structures
trinity% ls -F
mbox
News/
report/ book
trinity% rm book
trinity% ls -F
mbox
News/
report/
trinity% ls -F
mbox
News/
report/ style/
trinity% rm -r style
trinity% ls -F
mbox
News/
report/
trinity% rm -i book
rm: remove book? y
trinity% ls -F
mbox
News/
trinity% ls -F
mbox
News/
report/ book
report/
The rm command deletes files and directories. Beware that in Unix a deleted file is
lost forever. There is no mechanism to allow a file to be un-deleted since the disk
space associated with the file may immediately be re-used by some other process.
To recover a deleted file, the administrator must be asked to restore it from a system
backup. It is unlikely that the restored file will contain recent changes made to the
file.
The rm command also has the -i and -r options provided with cp. -i allows
interactive use of the command so that a use may stop the command from
accidently deleting a file. The -r option is necessary if directory structures must be
deleted.
Linking Files
Linking Files
Unix directories have multiple names
/
News
report
style
..
The Unix file system is held together through links. Each file is identified by a link
name, or file name as it is usually called. Every file in the file system must have a
name (a link), however it is possible (and often necessary) that some files have
multiple links.
The above example shows the multiple names associated with directories. All
directories have at least two names, their name in the parent and . in themselves.
Should they have sub-directories, then a new name is generated for them in each
It is also possible to create multiple names for
sub-directory, .. The . and .. directory links are created automatically when a
files
new sub-directory
is made. They are used as a short-hand notation to refer to the
current or parent directories.
Linking Files : ln
Linking Files : ln
Use the ln command to create links
ln [-s] f1 f2
Hard links : ln
Hard links : ln
$ ln original new
By default, ln creates hard links
A hard link is simply another directory entry pointing
at the inode of the file or directory
- Hard links cannot be made across different partitions
or physical disks
- It does not matter if the original file or directory is
deleted, as this simply removes one of the hard links to
the file
The number of hard links to a file is recorded in the inode of the file, and can be
seen with ls.
trinity$ ls -li /usr/bin/vi
401851 -r-xr-xr-x
5 root
/usr/bin/vi
bin
227828 Jun 19
2002
bin
You can see that the inode number of the two files is the same.
When the number of hard links to a file or directory is 0, then there are no longer
any directory entries for the file, so it ceases to be available, i.e. it has been deleted.
Symbolic links : ln
Symbolic links : ln
$ ln s original new
With the -s option, ln creates symbolic links
A symbolic link is a file that contains as its data, the
absolute path to another file
- Symbolic links, unlike hard links, can cross file system
boundaries
- The link will break if the file or directory to which it
points is removed
root
bin
9 May 13 15:06
9728 May 13 15:38
Note that since links are files in themselves, they will have their own inode number,
separate from that of the thing they point at.
Backwards compatibility
Pathname abbreviations
Pathname abbreviations
$HOME and ~
The home or login directory of the user
~username
The home or login directory of the user username
$PWD and .
The present working directory
..
The parent directory
Shell Meta-characters
Shell Meta-characters
Characters with special meanings to the shell
e.g.
* ? [ ] ` < > | ! ~ $ %
The dot ., underscore _ and hyphen - are
not meta-characters
It is advisable not to use these meta-characters
in directory or file names
* - Asterisk
* - Asterisk
* represents zero or more of any character
trinity% ls
dante dir dir2 dir3 eat fruit fruit2 zilog
trinity% ls d*
dante dir
dir2:
beans coffee nuts
dir3:
mango peach pear
trinity%
?- Question Mark
?- Question Mark
? represents any single character
trinity% ls
dante dir dir2 dir3 eat fruit fruit2 zilog
trinity% ls dir?
dir2:
beans coffee nuts
dir3:
mango peach pear
trinity%
[ ] Square Brackets
[ ] Square Brackets
[] defines an occurrence of a range
trinity% ls
dante dir dir2 dir3 eat fruit fruit2 zilog
trinity% ls [e-z]*
eat fruit fruit2 zilog
trinity% ls dir[0-5]
dir2:
beans coffee nuts
dir3:
mango peach pear
trinity%
` ` - Backticks
` ` - Backticks
` ` - backticks (or graves) force the command
enclosed in them to be executed and its output
substituted into command before the remainder
of the line is evaluated
trinity$ rm `cat obsolete_files.txt`
trinity$ YEAR=`date +%Y`
trinity$ echo $YEAR
2005
trinity$ echo the hostname is uname -n
the host name is trinity
Quoting in Shells [ ]
Quoting in Shells [ ]
Use single quotation marks to identify text
literally
trinity$ echo the path is $PATH
the path is $PATH
Why quote?
We have seen that the shell has meta-characters which have special meanings. We
have also seen that some of these characters have meanings to commands. We can
use quoting to force meta-characters to be dealt with in the way we expect, and by
the command we expect.
Escaping in shells [ \ ]
Escaping in shells [ \ ]
\ - The back-slash escapes the the meaning of
the following character so that it the shell does
not interpret it, if it normally would
trintiy$ echo \the path is \$PATH\
the path is $PATH
The backslash - \ - allows single characters to be escaped so that they are not
interpreted by the shell. This can be particularly useful for escaping quotes or
single characters that would still be interpreted inside quotes.
Getting Help
Getting Help
Good information is hard
to get. Doing anything with
it is even harder !
L. Skywalker
The standard way for getting help in Unix is the man command.
The standard way of using man requires that you know the name of what you want
help about.
Spacebar
b
f
q
h
/string
n
man : Output
man : Output
Header line
User Commands
head(1)
Name
head - display first few lines of files
Synopsis
head [ -number | -n number ] [ filename...
Description
A brief description of what the command does
man : Output
Options
A detail explanation of each of the options
supported by the command
Operands
A list of parameters, such as files, this command can
manipulate
Usage
How the command is used and what problems are
know about it
Examples
A simple example
man : Output
Environment
Any environmental variables which the application can
or does use.
Exit Status
What error levels or exit status are given when the
program has run
[very useful when writing scripts]
Attributes
Attributes of the command
See Also
commands associated with this one
man : example
man : example
User Commands
head(1)
NAME
head - display first few lines of files
SYNOPSIS
head [-number | -n number]
[filename...]
DESCRIPTION
The head utility copies the first number of lines of each
filename to the standard output. If no filename is given,
head copies lines from the standard input. The default value
of number is 10 lines.
When more than one file is specified, the start of each file
will look like:
==> filename <==
Thus, a common way to display a set of short files,
fying each one, is:
example% head -9999 filename1 filename2 ...
identi-
man : example
OPTIONS
The following options are supported:
-n number
The first number lines of each input file will be
copied to standard output. The number option-argument
must be a positive decimal integer.
-number
The number argument is a positive decimal integer with
the same effect as the -n number option.
If no options are specified, head will act as
been specified.
if
-n
10had
OPERANDS
The following operand is supported:
file A path name of an input file. If no file operands
specified, the standard input will be used.
are
man : example
USAGE
See largefile(5) for the description of the behavior of head
when encountering files greater than or equal to 2 Gbyte ( 2
**31 bytes).
EXAMPLES
Example 1: Writing the first ten lines of all files
To write the first ten lines of all files (except those with
a leading period) in the directory:
example% head *
ENVIRONMENT VARIABLES
See environ(5) for descriptions of the following environment
variables that affect the execution of head: LANG, LC_ALL,
variables that affect the execution of head: LANG, LC_ALL,
LC_CTYPE, LC_MESSAGES, and NLSPATH.
man : example
EXIT STATUS
The following exit values are returned:
0
Successful completion.
>0
An error occurred.
ATTRIBUTES
See attributes(5) for descriptions of the
butes:
following
attri-
____________________________________________________________
|
ATTRIBUTE TYPE
|
ATTRIBUTE VALUE
|
|_____________________________|_____________________________|
| Availability
| SUNWcsu
|
|_____________________________|_____________________________|
| CSI
| enabled
|
|_____________________________|_____________________________|
| Interface Stability
| Standard
|
|_____________________________|_____________________________|
SEE ALSO
cat(1), more(1), pg(1), tail(1), attributes(5),
largefile(5), standards(5)
environ(5),
User Commands
System Calls
C library functions
File Formats
System Administration
Introductory pages explain what the section of the manual contains, any subsections
and often list the pages within the section.
Google
Help can often be found on-line through search engines
such as Google
http://www.google.com/
Searches can be restricted using limiters
site
filetype
OR
Google: Example
Google: Example
SunSolve
SunSolve
SunSolve is Sun's official online help source
http://sunsolve.sun.com/
Available to the general Sun Community:
-
Security Information
Resolved Sun Alerts
Patch Descriptions (a.k.a. Patch ReadMe documents)
Archived SunSolve content
Limited Access to the SunSolve Knowledgebase
Sun Support Forums
Big Admin
Varieties of Files
Varieties of Files
Ordinary Files
ASCII text or binary data, formatting left to user
Subclass of ordinary is hidden (name starts with .)
Directory
Directory provides a connection between the names
of the files and the files themselves. They impose a
structure on the file system
Device Files
Often located in the /dev directory
Writing to the device file transfers data to the device.
A directory is a file whose data is a list of file names and the locations of the inodes
that describe those files.
Device files are used to access hardware. They come in two types, block and
character.
The file command is used to provide information about the contents of the file
passed as the parameter.
It performs a number of tests on the data in the file, including whether the file starts
with a particular magic number.
The file /etc/magic contains a plain text listing of these magic numbers and what
they mean about the file.
The strings command can be used to find ASCII strings within a binary file.
This can be useful for finding error messages in binary files, or identifying random
binaries.
The cat command displays the contents of a file to the standard output file handle.
This is usually the screen.
If given more than one file name, cat will display the files sequentially. This can be
used to join, or concatenate, files.
The more command is one of a group of commands known as pagers, i.e. they
display data a page at a time.
An alternative to more is the less command.
NAME
less - opposite of more
SYNOPSIS
less -?
less --help
less -V
less --version
less [-[+]aBcCdeEfgGiImMnNqQrsSuUVwX]
[-b bufs] [-h lines] [-j line] [-k keyfile]
[-{oO} logfile] [-p pattern] [-P prompt] [-t tag]
[-T tagsfile] [-x tab] [-y lines] [-[z] lines]
[+[+]cmd] [--] [filename]...
(See the OPTIONS section for alternate option syntax with
long option names.)
DESCRIPTION
Less is a program similar to more (1), but which allows
backward movement in the file as well as forward movement.
Also, less does not have to read the entire input file
before starting, so with large input files it starts up faster than text editors like vi (1).
NAME
head - display first few lines of files
SYNOPSIS
head [-number | -n number] [filename...]
DESCRIPTION
The head utility copies the first number of lines of each
filename to the standard output. If no filename is given,
head copies lines from the standard input. The default value
of number is 10 lines.
NAME
tail - deliver the last part of a file
DESCRIPTION
The tail utility copies the named file to the standard output beginning at a designated place. If no file is named,
the standard input is used.
-c
-f
list
[-n]
[-d delim]
[-s]
NAME
cut - cut out selected fields of each line of a file
SYNOPSIS
cut -b list [-n] [file...]
cut -c list [file...]
cut -f list [-d delim] [-s] [file...]
DESCRIPTION
Use the cut utility to cut out columns from a table or
fields from each line of a file; in data base parlance, it
implements the projection of a relation. The fields as
specified by list can be fixed length, that is, character
positions as on a punched card (-c option) or the length can
vary from line to line and be marked with a field delimiter
character like <TAB> (-f option). cut can be used as a
filter.
trinity$ wc dante
33 223 1320 dante
trinity$ wc -l dante
33
NAME
wc - display a count of lines, words and characters in a
file
SYNOPSIS
wc [-c | -m | -C] [-lw] [file...]
DESCRIPTION
The wc utility reads one or more input files and, by
default, writes the number of newline characters, words and
bytes contained in each input file to the standard output.
The utility also writes a total count for all named files,
if more than one input file is specified.
wc considers a word to be a non-zero-length string of characters delimited by white space (for example, SPACE, TAB).
See iswspace(3C) or isspace(3C).
NAME
diff - compare two files
SYNOPSIS
diff [-bitw] [-c | -e | -f | -h | -n | -u] file1 file2
diff [-bitw] [-C number | -U number] file1 file2
diff [-bitw] [-D string] file1 file2
diff [-bitw] [-c | -e | -f | -h | -n | -u] [-l] [-r] [-s]
[-S name] directory1 directory2
DESCRIPTION
The diff utility will compare the contents of file1 and
file2 and write to standard output a list of changes necessary to convert file1 into file2. This list should be
minimal. Except in rare circumstances, diff finds a smallest
sufficient set of file differences. No output will be produced if the files are identical.
unplugged
NAME
diff3 - 3-way differential file comparison
SYNOPSIS
diff3 [-exEX3] filename1 filename2 filename3
DESCRIPTION
diff3 compares three versions of a file, and publishes
disagreeing ranges of text
dictionary order
fold lower case into upper case
i.e. a follows A
- -n
numerically
- -M
compares months
i.e. Jan before Feb before Mar
- -r
reverses order
Use +n to sort on a particular column, where n is the column number
multiple columns may be sorted at the same time
- ordering options can be specified for each column
Sort can be used to sort multiple files into one sorted file.
Sort is often used as part of pipelines to sort the output of one command before it is
input into another.
NAME
uniq - report or filter out repeated lines in a file
SYNOPSIS
uniq [-c | -d | -u] [-f fields] [-s char] [ input_file
[output_file]]
uniq [-c | -d | -u] [-n] [ + m] [ input_file
[output_file]]
DESCRIPTION
The uniq utility will read an input file comparing adjacent
lines, and write one copy of each input line on the output.
The second and succeeding copies of repeated adjacent input
lines will not be written.
Repeated lines in the input will not be detected if they are
not adjacent.
Redirection
Redirection
D. Boone
Why ?
Why ?
For useful work to be performed data must be
transformed
Most work requires data to be transformed in a
number of different ways
Standard Files
Standard Files
stdin
stdout
stderr
Every process is assigned three files on creation; stdin, stdout and stderr.
These files are used to accept input, display output and display errors.
is redirected using its file descriptor 2 and the greater than symbol - 2>
This allows any errors output by the running command to be sent to a file, rather
than the display.
This can be particularly useful in scripts.
stderr
Redirection : >>
Redirection : >>
>
Causes a new file to be created each time the redirection occurs
>>
Causes the text to be appended to an existing file or creates a
new file if one does not exist
Single redirection arrows are used to create new files. If the file already exists, it is
overwritten by the new output.
Double redirection arrows are used to append data to files. If the file does not exist,
it will be created. However, if the file already exists, the output will be added to the
end of the file.
Redirection : Merging
Redirection : Merging
Sometimes useful to merge stderr and
stdout
for scripts, where we want to capture the output and
any errors in the same file
A very powerful way of using redirection, is to use more than one redirection with a
single command.
It is important to note that redirections are performed in a particular order, and
should be read from right to left.
Thus, in the example shown:
cp > out.a 2>&1
This reads as: redirect stderr to stdout (i.e. merge stderr and stdout) then
redirect stdout to the file out.a
cp 2>&1 > out.b
This reads as: redirect stdout to out.b, then redirect stderr to stdout.
However, as stdout has already been redirected, it is not possible to redirect
stderr to stdout, so the usage message from cp will go to the display.
Redirection : Examples
Redirection : Examples
trinity$ cat dante > newdante
Another useful method of file creation using redirection is called the Here
Document.
This is a specialised case of the second example shown, where text read from the
following lines until an end of file marker (typically the string EOF, but may be
anything) is entered.
cat > newfile <<EOF
And if anyone knows anything about anything,
said Bear to himself, its Owl who knows some
-thing about something, he said, or my names
not Winnie-the-Pooh, he said. Which it is, he
added. So there you are.
EOF
As in the example in the slide, a file called new file would be created containing the
data, however, this method is useful for scripts where one may wish to create long
files, e.g. containing configuration data, without using multiple echo statements
Pipelines : |
Pipelines : |
Pipes are command line FIFO buffers
Pipelines : examples
Pipelines : examples
trinity$ ls . | grep morpheus
Named Pipes
Named Pipes
Named pipes, or FIFOs, are used to facilitate
communications between a sending process and
a receiving process.
$ mknod name p
$ mkfifo [-m mode] path
Both commands will create a named pipe, either
called name or located at path
A FIFO is a queue where the first item in, is the first item out.
Named pipes can be used instead of temporary files in scripts where it is necessary
to pass data between processes.
File Security
File Security
Anyone who uses the phrase
as easy as taking candy from
a baby, has never tried taking
candy from a baby
R. Hood
Security Overview
Security Overview
The primary function of a system's security
feature is to deny access to unauthorized users
Unixs primary security features
User passwords
File and directory protection with permissions
Files that control remote logins and commands
on individual workstations
Logs and audit files for System Administrators
to check for unauthorized usage
The requirement for security comes directly from the multi-user, networked nature
of Unix.
By requiring users to log into the system, we can restrict access to systems to only
those people who need to access them. It also helps provide an audit trail as to who
has done what on a system. This is an important tool for administrators and is a
very good reason why you shouldnt allow other people to use your account.
Since the system has a concept of identity, security can be further refined, by
assigning ownership to files, then defining how this affects a users ability to read,
write or execute the file.
Permissions
Permissions
Unix has two default levels of security
Username and passwords to access the workstations
File access permissions
Usernames and passwords limit access to a system and provide identity once logged
in.
File and directory permissions provide access control within the file hierarchy,
limiting what users can see and do on a system.
thisfile
The mode of the file details its type and the permissions of the file, as stored in the
inode. It is listed in the first 10 characters of the output of the ls command when
the -l parameter is used.
The first character may be one of the following:
d
The entry is a directory.
D
The entry is a door.
l
The entry is a symbolic link.
b
The entry is a block special file.
c
The entry is a character special file.
p
The entry is a FIFO (or "named pipe") special file.
s
The entry is an AF_UNIX address family socket.
The entry is an ordinary file.
The remain nine characters should be examined as three groups of three and show
the permissions granted to the user who owns the file, the group of users the file is
associated with, and any other user who does not fall into one or other of the
previous categories.
Types of users
Types of users
User
Owner of a file may manipulate a file in any manner, except
transferring ownership
Only the super-user may change the user who ow ns a file
Group
A list of users, as in a class, all of whom have equivalent
permissions
To find w ho is in a group, look in the /etc/group file
Others
Public with a login on the system may access the file
The super-user, root, is a special case, and ignores all permissions on all files. This
can be very dangerous.
Access Permissions
Access Permissions
Access permissions affect files and directories in
different ways
readable
Files:
Directory:
writable
Files:
Directory:
executable
Files:
Directory:
Directories are files whose data consists of a list of file names and pointers to the
inodes of those files.
If a user has read access on a directory, then they may list the contents of that
directory, i.e. the data of the file is visible.
If a user has write access on a directory, they they may create and delete files in the
directory, i.e. modify the data in the directory file, by adding or removing links
between file names and inodes.
If a user has execute permissions on a directory, they are allowed to enter the
directory or pass through it.
For users other than root, access is processed using the most restrictive match first.
u user
r read
g group o other
w write x execute
How
= set
+ add
a all
- remove
Octal
When using symbolic modes, a is used to set a permission for all of the user, group
and others. If who the permission is for is omitted, then a is assumed.
For example, to specify that a file may be read and modified by its owner, and the
group, but only read by anyone else use the following modes
Symbolic:
chmod ug=rw,o=r myfile or chmod +r,ug+w
Octal: chmod 664 myfile
It is often easier to set permissions initially with an octal mode and then make
changes using the symbolic notation.
Octal Modes
Octal Modes
user
group
other
read
400
040
004
write
200
020
002
execute
100
010
001
r
1
root
w
x
1
1
user
4+2+1=7
other
r
1
34342
w
x
1
0
group
4+2+0=6
Jan 14 1999
thisfile
r
0
w
x
0
1 =761
other
0+0+1=1
In this example, we can see that the file has been given the following permissions
User (owner): may read, modify and execute the file
Group:
may read and modify the file
Other:
may execute the file
The octal mode which matches this permission set is 761
UIDs and GIDs can also be mapped to names using naming services, such as LDAP
or NIS. These are commonly used in large networked environments so that users
and groups are provided consistently across the entire network but can be managed
from a central location.
We have seen that ordinary users do not have access to the shadow file where
passwords are stored.
How then can a user change their own password?
Who am I [id]
Who am I [id]
$id [user]
Display the UID, GIDs and corresponding user names
and group names for the current, or specified, user
If real and effective UID and GID are not the same,
both will be displayed
trinity$ id
uid=115(guest) gid=10(staff)
The id command is particularly useful for finding the effective UID and GID of a
user.
Ownership
Ownership
trinity$ ls an thisfile
-rwxrw---x 1002
100
34342
Jan 14 1999
thisfile
0:00 /usr/lib/ssh/sshd
0:01 /usr/lib/ssh/sshd
other
other
chown can be used to change the ownership and group ownership of a file.
Generally, it is only used by the super user.
chgrp can be used to change the group ownership of a file.
As with rm, it can be dangerous to use chown or chgrp recursively.
Standard users may only have one real user id, but may be members of many
groups.
The super-user is not restricted by file permissions or ownership.
setuid
setuid
chmod +s filename
Program file owned by one user but run by another
Program runs as though by file owner
-r-sr-sr-x
1 root
sys
21964 Apr
2002 /usr/bin/passwd
passwd command runs as root, no matter which user invokes it. This allows it
access to the shadow file, which is not accessible by non-root users.
setuid should be used with care on root owned files as it removes some of the
protection granted by ownership and access permissions.
setgid
setgid
setgid operates in a similar fashion to setuid
When program is run it takes the permissions of
the program's group rather than the group(s) of
the user
chmod g+s filename
If a program has the has the set-group-ID bit set, then when any user runs the
program it will be run with all the access privileges of the program's group rather
than the group(s) of the user running the program. A program can give up this
privilege after starting (which is often done for security reasons).
If a directory has these bits set, everything created under that directory will be
owned by the directory's user or in the group of the directory, regardless of who
creates the file.
Sticky bit
Sticky bit
chmod
+t file
On a directory
sys
mail
On a file
The maximum permissions that can be set on a file are all of the user, group and
other having read and write permissions. The octal mode which corresponds with
this permission set is 666.
Files are not created executable, by default, for security reasons. Most files will
never be executed.
The maximum permissions that can be set on a directory are all of the user, group
and other having read, write and execute permissions. The octal mode which
corresponds with this permission set is 777.
Directories are created executable, by default, so that they may be traversed.
Why?
Why?
Useful work transforms data
This is often achieved using some form of
translation
It is useful to be able to find data
So that we can transform the right thing
So that we only transform what is necessary
find : Conditions
find : Conditions
$ find path condition
[-user uid]
[-group gid]
[-mtime [+|-] n]
[-atime [+|-] n]
[-perm nnn]
[-inum n]
[-size [+|-] n]
[-exec command {}\;]
find : Examples
find : Examples
$find / inum 767
Find all files who share the same i-node
i.e hard links
$ find / name core.0 exec rm {}\;
Find all core files and remove them
i.e. remove all crash dumps
$ find / size +400
Find all files larger than 400 blocks
We have previously seen that we can find all files whose listing contains the string
morpheus with by using grep on the output of ls -l
Similar, but more refined, searches can be performed using find.
e.g.
To find all files in the current working directory owned by morpheus use:
find . -user morpheus
To find all files in the current working directory whose group ownership is
morpheus
find . -group morpheus
To find all files called morpheus
find . -name morpheus
Regular Expressions
Regular Expressions
Regular Expressions - regexp - are a powerful
method for finding things
A Regular Expression is pattern of characters used to
match against the same characters in a search.
They usually include meta-characters, which
represent things other than themselves, to refine the
search.
The command evaluates text against the pattern to determine if the text and the
pattern match
If they match, the expression is true
Modifying meta-characters
*
0 or more of the preceding pattern
+
Positional meta-characters
^
Matching Characters
Printable characters (including w hitespace)
Alphabetic characters
Space and tab characters
Control characters
Numeric characters
Printable and visible (non-space) characters
Lowercase characters
Printable characters (includes w hitespace)
Punctuation characters
Whitespace characters
Uppercase characters
Hexedecimal digits
These character classes are defined by the POSIX standard and may or may not be
available in commands which implement Regular Expressions.
- .*
Finds the pattern of a line which ends with the word End
Translate [tr]
Translate [tr]
tr [set1] [set2]
Translates the characters in set1 to set2
- Each input character found in the range specified by
set1 is replaced by the character in the same relative
position in the range specified by set2.
trinity$ cat dante | tr [a-z] [A-Z]
HALF WAY ALONG THE ROAD WE HAVE TO GO,
I FOUND MYSELF OBSCURED IN A GREAT FOREST,
BEWILDERED, AND I KNEW I HAD LOST THE WAY.
IT IS HARD TO SAY JUST WHAT THE FOREST WAS LIKE,
HOW WILD AND ROUGH IT WAS, HOW OVERPOWERING;
EVEN TO REMEMBER IT MAKES ME AFRAID.
...
The tr command takes two ranges and replaces every character in the input that
matches the characters in the first range, by every character in the same relative
position in the second range.
The POSIX character classes mentioned previously, are particularly useful with the
tr command.
For example, the translation shown in the slide, could be rewritten as follows
trinity$ cat dante | tr [:lower:] [:upper:]
ignore case
[-v]
[-c]
counts matches
trinity$ grep root /etc/passwd
root:x:0:0:root:/root:/bin/sh
The grep command is particularly useful for finding simple strings in files or
output.
The name Leaning Toothpick Syndrome (LTS) was coined by Larry Wall, the
creator of the perl programming language, which makes heavy use of Regular
Expressions in its syntax.
sed
sed
sed is an extremely powerful tool for noninteractive editing
particularly useful in scripting
http://sed.sourceforge.net/sed1line.txt
TIME
May 24 10:17 trinity
pts/4
May 24 17:36 (trinity.matrix.com)
trinity$ who am i
morpheus
trinity$ who -r
.
run-level 3
May 15 10:28
The who command is useful for the administrator to find out which users are logged
into a system and from where.
The who am i version of the command is useful for finding the real UID of the
current user
trinity$
12:52pm
User
root
w
up 59 day(s), 20:57,
tty
login@
pts/0
12:52pm
Ulysses
Process Overview
Process Overview
All tasks within Unix begin as processes
Processes are running files
Process Identification Numbers (PIDs) are used
to keep track of separate processes
All processes have a UID and a GID associated
with them
One process may have many Light Weight
Processes, or threads, associated with it
Generating Processes
Generating Processes
Parent process runs fork() to generate an identical copy
of itself except it is given a new process ID
If fork() succeeds
child process inherits parents envir onment space
STDIN, STDOUT and STDERR redirected to parent
fork() returns value of child PID to parent
uses exec() to r un command
when command finishes, returns ONLY the exit status of
command ($?) to parent
If fork() fails
returns exit status of -1 to parent
Generating Processes
STDERR
PARENT
STDIN
STDOUT
ENV
failure
success
(i.e. -1)
Child PID
fork()
fork()
STDERR
Child
NOT created
Incorrect
ENV
CHILD permissions
status
STDIN
Out
ofcode
memory
STDOUT
exec()
($?)
STDOUT
STDIN
Out of process
slots
Understanding Processes
Understanding Processes
The cd command must be built into the shell
Why?
cd changes directory
- i.e. modifies the $PWD environment variable
C
80
80
27
80
80
STIME
16:46:40
16:46:40
16:46:40
16:46:40
18:13:12
TTY
?
?
?
?
console
TIME
00:01
00:40
00:00
04:33
00:01
CMD
sched
/etc/init pageout
fsflush
ksh
-a
SIZE
4568K
328K
2576K
1872K
2784K
1120K
SIZE
87M
4312K
RSS
4344K
256K
1888K
1288K
1952K
376K
RSS
55M
1416K
CPU
0.0%
0.0%
0.0%
0.0%
0.0%
0.0%
PROCESS/NLWP
prstat/1
sh/1
bash/1
in.telnetd/1
picld/4
dhcpagent/1
prstat is a useful way to see which commands are using the most CPU. This can be
particularly useful if a machine appears loaded unexpectedly.
It is also useful to see which users are using a machine most intensively.
prstat has many options which are listed in the man page
The -a option shown in the slide, shows user information at the same time as
process information
process ID
username of process ow ner
total virtual memory size of process in kilobytes
(K), megabytes (M) or gigabytes (G)
Includes the heap and stack assigned to the
process
RSS
resident set size, as above without the heap and
stack
state
current state of the process
- cpun
- running on cpun
- sleep - process is sleeping
- run
- process is runnable
- zombie - process is terminated but parent has not waited
for return value
- stop
- process is stopped
PID
username
size
A zombie process is a process that has completed execution but the exit status of
which has not been read by the parent process yet.
A process becomes a zombie process when it issues the exit subroutine and the
following circumstances occur: Its parent process is not running a wait subroutine
and has not notified the operating system that it does not intend to wait for its
children to finish.
The it is said that process has died, but has not yet been reaped.
process priority
nice
time
cpu
process
NLWP
NPROC
Nice values range from 0 to 39 and are used to bias the priority of a process. A
higher number results in a lower priority.
There are commands to change nice values, however, users can only affect the nice
value of processes which they own. They also cannot start processes with nice
values less than 20, nor can they lower the nice values of their processes after
they've raised them.
Managing Processes
Managing Processes
Commands executing take over the current
display until they complete
This is called foreground processing
A command run with a trailing ampersand (&) will be executed in the background.
It will be assigned a job number, separate from its process ID and both the job
number and process ID will be printed to the display.
When the command has finished running a done message and the process ID are
printed to the display on which it was started.
If the controlling terminal is killed, all running jobs in that terminal are also killed.
The terminal is the parent process for the jobs. When a parent process is killed, all
its children are also killed.
nohup
nohup
$ nohup command [&]
When a command is invoked by the nohup command
it will ignore hup signals
In practice, this means that the command is not
killed if the parent terminal dies
nohup can also be applied to processes after they
have been started using the -p PID option
trinity $ nohup find / -name bin
Sending output to nohup.out
nohup is a simple shell command that tells the program it is told to run not to exit
when the controlling terminal is killed.
It is particularly useful for leaving long running processes in the background
without having to keep a shell open - i.e. keeping them running in case you need to,
or accidentally, log out (or if the windows computer on which you've logged in
freezes and needs to be restarted.)
Example:
nohup long_running_command &
The '&' tells the shell to not only nohup the command, but to also run it in the
background, letting you continue using the terminal as usual.
By default, nohup sends all output (both stdout and stderr) to a file called nohup.out
in the current working directory. However, if this directory is not writable, the file
will be created in the users home directory. This file can be very useful for
examining if there are problems with the job.
trinity$ jobs
[1] + Running find . name *.gif &
will only show the jobs started in the terminal in which it is run. This can be a
problem if you have started jobs in multiple terminals or have used nohup and
closed the controlling terminal.
jobs
trinity$ jobs
[1] + Running find . name *.gif &
trinity$ fg %1
Processes running in the background may also be stopped with stop %job-id
Stopped jobs may be restarted with bg %job-id
$ jobs
[1] + Running find . name *.gif &
$ kill %1
[1] + Terminated find . name *.gif
Function
jobs
fg %n
Foreground a job
bg %n
Background a job
kill %n
Abort a job
Ctrl-C
Ctrl-Z
Job management commands only show or operate on jobs started in the terminal in
which they are run.
It is not possible to background a process in one terminal and then foreground it in
another.
/proc
/proc
Special filesystem
Contains information about all running processes
memory segments (as)
current w orking director y (cwd)
light weight processes (lwp)
/proc is a file system that provides access to the state of each process and lightweight process (thread) in the system. The name of each entry in the /proc directory
is a number corresponding to a process-ID. These entries are themselves
subdirectories.
Access to process state is provided by additional files contained within each
subdirectory.
The owner of each /proc file and subdirectory is determined by the user-ID of the
process.
Beelzebub
Modal Editor
Modal Editor
Two fundamental modes of operation
Insert/Replace Mode
Command Mode
Editing a file
Editing a file
To edit a file using the vi editor, just type
$ vi filename
Leaving vi
Leaving vi
To exit, you must be in Command mode
To verify this mode, press <ESC> until you hear
a beep
:q!
:w
:wq
ZZ
Entering Text
Entering Text
To enter insert mode from Command Mode,
press
i insert text before the cursor
a append text; insert after the cursor
o insert a new line after cursor line and remain in
insert mode
O insert a new line before the cursor line
Command Mode
Command Mode
To verify you are in Command mode, press
<ESC> until you hear a beep
Two forms of commands
direct commands
- executed immediately
ex commands
- are always preceded by a colon :
- followed by the command
Cursor Modes
Cursor Modes
The cursor keys may move one character in the
direction of the arrow
More certainly, you should use the following
keys:
j
k
h
l
space
Moving around in vi
Moving around in vi
To move further, you may use the following
keys:
Ctrl-f
Ctrl-b
G
3G
1G
0
$
Deleting Text
Deleting Text
Removing text by the cursor:
dd
5dd
d$
dw
x
5x
Searching in vi
Searching in vi
Text can be searched in the following ways:
/pattern
Replacing Text
Replacing Text
To replace text from Command Mode, enter one
of the following:
replace the character under the cursor with
the letter d. No <ESC> necessary
R
global replace mode. Text under cursor will
be replaced with typed text until <ESC> is
pressed
cw
Change the word from current cursor until
and not including the next white space with
the typed text until <ESC> is pressed.
A $ symbol marks the end of the text to be
replaced
rd
Substituting text
Substituting text
:s/first_exp/replacement_exp/[g]
Substitute the first_exp with the replacement_exp
The [g] at the end means global to the line.
:1,$s/first/second/ or :%s/first/second/
For the entire file, replace the first occurrence in a line of the
string first with the string second
:.,$s/meat/bones/g
From the present cursor line to the end of the file, substitute all
occurrences of the string meat with the string bones
Coping text
Coping text
Text can be copied with the following
commands
yy yank (copy) the current line to the temporary
buffer
3yy yank the current line plus two to the
temporary buffer
xp delete the character under the cursor and
retrieve the deleted character after the cursor.
(Interchanges two characters)
J join the current line with the next line
Retrieving text
Retrieving text
Yanked and deleted text can be inserted using:
pull (insert) the contents of the temporary buffer
following the cursor
P pull the contents of the temporary buffer before
the cursor
p
Miscellaneous tricks
Miscellaneous tricks
A few extras:
Ctrl-l
Ctrl-r
Ctrl-G
ex commands
ex commands
ex commands in fact invoke the ex line editor
on the file
for more information, see man ex
All ex commands
are executed from Command Mode
are prefaced by :
are terminated by a carriage return
! (bang)
! (bang)
:q!
In this context the command is to be executed
without error reporting
:!ls
In this context, it means to execute and display the
results of the shell command ls
:r !ls
Perform the shell command ls and insert the results
into the present file following the cursor
set commands
set commands
The set command allows modification of the
environment
The environment variables which can be
accessed through the set command can be seen
through the :set all command
Final Thoughts
Final Thoughts
All work is done on a temporary file
No changes to the original file occur until a
command which causes the write has been
executed
User must have write permission to modify the
file
User needs only read permission to view the file
All files may be edited, but binary files are
unintelligible
$$
0:00 ksh
$?
Variables can be viewed with the echo command and the name of the variable,
prefaced by a $ symbol to denote to the shell that it should treat the name as a
variable name and expand it before displaying it.
Export should be used with the bare variable name. A common mistake is to use
export $variable which the shell will expand to the contents of the variable
before attempting the export.
$ env
Displays the current environment space (global)
trinity$ set
ERRNO=1
FCEDIT=/bin/ed
HOME=/
IFS='
'
LINENO=1
LOGNAME=root
MAILCHECK=600
OPTIND=1
PATH=/usr/bin:/bin:/usr/sbin:/sbi
n
trinity$ env
_=/usr/bin/env
SSH_TTY=/dev/pts/1
PATH=/usr/bin:/bin:/usr/sbin:/sbi
n
LOGNAME=root
USER=root
SHELL=/sbin/sh
HOME=/
SSH_CLIENT=172.16.0.100 34415 22
TERM=screen
PWD=/
Search paths may contain an entry for dot, i.e. the current working directory. This
is considered unsafe for users and dangerous for the super-user as it can allow the
running of arbitrary code by accident.
which takes a list of names and looks for the files which would be executed had
these names been given as commands.
Each argument is expanded if it is aliased, and searched for along the user's PATH.
Both aliases and PATH are taken from the user's shell.
It is sometimes useful to create shell variables which are available every time a new
session is started without needing to be hand set.
e.g. in an Oracle environment, the ORAHOME variable is commonly set to last
between sessions.
In general, it is good practice to leave global shell configuration files as set up by
the operating system vendor and make changes only in the user-specific files.
on login
on new shell
sh
/etc/profile
$HOME/.profile
csh
/etc/.login
~/.cshrc
~/.login
~/.cshrc
ksh
/etc/profile
~/.profile
~/.kshrc
~/.kshrc
bash
/etc/profile
~/.bash_profile
or ~/.bash_login
or ~/.profile
~/.bashrc
Bill Copeland
Quoting in Shells [ ]
Quoting in Shells [ ]
Use single quotation marks to identify text literally
trinity$ echo the path is $PATH
the path is $PATH
Why quote?
We have seen that the shell has meta-characters which have special meanings. We
have also seen that some of these characters have meanings to commands. We can
use quoting to force meta-characters to be dealt with in the way we expect, and by
the command we expect.
The backslash - \ - allows single characters to be escaped so that they are not
interpreted by the shell. This can be particularly useful for escaping quotes or
single characters that would still be interpreted inside quotes.
Custom Prompts
Custom Prompts
$ PS1=value
PS1 is a predefined prompt variable that
users can change
NB there are no spaces around the =
$ PS1=uname -n:\$PWD $
trinity:/home/morpheus $
It can be useful to set the prompt in your shell to display certain information.
For example, if you are connected remotely to many machines, having the name of
the machine in the prompt can help identify which session is which, and reduce the
possibility of running a command on the wrong machine.
It may also be useful to display the current working directory in the prompt, so that
it is clear where one is in the file hierarchy at any time.
The prompt variable is a commonly set in your personal shell initialisation file.
Aliases [alias]
Aliases [alias]
$ alias [name=value]
with no options it lists which commands have aliases
substitutes the name for value when executing
commands so that the command set can be richer
NB there are no spaces around the =
trinity$ alias
trinity$ dir
-rw-r--r-1
drwxr-xr-x
2
-rw-r--r-1
dir=ls l
morpheus
morpheus
morpheus
users
users
users
trinity$ history
28
man set
29
man which
30
man -k which
31
dir
32
history
trinity$
When typing long commands, or pipelines, it can be useful to be able to recall them
to run again.
The history command lists the most recently run commands.
j
k
h
l
space
move
move
move
move
move
trinity$ set o vi
press <esc> key and then k until the desired command
is displayed
press <CR> to execute that command
ksh offers two methods of command line editing, using keys borrowed from the two
most popular Unix editors.
Ctrl-n
Ctrl-p
Ctrl-f
Ctrl-b
Ctrl-d
Ctrl-a
Ctrl-e
Emacs command editing mode may be preferred by people who are more used to
the emacs text editor.
Shell Scripting
Shell Scripting
I write scripts to serve as
skeletons awaiting the flesh
and sinew of images.
Ingmar Bergman
What is a command ?
What is a command ?
A command is a file which is marked executable
May be a pre-compiled binary or a script
Shell Scripts
Shell Scripts
What is a script ?
A file which is mar ked executable whose first line is of the form
#!/path/to/command
The #! header tells the operating s ystem w hat s ort of
commands are in the script
Why script?
A means of automating tasks
Flow control
Flow control
Commands within a script are usually executed
one after the other in the order they appear in
the file
Flow control commands can use input data to
decide which command to execute next
test condition or [ condition ]
Flow control allows scripts to be more than just a list of commands, by allowing
branches in logic based on conditions and data.
[ [condition] ]
The test utility evaluates the condition and indicates the result of the evaluation by
its exit status.
An exit status of zero indicates that the condition evaluated as true and an exit
status of 1 indicates that the condition evaluated as false.
When comparing strings and variables in scripts, it is a good idea to place them in
quotes.
Flow control: if
Flow control: if
Used to test the status of a condition and
proceed with an action of the status of the
condition is true
if [ condition ]
then
command
fi
fi marks end of if block.
Square brackets [ ] are used as shorthand for the
test command
- So, must have a space after the [
num=0
while [ $num -lt 7 ]
do
echo number is $num
num=`expr $num + 1`
done
password=today
name=nobody
until [ $name = pass
do
echo Enter Pass
read name
done
trinity$ sh until.sh
Enter Pass fred
Enter Pass bill
Enter Pass password
Enter Pass pass
trinity$
In the first example, the loop continues while the condition is true, i.e. until the
condition is false.
In the second example, the loop continues until the condition is true, i.e. while the
condition is false.
The two contructs can be used interchangeably, depending on which is the easier
form of logic to express.
Positional Parameters
Positional Parameters
Data can be passed to the script from the
command line
These parameters are referenced with the
following variables
$0
$1 to $9
$#
$*
$*
$@
$@
Data can be passed to scripts from the command line, as with any command.
These parameters are accessed using the positional parameters variable.
$0 is the first item from the command line, i.e. the command used to invoke the
script
$1-$9 are the first 9 parameters passed to the command.
$* is a single string containing all parameters, quoting it, will put quotes around the
whole string.
$@ is a single string containing all parameters, however, quoting it will put quotes
around each parameter in the string
$# contains the total number of paremeters
Set braces can be used to access beyond the ninth parameter and also to make
variable names clear.
Networking
Networking
The Network is the Computer
S. McNeally
Systems can
access files on
remote
machines as if
they were local
Files are
actuall y
stored her e
Applications and
users are
unaware of the
location of the
files
The networking facilities described above generally require the user to have some
knowledge of the network, such as which machine they wish to communicate with.
Modern network environments may also provide facilities where the actual
networking takes place at a lower level, and does not require specific knowledge by
the user that the network is being used.
Distributed file systems were the first systems to provide this. In the UNIX
environment, a user has access to files through a single hierarchical file system
which hides the details of which physical (or logical) disk actually contains the files
(unlike DOS, where each logical drive must be explicitly be named and has its own
hierarchy of files and directories). With distributed file systems, this concept is
extended so that the hierarchy on a system may include directories and files which
exist on a different system in the network.
The most common UNIX distributed file system is the Network File System, or
NFS, covered in some detail later in the course. Others are the Andrew File System
(AFS), and the DCE DIstributed File System (DFS).
The concept of transparent access to files on a remote system also forms the basis
of Novells NetWare network operating system.
The main Graphical User Interface systems for UNIX offer more than the ability to
create and manage windows and graphical output on the screen.
The architecture of the X-11 system allows it to operate in a distributed manner in a
networked environment. The application requiring the graphical output, and
keyboard and mouse input need not be running on the same system as the graphics
screen, keyboard and mouse being used. This allows a situation where a computeintensive application can be run on a more powerful machine on the network, which
does not have graphics facilities. The output is transmitted across the network to a
less powerful system which has a graphics display and can display the output.
Applications may be configured so that this division of computation from I/O is
invisible to the user, it will appear as though the application is running on the local,
graphics-based system.
Protocol Layers
Protocol Layers
Application
Application
message
message
s 1 message 1
t
a 2
message 1 2
c
k 3
message 1 2 3
s 1 message 1
t
a 2
message 1 2
c
k 3
message 1 2 3
Application
Application
TELNET, FTP
OSI Layer 4
Transport
Transport
OSI Layer 3
Network
Network
Data
DataLink
Link
TCP, UDP
Concepts
Concepts
APP S
APP S
TCP
IP
UDP
ICMP
TCP
IP
UDP
ICMP
Connectionless protocols
Connectionless protocols
DATA
ER
Connection-oriented protocols
Connection-oriented protocols
DATA
DATA
TWO-WAY COMMUNICATION
Ports + Sockets
Ports + Sockets
APPLICATION PROCESS
SOCKET
INPUT
OUTPUT
PORT
Service
Echo
Date + Time
Character Generation
FTP
Telnet
Mail (SMTP)
WWW
Mail (POP)
News
UDP - Fundamentals
UDP - Fundamentals
User Datagram Protocol (UDP)
Connectionless
Unreliable
Used for
Domain Name Service (DNS)
Routing Information Protocol (RIP)
Real Audio
Network File System (NFS)
Trivial File Transfer Protocol (TFTP)
Network Time Protocol (NTP)
Plus many others
UDP can be used wherever reliability is unimportant and where a stream of data is
not needed - i.e. no frame numbering is required.
OCTETS
UDP Length
UDP Checksum
Frame Format
DATA
(0-65508)
Within IP
IP HEADER
UDP HEADER
UDP DATA
Note that the UDP checksum covers both the UDP header and the UDP data fields.
This is distinct from the IP checksum which is a header checksum only, and does
not cover the integrity of the data.
This is not normally a problem with IP, as the data-link layer protocols often
provide a checksum for the network layer data. However, in some cases (e.g. SLIP)
such a check is not offered, and so it is required at this level.
However, if the receiving host detects an error in the UDP data frame, it will not
return an error to the sending host, but simply discard the frame - the same
behaviour that IP demonstrates.
UDP - Issues
UDP - Issues
Unreliability
No good for streamed services where reliability is
important, where a connection is needed
Examples
FTP
Mail
Telnet
WWW
TCP - Fundamentals
TCP - Fundamentals
Transmission Control Protocol (TCP)
Connection-oriented
Reliable
Used for
FTP
Mail
News
Web
And many more
Frame Format
OCTETS
SEQUENCE NUMBER
ACKNOWLEDGEMEN T NUMBER
4 Bits
SEE
WINDOW SIZE
URGENT POINTER
DATA
(0-????)
EXP ANDED
SECTION
U A
R C
G K
P
S
H
R
S
T
S
Y
N
F
I
N
(6 bits)
1
2
3
ESTABLISHMENT
Host
A
Host
B
ACK <seq2>+1
DATA TRANSFER
Host
A
D ATA x n
D ATA x m
Host
B
TERMINATION
FIN <seq1>+n, ACK <seq2>+m
Host
A
ACK <seq1>+n+1
FIN <seq2>+m, ACK <seq1>+n+1
Host
B
ACK <seq2>+m+1
mss stands for Maximum Segment Size, and is a limit on the max size of data
frames that can be sent to the host. This is primarily useful if the host in on a
network with a small MTU, and so wants to avoid too much fragmentation of the
data.
The reason we have 4 termination signals, but only 3 to set up the connection is that
each side of the connection must be shut down individually. TCP is full-duplex
communication, and half-duplex can be achieved by performing a half-close - i.e.
shutting only one side of the connection down.
TCP - Options
TCP - Options
End of
option
list
1
kind=0
1
No
operation
Max
segment
size
Window
scale
factor
Timestamp
kind=1
kind=2
len=4
max segment
size
kind=3
len=3
shift
count
kind=8
len=10
4
Timesta mp Value
4
Timestamp echo reply
Name Services
Name Services
Several Name Services exist
Common examples include
- DNS
- LDAP
ahost.mycompany.com
- A computer in the domain
www.company.com
www.othercompany.co.uk
com
org
uk
co
org
gov
LDAP
LDAP
Lightweight Directory Access Protocol
Protocol for enabling anyone to locate organizations,
individuals, and other resources such as files and
devices in a network
LDAP has a universal format, which supports display
of all names.
A typical LDAP server is a simple network-accessible
database where an organization stores information
about its authorized users and what privileges each
user has.
Provides centralised management
/etc/nsswitch.conf
/etc/nsswitch.conf
Configuration file for name services and system
databases
Tells system where to find user data and
computer name/IP address mapping
Data locations include
files
dns
ldap
Inside ftp
Inside ftp
The following commands are available at the ftp>
prompt
list the files in the current remote directory
changes the current remote directory
displays the current remote director y
execute the command command locally
specifies the time of file to be transferred
gets the file filename from remote directory
and makes a local copy
put filename puts the file filename fr om local directory
and makes a local copy in the remote director y
mput|mget
allow multiple puts or gets with wildcards to be
done
quit
ends the ftp session
nlist|dir|ls
cd
pwd
!command
ascii|bin
get filename
Boot Stages
Boot Stages
There are three distinct stages in the boot flow.
Firmware
Kernel Initialisation & hardware
Software run levels
runs rc scripts
runs init
loads k ernel
k ernel initialises
The power on self tests are used when a system is powered on or reset from the
PROM level. They check out the CPU and the MLB and the tests can vary from
system to system. By default the POST output is not displayed to the monitor,
however it can be viewed by connecting an ASCII terminal to the serial port.
User commands are used to control the operation of the PROM. They can change
PROM variables such as the boot device and security modes.
The PROM contains an entire programming language and operating system known
as forth. Developed in 1978, this high-level language can fit into an 8KByte chip.
Firmware
Firmware
Power on
banner
Test memory
POST output
POST output
ok setenv diag-switch? true
ok setenv auto-boot? false
ok reset
PROM Checksum test
Context Reg Test
Setting Segment Map
Sizing Memory
Mapping ROM
Setting up RAM for monitor.
Setting up memory used in decompress.
Decompressing code to RAM ...
Remapping monitor's virtual addresses to RAM.
Probing /sbus@1,f8000000 at 0,0 dma esp sd st le
Probing /sbus@1,f8000000 at 1,0 Nothing there
Probing /sbus@1,f8000000 at 2,0 Nothing there
Probing /sbus@1,f8000000 at 3,0 bwtwo
Can't open input device.
SPARCstation IPC, No Keyboard
ROM Rev. 2.4, 12 MB memory installed, Serial 27831.
Ethernet address 8:0:20:a:e9:da, Host ID: 52006cb7.
The tests carried out by POST are simple yes/no type tests. It checks the integrity
of the CPU, hardware and any devices it can probe.
POST output
Testing
Testing audio chip; listen for a beep
Synchronous Error Reg Test
Synchronous Virtual Address Reg Test
Asynchronous Error Reg Test
Asynchronous Virtual Address Reg Test
System Enable Reg Test
Testing 12 megs of memory. Still to go
Cache Tag Memory Test
Cache Data Memory Test
SBus
SBus
SBus
SBus
slot
slot
slot
slot
0 le esp dma
1
2
3 bwtwo
Kernel Initialisation
Kernel Initialisation
bootstrap file loads k ernel
k ernel identification
reports memory,
ethernet address,
CPU type.
executes init
moddir
forceload
exclude
rootfs
rootdev
set
Boot output
Boot output
{ok} boot
Boot device: disk File and args:
Loading ufs-file-system package 1.4 04 Aug 1995 13:02:54.
FCode UFS Reader 1.12 00/07/17 15:48:16.
Loading: /platform/SUNW,Ultra-Enterprise/ufsboot
Loading: /platform/sun4u/ufsboot
SunOS Release 5.9 Version Generic_112233-01 64-bit
Copyright 1983-2002 Sun Microsystems, Inc. All rights reserved.
Use is subject to license terms.
configuring IPv4 interfaces: hme0.
starting DHCP on primary interface hme0
Hostname: trinity
The system is coming up. Please wait.
starting rpc services: rpcbind done.
Setting default IPv4 interface for multicast: add net 224.0/4: gateway
10.42.0.1
syslog service starting.
syslogd: line 24: WARNING: loghost could not be resolved
volume management starting.
The system is ready.
trinity console login:
/sbin/rc3
executes /sbin/autopush
/sbin/rc2
/sbin/rcS
login prompt
Action
Bring the sy stem to S ingle user lev el w here some file sy stems are
mounted and user log ins are disa bled.
S, s
Bring the sy stem to S ingle user lev el w here some file sy stems are
mounted and user log ins are disa bled.
Q, q
a,b,c
The /etc/inittab file defines three main items for the /sbin/init process.
The systems default run level.
What processes to start, monitor, and restart if they die.
What actions to be taken when the system changes run levels.
id
s3
rstate
3
action
wait
command :/sbin/rc3>/dev/console
2>&1 </dev/console
id
This is a field of up to four characters which is used to uniquely identify the
entry.
rstate This field defines at which run level to execute.
action This key word field tells init how to treat the process.
Valid keywords are as follows:
initdefault
The default run level.
respawn
Restart the process when it dies.
powerfail
Start the process when init receives a power
fail. (Useful for UPS systems.)
sysinit Start the process and wait for completion.
wait Start process and wait for it to finish.
cmd The command or script to execute.
rc0
rc0.d
rc1
rc1.d
rc2
rc3
rc2.d
rc5
rc3.d
rc6
rcS.d
rcS
init.d
K20lp
S15nfs.server
For each run level there will be an entry in /etc/inittab which calls the rc scripts.
These controlling scripts are located in /sbin but are linked to files in /etc. Each run
level script in turns executes the files found under the /etc/rc#.d directory in
alphanumeric order.
Each run control scripts found in these sub directories is either in the format K## or
S##. The K## files are kill files and are used to stop processes when the system
enters this run level. The S## files are start files and are used to start processes.
There is also a directory /etc/init.d which is used for stopping and starting
individual services or processes without having to change run levels. Each of these
scripts is hard linked to the corresponding files in the /etc/rc*.d directories. These
files are in simple to remember format are used with either the parameter stop or
start.
/etc/init.d/lp stop
/etc/init.d/sendmail stop ; /etc/init.d/sendmail start
The above example is used to start and stop the print process. The file has two
other names: /etc/rc1.d/K20lp and /etc/rc2.d/S80lp. The K name ensure that the
process is killed when entering run level 1, and the S name ensures that it is started
when entering run level 2.
Note : To disable a start (or kill) file do not simply add on an extension. The
conventional way is to change the K or S prefix to a lower case k or s. This works
because the /sbin/rc scripts only search for K* and S*.
/etc/init.d/lp stop
/etc/init.d/volmgt stop
/etc/init.d/lp start
The /etc/init.d directory is used by the system administrator to start and stop system
daemons (processes) by hand. This is sometimes necessary when processes go
wrong, but is also useful to test updated rc scripts. Note that system processes
should always be stopped in this way, rather than simply using the kill command,
because some system processes may also require other processes to be stopped
and/or files (especially lock files) to be cleaned up.
The scripts in this directory are hard links to their appropriate S scripts and K
scripts found in the other directories. They do not have the S or K prefix because
the administrator explicitly passes a start or stop parameter depending on whether
the script should start or stop something.
Administrators usually create new run control scripts in this directory, and then link
them into the appropriate /etc/rc?.d directory with a K or S name and corresponding
number. Thus the administrator may define the run-level in which the processes are
started and stopped, and the order in which this occurs.
shutdown
halt
reboot
telinit
By default shutdown will take the system to run level S (single user mode). The
shutdown command will broadcast a warning message to all users who are currently
logged onto the system that it is about to go down. It will not inform any users who
may be NFS mounting directories. Use the rwall command to inform them.
The options available with this command are as follows :y shutdown the system with no operator intervention.
g A grace period before shutdown occurs (in seconds).
i Specify the run level to change to. Choices are 0, 1, 2, 5 & 6.
When in single user mode typing ^D (control-D) will move the system back to the
default run level (run level 3).
Note : It is good practice to exit any GUI environment (eg OpenWindows or CDE)
and change directory to root before running shutdown.
trinity$ halt
sync file systems [2] [2] [3] [3] [4]
ok
Using either of these commands will not broadcast any warning messages to the
users. The commands begin the shutdown process immediately.
The reboot utility restarts the kernel. The kernel is loaded into memory by the
PROM monitor, which transfers control to the loaded kernel.
Although reboot can be run by the super-user at any time, shutdown(1M) is
normally used first to warn all users logged in of the impending loss of service.
The reboot utility performs a sync(1M) operation on the disks, and then a
multi-user reboot is initiated.
The init command can move the system to any of the run levels. It is somewhat
more direct that shutdown, however, giving no opportunity for users to logout.
Devices
Devices
There are a number of mechanical
devices which increase sexual
arousal, particularly in women.
Chief among these is the
Mercedes-Benz 380SL convertible.
P. J. O'Rourke
Local Devices
Local Devices
Local devices are those which are directly
connected to the machine
These can include
Hard Disk Drives
CDROM Drives
Tape Drives and Jukeboxes
Controller number
Target ID or SCSI ID
Drive number or LUN
Slice or partition
Examples include
c0t0d0s0
c0t6d0s0
ok devalias
screen /sbus@1,f8000000/bwtwo@3,0
ttyb /zs@1,f1000000:b
ttya /zs@1,f1000000:a
keyboard! /zs@1,f0000000:forcemode
keyboard /zs@1,f0000000
disk /sbus/esp@0,800000/sd@3,0
net /sbus/le@0,c00000
cdroma /sbus/esp@0,800000/sd@6,0:a
cdrom /sbus/esp@0,800000/sd@6,0:c
tape /sbus/esp@0,800000/st@4,0
floppy /fd
tape0 /sbus/esp@0,800000/st@4,0
tape1 /sbus/esp@0,800000/st@5,0
disk3 /sbus/esp@0,800000/sd@0,0
disk2 /sbus/esp@0,800000/sd@2,0
disk1 /sbus/esp@0,800000/sd@1,0
disk0 /sbus/esp@0,800000/sd@3,0
scsi /sbus/esp@0,800000
ok
Partitions
Partitions
Logical divisions within each physical disk.
- A single range of contiguous blocks
- A physical dis k may have up to eight partitions
Why Partition?
Why Partition?
Simplifies Administration
Backup individual partitions
OS updates may only affect specific partitions
Partitions can exist on external disks
Performance Enhancement
Reduces seek time
Localises fragmentation
Partitions can be configured to suit file sizes
Partition Tables
Partition Tables
The Partition table of a disk is held in a Volume
Table of Contents (VTOC)
Partitions must be contiguous and must start
and end on cylinder boundaries
A Partition is defined as an offset and a size
O ffset
P artition 0
P artition 1
P artition 6
P artition 7
Size
55
Size
74
Size
167
Size
105
55
129
296
Initial partitioning is carried out at installation time and ensures there are no
overlapping or non-contiguous partitions. So, the first partition starts on cylinder 0
and continues through to the end of cylinder 54. The next partition then starts on
cylinder 55 and so on.
Should partitions need to be changed after installation time then the format utility is
available in Unix for this.
The output from prtvtoc reads the disk label and returns the partitioning
information.
[-f]
[-h]
[-s]
device
NAME
prtvtoc - report information about a disk geometry and partitioning
SYNOPSIS
prtvtoc [-fhs] [-t vfstab] [-m mnttab] device
DESCRIPTION
The prtvtoc command allows the contents of the VTOC (volume
table of contents) to be viewed. The command can be used
only by the super-user.
The device name can be the file name of a raw device in the
form of /dev/rdsk/c?t?d?s2 or can be the file name of a
block device in the form of /dev/dsk/c?t?d?s2.
prtvtoc output
prtvtoc output
trinity$
trinity$ prtvtoc
prtvtoc /dev/rdsk/c0t1d0s2
/dev/rdsk/c0t1d0s2
** /dev/rdsk/c0t1d0s2
/dev/rdsk/c0t1d0s2 partition
partition map
map
**
** Dimensions:
Dimensions:
**
512
512 bytes/sector
bytes/sector
**
80
80 sectors/track
sectors/track
**
19
tracks/cylinder
19 tracks/cylinder
**
1520
sectors/cylinder
1520 sectors/cylinder
**
3500
3500 cylinders
cylinders
**
2733
2733 accessible
accessible cylinders
cylinders
**
** Flags:
Flags:
** 1:
1: unmountable
unmountable
** 10:
10: read-only
read-only
**
First
Sector
Last
First
Sector
Last
** Partition
Sector
Count
Sector
Partition Tag
Tag Flags
Flags
Sector
Count
Sector Mount
Mount Dir
Directory
ectory
00
22
00
0
62320
62319
00
0
62320
62319
11
33
01
62320
197600
259919
01
62320
197600
259919
22
55
01
00 4154160
01
4154160 4154159
4154159
66
44
00
259920
3894240
4154159
00
259920
3894240
4154159
The format utility can only be run with root privileges and is a suite of programs
which allow the administrator to carry out a range of functions on the disk. When
format is run it will identify all disks known to the system. If the new disk is not
listed by format then there is no entry in /dev and /devices. A reconfiguration boot
will be required.
select a disk
select (define) a disk type
select (define) a partition table
describe the current disk
format and analyze the disk
repair a defective sector
write label to the disk
surface analysis
defect list management
search for backup labels
read and display labels
save new disk/partition definitions
show vendor, product and revision
set 8-character volume name
Menu choices can be abbreviated to two letters. The partition option is used to
partition the disk selected in in the previous menu.
Blocks
(0/0/0)
(0/0/0)
(1254/0/0)
(0/0/0)
(0/0/0)
(0/0/0)
(0/0/0)
(0/0/0)
0
0
406296
0
0
0
0
0
The modify option can only be used on an unmounted disk. It allows you to specify
the size of each partition on the disk (except partitions 2 and the Free Hog partition)
but it will not allow you to change either the Tag or the Flag.
The Free Hog partition is used to store all the disk space and this contracts as space
is allocated to each partition.
In the above example we will be creating three partitions as follows :Partition 0
50 Mbytes
Partition 1
125 Mbytes
Partition 7
The rest (Free Hog)
size
size
size
size
size
of
of
of
of
of
partition
partition
partition
partition
partition
Tag
root
swap
backup
unassigned
unassigned
unassigned
usr
unassigned
Flag
wm
wu
wu
wm
wm
wm
wm
wm
'1'
'3'
'4'
'5'
'6'
[0b,
[0b,
[0b,
[0b,
[0b,
0c,
0c,
0c,
0c,
0c,
Cylinders
0 - 316
317 - 1107
0 - 1253
0
0
0
0
1108 - 1253
0.00mb]:
0.00mb]:
0.00mb]:
0.00mb]:
0.00mb]:
125mb
<return>
<return>
<return>
<return>
Size
50.15MB
125.14MB
198.39MB
0
0
0
0
23.10MB
Blocks
(317/0/0)
(791/0/0)
(1254/0/0)
(0/0/0)
(0/0/0)
(0/0/0)
(0/0/0)
(146/0/0)
102708
256284
406296
0
0
0
0
47304
The modify option takes care of sizes and offsets and ensures there are no
overlapping or unused space. Sizes can be specified in either Blocks, Cylinders or
Mbytes and modify will always round up or down to the nearest cylinder boundary.
The table name is optional and can be up to eight characters in length. If you want
to include spaces then the name must be in quotes.
The label option at the end of modify writes the new partition table back to the disk.
File Systems
File Systems
File systems are ways of organising the way
data is stored on disks
The default file system in Solaris is ufs
Another popular file system is Veritas journaling
VxFS
Journaling file systems often provide better resilience
and faster recovery than non-journaling file systems
Journals should be stored somewhere sensible
- Journal in swap may be fast, but does not survive a
reboot, thus useless.
Media errors
Media errors
Errors occur on all media
Disk, tape, CDROM
Disk errors are reported to the console window
Error messages are also logged in the file
/var/adm/messages
Error for command 'read(10)' Error Level: Retryable
Requested Block 2422272, Error Block: 2422283
Sense Key: Media Error
Vendor 'SEAGATE':
ASC = 0x11 (unrecovered read error), ASCQ = 0x0, FRU = 0x0
Error for command 'read(10)' Error Level: Retryable
Requested Block 2422272, Error Block: 2422283
Sense Key: Media Error
Vendor 'SEAGATE':
ASC = 0x11 (unrecovered read error), ASCQ = 0x0, FRU = 0x0
NAME
fsck - check and repair file systems
SYNOPSIS
fsck [-F FSType] [-m] [-V] [special...]
fsck [-F FSType] [-n | N | y | Y] [-V] [-o FSTypespecific-options] [special...]
DESCRIPTION
fsck audits and interactively repairs inconsistent file system conditions. If the file system is inconsistent the
default action for each correction is to wait for the user
to respond yes or no. If the user does not have write permission fsck defaults to a no action. Some corrective
actions will result in loss of data. The amount and severity
of data loss can be determined from the diagnostic output.
Backup: Principles
Backup: Principles
Backups must be rigorously performed
Follow a well defined strategy
Backup: Principles
Store backup media properly
Keep away from any electro-magnetic fields
Store off-site if possible
[-c]
[-r]
[-t]
[-u]
[-x]
[-f filename]
The tar command is commonly used to backup files and directories. It can be used
by any user and is relatively simple in its syntax. In general tar is very portable
between different platforms and Operating Systems but has the drawback of not
being able to handle multiple-volumes.
When using tar , files and directories are all compacted into one single file (a tar
file) and this is specified with the -f filename option. Normally this is a device,
such as /dev/rmt/0, but can also be a file. This is very useful if you wish to email a
number of files and directories to another person. By creating a single tar file it is
much easier to send.
/dev/rmt/0 ./games
. . . . . . . .
examples.tar
. . . . . . . .
. . . . . . . .
Take care when using tar to always specify the relative pathname of the files and
directories to be archived. This will ensure that the archive is portable and may be
restored.
By using an absolute pathname when writing the archive, the files can only be
extracted into exactly the same directory path. This tends to limit the portability of
the files being archived.
[-i]
[-o]
[-t]
input (read)
output (create)
list
Backup Commands: dd
Backup Commands: dd
dd provides access to raw devices
dd [option=value]
of=/dev/rmt/0
. . . . . .
| tar xvBpf . . . . . .
The dd command stands for copy and convert and is literally a bit-copier. For this
reason it is useful when converting data between raw physical devices, and for
copying the entire contents of one disk to another disk or for duplicating tapes.
It is not usually used for backup purposes as it is slow and provides little or no
verbose output. However, when combined with utilities such as tar, it supports
remote backups.
In the final example above dd is used to convert the byte ordering of the data on
tape, before passing this data to tar for extraction. Such a command would be
useful when reading tapes on a Sun system which had been written on a byte
swapped machine such as those produced by Silicon Graphics.
The copy-and-convert utility is called dd rather than cc, because when it was
written for Unix cc had already been claimed by the C compiler. dd was the
next best thing!
dd is particularly useful for making backups of CDs to ISO9660 image files.
Backup Commands: mt
Backup Commands: mt
mt provides controls for magnetic tape drives
mt [-f tape_name] command [count]
fsf
bsf
rewind
retention
erase
#
#
#
mt -f /dev/rmt/0 rewind
mt -f /dev/rmt/0n fsf 2 ; ufsrestore -rvf /dev/rmt/0n
The /usr/bin/mt command is used to position and control a magnetic tape. The mt
command is useful when several archives (for example, ufsdump, tar, cpio) must
share the same tape. mt allows early archives to be scanned past, so that subsequent
backups appear later on the tape.
Note that in order for several backups to share a tape it is important that the device
is identified by its no - rewind name. /dev/rmt/0n tells the device driver
controlling access to the tape drive not to rewind when the device file is closed.