Create an SSH keypair
175787
def create_keypair(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        log.error(
            'The create_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

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

    data = aws.query(params,
                     return_url=True,
                     return_root=True,
                     location=get_location(),
                     provider=get_provider(),
                     opts=__opts__,
                     sigver='4')
    keys = [x for x in data[0] if 'requestId' not in x]

    return (keys, data[1])
410868
def _setSSH(self):
        
        if not os.path.exists('/root/.sshSuccess'):
            subprocess.check_call(['ssh-keygen', '-f', '/root/.ssh/id_rsa', '-t', 'rsa', '-N', ''])
            with open('/root/.sshSuccess', 'w') as f:
                f.write('written here because of restrictive permissions on .ssh dir')
        os.chmod('/root/.ssh', 0o700)
        subprocess.check_call(['bash', '-c', 'eval $(ssh-agent) && ssh-add -k'])
        with open('/root/.ssh/id_rsa.pub') as f:
            masterPublicKey = f.read()
        masterPublicKey = masterPublicKey.split(' ')[1]  # take 'body' of key
        # confirm it really is an RSA public key
        assert masterPublicKey.startswith('AAAAB3NzaC1yc2E'), masterPublicKey
        return masterPublicKey
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),
        }
    }
704123
def create_keypair(self, keypair_name):
        
        query = self.query_factory(
            action="CreateKeyPair", creds=self.creds, endpoint=self.endpoint,
            other_params={"KeyName": keypair_name})
        d = query.submit()
        return d.addCallback(self.parser.create_keypair)
1364524
def ssh(name):
    """"""
    env.host_string = lib.get_env_host_string()
    print("\nExecuting the command '{0}' on node {1}...".format(
          name, env.host_string))
    # Execute remotely using either the sudo or the run fabric functions
    with settings(hide("warnings"), warn_only=True):
        if name.startswith("sudo "):
            sudo(name[5:])
        else:
            run(name)
200608
def connect_ssh_with_cb(ssh_cb, user, host, auth_cb, allow_new=True, 
                        verbosity=0):
    

    with connect_ssh(user, host, auth_cb, allow_new=True, verbosity=0) as ssh:
        ssh_cb(ssh)
742383
def ssh_client(host, username=None, password=None, **kwargs):
    
    client = paramiko.SSHClient()
    # save hostname and username on the instance - this is a ugly hack
    # but I don't see any other way to do that for now. Note that
    # this is only used for SshSession.__str__.
    client.hostname = host
    client.username = username
    if username is not None:
        kwargs['username'] = username
    if password is not None:
        kwargs['password'] = password
    if username is not None and password is not None:
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        kwargs.setdefault('look_for_keys', False)
    client.connect(host, **kwargs)
    return client
126389
def create_or_get_keypair(self, nova, keypair_name="testkey"):
        """"""
        try:
            _keypair = nova.keypairs.get(keypair_name)
            self.log.debug('Keypair ({}) already exists, '
                           'using it.'.format(keypair_name))
            return _keypair
        except Exception:
            self.log.debug('Keypair ({}) does not exist, '
                           'creating it.'.format(keypair_name))

        _keypair = nova.keypairs.create(name=keypair_name)
        return _keypair
607754
def configure_ssh_command(ip, command)
      use_sudo = ChefWorkflow::KnifeSupport.use_sudo
      command = "#{use_sudo ? 'sudo ': ''}#{command}"

      options = { }

      options[:password] = ChefWorkflow::KnifeSupport.ssh_password          if ChefWorkflow::KnifeSupport.ssh_password
      options[:keys]     = [ChefWorkflow::KnifeSupport.ssh_identity_file]   if ChefWorkflow::KnifeSupport.ssh_identity_file

      Net::SSH.start(ip, ChefWorkflow::KnifeSupport.ssh_user, options) do |ssh|
        ssh.open_channel do |ch|
          ch.request_pty do |ch, success|
            if !success and use_sudo
              raise "The use_sudo setting requires a PTY, and your SSH is rejecting our attempt to get one."
            end
          end

          ch.on_open_failed do |ch, code, desc|
            raise "Connection Error to #{ip}: #{desc}"
          end

          ch.exec(command) do |ch, success|
            yield ch, success
          end
        end

        ssh.loop
      end
    end
1112468
def _github_create_ssh_key(cls):
        """"""
        try:
            login = cls._user.login
            pkey_path = '{home}/.ssh/{keyname}'.format(
                home=os.path.expanduser('~'),
                keyname=settings.GITHUB_SSH_KEYNAME.format(login=login))
            # generate ssh key only if it doesn't exist
            if not os.path.exists(pkey_path):
                ClHelper.run_command('ssh-keygen -t rsa -f {pkey_path}\
                                     -N \"\" -C \"DevAssistant\"'.
                                     format(pkey_path=pkey_path))
            try:
                ClHelper.run_command('ssh-add {pkey_path}'.format(pkey_path=pkey_path))
            except exceptions.ClException:
                # ssh agent might not be running
                env = cls._start_ssh_agent()
                ClHelper.run_command('ssh-add {pkey_path}'.format(pkey_path=pkey_path), env=env)
            public_key = ClHelper.run_command('cat {pkey_path}.pub'.format(pkey_path=pkey_path))
            cls._user.create_key("DevAssistant", public_key)
        except exceptions.ClException as e:
            msg = 'Couldn\'t create a new ssh key: {0}'.format(e)
            raise exceptions.CommandException(msg)
662858
async def ImportKeys(self, ssh_keys, user):
        '''
        
        '''
        # map input types to rpc msg
        _params = dict()
        msg = dict(type='KeyManager',
                   request='ImportKeys',
                   version=1,
                   params=_params)
        _params['ssh-keys'] = ssh_keys
        _params['user'] = user
        reply = await self.rpc(msg)
        return reply
15318
def connect_ssh(*args, **kwargs):
        

        client = SSHClient()
        client.connect(*args, **kwargs)
        return client
128840
def generate_keypair(curve='secp160r1', randfunc=None):
    
    if randfunc is None:
        randfunc = Crypto.Random.new().read
    curve = Curve.by_name(curve)
    raw_privkey = randfunc(curve.order_len_bin)
    privkey = serialize_number(deserialize_number(raw_privkey), SER_COMPACT)
    pubkey = str(passphrase_to_pubkey(privkey))
    return (privkey, pubkey)
871215
def _setup_ssh(self):
        """"""
        global paramiko
        if paramiko is none:
            import paramiko

        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(self.server, username=self.user, pkey=self.pkey)
546613
function pemToRsaSSHKey(pem, comment) {
    assert.equal('string', typeof (pem), 'typeof pem');

    var k = sshpk.parseKey(pem, 'pem');
    k.comment = comment;
    return (k.toString('ssh'));
  }
392909
def _add_ssh_key(ret):
    '''
    
    '''
    priv = None
    if __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 = __opts__.get(
            'ssh_priv',
            os.path.abspath(os.path.join(
                __opts__['pki_dir'],
                'ssh',
                'salt-ssh.rsa'
            ))
        )
    if priv and os.path.isfile(priv):
        ret['priv'] = priv
1348528
def generate_ssh(self, server, args, configure):
        
        self.reset_server_env(server, configure)

        # chmod project root owner
        sudo('chown {user}:{user} -R {path}'.format(
            user=configure[server]['user'],
            path=bigdata_conf.project_root
        ))

        # generate ssh key
        if not exists('~/.ssh/id_rsa.pub'):
            run('ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa')