简体   繁体   English

使用 Boto3 在 AWS 上创建新的 EC2 密钥对

[英]Create new EC2 keypair on AWS with Boto3

The boto3 1.1.2 docs say that the create_key_pair command is supposed to return a dict containing the private key of the newly created keypair. boto3 1.1.2 文档create_key_pair命令应该返回一个包含新创建的密钥对的私钥的字典。

I am indeed using that version…我确实在使用那个版本......

>>> import boto3
>>> boto3.__version__
'1.1.2'

…yet when I run create_key_pair I am instead returned a KeyPair object which does not appear to contain any information about the private key. …然而,当我运行create_key_pair时,我反而返回了一个KeyPair对象,该对象似乎不包含任何有关私钥的信息。 The keypair does get created, it's just that I have no way of retrieving the private key because it is only ever available at the time of the keypair's creation .确实创建了密钥对,只是我无法检索私钥,因为它仅在创建密钥对时可用 Older boto APIs apparently had a .save method on the KeyPair object to save the key to a file, but that too appears to have been removed from the API.较旧的 boto API 显然在KeyPair对象上有一个.save方法来将密钥保存到文件中,但它似乎也已从 API 中删除。

In boto3 1.1.2, how does one create a new EC2 keypair and retrieve its private key?在 boto3 1.1.2 中,如何创建新的 EC2 密钥对检索其私钥?

The private key is available in keypair['KeyMaterial'] :私钥在keypair['KeyMaterial']中可用:

>>> import boto3
>>> ec2 = boto3.client('ec2')
>>> keypair = ec2.create_key_pair(KeyName='foo')
>>> keypair['KeyMaterial']
'-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCA...\n-----END RSA PRIVATE KEY-----'

References:参考:

In the new versions of boto3 (I'm using 1.4.7) change this line:在新版本的 boto3(我使用的是 1.4.7)中更改此行:

keypair['KeyMaterial']

to

keypair.key_material

Add the feature to save to local keypair file添加保存到本地密钥对文件的功能

$ cat keypair.py

import boto3

keypair_name = "python_keypair"

ec2 = boto3.client('ec2')
keypair = ec2.create_key_pair(KeyName=keypair_name)

private_key_file=open(keypair_name,"w")
private_key_file.write(response['KeyMaterial'])
private_key_file.close

now you should get the private key locally现在你应该在本地获取私钥

$ cat python_keypair.pem

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA14D9GAC7zVSRr3iHUyEaIF8ol5ccWBj9InVqYnF28l10EUCz
g5OLL5Ll6WiIYvlxhcRHM5d0os2Lg5SuKi0mTktYQ7QVD8RkdoEYIVrqgBir3VMf
8jG08JRhaJs4/OQk2+WAGecjcVx6joz9yXTRT3Maaec/4qNigfYMLpSsdAoZ0hrk
....

move it to ~/.ssh and change permission to 600将其移至~/.ssh并将权限更改为 600

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM