LISHUZUOXUN_yangjiang/LSZXNetWork/NetworkDriverLinux/wifi.py

100 lines
2.7 KiB
Python

import os
import re
import sys
from LogRecord.log_recorder import GLOBAL_LOG
os.popen("sudo systemctl start NetworkManager").read()
def get_device_name():
while True:
GLOBAL_LOG.write("正在搜索无线网卡名称。。。")
echo = os.popen("nmcli -t -f DEVICE,TYPE,STATE dev | awk -F: '$2==\"wifi\"{print $1}'").read()
if echo:
return echo.strip()
# 获得默认Wi-Fi网卡名称
DEFAULT_DEVICE = get_device_name()
# 获得有线网卡名称
def get_eth_device_name():
while True:
GLOBAL_LOG.write("正在搜索有线网卡名称。。。")
echo = os.popen(
"nmcli -t -f DEVICE,TYPE,STATE dev | awk -F: '$2==\"ethernet\"{print $1}'"
).read()
if echo:
return echo.strip()
LAN_DEVICE = get_eth_device_name()
if not DEFAULT_DEVICE or not LAN_DEVICE:
sys.exit()
# 获得自身的ip地址
def get_self_ip_address():
echo = os.popen(f"ip -4 addr show {DEFAULT_DEVICE}"
+" | grep -oP '(?<=inet\s)\d+(\.\d+){3}'").read()
if echo:
return echo.strip()
else:
return "0.0.0.0"
def get_wifi_name():
echo = os.popen(f"iwgetid {DEFAULT_DEVICE} -r").read()
if echo.strip():
return echo.strip()
class WIFI:
def __init__(self) -> None:
super().__init__()
self.wifi_device_initial()
@staticmethod
def wifi_device_initial():
os.popen("sudo systemctl stop hostapd").read()
os.popen("sudo systemctl stop udhcpd").read()
os.popen("sudo systemctl start NetworkManager").read()
os.popen("sudo nmcli dev").read()
os.popen("sudo nmcli r wifi on").read()
os.popen(f"sudo ifconfig {DEFAULT_DEVICE} up")
@staticmethod
def get_connected_wifi_name():
return get_wifi_name()
@staticmethod
def wifi_connect_status():
if get_wifi_name():
return True
else:
return False
@staticmethod
def disconnect():
os.popen(f"sudo nmcli dev disconnect {DEFAULT_DEVICE}")
@staticmethod
def get_ip():
return get_self_ip_address()
@staticmethod
def scan_wifi():
os.popen("sudo systemctl stop hostapd")
os.popen("sudo systemctl stop udhcpd")
os.popen("sudo nmcli dev")
os.popen("sudo nmcli r wifi on")
os.popen(f"sudo ifconfig {DEFAULT_DEVICE} up")
echo = os.popen(f"sudo iwlist {DEFAULT_DEVICE} scan | grep ESSID").read()
wifi_name_re = re.findall(r"(?<=ESSID:\").*(?=\")", echo)
if wifi_name_re:
return wifi_name_re
else:
return []
@staticmethod
def connect_wifi(ssid, password):
os.popen(f"sudo nmcli dev wifi connect {ssid} password {password}")