コード例 #1
0
ファイル: pages.py プロジェクト: jasonrbriggs/sitebaker
def load_pages(directory, output_path, kernel):
    """
    Find all .text files in the specified directory and return a map of Page objects, keyed by the
    url for the page.

    \param directory
        starting directory to search
    \param output_path
        the directory we'll be writing output to
    \param configs
        the config map which we'll use to get the template for each page
    \param templates
        the Templates singleton
    """
    page_map = {}
    length = len(directory)
    for root, name in utils.find_files(directory, False, '.text'):
        path = os.path.join(root, name)
        base_path = root[length:]
        if not base_path.startswith('/'):
            base_path = '/' + base_path
        name = name[0:-5]

        url = utils.url_join(base_path, name)
        config = utils.find_config(kernel.configs, base_path)
        page = Page(kernel, path, output_path, url, config)
        page_map[url] = page

    return page_map
コード例 #2
0
ファイル: baker.py プロジェクト: jasonrbriggs/sitebaker
    def __init__(self, options):
        self.options = options
        self.version = __init__.__version__
        plugin_folders = [os.path.join(sys.path[0], 'plugins')]

        if os.path.exists('site.ini'):
            template.base_dir = os.path.join(options.dir, 'theme')
            self.verbose_log('Loading configuration files')
            self.configs = utils.load_configs(options.dir)
            config = utils.find_config(self.configs, '/')
            if config is not None:
                plugin_path = config.get('control', 'plugins_path')
                if plugin_path is not None:
                    plugin_folders.append(os.path.join(os.getcwd(), plugin_path))

        self.verbose_log('Initialising plugin manager')
        self.pm = PluginManager(plugin_folders)
        self.verbose_log('    - complete')

        if os.path.exists('site.ini'):
            self.verbose_log('Loading pages')
            self.pages = load_pages(options.dir, options.output, self)
            self.verbose_log('    - complete')
        self.commands = {}
        self.verbose_log('Running commands filter')
        apply_filter('commands', self.commands)
コード例 #3
0
ファイル: server.py プロジェクト: KK233/shadowsocks
def main():
    global SERVER, PORT, KEY, METHOD, IPv6
 
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')
   
    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    KEY = None
    METHOD = None
    IPv6 = False
 
    config_path = utils.find_config()
    optlist, args = getopt.getopt(sys.argv[1:], 'p:k:m:c:6')
    for key, value in optlist:
        if key == '-c':
            config_path = value

    if config_path:
        with open(config_path, 'rb') as f:
            config = json.load(f)
        logging.info('loading config from %s' % config_path)
        SERVER = config['server']
        PORT = config['server_port']
        KEY = config['password']
        METHOD = config.get('method', None)

    optlist, args = getopt.getopt(sys.argv[1:], 'p:k:m:c:6')
    for key, value in optlist:
        if key == '-p':
            PORT = int(value)
        elif key == '-k':
            KEY = value
        elif key == '-m':
            METHOD = value
        elif key == '-6':
            IPv6 = True
            
    if not KEY and not config_path:
        sys.exit('config not specified, please read https://github.com/clowwindy/shadowsocks')

    encrypt.init_table(KEY, METHOD)
    if IPv6:
        ThreadingTCPServer.address_family = socket.AF_INET6
    try:
        server = ThreadingTCPServer(('', PORT), Socks5Server)
        logging.info("starting server at port %d ..." % PORT)
        server.serve_forever()
    except socket.error, e:
        logging.error(e)
コード例 #4
0
def parse_options():
    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    KEY = None
    METHOD = None
    IPv6 = False

    config_path = utils.find_config()
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:6')
        for key, value in optlist:
            if key == '-c':
                config_path = value

        if config_path:
            logging.info('loading config from %s' % config_path)
            try:
                f = open(config_path, 'rb')
                config = json.load(f)
            except ValueError as e:
                logging.error('found an error in config.json: %s', e.message)
                sys.exit(1)
        else:
            config = {}

        optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:6')
        for key, value in optlist:
            if key == '-p':
                config['server_port'] = int(value)
            elif key == '-k':
                config['password'] = value
            elif key == '-s':
                config['server'] = value
            elif key == '-m':
                config['method'] = value
            elif key == '-6':
                IPv6 = True
    except getopt.GetoptError:
        utils.print_server_help()
        sys.exit(2)

    return config
コード例 #5
0
ファイル: blog_plugin.py プロジェクト: jasonrbriggs/sitebaker
def blog_command(kernel, *args):
    """
    Create the directory, and an empty .text file, for today's blog entry.
    """
    config = utils.find_config(kernel.configs, '/')
    paths = config.get('blog', 'paths').split(',')
    path = paths[0]
    newpath = utils.url_join(kernel.options.output, path, time.strftime('%Y/%m/%d'))
    if not os.path.exists(newpath):
        os.makedirs(newpath)
        print('Created new blog dir %s' % newpath)

    if args and len(*args) > 0:
        title = ' '.join(*args)
    else:
        title = 'Temporary post'

    filename = os.path.join(newpath, title.lower().replace(' ', '-') + '.text')

    if not os.path.exists(filename):
        posted_on = time.strftime('%d %b, %Y')
        content = '''title: %(title)s
posted-on: %(posted-on)s
tags:

%(title)s
%(dashes)s

''' % {
            'title': title,
            'posted-on': posted_on,
            'dashes': ('-' * len(title))
        }

        with open(filename, 'w') as blog_file:
            blog_file.write(content)
