欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

python手动连接无线网络wifi 自己亲自做的 有大用 有大大用 有大大大用 有大大大大用 有大大大大大用

#!/usr/bin/python3
#
# importing the os module
import sys
import os
import subprocess
import tkinter
from tkinter import messagebox
import time
def delete_all_ssid():
    # 执行命令并获取输出
    output = subprocess.check_output(["netsh", "wlan", "show", "profiles"])
    # print(output)
    # 将输出转换为字符串类型
    output_str = output.decode('GBK')
    # print(output_str)
    # 查找所有SSID并打印出来
    ssids = [line.split(": ")[1] for line in output_str.splitlines() if "Bbbb" in line]
    for ssid in ssids:
        print(ssid)
        wlan_command = "netsh wlan delete profile name =\"" + ssid + "\"" + " interface = WLAN"
        os.system(wlan_command)
    # wlan_command = "netsh wlan delete profile name =\"" + name + "\"" + " interface = WLAN"
# defining the function to establish a new connection
# def create_new_connection_nst_str(name):
#     config = f"""<?xml version="1.0"?>
#       <name>{name}</name>
#       <SSIDConfig>
#           <SSID>
#               <hex>4C757873686172652D4E5354</hex>
#               <name>{name}</name>
#           </SSID>
#           <nonBroadcast>true</nonBroadcast>
#       </SSIDConfig>
#       <connectionType>ESS</connectionType>
#       <connectionMode>auto</connectionMode>
#       <MSM>
#           <security>
#               <authEncryption>
#                   <authentication>WPA2</authentication>
#                   <encryption>AES</encryption>
#                   <useOneX>true</useOneX>
#               </authEncryption>
#               <PMKCacheMode>enabled</PMKCacheMode>
#               <PMKCacheTTL>720</PMKCacheTTL>
#               <PMKCacheSize>128</PMKCacheSize>
#               <preAuthMode>disabled</preAuthMode>
#               <OneX xmlns="http://www.microsoft.com/networking/OneX/v1">
#                   <authMode>machineOrUser</authMode>
#                   <EAPConfig><EapHostConfig xmlns="http://www.microsoft.com/provisioning/EapHostConfig"><EapMethod><Type xmlns="http://www.microsoft.com/provisioning/EapCommon">25</Type><VendorId xmlns="http://www.microsoft.com/provisioning/EapCommon">0</VendorId><VendorType xmlns="http://www.microsoft.com/provisioning/EapCommon">0</VendorType><AuthorId xmlns="http://www.microsoft.com/provisioning/EapCommon">0</AuthorId></EapMethod><Config xmlns="http://www.microsoft.com/provisioning/EapHostConfig"><Eap xmlns="http://www.microsoft.com/provisioning/BaseEapConnectionPropertiesV1"><Type>25</Type><EapType xmlns="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV1"><ServerValidation><DisableUserPromptForServerValidation>false</DisableUserPromptForServerValidation><ServerNames></ServerNames><TrustedRootCA>96 8d cb c5 40 4f 71 7f 00 2a c2 6b 09 0d 0a db 55 cf 6a 17 </TrustedRootCA></ServerValidation><FastReconnect>true</FastReconnect><InnerEapOptional>false</InnerEapOptional><Eap xmlns="http://www.microsoft.com/provisioning/BaseEapConnectionPropertiesV1"><Type>26</Type><EapType xmlns="http://www.microsoft.com/provisioning/MsChapV2ConnectionPropertiesV1"><UseWinLogonCredentials>false</UseWinLogonCredentials></EapType></Eap><EnableQuarantineChecks>false</EnableQuarantineChecks><RequireCryptoBinding>false</RequireCryptoBinding><PeapExtensions><PerformServerValidation xmlns="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV2">true</PerformServerValidation><AcceptServerName xmlns="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV2">true</AcceptServerName><PeapExtensionsV2 xmlns="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV2"><AllowPromptingWhenServerCANotFound xmlns="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV3">true</AllowPromptingWhenServerCANotFound></PeapExtensionsV2></PeapExtensions></EapType></Eap></Config></EapHostConfig></EAPConfig>
#               </OneX>
#           </security>
#       </MSM>
#       <MacRandomization xmlns="http://www.microsoft.com/networking/WLAN/profile/v3">
#           <enableRandomization>false</enableRandomization>
#           <randomizationSeed>3104594341</randomizationSeed>
#       </MacRandomization>
#     </WLANProfile>
#     """
#     return config
def create_new_connection_str(name):
    hex_representation = "".join([hex(ord(ch))[2:] for ch in name])
    config = f"""<?xml version="1.0"?>
        <name>{name}</name>
        <SSIDConfig>
            <SSID>
                <hex>{hex_representation}</hex>
                <name>{name}</name>
            </SSID>
            <nonBroadcast>true</nonBroadcast>
        </SSIDConfig>
        <connectionType>ESS</connectionType>
        <connectionMode>auto</connectionMode>
        <autoSwitch>false</autoSwitch>
        <MSM>
            <security>
                <authEncryption>
                    <authentication>WPA2</authentication>
                    <encryption>AES</encryption>
                    <useOneX>true</useOneX>
                </authEncryption>
                <OneX xmlns="http://www.microsoft.com/networking/OneX/v1">
                    <cacheUserData>true</cacheUserData>
                    <authMode>user</authMode>
                    <EAPConfig><EapHostConfig xmlns="http://www.microsoft.com/provisioning/EapHostConfig"><EapMethod><Type xmlns="http://www.microsoft.com/provisioning/EapCommon">25</Type><VendorId xmlns="http://www.microsoft.com/provisioning/EapCommon">0</VendorId><VendorType xmlns="http://www.microsoft.com/provisioning/EapCommon">0</VendorType><AuthorId xmlns="http://www.microsoft.com/provisioning/EapCommon">0</AuthorId></EapMethod><Config xmlns="http://www.microsoft.com/provisioning/EapHostConfig"><Eap xmlns="http://www.microsoft.com/provisioning/BaseEapConnectionPropertiesV1"><Type>25</Type><EapType xmlns="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV1"><ServerValidation><DisableUserPromptForServerValidation>false</DisableUserPromptForServerValidation><ServerNames></ServerNames></ServerValidation><FastReconnect>true</FastReconnect><InnerEapOptional>false</InnerEapOptional><Eap xmlns="http://www.microsoft.com/provisioning/BaseEapConnectionPropertiesV1"><Type>26</Type><EapType xmlns="http://www.microsoft.com/provisioning/MsChapV2ConnectionPropertiesV1"><UseWinLogonCredentials>false</UseWinLogonCredentials></EapType></Eap><EnableQuarantineChecks>false</EnableQuarantineChecks><RequireCryptoBinding>false</RequireCryptoBinding><PeapExtensions><PerformServerValidation xmlns="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV2">false</PerformServerValidation><AcceptServerName xmlns="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV2">false</AcceptServerName></PeapExtensions></EapType></Eap></Config></EapHostConfig></EAPConfig>
                </OneX>
            </security>
        </MSM>
    </WLANProfile>
    """
    return config


def create_new_connection(name):
    config = create_new_connection_str(name)
    # delete_all_ssid()
    wlan_command = "netsh wlan delete profile name =\"" + name + "\"" + " interface = WLAN"
    os.system(wlan_command)

    # path一定要用绝对路径,否则提示没有分配给指定接口的配置文件
    if getattr(sys, 'frozen', False):
        # 如果是通过PyInstaller冻结的(打包成exe)
        current_dir = os.path.dirname(sys.executable)
    else:
        # 如果是正常的python脚本运行
        current_dir = os.path.dirname(os.path.abspath(__file__))
    # path=current_dir+"\\"+name+".xml"
    path=current_dir+"\\"+name+".xml"
    # messagebox.showinfo("连接wifi", f"{path}")
    # print(path)
    # wlan_command = "netsh wlan add profile filename =\"" + name + ".xml\"" + " interface = WLAN"
    wlan_command = "netsh wlan add profile filename =\"" + path
    with open(path , 'w') as file:
        file.write(config)
    os.system(wlan_command)
    # defining function to connect to a network
def wlan_connect(name):
    wlan_command = "netsh wlan connect name =\"" + name + "\" ssid =\"" + name
    os.system(wlan_command)
    # defining function to display avavilabe Wi-Fi networks
def chuli_wifi(text):
    create_new_connection(text)
    # 延迟1秒
    time.sleep(1)
    wlan_connect(text)
    # 延迟2秒
    time.sleep(4)
    #虽然没有提供用户名和密码,但是连接上之后的话,仍然会自动填上空的用户名密码,所以下面两行是要删掉这个wifi
    wlan_command = "netsh wlan delete profile name =\"" + text + "\"" + " interface = WLAN"
    os.system(wlan_command)

    messagebox.showinfo("连接wifi", f"已打开{text},请查看")
root = tkinter.Tk()
text1 = "ZZZZ-LST"
btn1 = tkinter.Button(root,text=text1,width=15,height=2,bg="#7952b3", fg="white",command = lambda: chuli_wifi(text1))
btn1.grid(row=0,pady=5)
print(btn1.grid_info())
text2 = "ZZZZ-LYB"
btn2 = tkinter.Button(root,text=text2,width=15,height=2,bg="#7952b3", fg="white",command = lambda: chuli_wifi(text2))
btn2.grid(row=1,pady=5)
print(btn2.grid_info())
text3 = "ZZZZ-JST"
btn3 = tkinter.Button(root,text=text3,width=15,height=2,bg="#7952b3", fg="white",command = lambda: chuli_wifi(text3))
btn3.grid(row=2,padx=5)
text4 = "ZZZZ-JYB"
btn4 = tkinter.Button(root,text=text4,width=15,height=2,bg="#7952b3", fg="white",command = lambda: chuli_wifi(text4))
btn4.grid(row=3,pady=5)
text5 = "ZZZZ-QST"
btn5 = tkinter.Button(root,text=text5,width=15,height=2,bg="#7952b3", fg="white",command = lambda: chuli_wifi(text5))
btn5.grid(row=4,pady=5)
text6 = "ZZZZ-QYB"
btn6 = tkinter.Button(root,text=text6,width=15,height=2,bg="#7952b3", fg="white",command = lambda: chuli_wifi(text6))
btn6.grid(row=5,pady=5)
text7 = "ZZZZ-HPC"
btn7 = tkinter.Button(root,text=text7,width=15,height=2,bg="#7952b3", fg="white",command = lambda: chuli_wifi(text7))
btn7.grid(row=6,pady=5)
root.title('连接 wifi')
root.geometry("225x440")
root.mainloop()
# connecting to the Wi-Fi network
print("If the system is not connected to this network, try connecting with the correct password!")


普通分类: