Thursday, June 2, 2016

how to use systemctl command in RHEL7 and Centos 7 ?

systemctl command with all possible options rhel7 and centos7

systemctl is a command available in new version of Linux. Systemctl is used to control the systemd and service manager. To control services we have to use lot many options along with systemctl command. It is changed dramatically in new version of Linux. In this article we are going to explore as many possible ways as to use systemctl command in Linux.

Let’s start with checking the service status.

 Service Status Check and show service units
below is the command used to verify the service status
[root@Linuxforfreshers ~]# systemctl status network.service
network.service - LSB: Bring up/down networking
   Loaded: loaded (/etc/rc.d/init.d/network)
   Active: active (exited) since Thu 2016-04-28 13:39:38 IST; 32min ago
  Process: 5239 ExecReload=/etc/rc.d/init.d/network reload (code=killed, signal=TERM)
  Process: 5313 ExecStart=/etc/rc.d/init.d/network start (code=exited, status=0/SUCCESS)
[root@linuxforfreshers ~]# systemctl show crond.service
Id=crond.service
Names=crond.service
Requires=basic.target
Wants=system.slice
Conflicts=shutdown.target
Before=shutdown.target

Verify service is active and enabled

If service is active it means service is running without any issues.  As a example we verify web service is running OR not.
[root@Linuxforfreshers ~]# systemctl is-active httpd.service
active
Enabling service means we are ensuring that service should start when server is rebooted. In older versions chkconfig command.
[root@linuxforfreshers ~]# systemctl enable crond.service
[root@linuxforfreshers ~]# systemctl is-enabled crond.service
enabled
Start and restart service using systemctl
As simple as starting the services and restarting the services is very easy, Here we have little more than that in New version.
[root@linuxforfreshers ~]# systemctl start crond.service
[root@linuxforfreshers ~]# systemctl restart crond.service
as we say it is more than start and restart we have systemctl try-restart now your thinking about what is the difference between restart and try-restart..?
option restart will restart the service if it is in stopped state also.
option try-restart Restart one or more units specified on the command line if the units are running. This does nothing if units are not running. Note that, for compatibility with Red Hat init scripts, condrestart is equivalent to this command.
[root@linuxforfreshers ~]# systemctl try-restart crond.service

 Listing dependencies, jobs, sockets, unit-files and Units
Listing dependencies means what are the services we have to start before starting this required service this before version this feature was not there.
Shows required and wanted units of the specified unit. If no unit is specified, default.target is implied. Target units are recursively expanded. When –all is passed, all other units are recursively expanded as well
[root@linuxforfreshers ~]# systemctl list-dependencies crond.service
crond.service
system.slice
└─basic.target
alsa-restore.service
alsa-state.service
firewalld.service
microcode.service
rhel-autorelabel-mark.service
rhel-autorelabel.service
rhel-configure.service
rhel-dmesg.service
rhel-loadmodules.service
paths.target
slices.target
list-jobs will show what are jobs running currently in background
[root@linuxforfreshers ~]# systemctl list-jobs
No jobs running.
Listing installed unit files
[root@linuxforfreshers ~]# systemctl list-unit-files |grep sshd
anaconda-sshd.service static
sshd-keygen.service static
sshd.service enabled
sshd@.service static
sshd.socket disabled
List all available sockets
[root@linuxforfreshers ~]# systemctl list-sockets
LISTEN UNIT ACTIVATES
/dev/initctl systemd-initctl.socket systemd-initctl.service
/dev/log systemd-journald.socket systemd-journald.service
/run/dmeventd-client dm-event.socket dm-event.service
/run/dmeventd-linuxforfreshers dm-event.socket dm-event.service
/run/lvm/lvmetad.socket lvm2-lvmetad.socket lvm2-lvmetad.service
/run/systemd/journal/socket systemd-journald.socket systemd-journald.service
/run/systemd/journal/stdout systemd-journald.socket systemd-journald.service
/run/systemd/shutdownd systemd-shutdownd.socket systemd-shutdownd.service
/run/udev/control systemd-udevd-control.socket systemd-udevd.service
/var/run/avahi-daemon/socket avahi-daemon.socket avahi-daemon.service
/var/run/cups/cups.sock cups.socket cups.service
/var/run/dbus/system_bus_socket dbus.socket dbus.service
/var/run/rpcbind.sock rpcbind.socket rpcbind.service
@ISCSIADM_ABSTRACT_NAMESPACE iscsid.socket iscsid.service
@ISCSID_UIP_ABSTRACT_NAMESPACE iscsiuio.socket iscsiuio.service
kobject-uevent 1 systemd-udevd-kernel.socket systemd-udevd.service
16 sockets listed.
Pass --all to see loaded but inactive sockets, too.
Note: because the addresses might contains spaces, this output is not suitable for programmatic consumption.
[root@linuxforfreshers ~]# systemctl list-sockets --show-types
LISTEN TYPE UNIT ACTIVATES
/dev/initctl FIFO systemd-initctl.socket systemd-initctl.service
/dev/log Datagram systemd-journald.socket systemd-journald.service
/run/dmeventd-client FIFO dm-event.socket dm-event.service
/run/dmeventd-linuxforfreshers FIFO dm-event.socket dm-event.service
/run/lvm/lvmetad.socket Stream lvm2-lvmetad.socket lvm2-lvmetad.service
/run/systemd/journal/socket Datagram systemd-journald.socket systemd-journald.service
/run/systemd/journal/stdout Stream systemd-journald.socket systemd-journald.service
/run/systemd/shutdownd Datagram systemd-shutdownd.socket systemd-shutdownd.service
/run/udev/control SequentialPacket systemd-udevd-control.socket systemd-udevd.service
/var/run/avahi-daemon/socket Stream avahi-daemon.socket avahi-daemon.service
/var/run/cups/cups.sock Stream cups.socket cups.service
/var/run/dbus/system_bus_socket Stream dbus.socket dbus.service
/var/run/rpcbind.sock Stream rpcbind.socket rpcbind.service
@ISCSIADM_ABSTRACT_NAMESPACE Stream iscsid.socket iscsid.service
@ISCSID_UIP_ABSTRACT_NAMESPACE Stream iscsiuio.socket iscsiuio.service
kobject-uevent 1 Netlink systemd-udevd-kernel.socket systemd-udevd.service
16 sockets listed.
Pass --all to see loaded but inactive sockets, too.
[root@linuxforfreshers ~]# systemctl list-sockets --failed
0 sockets listed.
Pass --all to see loaded but inactive sockets, too.