コード例 #6
0
def main():
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        filemode='a+')

    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    KEY = None
    METHOD = None
    IPv6 = False

    config_path = utils.find_config()
    optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:6')
    for key, value in optlist:
        if key == '-c':
            config_path = value

    if config_path:
        logging.info('loading config from %s' % config_path)
        with open(config_path, 'rb') as f:
            try:
                config = json.load(f)
            except ValueError as e:
                logging.error('found an error in config.json: %s', e.message)
                sys.exit(1)
        logging.info('loading config from %s' % config_path)
    else:
        config = {}

    optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:6')
    for key, value in optlist:
        if key == '-p':
            config['server_port'] = int(value)
        elif key == '-k':
            config['password'] = value
        elif key == '-s':
            config['server'] = value
        elif key == '-m':
            config['method'] = value
        elif key == '-6':
            IPv6 = True

    SERVER = config['server']
    PORT = config['server_port']
    KEY = config['password']
    METHOD = config.get('method', None)
    PORTPASSWORD = config.get('port_password', None)
    TIMEOUT = config.get('timeout', 600)

    if not KEY and not config_path:
        sys.exit(
            'config not specified, please read https://github.com/clowwindy/shadowsocks'
        )

    utils.check_config(config)

    if PORTPASSWORD:
        if PORT or KEY:
            logging.warn(
                'warning: port_password should not be used with server_port and password. server_port and password will be ignored'
            )
    else:
        PORTPASSWORD = {}
        PORTPASSWORD[str(PORT)] = KEY

    encrypt.init_table(KEY, METHOD)
    if IPv6:
        ThreadingTCPServer.address_family = socket.AF_INET6
    for port, key in PORTPASSWORD.items():
        server = ThreadingTCPServer((SERVER, int(port)), Socks5Server)
        server.key, server.method, server.timeout = key, METHOD, int(TIMEOUT)
        logging.info("starting server at %s:%d" %
                     tuple(server.server_address[:2]))
        threading.Thread(target=server.serve_forever).start()
コード例 #7
0
ファイル: local.py プロジェクト: ohyeah521/shadowsocks_plus-1
def main():
    global SERVER, REMOTE_PORT, PORT, KEY, METHOD, LOCAL, IPv6

    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        filemode='a+')

    # fix py2exe
    if hasattr(sys, "frozen") and sys.frozen in \
            ("windows_exe", "console_exe"):
        p = os.path.dirname(os.path.abspath(sys.executable))
        os.chdir(p)
    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    KEY = None
    METHOD = None
    LOCAL = ''
    IPv6 = False

    config_path = utils.find_config()
    optlist, args = getopt.getopt(sys.argv[1:], 's:b:p:k:l:m:c:6')
    for key, value in optlist:
        if key == '-c':
            config_path = value

    if config_path:
        logging.info('loading config from %s' % config_path)
        with open(config_path, 'rb') as f:
            config = json.load(f)
    else:
        config = {}

    optlist, args = getopt.getopt(sys.argv[1:], 's:b:p:k:l:m:c:6')
    for key, value in optlist:
        if key == '-p':
            config['server_port'] = int(value)
        elif key == '-k':
            config['password'] = value
        elif key == '-l':
            config['local_port'] = int(value)
        elif key == '-s':
            config['server'] = value
        elif key == '-m':
            config['method'] = value
        elif key == '-b':
            config['local'] = value
        elif key == '-6':
            IPv6 = True

    SERVER = config['server']
    REMOTE_PORT = config['server_port']
    PORT = config['local_port']
    KEY = config['password']
    METHOD = config.get('method', None)
    LOCAL = config.get('local', '')

    if not KEY and not config_path:
        sys.exit(
            'config not specified, please read https://github.com/clowwindy/shadowsocks'
        )

    utils.check_config(config)

    encrypt.init_table(KEY, METHOD)

    try:
        if IPv6:
            ThreadingTCPServer.address_family = socket.AF_INET6
        server = ThreadingTCPServer((LOCAL, PORT), Socks5Server)
        logging.info("starting local at %s:%d" %
                     tuple(server.server_address[:2]))
        server.serve_forever()
    except socket.error, e:
        logging.error(e)
