python脚本切换wifi-pywifi使用
import time
import pywifi
from pywifi import const
#有密码
def connect_wifi_password(name, password):
wifi = pywifi.PyWiFi() # 创建一个wifi对象
ifaces = wifi.interfaces()[0] # 取第一个无限网卡
# print(ifaces.name()) # 输出无线网卡名称
ifaces.disconnect() # 断开网卡连接
time.sleep(3) # 缓冲3秒
profile = pywifi.Profile() # 配置文件
profile.ssid = name # wifi名称
profile.auth = const.AUTH_ALG_OPEN # 需要密码
profile.akm.append(const.AKM_TYPE_WPA2PSK) # 加密类型
profile.cipher = const.CIPHER_TYPE_CCMP # 加密单元
profile.key = password # wifi密码
ifaces.remove_all_network_profiles() # 删除其他配置文件
tmp_profile = ifaces.add_network_profile(profile) # 加载配置文件
ifaces.connect(tmp_profile) # 连接
for i in range(100):
print('等待时间', i)
time.sleep(1) # 尝试1秒能否成功连
print(ifaces.status())
if ifaces.status() == const.IFACE_CONNECTED:
print("成功连接")
return True
else:
time.sleep(1)
if ifaces.status() != const.IFACE_CONNECTED:
print("经过10s中等待,连接失败")
return False
#无密码
def connect_wifi(name):
wifi = pywifi.PyWiFi() # 创建一个wifi对象
ifaces = wifi.interfaces()[0] # 取第一个无限网卡
# print(ifaces.name()) # 输出无线网卡名称
ifaces.disconnect() # 断开网卡连接
time.sleep(3) # 缓冲3秒
profile = pywifi.Profile() # 配置文件
profile.ssid = name # wifi名称
ifaces.remove_all_network_profiles() # 删除其他配置文件
tmp_profile = ifaces.add_network_profile(profile) # 加载配置文件
ifaces.connect(tmp_profile) # 连接
for i in range(100):
print('等待时间', i)
time.sleep(1) # 尝试1秒能否成功连
print(ifaces.status())
if ifaces.status() == const.IFACE_CONNECTED:
print("成功连接")
return True
else:
time.sleep(1)
if ifaces.status() != const.IFACE_CONNECTED:
print("经过10s中等待,连接失败")
return False
参考地址:
http://m.weizhi.cc/tech/detail-334315.html

浙公网安备 33010602011771号