Created
April 24, 2012 03:58
-
-
Save xream/2476279 to your computer and use it in GitHub Desktop.
flora_pac.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# | |
# Refined by @phuslu | |
# Flora_Pac by @leaskh | |
# www.leaskh.com, [email protected] | |
# | |
# based on chnroutes project (by [email protected]) | |
# | |
import re | |
import struct | |
import optparse | |
import socket | |
import urllib2 | |
import logging | |
# logging format/datefmt config | |
logging.basicConfig(level=logging.INFO, | |
format='%(levelname)s - - %(asctime)s %(message)s', | |
datefmt='[%d/%b/%Y %H:%M:%S]') | |
def generate_pac(proxy): | |
url = r'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest' | |
opener = urllib2.build_opener() | |
logging.info('fetch ip from %r', url) | |
content = opener.open(url).read() | |
cndatas = re.findall(r'(?i)apnic\|cn\|ipv4\|([0-9\.]+)\|([0-9]+)\|[0-9]+\|a.*', content) | |
logging.info('download %s bytes %s items', len(content), len(cndatas)) | |
cndatas = [(ip, socket.inet_ntoa(struct.pack('!I', (int(n)-1)^0xffffffff))) for ip, n in cndatas] | |
cndataslist = [[] for i in xrange(256)] | |
for ip, mask in cndatas: | |
i = int(ip.partition('.')[0]) | |
cndataslist[i].append([ip, mask]) | |
PAC_TEMPLATE = ''' | |
//inspired from https://github.com/Leask/Flora_Pac | |
function FindProxyForURL(url, host) | |
{ | |
var lists = %s; | |
var ip = dnsResolve(host); | |
var index = parseInt(ip.split('.', 1)[0], 10); | |
var list = lists[index]; | |
for (var i in list) { | |
if (isInNet(ip, list[i][0], list[i][1])) { | |
return 'DIRECT'; | |
} | |
} | |
return '%s'; | |
}''' | |
return PAC_TEMPLATE % (repr(cndataslist), proxy) | |
def write_pac(proxy, filename): | |
pac_content = generate_pac(proxy) | |
with open(filename, 'wb') as fp: | |
fp.write(pac_content) | |
if __name__=='__main__': | |
parser = optparse.OptionParser(usage='usage: %prog -x <proxy>') | |
parser.add_option("-x", "--proxy", dest="proxy", default='PROXY 127.0.0.1:8087', help="Proxy Server") | |
parser.add_option("-f", "--filename", dest="filename", default='8087.pac', help="Proxy Pac Filename") | |
options, args = parser.parse_args() | |
write_pac(options.proxy, options.filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment