Example #1
0
    def test09_type(self):
        HEADING()
        print("Find key type of {0}:".format(self.mykey), keytype(self.mykey))
        for name in self.key_store.names():
            print(name)
            value = self.key_store[name]
            print(keytype(name), name, value)

        assert True
Example #2
0
    def test09_type(self):
        HEADING()
        print("Find key type of {0}:".format(self.mykey), keytype(self.mykey))
        for name in self.key_store.names():
            print(name)
            value = self.key_store[name]
            print(keytype(name), name, value)

        assert True
Example #3
0
    def initialize_user(self):
        self.set_credentials()
        element = {
            "firstname": self.profile["firstname"],
            "lastname": self.profile["lastname"],
            "uidNumber": self.profile["uid"],
            "phone": self.profile["phone"],
            "gidNumber": self.profile["gid"],
            "address": self.profile["address"][0],
            "cm_user_id": self.config.get("cloudmesh.hpc.username"),
            "email": self.profile["email"],
            "activeclouds": self.config.get("cloudmesh.active")
        }

        projects = {}

        active = self.config.get("cloudmesh.projects.active")

        if active != ['None']:
            projects["active"] = active

        completed = self.config.get("cloudmesh.projects.completed")
        if completed != ['None']:
            projects["completed"] = completed

        if projects != {}:
            element["projects"] = projects

        # get keys and clean the key titles (replace '.' with '_' due
        # to mongo restriction)
        keys = self.config.get("cloudmesh.keys.keylist")
        for keytitle in keys.keys():
            keycontent = keys[keytitle]
            if keytype(keycontent) == "file":
                keycontent = get_key_from_file(keycontent)
                if keycontent:
                    keycontent = keycontent.strip()
                    keys[keytitle] = keycontent
                else:
                    print(
                        "The specified key file does not exist and thus ingored!"
                    )
                    print("You can run ssh-keygen to generate one key pair")
                    del keys[keytitle]
                    break
            if "." in keytitle:
                newkeytitle = keytitle.replace(".", "_")
                del keys[keytitle]
                keys[newkeytitle] = keycontent
        element['keys'] = keys

        pprint(element)

        # hpc username as key
        username = element["cm_user_id"]
        # populate the local userinfo into the same mongo as though it
        # were from LDAP.
        userstore = cm_userLDAP()
        userstore.updates(username, element)

        self.user_obj = cm_user()
        self.user_obj.init_defaults(username)

        #
        # info disabled due to NameError: global name 'info' is not
        # defined info(username)
        # ------------------------------------------------------------------------------
        # added by Mark X. on Aug.25 2014 add clouds information to
        # mongo when initialize user iformation in mongo

        self.mongo.db_clouds.remove({
            'cm_kind': 'cloud',
            'cm_user_id': username
        })

        cloudsdict = self.config.get("cloudmesh", "clouds")

        for key in cloudsdict:
            Database.import_cloud_to_mongo(cloudsdict[key], key, username)
            print("cloud '{0}' added.".format(key))
Example #4
0
    def initialize_user(self):
        self.set_credentials()
        element = {
            "firstname": self.profile["firstname"],
            "lastname": self.profile["lastname"],
            "uidNumber": self.profile["uid"],
            "phone": self.profile["phone"],
            "gidNumber": self.profile["gid"],
            "address": self.profile["address"][0],
            "cm_user_id": self.config.get("cloudmesh.hpc.username"),
            "email": self.profile["email"],
            "activeclouds": self.config.get("cloudmesh.active")
        }

        projects = {}

        active = self.config.get("cloudmesh.projects.active")

        if active != ['None']:
            projects["active"] = active

        completed = self.config.get("cloudmesh.projects.completed")
        if completed != ['None']:
            projects["completed"] = completed

        if projects != {}:
            element["projects"] = projects

        # get keys and clean the key titles (replace '.' with '_' due
        # to mongo restriction)
        keys = self.config.get("cloudmesh.keys.keylist")
        for keytitle in keys.keys():
            keycontent = keys[keytitle]
            if keytype(keycontent) == "file":
                keycontent = get_key_from_file(keycontent)
                if keycontent:
                    keycontent = keycontent.strip()
                    keys[keytitle] = keycontent
                else:
                    print("The specified key file does not exist and thus ingored!")
                    print("You can run ssh-keygen to generate one key pair")
                    del keys[keytitle]
                    break
            if "." in keytitle:
                newkeytitle = keytitle.replace(".", "_")
                del keys[keytitle]
                keys[newkeytitle] = keycontent
        element['keys'] = keys

        pprint(element)

        # hpc username as key
        username = element["cm_user_id"]
        # populate the local userinfo into the same mongo as though it
        # were from LDAP.
        userstore = cm_userLDAP()
        userstore.updates(username, element)

        self.user_obj = cm_user()
        self.user_obj.init_defaults(username)

        #
        # info disabled due to NameError: global name 'info' is not
        # defined info(username)
        # ------------------------------------------------------------------------------
        # added by Mark X. on Aug.25 2014 add clouds information to
        # mongo when initialize user iformation in mongo

        self.mongo.db_clouds.remove({
            'cm_kind': 'cloud',
            'cm_user_id': username
        })

        cloudsdict = self.config.get("cloudmesh", "clouds")

        for key in cloudsdict:
            Database.import_cloud_to_mongo(cloudsdict[key], key, username)
            print("cloud '{0}' added.".format(key))
Example #5
0
    def do_key(self, args, arguments):
        """
        ::

          Usage:
                   key -h|--help
                   key list [--source=SOURCE] [--dir=DIR] [--format=FORMAT]
                   key add [--keyname=KEYNAME] FILENAME
                   key default [KEYNAME]
                   key delete KEYNAME

            Manages the keys

            Arguments:

              SOURCE         mongo, yaml, ssh
              KEYNAME        The name of a key
              FORMAT         The format of the output (table, json, yaml)
              FILENAME       The filename with full path in which the key
                             is located

            Options:

               --dir=DIR            the directory with keys [default: ~/.ssh]
               --format=FORMAT      the format of the output [default: table]
               --source=SOURCE      the source for the keys [default: mongo]
               --keyname=KEYNAME    the name of the keys

            Description:


            key list --source=ssh  [--dir=DIR] [--format=FORMAT]

               lists all keys in the directory. If the directory is not
               specified the default will be ~/.ssh

            key list --source=yaml  [--dir=DIR] [--format=FORMAT]

               lists all keys in cloudmesh.yaml file in the specified directory.
                dir is by default ~/.cloudmesh

            key list [--format=FORMAT]

                list the keys in mongo

            key add [--keyname=keyname] FILENAME

                adds the key specifid by the filename to mongodb


            key list

                 Prints list of keys. NAME of the key can be specified

            key default [NAME]

                 Used to set a key from the key-list as the default key if NAME
                 is given. Otherwise print the current default key

            key delete NAME

                 deletes a key. In yaml mode it can delete only key that
                 are not saved in mongo

        """

        # print arguments

        def _find_keys(directory):
            return [
                file for file in listdir(expanduser(directory))
                if file.lower().endswith(".pub")
            ]

        #
        # DIR (OK)
        #

        directory = path_expand(arguments["--dir"])
        source = arguments["--source"]

        if source not in ["ssh", "yaml", "mongo"]:
            print("ERROR: source is not defined")
            return

        #
        # PRINT DICT (OK)
        #

        def _print_dict(d, header=None):
            print_format = arguments['--format']
            if print_format == "json":
                return json.dumps(d, indent=4)
            elif print_format == "yaml":
                return yaml.dump(d, default_flow_style=False)
            else:
                return two_column_table(keys, header)

        #
        # PRINT SYSTEM (OK)
        #

        if arguments["list"] and source == "ssh":

            files = _find_keys(directory)

            keys = {}
            for key in files:
                keys[key] = directory + "/" + key
            print(_print_dict(keys, header=["Key", "Location"]))

            return

        #
        # PRINT YAML (OK)
        #

        if arguments["list"] and source == "yaml":

            key_store = cm_keys_yaml()
            keynames = key_store.names()
            keys = {}
            for key in keynames:
                keys[key] = get_fingerprint(key_store[key])

            print(_print_dict(keys, header=["Key", "Fingerprint"]))

            return

        #
        # FROM HERE ON BROKEN
        #

        if arguments["list"] and source == "mongo":

            username = cm_config().username()
            key_store = cm_keys_mongo(username)
            keynames = key_store.names()

            keys = {}
            for key in keynames:

                keys[key] = key_store[key]
                if keytype(keys[key]) == 'string':
                    keys[key] = get_fingerprint(keys[key])

            print(_print_dict(keys, header=["Key", "Fingerprint"]))

            return

        # self._load_keys_from_yaml()
        # self._load_mongo()
        # self._load_keys_mongo()

        if arguments["add"] and arguments["FILENAME"]:

            username = cm_config().username()
            key_store = cm_keys_mongo(username)
            filename = arguments["FILENAME"]

            # print filename
            # file existence check moved to the util function
            # if file does not exist it will return None
            keystring = get_key_from_file(filename)
            if keystring:
                keystring = keystring.strip()
                keysegments = key_parse(keystring)
                # key valid?
                if key_validate("string", keystring):
                    if arguments["--keyname"]:
                        keyname = arguments["--keyname"]
                    else:
                        # get keyname from the comment field of key
                        keyname = keysegments[2]
                        # in case a comment field is really missing
                        # use a timestamp for uniqueness
                        if keyname is None:
                            tstamp = datetime.now().strftime("%Y%m%d%H%M%S")
                            keyname = tstamp
                        # sanitize the key name for mongo use
                        else:
                            keyname = re.sub(r'@|-|\.', '_', keysegments[2])
                    key_store[keyname] = keystring
                else:
                    print("ERROR: INVALID key. Please verify!")
            else:
                print("ERROR: INVALID filename provided!")

            return
            """
            def func():
                if arguments["KEY"]:
                    key_store.__setitem__(
                        arguments["NAME"], arguments["KEY"])
                else:
                    files = _find_keys(directory)

                    result = menu_return_num(
                        title="Select a public key", menu_list=files, tries=3)
                    if result == 'q':
                        return
                    else:
                        key_store.__setitem__(arguments["NAME"],
                                                  "{0}/{1}".format(directory,files[result]))

            if arguments["NAME"] in key_store.names():
                if yn_choice("key {0} exists, update?"
                             .format(arguments["NAME"]), default='n'):
                    print "Updating key {0} ...".format(arguments["NAME"])
                    func()
                else:
                    return
            else:
                print "adding key {0} ...".format(arguments["NAME"])
                func()
            """

        if arguments["default"]:
            username = cm_config().username()
            key_store = cm_keys_mongo(username)
            # print key_store.names()
            # no name provided, will get current default key
            if not arguments["KEYNAME"]:
                defaultkey = key_store.default()
                print("Current default key is: {0}".format(defaultkey))
            # name provided, check if it exists in the db
            elif arguments["KEYNAME"] in key_store.names():
                key_store.setdefault(arguments["KEYNAME"])
                # Update mongo db defaults with new default key
                print('The default key was successfully set to: ',
                      arguments['KEYNAME'])
            else:
                print("ERROR: Specified key is not registered.")
            return

        if arguments["delete"]:
            username = cm_config().username()
            key_store = cm_keys_mongo(username)
            print("Attempting to delete key: {0}".format(arguments["KEYNAME"]))
            if self.use_yaml:

                print("WARNING: This will only remove the keys that"
                      "have not been written to the databse already when "
                      "'keys save' is"
                      "called. If your key is already in the database, "
                      "you should use mongo mode\n")

            key_store.delete(arguments["KEYNAME"])
            return

        # deprecating...
        """
Example #6
0
    def do_key(self, args, arguments):
        """
        Usage:
               key -h|--help
               key list [--source=SOURCE] [--dir=DIR] [--format=FORMAT]
               key add [--keyname=KEYNAME] FILENAME
               key default [KEYNAME]
               key delete KEYNAME

        Manages the keys

        Arguments:

          SOURCE         mongo, yaml, ssh
          KEYNAME        The name of a key
          FORMAT         The format of the output (table, json, yaml)
          FILENAME       The filename with full path in which the key is located

        Options:

           --dir=DIR            the directory with keys [default: ~/.ssh]
           --format=FORMAT      the format of the output [default: table]
           --source=SOURCE      the source for the keys [default: mongo]
           --keyname=KEYNAME    the name of the keys

        Description:


        key list --source=ssh  [--dir=DIR] [--format=FORMAT]

           lists all keys in the directory. If the directory is not
           specified the defualt will be ~/.ssh

        key list --source=yaml  [--dir=DIR] [--format=FORMAT]

           lists all keys in cloudmesh.yaml file in the specified directory.
            dir is by default ~/.cloudmesh

        key list [--format=FORMAT]

            list the keys in mongo

        key add [--keyname=keyname] FILENAME

            adds the key specifid by the filename to mongodb


        key list

             Prints list of keys. NAME of the key can be specified

        key default [NAME]

             Used to set a key from the key-list as the default key if NAME
             is given. Otherwise print the current default key

        key delete NAME

             deletes a key. In yaml mode it can delete only key that
             are not saved in mongo

        """
        # print arguments

        def _find_keys(directory):
            return [file for file in listdir(expanduser(directory))
                    if file.lower().endswith(".pub")]

        #
        # DIR (OK)
        #

        directory = path_expand(arguments["--dir"])
        source = arguments["--source"]

        if source not in ["ssh", "yaml", "mongo"]:
            print("ERROR: source is not defined")
            return

        #
        # PRINT DICT (OK)
        #

        def _print_dict(d, header=None):
            print_format = arguments['--format']
            if print_format == "json":
                return json.dumps(d, indent=4)
            elif print_format == "yaml":
                return yaml.dump(d, default_flow_style=False)
            else:
                return two_column_table(keys, header)

        #
        # PRINT SYSTEM (OK)
        #

        if arguments["list"] and source == "ssh":

            files = _find_keys(directory)

            keys = {}
            for key in files:
                keys[key] = directory + "/" + key
            print(_print_dict(keys, header=["Key", "Location"]))

            return

        #
        # PRINT YAML (OK)
        #

        if arguments["list"] and source == "yaml":

            key_store = cm_keys_yaml()
            keynames = key_store.names()
            keys = {}
            for key in keynames:
                keys[key] = get_fingerprint(key_store[key])

            print(_print_dict(keys, header=["Key", "Fingerprint"]))

            return

        #
        # FROM HERE ON BROKEN
        #

        if arguments["list"] and source == "mongo":

            username = cm_config().username()
            key_store = cm_keys_mongo(username)
            keynames = key_store.names()

            keys = {}
            for key in keynames:

                keys[key] = key_store[key]
                if keytype(keys[key]) == 'string':
                    keys[key] = get_fingerprint(keys[key])

            print(_print_dict(keys, header=["Key", "Fingerprint"]))

            return

        # self._load_keys_from_yaml()
        # self._load_mongo()
        # self._load_keys_mongo()

        if arguments["add"] and arguments["FILENAME"]:

            username = cm_config().username()
            key_store = cm_keys_mongo(username)
            filename = arguments["FILENAME"]

            # print filename
            # file existence check moved to the util function
            # if file does not exist it will return None
            keystring = get_key_from_file(filename)
            if keystring:
                keystring = keystring.strip()
                keysegments = key_parse(keystring)
                # key valid?
                if key_validate("string", keystring):
                    if arguments["--keyname"]:
                        keyname = arguments["--keyname"]
                    else:
                        # get keyname from the comment field of key
                        keyname = keysegments[2]
                        # in case a comment field is really missing
                        # use a timestamp for uniqueness
                        if keyname is None:
                            tstamp = datetime.now().strftime("%Y%m%d%H%M%S")
                            keyname = tstamp
                        # sanitize the key name for mongo use
                        else:
                            keyname = re.sub(r'@|-|\.', '_', keysegments[2])
                    key_store[keyname] = keystring
                else:
                    print("ERROR: INVALID key. Please verify!")
            else:
                print("ERROR: INVALID filename provided!")

            return

            """
            def func():
                if arguments["KEY"]:
                    key_store.__setitem__(
                        arguments["NAME"], arguments["KEY"])
                else:
                    files = _find_keys(directory)

                    result = menu_return_num(
                        title="Select a public key", menu_list=files, tries=3)
                    if result == 'q':
                        return
                    else:
                        key_store.__setitem__(arguments["NAME"],
                                                  "{0}/{1}".format(directory,files[result]))

            if arguments["NAME"] in key_store.names():
                if yn_choice("key {0} exists, update?"
                             .format(arguments["NAME"]), default='n'):
                    print "Updating key {0} ...".format(arguments["NAME"])
                    func()
                else:
                    return
            else:
                print "adding key {0} ...".format(arguments["NAME"])
                func()
            """

        if arguments["default"]:
            username = cm_config().username()
            key_store = cm_keys_mongo(username)
            # print key_store.names()
            # no name provided, will get current default key
            if not arguments["KEYNAME"]:
                defaultkey = key_store.default()
                print("Current default key is: {0}".format(defaultkey))
            # name provided, check if it exists in the db
            elif arguments["KEYNAME"] in key_store.names():
                key_store.setdefault(arguments["KEYNAME"])
                # Update mongo db defaults with new default key
                print('The default key was successfully set to: ', arguments['KEYNAME'])
            else:
                print("ERROR: Specified key is not registered.")
            return

        if arguments["delete"]:
            username = cm_config().username()
            key_store = cm_keys_mongo(username)
            print("Attempting to delete key: {0}".format(arguments["KEYNAME"]))
            if self.use_yaml:

                print("WARNING: This will only remove the keys that"
                      "have not been written to the databse already when "
                      "'keys save' is"
                      "called. If your key is already in the database, "
                      "you should use mongo mode\n")

            key_store.delete(arguments["KEYNAME"])
            return

        # deprecating...
        """