首页 > 解决方案 > 使用 boto3 Python 在 aws 中创建实例

问题描述

我正在尝试使用 boto3 在 aws 中创建一个实例。

instance = ec2.create_instances(
ImageId='ami-15e9c770',
MinCount=1,
MaxCount=1,
InstanceType='t2.micro',
KeyName="xyz",
Placement={'AvailabilityZone':'us-east-2b'})

我正在使用此代码创建一个实例,但它不允许我连接到该实例。我在某处错了。我还需要做些什么才能通过 ssh 连接到该实例。

标签: amazon-web-servicesboto3

解决方案


使用此脚本连接到您的实例

import boto3
import botocore
import paramiko

key = paramiko.RSAKey.from_private_key_file(path/to/mykey.pem)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect/ssh to an instance
try:
    # Here 'ubuntu' is user name and 'instance_ip' is public IP of EC2
    client.connect(hostname=instance_ip, username="ubuntu", pkey=key)

    # Execute a command(cmd) after connecting/ssh to an instance
    stdin, stdout, stderr = client.exec_command(cmd)
    print stdout.read()

    # close the client connection once the job is done
    client.close()
    break

except Exception, e:
    print e

推荐阅读