windows下修改ip地址的脚本

发布于 2024-12-07 02:45:49 字数 243 浏览 5 评论 0原文

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

我想要一个脚本,允许我快速选择一种或另一种以太网设置 - 硬件或互联网。

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

谢谢,

巴里。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

云淡月浅 2024-12-14 02:45:50

您可以使用 subprocess 模块从命令行

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。

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.

李白 2024-12-14 02:45:50

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

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

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

import os; os.system("ipconfig /renew")
岁月蹉跎了容颜 2024-12-14 02:45:50
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')

#再次恢复正常

def back2normal():
    adapter = find_net_device()
    normal = f'netsh interface ip set address {adapter} dhcp'
    subprocess.run(normal,stdout=PIPE, universal_newlines=True)
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)
别再吹冷风 2024-12-14 02:45:50

您可以使用 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

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
残花月 2024-12-14 02:45:49

您可以使用 Python WMI 模块 来执行此操作(安装 PyWin32 扩展 和运行这些脚本之前的 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()启用 DHCP()。 (“0”表示成功,“1”表示需要重新启动,其他值在方法名称链接到的 MSDN 页面上进行了描述。注意:对于 EnableStatic() 和 SetGateways(),错误代码以列表形式返回)。

有关 Win32NetworkAdapterConfiguration 类所有功能的完整信息也可以在 MSDN 上找到。

注意:我使用 Python 2.7 对此进行了测试,但由于 PyWIn32 和 WMI 模块可用于 Python 3,我相信您应该能够通过删除字符串文字前面的“u”来使其适用于 Python 3。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文