在Windows上更改IP地址的脚本

时间:2011-09-28 09:07:46

标签: python windows windows-7 batch-file ipv4

我使用计算机通过以太网与一块硬件进行通信。要与此设备通信,我将ip设置为192 168 0 11,将子网掩码设置为255 255 255 0,将默认网关设置为192 168 0 1 for IPv4。要使用互联网,我选择“通过控制面板自动获取IP地址”。

我希望有一个脚本允许我快速选择一个或另一个以太网设置 - 硬件或互联网。

我主要在python中编程,但也许有一个批处理文件解决方案。

谢谢,

巴里。

5 个答案:

答案 0 :(得分:16)

您可以使用Python WMI module执行此操作(在运行这些脚本之前安装PyWin32 extensions和WMI模块)。以下是如何配置要与硬件设备通信的内容:

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])

以下是如何恢复自动获取IP地址(通过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()

注意:在生产脚本中,您应该检查EnableStatic()SetGateways()EnableDHCP()返回的值。 ('0'表示成功,'1'表示需要重新启动,其他值在通过方法名称链接的MSDN页面上描述。注意:对于EnableStatic()和SetGateways(),错误代码将作为列表返回。)< / p>

有关Win32NetworkAdapterConfiguration类的所有功能的完整信息也可以是found on MSDN

注意:我使用Python 2.7进行了测试,但由于PyWIn32和WMI模块可用于Python 3,我相信你应该能够通过从字符串文字之前删除“u”来使Python 3工作。< / p>

答案 1 :(得分:5)

您可以使用子流程模块启动

netsh interface ip set address [params]

从命令行开始(没有[params])以获得如何使用它的帮助。然后就可以了

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

<强>更新

对于那些忙于rtfm的人,

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

此处lan是要配置的网络接口的名称,192.168.0.100是IP地址,255.255.255.0是网络掩码。第一个命令设置静态地址,第二个命令恢复为dhcp。

答案 2 :(得分:0)

实际上非常简单(仅Windows)(仅使用预安装的库):

import os; os.system("ipconfig /renew")

答案 3 :(得分:0)

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

#恢复正常

const [token, setToken] = useState("");

useEffect(() => {
  new firebase.auth.RecaptchaVerifier("request-otp", { size: "invisible" })
    .verify()
    .then(setToken);
}, []);

答案 4 :(得分:-1)

您可以使用vbscript更改IP地址,

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