python如何实现wifi自动连接,解决电脑wifi经常断开问题
作者:Achen's
这篇文章主要介绍了python实现wifi自动连接,解决电脑wifi经常断开的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
python实现wifi自动连接,解决电脑wifi经常断开
安装pywifi模块
pywifi依赖comtypes,不安装会报错
pip install pywifi pip install comtypes
代码
import pywifi
from pywifi import const
import time
def is_connected(wifi_inter):
if wifi_inter.status() in [const.IFACE_CONNECTED, const.IFACE_INACTIVE]:
return True
else:
return False
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
def set_profile():
wifi_profile = pywifi.Profile() # 配置文件
wifi_profile.ssid = "我的wifi" # 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 = "1234567" # wifi密码
return wifi_profile
if __name__ == '__main__':
wifi = pywifi.PyWiFi()
interface = wifi.interfaces()[0]
profile = set_profile()
n = 0
while True:
if not is_connected(interface):
print('网络已断开,重新连接中……')
con = connet_wifi(interface, profile)
n += 1
if not con and n <= 3:
continue
else:
res = '成功' if con else '失败'
print(f'尝试连接{n}次,连接{res}!')
n = 0
time.sleep(2)python实现连接指定的wifi
# -*-coding:utf-8-*-
import pywifi, time
from pywifi import const
# 1、python连接WiFi,需要使用pywifi包,安装pywifi:pip install pywifi
#注意:如果提示找不到comtypes,则还需要安装pip install comtypes
# 2、判断wifi连接状态:
def wifi_connect_status():
wifi = pywifi.PyWiFi()
iface = wifi.interfaces()[0] # acquire the first Wlan card,maybe not
if iface.status() in [const.IFACE_CONNECTED, const.IFACE_INACTIVE]:
print("wifi connected!")
return 1
else:
print("wifi not connected!")
return 0
# 3、扫描wifi:
def scan_wifi():
wifi = pywifi.PyWiFi()
iface = wifi.interfaces()[0]
iface.scan()
time.sleep(1)
basewifi = iface.scan_results()
for i in basewifi:
print("wifi scan result:{}".format(i.ssid))
print("wifi device MAC address:{}".format(i.bssid))
return basewifi
# 4、连接指定的wifi:
def connect_wifi():
wifi = pywifi.PyWiFi()
ifaces = wifi.interfaces()[0]
print(ifaces.name()) # 输出无线网卡名称
ifaces.disconnect()
time.sleep(3)
profile = pywifi.Profile() # 配置文件
profile.ssid = "JYKC-31F" # wifi名称
profile.auth = const.AUTH_ALG_OPEN # 需要密码
profile.akm.append(const.AKM_TYPE_WPA2PSK) # 加密类型
profile.cipher = const.CIPHER_TYPE_CCMP # 加密单元
profile.key = "2151155511" # wifi密码
ifaces.remove_all_network_profiles() # 删除其它配置文件
tmp_profile = ifaces.add_network_profile(profile) # 加载配置文件
ifaces.connect(tmp_profile)
time.sleep(5)
isok = True
if ifaces.status() == const.IFACE_CONNECTED:
print("connect successfully!")
else:
print("connect failed!")
time.sleep(1)
return isok
#5、测试
def main():
print("start")
wifi_connect_status()
scan_wifi()
connect_wifi()
print("finish!")
if __name__ == "__main__":
main()总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
