I need to connect to a device via an Ethernet connection on Windows and have to set a static IP Address and Submask for this.
I need to create a Python script, which automates this workflow. The workflow is the following on Windows (see https://pynq.readthedocs.io/en/latest/appendix/assign_a_static_ip.html):
- Go to Control Panel -> Network and Internet -> Network Connections
- Find your Ethernet network interface, usually Local Area Connection
- Double click on the network interface to open it, and click on Properties
- Select Internet Protocol Version 4 (TCP/IPv4) and click Properties
- Select Use the following IP address
- Set the Ip address to 192.168.2.1 (or any other address in the same range as the board)
- Set the subnet mask to 255.255.255.0 and click OK
Of course, one needs admin rights to execute this. I am using the pyuac
package for this (https://pypi.org/project/pyuac/).
This is my code so far (some is similar to Script to change ip address on windows). When I execute the change_nic_ip()
method only, it apparently changes my WiFi ip address, because I don't have an internet connection after running the script.
import pyuac
def change_nic_ip():
# Obtain network adapters configurations
nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)
# First network adapter
nic = nic_configs[0]
print(nic.IPAddress[0]) # debug message
# IP address, subnetmask and gateway values should be unicode objects
ip = '192.168.2.1'
subnetmask = '255.255.255.0'
# Set IP address and subnetmask
static_ip = nic.EnableStatic(IPAddress=[ip], SubnetMask=[subnetmask])
if 0 in static_ip:
print("Successful changing to static IP address!")
else:
raise ValueError("Error: Changing to static IP address unsuccessful! Error Code: " + static_ip)
print(nic.IPAddress[0]) # debug message
# TODO check if static IP Address is actually correct
def revert_to_automatic_ip():
# Obtain network adapters configurations
nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)
# First network adapter
nic = nic_configs[0]
# Enable DHCP
dhcp = nic.EnableDHCP()
if 0 in dhcp:
print("Successfully changed to automatic IP configuration!")
else:
raise ValueError("Error: Changing to automatic IP address unsuccessful! Error Code: " + dhcp)
if __name__ == '__main__':
if not pyuac.isUserAdmin():
pyuac.runAsAdmin()
else:
change_nic_ip()
revert_to_automatic_ip()
# TODO remove
import time
time.sleep(3)
TLDR: Tried using the following python script to change Ethernet IP Address from automatic to a static IP address, but it seems to change Wifi IP Address.
EDIT: I think I was off by one.
nic = nic_configs[0]
needs to be nic = nic_configs[1]