Exemplo n.º 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
Exemplo n.º 2
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
Exemplo n.º 3
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])
Exemplo n.º 4
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
Exemplo n.º 5
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)))
Exemplo n.º 6
0
def run_operation(oprtn, config_file, pid_file, log_file):
    if "start" == oprtn:
        if os.path.exists(pid_file):
            cit.ask('uwsgi is already running, start a new one? (Y/n)\n(Doing this will overwrite pid_file)')
            if cit.get_input().lower() != 'y':
                cit.info('User canceled start operation')
                return False
        ktk.runCmd("sudo uwsgi -x '{c}' --pidfile '{p}' --daemonize '{d}'".format(c=config_file, p=pid_file, d=log_file))
    elif "stop" == oprtn:
        ktk.runCmd("sudo uwsgi --stop " + pid_file)
        ktk.runCmd("sudo rm " + pid_file)
    elif "reload" == oprtn:
        ktk.runCmd("sudo uwsgi --reload " + pid_file)
    elif "*** update uwsgiTool ***" == oprtn:
        update_uwsgitool()
    else:
        cit.err("Wrong operation: " + oprtn)
        cit.bye()
Exemplo n.º 7
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
Exemplo n.º 8
0
    '184.51.198.91',
    '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'
Exemplo n.º 9
0
 def test_ask(self):
     with patch("sys.stdout", new=StringIO()) as fake_out:
         cit.ask("ABC")
         self.assertEqual(fake_out.getvalue(), "| (?) ABC\n")
Exemplo n.º 10
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_ask(self):
     cit.ask("ABC")
     self.assertEqual(self.fakeout.readline(ansi=False), "| (?) ABC\n")
Exemplo n.º 12
0
    for ln in f:
        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: