您的位置:

python切换ip脚本(python 拨号换ip)

本文目录一览:

如何设置指定ip和自动获取转换脚本

设置指定ip和自动获取转换脚本的方法

打开电脑的记事本,复制如下代码:

代码开始:

————————————————————

@echo off netsh int ip set ad name="本地连接" so=static ad=192.168.1.6 ma=255.255.255.0 ga=192.168.1.1 gw=0 echo 设置成功。

echo 正在设置DNS,请稍候.....netsh int ip set dns name="本地连接" source=static addr=192.168.1.1

————————————————————

代码结束

注意保存在电脑桌面上时,结尾为名称.bat,保存类型为所有文件。

我们先查看一下现在本机的ip

再运行我们的批处理

此时我们的ip,就变成我们自己设置的了。以后只要上不了网,就可以用这个批处理。超方便啦。

如果想设置成自动获取,则复制如下代码,

代码开始:

——————————————

@echo off echo 快速设置IP地址和DNS为"自动获得"echo.netsh int ip set addr "本地连接" dhcpnetsh int ip set dns "本地连接" dhcp

——————————————

代码结束

另存为 自动获取.bat

此时就可以自动获取了,上不了局域网的时候,就在这两个之间切换就可以了,不用手动设置,很方便。

python怎么改变自己的ip

双击任务栏上的电脑图表---属性-----选中TCP/IP协议-----点属性---选使用下面的IP---修改就可以了 !也可以右击桌面上的网上邻居----右击本地连接----属性-----选中TCP/IP协议-----点属性---选使用下面的IP---修改就可以了 !平常不要轻易去修改,以免造成不必要的麻烦!!

求知:python+selenium使用自己服务器多个IP的切换

可以考虑修改路由表的方法,Windows和Linux的route命令略有不同。

Win7系统

route CHANGE 157.0.0.0 MASK 255.0.0.0 157.55.80.5 METRIC 2 IF 2

Linux系统

ip route change to 192.168.0.0/24 dev eth0 src 192.168.0.22

python中,进行爬虫抓取怎么样能够使用代理IP?

网络数据量越来越大,从网页中获取信息变得越来越困难,如何有效地抓取并利用信息,已成为网络爬虫一个巨大的挑战。下面IPIDEA为大家讲明爬虫代理IP的使用方法。

1. 利用爬虫脚本每天定时爬取代理网站上的ip,写入MongoDB或者其他的数据库中,这张表作为原始表。

2. 使用之前需要做一步测试,就是测试这个ip是否有效,方法就是利用curl访问一个网站查看返回值,需要创建一张新表,循环读取原始表有效则插入,验证之后将其从原始表中删除,验证的同时能够利用响应时间来计算这个ip的质量,和最大使用次数,有一个算法能够参考一种基于连接代理优化管理的多线程网络爬虫处理方法。

3. 把有效的ip写入ip代理池的配置文件,重新加载配置文件。

4.让爬虫程序去指定的dailiy的服务ip和端口,进行爬取。

python 运维常用脚本

Python 批量遍历目录文件,并修改访问时间

import os

path = "D:/UASM64/include/"

dirs = os.listdir(path)

temp=[];

for file in dirs:

temp.append(os.path.join(path, file))

for x in temp:

os.utime(x, (1577808000, 1577808000))

Python 实现的自动化服务器管理

import sys

import os

import paramiko

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def ssh_cmd(user,passwd,port,userfile,cmd):

def ssh_put(user,passwd,source,target):

while True:

try:

shell=str(input("[Shell] # "))

if (shell == ""):

continue

elif (shell == "exit"):

exit()

elif (shell == "put"):

ssh_put("root","123123","./a.py","/root/a.py")

elif (shell =="cron"):

temp=input("输入一个计划任务: ")

temp1="(crontab -l; echo "+ temp + ") |crontab"

ssh_cmd("root","123123","22","./user_ip.conf",temp1)

elif (shell == "uncron"):

temp=input("输入要删除的计划任务: ")

temp1="crontab -l | grep -v " "+ temp + "|crontab"

ssh_cmd("root","123123","22","./user_ip.conf",temp1)

else:

ssh_cmd("lyshark","123123","22","./user_ip.conf",shell)

