最近想尝试做一个辅助工具用于将网卡设置成静态IP或禁用启用网卡,使用netsh命令禁用启用网卡需要用到网卡的名字,禁用网卡例如:
os.popen('netsh interface set interface "以太网" admin=DISABLE')
开启网卡:
os.popen('netsh interface set interface "以太网" admin=ENABLE')
ipconfig /all 命令只能查看到启用的网卡信息,使用netsh命令的前提是需要知道网卡的名字,太麻烦了,花了很长时间,最后通过下面的代码实现了获取网卡名称和状态,初学者的痛!!!
net_dict = {}
State = []
# 获取到电脑上所有的网卡信息
r = os.popen('netsh interface show interface name=""')
text = r.read()
# 将不要的信息删除掉
text1 = text.replace("Dedicated", "").replace("Disconnected", "").replace("Connected", "")
# 按行来分
text2 = text1.splitlines()
for line in text2:
if line != "":
#找到关键字后面的信息
interface = line[line.index('abled') + 5:].split(':')[0]
# 删除前面的空格,加入字典
net_dict[interface.lstrip()] = net_dict
p_example = line
# 删除空格后面的字符串,保留前面的
first_str = " "
head, sep, tail = p_example.partition(first_str)
clean_str = head
State.append(clean_str)
# 字典转换成列表
key_value = list(net_dict.keys())
x = len(text2)
# 循环获取到网卡的名称和对应状态
for i in range(1, x):
a = key_value[i - 1]
b = State[i-1]
print("网卡" + str(i) +"的名称为:%s" % a + ",网卡的状态为:%s" % b)