Beispiel #1
0
def xmkdir(host, path):
    try:
        hosts = ssh_config()
        r = hosts.execute(host, "mkdir -p {0}".format(path))
        print(r)
    except Exception as e:
        print(e)
    def do_ssh(self, args, arguments):
        """
        ::

            Usage:
                ssh list [--format=FORMAT]
                ssh register NAME PARAMETERS
                ssh ARGUMENTS


            conducts a ssh login on a machine while using a set of
            registered machines specified in ~/.ssh/config

            Arguments:

              NAME        Name or ip of the machine to log in
              list        Lists the machines that are registered and
                          the commands to login to them
              PARAMETERS  Register te resource and add the given
                          parameters to the ssh config file.  if the
                          resoource exists, it will be overwritten. The
                          information will be written in /.ssh/config

            Options:

               -v       verbose mode
               --format=FORMAT   the format in which this list is given
                                 formats incluse table, json, yaml, dict
                                 [default: table]

               --user=USER       overwrites the username that is
                                 specified in ~/.ssh/config

               --key=KEY         The keyname as defined in the key list
                                 or a location that contains a pblic key

        """
        # pprint(arguments)
        if arguments["list"]:
            output_format = arguments["--format"]
            Console.ok('list {}'.format(output_format))
            hosts = ssh_config()
            print(hosts.list())
            TOTO("Complete implementation with dict_printer")
        elif arguments["register"]:
            name = arguments["NAME"]
            parameters = arguments["PARAMETERS"]
            Console.ok('register {} {}'.format(name, parameters))
            TODO("Not implemented")
        else:  # ssh ARGUMENTS...
            args = arguments["ARGUMENTS"]
            os.system("ssh {}".format(args))
            return
Beispiel #3
0
    def load(self, yaml_filename=None):
        """
        Loads the cloudmesh pbs yaml file.

        :param yaml_filename: The filename of the yaml file
        """
        log.debug("PBS yaml filename: {0}".format(self.yaml_filename))
        if yaml_filename is None:
            yaml_filename = self.yaml_filename
        else:
            self.yaml_filename = config_file(yaml_filename)
        self.data = ConfigDict(filename=self.yaml_filename)
        self.hosts = ssh_config()
Beispiel #4
0
    def load(self, yaml_filename=None):
        """
        Loads the cloudmesh pbs yaml file.

        :param yaml_filename: The filename of the yaml file
        """
        log.debug("PBS yaml filename: {0}".format(self.yaml_filename))
        if yaml_filename is None:
            yaml_filename = self.yaml_filename
        else:
            self.yaml_filename = config_file(yaml_filename)
        self.data = ConfigDict(filename=self.yaml_filename)
        self.hosts = ssh_config()
Beispiel #5
0
    def __init__(self, context):
        cmd.Cmd.__init__(self)
        self.command_topics = {}
        self.register_topics()
        self.context = context
        if self.context.debug:
            print("init CloudmeshConsole")

        self.prompt = 'cm> '

        self.banner = textwrap.dedent("""
            +=======================================================+
            .   ____ _                 _                     _      .
            .  / ___| | ___  _   _  __| |_ __ ___   ___  ___| |__   .
            . | |   | |/ _ \| | | |/ _` | '_ ` _ \ / _ \/ __| '_ \  .
            . | |___| | (_) | |_| | (_| | | | | | |  __/\__ \ | | | .
            .  \____|_|\___/ \__,_|\__,_|_| |_| |_|\___||___/_| |_| .
            +=======================================================+
                                 Cloudmesh Shell
            """)
        # KeyCommands.__init__(self, context)

        #
        # set default cloud and default group if they do not exist
        # use the first cloud in cloudmesh.yaml as default
        #

        filename = path_expand("~/.cloudmesh/cloudmesh.yaml")
        create_cloudmesh_yaml(filename)

        # sys,exit(1)

        value = Default.get('cloud', cloud='general')
        if value is None:
            clouds = ConfigDict(filename=filename)["cloudmesh"]["clouds"]
            cloud = clouds.keys()[0]
            Default.set('cloud', cloud, cloud='general')

        value = Default.get('default', cloud='general')
        if value is None:
            Default.set('default', 'default', cloud='general')

        cluster = 'india'  # hardcode a value if not defined
        value = Default.get('cluster', cloud='general')
        if value is None:
            try:
                hosts = ssh_config().names()
                if hosts is not None:
                    cluster = hosts[0]
            except:
                pass  # use the hardcoded cluster

        else:
            cluster = value
        Default.set('cluster', cluster, cloud='general')

        #
        # Read cloud details from yaml file
        #
        filename = 'cloudmesh.yaml'
        config = ConfigDict(filename=filename)["cloudmesh"]
        clouds = config["clouds"]

        defaults = {'clouds': {},
                    'key': {}}

        for cloud in clouds:
            if "default" in config['clouds'][cloud]:
                defaults['clouds'][cloud] = config["clouds"][cloud]['default']

        if "default" in config["keys"]:
            defaults["keys"] = config["keys"]["default"]
        else:
            defaults['key'] = None

        for cloud in defaults["clouds"]:
            for default, value in defaults["clouds"][cloud].iteritems():
                Default.set(default, value, cloud=cloud)

        for c in CloudmeshConsole.__bases__[1:]:
            # noinspection PyArgumentList
            c.__init__(self, context)
Beispiel #6
0
    def do_ssh(self, args, arguments):
        """
        ::

            Usage:
                ssh table
                ssh list [--format=FORMAT]
                ssh cat
                ssh register NAME PARAMETERS
                ssh ARGUMENTS


            conducts a ssh login on a machine while using a set of
            registered machines specified in ~/.ssh/config

            Arguments:

              NAME        Name or ip of the machine to log in
              list        Lists the machines that are registered and
                          the commands to login to them
              PARAMETERS  Register te resource and add the given
                          parameters to the ssh config file.  if the
                          resoource exists, it will be overwritten. The
                          information will be written in /.ssh/config

            Options:

               -v       verbose mode
               --format=FORMAT   the format in which this list is given
                                 formats incluse table, json, yaml, dict
                                 [default: table]

               --user=USER       overwrites the username that is
                                 specified in ~/.ssh/config

               --key=KEY         The keyname as defined in the key list
                                 or a location that contains a pblic key

            Description:

                ssh list
                    lists the hostsnames  that are present in the
                    ~/.ssh/config file

                ssh cat
                    prints the ~/.ssh/config file

                ssh table
                    prints contents of the ~/.ssh/config file in table format

                ssh register NAME PARAMETERS
                    registers a host i ~/.ssh/config file
                    Parameters are attribute=value pairs
                    Note: Note yet implemented

                ssh ARGUMENTS
                    executes the ssh command with the given arguments
                    Example:
                        ssh myhost

                            conducts an ssh login to myhost if it is defined in
                            ~/.ssh/config file
        """
        # pprint(arguments)

        def read(filename="~/.ssh/config"):
            with open(path_expand("~/.ssh/config"), "r") as f:
                content = f.readlines()
            return "".join(content)

        if arguments["list"]:

            output_format = arguments["--format"]
            banner("List SSH config hosts")
            hosts = ssh_config()
            for host in hosts.list():
                print(host)

        elif arguments["table"]:

            content = read(filename="~/.ssh/config").split("\n")

            entries = []

            def empty():
                return {
                    "host": None,
                    "hostname": None,
                    "user": None,
                    "proxycommand": None,
                    "serveraliveinterval": None,
                    "localforward": None,
                    "forwardx11": None,
                }

            entry = empty()
            for line in content:
                line = line.strip()
                if line.startswith("#"):
                    pass
                elif line.strip() == "":
                    pass
                elif "Host " in line:
                    hostname = line.strip().split("Host")[1]
                    entry["host"] = hostname.strip()
                    if entry is not None:
                        entries.append(entry)
                    entry = empty()
                else:
                    attribute, value = line.strip().split(" ", 1)
                    entry[attribute.lower()] = value.strip()

            pprint(entries)
            order = ["host", "hostname", "user", "proxycommand", "serveraliveinterval", "localforward", "forwardx11"]

            print(list_printer(entries, order=order))

        elif arguments["cat"]:

            print(read(filename="~/.ssh/config"))

        elif arguments["register"]:

            name = arguments["NAME"]
            parameters = arguments["PARAMETERS"]
            Console.ok("register {} {}".format(name, parameters))
            TODO.implement("Not implemented")

        else:  # ssh ARGUMENTS...

            args = arguments["ARGUMENTS"]
            os.system("ssh {}".format(args))
            return ""

        return ""