Vous êtes sur la page 1sur 152

EMPOWERING SYSTEM ADMINISTRATORS

RHCSA-1

OS

UNIX
It is a complete operating System.
It comes with all the programs such as editor, compilers
etc.,
It Comes with Various file systems such as AIX, HP
UX,Solaris.
It was designed as a multiuser operating system.
Other wellknown operating systems included Windows,
Macintosh System 7, and MSDOS.

UNIX Operating System Names:


HP-UX
IBM AIX
SUN SOLARIS
MAC OS X
IRIX

MINIX (from "mini-Unix"):


Its a POSIX compliant, Unixlike computer operating
system based on a microkernel architecture.
NOTE: (Portable Operating System Interface, is a family of
standards specified by the IEEE Computer Society for
maintaining compatibility between operating systems)
Starting with MINIX 3, the primary aim of development
shifted from education to the creation of a highly
reliable and selfhealing microkernel OS.
MINIX is now developed as opensource software.
GNU/Linux:
The GNU system along with Unix or Linux as its kernel make
a complete operating system.

LINUX
Its not a operating system.
Its a free clone of the UNIX kernel, and like GNU
tools has succeeded beyond all expectations.
The kernel (from german kern,means core) is the main
component of most computer operating systems; its a
bridge between application software to the hardware of
a computer.
There are also free Unix variants as well, but they are
less likely to use GNU tools because of the
philosophical differences in code sharing and
licensing.
All linux distribution include installation and
management tools,gnu Utilities Such as cp, mv , ls and
gnu editors.

Linux Distribution Names:


Debian
Ubuntu
Slackware Linux
Suse
Redhat Enterprise
Fedora
CentOS

LINUX DISTROS

LINUX vs WINDOWS
S.No.

LINUX OS

WINDOWS OS

1.

Linux is open Source Os.

Windows is not open Source Os.

2.

Linux Os is freely available.

Windows Os is expensive.

3.

All flavors of Linux come from different


companies like Red Hat, Debian ,
Slackware , etc.,

All flavors of windows come from


Microsoft.

4.

Linux can boot from primary partition


or logical partition inside an extended
partition.

Windows must boot from the first hard


disk and must boot from a primary
partition.

5.

Linux is multiuser system.

Windows is single user system.

6.

Super user is root (/).

Super user is Administrator.

7.

Linux files names are case sensitive.

Windows files names are not case


sensitive.

8.

Linux uses ext2,ext3,ext4 and xfs file


systems.

Windows Uses FAT12,FAT16,FAT32 and


NTFS file Systems.

BOOTING
Booting is a process or set of operations that loads and
hence starts the operating system, starting from the
point when user switches on the power button.

BIOS
BIOS stands for Basic Input/Output System
Performs some system integrity checks (POSTPower On
Self Test)
Searches, loads, and executes the boot loader
program.
It looks for boot loader in floppy, cdrom, or hard
drive. You can press a key (typically F12 of F2, but
it depends on your system) during the BIOS startup
to change the boot sequence.
Once the boot loader program is detected and loaded
into the memory, BIOS gives the control to it.
So, in simple terms BIOS loads and executes the MBR
boot loader.

MBR
MBR stands for Master Boot Record.
It is located in the 1st sector of the bootable disk.
Typically /dev/hda, or /dev/sda
MBR is less than 512 bytes in size. This has three
components:

primary boot loader info in 1st 446 bytes,


partition table info in next 64 bytes(16,16,16,16) 4
partitions,
magic numbers as mbr validation check in last 2 bytes.

It contains information about GRUB (or LILO in old systems).


So, in simple terms MBR loads and executes the GRUB boot
loader.
* Note: A boot loader is the first software program that runs
when a computer starts. It is responsible for loading and
transferring control to the operating system kernel software
(such as the Hurd or Linux). The kernel, in turn, initializes
the rest of the operating system (e.g. GNU).

GRUB
GRUB stands for Grand Unified Bootloader.
It is a Multiboot boot loader.
If you have multiple kernel images installed on your
system, you can choose which one to be executed.
GRUB displays a splash screen, waits for few seconds,
if you dont enter anything, it loads the default
kernel image as specified in the grub configuration
file.
GRUB has the knowledge of the filesystem (the older
Linux loader LILO didnt understand filesystem).
Grub configuration file is /boot/grub/grub.conf
(/etc/grub.conf is a link to this).
The following is sample grub.conf of Linux.
As you notice from the above info, it contains kernel
and initrd image.
So, in simple terms GRUB just loads and executes Kernel
and initrd images.

KERNEL
Once

the control is given to kernel which is the central


part of all your OS and act as a mediator between
hardware and software.

Kernel once loaded into to RAM it always resides on RAM


until the machine is shutdown.
Once the Kernel starts its operations the first thing it
do is executing INIT process.

INIT
(initialization)
Looks at the /etc/inittab file to decide the Linux run
level.
Following are the available run levels

0
1
2
3
4
5

halt
Single user mode
Multiuser, without NFS
Full multiuser mode
unused
X11

6 reboot

Init identifies the default initlevel from /etc/inittab


and uses that to load all appropriate program.
Execute grep initdefault /etc/inittab on your system
to identify the default run level
If you want to get into trouble, you can set the
default run level to 0 or 6. Since you know what 0 and
6 means, probably you might not do that.
Typically you would set the default run level to either
3 or 5.

RUN LEVELS
When the
services
sendmail
from the

Linux system is booting up, you might see various


getting started. For example, it might say starting
. OK. Those are the runlevel programs, executed
run level directory as defined by your run level.

Depending on your default init level setting, the system will


execute the programs from one of the following directories.

Run
Run
Run
Run
Run
Run
Run

level
level
level
level
level
level
level

0
1
2
3
4
5
6

/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/

Please note that there are also symbolic links available


for these directory under /etc directly. So, /etc/rc0.d
is linked to /etc/rc.d/rc0.d.
Under the /etc/rc.d/rc*.d/ directories, you would see
programs that start with S and K.
Programs starts with S are used during startup. S for
startup.
Programs starts with K are used during shutdown. K for
kill.
There are numbers right next to S and K in the program
names. Those are the sequence number in which the
programs should be started or killed.
For example, S12syslog is to start the syslog deamon,
which has the sequence number of 12. S80sendmail is to
start the sendmail daemon, which has the sequence number
of 80. So, syslog program will be started before
sendmail.

LINUX HIERARCHY

pwd command :
It is used to display the present (or) current working directory.
Syntax:
#pwd
Example:
# pwd
/root
date command :
date command is used to print the system date and time.
Syntax:
# date
Example:
#date
#date s yyyymmdd hh:mm:ss

= To set date and time

cal command :
cal command is used to print the calendar of the current month.
Syntax:
# cal
Example:
#cal
# cal 3
#cal 2015
cd command:
The following command is used to change from one directory to
another directory.
Syntax:
#cd <directory name>
Example:
#cd .. To a directory one level up (parent directory)
#cd switch to previous working directory
#cd / To the / (slash) directory
#cd /root To switch to root directory

Absolute path:

A complete and full path of a file or folder is called absolute path.


A file or folder which begins with under / is called as absolute path.
Example:

# cd /test/team
Relative path:
A file or folder which starts without under / is called as relative path.
A shortcut path of file is called relative path.
Example:
# cd ../team

ls command:
It is used to list the files & folders in a present working directory.
Syntax:
ls <option> [argument]
Options:
l
a
d
h
R
i
t
Z
Example:
#ls l /root
#ls ldZ /home

long listing (properties)


hidden files & normal files
folder properties
human readable format
recursive in tree structure
Inode number
sort by time format.
display security context of the files

mkdir command :
It is used to create a directory.
Syntax:
mkdir <option> directory name
Options:
p parents (To create multiple directories)
Example:
#mkdir /data /data1
#mkdir p /soft/dvd/os
cat command:
It is use to create a file and view the content in the file.
Syntax:
#cat <file name>
Example1:
# cat > test = To create the file CTL+d to save the file
# cat test
= following command to view the file content
#cat >> test = The following command is used to append a text to
the file.

touch command:
It is used to update the time stamps of a file and create an empty file.
Syntax:
,

#touch [filename]
Example:
cp command:

# touch /test /hp /ibm linux solaris = To create multiple file on


single line command
It is used to copy the file or directory (by using Absolute or Relative
path)

Syntax:
#cp <option> [source] [destination]

Options:
a
p
v
r
f

archive ( It will not modify the time and date)


preserve ( It will not modify file permission)
verbose (explain what is being done)
recursive (To copy all folder)
force (Force to copy)

Example:
#cp rvf /root/data /soft/ = copy command with multiple options

mv command:
The following command is used to move and rename the files and
directories.
Syntax:
#mv <source> <destination>

Example:
# mv
rm command:

Syntax:
Options:

Example:

/root/songs /opt/

# mv /songs /mp3songs

= To move one location to another


location
= To rename the directory or file

The following command is used to remove files.


rm <filename>
i
r
v

interactive (prompt before removal)


recursive (remove directory and their
contents recursively)
verbose (explain what is being done)

#rm rvf /root/data.txt

whatis command:
It searches the short manual page descriptions in the whatis database
for each keyword & and print a oneline description to standard output for each match.
Syntax:
Example:
info command:
Syntax:
Example:
man command:

#whatis <keyword>
# whatis mv
It is used to provide the full information about the command.
#info <option> command
#info mkdir

It is used to view online manual pages of any command. Almost every


command has a man page.
Syntax:
Example:

#man <option> command


# man cp

history Command:
It is used d to view list of used commands.
Syntax:
#history [options]
Options :

= clear (Clear the history)

Example:
#history
#history c
Echo:
It is used to display the set of characters in the terminal
window. And it is widely used in scripting language in linux.
Syntax:
Example:

echo arguments
#echo my company name is sysadmin
#echo $HOSTNAME
#echo $SHELL
#echo $HOME

head command:
It is used to view first ten line of the file content.
Syntax:
#head [options] <arguments>
Options :
Example:

<value>
#head /etc/passwd
#head 5 /etc/passwd

tail command:
It is used to view last ten line of the file content.
Syntax:
#tail [options] <arguments>
Options :
Example:

<value>
#tail /etc/passwd
#tail 5 /etc/passwd

sort command:
It is used d to view the file content in ascending and
descending order.
Syntax:

#sort [options] <arguments>

Options :
f
r
Example:

( ascending order )
( descending order )

#sort f /etc/passwd
#sort r /etc/passwd

less command:
It is used d to view the file one page at a time.
Syntax:
#less <argument>
Example:

#less /etc/passwd

more command:
It is used d to view the big file little by little.
Syntax:
#more <argument>
Example:
cut command:
Syntax:

#more /etc/passwd
it is used to get particular field, column or character.
#cut [options] <arguments>

Example:

#cut d : f1 /etc/passwd [option is delimiter (i.e) separated by : ]


#cut c 26 file.txt [ Character 2 to 6 only display ]
nautilus command:
It is used to view the files & folders in a graphical browser.
Syntax:
nautilus [directory name]
Example:
# nautilus /mnt/

rsync command:
It is used to synchronize faster, flexible replacement for rcp.
Syntax:
rsync [src HOST] [des HOST]
Example:
rsync test tom@172.24.0.254:/home/tom
scp command:
It is used to copies the files between hosts on a network. It use for data transfer
& uses the same authentication & provides the same security as SSH.
Syntax:
scp <options> host1 host2
Example:
scp r data tom@172.24.0.254:/home/tom

GREP
GrepstandsforGlobalsearchforRegularExpressionsandPrint.
Mostofususegrepjustforfindingthewordsinafile.
Thepowerofgrepcomeswithusingitsoptionsandregular
expressions.
Youcananalyzelargesetsoflogfileswiththehelpofgrep
command.
Syntax:
grep[options]pattern[listoffiles]
Examples:
!grep
grep"Error"logfile.txt
grepi "UNix"file.txt
grep"^[09].*"file.txt
grepv"^$"file.txt

Runningthelastexecutedgrepcommand
Searchforastringinafile
Caseinsensitivesearch
Specifyingthesearchstringasa
regularexpressionpattern.
Displayingthenonemptylines

FIND
FindisoneofthepowerfulutilityofUnix(orLinux)used
forsearchingthefilesinadirectoryhierarchy.
Syntax:
find[conditions][pathnames]
Examples:
!find
(lastexecutedfindcommand)
findname"sum.java
(fileusingname)
findiname "sum.java
(usingnameandignoringcase)
find/etcname"*java*
(filesinaspecificdirectory)
findmindepth 2maxdepth 5namesum.java
(filesinthesubdirectoriesbetweenlevel1&4)
find.types(or)d(or)f (Findingsocketfiles(or)dir(or)files)
findtypedname".*
(Findinghiddendirectories)
find.typefname".*
(Findinghiddenfiles)
find.perm777
(filesbasedonthefilepermissions)
find.size1M(or)+1M(or)1M(filessizeisexactly1M/large/small)
find.typed(or)femptydelete(removeemptydir(or)files)
find.mmin 30
(modified30minutesback)
find.mtime 1
(modified1dayback)

Vi & Vim

This "vi" tutorial is intended for those who wish to master and advance their skills beyond the
basic features of the basic editor. It covers buffers, "vi" command line instructions, interfacing
with UNIX commands, and ctags. The vim editor is an enhanced version of vi. The
improvements are clearly noticed in the handling of tags.
The advantage of learning vi and learning it well is that one will find vi on all Unix based
systems and it does not consume an inordinate amount of system resources. Vi works great over
slow network ppp modem connections and on systems of limited resources. One can completely
utilize vi without departing a single finger from the keyboard. (No hand to mouse and return to
keyboard latency)
NOTE: Microsoft PC Notepad users who do not wish to use "vi" should use "gedit" (GNOME
edit) or "gnp" (GNOME Note Pad) on Linux. This is very similar in operation to the Microsoft
Windows editor, "Notepad". (Other Unix systems GUI editors: "dtpad", which can be found in
/usr/dt/bin/dtpad for AIX, vuepad on HP/UX, or xedit on all Unix systems.)

Start
Vi or
Vim

Command
Mode

Enter Insert
Mode

:w
q!

Esc

Back to
command mode

Insert mode

Press
a,I,o,Ins

There are three types of mode

Insert Mode
Command Mode
Execute Mode

Insert mode - inserting/appending text

Cut, Paste and delete

i - insert before the cursor


I - insert at the beginning of the line
a - insert (append) after the cursor
A - insert (append) at the end of the line
o - append (open) a new line below the
current line
O - append (open) a new line above the
current line
ea - insert (append) at the end of the word
Esc - exit insert mode

yy - yank (copy) a line


2yy - yank (copy) 2 lines
yw - yank (copy) word
y$ - yank (copy) to end of line
p - put (paste) the clipboard after cursor
P - put (paste) before cursor
dd - delete (cut) a line
2dd - delete (cut) 2 lines
dw - delete (cut) word
D - delete (cut) to the end of the line
d$ - delete (cut) to the end of the line
x - delete (cut) character

Parameters

:set list Show invisible characters


:set nolist Dont show invisible characters
:set number Show line numbers
:set nonumber Dont show line numbers
:set autoindent Indent after carriage return
:set noautoindent Turn off autoindent
:set showmatch Show matching sets of parentheses as
they are typed
:set noshowmatch Turn off showmatch
:set showmode Display mode on last line of screen
:set noshowmode Turn off showmode
:set all Show values of all possible parameters

Search and replace


/pattern - search for pattern
?pattern - search backward for pattern
n - repeat search in same direction
N - repeat search in opposite direction
:%s/old/new/g - replace all old with new throughout file
:%s/old/new/gc - replace all old with new throughout file with confirmations
Exiting
:w - write (save) the file, but don't exit
:wq or :x or ZZ - write (save) and quit
:q - quit (fails if there are unsaved changes)
:q! or ZQ - quit and throw away unsaved changes

User & Group


Management

Files and Directories for user

Password File Format

User Management

Password Aging

Group Administration

Switching Accounts

Sudo

GUI Tool for user management

Files&Directories
foruser
1. Basic files for user & groups
/etc/shadow

Secure user account information

/etc/passwd

User account information

/etc/gshadow

Contains the shadowed information for group accounts

/etc/group
/etc/sudoers

Define the groups to which user belong


List of who can run what by sudo

2. User Environment Files and Directory


/etc/skel

files and directories automatically copied over to newuser'shomedirectory

/etc/default/useradd useradd defaults file


/etc/login.defs

define the sitespecific configuration for the shadowpasswordsuite.

/etc/profile

controls systemwide defaultvariablessuch as export variables. File creation mask(umask).


Terminal types, Mail messages

~/.bash_profile

execute to configure your shell before the initial command prompt.

/etc/bashrc

interactive nonlogin shell started at the commandline using a shell program such as
/bin/bash or /bin/sh. Executed by ~/.bashrc

PasswordfileFormat
1.

Passwd File Format ( /etc/passwd )


sami:x:501:501::/home/sami:/bin/bash

username

password

uid gid Description Home directory Login shell

Password,X=referenceto/etc/shadow,empty=nopassword,*or!=nologinpossible

2.

Shadow File Format ( /etc/shadow )


sami:$6$i7.SAQK2$U9dSrT4E9tEoLEBfS:16729:0:99999:7:::

1.
2.
3.
4.
5.
6.
7.
8.
9.

Username:yourloginname
Password:encryptedpassword.$1$standsforMD5,$2a$isBlowfish,$5$isSHA256 and$6$ isSHA512.
Lastpasswordchange:Whenwasthepasswordlastchanged.
Minimum:Theminimumnumberofdaysrequiredbetweenpasswordchangei.ethenumberofdaysleftbefore
theuserisallowedtochangehis/herpassword.
Maximum:Themaximumnumberofdaysthepasswordisvalid(afterthatuserisforcedtochangehis/her
password)
Warn:numberofdaysbeforepasswordisexpirethatuseriswarnedthatpasswordmustbechanged
Inactive:Thenumberofdaysafterpasswordexpirethataccountisdisabled
Expire:Whenwasthataccountisdisabled.i.eanabsolutespecifyingwhentheloginmaynolongerbeused.
Specialflag:Thisfieldisreservedforfurtheruse.

UserManagement
1. Useradd
addnewuser
a.Addingnewuser
#useradd user1
b.Listdefaultsetting
#useradd D
#useradd D s /bin/sh
//changedefaultshell
c.Supplementarygroups
#useradd G mail user2
d.HomeDirectory
#useradd d /home/samihome user3
e.Changeskeldirectory
#useradd m k /etc/skel2 user4
f.Specificshell
#useradd s /bin/sh user5
///etc/shells
g.Specificuid
#useradd u 550 user6
h.Accountexpire
#useradd e 2015/10/30 user7

2.Usermod
modifyusersdata
a.Shellanddirectorychange
#usermod s /bin/csh d /home/samihome m tom
b.Loginnamechange
#usermod l nathan (new) tom(old)
c.Lockandunlockuser
#usermod L tom
//lock
#usermod U tom
//unlock
d.NewUID
#usermod u 510 tom
e.Expiredate
#usermod e 2015/11/30 tom
#usermod e tom
//removeexpiredate
3.Userdel
deleteuser
a.Deleteuserandleavinghomedirectory
#userdel tom
h.Deleteuserwithhomedirectory
#userdel r tom

4. Pwconv & pwunconv : combine or separate /etc/passwd and /etc/shadow


#pwconv
#grep root /etc/shadow
#pwunconv
#grep root /etc/shadow ; grep root /etc/passwd
#ls -l /etc/passwd /etc/shadow
5. Creating password for user
a. Passwd
#passwd tom
#passwd -S tom
// To check the passwd status of user account
6. Password lock and unlock for user
#passwd -l tom
#passwd -u tom
7. Login without password - empty field
#grep tom/etc/shadow
tom::16729:0:99999:7:::

8. Blocking login by emergent situation


#vi /etc/nologin
Under system checking currently
Please login again after 20:00!!!
9. Listing user information
#finger l tom
10. How to monitor user
a. Monitor file
/var/run/utmp : keeps track of the current login state of each user.
/var/log/wtmp : records all login and logouts history.
/var/log/btmp : records failed login attempts.
b. Monitoring command
Show who is logged on and what they are doing.
#whoami
Reports the most recent login of all users or of a given user from /var/log/lastlog
#lastlog
Contains all the bad or failed login attempts.
#lastb
Show who is logged on
#who

PASSWORD AGING

1. By defaults passwords do not expire


2. Forcing passwords to expire is part of a strong security policy
3. Modify default expiration setting in /etc/login.defs
PASS_MAX_DAYS
99999
PASS_MIN_DAYS
0
PASS_MIN_LEN
5
PASS_WARN_AGE
7
4. Chage
- to modify password aging
a. Chage
[-m mindays] [-M maxdays] [-d lastday] [-I inactive] [-E expiredate] [-W warndays] user
b. List users current setting
#chage l tom

c. Set Password Expire Date for an user chage option M


#chage M 10 tom
d. Password Expire Warning message during login
#chage W 5 tom
e. Set the Account Expire Date for an User
#chage E 2015-11-30 tom
f. Force the user account to be locked after X number of inactivity days
#chage I 10 tom
g. How to disable password aging for an user account
#chage m 0 M 99999 I -1 E -1 tom
#chage l tom

GROUP ADMINISTRATION
1. Group Administration
A user can be participant to more than one group at the same time.
A user who is member of a group can change to that group without password but a user NOT member
can only change to that group password exit and the user gives it.
One or more user can become group administrator for specific groups.
Group Administrator can:

1. Add/change/delete the password of the group


2. Add/delete users to the group
3. Reserve the group to member-only.
2. Types of group

Primary group

every user must be a member of at least one group, which is identified by the numeric GID
in /etc/passwd

Secondary group

A user may be listed as member of additional groups in the relevent entries in the /etc/group

User private group

Created whenever a new user is added to the system and has the same name as the user for
which it was created

Example:
[sami@server~]$id
Uid=501(tom) gid=502(tom) groups=502(tom),506(admin)

3. Group management commands


a. groupadd adding group
#groupadd admin
#groupadd r admin
#groupadd g 600 HR

//start group id 101 and increase up to GID 499

b. groupmod modifying group


#groupmod [-g newgid] [-n new name] group
#groupmod g 600 n manager admin
c. groupdel deleting group
#groupdel HR
d. gpasswd administer /etc/group and /etc/gshadow
#gpasswd admin
//making new password for admin
#gpasswd A tom admin
//administrator of admin
#gpasswd R admin
//restrict non-member login
#gpasswd r admin
//delete group passwd
#gpasswd a user1 admin
//adding group member
#gpasswd d user1 admin
//deleting group member

SWITCHING ACCOUNTS
1.

Su

a. Syntax
su [-] [user]
su [-] [user] c command
b. Allows the user to temporarily become another user in command line
c. Default user is root
d. The option makes the new shell a login shell
e. Most systems log the use of su to change to the root account
2. Example
$su
$su
$su tom
$su l tom

SSH stands for secure shell.


#yum install openssh* y
#service sshd start
#chkconfig sshd on
#service sshd status
#ssh (ipaddress of target pc)
#ssh user@(ipaddress of user)
#ssh X user@(ipaddress of user with graphical)
HowtogivebannerwarningatthetimeofSSHlogin
#vim /etc/issue.net
Dont entertomysystem..!
#vim /etc/ssh/sshd_config
Banner /etc/issue.net
#service sshd restart

TochangeSSHport:
#vim /etc/ssh/sshd_config
Port 3434
#service sshd restart
#vim /etc/ssh/sshd_config
#PermitRootLogin yes (remove#andpermitrootloginyesorno)
#service sshd restart
#vim /etc/ssh/sshd_config
#PasswordAuthentication yes (remove#andpermitpasswordauthyes/no)
#service sshd restart
#vim /etc/ssh/sshd_config
AllowUsers user2
or
AllowUsers user2@IP
DenyUsers user1
#service sshd restart

SUDO
1. Sudo
a. Purpose: to delegate root privileges to non-root users.
b. Users listed in /etc/sudoers execute commands with
An effective user id of 0
A group id of roots group
c. An administrator is contacted if a user not listed in /etc/sudoers attempts to use sudo

2. Example
a. Default Syntax

User

MACHINE=COMMANDS

b. Allow root to run any commands anywhere

root

ALL=(ALL)

ALL

c. Allows members of the sys groups to run networking, service management apps

%sys

ALL=NETWORKING, SERVICES, DELEGATING, PROCESSESS

d. Allows people in group wheel to run all commands

%whell ALL=(ALL)

ALL

e. Same thing without a password

%whell ALL=(ALL)

ALL

f. Allows member of the users group to mount and unmount the cdrom as a root

%users

ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom

3. How to use sudo


a. Set up sudo Environment in /etc/sudoers as group member
%whell ALL=(ALL)
ALL
#usermod G 10 tom
tom$froups
b. Executing a command as super user
$sudo mount /dev/cdrom /media/cdrom
c. If forgot to give sudo for root command, do it again using !!
$head n 4 /etc/sudoers
$sudo !!
d. Get Root Shell Access using Sudo
$sudo bash; id
e. Sudo logging
Defaults logfile=/var/log/sudolog
#touch /var/log/sudolog
$sudo ls /

GUI Tool for


User Management

1.

Package checking

#rpm qa | grep system-config-users

2. Package installation
#yum install system-config-users

3. Using GUI tool


#system-config-users&
Making new user
Making new group

File Permissions
Umask :
umask is the value with this umask mask value kernel can identify who is going to create a file or
directory. Umask is the command to find out umask value
root users umask 022
normal users umask 002
Example 1:
$ umask 333
$ umask
0333
File
- 666 0333
Directory
- 777 0333

=> 333
=> 444

=>-w- -w- - w => dr - -r - -r - -

Example 2:
$ umask 777
$ umask
0777
File
- 666 777
Directory
- 777 777

=> 000
=> 000

==> - - - - - - - - - ==> d- - - - - - - - -

Chmod command:
It is used to change the permissions for files and directories. The permission
instruction can be issued either

symbolic method
numeric method
Standard files & directories permission
# ls l
-rw- r r--rwx r-x r-x
File permissions is made for three groups of users:
The owner of the file.
For user => u
One of the groups existing on the system.
For group => g
All other users.
For others => o

Options:
u
g
o
a
+
=

user who owns the files


users in the files group
other users
all the three categories
add a permission
remove a permission
assign a permission:

Symbolic method :
r wx s t -

read
write
execute or cd
set user id bit or group
sticky bit

Syntax:
chmod u+w, go-w <file or folder name>
chmod u= rw <file or folder name>

Example 1:
The following command is used to add a permission for the permission of folder.
# chmod u+rwx,g+rw,o+r /songs

Example 2
The following command is used to remove the permission of files.
# chmod u-rwx,g-rwx,o-rwx /song.mp3

Numeric method:
File permissions
read
write
execute
all

4
2
1
7

read,write
read,execute
write,execute
no permission

Syntax :
chmod <UGO> <folder name>
chmod <-options> <file name>

=> 6
=> 5
=> 3
=> 0

Example 1:
The following command is used to modify the folder permissions.
# chmod 755 /movie

Example 2:
The following command is used to modify the file permissions.
# chmod 755
/movie/movie.avi

Chown command:
It is used to change the ownership of the files & directories.
Syntax:
chown <-options> [argument]
Example:
The following command is used to change the ownership
# chown R tom data

Chgrp command:
It is used to change group of the file / directories.
Syntax:
chgrp <-options> argument
Example:
The following command is used to change the group.
# chgrp technical /data

Special Permission
& ACL
Special Permission : SUID, SGID and Sticky Bit
File System ACLs
Three categories to which file permission apply
User, Group, Other

Three standard permission which may apply:

Permission

Effect on Reguler file

Effect on Directory

r (read)

Contents of the can be read

Content of the directory (file names) can be


listed

w (write)

Contents of the can be changed

Any file in directory can be created or deleted

x (executable)

Content of the file can be executed as


acommand

Content of the directory can be accessed


