ffmmx's Blog

Happy coding

[笔记] 一个生成基于gfwlist生成动态代理脚本的小程序pacmaker.py

ffmmx posted @ 2012年11月20日 11:09 in 未分类 , 6422 阅读

已经添加代理实现,现在直接运行就可以生成基于gfwlist的自动代理脚本了.先贴出代码

#!/usr/bin/env python
#Filename: pacmaker.py

'''
用于生成一个自动代理的脚本,使用autoproxy规则
'''

import os
from optparse import OptionParser
import urllib.request as req
import urllib.parse as urlparse
import base64


port = 80
protol = 'HTTP'
host = 'localhost'

avail_protol = ('HTTP','SOCKS4','SOCKS5',)
output = os.path.realpath('.') + os.path.sep + 'pacmaked.pac'
autoproxy_gfwlist = "http://autoproxy-gfwlist.googlecode.com/svn/trunk/gfwlist.txt"
online_proxy = (
        (
            'http://co.xinyali.info/includes/process.php?action=update',
            {
                'type':0,
                'u':autoproxy_gfwlist
            }
        ),
        )
gfwlist_file = None


def make_pac():
    
    gfwlist=None
    if gfwlist_file:
        with open(gfwlist_file,'r') as gfwfile:
            gfwlist = gfwfile.read()
            gfwlist = base64.b64decode(gfwlist).decode()
    else:
        import http.cookiejar
        
        cookie = http.cookiejar.CookieJar()
        opener = req.build_opener(req.HTTPCookieProcessor(cookie))
        data = urlparse.urlencode(online_proxy[0][1]).encode()
        res = opener.open(online_proxy[0][0],data)
        gfwlist = res.read()
        gfwlist = base64.b64decode(gfwlist).decode()

    #print(gfwlist)
    pac_content = '''
    function regExpMatch(url, pattern) {
	    try { return new RegExp(pattern).test(url); } catch(ex) { return false; }
    }

    function FindProxyForURL(url, host) {
        %s
        return "DIRECT";
    }
    '''
    pac_part = []

    
    for line in (i for i in gfwlist.split('\n') if i.find("!") != 0 
            and i.find('[') != 0 and len(i)>=3):
        return_str = 'return "{protol} {host}:{port}; DIRECT"; \n'.format(
                protol=protol,
                host=host,
                port=port
                )
        #print(line)
        if line.find('@@') == 0:
            return_str = 'return "DIRECT"; \n'
            line = line[2:]
        if line.find('||') == 0:
            line = line[2:]
            match_str = line.replace('.',r'\\.')
            match_str = match_str.replace('/',r'\\/')

            if_str = r'     if(regExpMatch(url,"^[\\w\\-]+:\\/+(?!\\/)(?:[^\\/]+\\.)?{match}"))'.format(match=match_str)
        else:
            if_str = r'     if(shExpMatch(url, "http://*' + line + '*"))'

        pac_part.append(if_str+' '+return_str)

    #print(''.join(pac_part))
    #print(pac_content % (''.join(pac_part)))
    pac_content = pac_content % (''.join(pac_part))
    with open(output,'w') as outfile:
        outfile.write(pac_content)

if __name__ == '__main__':
    usage = 'usage: %prog [option]'
    parser = OptionParser(usage=usage)
    
    parser.add_option('-o','--output',help='output file',dest='output',default=output)
    parser.add_option('-H','--host',help='hostname or ip of proxy',dest='host',default=host)
    parser.add_option('-p','--port',help='port of proxy',dest='port',default=port)
    parser.add_option('-t','--type',help='type of proxy',dest='protol',default=protol)
    parser.add_option('-i','--input',help="autoproxy input file",dest='input')
    (options,args) = parser.parse_args()
    
    print(options)
    
    if options.protol.upper() not in avail_protol:
        raise Exception('it\'s not support proxy protol.')
    
    protol = options.protol.upper()
    port = options.port
    host = options.host
    output = options.output
    gfwlist_file = options.input

    make_pac()


Avatar_small
Max Erlikilyika 说:
2018年7月15日 15:45

The device for the controlling of the heart beating is that how to work of the heart and the performances of the heart also. On the monitoring of the heart by the assignment writers uk in the hospitals are controlled by the pacemakers units.

Avatar_small
cleaning services du 说:
2021年9月15日 13:32

Whether that you are running a enterprise or maybe managing a office, you have time in a lot of these workplaces. And soon after spending a total day working in the office, it is reasonably manageable to take into consideration cleaning in the office living space. But, absolutely nothing is to stress about, because there are various options available to pick up your work environment. The productive professionals your service are simply just one press ways. Simply by taking fewer time in addition to money, the technical and encountered professionals will work the full cleaning aspect.

Avatar_small
Willy 说:
2024年1月15日 20:32

Starting a programming career is an exciting and difficult endeavor. Learn the basics first, such as problem-solving techniques and coding languages, in order to successfully navigate this path. The first steps are to stay curious, look for mentorship, and work on real -world projects. Remain persistent and view obstacles as chances for personal development. You'll discover that the path becomes clearer and the opportunities are endless as you go deeper into the world of programming. For those looking to delve deeper into complex ideas on this fascinating adventure [url=https://dissertationwritinghelp.uk/phd-dissertation-proposal-help/]Phd Dissertation Proposal Help Uk[/url] is an invaluable resource.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter