基于Flask与pyWiFi的WiFi到期后自动遗忘密码实现需求
实现WiFi时长耗尽后自动遗忘密码的解决方案
核心思路
要实现时长耗尽后自动遗忘WiFi密码,关键在于断开连接后删除对应SSID的网络配置文件——pyWiFi保存的WiFi密码都存储在网络配置(Profile)中,删除对应配置就等同于系统遗忘该WiFi的密码。
现有代码的问题
disconnect_wifi函数未定义iface变量,无法操作WiFi接口- 连接WiFi时调用
remove_all_network_profiles()会删除所有已保存的WiFi配置,逻辑不合理 - 连接后直接判断状态不准确,
connect是异步操作,需要等待状态稳定后再校验 - 缺少针对目标SSID的配置删除逻辑,无法实现遗忘密码的核心需求
修改后的完整代码
import time import pywifi from pywifi import const import schedule # 全局保存WiFi接口实例,方便后续断开和删除配置使用 iface = None def connect_to_wifi(ssid, password): global iface wifi = pywifi.PyWiFi() iface = wifi.interfaces()[0] # 先断开当前连接(如果有的话) if iface.status() == const.IFACE_CONNECTED: iface.disconnect() time.sleep(2) # 删除已存在的该SSID配置(避免残留旧密码) for profile in iface.network_profiles(): if profile.ssid == ssid: iface.remove_network_profile(profile) # 创建新的WiFi配置 profile = pywifi.Profile() profile.ssid = ssid profile.auth = const.AUTH_ALG_OPEN profile.akm.append(const.AKM_TYPE_WPA2PSK) profile.cipher = const.CIPHER_TYPE_CCMP profile.key = password # 添加配置并尝试连接 new_profile = iface.add_network_profile(profile) iface.connect(new_profile) # 等待连接状态变化,最多等待10秒 timeout = 10 while timeout > 0: if iface.status() == const.IFACE_CONNECTED: print(f"成功连接到WiFi: {ssid}") return True time.sleep(1) timeout -= 1 print(f"连接WiFi {ssid}失败") # 连接失败时删除刚添加的配置 iface.remove_network_profile(new_profile) return False def disconnect_and_forget_wifi(target_ssid): global iface if not iface: print("未找到WiFi接口实例") return schedule.CancelJob # 断开当前连接 if iface.status() == const.IFACE_CONNECTED: iface.disconnect() time.sleep(2) # 删除对应SSID的所有配置,实现遗忘密码 removed = False for profile in iface.network_profiles(): if profile.ssid == target_ssid: iface.remove_network_profile(profile) removed = True print(f"已遗忘WiFi {target_ssid}的密码") if not removed: print(f"未找到WiFi {target_ssid}的配置文件") return schedule.CancelJob # 配置要连接的WiFi信息 TARGET_SSID = 'Nimrodian' TARGET_PASSWORD = '12345678nm' # 尝试连接WiFi if connect_to_wifi(TARGET_SSID, TARGET_PASSWORD): # 设置时长(示例为30分钟后执行断开并遗忘) schedule.every(30).minutes.do(disconnect_and_forget_wifi, target_ssid=TARGET_SSID) # 保持定时任务运行 while True: schedule.run_pending() time.sleep(1)
关键修改点说明
- 全局WiFi接口实例:将
iface设为全局变量,让断开函数能直接操作同一个WiFi接口 - 精准删除配置:不再删除所有WiFi配置,只删除目标SSID的配置,避免影响其他已保存的WiFi
- 连接状态等待:添加超时等待逻辑,确保连接操作完成后再判断结果
- 参数化断开函数:将目标SSID作为参数传入,提升代码复用性
- 失败清理:连接失败时自动删除刚添加的配置,避免残留无效信息
内容的提问来源于stack exchange,提问作者Nimrod Mpandari
相关产品推荐
相关产品推荐