コード例 #8
0
def main():
    global config_server, config_server_port, config_password, config_method,\
        config_fast_open, config_timeout

    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        filemode='a+')

    # fix py2exe
    if hasattr(sys, "frozen") and sys.frozen in \
            ("windows_exe", "console_exe"):
        p = os.path.dirname(os.path.abspath(sys.executable))
        os.chdir(p)
    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    config_password = None
    config_method = None

    config_path = utils.find_config()
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 's:b:p:k:l:m:c:t:',
                                      ['fast-open'])
        for key, value in optlist:
            if key == '-c':
                config_path = value

        if config_path:
            logging.info('loading config from %s' % config_path)
            with open(config_path, 'rb') as f:
                try:
                    config = json.load(f)
                except ValueError as e:
                    logging.error('found an error in config.json: %s',
                                  e.message)
                    sys.exit(1)
        else:
            config = {}

        optlist, args = getopt.getopt(sys.argv[1:], 's:b:p:k:l:m:c:t:',
                                      ['fast-open'])
        for key, value in optlist:
            if key == '-p':
                config['server_port'] = int(value)
            elif key == '-k':
                config['password'] = value
            elif key == '-l':
                config['local_port'] = int(value)
            elif key == '-s':
                config['server'] = value
            elif key == '-m':
                config['method'] = value
            elif key == '-b':
                config['local_address'] = value
            elif key == '--fast-open':
                config['fast_open'] = True
    except getopt.GetoptError as e:
        logging.error(e)
        utils.print_local_help()
        sys.exit(2)

    config_server = config['server']
    config_server_port = config['server_port']
    config_local_port = config['local_port']
    config_password = config['password']
    config_method = config.get('method', None)
    config_local_address = config.get('local_address', '127.0.0.1')
    config_timeout = int(config.get('timeout', 300))
    config_fast_open = config.get('fast_open', False)

    if not config_password and not config_path:
        sys.exit('config not specified, please read '
                 'https://github.com/clowwindy/shadowsocks')

    utils.check_config(config)

    encrypt.init_table(config_password, config_method)

    addrs = socket.getaddrinfo(config_local_address, config_local_port)
    if not addrs:
        logging.error('cant resolve listen address')
        sys.exit(1)
    ThreadingTCPServer.address_family = addrs[0][0]
    try:
        udprelay.UDPRelay(config_local_address, int(config_local_port),
                          config_server, config_server_port, config_password,
                          config_method, int(config_timeout), True).start()
        server = ThreadingTCPServer((config_local_address, config_local_port),
                                    Socks5Server)
        server.timeout = int(config_timeout)
        logging.info("starting local at %s:%d" %
                     tuple(server.server_address[:2]))
        server.serve_forever()
    except socket.error, e:
        logging.error(e)
コード例 #9
0
ファイル: local.py プロジェクト: MOODOO-SH/shadowsocks
def main():
    global config_server, config_server_port, config_password, config_method,\
        config_fast_open

    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')

    # fix py2exe
    if hasattr(sys, "frozen") and sys.frozen in \
            ("windows_exe", "console_exe"):
        p = os.path.dirname(os.path.abspath(sys.executable))
        os.chdir(p)
    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    config_password = None
    config_method = None

    config_path = utils.find_config()
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 's:b:p:k:l:m:c:',
                                      ['fast-open'])
        for key, value in optlist:
            if key == '-c':
                config_path = value

        if config_path:
            logging.info('loading config from %s' % config_path)
            with open(config_path, 'rb') as f:
                try:
                    config = json.load(f)
                except ValueError as e:
                    logging.error('found an error in config.json: %s',
                                  e.message)
                    sys.exit(1)
        else:
            config = {}

        optlist, args = getopt.getopt(sys.argv[1:], 's:b:p:k:l:m:c:',
                                      ['fast-open'])
        for key, value in optlist:
            if key == '-p':
                config['server_port'] = int(value)
            elif key == '-k':
                config['password'] = value
            elif key == '-l':
                config['local_port'] = int(value)
            elif key == '-s':
                config['server'] = value
            elif key == '-m':
                config['method'] = value
            elif key == '-b':
                config['local_address'] = value
            elif key == '--fast-open':
                config['fast_open'] = True
    except getopt.GetoptError as e:
        logging.error(e)
        utils.print_local_help()
        sys.exit(2)

    config_server = config['server']
    config_server_port = config['server_port']
    config_local_port = config['local_port']
    config_password = config['password']
    config_method = config.get('method', None)
    config_local_address = config.get('local_address', '127.0.0.1')
    config_timeout = config.get('timeout', 600)
    config_fast_open = config.get('fast_open', False)

    if not config_password and not config_path:
        sys.exit('config not specified, please read '
                 'https://github.com/clowwindy/shadowsocks')

    utils.check_config(config)

    encrypt.init_table(config_password, config_method)

    addrs = socket.getaddrinfo(config_local_address, config_local_port)
    if not addrs:
        logging.error('cant resolve listen address')
        sys.exit(1)
    ThreadingTCPServer.address_family = addrs[0][0]
    try:
        udprelay.UDPRelay(config_local_address, int(config_local_port),
                          config_server, config_server_port, config_password,
                          config_method, int(config_timeout), True).start()
        server = ThreadingTCPServer((config_local_address, config_local_port),
                                    Socks5Server)
        logging.info("starting local at %s:%d" %
                     tuple(server.server_address[:2]))
        server.serve_forever()
    except socket.error, e:
        logging.error(e)
コード例 #10
0
ファイル: server.py プロジェクト: MOODOO-SH/shadowsocks
def main():
    global config_server, config_server_port, config_method, config_fast_open

    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')


    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    config_path = utils.find_config()
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:',
                                      ['fast-open'])
        for key, value in optlist:
            if key == '-c':
                config_path = value

        if config_path:
            logging.info('loading config from %s' % config_path)
            with open(config_path, 'rb') as f:
                try:
                    config = json.load(f)
                except ValueError as e:
                    logging.error('found an error in config.json: %s',
                                  e.message)
                    sys.exit(1)
        else:
            config = {}

        optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:',
                                      ['fast-open'])
        for key, value in optlist:
            if key == '-p':
                config['server_port'] = int(value)
            elif key == '-k':
                config['password'] = value
            elif key == '-s':
                config['server'] = value
            elif key == '-m':
                config['method'] = value
            elif key == '--fast-open':
                config['fast_open'] = True
    except getopt.GetoptError:
        utils.print_server_help()
        sys.exit(2)

    config_server = config['server']
    config_server_port = config['server_port']
    config_key = config['password']
    config_method = config.get('method', None)
    config_port_password = config.get('port_password', None)
    config_timeout = config.get('timeout', 600)
    config_fast_open = config.get('fast_open', False)

    if not config_key and not config_path:
        sys.exit('config not specified, please read '
                 'https://github.com/clowwindy/shadowsocks')

    utils.check_config(config)

    if config_port_password:
        if config_server_port or config_key:
            logging.warn('warning: port_password should not be used with '
                         'server_port and password. server_port and password '
                         'will be ignored')
    else:
        config_port_password = {}
        config_port_password[str(config_server_port)] = config_key

    encrypt.init_table(config_key, config_method)
    addrs = socket.getaddrinfo(config_server, int(8387))
    if not addrs:
        logging.error('cant resolve listen address')
        sys.exit(1)
    ThreadingTCPServer.address_family = addrs[0][0]
    for port, key in config_port_password.items():
        server = ThreadingTCPServer((config_server, int(port)), Socks5Server)
        server.key, server.method, server.timeout = key, config_method,\
            int(config_timeout)
        logging.info("starting server at %s:%d" %
                     tuple(server.server_address[:2]))
        threading.Thread(target=server.serve_forever).start()
        udprelay.UDPRelay(config_server, int(port), None, None, key,
                          config_method, int(config_timeout), False).start()
コード例 #11
0
def main():
    print('欢迎使用Time-Machine Shadowsocks多链接客户端')
    global SERVER, REMOTE_PORT, PORT, KEY, METHOD, LOCAL, IPv6

    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        filemode='a+')

    # py2exe 修复
    if hasattr(sys, "frozen") and sys.frozen in \
            ("windows_exe", "console_exe"):
        p = os.path.dirname(os.path.abspath(sys.executable))
        os.chdir(p)
    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    KEY = None
    METHOD = None
    LOCAL = ''
    IPv6 = False

    config_path = utils.find_config()
    optlist, args = getopt.getopt(sys.argv[1:], 's:b:p:k:l:m:c:6')
    for key, value in optlist:
        if key == '-c':
            config_path = value

    if config_path:
        logging.info('Loading Config From %s' % config_path)
        with open(config_path, 'rb') as f:
            config = json.load(f)

            #判断config.json中是否包含了"server_password"来确定是否启用了多端口
            if config.has_key("server_password") == True:
                #获得"server_password"的长度,得到服务器端口记录
                number = len(config["server_password"])
                #通过random来随机分配用哪一条服务器端口密码记录
                orientation = random.randint(0, number - 1)
                server_dict = {}
                server_dict[u"server"] = config["server_password"][
                    orientation][0]
                server_dict[u"server_port"] = config["server_password"][
                    orientation][1]
                server_dict[u"password"] = config["server_password"][
                    orientation][2]
                server_dict[u"local_port"] = config["local_port"]
                server_dict[u"method"] = config["method"]
                server_dict[u"timeout"] = config["timeout"]
                config = server_dict
                #print config

            #else:
            #    print config

    optlist, args = getopt.getopt(sys.argv[1:], 's:b:p:k:l:m:c:6')
    for key, value in optlist:
        if key == '-p':
            config['server_port'] = int(value)
        elif key == '-k':
            config['password'] = value
        elif key == '-l':
            config['local_port'] = int(value)
        elif key == '-s':
            config['server'] = value
        elif key == '-m':
            config['method'] = value
        elif key == '-b':
            config['local'] = value
        elif key == '-6':
            IPv6 = True

    SERVER = config['server']
    REMOTE_PORT = config['server_port']
    PORT = config['local_port']
    KEY = config['password']
    METHOD = config.get('method', None)
    LOCAL = config.get('local', '')

    if not KEY and not config_path:
        sys.exit('定义失败')

    utils.check_config(config)

    encrypt.init_table(KEY, METHOD)

    try:
        if IPv6:
            ThreadingTCPServer.address_family = socket.AF_INET6
        server = ThreadingTCPServer((LOCAL, PORT), Socks5Server)
        logging.info("存在的远端服务器 %s:%d" % (SERVER, REMOTE_PORT))
        logging.info("套接字启动链接 %s:%d" % tuple(server.server_address[:2]))
        server.serve_forever()
    except socket.error, e:
        logging.error(e)
コード例 #12
0
ファイル: server.py プロジェクト: venkatarajasekhar/code
def main():
    global SERVER, PORT, KEY, METHOD, IPv6
 
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')
   
    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    KEY = None
    METHOD = None
    IPv6 = False
 
    config_path = utils.find_config()
    optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:6')
    for key, value in optlist:
        if key == '-c':
            config_path = value

    if config_path:
        with open(config_path, 'rb') as f:
            config = json.load(f)
        logging.info('loading config from %s' % config_path)

    optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:6')
    for key, value in optlist:
        if key == '-p':
            config['server_port'] = int(value)
        elif key == '-k':
            config['password'] = value
        elif key == '-s':
            config['server'] = value
        elif key == '-m':
            config['method'] = value
        elif key == '-6':
            IPv6 = True

    SERVER = config['server']
    PORT = config['server_port']
    KEY = config['password']
    METHOD = config.get('method', None)

    if not KEY and not config_path:
        sys.exit('config not specified, please read https://github.com/clowwindy/shadowsocks')

    utils.check_config(config)

    encrypt.init_table(KEY, METHOD)
    if IPv6:
        ThreadingTCPServer.address_family = socket.AF_INET6
    try:
        server = ThreadingTCPServer((SERVER, PORT), Socks5Server)
        logging.info("starting server at %s:%d" % tuple(server.server_address[:2]))
        server.serve_forever()
    except socket.error, e:
        logging.error(e)
コード例 #13
0
ファイル: server.py プロジェクト: shengyao/shadowsocks
def main():
    global SERVER, PORT, KEY, METHOD, IPv6

    logging.basicConfig(
        level=logging.CRITICAL,
        format="%(asctime)s %(levelname)-8s %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
        filemode="a+",
    )

    version = ""
    try:
        import pkg_resources

        version = pkg_resources.get_distribution("shadowsocks").version
    except:
        pass
    print "shadowsocks %s" % version

    KEY = None
    METHOD = None
    IPv6 = False

    config_path = utils.find_config()
    optlist, args = getopt.getopt(sys.argv[1:], "s:p:k:m:c:6")
    for key, value in optlist:
        if key == "-c":
            config_path = value

    if config_path:
        with open(config_path, "rb") as f:
            config = json.load(f)
        logging.info("loading config from %s" % config_path)
    else:
        config = {}

    optlist, args = getopt.getopt(sys.argv[1:], "s:p:k:m:c:6")
    for key, value in optlist:
        if key == "-p":
            config["server_port"] = int(value)
        elif key == "-k":
            config["password"] = value
        elif key == "-s":
            config["server"] = value
        elif key == "-m":
            config["method"] = value
        elif key == "-6":
            IPv6 = True

    SERVER = config["server"]
    PORT = config["server_port"]
    KEY = config["password"]
    METHOD = config.get("method", None)

    if not KEY and not config_path:
        sys.exit("config not specified, please read https://github.com/clowwindy/shadowsocks")

    utils.check_config(config)

    encrypt.init_table(KEY, METHOD)
    if IPv6:
        ThreadingTCPServer.address_family = socket.AF_INET6
    try:
        server = ThreadingTCPServer((SERVER, PORT), Socks5Server)
        logging.info("starting server at %s:%d" % tuple(server.server_address[:2]))
        server.serve_forever()
    except socket.error, e:
        logging.error(e)
コード例 #14
0
ファイル: server.py プロジェクト: chihuanqi/shadowsocks
def main():
    global config_server, config_server_port, config_method, config_fast_open, \
        config_timeout

    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')


    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    config_path = utils.find_config()
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:t:',
                                      ['fast-open', 'workers:'])
        for key, value in optlist:
            if key == '-c':
                config_path = value

        if config_path:
            logging.info('loading config from %s' % config_path)
            with open(config_path, 'rb') as f:
                try:
                    config = json.load(f)
                except ValueError as e:
                    logging.error('found an error in config.json: %s',
                                  e.message)
                    sys.exit(1)
        else:
            config = {}

        optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:t:',
                                      ['fast-open', 'workers='])
        for key, value in optlist:
            if key == '-p':
                config['server_port'] = int(value)
            elif key == '-k':
                config['password'] = value
            elif key == '-s':
                config['server'] = value
            elif key == '-m':
                config['method'] = value
            elif key == '-t':
                config['timeout'] = value
            elif key == '--fast-open':
                config['fast_open'] = True
            elif key == '--workers':
                config['workers'] = value
    except getopt.GetoptError:
        utils.print_server_help()
        sys.exit(2)

    config_server = config['server']
    config_server_port = config['server_port']
    config_key = config['password']
    config_method = config.get('method', None)
    config_port_password = config.get('port_password', None)
    config_timeout = int(config.get('timeout', 300))
    config_fast_open = config.get('fast_open', False)
    config_workers = config.get('workers', 1)

    if not config_key and not config_path:
        sys.exit('config not specified, please read '
                 'https://github.com/clowwindy/shadowsocks')

    utils.check_config(config)

    if config_port_password:
        if config_server_port or config_key:
            logging.warn('warning: port_password should not be used with '
                         'server_port and password. server_port and password '
                         'will be ignored')
    else:
        config_port_password = {}
        config_port_password[str(config_server_port)] = config_key

    encrypt.init_table(config_key, config_method)
    addrs = socket.getaddrinfo(config_server, int(8387))
    if not addrs:
        logging.error('cant resolve listen address')
        sys.exit(1)
    ThreadingTCPServer.address_family = addrs[0][0]
    tcp_servers = []
    udp_servers = []
    for port, key in config_port_password.items():
        tcp_server = ThreadingTCPServer((config_server, int(port)),
                                        Socks5Server)
        tcp_server.key = key
        tcp_server.method = config_method
        tcp_server.timeout = int(config_timeout)
        logging.info("starting server at %s:%d" %
                     tuple(tcp_server.server_address[:2]))
        tcp_servers.append(tcp_server)
        udp_server = udprelay.UDPRelay(config_server, int(port), None, None,
                                       key, config_method, int(config_timeout),
                                       False)
        udp_servers.append(udp_server)

    def run_server():
        for tcp_server in tcp_servers:
            threading.Thread(target=tcp_server.serve_forever).start()
        for udp_server in udp_servers:
            udp_server.start()

    if int(config_workers) > 1:
        if os.name == 'posix':
            children = []
            is_child = False
            for i in xrange(0, int(config_workers)):
                r = os.fork()
                if r == 0:
                    logging.info('worker started')
                    is_child = True
                    run_server()
                    break
                else:
                    children.append(r)
            if not is_child:
                def handler(signum, frame):
                    for pid in children:
                        os.kill(pid, signum)
                        os.waitpid(pid, 0)
                    sys.exit()
                import signal
                signal.signal(signal.SIGTERM, handler)

                # master
                for tcp_server in tcp_servers:
                    tcp_server.server_close()
                for udp_server in udp_servers:
                    udp_server.close()

                for child in children:
                    os.waitpid(child, 0)
        else:
            logging.warn('worker is only available on Unix/Linux')
            run_server()
    else:
        run_server()
コード例 #15
0
ファイル: local.py プロジェクト: KK233/shadowsocks
def main():
    global SERVER, REMOTE_PORT, PORT, KEY, METHOD, LOCAL, IPv6

    logging.basicConfig(
        level=logging.DEBUG,
        format="%(asctime)s %(levelname)-8s %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
        filemode="a+",
    )

    # fix py2exe
    if hasattr(sys, "frozen") and sys.frozen in ("windows_exe", "console_exe"):
        p = os.path.dirname(os.path.abspath(sys.executable))
        os.chdir(p)
    version = ""
    try:
        import pkg_resources

        version = pkg_resources.get_distribution("shadowsocks").version
    except:
        pass
    print "shadowsocks %s" % version

    KEY = None
    METHOD = None
    LOCAL = ""
    IPv6 = False

    config_path = utils.find_config()
    optlist, args = getopt.getopt(sys.argv[1:], "s:b:p:k:l:m:c:6")
    for key, value in optlist:
        if key == "-c":
            config_path = value

    if config_path:
        logging.info("loading config from %s" % config_path)
        with open(config_path, "rb") as f:
            config = json.load(f)
        SERVER = config["server"]
        REMOTE_PORT = config["server_port"]
        PORT = config["local_port"]
        KEY = config["password"]
        METHOD = config.get("method", None)
        LOCAL = config.get("local", "")

    optlist, args = getopt.getopt(sys.argv[1:], "s:b:p:k:l:m:c:6")
    for key, value in optlist:
        if key == "-p":
            REMOTE_PORT = int(value)
        elif key == "-k":
            KEY = value
        elif key == "-l":
            PORT = int(value)
        elif key == "-s":
            SERVER = value
        elif key == "-m":
            METHOD = value
        elif key == "-b":
            LOCAL = value
        elif key == "-6":
            IPv6 = True

    if not KEY and not config_path:
        sys.exit("config not specified, please read https://github.com/clowwindy/shadowsocks")

    encrypt.init_table(KEY, METHOD)

    try:
        if IPv6:
            ThreadingTCPServer.address_family = socket.AF_INET6
        server = ThreadingTCPServer((LOCAL, PORT), Socks5Server)
        logging.info("starting server at %s:%d" % tuple(server.server_address[:2]))
        server.serve_forever()
    except socket.error, e:
        logging.error(e)
コード例 #16
0
ファイル: server.py プロジェクト: huhuchen/shadowsocks
def main():
    logging.basicConfig(
        level=logging.DEBUG,
        format="%(asctime)s %(levelname)-8s %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
        filemode="a+",
    )

    version = ""
    try:
        import pkg_resources

        version = pkg_resources.get_distribution("shadowsocks").version
    except:
        pass
    print "shadowsocks %s" % version

    KEY = None
    METHOD = None
    IPv6 = False

    config_path = utils.find_config()
    optlist, args = getopt.getopt(sys.argv[1:], "s:p:k:m:c:6")
    for key, value in optlist:
        if key == "-c":
            config_path = value

    if config_path:
        with open(config_path, "rb") as f:
            config = json.load(f)
        logging.info("loading config from %s" % config_path)
    else:
        config = {}

    optlist, args = getopt.getopt(sys.argv[1:], "s:p:k:m:c:6")
    for key, value in optlist:
        if key == "-p":
            config["server_port"] = int(value)
        elif key == "-k":
            config["password"] = value
        elif key == "-s":
            config["server"] = value
        elif key == "-m":
            config["method"] = value
        elif key == "-6":
            IPv6 = True

    SERVER = config["server"]
    PORT = config["server_port"]
    KEY = config["password"]
    METHOD = config.get("method", None)
    PORTPASSWORD = config.get("port_password", None)
    TIMEOUT = config.get("timeout", 600)

    if not KEY and not config_path:
        sys.exit("config not specified, please read https://github.com/clowwindy/shadowsocks")

    utils.check_config(config)

    if PORTPASSWORD:
        if PORT or KEY:
            logging.warn(
                "warning: port_password should not be used with server_port and password. server_port and password will be ignored"
            )
    else:
        PORTPASSWORD = {}
        PORTPASSWORD[str(PORT)] = KEY

    encrypt.init_table(KEY, METHOD)
    if IPv6:
        ThreadingTCPServer.address_family = socket.AF_INET6
    for port, key in PORTPASSWORD.items():
        server = ThreadingTCPServer((SERVER, int(port)), Socks5Server)
        server.key, server.method, server.timeout = key, METHOD, int(TIMEOUT)
        logging.info("starting server at %s:%d" % tuple(server.server_address[:2]))
        threading.Thread(target=server.serve_forever).start()
