찾다
백엔드 개발파이썬 튜토리얼python实现自动更换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程序设计有所帮助。

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
차이 이해 : 파이썬의 루프 및 루프 용차이 이해 : 파이썬의 루프 및 루프 용May 16, 2025 am 12:17 AM

thedifferencebet weenaforloopandawhileloopinpythonisthataforloopisusured wherleationsisknortiStiskNowninAdvance, whileLeOpisUssed whileLoopisUssedStoBeCheckedThoBeCheckedTherfeTefeateThinumberofiTeRations.1) forloopsareIdealFerenceCecenceS

Python 루프 제어 : 대 VS의 경우 - 비교Python 루프 제어 : 대 VS의 경우 - 비교May 16, 2025 am 12:16 AM

Python에서는 반복의 수가 알려진 경우에 루프가 적합한 반면, 반복 횟수가 알려지지 않고 더 많은 제어가 필요한 경우 루프는 적합합니다. 1) 루프의 경우 간결하고 피해자 코드가있는 목록, 문자열 등과 같은 시퀀스에 적합합니다. 2) 조건에 따라 루프를 제어하거나 사용자 입력을 기다릴 때 루프가 더 적절하지만 무한 루프를 피하기 위해주의를 기울여야합니다. 3) 성능 측면에서 For 루프는 약간 빠르지 만 차이는 일반적으로 크지 않습니다. 올바른 루프 유형을 선택하면 코드의 효율성과 가독성이 향상 될 수 있습니다.

파이썬에서 두 목록을 결합하는 방법 : 5 가지 쉬운 방법파이썬에서 두 목록을 결합하는 방법 : 5 가지 쉬운 방법May 16, 2025 am 12:16 AM

파이썬에서 목록은 5 가지 방법을 통해 병합 될 수 있습니다. 1) 단순하고 직관적 인 연산자를 사용하여 작은 목록에 적합합니다. 2) Extend () 메소드를 사용하여 자주 업데이트 해야하는 목록에 적합한 원본 목록을 직접 수정하십시오. 3) 목록 분석 공식, 요소에 대한 간결하고 운영; 4) 효율적인 메모리에 IterTools.chain () 함수를 사용하여 대형 데이터 세트에 적합합니다. 5) * 연산자 및 Zip () 함수를 사용하여 요소를 짝을 이루어야하는 장면에 적합합니다. 각 방법에는 특정 용도 및 장점 및 단점이 있으며 선택할 때 프로젝트 요구 사항 및 성능을 고려해야합니다.

루프 대 루프 : 파이썬 구문, 사용 사례 및 예제루프 대 루프 : 파이썬 구문, 사용 사례 및 예제May 16, 2025 am 12:14 AM

Forloopsareusedwhendumberofiterationsisknown, whileloopsareusediltilaconditionismet.1) forloopsareIdealfecquenceslikelists, idingsyntax likes'forfruitinfruits : print (fruit) '

Python Concatenate 목록 목록Python Concatenate 목록 목록May 16, 2025 am 12:08 AM

Toconcatenatealistoflistsinpython, usextend, listcomprehensions, itertools.chain, orrecursiveFunctions.1) extendMethodistRaightForwardButverbose.2) ListComprehensionsArecisancisancisancisancisanceciancectionforlargerdatasets.3) itertools.chainismory-lefforforlargedas

Python의 병합 목록 : 올바른 메소드 선택Python의 병합 목록 : 올바른 메소드 선택May 14, 2025 am 12:11 AM

Tomergelistsinpython, youcanusethe operator, extendmethod, listcomprehension, oritertools.chain, 각각은 각각의 지위를 불러 일으킨다

Python 3에서 두 목록을 연결하는 방법은 무엇입니까?Python 3에서 두 목록을 연결하는 방법은 무엇입니까?May 14, 2025 am 12:09 AM

Python 3에서는 다양한 방법을 통해 두 개의 목록을 연결할 수 있습니다. 1) 작은 목록에 적합하지만 큰 목록에는 비효율적입니다. 2) 메모리 효율이 높지만 원래 목록을 수정하는 큰 목록에 적합한 확장 방법을 사용합니다. 3) 원래 목록을 수정하지 않고 여러 목록을 병합하는 데 적합한 * 운영자 사용; 4) 메모리 효율이 높은 대형 데이터 세트에 적합한 itertools.chain을 사용하십시오.

Python은 문자열을 연결합니다Python은 문자열을 연결합니다May 14, 2025 am 12:08 AM

join () 메소드를 사용하는 것은 Python의 목록에서 문자열을 연결하는 가장 효율적인 방법입니다. 1) join () 메소드를 사용하여 효율적이고 읽기 쉽습니다. 2)주기는 큰 목록에 비효율적으로 운영자를 사용합니다. 3) List Comprehension과 Join ()의 조합은 변환이 필요한 시나리오에 적합합니다. 4) READE () 방법은 다른 유형의 감소에 적합하지만 문자열 연결에 비효율적입니다. 완전한 문장은 끝납니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

Nordhold : Fusion System, 설명
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌
<exp exp> 모호한 : 원정 33- 완벽한 크로마 촉매를 얻는 방법
2 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.