2014-08-28 491 views
-1

是否可以在Windows 7中禁用和启用Python中的网络连接?我在这里看到了一个关于此的前一个问题:How to programmatically enable/disable network interfaces? (Windows XP),但仍找不到解决方案!请与我分享代码!马丁的回答给了我这个:b'Index名称如何在Python中禁用网络连接代码

\r\r\n0  WAN Miniport (SSTP)             \r\r\n1  WAN Miniport (IKEv2)             \r\r\n2  WAN Miniport (L2TP)             \r\r\n3  WAN Miniport (PPTP)             \r\r\n4  WAN Miniport (PPPOE)             \r\r\n5  WAN Miniport (IPv6)             \r\r\n6  WAN Miniport (Network Monitor)          \r\r\n7  Realtek RTL8102E/RTL8103E Family PCI-E Fast Ethernet NIC (NDIS 6.20) \r\r\n8  WAN Miniport (IP)              \r\r\n9  Microsoft ISATAP Adapter            \r\r\n10  RAS Async Adapter              \r\r\n11  Atheros AR5007 802.11b/g WiFi Adapter         \r\r\n12  Teredo Tunneling Pseudo-Interface          \r\r\n13  Microsoft ISATAP Adapter #2           \r\r\n\r\r\n' 

回答

2

摘自from here

您需要使用subprocess启动下面的命令行实用程序:

开始提升的命令提示符。

# Get NIC list and index number: 
wmic nic get name, index 

# Enable NIC with index number: (eg: 7) 
wmic path win32_networkadapter where index=7 call enable 

# Disable NIC with index number: (eg: 7) 
wmic path win32_networkadapter where index=7 call disable 

所以在Python,你会使用类似

import subprocess 
# get list of adapters and find index of adapter you want to disable. 
subprocess.check_output('wmic nic get name, index') 

要获得适配器列表,然后再对其他命令运行subprocess.check_output一旦你知道了指数。另外请确保您以特权用户身份运行您的python脚本。

+0

更新了我的问题。这是如何禁用网络连接的? – 2014-08-28 18:48:38

+0

确保你'输出':'subprocess.check_output('wmic nic get name,index')。strip()' - 这将删除'\ n \ n'字符。那么你的第一个字符就是'0',这是索引。您应该可以调用'wmic path win32_networkadapter where index = 0 call disable' – 2014-08-28 18:52:00

+0

由于某些原因,.strip()不会删除'\ r'字符! – 2014-08-28 19:01:26