需要用到山东大学校园网,实现断网自动重连。
代码实现如下:
coding=utf-8 import requests import time import os import subprocess import re class Reconnect: # 初始化 def __init__(self): # 检测间隔时间,单位为秒 self.every = 10 # 获取当前时间戳,13位 def getNowTime(self): return str(int(time.time())) + "000" # 获取ip def get_ipconfig_ip(self): ipconfig_result_list = os.popen('ipconfig').readlines() # 执行cmd命令ipconfig,并将结果存于ipconfig_result_list for i in range(0, len(ipconfig_result_list)): # 逐行查找 if re.search(r'无线局域网适配器 WLAN', ipconfig_result_list[i]) != None: for j in range(1, 8): if re.search(r"IPv4 地址", ipconfig_result_list[i + j]) != None: match_ip = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', ipconfig_result_list[i + j]).group( 0) # 由正则表达式获取ip地址 return match_ip return None # 模拟登录 def login(self): print(self.getCurrentTime(), u"拼命连网中...") url = "http://192.168.8.10/portal/login.jsp?Flag=0" # 消息头 headers = { 'Host': "192.168.8.10", 'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36", 'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", 'Accept-Language': "zh-CN,zh;q=0.8", 'Accept-Encoding': "gzip, deflate", 'Referer': "http://192.168.8.10/portal/index_default.jsp?Language=Chinese", 'Upgrade - Insecure - Requests': '1', 'Cache - Control': 'max - age = 0', 'Connection': "keep-alive", 'Origin': 'http://192.168.8.10', 'Content-Type': "application/x-www-form-urlencoded", 'Content-Length': '360' } self.ip=self.get_ipconfig_ip() # 提交的信息 data = { 'Language': 'Chinese', 'ClientIP': self.ip, 'timeoutvalue': '45', 'heartbeat': '240', 'fastwebornot': False, 'StartTime': self.getNowTime(), 'username': '',#输入学号 'password': '',#输入密码 'shkOvertime': '720', 'strOldPrivateIP': self.ip, 'strOldPublicIP': self.ip, 'strPrivateIP': self.ip, 'PublicIP': self.ip, 'iIPCONFIG':0, 'sHttpPrefix': 'http://192.168.8.10' } try: r = requests.post(url, headers=headers, data=data) print(r.text) print(self.ip) print(self.getCurrentTime(), u'连上了...现在开始看连接是否正常') except: print("连接失败") def canConnect(self): fnull = open(os.devnull, 'w') result = subprocess.call('ping www.baidu.com', shell=True, stdout=fnull, stderr=fnull) fnull.close() if result: return False else: return True # 获取当前时间 def getCurrentTime(self): return time.strftime('[%Y-%m-%d %H:%M:%S]', time.localtime(time.time())) # 主函数 def main(self): print(self.getCurrentTime(), u"Hi,欢迎使用自动登陆系统") while True: self.login() while True: can_connect = self.canConnect() if not can_connect: print(self.getCurrentTime(), u"断网了...") self.login() else: print(self.getCurrentTime(), u"一切正常...") time.sleep(self.every) time.sleep(self.every) reconnect = Reconnect() reconnect.main()
转载自https://blog.csdn.net/yyhui95/article/details/73008602