脚本来改变窗口的IP地址 [英] Script to change ip address on windows

查看:371
本文介绍了脚本来改变窗口的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用我的电脑通过以太网与硬件进行通信。要使用此设备我我的IP设置为192 168 0 11,子网掩码为255 255 255 0,和默认网关192 168 0 1对IPv4通信。要使用互联网,我选择获得IP地址自动通过控制面板。

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.

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

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

谢谢,

巴里。

推荐答案

您可以使用Python WMI模块做到这一点(安装 PyWin32扩展并运行这些脚本之前,WMI模块)。下面是如何配置的东西去跟硬件设备:

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

下面是如何恢复(通过DHCP)自动获取IP地址:

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

请注意:在生产脚本,你应该检查由返回的值EnableStatic的() SetGateways()和 EnableDHCP时()。 (0表示成功,1意味着需要重新启动和其他值由方法名链接到MSDN页面描述注:为EnableStatic的()和SetGateways(),错误codeS作为返回列表)。

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

在Win32NetworkAdapterConfiguration类的所有功能的全面信息,也可以上找到MSDN

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

请注意:我使用Python 2.7测试这一点,但作为PyWIn32和WMI模块可用于Python 3中,我相信你应该能够从字符串之前删除U得到这个工作的Python 3

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.

这篇关于脚本来改变窗口的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