首页 > 编程知识 正文

如何用 Python 连接 Wi-Fi?

时间:2023-11-26 13:13:14 阅读:309420 作者:XVDE

现在要找到一台没有活跃网络连接的电脑几乎是不可能的。在 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)

我们现在可以借助之前在教程中使用的相同命令连接到无线网络,并像连接已知网络一样连接到网络。


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。