You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows 10下如何用ps命令或Python模块控制WiFi共享属性?

在Windows 10中启用/禁用WiFi的Internet连接共享(ICS)

以下是可用的PowerShell命令和Python实现方案,均需以管理员身份执行:


PowerShell 实现方法

1. 定位WiFi适配器名称

先运行命令获取所有网络适配器,找到你的WiFi适配器名称(通常含“WiFi”或“无线”关键字):

Get-NetAdapter | Select-Object Name, InterfaceDescription

2. 启用ICS

将命令中的"你的WiFi适配器名称"替换为实际名称后执行:

$adapter = Get-WmiObject -Class Win32_NetworkAdapter -Filter "Name='你的WiFi适配器名称'"
$ics = Get-WmiObject -Class Win32_InternetConnectionSharing -Filter "InterfaceIndex=$($adapter.InterfaceIndex)"
$ics.EnableSharing(1)

3. 禁用ICS

同样替换适配器名称后执行:

$adapter = Get-WmiObject -Class Win32_NetworkAdapter -Filter "Name='你的WiFi适配器名称'"
$ics = Get-WmiObject -Class Win32_InternetConnectionSharing -Filter "InterfaceIndex=$($adapter.InterfaceIndex)"
$ics.EnableSharing(0)

Python 实现方法

方法1:使用wmi模块

  1. 先安装依赖模块:
pip install wmi
  1. 编写脚本实现开关控制:
import wmi

def toggle_wifi_ics(adapter_name, enable=True):
    wmi_client = wmi.WMI()
    # 获取目标适配器
    adapters = wmi_client.Win32_NetworkAdapter(Name=adapter_name)
    if not adapters:
        print(f"未找到指定适配器:{adapter_name}")
        return
    target_adapter = adapters[0]
    # 获取ICS配置项
    ics_configs = wmi_client.Win32_InternetConnectionSharing(InterfaceIndex=target_adapter.InterfaceIndex)
    if not ics_configs:
        print("未找到该适配器的ICS配置")
        return
    ics_obj = ics_configs[0]
    # 执行启用/禁用操作
    result_code = ics_obj.EnableSharing(1 if enable else 0)[0]
    if result_code == 0:
        print(f"{'启用' if enable else '禁用'}WiFi的ICS成功")
    else:
        print(f"操作失败,错误代码:{result_code}")

# 调用示例
toggle_wifi_ics("你的WiFi适配器名称", enable=True)  # 启用ICS
# toggle_wifi_ics("你的WiFi适配器名称", enable=False)  # 禁用ICS

方法2:直接调用PowerShell命令(无需额外模块)

通过subprocess调用PowerShell命令,无需安装第三方库:

import subprocess

def run_admin_powershell(cmd):
    result = subprocess.run(
        ["powershell", "-Command", cmd],
        capture_output=True,
        text=True,
        shell=True
    )
    if result.returncode != 0:
        print(f"执行出错:{result.stderr.strip()}")
    else:
        print("操作成功")

def enable_wifi_ics(adapter_name):
    ps_cmd = f'''
$adapter = Get-WmiObject -Class Win32_NetworkAdapter -Filter "Name='{adapter_name}'"
$ics = Get-WmiObject -Class Win32_InternetConnectionSharing -Filter "InterfaceIndex=$($adapter.InterfaceIndex)"
$ics.EnableSharing(1)
'''
    run_admin_powershell(ps_cmd)

def disable_wifi_ics(adapter_name):
    ps_cmd = f'''
$adapter = Get-WmiObject -Class Win32_NetworkAdapter -Filter "Name='{adapter_name}'"
$ics = Get-WmiObject -Class Win32_InternetConnectionSharing -Filter "InterfaceIndex=$($adapter.InterfaceIndex)"
$ics.EnableSharing(0)
'''
    run_admin_powershell(ps_cmd)

# 调用示例
enable_wifi_ics("你的WiFi适配器名称")
# disable_wifi_ics("你的WiFi适配器名称")

内容的提问来源于stack exchange,提问作者Cezar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:30:47