Setting up default target (Older version Run Level) and getting default target
We have to use set-default to set default run level and we can see default run level using get-default option as shown below example
[root@linuxforfreshers ~]# systemctl set-default multi-user.target
rm '/etc/systemd/system/default.target'
ln -s '/usr/lib/systemd/system/multi-user.target' '/etc/systemd/system/default.target'
[root@linuxforfreshers ~]# systemctl get-default
multi-user.target

Masking service ans unmasking service
What is mean by masking service, there is situation that company will have multiple administrators working together still there are times one administrator will stop the service which is not required but another administrator will start the same service unfortunately Or unknowingly , will lead to lot of problems to avoid this types of situations. We have to disable, stop the service and mask it, when other administrator try to start also the service will never start until unless explicitly unmask.
[root@linuxforfreshers ~]# systemctl disable crond.service
rm '/etc/systemd/system/multi-user.target.wants/crond.service'
[root@linuxforfreshers ~]# systemctl stop crond.service
[root@linuxforfreshers ~]# systemctl mask crond.service
ln -s '/dev/null' '/etc/systemd/system/crond.service'
[root@linuxforfreshers ~]# systemctl status crond.service
crond.service
Loaded: masked (/dev/null)
 Active: inactive (dead)
As shown in above command examples we have stopped the service, disabled the service and masked the service. Now try to start the service.
[root@linuxforfreshers ~]# systemctl start crond.service
Failed to issue method call: Unit crond.service is masked.
now unmask the service and start it will start
[root@linuxforfreshers ~]# systemctl unmask crond.service
rm '/etc/systemd/system/crond.service'
[root@linuxforfreshers ~]# systemctl start crond.service
[root@linuxforfreshers ~]# systemctl status crond.service
crond.service - Command Scheduler
Loaded: loaded (/usr/lib/systemd/system/crond.service; disabled)
Active: active (running) since Thu 2016-04-28 22:45:12 IST; 9s ago
Main PID: 7521 (crond)
CGroup: /system.slice/crond.service
└─7521 /usr/sbin/crond -n

Reload and reset service status
Most of the administrator will still have an question that what is the difference between service reload and restart.
Service reload is used whenever we changed something to the service and we would like to push the changes to the service without interrupting the connected users. Reloading the service will never change existing PID (Process Identity)
Service restart is used to restart the service which means stop and start the service, whenever we run restart existing users will disconnect and new PID will be created. It required little downtime to the service changes.
Before reloading the service status
[root@linuxforfreshers ~]# systemctl status sshd.service
sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled)
Active: active (running) since Thu 2016-04-28 05:56:52 IST; 16h ago
Process: 7228 ExecReload=/bin/kill -HUP $MAINPID (code=exited, status=0/SUCCESS)
Main PID: 1601 (sshd)
CGroup: /system.slice/sshd.service
└─1601 /usr/sbin/sshd -D

After reloading the service

[root@linuxforfreshers ~]# systemctl reload sshd.service
[root@linuxforfreshers ~]# systemctl status sshd.service
sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled)
Active: active (running) since Thu 2016-04-28 05:56:52 IST; 16h ago
Process: 7243 ExecReload=/bin/kill -HUP $MAINPID (code=exited, status=0/SUCCESS)
Main PID: 1601 (sshd)
CGroup: /system.slice/sshd.service
└─1601 /usr/sbin/sshd -D
if observe correctly PID before and after reload not changed.
Reset the “failed” state of the specified units

[root@linuxforfreshers ~]# systemctl reset-failed sshd.service

 Daemon reload option
After deleting the file or directory, you should reload the systemd process so that it no longer attempts to reference these files and reverts back to using the system copies. You can do this by typing:
[root@linuxforfreshers ~]# systemctl daemon-reload

Isolating Targets using systemctl command
It is possible to start all of the units associated with a target and stop all units that are not part of the dependency tree. The command that we need to do this is called, appropriately, isolate. This is similar to changing the runlevel in other init systems.

For instance, if you are operating in a graphical environment with graphical.target active, you can shut down the graphical system and put the system into a multi-user command line state by isolating the multi-user.target. Since graphical.target depends on multi-user.target but not the other way around, all of the graphical units will be stopped.

You may wish to take a look at the dependencies of the target you are isolating before performing this procedure to ensure that you are not stopping vital services:

systemctl list-dependencies multi-user.target

When you are satisfied with the units that will be kept alive, you can isolate the target by typing:
systemctl isolate multi-user.target

Create service snapshot and delete
Create a snapshot. If a snapshot name is specified, the new snapshot will be named after it. If none is specified, an automatic snapshot name is generated. In either case, the snapshot name used is printed to STDOUT, unless –quiet is specified.

A snapshot refers to a saved state of the systemd manager. It is implemented itself as a unit that is generated dynamically with this command and has dependencies on all units active at the time. At a later time, the user may return to this state by using the isolate command on the snapshot unit.
Snapshots are only useful for saving and restoring which units are running or are stopped, they do not save/restore any other state. Snapshots are dynamic and lost on reboot.

[root@linuxforfreshers ~]# systemctl snapshot sshd.service
sshd.service.snapshot
[root@linuxforfreshers ~]# systemctl status sshd.service.snapshot
sshd.service.snapshot
Loaded: loaded
Active: inactive (dead)
[root@linuxforfreshers ~]# systemctl delete sshd.service.snapshot
[root@linuxforfreshers ~]# systemctl status sshd.service.snapshot
sshd.service.snapshot
Loaded: not-found (Reason: No such file or directory)

Active: inactive (dead)

How to install vnstat Network Monitoring tool in linux?

vnstat is a command line utility that displays and logs network traffic of the interfaces on your systems. This depends on the network statistics provided by the kernel. So, vnstat doesn’t add any additional load to your system for monitoring and logging the network traffic.

 Install vnStat

In Ubuntu
For example, on Ubuntu use apt-get to install it as shown below.
$ apt-get install vnstat

Install vnStat on your system from the repository that is specific to your Linux distributions.

In RHEL
Install rpmforge Repository
CentOS/RHEL 6, 32 Bit (i686):
# rpm -Uvh http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.i686.rpm

CentOS/RHEL 6, 64 Bit (x86_64):
# rpm -Uvh http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.x86_64.rpm
Install vnStat package using Yum
Use yum command line utility to install vnstat package on your system.

# yum install vnstat

Since vnstat depends on the information provided by kernel, execute the following command to verify whether kernel is providing all the information that vnStat is expecting.

# vnstat --testkernel
This test will take about 60 seconds.
Everything is ok.
Pick a Interface to Monitor using vnStat

vnStat doesn’t monitor any interfaces unless you specifically request it to do so.

To start monitoring eth0, do the following. This needs to be executed only once. As you see below, this creates a database file eth0 under /var/lib/vnstat directory that will contain all the network traffic log messages for this specific interface.

# vnstat -u -i eth0
Error: Unable to read database "/var/lib/vnstat/eth0".
Info: -> A new database has been created.
To view all the available interfaces on your system that vnStat can monitor, do the following.

# vnstat --iflist
Available interfaces: lo eth0 eth1 sit0
Start the vnstatd (vnstat daemon), which will monitor and log these information in the background.

