Oct 21, 2008

Python 自动搜索可用ip并设置

Python设置IP Address,用的是 qujinlong123@gmail.com 的,详见:用Python 干实事(一)自动修改Windows的IP、网关和DNS设置


我添加了搜索功能

# -*- coding: GB2312 -*-

# FileName: modify_ip.py
# Author  : ox0spy
# Email   : ossteerer@gmail.com
# Date    : 2008-10-21

# 程序的前两个函数是qujinlong123@gmail.com实现的,这里借用下


import _winreg
from ctypes import *

def    ModifyIpAddress(ipAddress, subnetMask, gateway, dnsServer):
    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: ', driverDesc
                netCfgInstanceID = _winreg.QueryValueEx(hSubKey, 'NetCfgInstanceID')[0]
                # print 'NetCfgInstanceID: ', netCfgInstanceID
                break
   
            _winreg.CloseKey(hNdiInfKey) # 关闭 RegKey
        except WindowsError, e:
                            pass
                # print r'Message: No Ndi\Interfaces Key'
           
        # 循环结束,目前只提供修改一个网卡IP的功能
        _winreg.CloseKey(hSubKey)
   
    _winreg.CloseKey(hkey)
   
    if netCfgInstanceID == None:
        print '修改IP失败 - 没有找到网络适配器'   
        exit()
   
    # print netCfgInstanceID
   
    # 通过修改注册表设置IP
    strKeyName = 'System\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\' + netCfgInstanceID
   
    # print strKeyName
   
    hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, \
                           strKeyName, \
                           0, \
                           _winreg.KEY_WRITE)
   
    try:
        _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)
    return netCfgInstanceID
   
# 调用DhcpNotifyConfigChange函数通知IP被修改
def Notify(netCfgInstanceID, ipAddress, subnetMask):
    DhcpNotifyConfigChange = windll.dhcpcsvc.DhcpNotifyConfigChange

    inet_addr = windll.Ws2_32.inet_addr

    # DhcpNotifyConfigChange 函数参数列表:
    # LPWSTR lpwszServerName,  本地机器为None
    # LPWSTR lpwszAdapterName, 网络适配器名称
    # BOOL bNewIpAddress,      True表示修改IP
    # DWORD dwIpIndex,         表示修改第几个IP, 从0开始
    # DWORD dwIpAddress,       修改后的IP地址
    # DWORD dwSubNetMask,      修改后的子码掩码
    # int nDhcpAction          对DHCP的操作, 0 - 不修改, 1 - 启用, 2 - 禁用
    DhcpNotifyConfigChange(None, \
                       netCfgInstanceID, \
                       True, \
                       0, \
                       inet_addr(ipAddress[0]), \
                       inet_addr(subnetMask[0]), \
                       0)


def Pin(ip = '192.168.1.1'):
    """ ping -n 1 ip"""
   
    import os
    if os.system("ping -n 1 %s >nul" % ip) == 0:
        return True
   
    return False   
               
def GetConfInfo(filename = 'conf.ini'):
        import re, sys
        try:
                f = open(filename, 'r')
                lines = [line.split('#')[0].strip() for line in f.readlines()]
                f.close()

                if len(lines) >= 6:
                        # ip网段
                        network = lines[0]
                        pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
                        if not re.search(pattern, network):
                                print '网段设置错误,请修改配置文件网段信息'
                                sys.exit(2)
                        network = network.split('.')
                        network.pop()
                        network = '.'.join(network)
                        # print 'network : ', network
                        # 开始ip
                        startIp = int(lines[1])
                        if (startIp < 1 or startIp > 254):
                                print '开始ip设置错误, ip :', startIp
                                sys.exit(3)
                        # 结束ip
                        endIp = int(lines[2])
                        if endIp < 2 or startIp > 255:
                                print '结束ip设置错误'
                                sys.exit(4)
                        # 子网掩码
                        subnetMask = lines[3]
                        # 默认网关
                        gateway = lines[4]
                        if not re.search(pattern, gateway):
                                print '默认网关设置错误'
                                sys.exit(5)
                        # dns
                        dnsServ = lines[5]
                        if not re.search(pattern, dnsServ):
                                print 'dns服务器设置错误'
                                sys.exit(6)
                else:
                        print '配置文件有误,请修正后重试'
                        sys.exit(1)
                     
        except IOError, e:
                print '确定配置文件名为 : %s' % filename
                sys.exit(7)

        return [network, startIp, endIp, subnetMask, gateway, dnsServ]

Info = GetConfInfo()
if not Info:
        sys.exit()

network, startIp, endIp, subnetMask, gateway, dnsServ = Info
if startIp == endIp:
        endIp += 1
       
ipAddress = ['%s.%s' % (network, i) for i in range(startIp, endIp)]
subnetMask = [subnetMask]
gateway = [gateway]
dnsServer = [dnsServ]
url = 'http://ox0spy.blogspot.com'

MessageBox = windll.user32.MessageBoxA

for ip in ipAddress:
    ip = [ip]
    # print 'IP Address : ', ip
    netCfgInstanceID = ModifyIpAddress(ip, subnetMask, gateway, dnsServer)
    Notify(netCfgInstanceID, ip, subnetMask)
    if Pin(url):
        # print '可用Ip地址 :', ip[0]
        msg = '可用Ip地址 : %s o(∩_∩)o...' % ip[0]
        MessageBox(0, msg, 'Good luck', 0)
        break;
else:
        msg = '没有可用ip,换个网段试试 ^_^'
        MessageBox(0, msg, 'sorry', 0)

No comments:

Post a Comment

您的评论将使我blog更有动力~