Posts Tagged ‘awk’

Asterisk: count active calls on certain peers

Sunday, October 8th, 2017

Let’s imagine that you have a number of peers – both internal users and trunks with VoIP providers.
And you need to count active calls on trunks only. Or even on trunks with some concrete provider, but not the total ‘core show calls’. As an example, you may need to pass that integer to Zabbix.

root@pbx:~# asterisk -C /etc/asterisk/asterisk.conf -rx 'sip show inuse' 
Setting max files open to 1000
* Peer name               In use          Limit           
104                       0/0/0           10              
107                       0/0/0           10              
100                       0/0/0           10                            
voip-isp-london1          1/0/0           6      
voip-isp-london2          2/1/0           6      
root@pbx:~# 

In fact, all magic is done with grep and especially awk tool. Firstly, you need to grep ‘voip-isp’, then extract the second column (is done with awk ‘{print $2}’ ) and then extract the first digit from three ones (e.g. 2 from 2/1/0).
At this point, you’ll get a list of integers, one per line, corresponding to number of active calls on each grepped trunk.
Now it’s time to summarize them, and the best way to do it is also awk! (is done with awk -F\/ ‘{sum += $1} END {print sum}’ )

root@pbx:~# asterisk -C /etc/asterisk/asterisk.conf -rx 'sip show inuse' | grep voip | awk '{print $2}' | awk -F\/ '{sum += $1} END {print sum}'
3

awk

Sunday, February 16th, 2014

Print the first line:
cat somefile.txt | awk ‘{print $1}’

… and see the number of active calls on Asterisk PBX:

asterisk -rx 'core show calls' | head -n 1 | awk '{print $1}'

Print all but first 6 columns of the file:
cat somefile.txt | awk ‘{$1=$2=$3=$4=$5=$6=””; print $0}’

… and see who’s trying to connect to 5060/TCP and 22/TCP (some fields reduced):

root@vds:~# tail -n 2 /var/log/syslog | awk '{$1=$2=$3=$4=$5=$6=""; print $0}'
      iptables denied Asterisk IN=eth0 SRC=69.60.119.204 DST=XX.XX.YY.ZZ PROTO=UDP SPT=5072 DPT=5060
      iptables denied SSH IN=eth0 SRC=222.186.62.39 DST=XX.XX.YY.ZZ PROTO=TCP SPT=6000 DPT=22

By default, awk doesn’t separate columns. To do that, use comma:

root@vds:~# grep Aster /var/log/syslog | awk '{print $1,$2,$3,$9,$13}'
Feb 17 07:03:25 Asterisk SRC=74.118.193.77
Feb 17 07:13:23 Asterisk SRC=85.25.194.185
Feb 17 07:56:31 Asterisk SRC=188.138.34.254
Feb 17 08:12:02 Asterisk SRC=200.12.49.147

PS: all these IPs are bad guys. They’re trying to connect to my SSH and SIP ports. So, I do not hide their addresses :)

Update:

In case you’ve got an output like

“123456”
“234567”
“345678”

and want to get rid of first and last symbols:

rev input_file.txt | cut -c2- | rev | cut -c2-

In case your columns have some other delimiters than space, p.e. comma, specify it:

cat file.txt | awk -F',' '{print $3}'