コード例 #17
0
ファイル: local.py プロジェクト: imcj/shadowsocks
def main():
    global SERVER, REMOTE_PORT, PORT, KEY, METHOD, LOCAL, IPv6
    
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')

    # fix py2exe
    if hasattr(sys, "frozen") and sys.frozen in \
            ("windows_exe", "console_exe"):
        p = os.path.dirname(os.path.abspath(sys.executable))
        os.chdir(p)
    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    KEY = None
    METHOD = None
    LOCAL = ''
    IPv6 = False
    
    config_path = utils.find_config()
    optlist, args = getopt.getopt(sys.argv[1:], 's:b:p:k:l:m:c:6')
    for key, value in optlist:
        if key == '-c':
            config_path = value

    if config_path:
        logging.info('loading config from %s' % config_path)
        with open(config_path, 'rb') as f:
            config = json.load(f)
    optlist, args = getopt.getopt(sys.argv[1:], 's:b:p:k:l:m:c:6')
    for key, value in optlist:
        if key == '-p':
            config['server_port'] = int(value)
        elif key == '-k':
            config['password'] = value
        elif key == '-l':
            config['local_port'] = int(value)
        elif key == '-s':
            config['server'] = value
        elif key == '-m':
            config['method'] = value
        elif key == '-b':
            config['local'] = value
        elif key == '-6':
            IPv6 = True

    SERVER = config['server']
    REMOTE_PORT = config['server_port']
    PORT = config['local_port']
    KEY = config['password']
    METHOD = config.get('method', None)
    LOCAL = config.get('local', '')

    if not KEY and not config_path:
        sys.exit('config not specified, please read https://github.com/clowwindy/shadowsocks')

    utils.check_config(config)
        
    encrypt.init_table(KEY, METHOD)
    Connection.shared().spawn()

    try:
        if IPv6:
            ThreadingTCPServer.address_family = socket.AF_INET6
        server = ThreadingTCPServer((LOCAL, PORT), Socks5Server)
        logging.info("starting local at %s:%d" % tuple(server.server_address[:2]))
        server.serve_forever()
    except socket.error, e:
        logging.error(e)
コード例 #18
0
def main():
    global config_server, config_server_port, config_method, config_fast_open, \
        config_timeout

    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        filemode='a+')

    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    config_path = utils.find_config()
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:t:',
                                      ['fast-open', 'workers:'])
        for key, value in optlist:
            if key == '-c':
                config_path = value

        if config_path:
            logging.info('loading config from %s' % config_path)
            with open(config_path, 'rb') as f:
                try:
                    config = json.load(f)
                except ValueError as e:
                    logging.error('found an error in config.json: %s',
                                  e.message)
                    sys.exit(1)
        else:
            config = {}

        optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:t:',
                                      ['fast-open', 'workers='])
        for key, value in optlist:
            if key == '-p':
                config['server_port'] = int(value)
            elif key == '-k':
                config['password'] = value
            elif key == '-s':
                config['server'] = value
            elif key == '-m':
                config['method'] = value
            elif key == '-t':
                config['timeout'] = value
            elif key == '--fast-open':
                config['fast_open'] = True
            elif key == '--workers':
                config['workers'] = value
    except getopt.GetoptError:
        utils.print_server_help()
        sys.exit(2)

    config_server = config['server']
    config_server_port = config['server_port']
    config_key = config['password']
    config_method = config.get('method', None)
    config_port_password = config.get('port_password', None)
    config_timeout = int(config.get('timeout', 300))
    config_fast_open = config.get('fast_open', False)
    config_workers = config.get('workers', 1)

    if not config_key and not config_path:
        sys.exit('config not specified, please read '
                 'https://github.com/clowwindy/shadowsocks')

    utils.check_config(config)

    if config_port_password:
        if config_server_port or config_key:
            logging.warn('warning: port_password should not be used with '
                         'server_port and password. server_port and password '
                         'will be ignored')
    else:
        config_port_password = {}
        config_port_password[str(config_server_port)] = config_key

    encrypt.init_table(config_key, config_method)
    addrs = socket.getaddrinfo(config_server, int(8387))
    if not addrs:
        logging.error('cant resolve listen address')
        sys.exit(1)
    ThreadingTCPServer.address_family = addrs[0][0]
    tcp_servers = []
    udp_servers = []
    for port, key in config_port_password.items():
        tcp_server = ThreadingTCPServer((config_server, int(port)),
                                        Socks5Server)
        tcp_server.key = key
        tcp_server.method = config_method
        tcp_server.timeout = int(config_timeout)
        logging.info("starting server at %s:%d" %
                     tuple(tcp_server.server_address[:2]))
        tcp_servers.append(tcp_server)
        udp_server = udprelay.UDPRelay(config_server, int(port), None,
                                       None, key, config_method,
                                       int(config_timeout), False)
        udp_servers.append(udp_server)

    def run_server():
        for tcp_server in tcp_servers:
            threading.Thread(target=tcp_server.serve_forever).start()
        for udp_server in udp_servers:
            udp_server.start()

    if int(config_workers) > 1:
        if os.name == 'posix':
            children = []
            is_child = False
            for i in xrange(0, int(config_workers)):
                r = os.fork()
                if r == 0:
                    logging.info('worker started')
                    is_child = True
                    run_server()
                    break
                else:
                    children.append(r)
            if not is_child:

                def handler(signum, frame):
                    for pid in children:
                        os.kill(pid, signum)
                        os.waitpid(pid, 0)
                    sys.exit()

                import signal
                signal.signal(signal.SIGTERM, handler)

                # master
                for tcp_server in tcp_servers:
                    tcp_server.server_close()
                for udp_server in udp_servers:
                    udp_server.close()

                for child in children:
                    os.waitpid(child, 0)
        else:
            logging.warn('worker is only available on Unix/Linux')
            run_server()
    else:
        run_server()
