自动判断网络连接状态,如断网则自动进行联网 (特定环境:某高校校园网)

编程环境:python3

使用环境:特定为东北某海滨高校的校园网

功能: 定期判断是否联网,如果网络端口则自动尽量网络连接操作(校园网登录,login认证)

说明:用户名及密码需要依照个人情况改写方可使用(必须是某高校的校园网下才可使用)

 

 

 

# encoding:UTF-8
from urllib.parse import urlencode
from urllib.request import urlopen
import urllib
import os
import sys
import getpass
import time


def login(username="123456", password="123456"):
    # username=input("please input your username\nUsername: ")
    # print "please input your password"
    # password=getpass.getpass()

    opener = urllib.request.build_opener(urllib.request.HTTPRedirectHandler(), urllib.request.HTTPHandler(debuglevel=0))
    opener.addheaders = [('User-agent',
                          "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)")]
    url = 'http://172.20.20.1:801/srun_portal_pc.php?ac_id=3&'

    try:
        response = opener.open(url, urlencode(
            {"ac_id": "3", "action": "login", "nas_ip": "", "password": password, "save_me": "1", "url": "",
             "user_ip": "", "user_mac": "", "username": username}).encode("utf-8"))

        xxx_print = response.read().decode("utf-8")

        if xxx_print.find(u'网络已连接') != -1:
            print('\n\n\n')
            print('##################################')
            print('您已经成功登录')
            print('##################################')
            print('\n\n\n')
        else:
            print('\n\n\n')
            print('##################################')
            print('抱歉,您登录失败')
            print('##################################')
            print('\n\n\n')
            print(xxx_print)
    except Exception as e:
        print('\n\n\n')
        print('##################################')
        print("网络联通有误, 请检测网络是否可达")
        print('##################################')
        print(e)

def ping():
    try:
        response = urllib.request.urlopen("https://www.baidu.com", timeout=10).read().decode("utf-8")
    except urllib.error.URLError as e:
        print(e)
        return False
    return True


if __name__ == "__main__":
    username = "123456"
    password = "123456"

    while True:
        flag = ping()
        
        if flag:
            time.sleep(180)
        else:
            login(username, password)
            

 

 

 

因为校园网运行会突发不稳定问题及定期的认证到期后的自动断网问题,很多人进行远程操作时需要定期的找人给手动联网,这个代码可以实现人在校外,假期在家,出差在外等都能使工作电脑持续保持网络连接状态而且不需要人为干预。

 

 

 

 

 

===========================

 

上一篇:python 爬虫基础


下一篇:简单的python爬虫图片获取