标签:
该脚本一直监测网络连接情况,若出现断网情况,自动连接网络。
话不多说,直接贴代码:
NetLogin.py
1 #coding: utf-8 2 3 import requests 4 import time 5 import datetime 6 import sys 7 8 reload(sys) 9 sys.setdefaultencoding("utf-8") 10 11 class NetLogin: 12 13 def __init__(self): 14 self.login_url = ‘http://p.nju.edu.cn/portal_io/login‘ 15 self.info_url = ‘http://p.nju.edu.cn/portal_io/getinfo‘ #登录状态下获取,方式:get 16 self.logout_url = ‘http://p.nju.edu.cn/portal_io/logout‘ 17 self.headers = { 18 ‘Accept‘: ‘text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8‘, 19 ‘Referer‘: ‘http://p.nju.edu.cn/‘, 20 ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36‘, 21 ‘X-Requested-With‘: ‘XMLHttpRequest‘ 22 } 23 24 self.form_data = { 25 ‘username‘: ‘MGxxxxxxx‘, 26 ‘password‘: ‘xxxxxx‘ 27 } 28 self.timeout = 5 29 30 self.test_url = ‘http://www.baidu.com/‘ 31 self.testStr = "030173" 32 33 34 def net_test(self): 35 try: 36 s = requests.session() 37 r = s.get(self.test_url, headers=self.headers, timeout=self.timeout) 38 pos = r.content.find(self.testStr) 39 if pos >= 1: 40 #print ‘Internet Ok‘ 41 return ‘Internet Ok‘ 42 else: 43 #print ‘Internet Wrong‘ 44 return ‘Internet Wrong‘ 45 except Exception, e: 46 print e 47 48 49 50 51 def create_session(self): 52 s = requests.session() 53 return s 54 55 def login(self): 56 s = self.create_session() 57 r = s.post(self.login_url, self.form_data, headers=self.headers) 58 if r.json()[‘reply_code‘] == 1: 59 print r.json()[‘reply_msg‘] 60 return r.json()[‘reply_msg‘] 61 else: 62 #print u"login failed" 63 return u"login failed" 64 65 #获取登录信息,需要完成登录后执行该函数 66 def getInfo(self): 67 s = self.create_session() 68 r = s.get(self.info_url, headers=self.headers) 69 70 #网络注销 71 def logout(self): 72 s = self.create_session() 73 r = s.post(self.logout_url, headers=self.headers) 74 75 76 if __name__ == "__main__": 77 net = NetLogin() 78 signal = net.net_test() 79 #log = open(‘netlog.txt‘, ‘a‘) 80 while True: 81 if signal == ‘Internet Ok‘: 82 #s = str(datetime.datetime.now()) 83 print datetime.datetime.now() 84 print signal 85 ‘‘‘ 86 log.write(s) 87 log.write(‘\n‘) 88 log.write(signal) 89 log.write(‘\n‘) 90 ‘‘‘ 91 92 else: 93 #s = str(datetime.datetime.now()) + ‘:‘ 94 print signal 95 str = net.login() 96 print datetime.datetime.now() 97 print str 98 ‘‘‘ 99 log.write(s) 100 log.write(‘\n‘) 101 log.write(str) 102 log.write(‘\n‘) 103 ‘‘‘ 104 time.sleep(1) 105 signal = net.net_test() 106 ‘‘‘ 107 num += 1 108 if num == 5: 109 flag = False 110 ‘‘‘ 111 112 #log.close()
标签:
原文地址:http://www.cnblogs.com/nju2014/p/4681890.html