Форум сайта python.su
#!/usr/bin/env python
# -*- coding: utf8 -*-
import telnetlib
import re
import time
import datetime
from MySQLdb import connections
import signal
import sys
sleep_time = 10
voip_host = "192.168.1.1"
voip_port = 23
voip_user = "voip_user"
voip_pass = ""
db_user = 'voip'
db_pass = '12345'
db_host = 'localhost'
db_name = 'voip_switch'
class VoipSwitch():
def __init__(self):
self.tn = telnetlib.Telnet(voip_host, voip_port)
self.tn.read_until("login: ")
self.tn.write(voip_user + "\n")
self.tn.read_until("password: ")
self.tn.write(voip_pass + "\n")
def get_port(self):
self.tn.write("line -print" + "\n")
text = self.tn.read_until("usr/config$ ")
matches = re.findall(r"Busy", text)
return len(matches)
def close(self):
self.tn.write("quit" + "\n")
self.tn.close()
class VoipDatabase():
def __init__(self):
self.con = connections.Connection(db=db_name, host=db_host, user=db_user, passwd=db_pass)
self.cu = self.con.cursor()
def add(self, port):
sql = """INSERT INTO main(port, cur_time) VALUES(%d, NOW());""" % (int(port))
self.cu.execute(sql)
self.con.commit()
def get(self):
sql = """SELECT port, cur_date FROM main;"""
self.cu.execute(sql)
data = []
for tmp in self.cu.fetchaall():
data.append(tmp[0])
return data
def close(self):
self.con.close()
if __name__ == "__main__":
def signal_handler(signal, frame):
global db
global voip
db.close()
voip.close()
sys.exit(0)
def signal_handler2(signal, frame):
global db
global voip
db.close()
voip.close()
sys.exit(0)
voip = VoipSwitch()
db = VoipDatabase()
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler2)
while(1):
port = voip.get_port()
print port, datetime.datetime.now()
db.add(port)
time.sleep(sleep_time)
lat=Regex("LAT")+number
payload = m.get_payload(decode=True)
charset = m.get_content_charset('')
#Строка с сообщением
content=payload.decode(charset)
#Разбор сообщения
llat=lat.parseString(content)
def Opener(self, url, headers, post=None, proxy=None, timeout=None):
socket.setdefaulttimeout(timeout)
upars = urlparse.urlparse(url)
self.headers['Host']= upars.netloc
if proxy:
proxy_handler = urllib2.ProxyHandler({'http':proxy})
opener = urllib2.build_opener(proxy_handler)
urllib2.install_opener(opener)
socket.setdefaulttimeout(self._Setting.proxy['TimeOut'])
if post:
post = urllib.urlencode(post)
req = urllib2.Request(url, post, headers)
try:
conn = urllib2.urlopen(req)
html, info = conn.read(), conn.info()
if html
return(html, info)
else: return False
except:
return False
def Worker(self):
while not self.proxylist.empty():
try: prox = self.proxylist.get()
except: prox = False
if prox:
curentproxy = prox.split(':')[0]
scripthtml = self.Opener(url='http://site1.ru/', headers=self.headers, post = {'zpost':'zpost'}, proxy = prox)
if scripthtml:
kthtml = self.Opener(url='http://site2.ru/', headers=self.headers, post = None, proxy=prox, timeout=20)
if kthtml:
self.htmlForParse.put_nowait((prox, scripthtml[0], kthtml[0]))
self.proxylist.task_done()
time.sleep(0.1)
def Start(self):
for x in xrange(500):
p = threading.Thread(target = self.Worker)
p.setName('Worker' + str(x))
p.start()
self.proxylist.join()
import thread
tread.start_new_thread(self.long, ())
class Item(models.Model):
name = models.CharField(_('Name'), max_length=200)
points = models.IntegerField(_('Points'), default=0)
cluster = models.ForeignKey(Cluster, verbose_name=_('Cluster'))
costumerservice = models.BooleanField(_('Customer Service'), blank=True, default=False)
class Meta:
verbose_name = _('Item')
verbose_name_plural = _('Items')
def __unicode__(self):
return u'%s (%d points)' % (self.name, self.points)
class Report(models.Model):
user = models.ForeignKey(User)
date = models.DateTimeField(_('Date'), default=datetime.now())
country = models.ForeignKey(Country)
publication = models.BooleanField(_('Publication'), blank=True, default=False)
total = models.IntegerField(default=0)
class Meta:
verbose_name = _('Report')
verbose_name_plural = _('Reports')
def cluster_name(self):
return self.country.cluster
def __unicode__(self):
return self.country.country
def save(self, *args, **kwargs):
self.total = 0
for report_item in ReportItem.objects.filter(report=self):
self.total += report_item.item.points * report_item.total
reports = Report.objects.filter(country=self.country, publication=True).all()
super(Report, self).save(*args, **kwargs)
class ReportItem(models.Model):
item = models.ForeignKey(Item)
total = models.IntegerField(default=0)
report = models.ForeignKey(Report, related_name='items', verbose_name=_('Report Item'))