This article provides few simple scripts to scan and monitor network using combination of bash and ping command. Obviously, these scripts are no match to a full monitoring dedicated software like nagios but they could be useful for a small home brand networks, where implementing sophisticated monitoring system can become an overhead.
In this example the bash script will scan network for hosts attached to an IP address 10.1.1.1 - 255. The script will print message Node with IP: IP-address is up if ping command was successful. Feel free to modify the script to scan your hosts range.
#!/bin/bash is_alive_ping() { ping -c 1 $1 > /dev/null [ $? -eq 0 ] && echo Node with IP: $i is up. } for i in 10.1.1.{1..255} do is_alive_ping $i & disown done
Execute:
./bash_ping_scan.sh
OUTPUT:
Node with IP: 10.1.1.1 is up. Node with IP: 10.1.1.4 is up. Node with IP: 10.1.1.9 is up.
Ping bash script example No.2 will send an email to a specified email address when ping cannot reach its destination. System admin can execute this in script regularly with use of a cron scheduler. The script first uses ping command to ping host or IP supplied as an argument. In case that destination is unreachable a mail command will be used to notify system administrator about this event.
#!/bin/bash for i in $@ do ping -c 1 $i &> /dev/null if [ $? -ne 0 ]; then echo "`date`: ping failed, $i host is down!" | mail -s "$i host is down!" my@email.address fi done
Execute:
./check_hosts.sh google.com yahoo.com 192.168.1.2 mylinuxbox N2100
The last example is a modified version of the previous example. When mail is not configured on the system the script will create a log file. The core of the script is wrapped into endless while loop which is set to execute ping check every hour ( 3600 second ). Modify the script according to your needs. Remove endless while loop when you intend to use this script with cron scheduler.
#!/bin/bash LOG=/tmp/mylog.log SECONDS=3600 EMAIL=my@email.address for i in $@; do echo "$i-UP!" > $LOG.$i done while true; do for i in $@; do ping -c 1 $i > /dev/null if [ $? -ne 0 ]; then STATUS=$(cat $LOG.$i) if [ $STATUS != "$i-DOWN!" ]; then echo "`date`: ping failed, $i host is down!" | mail -s "$i host is down!" $EMAIL fi echo "$i-DOWN!" > $LOG.$i else STATUS=$(cat $LOG.$i) if [ $STATUS != "$i-UP!" ]; then echo "`date`: ping OK, $i host is up!" | mail -s "$i host is up!" $EMAIL fi echo "$i-UP!" > $LOG.$i fi done sleep $SECONDS done
Execute:
./check-server-status.sh google.com yahoo.com 192.168.1.2 mylinuxbox N2100