Commit 124d4a83 authored by Valentin Samir's avatar Valentin Samir

Ajout des script pour asterisk

parent e9bae60e
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import time
import sys
timeout=10
server="asterisk.adm.crans.org"
port=5038
user="django"
password="HLWkzyITZAmBk"
reload_srv={
'sip':['chan_sip'],
'voicemail':['app_voicemail'],
'dialplan':['pbx_config'],
'all':['chan_sip','app_voicemail','pbx_config'],
}
def reload_config(config):
if not config in reload_srv.keys():
print >> sys.stderr, "Reload config from : \n * %s" % ('\n * '.join( reload_srv.keys()))
return
sock = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
def send(str):
msg='%s\r\n' % (str)
sock.send (msg)
sock.settimeout(timeout)
sock.connect ( ( server, port ) )
send ( 'ACTION: LOGIN')
send ( 'USERNAME: %s' % user)
send ( 'SECRET: %s' % password)
send ( '')
for module in reload_srv[config]:
send ( 'ACTION: RELOAD')
send ( 'MODULE: %s' % module)
send ( 'ActionID: %s' % time.time())
send ( '')
send ( 'ACTION: LOGOFF')
send ( '')
data=[]
while True:
data.extend(sock.recv( 4096 ).split('\r\n'))
if data==['']:
sock.close()
return
while len(data)>0:
del data[0]
sock.close()
if __name__ == '__main__' :
if len(sys.argv)<2:
print >> sys.stderr, "Usage %s [%s]" %(sys.argv[0],'|'.join(reload_srv.keys()))
print >> sys.stderr, "Reload config from : \n * %s" % ('\n * '.join(reload_srv.keys()))
exit(1)
reload_config(sys.argv[1])
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from sh import grep,ErrorReturnCode_1
sys.path.append('/usr/scripts/gestion')
sys.path.append('/usr/scripts/lc_ldap')
sys.path.append('/etc/crans/secrets/')
import lc_ldap
conn=lc_ldap.lc_ldap_admin()
try:
aid=int(sys.argv[1][1:])
except ValueError:
sys.stdout.write('NONE')
exit(0)
login=conn.search("aid=%s" % aid)[0]['uid'][0]
try:
sys.stdout.write(grep('-r',login,'/usr/scripts/var/digicode/').split('/')[-1].split(':')[0])
except ErrorReturnCode_1: sys.stdout.write('NONE')
#!/bin/bash
printf -v id "%q" "$1"
printf -v src "%q" "$2"
printf -v dst "%q" "$3"
psql -h pgsql.adm.crans.org -U crans django -c "INSERT INTO voip_history (uniq_id,src,dst) VALUES ('$id','$src','$dst')" >> /tmp/history
#!/bin/bash
printf -v id "%q" "$1"
psql -h pgsql.adm.crans.org -U crans django -c "DELETE FROM voip_history WHERE uniq_id='$id'" >> /tmp/history
#!/bin/bash
printf -v id "%q" "$1"
printf -v duration "%q" "$2"
psql -h pgsql.adm.crans.org -U crans django -c "UPDATE voip_history SET duration='$duration' WHERE uniq_id='$id'" >> /tmp/history
#!/bin/bash
printf -v limit "%q" "$1"
printf -v num "%q" "$2"
date=`date +"%Y-%m-01"`
num_call=`psql -h pgsql.adm.crans.org -U crans django --no-align -c "SELECT count(DISTINCT dst) FROM voip_history WHERE date>'$date' AND dst LIKE '+%'" | tail -n 2 | head -n 1`
if [[ $num_call = "" ]]; then
echo -n DENY
exit -1
fi
if [[ $num_call -ge $limit ]]; then
result=$((`psql -h pgsql.adm.crans.org -U crans django --no-align -c "SELECT dst FROM voip_history WHERE date>'$date' AND dst='$num'" | wc -l` -2))
if [[ $result -ge 1 ]]; then
echo -n ALLOWED
else
echo -n DENY
fi
else
echo -n ALLOWED
fi
exit 0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import psycopg2
sys.path.append('/usr/scripts/gestion')
sys.path.append('/usr/scripts/lc_ldap')
sys.path.append('/etc/crans/secrets/')
import lc_ldap
try:
conn = psycopg2.connect("dbname='django' user='crans' host='pgsql.adm.crans.org'")
cur = conn.cursor()
cur.execute("""SELECT caller_id from voip_profile WHERE num='%s'""" % sys.argv[1])
caller_id = cur.fetchall()[0][0]
if caller_id == 'full_name' or caller_id == 'both':
conn=lc_ldap.lc_ldap_admin()
aid=int(sys.argv[1][1:])
adh=conn.search('aid=%s' % aid)[0]
sys.stdout.write('%s %s' % (adh['prenom'][0],adh['nom'][0]))
else:
sys.stdout.write(sys.argv[1])
except:
sys.stdout.write(sys.argv[1])
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys,os,hashlib
sys.path.append('/usr/scripts/gestion')
sys.path.append('/usr/scripts/lc_ldap')
sys.path.append('/etc/crans/secrets/')
import secrets,lc_ldap
from sh import asterisk
conn=lc_ldap.lc_ldap_admin()
def gen_multidial(droit):
dial="exten => %(droit)s,1,Ringing\nexten => %(droit)s,n,Wait(4)\nexten => %(droit)s,n,Answer\nexten => %(droit)s,n,Dial(" % {'droit':droit}
adhs=conn.search('(&(droits=%s)(!(chbre=EXT)))' % droit)
for nounou in adhs:
dial+="SIP/1%04d&" % nounou['aid'][0].value
return dial[:-1]+",30)\nexten => %(droit)s,n,Wait(3)\nexten => %(droit)s,n,VoiceMail(%(droit)s@666)\nexten => %(droit)s,n,Hangup()\n" % {'droit':droit}
multidial=gen_multidial('nounou') + gen_multidial('bureau') + gen_multidial('cableur') + gen_multidial('imprimeur')
multidial_md5=hashlib.md5(multidial).hexdigest()
multidial_old_md5=hashlib.md5(open('/usr/scripts/var/sip/sip_multidial','r').read()).hexdigest()
if multidial_md5 !=multidial_old_md5:
file=open('/usr/scripts/var/sip/sip_multidial.new','w')
file.write(multidial)
file.close()
os.rename('/usr/scripts/var/sip/sip_multidial.new','/usr/scripts/var/sip/sip_multidial')
print asterisk('-x','dialplan reload')
#!/bin/bash
from="$1"
to="$2"
body="$3"
user="$4"
SMS_DIR="/var/spool/asterisk/sms/"
date=`date +%Y%m%d%H%M%S`
mkdir -p "${SMS_DIR}${user}/${date}"
echo -n "$from" > "${SMS_DIR}${user}/${date}/from"
echo -n "$to" > "${SMS_DIR}${user}/${date}/to"
echo -n "$body" > "${SMS_DIR}${user}/${date}/body"
#!/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/')
#!/bin/bash
pass=$3
pass=$((pass))
num=$2
num=$((num))
psql -h pgsql.adm.crans.org -U crans django -c "UPDATE voip_profile SET voicemail_password='$pass' WHERE num='$num'" >> /tmp/pin
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append('/usr/scripts/gestion')
sys.path.append('/usr/scripts/lc_ldap')
sys.path.append('/etc/crans/secrets/')
import secrets,lc_ldap
conn=lc_ldap.lc_ldap_admin()
try:
if len(sys.argv[1])==5:
aid=int(sys.argv[1][1:])
else:
raise ValueError('Pas un numero valide')
except ValueError:
sys.stdout.write('FALSE')
exit(0)
if conn.search("aid=%s" % aid):
sys.stdout.write('TRUE')
else:
sys.stdout.write('FALSE')
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment