#文件名 pyWIFI.py
#python自动检测wifi是否能联网,断开wifi重新连接wifi的代码。
# 网上下载安装Python3.8
# 配置环境变量 以下为参考
# python环境变量 \Python38
# C:\Users\LRJ\AppData\Local\Programs\Python\Python38
# pip环境变量 \Python38\Scripts
# C:\Users\LRJ\AppData\Local\Programs\Python\Python38\Scripts
#模块下载命令
#pip install pywifi
#pip install comtypes
#pip install requests
#若嫌弃下载太慢 后缀增加网址去加速下载
#pip install pywifi -i https://pypi.tuna.tsinghua.edu.cn/simple
#pip install comtypes -i https://pypi.tuna.tsinghua.edu.cn/simple
#pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple
import pywifi #wifi模块
from pywifi import const
import time #定时器模块
import requests #web网页模块
#判断wifi是否连接状态-------------------------------------------------------
def is_connected(wifi_inter):
if wifi_inter.status() in [const.IFACE_CONNECTED, const.IFACE_INACTIVE]:
return True
else:
return False
#连接wifi-------------------------------------------------------
def connet_wifi(wifi_inter, wifi_profile):
wifi_inter.remove_all_network_profiles() # 删除其它配置文件
tmp_profile = wifi_inter.add_network_profile(wifi_profile) # 加载配置文件
wifi_inter.connect(tmp_profile)
time.sleep(2)
if wifi_inter.status() == const.IFACE_CONNECTED:
return True
else:
return False
# 设置wifi-------------------------------------------------------
def set_profile():
wifi_profile = pywifi.Profile() # 配置文件
wifi_profile.ssid = "MERCURY_E452" # wifi名称
wifi_profile.auth = const.AUTH_ALG_OPEN # 需要密码
wifi_profile.akm.append(const.AKM_TYPE_WPA2PSK) # 加密类型
wifi_profile.cipher = const.CIPHER_TYPE_CCMP # 加密单元
wifi_profile.key = "88888888" # wifi密码
return wifi_profile # 返回wifi配置表
#获取网页数据-------------------------------------------------------
def get_webPage():
url="https://www.baidu.com"
url_temp="https://www.baidu.com/s?"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'}
#response = requests.get(url=url, headers=headers)
params = {"wd" : "中文"}
#esponse = requests.get(url=url, headers=headers ,params=params)
try:
#设定连接超时7秒
response = requests.get(url=url_temp, headers=headers ,params=params,timeout=7)
#response.encoding = 'utf-8'
#response.encoding = 'gbk'
if response.status_code != 200: #网页状态若不是200 说明连接不正常
print("status_code:"+response.status_code)
return 1
else:
#print("网页有数据")
return 0
except Exception as e: #抛出异常是因为网络连接时间过长
print("网页连接超时")
return 1
#函数入口-------------------------------------------------------
if __name__ == '__main__':
print('检测wifi网络连接状态软件,开始')
wifi = pywifi.PyWiFi() #获取wifi
interface = wifi.interfaces()[0] #获取wifi信息列表
profile = set_profile() #设置wifi属性
n = 0 #设置重连次数
sum = 0 #累计总和
while True:
if get_webPage() == 1: #判断是否能连接上外网
print()
print('连接不到网页 断开wifi')
if is_connected(interface): #判断wifi是否连接中
interface.disconnect() #断开wifi
time.sleep(2)
print('已经断开wifi')
if not is_connected(interface): #判断wifi是否连接中
print('网络已断开,重新连接中……')
con = connet_wifi(interface, profile) #连接wifi
n += 1
sum += 1
if not con and n <= 300:
continue
else:
res = '成功' if con else '失败'
print(f'尝试连接{n}次,累计{sum}次,连接{res}!')
n = 0
time.sleep(2) #2秒检测一次
#本人最近使用百度网盘下载文件,难得开了会员,但是下载文件的时候时不时出现,明明wifi是连接的但是就是没有网络。
#推理应该是路由器年久了,无法长时间满载运行导致的问题,后经过优快云查询 python自动连接wifi的代码。
#以上wifi连接代码大部分参考该博主,感谢该博主的无私奉献!
#https://blog.youkuaiyun.com/weixin_42246906/article/details/125701899?ops_request_misc=&request_id=&biz_id=102&utm_term=python%E6%96%AD%E5%BC%80wifi%E9%87%8D%E6%96%B0%E8%BF%9E%E6%8E%A5pywifi&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-2-125701899.nonecase&spm=1018.2226.3001.4187
#拿来使用需要修改代码
# wifi_profile.ssid = "MERCURY_E452" # wifi名称
# wifi_profile.key = "88888888" # wifi密码
#其中本人觉得重点是网页的超时设置 timeout=7
#另外本人遇到以下问题不知道是怎么回事,我的解决办法是,打开另外一个可以执行的py项目,把pyWIFI.py复制到新项目后就没问题了。但是旧项目依旧报错。
# 哎呀,出现问题。请在报告此 Bug 时添加以下详细信息。
# 在 GitHub 上报告: https://github.com/lzybkr/PSReadLine/issues/new-----------------------------------------------------------------------
# 上 50 个密钥:
# Space & Space ' C : \ U s e r s \ L R J \ A p p D a t a \ L o c
# a l \ P r o g r a m s \ P y t h o n \ P y t
# 异常:
# System.ArgumentOutOfRangeException: 该值必须大于或等于零,且必须
# 小于控制台缓冲区在该维度的大小。
# 参数名: left
# 实际值是 -1。
# 在 System.Console.SetCursorPosition(Int32 left, Int32 top)
# 在 Microsoft.PowerShell.Internal.VirtualTerminal.set_CursorLeft(Int32 value)
# 在 Microsoft.PowerShell.PSConsoleReadLine.ReallyRender(RenderData renderData, String defaultColor)
# 在 Microsoft.PowerShell.PSConsoleReadLine.ForceRender()
# 在 Microsoft.PowerShell.PSConsoleReadLine.Insert(Char c)
# 在 Microsoft.PowerShell.PSConsoleReadLine.SelfInsert(Nullable`1 key, Object arg)
# 在 Microsoft.PowerShell.PSConsoleReadLine.ProcessOneKey(ConsoleKeyInfo key, Dictionary`2 dispatchTable, Boolean ignoreIfNoAction, Object arg)
# 在 Microsoft.PowerShell.PSConsoleReadLine.InputLoop()
# 在 Microsoft.PowerShell.PSConsoleReadLine.ReadLine(Runspace runspace, EngineIntrinsics engineIntrinsics)
# -----------------------------------------------------------------------
# PS F:\001 my file\05 Generated File\Python code\Python Code WIFI> hon38\python.exe' 'c:\Users\LRJ\.vscode\extensions\ms-python.python-2023.2.0\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '64976' '--' 'F:\001 my file\05 Generated File\Python
# code\Python Code WIFI\pyWIFI.py'
# >> Python\Pyt
感谢该博主的无私奉献!
附软件运行图: