如何用 Python 連接 Wi-Fi?

現在要找到一台沒有活躍網絡連接的電腦幾乎是不可能的。在 21 世紀,互聯網具有至高無上的意義。有多種方法可以將他們的系統連接到互聯網。第一種是使用傳統電纜,即以太網,另一種是使用現代無線保真系統,也稱為無線保真。無線網絡讓我們的生活變得更加容易和快捷。只需輕點鼠標和拇指,我們幾乎可以立即連接到數據和資源的無垠海洋。在下面的教程中,我們將了解如何使用高級編程語言(如 Python)連接 Wi-Fi。

那麼,讓我們開始吧。

建立與已知無線網絡的連接

在下一節中,我們將討論連接到以前連接的無線網絡的過程。為了完成這項任務,我們將遵循下面描述的方法:

方法學:

我們將遵循這個程序的一個簡單程序:

第一步:首先,我們將導入所需的庫。

第二步:其次,我們將使用 cmd 命令和一個名為操作系統的 Python 庫掃描並顯示所有可用的 SSIDs。

第三步:然後我們將選擇已知的 Wi-Fi 網絡進行連接,並等待直到連接成功。

既然我們已經理解了過程,讓我們開始編碼部分。我們將利用 Windows 命令提示符的一些命令來訪問可用的無線網絡列表並連接到已知的無線網絡。但是,我們如何在 Python 腳本中編寫和執行 Windows 命令提示符的命令。

Python 編程語言提供了一個名為操作系統庫的內置庫。該庫為用戶提供了通過 Python 腳本直接與操作系統通信的能力,使用了各種方法,如路徑()、getcwd()、System()、等等。我們甚至可以藉助操作系統庫的功能來執行 cmd 命令。

讓我們考慮下面的實現來理解上面的陳述。

示例:


# importing the os library
import os
# scanning the available Wi-Fi networks
os.system('cmd /c "netsh wlan show networks"')
# providing the Wi-Fi name as input
router_name = input('Input Name/SSID of the Wi-Fi network we would like to connect: ')
# connecting to the provided Wi-Fi network
os.system(f'''cmd /c "netsh wlan connect name = {router_name}"''')
print("If the system is not connected yet, try reconnecting to an earlier connected SSID!")

輸出:

Interface name : Wi-Fi
There are 11 networks currently visible. 
SSID 1 : Benny
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 2 : Honest
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 3 : Sushii
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 4 : Amazon
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 5 : Unagi91
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 6 : Printer.5G
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 7 : Printer 2.4G
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 8 : Willett
    Network type            : Infrastructure
    Authentication          : WPA-Personal
    Encryption              : CCMP
SSID 9 : MARK1
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 10 : Disconnect
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 11 : MARK1_5G
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
Input Name/SSID of the Wi-Fi network we would like to connect: MARK1_5G  
Connection request was completed successfully.
If the system is not connected yet, try reconnecting to an earlier connected SSID! 

說明:

在上面的代碼片段中,我們已經使用 import 關鍵字導入了 OS 庫。然後,我們使用 os.system() 方法來執行以下 cmd 命令:

命令:


'cmd /c "netsh wlan show networks"'

上述命令有助於掃描所有可用的 SSIDs,並將它們與它們的基礎架構、身份驗證和加密類型一起顯示為輸出。然後我們定義了一個變量 router_name ,它將用戶輸入的 SSID 值存儲為字符串。

然後這個字符串變量被另一個 cmd 命令替換,我們應該在這個命令中提供 SSID 的名稱。

命令:


f'''cmd /c "netsh wlan connect name = {router_name}"'''

我們現在將成功連接到特定的 SSID。

建立與新無線網絡的連接

在下一節中,我們將通過幾個簡單的步驟來討論與新的無線網絡建立連接的方法。此外,藉助 XML 文件向系統添加新的無線網絡配置文件也很重要,以便連接到新的網絡。這將使無線網絡成為一個已知的 SSID,我們將能夠在以下步驟的幫助下成功連接到它:

方法學:

第一步:我們將從導入所需的庫開始,即操作系統庫。

步驟 2: 然後我們將設置新 Wi-Fi 網絡的 XML 配置。

第三步:一旦設置好配置,我們將選擇 Wi-Fi 網絡。

步驟 4: 然後我們將把 Wi-Fi 網絡的配置文件添加到系統中。

第五步:最後,我們將連接到 Wi-Fi 網絡。

讓我們在下面的例子中看到上面的過程:

示例:


# importing the os module
import os
# defining the function to establish a new connection
def create_new_connection(name, SSID, password):
    config = """<?xml version=\"1.0\"?>
<WLANProfile xmlns = "http://www.microsoft.com/networking/WLAN/profile/v1">
    <name>""" + name + """</name>
    <SSIDConfig>
        <SSID>
            <name>""" + SSID + """</name>
        </SSID>
    </SSIDConfig>
    <connectionType> ESS </connectionType>
    <connectionMode> auto </connectionMode>
    <MSM>
        <security>
            <authEncryption>
                <authentication> WPA2PSK </authentication>
                <encryption> AES </encryption>
                <useOneX> false </useOneX>
            </authEncryption>
            <sharedKey>
                <keyType> passPhrase </keyType>
                <protected> false </protected>
                <keyMaterial>""" + password + """</keyMaterial>
            </sharedKey>
        </security>
    </MSM>
</WLANProfile>"""
    wlan_command = "netsh wlan add profile filename =\"" + name + ".xml\"" + " interface = Wi-Fi"
    with open(name + ".xml", 'w') as file:
        file.write(config)
    os.system(wlan_command)
# defining function to connect to a network
def wlan_connect(name, SSID):
    wlan_command = "netsh wlan connect name =\"" + name + "\" ssid =\"" + SSID + "\" interface = Wi-Fi"
    os.system(wlan_command)
# defining function to display avavilabe Wi-Fi networks   
def display_available_networks():
    wlan_command = "netsh wlan show networks interface = Wi-Fi"
    os.system(wlan_command)
# displaying the available netwroks
display_available_networks()
# inputing the Wi-Fi name and password
name = input("Enter the Name of Wi-Fi: ")
password = input("Enter the Password: ") 
# establishing a new connection
create_new_connection(name, name, password)
# connecting to the Wi-Fi network
wlan_connect(name, name)
print("If the system is not connected to this network, try connecting with the correct password!")

輸出:

Interface name : Wi-Fi
There are 11 networks currently visible. 
SSID 1 : Benny
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 2 : Honest
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 3 : Sushii
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 4 : Amazon
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 5 : Unagi91
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 6 : Printer.5G
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 7 : Printer 2.4G
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 8 : Willett
    Network type            : Infrastructure
    Authentication          : WPA-Personal
    Encryption              : CCMP
SSID 9 : MARK1
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 10 : Disconnect
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
SSID 11 : MARK1_5G
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
Enter the Name of Wi-Fi: MARK1_5G
Enter the Password: Thereisnopassword.
Connection request was completed successfully.
If the system is not connected to this network, try connecting with the correct password!   

說明:

在上面的代碼片段中,我們已經導入了操作系統模塊,並定義了 create_new_connection 函數,該函數接受參數為名稱、SSID、和密碼。這些參數都是我們為了配置變量而必須完成的字符串。配置變量是一個字符串,允許程序員為新的無線網絡定義 XML 配置。

然後,我們接受了用戶輸入的 SSID 名稱和密碼。然後,它們被輸入到 XML 代碼中,在下面幾行代碼的幫助下,這些代碼作為概要文件被包含進來:

語法:


my_command = "netsh wlan add profile filename =\"" + name + ".xml\"" + " interface = Wi-Fi"
with open(name+".xml", 'w') as file:
    file.write(config)
os.system(my_command)

我們現在可以藉助之前在教程中使用的相同命令連接到無線網絡,並像連接已知網絡一樣連接到網絡。


原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/271610.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-16 19:22
下一篇 2024-12-16 19:23

相關推薦

  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29

發表回復

登錄後才能評論