# 链接网络 断开网络
import ctypes
import psutil
def run_command_as_admin(command):
try:
ctypes.windll.shell32.ShellExecuteW(None, "runas", "cmd.exe", f"/c {command}", None, 1)
except Exception as e:
print(f"出现错误:{e}")
def disable_network_adapter(adapter_name):
try:
adapters = psutil.net_if_stats()
if adapter_name in adapters and adapters[adapter_name].isup:
# 禁用适配器
command = f"netsh interface set interface \"{adapter_name}\" admin=disable"
run_command_as_admin(command)
print(f"已禁用网络适配器 {adapter_name}")
else:
print(f"网络适配器 {adapter_name} 不存在或已禁用")
except Exception as e:
print(f"出现错误:{e}")
def enable_network_adapter(adapter_name):
try:
adapters = psutil.net_if_stats()
print(list(adapters.keys()))
command = f"netsh interface set interface \"{adapter_name}\" admin=enable"
run_command_as_admin(command)
print(f"已启用网络适配器 {adapter_name}")
except Exception as e:
print(f"出现错误:{e}")
# 替换成你要操作的网络适配器的名称
adapter_name_to_disable = "WLAN"
adapter_name_to_enable = "WLAN"
# 禁用网络适配器
disable_network_adapter(adapter_name_to_disable)
# 启用网络适配器
# enable_network_adapter(adapter_name_to_enable)
python切换网络
于 2023-12-11 10:10:32 首次发布





