search
HomeBackend DevelopmentPython Tutorialpython实现自动更换ip的方法

本文实例讲述了python实现自动更换ip的方法。分享给大家供大家参考。具体实现方法如下:

#!/usr/bin/env python
#-*- encoding:gb2312 -*-
# Filename: IP.py
import sitecustomize
import _winreg
import ConfigParser
from ctypes import *
print '正在进行网络适配器检测,请稍候…'
print
netCfgInstanceID = None
hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, \
r'System\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}')
keyInfo = _winreg.QueryInfoKey(hkey)
# 寻找网卡对应的适配器名称 netCfgInstanceID
for index in range(keyInfo[0]):
hSubKeyName = _winreg.EnumKey(hkey, index)
hSubKey = _winreg.OpenKey(hkey, hSubKeyName)
try:
hNdiInfKey = _winreg.OpenKey(hSubKey, r'Ndi\Interfaces')
lowerRange = _winreg.QueryValueEx(hNdiInfKey, 'LowerRange')
# 检查是否是以太网
if lowerRange[0] == 'ethernet':
driverDesc = _winreg.QueryValueEx(hSubKey, 'DriverDesc')[0]
print '检测到网络适配器名:', driverDesc
netCfgInstanceID = _winreg.QueryValueEx(hSubKey, 'NetCfgInstanceID')[0]
print '检测到网络适配器ID:', netCfgInstanceID
if netCfgInstanceID == None:
print '没有找到网络适配器,程序退出'
exit()
break
_winreg.CloseKey(hNdiInfKey)
except WindowsError:
print r'Message: No Ndi\Interfaces Key'
# 循环结束,目前只提供修改一个网卡IP的功能
_winreg.CloseKey(hSubKey)
_winreg.CloseKey(hkey)
# 通过修改注册表设置IP
strKeyName = 'System\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\' + netCfgInstanceID
print '网络适配器的注册表地址是:\n', strKeyName
hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, \
strKeyName, \
0, \
_winreg.KEY_WRITE)
config = ConfigParser.ConfigParser()
print
print '正在打开IP.ini配置文件…'
config.readfp(open('IP.ini'))
IPAddress = config.get("school","IPAddress")
SubnetMask = config.get("school","SubnetMask")
GateWay = config.get("school","GateWay")
DNSServer1 = config.get("school","DNSServer1")
DNSServer2 = config.get("school","DNSServer2")
DNSServer = [DNSServer1,DNSServer2]
print '配置文件内设定的信息如下,请核对:'
print
print 'IP地址:', IPAddress
print '子关掩码:', SubnetMask
print '默认网关:', GateWay
print '主DNS服务器:', DNSServer1
print '次DNS服务器:', DNSServer2
print
res = raw_input('现在,请您决定:输入1,则将配置文件写入系统;输入2,则将现有的系统设定还原为全部自动获取;否则程序退出:')
if str(res) == '1':
try:
_winreg.SetValueEx(hkey, 'EnableDHCP', None, _winreg.REG_DWORD, 0x00000000)
_winreg.SetValueEx(hkey, 'IPAddress', None, _winreg.REG_MULTI_SZ, [IPAddress])
_winreg.SetValueEx(hkey, 'SubnetMask', None, _winreg.REG_MULTI_SZ, [SubnetMask])
_winreg.SetValueEx(hkey, 'DefaultGateway', None, _winreg.REG_MULTI_SZ, [GateWay])
_winreg.SetValueEx(hkey, 'NameServer', None, _winreg.REG_SZ, ','.join(DNSServer))
except WindowsError:
print 'Set IP Error'
exit()
_winreg.CloseKey(hkey)
print '切换成功!重置网络后即可生效'
elif str(res) == '2':
try:
_winreg.SetValueEx(hkey, 'EnableDHCP', None, _winreg.REG_DWORD, 0x00000001)
_winreg.SetValueEx(hkey, 'T1', None, _winreg.REG_DWORD, 0x00000000)
_winreg.SetValueEx(hkey, 'T2', None, _winreg.REG_DWORD, 0x00000000)
_winreg.SetValueEx(hkey, 'NameServer', None, _winreg.REG_SZ, None)
_winreg.SetValueEx(hkey, 'DhcpConnForceBroadcastFlag', None, _winreg.REG_DWORD, 0x00000000)
_winreg.SetValueEx(hkey, 'Lease', None, _winreg.REG_DWORD, 0x00000000)
_winreg.SetValueEx(hkey, 'LeaseObtainedTime', None, _winreg.REG_DWORD, 0x00000000)
_winreg.SetValueEx(hkey, 'LeaseTerminatesTime', None, _winreg.REG_DWORD, 0x00000000)
except WindowsError:
print 'Set IP Error'
exit()
_winreg.CloseKey(hkey)
print '切换成功!重置网络后即可生效'
else:
print '用户手动取消,程序退出'
exit('')

希望本文所述对大家的Python程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

How can you make a Python script executable on both Unix and Windows?How can you make a Python script executable on both Unix and Windows?May 06, 2025 am 12:13 AM

TomakeaPythonscriptexecutableonbothUnixandWindows:1)Addashebangline(#!/usr/bin/envpython3)andusechmod xtomakeitexecutableonUnix.2)OnWindows,ensurePythonisinstalledandassociatedwith.pyfiles,oruseabatchfile(run.bat)torunthescript.

What should you check if you get a 'command not found' error when trying to run a script?What should you check if you get a 'command not found' error when trying to run a script?May 06, 2025 am 12:03 AM

When encountering a "commandnotfound" error, the following points should be checked: 1. Confirm that the script exists and the path is correct; 2. Check file permissions and use chmod to add execution permissions if necessary; 3. Make sure the script interpreter is installed and in PATH; 4. Verify that the shebang line at the beginning of the script is correct. Doing so can effectively solve the script operation problem and ensure the coding process is smooth.

Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software