La forma correcta de abrir y cerrar un punto de acceso wifi usando código Python en win11 y win10

Pregunta uno

En win10 y win11, puede iniciar el punto de acceso móvil desde el ícono WIFI en la barra de tareas, pero no puede configurar el SSID ni la contraseña. Busqué en Internet durante mucho tiempo y no encontré ninguna solución.
La red omnipotente no puede resolver el problema, por lo que sólo podemos resolverlo nosotros mismos.

Pregunta 2

Mi controlador WiFi actual no admite redes alojadas. Si escribo netsh wlan show drivers, aparece "Redes alojadas compatibles: No". Después de reemplazar el controlador, todavía no es compatible y no se puede resolver, lo que significa que el punto de acceso móvil no se puede iniciar con el siguiente comando:

netsh wlan set hostednetwork mode=allow ssid=XXXXXXXXX key=YYYYYYYYYYY
netsh wlan start hostednetwork

Al ejecutar el comando "netsh wlan start hostingnetwork" aparecerá el mensaje "No se puede iniciar la red alojada".

Después de buscar en Internet, descubrí que Windows 10 abandonó la red portadora y que el punto de acceso móvil actual se basa en la tecnología WiFi Direct.
Es imposible iniciar un nuevo punto de acceso móvil basado en tecnología WiFi Direct a través de la línea de comando cmd.

solución

wifi.ps1:

[Windows.System.UserProfile.LockScreen,Windows.System.UserProfile,ContentType=WindowsRuntime] | Out-Null
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | ? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
 
Function Await($WinRtTask, $ResultType) {
    $asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
    $netTask = $asTask.Invoke($null, @($WinRtTask))
    $netTask.Wait(-1) | Out-Null
    $netTask.Result
}
 
# 这个函数本次的功能中没有使用,可以删除
Function AwaitAction($WinRtAction) {
    $asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | ? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and !$_.IsGenericMethod })[0]
    $netTask = $asTask.Invoke($null, @($WinRtAction))
    $netTask.Wait(-1) | Out-Null
}
 
$connectionProfile = [Windows.Networking.Connectivity.NetworkInformation,Windows.Networking.Connectivity,ContentType=WindowsRuntime]::GetInternetConnectionProfile()
$tetheringManager = [Windows.Networking.NetworkOperators.NetworkOperatorTetheringManager,Windows.Networking.NetworkOperators,ContentType=WindowsRuntime]::CreateFromConnectionProfile($connectionProfile)
 
 
# 检查 Windows 10 移动热点的状态
$tetheringManager.TetheringOperationalState
 
# 如果移动热点是开启状态,则关闭移动热点
if ($tetheringManager.TetheringOperationalState -eq 1){
    # 关闭移动热点
    Await ($tetheringManager.StopTetheringAsync()) ([Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationResult])
}
# 如果移动热点是关闭状态,则设置热点名称、热点的密码,然后开启移动热点
else{
 
    # 启动前先为移动热点设置SSID、密码
    $accessPoint = $tetheringManager.GetCurrentAccessPointConfiguration()
    # 为移动热点设置SSID
    $accessPoint.Ssid = "wifi_stzz"
    # 为移动热点设置密码
    $accessPoint.Passphrase = "12345678"
    $tetheringManager.ConfigureAccessPointAsync($accessPoint)
 
    # 启动/开启移动热点
    Await ($tetheringManager.StartTetheringAsync()) ([Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationResult])
}

Dado que la política predeterminada de los sistemas Windows 10 y Windows 111 prohíbe la ejecución directa de archivos de script ps1, primero debe modificar la política del sistema.

Abrir powershell con derechos de administrador

set-executionpolicy remotesigned

código Python:

import os
from glob import glob
import subprocess as sp


class PowerShell:
    # from scapy
    def __init__(self, coding, ):
        cmd = [self._where('PowerShell.exe'),
               "-NoLogo", "-NonInteractive",  # Do not print headers
               "-Command", "-"]  # Listen commands from stdin
        startupinfo = sp.STARTUPINFO()
        startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW
        self.popen = sp.Popen(cmd, stdout=sp.PIPE, stdin=sp.PIPE, stderr=sp.STDOUT, startupinfo=startupinfo)
        self.coding = coding

    def __enter__(self):
        return self

    def __exit__(self, a, b, c):
        self.popen.kill()

    def run(self, cmd, timeout=15):
        b_cmd = cmd.encode(encoding=self.coding)
        try:
            b_outs, errs = self.popen.communicate(b_cmd, timeout=timeout)
        except sp.TimeoutExpired:
            self.popen.kill()
            b_outs, errs = self.popen.communicate()
        outs = b_outs.decode(encoding=self.coding)
        return outs, errs

    @staticmethod
    def _where(filename, dirs=None, env="PATH"):
        """Find file in current dir, in deep_lookup cache or in system path"""
        if dirs is None:
            dirs = []
        if not isinstance(dirs, list):
            dirs = [dirs]
        if glob(filename):
            return filename
        paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs
        try:
            return next(os.path.normpath(match)
                        for path in paths
                        for match in glob(os.path.join(path, filename))
                        if match)
        except (StopIteration, RuntimeError):
            raise IOError("File not found: %s" % filename)


if __name__ == '__main__':
    # Example:
    with PowerShell('GBK') as ps:
        outs, errs = ps.run('set-executionpolicy remotesigned')
    print('error:', os.linesep, errs)
    print('output:', os.linesep, outs)

    with PowerShell('GBK') as ps:
        outs, errs = ps.run('./wifi.ps1')
    print('error:', os.linesep, errs)
    print('output:', os.linesep, outs)

Y para win7:

def start_wifi_hotspot(ssid, password):
    # 设置热点配置命令
    set_config_cmd = 'netsh wlan set hostednetwork mode=allow ssid={} key={}'.format(ssid, password)
    subprocess.call(set_config_cmd, shell=True)

    # 启动热点命令
    start_hotspot_cmd = 'netsh wlan start hostednetwork'
    subprocess.call(start_hotspot_cmd, shell=True)

# 在这里设置热点的名称和密码
ssid = "XXXXXXXXX"
password = "YYYYYYYYYYYY"

start_wifi_hotspot(ssid, password)

Supongo que te gusta

Origin blog.csdn.net/wtl1992/article/details/133309393
Recomendado
Clasificación