# coding=utf-8 import os, sys, pymysql, re, time from ldap3 import Server, Connection, NTLM def application(environ, start_response): #sys.stdout._encoding = 'utf-8'замена сцепления патриот стоимость работ смоленск status = '200 OK' # проверяем наличие параметров в запросе и всяко-разно реагируем if environ['QUERY_STRING'] == '': output = bytes((header() + body() + footer()).encode('utf8')) elif environ['QUERY_STRING'].split('&'): paramDict = {item.split('=')[0]: item.split('=')[1] for item in environ['QUERY_STRING'].split('&')} if paramDict.get('query_type') == 'internal': output = bytes((header() + body() + getInternalNumbers() + footer()).encode('utf8')) elif paramDict.get('query_type') == 'external': output = bytes((header() + body() + getCOline() + footer()).encode('utf8')) elif paramDict.get('query_type') == 'report': output = bytes((header() + body() + ReportForm() + ReportData(environ) + footer()).encode('utf8')) elif paramDict.get('query_type') == 'ldap': domain = paramDict.get('domain') group = paramDict.get('group') output = bytes((header() + body() + getLDAPusers(domain, group) + footer()).encode('utf8')) else: output = bytes((header() + body() + footer()).encode('utf8')) response_headers = [('Content-type', 'text/html;charset=utf-8'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] def header(): txtHeader = '\n' \ '\n' \ '\n' \ 'Телефоны\n' \ '\n' return txtHeader def footer(): txtFooter = '\n' return txtFooter def body(): txtBody = '\n' \ '

ТЕЛЕФОНЫ

{}
\n'.format(menu()) return txtBody def menu(): #
txtMenu = '
\n' return txtMenu def getInternalNumbers(): conn = connectDB() c = conn.cursor() order = 'int_number' result = '

Список внутренних телефонов

' qwr = "SELECT * FROM int_number ORDER by " + order c.execute(qwr) listHeader = '\n' \ '\n' \ '\n' \ '\n' result = result + listHeader for row in c.fetchall(): rowData = "\n" % (row[0], row[1], row[2], row[4], row[3]) result = result + rowData return (result + "
№ п/пТелефонФИООписаниеЭлектро-почта
%s%s%s%s%s
\n") # Список пользователей (ФИО, телефон, почта, отдел) из LDAP (AD) def getLDAPusers(domain, group): order = 'int_number' if domain == 'domain1': head = '

Для внешних абонентов звонить на xxxxxx + добавочный номер

' org = '1' s = Server('192.168.1.1') c = Connection(s, user='domain1\\phone', password="pass", authentication=NTLM) # perform the Bind operation if not c.bind(): print('error in bind', c.result) c.search('OU=users,dc=domain1,dc=local', '(objectclass=person)', attributes=['cn', 'mail', 'telephoneNumber', 'department', 'title', 'mobile']) elif domain == 'domain2': head = '

Для внешних абонентов звонить на xxxxxxx + добавочный номер

' org = '2' s = Server('192.168.2.2') c = Connection(s, user='domain2\\phone', password="pass", authentication=NTLM) # perform the Bind operation if not c.bind(): print('error in bind', c.result) c.search('OU=users,dc=domain2,dc=local', '(objectclass=person)', attributes=['cn', 'mail', 'telephoneNumber', 'department', 'title', 'mobile']) elif domain == 'domain3': head = '

Для внешних абонентов звонить на xxxxxxx + добавочный номер

' org = '3' s = Server('192.168.3.3') c = Connection(s, user='domain3\\phone', password="pass", authentication=NTLM) # perform the Bind operation if not c.bind(): print('error in bind', c.result) c.search('OU=users,dc=domain3,dc=local', '(objectclass=person)', attributes=['cn', 'mail', 'telephoneNumber', 'department', 'title', 'mobile']) result = '

Список абонентов %s

