本文共 9513 字,大约阅读时间需要 31 分钟。
搜集自网络
import re, urllib2, sys, argparse, math, textwrap, subprocess, string, tempfile, socket, struct, threading, SocketServer, traceback, random, wmi,atexit 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( ) downscript_header=textwrap.dedent( ) 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( ) downscript_header=textwrap.dedent( ) 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] for ip,mask,_ in results: subprocess.call('route add %s mask %s %s metric %d\n'%(ip,mask,gw,metric), shell=True) global netCfgInstanceID, objNicConfig 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( ) downscript_header=textwrap.dedent( ) 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 转载于:https://blog.51cto.com/763996/1130711