Пример #1
0
    def deploy_ssh_pubkey(self, username, pubkey):
        """
        Deploy authorized_key
        """
        path, thumbprint, value = pubkey
        if path is None:
            raise OSUtilError("Publich key path is None")

        crytputil = CryptUtil(conf.get_openssl_cmd())

        path = self._norm_path(path)
        dir_path = os.path.dirname(path)
        fileutil.mkdir(dir_path, mode=0o700, owner=username)
        if value is not None:
            if not value.startswith("ssh-"):
                raise OSUtilError("Bad public key: {0}".format(value))
            fileutil.write_file(path, value)
        elif thumbprint is not None:
            lib_dir = conf.get_lib_dir()
            crt_path = os.path.join(lib_dir, thumbprint + '.crt')
            if not os.path.isfile(crt_path):
                raise OSUtilError("Can't find {0}.crt".format(thumbprint))
            pub_path = os.path.join(lib_dir, thumbprint + '.pub')
            pub = crytputil.get_pubkey_from_crt(crt_path)
            fileutil.write_file(pub_path, pub)
            self.set_selinux_context(pub_path,
                                     'unconfined_u:object_r:ssh_home_t:s0')
            self.openssl_to_openssh(pub_path, path)
            fileutil.chmod(pub_path, 0o600)
        else:
            raise OSUtilError("SSH public key Fingerprint and Value are None")

        self.set_selinux_context(path, 'unconfined_u:object_r:ssh_home_t:s0')
        fileutil.chowner(path, username)
        fileutil.chmod(path, 0o644)
Пример #2
0
 def chpasswd(self, username, password, crypt_id=6, salt_len=10):
     if self.is_sys_user(username):
         raise OSUtilError(("User {0} is a system user. "
                            "Will not set passwd.").format(username))
     passwd_hash = textutil.gen_password_hash(password, crypt_id, salt_len)
     cmd = "usermod -p '{0}' {1}".format(passwd_hash, username)
     ret, output = shellutil.run_get_output(cmd, log_cmd=False)
     if ret != 0:
         raise OSUtilError(("Failed to set password for {0}: {1}"
                            "").format(username, output))
Пример #3
0
 def get_processor_cores(self):
     ret = shellutil.run_get_output(
         "grep 'processor.*:' /proc/cpuinfo |wc -l")
     if ret[0] == 0:
         return int(ret[1])
     else:
         raise OSUtilError("Failed to get procerssor cores")
Пример #4
0
 def get_total_mem(self):
     cmd = "grep MemTotal /proc/meminfo |awk '{print $2}'"
     ret = shellutil.run_get_output(cmd)
     if ret[0] == 0:
         return int(ret[1]) / 1024
     else:
         raise OSUtilError("Failed to get total memory: {0}".format(ret[1]))
Пример #5
0
    def mount_dvd(self, max_retry=6, chk_err=True):
        dvd = self.get_dvd_device()
        mount_point = conf.get_dvd_mount_point()
        mountlist = shellutil.run_get_output("mount")[1]
        existing = self.get_mount_point(mountlist, dvd)
        if existing is not None:  #Already mounted
            logger.info("{0} is already mounted at {1}", dvd, existing)
            return
        if not os.path.isdir(mount_point):
            os.makedirs(mount_point)

        for retry in range(0, max_retry):
            retcode = self.mount(dvd,
                                 mount_point,
                                 option="-o ro -t iso9660,udf",
                                 chk_err=chk_err)
            if retcode == 0:
                logger.info("Successfully mounted dvd")
                return
            if retry < max_retry - 1:
                logger.warn("Mount dvd failed: retry={0}, ret={1}", retry,
                            retcode)
                time.sleep(5)
        if chk_err:
            raise OSUtilError("Failed to mount dvd.")
Пример #6
0
 def openssl_to_openssh(self, input_file, output_file):
     pubkey = fileutil.read_file(input_file)
     try:
         cryptutil = CryptUtil(conf.get_openssl_cmd())
         ssh_rsa_pubkey = cryptutil.asn1_to_ssh(pubkey)
     except CryptError as e:
         raise OSUtilError(ustr(e))
     fileutil.write_file(output_file, ssh_rsa_pubkey)
Пример #7
0
 def del_root_password(self):
     try:
         passwd_file_path = conf.get_passwd_file_path()
         passwd_content = fileutil.read_file(passwd_file_path)
         passwd = passwd_content.split('\n')
         new_passwd = [x for x in passwd if not x.startswith("root:")]
         new_passwd.insert(0, "root:*LOCK*:14600::::::")
         fileutil.write_file(passwd_file_path, "\n".join(new_passwd))
     except IOError as e:
         raise OSUtilError("Failed to delete root password:{0}".format(e))
Пример #8
0
 def del_account(self, username):
     if self.is_sys_user(username):
         logger.error("{0} is a system user. Will not delete it.", username)
     shellutil.run("> /var/run/utmp")
     shellutil.run("userdel -f -r " + username)
     #Remove user from suders
     if os.path.isfile("/etc/suders.d/waagent"):
         try:
             content = fileutil.read_file("/etc/sudoers.d/waagent")
             sudoers = content.split("\n")
             sudoers = [x for x in sudoers if username not in x]
             fileutil.write_file("/etc/sudoers.d/waagent",
                                 "\n".join(sudoers))
         except IOError as e:
             raise OSUtilError("Failed to remove sudoer: {0}".format(e))
Пример #9
0
    def useradd(self, username, expiration=None):
        """
        Create user account with 'username'
        """
        userentry = self.get_userentry(username)
        if userentry is not None:
            logger.info("User {0} already exists, skip useradd", username)
            return

        if expiration is not None:
            cmd = "useradd -m {0} -e {1}".format(username, expiration)
        else:
            cmd = "useradd -m {0}".format(username)
        retcode, out = shellutil.run_get_output(cmd)
        if retcode != 0:
            raise OSUtilError(("Failed to create user account:{0}, "
                               "retcode:{1}, "
                               "output:{2}").format(username, retcode, out))
Пример #10
0
 def deploy_ssh_keypair(self, username, keypair):
     """
     Deploy id_rsa and id_rsa.pub
     """
     path, thumbprint = keypair
     path = self._norm_path(path)
     dir_path = os.path.dirname(path)
     fileutil.mkdir(dir_path, mode=0o700, owner=username)
     lib_dir = conf.get_lib_dir()
     prv_path = os.path.join(lib_dir, thumbprint + '.prv')
     if not os.path.isfile(prv_path):
         raise OSUtilError("Can't find {0}.prv".format(thumbprint))
     shutil.copyfile(prv_path, path)
     pub_path = path + '.pub'
     crytputil = CryptUtil(conf.get_openssl_cmd())
     pub = crytputil.get_pubkey_from_prv(prv_path)
     fileutil.write_file(pub_path, pub)
     self.set_selinux_context(pub_path,
                              'unconfined_u:object_r:ssh_home_t:s0')
     self.set_selinux_context(path, 'unconfined_u:object_r:ssh_home_t:s0')
     os.chmod(path, 0o644)
     os.chmod(pub_path, 0o600)
Пример #11
0
 def _set_wireserver_endpoint(self, endpoint):
     try:
         file_path = os.path.join(conf.get_lib_dir(), ENDPOINT_FILE_NAME)
         fileutil.write_file(file_path, endpoint)
     except IOError as e:
         raise OSUtilError(ustr(e))
Пример #12
0
 def _get_wireserver_endpoint(self):
     try:
         file_path = os.path.join(conf.get_lib_dir(), ENDPOINT_FILE_NAME)
         return fileutil.read_file(file_path)
     except IOError as e:
         raise OSUtilError(ustr(e))
Пример #13
0
 def eject_dvd(self, chk_err=True):
     dvd = self.get_dvd_device()
     retcode = shellutil.run("eject {0}".format(dvd))
     if chk_err and retcode != 0:
         raise OSUtilError("Failed to eject dvd: ret={0}".format(retcode))
Пример #14
0
 def umount_dvd(self, chk_err=True):
     mount_point = conf.get_dvd_mount_point()
     retcode = self.umount(mount_point, chk_err=chk_err)
     if chk_err and retcode != 0:
         raise OSUtilError("Failed to umount dvd.")
Пример #15
0
 def get_dvd_device(self, dev_dir='/dev'):
     patten = r'(sr[0-9]|hd[c-z]|cdrom[0-9])'
     for dvd in [re.match(patten, dev) for dev in os.listdir(dev_dir)]:
         if dvd is not None:
             return "/dev/{0}".format(dvd.group(0))
     raise OSUtilError("Failed to get dvd device")