Python
import requests
import time
import logging
import os
log_dir = "C:\\netlog"
log_file = os.path.join(log_dir, "network_connector.log")
try:
if not os.path.exists(log_dir):
os.makedirs(log_dir)
logging.info(f"文件夹: {log_dir}")
except Exception as e:
log_file = os.path.join(os.path.expanduser("~"), "network_connector.log")
print(f"创建C:\\netlog文件夹失败: {log_file}")
print(f"err: {str(e)}")
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler()
]
)
LOGIN_URL = "http://192.168.200.5/"
CHECK_URL = "https://www.baidu.com"
USERNAME = ""
PASSWORD = ""
CHECK_INTERVAL = 60
TIMEOUT = 10
def is_connected():
try:
response = requests.get(CHECK_URL, timeout=TIMEOUT)
return response.status_code == 200
except:
return False
def login():
try:
session = requests.Session()
response = session.get(LOGIN_URL, timeout=TIMEOUT)
login_data = {
"DDDDD": USERNAME,
"upass": PASSWORD,
"0MKKey": "登录 Login",
"v6ip": ""
}
login_response = session.post(LOGIN_URL, data=login_data, timeout=TIMEOUT)
if is_connected():
logging.info("成功")
return True
else:
logging.error("%s", login_response.text[:200])
return False
except Exception as e:
logging.error(" %s", str(e))
return False
def main():
logging.info(f"保存至: {log_file}")
logging.info(f"地址: {LOGIN_URL}")
logging.info(f"间隔: {CHECK_INTERVAL}秒")
while True:
if not is_connected():
logging.warning("another")
for i in range(3):
if login():
break
if i < 2:
time.sleep(10)
else:
logging.error("3f")
else:
logging.debug("win")
time.sleep(CHECK_INTERVAL)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
logging.info("handerr")
except Exception as e:
logging.critical(" %s", str(e), exc_info=True)