Add a keypair to nova (nova keypair-add)

    CLI Examples:

    .. code-block:: bash

        salt '*' nova.keypair_add mykey pubfile='/home/myuser/.ssh/id_rsa.pub'
        salt '*' nova.keypair_add mykey pubkey='ssh-rsa <key> myuser@mybox'
161075
def keypair_add(name, pubfile=None, pubkey=None, profile=None, **kwargs):
    '''
    
    '''
    conn = _auth(profile, **kwargs)
    return conn.keypair_add(
        name,
        pubfile,
        pubkey
    )
748649
def add_users_to(uri, username=nil, password=nil)
      begin
        uri = URI.parse(uri) if uri.instance_of?(String)
        if username
          userinfo = URI.escape(username, USERPW)
          userinfo += ":" + URI.escape(password, USERPW) unless password.nil?
          uri.userinfo = userinfo
        end
        uri
      rescue URI::InvalidURIError
        if uri =~ PATTERN::GIT_URI
          user, host, path = $1, $2, $3
          userinfo = URI.escape(user, USERPW)
          userinfo += ":" + URI.escape(username, USERPW) unless username.nil?
          path = "/" + path unless path.start_with?('/')
          URI::Generic::build({:scheme => "ssh",
                              :userinfo => userinfo,
                              :host => host,
                              :path => path
          })
        else
          raise
        end
      end
    end
1316958
def load_keypair(keypair_file):
    '''
    '''
    from Crypto.PublicKey import RSA

    # Load key
    with open(keypair_file, 'rb') as filey:
        key = RSA.import_key(filey.read())

    return quote_plus(key.publickey().exportKey().decode('utf-8'))
647563
def import_keypair(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        log.error(
            'The import_keypair 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 'file' not in kwargs:
        log.error('A public key file is required.')
        return False

    params = {'Action': 'ImportKeyPair',
              'KeyName': kwargs['keyname']}

    public_key_file = kwargs['file']

    if os.path.exists(public_key_file):
        with salt.utils.files.fopen(public_key_file, 'r') as fh_:
            public_key = salt.utils.stringutils.to_unicode(fh_.read())

    if public_key is not None:
        params['PublicKeyMaterial'] = base64.b64encode(public_key)

    data = aws.query(params,
                     return_url=True,
                     location=get_location(),
                     provider=get_provider(),
                     opts=__opts__,
                     sigver='4')
    return data
386620
def add_user(name, password=None, runas=None):
    '''
    
    '''
    clear_pw = False

    if password is None:
        # Generate a random, temporary password. RabbitMQ requires one.
        clear_pw = True
        password = ''.join(random.SystemRandom().choice(
            string.ascii_uppercase + string.digits) for x in range(15))

    if runas is None and not salt.utils.platform.is_windows():
        runas = salt.utils.user.get_user()

    if salt.utils.platform.is_windows():
        # On Windows, if the password contains a special character
        # such as '|', normal execution will fail. For example:
        # cmd: rabbitmq.add_user abc "asdf|def"
        # stderr: 'def' is not recognized as an internal or external
        #         command,\r\noperable program or batch file.
        # Work around this by using a shell and a quoted command.
        python_shell = True
        cmd = '"{0}" add_user "{1}" "{2}"'.format(
            RABBITMQCTL, name, password
        )
    else:
        python_shell = False
        cmd = [RABBITMQCTL, 'add_user', name, password]

    res = __salt__['cmd.run_all'](
        cmd,
        reset_system_locale=False,
        output_loglevel='quiet',
        runas=runas,
        python_shell=python_shell)

    if clear_pw:
        # Now, Clear the random password from the account, if necessary
        try:
            clear_password(name, runas)
        except Exception:
            # Clearing the password failed. We should try to cleanup
            # and rerun and error.
            delete_user(name, runas)
            raise

    msg = 'Added'
    return _format_response(res, msg)
172471
def _replace_auth_key(
        user,
        key,
        enc='ssh-rsa',
        comment='',
        options=None,
        config='.ssh/authorized_keys'):
    '''
    
    '''

    auth_line = _format_auth_line(key, enc, comment, options or [])

    lines = []
    full = _get_config_file(user, config)

    try:
        # open the file for both reading AND writing
        with salt.utils.files.fopen(full, 'r') as _fh:
            for line in _fh:
                # We don't need any whitespace-only containing lines or arbitrary doubled newlines
                line = salt.utils.stringutils.to_unicode(line.strip())
                if line == '':
                    continue
                line += '\n'

                if line.startswith('#'):
                    # Commented Line
                    lines.append(line)
                    continue
                comps = re.findall(r'((.*)\s)?(ssh-[a-z0-9-]+|ecdsa-[a-z0-9-]+)\s([a-zA-Z0-9+/]+={0,2})(\s(.*))?', line)
                if comps and len(comps[0]) > 3 and comps[0][3] == key:
                    # Found our key, replace it
                    lines.append(auth_line)
                else:
                    lines.append(line)
            _fh.close()
            # Re-open the file writable after properly closing it
            with salt.utils.files.fopen(full, 'wb') as _fh:
                # Write out any changes
                _fh.writelines(salt.utils.data.encode(lines))
    except (IOError, OSError) as exc:
        raise CommandExecutionError(
            'Problem reading or writing to key file: {0}'.format(exc)
        )
270287
def attach(cls, name, vhost, remote_name):
        """"""
        paas_access = cls.get('paas_access')

        if not paas_access:
            paas_info = cls.info(name)
            paas_access = '%s@%s' \
                          % (paas_info['user'], paas_info['git_server'])

        remote_url = 'ssh+git://%s/%s.git' % (paas_access, vhost)

        ret = cls.execute('git remote add %s %s' % (remote_name, remote_url,))

        if ret:
            cls.echo('Added remote `%s` to your local git repository.'
                     % (remote_name))
            cls.echo('Use `git push %s master` to push your code to the '
                     'instance.' % (remote_name))
            cls.echo('Then `$ gandi deploy` to build and deploy your '
                     'application.')
84546
def add_arguments(self, parser):
        
        parser.add_argument('--length', default=self.length,
                            type=int, help=_('SECRET_KEY length default=%d' % self.length))

        parser.add_argument('--alphabet', default=self.allowed_chars,
                            type=str, help=_('alphabet to use default=%s' % self.allowed_chars))
591528
public static function generateKeypair() : Keypair
    {
        try {
            $keypair = \sodium_crypto_box_keypair();
            return new Keypair(
                \sodium_crypto_box_secretkey($keypair),
                \sodium_crypto_box_publickey($keypair)
            );
        } catch (SodiumException $e) {
            throw new Exception($e->getMessage());
        }
    }
533326
def add_user(username='',password='',group='', site_user=False):
    
    if group: group = '-g %s'% group
    if not site_user:
        run('echo %s:%s > /tmp/users.txt'% (username,password))
    if not site_user:
        sudo('useradd -m -s /bin/bash %s %s'% (group,username))
        sudo('chpasswd < /tmp/users.txt')
        sudo('rm -rf /tmp/users.txt')
    else:
        sudo('useradd -M -d /var/www -s /bin/bash %s'% username)
        sudo('usermod -a -G www-data %s'% username)
991539
def _add_secret_hash(self, parameters, key):
        
        if self.client_secret is not None:
            secret_hash = AWSSRP.get_secret_hash(self.username, self.client_id,
                                                 self.client_secret)
            parameters[key] = secret_hash
1060256
def cli(env, identifier, label, note):
    """"""

    mgr = SoftLayer.SshKeyManager(env.client)

    key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')

    if not mgr.edit_key(key_id, label=label, notes=note):
        raise exceptions.CLIAbort('Failed to edit SSH key')
465935
def cli(ctx, key, metadata=""):
    
    return ctx.gi.cannedkeys.add_key(key, metadata=metadata)
776194
def add_key(pub):
    """"""
    global _server_keys
    key = rsa.PublicKey.load_pkcs1(pub)
    _server_keys[_compute_fingerprint(key)] = key
1288189
def do_ssh(self,args):
        """"""
        parser = CommandArgumentParser("ssh")
        parser.add_argument(dest='instance',help='instance index or name');
        parser.add_argument('-a','--address-number',default='0',dest='interface-number',help='instance id of the instance to ssh to');
        parser.add_argument('-ii','--ignore-host-key',dest='ignore-host-key',default=False,action='store_true',help='Ignore host key')
        parser.add_argument('-ne','--no-echo',dest='no-echo',default=False,action='store_true',help='Do not echo command')
        parser.add_argument('-L',dest='forwarding',nargs='*',help="port forwarding string of the form: {localport}:{host-visible-to-instance}:{remoteport} or {port}")
        parser.add_argument('-R','--replace-key',dest='replaceKey',default=False,action='store_true',help="Replace the host's key. This is useful when AWS recycles an IP address you've seen before.")
        parser.add_argument('-Y','--keyscan',dest='keyscan',default=False,action='store_true',help="Perform a keyscan to avoid having to say 'yes' for a new host. Implies -R.")
        parser.add_argument('-B','--background',dest='background',default=False,action='store_true',help="Run in the background. (e.g., forward an ssh session and then do other stuff in aws-shell).")
        parser.add_argument('-v',dest='verbosity',default=0,action=VAction,nargs='?',help='Verbosity. The more instances, the more verbose');        
        parser.add_argument('-m',dest='macro',default=False,action='store_true',help='{command} is a series of macros to execute, not the actual command to run on the host');
        parser.add_argument(dest='command',nargs='*',help="Command to run on all hosts.") # consider adding a filter option later
        args = vars(parser.parse_args(args))

        interfaceNumber = int(args['interface-number'])
        forwarding = args['forwarding']
        replaceKey = args['replaceKey']
        keyscan = args['keyscan']
        background = args['background']
        verbosity = args['verbosity']
        ignoreHostKey = args['ignore-host-key']
        noEcho = args['no-echo']

        # Figure out the host to connect to:
        target = args['instance']
        try:
            index = int(args['instance'])
            instances = self.scalingGroupDescription['AutoScalingGroups'][0]['Instances']
            instance = instances[index]
            target = instance['InstanceId']
        except ValueError: # if args['instance'] is not an int, for example.
            pass
        
        if args['macro']:
            if len(args['command']) > 1:
                print("Only one macro may be specified with the -m switch.")
                return
            else:
                macro = args['command'][0]
                print("Macro:{}".format(macro))
                command = Config.config['ssh-macros'][macro]
        else:
            command = ' '.join(args['command'])
            
        ssh(target,interfaceNumber,forwarding,replaceKey,keyscan,background,verbosity,command,ignoreHostKey=ignoreHostKey,echoCommand = not noEcho)
1102832
def add_slave_server(self):
        
        master = self.args.config[1]
        slave = self.args.add_slave

        # install java at slave server
        self.reset_server_env(slave, self.configure)
        if self.prompt_check("Update package at slave server"):
            self.update_source_list()
            self.common_update_sys()

        if self.prompt_check("Install java and python at slave server"):
            self.java_install()
            sudo('apt-get install -y python python3 python-dev python3-dev')

        # generate ssh key at master server
        if not self.args.skip_master:
            if self.prompt_check("Generate ssh key at Master Server"):
                self.generate_ssh(master, self.args, self.configure)

        # generate ssh key at slave server and make slave connect with master
        if self.prompt_check("Make ssh connection within master and slave"):
            self.generate_ssh(slave, self.args, self.configure)

            # scp slave server ssh key to master server
            run('scp ~/.ssh/id_rsa.pub {0}@{1}:~/.ssh/id_rsa.pub.{2}'.format(
                self.configure[master]['user'],
                self.configure[master]['host'],
                slave
            ))

            # add slave ssh key to master authorized_keys
            self.reset_server_env(master, self.configure)
            run('cat ~/.ssh/id_rsa.pub* >> ~/.ssh/authorized_keys')

            # scp master authorized_keys to slave authorized_keys
            run('scp ~/.ssh/authorized_keys {0}@{1}:~/.ssh'.format(
                self.configure[slave]['user'],
                self.configure[slave]['host']
            ))

        # config slave and master
        if self.prompt_check("Configure master and slave server"):
            master = self.args.config[1]
            slave = self.args.add_slave

            if self.args.bigdata_app == 'spark':
                self.add_spark_slave(master, slave, self.configure)
523539
def _connect_ssh(spec):
    
    if C.HOST_KEY_CHECKING:
        check_host_keys = 'enforce'
    else:
        check_host_keys = 'ignore'

    # #334: tilde-expand private_key_file to avoid implementation difference
    # between Python and OpenSSH.
    private_key_file = spec.private_key_file()
    if private_key_file is not None:
        private_key_file = os.path.expanduser(private_key_file)

    return {
        'method': 'ssh',
        'kwargs': {
            'check_host_keys': check_host_keys,
            'hostname': spec.remote_addr(),
            'username': spec.remote_user(),
            'compression': convert_bool(
                default(spec.mitogen_ssh_compression(), True)
            ),
            'password': spec.password(),
            'port': spec.port(),
            'python_path': spec.python_path(),
            'identity_file': private_key_file,
            'identities_only': False,
            'ssh_path': spec.ssh_executable(),
            'connect_timeout': spec.ansible_ssh_timeout(),
            'ssh_args': spec.ssh_args(),
            'ssh_debug_level': spec.mitogen_ssh_debug_level(),
            'remote_name': get_remote_name(spec),
        }
    }