搜集自网络
code.google、github开源项目
#!/usr/bin/env python
import re, urllib2, sys, argparse, math, textwrap, subprocess, string, tempfile, socket, struct, threading, SocketServer, traceback, random, wmi,atexit
#sys.setdefaultencoding('utf8')
DHOSTS = ['156.154.70.1',
'8.8.8.8',
'8.8.4.4',
'156.154.71.1',
]
DPORT = 53
TIMEOUT = 20
def exit_():
if sys.platform == 'win32':
try:
wmi.WMI().Win32_NetworkAdapterConfiguration(ServiceName=netCfgInstanceID)[0].SetDNSServerSearchOrder()
try:
if wmi.WMI().Win32_NetworkAdapterConfiguration(ServiceName=netCfgInstanceID)[0].DNSServerSearchOrder != objNicConfig:
wmi.WMI().Win32_NetworkAdapterConfiguration(ServiceName=netCfgInstanceID)[0].SetDNSServerSearchOrder(DNSServerSearchOrder = objNicConfig)
except:
exit(1)
except:
exit(1)
atexit.register(exit_)
def hexdump( src, width=16 ):
FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)])
result=[]
for i in xrange(0, len(src), width):
s = src[i:i+width]
hexa = ' '.join(["%02X"%ord(x) for x in s])
printable = s.translate(FILTER)
result.append("%04X %s %s\n" % (i, hexa, printable))
return ''.join(result)
def bytetodomain(s):
domain = ''
i = 0
length = struct.unpack('!B', s[0:1])[0]
while length != 0 :
i += 1
domain += s[i:i+length]
i += length
length = struct.unpack('!B', s[i:i+1])[0]
if length != 0 :
domain += '.'
return domain
def QueryDNS(server, port, querydata):
Buflen = struct.pack('!h', len(querydata))
sendbuf = Buflen + querydata
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TIMEOUT)
s.connect((server, int(port)))
s.send(sendbuf)
data = s.recv(2048)
except:
print traceback.print_exc(sys.stdout)
if s: s.close()
return
if s: s.close()
return data
def transfer(querydata, addr, server):
if not querydata: return
domain = bytetodomain(querydata[12:-4])
qtype = struct.unpack('!h', querydata[-4:-2])[0]
print 'domain:%s, qtype:%x, thread:%d' % \
(domain, qtype, threading.activeCount())
sys.stdout.flush()
choose = random.sample(xrange(len(DHOSTS)), 1)[0]
DHOST = DHOSTS[choose]
response = QueryDNS(DHOST, DPORT, querydata)
if response:
server.sendto(response[2:], addr)
return
class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
def __init__(self, s, t):
SocketServer.UDPServer.__init__(self, s, t)
class ThreadedUDPRequestHandler(SocketServer.BaseRequestHandler):
daemon_threads = True
allow_reuse_address = True
def handle(self):
data = self.request[0]
socket = self.request[1]
addr = self.client_address
transfer(data, addr, socket)
def generate_o***(metric):
results = fetch_ip_data()
rfile=open('routes.txt','w')
for ip,mask,_ in results:
route_item="route %s %s net_gateway %d\n"%(ip,mask,metric)
rfile.write(route_item)
rfile.close()
print "Usage: Append the content of the newly created routes.txt to your open*** config file," \
" and also add 'max-routes %d', which takes a line, to the head of the file." % (len(results)+20)
def generate_linux(metric):
results = fetch_ip_data()
upscript_header=textwrap.dedent("""\
#!/bin/bash
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"
OLDGW=`ip route show | grep '^default' | sed -e 's/default via \\([^ ]*\\).*/\\1/'`
if [ $OLDGW == '' ]; then
exit 0
fi
if [ ! -e /tmp/***_oldgw ]; then
echo $OLDGW > /tmp/***_oldgw
fi
""")
downscript_header=textwrap.dedent("""\
#!/bin/bash
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"
OLDGW=`cat /tmp/***_oldgw`
""")
upfile=open('ip-pre-up','w')
downfile=open('ip-down','w')
upfile.write(upscript_header)
upfile.write('\n')
downfile.write(downscript_header)
downfile.write('\n')
for ip,mask,_ in results:
upfile.write('route add -net %s netmask %s gw $OLDGW\n'%(ip,mask))
downfile.write('route del -net %s netmask %s\n'%(ip,mask))
downfile.write('rm /tmp/***_oldgw\n')
print "For pptp only, please copy the file ip-pre-up to the folder/etc/ppp," \
"and copy the file ip-down to the folder /etc/ppp/ip-down.d."
def generate_mac(metric):
results=fetch_ip_data()
upscript_header=textwrap.dedent("""\
#!/bin/sh
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"
OLDGW=`netstat -nr | grep '^default' | grep -v 'ppp' | sed 's/default *\\([0-9\.]*\\) .*/\\1/'`
if [ ! -e /tmp/pptp_oldgw ]; then
echo "${OLDGW}" > /tmp/pptp_oldgw
fi
dscacheutil -flushcache
""")
downscript_header=textwrap.dedent("""\
#!/bin/sh
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"
if [ ! -e /tmp/pptp_oldgw ]; then
exit 0
fi
ODLGW=`cat /tmp/pptp_oldgw`
""")
upfile=open('ip-up','w')
downfile=open('ip-down','w')
upfile.write(upscript_header)
upfile.write('\n')
downfile.write(downscript_header)
downfile.write('\n')
for ip,_,mask in results:
upfile.write('route add %s/%s "${OLDGW}"\n'%(ip,mask))
downfile.write('route delete %s/%s ${OLDGW}\n'%(ip,mask))
downfile.write('\n\nrm /tmp/pptp_oldgw\n')
upfile.close()
downfile.close()
print "For pptp on mac only, please copy ip-up and ip-down to the /etc/ppp folder," \
"don't forget to make them executable with the chmod command."
def generate_win(metric):
results = fetch_ip_data()
subprocess.Popen("ipconfig /flushdns", shell=True)
gw=[elem.strip().split() for elem in subprocess.Popen("route print", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].split("Metric\r\n")[1].split("\n") if re.match("^[0-9]", elem.strip())][0][2]
#upscript_header=textwrap.dedent("""@echo off
#for /F "tokens=3" %%* in ('route print ^| findstr "\<0.0.0.0\>"') do set "gw=%%*"
#""")
#apth = tempfile.mkdtemp()
#upfile=open(r'%s\***up.bat' %(apth),'w')
#downfile=open(r'%s\***down.bat' %(apth),'w')
#upfile.write(upscript_header)
#upfile.write('\n')
#upfile.write('ipconfig /flushdns\n\n')
#downfile.write("@echo off")
#downfile.write('\n')
for ip,mask,_ in results:
#upfile.write('route add %s mask %s %s metric %d\n'%(ip,mask,gw,metric))
#downfile.write('route delete %s\n'%(ip))
subprocess.call('route add %s mask %s %s metric %d\n'%(ip,mask,gw,metric), shell=True)
#upfile.close()
#downfile.close()
global netCfgInstanceID, objNicConfig
#up_vbs_wrapper=open(r'%s\***up.vbs' %(apth),'w')
#up_vbs_wrapper.write('Set objShell = CreateObject("Wscript.shell")\ncall objShell.Run("***up.bat",0,FALSE)')
#up_vbs_wrapper.close()
#down_vbs_wrapper=open(r'%s\***down.vbs' %(apth),'w')
#down_vbs_wrapper.write('Set objShell = CreateObject("Wscript.shell")\ncall objShell.Run("***down.bat",0,FALSE)')
#down_vbs_wrapper.close()
print "\r\nfor windows only, run before dialing to ***"
for interface in wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=1):
if interface.DefaultIPGateway != None:
netCfgInstanceID = interface.ServiceName
objNicConfig = interface.DNSServerSearchOrder
interface.SetDNSServerSearchOrder(DNSServerSearchOrder = ['127.0.0.1'])
print '\r\nNow changed dns 127.0.0.1\r\n'
server = ThreadedUDPServer(('127.0.0.1', 53), ThreadedUDPRequestHandler)
server.serve_forever()
server.shutdown()
def generate_android(metric):
results = fetch_ip_data()
upscript_header=textwrap.dedent("""\
#!/bin/sh
alias nestat='/system/xbin/busybox netstat'
alias grep='/system/xbin/busybox grep'
alias awk='/system/xbin/busybox awk'
alias route='/system/xbin/busybox route'
OLDGW=`netstat -rn | grep ^0\.0\.0\.0 | awk '{print $2}'`
""")
downscript_header=textwrap.dedent("""\
#!/bin/sh
alias route='/system/xbin/busybox route'
""")
upfile=open('***up.sh','w')
downfile=open('***down.sh','w')
upfile.write(upscript_header)
upfile.write('\n')
downfile.write(downscript_header)
downfile.write('\n')
for ip,mask,_ in results:
upfile.write('route add -net %s netmask %s gw $OLDGW\n'%(ip,mask))
downfile.write('route del -net %s netmask %s\n'%(ip,mask))
upfile.close()
downfile.close()
print "Old school way to call up/down script from open*** client. " \
"use the regular open*** 2.1 method to add routes if it's possible"
def fetch_ip_data():
print "Fetching data from apnic.net, it might take a few minutes, please wait..."
url=r'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest'
data=urllib2.urlopen(url).read()
cnregex=re.compile(r'apnic\|cn\|ipv4\|[0-9\.]+\|[0-9]+\|[0-9]+\|a.*',re.IGNORECASE)
cndata=cnregex.findall(data)
results=[]
for item in cndata:
unit_items=item.split('|')
starting_ip=unit_items[3]
num_ip=int(unit_items[4])
imask=0xffffffff^(num_ip-1)
imask=hex(imask)[2:]
mask=[0]*4
mask[0]=imask[0:2]
mask[1]=imask[2:4]
mask[2]=imask[4:6]
mask[3]=imask[6:8]
mask=[ int(i,16 ) for i in mask]
mask="%d.%d.%d.%d"%tuple(mask)
mask2=32-int(math.log(num_ip,2))
results.append((starting_ip,mask,mask2))
return results
if __name__=='__main__':
parser=argparse.ArgumentParser(description="Generate routing rules for ***.")
parser.add_argument('-p','--platform',
dest='platform',
default='win',
nargs='?',
help="Target platforms, it can be open***, mac, linux,"
"win, android. open*** by default.")
parser.add_argument('-m','--metric',
dest='metric',
default=5,
nargs='?',
type=int,
help="Metric setting for the route rules")
args = parser.parse_args()
if args.platform.lower() == 'open***':
generate_o***(args.metric)
elif args.platform.lower() == 'linux':
generate_linux(args.metric)
elif args.platform.lower() == 'mac':
generate_mac(args.metric)
elif args.platform.lower() == 'win':
generate_win(args.metric)
elif args.platform.lower() == 'android':
generate_android(args.metric)
else:
print>>sys.stderr, "Platform %s is not supported."%args.platform
exit(1)
参考
D ,jython
www.cnblogs.com/vamei/archive/2012/09/23/2698014.html
bbs.chinaunix.net/forum.php?mod=viewthread&tid=1620204&ordertype=1
www.pythonclub.org/python-network-application/get-ip-address
blog.sina.com.cn/s/blog_64d75a250100i9tv.html