遍历目录和文件

import os

def list_all_files(rootdir):

import os

_files = []

list = os.listdir(rootdir) #列出文件夹下所有的目录与文件

for i in range(0,len(list)):

path = os.path.join(rootdir,list[i])

if os.path.isdir(path):

_files.extend(list_all_files(path))

if os.path.isfile(path):

_files.append(path)

return _files

a=list_all_files("C:/Users/LyShark/Desktop/a")

print(a)

python检测指定端口状态

import socket

sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

sk.settimeout(1)

for ip in range(0,254):

try:

sk.connect(("192.168.1."+str(ip),443))

print("192.168.1.%d server open \n"%ip)

except Exception:

print("192.168.1.%d server not open"%ip)

sk.close()

python实现批量执行CMD命令

import sys

import os

import paramiko

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

print("------------------------------\n")

print("使用说明,在当前目录创建ip.txt写入ip地址")

print("------------------------------\n")

user=input("输入用户名:")

passwd=input("输入密码:")

port=input("输入端口:")

cmd=input("输入执行的命令:")

file = open("./ip.txt", "r")

line = file.readlines()

for i in range(len(line)):

print("对IP: %s 执行"%line[i].strip('\n'))

python3-实现钉钉报警

import requests

import sys

import json

dingding_url = ' '

data = {"msgtype": "markdown","markdown": {"title": "监控","text": "apche异常"}}

headers = {'Content-Type':'application/json;charset=UTF-8'}

send_data = json.dumps(data).encode('utf-8')

requests.post(url=dingding_url,data=send_data,headers=headers)

import psutil

import requests

import time

import os

import json

monitor_name = set(['httpd','cobblerd']) # 用户指定监控的服务进程名称

proc_dict = {}

proc_name = set() # 系统检测的进程名称

monitor_map = {

'httpd': 'systemctl restart httpd',

'cobblerd': 'systemctl restart cobblerd' # 系统在进程down掉后,自动重启

}

dingding_url = ' '

while True:

for proc in psutil.process_iter(attrs=['pid','name']):

proc_dict[proc.info['pid']] = proc.info['name']

proc_name.add(proc.info['name'])

判断指定端口是否开放

import socket

port_number = [135,443,80]

for index in port_number:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

result = sock.connect_ex(('127.0.0.1', index))

if result == 0:

print("Port %d is open" % index)

else:

print("Port %d is not open" % index)

sock.close()

判断指定端口并且实现钉钉轮询报警

import requests

import sys

import json

import socket

import time

def dingding(title,text):

dingding_url = ' '

data = {"msgtype": "markdown","markdown": {"title": title,"text": text}}

headers = {'Content-Type':'application/json;charset=UTF-8'}

send_data = json.dumps(data).encode('utf-8')

requests.post(url=dingding_url,data=send_data,headers=headers)

def net_scan():

port_number = [80,135,443]

for index in port_number:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

result = sock.connect_ex(('127.0.0.1', index))

if result == 0:

print("Port %d is open" % index)

else:

return index

sock.close()

while True:

dingding("Warning",net_scan())

time.sleep(60)

python-实现SSH批量CMD执行命令

import sys

import os

import paramiko

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def ssh_cmd(user,passwd,port,userfile,cmd):

file = open(userfile, "r")

line = file.readlines()

for i in range(len(line)):

print("对IP: %s 执行"%line[i].strip('\n'))

ssh.connect(hostname=line[i].strip('\n'),port=port,username=user,password=passwd)

cmd=cmd

stdin, stdout, stderr = ssh.exec_command(cmd)

result = stdout.read()

ssh_cmd("lyshark","123","22","./ip.txt","free -h |grep 'Mem:' |awk '{print $3}'")

用python写一个列举当前目录以及所有子目录下的文件,并打印出绝对路径

import sys

import os

for root,dirs,files in os.walk("C://"):

for name in files:

print(os.path.join(root,name))

os.walk()

按照这样的日期格式(xxxx-xx-xx)每日生成一个文件,例如今天生成的文件为2013-09-23.log, 并且把磁盘的使用情况写到到这个文件中。

import os

import sys

import time

new_time = time.strftime("%Y-%m-%d")

disk_status = os.popen("df -h").readlines()

str1 = ''.join(disk_status)

f = open(new_time+'.log','w')

f.write("%s"%str1)

f.flush()

f.close()

统计出每个IP的访问量有多少?(从日志文件中查找)

import sys

list = []

f = open("/var/log/httpd/access_log","r")

str1 = f.readlines()

f.close()

for i in str1:

ip=i.split()[0]

list.append(ip)

list_num=set(list)

for j in list_num:

num=list.count(j)

print("%s ----- %s" %(num,j))

写个程序,接受用户输入数字,并进行校验,非数字给出错误提示,然后重新等待用户输入。

import tab

import sys

while True:

try:

num=int(input("输入数字:").strip())

for x in range(2,num+1):

for y in range(2,x):

if x % y == 0:

break

else:

print(x)

except ValueError:

print("您输入的不是数字")

except KeyboardInterrupt:

sys.exit("\n")

ps 可以查看进程的内存占用大小,写一个脚本计算一下所有进程所占用内存大小的和。

import sys

import os

list=[]

sum=0

str1=os.popen("ps aux","r").readlines()

for i in str1:

str2=i.split()

new_rss=str2[5]

list.append(new_rss)

for i in list[1:-1]:

num=int(i)

sum=sum+num

print("%s --- %s"%(list[0],sum))

关于Python 命令行参数argv

import sys

if len(sys.argv) 2:

print ("没有输入任何参数")

sys.exit()

if sys.argv[1].startswith("-"):

option = sys.argv[1][1:]

利用random生成6位数字加字母随机验证码

import sys

import random

rand=[]

for x in range(6):

y=random.randrange(0,5)

if y == 2 or y == 4:

num=random.randrange(0,9)

rand.append(str(num))

else:

temp=random.randrange(65,91)

c=chr(temp)

rand.append(c)

result="".join(rand)

print(result)

自动化-使用pexpect非交互登陆系统

import pexpect

import sys

ssh = pexpect.spawn('ssh lyshark@59.110.167.239')

fout = file('sshlog.txt', 'w')

ssh.logfile = fout

ssh.expect("lyshark@59.110.167.239's password:")

ssh.sendline("密码")

ssh.expect('#')

ssh.sendline('ls /home')

ssh.expect('#')

Python-取系统时间

import sys

import time

time_str = time.strftime("日期:%Y-%m-%d",time.localtime())

print(time_str)

time_str= time.strftime("时间:%H:%M",time.localtime())

print(time_str)

psutil-获取内存使用情况

import sys

import os

import psutil

memory_convent = 1024 * 1024

mem =psutil.virtual_memory()

print("内存容量为:"+str(mem.total/(memory_convent))+"MB\n")

print("已使用内存:"+str(mem.used/(memory_convent))+"MB\n")

print("可用内存:"+str(mem.total/(memory_convent)-mem.used/(1024*1024))+"MB\n")

print("buffer容量:"+str(mem.buffers/( memory_convent ))+"MB\n")

print("cache容量:"+str(mem.cached/(memory_convent))+"MB\n")

Python-通过SNMP协议监控CPU

注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*

import os

def getAllitems(host, oid):

sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid + '|grep Raw|grep Cpu|grep -v Kernel').read().split('\n')[:-1]

return sn1

def getDate(host):

items = getAllitems(host, '.1.3.6.1.4.1.2021.11')

if name == ' main ':

Python-通过SNMP协议监控系统负载

注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*

import os

import sys

def getAllitems(host, oid):

sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('\n')

return sn1

def getload(host,loid):

load_oids = '1.3.6.1.4.1.2021.10.1.3.' + str(loid)

return getAllitems(host,load_oids)[0].split(':')[3]

if name == ' main ':

Python-通过SNMP协议监控内存

注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*

import os

def getAllitems(host, oid):

def getSwapTotal(host):

def getSwapUsed(host):

def getMemTotal(host):

def getMemUsed(host):

if name == ' main ':

Python-通过SNMP协议监控磁盘

注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*

import re

import os

def getAllitems(host,oid):

def getDate(source,newitem):

def getRealDate(item1,item2,listname):

def caculateDiskUsedRate(host):

if name == ' main ':

Python-通过SNMP协议监控网卡流量

注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*

import re

import os

def getAllitems(host,oid):

sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('\n')[:-1]

return sn1

def getDevices(host):

device_mib = getAllitems(host,'RFC1213-MIB::ifDescr')

device_list = []

def getDate(host,oid):

date_mib = getAllitems(host,oid)[1:]

date = []

if name == ' main ':

Python-实现多级菜单

import os

import sys

ps="[None]-"

ip=["192.168.1.1","192.168.1.2","192.168.1.3"]

flage=1

while True:

ps="[None]-"

temp=input(ps)

if (temp=="test"):

print("test page !!!!")

elif(temp=="user"):

while (flage == 1):

ps="[User]-"

temp1=input(ps)

if(temp1 =="exit"):

flage=0

break

elif(temp1=="show"):

for i in range(len(ip)):

print(i)

Python实现一个没用的东西

import sys

ps="[root@localhost]# "

ip=["192.168.1.1","192.168.1.2","192.168.1.3"]

while True:

temp=input(ps)

temp1=temp.split()

检查各个进程读写的磁盘IO

import sys

import os

import time

import signal

import re

class DiskIO:

def init (self, pname=None, pid=None, reads=0, writes=0):

self.pname = pname

self.pid = pid

self.reads = 0

self.writes = 0

def main():

argc = len(sys.argv)

if argc != 1:

print ("usage: please run this script like [./lyshark.py]")

sys.exit(0)

if os.getuid() != 0:

print ("Error: This script must be run as root")

sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

os.system('echo 1 /proc/sys/vm/block_dump')

print ("TASK PID READ WRITE")

while True:

os.system('dmesg -c /tmp/diskio.log')

l = []

f = open('/tmp/diskio.log', 'r')

line = f.readline()

while line:

m = re.match(

'^(\S+)(\d+)(\d+): (READ|WRITE) block (\d+) on (\S+)', line)

if m != None:

if not l:

l.append(DiskIO(m.group(1), m.group(2)))

line = f.readline()

continue

found = False

for item in l:

if item.pid == m.group(2):

found = True

if m.group(3) == "READ":

item.reads = item.reads + 1

elif m.group(3) == "WRITE":

item.writes = item.writes + 1

if not found:

l.append(DiskIO(m.group(1), m.group(2)))

line = f.readline()

time.sleep(1)

for item in l:

print ("%-10s %10s %10d %10d" %

(item.pname, item.pid, item.reads, item.writes))

def signal_handler(signal, frame):

os.system('echo 0 /proc/sys/vm/block_dump')

sys.exit(0)

if name ==" main ":

main()

利用Pexpect实现自动非交互登陆linux

import pexpect

import sys

ssh = pexpect.spawn('ssh root@59.110.167.239')

fout = file('sshlog.log', 'w')

ssh.logfile = fout

ssh.expect("root@59.110.167.239's password:")

ssh.sendline("密码")

ssh.expect('#')

ssh.sendline('ls /home')

ssh.expect('#')

利用psutil模块获取系统的各种统计信息

import sys

import psutil

import time

import os

time_str = time.strftime( "%Y-%m-%d", time.localtime( ) )

file_name = "./" + time_str + ".log"

if os.path.exists ( file_name ) == False :

os.mknod( file_name )

handle = open ( file_name , "w" )

else :

handle = open ( file_name , "a" )

if len( sys.argv ) == 1 :

print_type = 1

else :

print_type = 2

def isset ( list_arr , name ) :

if name in list_arr :

return True

else :

return False

print_str = "";

if ( print_type == 1 ) or isset( sys.argv,"mem" ) :

memory_convent = 1024 * 1024

mem = psutil.virtual_memory()

print_str += " 内存状态如下:\n"

print_str = print_str + " 系统的内存容量为: "+str( mem.total/( memory_convent ) ) + " MB\n"

print_str = print_str + " 系统的内存以使用容量为: "+str( mem.used/( memory_convent ) ) + " MB\n"

print_str = print_str + " 系统可用的内存容量为: "+str( mem.total/( memory_convent ) - mem.used/( 1024*1024 )) + "MB\n"

print_str = print_str + " 内存的buffer容量为: "+str( mem.buffers/( memory_convent ) ) + " MB\n"

print_str = print_str + " 内存的cache容量为:" +str( mem.cached/( memory_convent ) ) + " MB\n"

if ( print_type == 1 ) or isset( sys.argv,"cpu" ) :

print_str += " CPU状态如下:\n"

cpu_status = psutil.cpu_times()

print_str = print_str + " user = " + str( cpu_status.user ) + "\n"

print_str = print_str + " nice = " + str( cpu_status.nice ) + "\n"

print_str = print_str + " system = " + str( cpu_status.system ) + "\n"

print_str = print_str + " idle = " + str ( cpu_status.idle ) + "\n"

print_str = print_str + " iowait = " + str ( cpu_status.iowait ) + "\n"

print_str = print_str + " irq = " + str( cpu_status.irq ) + "\n"

print_str = print_str + " softirq = " + str ( cpu_status.softirq ) + "\n"

print_str = print_str + " steal = " + str ( cpu_status.steal ) + "\n"

print_str = print_str + " guest = " + str ( cpu_status.guest ) + "\n"

if ( print_type == 1 ) or isset ( sys.argv,"disk" ) :

print_str += " 硬盘信息如下:\n"

disk_status = psutil.disk_partitions()

for item in disk_status :

print_str = print_str + " "+ str( item ) + "\n"

if ( print_type == 1 ) or isset ( sys.argv,"user" ) :

print_str += " 登录用户信息如下:\n "

user_status = psutil.users()

for item in user_status :

print_str = print_str + " "+ str( item ) + "\n"

print_str += "---------------------------------------------------------------\n"

print ( print_str )

handle.write( print_str )

handle.close()

import psutil

mem = psutil.virtual_memory()

print mem.total,mem.used,mem

print psutil.swap_memory() # 输出获取SWAP分区信息

cpu = psutil.cpu_stats()

printcpu.interrupts,cpu.ctx_switches

psutil.cpu_times(percpu=True) # 输出每个核心的详细CPU信息

psutil.cpu_times().user # 获取CPU的单项数据 [用户态CPU的数据]

psutil.cpu_count() # 获取CPU逻辑核心数,默认logical=True

psutil.cpu_count(logical=False) # 获取CPU物理核心数

psutil.disk_partitions() # 列出全部的分区信息

psutil.disk_usage('/') # 显示出指定的挂载点情况【字节为单位】

psutil.disk_io_counters() # 磁盘总的IO个数

psutil.disk_io_counters(perdisk=True) # 获取单个分区IO个数

psutil.net_io_counter() 获取网络总的IO,默认参数pernic=False

psutil.net_io_counter(pernic=Ture)获取网络各个网卡的IO

psutil.pids() # 列出所有进程的pid号

p = psutil.Process(2047)

p.name() 列出进程名称

p.exe() 列出进程bin路径

p.cwd() 列出进程工作目录的绝对路径

p.status()进程当前状态[sleep等状态]

p.create_time() 进程创建的时间 [时间戳格式]

p.uids()

p.gids()

p.cputimes() 【进程的CPU时间,包括用户态、内核态】

p.cpu_affinity() # 显示CPU亲缘关系

p.memory_percent() 进程内存利用率

p.meminfo() 进程的RSS、VMS信息

p.io_counters() 进程IO信息,包括读写IO数及字节数

p.connections() 返回打开进程socket的namedutples列表

p.num_threads() 进程打开的线程数

import psutil

from subprocess import PIPE

p =psutil.Popen(["/usr/bin/python" ,"-c","print 'helloworld'"],stdout=PIPE)

p.name()

p.username()

p.communicate()

p.cpu_times()

psutil.users() # 显示当前登录的用户,和Linux的who命令差不多

psutil.boot_time() 结果是个UNIX时间戳,下面我们来转换它为标准时间格式,如下:

datetime.datetime.fromtimestamp(psutil.boot_time()) # 得出的结果不是str格式,继续进行转换 datetime.datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d%H:%M:%S')

Python生成一个随机密码

import random, string

def GenPassword(length):

if name == ' main ':

print (GenPassword(6))

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