由于对接的有个网关定期换IP,手动设定很麻烦。所以写了这么一个脚本扔到cron里。
首先需要修改/etc/asterisk/sip.conf,找到#include sip_custom.conf这里,修改成:
;#include sip_custom.conf #include sip_additional.conf #include sip_custom.conf
然后把py脚本整到/bin里:
import re import os part_a = '''[9031] disallow=all username=9031 type=friend secret=9031 qualify=yes insecure=invite host=dynamic dtmfmode=rfc2833 context=from-pstn canreinvite=0 allow=g723 [9031_Out] disallow=all username=9031 type=friend secret=9031 qualify=yes port=7878 host=''' part_b = ''' fromeuser=9031 context=from-pstn allow=g723 ''' res = os.popen('asterisk -x "sip show peers"').read() lines = res.split("\n") for line in lines: if line.find("9031/9031")>-1: inbound = re.match("9031/9031\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+D\s+Yes\s+Yes\s+\d+\s+OK \(\d+ ms\)",line) elif line.find("9031_Out/9031")>-1: outbound = re.match("9031_Out/9031\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Yes\s+Yes\s+\d+\s+UNREACHABLE",line) if inbound and outbound and inbound.group(1) <> outbound.group(1): print "Change peer IP "+outbound.group(1)+" to "+inbound.group(1) f = open("\etc\asterisk\sip_custom.conf","w") f.write(part_a+inbound.group(1)+part_b) f.close() os.popen('asterisk -x reload') else: print "Peer IP has not changed"
再修改/etc/crontab,添加一个定时任务:
*/10 * * * * root python /bin/check_trunk_ip.py
最后重启下crond服务就Ok啦。
service crond restart
49 queries in 1.101 seconds |