All Linux System Administration
All Linux System Administration
Administration
FFU SEMESTER 9 HANDOUTS
1965 Bell Laboratories joins with MIT and General Electric in the development effort
for the new operating system, Multics, which would provide multi-user, multi-
processor, and multi-level (hierarchical) file system, among its many forward-looking
features.
1969 AT&T was unhappy with the progress and drops out of the Multics project. Some
of the Bell Labs programmers who had worked on this project, Ken Thompson, Dennis
Ritchie, Rudd Canaday, and Doug McIlroy designed and implemented the first version
of the Unix File System on a PDP-7 along with a few utilities. It was given the name
UNIX by Brian Kernighan as a pun on Multics.
1971 The system now runs on a PDP-11, with 16Kbytes of memory, including 8Kbytes
for user programs and a 512Kbyte disk.
Its first real use is as a text processing tool for the patent department at Bell Labs. That
utilization justified further research and development by the programming group.
UNIX caught on among programmers because it was designed with these features:
• programmers environment
• simple user interface
• simple utilities that can be combined to perform powerful functions
• hierarchical file system
• simple interface to devices consistent with file format
• multi-user, multi-process system
• architecture independent and transparent to the user.
1974 Thompson and Ritchie publish a paper in the Communications of the ACM
describing the new Unix OS. This generates enthusiasm in the Academic community
which sees a potentially great teaching tool for studying programming systems
2
development. Since AT&T is prevented from marketing the product due to the 1956
Consent Decree they license it to Universities for educational purposes and to
commercial entities.
Software Development)
1984 There are now about 100,000 Unix sites running on many different hardware
platforms, of vastly different capabilities.
1988 AT&T and Sun Microsystems jointly develop System V Release 4 (SVR4).
This would later be developed into UnixWare and Solaris 2.
1995 Santa Cruz Operations buys UnixWare from Novell. Santa Cruz Operations and
Hewlett-Packard announce that they will jointly develop a 64-bit version of Unix.
1996 International Data Corporation forecasts that in 1997 there will be 3 million Unix
systems shipped world-wide.
3
Inside Linux
• Kernel
o The core of the UNIX system. Loaded at system start up (boot). Memory-
resident control program.
o Manages the entire resources of the system, presenting them to you and
every other user as a coherent system. Provides service to user
applications such as device management, process scheduling, etc.
o Example functions performed by the kernel are:
▪ Managing the machine's memory and allocating it to each process.
▪ Scheduling the work done by the CPU so that the work of each user
is carried out as efficiently as is possible.
▪ Accomplishing the transfer of data from one part of the machine to
another
▪ Interpreting and executing instructions from the shell
▪ Enforcing file access permissions
o You do not need to know anything about the kernel in order to use a
UNIX system. These details are provided for your information only.
• Shell
o Whenever you login to a Unix system you are placed in a shell program.
The shell's prompt is usually visible at the cursor's position on your
screen. To get your work done, you enter commands at this prompt.
o The shell is a command interpreter; it takes each command and passes it
to the operating system kernel to be acted upon. It then displays the
results of this operation on your screen.
o Several shells are usually available on any UNIX system, each with its
own strengths and weaknesses.
o Different users may use different shells. Initially, your system
adminstrator will supply a default shell, which can be overridden or
changed. The most commonly available shells are:
▪ Bourne shell (sh)
▪ C shell (csh)
▪ Korn shell (ksh)
▪ TC Shell (tcsh)
▪ Bourne Again Shell (bash)
4
o Each shell also includes its own programming language. Command
files, called "shell scripts" are used to accomplish a series of tasks.
• Utilities
Operating system
1
• It manages the sharing of internal memory among multiple applications.
• It handles input and output to and from attached hardware devices, such as
hard disks, printers, and dial-up ports.
• It sends messages to each application or interactive user (or to a system operator)
about the status of operation and any errors that may have occurred.
• It can offload the management of what are called batch jobs (for example,
printing) so that the initiating application is freed from this work.
• On computers that can provide parallel processing, an operating system can
manage how to divide the program so that it runs on more than one
processor at a time.
UNIX and 'UNIX-like' operating systems (such as Linux) consist of a kernel and some
system programs. There are also some application programs for doing work. The kernel
is the heart of the operating system. In fact, it is often mistakenly considered to be the
operating system itself, but it is not. An operating system provides many more services
than a plain kernel.
It keeps track of files on the disk, starts programs and runs them concurrently, assigns
memory and other resources to various processes, receives packets from and sends
packets to the network, and so on. The kernel does very little by itself, but it provides
tools with which all services can be built. It also prevents anyone from accessing the
hardware directly, forcing everyone to use the tools it provides. This way the kernel
provides some protection for users from each other. The tools provided by the kernel
2
are used via system calls.
The system programs use the tools provided by the kernel to implement the various
services required from an operating system. System programs, and all other programs,
run `on top of the kernel', in what is called the user mode. The difference between
system and application programs is one of intent: applications are intended for getting
useful things done (or for playing, if it happens to be a game), whereas system
programs are needed to get the system working. A word processor is an application;
mount is a system program. The difference is often somewhat blurry, however, and is
important only to compulsive categorizers.
An operating system can also contain compilers and their corresponding libraries (GCC
and the C library in particular under Linux), although not all programming languages
need be part of the operating system. Documentation, and sometimes even games, can
also be part of it.
• Process management
• Memory management
• Hardware device drivers
• Filesystem drivers
• Network management
• Various other bits and pieces
3
Probably the most important parts of the kernel (nothing else works without them) are
memory management and process management. Memory management takes care of
assigning memory areas and swap space areas to processes, parts of the kernel, and for
the buffer cache. Process management creates processes, and implements multitasking
by switching the active process on the processor.
At the lowest level, the kernel contains a hardware device driver for each kind of
hardware it supports. Since the world is full of different kinds of hardware, the number
of hardware device drivers is large. There are often many otherwise similar pieces of
hardware that differ in how they are controlled by software. The similarities make it
possible to have general classes of drivers that support similar operations; each member
of the class has the same interface to the rest of the kernel but differs in what it needs to
do to implement them. For example, all disk drivers look alike to the rest of the kernel,
i.e., they all have operations like `initialize the drive', `read sector N', and `write sector
N'.
4
2) system Access and File system
Linux Structure
Linux is a layered operating system. The innermost layer is the hardware that provides
the services for the OS. The operating system, referred to in Linux as the kernel,
interacts directly with the hardware and provides the services to the user programs.
These user programs don’t need to know anything about the hardware. They just need
to know how to interact with the kernel and it’s up to the kernel to provide the desired
service. One of the big appeals of Linux to programmers has been that most well
written user programs are independent of the underlying hardware, making them
readily portable to new systems.
User programs interact with the kernel through a set of standard system calls. These
system calls request services to be provided by the kernel. Such services would include
accessing a file: open close, read, write, link, or execute a file; starting or updating
accounting records; changing ownership of a file or directory; changing to a new
directory; creating, suspending, or killing a process; enabling access to hardware
devices; and setting limits on system resources.
Linux is a multi-user, multi-tasking operating system. You can have many users logged
into a system
simultaneously, each running many programs. It’s the kernel’s job to keep each process
and user separate and to regulate access to system hardware, including cpu, memory,
disk and other I/O devices.
5
Linux vs. Windows
Linux and Windows. Each has its own set of unique features, advantages and
disadvantages. While it is difficult to say which one is the better choice, it is not as
difficult to answer which is the better choice given your needs.
Note: The operating system that you use on your desktop computer (the vast majority of people
use some flavor of Windows) has absolutely nothing to do with the one that your host needs to
serve your web site. Most personal sites are created with MS FrontPage and even although that
is a Microsoft product, it can be hosted perfectly on a LINUX web server with FrontPage
Extensions installed.
Stability:
LINUX systems (we actually use Linux but for comparison purposes they are identical)
are hands-down the winner in this category. There are many factors here but to name
just a couple big ones: in our experience LINUX handles high server loads better than
Windows and LINUX machines seldom require reboots while Windows is constantly
needing them. Servers running on LINUX enjoy extremely high up- time and high
availability/reliability.
Performance:
While there is some debate about which operating system performs better, in our
experience both perform comparably in low-stress conditions however LINUX servers
under high load (which is what is important) are superior to Windows.
Scalability:
Web sites usually change over time. They start off small and grow as the needs of the
person or organization running them grow. While both platforms can often adapt to
your growing needs, Windows hosting is more easily made compatible with LINUX-
based programming features like PHP and MySQL. LINUX-based web software is not
always 100% compatible with Microsoft technologies like .NET and VB development.
Therefore if you wish to use these, you should choose Windows web hosting.
Compatibility:
6
Web sites designed and programmed to be served under a LINUX-based web server can
easily be hosted on a Windows server, whereas the reverse is not always true. This makes
programming for LINUX the better choice.
Price:
Servers hosting your web site require operating systems and licenses just like everyone
else. Windows 2003 and other related applications like SQL Server each cost a significant
amount of money; on the other hand, Linux is a free operating system to download,
install and operate. Windows hosting results in being a more expensive platform.
Conclusion:
To sum it up, LINUX-based hosting is more stable, performs faster and more compatible
than Windows- based hosting. You only need Windows hosting if you are going to
developing in .NET or Visual Basic, or some other application that limits your choices
Logging On To System
• Before you can begin to use the system you will need to have a valid username
and a password. Assignment of usernames and initial passwords is typically
handled by the System Administrator
• Your username, also called a userid, should be unique and should not change.
Initial passwords can be anything and should be changed after your first login.
To login to your account
• Type your username at the login prompt, initial of your first name followed
by last name (e.g iafzal). LINUX is case sensitive - if your username is kellyk
do not type KellyK . Press the RETURN or ENTER key after typing your
username.
• When the password prompt appears, type in your password. Your password is
never displayed on the screen as a security measure. It also is case sensitive.
Press the RETURN or ENTER key after entering your password.
• What happens after you successfully login depends upon your system, many
LINUX systems will display a login banner or "message of the day". Make a
habit of reading this since it may contain important information about the
system.
• Other LINUX systems will automatically configure your environment and
open one or more windows for you to do work in.
7
• You should see a prompt - usually a percent sign (%) or dollar sign ($). This is
called the "shell prompt" (the shell is discussed in detail later). It indicates that
the system is ready to accept commands from you.
If your login attempt was unsuccessful, there are several possible reasons:
login: kellyk
kellyk's
Password:
************************************************************
* Welcome to the Linux Systems Training Class
************************************************************
*
* Hello! (Greetings)
*
* System maintenance is scheduled today from 2:00
* until 4:00 pm EST
*
* (Thank you very much)
*
************************************************************
8
• You are in control of your home directory and the files which reside there. You are
also in control of the file access permissions (discussed later) to the files in your home
directory. Generally, you alone should be able to create/delete/modify files in your
home directory. Others may have permission to read or execute your files as you
determine.
• In most LINUX systems, you can "move around" or navigate to other parts of the
file system outside of your home directory. This depends upon how the file
permissions have been set by others and/or the System Administrator
Linux File System
A file system is a logical collection of files on a partition or disk. A partition is a container for
information and can span an entire hard drive if desired.
Your hard drive can have various partitions which usually contains only one file system,
such as one file system housing the / file system or another containing the /home file system.
One file system per partition allows for the logical maintenance and management of
differing file systems.
Everything in Linux is considered to be a file, including physical devices such as DVD-
ROMs, USB devices, floppy drives, and so forth.
Directory Structure:
Linux uses a hierarchical file system structure, much like an upside-down tree, with root (/) at
the base of the file system and all other directories spreading from there.
A LINUX filesystem is a collection of files and directories that has the following
properties: It has a root directory (/) that contains other files and directories.
Each file or directory is uniquely identified by its name, the directory in which it resides, and
a unique identifier, typically called an inode.
By convention, the root directory has an inode number of 2 and the lost+found directory
has an inode number of 3. Inode numbers 0 and 1 are not used. File inode numbers can be
seen by specifying the -i option to ls command.
It is self contained. There are no dependencies between one filesystem and any other.
9
File System:
What are filesystems?
A filesystem is the methods and data structures that an operating system uses to keep
track of files on a disk or partition; that is, the way the files are organized on the disk.
The word is also used to refer to a partition or disk that is used to store the files or the
type of the filesystem. Thus, one might say ``I have two filesystems'' meaning one has
two partitions on which one stores files, or that one is using the
``extended filesystem'', meaning the type of the filesystem.
The difference between a disk or partition and the filesystem it contains is important.
A few programs (including, reasonably enough, programs that create filesystems)
operate directly on the raw sectors of a disk or partition; if there is an existing file
system there it will be destroyed or seriously corrupted. Most programs operate on a
filesystem, and therefore won't work on a partition that doesn't contain one (or that
contains one of the wrong types).
Before a partition or disk can be used as a filesystem, it needs to be initialized, and the
bookkeeping data structures need to be written to the disk. This process is called making
a filesystem.
Most LINUX filesystem types have a similar general structure, although the exact
details vary quite a bit. The central concepts are superblock, inode , data block,
directory block , and indirection block. The superblock contains information about the
filesystem as a whole, such as its size (the exact information here depends on the
filesystem). An inode contains all information about a file, except its name. The name is
stored in the directory, together with the number of the inode. A directory entry
consists of a filename and the number of the inode which represents the file. The inode
contains the numbers of several data blocks, which are used to store the data in the file.
There is space only for a few data block numbers in the inode, however, and if more
are needed, more space for pointers to the data blocks is allocated dynamically. These
dynamically allocated blocks are indirect blocks; the name indicates that in order to find
the data block, one has to find its number in the indirect block first.
LINUX filesystems usually allow one to create a hole in a file (this is done with the
lseek() system call; check the manual page), which means that the filesystem just
pretends that at a particular place in the file there is just zero bytes, but no actual disk
sectors are reserved for that place in the file (this means that the file will use a bit less
disk space). This happens especially often for small binaries, Linux shared libraries,
some databases, and a few other special cases. (Holes are implemented by storing a
10
special value as the address of the data block in the indirect block or inode. This special
address means that no data block is allocated for that part of the file, ergo, there is a
hole in the file.)
Comparing Filesystem Features
11
This topic is loosely based on the Filesystems Hierarchy Standard (FHS), which attempts
to set a standard for how the directory tree in a Linux system should be organized.
Such a standard has the advantage that it will be easier to write or port software for
Linux, and to administer Linux machines, since everything should be in standardized
places. There is no authority behind the standard that forces anyone to comply with it,
but it has gained the support of many Linux distributions. It is not a good idea to break
with the FHS without very compelling reasons. The FHS attempts to follow Linux
tradition and current trends, making Linux systems familiar to those with experience
with other Linux systems, and vice versa.
The full directory tree is intended to be breakable into smaller parts, each capable of
being on its own disk or partition, to accommodate to disk size limits and to ease
backup and other system administration tasks. The major parts are the root (/ ), /usr ,
/var , and /home filesystems (see the following figure). Each part has a different purpose.
The directory tree has been designed so that it works well in a network of Linux
machines which may share some parts of the filesystems over a read-only device (e.g., a
CD-ROM), or over the network with NFS.
The roles of the different parts of the directory tree are described below
12
• The root filesystem is specific for each machine (it is generally stored on a local disk,
although it could be a ramdisk or network drive as well) and contains the files that are
necessary for booting the system up, and to bring it up to such a state that the other
filesystems may be mounted. The contents of the root filesystem will therefore be
sufficient for the single user state. It will also contain tools for fixing a broken system,
and for recovering lost files from backups.
• The /usr filesystem contains all commands, libraries, manual pages, and other
unchanging files needed during normal operation. No files in /usr should be specific
for any given machine, nor should they be modified during normal use. This allows
the files to be shared over the network, which can be cost- effective since it saves disk
space (there can easily be hundreds of megabytes, increasingly multiple gigabytes in
/usr). It can make administration easier (only the master /usr needs to be changed
when updating an application, not each machine separately) to have /usr network
mounted. Even if the filesystem is on a local disk, it could be mounted read-only, to
lessen the chance of filesystem corruption during a crash.
• The /var filesystem contains files that change, such as spool directories (for mail, news,
printers, etc), log files, formatted manual pages, and temporary files. Traditionally
everything in /var has been somewhere below /usr , but that made it impossible to mount
/usr read-only.
• The /home filesystem contains the users' home directories, i.e., all the real data on the
system. Separating home directories to their own directory tree or filesystem makes
backups easier; the other parts often do not have to be backed up, or at least not as often
as they seldom change. A big /home might have to be broken across several filesystems,
which requires adding an extra naming level below /home, for example
/home/students and /home/staff.
Although the different parts have been called filesystems above, there is no
requirement that they actually be on separate filesystems. They could easily be kept in a
single one if the system is a small single-user system and the user wants to keep things
simple. The directory tree might also be divided into filesystems differently, depending
on how large the disks are, and how space is allocated for various purposes. The
important part, though, is that all the standard names work; even if, say, /var and /usr
are actually on the same partition, the names /usr/lib/libc.a and /var/log/messages must
work, for example by moving files below /var into /usr/var, and making /var a symlink
to /usr/var.
The Linux filesystem structure groups files according to purpose, i.e., all commands are
13
in one place, all data files in another, documentation in a third, and so on. An
alternative would be to group files according to the program they belong to, i.e., all
Emacs files would be in one directory, all TeX in another, and so on. The problem with
the latter approach is that it makes it difficult to share files (the program directory often
contains both static and sharable and changing and non-sharable files), and sometimes
to even find the files (e.g., manual pages in a huge number of places, and making the
manual page programs find all of them is a maintenance nightmare).
The root filesystem should generally be small, since it contains very critical files and a
small, infrequently modified filesystem has a better chance of not getting corrupted. A
corrupted root filesystem will generally mean that the system becomes unbootable
except with special measures (e.g., from a floppy), so you don't want to risk it
14
15
1. / – Root
• Every single file and directory starts from the root directory.
• Only root user has write privilege under this directory.
• Please note that /root is root user’s home directory, which is
not same as /.
16
• Contains device files.
• These include terminal devices, usb, or any device attached to
the system.
• For example: /dev/tty1, /dev/usbmon0
18
• For example: ld-2.11.1.so, libncurses.so.5.7
19
File Names
• LINUX permits file names to use most characters, but avoid spaces, tabs and
characters that have a special meaning to the shell, such as:
• Case Sensitivity: uppercase and lowercase are not the same! These are three
different files:
• Hidden Files: have names that begin with a dot (.) For example:
.cshrc .login .mailrc .mwmrc
• Reserved Filenames:
/ - the root directory (slash)
. - current directory (period)
.. - parent directory (double period)
~ - your home directory (tilde)
20
Passwords Standards
When your account is issued, you will be given an initial password. It is important for
system and personal security that the password for your account be changed to
something of your choosing. The command for changing a password is "passwd". You
will be asked both for your old password and to type your new selected password twice.
If you mistype your old password or do not type your new password the same way
twice, the system will indicate that the password has not been changed.
Some system administrators have installed programs that check for appropriateness of
password (is it cryptic enough for reasonable system security). A password change may
be rejected by this program. When choosing a password, it is important that it be
something that could not be guessed -- either by somebody unknown to you trying to
break in, or by an acquaintance who knows you. Suggestions for choosing and using a
password follow:
Don't
use a word (or words) in any
language use a proper name
use information that can be found in your wallet
use information commonly known about you (car license, pet
name, etc) use control characters. Some systems can't handle them
write your password anywhere
ever give your password to *anybody*
Do
use a mixture of character types (alphabetic, numeric,
special) use a mixture of upper case and lower case
use at least 6 characters
choose a password you can
remember change your password
often
make sure nobody is looking over your shoulder when you are entering your password
21
Change Password in LINUX
To modify a user's password or your own password in LINUX use the passwd command. Open
the terminal and then type the passwd command entering the new password, the characters
entered do not display on screen, in order to avoid the password being seen by a passer-by. The
passwd command prompts for the new password twice in order to detect any typing errors. The
encrypted password is stored in /etc/shadow file.
Sample outputs:
Enter new LINUX password:
Retype new LINUX password:
passwd: password updated successfully
Sample outputs:
(current) LINUX password:
Enter new LINUX password:
Retype new LINUX
password:
passwd: password updated successfully
22
How to Use Wildcards
A wildcard is a character that can be used as a substitute for any of a class of characters
in a search, thereby greatly increasing the flexibility and efficiency of searches.
Wildcards are commonly used in shell commands in Linux and other Unix-like
operating systems. A shell is a program that provides a text-only user interface and
whose main function is to execute commands typed in by users and display their
results.
Wildcards are also used in regular expressions and programming languages. Regular
expressions are a pattern matching system that uses strings (i.e., sequences of characters)
constructed according to pre- defined syntax rules to find desired strings in text.
The term wildcard or wild card was originally used in card games to describe a card that
can be assigned any value that its holder desires. However, its usage has spread so that it
is now used to describe an unknown or unpredictable factor in a variety of fields.
Star Wildcard
Three types of wildcards are used with Linux commands. The most frequently employed
and usually the most useful is the star wildcard, which is the same as an asterisk (*). The
star wildcard has the broadest meaning of any of the wildcards, as it can represent zero
characters, all single characters or any string.
As an example, the file command provides information about any filesystem object
(i.e., file, directory or link) that is provided to it as an argument (i.e., input). Because the
star wildcard represents every string, it can be used as the argument for file to return
information about every object in the specified directory. Thus, the following would
display information about every object in the current directory (i.e., the directory in
which the user is currently working):
file *
If there are no matches, an error message is returned, such as *: can't stat `*' (No such file
or directory).. In the case of this example, the only way that there would be no matches is
if the directory were empty.
Wildcards can be combined with other characters to represent parts of strings. For
23
example, to represent any filesystem object that has a .jpg filename extension, *.jpg
would be used. Likewise, a* would represent all objects that begin with a lower case
(i.e., small) letter a.
As another example, the following would tell the ls command (which is used to list files)
to provide the names of all files in the current directory that have an .html or a .txt
extension:
ls *.html *.txt
Likewise, the following would tell the rm command (which is used to remove files and
directories) to delete all files in the current directory that have the string xxx in their
name:
rm *xxx*
The question mark (?) is used as a wildcard character in shell commands to represent
exactly one character, which can be any single character. Thus, two question marks in
succession would represent any two characters in succession, and three question marks
in succession would represent any string consisting of three characters.
Thus, for example, the following would return data on all objects in the current directory
whose names, inclusive of any extensions, are exactly three characters in length:
file ???
And the following would provide data on all objects whose names are one, two or three
characters in length:
file ? ?? ???
As is the case with the star wildcard, the question mark wildcard can be used in
combination with other characters. For example, the following would provide
information about all objects in the current directory that begin with the letter a and
are five characters in length:
file a????
24
The question mark wildcard can also be used in combination with other wildcards
when separated by some other character. For example, the following would return a
list of all files in the current directory that have a three-character filename extension:
ls *.???
25
Square Brackets Wildcard
The third type of wildcard in shell commands is a pair of square brackets, which can
represent any of the characters enclosed in the brackets. Thus, for example, the following
would provide information about all objects in the current directory that have an x, y
and/or z in them:
file *[xyz]*
And the following would list all files that had an extension that begins
with x, y or z: ls *.[xyz]*
The same results can be achieved by merely using the star and question mark wildcards.
However, it is clearly more efficient to use the bracket wildcard.
When a hyphen is used between two characters in the square brackets wildcard, it
indicates a range inclusive of those two characters. For example, the following would
provide information about all of the objects in the current directory that begin with any
letter from a through f:
file [a-f]*
And the following would provide information about every object in the current
directory whose name includes at least one numeral:
file *[0-9]*
The use of the square brackets to indicate a range can be combined with its use to
indicate a list. Thus, for example, the following would provide information about all
filesystem objects whose names begin with any letter from a through c or begin with s or
t:
file [a-cst]*
Likewise, multiple sets of ranges can be specified. Thus, for instance, the following
would return information about all objects whose names begin with the first three or the
final three lower case letters of the alphabet:
file [a-cx-z]*
ls jones[0-9][0-9][0-9]
Other Wild Cards
^ (caret) = means "the beginning of the line". So "^a" means find a line starting with an
"a".
$ (dollar sign) = means "the end of the line". So "a$" means find a line ending with an "a".
For example, this command searches the file myfile for lines starting with an "s" and
ending with an "n", and prints them to the standard output (screen):
27
Soft Link and Hard Links
blah2 And as
expected:
$ ln blah1 blah1-hard
$ ln -s blah2 blah2-soft
$ ls -l
blah1
blah1-
hard
blah2
blah2-soft -> blah2
$ mv blah1 blah1-new
$ cat blah1-
28
hard Cat
blah1-hard points to the inode, the contents, of the file - that wasn't changed.
$ mv blah2 blah2-new
$ ls blah2-
soft blah2-
soft
$ cat blah2-soft
The contents of the file could not be found because the soft link points to the name,
that was changed, and not to the contents.
Similarly, If blah1 is deleted, blah1-hard still holds the contents; if blah2 is deleted,
blah2-soft is just a link to a non-existing file.
29
3- Linux Fundamentals
A command is a program that tells the Linux system to do something. It has the form:
command [options] [arguments]
where an argument indicates on what the command is to perform its action, usually a
file or series of files. An option modifies the command, changing the way it performs.
Commands are case sensitive. command and Commands are not the same.
Options are generally preceded by a hyphen (-), and for most commands, more than one
option can be strung together, in the form:
command -[option][option][option]
e.g.:
ls –alR = will perform a long list on all files in the current directory and
recursively perform the list through all sub-directories.
For most commands you can separate the options, preceding each with a hyphen, e.g.:
command -option1 -option2 -option3
as in: ls -a -l -R
Some commands have options that require parameters. Options requiring parameters are
usually specified separately, e.g.:
lpr -Pprinter3 -# 2 file
will send 2 copies of file to printer3.
These are the standard conventions for commands. However, not all Linux commands
will follow the standard. Some don’t require the hyphen before options and some won’t
let you group options together, i.e. they may require that each option be preceded by a
hyphen and separated by whitespace from other options and arguments.
Options and syntax for a command are listed in the man page for the command.
30
File Permissions
• UNIX is a multi-user system. Every file and directory in your account can be protected from or
made accessible to other users by changing its access permissions. Every user has responsibility
for controlling access to their files.
Example:
31
Permissions can also be change through numerical method. Each of the permission types is
represented by either a numeric equivalent:
read=4, write=2, execute=1
or a single letter:
read=r, write=w, execute=x
A permission of 4 or r would specify read permissions. If the permissions desired are read and write, the
4 (representing read) and the 2 (representing write) are added together to make a permission of 6.
Therefore, a permission setting of 6 would allow read and write permissions.
Common Options
-f force (no error message is generated if the change is unsuccessful)
-R recursively descend through the directory structure and change the modes
Examples
If the permission desired for file1 is user: read, write, execute, group: read, execute, other: read, execute,
the command to use would be
Reminder: When giving permissions to group and other to use a file, it is necessary to allow at least
execute permission to the directories for the path in which the file is located. The easiest way to do this
is to be in the directory for which permissions need to be granted:
File Ownership
Syntax
chown [options] user[:group] file (SVR4)
chown [options] user[.group] file (BSD)
Common Options
-R recursively descend through the directory structure
32
-f force, and don’t report any errors
Examples
# chown new_owner file
Syntax
chgrp [options] group file
Common Options
-R recursively descend through the directory structure
-f force, and don’t report any errors
Examples
% chgrp
echo command
• echo “Your text goes here” > filename (To add text and create a new file)
• echo “Additional text” >> filename (To append to an existing file)
cp command
• cp existing-file new-filename (To copy an existing file to new file)
• cat existing-file > new-filename (cat the content of an existing file and add to new file. This
command does the same as above)
vi command
• vi filename (Create a new file and enter text using vi insert mode)
Pipes
• A pipe is used by the shell to connect the stdout of one command directly to the stdin of
anothercommand.
• The symbol for a pipe is the vertical bar ( | ). The command syntax is:
• Pipes accomplish with one command what otherwise would take intermediate files and
multiplecommands. For example, operation 1 and operation 2 are equivalent:
33
Operation 1
who > tempsorttemp
Operation 2
who | sort
• Pipes do not affect the contents of the input files.
• Two very common uses of a pipe are with the "more" and "grep" utilities. Some examples:
Syntax
cat [options] [file]
Common Options
-n precede each line with a line number
-v display non-printing characters, except tabs, new-lines, and form-feeds
-e display $ at the end of each line (prior to new-line) (when used with -v option)
Examples
% cat filename
You can list a series of files on the command line, and cat will concatenate them, starting each in turn,
immediately after completing the previous one, e.g.:
% cat file1 file2 file3
Syntax
more [options] [+/pattern] [filename]
less [options] [+/pattern] [filename]
34
p g [options] [+/pattern] [filename]
Options
more less pg Action
-c -c -c clear display before displaying
-i ignore case
-w default default don’t exit at end of input, but prompt and wait
-lines -lines # of lines/screenful
+/pattern +/pattern +/pattern search for the pattern
Internal Controls
35
echo - echo a statement
The echo command is used to repeat, or echo, the argument you give it back to the standard output
device. It normally ends with a line-feed, but you can specify an option to prevent this.
Syntax
echo [string]
Common Options
-n don’t print <new-line> (BSD, shell built-in)
\c don’t print <new-line> (SVR4)
\0n where n is the 8-bit ASCII character code (SVR4)
\t tab (SVR4)
\f form-feed (SVR4)
\n new-line (SVR4)
\v vertical tab (SVR4)
Examples
% echo Hello Class or echo "Hello Class"
To prevent the line feed:
% echo -n Hello Class or echo "Hello Class \c"
where the style to use in the last example depends on the echo command in use.
The \x options must be within pairs of single or double quotes, with or without other string characters.
Syntax
head [options] file
Common Options
-n number number of lines to display, counting from the top of the file
36
-number same as above
Examples
By default head displays the first 10 lines. You can display more with the "-n number", or"-
number" options, e.g., to display the first 40 lines:
% head -40 filename or head -n 40 filename
more
Browses/displays files one screen at a time.
Example:
more sample.f
Syntax
tail [options] file
Common Options
-number number of lines to display, counting from the bottom of the file
Examples
The default is to display the last 10 lines, but you can specify different line or byte numbers, or a
different starting point within the file. To display the last 30 lines of a file use the -number style:
% tail -30 filename
37
Filter / Text Processing Commands
grep
The grep utility is used to search for generalized regular expressions occurring in Linux files. Regular
expressions, such as those shown above, are best specified in apostrophes (or single quotes) when
specified in the grep utility. The egrep utility provides searching capability using an extended set of
meta-characters. The syntax of the grep utility, some of the available options, and a few examples are
shown below.
Syntax
grep [options] regexp [file[s]]
Common Options
-i ignore case
-c report only a count of the number of lines containing matches, not the matches
themselves
-v invert the search, displaying only lines that do not match
-n display the line number along with the line on which a match was found
-s work silently, reporting only the final status:
0, for match(es) found
1, for no matches2, for errors
-l list filenames, but not lines, in which matches were found
Examples
Consider the following file: cat
num.list
1 15 fifteen
2 14 fourteen
3 13 thirteen
4 12 twelve
5 11 eleven
6 10 ten
8 8 eight
9 7 seven
10 6 six
11 5 five
14 2 two
15 1 one
38
Here are some grep examples using this file. In the first we’ll search for the number 15:
> grep '15' num.list1
15 fifteen
15 1 one
Now we’ll use the "-c" option to count the number of lines matching the search criterion:
> grep -c '15' num.list
2
Here we’ll be a little more general in our search, selecting for all lines containing the character 1followed
by either of 1, 2 or 5:
> grep '1[125]' num.list1
15 fifteen
4 12 twelve
5 11 eleven
11 5 five
12 4 four
15 1 one
Now we’ll search for all lines that begin with a space:
> grep '^ ' num.list1
15 fifteen
2 14 fourteen
3 13 thirteen
4 12 twelve
5 11 eleven
6 10 ten
7 9 nine
8 8 eight
9 7 seven
The latter could also be done by using the -v option with the original search string, e.g.:
> grep -v '^ ' num.list
39
10 6 six
11 5 five
12 4 four
13 3 three
14 2 two
15 1 one
Here we search for all lines that begin with the characters 1 through 9:
> grep '^[1-9]' num.list
10 6 six
11 5 five
12 4 four
13 3 three
14 2 two
15 1 one
This example will search for any instances of t followed by zero or more occurrences of e:
> grep 'te*' num.list1
15 fifteen
2 14 fourteen
3 13 thirteen
4 12 twelve
6 10 ten
8 8 eight
13 3 three
14 2 two
This example will search for any instances of t followed by one or more occurrences of e:
> grep 'tee*' num.list1
15 fifteen
2 14 fourteen
3 13 thirteen
6 10 ten
We can also take our input from a program, rather than a file. Here we report on any lines output bythe
who program that begin with the letter l.
> who | grep '^l'
lcondron ttyp0 Dec 1 02:41 (lcondron-pc.acs.)
40
awk, nawk, gawk
awk is a pattern scanning and processing language. Its name comes from the last initials of the three
authors: Alfred. V. Aho, Brian. W. Kernighan, and Peter. J. Weinberger. nawk is new awk, a newer
version of the program, and gawk is gnu awk, from the Free Software Foundation. Each version is a
little different. Here we’ll confine ourselves to simple examples which should be the same for all
versions. On some OSs awk is really nawk.
awk searches its input for patterns and performs the specified operation on each line, or fields of theline,
that contain those patterns. You can specify the pattern matching statements for awk either on
the command line, or by putting them in a file and using the -f program_file option.
Syntax
awk program [file]
where program is composed of one or more:
pattern { action }
fields. Each input line is checked for a pattern match with the indicated action being taken on a match.
This continues through the full sequence of patterns, then the next line of input is checked.
Input is divided into records and fields. The default record separator is <newline>, and the variable NR
keeps the record count. The default field separator is whitespace, spaces and tabs, and the variable NF
keeps the field count. Input field, FS, and record, RS, separators can be set at any time tomatch any
single character. Output field, OFS, and record, ORS, separators can also be changed to any single
character, as desired. $n, where n is an integer, is used to represent the nth field of the input record,
while $0 represents the entire input record.
BEGIN and END are special patterns matching the beginning of input, before the first field is read, and
the end of input, after the last field is read, respectively.
Printing is allowed through the print, and formatted print, printf, statements.
Patterns may be regular expressions, arithmetic relational expressions, string-valued expressions, and
boolean combinations of any of these. For the latter the patterns can be combined with the boolean
operators below, using parentheses to define the combination:
|| or
&& and
! not
Comma separated patterns define the range for which the pattern is applicable, e.g.:
/first/,/last/
41
selects all lines starting with the one containing first, and continuing inclusively, through the one
containing last.
Regular expressions must be enclosed with slashes (/) and meta-characters can be escaped with thebackslash
(\). Regular expressions can be grouped with the operators:
| or, to separate alternatives
+ one or more
? zero or one
So the program:
$1 ~ /[Ff]rank/
is true if the first field, $1, contains "Frank" or "frank" anywhere within the field. To match a field
identical to "Frank" or "frank" use:
$1 ~ /^[Ff]rank$/
Offhand you don’t know if variables are strings or numbers. If neither operand is known to be numeric,
than string comparisons are performed. Otherwise, a numeric comparison is done. In theabsence of any
information to the contrary, a string comparison is done, so that:
$1 > $2
will compare the string values. To ensure a numerical comparison do something similar to:( $1
+ 0 ) > $2
The mathematical functions: exp, log and sqrt are built-in
42
index(s,t) returns the position of string s where t first occurs, or 0 if it doesn’t
length(s) returns the length of string s
substr(s,m,n) returns the n-character substring of s, beginning at position m
Arrays are declared automatically when they are used, e.g.: arr[i] =
$1
assigns the first field of the current input record to the ith element of the array.
Flow control statements using if-else, while, and for are allowed with C type syntax: for
(i=1; i <= NF; i++) {actions
Common Options
-f program_file read the commands from program_file
-Fc use character c as the field separator character
Examples
% cat filex | tr a-z A-Z | awk -F: '{printf ("7R %-6s %-9s %-24s \n",$1,$2,$3)}'>upload.file
43
cut - select parts of a line
The cut command allows a portion of a file to be extracted for another use.
Syntax
Common Options
-c character_list character positions to select (first character is 1)
-d delimiter field delimiter (defaults to <TAB>)
-f field_list fields to select (first field is 1)
Both the character and field lists may contain comma-separated or blank-character-separated numbers
(in increasing order), and may contain a hyphen (-) to indicate a range. Any numbers
missing at either before (e.g. -5) or after (e.g. 5-) the hyphen indicates the full range starting with the first, or
ending with the last character or field, respectively. Blank-character-separated lists must be enclosed in
quotes. The field delimiter should be enclosed in quotes if it has special meaning to the shell, e.g. when
specifying a <space> or <TAB> character.
Examples
In these examples we will use the file users:
If you only wanted the username and the user's real name, the cut command could be used to get onlythat
information:
The cut command can also be used with other options. The -c option allows characters to be theselected
cut. To select the first 4 characters:
44
sort - sort file contents
The sort command is used to order the lines of a file. Various options can be used to choose the order as
well as the field on which a file is sorted. Without any options, the sort compares entire lines in the file and
outputs them in ASCII order (numbers first, upper case letters, then lower case letters).
Syntax
sort [options] [+pos1 [ -pos2 ]] file
Common Options
-b ignore leading blanks (<space> & <tab>) when determining starting andending
characters for the sort key
-d dictionary order, only letters, digits, <space> and <tab> are significant
-f fold upper case to lower case
45
-k keydef sort on the defined keys (not available on all systems)
-i ignore non-printable characters
-n numeric sort
-o outfile output file
-r reverse the sort
-t char use char as the field separator character
-u unique; omit multiple copies of the same line (after the sort)
+pos1 [-pos2] (old style) provides functionality similar to the "-k keydef" option.
For the +/-position entries pos1 is the starting word number, beginning with 0 and pos2 is the ending word
number. When -pos2 is omitted the sort field continues through the end of the line. Both pos1 and pos2 can
be written in the form w.c, where w is the word number and c is the character within the word.For c 0
specifies the delimiter preceding the first character, and 1 is the first character of the word. These entries can
be followed by type modifiers, e.g. n for numeric, b to skip blanks, etc.
where:
start_field, end_field define the keys to restrict the sort to a portion of the line
type modifies the sort, valid modifiers are given the single characters (bdfiMnr) from
the similar sort options, e.g. a type b is equivalent to "-b", but applies
only to the specified field
Examples
In the file users:
jdoe John Doe 4/15/96 lsmith
Laura Smith 3/12/96pchen
Paul Chen 1/5/96 jhsu Jake
Hsu 4/17/96 sphilip Sue
Phillip 4/2/96
sort users yields the following:
jdoe John Doe 4/15/96 jhsu
Jake Hsu 4/17/96 lsmith
Laura Smith 3/12/96pchen
Paul Chen 1/5/96 sphilip Sue
Phillip 4/2/96
If, however, a listing sorted by last name is desired, use the option to specify which field to sort on (fieldsare
numbered starting at 0):
% sort +2 users:
pchen Paul Chen 1/5/96 jdoe
John Doe 4/15/96 jhsu Jake
Hsu 4/17/96 sphilip Sue
Phillip 4/2/96lsmith Laura
Smith 3/12/96
46
jhsu Jake Hsu 4/17/96
jdoe John Doe 4/15/96
A particularly useful sort option is the -u option, which eliminates any duplicate entries in a file whileordering
the file. For example, the file todays.logins:
sphillip
jchen jdoe
lkeres
jmarsch
ageorge
lkeres
proy jchen
shows a listing of each username that logged into the system today. If we want to know how many
unique users logged into the system today, using sort with the -u option will list each user only once.
(The command can then be piped into "wc -l" to get a number):
% sort -u todays.logins
ageorge
jchen jdoe
jmarsch
lkeres
proy
sphillip
Syntax
uniq [options] [+|-n] file [file.new]
Common Options
-d one copy of only the repeated lines
-u select only the lines not repeated
+n ignore the first n characters
-s n same as above (SVR4 only)
-n skip the first n fields, including any blanks (<space> & <tab>)
-f fields same as above (SVR4 only)
Examples
Consider the following file and example, in which uniq removes the 4th line from file and places the
result in a file called file.new.
$ cat file
47
1 2 3 6
4 5 3 6
7 8 9 0
7 8 9 0
$ cat file.new
1 2 3 6
4 5 3 6
7 8 9 0
Below, the -n option of the uniq command is used to skip the first 2 fields in file, and filter out lines
which are duplicates from the 3rd field onward.
$ uniq -2 file1
2 3 6
7 8 9 0
Syntax
tee [options] [file[s]]
Common Options
-a append the output to the files
-i ignore interrupts
Examples
In this first example the output of who is displayed on the screen and stored in the file users.file:
> who | tee users.file
condron ttyp0 Apr 22 14:10 (lcondron-pc.acs.)
frank ttyp1 Apr 22 16:19 (nyssa)
condron ttyp9 Apr 22 15:52 (lcondron-mac.acs)
In this next example the output of who is sent to the files users.a and users.b. It is also piped to thewc
command, which reports the line count.
> who | tee users.a users.b | wc -l
3
> cat users.a
condron ttyp0 Apr 22 14:10 (lcondron-pc.acs.)
frank ttyp1 Apr 22 16:19 (nyssa)
48
condron ttyp0 Apr 22 14:10 (lcondron-pc.acs.)
frank ttyp1 Apr 22 16:19 (nyssa)
condron ttyp9 Apr 22 15:52 (lcondron-mac.acs)
In the following example a long directory listing is sent to the file files.long. It is also piped tothegrep
command which reports which files were last modified in August.
> ls -l | tee files.long |grep Aug
1 drwxr-sr-x 2 condron 512 Aug 8 1995 News/
2 -rw-r--r-- 1 condron 1076 Aug 8 1995 magnus.cshrc
2 -rw-r--r-- 1 condron 1252 Aug 8 1995 magnus.login
> cat
files.lo
ngtotal
34
2 -rw-r--r-- 1 condron 1253 Oct 10 1995 #.login#
1 drwx------ 2 condron 512 Oct 17 1995 Mail/
1 drwxr-sr-x 2 condron 512 Aug 8 1995 News/
5 -rw-r--r-- 1 condron 4299 Apr 21 00:18 editors.txt
2 -rw-r--r-- 1 condron 1076 Aug 8 1995 magnus.cshrc
2 -rw-r--r-- 1 condron 1252 Aug 8 1995 magnus.login
7 -rw-r--r-- 1 condron 6436 Apr 21 23:50 resources.txt
4 -rw-r--r-- 1 condron 3094 Apr 18 18:24 telnet.ftp
1 drwxr-sr-x 2 condron 512 Apr 21 23:56 uc/
1 -rw-r--r-- 1 condron 1002 Apr 22 00:14 uniq.tee.txt
1 -rw-r--r-- 1 condron 1001 Apr 20 15:05 uniq.tee.txt~
7 -rw-r--r-- 1 condron 6194 Apr 15 20:18 Linuxgrep.txt
49
4- system administration
User Account Management:
• useradd
To create a new user in Linux. A different options can be used to modify userId, home
directory etc.
• userdel
This command is used to delete the user. Please note this command alone will not delete
the user home directory. You will have to use option –r to delete user home directory
• groupadd
Creates a new group
• groupdel
Removes an existing group
• usermod
Modify user attributes such as user home directory, user group, user ID etc.
User Files
• /etc/passw = This file has all user’s attributes
d
• /etc/shado = This file contains encrypted user password and
w password policy
• /etc/group = All group and user group information
50
Basic syntax of command is:
useradd [options] username
In this article we will show you the most used 15 useradd commands with their practical examples
in Linux. We have divided the section into two parts from Basic to Advance usage of command.
Part I: Basic usage with 10 examples Part II: Advance usage with 5 examples
To add/create a new user, all you’ve to follow the command ‘useradd‘ or ‘adduser‘ with
‘username’. The ‘username’ is a user login name, that is used by user to login into the system.
Only one user can be added and that username must be unique (different from other username
already exists on the system).
For example, to add a new user called ‘solider‘, use the following command. [root@localhost ~]#
useradd solider
When we add a new user in Linux with ‘useradd‘ command it gets created in locked state and to
unlock that user account, we need to set a password for that account with ‘passwd‘ command.
[root@localhost ~]# passwd solider Changing password for user solider. New LINUX password:
Retype new LINUX password:
passwd: all authentication tokens updated successfully.
Once a new user created, it’s entry automatically added to the ‘/etc/passwd‘ file. The file is used
to store users information and the entry should be.
solider:x:504:504:solider:/home/solider:/bin/bash
51
The above entry contains a set of seven colon-separated fields, each field has it’s own meaning.
Let’s see what are these fields:
Username: User login name used to login into system. It should be between 1 to 32 charcters long.
Password: User password (or x character) stored in /etc/shadow file in encrypted format.
User ID (UID): Every user must have a User ID (UID) User Identification Number. By default UID 0 is
reserved for root user and UID’s ranging from 1-99 are reserved for other predefined accounts.
Further UID’s ranging from 100-999 are reserved for system accounts and groups.
Group ID (GID): The primary Group ID (GID) Group Identification Number stored in /etc/group file.
User Info: This field is optional and allow you to define extra information about the user. For
example, user full name. This field is filled by ‘finger’ command.
Home Directory: The absolute location of user’s home directory. Shell: The absolute location of a
user’s shell i.e. /bin/bash.
By default ‘useradd‘ command creates a user’s home directory under /home directory with
username. Thus, for example, we’ve seen above the default home directory for the user ‘solider‘ is
‘/home/solider‘.
However, this action can be changed by using ‘-d‘ option along with the location of new home
directory (i.e. /home/newusers). For example, the following command will create a user ‘solider‘
with a home directory ‘/home/newusers‘.
You can see the user home directory and other user related information like user id, group id, shell
and comments.
52
3. Create a User with Specific User ID
In Linux, every user has its own UID (Unique Identification Number). By default, whenever we
create a new user accounts in Linux, it assigns userid 500, 501, 502 and so on…
But, we can create user’s with custom userid with ‘-u‘ option. For example, the following
command will create a user ‘navin‘ with custom userid ‘999‘.
NOTE: Make sure the value of a user ID must be unique from any other already created users on
the system.
53
5. Add a User to Multiple Groups
The ‘-G‘ option is used to add a user to additional groups. Each group name is separated by a
comma, with no intervening spaces.
Here in this example, we are adding a user ‘solider‘ into multiple groups like admins, webadmin
and developer.
In some situations, where we don’t want to assign a home directories for a user’s, due to some
security reasons. In such situation, when a user logs into a system that has just restarted, its home
directory will be root. When such user uses su command, its login directory will be the previous
user home directory.
To create user’s without their home directories, ‘-M‘ is used. For example, the following command
will create a user ‘shilpi‘ without a home directory.
54
7. Create a User with Account Expiry Date
By default, when we add user’s with ‘useradd‘ command user account never get expires i.e their
expiry date is set to 0 (means never expired).
However, we can set the expiry date using ‘-e‘ option, that sets date in YYYY-MM-DD format. This
is helpful for creating temporary accounts for a specific period of time.
Here in this example, we create a user ‘aparna‘ with account expiry date i.e. 27th April 2014 in
YYYY- MM-DD format.
[root@localhost ~]# useradd -e 2014-03-27 aparna
Next, verify the age of account and password with ‘chage‘ command for user ‘aparna‘ after setting
account expiry date.
[root@localhost ~]# chage -l aparna
Last password change : Mar 28, 2014
Password expires : never
Password inactive : never
Account expires : Mar 27, 2014
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires :7
8. Create a User with Password Expiry Date
The ‘-f‘ argument is used to define the number of days
after a password expires. A value of 0 inactive the user
account as soon as the password has expired. By
default, the password expiry value set to -1 means
never expire.
Here in this example, we will set a account password
expiry date i.e. 45 days on a user ‘solider’ using ‘-e‘ and
‘-f‘ options.
55
[root@localhost ~]# useradd -e 2014-04-27 -f 45
solider
56
[root@localhost ~]# tail -1 /etc/passwd
solider:x:1002:1002::/home/solider:/sbin/nologin
57
[root@localhost ~]# useradd -m -d
/var/www/tarunika -s /bin/zsh -c "Solider Technical
Writer" -u 1000 -g 1000 tarunika
58
Switch Users and Sudo Access:
Switch Users:
Following is the user switch command that can be used to switch from one user to another
• su - username
su - invokes a login shell after switching the user. A login shell resets most environment variables,
providing a clean base.
• su username
just switches the user, providing a normal shell with an environment nearly the same as with the
old user
Sudo Access:
• sudo command-name
The above command “sudo command-name” will run any command owned and authorized by
root account as long as that user is authorized to run it in /etc/sudoers file
# useradd USERNAME
3. Set a password for the new user using the passwd command.
4. # passwd USERNAME
59
5. Changing password for user USERNAME.
6. New password:
7. Retype new password:
passwd: all authentication tokens updated successfully.
8. Run the visudo to edit the /etc/sudoers file. This file defines the policies applied by the
sudo command.
# visudo
9. Find the lines in the file that grant sudo access to users in the group wheel when
enabled.
10. ## Allows people in group wheel to run all commands # %wheel ALL=(ALL) ALL
11. Remove the comment character (#) at the start of the second line. This enables the
configuration option.
12. Save your changes and exit the editor.
13. Add the user you created to the wheel group using the usermod command.
# usermod -aG wheel USERNAME
14. Test that the updated configuration allows the user you created to run commands using
sudo.
1. Use the su to switch to the new user account that you created.
# su USERNAME -
2. Use the groups to verify that the user is in the wheel group.
3. $ groups
USERNAME wheel
4. Use the sudo command to run the whoami command. As this is the first time you
have run a command using sudo from this user account the banner message will
be displayed. You will be also be prompted to enter the password for the user
60
account.
5. $ sudo whoami
6. We trust you have received the usual lecture from the local System
7. Administrator. It usually boils down to these three things: 8.
9. #1) Respect the privacy of others.
10. #2) Think before you type.
11. #3) With great power comes great responsibility. 12.
13. [sudo] password for USERNAME: root
The last line of the output is the user name returned by the whoami command. If
sudo is configured correctly this value will be root.
You have successfully configured a user with sudo access. You can now log in to this user account
and use sudo to run commands as if you were logged in to the account of the root user.
• who
• last
• w
• id
who
As a Linux user, sometimes it is required to know some basic information like :
Though this type of information can be obtained from various files in the Linux system but there is
a command line utility 'who' that does exactly the same for you. In this article, we will discuss the
capabilities and features provided by the 'who' command.
61
The basic syntax of the who command is :
This is done by simply running the 'who' command (without any options). Consider the following
example:
$ who
iafzal tty7 2012-08-07 05:33 (:0)
iafzal pts/0
2012-08-07 06:47 (:0.0)
iafzal pts/1
$ who -b
system boot 2012-08-07 05:32
The is done using the -b option. Consider the following example:
So we see that the above output gives the exact date and time of last system boot.
62
3. Get information on system login processes
$ who -r
run-level 2 2012-08-07 05:32
This is done using the -r option. Consider the following example:
So we see that the information related to current run level (which is 2) was produced in the
output.
63
6. Get the list of user logged in
$ who -q
iafzal iafzal iafzal
# users=3
This is done using the -q option. Consider the following example:
So we see that information related to number of logged-in users and their user names was
produced in the output.
64
LOGIN tty4 2012-08-07 05:32 1309 id=4
LOGIN tty5 2012-08-07 05:32 1313 id=5
LOGIN tty2 2012-08-07 05:32 1322 id=2
LOGIN tty3 2012-08-07 05:32 1324 id=3
LOGIN tty6 2012-08-07 05:32 1327 id=6
LOGIN tty1 2012-08-07 05:32 1492 id=1
iafzal + tty7 2012-08-07 05:33 old 1619 (:0)
iafzal + pts/0 2012-08-07 06:47 . 2336 (:0.0)
iafzal + pts/1 2012-08-07 07:58 . 2336 (:0.0)
So we see that all the information that 'who' can print is produced in output.
65
last command:
To find out when a particular user last logged in to the Linux or Unix server.
Syntax
last
last [userNameHere] last [tty]
last [options] [userNameHere]
If no options provided last command displays a list of all users logged in (and out). You can filter
out results by supplying names of users or terminal to show only those entries matching the
username/tty.
To find out who has recently logged in and out on your server, type:
$ last
Sample outputs:
66
root pts/0 10.1.6.120 Tue Jan 7 12:02 - 12:38 (00:35)
last command searches back through the file /var/log/wtmp file and the output may go back to
several months. Just use the less command or more command as follows to display output one
screen at a time:
$ last | more last | less
Sample outputs:
67
68
Hide hostnames (Linux only)
To hide the display of the hostname field pass -R option:
$ last -R
last -R iafzal
Sample outputs:
By default year is now displayed by last command. You can force last command to display full login
and logout times and dates by passing -F option:
$ last -F
Sample outputs:
69
70
Display full user/domain names
$ last -w
The user reboot logs in each time the system is rebooted. Thus following command will show a log
of all reboots since the log file was created:
$ last reboot
$ last -x reboot
Find out the system shutdown entries and run level changes:
$ last -x
$ last -x shutdown
The syntax is as follows to see the state of logins as of the specified time:
$ last -t YYYYMMDDHHMMSS
$ last -t YYYYMMDDHHMMSS userNameHere
71
w command:
Options:
-h, --no-header do not print header
-u, --no-current ignore current process username
-s, --short short format
-f, --from show remote hostname field
-o, --old-style old style output
-i, --ip-addr display IP address instead of hostname (if possible)
id command:
Print user and group information for the specified USER, or (when USER omitted) for the current
user.
-a ignore, for compatibility with other versions
-Z, --context print only the security context of the current user
-g, --group print only the effective group ID
-G, --groups print all group IDs
-n, --name print a name instead of a number, for -ugG
-r, --real print the real ID instead of the effective ID, with -ugG
-u, --user print only the effective user ID
72
-z, --zero delimit entries with NUL characters, not whitespace; not permitted in default
format
--help display this help and exit
--version output version information and exit
• date
• uptime
• hostname
• uname
• which
• cal
• bc
date
Print or set the system date and time
Mandatory arguments to long options are mandatory for short options too.
-d, --date=STRING display time described by STRING, not 'now'
-f, --file=DATEFILE like --date once for each line of DATEFILE
-I[TIMESPEC], --iso-8601[=TIMESPEC] output date/time in ISO 8601 format.
TIMESPEC='date' for date only (the default), 'hours', 'minutes', 'seconds', or 'ns' for date and
time to the indicated precision.
-r, --reference=FILE display the last modification time of FILE
-R, --rfc-2822 output date and time in RFC 2822 format.
Example: Mon, 07 Aug 2006 12:34:56 -0600
73
--rfc-3339=TIMESPEC output date and time in RFC 3339 format.
TIMESPEC='date', 'seconds', or 'ns' for date and time to the indicated precision. Date and time
components are separated by a single space: 2006-08-07 12:34:56-06:00
-s, --set=STRING set time described by STRING
-u, --utc, --universal print or set Coordinated Universal Time (UTC)
--help display this help and exit
--version output version information and exit
uptime:
Tell how long the system has been running
uptime gives a one line display of the following information. The current time, how long the
system has been running, how many users are currently logged on, and the system load averages
for the past 1, 5, and 15 minutes
Options:
-p, --pretty show uptime in pretty format
-h, --help display this help and exit
-s, --since system up since
-V, --version output version information and exit
hostname
Show or set the system's host name
Program options:
-a, --alias alias names
-A, --all-fqdns all long host names (FQDNs)
-b, --boot set default hostname if none available
74
-d, --domain DNS domain name
-f, --fqdn, --long long host name (FQDN)
-F, --file read host name or NIS domain name from given file
-i, --ip-address addresses for the host name
-I, --all-ip-addresses all addresses for the host
-s, --short short host name
-y, --yp, --nis NIS/YP domain name
Description:
This command can get or set the host name or the NIS domain name. You can also get the DNS
domain or the FQDN (fully qualified domain name).
Unless you are using bind or NIS for host lookups you can change the FQDN (Fully Qualified
Domain Name) and the DNS domain name (which is part of the FQDN) in the /etc/hosts file
uname
This command will give you system information. It is one of the important command that should
be used every time you login to a Linux/Unix machine.
-a, --all print all information, in the following order, except omit -p and -i if unknown:
-s, --kernel-name print the kernel name
-n, --nodename print the network node hostname
-r, --kernel-release print the kernel release
-v, --kernel-version print the kernel version
75
-m, --machine print the machine hardware name
-p, --processor print the processor type or "unknown"
-i, --hardware-platform print the hardware platform or "unknown"
-o, --operating-system print the operating system
--help display this help and exit
--version output version information and exit
76
which
Shows the full path of (shell) commands
cal and bc
cal command is simply for calendar and bc is for calculator
77
Processes
•Whenever you enter a command at the shell prompt, it invokes a program. While this
program is running it is called a process. Your login shell is also a process, created for you
upon logging in and existing until you logout.
• LINUX is a multi-tasking operating system. Any user can have multiple processes running
simultaneously, including multiple login sessions. As you do your work within the login
shell, each command creates at least one new process while it executes.
• Process id: every process in a LINUX system has a unique PID - process identifier.
• ps - displays information about processes. Note that the ps command differs between
different LINUX systems - see the local ps man page for details.
To see your current shell's processes:
% ps
PID TTY TIME CMD
26450 pts/9 0:00 ps
66801 pts/9 0:00 -csh
To see a detailed list of all of your processes on a machine (current shell and all other shells):
% ps uc
USER PID %CPU %MEM SZ RSS TTY STAT STIME TIME COMMA
ND
jsmith 26451 0.0 0.0 120 232 pts/9 R 21:01:14 0:00 ps
jsmith 43520 0.0 1.0 300 660 pts/76 S 19:18:31 0:00 elm
jsmith 66801 0.0 1.0 348 640 pts/9 S 20:49:20 0:00 csh
jsmith 112453 0.0 0.0 340 432 pts/76 S Mar 03 0:00 csh
78
% ps ug
USER PID %CP %ME SZ RSS TTY STAT STIME TIME COMMAND
U M
root 0 0.0 0.0 8 8 - S Feb 08 32:57 swapper
root 1 0.1 0.0 252 188 - S Feb 08 39:16 /etc/init
root 514 72.6 0.0 12 8 - R Feb 08 28984:05 kproc
root 771 0.2 0.0 16 16 - S Feb 08 65:14 kproc
root 1028 0.0 0.0 16 16 - S Feb 08 0:00 kproc
{ lines deleted }
root 60010 0.0 0.0 1296 536 - S Mar 07 0:00 -ncd19:0
kdr 60647 0.0 0.0 288 392 pts/87 S Mar 06 0:00 -ksh
manfield 60968 0.0 0.0 268 200 - S 10:12:52 0:00 mwm
kelly 61334 0.0 0.0 424 640 - S 08:18:10 0:00 twm
sjw 61925 0.0 0.0 552 376 - S Mar 06 0:00 rlogin kanaha
mkm 62357 0.0 0.0 460 240 - S Feb 08 0:00 xterm
ishley 62637 0.0 0.0 324 152 pts/106 S Mar 06 0:00 xedit march2
tusciora 62998 0.0 0.0 340 448 - S Mar 06 0:05 xterm -e
dilfeath 63564 0.0 0.0 200 268 - S 07:32:45 0:00 xclock
tusciora 63878 0.0 0.0 548 412 - S Mar 06 0:41 twm
• kill - use the kill command to send a signal to a process. In most cases, this will be a kill
signal, hence the command name. However, other types of signals are usually supported.
Note that you can only kill processes which you own. The command syntax is:
79
kill [-signal] process_identifier(PID)
Examples:
You can also use CTRL-C to kill the currently running process.
myprog &
To put an already running job in the background, first suspend it with CRTL-Z and then use the
"bg" command:
• Foreground a process: To move a background job to the foreground, find its "job" number
and then use the "fg" command. In this example, the jobs command shows that two
processes are running in the background. The fg command is used to bring the second job
(%2) to the foreground.
80
jobs
[1] + Running xcalc
[2] Running find / -name core -print
fg %2
• Stop a job running in the background: Use the jobs command to find its job number, and
then use the stop command. You can then bring it to the foreground or restart execution
later.
jobs
[1] + Running xcalc
[2] Running find / -name core -print
stop %2
• Kill a job running in the background, use the jobs command to find its job number,
and then use the kill command. Note that you can also use the ps and kill commands
to accomplish the same task.
jobs
[1] + Running xcalc
[2] Running find / -name core -print
kill %2
81
System Resources Commands:
Syntax
df [options] [resource]
Common Options
-l local file systems only (SVR4)
-k report in kilobytes (SVR4)
82
du - report disk space in use
du reports the amount of disk space in use for the files or directories you specify.
Syntax
du [options] [directory or file]
Common Options
-a display disk usage for each file, not just subdirectories
-s display a summary total only
-k report in kilobytes (SVR4)
Syntax
who [am i]
Examples
> who
wmtell ttyp1 Apr 21 20:15 (apple.acs.ohio-s)
fbwalk ttyp2 Apr 21 23:21 (worf.acs.ohio-st)
stwang ttyp3 Apr 21 23:22 (127.99.25.8)
83
whereis - report program locations
whereis reports the filenames of source, binary, and manual page files associated with
command(s).
Syntax
whereis [options] command(s)
Common Options
-b report binary files only
-m report manual sections only
-s report source files only
Examples
> whereis Mail
Mail: /usr/ucb/Mail /usr/lib/Mail.help /usr/lib/Mail.rc /usr/man/man1/Mail.1
> whereis -b Mail
Mail: /usr/ucb/Mail /usr/lib/Mail.help /usr/lib/Mail.rc
> whereis -m Mail
Mail: /usr/man/man1/Mail.1
Syntax
which command(s)
example--
> which Mail
/usr/ucb/Mail
84
hostname/uname –n = name of machine
hostname (uname -n on SysV) reports the host name of the machine the user is logged into,
e.g.:
> hostname yourcomputername
uname has additional options to print information about system hardware type and software
version.
Syntax
date [options] [+format]
Common Options
-u use Universal Time (or Greenwich Mean Time)
+format specify the output format
%a weekday abbreviation, Sun to Sat
%h month abbreviation, Jan to Dec
%j day of year, 001 to 366
%n <new-line>
%t <TAB>
%y last 2 digits of year, 00 to 99
%D MM/DD/YY date
85
%H hour, 00 to 23
%M minute, 00 to 59
%S second, 00 to 59
%T HH:MM:SS time
Examples
> date
Mon Jun 10 09:01:05 EDT 1996
> date -u
Mon Jun 10 13:01:33 GMT 1996
> date +%a%t%D Mon 06/10/96
> date '+%y:%j' 96:162
86
87
3 – Go to the line = ro and change it with rw init=/sysroot/bin/sh
88
8 - Reboot your system
reboot
89
GOOD LUCK