Add a new SSH key.
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'))
260487
def update_credentials(self, key, secret):
        '''  '''
        self.access_key = key
        self.secret_key = secret
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)
        )
56739
def gen_key(path):
    '''
    
    '''
    cmd = 'ssh-keygen -P "" -f {0} -t rsa -q'.format(path)
    if not os.path.isdir(os.path.dirname(path)):
        os.makedirs(os.path.dirname(path))
    subprocess.call(cmd, shell=True)
94080
def setup(self):
        ''''''
        log.debug( 'New request from address %s, port %d',  self.client_address )
        
        try:
            self.transport.load_server_moduli()
        except:
            log.exception( '(Failed to load moduli -- gex will be unsupported.)' )
            raise
        try:
            self.transport.add_server_key(self.host_key)
        except:
            if self.host_key is None:
                log.critical('Host key not set!  SSHHandler MUST define the host_key parameter.')
                raise NotImplementedError('Host key not set!  SSHHandler instance must define the host_key parameter.  Try host_key = paramiko_ssh.getRsaKeyFile("server_rsa.key").')
        
        try:
            # Tell transport to use this object as a server
            log.debug( 'Starting SSH server-side negotiation' )
            self.transport.start_server(server=self)
        except SSHException, e:
           log.warn('SSH negotiation failed. %s', e)
           raise
        
        # Accept any requested channels
        while True:
            channel = self.transport.accept(20)
            if channel is None:
                # check to see if any thread is running
                any_running = False
                for c, thread in self.channels.items():
                    if thread.is_alive():
                        any_running = True
                        break
                if not any_running:
                    break
            else:
                log.info( 'Accepted channel %s', channel )
1322357
protected function appendSSHConfig()
    {
        $ssh_config_file = $this->sshConfigFile();

        $hostname = $this->hostNameForConfigFile();

        $host_string = "Host " . $hostname;

        if (strpos(file_get_contents($ssh_config_file), $host_string) !== false) {
            $this->info("SSH config for host: $host_string already exists");
            return;
        }

        $this->info("Adding server config to SSH config file $ssh_config_file");
        if (! File::exists($ssh_config_file)) {
            touch($ssh_config_file);
        }
        $ip_address = $this->ip_address();
        $config_string = "\n$host_string\n  Hostname $ip_address \n  User forge\n  IdentityFile /home/sergi/.ssh/id_rsa\n  Port 22\n  StrictHostKeyChecking no\n";
        File::append($ssh_config_file, $config_string);

        $this->info('The following config has been added:' . $config_string);
    }
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)
1238608
def establish_scp_conn(self):
        """"""
        ssh_connect_params = self.ssh_ctl_chan._connect_params_dict()
        self.scp_conn = self.ssh_ctl_chan._build_ssh_client()
        self.scp_conn.connect(**ssh_connect_params)
        self.scp_client = scp.SCPClient(self.scp_conn.get_transport())
371416
def post(self, *args, **kwargs):
        """"""

        existing_ssh = models.SSHConfig.objects.all()

        if existing_ssh.exists():
            return self.get_view()

        remote_user = self.request.POST.get('remote_user', 'root')

        create_ssh_config(remote_user=remote_user)

        return self.get_view()
1122246
def add_subkey(self, subkey):
        
        if self.key.lower() == 'atoms' or not self.has_subkey(subkey):
            self.subkeys.append(subkey)
922106
def add_key(self, key_name, private):
        
        payload = {
            'name': key_name,
            'priv': private
        }

        data = json.dumps(payload)

        req = self.request(self.uri + '/keys', data=data)
        response = req.put().json()

        self.update_keys()
        return response
42260
def ssh(cls, vm_id, login, identity, args=None):
        """"""
        cmd = ['ssh']
        if identity:
            cmd.extend(('-i', identity,))

        version, ip_addr = cls.vm_ip(vm_id)
        if version == 6:
            cmd.append('-6')

        if not ip_addr:
            cls.echo('No IP address found for vm %s, aborting.' % vm_id)
            return

        cmd.append('%s@%s' % (login, ip_addr,))

        if args:
            cmd.extend(args)

        cls.echo('Requesting access using: %s ...' % ' '.join(cmd))
        return cls.execute(cmd, False)
394766
def create(self, key=None, label=None):
        
        key = '%s' % key
        url = self.bitbucket.url('SET_SSH_KEY')
        return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, key=key, label=label)
655715
def add_key(self, key, first=False):
        
        if first:
            self.keys = [key] + self.keys
        else:
            self.keys.append(key)
        if isinstance(key, VSpaceKey):
            self.space = key
1058847
def cli(env, identifier):
    """"""
    mgr = SoftLayer.SshKeyManager(env.client)

    key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')
    if not (env.skip_confirmations or formatting.no_going_back(key_id)):
        raise exceptions.CLIAbort('Aborted')

    mgr.delete_key(key_id)
785291
def create_ssh_key(kwargs=None, call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The create_ssh_key function must be called with '
            '-f or --function'
        )

    conn = get_conn()

    # Assemble the composite SshKey object.
    ssh_key = _get_ssh_key(kwargs)

    data = conn.create_ssh_key(ssh_key=ssh_key)

    return {'SshKey': data}
900089
def put(self, key='hello', value='world'):
        
        return self.connection.put('echo/key', data=dict(key=key,           value=value))