首页 > 解决方案 > python wifi exersice(opionon/comments)

问题描述

我有一个练习:

  1. 显示所有 Wi-Fi 接入点的列表
  2. 突出显示可能的最佳连接点(RSSI 最接近于零的位置)
  3. 提示用户输入该接入点的密码
  4. 连接到该接入点
  5. 表明您能够通过该接入点访问 Internet

我想对新手提出意见或任何意见,我认为可能有更正式的方式来做到这一点?或者让它看起来更好

import subprocess
import urllib.request
import pywifi
from pywifi import const
import time




def look_for():
    sid = "SSID"

    networks = subprocess.check_output(['netsh', 'wlan', 'show', 'network', 'mode=Bssid'])
    networks = networks.decode('ascii')
    networks = networks.replace('\r', '')
    networks_list = networks.split('\n')

    ssids = []

    for network in networks_list:
        if sid in network and 'BSSID' not in network:
            ssids.append(network[9:])

    # for ssid in ssids:
    #     print(ssid)

    res = []
    results = []
    SSID_list = networks.split("BSSID")
    counter = 0
    for i in range(1, len(SSID_list)):
        temp = SSID_list[i]
        if (temp[1] == '1'):
            counter += 1
            results.append([0])
        pos = 0
        if temp.find('Signal', pos) != -1:
            pos = temp.find('Signal', pos)
            val = (temp[pos + 6:pos + 30].replace(':', '').strip().replace('%', ''))
            if int(results[-1][0]) < int(val):
                results[-1][0] = val

    max_val = 0
    max_index = 0
    for i in range(len(results)):
        if int(results[i][0]) > max_val:
            max_val = int(results[i][0])
            max_index = i
    print(ssids[max_index], 'is the strongest network around')

    password = input("Enter the password for " + ssids[max_index] + ' :')
    connect_to_wifi(ssids[max_index],password)



def check_conection():
    try:
        urllib.request.urlopen('https://google.com')
        return True
    except Exception as e:
        return False





def connect_to_wifi(ssid,password):
    wifi=pywifi.PyWiFi()
    iface=wifi.interfaces()[0]
    iface.disconnect()
    time.sleep(1)
    assert iface.status() in \
           [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]

    profile = pywifi.Profile()
    profile.ssid = ssid
    profile.auth = const.AUTH_ALG_OPEN
    profile.akm.append(const.AKM_TYPE_WPA2PSK)
    profile.cipher = const.CIPHER_TYPE_CCMP
    profile.key = password

    iface.remove_all_network_profiles()
    tmp_profile = iface.add_network_profile(profile)

    iface.connect(tmp_profile)
    time.sleep(30)
    assert iface.status() == const.IFACE_CONNECTED




if __name__ == '__main__':
    look_for()
    print('Connected' if check_conection() else 'Not connected')

感谢您的阅读和帮助,任何建议都会受到祝福!

标签: pythonnetworkingwifi

解决方案


推荐阅读