You are on page 1of 153

EMPOWERING SYSTEM ADMINISTRATORS

RHCSA-2

LOG FILES
Log Files Location And How Do I View Logs Files
Almost all logfiles are located under /var/log directory and its sub
directories on Linux. You can change to this directory using the cd command. You
need be the root user to view or access log files on Linux or Unix like operating
systems. You can use the following commands to see the log files:
less command
more command
cat command
grep command
tail command
zcat command
zgrep command
zmore command
How do I view log files on Linux?
Open the Terminal or login as root user using ssh command. Go to /var/log
directory using the following cd command:
# cd /var/log

To view a common log file called /var/log/messages use any one of the following command:
# less /var/log/messages
# more f /var/log/messages
# cat /var/log/messages
# tail f /var/log/messages
# grep i error /var/log/messages
Common Linux log files names and usage
/var/log/messages : General message and system related stuff
/var/log/auth.log : Authenication logs
/var/log/kern.log : Kernel logs
/var/log/cron.log : Crond logs (cron job)
/var/log/maillog : Mail server logs
/var/log/qmail/ : Qmail log directory (more files inside this directory)
/var/log/httpd/ : Apache access and error logs directory
/var/log/lighttpd/ : Lighttpd access and error logs directory
/var/log/boot.log : System boot log
/var/log/mysqld.log : MySQL database server log file
/var/log/secure or /var/log/auth.log : Authentication log
/var/log/utmp or /var/log/wtmp : Login records file
/var/log/yum.log : Yum command log file.

MONITORING TOOLS

TOP Command
Linux Top command is a performance monitoring program which is used frequently by
many system administrators to monitor Linux performance and it is available under
many Linux/Unix like operating systems. The top command used to dipslay all the
running and active realtime processes in ordered list and updates it regularly. It
display CPU usage, Memory usage, Swap Memory, Cache Size, Buffer Size, Process
PID, User, Commands and much more. It also shows high memory and cpu utilization
of a running processess. The top command is much userful for system administrator
to monitor and take correct action when required. Lets see top command in action.
# top
2. Sorting with O (Uppercase Letter O)
Press (Shift+O) to Sort field via field letter, for example press a letter to sort process with
PID (Process ID).
3. Display Specific User Process
# top u tecmint
4. Highlight Running Process in Top
Press z option in running top command will display running process in color which may
help you to identified running process easily.
5. Shows Absolute Path of Processes
Press c option in running top command, it will display absolute path of running process.

6. Change Delay or Set Screen Refresh Interval in Top


By default screen refresh interval is 3.0 seconds, same can be change pressing d option
in running top command and change it as desired as shown below.
7. Kill running process with argument k
You can kill a process after finding PID of process by pressing k option in running top
command without exiting from top window as shown below.
8. Sort by CPU Utilisation
Press (Shift+P) to sort processes as per CPU utilization. See screenshot below.
9. Renice a Process
You can use r option to change the priority of the process also called Renice.
10. Save Top Command Results
Press (Shift+W) to save the running top command results under /root/.toprc.
11. Getting Top Command Help
Press h option to obtain the top command help.
12. Exit Top Command After Specific repetition
Top output keep refreshing until you press q. With below command top command will
automatically exit after 10 number of repetition.
There are number of arguments to know more about top command you may refer man
page of top command.

VmStat Virtual Memory Statistics


Linux VmStat command used to display statistics of virtual memory, kernerl
threads, disks, system processes, I/O blocks, interrupts, CPU activity and
much more. By default vmstat command is not available under Linux
systems you need to install a package called sysstat that includes a vmstat
program.
If vmstat and iostat commands are not available on your box, please install
sysstat package. The vmstat, sar and iostat commands are the collection
of package included in sysstat the system monitoring tools. The iostat
generates reports of CPU & all device statistics. You may download and
install sysstat using source tarball from link sysstat, but we recommend
installing through YUM command.
Install Sysstat in Linux
# yum y install sysstat
vmstat Summary information of Memory, Processes, Paging etc.
iostat Central Processing Unit (CPU) statistics and input/output statistics
for devices and partitions

1. List Active and Inactive Memory


In the below example, there are six columns. The significant of the columns are
explained in man page of vmstat in details. Most important fields are free under
memory and si, so under swap column.
# vmstat a
procs memory swap io system cpu
r b swpd free inact active si so bi bo in cs us sy id wa st
1 0 0 810420 97380 70628 0 0 115 4 89 79 1 6 90 3 0
Free Amount of free/idle memory spaces.
si Swaped in every second from disk in Kilo Bytes.
so Swaped out every second to disk in Kilo Bytes.
Note: If you run vmstat without parameters itll displays summary report since system
boot.
2. Execute vmstat X seconds and (Nnumber of times)
With this command, vmstat execute every two seconds and stop automatically after
executing six intervals.
# vmstat 2 6

3. Vmstat with timestamps


vmstat command with t parameter shows timestamps with every line
printed as shown below.
$ vmstat t 1 5
4. Statistics of Various Counter
vmstat command and s switch displays summary of various event counters
and memory statistics.
$ vmstat s
5. Disks Statistics
vmstat with d option display all disks statistics.
$ vmstat d
6. Display Statistics in Megabytes
The vmstat displays in Megabytes with parameters S and M(Uppercase &
megabytes). By default vmstat displays statistics in kilobytes.
# vmstat S M 1 5

Iostat Command
1. Display CPU and I/O statistics
iostat without arguments displays CPU and I/O statistics of all partitions as shown below.
# iostat
2. Shows only CPU Statistics
iostat with c arguments displays only CPU statistics as shown below.
# iostat c
3. Shows only Disks I/O Statistics
iostat with d arguments displays only disks I/O statistics of all partitions as shown.
# iostat d
4. Shows I/O statistics only of a single device.
By default it displays statistics of all partitions, with p and device name arguments displays only disks I/O
statistics for specific device only as shown.
# iostat p sda
5. Display LVM Statistics
With N (Uppercase) parameter displays only LVM statistics as shown.
# iostat N
6. iostat version.
With V (Uppercase) parameter displays version of iostat as shown.
# iostat V
Note: vmstat and iostat contains number of columns and flags which may not possible to explain in details. If
you want to know more about it you may refer man page of vmstat and iostat.

Lsof List Open Files


Lsof command used in many Linux/Unix like system that is used to display list of all the open files and the
processes. The open files included are disk files, network sockets, pipes, devices and processes. One of
the main reason for using this command is when a disk cannot be unmounted and displays the error
that files are being used or opened. With this commmand you can easily identify which files are in use.
1. List all Open Files with lsof Command
In the below example, it will show long listing of open files some of them are extracted for better
understanding which displays the columns like Command, PID, USER, FD, TYPE etc.
# lsof
Sections and its values are selfexplanatory. However, well review FD & TYPE columns more precisely.
FD stands for File descriptor and may seen some of the values as:
cwd current working directory
rtd root directory
txt program text (code and data)
mem memorymapped file
Also in FD column numbers like 1u is actual file descriptor and followed by u,r,w of its mode as:
r for read access.
w for write access.
u for read and write access.
TYPE of files and its identification.
DIR Directory
REG Regular file
CHR Character special file.
FIFO First In First Out

2. List User Specific Opened Files


The below command will display the list of all opened files of user tecmint.
# lsof u tecmint
3. Find Processes running on Specific Port
To find out all the running process of specific port, just use the following command
with option i. The below example will list all running process of port 22.
# lsof i TCP:22
4. List Only IPv4 & IPv6 Open Files
In below example shows only IPv4 and IPv6 network files open with separate
commands.
# lsof i 4
# lsof i 6
5. List Open Files of TCP Port ranges 11024
To list all the running process of open files of TCP Port ranges from 11024.
# lsof i TCP:11024
6. Exclude User with ^ Character
Here, we have excluded root user. You can exclude a particular user using ^ with
command as shown above.
# lsof i u^root

7. Find Out whos Looking What Files and Commands?


Below example shows user tecmint is using command like ping and /etc directory .
# lsof i u tecmint
8. List all Network Connections
The following command with option i shows the list of all network connections
LISTENING & ESTABLISHED.
# lsof i
9. Search by PID
The below example only shows whose PID is 1 [One].
# lsof p 1
10. Kill all Activity of Particular User
Sometimes you may have to kill all the processes for a specific user. Below command
will kills all the processes of tecmint user.
# kill 9 `lsof t u tecmint`
Note: Here, its not possible to give example of all available options, this guide is only
to show how lsof command can be use. You may refer man page of lsof command
to know more about it.

Tcpdump Network Packet Analyzer


Tcpdump one of the most widely used commandline network packet analyzer or packets sniffer
program that is used capture or filter TCP/IP packets that received or transferred on a specific
interface over a network. It also provides a option to save captured packages in a file for later
analysis.
How to Install tcpdump in Linux
Many of Linux distributions already shipped with tcpdump tool, if in case you dont have it on
systems, you can install it using following Yum command.
# yum install tcpdump
1. Capture Packets from Specific Interface
The command screen will scroll up until you interrupt and when we execute tcpdump command it
will captures from all the interfaces, however with i switch only capture from desire interface.
# tcpdump i eth0
2. Capture Only N Number of Packets
When you run tcpdump command it will capture all the packets for specified interface, until you Hit
cancel button. But using c option, you can capture specified number of packets. The below
example will only capture 6 packets.
# tcpdump c 5 i eth0
3. Print Captured Packets in ASCII
The below tcpdump command with option A displays the package in ASCII format. It is a character
encoding scheme format.
# tcpdump A i eth0

4. Display Available Interfaces


To list number of available interfaces on the system, run the following command with D
option.
# tcpdump D
5. Display Captured Packets in HEX and ASCII
The following command with option XX capture the data of each packet, including its link
level header in HEX and ASCII format.
# tcpdump XX i eth0
6. Capture and Save Packets in a File
As we said, that tcpdump has a feature to capture and save the file in a .pcap format, to
do this just execute command with w option.
# tcpdump w 0001.pcap i eth0
7. Read Captured Packets File
To read and analyze captured packet 0001.pcap file use the command with r option, as
shown below.
# tcpdump r 0001.pcap
8. Capture IP address Packets
To capture packets for a specific interface, run the following command with option n.
# tcpdump n i eth0

9. Capture only TCP Packets.


To capture packets based on TCP port, run the following command with option tcp.
# tcpdump i eth0 tcp
10. Capture Packet from Specific Port
Lets say you want to capture packets for specific port 22, execute the below command by
specifying port number 22 as shown below.
# tcpdump i eth0 port 22
11. Capture Packets from source IP
To capture packets from source IP, say you want to capture packets for 192.168.0.2, use
the command as follows.
# tcpdump i eth0 src 192.168.0.2
12. Capture Packets from destination IP
To capture packets from destination IP, say you want to capture packets for 50.116.66.139,
use the command as follows.
# tcpdump i eth0 dst 50.116.66.139
This article may help you to explore tcpdump command in depth and also to capture and
analysis packets in future. There are number of options available, you can use the
options as per your requirement.

Netstat Network Statistics


Netstat is a command line tool for monitoring incoming and outgoing network packets
statistics as well as interface statistics. It is very useful tool for every system
administrator to monitor network performance and troubleshoot network related
problems.
1. Listing all the LISTENING Ports of TCP and UDP connections
Listing all ports (both TCP and UDP) using netstat a option.
# netstat a | more
2. Listing TCP Ports connections
Listing only TCP (Transmission Control Protocol) port connections using netstat at.
# netstat at
3. Listing UDP Ports connections
Listing only UDP (User Datagram Protocol ) port connections using netstat au.
# netstat au
4. Listing all LISTENING Connections
Listing all active listening ports connections with netstat l.
# netstat l
5. Listing all TCP Listening Ports
Listing all active listening TCP ports by using option netstat lt.
# netstat lt

6. Listing all UDP Listening Ports


Listing all active listening UDP ports by using option netstat lu.
# netstat lu
7. Listing all UNIX Listening Ports
Listing all active UNIX listening ports using netstat lx.
# netstat lx
8. Showing Statistics by Protocol
Displays statistics by protocol. By default, statistics are shown for the TCP, UDP, ICMP, and IP protocols. The
s parameter can be used to specify a set of protocols.
# netstat s
9. Showing Statistics by TCP Protocol
Showing statistics of only TCP protocol by using option netstat st.
# netstat st
10. Showing Statistics by UDP Protocol
# netstat su
11. Displaying Service name with PID
Displaying service name with their PID number, using option netstat tp will display PID/Program Name.
# netstat tp
12. Displaying Promiscuous Mode
Displaying Promiscuous mode with ac switch, netstat print the selected information or refresh screen
every five second. Default screen refresh in every second.
# netstat ac 5 | grep tcp

13. Displaying Kernel IP routing


Display Kernel IP routing table with netstat and route command.
# netstat r
14. Showing Network Interface Transactions
Showing network interface packet transactions including both transferring and receiving
packets with MTU size.
# netstat i
15. Showing Kernel Interface Table
Showing Kernel interface table, similar to ifconfig command.
# netstat ie
16. Displaying IPv4 and IPv6 Information
Displays multicast group membership information for both IPv4 and IPv6.
# netstat g
17. Print Netstat Information Continuously
To get netstat information every few second, then use the following command, it will
print netstat information continuously, say every few seconds.
# netstat c

18. Finding non supportive Address


Finding unconfigured address families with some useful information.
# netstat verbose
19. Finding Listening Programs
Find out how many listening programs running on a port.
# netstat ap | grep http
20. Displaying RAW Network Statistics
# netstat statistics raw
Thats it, If you are looking for more information and options about
netstat command, refer netstat manual docs or use man netstat
command to know all the information.

IPTraf Real Time IP LAN Monitoring


IPTraf is an open source consolebased real time network (IP LAN)
monitoring utility for Linux. It collects a variety of information such as
IP traffic monitor that passes over the network, including TCP flag
information, ICMP details, TCP/UDP traffic breakdowns, TCP
connection packet and byne counts. It also gathers information of
general and detaled interface statistics of TCP, UDP, IP, ICMP, nonIP, IP
checksum errors, interface activity etc.
Installing IPTraf
IPTraf is part of the Linux distribution and can be installed on RHEL,
CentOS and Fedora servers using yum command from terminal.
# yum install iptraf
IPTraf Usage
Once IPTraf installed, run the following command from the terminal to
launch an ascii based menu interface that will allow you to view
current IP traffic monitoring, General interface statistics, Detailed
interface statistics, Statistical breakdowns, Filters and also provide
some configure options where you can configure as per your need.

#iptraf

IPTraf Startup Screen


The iptraf interactive screen, displays a menu system with different options to choose from. Here
are the some screenshots that shows real time IP traffic counts and interface statistics etc.

IP traffic monitor
General interface statistics
Detailed interface statistics
Statistical breakdowns
LAN station monitor
Configure

IPTraf Options
Using iptraf -i will immediately start the IP traffic monitor on a particular interface.
For example, the following command will start the IP traffic on interface eth0. This is
the primary interface card that attached to your system. Else you can also monitor all
your network interface traffic using argument as iptraf -i all.

# iptraf i eth0
IPTraf Eth0 Monitoring
Similarly, you can also monitor TCP/UDP traffic on a specific interface, using the
following command.
# iptraf s eth0

Psacct or Acct Monitor User Activity

The psacct or acct package provides several features for monitoring process activities.
ac command prints the statistics of user logins/logouts (connect time) in hours.
lastcomm command prints the information of previously executed commands of user.
accton commands is used to turn on/off process for accounting.
sa command summarizes information of previously executed commands.
last and lastb commands show listing of last logged in users.
Using command ac -d will prints out the total login time in hours by daywise.
Using command ac -p will print the total login time of each user in hours.
To get the total login statistics time of user tecmint in hours, use the command as. # ac tecmint
The following command will prints the daywise total login time of user tecmint in hours. # ac
d tecmint
Print All Account Activity Information # sa
Print Individual User Information
# sa u
Print Number of Processes
# sa m
Print Sort by Percentage
# sa c
List Last Executed Commands of User
# lastcomm tecmint
Search Logs for Commands
# lastcomm ls

RPM
RPM (Red Hat Package Manager) utility for Red Hat based systems like (RHEL, CentOS and Fedora).
The tool allows system administrators and users to install, update, uninstall, query, verify and manage
system software packages in Unix/Linux operating systems. The RPM formerly known as .rpm file, that
includes compiled software programs and libraries needed by the packages. This utility only works with
packages that built on .rpm format. is an default open source and most popular package management
Some Facts about RPM (RedHat Package Manager)

RPM is free and released under GPL (General Public License).


RPM keeps the information of all the installed packages under /var/lib/rpm database.
RPM is the only way to install packages under Linux systems, if youve installed packages using source
code, then rpm wont manage it.
RPM deals with .rpm files, which contains the actual information about the packages such as: what
it is, from where it comes, dependencies info, version info etc.

There are five basic modes for RPM command

Install
Remove
Upgrade
Verify
Query

It is used to install any RPM package.


It is used to erase, remove or un-install any RPM package.
It is used to update the existing RPM package.
It is used to query about different RPM packages.
It is used for the verification of any RPM package.

Where to find RPM packages


Below is the list of rpm sites, where you can find and download all RPM
packages.
http://rpmfind.net
http://www.redhat.com
http://freshrpms.net/
http://rpm.pbone.net/
How to Mount RPM Packages from cdrom iso image
#mount /dev/sr0 /mnt
#cd /mnt
#ls
#cd Package
#ls

1. How to Check an RPM Signature Package


# rpm --checksig pidgin-2.7.9-5.el6.2.i686.rpm
2. How to Install an RPM Package
# rpm -ivh pidgin-2.7.9-5.el6.2.i686.rpm
RPM command and options
-i : install a package
-v : verbose for a nicer display
-h: print hash marks as the package archive is unpacked.

3. How to check dependencies of RPM Package before Installing


# rpm -qpR BitTorrent-5.2.2-1-Python2.4.noarch.rpm
RPM command and options
-q : Query a package
-p : List capabilities this package provides.
-R: List capabilities on which this package depends..

4. How to Install a RPM Package Without Dependencies


# rpm -ivh --nodeps BitTorrent-5.2.2-1-Python2.4.noarch.rpm
5. How to check an Installed RPM Package
Using -q option with package name, will show whether an rpm installed or not.

# rpm -q BitTorrent
6. How to List all files of an installed RPM package
To view all the files of an installed rpm packages, use the -ql (query list) with rpm command.

# rpm -ql BitTorrent

7. How to List Recently Installed RPM Packages


Use the following rpm command with -qa (query all) option, will list all the recently installed
rpm packages.

# rpm -qa --last


8. How to List All Installed RPM Packages
Type the following command to print the all the names of installed packages on your Linux system.

# rpm qa
9. How to Upgrade a RPM Package
If we want to upgrade any RPM package U (upgrade) option will be used.
One of the major advantages of using this option is that it will not only upgrade
the latest version of any package, but it will also maintain the backup of the
older package so that in case if the newer upgraded package does not run the
previously installed package can be used again.
# rpm -Uvh nx-3.5.0-2.el6.centos.i686.rpm

10. How to Remove a RPM Package


To un-install an RPM package, for example we use the package name nx, not the original package
name nx-3.5.0-2.el6.centos.i686.rpm. The -e (erase) option is used to remove package.

# rpm -evv nx
11. How to Remove an RPM Package Without Dependencies
The nodeps (Do not check dependencies) option forcefully remove the rpm package from the
system. But keep in mind removing particular package may break other working applications.

# rpm -ev --nodeps vsftpd


12. How to Query a file that belongs which RPM Package
Lets say, you have list of files and you would like to find out which package belongs to these files. For
example, the following command with -qf (query file) option will show you a file /usr/bin/htpasswd is
own by package httpd-tools-2.2.15-15.el6.centos.1.i686.

# rpm -qf /usr/bin/htpasswd

13. How to Query a Information of Installed RPM Package


Lets say you have installed an rpm package and want to know the information about the
package. The following -qi (query info) option will print the available information of the
installed package.

# rpm -qi vsftpd


14. Get the Information of RPM Package Before Installing
You have download a package from the internet and want to know the information of a package before
installing. For example, the following option -qip (query info package) will print the information of a
package sqlbuddy.

# rpm -qip sqlbuddy-1.3.3-1.noarch.rpm


15. How to Query documentation of Installed RPM Package
To get the list of available documentation of an installed package, use the following command with
option -qdf (query document file) will display the manual pages related to vmstat package.

# rpm -qdf /usr/bin/vmstat

16. How to Verify a RPM Package


Verifying a package compares information of installed files of the package against the rpm database. The
-Vp (verify package) is used to verify a package.

# rpm -Vp sqlbuddy-1.3.3-1.noarch.rpm


17. How to Verify all RPM Packages
Type the following command to verify all the installed rpm packages.

# rpm Va
18. How to Import an RPM GPG key
To verify RHEL/CentOS/Fedora packages, you must import the GPG key. To do so, execute the
following command. It will import CentOS 6 GPG key.

# rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6


19. How to List all Imported RPM GPG keys
To print all the imported GPG keys in your system, use the following command.

# rpm -qa gpg-pubkey*

20. How To rebuild Corrupted RPM Database


Sometimes rpm database gets corrupted and stops all the functionality of rpm and other
applications on the system. So, at the time we need to rebuild the rpm database and restore it with
the help of following command.

# cd /var/lib
# rm __db*
# rpm --rebuilddb
# rpmdb_verify Packages

YUM
YUM (Yellow dog Updater Modified) is an open source command-line as well as
graphical based package management tool for RPM (RedHat Package Manager)
based Linux systems. It allows users and system administrator to easily install, update,
remove or search software packages on a systems. It was developed and released by
Seth Vidal under GPL (General Public License) as an open source, means anyone can
allowed to download and access the code to fix bugs and develop customized
packages. YUM uses numerous third party repositories to install packages
automatically by resolving their dependencies issues.
Syntax
yum [options] [command] [package ...]
repository: A repository is a collection of rpms under some sort of filesystem tree. For
most purposes associated with yum, the repository will have two more important
characteristics. It has had the command createrepo run on the tree, which extracts and
encodes all of the metadata that yum relies on in order to function. Also, the tree, and is
made accessible by URL from a server (which means as one or more of
http://my.web.server/path, ftp://my.ftp.server/path, file://full/file/path to the repository
tree).

what are the drawbacks of this RPM package management and what are the advantage of YUM

S.No

RPM

YUM

If we want to install an application(Ex: apache), rpm


need to install all the packages required for this
application, these packages may vary from 1 rpm to
several rpms depending on shared rpm packages.

Install an application with single command


Ex: yum install httpd

RPM package dependencies is bit tough

YUM resolves dependencies with ease

Batch installation of applications is


possible with one command

YUM command can install number of applications


in one single command
Ex: yum install httpd vsftpd

RPM can not handle updated software


installation automatically

Does YUM install updates of the existing packages


by using
yum install upgrade

Can not connect to online repositories

Can connect to online repositories to get latest


software before installing the applications

Create Repository:
Step:1
# mount 192.168.0.254:/soft /mnt
# cd /mnt
#ls
# df Th
192.168.0.254:/soft
nfs 5.0G 3.6G 1.2G 77% /mnt
#cd /Packages
#rpm ivh vsftpd2.2.211.el6.x86_64.rpm
# cp rvf /mnt/Packages/ /var/ftp/pub/
# ls l /var/ftp/pub/
Step 2:
(i) # rpm -ivh createrepo-0.9.8-5.el6.noarch.rpm
(ii) # rpm -ivh deltarpm-3.5-0.5.20090913git.el6.x86_64.rpm
(iii) # rpm -ivh python-deltarpm-3.5-0.5.20090913git.el6.x86_64.rpm
Note : (ii) & (iii) are the dependence rpm for createrepo

To Create a repo
# createrepo .
(or)
# createrepo -v /var/ftp/pub/

Step 3
Now Crate a repository
# cd /etc/yum.repos.d/
# vim redhat.repo
[redhat]
baseurl=file:///software
enabled=1
gpgcheck=0
:wq!
Note :
enabled =1 ---> get repodata from (1 from local 0 - from web site)
gpgcheck=0 --> Key checking ( 0 - no need key, 1 - need Key)

# yum clean all


# yum clean dbcache
# yum repolist
#service vsftpd restart
#chkconfig vsftpd on

II Method for centralized yum Server creation


#ln -s /var/ftp/pub/ /var/www/html/
# vim /etc/yum.repos.d/redhat.repo
[redhat]
baseurl=ftp://127.0.0.1/pub/ (or) http://server ip/pub/
enabled=1
gpgcheck=0
:wq!

# yum clean all


# yum clean dbcache
# yum repolist
Note: if your are using yum via http please restart the httpd service.

Client server repos id configuration


# vim /etc/yum.repos.d/admin.repo
[admin]
baseurl=ftp://yum server ip/pub/ (or) http://server ip/pub/
enabled=1
gpgcheck=0
:wq!
# yum clean all
# yum clean dbcache
# yum repolist

1. Install a Package with YUM


To install a package called Firefox 14, just run the below command it will
automatically find and install all required dependencies for Firefox.
# yum install firefox
The above command will ask confirmation before installing any package on
your system. If you want to install packages automatically without asking any
confirmation, use option -y as shown in below example.
# yum -y install firefox
2. Removing a Package with YUM
To remove a package completely with their all dependencies, just run the
following command as shown below.
# yum remove firefox
Same way the above command will ask confirmation before removing a
package. To disable confirmation prompt just add option -y as shown in below.

3. Updating a Package using YUM


Lets say you have outdated version of MySQL package and you want
to update it to the latest stable version. Just run the following command
it will automatically resolves all dependencies issues and install them.
# yum update mysql
4. List a Package using YUM
Use the list function to search for the specific package with name. For
example to search for a package called openssh, use the command.
# yum list openssh
To make your search more accurate, define package name with their
version, in case you know. For example to search for a specific version
openssh-4.3p2 of the package, use the command.
# yum list openssh-4.3p2

5. Search for a Package using YUM


If you dont remember the exact name of the package, then use search
function to search all the available packages to match the name of the
package you specified. For example, to search all the packages that
matches the word .
# yum search vsftpd
6. Get Information of a Package using YUM
Say you would like to know information of a package before installing
it. To get information of a package just issue the below command.
# yum info firefox
7. List all Available Packages using YUM
To list all the available packages in the Yum database, use the below command.
# yum list | less

8. List all Installed Packages using YUM


To list all the installed packages on a system, just issue below command, it will
display all the installed packages.

# yum list installed | less


9. Yum Provides Function
Yum provides function is used to find which package a specific file
belongs to. For example, if you would like to know the name of the
package that has the /etc/httpd/conf/httpd.conf.
# yum provides /etc/httpd/conf/httpd.conf
10. Check for Available Updates using Yum
To find how many of installed packages on your system have updates
available, to check use the following command.
# yum check-update

11. Update System using Yum


To keep your system up-to-date with all security and binary package updates,
run the following command. It will install all latest patches and security
updates to your system.
# yum update
12. List all available Group Packages
In Linux, number of packages are bundled to particular group. Instead of
installing individual packages with yum, you can install particular group that
will install all the related packages that belongs to the group. For example to
list all the available groups, just issue following command.
# yum grouplist
13. Install a Group Packages
To install a particular package group, we use option as groupinstall. Fore
example, to install MySQL Database, just execute the below command.
# yum groupinstall 'MySQL Database'

14. Update a Group Packages


To update any existing installed group packages, just run the following
command as shown below.
# yum groupupdate 'DNS Name Server
15. Remove a Group Packages
To delete or remove any existing installed group from the system, just use
below command.
# yum groupremove 'DNS Name Server
16. List Enabled Yum Repositories
To list all enabled Yum repositories in your system, use following option.
# yum repolist
16. List all Enabled and Disabled Yum Repositories
The following command will display all enabled and disabled yum repositories
on the system.
# yum repolist all

17. Install a Package from Specific Repository


To install a particular package from a specific enabled or disabled repository, you must
use --enablerepo option in your yum command. For example to Install PhpMyAdmin
3.5.2 package, just execute the command.
# yum --enablerepo=epel install phpmyadmin
18. Interactive Yum Shell
Yum utility provides a custom shell where you can execute multiple commands.
19. Clean Yum Cache
By default yum keeps all the repository enabled package data in /var/cache/yum/ with
each sub-directory, to clean all cached files from enabled repository, you need to run the
following command regularly to clean up all the cache and make sure that there is
nothing unnecessary space is using. We dont want to give the output of the below
command, because we like to keep cached data as it is.
# yum clean all
20. View History of Yum
To view all the past transactions of yum command, just use the following command.
# yum history

Mount the ISO image into server


# mount /dev/sr0 /mnt
#df /mnt
#cd Packages
#rpm ivh createreporpm
#rpm ivh deltarpmrpm
#rpm ivh python-deltarpmrpm
#rpm ivh vsftpdrpm
Copy the packages into /var/ftp/pub/
#cp rvf /mnt/Packages/ /var/ftp/pub/
Note: The cp command will take a while so the -v flag will show what it is doing
Create the local repo with createrepo command
#createrepo v /var/ftp/pub/
Note: Again this will take a few minutes as it analyses all the Packages

Set up your local repository


Now you have the repo created you can use it on the local system by setting up a repo conf
file for it. Use your editor of choice (which is vi of course) to create repo
#vi /etc/yum.repos.d/rhel7.repo
[rhel7]
name=Local repo
baseurl=file:///var/ftp/pub
enabled=1
gpgcheck=0
Note: The three / is in the file URL. The enabled set to 1 so that it will not get repository in
online and it will get it from locally, gpgcheck is set to zero so that it will not look for
signatures.
Confirm the repo is now available locally
#yum clean all
#yum clean dbcache
#yum repolist

Centralized yum Server Configuration


# systemctl start vsftpd
# systemctl status vsftpd
We are going to use the default anonymous ftp configuration so the repo needs to be made
available via /var/ftp/pub .
Before all that though we have to test vsftpd is working and set up the firewall rules if
applicable.
# systemctl status firewalld
If you are not using a firewall then you can skip the commands below that allow the ftp
service
#firewall-cmd --get-default-zone
public
# firewall-cmd --query-service=ftp
no
# firewall-cmd --query-service=ftp --permanent
no

If the service is not allowed then add it both in the runtime config and the permanent
config.
# firewall-cmd --add-service=ftp
success
# firewall-cmd --add-service=ftp permanent
success
# firewall-cmd --query-service=ftp
yes
# firewall-cmd --query-service=ftp --permanent
yes
You can now test vsftp by going to a remote server and using an ftp client to login
anonymously. ( You can also test it locally ). If you dont have an ftp client you can install a
basic command line one using
#yum install ftp
You should be able to log in anonymous users and see the root directory. ( Which is
chrooted to /var/ftp/ by default).
# ftp serverX.example.com

Set up your ftp repository


#vi /etc/yum.repos.d/rhel7.repo
[ftprepo]
name=ftp
baseurl=ftp://127.0.0.1/pub
enabled=1
gpgcheck=0
Note: The three / is in the file URL. The enabled set to 1 so that it will not get repository in
online and it will get it from locally, gpgcheck is set to zero so that it will not look for
signatures.
Confirm the repo is now available through ftp
#yum clean all
#yum clean dbcache
#yum repolist

Client server repos id configuration


# vim /etc/yum.repos.d/admin.repo
[admin]
baseurl=ftp://yum server ip/pub
enabled=1
gpgcheck=0
:wq!
# yum clean all
# yum clean dbcache
# yum repolist

CRON
Cron format is a simple, yet powerful and flexible way to define time and frequency of various actions. nnCron make
active use of cron format in both classic and extended modes.
Traditional (inherited from Unix) cron format consists of five fields separated by white spaces:
<Minute> <Hour> <Day_of_the_Month> <Month_of_the_Year> <Day_of_the_Week>
nnCron can use both traditional and "enhanced" version of cron format, which has an additional (6th) field: <Year>
<Minute> <Hour> <Day_of_the_Month> <Month_of_the_Year> <Day_of_the_Week> <Year>
A user can select the format he would like to use by selecting or unselecting the Year field checkbox on General tab in
Options dialog (which can be opened by doublecliking the nnCron icon in system tray). By default, nnCron uses the
enhanced format.
The following graph shows what it consists of:
******
||||||
| | | | | +-Year
(range: 1900-3000)
| | | | +---- Day of the Week
(range: 1-7, 1 standing for Monday)
| | | +------ Month of the Year
(range: 1-12)
| | +-------- Day of the Month
(range: 1-31)
| +---------- Hour
(range: 0-23)
+------------ Minute
(range: 0-59)

Any of these 6 fields may be an asterisk (*). This would mean the entire range of possible values, i.e.
each minute, each hour, etc. In the first four fields, nnCron users can also use "nonstandard"
character ? (question mark), described here.

Any field may contain a list of values separated by commas, (e.g. 1,3,7) or a range of values (two
integers separated by a hyphen, e.g. 1-5).

After an asterisk (*) or a range of values, you can use character / to specify that values are repeated
over and over with a certain interval between them. For example, you can write "0-23/2" in Hour
field to specify that some action should be performed every two hours (it will have the same effect
as "0,2,4,6,8,10,12,14,16,18,20,22"); value "*/4" in Minute field means that the action should be
performed every 4 minutes, "1-30/3" means the same as "1,4,7,10,13,16,19,22,25,28".

In Month and Day of Week fields, you can use names of months or days of weeks abbreviated to
first three letters ("Jan,Feb,...,Dec" or "Mon,Tue,...,Sun") instead of their numeric values.

How to Add/Edit Crontab


To add or update job in crontab, use below command. It will open crontab file in editor where job
can be added/updated.
# crontab -e
By default it will edit crontab entries of current logged in user. To edit other user crontab use
command as below
# crontab -u username -e
Change EDITOR environment variable to change your default editor.
How to List Crontab
To view crontab entries of current user use following command .
# crontab -l
To view crontab entries of other user use following command .
# crontab -u username l
20 Useful Crontab Examples:
1. Schedule a cron to execute at 2am daily.
This will be useful for scheduling database backup on daily basis.
0 2 * * * /bin/sh backup.sh
are used for matching all the records.

2. Schedule a cron to execute twice a day.


Below example command will execute at 5AM and 5PM daily. You can specify multiple time stamp by comma
seprated.
0 5,17 * * * /scripts/script.sh
3. Schedule a cron to execute on every minutes.
Generally we dont require any script to execute on every minutes but in some case you may need to configure it.
* * * * * /scripts/script.sh
4. Schedule a cron to execute on every Sunday at 5 PM.
This type of cron are useful for doing weekly tasks, like log rotation etc.
0 17 * * sun /scripts/script.sh
5. Schedule a cron to execute on every 10 minutes.
If you want to run your script on 10 minutes interval, can configure like below. These type of crons are useful for
monitoring.
*/10 * * * * /scripts/monitor.sh
*/10: means to on each 10 minutes. Same as if you want to execute on every 5 minutes use */5.
6. Schedule a cron to execute on selected months.
Some times we required to schedule a task to be execute for selected months only. Below example script will run on
January, May and August months.
* * * jan,may,aug * /script/script.sh

7. Schedule a cron to execute on selected days.


