Unix Administration
Unix Administration
Unix Administration
CONTENTS
Lecture 1 Introduction to Unix Administration Introduction to Unix OS Introduction to Operating System History of Operating System Features of Unix Operating System Unix Architecture Unix File System System Administration 15 1
Lecture 2
Unix Refresher Login Logout Unix Command date cal finger id man who
Lecture 3
Files and Directories Command Unix Directories File name Expansion Working with Files Comparing Files Printing Files
25
Lecture 4
Working with IO Redirection, Pipes and Filters IO Redirection, Pipes and Filters Standard Input IO Redirection Pipes Filters Unix Process Processes Switching between Processes Introduction to Shell Programming Shell Programming Types of shell Processing command by shells Variable Types of variables Command substitution
40
Lecture 5
59
ii
Lecture 6
Advanced Shell Scripts Advanced Shell Scripts The echo command Read command The expr command The if Statement The for statement The while statement The until statement The case statement The break command The Continue statement The trap command
Lecture 7
Booting and Shutting Booting Types of booting Boot Process System Boot Sequence Init process Daemons Run Levels Overview of Run levels Run levels functions Run level identification Run control scripts Single/multi user mode Shutting down
83
Lecture 8
User and Group Management Managing Group Groupadd command Groupmod command Groupdel command Managing User Useradd command Usermod command Userdel command
94
Lecture 9
Device and Disk Management Device and Disk Management Device Geometry Partitions
108
iii
Lecture 10
Device naming Adding hard disks Character and block mode devices 121
Introduction to File System Local Based File System Types Ofs (HDD) Floppy CD-ROM The ext2 File System Raw & Block device Boot block Super block Backup super block Cylinder groups Inodes Types of File System Mounting the Local Based File System Common Commands for File System Management Managing Disk Use (Tasks)
Lecture 11
Network File system Network File System (NFS) nsfd mountd lockd statd rpc.portmapper Starting and Stopping the nfs Daemons To start and stop NFS Daemons Configuring nfs Servers and Clients Mounting the Remote File System NFS-mounting the File System Mounting the NFS File System
145
Lecture 12
Virtual File System Virtual File System Types of Virtual File Systemc Swap File System Process File System Process File System What is /proc File System? What is in this File System?
157
Lecture 13
Security
163 iv
Security Types of Security File Server Security System Level Security 177
Lecture 14
Printer Management Printer Management Configuring Print Services Setting up the Printer Setting up the Print server Setting up the Print client Print service Architecture Print Service Directories Print Functions Starting and Stopping Daemons Configuring Printer Printing a file To print a file To view the status of a printer Canceling the print job
Lecture 15
Backup and Recovery Backups tar command cpio command dd command mt command dump/restore command
186
Lecture 16
Space Management Space Management Quota Quota set up for a user Turning quotas on Setting up quotas for single user Setting quotas for multiple user To check quota consistency Checking quotas on a file system
201
Lecture 17 Scheduling of System Events Scheduling of System Events Types of Scheduling Events Jobs Scheduling Using Crontab Jobs Scheduling Using At
208
Lecture 18
Performance Monitoring Managing System Performance Process Management Process States Process Management Commands ps command Listing Processes Network Management Network Types of network Classification of network LAN Fundamentals Characteristic of LAN Features of LAN LANs and OSI Reference Model OSI Reference Model LAN interconnection Basic Network design Wide Area Network TCP/IP Reference Models Protocols in TCP/IP Protocol Suite Testing the TCP/IP using IPCONFIG and PING IP address
215
Lecture 19
227
Syllabus
245
vi
Lecture 1
Objectives
In this lecture you learn the following
Understanding the concept of UNIX Operating system Knowing about Unix File System Able to understand the features of UNIX Operating System Understand the UNIX Architecture
will
UNIX Administration
Coverage Plan
Lecture 1
1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 Snap Shot Introduction to Operating Systems History of Unix Operating System Features of Unix Operating System Unix Architecture Unix File System What is System Administration Short Summary Brain Storm
Introduction to Unix OS
Unix Administration Introduction to Unix OS Introduction to Operating System History of UNIX Operating System Features of UNIX Operating System Unix Architecture Unix File System
Running a Program
When a filename is entered on the terminal at the command line, the operating system interprets the command, loads the program into computers memory and executes the program. When more than one program/process run simultaneously on the system, the operating system takes care of scheduling the CPU for various processes, managing the computers memory and other related tasks.
UNIX Administration When the computer is shutdown, the operating system ensures that the hardware is shutdown correctly. Without an operating system, no application can run.
Multi-user OS
Multi-user refers to an OS that allows multiple users to use the system simultaneously. The theory of multi-user system is to approach 100% computer utilization while reducing the cost per user. A single user cannot use the printer, disk, memory or CPU 100% of the time. But multiple users can increase the use of these devices and resources by having an OS that manages the resources for them.
Multi-tasking system
Multitasking refers to an OS that executes multiple tasks simultaneously. Unix refers to a task as a process. A user can run several commands in the background while executing another command in the foreground. When a background task is being executed, the user can continue doing another task e.g., printing a large document can be performed in the background while editing some other document in the foreground.
Portability
Unix is highly portable. Portability is the ability of the software that operates on one machine to operate as efficiently on another, different machine.
Job Control
Job Control on Unix refers to the ability to control which job is to be executed in the foreground, background or suspended. Using Job control to be the productivity of a user can be used by allowing multiple tasks to be juggled back and forth between background, foreground and suspended states.
Hierarchical Structure
Unix uses a hierarchical structure to store and maintain files. This structure allows maximum flexibility for storing information to resemble its real life structure. Multiple users may be grouped by corporate departments. An individual user, you may group the data by project or subject.
Unix Shell
The shell is a very powerful and dynamic Unix utility. It is the primary interface to the OS (Kernel). It can be interactively programmed or used to write scripts that help to solve simple to complex problems.
Device Independence
Unix system considers all the devices that are connected to it as files. It hides the machine architecture from the user, makes it easier to write programs that run on different hardware implementations.
System Security:
Being a multi-user OS, Unix offers protection to one users information from other users. It maintains a list of users who are allowed to access the system and keeps track of the files and resources that each user is authorized to use.
Communication
UNIX Administration The Unix system has several built in programs, that enable the user to communicate, transfer files across different Unix systems and between Unix and other OS system.
Other Applications
Kernel
Hardware
Other Applications Fig 1.1 The Unix operating system is commonly called as Kernel. It provides an interface for all other Unix programs to use the hardware resources. This concept allows the higher level programs to be hardware independent. When the user logs in to Unix communicates with the kernel through the shell program. It does not make itself available for the end user. The Kernel provides the basic services of System initialization, Process management, Memory management, File System management, Communication facilities and Programmatic interface through system calls. Programs such as the shell and editors (ed and vi) that are shown in the outer layers interact with the Kernel by invoking a well defined set of system calls. The system calls instruct the kernel to perform various operations for the calling program and exchange of data between the kernel and the program. One of the prominent features of the Unix system is its wide variety of powerful utility programs. A utility can be used to locate system information, manage files or the contents of files and manipulate the output of other utilities. The shell is a utility program that acts as a command interpreter. It is the primary interface to the kernel. The shell is a command language as well as a programming language. As a command language, it can be used to communicate interactively with the Kernel. As a programming language, users can write shell scripts to solve the various problems. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Introduction to Unix Administration Several programs shown in the figure are in standard system configuration and are known as commands. Over 200 utility programs (commands) are supplied with Unix system. These are also used to solve complex problems. In addition to utility programs, there are a number of Unix-based application programs like word processors, spreadsheets, database managers and language processors which form the outer most ring in the architecture.
Structureless Files
There is no internal structure imposed on the content of the files. Any structure given by the user can be used.
Security
Unauthorized users can be restricted from using a file.
Device independent
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
UNIX Administration Input and output from a device are processed as if it were in a file. Therefore, programs that process data can also process data to and from a device.
Types of files
A Unix file system may contain six different types of files:
Regular files Directories Special files Named pipes (FIFO) Links Symbolic Links
Regular files
A regular file (also known as an ordinary file) contains arbitrary data in zero or more data blocks stored within a file system. These files may simply contain ASCII text , or binary data. Individual applications may store their files in a specific format. There is no structure imposed by the operating system about how a regular file must be formatted. Data blocks belonging to a regular file may not necessarily reside on the disk in a contiguous order. However, the Unix operating system hides this side effect from the user and presents a file as if it were a contiguous stream of bytes; the user need not be concerned with a files underlying storage structure. Unix identifies the files by a unique number called the index node (inode) number. A file has only one inode number, although it may have many filenames. The inode numbers are maintained in a directory file along with the related filenames.
Directory files
Directories are a collection of files. For instance, a user may need to group all his project files into one directory. Each directory has a name and each file within the directory has a filename. Directories are special types of files since they provide mapping between the names of files and the files themselves. As a result, the structure of directories defines the structure of the file system as a whole. The directory consists of a table containing two fields: inode number filename (to symbolically reference the inode).
Special Files
Special files do not contain data. Instead, they provide a mechanism to map physical devices to file names in a file system. Each device supported by the system, including memory, is associated with at least one special file. Special files have associated software incorporated into the Kernel called device drivers. There are two types of special files : block-special and character-special. A block-special file is associated with a block structured device such as a disk, which transfers data to the machines memory in blocks, typically made up of 512, 1024 bytes. A character-special file is associated with any device that is not necessarily block structured. Terminals, system console, serial devices, tape drives are character-special files.
Links
The Unix file system provides a facility for linking files together with different file names. This facility is called linking. The purpose of linking files together is to allow a single program to administer different Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Introduction to Unix Administration names. Actually only one copy of data is stored in the file system. The linked files share the same inode number and only a directory entry is made for the file.
Symbolic links
A symbolic link is a data file containing the name of the file to which it is supposed to be linked to. A symbolic link can be created even if the file it is supposed to be linked to does not exist. The advantage of having symbolic link is when the file system has lesser in space but a new software package has to be installed in it, a directory can be made on another file system which is then symbolically linked to the name of the expected installation directory. With symbolic links, both a directory entry and new inode are created. Additionally, a single data block is reserved for it containing the full pathname of the file it references.
FIFOs (Pipes)
Pipes are used to join two or more Unix processes together allowing the data to flow from one process to another without storing the data on the disk. A pipe file is a special file that buffers up data received in its input so that a process that reads from its output receives the data on a first-in-first-out basis (FIFO). No data is associated with a pipe special file although it uses up a directory entry and inode.
/bin
/usr
/lib
/tmp
/dev
/home
The top level directory is called the root directory and is denoted by a single / (forward slash). All the directories and files belongs to the root directory. Following are the list of standard directory names in the Unix file system. / /etc Root directory. This is the parent of all the directories and files in the Unix file system. System configuration files and executable directory. Most of the administrative, command-related files are stored here.
UNIX Administration /bin /usr /lib Command-line executable directory. executables This directory contains all the Unix native command
Architecture dependent and architecture independent sharable files The library files for various programming languages such as C are stored in this directory
/tmp This directory is used for the temporary storage of files /dev Device directory containing special files for character- and block-oriented devices such a printers and keyboards. A file called null existing in this directory is called the bit bucket and can be used to redirect output to nowhere
System Administration involves planning, installing, and maintaining computer systems. The system administrator takes care of administration. System Administrator has to install and configure the operating system, add new users, back up the system(s), keep the systems secure, and ensure their running condition. Installing, running, and maintaining all the major Unix variants is only part of the art of the system administration. There is a significant nontechnical component to being a system administrator, especially in terms of planning, organizational, and people skills. As computers become more and more pervasive in business, system administration becomes a critical in many organizations. The administrator has to understand the systems that he is responsible for, the users, and purpose.
10
Introduction to Unix Administration but has been more powerful and stable even in the earlier versions of Unix when compared than the latest versions of Windows and Windows NT.
Network Centricity
Networking has become an integral part of Unix. The ability to share files, support network logins, share information about network configuration, and run applications across a network is included in all the major Unix distributions. It is a natural extension of the base operating system, not an application that is designed by an individual vendor, with idea of networking and administration that has to be purchased separately. When configured to allow networking, anything that can be done at the console (main keyboard and monitor) of a Unix system can also be done at another system through a network connection. (They are referred to as remote nodes or remote systems.) Actually many server systems, such as Web servers and file servers, have consoles with very limited capabilities (such as a text-only terminal), and are deliberately designed with the idea of doing as much administration as possible from remote nodes outside the data center.
Unix is Heterogeneous
Unix is being frequently criticized for lacking consistency between versions, vendors and even applications. Unix is not the product of any single corporation or group, and this does have a significant impact on its personality. Linux is probably the ultimate expression of UNIXs collective identity. After Linus Torvalds has created the Linux kernel and announced it to the Internet, people from all over the world began to contribute to the Linux Operating System. Obviously, Linux reflects a different views on how computers should work. Unix does too. Unix has historically been divided into two major variants: AT&Ts Unix System V and The University of Californias BSD Unix. Most of the major vendors are now moving toward System V system, but many BSD extensions will always remain.
Supporting Users
Users are the customers. The network would be a single computer, without them probably running a frivolous application like Doom and generating no business or creating no new sales. Creating User Accounts The most fundamental thing that an administrator can do for a user is to create an account. Unix accounts are contained in the /etc/passwd file with the actual encrypted password being contained in either the passwd file or the /etc/shadow file if the system implements shadow passwords.
Supporting Systems
Unix is supports the systems. Systems have to be built, backed up, upgraded, and fixed. Adding Nodes A frequent system administration task is adding new nodes to the network. It is also one of the tasks of the system administration that can truly benefit from some planning and insight. Not all the systems are created equal, and not all of them are used for the same purpose. Spending some time in understanding what the network is really used for and then applying that to the systems is key to
11
UNIX Administration network planning. Workstations should have well defined roles and should be configured in accordance with those roles. When the systems are designed and evaluated, some of the questions that an administrator can ask are:
Will users be able to access all or some of the systems? Do users need to access more than one system? Are there system that users should never access? What network file systems will each workstation need to access? Are there enough that automount would help? What network services, such as telnet, remote logins, sharing file systems, and e-mail, do workstations need to provide? Can each service be justified? What networks will workstations need to access? Are there networks that should be inaccessible from others?
These questions should help the System Administrators in developing a profile for each workstation. Following a profile makes workstations easier to build, maintain, and troubleshoot. Moreover it makes them more reliable since they tend to be less complex. Backups Files may get corrupted, lost, accidentally overwritten, or deleted. Backups safeguard the files from such situations. Unix provides several backup tools.
Administration Resources
A system administrator needs minute details and help to carry out the job of system administration successfully.
12
Introduction to Unix Administration User commandscommands like ls, tar, and cpio System callsC programming functions that are considered system calls, like opening and closing files C library functionsC programming functions that are not considered system calls, like printing text File formatsdescriptions of file layouts, such as hosts.equiv and inetd.conf Headers, Tables and Macrosmiscellaneous documentation, such as character sets and header files, not already covered Games and Demosgames and demo software. (Even Doom for Unix has a man page!)
This is a generalized table of contents. BSD and System V started out with slightly different section schemes, and vendors tend to add their own sections and make their own improvements.
13
UNIX Administration
1. 2. 3. 4. 5.
Brief about the roles of system administrator. Mention how the system load performance is measured. Is Unix operating system heterogeneous? What does it mean ? What is the use of Network Centricity? What are the various tasks of system administration?
14
Unix Refresher
Lecture 2
Unix Refresher
Objectives
In this lecture you learn the following
About Unix Commands Makes the user conversant with UNIX directory commands and their usage.
will
15
UNIX Administration
Coverage Plan
Lecture 2
2.1 Snap Shot 2.2 Logout 2.3 Unix Command 2.4 Short Summary 2.5 Brain Storm
16
Unix Refresher
Login
Once the user name and password are provided, the user can access the system. The system prompts for the user name by printing login.
login:
The user should respond to this prompt by typing a valid username (supplied by the system administrator) called the user_id. On pressing the <Enter> key, the next line prompts for a password:
Password:
Password is a sequence of letters and digits that is used to verify if the user is allowed to use the user_id. Initially, the password is supplied by the system administrator. Later the user can change it to some secret key. It is password that identifies the authorised users of a system. After the valid username and password have been entered, the # prompt is displayed on the screen. The # prompt indicates that theUNIX system is ready to accept commands.
Example
UNIX(r) System V Release 4.0 (radiant) login: root Password Last login: Sat May 15 12:00:00 #
Root User
There is a user id called root or super user. This user has special privileges. The root user has access to all parts of the UNIX operating system. There are no files that cannot be read by the super user, there are no portions of the file system inaccessible to the super user and there are no UNIX commands unavailable Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
17
UNIX Administration to the super user. The super user controls all aspects of UNIX system usage and configuration. The super user is entitled to the special prompt: #.
2.2 Logout
Unix Administration Logout Logout after use the system, you should log out Prevents other people from accidentally or intentionally accessing files Makes others the system available for their uses
When the user has completed using the system, he/she user should log out. This will prevent other people from accidentally or intentionally getting access to files. It will also make the system available for other users. The normal way to log out is to type exit. Another way of logging out is to type the end-of-file character (typically Control +D) as shown below: # exit # ^D
Note : It is always safe to logout when a user no longer wants to work on the system.
Unix Commands
A series of characters. These characters consist of words that are separated by whitespace. The first word is the name of the command. The rest of the words are called the commands arguments. The arguments give the received command information or specify varying behavior of the command.
The # prompt is called the command prompt or shell prompt. A UNIX command is a series of characters that are being typed. These characters consist of words that are separated by whitespaces. Whitespace is the result of typing one or more Space or Tab keys. The first word is the name of the command. The rest of the words are called as the arguments of the command. The arguments give the command information that it might need, or specify varying behavior of the Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
18
Unix Refresher command. To invoke a command, the command name must be typed, followed by the arguments. The shell collects all the characters that are typed until the enter key is pressed and interprets them.
date
This command is used to display the current date and current time of the system.
Syntax
date [+<string> <options>] The following options can be used in the date command %D %d Displays the date in MM/DD/YY format Displays the day of the month(01-31)
The following options can be used with the date command to display the weekdays and months in the abbreviated format: %a %A %b %B Displays abbreviated weekdays(Sun-Sat) Displays abbreviated weekdays (Sunday-Saturday) Displays abbreviated months (Jan-Dec) Displays abbreviated months (January-December)
The following options can be used with the date command to display the current time. %H %M %S %I %r %n Displays the hour Displays the minutes Displays the seconds Displays the IST time Displays the time with meridian (AM/PM) Displays the output in the newline
Practice 2.1
The following example shows how to display the current date and time. # date
Sat May 15 14:09:01 GMT 1999 As seen above, the date command gives the day of the week, month, day, time (24 hour clock, Greenwich Meantime) and the year. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
19
UNIX Administration
Practice 2.2
The following example shows how to display the date with strings. # date + Current Date : %D
Current Date : 09/22/00 In the above example the date is displayed along with the string Current Date.
Cal
The cal command generates a simple calendar as the output. By default, the output is the calendar for current month.
Syntax
cal [ [month] year] where month specifies the month to be displayed, represented as a decimal integer from 1 (January) to 12 (December). The default is the current month. Year specifies the year for which the calendar is to be displayed, represented as a decimal integer from 1 to 9999. The default is the current year.
The following example shows the usage of the cal command. # cal
Practice 2.3
May 1999
Tu W
Th F
S 1
2 9
8 15 22 29
10 11 12
13 14 20 21 27 28
16 17 18 19 23 24 25 26
In this example the calendar for the current month is displayed as no options have been specified.
20
Unix Refresher Note :Year must be entered as a four-digit number. calendar for the year 99 A.D., and not the year 1999. If only one argument is given to the cal command, it is considered as the year and not the month. For example: cal 07 will display the calendar for the year 07 A.D. and not the month July.
Finger
The finger command displays a detailed list of the user information. If a user name is specified, information only for that user is displayed. If no user name is given, information for all users currently logged in to the system is displayed.
Syntax
finger [-lmsp] Options are: -l Produces a multi-line format displaying all of the information described for the -s option as well as the users home directory, home phone number, login shell, mail status, and the contents of the files .plan and .project and .forward from the users home directory. Prevents matching of user names. User is usually a login name; however, matching will also be done on the users real names, unless the -m option is supplied. All name matching performed by finger is case insensitive. Prevents the -l option of finger from displaying the contents of the .plan and .project files. Finger displays the users login name, real name, terminal name and write status (as a * after the terminal name if write permission is denied), idle time, login time, office location and office phone number. Login time is displayed as month, day, hours and minutes, unless more than six months ago, in which case the year is displayed rather than the hours and minutes.
-m
-p -s
The finger command displays in multi-column format the following information about each logged-in user: + user name + users full name
+ terminal name (prefixed with a * (asterisk) if write-permission is denied) + idle time + login time + host name, if logged in remotely The following options can be used -f Suppresses the printing of the header line (short format).
Practice 2.4
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
21
UNIX Administration The following example shows the usage of the finger command. # finger root
Login name: root In real life: Super-User Directory: / Shell: /sbin/sh On since May 15 13:37:52 on pts/0 from 80.0.0.98 25 minutes Idle Time Mail last read Fri May 14 20:22:14 1999 No Plan. The above example shows that the finger command displays information about the user such as login name, directory, idle time, time at which the last mail was received etc.
Id
This command displays the user ID, user name, group ID, group name. The system uses this user ID to identify the files owned by the user. The group ID works the same except it is used for the group level identification.
Syntax
id [username] If no user operand is provided, the id utility will write the user and group IDs and the corresponding user and group names of the invoking process on the terminal. The following options can be used in id command -g -u displays the output of group id displays the output of user id
Practice 2.5
The following example shows the usage of the id command.
# id uid = 102(sunil) gid = 40(radiant) It can be seen that the id command displays the user id and the group id. In brackets are the username and the group name respectively.
Man
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
22
Unix Refresher The man command enables information to be found in the online manuals by specifying a keyword. The manual entry is called a man page, even though it is often more than one page long. There are common sections to man pages. Depending on the command, some or all of the sections may be present. At the start of the man page is the Name. This is usually a one-line that give the commands name along with a phrase describing what it does. Next is the Synopsis, which gives the commands syntax including its arguments and options. In the Synopsis, if any argument is enclosed in square brackets ([ ]), then the argument is optional. If two elements of the syntax are separated with a vertical bar (|), then either one or the other (but not both) of the items is allowed. The other sections are Description, Files and See Also.
For example, the following command would display the man pages for the pwd commnad
# man pwd
Who
who prints information about users who are currently logged on. If given no non-option arguments, who prints the following information for each user currently logged on: login name, terminal line, login time, and remote hostname or X display. The who command enables you to find out the users on the system.
Syntax
who [OPTION] Options -H -i -q heading print line of column headings adds user idle time as HOURS:MINUTES, or old counts and prints only the login names and the number of users logged on. [am i]
Who am i
It displays the current username, terminal type, date and login time
Practice 2.6
The following example shows the usage of the who command. # who
23
UNIX Administration
System Commands
The uname command displays the name of the operating system. The logname command displays the login name of the current user. The hostname command displays the host name of the unix operating system.
24
Lecture 3
Objectives
In this lecture will learn following
Able to create components directories and
you the
manipulating
Shows how to work with files Various File manipulating commands Knowing about File printing commands
25
UNIX Administration
Coverage Plan
Lecture 3
3.1 Snap Shot 3.2 Unix Files & Directories 3.3 Filename Expansion 3.4 Working with Files 3.5 Comparing Files 3.6 Printing Files 3.7 Short Summary 3.8 Brain Storm
26
Unix Directories
Directories provide a convenient means of organizing files. Since, in the UNIX system, the file system has a hierarchical structure, a directory can further contain sub directories.
pwd
pwd command displays the absolute path of the present working directory.
Syntax
pwd For example, consider # pwd /user/sunil The output from this command verifies that the current working directory is /user/sunil.
27
UNIX Administration
Absolute pathname: It is the complete path name from the root that UNIX must follow to reach a particular file. Absolute path name starts with a slash (/). For example, to access the file myfile residing under the sub-directory files in the home directory, /usr/sunil, the notation is as follows /usr/sunil/files/myfile The initial slash (/) refers to the root directory. The following slashes separate the names of subdirectories. The final slash denotes the actual file name. Relative Pathname: Absolute pathnames could be tedious to type if they are very long. In such cases a relative pathname can be used. This is the pathname that is shortened in relationship to the present directory position. Relative path name is represented by a dot (.). If the current working directory is /user/sunil, a particular file can be accessed relative to the present directory. For example, to access myfile, instead of starting the search from the root, relative referencing starts from the present directory to reach myfile as shown below. ./files/myfile The dot represents the present directory. The following slashes separate the subdirectories and the final slash denotes the actual file name.
cd
The cd command enables the user to change from the present working directory to a new directory.
Syntax
cd [directory] directory is the name of the directory to be changed to. where
Let us assume the present directory is /user/sunil To move to another directory, the cd command has to be used with the path name as follows # cd /usr/ajay Either the absolute pathname or the relative pathname can be used to change directories. Note: cd cd cannot perform the requested directory change if it does not exist . without any argument will always take the user to his/her HOME directory.
cd ../ takes the user to the parent (previous directory) i.e. one level up. cd ../../ takes the user to the parents parent directory i.e. two levels up.
mkdir
The mkdir command is used to create new directories, thus building a hierarchy of directories to maintain files in an orderly manner. If there are hundreds of files, it is always better to organize files based on the information that they contain. For example, all files containing the personal information of the employees
28
Files and Directories can be kept under one directory, say, personal. This helps in locating files if they are categorized into subdirectories.
Syntax
mkdir [ pathname] where pathname is the path of the directory to be created.
Practice 3.1
The following example shows the usage of the mkdir command. # mkdir salary # cd salary # pwd
/usr/sunil/personal/salary The above example shows how to create a directory from the current directory (personal). In this way, directories within directories can be created. Note: mkdir command only creates a new directory. It does not change the current directory. More than one directory can be created at a time.
ls
ls command can be used to display the names of files and directories. This utility is used to know the files and subdirectories that exist within the directories. Different options can be used with the ls command to list the contents in different formats.
Syntax
ls [options] The following options can be used with ls command
29
UNIX Administration -a -C,-x -F Lists all files, including the hidden file Multi-column output with files sorted down the in column wise Puts a slash (/) after each filename if the file is a directory, an asterisk (*) if the file is an executable, and an at-sign (@) if the file is a symbolic link. For each file, prints the i-node number i n the first column of the report. Lists in long format, giving mode, ACL indication, number of links, owner, group, size in bytes, and time of last modification for each file etc. Recursively lists subdirectories encountered. Sorts by time stamp (latest first) instead of by name. The default is the last modification time.
-i -l
-R -t
Practice 3.2
The following example shows the usage of the ls command. # pwd /usr/sunil # ls
In the above example all the files and directories that exist within the /usr/sunil directory have been listed. Note : ls command lists files in an alphabetical order.
rmdir
The rmdir command can be used to remove directories when they are no longer needed. Before removing a directory it should be ensured that it does not contain any files i.e. it should be empty. If there are files in the directory when rmdir is executed, the directory will not be removed.
Syntax
rmdir [ [options] dir-name ] For example, # cd /user/sunil/fruits/ # rmdir apple
30
Files and Directories The directory apple is removed. The user has to change to the corresponding parent directory, only then the files can be deleted. Note : The directory to be removed must be empty. The empty directory has two entries, the .(dot) representing itself and the ..(dot dot ) representing the parent directory. More than one directory can be removed at a time.
One powerful feature of the UNIX system is filename expansion. It enables to work with files collectively. The group of filename-matching characters is represented by wildcards. Wildcards allow multiple files to be manipulated at the same time using a single command. Wildcards are a kind of shorthand that allows similar files to be specified without having to type multiple names. There are three types of UNIX wildcards: *, ?, []. The shell expands these wildcards, substitutes a group of valid filenames and these filenames are then given to the respective commands.
* ? []
Matches zero or more characters Matches exactly one character Matches any one of the characters in the given range
Asterisk (*)
The * is interpreted as a set of zero or more characters. It provides an easier and quicker way to search directories and access files. The following command lists all files which begin with the letter a. # ls acs a* ajay.txt
31
UNIX Administration
Range specifier []
The [ ] can be used to specify a range of characters which matches either occurrence of the character. The following command lists all the files starting with any one of the alphabets and ending in t. # ls [a-z]*t
The UNIX system provides many tools that enable to work easily with files. Among these tools are the commands that enable to create new files, copy files, remove files, move files between directories, examine the contents of the files, and so on. In this session we will learn to use some of these commands.
cat
The cat command can be used for the following purposes:
Syntax
cat [ filename] where filename is the name of the file to be created or displayed. The following example shows how to create a new file newfile using the cat command. # cat > newfile This is my new file created by cat command ^D Pressing ctrl-d marks the end of file. The contents of the file newfile can be viewed as shown below. # cat newfile This is my new file created by cat command Note the difference between two Commands. One is used to create a file and the other to display its contents. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
32
Files and Directories Redirection symbols that are used along with the cat command are as follows: > < Used to create a file Used to input the file to commands
cat command can be used to display the contents of more than one file by giving the filenames separated by a space.
cp
A copy of a file may be required for backup purposes or the user may want to use an existing file as the basis for a new document. If the original file is accidentally removed, it can be restored from the backup. These tasks are accomplished with the cp command.
Syntax
First Form cp file1 file2 where file1 is the source file, file2 is the target file. Second Form cp file1 file2 file3 . d1 where file1, file2, file3.. are the source files, d1 is the target directory. Third Form cp R where s1 d1 s1 is the source directory , d1 is the target directory, -R copies all files and subdirectories.
The following Practice 3.3how the cp command is used to copy the contents of one file into another. example shows # cp newfile file3
# This will cause the file named newfile to be copied into the file named file3. The # sign after the cp command indicates that the command has been executed successfully.
Practice 3.4
The following example shows how the cp command can be used to copy files into a directory. # cp file1 file2 file3 personal # ls personal
33
UNIX Administration
file1
file2
file3
salary
From the above example it can be seen that the files file1,file2,file3 have been copied to the directory personal. Note: If the target file is an ordinary file and it already exists, its contents are erased and are overwritten with the contents of the source file. If the target file is a directory, the source file is copied to that directory with the same name as the source. With one cp command, only one file can be copied to another file but one or more files can be copied to a directory at the same time.
mv
There are many instances where a file may have to be moved from one directory to another: The mv command allows for the movement of files in UNIX. The mv command can be used for three purposes: To rename a file with a new name To move one or more files to a different directory Rename a directory with a new directory name
Syntax
First Form mv file1 file2 where file1 is the old filename, file2 is the new name Second Form mv file1 file2 .. d1 where file1, file2, . are the names of the files to be moved, d1 is the destination directory
Third Form mv d1 d2 where d1 is the old directory name, d2 is the new directory name. In the following example the files file1, file2 are moved to the directory newpersonal. # mkdir newpersonal # mv file1 file2 newpersonal Note : The new and the old files may have the same names provided they reside in different directories. If the name of the new file is the same as that of an existing file, its contents are lost.
rm
Unwanted files can clog up a hard disk, slowing it down and making file management chores unnecessarily complicated. It is a good practice to regularly go through the subdirectories and remove the files that are not required. rm command is used to delete files that are no longer needed.
Syntax
rm [option] (filename) Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
34
Files and Directories where filename is the name of the file to be removed Option can be one or any combination of the following: -f -i -r Forcefully removes a file even if it is write-protected Interactively asks for confirming the deletion of the files Removes a directory even if it is not empty
In the following example the file file2 in the newpersonal directory is removed. # rm newpersonal/file2
ln
The ln command is used to create one or more links to a file. A link is another name for the same filename, having the same physical storage and same inode number. This means that more than one file can point to the same physical storage.
Syntax
# ln filename1 filename2 where filename1 is the name of the file on which a link is being created, filename2 is the link created on filename1. Consider the following # ln newfile file1 This will create a link for newfile and the name of the link is file1. The number of links a file has can be seen from the long listing of files. For creating a symbolic link, the s option has to be used with the ln command: Note : ln command gives more than one name to a file but the physical storage of the file is the same. The cp command makes two files with different physical storages. Inode numbers of all hard linked files are the same. A symbolic link can be created even when the file on which the symbolic link is created is not present.
Normally, many new files are created during the course of updating older files. Many versions of the same file with slight differences in the content are maintained. At some point of time, it becomes very difficult to keep track of the files and it becomes essential to cleanup the directories by removing the unwanted older versions. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
35
UNIX Administration There are utilities in UNIX that can be used to compare the contents of two files to see if they are same. If they are not, the nature of the difference can be determined.
cmp
cmp command is used to compare two files. It compares two files and displays the first instance where the files differ. If there is no difference, cmp returns no output.
Syntax
cmp file1 file2 where file1 and file2 are the files to be compared.
Practice 3.5
The following example shows the usage of the cmp command. # cat > myfile This is a demonstration of cmp command ^D # cat > yourfile This is the demonstrations of cmp command ^D # cmp myfile yourfile
myfile yourfile differ: char 9, line 1 In the above example the cmp command reports that the two files differ in the ninth character of the document, located in line 1. Note : cmp indicates only the first character at which the files differ. cmp reports the difference on a character-by-character basis.
diff
Using cmp it can only be known if the files compared are different. It neither shows the extent to which the files are different nor how different they are. The diff command compares two files for differences. It determines which lines must be changed to make the two files identical. The diff command scans two files and indicates editing changes that must be made to the first file to make it identical to the second file. Editing may include adding a line, deleting a line, changing a line, and so on.
Syntax
diff file1 file2 where file1 and file2 are the files to be compared.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University Practice 3.6
36
Files and Directories The following example shows the usage of the cmp command in comparing two files file1 and file2 # cat file2 diff login kill mv ln more pg ^D # cat file1 diff id sh mv ln ^D # diff file1 file2
2,3c2,3 < id < sh > login > kill 5a6,7 > more > pg From the above example it can be seen that lines beginning with < are found only in the first file and lines beginning with > are found only in the second file. The dashed line separates the two lines that appear in the same place in the differing files. The numerals indicate exactly where and how the differences occur. In the above output, the second and the third lines from file1 have to be changed with second and third lines of file2 to make the two files agree.This is indicated by 2,3c2,3. Similarly, 5a6,7 indicates that the lines 6 and 7 of file2 needs to be appended to file1 to make them equal. Likewise sign d can be used to delete lines from file1 if these lines do not exist in file2. Note : diff command makes changes in the first file to make it resemble second file. diff command is used to compare files on a line to line basis.
37
UNIX Administration
Unix Administration In certain cases, it may be required to take a hard copy of the documents that have been created and that are being stored in the hard disk. This requires the document to be printed on a sheet of paper. For this, a printer is to be attached to the system. The system should request the printer to print the required document. It is the task of the system administrator to setup the printer.
lp
lp spools the output to the printer queue. Spooling is the process of sending the output to a temporary storage area for later processing by the printer.
Syntax
lp filename where filename is the name of the document to be printed. The print jobs are placed in a print queue as printer requests. The request ids consist of destination printer name and a sequence number. The following example shows that the file myfile is sent to the printer hplj for printing and the request id is hplj-15. # lp myfile request id is hplj-15 (1 file)
cancel
Cancel command removes or cancels print requests made using the lp command.
Syntax
cancel request_id where request_id is the ID number given by the system when a lp request is placed. The following example shows how to cancel all queued requests that have been queued up in the printer hplj. # cancel hplj
lpstat
The print requests are spooled and they may not be performed immediately. The lpstat command to display the current status of all line printers.
Syntax
lpstat [options] Centre for Information Technology and Engineering, Manonmaniam Sundaranar University Practice 3.7
38
Files and Directories The following example shows the usage of the lpstat command. #lpstat
1524 1024
Here lpstat indicates that there are two requests in the print queue. The first request is with ID hplj-14 initated by root of size 1524 blocks on May 10th 17:34 Hrs and the second request is with ID hplj-15 initiated by sunil of size 1024 block on May 11th at 11:10 Hrs.
39
UNIX Administration
Lecture 4
Objectives
In this lecture you learn the following
commands using the concept of pipes About Filters and its command Knowing about Unix process and it types Able to switch between processes
will
40
Coverage Plan
Lecture 4
4.1 Snap Shot 4.2 I/O Redirection, Pipes & Filters 4.3 Pipes 4.4 Filters 4.5 Unix Process 4.6 Short Summary 4.7 Brain Storm
41
UNIX Administration
I/O Redirection
The shell allows the redirection of the standard input, output, and error of a command. Redirection of input/output is the capability to change the source of the input and the destination of the output. This is done by using greater than (>) and less than (<) signs.
Output Redirection
Under the UNIX system, the output from a command usually intended for standard output can be easily diverted to a file. This capability is known as output redirection.
Syntax
command > filename The above format indicates that the command is being diverted to a file filename using a > sign. Suppose the names of the logged_in_users have to be stored inside a file names. # who > names In the above example, the who command gets executed and instead of writing the output to the standard output (terminal), the output is being written to the file names. If a command redirects its output to a file and the file already contains some data, then that data is lost and the new data is overwritten. The existing contents can be retained as shown below: # echo Hi, Good Morning > salute # cat salute Hi, Good Morning # echo Hi, Good Evening >> salute # cat salute Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
42
Working with Pipes & Filters Hi, Good Morning Hi, Good Evening The second echo command uses a different type of redirection symbol >> (double greater than) sign. This sign causes the standard output from the command to be appended to the specified file. Therefore, the previous contents of the file are not lost and the new output is simply added onto the end of the first. Note : In the output redirection, the stdout can be made explicit by preceding the > by the number 1, which is the file descriptor for stdout.( # echo Hi, Good Morning 1> salute)
Input Redirection
Just as the output of a command can be redirected to a file, so can the input of a command be redirected from a file i.e., the input for a command can be taken from a file instead of taking from the standard input (keyboard).
Syntax
command < filename In this case, less than (<) sign is used to redirect the input of command from the filename. Consider the following: # sort < mydata When the sort command opens the standard input and begins to read, it will read from the file mydata and not from the keyboard.
Error Redirection
As mentioned earlier, along with the standard output, the error messages, if any, generated by executing the command is also displayed on the screen. At times it may be difficult to catch the error message as it might get mixed up with the standard output. It would be better, if the error messages are made available separately. Just as the output is redirected to a file, the error can also be redirected. In the command line, by preceding the > output redirection symbol by a 2 the standard error message can be redirected.
Practice 4.1
The following example shows how to redirect the error message. # ls *.txt 2> /tmp/err.out # cat /tmp/err.out ls: *.txt not found In the above example the error message is redirected to the file /tmp
Practice 4.2
The following example illustrates the simultaneous redirection of both the input and the output. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
43
17 17 17 17
In this example, the sort command takes its input from the file names and its output is redirected to the file sort_names.
4.3 PIPES
The unix system enables the user to effectively connect two or more commands together. This connection is called a pipe. A pipe enables to take the output from one command and feed it directly into the input of the another command. A pipe is effected by the character | (called pipe), which is placed between two commands. All the commands in a pipeline are executed sequentially. Unix handles the flow of data from one command to the next, producing the effect as if one command is being executed.
As an example of a pipe, suppose you wanted to count the number of files in your directory. Now we know that ls command displays the names of all files, and the command wc l is used to count the number of lines in a file. So both these commands can be effectively piped to get the desired result. Consider the following #ls | wc -l 10 The output indicates that the directory contains 10 files. First, the ls command is executed to list the files, this output is then sent through the pipe as an input to the wc l command, which is executed to give the number of files. The final output is the output of the last command.
44
4.4 Filters
Unix Administration Filters
Filter is a UNIX utility that takes input data, processes it, and sends the result to the output. A filter selectively alters the data that passes through it. For example, the grep command (discussed below) filters out unwanted data and passes on the selected data to an output file.
sort
sort is a filter utility that is used to order the contents of the indicated file, alphabetically and display the result of the sort at the terminal. The original contents of the file remain unchanged.
Syntax
sort [options] filename Options can be -n -r -f -o -k -t SEP Sorts the input numerically Sorts the input in reverse order Ignores the significance of uppercase and lowercase letters Sends the output to a file rather than the standard output Sorts the records fieldwise Uses SEParator instead of non- to whitespace transition
Practice 4.3
The following shows the usage of the sort command. # cat students Rama Anju Anita Sanjana Hema Jeevan Bobby Neha Priya # sort students
45
UNIX Administration
Anita Anju Bobby Hema Jeevan Neha Priya Rama Sanjana In the above example there is a file students that contains the names of the students of a particular batch. In order to display the names in an alphabetical order, the sort command is used. The sort command orders the names alphabetically.
Wc
Using the UNIX utility wc, the user can count all the lines, words and characters in a file.
Syntax
wc [options] filename The following options can be used with wc command. -l -w -c Indicates the number of lines Indicates the number of words Indicates the number of characters
From the output it can be seen that there are four fields: Number of lines Number of words Total number of characters Name of the file 12 12 36 num
tr
tr command can be used to translate a set of characters to another. It reads from the standard input, searches for all the special characters, and translates each into another specified character and writes to the standard output. It cannot read/write from/to the files. Therefore, the redirection symbols or pipe must be used to input to the tr command.
Syntax
tr string1 string2
46
Working with Pipes & Filters where string1, string2 are the translation control strings. Each string represents a set of
characters to be converted into an array of characters used for the translation. Consider the following # tr 123 ABC < mydata
As a result of executing tr, the following translation takes place in the file mydata which is output on the terminal. 1 -> A 2-> B 3 -> C
grep
The grep command searches files for a pattern and prints all lines that contain that pattern.
Syntax
grep [options] pattern filename If no files are specified, grep assumes standard input. Normally, each line found is copied to standard output. The file name is printed before each line found if there is more than one input file. The file is searched line by line for the pattern. Every line that contains the pattern is displayed on the terminal. The pattern that is searched for in the file is called a regular expression.
Regular Expressions
Character [ class ] [ c1-c2] ^ Description A character class. Matches any one character in the class. Matches any one of the character specified in the range. Pattern following it must occur at the beginning of each line. Does NOT match any of the characters specified. Matches the end of line. Escapes the special meaning of the character. Matches any single character. Example [xyz] specifies the pattern either x or y or z. [a-d] specifies the pattern either a, b, c or d. ^my specifies the pattern my should appear at the beginning of each line. [^abc] specifies that the pattern should not contain a,b or c. ball# specifies the pattern ball at the end of each line. \#900 specifies the pattern #900, the sign # loses its special meaning. [abc]. Specifies the pattern a, b, or c followed by any one character.
[^ class] # \
. (dot)
The options can be : -i -n -c -l Ignore upper/lower case distinction during comparisons. Precede each line by its line number in the file (first line is 1). Print only a count of the lines that contain the pattern. Print only the names of files with matching lines, separated by NEWLINE characters. Do not repeat the names of files when the pattern is found more than once.
47
UNIX Administration -v Print all lines except those that contain the pattern.
Consider the file stud_rec with the following data # cat stud_rec Anjana Divya Farida Prashant Rahul Fardeen
23 19 26 22 21 27
UC++ Annanagar UC++ Padi DBA T.Nagar UNIX Admin Kilpauk ORVB Shenoy Nagar DBA Adayar
The students who are taking UCC++ course can be displayed using the grep as follows: # grep UC++ stud_rec Anjana 23 Divya 19
find
The find command locates the files that match specified expression. It starts searching for files in the given directory and continues its search through all subdirectories. It also provides a mechanism for performing actions on the files that meet the search criteria.
Syntax
find path expression where path is the list of directories to be searched. The names are separated by space or tab. To search the current directory, the dot (.) notation can be used. Here expression can be :
48
Working with Pipes & Filters -name <file> Indicates the names of files to be found in the specified directory. For example: find /usr/ajay name *.c will search all files with extension .c in the /usr/ajay directory. -print -type c Causes the current path name to be printed. Indicates the type of the file is c, where c is b, c, d, l, p, or f for block special file, character special file, directory, symbolic link, fifo (named pipe), or plain file, respectively. Finds the files containing n blocks. If n is followed by c, then n is counted in characters instead of blocks. Executes the command cmd. A pair of braces {} can be set to signify the presence of current pathname. The cmd must end with an escaped semicolon (\;). The expressions can also be used in combination.
-size n[c]
-exec cmd
-ok command Like exec, except that the generated command line is printed with a question mark first, and is executed only if the user responds by typing y. The following example finds all the files under the current directory and prints them # pwd /usr/sunil # find . . ./salary ./file1 ./file2 ./file3
cut
cut is a filter utility that is used to cut out columns or fields from each line of a file. A field is normally separated by a tab character (default delimiter), but it can also be delimited by any other character.
Syntax
cut -c columnlist [ file ... ] cut -f fieldlist [ -d delim ] [ -s ] [ file ... ] where list is a comma-separated or blank-character-separated list of integer field numbers (in increasing order), with optional - to indicate ranges (for instance, 1,4,7; 1-3,8; -5,10 (short for 1-5,10); or 3- (short for third through last field)). the list following -c specifies character positions (for instance, -c1-72 would pass the first 72 characters of each line). the list following -f is a list of fields assumed to be separated in the file by a delimiter character.
-c list,
-f list,
49
UNIX Administration -d delimiter,the character following -d is the field delimiter (-f option only). Default is tab. Space or other characters with special meaning to the shell must be quoted. delimiter can be a multi-byte character.
Practice 4.4
Consider the file names containing the following information Pat Tedd Anju Hema Raju Sonu Gaja Boycott Ahuja Malini Naidu Misra 22 34 25 27 31 28 C++ ORVB C++ DBA ORVB ORVB
The following example shows the usage of the cut command. # cut f 2,4 names
In the above example the second, fourth fields are cut from the file using the cut command.
paste
The paste command joins two files horizontally (column wise). For instance, if a file contains the list of students and the other file contains their ages, the two files can easily be joined together to get two columns: one containing names and the other containing ages.
Practice 4.5
Consider two files students and stu_age whose contents are as follows: # cat students Rama Anju Anita Sanjana Hema Jeevan Bobby Neha Priya # cat stu_age 29 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
50
Working with Pipes & Filters 19 22 32 35 24 19 23 31 The following example shows the usage of the paste command # paste students stu_age
29 19 22 32 35 24 19 23 31
It can be seen that when the paste command is issued, the two files merge and the output appears in two columns.
head
The head utility copies the specified number of lines from the beginning of the file to the standard output. If no filename is given, head copies lines from the standard input. The default value is 10 lines.
Syntax
head [- number] file
Practice 4.6
Consider the file mybook that contains 16 lines. The following example shows the use of the head command. # head mybook
You may be wondering Why? Because, I am a writer and I have to think. I want to write but nothing seems to be coming out. I have severe constipation of ideas.
51
UNIX Administration Here since the numberof lines have not been specified, the first 10 lines (default value) of mybook are displayed.
tail
tail command is the reverse of the head command. It is used to display the last few lines of a file. If no file is named, the standard input is used. By default, it displays the last 10 lines.
Syntax
tail [ -/+ number ] file
Practice 4.7
Consider the file mybook discussed in the previous example. The following example shows how to display the lines from the end of the file mybook. # tail -5 mybook
Anyway, I am not going to give up. Definitely, one day I am going to be a greater writer. But, today I think, I need a break. Good Bye. Good Bye. In this example the last 5 lines of mybook are displayed.
more
more is a filter that displays the contents of a text file normally pauses after each screen. on the terminal, one screen at a time. It
Syntax
more filename more scrolls up to display one more line in response to a RETURN character; it displays another screen in response to a SPACE character.
tee
Any output from a command that gets piped into another command is not seen at the terminal. Sometimes, the user might want to save the output that is produced in the middle of a pipe. The tee command enables to do this easily.
Syntax
tee file The tee command simply copies the data coming in to the standard output, while saving a copy in the specified file. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
52
Working with Pipes & Filters Consider the following example # sort students | tee stud | more Anita Anju Bobby Hema Jeevan Neha Priya Rama Sanjana (EOF): This will sort the student file, display it page wise and save it in file stud. Now the sorted file stud can be displayed on the terminal using cat command.
4. 5 Unix Processes
Unix Administration Unix Processes Processes Foreground Processes Background Processes Suspended Processes Switching between Processes jobs ps stop kill fg nohup bg
Processes
Unix is a multi-user as well as multitasking system. This means that more than one user can use the system and each user can perform a number of tasks at the same time. In UNIX system, a task is referred to as a process. A process is the existence of an executing program in the computer. Since the CPU can carry out one task at a time, multitasking is accomplished using the concept of timesharing. The UNIX Kernel maintains a list of processes started by a user and each process is allocated a small time quantum, called time slice, during which it can carry out its execution. When its time elapses, the first process is suspended and other is given a chance to run. When all processes in the list have had their chance to run, the kernel switches back to the first process, starting the execution from where it was suspended. In this way, every process is allowed to work its way to completion, a little bit at a time. The time slice for each process is so small (a few hundredths of a second), it gives the impression that each user is being served simultaneously, even though, they are being served one at a time. There are various types of processes that can be started simultaneously by a user. These processes fall into the following categories: Foreground processes- processes with which the user directly interacts. Background processes- processes that are dissociated from the terminal. Suspended processes- processes whose execution has been suspended for a while. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
53
UNIX Administration
Foreground Processes
A foreground process is the one in which the user interfaces with, from the keyboard. The user writes a command at the # prompt and waits till the execution is over. When the command is issued, it gets executed and the result is echoed to the screen.
Background Processes
A background process can be started along with a foreground process. When a command is appended with an ampersand (&) sign, it gets dissociated from the terminal and carries its execution in the background. Consider the following example # sort data > /tmp/out & [1] 1074 # [1] + Done(0) #
The above command sorts the file data and redirects the output to another file out. This whole process is appended by an &, implying that it has to be carried out in the background. When a process is sent to the background, UNIX automatically displays a unique number identifying that process, called process id (PID). In the above example, it is 1074. After displaying the PID number, the terminal is immediately available to the user (indicated by the # sign). It is useful to carry out those processes in the background which do not require user input so that, in the meantime, another process can be executed in the foreground. For example, printing a large document in the background while editing another document in the foreground.
Suspended Processes
A user can suspend a job running in the background or one running in the foreground. This is useful when the user is running a command and some other function needs to be performed. A running job can be suspended by pressing Ctrl-Z.
jobs
The jobs command enables to know about the processes that are in background or in the suspended state.
Syntax
jobs [+/-] + Indicates the current background process Indicates the previous process Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
54
Working with Pipes & Filters Note : Using the option l, the process IDs of the processes can also be displayed.
stop
This command is used to stop the background process.
Syntax
# stop [% job id] The following example shows how to stop the sixth process. # stop %6 #jobs [6] [5] [4] [3] [2] [1] + Stopped(signal) + Running find + Running find + Running find + Running find + Running find find / -name sample& / -name sample& / -name sample& / -name sample& / -name sample& / -name sample&
fg
The fg command allows the suspended jobs to be resumed by placing them in the foreground. The suspended jobs, when brought back to the foreground, become interactive again.
Syntax
fg [ % job] where % job can be :
% num Indicates a job number for an associated process % + Indicates the current job; the last job suspended % - Indicates the previous job; process before the current job The following example shows how to bring the stopped job 6 to foreground. # fg %6
bg
The bg command allows the suspended jobs to be resumed by placing them in background.
Syntax
bg [ % job] where % job can be % num %+ %Indicates a job number for an associated process Indicates the currernt job; the last job suspended Indicates the previous job; process before the current job
The following example shows how to restart the suspended job 6. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
55
ls -Rl / 1>/tmp/out1
ps
The ps command is used to display the status of the running processes. The ps command reports the process ID, the associated terminal type, the amount of time a process has used and the command being executed.
Syntax
ps [options] Options: -u <username> -e -f -t <terminal> Displays the process status for a particular user Displays the information about every process Displays the full listing of header information Displays the process status for a particular terminal
The column headers are: UID PID PPID C STIME TTY TIME users ID no. of the processs owner process ID of the process process ID of the parent process the processor utilization used for scheduling purposes time the command started terminal from which the process was started cumulative execution time for the process
COMMAND name of the process started The following example shows how to get the process status of the processes executed from the current terminal # ps PID 1077 1070 1072
CMD ls sh jsh
Note : A ? mark in the TTY column represents that the process is started automatically and there is no controlling terminal.
kill
If a process is running in background and for some reasons that process has to be terminated, then kill command can be used to accomplish the task.
Syntax
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
56
where pid is the procees id number The following example shows how to kill a process. # ls -R / > /tmp/out [1] 1098 # # # ps PID TTY TIME 1098 pts/2 0:00 1070 pts/2 0:00 1072 pts/2 0:00 # kill 1098 # ps PID TTY TIME 1070 pts/2 0:00 1072 pts/2 0:00 [1] + Terminated &
CMD ls sh jsh
When a process is placed in background, its PID number is immediately displayed. To know the PID number of the process to be terminated, the ps or jobs l command can be used. Note : Only the owner of the process or the superuser can kill a process. Killing the shell will logout the user from the system.
nohup
A background process can continue its execution even after the user has logged out. Normally, all processes terminate at the time of logout. But if the background process is started with a nohup command, the background process can still be continued. The nohup utility invokes the named command with the arguments supplied. When the command is invoked, nohup arranges for the Hangup signal which intimates the process to hangup, to be ignored by the process. nohup can be used when it is known that command will take a long time to run and the user wants to logout of the terminal; when a shell exits, the system sends its children hangup signals, which by default cause them to be killed.
Syntax
nohup command [arguments] All stopped, running, and background jobs will ignore hangup signal and continue running, if their invocation is preceded by the nohup command. The output of the nohup command is captured in a file called nohup.out if standard output is a terminal and if the current directory is writable. The following example shows the usage of the nohup command. # nohup ls -Rl / > /tmp/out & [1] 1101 # exit Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
57
UNIX Administration On logging in again and it can be seen that the command that has been issued is still running.
58
Lecture 5
Objectives
In this lecture you learn the following
Knowing about Shell and its types Processing commands by shells Understand about the variable and their types
will
59
UNIX Administration
Coverage Plan
Lecture 5
5.1 Snap Shot 5.2 What is a Shell? 5.3 What is a Variable? 5.4 Command Substitution 5.5 Short Summary 5.6 Brain Storm
60
Types of Shells Processing Commands by shells Variables Types of Variables Command Substitution Positional Parameters Export Command
The Shell is both a command-line interpreter and a high-level programming language. When it is acting as a command-line interpreter, it processes commands as entered at the command prompt. When it is used as a programming language, it processes commands that are stored in files known as Shell scripts. Shell scripts allow to group command lines together and execute them by entering a single command at the command line. This allows complex functions to be completed by any user, and repetitive functions can be completed easily. Input and output can also be redirected from a Shell script.
Types of Shell
There are three types of shells available in most Unix Systems.They are as follows Shell Name Bourne(sh) C(csh) Prompt $ % Calfornia Korne(ksh) $ Developed By Steven Bourne at AT&T Bell Labs Bill Joy at Description The default shell for all Unix operating system. The C shell was separately
University of developed and it is similar to C programming language. David G.Korn at AT & T Bell labs features of C shell. This is derived from bourne shell and with some enhanced
Table 5.1 Bourne shell is the accepted standard for SystemV UNIX.
61
UNIX Administration Each shell creates subshells and child processessubordinate shells and processes that are executed within the originating, or parent, shellto interpret and execute commands. For example, the following list shows a simplified version of the order in which the Korne shell processes commands: 1. Parses (divides up) the command into units separated by the fixed set of meta characters: Space Tab Newline ;( ) < > | &. Types of units include words, keywords, I/O redirectors, semicolons, and others. 2. Checks the first part of each unit for shell keywords, such as function or if statements, with no quotes or backslashes. When it finds a keyword, the shell processes the compound command. 3. Searches the list of aliases. 4. Expands any tilde (~) expressions. 5. Substitutes variables. 6. Substitutes commands. 7. Substitutes arithmetic expressions. 8. Splits the items that result from parameter, command, and arithmetic substitution and again splits them into words 9. Expands wildcards. 10. Looks up built-in commands, functions, and executable files. 11. Sets up I/O redirection. 12. Runs the command. Note : The Bourne shell interprets commands similarly, but does not check for aliases, tildes, or arithmetic. The C shell interprets commands in a different order.
Variable is nothing but a memory storage, which is used to store the value. It helps to refer the value during processing.
Syntax
variable-name=value Only letters, digits, underscore and $ should be used in variable names. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
62
Introduction to Shell Programming Note: No blanks are allowed before and after the = sign Shell variables are string variables # name=radiant # a=10 Here radiant and the value 10 will be treated as strings. It is not possible to perform arithmetic operations on the variable a. The value stored in the variable name can be viewed given by using echo $variablename. The echo command is used to print the value on the screen.
Example
# name=radiant # a=10 # echo $name radiant # echo $a 10 To perform the arithmetic operations, the expr command has to be used as shown below # echo $a + 10 which will produce the output as 10 + 10 The user can store a null string, which consists of no characters in a variable in the following formats # # # name= name= name=
63
UNIX Administration $$ Returns the process number of the shell (in decimal). Since process numbers are unique among all existing processes, this string is frequently used to generate unique temporary file names. # echo $$ 786 $! Returns the process number of the last process that runs in the background (in decimal). # echo $! 790 $Returns the current shell flags, such as -x and -v. Some variables have a special meaning to the shell and should be avoided for general use.
Environment Variables
It is a predefined variable where the user can store values and make it as the current environment settings. $MAIL When used interactively the shell looks at the file specified by this variable before it issues a prompt. If the specified file has been modified since it was last opened, the shell prints the message you have mail before prompting for the next command. This variable is typically set in the file .profile, in the users login directory. MAIL=/usr/mail/fred $HOME This is the default argument for the cd command. The current directory is used to resolve file name references that do not begin with a /, and is changed using the cd command. The following command #cd /usr/fred/bin changes the current directory to /usr/fred/bin.
The command cd with no argument is equivalent to #cd $HOME This variable is also set in the users login profile. $PATH Stores the list of directories that contain commands (the search path). Each time a command is executed by the shell, a list of directories is searched for an executable file. If $PATH is not set then the current directory, /bin, and /usr/bin are searched by default. Otherwise $PATH consists of the directory names separated by :(semicolon). The following command PATH=:/usr/fred/bin:/bin:/usr/bin
64
Introduction to Shell Programming specifies that the directories, the current directory (the null string before the first :), /usr/fred/bin, /bin and /usr/bin are to be searched in that order. This enables individual users to have their own private commands that are accessible independent of the current directory. If the command name contains a / then this directory search is not used; a single attempt is made to execute the command. $PS1 Stores the primary shell prompt string, by default, $ . The user can change his prompt. For example, consider the following # PS1=radiant Now the prompt will be radiant $PS2 Stores the shell prompt string, by default, >
Example
#PS2=radiant now the prompt will be radiant> $TERM Stores the terminal specification. A Unix system can have different types of terminals like vt100,vt220 and so on $LOGNAME This variable contains the users login name. # echo $LOGNAME root $SHELL Stores the name of the shell. # echo $SHELL /bin/sh Note : Using env command, all the environment variables can be viewed.
65
UNIX Administration will display the output of date command. The following assignment saves, in the files variable, the number of files in the current directory: # files=ls | wc -l Now the following command # echo $files will display the total number of files in the current directory. Command substitution can be performed on any command that writes to the standard output. To nest command substitutions, each of the nested backquotes have to be preceded by a \ (backslash), as in the following # logmsg=echo Your login directory is \pwd\ # echo $logmsg Your login directory is /home/manu
Positional Parameters
Positional parameters are defined as numbered variables representing the position of the arguments passed to the shell script. The name of the shell script is passed as the positional parameter $0, the first argument is passed as positional parameter $1 and so on. Unix shell creates a number of arguments that are specified in the command and the shell assigns values to these positional parameters. $0 Command or Source file name $1-$9 Passed as an argument using the user defined file or commands $# - list the total number of parameter $* - list the individual details about each and every arguments.
Practice 5.1
The following shell program shows how to implement the positional parameters. # cat > pscript echo echo echo echo echo The The The The The command is $0 First argument is $1 Second argument is $1 Third argument is $1 Fourth argument is $1
# chmod u + x pscript #./ pscript a b c d The command is pscript Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
66
Introduction to Shell Programming The The The The First argument is a Second argument is b Third argument is c Fourth argument is d
In the above program, the pscript (filename) is $0 and the parameters are a, b, c and d are represented as $0,$1,$2 and $3 respectively.
Syntax
export variablename where variablename is the name of the variable to be exported. Consider the following Here a local variable Z is assigned a value of 100. Thereafter,another process starts. The new process does not know about the variable Z, which is assigned in its parent shell. # Z=100 # echo $Z 100 # sh # echo $Z # exit The variable Z can be made global so that it is available to all the processes as shown in the following example # export # sh # echo $Z 100 # Z=200 # echo $Z 200 # exit # echo $Z 100 Here the value of Z is available to all the subprocesses.If another value is assigned to Z within the subprocess,the local variable Z precedes the global variable Z. Note : Local variables are available only during the lifetime of the process. They get destroyed with the process. Global variables are available throughout the shell session. When the local and the global variable have the same name, the local variable gets the precedence during execution. If an export command is used without any argument, it lists out all the exported variables, if you are in a sub shell, only the variables that have been exported. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University Z
67
UNIX Administration
5. 6 Brain Storm
1. 2. 3. 4. 5. 6. 7. What is shell? Mention the types of shell? What is the difference between system variables and environment variables? What is the purpose of command substitution? What is the use of the export command? What are the different positional parameters used in shell scripts? What is the use of the shift operator? What is the use of the trap command?
68
Lecture 6
Objectives
In this lecture you learn the following
About Shell Scripts Knowing the command constructs in the Shell programming
will
69
UNIX Administration
Coverage Plan
Lecture 6
6.1 Snap Shot 6.2 Advance Shell Scripts 6.3 Short Summary 6.4 Brain Storm
70
This command writes each given STRING to the standard output, with a space between each STRING and a new line after the last one.
Syntax
echo [OPTION]... [STRING]... This command accepts the following options. This command is exclusivly used in shell scripts. -n -e Disables output of trailing new line. Enable interpretation of the following each STRING: only in the case of LINUX alert (bell) backspace suppress trailing newline form feed new line carriage return horizontal tab vertical tab back slash
backslash-escaped
characters
in
\a \b \c \f \n \r \t \v \\
Consider the following example # echo hello welcome to shell programming hello welcome to shell programming # a=10 # name=lambent #echo the value of a is $a the value of a is 10 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
71
UNIX Administration # echo The Name is $name The Name is lambent # echo -e hello \a The output will be hello with an alarm sound.
Syntax
read variablename The read command waits for the user to enter a value. The shell assigns that value to the shell variable, which is specified by variable name.
Practice 6.1
The following program illustrates the usage of the read command. # cat > read echo enter the name: read name echo $name Welcome to Unix environment
# sh read enter the name raj raj welcome to Unix environment The above program will interact the user and get the name raj from the user through the keyboard and substitute the name and display the message raj Welcome to Unix Environment.
Numeric expressions
The expr command supports the numeric operators.The numerical operators that are supported in the order increasing precedence are +,-,*,/,%.The arguments are coerced to number ( an error can occur if this cannot be done). Consider the following example # a=10 # b=20 # echo Addition `expr $a + $b` Addition 30 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
72
Advanced Shell Scripts # echo Subtraction `expr $b - $a` Subtraction 10 # a=10 # b=20 # echo Multiplication `expr $a \* $b` Multiplication 200 # echo Division `expr $b / $a ` Division 2 which gives quotient part # echo Modulus `expr $b / $a` Modulus 0 which gives remainder part
Syntax
test expression or [ expression ] Applying Integer Operator using test command Operator int1 -eq int2 int1 -ge int2 int1 -gt int2 int1 -le int2 int1 -lt int2 int1 -ne int2 Table 6.1 Description Returns true if int1 is equal to int2 Returns true if int1 is greater than or equal to int2 Returns true if int1 is greater than int2 Returns true if int1 is less than or equal to int2 Returns true if int1 is less than int2 Returns true if int1 is not equal to int2
Applying String Operator using test command Operator str1 = str2 str1 != str2 str -n str -z str Table 6.2 Description Returns true if str1 is identical to str2 Returns true if str1 is not identical to str2 Return true if str is not null Return true if the length of str is greater than zero Return true if the length of str is equal to zero
Applying File Operator using test command Operator -d filename -f filename -r filename -s filename Description Returns true if file,filename is directory Returns true if file,filename is an ordinary file Returns true if file,filename can be read by the Returns true if file,filename has a nonzero length process
73
UNIX Administration -w filename -x filename Table 6.3 Returns true if file,filename canbe written by the process Returns true if file,filename is executable
Applying Logical Operator using test command Operator ! expr expr1 -a expr2 expr1 -o expr2 Table 6.4 Description Returns true if expr is not true. Returns true if expr1 and expr2 are true. Returns true if expr1 or expr2 is true.
The if statement
All the three shells support nested if..then..else statements.These statements provide a way of performing complicated conditional tests in shell programs.
Syntax
if [ expression ] then commands elif [ expression ] then commands else commands fi
Practice 6.2
The following shell program will find if the .profile file is present in the current directory # vi checkprofile echo -e Enter the filename to search :\\c read fname if [ -f $fname ] then echo There is $fname file in the current directory else echo Could not find the .profile file fi
# sh checkprofile The above program will check for the file. Profile in the current directory using the test option f. If the file is found, then it will display the message there is. Profile file in the current directory else it will display the message Could not find the .profile file. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
74
Practice 6.3
The following shell program will find the of 3 numbers. # vi greatnum echo read read read -e Enter the value for a, b and c: a b c $c ] $b and $c
if [ $a -gt $b -a $a -gt then echo $a is greater than elif [ $b -gt $c ] then echo $b is greater than else echo $c is greater than fi
$a and $c $a and $b
# sh greatnum Enter the value for a, b and c: 12 34 56 56 is greater than 12 and 34 The above program accepts three numbers for a, b and c respectively. Using the if statement and logical AND operator (-a) checking will be performed .It will check the value of a with b and c and confirm whether a is greater than b and c else it will check b value with c and confirm whether b is greater than a and c else c is greater than a and b.
Syntax
for variable in list-of-commands do commands done
Practice 6.4
The following shell program will convert all the file content to uppercase started with a as first name and by creating with same file name and extension as caps. # vi upperconv for fname in ls a* do tr [a-z] [A-Z] < $fname > $fname.caps done Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
75
UNIX Administration
# sh upperconv The above program will find the filename which starts with a as the first letter and open the file ID will then convert the entire file content into uppercase and store it in a file with the same filename but with extension in caps.
Syntax
while [ command-list1 ] do command-list2 done The value tested by the while command is the exit status of the last simple command following while. After each iteration command-list1 is executed; if a zero exit status is returned then command-list2 is executed; otherwise, the loop terminates. For example, while test $1 do ... shift done is equivalent to for i do ... done shift is a shell command that renames the positional parameters $2, $3, ... as $1, $2, ... and loses the parameter $1. Here the shift command moves the command-line parameters to the left by one parameter.
The followingPractice 6.5 shell program lists the parameters that are passed to the program , along with the number of the parameter. # vi whileparam count=1 while [ -n $* ] do echo This is parameter number $count $1 shift count=expr $count + 1 done
76
Advanced Shell Scripts # sh while 1 2 3 4 5 6 This This This This This This is is is is is is parameter parameter parameter parameter parameter parameter number number number number number number 1 2 3 4 5 6 1 2 3 4 5 6
The above program will accept the arguments and display the respective position of each argument or parameter. Here the shift command has been used to shift the parameter to next position.
The following shell program will generate the fibonacci series 0,1,1,2,3,5,8,13,...... # vi whilefib n1=0 n2=1 echo $n1 while [ $n2 -lt 200 ] do echo $n2 n2=expr $n2 + $n2 n1=expr $n2 - $n1 done
Practice 6.6
# sh whilefib 0 1 1 2 3 5 8 13 21 The above program uses the while statement to generate the fibonacci series.
Practice 6.7
77
UNIX Administration
The following shell program lists the parameters that were passed to the program , along with parameter number count=1 until [ -n $* ] do echo This is parameter number $count shift count=expr $count + 1 done
$1
# sh while 1 2 3 4 5 6 This This This This This This is is is is is is parameter parameter parameter parameter parameter parameter number number number number number number 1 2 3 4 5 6 1 2 3 4 5 6
The above program will accept the arguments and display the respective position of each argument or parameter. Here the shift command has been used to shift the parameter to the next position.
Syntax
case string1 in str1) commands;; str2) commands;; *) commands;; esac
Practice 6.8
The following shell program will create,display and delete a file the using case statement # vi casefile echo -e Enter the filename :\\c read fname echo -e Enter the choice (1-create;2-display;3-delete):\\c read choice case $choice in Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
78
Advanced Shell Scripts 1) 2) 3) *) cat > $fname;; cat $fname;; rm $fname;; echo please choose option between [1-3] break; esac
# sh casefile Enter the filename: sivam Enter the choice (1-create;2-display;3-delete):1 This is a demo to create a file using case statement To display the file ^d # sh casefile Enter the filename: sivam Enter the choice (1-create;2-display;3-delete):2 This is a demo to create a file using case statement To display the file # sh casefile Enter the filename: sivam Enter the choice (1-create;2-display;3-delete):4 please choose option between [1-3] The above program gives 3 choices from 1 to 3. Depending on the value that is chosen the corresponding command is executed. If any other value is chosen, it will display please choose option between [1-3].
The following shell program will find whether the file is available in the directory or not. # cat > break while true do echo Enter the file name: read fname if [ -f $fname ] then echo File not found break else echo File found fi echo Bye done Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Practice 6.9
79
UNIX Administration
# sh break Enter the filename: casefile file found bye Enter the filename Case File not found # The above program will accept the filename and find whether file exists in the directory or not. If it is found, it prompts file found and get another filename to search. If the file is not found, it will automatically break from the while loop.
Practice 6.10
The following shell program if a given number is greater than 1000 or not. $ cat > until until false do echo enter a number less than 1000: read nm if [ $nm ge 1000 ] then continue else echo The number is $num fi done Explanation Here if a number less than 1000 is entered that numbere is displayed and program exits. But if the number is greater than 1000 then the program encounters the continue statement and the program repeats prompting the user to enter a number less than 1000. This process continues till the users enters a number less than 1000.
80
Advanced Shell Scripts Sometimes, the user might want to take some special action when a signal is received. If a program is creating temporary data files, and it is terminated by a signal, the temporary data files remain. The user can change the default action of the program by using the trap command.
Syntax
trap command-string signals where signals are one or more signals which are to be trapped command-string is one or more commands separated by semicolon which are to be executed when the signals are received.
Example
$ trap rm /tmp/*$$ ; exit 1 2 15 The command informs the shell to remove the files that end with PID at the temporary directory and exit the program when signals 1,2 and 15 are received. Signal 1. 2. 15 Description Hangup Operator Input Software Termination (kill signal
Environment variable is predefined variable where the user can store values and make it as the current environment settings Command substitution allows to capture the output of any command as an argument to another command Positional Parameters are numbered variables that represent the position of the arguments that are passed to the shell script.
The export command makes the variable available for global usage.
81
UNIX Administration
82
Lecture 7
Booting Shutting
Objectives
In this lecture you learn the following
About Booting and shutting Knowing the types of Booting About Boot Process Knowing about Run levels Overview of different run levels
will
83
UNIX Administration
Coverage Plan
Lecture 7
7.1 Snap Shot 7.2 Booting 7.3 Boot Process 7.4 Run Levels 7.5 Short Summary 7.6 Brain Storm
84
7.2 Booting
Unix Administration Booting Types of Booting Automatic Booting Manual Booting
Loading the OS into memory and getting it running is called bootstrapping. In simpler terms, it is referred to as booting. The boot process can be complex and understanding it requires an in-depth knowledge of the working of Unix. Understanding the boot process will help in understanding Unix in general. In the boot process the philosophy of Unix having many small programs can be seen. These programs perform a specific jobs, rather than having one large program which attempts to do everything.
Types of Booting
There are two types of booting which are as follows:
Automatic Booting
Here the system bootstraps itself, and comes up running normally (often called multi-user mode). This is the default.
Manual Booting
The user intervenes, and tells the system to load a different kernel, or come up in single-user mode, which may be necessary to fix certain problems.
85
UNIX Administration
All computer systems start the boot process by executing the code in ROM (specifically, the BIOS) to load the sector from sector 0 of the boot drive. The boot drive is usually the first hard disk. The BIOS then tries to execute this sector. On all hard disks, sector 0, contains the start of an operating system kernel, such as Unix. Once the Kernel is completely loaded, it goes through some basic device initializations. The kernel has to look for the root file system, if it does not find a loadable image there, it halts. At this point the system finds the init program on the root file system (in /bin or /sbin) and executes it. The init program reads its configuration file /etc/inittab, looks for a line-designated sysinit, and executes the named script. The sysinit script is usually something like /etc/rc.d/rc.sysinit. This script is a set of shell commands that set up the basic system services, such as Loading necessary Kernel modules Starts swapping, Running fsck on all disks, Initializing the network Mounting disks mentioned in /etc/fstab
This script often invokes various other scripts to do modular initialization. For example, in the common SysV init structure, the directory /etc/rc.d contains a complex structure of subdirectories whose files specify how to startup and shutdown most system services. However, on a boot disk the sysinit script is often very simple.
86
Interactive Mode
Figure 7.1
init Process
Init is the program that is run by the kernel at boot time. It is in charge of starting all the normal processes that need to run at boot time. These include the getty processes that allow to login, NFS daemons, FTP daemons. init is quickly becoming the standard in the world of Unix to control the startup of software at boot time. This is due to the fact that it is easier to use and more powerful and flexible. It resides in /etc/rc.d. /etc/rc.d/init.d /etc/rc.d/rc0.d /etc/rc.d/rc1.d /etc/rc.d/rc2.d /etc/rc.d/rc3.d /etc/rc.d/rc4.d /etc/rc.d/rc5.d /etc/rc.d/rc6.d The above directories contain scripts, which are controlled by rc.sysinit process. Note : All the mentioned directories reside directly in /etc in SUN UNIX and SCO UNIX.
Example
/etc/init.d, /etc/rc0.d init.d contains a variety of scripts. Basically, one script for each service is required to start at boot time or when entering another run level. Services include things like nfs, sendmail, httpd, etc. Services do not include items such as set serial that must only be run once and then exited. Such services are found in rc.local or rc.serial. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
87
UNIX Administration
Example
# /etc/rc.d/init.d/nfs start # /etc/rc.d/init.d/nfs stop init is the parent process of all the processes. The primary role of this process is to create child processes from the script stored in the file /etc/inittab. This script has entries related to init level through which all corresponding scripts get executed at startup. The init process is located in the /sbin/init. Init is centrally configured through the /etc/inittab file. Here, the so-called run levels are defined. Depending on the entries in /etc/inittab several scripts are started by init. These script are located in the /sbin/init.d folder.init maintains the process of starting and shutting down. /etc/inittab The inittab file describes the processes that are started at bootup and during normal operation. The format of the inittab file is as follows. id:runlevel:action:process Id Run level Action Process Id is unique identifier within the inittab file which identifies each entry with a limit of 14 characters. Lists the run level for which the specified action should be taken. Describes the action to be taken. Specifies the process to be executed.
Action fields are as follows: Respawn Wait Boot Initdefault Sysinit Powerfail The process will be restored whenever it terminates. The process will be started once when the specified run level is entered and init will wait for its termination. The process will be executed during the booting of the system . The run level field is ignored. An initdefault entry specifies the run level, which should be entered after system boot. If none exists, init will ask for a run level on the console. The process fields are ignored. The process will be executed during the booting of the system. It will be executed before any boot or bootwait entries. The run level field is ignored. The process will be executed when the power goes off. Init is usually informed about this by a process that takes to a UPS which is connected to the system. Init does not wait for the process to complete.
init process and the /etc/inittab file work in the following manner /etc/inittab If init default is set to level 3 the init process will run entries with sysinit in the action field and entries with 3 in rstate field Steps involved in the init process are as follows: 1. 2. 3. The init process reads the inittab file. The init process scans for other default run level by reading the initdefault entry. The init process executes the commands or scripts for entries that have sysinit in the action field.
88
Booting and Shutting 4. The init process executes the scripts for any entry that has a 3 in the rstate field.
Inittab resembles Id:5:initdefault: Si:sysinit:/etc/rc.d/rc 0 10:0:wait:/etc/rc.d/rc 0 11:1:wait:/etc/rc.d/rc 1 12:2:wait:/etc/rc.d/rc 2 13:3:wait:/etc/rc.d/rc 3 14:4:wait:/etc/rc.d/rc 4 15:5:wait:/etc/rc.d/rc 1 16:6:wait:/etc/rc.d/rc 1
Daemons
These are a group of programs running in the back ground which provides services to the user. All daemons are stored in /bin directory and executed by the services stored in /etc/rc.d/init.d directory. All current running processes are stored in /proc file system.
Example
Services Nfs,Volmgt etc., Daemons Vold,nfsd etc.,
The Unix system environment provides several run levels that determine the various modes of system operation. The Run Levels under Unix, define how the system gets started up. After booting, the system starts as defined in ./etc/inittab. An alternative to this method is assigning a special run level at boot time. The kernel passes any parameters, which it does not need, directly to init. Run levels can be changed while the system is running , as shown below. # init S which brings in a single user mode, which is for maintenance and administration of the system. One can go to runlevel 2 again by the following # init 2 Now all the essential programs are started and users can log in and work with the system.
89
UNIX Administration A run level is a software configuration of the system, which allows only a selected group of processes to execute. Init has eight run levels from 0-6 and S or s. Here telinit is the privileged user, which sends a signal to init, telling it which run level to change. For change of each run level in inittab the init process executes a script. After init is invoked as the last step of the kernel boot sequence it looks for the script /etc/inittab to see if there is any entry of the type initdefault.This initdefault entry determines the initial run levels of the system startup.Run level S or s brings the system to single user mode and does not check for the script /etc/inittab.In the single user mode it is opened on /dev/console. If the system is entering into the multiuser mode for the first time, init performs the boot and bootwait entries to allow file systems to be mounted and all entries that match the run level are processed before getting in to login prompt. When starting a new process, init first checks whether the file /etc/initscripts exists and uses this script to start the process. Each time a child terminates, init records the facts and reasons for its termination in. /var/run/utmp and /var/log/wtmp, provided these files exist.
Runlevel Functions
Run Level 0 S 1 2 3 4 5 6 Description Halt, graceful or proper shutdown Single user mode ( To repair corrupted file system ) Single user mode (administrative purpose) without network Multi-user mode with network (standard) Multi-user mode with network Unused Takes to Windows environment Reboot or restart the system
Note : In Sun UNIX, the default run level is 3 and run level 5 is to switch off the power of the system. In SCO UNIX the default run level is S and run level 2 is for full multi-user mode and run level 3 is the alternative multi-user mode.
Runlevel Identification
To identify the current runlevel and previous run level the command is # runlevel N 3 Here N indicates the previous run level and the second column indicates the current run level . Note: In the case of SUN SOLARIS and SCO UNIX to identify the runlevel the command is # who r run-level 2 Feb 29 12:27
90
Booting and Shutting The first column indicates the current run level, date & time at which this run level has been entered. The next column indicates the current level and the subsequent column gives the number of times the run level has been run and S indicates the previous run level.
The runcontrol scripts located in the /etc/rc.d directory direct the system to read script files in the related run level directories located in /etc/rc.d/rc#.d. For example , the /etc/rc.d/rc script would read the files located in the /etc/rc.d/rc2.d directory . The /etc/rc.d/rc#.d directories contain scripts that start and stop system services. Files that start with S are used to start processes. Files that start with K are used to kill processes. These files are run in alphanumeric orders. The sequential order is determined by Uppercase K(0-9)(A-Z,a-z,0-9) Uppercase S(0-9) (A-Z,a-z,0-9) File name starting with lowercase letters will not run Note : To run a startup file, the filename has to be add in sequential order with S as a prefix to the filename.
Practice 7.1
The following program shows how to write a run control script # cd /etc/rc.d/rc3.d # cat > S100sample echo echo echo echo echo echo echo echo echo
# init 6
########################################## Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
91
UNIX Administration DEMO FOR RUNCONTROL SCRIPTS DEFAULT RUN LEVEL ########################################## The above procedure will echo the message to indicate the DEFAULT RUN LEVEL which is kept in /etc/rc.d/rc3.d. Here the default run level is 3 and when init 6(reboot) is given the updation will be done to the system and the appropriate process will be invoked.
Multi-User Mode
Multi user mode means all the defined terminal and daemon processes are running. By default, the system is brought to run level 3(full multi-user mode)
Shutting Down
There are many ways of shutting down the Unix system but that cannot include switching off the power of the computer. In fact, like many other operating systems, Unix intensely uses cache memories to accelerate the input/output processes, mostly with the disks (hard disk, floppy disk...). It can never be ensured that all the data are saved recently are actually on the disk or not. Hence the user has to quite the system properly. Under the root command line, type init 0,shutdown, halt, and wait for the computer to print System Halted before cutting off the power. A faster version of the previous solution consists of pressing the ctrl-alt-del keys simultaneously. Then, the system unmounts all peripherals properly. The user has to wait for the computer to reinitialize and then cut off the power. The shutdown command, which resides in a directory named /sbin can be used as follows: # /sbin/shutdown -h now h - To halt the system Only the root user can issue the shutdown command. To restart a Unix system, an alternative form of the shutdown command has to be used as shown below: # /sbin/shutdown -r now r - To restart the system # # # # init 0 init 6 halt reboot
While shutting down a system, Unix automatically logs off all users, terminates all running programs, and closes all open files. Before shutting down a system, each virtual console has to be checked to determine if an important operation is in progress. If so, the shutting of the system should be delayed until the operation is completed.
92
Booting and Shutting The process of loading the OS into memory and getting it running is call bootstrapping often called booting Runlevel allows only a selected group of processes to execute. While shutting down a system, Unix automatically logs off all users, terminates all running programs, and closes all open files.
93
UNIX Administration
Lecture 8
Objectives
In this lecture you learn the following
Able to manage the groups Knowing to manage the users
will
94
Coverage Plan
Lecture 8
8.1 Snap Shot 8.2 Managing Groups 8.3 Managing Users 8.4 Short Summary 8.5 Brain Storm
95
UNIX Administration
Every user on a UNIX system belongs to a group. A group is a collection of individuals. The users in a group may belong to the same department, need access to a particular utility etc. Users can belong to any number of groups. However, at any point of time the user should belong to only one group. This is due to the fact that UNIX allows one group ID per user at any point in time. Groups can have their permissions set to enable their members to gain access to devices, directories, files, filesystems etc., Group information is maintained in the file /etc/group, /etc/gshadow. The common system administrative tasks to be performed to manage groups are: Adding a group Adding users to new groups Deleting a group
Groupadd command
Syntax
groupadd [ Options ] The groupadd command creates a new group account using the values specified on the command line and the default values from the system. The new group will be entered into the system files as needed. The options which apply to the groupadd command are -g gid This is the numerical value of the groups ID. The value must be unique, unless the -o option is used. The value must be non-negative. The default is to use the smallest value which is greater than 500. Moreover, this value must be greater than the group ID value of the already existing groups. Values between 0 and 499 are typically reserved for system accounts. -r
96
User and Group Management This flag instructs groupadd to add a system account. The first available gid which is lower than 499 will be automatically selected unless -g option is givenalso on the command line. Related files to be updated when the groupadd command is used are /etc/group - group account information /etc/gshadow - secure group account information
Practice 8.1
The following shows how to create groups # groupadd g 515 marketing # groupadd g 516 sales # groupadd g 517 technical # groupadd g 518 student # groupadd g 519 manager # groupadd g 520 dummy1 # groupadd g 521 dummy2 # groupadd g 522 dummy3 The above command will create groups for marketing, sales, technical, student, manager, dummy1, dummy2, and dummy3 with unique ids.
Syntax
groupmod [ options ] The options which apply to the groupmod command are -g gid This is used to specify the numerical value of the groups ID. This value must be unique. The value must be non-negative. The values between 0 and 499 are typically reserved for system groups. -n group_name This is used to change the name of the group from group to group_name. Related files to be updated when the groupmod command is used are /etc/group - group information /etc/gshadow - secure group information
Practice 8.2
The following shows how to modify group names and group ids. # groupmod g 515 n mark marketing # groupmod g 516 n sale sales Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
97
UNIX Administration # groupmod g 517 n tech technical # groupmod g 528 student # groupmod g 529 manager The above command will modify group ids for student and manager and modify the group names for marketing, sales and technical as mark, sale and tech respectively
Syntax
groupdel [ group ] group - name of the group Note : The primary group of any existing user may not be removed. But the user must be removed before removing the group. Related files to be updated when the groupdel command is used are /etc/group - group information /etc/gshadow - secure group information
Practice 8.3
# groupdel # groupdel # groupdel dummy1 dummy2 dummy3
The above command will delete groups dummy1, dummy2 and dummy3.
98
User and Group Management All access to a UNIX system is through a user account. Every user except the root account must be set up by the system administrator. Every person using the UNIX system should have his / her unique user name and password. The common system administrative tasks associated with the management of users are Adding users Modifying users Deleting users
Syntax
Useradd - [ Options ] hostname: username
Note : Other flavors of UNIX use something similar; often, it is adduser. The individual must login as root to add users to UNIX workstations. Useradd has a specific syntax and many options, which may or may not be useful. Frequently, the tool to add new user account works with default files that are normally stored in the /etc directory. In some flavors, these default files may be stored elsewhere. The default files are called /etc/login.defs. This file determines how the computer adds user accounts. It defines The range of acceptable user ID and group ID numbers Whether or not a users password or account expires and if so, when and where the users mail will be kept Whether and where the computer will create a home directory for new users; the minimum acceptable length for user passwords. Whether or not the system will remove all processes that are owned by a deleted user
The default files contain information about disk space quotas, standard home directory structures, password aging requirements, and so on. If values for these are not specified when creating a new user, the system will use the default values stored in these files. The options that apply to this command are -u user-id
It is a numerical id for the user and should be unique. The range of values that are utilized for creating user-ids will start from 500. The upper limit of the range is based on the respective flavors. Note : The values between 0 to 499 are reserved for system accounts in linux. -g group-id It specifies a numerical id for the group which already exists. The range of values that are utilized for the creation of group-id start from 500 The upper limit based on their respective flavors. By default the group id will be 1 when no value is specified for the group. -G secondary group-id
99
UNIX Administration It is used to add a user in secondary groups belong to provided, the same user belong to the primary group. Note : The user may be allowed to belong to 16 secondary groups. -c comment This specifies a text string of not more than 512 characters. The string must not contain colons (:) or new lines. -d home directory This specifies the new home directory of the user. If the home directory is being changed, the contents of the previous home directory are modified only if -m is specified. Directory names must not contain colons (:). -m -k skeleton directory The users home directory will be created if it does not exist. The files contained in skeleton_dir will be copied to the home directory if the -k option is used, otherwise the files contained in /etc/skel will be used. Any directories contained in skeleton_dir or /etc/skel will be created in the users home directory as well. The -k option is only valid in conjunction with the m option. The default is not to create the directory and not to copy any files. - s default shell This specifies the name of the users login shell. The default is to leave this field blank, which causes the system to select the default login shell. It is possible to change the shell while creating the user by providing this option with either /bin/ksh or /bin/csh. Note : The default shell is Bourne shell (/etc/sh) and in the case of LINUX. The default shell is Bourne again shell (/bin/bash) which is derived from Bourne shell. -e [expire-date] This indicates the date on which the user account will be disabled. The date is specified in the format YYYY-MM-DD. Note : It is only available in LINUX. -f [Inactive time period]
This indicates the number of days for which the account will remain inactive after a password expires until the account is permanently disabled. A value of 0 disables the account as soon as the password, and a value of -1 disables this feature. The default value is -1. Note : It is only available in LINUX. -r This flag is used to create a system account. if the user with an UID lower than the value of UID_MIN defined in /etc/login.defs. Useradd will not create a home directory for such a user, regardless of the default setting in /etc/login.defs. -m option must be specified to have a home directory to create a system account. Note : It is only available in LINUX. username
100
User and Group Management A user name has a limit of 8 lowercase letters or numbers, but must not begin with a number. In addition, user names cannot include colons (:) (besides the hostname: user syntax used to create a remote account) or new lines. For distributed accounts, only the user name, comment, password, login shell, home directory, login group, group membership, password, and lock status are valid across the network. For example, the maximum number of failed login attempts cannot be set for a distributed user on a remote system (it only takes effect on the master server). Related Files to be updated when the useradd command is used are /etc/passwd - user account information /etc/shadow - secure user account information /etc/group - group information /etc/default/useradd - default information /etc/login.defs - system-wide settings /etc/skel - directory containing default files To Add a User
# useradd u 501 g 501 G 502,503,504,505 c demo for adding new user
-d /home/demo1 m s /bin/sh
-e 2001-03-01 f 5 r demo1
Practice 8.4
# useradd u 525 g 515 d /home/sudha m s / bin/sh sudha # useradd u 526 g 516 d /home/raja m s / bin/sh raja # useradd u 527 g 517 d /home/ravi m s / bin/sh ravi
# useradd u 528 g 528 d /home/ragu m s / bin/sh e 25-09-2001 ragu
# useradd u 529 g 529 d /home/ramesh m s / bin/sh ramesh # useradd u 530 g 520 d /home/dummy1 m s / bin/sh dummy1 # useradd u 531 g 521 d /home/dummy2 m s / bin/sh dummy2 # useradd u 532 g 522 d /home/dummy2 m s / bin/sh dummy2
set password for sudha, raja, ravi, ragu, ramesh, dummy1, dummy2, dummy3
The above command will create users sudha, raja, ravi, ragu, ramesh, dummy1, dummy2 and dummy3 with respective users ids and group ids. Finally you have to create password for all the above users. For user ragu we are assinging expiry date.
Syntax
Usermod [options ] login The options which apply to the usermod command are as follows: Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
101
UNIX Administration -c comment This specifies new information about the users password file comment field. -d home_dir This indicates the users new login directory. If the -m option is given, the contents of the current home directory will be moved to the new home directory, which is created if it does not exist already. -e expire_date This specifies the date on which the users account will be disabled. The date is specified in the format YYYY- MM-DD. -f inactive_days This specifies the number of days for which the account will remain inactive after the password expires until the account is permanently disabled. A value of 0 disables the account as soon as the password expires, and a value of -1 disables this feature.The default value is -1. -g initial_group This specifies the group name or number of the users new initial login group. The group name must exist. A group number must refer to an already existing group. The default group number is 1. -G group,[...] This indicates a list of supplementary groups to which the user belongs. Each group is separated from the next by a comma, with no intervening whitespace. The groups are subject to the same restrictions as the group given with the -g option. If the user is currently a member of a group which is not listed, the user will be removed from the group. -l login_name This is used to change the name of the user from login to login_name. In particular, the users home directory name should probably be changed to reflect the new login name. -s shell This is used to specify the name of the users new login shell. Setting this field to blank causes the system to select the default login shell.
-u uid This specifies the numerical value of the users ID.This value must be unique, unless the -o option is used. The value must be non-negative. Values between 0 and 499 are typically reserved for system accounts. Any files which the user owns that are located in the directory tree rooted at the users home directory will have the file user ID changed automatically. Files that are outside the users home directory must be altered manually. -L This option locks a users password. This puts a ! in front of the encrypted password and effectively disables it. -U This option is used to unlock a users password. This removes the ! in front of the encrypted password. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
102
User and Group Management Note : usermod does not allow the name of a user who is logged in to be changed. It should be ensured that the named user is not executing any process when this comand is issued. The owner of any crontab files should be changed manually. Changes involving NIS should be made on the NIS server. Related files to be updated when the usermod command is used are /etc/passwd - user account information /etc/shadow - secure user account information /etc/group - group information
Practice 8.5
# usermod G 515,517 raja # usermod s /bin/bash sudha # usermod l ravi # usermod u ravi The above command will modify user raja by adding two secontary groups. For user sudha we are changing the default login shell to bash. Using the usermod locking and unlocking the user ravi.
Syntax
userdel [-r] login There is only one option that is used with this command. -r This option is used to remove files in the users home directory along with the home directory. Files located in other file systems will have to be searched and deleted manually. Note : Userdel does not allow an account to be removed if the user is currently logged in. Any running process, which belongs to an account that is being deleted has to be killed. Any NIS attributes on an NIS client need not be removed. This must be performed on the NIS server. Related files to be updated when the userdel command is used /etc/passwd - user account information /etc/shadow - secure user account information /etc/group - group information
Practice 8.6
# userdel r dummy1 # userdel r dummy2 # userdel r dummy3
103
UNIX Administration The above command userdel will delete the user dummy1,dummy2 and dummy3 and also removing the respective users home directories and files.
Password Changes
The user is first prompted for the old password. This password is then encrypted and compared against the stored password. The user has only one chance to enter the correct password. The super user is permitted to bypass this step so that the forgotten passwords may be changed. After the password has been entered, password-aging information is checked to see if the user is permitted to change the password at that particular time. If not, passwd refuses to change the password and exits. The user is then prompted for a replacement password. This password is tested for complexity. As a general guideline, passwords should consist of 6 to 8 characters including one or more from each of the following sets: Lower case alphabets Upper case alphabets Digits 0 - 9
Care must be taken not to include the system default erase or kill characters. passwd will reject any password which is not suitably complex. If the password is accepted, passwd will prompt again for the password and compare the second entry against the first. Both entries are required to match in order to change the password.
Syntax
Passwd [options] username The options that can be used with this command are -l This option is used to lock the specified account and it is available to only the root user. The locking is performed by rendering the encrypted password into an invalid string (by prefixing the encrypted string with an !). -u This is the reverse of the previous option. It unlocks the account password by removing the ! prefix. This option is available to only the root user. By default, passwd will refuse to the create a passwordless account (it will not unlock an account that has only ! as a password). The force option -f will override this protection. -d This is a quicker way of disabling a password for an account. It will set the named account passwordless. This option is only available to the root user. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
104
User and Group Management -S This will output a short information about the status of the password for a given account. It is available to the root user only. Related files to be updated when the passwd command is used are /etc/pam.d/passwd Note : In the case of SUN and SCO /etc/passwd
Practice 8.7
# passwd L sudha # passwd U sudha # passwd d ramesh # passwd s ragu The above command passwd will lock and unlock user sudha, disable the user ramesh and print the status for the user ragu.
105
UNIX Administration The maximum number of days during which the password remains valid. warn The number of days before the password expires that the user is warned. Indicates the expiry of password. inactive This indicates the number of days of inactivity allowed for the user. expire This indicates an absolute date specifying when the login may no longer be used. flag This indicates that it is reserved for future use, and set to zero. Currently it is not used. Related files get updated when the passwd command is used /etc/pam.d/passwd /etc/shadow - shadow password file Note : In the case of SUN and SCO. /etc/passwd. The encrypted password consists of 34 characters that are chosen from a 64-character alphabet (., /, 0-9, A-Z, a-z). In order to make the system administration manageable, /etc/shadow entries should appear exactly in the same order as /etc/passwd entries; this includes + and - entries if the compute source is being used.
106
107
UNIX Administration
Lecture 9
Objectives
In this lecture you learn the following
Knowing about the Devices and Disk management About the geometry of the Hard disk. Able to create partition and Formatting the hard disk About Device naming
will
108
Coverage Plan
Lecture 9
9.1 Snap Shot 9.2 Device & Disk Management 9.3 Short Summary 9.4 Brain Storm
109
UNIX Administration
Disk Geometry
Hard disks are made of one or more magnetic disks, called PLATTERS, which rotate around a central shaft. Each platter contains millions of magnetic particles, whose magnetic field determines the storage of information.
Boom Head Sector Spindle Track Platter
Cylinder
For each platter there is a movable arm from the outer edge of the disk to the central shaft. At the end of each arm is a read-write head that can access any point on the disks surface. All the arms are connected Fig 9.1 together so that they move in unison. Each platter contains a set of blocks or sectors, which are used to store data. Sector is the smallest unit of one platter. One sector contains 512 bytes. The blocks are organized into circular rings called tracks. A group of sectors together form a track.
110
Figure 7.2
Fig 9.2 Tracks on different platters that are located at the same distance from the edge of their respective disk platter, are combined to form a cylinder. This is diagrammatically represented in Figure No. 9.3
Fig 9.3 Since all the tracks of a cylinder are accessed by the read-write head at the same time, the delay in accessing the data stored on different platters but in the same cylinder is much lesser than if the data is located in different cylinders.
Partitions
A hard disk can be divided into several partitions. Each partition functions as if it were a separate hard disk. So, one hard disk can be divided into two partitions to have two operating systems on it. Each operating system uses its partition according to its preference without disturbing the other. In this way the two operating systems can co-exist peacefully on the same hard disk. Floppies are not partitioned. There is no technical reason against this, but since they are so small, partitions would be useful only very rarely. CD-ROMs are also not partitioned, also since its easier to use them as one big disk, and there is seldom a need to have several operating systems on one.
111
UNIX Administration The information about how a hard disk has been partitioned is stored in its first sector (that is, the first sector of the first track on the first disk surface). The first sector is the master boot record (MBR) of the disk. This is the sector that the BIOS reads and starts when the machine is first booted. The master boot record contains a small program that reads the partition table, checks the type of partition that is active (that is, marked bootable), and reads the first sector of that partition, the boot sector (the MBR is also a boot sector, but it has a special status). This boot sector contains a smaller program that reads the first part of the operating system that is stored on that partition (assuming it is bootable), and then starts it. The partitioning scheme is not built into the hardware, or the BIOS. It is only a convention that many operating systems follow. Some operating systems support partitions, but they occupy one partition on the hard disk, and use their internal partitioning method within that partition. The latter type co-exists with other operating systems (including Linux), and does not require any special measures. But an operating system that does not support partitions cannot co-exist with any other operating system on the same disk . It is a wise practice to create a physical record of the partition table, so that it can be retrieved when the partition gets corrupted. The relevant information is given by the fdisk -l command: # fdisk -l /dev/hda Disk /dev/hda: 15 heads, 57 sectors, 790 cylinders Units = cylinders of 855 * 512 bytes Device Boot /dev/hda1 /dev/hda2 /dev/hda3 /dev/hda4 /dev/hda5 /dev/hda6 # Begin 1 25 49 409 409 745 Start 1 25 49 409 409 745 End 24 48 408 790 744 790 Blocks 10231+ 10260 153900 163305 143611+ 19636+ Id 82 83 83 5 83 83 System Linux swap Linux native Linux native Extended Linux native Linux native
112
Boot sector Logical partition Unused boot sector Data area Logical partition Unused boot sector Data area Unused disk space Boot sector Extended partition
Fig 9.4
Data area
Primary Partition
113
UNIX Administration with different configurations. Since there is no data to be backed up it is not tedious to modify the size of the partition several times. There is a program for MS-DOS, called fips, which resizes an MS-DOS partition without requiring the backup and restore, but for other filesystems it is still necessary. Note : In Sun Solaris, the format command can be used to create or modify partitions in a disk. After selecting the disk, the format menu is displayed, partition should be selected to display the partition menu. The required commands are provided in this menu to changeand modify the partitions.
Formatting
Formatting is the process of writing marks on the magnetic media that are used to mark tracks and sectors. Before a disk is formatted, its magnetic surface is a complete mess of magnetic signals. When it is formatted, some order is brought into the chaos by essentially drawing lines where the tracks go, and where they are divided into sectors. The actual details are not quite exactly like this, but that is irrelevant. A disk cannot be used unless it is formatted. In MS-DOS, the word formatting is also used to refer to the process of creating a file-system. There, the two processes are often combined, especially for floppies. When the distinction needs to be made, the real formatting is called low-level formatting, while making the file-system is called high-level formatting. In UNIX, the two are called formatting and making a file-system. For IDE and some SCSI disks the formatting is actually done at the factory and does not need to be repeated. In fact, formatting a hard disk can cause it to work less efficiently, for example because a disk might need to be formatted in a unique way to allow automatic bad sector replacement to work. Disks that need to be or can be formatted often require a special program because the interface to the formatting logic inside the drive differs from drive to drive. The formatting program is often either on the controller BIOS, or is supplied as an MS-DOS program; neither of these can easily be used from within Linux. During formatting bad spots might be encountered on the disk, called bad blocks or bad sectors. These are sometimes handled by the drive itself, but if more of them develop parts of the disk should not be used. The logic behind this is built into the file-system. Alternatively, one might create a small partition that covers just the bad part of the disk. This approach might be a good idea if the bad spot is very large, since filesystems can sometimes have trouble with very large bad areas.
114
Device and Disk Management Floppies are formatted using fdformat. The floppy device file that is to be used is given as the parameter. For example, the following command would format a high density, 3.5 inch floppy in the first floppy drive: # fdformat /dev/fd0H1440 Double-sided, 80 tracks, 18 sec/track. Total capacity 1440 kB. Formatting ... done Verifying ... done # The above command would format a high density, 3.5 inch floppy in the first floppy drive. To use an autodetecting device (e.g., /dev/fd0), the parameters of the device have to be set with setfdprm first. To achieve the same effect as above, the following has to be performed: # setfdprm /dev/fd0 1440/1440 # fdformat /dev/fd0 Double-sided, 80 tracks, 18 sec/track. Total capacity 1440 kb. Formatting ... done Verifying ... done # Here the setfdprm, will automatically set the device and when using the fdformat command there is no need to specify particulars of the device. It is usually more convenient to choose the correct device file that matches the type of the floppy. Note that it is unwise to format floppies to contain more information than what they are designed for. fdformat will also validate the floppy, i.e., check for bad blocks. It will try a bad block several times ( the drive noise changes dramatically). If the floppy is only marginally bad (due to dirt on the read/write head, some errors or false signals), fdformat would not complain, but a real error will abort the validation process. The kernel will print log messages for each I/O error that it finds. These messages will go to the console or, if syslog is being used, to the file /usr/log/messages. fdformat itself does not indicate the error. # fdformat /dev/fd0H1440 Double-sided, 80 tracks, 18 sec/track. Total capacity 1440 kB. Formatting ... done Verifying ... read: Unknown error # Here the errors indicate the bad floppy and the format process is incomplete. Hence the floppy cannot be used. The badblocks command can be used to search any disk or partition for bad blocks (including a floppy). It does not format the disk, so it can be used to check even existing filesystems. The example below checks a 3.5 inch floppy with two bad blocks. # badblocks /dev/fd0H1440 1440 718 719 #
115
UNIX Administration Badblocks command outputs the block numbers of the bad blocks that are found. Most filesystems can avoid such bad blocks. They maintain a list of known bad blocks, which is initialized when the filesystem is made, and can be modified later. The initial search for bad blocks can be done by the mkfs command (which initializes the filesystem), but later checks should be done with badblocks and the new blocks should be added with fsck. Many modern disks automatically notice bad blocks, and attempt to fix them by using a special, reserved good block. This is invisible to the operating system. Even such disks can fail, if the number of bad blocks grows very large.
Device Naming
Most of the implementations of Unix automatically create the correct device entry when the system is made to boot with the new drive attached. Once this entry is created, permissions should be checked. Only root should be given read and write access to it. Comparison of device names Linux Sco Solaris 2.X /dev/hda0 /dev/sda0 /dev/[r]dsk/c#b#t#d#s# /dev/[r]dsk/c#b#t#d#s# /dev/dsk/c0t0d0s0 /dev/fd0 /dev/fd0, /dev/diskette0 /dev/ht0 /dev/st0 /dev/rmt/0 /dev/nht0 /dev/st0 /dev/tape
Disk *
/dev/rmt/0n
dmesg command - Identifies the devices that are connected to the system, from the output of dmesg command the logical disk names can be identified.
The system with the new hard disk installed is rebooted. Linux will auto detect the disk. Use thedmesg command to find out the device that is being used by the disk.
116
Device and Disk Management For IDE machines primary master =>/dev/hda primary slave =>/dev/hdb secondary master=>/dev/hdc secondary slave =>/dev/hdd
Use cfdisk to partition the disk. Use mke2fs to create a file system Edit fstab to make mounting easier.
SCSI hard disks are named with sdx, where x is a hard disk letter. The disk with the lowest SCSI ID on the first controller will become sda, the next one will become sdb, and so on. Hard disks, are called hda, hdb, hdc, and so on. Hda is the master disk on the first controller, hdb is the slave disk on the first controller, hdc is the master disk on the second controller, and so on. GNU/Linux systems generally use a partition scheme where a hard disk can have up to four primary partitions. To make more partitions one of these should be made as an extended partition where several logical partitions can be made. The partitions take the name of the disk they belong to, and a number. The first primary partition on the first SCSI disk is therefore sda1, the second primary partition is sda2, and so on. The first and second logical partition on an extended partition on the first SCSI disk are sda5 and sda6, and so on. cfdisk can be started from the command line with the command cfdisk /dev/sdx where x is the SCSI hard disk letter, like a, b, c, d, etc. So to partition the first hard disk on the SCSI controller, the command cfdisk /dev/sda should be used. When cfdisk is started an interface is obtained where the current partition table is listed with the names and, is started command buttons on the bottom of the screen. To change between partitions, the up and down arrow keys have to used. To change between commands, the left and right arrow keys are to be used. To delete an existing partition, the up and down keys should be highlighted, the delete command should be selected with the left and right arrows keys, and Enter should be pressed. To make a new partition, the New command should be selected with the left and right arrow keys, and entered. Choice is obtained between a primary and a logical partition. For a logical partition, the program will automatically make an extended partition. Then the size of the partition (in MB) must be chosen. If the value cannot be entered in MB, the user must return to the main screen with the Esc key, and select MB with the Units command. To set the type of a partition, for bootable PReP, Linux swap or Linux ext2, the actual partition needs to be selected, and Type command must be selected. A list of different types is obtained. On pressing space more choice is obtained. The type that is needed is to be typed, and the number at the prompt should be entered. To be able to boot from a primary partition, it should be made bootable. The actual partition should be highlighted and the Bootable command should be selected.
117
UNIX Administration After choosing the layout of the disk, the Write command should be selected. The partition table will be written to disk that will destroy all data on partitions has been deleted or changed. To exit the program, the Quit command should be selected. Note : In Solaris, if a new hard disk is added, a reconfiguration file is created in the root directory to detect the presence of new hardware, then the system should be shutdown. Connect the new disk to the system and reboot. The disk will be identified by the system. If required partitions should be created using format command, file system should be created using newfs. Make necessary changes in the /etc/vfstab for mounting the new created file system. The following program shows how to create a /reconfiguare file. i) Create a /reconfigure file # touch /reconfigure #init 0 Connect the new disk to the system
ii)
iii) Turn on the power iv) Boot the system v) Create partitions on the disk using the format command (if required) # format Create file system # newfs/dev/rdsk/c # t # d # s # vii) Make necessary changes in the /etc/vfstab file Instead of creating a /reconfigure file a reconfigure boot can be performed by using b r command at the PROM level in order to make the system recognize the presence of a new device. Hard disk can be added without shutting down the system. In this case, drvconfig and disks commands have to be used to identify the new disk. These commands should be invoked with no parameters. Never attempt a low-level format on IDE disk. It will destroy the disk itself.
vi)
118
Device and Disk Management are made to a peripheral, small changes to the device driver file can be linked to the kernel to keep the operating system informed of the new features and capabilities. When an application instructs a device to perform an action, the Linux kernel passes the request to the device driver and allows it to handle the communications. Linux keeps device files in the /dev directory by default and convention. It is permissible to keep device files anywhere on the file system, but keeping them all in /dev makes it obvious that they are device files. Every type of device on the Linux system communicates in one of the two ways: character by character or as a set of data in a predefined chunk or block. Terminals, printers, and asynchronous modems are character devices, using characters sent one at a time and echoed by the other end. Hard drives and most tape drives, on the other hand, use blocks of data, because this is the fastest way to send large chunks of information. These peripherals are called either character mode or block mode devices, based on the mode of communication. Note : Another way to differentiate between character and block mode devices is by the way in which buffering to the device is handled. Character mode devices do their own buffering. Block mode devices, which usually communicate in chunks of 512 or 1,024 bytes, have the kernel perform the buffering. Some devices can be both character and block mode devices. Some tape drives, for example, can handle both character and block modes, and therefore have two different device drivers. The device driver that is used depends on how the user wants to write data to the device. The device file has all the details about whether the device is a character mode or block mode device. There is an easy way to find out the type of device of a peripheral. The output of the listing command shows file permissions (such as ls -l). If the first character is a b, the device is a block mode device; a c indicates a character mode device. Device files are usually named to indicate the type of device. Most terminals, for example, have a device driver with the name tty followed by two or more letters or numbers, such as tty1, tty1A, or tty04. The letters tty identify the file as a terminal (tty stands for teletype), and the numbers or letters identify the specific terminal referred to. When coupled with the directory name /dev, the full device driver name becomes /dev/tty01.
119
UNIX Administration Some devices use the major and minor device numbers in a strange way. Some tape drives, for example, use the minor number to identify the density of the tape and adjust its output in that manner. Device files are created with the command mknod (make node) and removed with the standard rm command.
The argument after the device or pathname specifies whether the file is a block mode device , character mode device , FIFO device (p), or unbuffered character mode device (u). One of these arguments must be present on the command line. Following the type of file argument are two numbers for the major and minor device numbers assigned to the new file. Every device on a UNIX system has a unique number that identifies the type of device (the major number) and the specific device itself (the minor number). Both the major and minor numbers must be specified for any new block, character, or unbuffered mode device. Device numbers are not specified for a type p device.
120
Lecture 10
Objectives
In this lecture you learn the following
About File System Knowing about Local Based File System, RAM Based File System and Network File System Understand the Types of File Systems Mounting the Local Based File System
will
121
UNIX Administration
Coverage Plan
Lecture 10
10.1 Snap Shot 10.2 Local Based File System Types 10.3 The ext2 File System 10.4 Types of Files System 10.5 Mounting the Local Based File System 10.6 Common Commands Management 10.7 Short Summary for File System
122
These File System types are implemented on the hard disk. (Disk based,CD-ROM, or Floppy). Ext2, is the default Unix File System in the case of Linux . It is used to optimize disk performance through the use of cylinder groups, sectors, tracks and data Blocks.
123
UNIX Administration This boot block can be found only in the root File System. There is some space allocated for the boot Block at the beginning of each File System.
The SuperBlock
The SuperBlock is located next to the boot Block. The SuperBlock contains a table of information about the File System. The following information is included in the SuperBlock: Number of data Blocks, cylinder groups Size of the data Block Mount, where the File System gets mounted
Backup SuperBlocks
This contains the backup of the superBlock. It is replicated in each and every dataBlock and cylinder group. This enables to protect against data loss. These Blocks are created when File Systems are created.
Cylinder Groups
The HDD are partitioned by cylinder groups. The data of the File System will get stored across several cylinder groups. The cylinder group contains inodes, dataBlocks, free Blocks and free inodes.
Inodes
An inode maintains information about each file The inode contains information about the type of file, the access mode of the file, the user and group to which the file belongs, the size of the file, the time at which it was last accessed and modified, the number of data Blocks which are allocated and used for that particular file and pointers. Depending on the type of File System, the inode can contain more than 40 pieces of information. The fields that are of concern for the system administrator are as follows: mode Indicates the permission mask and type of the file.
link count Indicates the number of directories that contain an entry with this inode number. user ID Indicates the ID of the files owner.
group ID Indicates the ID of the files group. size access time mod time inode time Block list Indicates number of bytes in this file. Indicates the time at which the file was last accessed. Indicates the time at which the file was last modified. Indicates the time at which this inode structure was last modified. Indicates a list of disk Block numbers which contain the first segment of the file.
indirect list Indicates a list of other Block lists. The fields mode, link count, user ID, group ID, size, and access time are used when generating file listings. Note : The inode does not contain the name of the file. This information is held in the directory file .
Pointers
There are two types of pointers: Direct pointer and indirect pointer.
124
Introduction to File System Direct Pointer These pointers directly refer to the data Blocks. There are 12 direct pointers that directly reference the data Blocks of a file up to 96Kb.
Indirect Pointer There are three types of indirect pointers. They are described below:
Single Indirect It refers to a File System Block containing pointers to data Blocks. It will contain 4-Kbyte data Blocks and it will point up to an additional 8 Mb of data.
125
UNIX Administration
Generally speaking, each operating system has its own unique filesystem. Files created on one operating system are not readable on any other operating system. At present, Unix supports more filesystems than any other OS. When Unix is installed the filesystem is created on the hard disk. As far as Unix is concerned, a filesystem is a device that is formatted to store files that can be randomly accessed. This includes the hard disk partitions, floppy disks, CD-ROMs, but not tape drives (which are accessed sequentially and thus cannot contain a filesystem per se). The current list of major filesystems supported by Unix are as follows: Linux Swap Filesystem - swap MS-DOS Filesystem - msdos Network File System (NFS) - nfs Novell Filesystem - ncpfs NT - ntfs Second Extended Filesystem - ext2 (Linux standard filesystem) Uniform Filesystem - ufs Used by BSD , SunOS
Normal Files
These are the files that are used the most. They can be either text or binary files. However, their internal structure is irrelevant from a System Administrators standpoint. The characteristics of a file are specified by the inode in the File System that describes it. An ls -l on a normal file will look as follows: -rw 1 kishore unix 42 May 12 13:09 hello
126
Directories
These are special kind of files that contain a list of other files. Although there is a one-to-one mapping of inodes to disk Blocks, there can be a many-to-one mapping from a directory entry to an inode. When viewing a directory listing using the ls -l command, the directories can be identified by their permissions starting with the d character. An ls -l on a directory will look as shown below: drwx 2 kishore unix 512 May 12 13:08 public_html
Hard Links
A hard link is actually a normal directory entry except that instead of pointing to a unique file , it points to an already existing file . This gives the illusion that there are two identical files when a directory listing is done. Since the system sees the hard-linked file as another file, it treats it as such. This is most apparent during backups because hard-linked files get backed up as many times as there are hard links to them. Because a hard link shares an inode, it cannot exist across File Systems. Hard links are created with the ln command. For example, when a directory listing is performed using ls -l, the result would be as shown below: -rw 1 kishore unix 42 May 12 13:04 hello
When ln hello goodbye is typed and another directory listing is again performed using ls -l, the following can be observed: -rw -rw 2 kishore 2 kishore unix unix 42 May 12 13:04 goodbye 42 May 12 13:04 hello
Notice how this appears as two separate files that just happen to have the same file lengths. Also note that the link count (second column) has increased from one to two. It can be verified that both the files are actually the same by using ls -il: 13180 -rw 13180 -rw 2 kishore 2 kishore unix unix 42 May 12 13:04 goodbye 42 May 12 13:04 hello
Note : Care should be taken when creating hardlinks, especially when hardlinking to a directory. It is possible to corrupt a filesystem by doing so since the hardlink does not contain the fact that the i-node being pointed to needs to be treated as a directory.
Symbolic Links
A symbolic link (sometimes referred to as a symlink) differs from a hard link because it does not point to another inode but to another filename. This allows symbolic links to exist across File Systems as well as be recognized as a special file by the operating system:
Example
drwx lrwx 2 kishore 1 kishore icg icg 512 May 12 13:08 public_html 11 May 12 13:08 www -> public_html
Sockets
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
127
UNIX Administration Sockets are the means for UNIX to network with other machines. Typically, this is done using network ports. However, the File System has a provision to allow for interprocess communication through socket files. If a socket file needs to be removed, the rm command has to be used. Socket files are identified by their permission settings beginning with an s character. .
Example
srwxrwxrwx 1 root admin 0 May 10 14:38 X0
Named Pipes
Similar to sockets, named pipes enable programs to communicate with one another through the File System. The mknod command can be used to create a named pipe. Named pipes are recognizable by their permission settings beginning with the p character.
Example
prw 1 kishore unix 0 May 12 22:02 mypipe
Character Devices
These special files are typically found in the /dev directory and provide a mechanism for communicating with system device drivers through the File System one character at a time. They are easily noticed by their permission bits starting with the c character.
Example
crw-rw-rw1 root wheel 21, 4 May 12 13:40 ptyp4
Block Devices
Block devices also share many characteristics with character devices. That is, they too exist in the /dev directory and are used to communicate with device drivers, and have major and minor numbers. The key difference is that Block devices typically transfer large Blocks of data at a time versus one character at a time.
Example
brw 2 root staff 16, 2 Jul 29 1992 fd0c
128
Introduction to File System / /bin /dev /etc /home /lib /opt /proc /sbin /tmp /usr /usr/bin /var Root directory, start of the directory tree Commands needed to run the system Device files that represent the system hardware Important system configuration files The (private) directories of the users Shared libraries Optional software, large systems The process File System Commands reserved for the superuser and needed for system start Temporary files User commands and applications, Configuration files, can be mounted read-only Publicly accessible commands Commands reserved for the superuser Configuration files (linked from /usr) /usr/sbin
The option -t indicates the type of the File System and the option -c indicates the device path on which the new File System is to be created.
Practice 10.1
The following example illustrates how to create a new File System. # mkfs -t ext2 -c /dev/hda*
Blocksize=4096,611648 Inodes 1220932 Blocks 61046 Blocks(5.00%) reserved for Super user 32768 inodes per group. Super Block backups states on Blocks (for fsck ) 32768,98304,163840,229376,294912,819200,884736. mkfs is the command which is used to create a new File System on the device called /dev/hda12. Once a new File System is created by using mkfs and the new File System has to be pointed on the mount point. The mount point should be unique.
129
UNIX Administration Note : In Solaris and SCO mkfs is the commmand which is used to create a new File System, newfs is a user-friendly command which is used to create a New File System on Solaris.
Syntax:
# newfs s [size of the File System] d [ device]
Options:
-s -d Indicates the size of the File System. Indicates the device path where a new filesystem has to be created.
130
There are options that can be passed to the mount command. The most important characteristics are specified in the -o option. These characteristics are: rw read/write ro read only bg background mount (if the mount fails, place the process into the background and keep trying until success.)
131
UNIX Administration All the mounted File System information will stored in /etc/mtab.. /etc/fstab virtual File System table provides entries for mounting File Systems at the time of booting the system. mount is the command which is used to mount a File System in Solaris. Mounted File Systems are found in /etc/vfstab in Sun Solaris and in SCO Unix.
Syntax
# mount F [File System type] o [options] [device to mount] [mountpoint]
Options:
-F Indicates File System which is used for mounting.ufs is the file type in Solaris. Pcfs is the File System to access floppy, hsfs is the File System to accessing CdRom. Indicates the permission. Read and write permission read only permission.
-o rw: ro:
Syntax
# mount /dev/device /directory/to/mount
Practice 10.2
The following example illustrates the mounting of a floppy disk. # mount /dev/fd0 /mnt /dev/fd0 is the name of the floppy device to be mounted and the floppy is mounted on the /mnt directory.
Practice 10.3
The following example illustrates the mounting of a CD ROM disk # mount /dev/cdrom0 /mnt
/dev/cdrom0 is the CD ROM device to be mounted and the CD ROM is mounted on the /mnt directory. To access the CD ROM disk the following should be done: # # # # cd /mnt ls umount /mnt eject cdrom0
Note : The eject command is used to eject the CD ROM. Before ejecting the CD ROM, the CD has to be unmounted using the umount command. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
132
All the mounted File System information will be stored in ,/etc/mnttab in Sun Solaris and in ,/etc/mnttab in SCO Unix. Linux uses a special file called /etc/fstab. This file lists all the partitions that need to be mounted at boot time and the directory where they need to be mounted. Along with that information parameters to the mount command can be passed. Each File System to be mounted is listed in the /etc/fstab file in the following format: /dev/device /dir/to/mount ftype parameters fs_freq fs_passno
Practice 10.4
The following example illustrates how to mount a File System. /dev/hda1 /dev/device /dir/to/mount /home/kishore /ext2 rw 0 0
The device to be mounted, for instance, /dev/hda4. The location at which the File System should be mounted on your directory tree.
Ftype
The File System type. This should be 4.2 under SunOS, ufs under Solaris, ext2 under Linux, nfs for NFS mounted File Systems, swap for swap partitions, and proc for the /proc File System. Some operating systems, such as Linux, support additional filesystem types, although they are not as likely to be used. The parameters that are passed to mount using the -o option. They follow the same comma-delineated format. An example entry would look like rw,intr,bg. Used by dump to determine whether a File System needs to be dumped. Used by the fsck program to determine the order to check disks at boot time.
Parameters
fs_freq fs_passno
Note : In Sun Solaris, /etc/vfstab is the virtual File System table that provides entries for mounting the File System at the time of booting the system. #vi /etc/vfstab <device to mount> <device to fsck> < mount point> <fs type> <fsck pass> <mount at boot> <mount options> The fields are described below: Device to mount Device to fsck entry should be - . mountpoint : Which is the mount point on which the resource is to be mounted. (/mnt). : : Is the device to be mounted. What is the name of the raw device to fsck; for a remote mount, the parameter is not applicable, and the
133
UNIX Administration Fstype : Which is the type of File System of the resource to be mounted. (ufs) Which is the pass number to use for multiple fscks. For a remote mount, the parameter is not applicable, and the entry should be - . The options passed to the mount command
fsckpass
mntopts
Syntax:
# umount [mount point]
Practice 10.5
The following command illustrates how to unmount a File System. # umount /var
134
Introduction to File System 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. Listing the Newest Files Finding and Remove Old or Inactive Files Remove the inactive files that you listed in the previous step Clearing out temporary directories Finding and delete core files Deleting crash dump files What is fsck? The fsck Utility Where is fsck? When should an fsck run? How to use fsck?
df command and its options can be used to report the number of free disk blocks and files.
Syntax:
df [option] option: -k - prints the free disk space in terms of k bytes. Consider the following example # df Filesystem /dev/hda3 /dev/hda6 /dev/hda7 # df -k 1k-blocks 396623 101089 1517920 1517920 54416 Used 71930 2453 12952 1276308 18548 Available 304212 93417 1427860 164504 33059 Use% Mounted on 19% / 3% /boot /home 89% /usr 36% /var 1024-blocks 247871 50717 481998 Used Available 212909 22161 15507 32591 15 457087 Capacity 91% 32% 0% Mounted on / /var /local
1%
The columns reported show: Filesystem 1024-blocks Used Available Capacity Refers to the file system being shown. File systems mounted using NFS are shown as hostname:/dir/that/is/mounted The number of 1 KB blocks the file system consists of. (Its total size.)
The number of blocks used. The number of blocks available for use.
Percentage of partition currently used.
135
UNIX Administration Mounted on The location in the directory tree where this partition has been mounted on.
The du command summarizes disk usage by directory. It recurses through all subdirectories and shows disk usage by each subdirectory with a final total at the end. Displaying the size of directories The following command illustrates the disk usage by the directoy.
Syntax
du [options] <directory-name> Options Directory -a -s # du 409 945 68 60 391 141 873 3402 ./doc ./lib ./man ./m4 ./src ./intl ./po . Show usage for the specified directory. The default is the current directory. Show usage for all files, not just directories. Show only the total disk usage.
The first column shows the blocks of disk used by the subdirectories. The second column shows the names of the subdirectory being evaluated and to see how many kilobytes each subdirectory consumes.
1 2 1 2 2
585872 Jan 28 512 Dec 1 562 Jan 2 512 Dec 1 512 Jan 28
136
Introduction to File System -rw-rw-r 1 adm adm 125736 Jan 28 14:53 wtmpx
# ls s | sort -nr | more here sort nr Sorts the list of files by block size from smallest to largest. Consider the following example In the following example, wtmpx and lastlog are the largest files in the /var/adm directory. # cd /var/adm # ls -s | sort -nr | more 320 wtmpx 128 lastlog 74 pacct 56 messages 30 wtmp 6 utmpx 2 utmp 2 sulog 2 sa 2 passwd 2 log 0 spellhist total 624 Finding files that exceed a given size limit To locate and display the names of files that exceed a specified size, the find command can be used as shown below. # find directory -size +nnn Directory -size +nnn listed. Where is the directory to be searched Is a number of 512-byte blocks. Files that exceed the size indicated are
137
space taken up by user accounts on local file system can be found. Sizes are displayed in 512-byte blocks. Consider the following example # du /var/log /var/cron 4 /var/log 3250 /var/cron Consider the following example displays the sizes of two directories, all of the subdirectories and files they contain, and the total number of blocks contained in each directory. # du -a /var/log /var/cron 0 /var/log/authlog 0 /var/log/syslog 2 /var/log/sysidconfig.log 4 /var/log 3248 /var/cron/log 3250 /var/cron Consider the following example displays the total sizes of two directories. # du -s /var/log /var/cron 4 /var/log 3250 /var/cron
conserve disk space include emptying temporary directories such as the ones located in /var/tmp or
138
Introduction to File System # ls t /var/adm sulog wtmpx messages utmp utmpx lastlog # ls -l /var/adm total 686 drwxr-xr-x 5 adm -rw 1 uucp -rrr 1 root drwxr-xr-x 2 adm -drwxr-xr-x 2 adm drwxr-xr-x 2 adm wtmp sa messages.0 messages.1 messages.2 messages.3 vold.log log acct spellhist aculog passwd
13 13 27 13 13 20
The inactive files can now be deleted as follows # rm cat filename Here filename refers to the file created by this command which contains the list of inactive files.
Example Finding and Removing Old or Inactive Files The following example locates regular files in /var/adm and its directories that have not been accessed in the last 60 days and saves the list of inactive files in /var/tmp/deadfiles. These files are then removed with the rm command. # find /var/adm -type f -atime +60 print > /var/tmp/deadfiles & # more /var/tmp/deadfiles /var/adm/wtmp /var/adm/wtmpx /var/adm/sulog # rm cat /var/tmp/deadfiles
139
CAUTION
It should be ensured that the user is in the right directory before completing the following step.The next step deletes all files in the current directory. The files and subdirectories in the current directory can be deleted as follows. # rm -r * The user can change to other directories containing temporary or obsolete subdirectories and files and delete them by repeating Step 3 above.
wxconAAAa0003r:0.0 wxconAAAa0003u:0.0
wxconAAAa000NA:0.0 wxconAAAa000cc:0.0
140
CAUTION
It should be ensured that the user is in the right directory before completing the following step. The next step deletes all files in the current directory. The crash dump files can be removed as shown below. # rm * It can be verified if the crash dump files are removed as follows # ls Consider the following example The following example shows how to remove crash dump files from the system lambent, and how to verify that the crash dump files were removed. # cd /var/crash/lambent # rm * # ls
141
CAUTION
These checks do not apply to compressed file systems. Directory checks Directory entry containing an i-node number marked free in the i-node map i-node number out of range Dot (.) link missing or not pointing to itself Dot dot (..) link missing or not pointing to the parent directory Files that are not referenced or directories that are not reachable Inconsistent disk map Inconsistent i-node map
fsck command does not make corrections to a mounted file system fsck command can be run on a mounted file system for reasons other than repairs. However, inaccurate error messages may be returned when the file system is mounted
Where is fsck?
When fsck is run, an executable in either the /usr/sbin utility. or /bin directory called fsck is
run but this is not the real fsck. It is just a dispatcher that invokes a file system type-specific fsck
CAUTION
It is better to run fsck after the backups rather than before. If fsck finds major problems, it could leave the file system in a worser shape than it was prior to running.
Syntax
fsck [options] [ device or mount point ] Options Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
142
Introduction to File System A -N -V -t Runs fsck for all the file system, Prints out the help message. (Solaris) Prints the help message. Indicates the file system for which fsck is to be run.
It checks and fixes the file system in a noninteractive mode and exists immediately if there is a problem that needs users intervention.
143
UNIX Administration
144
Lecture 11
Objectives
In this lecture you learn the following
Understanding the concept of NFS Able to Start and Stop the nfs Deamons Mounting the File System Able to Configure nfs Servers and Clients
will
145
UNIX Administration
Coverage Plan
Lecture 11
11.1 Snap Shot 11.2 What is NFS 11.3 Starting and Stopping the nfs Daemons 11.4 Mounting the Remote File System 11.5 Short Summary 11.6 Brain Storm
146
Allows multiple computers to use the same files, so everyone on the network can access the same data
Reduces storage costs by having computers share applications instead of needing local disk space for each user application
Provides data consistency and reliability because all users can read the same set of files
The Network File System (NFS) was developed to allow machines to mount a disk partition on a remote machine as if it were on a local hard drive. This allows for fast sharing of files across a network. The version of nfs is 2. It also gives the potential for unauthorised access of the hard drive over the network (and thereby possibly read the users email and delete files as well as break into the system) NFS is a stateless protocol,which means that the request that is made between the client and server is complete in itself and doesnt require keys of prior transactions. NFS services are activated in runlevel 3, nfs is the service which allows the user to share or access the remote files, directories and file systems , nfs service controls four daemons,they are
nfsd
This is the Network File System (NFS) daemon. It runs on the file server, and is responsible for handling client requests.
mountd
This daemon runs on the NFS server and is responsible for responding to client NFS mount requests. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
147
UNIX Administration
lockd
This is run by both the client and the server, this daemon handles file locks.
statd
This is run by both the client and the server, statd maintains the status of currently enforced file locks.
Rpc.portmapper
These daemons do not directly provide nfs services. They map calls made from other machines to the correct nfs daemons. Listing of daemons that are invoked by NFS on both the client and the server hosts are given below. It should be noted that both lockd and statd daemons are invoked on both the hosts. Client Daemons lockd statd Table 9.1 Server Daemons nfsd lockd statd mountd
There would be instances where it might be required to stop the nfs and restart it later.This can be done by using the startup scripts that are executed at boot time and shutdown. nfs scripts are in /etc/rc.d/nfs. Note : In Solaris /etc/init.d/nfs.server . is the service that provides the network file system services, for accessing and sharing the remote file system. To stop the nfs Daemon # /etc/rc.d/init.d/nfs stop
148
Network File System There are two key files to nfs .They are /etc/exportfs and /etc/fstab. /etc/exportfs is used to share files, directories and file system to nfs clients.This file is configured on the server. It specifies the files that are to be shared with a specific client and the client access rights./etc/fstab is configured on the client side and specifies the servers to be contacted for certain directories as well as where to place them in their machines.
directory
Specifies the directory to be shared. If an entire volume is shared then all directories under it within the same file system will be shared as well. machine1 and machine2.Specifies the client machines that will have access to the directory. The machines may be listed by their IP addresses or their DNS addresses (e.g., machine.company.com or 192.168.0.8). Using IP addresses is more reliable and more secure.
optionxx
The option listing for each machine will describe what kind of access that machine will have. Important options are: ro: Indicates that the directory is shared read only; the client machine will not be able to write to it. This is the default. rw: Indicates that the client machine will have read and write access to the directory. Consider the following example /home/abchost1(rw) host2(ro) host3(ro)
CAUTION
Never edit the /etc/rmtab manually. Note : /etc/rmttab is the file That lists directories that are currently exported.
149
UNIX Administration
Syntax
exportfs [ options ] options -a -v -u -I Exports all directories listed in the /etc/exports file. Prints the name of each directory as it is exported or unexported. Unexports the directories that are specified. When used with the -a flag, unexports all directories listed in the /etc/exports file. Allows the exporting of directories not specified in the exports file or ignores the options in the /etc/exports file. Normally the exportfs command consults the /etc/exports file for the options associated with the exported directory. Specifies an export file, other than the /etc/exports file, that contains a list of directories that can be exported. This file should follow the same format as the /etc/exports file. NOTE: This alternate file will not be used for exporting directories automatically when the system and NFS is started. The /etc/exports file is the only file that is supported for specifying directories to export at system start. Specifies optional characteristics for the exported directory. More than one variable can be entered by separating them with commas. Exports the directory with read-only permission. Otherwise, if not specified, the directory is exported with read-write permission
-f file
-o options Ro
Rw = Client [:Client] Exports the directory with read-write permission to the machines specified by the Client parameter and read-only to all others. The Client parameter can be either the host name or the network name. If a rw host name is not specified, the directory is exported with read-write permission to all.
/etc/exports format:
# vi /etc/exports [directory] manchine1[option] machine2[option] /home/kishore radiant1(rw) radiant2(ro)
In the above example the directory called /home/kishore is available to the hosts radiant1 and radiant2 .For radiant1 the access is both read and write and for radiant2 the access is only for reading.After the entry is made the nfs services have to be restarted.These services are normally started at boot time by the run level3.These services can also be run manually to stop and start the nfs system.To stop nfs, the user will have to log in as root and enter the following: Consider the following example and can be used to start and stop nfs daemons # /etc/rc.d/init.d/nfs stop The nfs services can be started as follows: # /etc/rc.d/init.d/nfs start The following command can be used to check whether the nfs daemons are currently running: # /etc/rc.d/init.d/nfs status Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
150
Network File System Once an entry is made in /etc/exports file to share the directory,the exportfs command has to be run to check whether the directory is shared.
The following examples show how to user the exportfs command. # exportfs /home/kishore /home/rams
radiant1 radiant2
In the above example /home/kishore is exported to radiant1 and /home/rams is exported to radiant2 To export entries in /etc/exports the following can be done: # exportfs -a
-a exports all the files and directories from /etc/exportfs to nfs clients. To unexport all exported files and directories the following is done: # exportfs -ua
-u Unexports all the files and directories from /etc/exportfs to nfs clinets. Note : unshare is the command which is used to unexport the file sytem to clients. unshare the file system # # unshare [ file system] unshare /home/kishore
In the above example /home/kishore is unexported to nfs clients. To export /home/kishore in read-only mode the following can be done: # exportfs -o ro: /home/kishore Here the options -o Specifies a comma-separated list of optional characteristics for the directory being exported To export /home/kishore read and write mode to the radiant1,radiant2 the following can be done: # exportfs -o rw= radiant1:radiant2 /home/kishore
In the above example /home/kishore is shared in read and write mode to the clients of radiant1and radiant2.
uy
Note : share is the command which is used to share the file system to the nfs clients.
151
UNIX Administration -o rw ro -d Indicates the access rights to the directories. Read and write access to the directories. Read only access to the directories. Indicates the nfs client. Indicates the description for the directories which are exported to the nfs clients.
hostname
Consider the following example # share F nfs o rw:radiant1:radiant2 /home/kishoe d only for Admin.pupils In the above example share is the command which is used to export the /home/kishore directory to the nfs clients called radiant1 & radiant2.
Mounting the Remote File system NFS-Mounting the file system Mounting the NFS file system
2. 3. 4.
options -t
There are options that can be passed to the mount command. The most important characteristics are specified in the -o option. These characteristics are:
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
152
Network File System rw ro bg fg soft hard read/write. read only. background mount (if the mount fails, place the process into the background and keep trying until success). foreground mount (if the mount fails, place the process into the background and keep trying until success). The soft option gives an error if the server doesnt respond.Do not use this option on writable file systems. Continue retrying a request until the server responds.Use this option on all file systems mounted with read-write permission.
nfs o rw radiant1:/home/kishore
Ftype Parameters
Fs_freq Fs_passno
Used by dump to determine whether a file system needs to be dumped. Used by the fsck program to determine the order of checking the disks at boot time.
The system administrator can tell the OS about any filesystem the machine may have access to in the /etc/fstab . It also allows default parameters to be provided for each filesystem. local mount /dev/device /dir/to/mount /dev/hda1/ /home Remote mount ftype ext2 parameters rw fs_freq fs_passno 0 0
153
UNIX Administration /dev/device /dir/to/mount lambent:/home/kishore /mnt The Structure of /etc/fstab The first field (lambent:/home/kishore) is the remote filesystem which is to be described. The second field (/mnt) specifies the mount point where the filesystem will be mounted. The third field (nfs) is the type of filesystem on the device from the first field. The fourth field (rw) is a options which mount should use when mounting the filesystem. The fifth field (0) is used by dump (a backup utility) to decide if a filesystem should be backed up. If zero then dump will ignore that filesystem. The sixth field (0) is used by fsck (the filesystem check utility) to determine the order in which filesystems should be checked. Note : In Solaris /etc/vfstab is the file that lists all the partitions that need to be mounted at boot time and the directory where they need to be mounted. #vi /etc/vfstab <device to mount> <device to fsck> < mount point> <mount at boot> <mount options> # remote mount lambent:/home/kishore - /mnt The fields are described below: Device to mount This is the name of the server sharing the resource the client wants to mount, if is the resource is an Nfs resource followed by a colon, then thename of the resource to be mounted. (lambent:/home/kishore).lambent is the name of the server and /home/kishore is the name of the remote directory. Specifies the name of the raw device to fsck; for a remote mount, the parameter is not applicable, and the entry should be - . mountpoint fstype fsckpass which is the mount point on which the resource is to be mounted.(/mnt). Specifies the file system type of the resource that is to mount.(nfs) This is the pass number to use for multiple nfs yes <fs type> <fsck pass> ftype nfs parameters fs_freq rw 0 fs_passno 0
Device to fsck
parameter is not applicable, and the entry should be mntopts Specifies the options passed to the mount command;.
There are options that can be passed to the mountoption field(7th coloum). The most important characteristics are specified:
rw ro
bg
background mount (if the mount fails, place the process into the background and keep trying until success.) foreground mount (if the mount fails, place the process into the background and keep trying until success.)
The soft option gives an error if the server doesnt respond. Dont use this option on Writable file system.
fg
soft
hard
Continue retrying a request until the server responds.Use this option on all file systems mounted with read-write permission.
End Note: showmount queries the mount daemon on a remote host for information about the state of the NFS server on that machine. With no options showmount lists the set of clients who are mounting from that host.
Practice 11.1
The following example shows the list of clients on which file system are mounted # showmount
hostname on radiant1:/home/kishore
Options
-a or all Lists both the client hostname and mounted directory in host:dir format. -d or directories Lists only the directories mounted by some client. -e or exports The file /var/lib/nfs/rmtab contains a record of all clients that mount remote file systems from the current machine. Whenever a remote mount is done, an entry is made in the rmtab file of the machine serving that file system. umount removes the entry of a remotely mounted file system. umount -a broadcasts to all servers that they should remove all entries from rmtab. rmtab contains a table of filesystems that are remotely mounted by NFS clients. This file is maintained by mountd the mount daemon. The data in this file should be obtained only from
mountd the mount daemon The file contains a line of information for
155
In the above file /home/kishore is being accessed by radiant1,/home/rams is being accessed by radiant2.
156
Lecture 12
Objectives
In this lecture you learn the following
Understanding the type of Virtual File system About the Process file System
will
157
UNIX Administration
Coverage Plan
Lecture 12
12.1 Snap Shot 12.2 Types of Virtual File System 12.3 The Process File System 12.4 Short Summary 12.5 Brain Storm
158
The Virtual File sytem supported in the Unix Operating System environment are described below:
159
UNIX Administration Create a swap file by using mkswap command Activitate the swap with the swapon command mkswap Command: The mkswap command is used to add a swap file.
Syntax
mkswap [device ] [ block ] The options for the mkswap command: -c: -f: Checks the device for bad blocks before a swap fileis created. Forcibly creates a swap file.
Consider the following example to create a swap file: # mkswap /dev/hda9 2000
mkfile is the command which is used to create a swap file, swap is the commands which is used to activate and check the swap staus in Solaris. Syntax: # mkfile nnn[k/b/m] filename Consider the following example to create a swap file: # mkfile 24m /opt/abc The swap file of the size nnn(in Kbytes,bytes, or Mbytes) and the specified name is created Swapon Command: swapon is the command which is used to activate the swap on the device.
Syntax:
# swapon [options] [ device ] Options: h -s Prints the help information. Prints the swap usage information.
swap is the command which is used to activate and check the status of a swap file system in Solaris.
160
Virtual File System Syntax: # swap a [file name] The options of swap command: a: It is used to add swap file. -l: It is used to verify the swap file is added. -s: It is used to list the status of swap file. -d: It is used to remove the swap file from use. Consider the following example # swap -a /opt/kishore
Deleting the swap space The swap space can be deleted by using the swapoff command.
Syntax:
swapoff [device] Consider the following example # swapoff /dev/hda9
This file system contains a list of active processes, named according to the process number,in the /proc directory.
161
UNIX Administration pid/ contains information about process number pid. The kernel maintains a directory containing process information for each process pid/cmdline contains the command that was used to start the process (using null characters to separate arguments) pid/environ contains a list of the environment variables that are available to the process pid/exe contains a link to the program that is running in the process pid/fd/ is a directory containing a link to each of the files that the process has opened pid/mem contains the memory contents of the process pid/stat contains the process status information pid/statm contains the process memory usage information
The /proc file system is not a file system in the standard sense. The large files found in /proc are the address spaces of running processes, just the PID of the running processes. The owner and group owner of each file are the real-UID and primary group of the processs owner. A sample listing from /proc is as follows ls -l /proc total 43384 -rw 1 root -rw 1 root -rw 1 root -rw 1 root -rw 1 root -rw 1 root -rw 1 root
2 2 2 2 2 2 2
162
Security
Lecture 13
Security
Objectives
In this lecture you learn the following
OS. About the types of UNIX Security
will
163
UNIX Administration
Coverage Plan
Lecture 13
13.1 Snap Shot 13.2 Security 13.3 File Level Security 13.4 System Level Security 13.5 Short Summary 13.6 Brain Storm
164
Security
access to information by unauthorized recipients intentional but unauthorized destruction or alteration of that information.
This can be re-stated: Security is the ability of a system to protect information and system resources with respect to confidentiality and integrity. It should be noted that the scope of this second definition includes system resources, which include CPUs, disks, and programs, in addition to information.
13.2 Security
Unix Administration Security
Being a multi-user operating system , UNIX has incorporated various security measures at different levels to ensure complete safety from any unauthorized access to the system. This session deals with two types of UNIX security, 1) File level security and 2) System level security.
In the UNIX operating system the file access by users is controlled with respect to the owner, group and others .
165
UNIX Administration u - Tthe user who owns the file g - Tthe group to which the file belongs o - Eeverybody else For each of these users, a file or directory has three type of permissions: r w x Read the file or directory Write to (or remove)the file or directory Execute the file or list the directory
Each of these permissions can be listed as 9 characters, listed by user, group and others as shown below: user group others rwx rwx rwx |___| |___| |___| | | | | | Access granted to non-owner, non-group | | Access granted to group members | Access granted to files owner
166
Security Normally the umask value assigned to users by default is 022 which grants permissions to newly created files or directory. By changing the value of umask the permissions granted to a file or directory can be controlled on creation. After changing the value of the umask from the command line or in the .profile file the user has to logout from the current session and again login into the system in order to make the umask settings effective
Syntax
chmod chmod [ -fR ] <absolute-mode> file ... [ -fR ] <symbolic-mode-list> file ...
chmod changes or assigns the mode of a file. The mode of a file specifies its permission and other attributes. The mode may be absolute or symbolic. Absolute mode: An absolute mode is specified using octal numbers chmod nnnn file ... where n is a number from 0 to 7. For directories, files are created with BSD semantics for propagation of the group ID. With this option, files and subdirectories created in the directory inherit the group ID of the directory, rather than that of the current process. It may be cleared only by using symbolic mode.
Options
The following options are supported: -f -R Forces the change, chmod will not complain if it fails to change the mode of a file
Recursively descends through directory arguments, setting the mode for each file as described above
When symbolic links are encountered, the mode of the target file is changed, but no recursion takes place Consider the following examples
167
UNIX Administration 1. Deny execute permission to everyone: # chmod a-x filename 2. Allow only read permission to everyone: # chmod 444 filename 3. Make a file readable and writable by the group and others: # chmod go+rw filename # chmod 066 filename
Syntax
chown Options -f -h -R When this option is used errors are not reported option, [ -fhR ] owner [ : group ] file ...
If the file is a symbolic link, changes the owner of the symbolic link. Without this the owner of the file referenced by the symbolic link is changed
Recursively descends through the directory, and any subdirectories, setting the ownership ID as it proceeds. When a symbolic link is encountered, the owner of the target file is changed (unless the -h option is specified), but no recursion takes place.
The following operands are supported: owner[:group] file Specifies a user and optional group ID to be assigned to a file . The owner portion of this operand must be a user name from the user database or a numeric user ID Specifies a path name of a file whose user ID is to be modified
To change ownership of all files in the hierarchy, including symbolic links, but not the targets of the links the following can be used: $ chown -R -h owner [:group] file...
Note : Only the owner of a file or the super-user may change the owner of that file. But by default the owner of the file is prevented from changing the owner ID of the file. Only the super-user can arbitrarily change owner IDs to make the user to change the ownership of a file, include the following line in /etc/system in Solaris: set rstchown = 1 To disable this option, the following line in /etc/system: set rstchown = 0
168
Security
Syntax
chgrp [ -fhR ] group file
Options
-f -h -R Forces the change. Errors are not reported. If the file is a symbolic link, changes the group of the symbolic link. Without this option, the group of the file referenced by the symbolic link is changed Recursively descends through the directory , and any subdirectories, setting the specified group ID as it proceeds. When a symbolic link is encountered, the group of the target file is changed (unless the -h option is specified), but no recursion takes place
The following operands are supported: group Indicates the group name from the group database or a numeric group ID. Either of these specifies a group ID to be given to each file named by one of the file operands. If a numeric group operand exists in the group data base as a group name, the group ID number associated with that group name is used as the group ID Indicates the path name of a file whose group ID is to be modified
file
Umask Filter
The umask utility sets the file mode creation mask of the current shell execution environment to the value specified by the mask operand. This mask affects the initial value of the file permission bits of subsequently created files.If we are giving the command umask alone ( $umask) is given , the current value of the mask is printed. umask is recognized and executed by the shell. umask can be included in the users .profile file and invoked at login to automatically set the users permissions on files or directories created. umask 022 removes write permission for group and other (files normally created with mode 777 become mode 755; files created with mode 666 become mode 644). The following options are supported: -S Produce symbolic output.
Consider the following example # umask 027 ( for the current session) or $ vi .profile umask 027 :wq! In the first case above the umask value is changed temporarily. If the user logs out and then again logs in the umask value goes back to the default value. In the second case the new umask value is entered into the .profile file of the user which permanently changes the umask value and hence changes the file permissions accordingly. After changing the value of UMASK in .profile file the user have to logout from the current session and again he have to login in order to initialize umasks new value.
169
UNIX Administration
From the above example it is clear that in the shadow file, only root has read permission and all others do not have any permissions. But any user can change their password using /usr/bin/passwd command, that will make changes in the /etc/shadow file. This happens because /usr/bin/passwd is a setuid program Directories that have setgid permission will propagate their GID to files created below them, i.e., new files and directories will belong to the same group as the parent directory. It is very useful in the case of a shared project directory
170
The setgid bit on a directory must be set or changed using symbolic notation. The file or directory that is set to a setuid/setgid program can be checked using the ls command as shown below. $ls l setuid_executable file -rwsr-xr-x 1 setuid_executable file -rwxr-sr-x 1 setgid_executable file root root other other 567 678 Mar Mar 18 18 19.25 19.27
Note: In some cases S (capital S) instead of s can be found in the output of ls l command for a setuid or setgid file which shows an error condition that the setuid or setgid bit is set but the execute bit is off.
In some cases a T in the instead of t can be found in the output, this indicates an error condition that, the save text attribute bit is on but the execute permission bit is off. In Solaris and SCO OS the save text attribute is known as a sticky bit.
The following example replaces the entire ACL for the file, which gives the user shea read access, Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
171
UNIX Administration the file owner all access, the file group owner read access only, the ACL mask read/write access, and others no access. #setfacl-s user:shea:rwx,user::rwx,group::rw-,mask:r,other:abc OR # setfacl -s u:shea:7,user::7,group::6,mask:4,other:0 abc Note that after this command, the file permission bits are rwxr. Even though the file group owner was set with read/write permissions, the ACL mask entry limits it to have only read permissions. The mask entry also specifies the maximum permissions available to all additional user and group ACL entries. Once again, even though the user shea was set with all access, the mask limits it to have only read permissions. The ACL mask entry is a quick way to limit or open access to all the user and group entries in an ACL. For example, by changing the mask entry to read/write, both the file group owner and user shea would be given read/write access. The following example adds one ACL entry to the file abc, which gives user shea read permission only. # setfacl -m user:shea:rabc OR # setfacl -m u:shea:4 abc The ACLs for a file or a directory can be displayed using getfacl command. # getfacl d abc The asroot command can be used in SCO, as there is no concept of ACLs in SCO. After setting the appropriate setgid using chmod, the files in /tcb/files/rootcmds/... have to be edited to enable the users to run as root. Refer the asroot man pages for more details.
172
Security The root account is created automatically when the Unix/Linux operating systems is installed. The Superuser can Shutdown the system Back up and restore the file systems Mount and unmount file systems Add and delete users Maintain password aging of the users
It is recommended to change the root password on a regular basis The root account should be only used only while performing system administration tasks.For everyday use ,it is not advisable to use the root account. This helps to protect the system from unauthorized access and also , critical mistakes are less likely to occur if routine work is done as an alternate user.
173
UNIX Administration A group may contain no members (i.e. it is unused), a single member or multiple members, and the password is optional (and typically not used).
Restricted Shell
There are restricted versions of the Bourne and Korn shells (rsh and rksh), that prohibit changing directory with cd, setting the value of $PATH, using command names containing slashes, and redirecting output using > and >>. /etc/login.defs This file (/etc/login.defs) allows to define some useful default values for various programs such as useradd and password expiry. It tends to vary slightly across distributions and even versions, but typically is well commented and tends to contain sane default values. /etc/shells The shells file contains a list of valid shells, if a users default shell is not listed here they may not log in interactively. /etc/securetty This file contains a list of ttys that the root can log in from. Console ttys are usually /dev/tty1 through /dev/tty6. Serial ports are /dev/ttyS0 and up typically. If root is to be allowed to login via the network then add /dev/ttyp1 have to added and up. Generally only root should be allowed to login from /dev/tty1, and it is advisable to disable the root account altogether. Before doing this sudo or program has to be installed that allows root access to commands. Note : How to temporarily disable user logins (Solaris ) The following procedures show how to temporarily disable user logins in Solaris Become superuser. Create the /etc/nologin file using an editor. # vi /etc/nologin Include a message regarding system availability. Close and save the file. ExampleDisabling User Logins This example shows how to notify users of system unavailability. # vi /etc/nologin (Add system message here) # cat /etc/nologin ***No logins permitted*** ***The system will be unavailable until 12 noon***
174
Security
Note : With regard to disabling logins, in Solaris it will work and there is no nologin file concept in SCO. However, the /etc/profile can be edited with an appropriate message with the last line as /bin/true and exit. This will throw all the users who are trying to login. To ensure that it does not throw the root, a condition by checking the LOGNAME for non-root has to be added.
Example
# passwd -l unix < to lock the account named unix # passwd unix < to unlock the account by issuing a new password.
UNIX Administration
For each file there are three classes of users- owner (the user who creates the file), group (members who belong to owners group), others (Rest of the users) There are three types of permissions read, write and execute The default permissions of a file or a directory are controlled by the umask value Chmod command is used to change the access permissions of a file Chown command is used to change the ownership of a file and chgrp command is used to change a group of a file Setuid and setgid permissions can be set on executable files and setgid permission can be set on directories Save text attribute (sticky bit) can be set on public directories for the purpose of security Access of a system is controlled by login name and password assigned to the users which can be found in /etc/passwd and /etc/shadow files
Root account is automatically created when the operating system is installed Root can temporarily disable user logins with the help of /etc/nologin file
176
Printer Management
Lecture 14
Printer Management
Objectives
In this lecture you learn the following
Able to configure the Print Service About Print Service Architecture Able to print a file
will
177
UNIX Administration
Coverage Plan
Lecture 14
14.1 Snap Shot 14.2 Configuring Print Services 14.3 Print Service Architecture 14.4 Printing a File 14.5 Short Summary 14.5 Brain Storm
178
Printer Management
Configuring Printer services in Unix involves three main tasks: setting up the printer, setting up the printer server and setting up the print client.
Note : A printer can be configured in Solaris using lpadmin, accept, enable commands. lp is the daemon which provides the print service in Solaris and SCO. These services are invoked in run level 2. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
179
UNIX Administration
Print Functions
he print functions are as follows Queuing Tracking Initialization
Queuing
When the print requests are spooled, the jobs are lined up with other jobs that are waiting to be printed. This process of lining up of jobs is called queuing.
Tracking
The print service tracks the status of every job to enable users to remove jobs and system administrators to manage jobs.
Initialization
The print service initializes a printer before sending it a print job to ensure that it is in a known state.
180
Printer Management
Configuring Printer
The /etc/printcap file explains the Linux OS about a printer. Each entry defines a printer, provides a name to be addressed and explains the OS about ways of handling output to it. Multiple printers that access the same physical printer can be installed in a system.
Practice 14.1 Consider the following example illustrate how to configure a printer.
The /etc/printcap file is first edited.
# vi /etc/printcap #Local Printer hp|Our printer:\ :sd=/var/spool/lpd/hp:\ :mx#0:\ :sh:\ :hp=/dev/lp0:\ s The printer name The first line of a /etc/printcap entry is the printer name. It contains the printer name, which is followed by a | character, a text description of the printer, and ends with a : character. For example: Hp:\ is a printer called HP with the description OurPrinter The spool directory This is a directory for print spooling. The tag sd= identifies the spool directory for the printer. Additional Tags There are three additional things to be put in the printcap entries. They can be seen below: :mx#0:\ :sh:\ :sf: The mx#0 means dont limit the size of the file we can print. The sf prevents a form-feed from being sent after the document ends. Finally, the ``sh prevents a header page from being sent at the beginning of each job. These may be added to the printcap entries. The printer device The tag hp= takes the name of the printing device. In this case, it is /dev/lp1, the parallel port. There are printers that connect to the serial port. The Print Spool Daemon, lpd
181
UNIX Administration The program that actually does the spooling and printing of files is lpd. It reads the /etc/printcap file. You can also execute lpd can also be execute as a background job from the command line if logged on as root. lpd is the line printer daemon (spool area handler) and is normally invoked at boot time.
Example
# lpd l /dev/lp0 Available options: -l The -l flag causes lpd to log valid requests that are received from the network. port# lpq The port indicates under which port the request has been accepted. The spool queue examination program lpq examines the spooling area used by lpd for printing files on the line printer, and reports the status of the specified jobs or all jobs associated with a user. lpq, that is invoked without any arguments, reports on any jobs currently in the queue.
Note : lpadmin is the command that is used to configure the printer in Solaris. lp is the service which provides the print services. lpadmin configures the LP print service by defining printers and devices. It is used to add and change printers, to remove printers from service, to set or change the system default destination.
Example
# lpadmin -p printer options # lpadmin p epson v /dev/lp0 -p Indicates the name of the printer -v Indicates the port
182
Printer Management -l - Information about each of the files comprising the job entry is printed.
Practice 14.2
Consider the following example illustrate to print file. # lpr Php /radiant/kishore The above example shows the usage of the lpr command , -p inidcates the name of the printer , /radiant/kishore is the name of the file to be printed. The /var/spool/lpd/hp directory is the spool directory where all the jobs of a printer queue are stored, # /var/spool/lpd/hp/status is a file that contains the status of printer.
Example
# vi /var/spool/lpd/hp/status Note : Hp enabled and accepting requests # /var/spool/lpd/hp/lock file contains the print jobs. Lock file is used to obtain the pid of the current daemon and the job number of the currently active job. lp is used to print a file in Solaris and SCO.
Syntax
lp [file name] Consider the following example. # lp /kishore
Syntax
/usr/etc/lpc [command [argument...] ] # lpc abort { all | printer ... } Terminates an active spooling daemon on the local host immediately and then disables printing (preventing new daemons from being started by lpr) for the specified printers. # lpc clean { all | printer ... } Removes any temporary files, data files, and control files that cannot be printed (i.e., do not form a complete printer job) from the specified printer queue(s) on the local machine.
183
UNIX Administration #lpc disable { all | printer ... } Turns the specified printer queues off. This prevents new printer jobs from being entered into the queue by lpr. # lpc down { all | printer } message ... Turns the specified printer queue off, disable printing and puts message in the printer status file. # lpc enable { all | printer ... } Enables spooling on the local queue for the listed printers. This will allow lpr to put new jobs in the spool queue. # lpc restart { all | printer ... } Attempts to start a new printer daemon. This is useful when some abnormal condition causes the daemon to die unexpectedly leaving jobs in the queue. Lpq will report that there is no daemon present when this condition occurs. If the user is the super-user, it will try to abort the current daemon first (i.e., kill and restart a stuck daemon). # lpc start { all | printer ... } Enables printing and starts a spooling daemon for the listed printers. # lpc status { all | printer ... } Displays the status of daemons and queues on the local machine. # lpc stop { all | printer ... } Stops a spooling daemon after the current job completes and disables printing. # lpc up { all | printer ... } Enables everything and starts a new printer daemon. Undoes the effects of down. Note: lpstat is used to check the status of the print service in Solaris. # lpstat [ printer ]
Syntax
lprm [ -P printer ] [ - ] [ job # ... ] [ user ... ] Options -P printer - Specifies the associated queue with a specific printer (otherwise the default printer is used). user - Causes lprm to attempt to remove any jobs that are queued and belonging to that user (or users). This form of invoking lprm is useful only to the super-user. A single - is given, lprm will remove all jobs of a user. If the super-user employs this flag, the spool queue will be emptied entirely. A user may remove an individual job by specifying its job number.
job #
Note : cancel is the command which is used to cancel the print request in Solaris. # cancel [ request-ID ... ] # cancel epson-1 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
184
Printer Management
User commands
Linux lpr lpq lprm Solaris 2.7 lp lpstat cancel Description Submits a request to the printer Reports on the status of the print request and service Cancels a print request
Administrative Commands:
Administrative commands are located in /usr/lib. These files are symbolic links to the actual files residing in /usr/sbin and /usr/lib/lp. The commands accept and reject are in /usr/sbin, and the commands enable and disable are in /usr/bin.
Administrative Commands
linux lpc enable lpc disable further SunOS 5.X enable disable Description Enables the queue for the named printer Disables the queue of the named printer for requests
lpc
lpadmin
185
UNIX Administration
Lecture 15
Objectives
In this lecture you learn the following
Understand about Backup utility Able to apply the Backup command
will
186
Coverage Plan
Lecture 15
15.1 Snap Shot 15.2 Backups 15.3 Short Summary 15.4 Brain Storm
187
UNIX Administration
15.2 Backups
Unix Administration Backups tar command cpio command dd command mt command dump/restore command
Backup is the procedure of taking a copy of relevant and important information on the workstation or server systems.Backing of files is one of the most crucial functions of system administration. It must be planned and carried regularly at scheduled intervals for the following five major reasons. Accidental file removal External failure of system Internal failure of systems A user or superuser may accidentally removed an important file. Power failure may lead to file system corruption and data loss. Hard disk crash or failure in some other system components which may lead to data loss. Natural disaster may destroy the local site.
Environmental damages
So backups should be protected against these types of dangers. Backing of files means making copies of them, usually on removable media, as safeguard in case the originals get lost or damaged. Backups should be performed on a regular basis. If backups are automated sufficiently, the only limitation on how often backups are performed should be the size and availability of data.
tar command
One of the oldest and most often used commands for archiving and backing up files is the tar command. Due to its simplicity and ease of use, this becomes the most common format for tape and disk archives today. One of the best features of tar is the flexibility to save any medium, since it treats file and tape (or other backup media) device targets the same. The tar command helps to backup single or multiple files in a directory hierarchy. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
188
Backup and Recovery The format of the tar command is # tar options [ argument ] (tar filename .) (files to backup or restore) Options c t Creates a new archive; writing begins at the beginning of the archive, and not after the last file. The names of the specified files are listed each time that they occur on the archive. If no files argument is given, all the names on the archive are listed. Normally, tar does its work silently. The v (verbose) function modifier causes tar to display the name of each file it treats, preceded by the function letter. With the t function, v gives more information about the archive entries than just the name. Causes tar to use the next argument as the name of the archive instead of the default device listed in /etc/default/tar. If the name of the file is a dash (-), tar writes to the standard output or reads from the standard input, whichever is appropriate. Thus, tar can be used as the head or tail of a pipeline. tar can also be used as archive file or device F (default /dev/rmt0) used to move hierarchies with the command: cd fromdir; tar cf - . | (cd todir; tar xf -) x The named files are extracted from the archive. If a named file matches a directory whose contents had been written onto the archive, this directory is (recursively) extracted. The owner, modification time, and mode are restored (if possible). If no files argument is given, the entire contents of the archive are extracted. If several files with the same name are on the archive, the last one overwrites all earlier ones. There is no way to ask for the nth occurrence of a file. The names of the specified files are listed each time that they occur on the archive. If no files argument is given, all the names on the archive are listed. The named files are written to the end of an existing archive. This function letter is only valid for appending files to disk archives. When specifying the absolute path of an archive device with the function modifier, use the n function modifier to indicate that the device is not a magnetic tape. this function letter cannot be used with tape devices.
v -
t r
The tar command is unaware of the file systems; however if a directory is specified as a tar argument, it copies the entire hierarchy below a directory. use a ./ in front of the directory name so that it can be restored relative to a current working directory.
Practice 15.1
Consider the following command illustrates a method to take backup. # tar cvf /dev/fd0 ./test*
189
UNIX Administration
./test ./test1 ./test2 ./test3 In the above example tar is the command which is used to take backup, /dev/fd0 is the device used to take backup and ./test* is the directory. c Creates a new archive; writing begins at the beginning of the archive, instead of after the last file. Normally, tar does its work silently. The v (verbose) function modifier causes tar to display the name of each file it treats, preceded by the function letter. With the t function, v gives more information about the archive entries than just the name. Causes tar to use the next argument as the name of the archive instead of the default device listed in /etc/default/tar. If the name of the file is a dash (-), tar writes to the standard output or reads from the standard input, whichever is appropriate. Thus, tar can be used as the head or tail of a pipeline.
Note : To use tape archive as device file use /dev/st0 (st0 indicates the first tape drive) is to be used. In Solaris, it is different. /dev/rmt/0 /dev/rmt-logical device name of tape 0-indicate first tape drive
Practice 15.2
The following example illustrates how to display the content of the floppy using tar. # tar tvf /dev/fd0
Here t represents the names of the specified files are listed each time when they occur on the archive. If the files argument is not given, all the names on the archive are listed. v means normally, tar does its work silently. The v (verbose) function modifier causes tar to display the name of each file it treats, preceded by the function letter. The function, gives more information about the archive entries than just the name. f shows causes tar to use the next argument as the name of the archive instead of the default device listed in /etc/default/tar. If the name of the file is a dash (-), tar writes to the standard output or reads from the standard input, whichever is appropriate. Thus, tar can be used as the head or tail of a pipeline. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
190
Backup and Recovery Note : If we use tape archive as device file use /dev/rmt0.
Practice 15.3
The following example illustrates about restoring the file. # tar xvf /dev/fd0 ./test*
./test ./test1 ./test2 ./test3 Here, x represents the named files are extracted from the archive. If a named file matches a directory whose contents had been written onto the archive, this directory is (recursively) extracted. The owner, modification time, and mode are restored (if possible). If no files argument is given, the entire contents of the archive are extracted. If several files with the same name are on the archive, the last one overwrites all earlier ones. Normally, tar does its work silently. The v (verbose) function modifier causes tar to display the name of each file it treats, preceded by the function letter. With the t function, v gives more information about the archive entries than just the name. f means causes tar to use the next argument as the name of the archive instead of the default device listed in /etc/default/tar. If the name of the file is a dash (-), tar writes to the standard output or reads from the standard input, whichever is appropriate. Thus, tar can be used as the head or tail of a pipeline.
cpio command
One of the more popular generic backup utilities in use today is the cpio command. In large part, its popularity is due to its capability to append backup volumes and span tapes, allowing to create incremental backup sets and full system backups without losing data integrity. cpio allows to copy files into and out of a cpio archive. The term cpio stands for copy in/out. cpio copies files to and from an archive file or another directory hierarchy. There are two main options to cpio which determine its mode of operation. These modes are used to create an archive (cpio -o), extract files from an archive (cpio -i) c - For portability, write header information in ASCII Character form. Always use this option should be used when the origin and destination machines are of different types. (copy out) Reads a list of pathnames from the standard input, and copies those files onto the standard output together with pathname and status information. Output is padded to a 512- byte boundary by default.
191
UNIX Administration i v t b (copy in) Extracts files from the standard input, which is assumed to be the product of a previous cpio -o. Only files with names that match the wildcard patterns are selected. Lists the files processed, or with -t, give an ls -l style table of contents listing. Prints a table of contents of the input. No files are created. Sets the I/O block size to 5120 bytes.Initially the block size is 512 bytes. MESSAGE, message=MESSAGE Prints MESSAGE when the end of a volume of the backup media (such as a tape or a floppy disk) is reached, to prompt the user to insert a new volume.
m -
If MESSAGE contains the string %d, it is replaced by the current volume number (starting at 1). -a Suppresses absolute filenames. A leading / character is removed from the filename during copyin.
If a pattern is provided, it should match the relative (rather than the absolute) pathname. Note : In linux this -a, option is different, here it is used to append to an existing archive. Only works in copy- out mode. The archive must be a disk file specified with the -O or -F (file) option
Practice 15.4
The following example illustrates the copying of files using cpio. #cd /home # ls tes*|cpio -ovc >/dev/fd0
test test1 test2 test3 2 blocks In the above example, files were copied under the directory called /home/test by using cpio command. o represents (copy out) Reads a list of pathnames from the standard input, and copies those files onto the standard output together with pathname and status information. Output is padded to a 512- byte boundary by default. v means list the files processed, or with -t, give an ls, l shows style table of contents listing, and c means for portability, write header information in ASCII Character form. Always use this option when the origin and destination machines are of different types >/dev/fd0-Output is redirected to a floppy disk in the first drive.
Practice 15.5
Consider the following example illustrate how to restore the files under home directory. #cd /home # cpio -ivc </dev/fd0
192
test test1 test2 test3 2 blocks Here, i represents (copy in) Extracts files from the standard input, which is assumed to be the product of a previous cpio -o. Only files with names that match the wildcard patterns are selected, v shows list the files processed, or with -t, give an ls, l shows style table of contents listing, c means for portability, write header information in ASCII Character form. Always use this option when the origin and destination machines are of different types >/dev/fd0-Output is redirected from a floppy disk in the first drive.
dd command
The purpose of the Unix dd command is to copy data from one device to another; the command stands for device dump. The dd command transfers raw data between devices.
Syntax
dd [OPTION]...
This command copies a file, convert and formatts according to the following options.
Options: if=FILE of=FILE bs=BYTES ibs=BYTES obs=BYTES read from FILE instead of stdin write to FILE instead of stdout force ibs=BYTES and obs=BYTES read BYTES bytes at a time write BYTES bytes at a time
Practice 15.6
Consider the following example illustrates how to copy the contents of one floppy disk to another, using /tmp as a temporary storage area. The source disk is inserted in the drive, and the following command entered: #dd if=/dev/fd0 of=/tmp/tmpfile bs=50k 28+1 records in 28+1 records out Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
193
UNIX Administration In the above example dd is the command which is used to copy from one disk to another disk.Numbers of full and partial blocks read in the current input block size.ie bs=50k 28+1 records out means.Numbers of full and partial blocks written in the current output block size. Where if=FILE read from FILE instead of stdin of=FILE write to FILE instead of stdout bs=BYTES force ibs=BYTES and obs=BYTES
Practice 15.7
This example shows how to copy the data in temporary file, /tmp/tmpfile to the destination that is inserted after removing the source. #dd if=/tmp/tmpfile of=/dev/fd0 28+1 records in 28+1 records out where 28+1 records in means Numbers of full and partial blocks read in the current input block size. ie 28+1 records out means Numbers of full and partial blocks written in the current output block size. Where if=FILE read from FILE instead of stdin of=FILE write to FILE instead of stdout bs=BYTES force ibs=BYTES and obs=BYTES Finally remove the temporary file: #rm /tmp/tempfile
mt command
The mt command enables direct tape manipulation.
Syntax
mt[ -f tape-device-name ] command [count ] Commands status rewind retention erase fsf bsf Displays status information about the tape drive Rewinds the tape Rewinds the cartridge tape completely Erases the entire tape Forward skips count tape files Backward skips count tape files
194
Backup and Recovery eom Table 15.1 Skips to the end of the records cd media
195
UNIX Administration to install these packages: rpm and glint. glint is the GUI tool for managing packages. Refer to the RedHat documentation for more details on using these tools. The dump package can be found under the Utilities /System folder. Before the dump package is installed the rmt package. dump dump is generally used to backup an entire partition (file system). If given a list of filenames, dump will backup the individual files.
Syntax:
dump [ options [ arguments ] ] file system dump [ options [ arguments ] ] filename Arguments must appear after all options and must appear in a set order. Using dump command the user can take full or incremental backups, dump works on the concept of levels (it uses 9 levels). A dump level of 0 (full backup) means that all files will be backed up. A dump level of 1...9 (incremental) means that all files that have changed since the last dump of a lower level will be backed up. If the u option is specified with the dump command it will update the dump information in the /etc/dumpdates file, which will help the system to perform the next incremental backup. This file, after the dump performed, contains the date and time of backup and the level specified for the backup. Options 0-9 Dump level. Refers the Archive-file will be a table of contents of the archive Specifies the file (usually a device file) to write the dump to, a - specifies standard output Updates the dump record (/etc/dumpdates) After writing each volume, rewinds the tape and verifies. The file system must not be used during dump or the verification.
a archive-file f dump-file u v -
The restore command Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
196
Backup and Recovery The purpose of the restore command is to extract files archived using the dump command. This command restore provides the ability to extract single individual files, directories and their contents and even an entire file system.
Syntax
restore -irRtx [ modifiers ] [ filenames ] The restore command has an interactive mode where commands like ls etc can be used to search through the backup. Arguments -I -r -t -x Interactive, directory information is read from the tape after which the user can through the directory hierarchy and select files to be extracted. browse
Restore the entire tape. Should only be used to restore an entire file system or to restore an incremental tape after a full level 0 restore. Table of contents, if no filename provided, root directory is listed including all subdirectories (unless the h modifier is in effect) Extract named files. If a directory is specified, it and all its sub-directories are extracted.
Arguments for the restore Command. Modifiers Purpose Uses an archive file to search for a files location. Converts contents of the dump tape to the new file system format Turns on debugging Prevents hierarchical restoration of sub-directories Verbose mode Specifies dump-file to use, - refers to standard input Skips to the nth dump file on the tape a archive-file d h v f dump-file sn -
Argument modifiers for the restore Command. Using dump and restore without a tape
Practice 15.8
For all our experimentation with the commands in this chapter we are going to work with a practice file system. Practising backups with hard-drive partitions is not going to be all that efficient as they will almost certainly be very large. Instead we are going to work with a floppy drive. The first step then is to format a floppy with the ext2 file system. By now you should know how to do this. Heres what I did to format a floppy and put some material on it. [root@icg]# /sbin/mke2fs /dev/fd0 mke2fs 1.10, 24-Apr-97 for EXT2 FS 0.5b, 95/08/09 Linux ext2 filesystem format Filesystem label= 360 inodes, 1440 blocks 72 blocks (5.00%) reserved for the super user First data block=1 Block size=1024 (log=0) Fragment size=1024 (log=0) Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
197
UNIX Administration 1 block group 8192 blocks per group, 8192 fragments per group 360 inodes per group Writing inode tables: done Writing superblocks and filesystem accounting information: done [root@icg]# mount -t ext2 /dev/fd0 /mnt/floppy [root@icg]# cp /etc/passwd /etc/issue /etc/group /var/log/messages /mnt/floppy [root@icg dump-0.3]# Doing a level 0 dump Lets assume If we want to do a level 0 dump of the /mnt/floppy file system. [root@icg]# /sbin/dump 0f /tmp/backup /mnt/floppy DUMP: DUMP: DUMP: DUMP: DUMP: DUMP: DUMP: DUMP: DUMP: DUMP: DUMP: Date of this level 0 dump: Sun Jan 25 15:05:11 1998 Date of last level 0 dump: the epoch Dumping /dev/fd0 (/mnt/floppy) to /tmp/backup mapping (Pass I) [regular files] mapping (Pass II) [directories] estimated 42 tape blocks on 0.00 tape(s). dumping (Pass III) [directories] dumping (Pass IV) [regular files] DUMP: 29 tape blocks on 1 volumes(s) Closing /tmp/backup DUMP IS DONE
The arguments to the dump command are 0 F This tells dump I wish to perform a level 0 dump of the file system. This is telling dump that I will tell it the name of the file that it should write the backup to. This is the name of the file I want the backup to go to. Normally, this would be the device file for a tape drive or other backup device. However, since I dont have one Im telling it a normal file. This is the file system I want to backup.
/tmp/backup-
/mnt/floppy -
What this means is that I have now created a file, /tmp/backup, which contains a level 0 dump of the floppy. [root@icg]# ls -l /tmp/backup -rw-rw-r 1 root tty 20480 Jan 25 15:05 /tmp/backup Restoring the backup Now that we have a dump archive to work with, we can try using the restore command to retrieve files. [root@icg dump-0.3]# /sbin/restore -if /tmp/backup restore > ? Available commands are: Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
198
Backup and Recovery ls [arg] - list directory cd arg - change directory pwd - print current directory add [arg] - add arg to list of files to be extracted delete [arg] - delete arg from list of files to be extracted extract - extract requested files setmodes - set modes of requested directories quit - immediately exit program what - list dump header information verbose - toggle verbose flag (useful with ls) help or ? - print this list If no arg is supplied, the current directory is used restore > ls .: group issue lost+found/ messages passwd restore > add passwd restore > extract You have not read any tapes yet. Unless you know which volume your file(s) are on you should start with the last volume and work towards towards the first. Specify next volume #: 1 Mount tape volume 1 Enter none if there are no more tapes otherwise enter tape name (default: /tmp/backup) set owner/mode for .? [yn] y restore > quit [root@icg]# ls -l passwd -rw-rr 1 root root 787 Jan 25 15:00 passwd Alternative Rather than backup to a normal file on the hard-drive the user could choose to backup files directly to a floppy drive (i.e. use /dev/fd0 rather than /tmp/backup). One problem with this alternative is that the user limited to 1.44Mb. According to the known bugs document distributed with Linux dump it does not yet support multiple volumes. Note: In Solaris environment the ufsdump and ufsrestore commands which are almost similar to the dump/restore commands in Linux can be used.
199
UNIX Administration The previous dump information are stored in the /etc/dumpdates file The restore command is to extract files archived using the dump command Restore provides the ability to extract single individual files, directories and their contents and even an entire file system
200
Space Management
Lecture 16
Space Management
Objectives
In this lecture you learn the following
Understand about Space Management Able to set Quota for a user Knowing to check Quota consistency Able to check quota on a file system
will
201
UNIX Administration
Coverage Plan
Lecture 16
16.1 Snap Shot 16.2 Space Management 16.3 Short Summary 16.4 Brain Storm
202
Space Management
Quota
Quota allows to specify limits on two aspects of disk storage: the number of inodes a user or a group of users may possess; and the number of disk blocks that may be allocated to a user or a group of users. Quota forces users to stay under their disk consumption limit, taking away their ability to consume unlimited disk space on a system. Quota is handled on a per user, per file system basis. If there is more than one file system which a user is expected to use, then quota must be set for each file system separately.
203
UNIX Administration # vi /etc/fstab /dev/device /dir/to/mount ftype /dev/hda6 where: /dev/device /dir/to/mount Ftype Is the device to be mounted, for instance, /dev/hda4. Is the location at which the file system should be mounted on the directory tree. Is the file system type. This should be 4.2 under SunOS, ufs under Solaris, ext2 under Linux, nfs for NFS mounted file systems, swap for swap partitions, and proc for the /proc file system. Some operating systems, such as Unix, support additional filesystem types, although they are not as likely to be used. Are the parameters we passed to enable the quota using the usrquota,grpquota option. They follow the same comma-delineated format. An example entry would look like usrquota, grpquota. Is used by dump to determine whether a file system needs to be dumped. Is used by the fsck program to determine the order to check disks at boot time. /home ext2 parameters defaults, fs_freq grpquota fs_passno 1 1
Parameters
fs_freq fs_passno
Create quota record quota.user and quota.group Both the quota record files, quota.user and quota.group, should be owned by root, and read-write permission for root and none for anybody else. Login as root. Go to the root of the partition for which quota has to be enabled, then create quota.user and quota.group.
Consider the following examples. # touch /home/quota.user To change the permission to read/write for root only the following can be done. # chmod 600 /home/quota.user
Syntax:
# touch [ file name ]
The permission can be changed to read/write for root only as follows. # chmod 600 /home/quota.group Now the system has to be rebooted for the changes that have been made to take effect. Note : Quota Setup on Sun Solaris: In Sun Solaris /etc/vfstab virtual file system table provides entries for mounting file system at systems boot time. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
204
Space Management
To enable user quota support on a file system, rq has to be added to the seventh field containing the mount options: Modify /etc/vfstab # vi /etc/vfstab devicetomount devicetofsck mountpoint mountoptions fstype fsckpass mountatboot
/dev/dsk/c0t3d0s7/dev/rdsk/c0t3d0s7 /export/home ufs2 yes rq The fields are described below: device to mount Device to fsck Mountp fstype fsckpass automnt Mntopts : : : : : : : The name of the resource to be mounted. The name of the raw device to fsck; for a remote mount, the parameter is not applicable, and the entry should be -. The mount point on which the resource is to be mounted. The file system type of the resource to be mounted. the pass number to be used for multiple fscks. For a remote mount, the parameter is not applicable, and the entry should be 0 Indicates whether the entry should be automounted by /sbin/mountall (yes) or not (no) when the client is booted or enters the appropriate run level. Adds the parameters that are passed to enable the quota using the rq option.
Turning Quotas on
quotaon is used to turn on quota accounting; quotaoff to turn it off. Actually both files are similar. They are executed at system startup and shutdown respectively. To turn on quotas the following command should be used:
Syntax:
quotaon [options] [filesystem] Options for quotaon command are as follows: -v -a verbose option. Turns quotas on for all the file systems with an usrquta,grpquota entry in /etc/fstab file.
Consider the following example. #quotaon -va /home dev/hda6 quota turned on To turn off quotas the following command should be used: quotaoff [options] [filesystem]
205
UNIX Administration -a Turns quotas off for all the file system with an usrquta,grpquota entry in /etc/fstab file.
Consider the following example. #quotaoff -va /home /dev/hda6 quota turned off
The following example shows how to set up quotas for a single user! # edquota u kishore
Quotas for user kishore: /dev/hda6: blocks in use: 0, limits (soft = 0, hard = 0) inodes in use: 0, limits (soft = 0, hard = 0) Here blocks in use is the total number of blocks (in kilobytes) a user has consumed on a partition, inodes in use is the total number of files a user has on a partition. Only the soft and hard limit values should be edited. The value of 0 means no limits will be imposed.
Soft Limit
Soft limit indicates the maximum amount of disk usage a quota user has on a partition. When combined with grace period, it acts as the borderline, which a quota user is issued warnings about his impending quota violation when passed.
Hard Limit
Hard limit works only when the grace period is set. It specifies the absolute limit on the disk usage, which a quota user cannot go beyond.
Syntax:
#edquota p [ prototype-user ] [member list ] Consider the following example. #edquota -p kishore rams senthil rangarajan sekar
In the above example kishores quota limit has been set to all the other users.
206
Space Management -v -a verbose option. Turns quotas off for all the file systems with an usrquta,grpquota entry in /etc/fstab file. -va /home
# quotacheck
Checking quotas on a File System To check the quotas in what are the file system it has been applied. Syntax:
repquota Options: -v - verbose mode Consider the following example. # repquota -va /home *** Report for user quotas on /dev/hda6 (/home) Block limits File limits User used soft hard used soft hard root 10224 0 0 1648 0 0 Kishore 184 1 4 46 1 5 In the above example, the quotas for the users in the file system /home is displayed in the output. [ options ] [ file system ]
Block Limits:
Used Soft Hard Is the current block usage Is the soft block limit The hard block limit Is the current block usage Is the soft block limit The hard block limit
File Limits:
Used Soft Hard
Quota allows to specify limits on two aspects of disk storage: the number of inodes a user or a group of users may possess; and the number of disk blocks that may be allocated to a user or a group of users. Allocation of space for users or groups on a file system Report about quotas applied on filesystem
207
UNIX Administration
Lecture 17
Objectives
In this lecture you learn the following
About Scheduling Events Knowing the types of scheduling
will
208
Coverage Plan
Lecture 17
17.1 Snap Shot 17.2 Scheduling Events 17.3 Short Summary 17.4 Brain Storm
209
UNIX Administration
Scheduling of repetitive execution of system events can be accomplished using the crontab command. A single system event can be scheduled at a specified time by using the at command.
Crond
Crond is a daemon. This program is executed when the Linux system is initially booted. It scans the /etc/crontab file and the /var/spool/cron directory, looking for the regularly scheduled jobs entered by root or other system users.
Crontab
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
210
Scheduling of System Events The crontab command, not to be confused with the /etc/crontab file, is used by the users of the system to schedule personal events. The cron files are stored under the /var/spool/cron directory. The system administrators can control whether or not this facility exists on the system through the /etc/cron.allow or /etc/cron.deny files. All current cron jobs are listed with the crontab -l option. The -e option has to be used to create or edit a job and -r to remove a job
Syntax:
crontab [option] [username]
Practice 17.1
The following example shows how to edit a crontab file for a user to run welcome at midnight of every Sunday. # crontab e kishore
0 0 0 * * banner welcome > /dev/console This indicates that the command should be run on the zeroth minute of the zeroth hour (midnight) of the zeroth day (Sunday) of every week. Once the crontab file has been set up (and that of the systems, if the user is the root user), there is no necessity to worry about it again, until the configuration has to be changed. To list the current crontab entries the following command should be used: # crontab l [username]
Practice 17.2
The following example illustrates how to list out the crontab entries for the user. # crontab l kishore
30 10 5 * *
rm /a*
The above example shows that at the thirtieth minute of the tenth hour of the fifth day of every month and every year, the files whose names begin with a under the root will be removed. To remove the crontab entiries for a particular user the following should be used:
211
UNIX Administration The above command would remove the crontab entries for the user kishore. Note : If crontab command is accidentally entered without any option, the interrupt character for the editor has to be pressed. This allows the user to quit without saving changes. Exiting the file and saving changes at this point would overwrite an existing crontab file with an empty file.
atq
The atq command can be used to list the queue of waiting jobs. The atq command prints a list of all waiting jobs for the at command. These jobs can be found in the /var/spool/at directory.
atrm
The atrm command can be used to remove a specified job. The atrm command removes one or several jobs waiting in the at queue. The atrm command can be used by the users or by the root to delete the pending events. Note : The output from the at command or script is important. The user should ensure to direct it to a file for later examination. In Solaris environment at r command can be used to delete at jobs.
Practice 17.3
The following example shows the use of the at command. [root@icg3 /etc]# at 11:45 pm at> rm /home/kishore/*core* at> <EOT>
warning: commands will be executed using /bin/sh Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
212
Scheduling of System Events job 1 at 2001-05-26 23:45 [root@icg3 /etc]# In the above example the at job removes core files from the user account belonging to kishore near midnight. Creating an at Job The at command allows the user to schedule a command for execution at a specified time, display a list of scheduled jobs and remove jobs from the scheduled jobs list. Jobs can be scheduled by specifying either the absolute time or a time relative to the current time.
Practice 17.4 The following example shows how an at job can be created.
$ at -m 1930 at> rm /home/kishore/*.backup at> Press Control-d
warning: commands will be executed using /bin/sh job 5 at 2001-05-23 19:30 Send mail to the user In the above example the user kishore has created an at job to remove his backup files at 7:30 p.m. The -m option enables the user to receive a mail message after the job completed. The user will receive a mail message when the job is completed, even if there is no output. Controlling Access to at A file can be set up to control access to the at command, permitting only specified users to create, remove, or display queue information about their at jobs. The file that controls access to at, is /etc/at.deny. The users listed in this file cannot access at commands. Root permissions are required to edit this file. Moreover, the at.allow file can be created in the /etc directory, in this case only users listed in the at.allow file can execute at command other than root. The same files are available in the Solaris and SCO environments in the /etc/cron.d/ directory.
Displaying at Jobs
The at jobs can be displayed by using the following:
Syntax:
at -l [username]
Practice 17.5
The following example shows how to display information about the execution times of the at jobs for a user. # at l kishore
1 2001-05-24 09:45 a 2 2001-05-23 19:30 b Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
213
UNIX Administration The above example shows the status information on all jobs submitted by the user kishore. Linux does not return any message to indicate that the job has been cancelled, but the job will not be listed in the queue. Users can remove only their own jobs (root can remove any). Some Linux versions support the atrm command as well as the -r option. Daemon Command used for repetitive scheduling i) edit ii) list crontab entries Location of crontab files Files to control LINUX Crond SOLARIS Crond SCO Crond
One time scheduling To list at jobs To verify at commands waiting to execute To remove an at job Table 17.1
Crontab e Crontab e Crontab e crontab l crontab l crontab l /var/spool/cron /var/spool/cron/crontabs /usr/spool/cron/crontabs /etc/cron.deny /etc/cron.allow /etc/cron.d/cron.deny /etc/cron.d/cron.allow /etc/cron.d/cron.deny /etc/cron.d/cron.allow At at At at l at -l at l Atq Atrm <job id> atq at r <job id> Atq atrm <job id>
214
Performance Monitoring
Lecture 18
Performance Monitoring
Objectives
In this lecture you learn the following
Able to monitor the system performance Knowing Process Management Commands Knowing the tools to Monitor the System Performance in Sun Solaris
will
215
UNIX Administration
Coverage Plan
Lecture 18
18.1 Snap Shot 18.2 Managing System Performance 18.3 Process Management Commands 18.4 Tools to Monitor the System Performance in Sun Solaris 18.5 Short Summary 18.6 Brain Storm
216
Performance Monitoring
The performance of a computer system depends upon how the system uses and allocates its resources. It is important to monitor the performance of the system regularly because this would enable to know about its behavioral pattern under normal conditions. The system administrator should essentially foresee and be able to recognize a problem when it occurs. System resources that affect performance include
Central processing unit (CPU) - The CPU processes instructions, receiving instructions from memory and executing them Input/output (I/O) devices - I/O devices transfer information into and out of the computer. Such a device could be a terminal, keyboard, a disk drive, or a printer Memory - Physical (or main) memory is the amount of memory (RAM) on the system
Process States
As soon as a process is created, the system assigns it a state. A process can be in one of several states. The state of the processes can be viewed on a system using the ps(C) command with the -el options. The S field displays the current state as a single letter. The important states for performance tuning are: O On processor This indicates that the processor is executing on the CPU in either user or system mode. R Runnable This indicates that the process is on a run queue and is ready-to-run. A runnable process has every resource that it needs to execute except the CPU itself. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
217
UNIX Administration S Sleeping This indicates that the process is waiting for some I/O event to complete such as keyboard input or a disk transfer. Sleeping processes are not runnable until the I/O resource becomes available. The figure 18.1 represents these states and the possible transitions between them. On single CPU systems only one process can run on the CPU at a time. All other runnable processes have to wait on the run queue. A portion of the Kernel known as the scheduler chooses which process to run on the CPU(s). When the scheduler wants to run a different process on the CPU, the run queue is scanned from the highest priority to the lowest for the first runnable process. When a process becomes runnable, its priority is calculated by the Kernel and is placed on the run queue at that priority. While it remains runnable, the priority of the process is recalculated once every second, and its position in the run queue is adjusted. When there are no higher-priority runnable processes on the run queue, the process is placed on the CPU to run for a fixed amount of time known as a time slice. a. Main Process states
on CPU in Memory
RRR
RRR
SS SS
Main Flow Swapping Fig 18.1 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
218
Performance Monitoring
This section describes the commands that are used to manage process information.
ps Command
The ps command enables to check the status of active processes on a system, as well as display technical information about the processes. This data is useful for administrative tasks such as determining how to set process priorities. Depending on the option that is chosen, ps reports the following information:
Current status of the process Process ID Parent process ID User ID Scheduling class Priority Address of the process Memory used CPU time used
Listing Processes
The ps command can be used to list all the processes being executed on a system. $ ps [-ef] -e Selects all processes. -f Does full listing. ps displays only the processes associated with the users login session. -ef displays full information about all the processes being executed on the system.
Practice 18.1
The following example shows the output from the ps command when no options are used. #ps Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
219
UNIX Administration
Here, PID refers to the process ID. TTY refers to the terminal from which the process (or its parent) is started. A question mark indicates that there is no controlling terminal. TIME indicates the total amount of CPU time used by the process since it began. COMMAND shows the command that has generated the process.
Practice 18.2
The following example shows the output from ps ef. Only part of the output is given below. # ps ef UID root root root root root root bin root root root root root nobody nobody nobody nobody nobody daemon root root root PID 1 2 3 4 5 6 330 345 346 355 449 458 472 475 476 478 479 490 504 522 536 PPID 0 1 1 1 1 1 1 1 345 1 1 1 1 472 475 475 475 1 1 1 1 C 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 STIME 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 05:41 TTY ? ?\ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? TIME CMD 00:00:04 init 00:00:00 [kflushd] 00:00:00 [kupdate] 00:00:00 [kpiod] 00:00:00 [kswapd] 00:00:00 [mdrecoveryd] 00:00:00 portmap 00:00:00 [lockd] 00:00:00 [rpciod] 00:00:00 rpc.statd 00:00:00 syslogd -m 0 00:00:00 klogd 00:00:00 identd -e o 00:00:00 identd -e o 00:00:00 identd -e o 00:00:00 identd -e o 00:00:00 identd -e o 00:00:00 /usr/sbin/atd 00:00:00 crond 00:00:00 inetd 00:00:00 lpd
Here UID refers to the effective user ID of the owner of the process. PPID indicates the ID of the parent process. C shows the processor utilization for scheduling. This field is not displayed when the c option is used. STIME indicates the starting time of the process (in hours, minutes, and seconds). TIME indicates the total CPU time that has been used by the process since it began. CMD indicates the command that has generated the process. Displaying Information about Processes Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
220
Performance Monitoring The output from the ps command can be used (optional) to obtain the identification number of the process about which more information needs to be displayed. This can be done as follows: # ps -e | grep process Here process indicates the name of the process about which more information needs to be displayed.
Practice 18.3
The following example shows how to display information about a process. # ps -e|grep init 1 ? 00:00:04 init
Here first field represents the process-id(PID), the second field shows the terminal type (TTY), then the third field shows the total amount of CPU time that has been used by the process since it began (TIME), and the final field shows the command that has generated the process (CMD). Displaying the Global Priority of a Process The global priority of a process can be displayed by using the ps command as shown below. $ ps ecl -e -c -l Selects all processes. Selects by command name. Long format.
Practice 18.4
The following shows how to display the global priority of a process. # ps ecl
F 100 040 040 040 040 040 140 040 040 140 140 040 140 140 140
S S S S S S S S S S S S S S S S
UID 0 0 0 0 0 0 1 0 0 0 0 0 0 0 99
PID 1 2 3 4 5 6 330 345 346 355 369 396 449 458 472
PPI 0 1 1 1 1 1 1 1 345 1 1 1 1 1 1
CLS -
PRI 9 39 39 39 39 59 39 39 39 39 39 39 39 39 39
ADDR -
WCHAN do_sel bdflus kupdat kpiod kswapd md_thr do_sel end end do_sel do_sel pipe_r do_sel do_sys wait_f
TTY ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
TIME CMD 00:00:04 init 00:00:00 flushed 00:00:00 0 00:00:00 kpiod 00:00:00 kswapd 00:00:00 drecovery 00:00:00 portmap 00:00:00 lockd 00:00:00 rpciod 00:00:00 pc.statd 00:00:00 apmd 00:00:00 automount 00:00:00 syslogd 00:00:00 klogd 00:00:00 identd
221
UNIX Administration
040 040 040 040 040 040 140 140 140 140 040 100 100 100 100 100 100 100 100 140 100 100 000 100 100 S S S S S S S S S S S S S S S S S S S S S S S S R 99 99 99 99 2 0 0 0 0 0 43 0 0 0 0 0 0 0 0 0 0 101 0 0 0 475 476 478 479 490 504 522 536 584 599 683 723 724 725 726 727 728 729 739 740 752 878 895 896 909 472 475 475 475 1 1 1 1 1 1 1 1 1 1 1 1 1 1 729 729 740 877 878 895 896 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 37 37 29 28 323 323 323 323 286 332 286 301 532 288 926 556 273 273 273 273 273 686 3930 856 1405 423 539 432 636 do_pol ? 00:00:00 rt_sig ? 00:00:00 rt_sig ? 00:00:00 rt_sig ? 00:00:00 nanosl ? 00:00:00 nanosl ? 00:00:00 do_sel ? do_sel ? do_sel ? do_sel ttyS0 do_sel ? wait4 tty1 read_c tty2 read_c tty3 read_c tty4 read_c tty5 read_c tty6 do_pol ? do_sel ? wait4 ? do_pol ? wait4 pts/0 wait4 pts/0 wait4 pts/0 pts/0 identd identd identd identd atd crond
00:00:00 inetd 00:00:00 lpd 00:00:00 sendmail 00:00:00 gpm 00:00:00 xfs 00:00:00 login 00:00:00 mingetty 00:00:00 mingetty 00:00:00 mingetty 00:00:00 mingetty 00:00:00 mingetty 00:00:00 gdm 00:00:01 X 00:00:00 gdm 00:00:00 gnome-sess 00:00:00 sh 00:00:00 su 00:00:00 bash 00:00:00 ps
CLS represents the scheduling class to which the process belongs: real-time, system, or timesharing. This field is included only with the -c option. PRI means the Kernel threads scheduling priority. Higher numbers mean higher priority. ADDR indicates the address of the proc structure. SZ shows the virtual address size of the process. WCHAN indicates the address of an event or lock for which the process is sleeping. Data in the PRI column show that kflushd has the highest priority, while sh has the lowest. This output clearly shows that the system processes will always have higher priority than user processes.
Practice 18.5
222
Performance Monitoring
The following example shows the usage of the uptime command. # uptime
2:06pm up 1 min, 1 user, 0.62 for 1minutes 0.20 for 5 minutes 0.05 for 15 minutes
The output indicates the current time. It shows that there is one user and that the system has been up for 1 minute. It also gives the load averages for the past 1, 5 and 15 minutes respectively. The optimal load average values are 1 for 1 minute, 2 for 5 minutes and 10 for 15 minutes. The load average has to be checked. If this load average is abnormal then different areas in the system such as disk , CPU and RAM need to be checked.
Practice 18.6
The following example shows the usage of the vmstat commands. # vmstat
r 0
io bi bo 35 96
in 418
system cs us 27 1
sy 4
cpu id 96
Here, under procs there are 3 fields. i.e. the number of processes waiting for run time (r), the number of processes in uninterruptable sleep(b) and the number of processes swapped out but otherwise runnable (w), the memory field reports on usage of real and virtual memory. Here there are 3 fields: The amount of virtual memory used in kB (swpd), the amount of idle memory in kB (free). and the amount of memory used as buffers in kB (buff). Under Swap we are having 3 fields: Amount of memory swapped in from disk in kB/s (si), amount of memory swapped to disk in kB/s (so) and the blocks sent to a block device in blocks/s (IO), the blocks received from a block device in blocks/s (bo). Under system there are 2 fields: The number of interrupts per second, including the clock (in), and the number of context switches per second (cs), and these are percentages of total CPU time, user time(us),Under cpu there are 2 fields: system time (sy) and idle time (id).
223
UNIX Administration SAR, in the first instance, samples cumulative activity counters in the operating system at n intervals of t seconds, where t should be 5 or greater. If the -o option is specified, it saves the samples in the file in binary format. The default value of n is 1. In the second instance, with no sampling interval specified, SAR extracts data from a previously recorded file, either the one specified by -f option or, by default, the standard system activity daily data file /var/adm/sa/sadd for the current day dd. The starting and ending times of the report can be bound through the -s and -e time arguments of the form hh[:mm[:ss]]. The -i option selects records at second intervals. Otherwise, all the intervals found in the data file are reported. In either case, subsets of data to be printed are specified by the following options: -a Reports use of file access system routines. -b Reports buffer activity. -c Reports system calls. -d Reports activity for each block device, that is, disk drives. -g Reports graphics activity. -m Reports message and semaphore activities. -p Reports paging activities. -q Reports average queue length while occupied, and % of time occupied. -r Reports unused memory pages and disk blocks. -u Reports CPU utilization (the default). -v Reports status of process, i-node, file tables and record lock tables. -w Reports system swapping and switching activity. -y Reports TTY device activity.
Practice 18.7
The following example is an illustration of the SAR command. # SAR -a 22 17:56:20 iget/s namei/s dirbk/s (-a) 17:56:22 0 0 0 17:56:24 4 1 0 Average 2 1 0 Here 2 samples are taken at an interval of two seconds. iget/s indicates the number of requests made for the inodes that were not in the directory name lookup cache(dnlc). namei/s indicates the number of file system path searches per second. dirbk/s indicates this is the number of directory block reads issued per second.
Practice 18.8
The following example shows how to check buffer activity using SAR # SAR-b 2 2
17:56:37 bread/s lread/s %rcache bwrit/s lwrit/s %wcache pread/s pwrit/s(-b)
0 2 1
2 0 1
100 0 20
8 0 4
2 0 1
0 0 0
0 0 0
0 0 0
224
Performance Monitoring Here bread/s indicates the average number of reads per second submitted to the buffer cache from the disk. lread/s indicates average number of logical reads per second from the buffer cache. %rcache indicates the fraction of logical writes found in the buffer cache (100% minus the ratio of bread/s to lread/s). bwrite average number of physical blocks (512 blocks) written from the buffer cache to disk, per second. lwrite/s indicates the average number of logical writes to the buffer cache, per second. %wcache indicates the fraction of logical writes found in the buffer cache (100% minus the ratio of bwrite/s to lwrite/s). pread/s indicates the average number of physical reads, per second, using character device interface. pwrite/s indicates the average number of physical write requests, per second, using character device interfaces.
Practice 18.9 This example illustrates how to display disk activity statistics with the SAR d command
# SAR -d 22 17:57:14 device %busy 17:57:16 17:57:18 wd-0 0.50 Average wd-0 0.25
Here, devices represents the name of the disk device being mounted. %busy indicates the percentage of time the device has spent in servicing a tranfer request. avque indicates the sum of the average wait time plus average service time. r+w/s shows the number of read and write transfers to the device per second. blks/s indicates the number of 512-byte blocks transferred to the device per second. avwait indicates the average time in milliseconds that transfer to the device per second. avserv indicates the average time in milliseconds, for a transfer request to be completed by the device (for disk). pwrite/s shows the average number of physical write requests, per second, using character device interfaces.
The following example shows how to display Inter-process communication activities using SAR -m # SAR -m 2 2 17:58:37 msg/s 17:58:39 0.00 17:58:41 0.00 Average 0.00
Practice 18.10
Here, msg/s represents the number of message operations (send and receives) per second., sema/s shows the number of semaphore operations per second.
Practice 18.11
The following example illustrates how to monitor unused memory. # SAR -r 2 2 17:59:24 freemem freeswp (-r) 17:59:26 25807 96000 17:59:28 25830 96000 Average 25818 96000 Here, Freemem refers to the free ram space. Freeswp indicates the free swap space. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
225
UNIX Administration
Practice 18.12
The following example shows how to check if the processor is busy or idle. # SAR -u 2 2 17:59:40 %usr 17:59:42 0 17:59:44 0 Average 0
%sys 0 0 0
%wio 0 0 0
Here, %sys represents the percentage of time that the processor is in system mode. %user represents the percentage of time the processor is in user mode. %wio indicates the percentage of time the processor is idle and waiting for I/O completion. %idle shows the percentage of time the processor is idle and is not waiting for I/O. SAR reports may indicate that the processor takes more time in processing the user requests. There might be some programs that use many unwanted system calls, that is, some shell scripts that might refer unwanted files which results in unwanted system calls.
226
Network Management
Lecture 19
Network Management
Objectives
In this lecture you learn the following
Knowing about LAN Fundamentals Understanding the concept of LAN Interconnection About Reference Model Able to test the TCP/IP using IPCONFIG and PING
will
227
UNIX Administration
Coverage Plan
Lecture 19
19.1 Snap Shot 19.2 Network 19.3 LAN Fundamentals 19.4 LANs and the OSI Reference Model 19.5 LAN Interconnection 19.6 Wide Area Networks 19.7 TCP/IP 19.8 Short Summary 19.9 Brain Storm
228
Network Management
19.2 Network
Unix Administration Network Types of Network LAN WAN Topology Protocol Architecture
Classification of Networks
A network is a group of two or more computers that are linked together to share the resources like printers, data, disk drives, cdrom drives and tapedrive.
Types of Network
Many types of network exist, but the most common types of networks are Local-Area Networks (LANs) and Wide-Area Networks (WANs). In a LAN, computers are connected together within a local area (for example, an office or home). In a WAN, computers are geographically distributed and are connected through telephone/communication lines, radio waves, or other means of connection.
Classification of Networks
Networks are usually classified using three properties: Topology, Protocol, and Architecture. Topology specifies the geometric arrangement of the network. Common topologies are bus, ring, and star. Protocol specifies a common set of rules and signals, which the computers on the network use to communicate. Most networks use Ethernet, but some networks may use IBMs Token Ring protocol. Architecture refers to one of the two major types of network architecture: Peer-to-Peer or client/server. In a Peer-to-Peer networking configuration, computers simply connect with each other in a workgroup to share files, printers, and Internet access. This is most commonly found in home configurations, and is only practical for workgroups of a dozen or less computers. In a client/server network, an NT Domain Controller, is usually present to which all the computers log on to. This server can provide various services, including centrally routed Internet access, mail (including e-mail), file sharing, and printer access, as well as ensuring security across the network. This is most commonly found in corporate configurations, where network security is essential.
229
UNIX Administration
Characteristics of LAN
A local area network (LAN) consists of hardware and software that provide the capability to interconnect a variety of data-communicating devices within a limited area. LANs have become an integral part of computing and data communication. Today, most computer manufacturers provide some means for connecting their equipment to a LAN. It is expected that, in the future, installation and use of LANs will increase dramatically. Users connected to a LAN can share devices such as processors, printers, and disk storage. The most efficient use of each device can be achieved by allowing access to it by multiple users; the need to obtain individual devices for each user is eliminated. For example, through a LAN, several workstations can access a single disk. While networks as a whole permit a variety of intelligent devices to exchange data, several important features distinguish a LAN from a wide area network (WAN).
Features of LAN
Service to a limited area. LANs provide network services to a limited area such as a single building or a group of buildings known as a campus, whereas WANs may provide national or international service Private ownership and administration. Unlike wide area networks, which may be subject to the rules of a regulatory agency such as the Federal Communications Commission in the United States or the Office of Telecommunications (OFTEL) in Great Britain, LANs are owned and administered privately. This means a LAN can be designed, installed, maintained, and expanded without external involvement or approval
Complete device connectivity. Each device that is connected to a LAN potentially has equal access to every other network device Self-contained. LANs are self-contained entities that can be constructed with relatively fewer equipments. The geographic coverage that a wide area network provides requires a large array of telecommunication equipments (telephone lines, satellites, and microwave links, to name a few). LANs often connect to a wide area network through a device known as a gateway, but the LAN is always a distinct and independent entity
230
Network Management
The International Standards Organization (ISO) has defined an architecture that describes how devices can communicate over a network. The architecture, referred to as the Open Systems Interconnection (OSI) Reference Model, divides the communication functions into seven distinct and independent layers. Figure 17.1 shows the OSI model.
Application
The application layer defines how a user or process accesses the network. File transfer and mail facilities are the typical examples of application-layer processes.
Presentation
The presentation layer defines the format, including syntax and semantics of the data exchanged between devices. The application layer may deliver the data in a particular format (ASCII, for example) to the presentation layer, where it is transformed into a format suitable for transmission over the network.
Session
The session layer defines how communication (known as a session) is established between machines. The services in this layer also manage different aspects of the session such as synchronization and traffic direction.
Transport
The transport layer defines the connection between the source and destination machines (end-to- end). It ensures that the data from upper-layer processes, usually encapsulated in packets, arrives at its destination error-free and in the correct order.
231
UNIX Administration The following paragraphs define the services provided by each layer of the OSI model: OS Reference Model Application Protocol
Application
Application
Presentation
Presentation
Session
Session
Transport
Transport Protocol
Transport
Network
Network Protocol
Network
Data Link
Data Link
Physical
Physical Protocol
Physical
Figure 19.1
Network
The network layer defines how the packets are routed through the network to their final destination. This layer isolates the upper layers from the underlying aspects of the network.
Data Link
The data link layer defines how blocks of data (packets) are reliably transferred between adjacent network nodes. It is also responsible for error detection and flow control.
Physical
The physical layer defines how the raw bits of upper-level data are physically transferred over the network medium (Physical cable). This layer concerns itself with the electrical and mechanical aspects of data transmission. As shown in Figure 17.1, LANs implement the services defined by the physical and data link layers of the OSI reference model. Additional communications standards, such as the BSD/DOD application utilities and the TCP/IP protocols, must be implemented in some manner to achieve the services defined by the upper layers of the OSI reference model.
232
Network Management
The existence of separate LANs within an organization can be necessitated by a number of factors (such as too many users for one network to support, too large a geographic distance to cover, different network needs of various work groups, or a need for special network security). Organizations containing separate LANs often need to pass data back and forth between them. The generic term relay refers to the equipment that connects LANs. Relays are usually implemented in the lower three layers of the OSI reference model. At the Physical Layer (Layer 1), relays are repeaters that copy signals from one LAN segment to another. Repeaters extend LANs, thus inexpensively solving distance problems at a single location. At the Data Link Layer (Layer 2), relays are bridges that store and forward data packets. LANs use 48-bit source and destination addresses that are administered by the Institute of Electrical and Electronic Engineers (IEEE) so that each system connected to a LAN has a globally unique source address. A bridge examines the source and destination addresses in each data packet transmitted over the LANs to which it is connected. It constructs (and frequently updates) an address table that associates each source address with the LAN on which it is seen. Each packets destination address is compared to the source-address table. If the address is found to be associated with the LAN on which the packet was found, the packet is filtered (discarded). Otherwise, the packet is forwarded. Some bridges can connect different LAN types and are therefore called translation bridges. Bridges have a number of advantages as a means of connecting LANs, the biggest advantage is that they do not require end-user systems to execute any special routing protocols or services. Consequently, bridges are said to be transparent. By filtering out some data packets, bridges can significantly reduce traffic on associated LANs, thus increasing LAN throughput. Many bridges allow network managers to further optimize, or increase the security of their networks by providing additional filters that discard specified types of packets or packets that have particular destination addresses. The greatest disadvantage of connecting LANs with a bridge is that, when filtering is inadequate, the bridge can saturate the network with propagated packets, thus degrading network performance. However, bridges are a low-cost, high-performance means of connecting LANs if the networks contain a limited number of LAN nodes that are not spread over too wide an area. At the Network Layer (Layer 3), relays are either gateways or routers. A router stores and forwards data packets that are directly addressed to it by the user systems. For a router and the source and destination systems must adhere to a common routing protocol. Unlike bridges, routers require the active participation of all end users.
233
UNIX Administration
Ethernet Hardware
Ethernet has evolved over time. Ethernet version 2 released in 1982 was originally developed by XeroxIntel-Dec. In 1985 the IEEE released a new standard for ethernet. This standard is named IEEE 802.2. In general, these two versions of ethernet can inter-operate, however there are a few minor differences. The first difference is that in the ethernet packet header Version 2 defined a two byte Type field while IEEE created a 2 byte length field in that location. Luckily, values for type cannot conflict with valid length values and most systems can determine the Ethernet Frame type by examining this field. A second difference is that the Ethernet version 2 specification required that a transceiver send a heartbeat signal each second. The IEEE 802.2 specification removed this. This has resulted in most vendors offering transceivers that have a switch to enable or disable heart-beat. It should be off unless connected to a piece of equipment using the ethernet version 2 specification. Fortunately, all new devices are built to conform to the 802.2 specification. However, occasionally devices are found that were installed years ago that still need this. In either specification, ethernet uses a 48-bit identifier to uniquely identify each source and destination device. A range of addresses is assigned to each manufacturer of ethernet equipment. There are basically two categories of ethernet components, one type that passes the signal onto other devices, generally these are known as repeaters. A second type of device which takes the signal and regenerates the signal onto a new network, these types of devices are generally known as bridges or routers. Repeaters are useful for propagating a network signal, a signal comes in on an input port is often output to many ports. However, since they add some delay to the transmittal of packets they reduce the maximum size of a segment. However, repeaters can simplify the design of a network. Devices such as bridges and routers, which regenerate the signal, allow to build larger networks. Since the signal is regenerated, it becomes the responsibility of the bridge or router to guarantee the packets arrival at the destination (or the next router or bridge). Bridges and routers work at different levels of the network. Bridges work at the ethernet frame level while routers work at the protocol level. In both cases, the bridge or router, have the property of filtering traffic and only transmitting the signal onto networks. Thus, in each case they have the effect of reducing unnecessary traffic. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
234
Network Management Types of Media used with Ethernet The IEEE 802.2 specification defines the general properties of ethernet. Subsequent standards define how each media type will operate. At present, ethernet can be run over voice grade twisted pair (10BASE-T), thin-wire coaxial cable (10Base-2), thick-wire coaxial cable (10Base-5), and fiber optic cable (10Base-F). The overwhelming majority of connections made today use twisted-pair wiring. This option is now offered as standard equipment on many workstation models. Each media type has different signal properties and limits. For example, (10BASE-T) only supports one machine per segment and is limited in distance to 100 meters. Thinwire (10BASE-2) can support up to 29 stations and is limited to a maximum distance of 185 meters. Fiber optic cabling can support 1024 devices and can operate at distances up to 2 Kilometers. Thickcoaxial cable (10BASE-5) can operate up to 500 meters and support up to 1024 stations. Trancievers often allow dissimilar devices to be attached together. Many machines have a 15 pin Ethernet AUI interface. Tranceivers exist which allow the users to adapt the AUI interface to whatever media you have running to the desktop.
Use twisted pair connections for all desktop connections. This is cost effective and provides an easy way to troubleshoot problems Build networks such that wherever possible servers and clients are on the same network Use routers to build enterprise networks. Routers are more effective at isolating and controlling traffic among networks. Use bridges to seperate traffic within a network Adopt the Simple Network Management Protocol (SNMP) as a management standard and only purchase equipment supporting that standard It is wise to purchase machines with an AUI interface and then use transceivers to connect the machine to whatever media you have
Ensure and follow the design limitations for each media type that is being used before designing networks. The ethernet standard is conservative by nature and the user should strictly adhere to the standards. Often referred to as Thicknet, 10Base5 technology was the first incarnation of Ethernet. It was used in the 1980s until 10Base2 Thinnet with more flexible cabling appeared. (At five millimeters, Thinnet is one-half the thickness of Thicknet.) The most common form of traditional Ethernet, however, is 10Base-T due to the inherent advantages of unshielded twisted pair (UTP) over coaxial cabling and its low cost compared to alternatives like fiber. The following table lists these well-known forms of Ethernet technology. Besides the type of cable involved, another important factor in Ethernet networking is the segment length. A single uninterrupted network cable can only span a certain physical distance before its electrical characteristics are critically affected by factors such as line noise or reduced signal strength. Name 10Base5 10Base2 Segment Length (Max.) 500m / 1640ft. 185m / 606ft. Cable RG-8 or RG-11 coaxial RG 58 A/U or RG 58 C/U coaxial
235
UNIX Administration 10Base-T Table 19.1 Several other less well-known Ethernet standards exist, including 10Base-FL, 10Base-FB, and 10Base-FP for fiber optic networks and 10Broad36 for broadband (CATV) cabling. 100m / 328ft. Category 3 or better unshielded twisted pair
Fast Ethernet
In the mid-1990s, Fast Ethernet achieved its design goal of increasing the performance of traditional Ethernet while avoiding the need to completely re-cable existing networks. Fast Ethernet comes in two major varieties:
100Base-T (using unshielded twisted pair cable) 100Base-FX (using fiber optic cable)
By far the most popular of these is 100Base-T, a standard that includes 100Base-TX (Category 5 UTP), 100Base-T2 (Category 3 or better UTP), and 100Base-T4 (100Base-T2 cabling modified to include two additional wire pairs).
Physical Devices
Standard Hubs The criteria to be ensured before purchasing a standard hub is that it should be capable of handling network expansions Standalone Hubs Standalone hubs are single products with a number of ports. Standalone hubs usually include methods for linking them to other standalone hubs for network expansion. Standalone hubs are usually the least expensive type of hub and are best suited for small, independent workgroups, departments, or offices. Standalone hubs usually include methods for linking them to other standalone hubs for network expansion. typically with fewer than 12 users per LAN. Stackable Hubs Stackable hubs work just like standalone hubs, except that several of them can be stacked (connected) together, usually by short lengths of cable. When they are connected together, they act like a modular hub, because they can be managed as a single unit. These hubs are ideal want to start with a minimal investment, but it should be realized the LAN will grow. Modular Hubs Modular hubs are popular in networks because they are easily expanded and always have a management option. A modular hub is purchased as a chassis, or card cage, with multiple card slots, each of which accepts a communications card, or module. Each module acts like a standalone hub and usually has 12 twisted pair ports. Modules supporting different types of network cabling, like coaxial or token ring, can also be purchased. For a home or small office network, it is preferable to purchase a standalone or stackable hub. For a medium to large sized company, a modular hub will probably fit the needs more efficiently. The other types of network hardware are discussed below. Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
236
Network Management
As the term implies, a wide-area network spans a large physical distance. A WAN, like the Internet spans most of the world. A WAN is a geographically distributed collection of LANs. A network device called a router connects LANs to a WAN. In IP networking, the routers maintain both the addresses of LAN and WAN. WANs differ from LANs in several important ways. Like the Internet, most WANs are not owned by any one organization but rather exist under collective or distributed ownership and management. WANs use technology like ATM, Frame Relay and X.25 for connectivity.
237
UNIX Administration
TCP/IP Reference Models Protocols in TCP/IP Protocol Suite Testing the TCP/IP Using IFCONFIG and PING IP Address
It is a communication protocol that can be used by an application to package its information for sending across a network or networks. It is also referred as a protocol suite. An entire collection of protocols is termed as a protocol suite. The collection includes
Reference Models
A reference model is a blueprint that states how communication should accomplished. It gives addresses for all the processes that are required for effective communication. Here each of the processes are divided into logical groupings called layers. It can be referred as layered architecture. Each layer has its own protocol and supplies the necessary parameter to all layers.
Network Management The OSI reference model has seven layers. They are Application, Presentation, Session, Transport, Network, DataLink and Physical layer. This model has four layers.These layers are Process/Application,Host-to-Host (Transport), Internet and Network Access(Network layer).This model is referred to as the internet protocol suite. In the DOD model the process/application layer performed by the top three layers of the OSI model. This layer contains a vast array of protocols that combine to integrate the various activities and duties performed by the OSIs presentation, Session and Application layers. The Process/Application layer defines protocols for application communication .It also controls user interface applications. The Host-to-Host layer parallels the function of the transport layer of the OSI model. This layer defines a protocol for setting up levels of transmission service for applications. It deals with issues like creating reliable end-to-end communication and ensuring error-free delivery of data. It handles packet sequencing and maintains data integrity. The internet layer corresponds to the network layer of OSI model. This layer defines a protocol relating to the logical transmission of packets over the entire network. It takes care of addressing the hosts by giving them an IP address. It also handles routing of packets among multiple networks. The internet layer controls the communication flow between applications.
In the OSI model the top three layers such as the application, presentation and session layers deal with functions that aid applications in communicating with other applications.They specifically deal with tasks like filename formats, code sets, user interfaces, compression, encryption and other functions relating to the exchange occurring between applications.
The transport layer deals with the logical transmission of data. The layer takes care of sizing of the packets sent by each application. The transport layer ensures error-free delivery of data.
The network layer sets the degree of reliability for packets reaching the destination and the logical address for each machine. When messages reach this layer from the ones above it, the network layer attaches a directive that includes both, the messages source and destination address, forming a packet ready for delivery. Next, the best route for the packet to take across the network to its destination must be chosen. This is known as routing and is handled by routers. The datalink and the physical layers are the bottom layers of the OSI model, which handles the physical transmission of data. The layers take what is passed down to them and put it into a format that can be sent over a variety of physical transmission media like cable, fiber optics, microwave and radio links. They encode data into different media signals to match the specific media over which they will be transmitted.
The network access layer monitors the of data exchange between the host and the network. This layer is equivalent of the data link and the physical layers of the OSI model. This layer defines the protocol for the physical transmission of data.
Table 19.2
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
239
UNIX Administration
Simple Network Management Protocol(SNMP) This protocol provides for the collection and manipulation of valuable network information needed in trouble shooting the network problems. X Windows Designed for client server operations, X windows defines a protocol for the writing of graphical user interface-based client/server application.
Internet Protocol (IP) IP takes segments from the host-to-host layer and fragments them into datagrams (packets) Address Resolution Protocol (ARP) It is used to find the destinations hardware address
Receiving an IP datagram and framing it into a stream of bits (1s and 0s) for physical transmission of data
240
Network Management
Ensuring that the stream of bits that make up the frame have been accurately received by calculating a Cyclic Redundancy Checksum(CRC) jellybean count
Specifying the access methods to the physical networks, such as Token-passing for token ring, fiber distribution data distribution (FDDI) and polling for IBM Mainframes
Specifying the physical media , the connector, electrical signaling and timing rules
Some of the technologies used to implement the network access layers are
LAN-oriented protocols Ethernet (thick coaxial cable, thin coaxial cable and twisted-pair cable) Token Ring ARCnet WAN Oriented protocols Point-to-Point protocol(PPP) X.25 Frame Delay
PING Utility
The PING (Packet Internet Gopher) utility is used to test connectivity of the TCP/IP host, after the configuration is verified with the IFCONFIG utility. The PING utility is a diagnostic tool which is used to test TCP/IP configurations. It is also used to diagnose connection failures. The ICMP echo request and echo failure messages are used by PING to determine whether a particular TCP/IP host is available and functional. # ping <ip-address>
IP Address
An IP address is a numeric identifier that is assigned to each machine on an IP network. It is used to identify the location of the device that is assigned to it on the network. The IP address of the machine is a software address and not a hardware address. TCP/IP host is identified by a logical IP address. A unique IP address is required for each host and the network component uses TCP/IP for purposes of communication. The IP address identifies the location of the system on the network and it is globally unique format.
241
UNIX Administration Each IP address defines the networkID and hostID. NetworkID is used to identify the systems that are located on the same physical network. All the systems on the network must have the same networkID. It should be unique. NetworkID is 130. 56. 30.57 |_____| |______________ HostID is used to identifies a workstation, server, router or other TCP/IP hosts within a network. It is used to uniquely identify each machine on the network. It has its own unique hostID for each and every machine
Example
HostID is 130.56.30.57 |_____| |______________ Each IP address is 32 bits long and is composed of four 8 bit fields called octets. The octet represents a decimal in the range 0-255.This format is called dotted decimal notation. Binary Format 10000011 01101011 00000011 00011000 Dotted Decimal Notation 131.107.3.24
Address Classes
The address class defines which bits are used for the network ID and which bits are used for the Host IDs. It also defines the possible number of networks and the number of hosts per network The internet community has defined three address classes based on the network size. There are three address classes:
242
Network Management Class B addresses are assigned to medium-sized to large-sized networks. The two high-order bits in a class B network are always set to binary 10.The next 14 bits complete the networkID. The remaining 16 bits represent the host ID. There can be a maximum of 16,384 networks and approximately 65000 hosts per network in class B address class. Specification: Class Format Leading Bit Pattern Decimal range of first byte of network address Maximum Networks Maximum Networks Maximum Nodes per Network B Net.Net.Node.Node 10 128-191 127 16,384 65,534
A network is a group of two or more computers linked together to share the resources like printers, data, disk drives, cdrom drives & tapedrive The P2P acronym technically stands for peer-to-peer computer networking In a P2P type of network each workstation has equivalent capabilities and responsibilities. This differs from client/server architectures, in which some computers are dedicated to serving the others A local area network (LAN) consists of hardware and software that provide the capability to interconnect a variety of data-communicating devices within a limited area. LANs have become an integral part of computing and data communications A WAN is a geographically-dispersed collection of LANs. A network device called a router connects LANs to a WAN. In IP networking, the router maintains both a LAN address and a WAN address WANs differ from LANs in several important ways. Like the Internet, most WANs are not owned by any one organization but rather exist under collective or distributed ownership and management. WANs use technology like ATM, Frame Relay and X.25 for connectivity
243
UNIX Administration A reference model is a blueprint of how communication should be accomplished An IP address is a numeric identifier assigned to each machine on an IP network Transmission Control Protocol (TCP) tests for errors, resends data if necessary and reports the occurrence of errors to the upper layers if it cannot manage to solve the problem itself UDP is considered as a thin protocol since it does not occupy much space over the network The address class defines the type of bits are used for the network ID and which bits are used for the Host IDs The application layer defines how a user or process accesses the network The presentation layer defines the format, including syntax and semantics, of the data exchanged between devices The session layer defines how communication (known as a session) is established between the machines The transport layer defines the connection between the source and destination machines (end-to-end) The network layer defines how packets are routed through the network to their final destination The data link layer defines how blocks of data (packets) are reliably transferred between adjacent network nodes The physical layer defines how the raw bits of upper-level data are physically transferred over the network medium (Physical cable) The different types of Transmission Media are: twisted pair cable, coaxial cable, Fiber Optic cables The Transmission Modes are: base band transmission, broad band transmission The different network topologies are Bus, Ring and Star
244
Syllabus
245
UNIX Administration Lecture 11Network File system Network File System (NFS) nsfd mountd lockd statd - rpc.portmapper - Starting and Stopping the nfs Daemons - To start and stop NFS Daemons - Configuring nfs Servers and Clients Mounting the Remote File System - NFS-mounting the File System - Mounting the NFS File System Lecture 12Virtual File System Virtual File System - Types of Virtual File System - Swap File System - Process File System Process File System - What is /proc File System? - What is in this File System? Lecture 13Security Security - Types of Security - File Server Security - System Level Security Lecture 14Printer Management Printer Management - Configuring Print Services - Setting up the Printer - Setting up the Print server - Setting up the Print client - Print service Architecture - Print Service Directories - Print Functions - Starting and Stopping Daemons - Configuring Printer - Printing a file - To print a file To view the status of a printer - Canceling the print job Lecture 15Backup and Recovery Backups - tar command - cpio command - dd command - mt command - dump/restore command Lecture 16Space Management Space Management Quota - Quota set up for a user -Turning quotas on - Setting up quotas for single user - Setting quotas for multiple user - To check quota consistency - Checking quotas on a file system Lecture 17 Scheduling of System Events Scheduling of System Events - Types of Scheduling Events - Jobs Scheduling Using Crontab - Jobs Scheduling Using At Lecture 18Performance Monitoring Managing System Performance - Process Management - Process States - Process Management Commands - ps command - Listing Processes Lecture 19Network Management Network - Types of network - Classification of network - LAN Fundamentals - Characteristic of LAN - Features of LAN - LANs and OSI Reference Model - OSI Reference Model - LAN interconnection - Basic Network design - Wide Area Network - TCP/IP - Reference Models Protocols in TCP/IP Protocol Suite - Testing the TCP/IP using IPCONFIG and PING - IP address
246