脚本解放双手:用selenium自动化连接北师大校园网

手把手教你无限自动连接北师大校园网

0 编写目的

快寒假了,和大家一样都要回老家过年。奈何有任务压在头上,数据又在实验室的电脑上带不走,笔者和很多人一样选择远程办公。
主机科研24小时运行,但问题就出在时而断掉的校园网上,要是实验室这边的网络断掉,我就没法愉快地远程操作了。于是笔者就动了念头写个python小程序,想来实现:

  1. 自动连接校园网
  2. 能隔30分钟就检查计算机网络连接状态,断线了自动执行1

1 自动连接校园网

1.1 工具:

  • 一个大家都有的python(笔者用的是python 3.7,3以上版本随意),安装好selenium包,这里推荐pip方式。
pip install selenium 
  • chromedriver.exe,从下面获取吧

链接:https://pan.baidu.com/s/11JhQrybfS1tdDIdlRiKyig
提取码:182h

废话不多说,先上代码。小伙伴可以直接Copy源码,改成你的学号和密码,保存成.py后缀格式的文件了。

1.2 代码:

from selenium import webdriver
import requests
import time


stop = False
success=False
trynum=0
while not stop:
    try:
        trynum+=1
        with open("login.log",'a') as f:
            f.writelines('\n'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
            f.writelines("\n第 {0} 次尝试连接 https://www.baidu.com".format(trynum))
        print("第 {0} 次尝试连接 https://www.baidu.com".format(trynum))
        r = requests.get("https://www.baidu.com")
        r.raise_for_status()
        if (r.status_code == 200):
            stop = True
            success=True

    except:
        print("无法连接,开始执行登录脚本")
        option = webdriver.ChromeOptions()
        option.add_argument('headless')
        driver = webdriver.Chrome('chromedriver.exe',options=option)
        try:
            driver.get("http://172.16.202.204/srun_portal_pc?ac_id=1&theme=bnu")
            driver.find_element_by_id('username').clear()
            driver.find_element_by_id('username').send_keys("***********")     # 将*替换成账号
            driver.find_element_by_id('password').clear()
            driver.find_element_by_id('password').send_keys("**********")      # 将*替换成密码
            driver.find_element_by_id('login').click()
            print("执行登录脚本完成")
        except Exception as e:
            # print(e)
            stop=True
            success=False
            with open("login.log", 'a') as f:
                f.writelines("\n发生错误:网络不通")
    time.sleep(1)
if(success):
    print("登陆成功")
    with open("login.log", 'a') as f:
        f.writelines("\n成功连接 https://www.baidu.com")
else:
    print("登陆失败:无网络")
    with open("login.log", 'a') as f:
        f.writelines("\n在第 {0} 次尝试后失败".format(trynum))

1.3 打包程序:

在这里插入图片描述

将上面的python文件打包成exe

pyinstaller -F D:\autostart\hq\hqloginhit.py

在这里插入图片描述

你可以尝试一下这个程序

在这里插入图片描述

2 隔30分钟自动检测、自动连接

恭喜你拥有了一个自动连接北师大校园网的脚本,运用电脑自带的事件程序实现每隔30分钟检测和连接WIFI

2.1 创建任务

打开window自带的事件管理器(此电脑->管理),点击右侧创建任务

在这里插入图片描述

在这里插入图片描述

2.2 设置任务:

按照截图设置任务即可,记得修改你的路径:

在这里插入图片描述

在这里插入图片描述

将我们刚刚做好的exe文件放到操作里去
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

点击确定,结束!!!

恭喜走到这一步的你,搞定这不稳定的WIFI,现在可以配合远程设备无所顾忌地办公啦,享受永远不用打开校园网连接页面,享受即用即连的快乐吧~

猜你喜欢

转载自blog.csdn.net/qq_42671556/article/details/122396158