74 lines
2.9 KiB
Python
Executable file
74 lines
2.9 KiB
Python
Executable file
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
import socket,time, os, shutil,sys
|
|
|
|
class Sms(object):
|
|
def __init__(self, server,port,user,password,sms_dir,timeout=360):
|
|
self.sms_dir=sms_dir
|
|
self.lastsend=None
|
|
while True:
|
|
try:
|
|
print("Connect to Asterisk")
|
|
self.irc = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
|
|
self.irc.settimeout(timeout)
|
|
self.irc.connect ( ( server, port ) )
|
|
self.send ( 'ACTION: LOGIN')
|
|
self.send ( 'USERNAME: %s' % user)
|
|
self.send ( 'SECRET: %s' % password)
|
|
self.send ( '')
|
|
print(self.irc.recv ( 4096 ))
|
|
data=[]
|
|
while True:
|
|
recv=self.irc.recv ( 4096 )
|
|
if len(recv)==0:
|
|
break
|
|
data.extend(recv.split('\r\n'))
|
|
while len(data)!=0:
|
|
line_id_init=0
|
|
line_id_read=0
|
|
if data[0] == 'Event: PeerStatus':
|
|
if len(data)<8:
|
|
break;
|
|
status=data[4].split()[1]
|
|
if status in ['Reachable','Registered']:
|
|
num=data[3].split('/')[1]
|
|
if os.path.isdir(sms_dir + '/' + num + '/'):
|
|
dir=os.listdir(sms_dir + '/' + num + '/')
|
|
dir.sort()
|
|
for sms in dir:
|
|
sms_path=sms_dir + '/' + num + '/' + sms + '/'
|
|
if os.path.isfile(sms_path + 'from') and os.path.isfile(sms_path + 'to') and os.path.isfile(sms_path + 'body'):
|
|
sms_from=open(sms_path + 'from').read()
|
|
sms_to=open(sms_path + 'to').read()
|
|
sms_body=open(sms_path + 'body').read()
|
|
self.send ('action:MessageSend')
|
|
self.send ('to:%s' % sms_to)
|
|
self.send ('from:%s' % sms_from)
|
|
self.send ('Base64Body:%s' % sms_body)
|
|
self.send ( '')
|
|
self.lastsend=(sms_dir + '/' + num + '/',sms_path)
|
|
if data[0] == "Response: Success":
|
|
if self.lastsend:
|
|
shutil.rmtree(self.lastsend[1])
|
|
try:os.rmdir(self.lastsend[0])
|
|
except OSError as e: print(e)
|
|
self.lastsend=None
|
|
if data[0] == "Response: Error":
|
|
self.lastsend=None
|
|
del(data[0])
|
|
except socket.error as e: print(e)
|
|
finally:
|
|
if self.irc:
|
|
try: self.irc.close()
|
|
except: pass
|
|
time.sleep(0.1)
|
|
|
|
def send(self,str):
|
|
print(str)
|
|
msg='%s\r\n' % (str)
|
|
self.irc.send (msg)
|
|
|
|
|
|
|
|
Sms('localhost',5038,'sms','6m6lTaEOTMsyM','/var/spool/asterisk/sms/')
|
|
|