Skip to content

Instantly share code, notes, and snippets.

@dongguosheng
Last active January 3, 2016 08:29
Show Gist options
  • Save dongguosheng/8436087 to your computer and use it in GitHub Desktop.
Save dongguosheng/8436087 to your computer and use it in GitHub Desktop.
TJU更改pppoe后查询流量和账户余额,以及切换账户的小脚本。顺便也体验了一下getter和setter的语法糖和yaml。 之前为固定IP时,切换账户的同时需要切换IP以及mac地址,当时粗暴地使用os.system+cmd和_winreg模块拼凑而成。使用cPickle存储。 运行环境为win server 2003,使用pyinstaller-2.0做成单exe。
accounts:
- {password: 'xxxxxx', username: 'yyyyyy'}
- {password: 'zzzzzz', username: 'lalala'}
ip_using: 0
last_switch: 2014-01-15 20:55:21.551000
# -*- coding: utf-8 -*-
import requests
from pyquery import PyQuery as pq
import yaml
from hashlib import md5
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
class AutoSwitch(object):
'''This class uses the data from the yaml file to decide if switch the account.'''
def __init__(self, filename='accounts.yaml'):
'''Initialize the username, password from the yaml file.'''
with open(filename, 'r') as f:
self.__data = yaml.load(f)
self.__ip_using = self.__data['ip_using']
accounts_dict = self.__data['accounts'][self.__ip_using]
self.__username = accounts_dict['username']
self.__password = accounts_dict['password']
self.__password_md5 = md5(self.__password).hexdigest()[8: -8]
self.__payload = {'drop': '0', 'type': '1', 'n': '100', 'force': 'true', 'username': self.__username, 'password': self.__password_md5}
self.__response = []
self.__surplus_flow = 0
self.__balance = 0
def login(self, url=r'http://202.113.15.129/cgi-bin/do_login'):
'''Login and connect to the Internet.'''
try:
r = requests.post(url, data=self.__payload)
# print r.status_code
except Exception, e:
print e
def __get_response(self, url=r'http://g.tju.edu.cn:8800/do_services.php'):
'''Get the response with network flow and balance.'''
try:
# use wireshark to capture the package
r = requests.post(url, data={'uname': self.__username, 'pass': self.__password, 'save_me': '1'})
self.__response = pq(r.content).find('td').filter('.maintd').eq(19).html().split('\n')
except Exception, e:
print e
@property
def surplus_flow(self):
'''Get the surplus network flow this account.'''
if not self.__response:
self.__get_response()
if self.__response:
surplus_flow_str = self.__response[2][46 : -6]
comma_index = surplus_flow_str.find(',')
return float(surplus_flow_str[: comma_index] + surplus_flow_str[comma_index + 1 :])
@property
def balance(self):
'''Get the balance of this account.'''
if not self.__response:
self.__get_response()
if self.__response:
balance_str = self.__response[1][43 : -7]
return float(balance_str)
@property
def data(self):
return self.__data
@property
def ip_using(self):
return self.__ip_using
@ip_using.setter
def ip_using(self, ip_using):
self.__ip_using = ip_using
@property
def username(self):
return self.__username
def switch_and_login(self, filename='accounts.yaml', is_login=True):
'''Switch to the next account.'''
self.__data['ip_using'] = self.__data['ip_using'] + 1
self.__data['last_switch'] = datetime.now()
if is_login:
accounts_dict = self.__data['accounts'][self.__data['ip_using']]
self.__username = accounts_dict['username']
self.__payload['username'] = accounts_dict['username']
self.__payload['password'] = md5(accounts_dict['password']).hexdigest()[8 : -8]
# print self.__username
self.login()
else:
pass
def save_to_yaml(self, filename='accounts.yaml'):
'''Save data to account.yaml.'''
with open(filename, 'w') as f:
f.write(yaml.dump(self.__data))
class Message(object):
'''Email util.'''
def __init__(self, mailto_list=['xxxxxx@qq.com'], mail_host='smtp.126.com',
mail_user='yyyyyy', mail_password='zzzzzz', mail_postfix='126.com'):
'''Initialize the Message util.'''
self.mailto_list = mailto_list
self.mail_host = mail_host
self.mail_user = mail_user
self.mail_password = mail_password
self.mail_postfix = mail_postfix
self.__subject = ''
self.__content = ''
self.server = smtplib.SMTP()
@property
def subject(self):
return self.__subject
@property
def content(self):
return self.__content
@subject.setter
def subject(self, subject):
self.__subject = subject
@content.setter
def content(self, content):
self.__content = content
def send_mail(self):
'''Send mail.'''
self.msg = MIMEText(self.__content, _subtype='plain', _charset='utf-8')
self.msg['Subject'] = self.__subject
self.msg['From'] = '<' + self.mail_user + '@' + self.mail_postfix + '>'
self.msg['To'] = ';'.join(self.mailto_list)
try:
self.server.connect(self.mail_host)
self.server.login(self.mail_user, self.mail_password)
self.server.sendmail(self.msg['From'], self.mailto_list, self.msg.as_string())
self.server.close()
print 'email succeed.'
return True
except Exception, e:
print str(e)
print 'email failed.'
return False
def sendmail(subject, content):
msg = Message()
msg.subject = subject
msg.content = content
msg.send_mail()
def main():
auto_switch = AutoSwitch()
auto_switch.login()
if auto_switch.ip_using == len(auto_switch.data['accounts']) - 2:
sendmail(u'本月账户即将用尽', u'本月账户仅剩两个,请提前做好准备。')
if auto_switch.surplus_flow < 0.1 and auto_switch.ip_using < len(auto_switch.data['accounts']) - 1:
auto_switch.switch_and_login()
auto_switch.save_to_yaml()
sendmail(u'账户切换通知', u'账户已切换为' + auto_switch.username)
print auto_switch.username
print u'剩余流量', auto_switch.surplus_flow, 'M'
print u'账户余额', auto_switch.balance, u'元'
if datetime.now().day == 1 and datetime.now().hour > 0 and datetime.now().hour < 8:
auto_switch.ip_using = 0
auto_switch.save_to_yaml()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment