You can simply monitor your remote system hosted in some remote IDC. There may be many reasons for which system may out of the network. This simple script is useful to monitor your own small network at home or work.
Understanding the ping command
The ping is one of the basic and nifty command to test network connection. For example, you can send 4 ping request to cyberciti.biz with the following command:
$ ping -c 4 cyberciti.biz
$ ping -c 4 router
Output:
PING router (192.168.1.254) 56(84) bytes of data. 64 bytes from router (192.168.1.254): icmp_seq=1 ttl=64 time=1.02 ms 64 bytes from router (192.168.1.254): icmp_seq=2 ttl=64 time=0.824 ms 64 bytes from router (192.168.1.254): icmp_seq=3 ttl=64 time=0.826 ms 64 bytes from router (192.168.1.254): icmp_seq=4 ttl=64 time=0.843 ms --- router ping statistics --- 4 packets transmitted, 4 received, 0% packet loss, time 3012ms rtt min/avg/max/mdev = 0.824/0.880/1.027/0.085 ms
Just see output line ‘— router ping statistics —‘ and note down the ‘4 received’ field. This the key to verify that 4 packets send and received successfully. You can extract words ‘4 received’ with the following command:
$ ping -c4 router | grep 'received'
Outputs:
4 packets transmitted, 4 received, 0% packet loss, time 3012ms
Next logical step is to just get number 4 received using the awk command:
$ ping -c4 router | grep 'received' | awk -F',' '{ print $2}'
Outputs:
4 received
Last step is to just get 4 number and remove received word:
$ ping -c4 router | grep 'received' | awk -F',' '{ print $2}' | awk '{ print $1}'
Outputs:
4
Shell script to system monitoring with ping command
Now you know how to obtained received packets, it is time to automate entire process with simple script. Here is a sample shell script (download link):
#!/bin/bash HOSTS="cyberciti.biz theos.in router" COUNT=4 for myHost in $HOSTS do count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }') if [ $count -eq 0 ]; then # 100% failed echo "Host : $myHost is down (ping failed) at $(date)" fi done
You can download complete working script which sends an email alert here.
Setup Cron job
In order to run this script every 30 minutes (or as per your requirements), you need to install a script as cron job:
$ chmod +x /path/to/monitorHost
Install the monitorHost script as crontab using the editor:
$ crontab -e
Append the following cronjob entry:
# Monitor remote host every 30 minutes using monitorHost
30 * * * * /home/vivek/bin/monitorHost
Save and close the file.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via:
- RSS feed or Weekly email newsletter
- Share on Twitter • Facebook • 49 comments... add one ↓
Category | List of Unix and Linux commands |
---|---|
File Management | cat |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Network Utilities | dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time |
Searching | grep • whereis • which |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Hi, all ”
can any one help how to add 3 more host in the script
Thank you
Hi all,
Currently i’m run centos crontab unfortunately crontab didn’t perform the job. i’m unsure which part i’m wrong, if i run manually it is working fine without any issue. kindly need you all advise.
crontab -e
* * * * * /bin/sh /root/scripts/check.sh
104214022960057eb39a48d_000001
Hi all… I have a script that pings a server emails me if there is no response, but it does not work. Below is the script, can someone please point out what is wrong with it and how can I fix it?
Try
Why such long ways to do this…
`
[ `ping -c 4 domain.com > /dev/null 2<&1; echo $?` -eq 0 ] && echo "Host is up" || echo "Host is Down";
`
There is a typo in your first awk command (“Next logical step…”) — should use $2, not $4.
–> $ ping -c4 router | grep 'received' | awk -F',' '{ print $2}'
Simple Script to check whether the remote host is up or down;
ping -c 4 192.168.1.1
if [ “`echo $?`” == 0 ]; then
echo “192.168.1.1 is up”
else
echo “192.168.1.1 is down”
fi
execute it through cron daemon and put use mail command to receive it to your email.
Thanks,
Thanks much. It helped me.
Hi ,
I was looking for a way by which I can ping the remote UNIX Servers from my Local (WINDOWS) system. Any suggestions on how can this be achieved? I fear that checking the server availability from a unix server may fail if the unix server on which the check script is hosted goes down anyday.
Aritra
I have developed the script such that to ping it forever:
function CheckHost()
{
HOSTS=”IP”
ping=”5″
SUBJECT=”Ping UAT $HOSTS”
EMAILID=”MAIL ID”
count=$(ping -s $HOSTS 56 $ping | grep “received” | awk -F, ‘{print $1 $2 $3}’)
echo $count
op=$(echo $count | awk ‘{print $1 $4}’)
echo $op
if [ $op != $ping$ping ];
then
echo “Host : $HOSTS Ping Failed $count” | mailx -s “$SUBJECT” $EMAILID
fi
echo ‘Calling CheckHost Again!’
CheckHost
}
CheckHost
Really big thanks for your great help
very good…..
thank you
Any suggestions on if I want a script to ping a host every 10 sec 6 times and send an e-mail if packet loss is anything other than 0%?
Simple Script to check whether the remote host is up or down;
ping -c 6 192.168.1.1
if [ “`echo $?`” == 0 ]; then
echo “192.168.1.1 is upâ€
else
echo “192.168.1.1 is downâ€
fi
sleep 10
sh /root/script
Execute it once and it will not stop until you kill the script , put ‘mail’ command in the script and you will receive it in your email if there is no response from the remote host.
Thanks,
I think the code could be sligtly improved.
Sending an email for each machine that is down can lead to a very high number of emails,
Sending one email reporting just the ones that were down during the check is easier to go through and check.
I am also using the same procedure to monitor multiple systems
I like the code but think fping is better at this and easier coding.
install apt-get install fping
then put in the code as
For testing if host alive just use fping -a or fping -u:
-a show all host in your list as alive or -u shows unavailble.
You can also predefine using a file with th -f and a filename.
Long and short you can do what you want by adding:
a file called something like host.txt and code would be one line such as:
fping -ag -f /path/host.txt > results
your host.txt would hold all hosts you want to monitor. This one line will go out and check the hosts listed and let you know everything alive in the results file. if you leave off the -a it will list the status up or down in the results. this is getting wordy and not trying to over ride the post everyone has there own way. I am just giving a quick response of an alternate way of doing it with less lines of code.
Thanks and great job on the code,
Robby Loyed
Hi friends,can anybody suggest me some code for how to get respond for a client side Ping to a server in C on unix platform?
@КонÑтантин КръÑтев
I love your line, but could you explain the bit after the “>” I don’t get that.
It does work I just don’t know why!
Thanks,
Der
ping -qnc 2 google.com > /dev/null 2>&1 && echo ‘Host up!’ || echo ‘Host down!’
thanks , this work 😀
This is a great tutorial but there is a little problem. Your cron job won’t be executed every 30 minutes but instead 1 time per hour at 30 minute (1:30, 2:30, 3:30). To run it every 30 min, you should change the first parameter to */30.
Hi coders
What would i use if i needed 1 timestamp when “Ping up again” ?
Thanks
can anybody suggest me a solution plz
hi,
i am doing a small program on the working of ping command in linux using icmp protocol. here is the code but its giving an error at getuid()
have to implement ping command using raw socket in unix
@shilpa: PING using icmp protocol. You can read more here:
http://www.iana.org/assignments/icmp-parameters
how to check server is alive using ping command at client in unix system programming using ICMP protocol
It works fine except i tried to use it to make sure my internet connection was still up and if the internet connection fails It can’t resolve the host so it can’t try ping to ping it. How could i add a check for this situation?
Check dns settings in /etc/resolv.conf file including firewall settings.
HTF: Yes
if [ $count -eq 0 ]; then <- only if 100% failed.
Quick question:
If I set the ping count to 4 and only one of four will failed will I get the true positive alarm anyway?
Along a slightly different vein- I’ve got my e-mail client set to start as soon as I log in, which is often before the network is online. It then tells me it can’t find the server and decides to work off-line. This is annoying, so I added a slight modification of the above at the head of its initialisation script:
while :
do
count=$(ping -c 1 imap.1and1.co.uk | grep ‘received’ | awk -F’,’ ‘{ print $2 }’ | awk ‘{ print $1 }’)
if [ $count -eq 1 ]; then
break
fi
sleep 5
done
nice..
thanks you ^,^
@BenV – Will your script work if $host does not exist? Typo’s happen.
Will adding a ‘ping -c1 -w1″ enable a timeout and avoid hanging indefinitely? or is the -w not used that way?
@ishfaq :
echo “Host : $myHost is down (ping failed) at $(date)” >> /var/www/network.txt
nice script but any tell how to paste the out put on apache page
Short and sweet code Benv
can someone show me a script I could cron every 15 min or so, that would email ‘root’ each time a computer comes up on the LAN or goes off the LAN, giving the ip address and the windows computer name?
I commonly use this. Just another way to do it.
if [[ $(ping -q -c 3 10.1.1.1) == @(*100% packet loss*) ]]; then
echo “$host is down”
else
echo “$host is alive”
fi
TonyK
Yes you can always use another set of commands to do the same thing. Coding is like that… heh
Appreciate your post!
You can skip the awk stuff by using cut like this:
ping -c4 localhost | grep ‘received’ | cut -f2 -d’,’ |cut -f2 -d’ ‘
it also returns 4
ping -c4 localhost |grep received| cut -d “,” -f2| cut -d ” ” -f2
Go here
HTH
Hie
this is an ingenious script:)
thanks to share it
I have just a little question.
I didn’t find “Email ID”
can you help me to find it please??
thanks for your help
Kotnik,
Short and sweet code 😀
No, ( is not missing. Try it:
http://pastebin.ca/102156
Nice, though I think a ( got dropped before *’100% packet loss’*) ?
This is the script I’m using for the same thing:
case `ping -qnc 1 google.com 2>&1` in
*’100% packet loss’*)
echo “The network is DOWN.”
exit 1
;;
esac
One way or around…