(dependent on file's own permission)

SUID (set UID):


When executable file is run, it executes as the user that owns it,
not as the user that ran it.
Syntax:
chmod u+s <file>
chmod u-s <file>

= sets SUID permission on a file


= removes SUID permission

SGID (set GID):


When executable file is run, it executes as the group that owns
it. All files created below a directory with SGID bit set inherit the group ownership of the
parent directory.
Syntax:
chmod g+s <file>
chmod g-s <file>
chmod g+s <directory>
chmod g-s <directory>

= sets SGID permission on a file


= removes SGID permission for a file
= sets SGID permission on a directory
= removes SGID permission for a directory

Note: Useful for sharing files between users

Sticky Bit:
When set on a directory, users with write access to the directory can
only files they own in the directory.
Syntax:
Chmod o+t
Chmod 0-t

= sets the sticky bit on a directory


= removes the sticky bit for a directory

Note: Useful for /tmp and other world-writable directories.


Permission

Effect on Reguler file

Effect on Directory

SUID chmod u+s file

File executes as user that owns the file, not


No effect
the user that ran the file.

SGID chmod u+g file File executes as group that owns the file

Files newly created in the directory


have group owner set to match group
that owns the directory

"sticky bit"
chmod o+t file

Users with write on the directory can


only remove file they own, they can
not remove files owned by other users

No effect

Access Control Lists


Access Control List (ACL) provides an additional, more flexible permission
mechanism for file systems. It is designed to assist with UNIX file permissions. ACL
allows you to give permissions for any user or group to any disc resource.

ACLs Commands:
setfacl sets an ACL entry on a file
getfacl gets the list of ACL entries on a file
Syntax:
setfacl u:<username>:<perms> <filename>
setfacl g:<username>:<perms> <filename>
getfacl <filename>
Example:
#setfacl m u:sysadmin:r-x/data
#setfacl m g:admin:rwx /data
#setfacl x u:sysadmin /data
#setfacl b /data

Tar Command
Tar is an archiving program created to store, maintain, modify and extract files from an archive file
known as a tarfile. A tarfile may be made on a tape drive, however, it is also common to write a
tarfile to a normal file. Is most widely used command to create compressed archive files and that
can be moved easily from one disk to another disk or one server to another server.
Usage and Options

c create a archive file.


x extract a archive file.
v show the progress of archive file.
f filename of archive file.
t viewing content of archive file.
j filter archive through bzip2.
z filter archive through gzip.
r append or update files or directories to existing archive file.
W Verify a archive file.
wildcards Specify patters in unix tar command.

1. Create an archive file


This is the basic command to create an archive it will not create a compressed archive. Just a plain
archive, that puts multiple files together.

# tar -cvf doc.tar /tmp/sysadmin


2. Create compressed archive file
Now we are going to create a compressed archive, In order to compress, use the z or j option for
gzip or bzip respectively.

# tar -cvzf doc.tar.gz /tmp/sysadmin (gzip)


Note: .tgz is same as .tar.gz

# tar -cvfj doc.tar.bz2 /tmp/sysadmin (bzip2)


Note: .tbz and .tb2 is same as .tar.bz2

Difference between gzip and bzip2:


bzip2 takes more time to compress and decompress than gzip but archival size is less than gzip.
3. Extracting (untar) an archive
To untar or extract a (*.tar) file, just issue following command using option x (extract)
# tar -xvf dragon_ball.tar

4. Uncompress tar.gz archive file


To extract a gzipped tar archive ( *.tar.gz ) use the option z for uncompressing a gzip tar archive.

# tar -xvzf doc.tar.gz


Extract files to a specific directory or path

# tar -xvzf doc.tar.gz -C /home/sysadmin/


Make sure that the destination directory exists, tar is not going to create the directory for you.
5. Uncompress tar.bz2 archive file
Extracting a bzipped tar archive ( *.tar.bz2 ) use the option j for uncompressing a bzip2
tar archive.
# tar -xvjf doc.tar.bz2
6. Extract a one or multiple files
To extract a single file out of an archive just add the file name at the end of the line
# tar -zxvf doc.tar.gz "./home/goku.txt" (gzip)
# tar -jxvf doc.tar.bz2 "./home/goku.txt" (bzip2)
You can also extract more than one file.

# tar -zxvf doc.gz "./home/goku.txt" "./home/gohan.txt (gzip)


# tar -jxvf doc.tar.bz2 "./homegoku.txt" "./home/gohan.txt (bzip2)

Wildcards can be used to extract out a bunch of files matching the given wildcards.

# tar -zxvf doc.tar.gz --wildcards "*.txt" (gzip)


# tar -jxvf doc.tar.bz2 --wildcards "*.txt" (bzip2)
The example above will extract all files with .txt extension.
7. Listing the archive content
List out the contents of the tar archive and not extract them, use the t option.
# tar -tvf dragon_ball.tar
View the (*.tar.gz) file content without extracting
# tar -tvfz doc.tar.gz
View the (*.tar.bz2) file content without extracting
# tar -tvfj doc.tar.bz2
8. Search content of the archive
Use the tar command in combination with the grep search the archive.
# tar -tvf doc.tar | grep goku.txt
For tar.gz/bz2 files use the z and j option respectively.
Also read Using Grep To Search For Text Patterns

9. Adding a file or directory to an existing archive


You can add files or directories to existing archives, without having to create new ones.

# tar -rvf doc.tar trunks.txt


Adding a directory to the tar is also similar.
# tar -rvf doc.tar /tmp/raj
You cannot add file or directory to a compressed archive

10. Verify archive files


You can verify the archive file that got created.

# tar -tvfW doc.tar


You cannot do verification on a compressed ( *.tar.gz, *.tar.bz2 )
11. Check the size of an archive file
To check the size of any tar, tar.gz and tar.bz2 archive file, use the following command.
# tar -czf - doc.tar | wc -c
For tar.gz/bz2 files use the z and j option respectively.

Linux Filesystem
Management
Part 1 Filesystem Management
Chapter 1 Filesystem Management Process
Chapter 2 Device Recognition
Chapter 3 Disk Partitions
Chapter 4 Making Filesystem
Part 2 How to use New Filesystem
Chapter 5 Filesystem Labels
Chapter 6 Mount points & /etc/fstab
Chapter 7 Mount & Unmount
Chapter 8 Handing Swap files and Partitions

Filesystem Management
Process
1.Objectives
Upon completion of this unit, you should be able to:
Manage virtual memory
Add new drives and partitions
Mount filesystems
How to use new Filesystem
2.Over view: Adding new Filesystems to the Filesystem tree
1)Identify Device: /dev/hda or /dev/sda
2)Partition Device: fdisk, sfdisk, GNU parted, Partprobe
3)Make Filesystem: mkfs, mkfs.ext3, mkfs.ext4, mkfs.xfs, mkfs.vfat
4)Label filesystem: e2lable, tune2fs
5)Create entry in /etc/fstab: mount points, mount, and fsck
6)Mount new filesystem: mount, umount

Device Recognition
1.BIOS a list of device to start Operating System (CD, hard disk)
2.First sector of the first cylinder at hard disk Master Boot Record
3.Master Boot Record (MBR) contains:
a.Executables code to load operating system Boot Loader
b.GRUB Grand Unified Boot Loader in Linux systems
c.Space for partition tables information, Including:

Hard Disk type IDE (hda, hdb), SCSI or SATA (sda, sdb)
Partition id Linux swap, Linux , Linux LVM, RAID, DOS
Partition type Primary, Extended and Logical
Partition has each size sector, blocks or cylinders
Starting cylinder for partition 1 cylinder is about 8 MB
Number of cylinder for partition

Disk Partition
1.Types of partitions
a.Primary Partitions: supports only 4 partitions per drive
b.Extended Partitions: one of Primary, includes all Logical partitions
c.Logical partitions: permits the definition of more than four
partitions
2.Total maximum number of partitions supported by the Kernel:
a.63 for IDE drives
b.15 for SCSI or SATA drives
3.Why partition drives?
a.Containment: security breach, user demand
b.Performance: Keeping data together which reduce disk head seek
c.Quotas: using specific file partition
Recovery: easy backup and recovery

4.Managing Partitions
1)Create Partitions using:
a.fdisk most commonly used partitioning program
# fdisk /dev/sda
b)sfdisk more accurate and flexible than fdisk
#sfdisk /dev/sda
c)GNU parted advanced partition manipulation ( create, copy, resize,
etc.)
#parted l /dev/sda
#yum install gparted y ; gparted &
2)Partprobe /proc/partitions
Need to reboot after creating new partition so that kernel reads new partition
table
Reinitializes the kernels inmemory version of the partition table without
rebooting again
#partprobe
#kpartx a /dev/sda; kpartx l /dev/sda

Making Filesystems
1.Mkfs Creating file system
Mkfs.ext3, mkfs.ext4, mkfs.xfs, mkfs.vfat, mkfs.msdos
Specific filesystem utilities can be call directly
#mkfs t ext4 /dev/sda5
(or)
#mkfs.ext4 /dev/sda5
2.mke2fs [options] device
#mke2fs j L data b 2048 i 4096 /dev/sda6
L: filesystem label
j: journaling
b: block size
i: inode per ever 4 kb of disk space

Filesystems Labels
1.e2label filesystem label
a.e2label special _dev_file
#e2label /dev/sda5 data; e2label /dev/sda5
b.Mount label=fslabel mount _point
#mount LABEL=data /data
c.See labels and filesystem type of all devices
#blkid
1.Tune2fs Adjust filesystem parameters
Reserved blocks, default mount options, fsck frequency
a.View current settings
#dumpe2fs /dev/sda5
b.Modify the percentage of reserved clocks
#tune2fs m 10 /dev/sda5
c.Set the default mount options
#tune2fs o acl,user_xattr /dev/sda1
d.Disable mandatory filesystem checks
#tune2fs i0 c0 /dev/sda5

Mount points &


/etc/fstab
1.Configuration of the filesystem /etc/fstab
#device mount_point FS_TYPE option dump_freq fsck_order
LABEL=/data /data ext3 defaults 0 0
Device: special device file name or filesystem label
Mount_point: the path used to access the filesystem
FS_type: filesystem type
Options: a commaseparated list of options
Dump_freq: dump frequence: 1=daily, 2=every other day, 0=never dump
Fsck_order: 0 =ignore, 1=first, 29: second third
2.Used by mount, fsck and other programs
3.May use filesystem volume labels in the device field
4.# mount a can be used to mount all filesystems listed in the /etc/fstab
5.# mount /dev/sda5
# mount L /data
# mount LABEL=/data

Mount & Umount


1.Mount options device mount_point
mount [0 options] [t fs_type] device mount_point
a.Denying permission to execute files
#mount t ext3 o noexec /dev/sda5 /home
b.Mount CDRom image file
#mount t iso9660 o loop /iso/documents.iso /mnt/cdimage
c.Each file is owned by a specific UID and GID
#mount t vfat o uid=500,gid=510 /dev/sdb /mnt/windows
d.Mount filesystem to increase I/O performance by reducing disk access
#mount t ext3 o noatime /dev/sda6 /data
2.Unmounting filesystems
Umount [options] device | mount_point
#umount /data
a.Cannot umount a filesystem that is in use
b.Use the remount option to change a mounted filesystems options
atomically
#mount o remount,ro /data

Handing Swap files


& Partitions
1.Swap space is a supplement to system RAM
2.Process to create swap file and partitions
a.Create swap partition using fdisk
#fdisk /dev/sda
#mkswap /dev/sda9
#vi /etc/fstab
/dev/sda9 swap swap defaults 0 0
#Swapon a ; swapon s; free m
b.Create swap file
#dd if=/dev/zero of=/swapfile bs=1024 count=100000 (100Mb)
#mkswap /swapfile
#vi /etc/fstab
/swapfile swap swap defaults 0 0
#swapon a
#swapon a; free m

Summary
Five steps to control linux filesystems
1.Bios recognition
2.Creating partitions fdisk, gparted, sfdisk
3.Making filesystems for new partition mkfs
4.Labeling new partitions e2label
5.Mounting and using new filesystem
mount, /etc/fstab

In Linux, Logical Volume Manager (LVM) is a device mapper target that provides logical
volume management for the Linux kernel. Most modern Linux distributions are LVM-aware
to the point of being able to have their root file systems on a logical volume.
Heinz Mauelshagen wrote the original LVM code in 1998, taking its primary design
guidelines from the HP-UX's volume manager.
LVM is commonly used for the following purposes:

Managing large hard disk farms by allowing disks to be added and replaced without downtime
or service disruption, in combination with hot swapping.
On small systems (like a desktop at home), instead of having to estimate at installation time
how big a partition might need to be in the future, LVM allows file systems to be easily
resized later as needed.
Performing consistent backups by taking snapshots of the logical volumes.
Creating single logical volumes of multiple physical volumes or entire hard disks (somewhat
similar to RAID 0, but more similar to JBOD), allowing for dynamic volume resizing.
LVM can be considered as a thin software layer on top of the hard disks and partitions, which
creates an abstraction of continuity and ease-of-use for managing hard drive replacement, repartitioning, and backup.

To create a LVM, we need to run through the following steps.


Select the physical storage devices for LVM
Create the Volume Group from Physical Volumes
Create Logical Volumes from Volume Group

Let's find out about our hard disks:


#fdisk -l
#fdisk /dev/sda
Command (m for help): <-- m
Command (m for help): <-- n
Command action
e extended
p primary partition (1-4)
<-- p
Partition number (1-4): <-- 1
First cylinder (1-10443, default 1): <-- <ENTER>
Using default value 1
Last cylinder or +size or +sizeM or +sizeK (1-10443, default 10443): <-- +1G
Command (m for help): <-- t
Selected partition 1
Hex code (type L to list codes): <-- L
Hex code (type L to list codes): <-- 8e
Changed system type of partition 1 to 8e (Linux LVM)
Command (m for help): <-- p
Command (m for help): <-- w
same configuration create another two partition
Then run
#partprobe (or) partx -a -v /dev/sda /
#fdisk -l

/we informed new partition tables reload to os

Now we prepare our new partitions for PV:


#pvcreate /dev/sda1
#pvdisplay (or) pvscan (or) pvs
Now we prepare our PV partitions for VG:
#vgcreate oracle /dev/sda1
#vgdisplay (or) vgscan (or) vgs
Now we prepare our VG partitions for LV:
#lvcreate -L 500M oracle -n db01
#lvcreate -L 500M oracle -n db02
#lvdisplay (or) lvscan (or) lvs
Now we create a directory for mount those LVM's:
#mkdir /data1
#mkdir /data2
Now we format those LVM's into ext4 FS:
#mkfs.ext4 /dev/oracle/db01
#mkfs.ext4 /dev/oracle/db02
Mount those LVM's into permanent mount:
#vim /etc/fstab
/dev/oracle/db01 /data1 ext4 defaults 0 0
/dev/oracle/db02 /data2 ext4 defaults 0 0
:wq
#mount -a
#df -Th

Now let's enlarge /data1 500M to 1GB:


#lvextend -L +500M /dev/oracle/db01
#resize2fs /dev/oracle/db01
#df -Th
Now let's reduce /data2 500M to 250M:
#umount /data2
#e2fsck -f /dev/oracle/db02
#resize2fs /dev/oracle/db02 250M
#lvreduce -L 250M /dev/oracle/db02
#mount -a
#df -Th
Now let's extend VG:
#vgextend oracle /dev/sdb2
#vgs
Additional configuration in LV and VG
How to create with VG size and other parameter
#vgcreate -l 20 -p 5 -s 16M -Ay java /dev/sda5
-l
20
-p
5
-s
-Ay

====> Number of logical volume can be created on the VG


====> Max can created 20 LV on the current VG
====> Number of Physical volume can be added into current VG
====> Max can added 5 PV on the VG
====> PE size should be 16M
====> Autobackup (yes)

How to change VG parameter


#vgchange -l 30 -p 10 -s 32M java
How to rename VG
#vgrename java sql
How to split VG
#vgsplit sql veritas /dev/sda5
How to merge 2 VG
#vgmerge -v veritas sql
How LV create with PE size
#lvcreate -l 16 -n /dev/veritas/db01
How to activate and deactivate LV
#lvchange -a y /dev/veritas/db01
#lvdisplay
#lvchange -a n /dev/veritas/db01
#lvdisplay
How to restore the removed VG
#lvremove -f /dev/veritas/db01
#lvs
#vgremove -f veritas
#vgs

Once removed LV and VG and follow the steps VG restoration


#cd /etc/lvm/archive
#ls
#cat veritas-vg_00000-106603032.vg
please find last LV file and then copy to /etc/lvm/backup
#cp -r veritas-vg_00000-106603032.vg /etc/lvm/backup
#cd /etc/lvm/backup
#ls
#vgcfgrestore -f veritas-vg_00000-106603032.vg veritas
#vgchange -a y veritas
#vgs
#lvs
Now you could able to see VG and LV

OSI LAYER
The Open System Interconnection (OSI) model defines a
networking framework to implement protocols in
seven layers.

NIC Network Interface Card