If you required to schedule a task to be execute for selected days only. Below example will run on each Sunday and Friday at
5PM .
0 17 * * sun,fri /script/script.sh
8. Schedule a cron to execute on first sunday of every month.
To schedule a script to execute a script on first sunday only is not possible by time parameter, But we can use condition in
command fields to do it.
0 2 * * sun [ $(date +\%d) -le 07 ] && /script/script.sh
9. Schedule a cron to execute on every four hours.
If you want to run script on 4 hours interval. It can be configure like below.
0 */4 * * * /scripts/script.sh
10. Schedule a cron to execute twice on every Sunday and Monday.
To schedule a task to execute twice on Sunday and Monday only. Use following settings to do it.
0 4,17 * * sun,mon /scripts/script.sh
11. Schedule a cron to execute on every 30 Seconds.
To schedule a task to exectue on every 30 seconds is not possible by time parameters, But it can be done by schedule same cron
twice like below.
* * * * * /scripts/script.sh
* * * * sleep 30; /scripts/script.sh
12. Schedule a multiple tasks in single cron.
To configure multiple tasks with single cron, Can be done by seprating tasks by semicolon ( ; ).
* * * * * /scripts/script.sh; /scripts/scrit2.sh

12. Schedule a multiple tasks in single cron.


To configure multiple tasks with single cron, Can be done by separating tasks by semicolon ( ; ).
* * * * /scripts/script.sh; /scripts/scrit2.sh
13. Schedule a tasks to execute on yearly ( @yearly ).
@yearly timestamp is similar to 0 0 1 1 *. It will execute task on first minute of every year, It may useful to send
new year greetings :)
@yearly /scripts/script.sh
14. Schedule a tasks to execute on monthly ( @monthly ).
@monthly timestamp is similar to 0 0 1 * *. It will execute task on first minute of month. It may useful to do
monthly tasks like pay the bills and invoicing to customers.
@monthly /scripts/script.sh
15. Schedule a tasks to execute on Weekly ( @weekly ).
@weekly timestamp is similar to 0 0 1 * *. It will execute task on first minute of month. It may useful to do weekly
tasks like cleanup of system etc.
@weekly /bin/script.sh
16. Schedule a tasks to execute on daily ( @daily ).
@daily timestamp is similar to 0 0 * * *. It will execute task on first minute of every day, It may useful to do daily
tasks.
@daily /scripts/script.sh

17. Schedule a tasks to execute on hourly ( @hourly ).


@hourly timestamp is similar to 0 * * * *. It will execute task on first minute of every hour, It may usefull to do
hourly tasks.
@hourly /scripts/script.sh
18. Schedule a tasks to execute on system reboot ( @reboot ).
@reboot is usefull for those tasks which you want to run on your system startup. It will be same as system startup
scripts. It is usefull for starting tasks in background automatically.
@reboot /scripts/script.sh
19. Redirect Cron Results to specified email account.
By default cron sends details to current user where cron is scheduled. If you want to redirect it to your other account,
can be done by setup MAIL variable like below
# crontab -l
MAIL=bob
0 2 * * * /script/backup.sh
20. Taking backup of all crons to plain text file.
I recommend to keep backup of all jobs entry in a file. It this is a way to recover crons if you lost them.
Check current scheduled cron:
# crontab -l
MAIL=rahul
0 2 * * * /script/backup.sh

# crontab -l
MAIL=rahul
0 2 * * * /script/backup.sh
Backup cron to text file:
# crontab -l > cron-backup.txt
# cat cron-backup.txt
MAIL=rahul
0 2 * * * /script/backup.sh
Removing current scheduled cron:
# crontab -r
# crontab -l
no crontab for root
Restore crons from text file:
# crontab cron-backup.txt
# crontab -l
MAIL=rahul
0 2 * * * /script/backup.sh

AT
While working on Linux systems we preferred crontab for scheduling jobs generally. There are another utility
command is very useful for scheduling one time tasks. It reads commands from standard input or
script/file which can be executed later once. But we cant use at command for any recurring tasks. For
recurring tasks use Linux crontab.
At command can be useful for shutdown system at specified time, Taking one time backup, sending email as
reminder at specified time etc. This article will help you to understand the working of at command with
useful examples.
Commands used with at:
at : execute commands at specified time.
atq : lists the pending jobs of users.
atrm : delete jobs by their job number.
1. Schedule first job using at command
Below example will schedule ls l command to be executed on next 9:00 AM once.
# at 9:00 AM
at> ls l
at> ^d
job 3 at 20130323 09:00
Use ^d to exit from at prompt.
2. List the scheduled jobs using atq
When we list jobs by root account using atq , it shows all users jobs in result. But if we execute it from non
root account, it will show only that users jobs.
# atq
3
5
1

20130323 09:00 a root


20130323 10:00 a rahul
20130323 12:00 a root

Fields description:
First filed: job id
Second filed: Job execution date
third filed: Job execution time
Last field: User name, under which job is scheduled.
3. Remove scheduled job using atrm
You can remove any at job using atrm using their job id.
# atrm 3
# atq
5
20130323 10:00 a rahul
1
20130323 12:00 a root
4. Check the content of scheduled at job
atq command only shows the list of jobs but if you want to check what script/commands are scheduled with that task, below
example will help you.
# at c 5
In above example 5 is the job id.
Examples of at Command:
Example 1: Schedule task at coming 10:00 AM.
# at 10:00 AM
Example 2: Schedule task at 10:00 AM on coming Sunday.
# at 10:00 AM Sun
Example 3: Schedule task at 10:00 AM on coming 25th July.
# at 10:00 AM July 25
Example 4: Schedule task at 10:00 AM on coming 22nd June 2015.
# at 10:00 AM 6/22/2015
# at 10:00 AM 6.22.2015

Example 5: Schedule task at 10:00 AM on same date at next month.


# at 10:00 AM next month
Example 6: Schedule task at 10:00 AM tomorrow.
# at 10:00 AM tomorrow
Example 7: Schedule task at 10:00 AM tomorrow.
# at 10:00 AM tomorrow
Example 8: Schedule task to execute just after 1 hour.
# at now + 1 hour
Example 9: Schedule task to execute just after 30 minutes.
# at now + 30 minutes
Example 10: Schedule task to execute just after 1 and 2 weeks.
# at now + 1 week
# at now + 2 weeks
Example 11: Schedule task to execute just after 1 and 2 years.
# at now + 1 year
# at now + 2 years
Example 12: Schedule task to execute at mid night.
# at midnight
Above job will execute on next 12:00 AM

NTP
NTP Server
PORT NUMBER: 123
Definition: In computer networking, NTP is a system to synchronize time
of day computer clocks across the Internet.
a) The NTP system is based on Internet time servers, computers with
access to atomic clocks such as those operated by the U.S.
government. These NTP servers run a software service that provides
the clock's time of day to client computers over UDP port 123. NTP
supports a hierarchy of multiple server levels to handle a large load of
client requests.
b) The protocol includes algorithms to accurately adjust the time of day
being reported to account for Internet network transmission delays.
c) Computers running Windows, Mac OS X and Linux operating
systems can be configured to use an NTP server. Starting with Linux
OS, for example, on terminal type system-config-date option
contains an NTP server, which allows choosing an NTP server and
turning time synchronization on or off.

NTP CLIENT
USING TEXT METHOD:
# yum install chrony* y
# vim /etc/chrony.conf
server classroom.example.com iburst
# systemctl restart chronyd.service
# firewallcmd permanent addservice=ntp
# firewallcmd reload
# chronyc sources v
# timedatectl
# chronyc tracking

USING GRAPHICAL METHOD:


# yum install systemconfigdate y
# systemconfigdate
Synchronize date and time over the network>click it
NTP Servers
> PRESS add and type into box
classroom.example.com[OR]172.25.254.254 > Give Enter
Advanced options
speedup initial synchronization > Click this& apply
# firewallcmd permanent addservice=ntp
# firewallcmd reload
# chronyc sources v
# timedatectl
# chronyc tracking

LDAP
LDAP PORT NUMBER: 389
LDAPS PORT NUMBER: 636
Global Catalog is available by default on ports 3268, and 3269 for
LDAPS.
LDAP stands for Lightweight Directory Access Protocol. As the name
suggests, it is a lightweight protocol for accessing directory services,
specifically X.500based directory services. LDAP runs over TCP/IP or
other connection oriented transfer services.
What kind of information can be stored in the directory? The LDAP
information model is based on entries. An entry is a collection of
attributes that has a globallyunique Distinguished Name (DN). The DN
is used to refer to the entry unambiguously. Each of the entry's
attributes has a type and one or more values. The types are typically
mnemonic strings, like "cn" for common name, or "mail" for email
address. The syntax of values depend on the attribute type.

LDAP CLIENT
USING GRAPHICAL METHOD:
# yum install sssd* authconfig* autofs* y
# systemctl enable sssd.service
# systemctl start sssd.service
>sssd is not active now
# authconfiggtk
User account database
: LDAP
Ldap Search base DN
: dc=example,dc=com
Ldap server
: ldaps://classroom.example.com
Use TLS to encrypted connection
>Tick it
>Click Download certicficate
url: http://classroom.example.com/pub/EXAMPLECACERT
Authendication method : LDAP password
# systemctl restart sssd.service
# firewallcmd permanent addservice=sssd
# firewallcmd reload

AUTO MOUNT:
# vim /etc/auto.master
/misc /etc/auto.misc
/home/guests /etc/auto.misc
# vim /etc/auto.misc
ldapuserX

