Read public keys from specified user's authorized_keys file.

    args:
        username (str): username.

    returns:
        list: Authorised keys for the specified user.
354888
def read_authorized_keys(username=None):
    
    authorized_keys_path = '{0}/.ssh/authorized_keys'.format(os.path.expanduser('~{0}'.format(username)))
    rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
    tmp_authorized_keys_path = '/tmp/authorized_keys_{0}_{1}'.format(username, rnd_chars)
    authorized_keys = list()
    copy_result = execute_command(
        shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), authorized_keys_path, tmp_authorized_keys_path))))
    result_message = copy_result[0][1].decode('UTF-8')
    if 'you must have a tty to run sudo' in result_message:  # pragma: no cover
        raise OSError("/etc/sudoers is blocked sudo. Remove entry: 'Defaults    requiretty'.")
    elif 'No such file or directory' not in result_message:
        execute_command(shlex.split(str('{0} chmod 755 {1}'.format(sudo_check(), tmp_authorized_keys_path))))
        with open(tmp_authorized_keys_path) as keys_file:
            for key in keys_file:
                authorized_keys.append(PublicKey(raw=key))
        execute_command(shlex.split(str('{0} rm {1}'.format(sudo_check(), tmp_authorized_keys_path))))
    return authorized_keys
201213
def get_blocked_usernames():
    
    if config.DISABLE_USERNAME_LOCKOUT:
        # There are no blocked usernames since we disabled them.
        return []
    key = get_username_blocked_cache_key("*")
    key_list = [redis_key.decode('utf-8')
                for redis_key in REDIS_SERVER.keys(key)]
    return strip_keys(key_list)
443040
def get_values_of_matching_keys(pattern_dict, user_name):
    '''
    
    '''
    ret = []
    for expr in pattern_dict:
        if salt.utils.stringutils.expr_match(user_name, expr):
            ret.extend(pattern_dict[expr])
    return ret
317349
def _RemoveAuthorizedKeys(self, user):
    
    pw_entry = self._GetUser(user)
    if not pw_entry:
      return

    home_dir = pw_entry.pw_dir
    authorized_keys_file = os.path.join(home_dir, '.ssh', 'authorized_keys')
    if os.path.exists(authorized_keys_file):
      try:
        os.remove(authorized_keys_file)
      except OSError as e:
        message = 'Could not remove authorized keys for user %s. %s.'
        self.logger.warning(message, user, str(e))
548467
def key_from_keybase(username, fingerprint=None):
    """"""
    url = keybase_lookup_url(username)
    resp = requests.get(url)
    if resp.status_code == 200:
        j_resp = json.loads(polite_string(resp.content))
        if 'them' in j_resp and len(j_resp['them']) == 1:
            kb_obj = j_resp['them'][0]
            if fingerprint:
                return fingerprint_from_keybase(fingerprint, kb_obj)
            else:
                if 'public_keys' in kb_obj \
                   and 'pgp_public_keys' in kb_obj['public_keys']:
                    key = kb_obj['public_keys']['primary']
                    return massage_key(key)

    return None
565965
def _get_user(self, username):
        
        if username is None:
            return {}
        ret = {}
        for b in self.backends:
            try:
                tmp = self.backends[b].get_user(username)
            except UserDoesntExist as e:
                self._handle_exception(e)
                tmp = {}
            self._merge_user_attrs(tmp, ret, b)

        cherrypy.log.error(
            msg="user '" + username + "' attributes " + str(ret),
            severity=logging.DEBUG
        )
        return ret
888205
def public_keys(self):
        """"""
        if not self.public_keys_cache:
            conn = self.conn_factory()
            self.public_keys_cache = conn.export_public_keys(self.identities)
        return self.public_keys_cache
1087220
def read_credentials(self, credentials):
        
        self._items.clear()
        for key in credentials.get_key_names():
            value = credentials.get_as_nullable_string(key)
            self._items.append(CredentialParams.from_tuples([key, value]))
1272643
def construct_user_list(raw_users=None):
        """"""
        users = Users(oktypes=User)
        for user_dict in raw_users:
            public_keys = None
            if user_dict.get('public_keys'):
                public_keys = [PublicKey(b64encoded=x, raw=None)
                               for x in user_dict.get('public_keys')]
            users.append(User(name=user_dict.get('name'),
                              passwd=user_dict.get('passwd'),
                              uid=user_dict.get('uid'),
                              gid=user_dict.get('gid'),
                              home_dir=user_dict.get('home_dir'),
                              gecos=user_dict.get('gecos'),
                              shell=user_dict.get('shell'),
                              public_keys=public_keys,
                              sudoers_entry=user_dict.get('sudoers_entry')))
        return users
195831
def _parse_username(self, config):
        
        (username, priv, role, nopass, fmt, secret, sshkey) = config
        resource = dict()
        resource['privilege'] = priv
        resource['role'] = role
        resource['nopassword'] = nopass == 'nopassword'
        resource['format'] = fmt
        resource['secret'] = secret
        resource['sshkey'] = sshkey
        return {username: resource}
592850
def load_private_key(key_file, key_password=None):
    
    key_file = os.path.expanduser(key_file)
    key_file = os.path.abspath(key_file)

    if not key_password:
        with open(key_file, 'r') as key:
            return key.read()

    with open(key_file, 'rb') as key:
        key_bytes = key.read()
    return decrypt_key(key_bytes, key_password).decode(ENCODING)
906243
def update_authorized_keys(public_key)
      auth_key_file = "/root/.ssh/authorized_keys"

      FileUtils.mkdir_p(File.dirname(auth_key_file)) # make sure the directory exists

      key_exists = false

      File.open(auth_key_file, "r") do |file|
        file.each_line { |line| key_exists = true if line == public_key }
      end if File.exists?(auth_key_file)

      if key_exists
        puts "Public ssh key for root already exists in #{auth_key_file}"
      else
        puts "Appending public ssh key to #{auth_key_file}"
        File.open(auth_key_file, "a") { |f| f.puts(public_key) }
      end

      # make sure it's private
      FileUtils.chmod(0600, auth_key_file)
      true
    end
628108
def extract_public_key(args):
    
    sk = _load_ecdsa_signing_key(args)
    vk = sk.get_verifying_key()
    args.public_keyfile.write(vk.to_string())
    print("%s public key extracted to %s" % (args.keyfile.name, args.public_keyfile.name))
1242433
def parse_public_keys(self):
        """"""
        public_keys = [formats.import_public_key(pk)
                       for pk in self.public_keys()]
        for pk, identity in zip(public_keys, self.identities):
            pk['identity'] = identity
        return public_keys
841634
def get_user(self, username):
        

        r = self._query_('/users/%s' % username, 'GET')

        result = User(r.json())
        return result
445790
def get_projects_in_user(self, username):
        
        cmd = ["list", "assoc", "where", "user=%s" % username]
        results = self._read_output(cmd)

        project_list = []
        for result in results:
            project_list.append(result["Account"])
        return project_list
64995
def _get_roles(self, username):
        
        groups = self._get_groups(username)
        user_roles = self.roles.get_roles(groups)
        cherrypy.log.error(
            msg="user '" + username + "' roles: " + str(user_roles),
            severity=logging.DEBUG,
        )
        return user_roles