IP Address Internet Protocol Address
IPv4> 32 bit separated by dots(.)
IPv6 >128 bit separated by colon (:)

Private IP
Class A 10.0.0.0
Class B 172.16.0.0
class C 192.168.0.0
Public IP

APIPA IP:

169.254.0.1

10.255.255.255
172.31.255.255
192.168.255.255

169.254.255.254

What is the Difference Between 127.0.0.1 and 0.0.0.0?


127.0.0.1 is the loopback address (also known as
localhost).
0.0.0.0 is a nonroutable metaaddress used to designate
an invalid, unknown, or nonapplicable target
In the context of a route entry, it usually means the
default route.
In the context of servers, 0.0.0.0 means all IPv4
addresses on the local machine. If a host has two IP
addresses, 192.168.1.1 and 10.1.2.1, and a server running
on the host listens on 0.0.0.0, it will be reachable at
both of those IPs.
Subnet used in IP N/W to break up large N/W in to Smaller
N/W
To communicate a network
IP address
hardware address
host name
dns

Peer-to-peer network

Serverbased network (or) Client/Server network

Host Name finding host/domain name and IP address


hostname
--->
with no options displays the machines host
name
hostname -d ---> displays the domain name the machine
belongs to
hostname f
> displays the fully qualified host and
domain name
hostname i
> displays the IP address for the current
machine
uname n
> Display the HostName for the current
machine
To Check IP Address
ip a
ifconfig -a
ifconfig eth1
ifconfig eth1 down
ifconfig eth1 up

Temporary ip
Note : Maximum 255 IP address in a single N/W card can assign as alias
i) # ifconfig eth0:0 192.168.6.146 255.255.255.0
ii) # ifconfig eth0:1 192.168.6.150 255.255.255.0 up
iii) # ifconfig eth0:2 192.168.6.151/24
# service network restart > It will destroy the temporary ip
Permonent IP Address
cd /etc/sysconfig/networkscripts/
ls l | grep ifcfgeth
cp p ifcfgeth0 ifcfgeth0:1

vim ifcfgeth0:1
DEVICE=eth0:1
ONBOOT=yes
HWADDR=00:0c:29:3e:a7:a4
IPADDR=192.168.6.150
TYPE=Ethernet
BOOTPROTO=none
NETMASK=255.255.255.0
NAME="System eth0:1"

ifconfig eth0:1
service NetworkManager stop
chkconfig NetworkManager on
service iptables stop
service ip6tables stop
chkconfig ip6tables on
chkconfig iptables on
service network restart
ifconfig a
watch ifconfig
ip addr show
ip route show
ip 4 addr show
ip 6 addr show

ethtool
#ethtool eth0 >
#ethtool t eth0 online > HW component LAN card is
working perfectly or not
#ethtool t eth0 offline
#ethtool i eth0 >
driver information
#ethtool s eth0 speed 100 autoneg off
#ethtool a eth0 > Display auto negotiation on or off
#ethtool s eth0

netstat
#netstat in
#service network restart
#ifconfig
#setup
# cat /etc/hosts
#hostname server1.verizon.com ====To set the hostname temporary
To set the hostname permenant
[root@server ~]# cat /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=server.verizon.com
To Put DNS entry
[root@desktop75 ~]# cat /etc/resolv.conf
search example.com
nameserver 192.168.0.254

IP FORWARDING
Enable ip forwarding on your machine.
Temporarily set:
# sysctl w net.ipv4.ip_forward=1
[OR]
# echo 1 > /proc/sys/net/ipv4/ip_forward
Permanently set:
# vim /etc/sysctl.conf
net.ipv4.ip_forward=1
#vim /etc/sysconfig/network
FORWARD_IPV4=true
# sysctl p /etc/sysctl.conf
[OR]
# systemctl restart network.service
NOTE: sysctl configure kernel parameters at runtime
VERIFICATION:
# sysctl a | grep net.ipv4.ip_forward
# cat /proc/sys/net/ipv4/ip_forward

To stop ipv6 protocols permanently


#vim /etc/sysctl.conf
net.ipv6.conf.all.disable_ipv6 = 1
#sysctl p
p > Load in sysctl settings from the file specified.
Note : To disable a particular network card like eth0 permanently
#vim /etc/sysctl.conf
net.ipv6.conf.eth0.disable_ipv6 = 1
#sysctl p
Note : To disable a particular network card like eth0 Temporary
# echo 1 > /proc/sys/net/ipv6/conf/eth0/disable_ipv6
I successfully disabled IPv6 once putting the following lines in
/etc/sysctl.conf:
net.ipv6.conf.all.disable_ipv6 = 1net.ipv6.conf.default.disable_ipv6 =
1net.ipv6.conf.lo.disable_ipv6 = 1

How to Display Routing Table


# route n
# netstat rn
r option specifies that you want the routing table.
n option similer to that route command
# ip route list
#ifconfig br0:2 192.168.1.63/24
# route add default gw 192.168.1.1
# route n
Kernel IP routing table
# route del default gw 192.168.0.254
#vim /etc/resolv.conf
search example.com
#nameserver 192.168.0.254
nameserver 203.145.184.13
nameserver 203.145.184.32
# ping google.com

GUI
#systemconfignetworktui
(or)
#setup
Note :
Port Information can be seen in the file: /etc/services
#cat /etc/services | grep i telnet
#yum install telnet* y
# telnet 192.168.0.85 22 > port no
#netstat an | grep w 22
#netstat ant

>It will gives network statistics(which port number of the server is


connected to which port number of client)

[root@localhost ~]# arp


Address
HWtype HWaddress
Flags Mask
192.168.6.1
ether 00:50:56:c0:00:08 C

Iface
eth0

PORT FORWARDING
SYNTAX FOR RHEL6:
ssh L local-port:remote-hostname:remote-port
username@hostname
SYNTAX FOR RHEL7:
#firewallcmd permanent addrichrule='rule
family=ipv4 source address=clientIP forwardport
port=5243 prfamily=ipv4 sotocol=tcp toport=22'
#firewallcmd reload
#firewallcmd listrichrules
Verfication On Client Machine:
#ssh serverIP p 5243

HARDWARE
MANAGEMENT
dmidecode - DMI table decoder
# dmidecode t <keywords/number>
dmidecode: an argument 't Type number or keyword
expected.
Valid type keywords are:
bios
system
baseboard
chassis
processor
memory
cache
connector
slot

The SMBIOS specification defines the following DMI types:


Type

Information

Type

Information

BIOS

10

On Board Devices

System

11

OEM Strings

Base Board

12

System Configuration Options

Chassis

13

BIOS Language

Processor

14

Group Associations

Memory Controller

15

System Event Log

Memory Module

16

Physical Memory Array

Cache

17

Memory Device

Port Connector

18

32bit Memory Error

System Slots

19

Memory Array Mapped


Address

Type

Information

Type

Information

20

Memory Device Mapped Address

31

Boot Integrity Services

21

Builtin Pointing Device

32

System Boot

22

Portable Battery

33

64bit Memory Error

23

System Reset

34

Management Device

24

Hardware Security

35

Management Device Component

25

System Power Controls

36

Management Device Threshold


Data

26

Voltage Probe

37

Memory Channel

27

Cooling Device

38

IPMI Device

28

Temperature Probe

39

Power Supply

29

Electrical Current Probe

40

Additional Information

30

Outofband Remote Access

41

Onboard Device

Additionally, type 126 is used for disabled entries and type 127 is an endoftable
marker. Types 128 to 255 are for OEMspecific data.
dmidecode will display these entries by default, but it can only decode them when
the vendors have contributed documentation or code for them.
Keyword

Types

bios

0, 13

system

1, 12, 15, 23, 32

baseboard

2, 10, 41

chassis

processor

memory

5, 6, 16, 17

cache

connector

slot

Keywords can be used instead of type numbers


with type. Each keyword is equivalent to a list
of type numbers:

Keywords are matched caseinsensitively.


The following command lines are equivalent:
dmidecode type 0 type 13
dmidecode type 0,13
dmidecode type bios

CPU Information
dmidecode t processor
cat /proc/cpuinfo > All the info. about the cpu
lscpu
cat /proc/cpuinfo | grep processor
cat /proc/cpuinfo | grep cores
grep "core id" /proc/cpuinfo
cat /proc/cpuinfo | grep processor | wc l
cat /proc/cpuinfo | grep core | wc l
nproc
Note : The nproc command just prints out the number of processing units available. Note
that the number of processing units might not always be the same as number of
cores.

Note: can see the usage of your CPU cores using top
command.
Open a Terminal.
Type top. You will see some information about tasks,
memory etc.
Type 1 to show individual CPU usage
Note : you can follow the below steps to install lshw tools,
then you can use it
1.wget http://ezix.org/software/files/lshwB.02.14.tar.gz
tar zxvf lshwB.02.14.tar.gz
cd lshwB.02.14
make && make install

#lshw class processor


# grep count processor /proc/cpuinfo
# ls /sys/devices/system/cpu/
# cat /sys/devices/system/cpu/kernel_max
# cat /sys/devices/system/cpu/offline
# cat /sys/devices/system/cpu/possible
# cat /sys/devices/system/cpu/present
# cat /sys/devices/system/cpu/online

RAM
# dmidecode t memory | grep "Type"
# dmidecode t 17 | grep i Type
# dmidecode t 17
# lshw class memory
PCI (Peripheral Component Interconnect)
#lspci
00:19.0 Ethernet controller: Intel Corporation 82579V Gigabit Network Connection (rev
05)
1
2
3
4

Field 1: PCI bus slot number (Device ID)


Field 2: PCI slot name (Device Name)
Field 3: Name of device attached and its manufactured company
name.(Device Desc)
# lspci vmm | more > mm Dump PCI device data in a machine
readable form for
easy
parsing by scripts.
#lspci k > Show kernel drivers handling each device and also kernel
modules capable of handling it.
#lspci v > Be verbose and display detailed information about all
devices.
# dmidecode t bios | more
# dmidecode t baseboard | more
# dmidecode t chassis > cabinet info
# lspci tv > your master PCI bus is 00. It is better to use v option with
t to get detailed information
# lspci m

DISK Information
# lspci | grep i scsi
or
# lspci | grep i sata
# lspci | grep i eth
# cd /sys/bus/pci
# ls
cd devices/
# ls
# cd 0000:00:19.0
# ls
# cat device
# cat /proc/scsi/scsi
# hdparm i /dev/sda > HDD Model No & Serial NO
# free m
# lsblk
# mount | column t
# mount | column t | grep ext
# dmidecode | grep ^Handle | wc l
# dmidecode | grep structures

To add a HDD
# lspci | grep i scsi
# cd /sys/bus/pci/devices
#ls
# cd 0000\:00\:10.0/
#ls
Note : open one duplicate terminal and watch
#udevadm monitor
Note : add a HDD in virtula server then scan
#fdisk l
# echo " " > /sys/class/scsi_host/host2/scan
Note : you can monitor the process
Note : Now remove the HDD
# echo 1 > /sys/block/sdb/device/delete
# fdisk l
Note : Now remove the HDD physically

# fdisk l | grep i disk


# cd /sys/class/scsi_host/
# ls
#cd host2
#ls
To Add and remove a ethernet card driver
To locate a kernal Modules
Step 1
#ethtool i eth0
or
Step 2
# cd /lib/modules/
# ls
#cd 2.6.32220.el6.x86_64/
#ls
#cd kernel/
#cd drivers/

#cd net/
#cd e1000
#ls
#modinfo e1000 | more
# ethtool i eth0
#lspci | grep i eth
/sys/class/net/eth0/device/driver
#ls l
modprobe r e1000 > To remove a lan card driver
Go to console and enter the command
#modprobe e1000
# service network restart
Now go to putty reload the server
To Change the HW address
step 1: bring down the interface
# ifconfig a
# ifconfig eth2 down
#ifconfig eth2 hw ether 00:01:02:03:04:05

DU
The Linux du (Disk Usage) is a standard Unix/Linux
command, used to check the information of disk usage of
files and directories on a machine.
The du command also displays the files and directory
sizes in a recursively manner.
Syntax:
du <options> <file or dir name>
Options
-h
-s
-a
-k
-m
--exclude
time

Descriptions
Human Readable Format
summary
all the files and directories
Kilobyte(size in 1024 bytes)
Megabytes (MB)
exclude any file formats.
Ex: du ah exclude="*.txt" /home
modification of time
Ex: du ha time /home

DD COMMAND
This tool is mainly used for copying and converting data, hence it stands for
Data Duplicator.
Only superuser can execute this command. You should be very careful while
using this command as improper usage may cause huge data loss. So, some
people consider this tool as Data Destroyer.
Syntax of dd command
dd if=<source file name> of=<target file name> [Options]

Backing up and restoring an entire hard drive or a partition


Description

Command

Backup entire hard drive to


another drive.

dd if=/dev/sda of=/dev/sdb bs=4096 conv=noerror,sync

Creating a disk image

dd if=/dev/sda of=/tmp/sdadisk.img

Creating a compressed disk


image

dd if=/dev/sda | gzip >/tmp/sdadisk.img.gz

Restoring hard disk image

dd if=/tmp/sdadisk.img of=/dev/sda

Restoring compressed image gzip dc /tmp/sdadisk.img.gz | dd of=/dev/sda


Clone one partition to
another

dd if=/dev/sda1 of=/dev/sdb1 bs=4096 conv=noerror,sync

Backing up and Restoring MBR


Master Boot record is the boot sector which houses the GRUB boot loader. If
MBR got corrupted, we will not be able to boot into Linux. MBR 512 byte
data is located at the first sector of the hard disk. It consists of 446 byte
bootstrap, 64 byte partition table and 2 bytes signature.
Description

Command

Backing up MBR

dd if=/dev/sda of=/tmp/mbr.img bs=512 count=1


The option count refers to the number of input blocks to
be copied

Backing up the boot data of dd if=/dev/sda of=/tmp/mbr.img bs=446 count=1


MBR excluding the
partition table
Restoring MBR from MBR
image

dd if=/tmp/mbr.img of=/dev/sda

Display master boot record

dd if=/dev/hda of=mbr.bin bs=512 count=1 od xa mbr.bin

Converting data formats


Description

Command

Convert the data format of a


file from ASCII to EBCDIC

dd if=textfile.ascii of=textfile.ebcdic conv=ebcdic

Convert the data format of a


file from EBCDIC to ASCII

dd if=textfile.ebcdic of=textfile.ascii conv=ascii

Converting case of a file


Description

Command

Converting a file to Uppercase

dd if=file1 of=file2 conv=ucase

Converting a file to lowercase

dd if=file1 of=file2 conv=lcase

Creating or modifying data files


Description

Command

Create a fixed size, say 10MB file

dd if=/dev/zero of=file1 bs=10485760 count=1


The block size is calculated as 10MB=10*1024*1024

Modify the first 512 bytes of a


file with null data

dd if=/dev/zero of=file1 bs=512 count=1 conv=notrunc


The option notrunc refers to do not truncate the file,
only replace the first 512 bytes, if it exists. Otherwise,
you will get a 512 byte file.