Python 实现断网自动重连
为了实现 断网了,自动连接网络
原理:每隔一段时间ping一下百度,判断网络状态,没有联网的话,就模仿浏览器发一条Post给服务器
import urllib
import hashlib
import subprocess
import os
import time
def getPass(password):
pass1 = hashlib.md5()
pass1.update(password)
pass2 = pass1.hexdigest()
return pass2[8:24]
def postLogin(url, user, password):
pass2 = getPass(password)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393'}
post_data = {'username': user, 'password': pass2, 'drop': '0', 'type': '1', 'n': '100'}
post_data = urllib.urlencode(post_data)
req = urllib.Request(url, post_data, headers)
response = urllib.urlopen(req)
#就是Post的内容了,当然密码是MD5加密过后的,这个随便找找也没有问题的
#接下来是 检测网络是否连接,我采用Ping百度的办法,毕竟这是百度最大的功能之一,网上参考一下别人的代码
def ping(user, password):
fnull = open(os.devnull, 'w')
return1 = subprocess.call('ping 61.135.169.125', shell=True, stdout=fnull, stderr=fnull)
if return1:
print_ts('Internet not connected!')
print_ts('Connecting now...')
postLogin('http://159.226.39.22/cgi-bin/do_login', user, password)
ping(user, password)
else:
print_ts('Internet connected!')
fnull.close()
def print_ts(message):
print("[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), message))
# 定时运行,需要用到Python的time模块
def run(interval, user, password):
print_ts("-" * 50)
print_ts('Copyright (c) Huntley')
print_ts('Email:zhangzihao@ict.ac.cn')
print_ts('')
print_ts("Check the Internet every %s seconds." % interval)
print_ts("-" * 50)
while True:
try:
time_remaining = interval - time.time() % interval
time.sleep(time_remaining)
print_ts("Checking Internet connection...")
ping(user, password)
print_ts("Next check will start after %s seconds" % interval)
except Exception as e:
print(e)
if __name__ == '__main__':
# 设置联网检查时间间隔
# interval = 600
interval = 10
# 设置用户名
user = 'TYPE YOUR USERNAME HERE'
# 设置密码
password = 'TYPE YOUR PASSWORD HERE'
# 运行
run(interval, user, password)