コード例 #19
0
def main():
    global SERVER, REMOTE_PORT, PORT, KEY, METHOD, LOCAL, IPv6
    
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')

    # fix py2exe
    if hasattr(sys, "frozen") and sys.frozen in \
            ("windows_exe", "console_exe"):
        p = os.path.dirname(os.path.abspath(sys.executable))
        os.chdir(p)
    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    KEY = None
    METHOD = None
    LOCAL = ''
    IPv6 = False
    
    config_path = utils.find_config()
    optlist, args = getopt.getopt(sys.argv[1:], 's:b:p:k:l:m:c:6')
    for key, value in optlist:
        if key == '-c':
            config_path = value

    if config_path:
        logging.info('Loading Config From %s' % config_path)
        with open(config_path, 'rb') as f:
            config = json.load(f)

            #通过判断config.json中是否包含了"server_password"来确定是否启用了多端口
            if config.has_key("server_password") == True:
                #获得"server_password"的长度,得到服务器多端口记录数据
                number = len(config["server_password"]) 
                #通过random取一个随机数、来随机分配用哪一条服务器端口密码记录
                orientation = random.randint(0, number - 1) 
                server_dict = {}
                server_dict[u"server"]= config["server_password"][orientation][0]
                server_dict[u"server_port"] = config["server_password"][orientation][1]
                server_dict[u"password"] = config["server_password"][orientation][2]
                server_dict[u"local_port"] = config["local_port"]
                server_dict[u"method"] = config["method"]
                server_dict[u"timeout"] = config["timeout"]
                config = server_dict
                #print config

            #else:
            #    print config



    optlist, args = getopt.getopt(sys.argv[1:], 's:b:p:k:l:m:c:6')
    for key, value in optlist:
        if key == '-p':
            config['server_port'] = int(value)
        elif key == '-k':
            config['password'] = value
        elif key == '-l':
            config['local_port'] = int(value)
        elif key == '-s':
            config['server'] = value
        elif key == '-m':
            config['method'] = value
        elif key == '-b':
            config['local'] = value
        elif key == '-6':
            IPv6 = True

    SERVER = config['server']
    REMOTE_PORT = config['server_port']
    PORT = config['local_port']
    KEY = config['password']
    METHOD = config.get('method', None)
    LOCAL = config.get('local', '')


    if not KEY and not config_path:
        sys.exit('config not specified, please read https://github.com/huaisha1224/ShadowSocks-Client')

    utils.check_config(config)
        
    encrypt.init_table(KEY, METHOD)

    try:
        if IPv6:
            ThreadingTCPServer.address_family = socket.AF_INET6
        server = ThreadingTCPServer((LOCAL, PORT), Socks5Server)
        logging.info("Available Remoto Server %s:%d" %(SERVER, REMOTE_PORT))
        logging.info("Starting Local Socks5 Server At %s:%d" % tuple(server.server_address[:2]))
        server.serve_forever()
    except socket.error, e:
        logging.error(e)
コード例 #20
0
ファイル: server.py プロジェクト: Bitesher/shadowsocks
def main():
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')


    version = ''
    try:
        import pkg_resources
        version = pkg_resources.get_distribution('shadowsocks').version
    except:
        pass
    print 'shadowsocks %s' % version

    KEY = None
    METHOD = None
    IPv6 = False

    config_path = utils.find_config()
    optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:6')
    for key, value in optlist:
        if key == '-c':
            config_path = value

    if config_path:
        logging.info('loading config from %s' % config_path)
        with open(config_path, 'rb') as f:
            try:
                config = json.load(f)
            except ValueError as e:
                logging.error('found an error in config.json: %s', e.message)
                sys.exit(1)
        logging.info('loading config from %s' % config_path)
    else:
        config = {}

    optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:6')
    for key, value in optlist:
        if key == '-p':
            config['server_port'] = int(value)
        elif key == '-k':
            config['password'] = value
        elif key == '-s':
            config['server'] = value
        elif key == '-m':
            config['method'] = value
        elif key == '-6':
            IPv6 = True

    SERVER = config['server']
    PORT = config['server_port']
    KEY = config['password']
    METHOD = config.get('method', None)
    PORTPASSWORD = config.get('port_password', None)
    TIMEOUT = config.get('timeout', 600)

    if not KEY and not config_path:
        sys.exit('config not specified, please read https://github.com/clowwindy/shadowsocks')

    utils.check_config(config)

    if PORTPASSWORD:
        if PORT or KEY:
            logging.warn('warning: port_password should not be used with server_port and password. server_port and password will be ignored')
    else:
        PORTPASSWORD = {}
        PORTPASSWORD[str(PORT)] = KEY

    encrypt.init_table(KEY, METHOD)
    if IPv6:
        ThreadingTCPServer.address_family = socket.AF_INET6
    for port, key in PORTPASSWORD.items():
        server = ThreadingTCPServer((SERVER, int(port)), Socks5Server)
        server.key, server.method, server.timeout = key, METHOD, int(TIMEOUT)
        logging.info("starting server at %s:%d" % tuple(server.server_address[:2]))
        threading.Thread(target=server.serve_forever).start()