Add a key to the authorized_keys file, using a file as the source.

    CLI Example:

    .. code-block:: bash

        salt '*' ssh.set_auth_key_from_file <user> salt://ssh_keys/<user>.id_rsa.pub
338330
def set_auth_key_from_file(user,
                           source,
                           config='.ssh/authorized_keys',
                           saltenv='base',
                           fingerprint_hash_type=None):
    '''
    
    '''
    # TODO: add support for pulling keys from other file sources as well
    lfile = __salt__['cp.cache_file'](source, saltenv)
    if not os.path.isfile(lfile):
        raise CommandExecutionError(
            'Failed to pull key file from salt file server'
        )

    s_keys = _validate_keys(lfile, fingerprint_hash_type)
    if not s_keys:
        err = (
            'No keys detected in {0}. Is file properly formatted?'.format(
                source
            )
        )
        log.error(err)
        __context__['ssh_auth.error'] = err
        return 'fail'
    else:
        rval = ''
        for key in s_keys:
            rval += set_auth_key(
                user,
                key,
                enc=s_keys[key]['enc'],
                comment=s_keys[key]['comment'],
                options=s_keys[key]['options'],
                config=config,
                cache_keys=list(s_keys.keys()),
                fingerprint_hash_type=fingerprint_hash_type
            )
        # Due to the ability for a single file to have multiple keys, it's
        # possible for a single call to this function to have both "replace"
        # and "new" as possible valid returns. I ordered the following as I
        # thought best.
        if 'fail' in rval:
            return 'fail'
        elif 'replace' in rval:
            return 'replace'
        elif 'new' in rval:
            return 'new'
        else:
            return 'no change'
253812
def _create_ssh_keys(self):
        
        ret, _, _ = utils.run_command(
            [
                'ssh-keygen',
                '-t',
                'rsa',
                '-m',
                'PEM',
                '-N',
                '',
                '-f',
                self.paths.ssh_id_rsa(),
            ]
        )
        if ret != 0:
            raise RuntimeError(
                'Failed to crate ssh keys at %s',
                self.paths.ssh_id_rsa(),
            )
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))
775366
def _expand_authorized_keys_path(path, user, home):
    '''
    
    '''
    converted_path = ''
    had_escape = False
    for char in path:
        if had_escape:
            had_escape = False
            if char == '%':
                converted_path += '%'
            elif char == 'u':
                converted_path += user
            elif char == 'h':
                converted_path += home
            else:
                error = 'AuthorizedKeysFile path: unknown token character "%{0}"'.format(char)
                raise CommandExecutionError(error)
            continue
        elif char == '%':
            had_escape = True
        else:
            converted_path += char
    if had_escape:
        error = "AuthorizedKeysFile path: Last character can't be escape character"
        raise CommandExecutionError(error)
    return converted_path
517783
def create_user(name, groups=None, key_file=None):
    """"""

    groups = groups or []
    if not user_exists(name):
        for group in groups:
            if not group_exists(group):
                sudo(u"addgroup %s" % group)
        groups = groups and u'-G %s' % u','.join(groups) or ''
        sudo(u"useradd -m %s -s /bin/bash %s" % (groups, name))
        sudo(u"passwd -d %s" % name)
    if key_file:
        sudo(u"mkdir -p /home/%s/.ssh" % name)
        put(key_file, u"/home/%s/.ssh/authorized_keys" % name, use_sudo=True)
        sudo(u"chown -R %(name)s:%(name)s /home/%(name)s/.ssh" % {'name': name})
465935
def cli(ctx, key, metadata=""):
    
    return ctx.gi.cannedkeys.add_key(key, metadata=metadata)
1252910
def get_key_auth_cb(key_filepath):
    """"""

    def auth_cb(ssh):
        key = ssh_pki_import_privkey_file(key_filepath)
        ssh.userauth_publickey(key)

    return auth_cb
908225
def generate_public_ssh_key(ssh_private_key_file):
    """"""
    try:
        with open(ssh_private_key_file, "rb") as key_file:
            key = key_file.read()
    except FileNotFoundError:
        raise IpaUtilsException(
            'SSH private key file: %s cannot be found.' % ssh_private_key_file
        )

    try:
        private_key = serialization.load_pem_private_key(
            key,
            password=None,
            backend=default_backend()
        )
    except ValueError:
        raise IpaUtilsException(
            'SSH private key file: %s is not a valid key file.'
            % ssh_private_key_file
        )

    return private_key.public_key().public_bytes(
        serialization.Encoding.OpenSSH,
        serialization.PublicFormat.OpenSSH
    )
283302
def create_key(file_):
    
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)

    file_.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    file_.flush()
566925
def add_sources_from_file(file_name, update=True):
    

    key_regex = re.compile(r'(?P<source>[^()]*)(\s+\((?P<key>.*)\))?$')
    for line in _read_lines_from_file(file_name):
        kwargs = key_regex.match(line).groupdict()
        kwargs['update'] = False
        add_apt_source(**kwargs)
    if update:
        update_apt_sources()
684562
def add(name, connection_uri, id_file="", o=[], config=None):
    
    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)
        sys.exit(1)
282107
def add(self, pubkey):
        
        f = get_fingerprint_from_public_key(pubkey)
        if f not in self._keys:
            self._order[len(self._keys)] = f
            self._keys[f] = pubkey
323212
def import_key(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        log.error(
            'The import_key function must be called with -f or --function.'
        )
        return False

    if not kwargs:
        kwargs = {}

    if 'keyname' not in kwargs:
        log.error('A keyname is required.')
        return False

    if 'keyfile' not in kwargs:
        log.error('The location of the SSH keyfile is required.')
        return False

    if not os.path.isfile(kwargs['keyfile']):
        log.error('The specified keyfile (%s) does not exist.', kwargs['keyfile'])
        return False

    with salt.utils.files.fopen(kwargs['keyfile'], 'r') as fp_:
        kwargs['key'] = salt.utils.stringutils.to_unicode(fp_.read())

    send_data = {'name': kwargs['keyname'], 'key': kwargs['key']}
    kwargs['data'] = salt.utils.json.dumps(send_data)

    rcode, data = query(
        command='my/keys',
        method='POST',
        data=kwargs['data'],
    )
    log.debug(pprint.pformat(data))
    return {'keys': {data['name']: data['key']}}
910687
def from_file(cls, filename):
        
        import csv
        with open(filename, 'r') as f:
            reader = csv.DictReader(f)
            row = reader.next()  # Only one row in the file
        try:
            cls.ACCESS_KEY_ID = row['Access Key Id']
            cls.SECRET_ACCESS_KEY = row['Secret Access Key']
        except KeyError:
            raise IOError('Invalid credentials format')
489657
def cli(env, label, in_file, key, note):
    """"""

    if in_file is None and key is None:
        raise exceptions.ArgumentError(
            'Either [-f | --in-file] or [-k | --key] arguments are required to add a key'
        )

    if in_file and key:
        raise exceptions.ArgumentError(
            '[-f | --in-file] is not allowed with [-k | --key]'
        )

    if key:
        key_text = key
    else:
        key_file = open(path.expanduser(in_file), 'rU')
        key_text = key_file.read().strip()
        key_file.close()

    mgr = SoftLayer.SshKeyManager(env.client)
    result = mgr.add_key(key_text, label, note)

    env.fout("SSH key added: %s" % result.get('fingerprint'))
623278
def get_pubkey(self):
        '''
        
        '''
        if '__master_opts__' in self.opts and \
                self.opts['__master_opts__'].get('ssh_use_home_key') and \
                os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
            priv = os.path.expanduser('~/.ssh/id_rsa')
        else:
            priv = self.opts.get(
                    'ssh_priv',
                    os.path.join(
                        self.opts['pki_dir'],
                        'ssh',
                        'salt-ssh.rsa'
                        )
                    )
        pub = '{0}.pub'.format(priv)
        with salt.utils.files.fopen(pub, 'r') as fp_:
            return '{0} rsa root@master'.format(fp_.read().split()[1])
256342
def _use_private_key(
            self,
            client_certchain_file: str,
            client_key_file: str,
            client_key_type: OpenSslFileTypeEnum,
            client_key_password: str
    ) -> None:
        
        # Ensure the files exist
        with open(client_certchain_file):
            pass
        with open(client_key_file):
            pass

        self._ssl_ctx.use_certificate_chain_file(client_certchain_file)
        self._ssl_ctx.set_private_key_password(client_key_password)
        try:
            self._ssl_ctx.use_PrivateKey_file(client_key_file, client_key_type.value)
        except OpenSSLError as e:
            if 'bad password read' in str(e) or 'bad decrypt' in str(e):
                raise ValueError('Invalid Private Key')
            else:
                raise

        self._ssl_ctx.check_private_key()