Python 實現斷網自動重連

.未央發表於2021-10-18
為了實現 斷網了,自動連線網路

原理:每隔一段時間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)

相關文章