selenium 实现开机自动登录认证网络(校园网)

最近,需要远程操控电脑,但是被控电脑总是时不时卡顿或者断网,又不敢远程重启,因为重启需要登录校园网,因此基于 selenium 写了一个开机脚本用于开机自动连接校园网

开机脚本总共 4个文件
在这里插入图片描述
loginhit.py 文件

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("****")
            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))

activate.bat 文件

cmd /k "timeout /t 5&&D:\2020\Python\Pycharm\env\Scripts\python.exe loginhit.py"

使用 Win+R 弹出运行窗口,输入以下代码浏览开机启动项文件夹

shell:startup

在这里插入图片描述
把 activate.bat 快捷方式放到开机启动项即可

猜你喜欢

转载自blog.csdn.net/chaoge_dgqb/article/details/107910858