rw,soft,intr classroom.example.com:/home/guests/ldapuserX

# systemctl restart autofs.service


# firewallcmd permanent addservice=autofs
# firewallcmd reload
# su ldapuserX

USING TEXT METHOD:


# authconfigtui
Authentication Configuration

User Information
Authentication
[ ] Cache Informaon
[*] Use MD5 Passwords
[*] Use LDAP
[*] Use Shadow Passwords
[ ] Use NIS
[*] Use LDAP Authentication
[ ] Use IPAv2
[ ] Use Kerberos
[ ] Use Winbind
[ ] Use Fingerprint reader
[ ] Use Winbind Authentication
[*] Local authorization is sufficient

Cancel
Next

>PRESS NEXT

[*] Use TLS

Server: ldaps://classroom.example.com

Base DN: dc=example,dc=com

> PRESS OK
> PRESS OK
# cd /etc/openldap/cacerts/
# wget http://172.25.254.100/pub/EXAMPLECACERT
# systemctl restart sssd.service
# firewallcmd permanent addservice=sssd
# firewallcmd reload
# getent passwd ldapuserX

AUTO MOUNT:
# vim /etc/auto.master
/misc /etc/auto.misc
/home/guests /etc/auto.misc
# vim /etc/auto.misc
ldapuserX

rw,soft,intr classroom.example.com:/home/guests/ldapuserX

# systemctl restart autofs.service


# firewallcmd permanent addservice=autofs
# firewallcmd reload
# su ldapuserX

Virtualization
Virtualization is the creation of a virtual (rather than actual) version of
something, such as an operating, a server, a storage device or network
resources.
Why should we use virtualization
Consolidation It means combining multiple software workloads on one
computer system. You can run various virtual machines in order to save
money and power (electricity).
Testing You can test various configuration. You can create less resource
hungry and low priority virtual machines (VM). Often, I test new Linux
distro inside VM. This is also good for students who wish to learn new
operating systems and programming languages / database without making
any changes to working environment. At my work place I give developers
virtual test machines for testing and debugging their software.
Security and Isolation If mail server or any other app gets cracked, only
that VM will be under control of the attacker. Also, isolation means
misbehaving apps (e.g. memory leaks) cannot bring down whole server

open Source Linux Virtualization Software


1. Openvz
2. Xen
3. Kernelbased Virtual Machine (KVM)
4. LinuxVserver
5. VirtualBox
6. Bochs
7. User Mode Linux (UML)
Proprietary Linux Virtualization Software
1. VMware ESX Server and VMWare Server
2. Citrix XenServer, Oracle VM, Sun xVM
3. Parallels Virtuozzo Containers

KernelBased
Virtual Machine (KVM)

A kernelbased virtual machine (KVM) is a virtualization infrastructure built for


Linux OS and designed to operate on x86based processor architecture.
KVM is developed by Red Hat Corporation to provide a virtualization solution and
services on the Linux operating system platform. KVM is designed over the primary
Linux OS kernel.
Explains KernelBased Virtual Machine (KVM)
KVM is a type of hypervisor that enables, emulates and provides for the creation
of virtual machines on operating systems. These machines are built on top of the
Linux kernel, using operating systems such as Linux, Ubuntu and Fedora. KVM can
be installed on all x86 processors and provide separate instruction set extensions
for Intel and AMD processors.
KVM supports multiple different guest operating system images including Linux
Kernel, Windows, BSD and Solaris. It also allocates separate virtualized computing
resources for each virtual machine such as the processor, storage, memory, etc.

KVM Bridge Setup


Bridging requires the bridgeutils package to be installed on the server. To check if it's installed, do the
following:
#rpm q bridgeutils
If you get an output it's installed, if not, it needs installing:
#yum install bridgeutils
Before setting up your bridge, the contents of /etc/sysconfig/networkscripts/ifcfgeth0 will look like the
following:
DEVICE=eth0
TYPE=ETHERNET
NAME=System eth0
BOOTPROTO=static
HWADDR=00:27:0E:09:0C:B2
IPADDR=192.168.0.254
NETMASK=255.255.255.0
ONBOOT=yes

To back up your current ifcfgeth0 before modification:


1. Run the following command:
#cp /etc/sysconfig/networkscripts/ifcfgeth0 /etc/sysconfig/networkscripts/backup
ifcfgeth0
2.Create the bridge file:
#vim /etc/sysconfig/networkscripts/ifcfgbr0
3. Copy parts of ifcfgeth0 to it:
DEVICE=br0
TYPE=Bridge
BOOTPROTO=static
BROADCAST=192.168.0.255
IPADDR=192.168.0.254
NETMASK=255.255.255.0
ONBOOT=yes

4. Save that file and edit ifcfgeth0:


#vim /etc/sysconfig/networkscripts/ifcfgeth0
5. Remove the networking parts and specify the bridge:
DEVICE=eth0
HWADDR=00:27:0E:09:0C:B2
ONBOOT=yes
BRIDGE=br0
6. Bridge is setup. Make sure that the changes are correct and restart the networking:
#/etc/init.d/network restart
7. Once it's restarted you see the new bridge using the ifconfig command:
# ifconfig

To check whether your CPU supports the hardware virtualization, execute the
following command.
# egrep '(vmx|svm)' /proc/cpuinfo
Install KVM packages using your distro specific package management tool (for
example, yum on RedHat and CentOS).
# yum install kvm
Once you install the main kvm package, install the following KVM related packages
that will help you to manage the VMs on your system.
# yum install qemukvm pythonvirtinst libvirt libvirtpython virtmanager libguestfs
tools
virtinstall tool is used to create the VM. This tool can be used in both interactive or
noninteractive mode.
service libvirtd start

In the following example, I passed all the required values to create an VM as


command line parameters to the virtinstall command.
# virtinstall \
n myRHELVM1 \
description "Test VM with RHEL 6" \
ostype=Linux \
osvariant=rhel6 \
ram=2048 \
vcpus=2 \
disk path=/var/lib/libvirt/images/myRHELVM1.img,bus=virtio,size=10 \
graphics none \
cdrom /var/rhelserver6.5x86_64dvd.iso (or)

location=http://.com/pub/rhel6/x86_64/ \
network bridge:br0

In the above virt-install command:


n Name of your virtual machine
description Some valid description about your VM. For example: Application server, database
server, web server, etc.
os-type OS type can be Linux, Solaris, Unix or Windows.
os-variant Distribution type for the above ostype. For example, for linux, it can be rhel6, centos6,
ubuntu14, suse11, fedora6 , etc. For windows, this can be win2k, win2k8, win8, win7
ram Memory for the VM in MB
vcpu Total number of virtual CPUs for the VM.
disk path=/var/lib/libvirt/images/myRHELVM1.img,bus=virtio,size=10 Path where the VM image
files is stored. Size in GB. In this example, this VM image file is 10GB.
graphics none This instructs virtinstall to use a text console on VM serial port instead of graphical
VNC window. If you have the xmanager set up, then you can ignore this parameter.
cdrom Indicates the location of installation image. You can specify the NFS or http installation
location (instaed of cdrom). For example, location=http://.com/pub/rhel6/x86_64/
network bridge:br0 This example uses bridged adapter br0. It is also possible to create your own
network on any specific port instead of bridged adapter. If you want to use the NAT then use
something like below for the network parameter with the virtual network name known as
VMnetwork1. All the network configuration files are located under /etc/libvirt/qemu/networks/
for the virtual machines. For example: network network=VMnetwork1

KVM Migrations
Creating a Copy of the Virtual Server
To find the correct LV that needs being backed up, you can use lvdisplay in
SSH on the source node:
# lvdisplay
Shutdown the source VPS either using SolusVM or the command line:
#virsh shutdown <servername>
Create the backup:
#dd if=/dev/vps/kvm101_img | gzip | dd of=/home/kvm101_backup.gz
bs=4096
Transfer to the Destination Node
On the destination node we need to create a logical volume the same size
as the original one:
#lvcreate n kvm101_img size 10G /dev/vps
Transfer the backup to the destination server:
#scp C /home/kvm101_backup.gz root@remote.server.com:/home/

Restoring the Virtual Server


Once you have transferred the backup of your VPS to the
destination server you can restore the backup to the new
LV:
#dd if=/home/kvm101_backup.gz | gzip d | dd
of=/dev/vps/kvm101_img bs=4096

VNC
Virtual Network Computing
VNC by default uses TCP port 5900+N, where N is
the display number (usually :0 for a physical
display). Several implementations also start a
basic HTTP server on port 5800+N to provide a
VNC viewer as a Java applet, allowing easy
connection through any Javaenabled web
browser.

VNC 6
SERVER:
# yum install tigervnc* y
# vim /etc/sysconfig/vncservers
GO LAST LINE
VNCSERVERS="2:username1 3:username2"
# useradd username1
# useradd username2
# passwd username1
# passwd username2
# su username1
$ vncpasswd
$ logout
# su username2
$ vncpasswd
$ logout
# service vncserver restart

