#!/usr/bin/python # This script connects to an Asterisk server using AGI. # It counts the number of SIP registrations that are not in the state # "Registered". # All registration information of that kind are collected and sent as a # notification e-mail. import os import sys import time import smtplib # Python AMI-Interface von: # https://github.com/ettoreleandrotognoli/python-ami/ from asterisk.ami import AMIClient from asterisk.ami import SimpleAction from email.mime.text import MIMEText # RegistrationsComplete event received yet? complete=False regErrors=[] # Listen for one registration event, # add all erroneous registrations to regErrors list def reg_event(event,**kwargs): global regErrors # print(event) if (event.keys['State']!='Registered'): regErrors.append(event.keys['Domain']+': '+event.keys['State']) # Listen for registration completed event, trigger logoff from AMI then def reg_events_completed(event,**kwargs): global complete global client complete=True client.logoff() client = AMIClient(address='127.0.0.1',port=5038) future = client.login(username='superusername',secret='supersecretpassword') if future.response.is_error(): raise Exception(str(future.response)) # Each registration is described via one RegistryEntry event client.add_event_listener(reg_event, white_list=['RegistryEntry']) # Asterisk sends one Event per SIP registration. When this process is completed, # a RegistrationsComplete event is sent. client.add_event_listener(reg_events_completed, white_list=['RegistrationsComplete']) # The command SIPshowregistry triggers Asterisk to send one RegistryEntry event # for each known registration (see above) action = SimpleAction('SIPshowregistry') client.send_action(action) try: while not complete: time.sleep(5) except (KeyboardInterrupt, SystemExit): client.logoff() # In case errors have been recorded, send an e-mail if (len(regErrors)>0): #print(regErrors) body='Errors in SIP registrations: '+str(regErrors) msg=MIMEText(body) mFrom='Mail sender ' mTo='target@domain.tld' msg['Subject'] = 'SIP Registry error' msg['From'] = mFrom msg['To'] = mTo # Send the message via local SMTP service s = smtplib.SMTP('localhost') s.sendmail(mFrom,mTo,msg.as_string()) s.quit()