How do use IPs and have the device name sent in the alert emails of the script?

Hello Everyone,

I have this script below working beautifully. It polls every hour certain devices from an IP list and then sends an email if any of these are down. So this includes IP address. I wanted to know the corresponding device name as we cannot remember IPs allocated to devices.

While I solved that issue with adding locally in the /etc/hosts, the IP to name mappings and then changing my list to replace the IPs with the names. But I need a better way, so that everything is in the script and we are not messing up with the hosts files, which we will tend to forget about.

Ideally, the list could be an array / dictionary with key-value pairs in it and then IPs are used for the polling, but the failed device builds from the associated value which will be the name. I have just started reading up on scripting, but have no clue how to create this key-value lookup in the script below.

Here is the working script, otherwise using IPs (or names with hosts file configured for the mappings).

||## SCRIPT|
||# Info needed for sending mails|
||# pings devices, sequentially, from the list 3 times at 2 sec interval.|
||DEVICELIST=''         |
||        ping -c 3 -i 2 $DEVICE > /dev/null || DOWN_DEVICELIST=$DOWN_DEVICELIST $DEVICE|
||echo To: \$TO_NAME\ <$TO_ADDRESS> >> $MAIL_FILE|
||if [ -n $DOWN_DEVICELIST ] ; then|
||        echo Subject: Possible DEVICE Down >> $MAIL_FILE|
||        echo X-Priority: 1 (Highest) >> $MAIL_FILE|
||        echo X-MSMail-Priority: High >> $MAIL_FILE|
||        echo Importance: High >> $MAIL_FILE|
||        echo ___________________________________________ >> $MAIL_FILE|
||        echo The following Devices failed the ping test:-  >> $MAIL_FILE|
||        echo $DOWN_DEVICELIST | xargs -n 1 >> $MAIL_FILE|
||        echo ___________________________________________  >> $MAIL_FILE|
||        echo Sent by PCEng ${0##*/} script >> $MAIL_FILE|
||        cat $MAIL_FILE | sendmail -f $FROM_ADDRESS $TO_ADDRESS && logger ${0##*/}: Potential Device Down: , mail sent|
||fi |
||rm $MAIL_FILE|
||chmod +x /usr/local/bin/|
||crontab -e|
||# pings Devices every hour and sends mail if any is down|
||0 * * * * sudo bash /usr/local/bin/|
||service cron reload|
||systemctl restart cron|
1 Like

I guess the pipes would need to be removed from the script?

1 Like

Sorry about that and good catch. I copied my script into notepad ++ and from there pasted into the post and I did not pay attention that it added these additional characters.