CLIENT:
# yum install tigervnc* y
# vncviewer
VNC server: serverip:2 [OR] 3
Password:
[OR]
# vncviewer SERVERIP:2 [OR] 3
IF YOU WANT TO TAKE ROOT IN VNC DO FOLLOWING STEPS IN SERVER:
GO SYSTEM > PREFERENCES > REMOTE DESKTOP
TICK ALLOW OTHER USERS TO VIEW YOUR DESKTOP ETC.,
WE CAN SET THE PASSWORD FOR AUTHENTICATION.

VNC 7
SERVER:
# yum install tigervnc* y
# systemctl enable vncserver@.service
# vim /etc/sysconfig/vncservers
THIS FILE HAS BEEN REPLACED BY
/lib/systemd/system/vncserver@.service
# cp rvf /lib/systemd/system/vncserver@.service
/lib/systemd/system/vncserver_username1@.service
# cp rvf /lib/systemd/system/vncserver@.service
/lib/systemd/system/vncserver_username2@.service

# vim /lib/systemd/system/vncserver_username1@.service
LINE NO: 40 AND 41
REPLACE <USER> AS USERNAME
# vim /lib/systemd/system/vncserver_username2@.service
LINE NO: 40 AND 41
REPLACE <USER> AS USERNAME
#
#
#
#

useradd username1
useradd username2
passwd username1
passwd username2

#
$
$
#
$
$
#
#
#
#
#
#
#

su username1
vncpasswd
logout
su username2
vncpasswd
logout
systemctl daemonreload
systemctl enable vncserver_username1@.service
systemctl enable vncserver_username2@.service
systemctl restart vncserver_username1@:1.service
systemctl restart vncserver_username2@:2.service
firewallcmd permanent addservice=vncserver
firewallcmd reload

CLIENT:
# yum install tigervnc* y
# vncviewer
VNC server: serverip:2 [OR] 3
Password:
[OR]
# vncviewer SERVERIP:2 [OR] 3

TELNET
Telnet( Text-based network):

port-23

Telnet is a simple, textbased network protocol that is used for accessing


remote computers over TCP/IP networks like the Internet.

TELNET 6
SERVER:
#yum install telnet telnetserver y
#vi /etc/xinetd.d/telnet
disable

= no

#vim /etc/securetty
pts/1
pts/2
pts/3
etc.,
#vi /etc/sysconfig/iptables
A INPUT p tcp m state state NEW dport 23 j ACCEPT

#useradd user1
#echo "redhat" | passwd stdin user1
#service xinetd start
#chkconfig telnet on
#chkconfig xinetd on

CLIENT:
#yum install telnet y
#telnet ServerIP
[OR]
#telnet ServerIP portNo(using this step we can know this port is opened or
not)
#username
#password

TELNET 7
SERVER:
#yum install telnet telnetserver y
#systemctl enable telnet.service
#systemctl start telnet.service
#vi /etc/xinetd.d/telnet
disable

= no

#vim /etc/securetty
pts/1
pts/2
pts/3
etc.,

[Optional]

#useradd user1
#echo "redhat" | passwd stdin user1
#systemctl restart telnet.service
#firewallcmd permanent addport=23/tcp
#firewallcmd reload
CLIENT:
#yum install telnet y
#telnet ServerIP
[OR]
#telnet ServerIP portNo(using this step we can know this port is opened or not)
#username
#password

FTP
FTP PORT NUMBER:20
SFTP PORT NUMBER: 21
Definition: FTP allows you to transfer files between two
computers on the Internet. FTP is a simple network protocol
based on Internet Protocol and also a term used when
referring to the process of copying files when using FTP
technology.
FTP supports two modes of data transfer: plain text (ASCII),
and binary. You set the mode in the FTP client. A common
error when using FTP is attempting to transfer a binary file
(such as a program or music file) while in text mode,
causing the transferred file to be unusable.
Also Known As: File Transfer Protocol

FTP Server Setup using vsftp on RHEL 6


Package installation and startup
Downloading Configuration
Uploading Configuration
FTP Server User Management
Log file & Banner
Access Control

Client Server2

Client Server1

FTP Server

Client Mobile2

Client Mobile1

Client System1

Client System2

Package installation & service startup


1) Package installation
Vsftpd-3.0.2-9.el7.x86_64
2) Service startup
#service vsftpd start
3) Service startup checking
#ps -ef | grep vsftpd
#netstat -nat | grep 21
4) Runlevel registration
#chkconfig vsftpd on
#chkconfig --list vsftpd

Downloading Configuration
1) Configuration file
/etc/vsftpd/vsftpd.conf
2) Downloading configuration
anonymous_enable=YES
// anonymous users
local_enable=YES
// local users
write_enable=YES
3) Service restart
#service vsftpd restart
4) Testing on Linux
#lftp ftpserver
#lftp u username ftpserver
5) Testing on windows
Use FileZilla tools

Step 3 Uploading Configuration


1) Configuration file
/etc/vsftpd/vsftpd.conf
2) Uploading Configuration
anon_upload_enable=YES
anon_mkdir_write_enable=YES
chown_uploads=YES
chown_username=root
anon_umask=077
3) Incoming directory
#mkdir /var/ftp/incoming
#chown root.ftp /var/ftp/incoming
#chmod 773 /var/ftp/incoming
4) Service restart
#service vsftpd restart
5) Testing on Linux
#lftp ftpserver
#lftp u username ftpuser
6) On windows
Use Filezilla tools

// 600

Step 4 FTP Server User Management


1) /etc/vsftpd/ftpusers
#Users that are not allowed to login via ftp
/etc/vsftpd/users_list
2) In /etc/vsftpd/vsftpd.conf
userlist_deny=NO
// only allow users in this file
userslist_deny=YES
// never allow users in this file
3) chroot ( Change root directory)
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd/chroot_list

Step 5 Log file & Banner


1) /var/log/xferlog
xferlog_enable=YES
xferlog_file=/var/log/xferlog
xferlog_std_format=YES or NO
YES
-> /var/log/xferlog
NO-> /var/log/vsftpd.log
2) Login banner (Security for version information)
/etc/vsftpd/vsftpd.conf
ftpd_banner=FTP Server Ready!!!
3) Directory display
Dirmessage_enable=YES
Message_file=.message

Step 6 Access Control


1) Access Control using tcp_wraper
Tcp_wrapers=YES
/etc/hosts.allow
/etc/hosts.deny
Vsftpd:192.168.0.20/255.255.255.0.0:twist /bin/cat /var/ftp/.denied
2) Connection Restrictions
Max_clients=10
//client to access simultaneously
Max_per_ip=10
//one IP address can have 10 concurrent
connections
3) Limits for transfer rate
Anon_max_rate
//maximum rate in bytes per second for anonymous
Local_max_rate
//maximum rate in bytes per second for local users

FTP
SERVER:
# yum install ftp.x86_64 vsftpd.x86_64 y
# systemctl enable vsftpd.service
# systemctl start vsftpd.service
# vim /etc/vsftpd/vsftpd.conf
LINE NO: 12,16 (CHECK)
anonymous_enable=YES (IF YOU WANT TO DENY ANONYMOUS USER LOGIN,
REPLACE "YES" TO "NO")
local_enable=YES
LINE NO: 125,126 (CHECK)
pam_service_name=vsftpd
userlist_enable=YES
# getsebool a | grep ftp

# setsebool P ftp_home_dir=on (FOR USER HOME DIRECTORY SHARING)


# setsebool P ftpd_full_access=on (FOR FULL ACCESS)
# vim /etc/vsftpd/user_list
[NOTE: userlist_deny=YES (default), never allow users in this file and do not
even prompt for a password.
The default vsftpd pam config also checks /etc/vsftpd/ftpusers]
# vim /etc/vsftpd/ftpusers
[NOTE: The entry of Users that are not allowed to login via ftp]
# cd /var/ftp/pub/
# cat [OR] touch (CREATE SOME FILES)
# systemctl restart vsftpd.service
# firewallcmd permanent addservice=ftp
# firewallcmd reload

CLIENT:
# yum install ftp.x86_64 vsftpd.x86_64 y
# ftp 172.25.X.11
Name (172.25.X.11:root):
Password:
ftp>
.
.
[HERE WE CAN USE PUT AND GET COMMAND FOR
UPLOAD AND DOWNLOAD]
.
ftp>bye

SELINUX CONCEPT

SELINUX
CONFIGURATION

HARD LINK &


SOFT LINK
Creating a Hard Link:
A hard link essentially creates a mirror copy of the original linked file. Each
hard linked file is assigned the same inode value as the original, therefore
they both reference the same physical file location. Any changes to the
data in either file is reflected in the other.
Hard links are beneficial as they are more flexible and remain linked even
if the original or linked files are moved throughout the file system,
although hard links are unable to cross different file systems. Lastly, hard
links can only be assigned to files and not directories as to avoid recursive
loops.
In the following example, the original file and hard linked file point to the
same inode value of 101.
To configure a hard link, issue
the following command
ln [original filename] [link name]
#ln original_file new_hardlink_file

Creating a Soft Link (also known as Symbolic Link):


