Associate an ssh key with your repo and return it.
167749
def create(self, repo_slug=None, key=None, label=None):
        
        key = '%s' % key
        repo_slug = repo_slug or self.bitbucket.repo_slug or ''
        url = self.bitbucket.url('SET_DEPLOY_KEY',
                                 username=self.bitbucket.username,
                                 repo_slug=repo_slug)
        return self.bitbucket.dispatch('POST',
                                       url,
                                       auth=self.bitbucket.auth,
                                       key=key,
                                       label=label)
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)
98047
def git_remote(git_repo):
    
    github_token = os.getenv(GITHUB_TOKEN_KEY)
    if github_token:
        return 'https://{0}@github.com/{1}'.format(
            github_token, git_repo)
    return 'git@github.com:{0}'.format(git_repo)
1238038
def ensure_repo_exists(self):
        """"""
        if not os.path.isdir(self.cwd):
            os.makedirs(self.cwd)
        if not os.path.isdir(os.path.join(self.cwd, ".git")):
            self.git.init()
            self.git.config("user.email", "you@example.com")
            self.git.config("user.name", "Your Name")
1325888
def register(self):
        """"""
        log.info('Installing ssh key, %s' % self.name)
        self.consul.create_ssh_pub_key(self.name, self.key)
796026
def get_value(repo_directory, key, expect_type=None):
    """"""
    config = read_config(repo_directory)
    value = config.get(key)
    if expect_type and value is not None and not isinstance(value, expect_type):
        raise ConfigSchemaError('Expected config variable %s to be type %s, got %s'
            % (repr(key), repr(expect_type), repr(type(value))))
    return value
1277862
def authenticate():
    

    client_ip     = request.environ['REMOTE_ADDR']
    repository    = request.headers['repository']
    if repository not in config['repositories']: return fail(no_such_repo_msg)

    # ==
    repository_path = config['repositories'][repository]['path']
    conn = auth_db_connect(cpjoin(repository_path, 'auth_transient.db')); gc_tokens(conn)
    gc_tokens(conn)

    # Allow resume of an existing session
    if 'session_token' in request.headers:
        session_token = request.headers['session_token']

        conn.execute("delete from session_tokens where expires < ?", (time.time(),)); conn.commit()
        res = conn.execute("select * from session_tokens where token = ? and ip = ?", (session_token, client_ip)).fetchall()
        if res != []: return success({'session_token'  : session_token})
        else:         return fail(user_auth_fail_msg)

    # Create a new session
    else:
        user       = request.headers['user']
        auth_token = request.headers['auth_token']
        signiture  = request.headers['signature']

        try:
            public_key = config['users'][user]['public_key']

            # signature
            pysodium.crypto_sign_verify_detached(base64.b64decode(signiture), auth_token, base64.b64decode(public_key))

            # check token was previously issued by this system and is still valid
            res = conn.execute("select * from tokens where token = ? and ip = ? ", (auth_token, client_ip)).fetchall()

            # Validate token matches one we sent
            if res == [] or len(res) > 1: return fail(user_auth_fail_msg)

            # Does the user have permission to use this repository?
            if repository not in config['users'][user]['uses_repositories']: return fail(user_auth_fail_msg)

            # Everything OK
            conn.execute("delete from tokens where token = ?", (auth_token,)); conn.commit()

            # generate a session token and send it to the client
            session_token = base64.b64encode(pysodium.randombytes(35))
            conn.execute("insert into session_tokens (token, expires, ip, username) values (?,?,?, ?)",
                         (session_token, time.time() + extend_session_duration, client_ip, user))
            conn.commit()
            return success({'session_token'  : session_token})

        except Exception: # pylint: disable=broad-except
            return fail(user_auth_fail_msg)
1348562
def install_repo(self, repo, location=''):
        

        dst = location or settings.upkg_destdir

        # make sure the destination dir exists.
        if not os.path.exists(dst):
            os.makedirs(dst)

        # repo = Repo(url=repo, repo_dir=dst)
        repo = Repo(url=repo)
        repo.install()

        return repo
158246
def establish_ssh(target=None, auto_trust=False, allow_agent=True, look_keys=True):
    
    '''

    def password_prompt(username, hostname):
        r'''
        If the Host is relying on password authentication, lets ask it.
        Relying on SSH itself to take care of that would not work when the
        remote authentication is password behind a SSH-key+2FA jumphost.
        '''
        return getpass.getpass('No SSH key for %s@%s, please provide password: ' % (username, hostname))

    ssh_conn = None
    if target is not None:
        ssh_conf = get_sshconfig()
        cfg = {
            'hostname': None,
            'port': 22,
            'allow_agent': allow_agent,
            'look_for_keys': look_keys
        }
        if ssh_conf.has_key(target):
            user_config = ssh_conf.get(target)

            # If ssh_config file's Host defined 'User' instead of 'Username'
            if user_config.has_key('user') and not user_config.has_key('username'):
                user_config['username'] = user_config['user']
                del user_config['user']

            for k in ('username', 'hostname', 'port'):
                if k in user_config:
                    cfg[k] = user_config[k]

            # Assume Password auth. If we don't do that, then when connecting
            # through a jumphost we will run into issues and the user will
            # not be able to input his password to the SSH prompt.
            if 'identityfile' in user_config:
                cfg['key_filename'] = user_config['identityfile']
            else:
                cfg['password'] = password_prompt(cfg['username'], cfg['hostname'] or target)

            # Should be the last one, since ProxyCommand will issue connection to remote host
            if 'proxycommand' in user_config:
                cfg['sock'] = paramiko.ProxyCommand(user_config['proxycommand'])

        else:
            cfg['username'] = target.split('@')[0]
            cfg['hostname'] = target.split('@')[1].split(':')[0]
            cfg['password'] = password_prompt(cfg['username'], cfg['hostname'])
            try:
                cfg['port'] = int(target.split('@')[1].split(':')[1])
            except IndexError:
                # IndexError will happen if no :PORT is there.
                # Default value 22 is defined above in 'cfg'.
                pass

        ssh_conn = paramiko.SSHClient()
        if auto_trust:
            ssh_conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        ssh_conn.connect(**cfg)

    return ssh_conn
1066568
def import_public_key(line):
    """"""
    log.debug('loading SSH public key: %r', line)
    file_type, base64blob, name = line.split()
    blob = base64.b64decode(base64blob)
    result = parse_pubkey(blob)
    result['name'] = name.encode('utf-8')
    assert result['type'] == file_type.encode('ascii')
    log.debug('loaded %s public key: %s', file_type, result['fingerprint'])
    return result
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
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()
28355
def upload_ssh_key(rollback=False):
    
    auth_keys = '/home/%s/.ssh/authorized_keys'% env.user
    if not rollback:
        local_user = getpass.getuser()
        host = socket.gethostname()
        u = '@'.join([local_user,host])
        u = 'ssh-key-uploaded-%s'% u
        if not env.overwrite and server_state(u): return
        if not exists('.ssh'):
            run('mkdir .ssh')
           
        #determine local .ssh dir
        home = os.path.expanduser('~')
        ssh_key = None
        upload_key = True
        ssh_dsa = os.path.join(home,'.ssh/id_dsa.pub')
        ssh_rsa =  os.path.join(home,'.ssh/id_rsa.pub')
        if env.key_filename and env.INTERACTIVE:
                upload_key = confirm('Would you like to upload your personal key in addition to %s'% str(env.key_filename), default=True)
        if upload_key:  
            if os.path.exists(ssh_dsa):
                ssh_key = ssh_dsa
            elif os.path.exists(ssh_rsa):
                ssh_key = ssh_rsa
    
        if ssh_key:
            ssh_file = open(ssh_key,'r').read()
            
            if exists(auth_keys):
                _backup_file(auth_keys)
            if env.verbosity:
                print env.host, "UPLOADING SSH KEY"
            append(auth_keys,ssh_file) #append prevents uploading twice
            set_server_state(u)
        return
    else:
        if exists(auth_keys+'.wovenbak'):
            _restore_file('/home/%s/.ssh/authorized_keys'% env.user)
        else: #no pre-existing keys remove the .ssh directory
            sudo('rm -rf /home/%s/.ssh')
        return
712571
async def add_ssh_key(self, user, key):
        
        key_facade = client.KeyManagerFacade.from_connection(self.connection())
        return await key_facade.AddKeys([key], user)
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
1103559
def update_ssh_key(self, name):
        # The `_ssh_key` is to avoid conflicts with MutableMapping.update.
        
        api = self.doapi_manager
        return api._ssh_key(api.request(self.url, method='PUT',
                                       data={"name": name})["ssh_key"])
1357185
def download_repo(repo_url, destination, commit=None):
    '''
    '''
    command = "git clone %s %s" % (repo_url, destination)
    os.system(command)
    return destination