Esempio n. 1
0
def add(name, connection_uri, id_file="", o=[], config=None):
    """
    Adds a new entry to sshconfig.
    """
    storm_ = get_storm_instance(config)

    try:

        # validate name
        if '@' in name:
            raise ValueError('invalid value: "@" cannot be used in name.')

        user, host, port = parse(connection_uri,
                                 user=get_default("user", storm_.defaults),
                                 port=get_default("port", storm_.defaults))

        storm_.add_entry(name, host, user, port, id_file, o)

        print(
            get_formatted_message(
                '{0} added to your ssh config. you can connect '
                'it by typing "ssh {0}".'.format(name), 'success'))

    except ValueError as error:
        print(get_formatted_message(error, 'error'), file=sys.stderr)
Esempio n. 2
0
def add(name, connection_uri, id_file="", o=[], config=None):
    """
    Adds a new entry to sshconfig.
    """
    storm_ = get_storm_instance(config)

    try:

        # validate name
        if '@' in name:
            raise ValueError('invalid value: "@" cannot be used in name.')

        user, host, port = parse(
            connection_uri,
            user=get_default("user", storm_.defaults),
            port=get_default("port", storm_.defaults)
        )

        storm_.add_entry(name, host, user, port, id_file, o)

        print(get_formatted_message('{0} added to your ssh config. you can connect it by typing "ssh {0}".'.format(

            name
        ), 'success'))

    except ValueError as error:
        print(get_formatted_message(error, 'error'), file=sys.stderr)
Esempio n. 3
0
def get_ip_(name, glob, uri, config):
    # TODO: add user@hostname connection output
    storm_ = get_storm_instance(config)

    if uri:
        res = storm_.list_entries(search=name)
        if res:
            for entry in res:
                # host = entry.get('host')
                _user = entry.get("options").get(
                    "user", get_default("user", storm_.defaults)
                )
                _host = entry.get("options").get("hostname", "[hostname_not_specified]")
                _port = entry.get("options").get(
                    "port", get_default("port", storm_.defaults)
                )
                print(colored(f"{_user}@{_host}:{_port}", "green"))
        else:
            cprint(f"No entry found matching '{name}'", "error")
    else:
        ips = storm_.get_hostname(name, glob=glob)
        if ips:
            for ip in ips:
                print(colored(ip, "green"))
        else:
            cprint(f"No entry found matching '{name}'", "error")
Esempio n. 4
0
def list(config=None):
    """
    Lists all hosts from ssh config.
    """
    storm_ = get_storm_instance(config)

    try:
        result = colored('Listing entries:', 'white', attrs=["bold", ]) + "\n\n"
        result_stack = ""
        for host in storm_.list_entries(True):

            if host.get("type") == 'entry':
                if not host.get("host") == "*":
                    result += "    {0} -> {1}@{2}:{3}".format(
                        colored(host["host"], 'green', attrs=["bold", ]),
                        host.get("options").get("user", get_default("user", storm_.defaults)),
                        host.get("options").get("hostname", "[hostname_not_specified]"),
                        host.get("options").get("port", get_default("port", storm_.defaults))
                    )

                    extra = False
                    for key, value in six.iteritems(host.get("options")):

                        if not key in ["user", "hostname", "port"]:
                            if not extra:
                                custom_options = colored('\n\t[custom options] ', 'white')
                                result += " {0}".format(custom_options)
                            extra = True

                            if isinstance(value, collections.Sequence):
                                if isinstance(value, builtins.list):
                                    value = ",".join(value)
                                    
                            result += "{0}={1} ".format(key, value)
                    if extra:
                        result = result[0:-1]

                    result += "\n\n"
                else:
                    result_stack = colored("   (*) General options: \n", "green", attrs=["bold",])
                    for key, value in six.iteritems(host.get("options")):
                        if isinstance(value, type([])):
                            result_stack += "\t  {0}: ".format(colored(key, "magenta"))
                            result_stack += ', '.join(value)
                            result_stack += "\n"
                        else:
                            result_stack += "\t  {0}: {1}\n".format(
                                colored(key, "magenta"),
                                value,
                            )
                    result_stack = result_stack[0:-1] + "\n"

        result += result_stack
        print(get_formatted_message(result, ""))
    except Exception as error:
        print(get_formatted_message(str(error), 'error'), file=sys.stderr)
Esempio n. 5
0
def edit_(name, connection_uri, id_file, options, config):
    options = [i for i in options]

    storm_ = get_storm_instance(config)

    try:
        if "," in name:
            name = " ".join(name.split(","))

        user, host, port = parse(
            connection_uri,
            user=get_default("user", storm_.defaults),
            port=get_default("port", storm_.defaults),
        )
        storm_.edit_entry(name, host, user, port, id_file, options)
        cprint(f"'{name}' updated successfully.", "success")
    except ValueError as error:
        cprint(error, "error")
        sys.exit(1)
Esempio n. 6
0
def edit(name, connection_uri, id_file="", o=[], config=None):
    """
    Edits the related entry in ssh config.
    """
    storm_ = get_storm_instance(config)

    try:
        if ',' in name:
            name = " ".join(name.split(","))

        user, host, port = parse(connection_uri,
                                 user=get_default("user", storm_.defaults),
                                 port=get_default("port", storm_.defaults))

        storm_.edit_entry(name, host, user, port, id_file, o)
        print(
            get_formatted_message('"{0}" updated successfully.'.format(name),
                                  'success'))
    except ValueError as error:
        print(get_formatted_message(error, 'error'), file=sys.stderr)
Esempio n. 7
0
def add_(name, connection_uri, copy_id, id_file, options, config):
    options = [i for i in options]
    storm_ = get_storm_instance(config)

    try:
        if "@" in name:
            raise InvalidValueError

        user, host, port = parse(
            connection_uri,
            user=get_default("user", storm_.defaults),
            port=get_default("port", storm_.defaults),
        )

        storm_.add_entry(name, host, user, port, id_file, options)

        try:
            if copy_id:
                if ping(host):
                    ret = ssh_copy_id(name)
                    if ret:
                        cprint(f"ssh key added to host '{name}'", "success")
                else:
                    cprint(
                        f"Could not add ssh key to host '{name}', The host is not reachable",
                        "error",
                    )

        except Exception as error:
            cprint(str(error), "error")
            sys.exit(1)

        cprint(
            f"'{name}' added to your ssh config. "
            f"you can connect to it by typing \nssh {name}",
            "success",
        )

    except ValueError as error:
        cprint(str(error), "error")
        sys.exit(1)
Esempio n. 8
0
def edit(name, connection_uri, id_file="", o=[], config=None):
    """
    Edits the related entry in ssh config.
    """
    storm_ = get_storm_instance(config)

    try:
        if ',' in name:
            name = " ".join(name.split(","))

        user, host, port = parse(
            connection_uri,
            user=get_default("user", storm_.defaults),
            port=get_default("port", storm_.defaults)
        )

        storm_.edit_entry(name, host, user, port, id_file, o)
        print(get_formatted_message(
            '"{0}" updated successfully.'.format(
                name
            ), 'success'))
    except ValueError as error:
        print(get_formatted_message(error, 'error'), file=sys.stderr)
Esempio n. 9
0
def list(config=None):
    """
    Lists all hosts from ssh config.
    """
    storm_ = get_storm_instance(config)

    try:
        result = colored('Listing entries:', 'white', attrs=[
            "bold",
        ]) + "\n\n"
        result_stack = ""
        for host in storm_.list_entries(True):

            if host.get("type") == 'entry':
                if not host.get("host") == "*":
                    result += "    {0} -> {1}@{2}:{3}".format(
                        colored(host["host"], 'green', attrs=[
                            "bold",
                        ]),
                        host.get("options").get(
                            "user", get_default("user", storm_.defaults)),
                        host.get("options").get("hostname",
                                                "[hostname_not_specified]"),
                        host.get("options").get(
                            "port", get_default("port", storm_.defaults)))

                    extra = False
                    for key, value in six.iteritems(host.get("options")):

                        if not key in ["user", "hostname", "port"]:
                            if not extra:
                                custom_options = colored(
                                    '\n\t[custom options] ', 'white')
                                result += " {0}".format(custom_options)
                            extra = True

                            if isinstance(value, collections.Sequence):
                                if isinstance(value, builtins.list):
                                    value = ",".join(value)

                            result += "{0}={1} ".format(key, value)
                    if extra:
                        result = result[0:-1]

                    result += "\n\n"
                else:
                    result_stack = colored("   (*) General options: \n",
                                           "green",
                                           attrs=[
                                               "bold",
                                           ])
                    for key, value in six.iteritems(host.get("options")):
                        if isinstance(value, type([])):
                            result_stack += "\t  {0}: ".format(
                                colored(key, "magenta"))
                            result_stack += ', '.join(value)
                            result_stack += "\n"
                        else:
                            result_stack += "\t  {0}: {1}\n".format(
                                colored(key, "magenta"),
                                value,
                            )
                    result_stack = result_stack[0:-1] + "\n"

        result += result_stack
        print(get_formatted_message(result, ""))
    except Exception as error:
        print(get_formatted_message(str(error), 'error'), file=sys.stderr)
Esempio n. 10
0
def list_items_(name, config):
    storm_ = get_storm_instance(config)
    col = HostColors()

    try:
        padding = storm_.get_padding()
        head = "Listing entries: "
        if not name:
            head += "All"
            entry_list = storm_.list_entries(order=True)
            cprint(colored(head, "cyan"))
        else:
            entry_list = storm_.list_entries(order=True, search=name[0])
            if entry_list:
                head += f"Matching '{name[0]}'"
                cprint(colored(head, "cyan"))
            else:
                cprint(f"Could not find entries matching '{name[0]}'.", "error")
                return

        result, result_stack = "", ""
        for host in entry_list:
            if host.get("type") == "entry":
                if not host.get("host") == "*":
                    _user = host.get("options").get(
                        "user", get_default("user", storm_.defaults)
                    )
                    _host = host.get("options").get(
                        "hostname", "[hostname_not_specified]"
                    )
                    _port = host.get("options").get(
                        "port", get_default("port", storm_.defaults)
                    )
                    result += (
                        f"{colored(host['host'].ljust(padding), 'green')}"
                        f"\t->\t"
                        f"{colored(_user, col.user(_user))}"
                        f"{colored('@', 'green')}"
                        f"{colored(_host, col.host(_host))}"
                        f"{colored(':', 'green')}"
                        f"{colored(_port, col.port(_port))}"
                    )
                    extra = False
                    for key, value in six.iteritems(host.get("options")):
                        if key not in ["user", "hostname", "port"]:
                            if not extra:
                                custom_options = colored("\t[options] ", "white")
                                result += " {0}".format(custom_options)
                            extra = True
                            if isinstance(value, Sequence):
                                if isinstance(value, builtins.list):
                                    value = ",".join(value)
                            result += "{0}={1} ".format(key, value)
                    if extra:
                        result = result[0:-1]
                    result += "\n"  # \n
                else:
                    result_stack = colored(
                        "   (*) General options: \n",
                        "green",
                        attrs=[
                            "bold",
                        ],
                    )
                    for key, value in six.iteritems(host.get("options")):
                        if isinstance(value, type([])):
                            result_stack += "\t  {0}: ".format(colored(key, "magenta"))
                            result_stack += ", ".join(value)
                            result_stack += "\n"
                        else:
                            result_stack += "\t  {0}: {1}\n".format(
                                colored(key, "magenta"),
                                value,
                            )
                    result_stack = result_stack[0:-1] + "\n"
        result += result_stack
        cprint(result)
    except ValueError as error:
        cprint(str(error), "error")
        sys.exit(1)
Esempio n. 11
0
def list(config=None):
    """
    Lists all hosts from ssh config.
    """
    storm_ = get_storm_instance(config)

    try:
        result = colored('Listing entries:', 'white', attrs=[
            "bold",
        ]) + "\n\n"
        result_stack = ""
        for host in storm_.list_entries(True):
            if host.get("type") == 'entry':
                if not host.get("host") == "*":
                    myhost = host["host"]
                    user = host.get("options").get(
                        "user", get_default("user", storm_.defaults))
                    hostname = host.get("options").get("hostname", myhost)
                    port = host.get("options").get(
                        "port", get_default("port", storm_.defaults))
                    proxy = colored(host.get("options").get("proxyjump", None),
                                    'green',
                                    attrs=[
                                        "bold",
                                    ])
                    myhost = colored(host["host"], 'green', attrs=[
                        "bold",
                    ])
                    agent = ''
                    control = ''
                    if host.get("options").get("forwardagent", None):
                        agent = colored('agent', 'red', attrs=[
                            "bold",
                        ])
                    if host.get("options").get("controlmaster", None):
                        control = colored('control', 'red', attrs=[
                            "bold",
                        ])
                    #control = colored(host.get("options").get("controlmaster", None), 'red', attrs=["bold", ])

                    if host.get("options").get("proxyjump", None):
                        result += "    {0} -> {1}@{2}:{3} via {4} {5} {6}".format(
                            myhost, user, hostname, port, proxy, agent,
                            control)
                    else:
                        result += "    {0} -> {1}@{2}:{3} {4} {5}".format(
                            myhost, user, hostname, port, agent, control)

                    extra = False
                    for key, value in six.iteritems(host.get("options")):

                        if not key in [
                                "user", "hostname", "port", "proxyjump"
                        ]:
                            if not extra:
                                custom_options = colored(
                                    '\n\t[custom options] ', 'white')
                                result += " {0}".format(custom_options)
                            extra = True

                            if isinstance(value, collections.Sequence):
                                if isinstance(value, builtins.list):
                                    value = ",".join(value)

                            result += "{0}={1} ".format(key, value)
                    if extra:
                        result = result[0:-1]

                    result += "\n\n"
                else:
                    result_stack = colored("   (*) General options: \n",
                                           "green",
                                           attrs=[
                                               "bold",
                                           ])
                    for key, value in six.iteritems(host.get("options")):
                        if isinstance(value, type([])):
                            result_stack += "\t  {0}: ".format(
                                colored(key, "magenta"))
                            result_stack += ', '.join(value)
                            result_stack += "\n"
                        else:
                            result_stack += "\t  {0}: {1}\n".format(
                                colored(key, "magenta"),
                                value,
                            )
                    result_stack = result_stack[0:-1] + "\n"
        result += result_stack
        print(get_formatted_message(result, ""))
    except Exception as error:
        print(get_formatted_message(str(error), 'error'), file=sys.stderr)
        sys.exit(1)
Esempio n. 12
0
def format_host(host, defaults, with_tags=False, compact_tags=False):
    result = ""
    result_stack = ""
    if host.get("type") == 'entry':
        if not host.get("host") == "*":
            result += "    {0} -> {1}@{2}:{3}".format(
                colored(host["host"], 'green', attrs=[
                    "bold",
                ]),
                host.get("options").get("user", get_default("user", defaults)),
                host.get("options").get("hostname",
                                        "[hostname_not_specified]"),
                host.get("options").get("port", get_default("port", defaults)))
            extra = False
            for key, value in six.iteritems(host.get("options")):

                if not key in ["user", "hostname", "port"]:
                    if not extra:
                        custom_options = colored('\n\t[custom options] ',
                                                 'white')
                        result += " {0}".format(custom_options)
                    extra = True

                    if isinstance(value, collections.Sequence):
                        if isinstance(value, builtins.list):
                            value = ",".join(value)

                    result += "{0}={1} ".format(key, value)
            if extra:
                result = result[0:-1]

            if with_tags:
                if len(host.get('tags')) > 0:
                    if compact_tags:
                        result += " {0}".format('')
                        value = " ".join(
                            map(
                                lambda tag: colored(
                                    tag, 'green', attrs=[
                                        "bold",
                                    ]), host.get('tags')))
                        result += "{0} ".format(value)
                    else:
                        tags = colored('\n\t[tags] ', 'white')
                        result += " {0}".format(tags)
                        value = ", ".join(host.get('tags'))
                        result += "{0} ".format(value)

            result += "\n\n"
        elif host.get("options") != {}:
            result_stack = colored("   (*) General options: \n",
                                   "green",
                                   attrs=[
                                       "bold",
                                   ])
            for key, value in six.iteritems(host.get("options")):
                if isinstance(value, type([])):
                    result_stack += "\t  {0}: ".format(colored(key, "magenta"))
                    result_stack += ', '.join(value)
                    result_stack += "\n"
                else:
                    result_stack += "\t  {0}: {1}\n".format(
                        colored(key, "magenta"),
                        value,
                    )
            result_stack = result_stack[0:-1] + "\n"
        result += result_stack
    return result