Search code examples
pythonnetwork-programmingwmipywin32

Using WMI and PYWIN32 to change IPV4 settings on Ethernet card


Im trying to change the IPV4 adress on the Ethernet-card. But when i run the script only the subnetmask changes and the IPV4 settings remain on "obtain an IP address automaticly". Any clue?

Info: The var_ip, var_mask, var_gateway comes from entry widgets.

import wmi

def set_ip():

nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)

# First network adaptor
nic = nic_configs[0]
ip = var_ip.get()
subnetmask = var_mask.get()
gateway = var_gateway.get()

# Set IP address, subnet mask and default gateway
a = nic.EnableStatic(IPAddress=[ip], SubnetMask=[subnetmask])
b = nic.SetGateways(DefaultIPGateway=[gateway])

Solution

  • In one of my projects I also tried to do this using WMI, finally changed this to using netsh program. You can use CreateProcess and pass required parameters to netsh. For example, assuming that Etnernet adapter name is eth1, command-line utility netsh can be used by the following way:

    netsh interface ipv4 set address "eth1" dhcp
    
    netsh interface ipv4 set address "eth1" static 192.168.0.1 255.255.255.0
    

    See also: https://www.howtogeek.com/103190/change-your-ip-address-from-the-command-prompt/