[HOW-TO] Use shell script to monitor extension status and get email notification

I have a script to check if an extension is up and it run on cron job every 30 minutes. Any thoughts on how to make the script send an email once and not every 30 minutes while the extension is down?

#!/bin/bash
email="[email protected]"
A=`/usr/sbin/asterisk -x 'sip show peer 200' | grep -i status | cut -d' ' -f11`
if [ "$A" != "OK" ]; then
(
echo "Subject: Extension 200 is down"
printf 'Extension 200 is down"...'
) | /usr/sbin/sendmail ${email}
fi

Inside your if before the email sends.
Add another if to check the variable and only email if it is 0

read emailsent < savedvar.txt
If $emailsent == 0 then
# send the email and set the variable
# set email sent variable
$emailsent=1
#write it to a file 
echo $emailsent > savedvar.txt

add an else to your existing ifand set it to 0

Thank you, Jared. Your suggestion worked. I also had another workaround that worked with similar approach.

#!/bin/sh
email="[email protected]"
/usr/sbin/asterisk -x 'sip show peer 204' | grep -i status | cut -d' ' -f11 > /tmp/204status1.txt
A=`comm -23 /tmp/204status1.txt /tmp/204status2.txt`
cp /tmp/204status1.txt /tmp/204status2.txt
if [[ "$A" == "UNKNOWN" || "$A" == "UNREACHABLE" ]]; then
(
echo "Subject: System is down - 204"
printf 'System is down...'
) | /usr/sbin/sendmail ${email}
fi

The script below works as well

#!/bin/sh
email="[email protected]"
rasterisk -x 'sip show peer 201' | grep -i status | cut -d' ' -f11 > /tmp/201status1.txt
A=`comm -23 /tmp/201status1.txt /tmp/201status2.txt`
cp /tmp/201status1.txt /tmp/201status2.txt
if [[ "$A" == "UNKNOWN" || "$A" == "UNREACHABLE" ]]; then
(
echo "Subject: Extension is down - 201 line."
printf 'System is down...201 line'
) | /usr/sbin/sendmail ${email}
fi
  • Save the file somewhere like /usr/201.sh
  • chmod +x /usr/201.sh
  • Then run the script twice and it will generate /tmp/201status1.txt & /tmp/201status2.txt files.

You script is working, so don’t mess with it, but using the Asterisk ASTDB for this might not be a bad idea. You can use an "rasterisk -x ‘your_command_goes_here’ " to get and set a variable in the extension hierarchy. With that, you can then use the same variable for other fun things you might want to do with this knowledge. I don’t know what else you might want to use, but you never know.

1 Like

Thank you, Dave. I will look into this and if I have a working script I will post it here.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.