别给我搞炸了

This commit is contained in:
Pyhtagodzilla 2025-06-04 15:24:13 +08:00
commit 81553d27a2
5 changed files with 168 additions and 0 deletions

101
Authtication.py Normal file
View File

@ -0,0 +1,101 @@
import os
import requests
import selenium.common.exceptions
import urllib3
import logging
from dotenv import load_dotenv
from selenium import webdriver
from selenium.webdriver.common.by import By
logging.basicConfig(
level=logging.INFO,
format="%(levelno)s - %(levelname)s - %(asctime)s - %(name)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
filename="log.log",
filemode="a"
)
class BUCTAU:
def __init__(self):
load_dotenv()
self.USER_USERNAME = os.environ.get('BUCT_AUTHENTICATION_USERNAME')
self.USER_PASSWORD = os.environ.get('BUCT_AUTHENTICATION_PASSWORD')
self.USER_NAME = os.getlogin()
logging.info(f"USER now is {self.USER_NAME}")
logging.info(f"BUCTAU initialized with username:{self.USER_USERNAME}")
logging.info(f"BUCTAU initialized with password:{self.USER_PASSWORD}")
# print(f"USER now is {self.USER_NAME}")
# print("BUCTAU initialized with username:", self.USER_USERNAME)
# print("BUCTAU initialized with password:", self.USER_PASSWORD)
@staticmethod
def init_driver_edge():
"""Initialize the Selenium WebDriver with Edge options.
Returns:
WebDriver: The initialized Selenium WebDriver instance.
"""
from selenium.webdriver.edge.options import Options
from selenium.webdriver.edge.service import Service
service = Service()
options = Options()
options.add_argument("--headless") # Run in headless mode
options.add_argument("--no-sandbox")
# options.add_experimental_option("detach", True)
driver = webdriver.Edge(service=service, options=options)
driver.implicitly_wait(5) # Implicit wait for elements to load
return driver
@staticmethod
def init_driver_chrome():
"""Initialize the Selenium WebDriver with Chrome options.
Returns:
WebDriver: The initialized Selenium WebDriver instance.
"""
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
service = Service(executable_path="/usr/bin/chromedriver")
options = Options()
options.add_argument("--headless") # Run in headless mode
options.add_argument("--no-sandbox")
# options.add_experimental_option("detach", True)
driver = webdriver.Chrome(service=service, options=options)
driver.implicitly_wait(5) # Implicit wait for elements to load
return driver
def login(self, driver):
"""open the page and login"""
logging.info("LOGIN")
driver.get("https://tree.buct.edu.cn/index_20.html")
driver.maximize_window()
try:
driver.find_element(By.XPATH, '/html/body/main/section/div[1]/div[2]/input').send_keys(self.USER_USERNAME)
driver.find_element(By.XPATH, '//*[@id="password"]').send_keys(self.USER_PASSWORD)
driver.find_element(By.XPATH, '/html/body/main/section/div[1]/div[8]/button[1]').click()
return True
except selenium.common.exceptions.NoSuchElementException as e:
logging.info("NoSuchElementException: ", e)
return False
@staticmethod
def detect_net():
# noinspection PyBroadException
try:
detector = requests.get(url="https://www.baidu.com", timeout=5)
if detector.status_code == 200:
logging.info("Network is available")
return True
else:
logging.info("Network is not available")
return False
except urllib3.exceptions.MaxRetryError:
logging.info("MaxRetryError: False")
return False
except requests.ConnectionError:
logging.info("ConnectionError: False")
return False
except Exception:
return False

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Zhou Zhaoyu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

15
README.md Normal file
View File

@ -0,0 +1,15 @@
# BUCT校园网自动认证
使用selenium实现将edge的webdriver放入系统路径。准备使用树莓派进行自动定时认证。
# 食用
## 配置selenium环境
### Windows
1. Python和pip安装加入环境变量
2. 用pip安装selenium库
3. 下载相应浏览器版本的webdriver并存入环境变量
4. run code
### Rasbian
1. 安装selenium库
`sudo apt-get install python3-selenium`
他会**自行**安装**所有**需要的库、Webdriver、chronium等等。

5
requirements.txt Normal file
View File

@ -0,0 +1,5 @@
requests~=2.32.3
selenium~=4.31.0
urllib3~=2.4.0
dotenv~=0.9.9
python-dotenv~=1.1.0

26
run.py Normal file
View File

@ -0,0 +1,26 @@
import time
import logging
from Authtication import BUCTAU
def main():
"""Main function to run the script."""
authenticator = BUCTAU()
driver = authenticator.init_driver_edge()
past_time = time.time()
while True:
if time.time() - past_time > 10.0:
if authenticator.detect_net():
past_time = time.time()
continue
else:
authenticator.login(driver)
past_time = time.time()
continue
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
logging.info("Script interrupted by user. Exiting...")
except Exception as e:
logging.error(f"An error occurred: {e}")