def create_keypair():
    """Create a new keypair and upload it to Ravello."""
    cfgdir = util.get_config_dir()
    privname = os.path.join(cfgdir, 'id_ravello')
    pubname = privname + '.pub'
    keyname = 'ravello@%s' % socket.gethostname()
    # Prefer to generate the key locallly with ssh-keygen because
    # that gives us more privacy. If ssh-keygen is not available, ask
    # for a key through the API.
    sshkeygen = util.which('ssh-keygen')
    if sshkeygen:
        try:
            console.info("Generating keypair using 'ssh-keygen'...")
            subprocess.call(['ssh-keygen', '-q', '-t', 'rsa', '-C', keyname,
                             '-b', '2048', '-N', '', '-f', privname])
        except subprocess.CalledProcessError as e:
            error.raise_error('ssh-keygen returned with error status {0}',
                              e.returncode)
        with file(pubname) as fin:
            pubkey = fin.read()
        keyparts = pubkey.strip().split()
    else:
        keyname = 'ravello@api-generated'
        console.info('Requesting a new keypair via the API...')
        keypair = env.api.create_keypair()
        with file(privname, 'w') as fout:
            fout.write(keypair['privateKey'])
        with file(pubname, 'w') as fout:
            fout.write(keypair['publicKey'].rstrip())
            fout.write(' {0} (generated remotely)\n'.format(keyname))
        pubkey = keypair['publicKey'].rstrip()
        keyparts = pubkey.split()
        keyparts[2:] = [keyname]
    # Create the pubkey in the API under a unique name
    pubkeys = env.api.get_pubkeys()
    keyname = util.get_unused_name(keyname, pubkeys)
    keyparts[2] = keyname
    keydata = '{0} {1} {2}\n'.format(*keyparts)
    pubkey = {'name': keyname}
    pubkey['publicKey'] = keydata
    pubkey = env.api.create_pubkey(pubkey)
    with file(pubname, 'w') as fout:
        fout.write(keydata)
    env.public_key = pubkey
    env.private_key_file = privname
    return pubkey
dataset/ETHPy150Open ravello/testmill/lib/testmill/keypair.py/create_keypair/original