- 需求:实现通过python代码结合命令行连接wifi。
- 代码:若提供的密码能够连接上,则返回密码结果,否则返回
strong
。
import subprocess
import os
import time
import traceback
def connect_wifi(net_card, ssid, bssid, password):
"""连接wifi"""
try:
wifi_process = subprocess.Popen('ifconfig', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
(res, error) = wifi_process.communicate()
print(res.decode())
if 'wlan0mon' in res.decode():
os.system("airmon-ng stop wlan0mon")
os.system('systemctl start NetworkManager')
wifi2_process = subprocess.Popen('ifconfig', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
(resif, error) = wifi2_process.communicate()
print(resif.decode())
if 'wlan0' not in resif.decode():
os.system("ifconfig wlp3s0 down")
os.system('ip link set wlp3s0 name wlan0')
os.system('ip link set dev wlan0 up')
os.system('ifconfig wlan0 up')
time.sleep(5)
wifi_status_command = 'nmcli dev status'
wifi_status_process = subprocess.Popen(wifi_status_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
(res1, error) = wifi_status_process.communicate()
print(res1.decode().split('\n'))
res1_list = res1.decode().split('\n')
for i in res1_list:
if (('wlan0' in i) and ('unmanaged' in i)) or ('wlan0' in i) and ('不可用' in i):
os.system('rfkill unblock all')
os.system('ifconfig wlan0 up')
else:
pass
wifi_is_conn_command = 'nmcli connection show --active'
wifi_is_conn_process = subprocess.Popen(wifi_is_conn_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
(ver, error) = wifi_is_conn_process.communicate()
print(ver.decode())
if 'wlan0' in ver.decode():
return "wlan0已被连接占用"
else:
pass
wifi_list_command = 'nmcli dev wifi list'
wifi_list_process = subprocess.Popen(wifi_list_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
wifi_list_process.wait()
(res2, error) = wifi_list_process.communicate()
print(res2.decode())
if ssid in res2.decode():
print("%s 在其中" % ssid)
else:
print("%s 不在其中" % ssid)
wifi_conn_command = 'nmcli dev wifi connect {} password {} ifname {}'.format(ssid, password, net_card)
wifi_conn_process = subprocess.Popen(wifi_conn_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
(res3, error) = wifi_conn_process.communicate()
print(res3.decode())
wifi_conn_command = 'nmcli device wifi connect {} password {} ifname {}'.format(bssid, password, net_card)
wifi_conn_process = subprocess.Popen(wifi_conn_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
(res3, error) = wifi_conn_process.communicate()
print(res3.decode())
wifi_del_command = 'nmcli con del {}'.format(ssid)
wifi_del_process = subprocess.Popen(wifi_del_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
(res4, error) = wifi_del_process.communicate()
os.system('systemctl stop NetworkManager')
print(res4.decode())
if '成功' in res3.decode():
return password
else:
password = "strong"
return password
except:
print(traceback.format_exc())
print(connect_wifi(net_card='无线网卡名称', ssid='wifi名称', bssid='bssid', password='wifi密码'))