user@host:$ mkfifo to_script && ./check_offending_channels.sh < to_script | telnet > to_script; rm to_script
check_offending_channels.sh
#!/bin/sh
# Invoke as follows:
# mkfifo to_script && ./script.sh < to_script | telnet > to_script; rm to_script
# Some variables for customisation
SECONDS_THRESHOLD=10
ASTERISK_HOST=localhost
AMI_USER=manager
AMI_PASS=password
SUBJECT="WARNING: Channels found which are more than $SECONDS_THRESHOLD up"
EMAIL="[email protected]"
BODY=$( cat <<EOF
There is at least one channel which exceeds the offending threshold.
See attached file for details
EOF)
# Files used for logging data (will be removed)
CHANSTATUS=/tmp/channels_`date +%s`.txt
ERRORLOG=/tmp/channel_error_`date +%s`.txt
function noOp() {
return;
}
function channelCb() {
echo "$1" >> $CHANSTATUS
}
# Reads from asterisk, invokes a callback with the line
# and breaks as soon as a certain regular expression matches
function readResponse() {
break=$1
callback=$2
while true; do
read RESPONSE
$callback "${RESPONSE}"
if echo "$RESPONSE" | grep "$break"; then
break;
fi
done
}
rm $CHANSTATUS > /dev/null 2>&1
# Tell telnet to connect
echo "open $ASTERISK_HOST 5038"
# Wait for asterisk to say hello
readResponse "Asterisk Call Manager" noOp
# login to the AMI
cat <<EOF
Action: Login
ActionID: 1
Username: $AMI_USER
Secret: $AMI_PASS
Events: off
EOF
# Invoke the Status action
cat <<EOF
Action: Status
ActionID: 2
EOF
# Wait for asterisk to complete the Status action and log responses to file
readResponse "Event: StatusComplete" channelCb
cat <<EOF
Action: Logoff
ActionID: 3
EOF
# Tell telnet to quit
echo "quit"
# Function for logging offending channels
function printChannelInfo() {
if ! [ -z $PRINTINFO ]; then
echo "Printing $CHANNEL" >&2
echo -e "$CHANNELINFO" >> $ERRORLOG
echo "----------------" >> $ERRORLOG
fi
}
rm $ERRORLOG > /dev/null 2>&1
CHANNELINFO=""
PRINTINFO=
FOUNDOFFENDINGCHANNEL=
IFS=$'\012' # Split on newline
# Read asterisk channel info
for line in `cat $CHANSTATUS`; do
if echo "$line" | grep 'Channel: ' > /dev/null; then
printChannelInfo
CHANNEL=`echo $line | awk '{ print $2 }'`
PRINTINFO=
CHANNELINFO=
fi
CHANNELINFO="${CHANNELINFO}\n$line"
sec=`echo $line | grep 'Seconds: ' | awk '{ print $2 }'`
if ! [ -z $sec ]; then
if [ $sec -gt $SECONDS_THRESHOLD ]; then
echo "Found offending channel $CHANNEL" >&2
PRINTINFO=yes
FOUNDOFFENDINGCHANNEL=yes
fi
fi
done
printChannelInfo
rm $CHANSTATUS > /dev/null 2>&1
# Mail offending channels if there are any
if ! [ -z $FOUNDOFFENDINGCHANNEL ]; then
echo "Mailing error" >&2
echo "$SUBJECT" >&2
echo "$EMAIL" >&2
echo "$ERRORLOG" >&2
echo "$BODY" >&2
# Set home for mutt
HOME=/tmp
mutt -f /dev/null -R -s "$SUBJECT" -a "$ERRORLOG" "$EMAIL" 1>&2 <<EOF
$BODY
EOF
fi
rm $ERRORLOG > /dev/null 2>&1
exit 0