14

I use my computer to communicate with a piece of hardware via ethernet. To communicate with this device I set my ip to 192 168 0 11, subnet mask to 255 255 255 0, and default gateway to 192 168 0 1 for IPv4. To use the internet, I choose "Obtain an IP address automatically" via control panel.

I'd like to have a script that allows my to quickly choose one or the other ethernet setting - hardware or internet.

I program mostly in python but maybe there is a batch file solution.

Thanks,

Barry.

1

5 Answers 5

27

You can use the Python WMI module to do this (install the PyWin32 extensions and the WMI module before running these scripts). Here is how to configure things to talk to the hardware device:

import wmi

# Obtain network adaptors configurations
nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)

# First network adaptor
nic = nic_configs[0]

# IP address, subnetmask and gateway values should be unicode objects
ip = u'192.168.0.11'
subnetmask = u'255.255.255.0'
gateway = u'192.168.0.1'

# Set IP address, subnetmask and default gateway
# Note: EnableStatic() and SetGateways() methods require *lists* of values to be passed
nic.EnableStatic(IPAddress=[ip],SubnetMask=[subnetmask])
nic.SetGateways(DefaultIPGateway=[gateway])

Here is how to revert to obtaining an IP address automatically (via DHCP):

import wmi

# Obtain network adaptors configurations
nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)

# First network adaptor
nic = nic_configs[0]

# Enable DHCP
nic.EnableDHCP()

Note: in a production script you should check the values returned by EnableStatic(), SetGateways() and EnableDHCP(). ('0' means success, '1' means reboot required and other values are described on the MSDN pages linked to by the method names. Note: for EnableStatic() and SetGateways(), the error codes are returned as lists).

Full information on all the functionality of the Win32NetworkAdapterConfiguration class can also be found on MSDN.

Note: I tested this with Python 2.7, but as PyWIn32 and WMI modules are available for Python 3, I believe you should be able to get this working for Python 3 by removing the "u" from before the string literals.

1
  • Nice answer, except that it's not clear how to tell between several network interfaces if there're more than one (nic.Description for that) and that the script must be called with Administrator rights (see stackoverflow.com/questions/6811372/…) Mar 28, 2019 at 8:57
6

You can use the subprocess module to start

netsh interface ip set address [params]

Start this from the commandline (without[params]) to get some help how to use it. Then you can do

import subprocess
subprocess.call("netsh interface ip set address ....".split())

Update:

For those who's too busy to rtfm,

netsh interface ip set address lan static 192.168.0.100 255.255.255.0
netsh interface ip set address lan dhcp

here lan is the name of the network interface to configure, 192.168.0.100 is ip address, 255.255.255.0 is network mask. The first command sets static address, the second reverts to dhcp.

1
  • 1
    I've updated the answer with some details, hope you don't mind ;) Mar 28, 2019 at 8:48
-1

Actually very simple to do (windows only) (uses preinstalled libraries only):

import os; os.system("ipconfig /renew")
-1
import os
import subprocess

from subprocess import PIPE
def find_net_device():
    cmd ='netsh interface ipv4 show interfaces'.split()

    result = subprocess.run(cmd, universal_newlines = True,
                            stdout = subprocess.PIPE)                              
    result = result.stdout
    result = result.split('connected')[2]
    result = result.split('\n')[0]
    result = result.strip()
    return result








def change_ip(ip):
    adapter = find_net_device()
    change =f'netsh interface ip set address {adapter} static {ip} 255.255.255.0'
    change = change.split()


change_ip('165.22.64.68')

#again back to normal

def back2normal():
    adapter = find_net_device()
    normal = f'netsh interface ip set address {adapter} dhcp'
    subprocess.run(normal,stdout=PIPE, universal_newlines=True)
-2

You can use vbscript to change IP Address,

Dim strIPAddress, strSubnetMask,strGateway, intGatewayMetric, strDns1, strDns2, objWMIService, colItems, stradaptername, objFSO
Const ForReading = 1 
Const ForAppending = 8
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set OutPutFile = objFSO.CreateTextFile("C:\ProgramData\test.txt" ,2 , True)
Set InterfaceName = objWMIService.ExecQuery ("Select * From Win32_NetworkAdapter Where NetConnectionStatus >= 0")
If objFSO.FileExists("C:\ProgramData\test.txt") Then
Set OutPutFile = objFSO.CreateTextFile("C:\ProgramData\test1.txt" ,2 , True)
End If
For Each objItem in InterfaceName
If objFSO.FileExists("C:\ProgramData\test.txt") Then
arrInterfaces = objItem.NetConnectionID
'wscript.echo "test: " &arrInterfaces
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\ProgramData\test.txt",8,true)
ObjFileToWrite.WriteLine(arrInterfaces)
objFileToWrite.Close
Set objFileToWrite = Nothing
End If
next
If objFSO.FileExists("C:\ProgramData\test.txt") Then
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\ProgramData\test.txt",1)
strFileText = objFileToRead.ReadAll()
objFileToRead.Close
Set objFileToRead = Nothing
'wscript.echo "obtained" &strFileText
End If
Result = inputbox("Enter the AdapterName: " &vbCrLf &strFileText)
If Result = "" then
'wscript.echo "user selected cancel"
Else
strIPAddress=InputBox("Enter Static IP Adrress: ")
strSubnetMask =InputBox("Enter SubnetMask: " )
strGateway=InputBox("Enter Default Gateway: ")
strDns1=InputBox("Enter Preferred DNS: ")
strDns2=InputBox("Enter Alternate DNS: ")
Set objShell = WScript.CreateObject("Wscript.Shell")
objShell.CurrentDirectory = "C:\Windows\System32"
objShell.Run "netsh interface ip set address name=""" & Result & """ static " & strIPAddress & " " & strSubnetMask & " " & strGateway & " " & intGatewayMetric, 0, True
objShell.Run "netsh interface ip set dns name=" & Result & " static "& strDns1, 0, True
objShell.Run "netsh interface ip add dns name=" & Result & " addr="& strDns2, 0, True
Set objShell = Nothing: Set obj=Nothing
End If
WScript.Quit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.