• aard@kyu.de
    link
    fedilink
    arrow-up
    4
    ·
    1 year ago

    I assume you mean “lookup”, as import doesn’t really make much sense.

    I’m currently using this with wofi, though I’ll eventually rewrite it as anyrun plugin, which provides a bit more control:

    #!/usr/bin/env python3
    from argparse import ArgumentParser
    import subprocess
    import json
    import os
     
    ssh_config_file = "~/.ssh/config"
    ssh_known_hosts_file = "~/.ssh/known_hosts"
     
    # Returns a list of all hosts
    def get_hosts():
     
        hosts = []
     
        with open(os.path.expanduser(ssh_config_file)) as f:
            content = f.readlines()
     
        for line in content:
            line = line.lstrip()
            # Ignore wildcards
            if line.startswith('Host ') and not '*' in line:
                for host in line.split()[1:]:
                    hosts.append(host)
     
        # Removes duplicate entries
        hosts = sorted(set(hosts))
     
        return hosts
     
    def get_known_hosts():
     
        hosts = []
     
        with open(os.path.expanduser(ssh_known_hosts_file)) as f:
            content = f.readlines()
     
        for line in content:
            line = line.lstrip()
            host_entry = line.partition(" ")[0]
            hosts.append(host_entry.partition(",")[0])
     
        # Removes duplicate entries
        hosts = sorted(set(hosts))
     
        return hosts
     
    # Returns a newline seperated UFT-8 encoded string of all ssh hosts
    def parse_hosts(hosts):
        return "\n".join(hosts).encode("UTF-8")
     
    # Executes wofi with the given input string
    def show_wofi(command, hosts):
     
        process = subprocess.Popen(command,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
        ret = process.communicate(input=hosts)
        host, rest = ret
        return host
     
    # Switches the focus to the given id
    def ssh_to_host(host, terminal, ssh_command):
     
        if "]:" in host:
            host, port = host[1:].split("]:")
            command = "{terminal} \'{ssh_command} {host} -p {port}\'".format(terminal=terminal, ssh_command=ssh_command, host=host, port=port)
        else:
            command = "{terminal} \'{ssh_command} {host}\'".format(terminal=terminal, ssh_command=ssh_command, host=host)
     
        process = subprocess.Popen(command,shell=True)
     
    # Entry point
    if __name__ == "__main__":
     
        parser = ArgumentParser(description="Wofi based ssh launcher")
        parser.add_argument("terminal", help='Terminal command to use')
        parser.add_argument("--ssh-command", dest='ssh_command', default='ssh', help='ssh command to use (default=ssh)')
        parser.add_argument("--mode", dest='mode', default='known_hosts', help='where to read from (default=known_hosts)')
        parser.add_argument("--command", default='wofi -p \"SSH hosts: \" -d -i --hide-scroll', help='launcher command to use')
        args = parser.parse_args()
     
        if (args.mode == "config"):
            hosts = get_hosts()
        elif (args.mode == "known_hosts"):
            hosts = get_known_hosts()
     
        parsed_hosts = parse_hosts(hosts)
     
        selected = show_wofi(args.command, parsed_hosts)
     
        selected_host = selected.decode('utf-8').rstrip()
     
        if selected_host != "":
            ssh_to_host(selected_host, args.terminal, args.ssh_command)