继续尝试连接Python中的WiFi网络,即使它不可用

2024-04-29 01:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个脚本,在其中它不断尝试连接到一个网络,即使它不可用,所以一旦它变得可用,它将连接到它。 这就是我现在拥有的

def connect_to_yeelight(ssid, iface):
sys.setrecursionlimit(2000)
iface_channel = f"sudo iwconfig {iface} channel 6"
os.system(iface_channel)
connect_yeelight_cmd = f"nmcli d wifi connect {ssid} ifname {iface} > /dev/null 2>&1"

def try_connection():
    if os.system(connect_yeelight_cmd) != 0:
            try_connection()
            time.sleep(1)
    else:
        return True

try_connection()

正如您可能从这段代码中看到的,我得到了一个“RecursionError:比较中超过了最大递归深度”。有没有其他方法可以实现这样的脚本,我觉得我从一个错误的角度看这个


Tags: to网络脚本cmdosdefconnectsys
2条回答
cmd = ["nmcli", "-f",  "SSID,BSSID,ACTIVE", "dev", "wifi", "list"] 
networks = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output, errors = networks.communicate()
print(output.decode("utf-8"))

这将返回所有活动的Wi-Fi。如果您的Wi-Fi在此列表中联机,您可以尝试连接到它

首先可以使用sleep()或schedule功能来实现函数的连续调用

我编写了一个函数,用于执行控制台命令并返回输出:

def _executeConsoleCommand(command):
    '''Executes the linux command line arguments and returns the output if needed'''
     try:
         stream = os.popen(command)
         return stream.read().strip()
     except:
         return ''

现在,如果wifi可用,您只需要一个连接您的功能。请注意,每10到20秒只能调用nmcli rescan function,否则下次它将拒绝扫描任何内容。这就是为什么我建议使用iw module进行扫描

def tryConnect():
    yourSSID = 'TestWifi'
    yourPassword = '12345678'
    ssids = _executeConsoleCommand('sudo iwlist wlan0 scan | grep "SSID" | awk \'!a[$0]++\' | cut -d \':\' -f2').split(os.linesep) # scans your deviceses 
    ssids = [ssid.replace('"', '') for ssid in ssids] # remove the exclaimation marks
    if yourSSID in ssids:
        _executeConsoleCommand('sudo nmcli device wifi rescan ifname wlan0 ssid {}'.format(yourSSID)) #you have to call this before you connect  - thats a thing of nmcli
        _executeConsoleCommand('sudo nmcli dev wifi connect {} password "{}" ifname wlan0'.format(yourSSID, yourPassword))
        # now check if your connected 
        ssid_on_interface_wlan0 = 'sudo iw wlan0 info | grep ssid | awk \'{{ print $2 }}\'' 
        if yourSSID in _executeConsoleCommand(ssid_on_interface_wlan0):
            return True
    return False

现在你只要经常打电话就行了。。。。e、 g:

def run():
    connected = False
    while not connected:
        connected = tryConnect
        time.sleep(10)
run()

相关问题 更多 >