更新:由于我已经弄清楚了如何获取NIC的索引,因此对该问题进行了很多更新,但不允许我设置IP。当我尝试应用IP设置时,我会丢失哪些不接受IP设置的信息?
我需要编写一种方法来编写Python 3.7中的网络适配器设置的方法,但是它基于用户输入,其中列出了笔记本电脑上的所有网络适配器,然后用户选择了正确的适配器。
我一直在使用WMI模块,并尝试了多种方法来使这项工作顺利进行。我可以获取枚举适配器的列表,然后提供输入。我只是无法将所选的适配器号转换为WMI找到的网络适配器。
import wmi
#List NICs by Index and Description
c = wmi.WMI()
for nic in c.Win32_NetworkAdapterConfiguration(IPEnabled=True):
print(nic.Index, nic.Description)
#Choose which NIC to apply changes to:
nic_selection_index = c.Win32_NetworkAdapterConfiguration(Index = input('Choose Network Adapter Number on left to change: '))
#Will be hidden once working
print(nic_selection_index)
#Get IP Info to use on NIC
ip = input('Enter IP to use: ')
subnetmask = input('Enter Subnet Mask to use: ')
gateway = input('Enter Default Gateway to use: ')
print(ip)
print(subnetmask)
print(gateway)
## Set IP address, subnetmask and default gateway
## Note: EnableStatic() and SetGateways() methods require *lists* of values to be passed
nic_selection_index.EnableStatic(IPAddress=[ip],SubnetMask=[subnetmask])
nic_selection_index.SetGateways(DefaultIPGateway=[gateway])
#Results:
Traceback (most recent call last):
File "test nic change.py", line 56, in <module>
nic_selection_index.EnableStatic(IPAddress=[ip],SubnetMask=[subnetmask])
AttributeError: 'list' object has no attribute 'EnableStatic'
我已经参考了其他设置IP的问题,但这些问题不是基于我输入的用户输入来设置的。我需要能够提示用户输入信息。谢谢!
答案 0 :(得分:0)
所有,我都能正常工作,甚至还添加了一些DNS更改。我正在发布,以防其他任何人正在寻找这种确切的需求。
import wmi
#List NICs by Index and Description
c = wmi.WMI()
for nic in c.Win32_NetworkAdapterConfiguration(IPEnabled=True):
print(nic.Index, nic.Description)
#Choose which NIC to apply changes to:
nic_selection_index = c.Win32_NetworkAdapterConfiguration(Index = input('Choose Network Adapter Number on left to change: '))
#This selects the entire NIC properties -- can't just use the index value above
nic_selection_all = nic_selection_index[0]
#Will be hidden once working
print(nic_selection_all)
#Get IP Info to use on NIC
ip = input('Enter IP to use: ')
subnetmask = input('Enter Subnet Mask to use: ')
gateway = input('Enter Default Gateway to use: ')
dns = '127.0.0.1'
print(ip)
print(subnetmask)
print(gateway)
## Set IP address, subnetmask and default gateway
## Note: EnableStatic() and SetGateways() methods require *lists* of values to be passed
nic_selection_all.EnableStatic(IPAddress=[ip],SubnetMask=[subnetmask])
nic_selection_all.SetGateways(DefaultIPGateway=[gateway])
nic_selection_all.SetDNSServerSearchOrder([dns])
nic_selection_all.SetDNSDomain("my.random.domain")