Пример #1
0
def run(init: bool, server: str, country_code: str, country: str, area: str, tcp: bool, daemon: bool,
        max_load: int, top_servers: int, pings: str, kill: bool, kill_flush: bool, update: bool, list_servers: bool,
        force_fw_rules: bool, p2p: bool, dedicated: bool, double_vpn: bool, tor_over_vpn: bool, anti_ddos: bool,
        netflix: bool, test: bool, internally_allowed: List, skip_dns_patch: bool, silent: bool, nvram: str,
        openvpn_options: str, location: float) -> bool:

    if init:
        initialise(log_folder)

    fieldstyles = {
        'asctime': {'color': 'green'},
        'hostname': {'color': 'magenta'},
        'levelname': {'color': 'black', 'bold': True},
        'name': {'color': 'blue'},
        'programname': {'color': 'cyan'},
    }
    levelstyles = {
        'spam': {'color': 'green', 'faint': True},
        'debug': {'color': 'green', 'bold': True},
        'verbose': {'color': 'blue', 'bold': True},
        'info': {},
        'notice': {'color': 'magenta', 'bold': True},
        'warning': {'color': 'yellow', 'bold': True},
        'success': {'color': 'green', 'bold': True},
        'error': {'color': 'red', 'bold': True},
        'critical': {'color': 'white', 'background': 'red', 'bold': True}
    }

    logger.addHandler(logging.StreamHandler())

    # if log folder doesnt exist, exit, "--init" creates it
    if not os.path.exists(log_folder):
        logger.error(
            "Please initialise first by running 'sudo openpyn --init', then start using 'openpyn' without sudo")
        return 1

    # Add another rotating handler to log to .log files
    # fix permissions if needed
    for attempt in range(2):
        try:
            file_handler = logging.handlers.TimedRotatingFileHandler(
                log_folder + '/openpyn.log', when='W0', interval=4)
            file_handler_formatter = logging.Formatter(log_format)
            file_handler.setFormatter(file_handler_formatter)
            logger.addHandler(file_handler)
        except PermissionError:
            root.verify_root_access(
                "Root access needed to set permissions of {}/openpyn.log".format(log_folder))
            subprocess.run("sudo chmod 777 {}/openpyn.log".format(log_folder).split())
            subprocess.run("sudo chmod 777 {}/openpyn-notifications.log".format(log_folder).split())
        else:
            break

    # In this case only log messages originating from this logger will show up on the terminal.
    coloredlogs.install(level="verbose", logger=logger, fmt=log_format,
                        level_styles=levelstyles, field_styles=fieldstyles)

    stats = True
    if sys.__stdin__.isatty():
        logger.debug("Interactive")
    else:
        logger.addHandler(logging.StreamHandler(sys.stdout))
        logger.setLevel(logging.WARNING)
        logger.debug("Non-Interactive")
        stats = False

    port = "udp"
    if tcp:
        port = "tcp"

    detected_os = sys.platform
    if detected_os == "linux":
        if subprocess.check_output(["/bin/uname", "-o"]).decode(sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
            force_fw_rules = False
            silent = True
            skip_dns_patch = True
            if openvpn_options:
                openvpn_options += " " + "--syslog openpyn"
            else:
                openvpn_options = "--syslog openpyn"
            logger.debug(openvpn_options)
        elif os.path.exists("/etc/openwrt_release"):
            force_fw_rules = False
            silent = True
            skip_dns_patch = True
            nvram = None
        else:
            nvram = None
    elif detected_os == "win32":
        logger.error("Are you even a l33t mate? Try GNU/Linux")
        return 1

    # check if dependencies are installed
    if shutil.which("openvpn") is None or shutil.which("wget") is None or shutil.which("unzip") is None:
        # In case of Debian Sid where "openvpn" is only in root's PATH, don't error out
        try:
            root_access = root.verify_root_access(
                "Sudo credentials required to check if 'openvpn' is available in root's PATH")
            if root_access is False:
                root.obtain_root_access()
            subprocess.check_output(["sudo", "which", "wget"])
            subprocess.check_output(["sudo", "which", "unzip"])
            # subprocess.check_output(["sudo", "which", "openvpn"])
        except subprocess.CalledProcessError:
            logger.error("Please Install 'openvpn' 'wget' 'unzip' first")
            return 1

    elif daemon:
        if detected_os != "linux":
            logger.error("Daemon mode is only available in GNU/Linux distros")
            return 1

        if not root.verify_running_as_root():
            logger.error("Please run '--daemon' or '-d' mode with sudo")
            return 1
        openpyn_options = ""

        # if only positional argument used
        if country_code is None and server is None:
            country_code = country      # consider the positional arg e.g "us" same as "-c us"
        # if either "-c" or positional arg f.e "au" is present

        if country_code:
            if len(country_code) > 2:   # full country name
                # get the country_code from the full name
                country_code = api.get_country_code(full_name=country_code)
            country_code = country_code.lower()
            openpyn_options += country_code

        elif server:
            openpyn_options += " --server " + server

        if area:
            openpyn_options += " --area " + area
        if tcp:
            openpyn_options += " --tcp"
        if max_load:
            openpyn_options += " --max-load " + str(max_load)
        if top_servers:
            openpyn_options += " --top-servers " + str(top_servers)
        if pings:
            openpyn_options += " --pings " + str(pings)
        if force_fw_rules:
            openpyn_options += " --force-fw-rules"
        if p2p:
            openpyn_options += " --p2p"
        if dedicated:
            openpyn_options += " --dedicated"
        if double_vpn:
            openpyn_options += " --double"
        if tor_over_vpn:
            openpyn_options += " --tor"
        if anti_ddos:
            openpyn_options += " --anti-ddos"
        if netflix:
            openpyn_options += " --netflix"
        if test:
            openpyn_options += " --test"
        if internally_allowed:
            open_ports = ""
            for port_number in internally_allowed:
                open_ports += " " + port_number
            openpyn_options += " --allow" + open_ports
        if skip_dns_patch:
            openpyn_options += " --skip-dns-patch"
        if nvram:
            openpyn_options += " --nvram " + str(nvram)
        if openvpn_options:
            openpyn_options += " --openvpn-options '" + openvpn_options + "'"
        # logger.debug(openpyn_options)
        if subprocess.check_output(["/bin/uname", "-o"]).decode(sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
            initd.update_service(openpyn_options, run=True)
        elif os.path.exists("/etc/openwrt_release"):
            initd.update_service(openpyn_options, run=True)
        else:
            systemd.update_service(openpyn_options, run=True)
        return 0

    elif kill:
        logger.warning("Killing the running processes")
        kill_management_client()
        kill_vpn_processes()  # don't touch iptable rules
        kill_openpyn_process()

    elif kill_flush:
        firewall.clear_fw_rules()      # also clear iptable rules
        # if --allow present, allow those ports internally
        logger.info("Re-enabling ipv6")
        firewall.manage_ipv6(disable=False)
        if internally_allowed:
            network_interfaces = get_network_interfaces()
            firewall.internally_allow_ports(network_interfaces, internally_allowed)
        kill_management_client()
        kill_vpn_processes()
        kill_openpyn_process()

    elif update:
        update_config_files()

    # a hack to list all countries and their codes when no arg supplied with "-l"
    elif list_servers != 'nope':      # means "-l" supplied
        if list_servers is None:      # no arg given with "-l"
            if p2p or dedicated or double_vpn or tor_over_vpn or anti_ddos or netflix:
                # show the special servers in all countries
                display_servers(
                    list_servers="all", port=port, area=area, p2p=p2p, dedicated=dedicated,
                    double_vpn=double_vpn, tor_over_vpn=tor_over_vpn, anti_ddos=anti_ddos,
                    netflix=netflix, location=location)
            else:
                api.list_all_countries()
        # if a country code is supplied give details about that country only.
        else:
            # if full name of the country supplied get country_code
            if len(list_servers) > 2:
                list_servers = api.get_country_code(full_name=list_servers)
            display_servers(
                list_servers=list_servers, port=port, area=area, p2p=p2p, dedicated=dedicated,
                double_vpn=double_vpn, tor_over_vpn=tor_over_vpn, anti_ddos=anti_ddos,
                netflix=netflix, location=location)

    # only clear/touch FW Rules if "-f" used
    elif force_fw_rules:
        firewall.clear_fw_rules()

    # check if OpenVPN config files exist if not download them.
    check_config_files()

    # if only positional argument used
    if country_code is None and server is None:
        country_code = country      # consider the positional arg e.g "us" same as "-c us"
    # if either "-c" or positional arg f.e "au" is present
    if country_code:
        # ask for and store credentials if not present, skip if "--test"
        if not test:
            if credentials.check_credentials() is False:
                credentials.save_credentials()

        if len(country_code) > 2:   # full country name
            # get the country_code from the full name
            country_code = api.get_country_code(full_name=country_code)
        country_code = country_code.lower()

        # keep trying to connect to new servers
        for tries in range(3):  # pylint: disable=W0612
            better_servers_list = find_better_servers(
                country_code, area, max_load, top_servers, tcp, p2p,
                dedicated, double_vpn, tor_over_vpn, anti_ddos, netflix, location, stats)
            pinged_servers_list = ping_servers(better_servers_list, pings, stats)
            chosen_servers = choose_best_servers(pinged_servers_list, stats)

            # connect to chosen_servers, if one fails go to next
            for aserver in chosen_servers:
                if stats:
                    print(Style.BRIGHT + Fore.BLUE + "Out of the Best Available Servers, Chose",
                          (Fore.GREEN + aserver + Fore.BLUE) + "\n")
                # if "-f" used apply firewall rules
                if force_fw_rules:
                    network_interfaces = get_network_interfaces()
                    vpn_server_ip = get_vpn_server_ip(aserver, port)
                    firewall.apply_fw_rules(network_interfaces, vpn_server_ip, skip_dns_patch)
                    if internally_allowed:
                        firewall.internally_allow_ports(network_interfaces, internally_allowed)
                if nvram:
                    # TODO return 0 on success else 1 in asus.run()
                    asus.run(aserver, country_code, nvram, "All", "adaptive", "Strict", tcp, test)
                    logger.success("SAVED SERVER " + aserver + " ON PORT " + port + " TO NVRAM")
                return(connect(aserver, port, silent, test, skip_dns_patch, openvpn_options))
    elif server:
        # ask for and store credentials if not present, skip if "--test"
        if not test:
            if credentials.check_credentials() is False:
                credentials.save_credentials()

        server = server.lower()
        # if "-f" used apply firewall rules
        if force_fw_rules:
            network_interfaces = get_network_interfaces()
            vpn_server_ip = get_vpn_server_ip(server, port)
            firewall.apply_fw_rules(network_interfaces, vpn_server_ip, skip_dns_patch)
            if internally_allowed:
                firewall.internally_allow_ports(network_interfaces, internally_allowed)
        if nvram:
            asus.run(server, country_code, nvram, "All", "adaptive", "Strict", tcp, test)
            logger.success("SAVED SERVER " + server + " ON PORT " + port + " TO NVRAM")
            return 0
        for i in range(20):  # pylint: disable=W0612
            return(connect(server, port, silent, test, skip_dns_patch, openvpn_options))
    else:
        logger.info('To see usage options type: "openpyn -h" or "openpyn --help"')
    return 0        # if everything went ok
Пример #2
0
def run(init, server, country_code, country, area, tcp, daemon, max_load,
        top_servers, pings, kill, kill_flush, update, list_servers,
        force_fw_rules, p2p, dedicated, double_vpn, tor_over_vpn, anti_ddos,
        netflix, test, internally_allowed, skip_dns_patch, silent, nvram,
        openvpn_options):
    port = "udp"
    if tcp:
        port = "tcp"

    detected_os = sys.platform
    if detected_os == "linux":
        if subprocess.check_output(["/bin/uname", "-o"]).decode(
                sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
            silent = True
            skip_dns_patch = True
        elif os.path.exists("/etc/openwrt_release"):
            silent = True
            skip_dns_patch = True
            nvram = None
        else:
            nvram = None
    elif detected_os == "win32":
        print(Fore.BLUE + "Are you even a l33t mate? Try GNU/Linux")
        print(Style.RESET_ALL)
        sys.exit()

    if init:
        initialise()
    elif daemon:
        if detected_os != "linux":
            print(Fore.RED +
                  "Daemon mode is only available in GNU/Linux distros")
            print(Style.RESET_ALL)
            sys.exit()

        if not root.verify_running_as_root():
            print(Fore.RED + "Please run '--daemon' or '-d' mode with sudo")
            print(Style.RESET_ALL)
            sys.exit()
        openpyn_options = ""

        # if only positional argument used
        if country_code is None and server is None:
            country_code = country  # consider the positional arg e.g "us" same as "-c us"
        # if either "-c" or positional arg f.e "au" is present

        if country_code:
            if len(country_code) > 2:  # full country name
                # get the country_code from the full name
                country_code = api.get_country_code(full_name=country_code)
            country_code = country_code.lower()
            openpyn_options += country_code

        elif server:
            openpyn_options += server

        if area:
            openpyn_options += " --area " + area
        if tcp:
            openpyn_options += " --tcp"
        if max_load:
            openpyn_options += " --max-load " + str(max_load)
        if top_servers:
            openpyn_options += " --top-servers " + str(top_servers)
        if pings:
            openpyn_options += " --pings " + str(pings)
        if force_fw_rules:
            openpyn_options += " --force-fw-rules"
        if p2p:
            openpyn_options += " --p2p"
        if dedicated:
            openpyn_options += " --dedicated"
        if double_vpn:
            openpyn_options += " --double"
        if tor_over_vpn:
            openpyn_options += " --tor"
        if anti_ddos:
            openpyn_options += " --anti-ddos"
        if netflix:
            openpyn_options += " --netflix"
        if test:
            openpyn_options += " --test"
        if internally_allowed:
            open_ports = ""
            for port_number in internally_allowed:
                open_ports += " " + port_number
            openpyn_options += " --allow" + open_ports
        if skip_dns_patch:
            openpyn_options += " --skip-dns-patch"
        if nvram:
            openpyn_options += " --nvram " + str(nvram)
        if openvpn_options:
            openpyn_options += " --openvpn-options '" + openvpn_options + "'"
        openpyn_options += " --silent"
        # print(openpyn_options)
        if subprocess.check_output(["/bin/uname", "-o"]).decode(
                sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
            initd.update_service(openpyn_options, run=True)
        elif os.path.exists("/etc/openwrt_release"):
            initd.update_service(openpyn_options, run=True)
        else:
            systemd.update_service(openpyn_options, run=True)
        sys.exit()

    elif kill:
        kill_management_client()
        kill_vpn_processes()  # dont touch iptable rules
        kill_openpyn_process()
        sys.exit()
    elif kill_flush:
        firewall.clear_fw_rules()  # also clear iptable rules
        # if --allow present, allow those ports internally
        if internally_allowed:
            network_interfaces = get_network_interfaces()
            firewall.internally_allow_ports(network_interfaces,
                                            internally_allowed)
        kill_management_client()
        kill_vpn_processes()
        kill_openpyn_process()
        sys.exit()
    elif update:
        update_config_files()
        sys.exit()

    # a hack to list all countries and thier codes when no arg supplied with "-l"
    elif list_servers != 'nope':  # means "-l" supplied
        if list_servers is None:  # no arg given with "-l"
            if p2p or dedicated or double_vpn or tor_over_vpn or anti_ddos or netflix:
                # show the special servers in all countries
                display_servers(list_servers="all",
                                port=port,
                                area=area,
                                p2p=p2p,
                                dedicated=dedicated,
                                double_vpn=double_vpn,
                                tor_over_vpn=tor_over_vpn,
                                anti_ddos=anti_ddos,
                                netflix=netflix)
            else:
                api.list_all_countries()
        # if a country code is supplied give details about that country only.
        else:
            # if full name of the country supplied get country_code
            if len(list_servers) > 2:
                list_servers = api.get_country_code(full_name=list_servers)
            display_servers(list_servers=list_servers,
                            port=port,
                            area=area,
                            p2p=p2p,
                            dedicated=dedicated,
                            double_vpn=double_vpn,
                            tor_over_vpn=tor_over_vpn,
                            anti_ddos=anti_ddos,
                            netflix=netflix)

    # only clear/touch FW Rules if "-f" used
    elif force_fw_rules:
        firewall.clear_fw_rules()

    # check if openvpn config files exist if not download them.
    check_config_files()

    # if only positional argument used
    if country_code is None and server is None:
        country_code = country  # consider the positional arg e.g "us" same as "-c us"
    # if either "-c" or positional arg f.e "au" is present
    if country_code:
        # ask for and store credentials if not present, skip if "--test"
        if not test:
            if credentials.check_credentials() is False:
                credentials.save_credentials()

        if len(country_code) > 2:  # full country name
            # get the country_code from the full name
            country_code = api.get_country_code(full_name=country_code)
        country_code = country_code.lower()

        # keep trying to connect to new servers
        for tries in range(3):  # pylint: disable=W0612
            better_servers_list = find_better_servers(country_code, area,
                                                      max_load, top_servers,
                                                      tcp, p2p, dedicated,
                                                      double_vpn, tor_over_vpn,
                                                      anti_ddos, netflix)
            pinged_servers_list = ping_servers(better_servers_list, pings)
            chosen_servers = choose_best_servers(pinged_servers_list)
            # connect to chosen_servers, if one fails go to next
            for aserver in chosen_servers:
                # if "-f" used appy Firewall rules
                if force_fw_rules:
                    network_interfaces = get_network_interfaces()
                    vpn_server_ip = get_vpn_server_ip(aserver, port)
                    firewall.apply_fw_rules(network_interfaces, vpn_server_ip,
                                            skip_dns_patch)
                    if internally_allowed:
                        firewall.internally_allow_ports(
                            network_interfaces, internally_allowed)
                if nvram:
                    asus.run(aserver, country_code, nvram, "All", "adaptive",
                             "Strict", tcp, test)
                    sys.exit()
                print(
                    Style.BRIGHT + Fore.BLUE +
                    "Out of the Best Available Servers, Chose",
                    (Fore.GREEN + aserver + Fore.BLUE))
                connect(aserver, port, silent, test, skip_dns_patch,
                        openvpn_options)
    elif server:
        # ask for and store credentials if not present, skip if "--test"
        if not test:
            if credentials.check_credentials() is False:
                credentials.save_credentials()

        server = server.lower()
        # if "-f" used appy Firewall rules
        if force_fw_rules:
            network_interfaces = get_network_interfaces()
            vpn_server_ip = get_vpn_server_ip(server, port)
            firewall.apply_fw_rules(network_interfaces, vpn_server_ip,
                                    skip_dns_patch)
            if internally_allowed:
                firewall.internally_allow_ports(network_interfaces,
                                                internally_allowed)
        if nvram:
            asus.run(server, country_code, nvram, "All", "adaptive", "Strict",
                     tcp, test)
            sys.exit()
        for i in range(20):  # pylint: disable=W0612
            connect(server, port, silent, test, skip_dns_patch,
                    openvpn_options)
    else:
        print('To see usage options type: "openpyn -h" or "openpyn --help"')
    sys.exit()
Пример #3
0
def install_service() -> None:
    if not sys.__stdin__.isatty():
        raise RuntimeError("Please run %s in interactive mode" % __name__)

    openpyn_options = (input(
        "\nEnter Openpyn options to be stored in initd service file (/opt/etc/init.d/S23openpyn, Default(Just Press"
        " Enter) is, uk : ") or "uk")

    # regex used
    # .*add_argument_group.*\n --> ""
    # \, help='(.|\\\n)+', --> ","
    # \, help='(.|\\\n)+' --> ""
    # (\n).+       ' --> "'"
    # (\n).+       ac --> " ac"

    parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
    parser.add_argument('--allow', dest='internally_allowed', nargs='+')
    # parser.add_argument('--allow-config', dest='internally_allowed_config')
    parser.add_argument('--allow-config-json',
                        dest='internally_allowed_config_json')
    parser.add_argument('--allow-locally',
                        dest='allow_locally',
                        action='store_true')
    parser.add_argument('--anti-ddos', dest='anti_ddos', action='store_true')
    parser.add_argument('--dedicated', action='store_true')
    parser.add_argument('--double', dest='double_vpn', action='store_true')
    parser.add_argument('--netflix', dest='netflix', action='store_true')
    parser.add_argument('--p2p', action='store_true')
    parser.add_argument('--silent', action='store_true')
    parser.add_argument('--skip-dns-patch',
                        dest='skip_dns_patch',
                        action='store_true')
    parser.add_argument('--tcp', action='store_true')
    parser.add_argument('--test', action='store_true')
    parser.add_argument('--tor', dest='tor_over_vpn', action='store_true')
    parser.add_argument('--update', action='store_true')
    parser.add_argument('-a', '--area', type=str)
    parser.add_argument('-c', '--country-code', type=str)
    parser.add_argument('-f', '--force-fw-rules', action='store_true')
    parser.add_argument('-loc', '--location', nargs=2, type=float)
    parser.add_argument('-m', '--max-load', type=int, default=70)
    parser.add_argument('-n', '--nvram', type=str)
    parser.add_argument('-o',
                        '--openvpn-options',
                        dest='openvpn_options',
                        type=str)
    parser.add_argument('-s', '--server', type=str)
    parser.add_argument('-t', '--top-servers', type=int, default=10)
    parser.add_argument('country', nargs='?')

    try:
        args = parser.parse_args(openpyn_options.split())
    except SystemExit as e:
        if e.code == 2:
            openpyn_options = (input(
                "\nEnter Openpyn options to be stored in initd service file (/opt/etc/init.d/S23openpyn, Default(Just"
                " Press Enter) is, uk : ") or "uk")
            args = parser.parse_args(openpyn_options.split())

    if args.update:
        update_service("--update")
        return

    server = args.server
    country_code = args.country_code
    country = args.country
    area = args.area
    tcp = args.tcp
    max_load = args.max_load
    top_servers = args.top_servers
    force_fw_rules = args.force_fw_rules
    p2p = args.p2p
    dedicated = args.dedicated
    double_vpn = args.double_vpn
    tor_over_vpn = args.tor_over_vpn
    anti_ddos = args.anti_ddos
    netflix = args.netflix
    test = args.test
    internally_allowed = args.internally_allowed
    internally_allowed_config_json = args.internally_allowed_config_json
    skip_dns_patch = args.skip_dns_patch
    silent = args.silent
    nvram = args.nvram
    openvpn_options = args.openvpn_options
    location = args.location

    detected_os = sys.platform
    if detected_os == "linux":
        if subprocess.check_output(["/bin/uname", "-o"]).decode(
                sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
            force_fw_rules = False
            internally_allowed = None
            silent = True
            skip_dns_patch = True
        elif os.path.exists("/etc/openwrt_release"):
            force_fw_rules = False
            internally_allowed = None
            silent = True
            skip_dns_patch = True
            nvram = None
        else:
            nvram = None

    openpyn_options = ""

    # if only positional argument used
    if country_code is None and server is None:
        # consider the positional arg e.g "us" same as "-c us"
        country_code = country

    # if either "-c" or positional arg f.e "au" is present
    if country_code:
        # if full name of the country supplied get country_code
        if len(country_code) > 2:
            country_code = api.get_country_code(full_name=country_code)
        country_code = country_code.lower()
        openpyn_options += country_code

    elif server:
        openpyn_options += " --server " + server

    if area:
        openpyn_options += " --area " + area
    if tcp:
        openpyn_options += " --tcp"
    if max_load:
        openpyn_options += " --max-load " + str(max_load)
    if top_servers:
        openpyn_options += " --top-servers " + str(top_servers)
    if force_fw_rules:
        openpyn_options += " --force-fw-rules"
    if p2p:
        openpyn_options += " --p2p"
    if dedicated:
        openpyn_options += " --dedicated"
    if double_vpn:
        openpyn_options += " --double"
    if tor_over_vpn:
        openpyn_options += " --tor"
    if anti_ddos:
        openpyn_options += " --anti-ddos"
    if netflix:
        openpyn_options += " --netflix"
    if test:
        openpyn_options += " --test"
    if internally_allowed:
        open_ports = ""
        for port_number in internally_allowed:
            open_ports += " " + port_number
        openpyn_options += " --allow" + open_ports
    if internally_allowed_config_json:
        # Assume at this stage the JSON has been passed as string so it can be directly loaded
        openpyn_options += " --allow-config-json=" + internally_allowed_config_json
    if skip_dns_patch:
        openpyn_options += " --skip-dns-patch"
    if silent:
        openpyn_options += " --silent"
    if nvram:
        openpyn_options += " --nvram " + nvram
    if openvpn_options:
        openpyn_options += " --openvpn-options '" + openvpn_options + "'"
    if location:
        openpyn_options += " --location " + str(location[1]) + " " + str(
            location[2])

    update_service(openpyn_options)
Пример #4
0
def install_service():
    openpyn_options = input("Enter Openpyn options to be stored in initd \
service file (/opt/etc/init.d/S23openpyn, \
Default(Just Press Enter) is, uk : ") or "uk"

    # regex used
    # (, help).+' --> “”
    # (\n).+       ' --> “'”
    # (\n).+       ac --> “ ac”

    parser = argparse.ArgumentParser(add_help=False)
    # parser.add_argument('--init')
    parser.add_argument('-s', '--server')
    parser.add_argument('--tcp', action='store_true')
    parser.add_argument('-c', '--country-code', type=str)
    parser.add_argument('country', nargs='?')
    parser.add_argument('-a', '--area', type=str)
    parser.add_argument('-d', '--daemon', action='store_true')
    parser.add_argument('-m', '--max-load', type=int, default=70)
    parser.add_argument('-t', '--top-servers', type=int, default=10)
    parser.add_argument('-p', '--pings', type=str, default="5")
    # parser.add_argument('-k', '--kill', action='store_true')
    # parser.add_argument('-x', '--kill-flush', action='store_true')
    # parser.add_argument('--update', action='store_true')
    parser.add_argument('--skip-dns-patch', dest='skip_dns_patch')
    parser.add_argument('-f', '--force-fw-rules')
    parser.add_argument('--allow', dest='internally_allowed')
    # parser.add_argument('-l', '--list', dest="list_servers", type=str, nargs='?', default="nope")
    parser.add_argument('--silent')
    parser.add_argument('--p2p')
    parser.add_argument('--dedicated', action='store_true')
    parser.add_argument('--tor', dest='tor_over_vpn', action='store_true')
    parser.add_argument('--double', dest='double_vpn', action='store_true')
    parser.add_argument('--anti-ddos', dest='anti_ddos', action='store_true')
    parser.add_argument('--netflix', dest='netflix', action='store_true')
    parser.add_argument('--test', action='store_true')
    parser.add_argument('-n', '--nvram', type=str, default="5")
    parser.add_argument('-o',
                        '--openvpn-options',
                        dest='openvpn_options',
                        type=str)

    try:
        args = parser.parse_args(openpyn_options.split())
    except SystemExit as e:
        if e.code == 2:
            openpyn_options = input(
                "Enter Openpyn options to be stored in initd \
service file (/opt/etc/init.d/S23openpyn, \
Default(Just Press Enter) is, uk : ") or "uk"
            args = parser.parse_args(openpyn_options.split())

    server = args.server
    country_code = args.country_code
    country = args.country
    area = args.area
    tcp = args.tcp
    max_load = args.max_load
    top_servers = args.top_servers
    pings = args.pings
    force_fw_rules = args.force_fw_rules
    p2p = args.p2p
    dedicated = args.dedicated
    double_vpn = args.double_vpn
    tor_over_vpn = args.tor_over_vpn
    anti_ddos = args.anti_ddos
    netflix = args.netflix
    test = args.test
    internally_allowed = args.internally_allowed
    skip_dns_patch = args.skip_dns_patch
    silent = args.silent
    nvram = args.nvram
    openvpn_options = args.openvpn_options

    detected_os = sys.platform
    if detected_os == "linux":
        if subprocess.check_output(["/bin/uname", "-o"]).decode(
                sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
            silent = True
            skip_dns_patch = True
        elif os.path.exists("/etc/openwrt_release"):
            silent = True
            skip_dns_patch = True

    openpyn_options = ""

    # if only positional argument used
    if country_code is None and server is None:
        country_code = country  # consider the positional arg e.g "us" same as "-c us"
    # if either "-c" or positional arg f.e "au" is present

    if country_code:
        if len(country_code) > 2:  # full country name
            # get the country_code from the full name
            country_code = api.get_country_code(full_name=country_code)
        country_code = country_code.lower()
        openpyn_options += country_code

    elif server:
        openpyn_options += server

    if area:
        openpyn_options += " --area " + area
    if tcp:
        openpyn_options += " --tcp"
    if max_load:
        openpyn_options += " --max-load " + str(max_load)
    if top_servers:
        openpyn_options += " --top-servers " + str(top_servers)
    if pings:
        openpyn_options += " --pings " + str(pings)
    if force_fw_rules:
        openpyn_options += " --force-fw-rules"
    if p2p:
        openpyn_options += " --p2p"
    if dedicated:
        openpyn_options += " --dedicated"
    if double_vpn:
        openpyn_options += " --double"
    if tor_over_vpn:
        openpyn_options += " --tor"
    if anti_ddos:
        openpyn_options += " --anti-ddos"
    if netflix:
        openpyn_options += " --netflix"
    if test:
        openpyn_options += " --test"
    if internally_allowed:
        open_ports = ""
        for port_number in internally_allowed:
            open_ports += " " + port_number
        openpyn_options += " --allow" + open_ports
    if skip_dns_patch:
        openpyn_options += " --skip-dns-patch"
    if silent:
        openpyn_options += " --silent"
    if nvram:
        openpyn_options += " --nvram " + str(nvram)
    if openvpn_options:
        openpyn_options += " --openvpn-options '" + openvpn_options + "'"

    update_service(openpyn_options)