\n%s' % (org, head) #return (result + "\n") # listHeader = '\n' \ # '\n' \ # '\n' \ # '\n' \ # '\n' listHeader = '
ФИООтделДолжностьТелефонЭл.почтаМобильный телефон
\n' \ '\n' \ '\n' \ '\n' \ '\n' result = result + listHeader for item in c.entries: # print(item) # item = re.sub('\n', '', str(item)) item = str(item) name = re.search('(cn:)(.+?)(\n)', item) if name: name = name.groups()[1] else: name=name #print(name.groups()[1]) department = re.search("(department:)(.+?)(\n)", item) if department: dep = department.groups()[1] else: dep = "" title = re.search("(title:)(.+?)(\n)", item) if title: title = title.groups()[1] else: title = "" mail = re.search("(mail:)(.+?)(\n)", item) if mail: mail = mail.groups()[1] else: mail = "" telephone = re.search("(telephoneNumber:)(.+?)(\n)", item) if telephone: phone = telephone.groups()[1] else: phone = "" mobile = re.search("(mobile:)(.+?)(\n)", item) if mobile: mobile = mobile.groups()[1] else: mobile = "" rowData = "\n" % (name, dep, title, phone, mail, mail, mobile) result = result + rowData return (result + "
ФИООтделДолжностьТелефонЭл.почтаМобильный телефон
%s%s%s%s%s%s
\n") def getCOline(): conn = connectDB() c = conn.cursor() order = 'ext_co_line' result = '

Список внешних линий

' qwr = "SELECT * FROM ext_co_line ORDER by " + order c.execute(qwr) listHeader = '\n' \ '\n' \ '\n' \ '\n' result = result + listHeader for row in c.fetchall(): rowData = "" % (row[0], row[1], row[2], row[3]) result = result + rowData return (result + "
№ п/пЛинияНомер телефонаОписание
%s%s%s%s
\n") def ReportForm(): txtReportForm = '

Отчёт по звонкам

' return txtReportForm def ReportData(environ): paramDict = {item.split('=')[0]: item.split('=')[1] for item in environ['QUERY_STRING'].split('&')} # проверка корректности параметров # внутренний номер (3 цифры 100-999) templateNumber = '(^[1-9][0-9][0-9]$)' if re.match(templateNumber, str(paramDict.get('int_number'))) is not None: numbers = paramDict.get('int_number') else: return ErrorMessage('Введите внутренний номер') # проверка и преобразование дат в удобоваримый для субд формат templateDate = '^(0[1-9]|[12][0-9]|3[01])[.](0[1-9]|1[012])[.](19|20)[0-9][0-9]$' if re.match(templateDate, str(paramDict.get('date_begin'))) is not None: date_begin = time.strftime("%Y-%m-%d", time.strptime(str(paramDict.get('date_begin')), "%d.%m.%Y")) else: return ErrorMessage('Неверный формат даты начала периода') if re.match(templateDate, paramDict.get('date_end')) is not None: date_end = time.strftime("%Y-%m-%d", time.strptime(str(paramDict.get('date_end')), "%d.%m.%Y")) else: return ErrorMessage('Неверный формат даты окончания периода') conn = connectDB() c = conn.cursor() order = 'call_date' result = '
' \ '
' \ '
' \ '' \ '' \ '' \ '
' \ '
' \ '' \ '

Список звонков с номера {}

'.format(numbers) qwr = "SELECT * FROM cdr where int_number=\'{}\' AND call_date BETWEEN CAST(\'{}\' AS DATE) AND CAST(\'{}\' AS DATE) LIMIT 1000".format(numbers, date_begin, date_end) c.execute(qwr) listHeader = '' \ '' \ '\n' result = result + listHeader for row in c.fetchall(): rowData = ''\ .format(row[0], row[1], row[2], row[3], row[4], row[5], row[5], row[7], row[9], row[9], row[10]) result = result + rowData return (result + "
№ п/пДатаВремяВнут.номерВнеш.линияВызываемый номерRingДлительностьАССКод звонкаНаправление
{}{}{}{}{}{}{}{}{}{}{}
\n" + qwr) def ErrorMessage(txt): return ('{}'.format(txt)) def connectDB(): c = pymysql.connect( db='ats', user='ats', passwd='pass', host='x.x.x.x', charset='utf8') return c