# vnstatd -d
# ps -ef | grep vnst
root     14353     1  0 09:12 ?        00:00:00 vnstatd -d
root     14355   330  0 09:12 pts/1    00:00:00 grep vnst
Note: You can add “vnstatd -d” to your /etc/rc.local file, so that it starts automatically anytime you reboot your system.
vnStat Basic Usage

vnstat without any argument will give you a quick summary with the following info:

The last time when the vnStat datbase located under /var/lib/vnstat/ was updated
From when it started collecting the statistics for a specific interface
The network statistic data (bytes transmitted, bytes received) for the last two months, and last two days.
# vnstat
Database updated: Sat Oct 15 11:54:00 2015

   eth0 since 10/01/15

          rx:  12.89 MiB      tx:  6.94 MiB      total:  19.82 MiB

   monthly
                     rx      |     tx      |    total    |   avg. rate
     ------------------------+-------------+-------------+---------------
       Sep '15     12.90 MiB |    6.90 MiB |   19.81 MiB |    0.14 kbit/s
       Oct '15     12.89 MiB |    6.94 MiB |   19.82 MiB |    0.15 kbit/s
     ------------------------+-------------+-------------+---------------
     estimated        29 MiB |      14 MiB |      43 MiB |

             daily
                     rx      |     tx      |    total    |   avg. rate
     ------------------------+-------------+-------------+---------------
     yesterday      4.30 MiB |    2.42 MiB |    6.72 MiB |    0.64 kbit/s
         today      2.03 MiB |    1.07 MiB |    3.10 MiB |    0.59 kbit/s
     ------------------------+-------------+-------------+---------------
     estimated         4 MiB |       2 MiB |       6 MiB |
Note: If you just installed the vnStat, it will give the following message “eth0: Not enough data available yet.”. Wait for some time and try the command again.
vnStat hours, days, months, weeks Network Data

Use “vnstat -h” (or) “vnstat –hours” for network statistic data breakdown by hour. This also displays a text based graph.

Use “vnstat -d” (or) “vnstat –days” for network statistic data breakdown by day.

# vnstat -d
 eth0  /  daily
         day         rx      |     tx      |    total    |   avg. rate
     ------------------------+-------------+-------------+---------------
      10/10/15      2.48 MiB |    1.28 MiB |    3.76 MiB |    0.36 kbit/s
      10/11/15      4.07 MiB |    2.17 MiB |    6.24 MiB |    0.59 kbit/s
      10/12/15      4.30 MiB |    2.42 MiB |    6.72 MiB |    0.64 kbit/s
      10/13/15      2.06 MiB |    1.10 MiB |    3.16 MiB |    0.60 kbit/s
     ------------------------+-------------+-------------+---------------
     estimated         3 MiB |       1 MiB |       4 MiB |
Use “vnstat -m” (or) “vnstat –months” for network statistic data breakdown by month.

# vnstat --m

 eth0  /  monthly

       month        rx      |     tx      |    total    |   avg. rate
    ------------------------+-------------+-------------+---------------
      Sep '15     12.90 MiB |    6.90 MiB |   19.81 MiB |    0.14 kbit/s
      Oct '15     12.92 MiB |    6.96 MiB |   19.89 MiB |    0.15 kbit/s
    ------------------------+-------------+-------------+---------------
    estimated        29 MiB |      14 MiB |      43 MiB |
Similar to days and months, use “vnstat -m” (or) “vnstat –months” for network statistic data breakdown by week.

Export the data to Excel or other DB

If you like to export the network monitoring data to an excel or other database, you can dump the data in a text format delimited with semi-colon, which you can import to Excel or other db.

The 1st few lines of the –dumpdb output contains some header information. After the header lines, it has 30 lines that starts with “d;” (d;0;1318316406;1;0;386;698;1). This lines has the following information separated by semi-colon.

d – stands for days
0 – number of the day. 0 indicates today.
1318316406 – data in Unix format
Followed by this, it contains the bytes transmitted and received
$ vnstat --dumpdb
interface;eth0
created;1218562937
updated;1218546895
totalrx;3
totaltx;1
...
...
d;0;1328316406;1;0;386;698;1
d;1;1345262937;2;1;494;289;1
You can also use “vnstat –oneline”, which displays the traffic summary in a single line where the values are delimited with semi-colon.

$ vnstat --oneline
1;eth0;10/11/15;1.45 MiB;801 KiB;2.23 MiB;0.59 kbit/s;Oct '15;3.93 MiB;2.06 MiB;6.00 MiB;0.05 kbit/s;3.93 MiB;2.06 MiB;6.00 MiB
Display Live Network Statistics

Use “vnstat -l” or “vnstat –live” to display the live network statistic information.

$ vnstat -l
Monitoring eth0...    (press CTRL-C to stop)

   rx:        2 kbit/s     5 p/s          tx:        2 kbit/s     4 p/s
After you press Ctrl-C to stop it, vnstat will display a summary for the time period the live monitor was running.


Wednesday, May 25, 2016

what is the use of nohup command in linux ?


Most of the time you login into remote server via ssh. If you start a shell script or command and you exit (abort remote connection), the process / command will get killed. Sometime job or command takes a long time. If you are not sure when the job will finish, then it is better to leave job running in background. But, if you log out of the system, the job will be stopped and terminated by your shell. What do you do to keep job running in the background when process gets SIGHUP?
 nohup command line-utility which allows to run command/process or shell script that can continue running in the background after you log out from a shell:

nohup command syntax:
The syntax is as follows
nohup command-name &

OR
nohup /path/to/command-name arg1 arg2 &

Where,

command-name : is name of shell script or command name. You can pass argument to command or a shell script.
& : nohup does not automatically put the command it runs in the background; you must do that explicitly, by ending the command line with an & symbol.
Use jobs -l command to list all jobs:
# jobs -l

nohup command examples

First, login to remote server using ssh command:
$ ssh user@remote.server.com

OR
$ ssh rajesh@linuxforfreshers.com

I am going to execute a shell script called ftp.sh:
# nohup ftp.sh &

Type exit or press CTRL + D exit from remote server:
# exit

In this example, I am going to find all programs and scripts with setuid bit set on, enter:
# nohup find / -xdev -type f -perm +u=s -print > out.txt &

Type exit or press CTRL + D exit from remote server.
# exit

Please note that nohup does not change the scheduling priority of COMMAND; use nice command for that purpose. The syntax is:
# nohup nice -n -5 ls / > out.txt &


As you can see nohup keep processes running after you exit from a shell. Read man page of nohup(1) and nice(1) for more information. Please note that nohup is almost available on Solaris/BSD/Linux/UNIX variants.

Tuesday, May 24, 2016

How to Get Current Time In Shell Script ?


How do I get the current server time in shell script on Linux or Unix-like operating systems? 
How do I store the current time in the shell variable and use in my scripts?

You can use the date command to display or set the current date and time. You need to use the date FORMAT syntax to controls the output of the date command. The %T format sequence interpreted by the date command to display the current time. The syntax is:


date +%FORMAT
date +"%FORMAT"
var=$(date +"%FORMAT")

Example: Show current time

Open a terminal and type the following command:
date +"%T"
Sample outputs:
13:24:21
To store time to a shell variable called now, enter:
now=$(date +"%T")
echo "Current time : $now"
Sample outputs:
Current time : 13:24:21
date +%FORMAT
date +"%FORMAT"
var=$(date +"%FORMAT")

Example: Show current time

Open a terminal and type the following command:
date +"%T"
Sample outputs:
16:33:22
To store time to a shell variable called now, enter:
now=$(date +"%T")
echo "Current time : $now"
Sample outputs:
Current time : 13:31:55

Example: 12 hour clock time

Pass the %r format to the date command:
date +”%r”
Sample outputs:
”12:25:43 PM”
To remove AM or PM from the output use, type:
date +"%I:%M:%S"
Sample outputs:
12:26:27


Tuesday, May 10, 2016

tee command examples in linux?


In computing, tee is a command in command-line interpreters (shells) using standard streams which reads standard input and writes it to both standard output and one or more files, effectively duplicating its input. It is primarily used in conjunction with pipes and filters.




Image result for tee command in unix



Example 1: Write output to stdout, and also to a file

The following command displays output only on the screen (stdout).
$ ls
The following command writes the output only to the file and not to the screen.
$ ls > file
The following command (with the help of tee command) writes the output both to the screen (stdout) and to the file.
$ ls | tee file

Example 2: Write the output to two commands
You can also use tee command to store the output of a command to a file and redirect the same output as an input to another command.
The following command will take a backup of the crontab entries, and pass the crontab entries as an input to sed command which will do the substituion. After the substitution, it will be added as a new cron job.
$ crontab -l | tee crontab-backup.txt | sed 's/old/new/' | crontab  -e

Misc Tee Command Operations

By default tee command overwrites the file. You can instruct tee command to append to the file using the option –a as shown below.
$ ls | tee –a file
You can also write the output to multiple files as shown below.
$ ls | tee file1 file2 file3