Пример #1
0
def update_file(filename: str, url: str) -> bool:
    """Check and update file compares with remote_url

    Args:
        filename: str. Local filename, normally it's `__file__`
        url: str or urllib.request.Request object. Remote url of raw file content. Use urllib.request.Request object for headers.
    Returns:
        bool: file updated or not
    """
    def compare(s1, s2):
        return s1 == s2, len(s2) - len(s1)

    if not url or not filename:
        return False
    try:
        raw_codes = read_url(url)
        with open(filename, "rb") as f:
            current_codes = f.read().replace(b"\r", b"")
        is_same, diff = compare(current_codes, raw_codes)
        if is_same:
            cit.info("{} is already up-to-date.".format(filename))
            return False
        else:
            cit.ask("A new version is available. Update? (Diff: {})".format(diff))
            if cit.get_choice(["Yes", "No"]) == "Yes":
                with open(filename, "wb") as f:
                    f.write(raw_codes)
                cit.info("Update Success.")
                return True
            else:
                cit.warn("Update Canceled")
                return False
    except Exception as e:
        cit.err("{f} update failed: {e}".format(f=filename, e=e))
        return False
Пример #2
0
def get_operation():
    """start a new uwsgi, stop a running uwsgi, or reload the config and codes"""
    operations = ["*** update uwsgiTool ***", "start", "stop", "reload"]
    if len(sys.argv) != 2:
        return cit.get_choice(operations)
    elif sys.argv[1] in operations:
        selected = sys.argv[1]
        cit.info("Selected: {}".format(selected))
        return selected
    else:
        cit.err("Wrong Params: " + sys.argv[1])
        cit.bye()
Пример #3
0
def menu():
    confs = ['.vimrc', '.tcshrc', '.bashrc', '.tcsh_aliases', '.tcsh_prompt', '.bash_aliases', '.bash_prompt']
    cit.ask('Which config file to update:')
    choice = cit.get_choice(['ALL'] + confs + ['exit'])
    if choice == 'ALL':
        for conf in confs:
            apply_config(conf)
        cit.info('Done')
        cit.bye()
    elif choice == 'exit':
        cit.bye()
    else:
        return choice
Пример #4
0
def show_in_folder(path: str, ask: bool = False):
    """Show file in Explorer/Finder/Folder"""
    import subprocess
    import platform
    if ask:
        cit.ask("Show in folder?")
        if cit.get_choice(('Yes', 'No')) == 'No':
            return False
    if sys.platform.startswith("win"):
        os.startfile(path)
    elif platform.system() == "Darwin":
        subprocess.Popen(["open", path])
    else:
        subprocess.Popen(["xdg-open", path])
Пример #5
0
def menu():
    confs = ['.vimrc', '.tcshrc', '.aliases', '.promptrc']
    cit.ask('Which config file to update:')
    choice = cit.get_choice(['ALL'] + confs + ['exit'])
    if choice == 'ALL':
        for conf in confs:
            config(conf)
        cit.info('Done')
        cit.pause('Press Enter to exit ...')
        cit.bye()
    elif choice == 'exit':
        cit.bye()
    else:
        return choice
Пример #6
0
def generate_UDP_file(Phraser: object, output: str, phrases: list):
    if not Phraser:
        raise Exception("Phraser must provided!")
    if not output:
        raise Exception("No output filename provided!")
    phraser = Phraser(phrases)
    filepath = os.path.join(GENERATED_DIR, output)
    if os.path.exists(filepath):
        cit.ask("'{}' is already exists. Overwrite it?".format(filepath))
        if cit.get_choice(['Yes', 'No']) == 'Yes':
            os.remove(filepath)
        else:
            cit.warn("Output is not overwrited. No file generated.")
            return
    phraser.to_file(filepath)
    cit.info("'{o}' is generated, {length} phrases.".format(
        o=output, length=len(phraser.phrases)))
Пример #7
0
def show_menu():
    """Show commands menu

    Globals:
        COMMANDS: Dict of menu commands.
            Key: description of func
            Val: func
    """
    #     'Django system check': functools.partial(run_by_py3, ),
    # }
    menu = sorted(COMMANDS.keys())
    if len(sys.argv) > 1:
        arg = sys.argv.pop()
        selection = arg if arg in COMMANDS else menu[int(arg) - 1]
    else:
        cit.echo('Select one of these:')
        selection = cit.get_choice(menu)
    return COMMANDS.get(selection)
Пример #8
0
def show_menu():
    """Show commands menu

    returns:
        a callable function name
    """
    commands = collections.OrderedDict({
        'Install Requirements Modules': requirements_install,
        'Make & migrate database': migrate_db,
        'Create superuser account': create_superuser,
        'Runserver (localhost:8000)': runserver_dev,
        'Runserver (LAN ip:8000)': runserver_lan,
        'Shell: Interactive': interactive_shell,
        'Shell: Database': db_shell,
        'Django system check': system_check,
        'Exit': cit.bye,
    })
    cit.echo('Select one of these:')
    selection = cit.get_choice(sorted(commands.keys()))
    return commands.get(selection)
Пример #9
0
    def updateFile(cls, file_, url):
        """Check and update file compares with remote_url

        Args:
            file_: str. Local filename. Normally it's __file__
            url: str. Remote url of raw file content. Normally it's https://raw.github.com/...
        Returns:
            bool: file updated or not
        """
        def compare(s1, s2):
            return s1 == s2, len(s2) - len(s1)

        if not url or not file_:
            return False
        try:
            req = urllib.request.urlopen(url)
            raw_codes = req.read()
            with open(file_, 'rb') as f:
                current_codes = f.read().replace(b'\r', b'')
            is_same, diff = compare(current_codes, raw_codes)
            if is_same:
                cit.info("{} is already up-to-date.".format(file_))
                return False
            else:
                cit.ask("A new version is available. Update? (Diff: {})".format(diff))
                if cit.get_choice(['Yes', 'No']) == 'Yes':
                    with open(file_, 'wb') as f:
                        f.write(raw_codes)
                    cit.info("Update Success.")
                    return True
                else:
                    cit.warn("Update Canceled")
                    return False
        except Exception as e:
            cit.err("{f} update failed: {e}".format(f=file_, e=e))
            return False
Пример #10
0
    '184.51.198.73',
    '213.248.126.138',
    '213.248.126.137',
    '213.248.126.155',
    '111.108.54.16',
    '52.76.139.242',
]
if not ip_list:
    cit.err('Ip List is empty').bye()
vpn_route = '10.100.0.1'  # duetime
cit.info('VPN route = {}'.format(vpn_route))

# get mode, delete / set / print
available_modes = ['set', 'delete', 'print']
cit.ask("Choose mode:")
mode = cit.get_choice(available_modes)
if mode not in available_modes:
    cit.err('Mode {} is not supported, available modes: {}'.format(mode, available_modes)).bye()
cit.info('Mode = {}'.format(mode))

if mode == 'set':
    for ip in ip_list:
        cmd = 'route add {ip} mask 255.255.255.255 {vpn_route}'.format(vpn_route=vpn_route, ip=ip)
        ktk.runCmd(cmd)
elif mode == 'delete':
    for ip in ip_list:
        cmd = 'route delete {ip}'.format(ip=ip)
        ktk.runCmd(cmd)
elif mode == 'print':
    cmd = 'route print'
    ktk.runCmd(cmd)
Пример #11
0
 def test_get_choice_index(self):
     with patch("sys.stdout", new=StringIO()) as fake_out, patch("sys.stdin", new=StringIO("1\n")):
         self.assertEqual(cit.get_choice(["ABC", "DEF"]), "ABC")
         expect_word = "|  1) ABC\n|  2) DEF\n> "
         self.assertEqual(fake_out.getvalue(), expect_word)
Пример #12
0
    if sys.platform.startswith("win"):
        os.startfile(path)
    elif platform.system() == "Darwin":
        subprocess.Popen(["open", path])
    else:
        subprocess.Popen(["xdg-open", path])


if __name__ == "__main__":
    cit.info("Output Folder: {}".format(GENERATED_DIR))
    cit.info("Phrases File location: {}".format(PHRASES_DIR))
    deco = "\n| * "
    phrases_filenames = get_phrases_filenames()
    cit.info("Phrases JSON Files:")
    for filename in phrases_filenames:
        cit.echo(filename, pre="*")
    phrases_paths = [os.path.join(PHRASES_DIR, fn) for fn in phrases_filenames]
    phrases = load_all_phrases(phrases_paths)
    cit.ask("Which one you wanna convert?")
    phrsr_keys = cit.get_choices(list(AVAIL_PHRASER.keys()), allable=True)
    for key in phrsr_keys:
        cit.title("Generating {}".format(key))
        phraselet = AVAIL_PHRASER[key]
        generate_UDP_file(Phraser=phraselet['phraser'],
                          output=phraselet['output'],
                          phrases=phrases)
        cit.end()
    cit.ask("Open Output Folder?")
    if cit.get_choice(('Yes', 'No')) == 'Yes':
        show_file(GENERATED_DIR)
 def test_get_choice_2(self):
     self.fakein.write("ABC")
     self.assertEqual(cit.get_choice(["ABC", "DEF"]), "ABC")
     expect_word = "|  1) ABC\n|  2) DEF\n> "
     self.assertEqual(self.fakeout.readline(ansi=False), expect_word)
Пример #14
0
if os.path.isfile(uwsgi_xml):
    cit.info("uwsgi config file: " + uwsgi_xml)
else:
    cit.err("uwsgi config file not found: " + uwsgi_xml)
# pid file
dir_name = os.path.basename(os.path.dirname(os.path.abspath(__file__)))
pid_file = "/var/run/uwsgi_{}.pid".format(dir_name)
if os.path.exists(pid_file):
    cit.warn("uwsgi is running @ " + pid_file)
else:
    cit.info("No uwsgi running")
# choice
operations = ["start", "stop", "reload"]
oprtn = ""
if len(sys.argv) != 2:
    oprtn = cit.get_choice(operations)
elif sys.argv[1] in operations:
    oprtn = sys.argv[1]
else:
    cit.err("Wrong Params: " + sys.argv[1])
    cit.bye()

# -run commands---------------------------------------------------
if "start" == oprtn:
    ktk.runCmd("sudo echo ''")
    ktk.runCmd("sudo uwsgi -x '" + uwsgi_xml + "' --pidfile '" + pid_file + "' &")
elif "stop" == oprtn:
    ktk.runCmd("sudo uwsgi --stop " + pid_file)
elif "reload" == oprtn:
    ktk.runCmd("sudo uwsgi --reload " + pid_file)
else:
Пример #15
0
        pattern = re.compile(r': ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+).*45\.32\.45\.176\.10080')
        matches = pattern.findall(ln)
        if matches:
            key = matches[0]
            value = clients.setdefault(key, 0)
            clients[key] = value + 1

# print
clients_count = len(clients)
if clients_count == 0:
    cit.err("0 client logged").bye()
cit.title("Total: {} clients:".format(clients_count))

threshold = 5
cit.ask("See clients lower than {} ?".format(threshold))
see_all = cit.get_choice(['Yes', 'No'])
if clients:
    for (k, v) in clients.items():
        if v < threshold and see_all == 'No':
            continue
        if k == '173.230.148.199':
            k += ' (superfarmer.net)'
        if k == '106.186.20.163':
            k += ' (lnhote.me)'
        cit.info("{} : {}".format(k, v))

# clear
cit.ask("Need clear the log?")
need_clear = cit.get_choice(['Yes', 'No'])
if "Yes" == need_clear:
    ktk.runCmd("sudo echo")