A soft link is similar to the file shortcut feature which is used in Windows
Operating systems. Each soft linked file contains a separate inode value that
points to the original file. As similar to hard links, any changes to the data in
either file is reflected in the other.
Soft links are beneficial as they can be linked across different file systems,
although if the original file is deleted or moved, the soft linked file will not
work correctly (called hanging link).
In the following example, the softlink points to the location of the original file.
Notice that both files contain different inode values.
To configure a soft link, issue the following command ln s [original filename]
[link name]
#ln -s original_file new_softlink_file

Hard Links:

Issue the ln [original filename] [link name] command to create a hard link
Original File and Hard Linked file contain the same inode value
Creates a mirror copy of the file
Any changes to either original file or hard linked file are reflected in the other file
Benefit more flexible and remain linked if either the original or hard linked file is
moved
Negative unable to cross different file systems

Soft Links:

Issue the ln -s [original filename] [link name] command to create a soft link
Similar to shortcut feature in Windows Operating system
Original File and Hard Linked file contain different inode values
Each soft link file points to the original files inode
Any changes to either original file or soft linked file are reflected in the other file
Benefit soft linked file can cross different file systems
Negative if original file is deleted or moved, the soft link is broken (hanging link)

How to fix a hanging link:


To fix a hanging link, you must first determine the original file that the soft link
pointed to. Issue the command ls l command to verify this file the broken link will
typically be indicated by red colored text. In this example, the file original_file has
been moved which resulted in the associated soft link to become broken.
#ls l
new_softlink_file original_file
Next, you must determine where the new file is located. Issue the command find name
"filename" to locate the desired file:
#find -iname orifinal_file
Lastly, remove the current soft link by issuing the unlink [link name] command and re
configure the new soft link location with the following commands notice when you
issue the unlink command, the soft link file disappears:
#unlink new_softlink_file
#ls -l
#ln -s Folder_1/original_file new_softlink_file
#ls -l

IPTABLES
# Modify this file accordingly for your specific requirement.
# http://www.thegeekstuff.com
# 1. Delete all existing rules
iptables F
# 2. Set default chain policies
iptables P INPUT DROP
iptables P FORWARD DROP
iptables P OUTPUT DROP
# 3. Block a specific ipaddress
#BLOCK_THIS_IP="x.x.x.x"
#iptables A INPUT s "$BLOCK_THIS_IP" j DROP
# 4. Allow ALL incoming SSH
#iptables A INPUT i eth0 p tcp dport 22 m state state NEW,ESTABLISHED j ACCEPT
#iptables A OUTPUT o eth0 p tcp sport 22 m state state ESTABLISHED j ACCEPT
# 5. Allow incoming SSH only from a sepcific network
#iptables A INPUT i eth0 p tcp s 192.168.200.0/24 dport 22 m state state NEW,ESTABLISHED j
ACCEPT
#iptables A OUTPUT o eth0 p tcp sport 22 m state state ESTABLISHED j ACCEPT

# 6. Allow incoming HTTP


#iptables A INPUT i eth0 p tcp dport 80 m state state NEW,ESTABLISHED j ACCEPT
#iptables A OUTPUT o eth0 p tcp sport 80 m state state ESTABLISHED j ACCEPT
# Allow incoming HTTPS
#iptables A INPUT i eth0 p tcp dport 443 m state state NEW,ESTABLISHED j ACCEPT
#iptables A OUTPUT o eth0 p tcp sport 443 m state state ESTABLISHED j ACCEPT
# 7. MultiPorts (Allow incoming SSH, HTTP, and HTTPS)
iptables A INPUT i eth0 p tcp m multiport dports 22,80,443 m state state NEW,ESTABLISHED j ACCEPT
iptables A OUTPUT o eth0 p tcp m multiport sports 22,80,443 m state state ESTABLISHED j ACCEPT
# 8. Allow outgoing SSH
iptables A OUTPUT o eth0 p tcp dport 22 m state state NEW,ESTABLISHED j ACCEPT
iptables A INPUT i eth0 p tcp sport 22 m state state ESTABLISHED j ACCEPT
# 9. Allow outgoing SSH only to a specific network
#iptables A OUTPUT o eth0 p tcp d 192.168.101.0/24 dport 22 m state state NEW,ESTABLISHED j
ACCEPT
#iptables A INPUT i eth0 p tcp sport 22 m state state ESTABLISHED j ACCEPT
# 10. Allow outgoing HTTPS
iptables A OUTPUT o eth0 p tcp dport 443 m state state NEW,ESTABLISHED j ACCEPT
iptables A INPUT i eth0 p tcp sport 443 m state state ESTABLISHED j ACCEPT

# 11. Load balance incoming HTTPS traffic


#iptables A PREROUTING i eth0 p tcp dport 443 m state state NEW m nth counter 0 every 3
packet 0 j DNAT todestination 192.168.1.101:443
#iptables A PREROUTING i eth0 p tcp dport 443 m state state NEW m nth counter 0 every 3
packet 1 j DNAT todestination 192.168.1.102:443
#iptables A PREROUTING i eth0 p tcp dport 443 m state state NEW m nth counter 0 every 3
packet 2 j DNAT todestination 192.168.1.103:443
# 12. Ping from inside to outside
iptables A OUTPUT p icmp icmptype echorequest j ACCEPT
iptables A INPUT p icmp icmptype echoreply j ACCEPT
# 13. Ping from outside to inside
iptables A INPUT p icmp icmptype echorequest j ACCEPT
iptables A OUTPUT p icmp icmptype echoreply j ACCEPT
# 14. Allow loopback access
iptables A INPUT i lo j ACCEPT
iptables A OUTPUT o lo j ACCEPT
# 15. Allow packets from internal network to reach external network.
# if eth1 is connected to external network (internet)
# if eth0 is connected to internal network (192.168.1.x)
iptables A FORWARD i eth0 o eth1 j ACCEPT

# 16. Allow outbound DNS


#iptables A OUTPUT p udp o eth0 dport 53 j ACCEPT
#iptables A INPUT p udp i eth0 sport 53 j ACCEPT
# 17. Allow NIS Connections
# rpcinfo p | grep ypbind ; This port is 853 and 850
#iptables A INPUT p tcp dport 111 j ACCEPT
#iptables A INPUT p udp dport 111 j ACCEPT
#iptables A INPUT p tcp dport 853 j ACCEPT
#iptables A INPUT p udp dport 853 j ACCEPT
#iptables A INPUT p tcp dport 850 j ACCEPT
#iptables A INPUT p udp dport 850 j ACCEPT
# 18. Allow rsync from a specific network
iptables A INPUT i eth0 p tcp s 192.168.101.0/24 dport 873 m state state NEW,ESTABLISHED j ACCEPT
iptables A OUTPUT o eth0 p tcp sport 873 m state state ESTABLISHED j ACCEPT
# 19. Allow MySQL connection only from a specific network
iptables A INPUT i eth0 p tcp s 192.168.200.0/24 dport 3306 m state state NEW,ESTABLISHED j
ACCEPT
iptables A OUTPUT o eth0 p tcp sport 3306 m state state ESTABLISHED j ACCEPT
# 20. Allow Sendmail or Postfix
iptables A INPUT i eth0 p tcp dport 25 m state state NEW,ESTABLISHED j ACCEPT
iptables A OUTPUT o eth0 p tcp sport 25 m state state ESTABLISHED j ACCEPT

# 21. Allow IMAP and IMAPS


iptables A INPUT i eth0 p tcp dport 143 m state state NEW,ESTABLISHED j ACCEPT
iptables A OUTPUT o eth0 p tcp sport 143 m state state ESTABLISHED j ACCEPT
iptables A INPUT i eth0 p tcp dport 993 m state state NEW,ESTABLISHED j ACCEPT
iptables A OUTPUT o eth0 p tcp sport 993 m state state ESTABLISHED j ACCEPT
# 22. Allow POP3 and POP3S
iptables A INPUT i eth0 p tcp dport 110 m state state NEW,ESTABLISHED j ACCEPT
iptables A OUTPUT o eth0 p tcp sport 110 m state state ESTABLISHED j ACCEPT
iptables A INPUT i eth0 p tcp dport 995 m state state NEW,ESTABLISHED j ACCEPT
iptables A OUTPUT o eth0 p tcp sport 995 m state state ESTABLISHED j ACCEPT
# 23. Prevent DoS attack
iptables A INPUT p tcp dport 80 m limit limit 25/minute limitburst 100 j ACCEPT
# 24. Port forwarding 422 to 22
iptables t nat A PREROUTING p tcp d 192.168.102.37 dport 422 j DNAT to 192.168.102.37:22
iptables A INPUT i eth0 p tcp dport 422 m state state NEW,ESTABLISHED j ACCEPT
iptables A OUTPUT o eth0 p tcp sport 422 m state state ESTABLISHED j ACCEPT

# 25. Log dropped packets


iptables N LOGGING
iptables A INPUT j LOGGING
iptables A LOGGING m limit limit 2/min j LOG logprefix "IPTables Packet
Dropped: " loglevel 7
iptables A LOGGING j DROP