【问题标题】:Amazon ec2 python boto, spawning and connecting to server instance, cannot ssh into spawned instancesAmazon ec2 python boto,生成并连接到服务器实例,无法通过 ssh 进入生成的实例
【发布时间】:2014-02-03 01:46:44
【问题描述】:

我正在生成 python 代码来分析 Amazon EC2 提供的各种服务器 AMI 的性能。我目前在尝试 ssh 到我生成的实例时遇到问题。我已经通过他们的网络界面成功地做到了这一点,但不能以编程方式。

下面的代码使用以编程方式生成的安全组和密钥对(保存在本地)生成单个 Red hat AMI。实例运行后,我尝试使用保存的密钥对(在它已被 chmod 400'd 之后)通过 ssh 进入实例,但 ssh 命令冻结不产生任何输出。

代码:

#!/usr/bin/env python

import sys
from boto.ec2 import EC2Connection

#Fill in with your respective keys
awsAccessKey = "" 
awsSecretKey = ""

#All AMI instance names from the free tier 
#In the EC2 panel, goto "instances" -> "launch instance" -> "free tier"
amiNameArr = ["ami-bba18dd2","ami-a25415cb","ami-e8084981","ami-ad184ac4","ami-7527031c"]
#Lets just use a varying set of AMI's 
amiDescArr = ["Amazon Linux","Red Hat Enterprise","SUSE Enterprise", 
              "Ubuntu Server 13.10","Microsoft Server 2012"]
#AMI Instance types, physical machine types that the AMIs run on; ti.micro only free one
#In order of optimizations: Micro, General, Memory, Storage, Compute 
amiInstTypesArr = ["t1.micro",
                   "m1.small","m1.medium","m1.large","m1.xlarge","m3.medium",
                   "m2.xlarge","m2.2xlarge","m2.4xlarge",
                   "hi1.4xlarge","hs1.8xlarge",
                   "c1.medium","c1.large","c3.large","c3.xlarge","c3.2xlarge"]

if __name__ == "__main__":
    from time import gmtime, strftime
    sessionStart = strftime("h%Hm%Ms%S", gmtime())
    #Connect to amazon AWS
    print("\nConnectiong to AWS, start time: " + sessionStart)
    awsConn = EC2Connection(awsAccessKey, awsSecretKey)
    connParms = awsConn.get_params()
    print("Connected with access key id: " + str(connParms['aws_access_key_id'])) 

    #Create a key pair for this session
    print("Creating key pair...")
    keyPairName = "AWSAnalysisKeyPair" + sessionStart
    awsKeyPair = awsConn.create_key_pair(keyPairName)
    awsKeyPair.save("~")
    print("Saved key pair: " + keyPairName)

    #Create a security group for all server instances to use
    print("Creating security group...")
    securityGroupName = "AWSAnalysisSecurityGroup" + sessionStart
    securityGroupDesc = "For access and analysis of programmatically spawned machines"
    awsSecGroup = awsConn.create_security_group(securityGroupName, securityGroupDesc)
    awsSecGroup.authorize('tcp',22,22,'0.0.0.0/0',awsSecGroup)
    awsSecGroup.authorize('tcp',80,80,'0.0.0.0/0',awsSecGroup)

    #Start spawning new server instances!
    #For each AMI, create all machine instance types we can
    print("Spawning instances...")
    for amiIndx in range(1, 2): #len(amiNameArr)):
        print("   AMI description: " + str(amiDescArr[amiIndx]))
        for typeIndx in range(0, 1): #len(amiInstTypesArr)):
            print("      starting machine: " + str(amiInstTypesArr[typeIndx]))
            awsConn.run_instances(
                amiNameArr[amiIndx],
                instance_type = amiInstTypesArr[typeIndx],
                security_groups = [securityGroupName],
                key_name = keyPairName,
                max_count = 1
            )

    #We now want to get information about each machine instance so we can analyze it


    #conn.get_all_instances() returns a list of Reservation objects
    from pprint import pprint
    print("All spawned instance information")
    reservations = awsConn.get_all_instances()
    instances = [i for r in reservations for i in r.instances]
    for i in instances:
        #pprint(i.__dict__) #Shows all possible instance info
        print("- id: " + str(i.__dict__['id']) + "\n"
              "   image: " + str(i.__dict__['image_id']) + "\n" + 
              "    type: " + str(i.__dict__['instance_type']) + "\n" + 
              "   state: " + str(i.__dict__['state']) + "\n" )

通过查看在线 EC2 界面,我知道我正在生成一个实例并且它正在运行,并且它具有以编程方式生成的密钥对和与之关联的安全组。鉴于它与这两个相关联,我不得不弄清楚我的问题在于我如何构建密钥对和安全组。

我是否正确构建了安全组和密钥对?还有其他原因导致我无法通过 ssh 访问这些实例吗?

我也知道我正确地尝试使用 ssh 访问机器实例,因为我可以通过从 Web 界面生成实例并通过 ssh 进入它们来成功地做到这一点。

【问题讨论】:

  • 您使用哪个用户进行连接。在 RedHat 和 Amazon Linux 上,您必须使用 ec2-user。在 Ubuntu 上,使用 ubuntu

标签: python linux amazon-web-services ssh amazon-ec2


【解决方案1】:

我刚刚测试了您的脚本 - 确实 - 它没有按预期工作 :-)

首先,它在最后一行崩溃。 “状态”信息现在在名为“_state”的属性中返回。因此,您需要将第 76 行更改为:

  "   state: " + str(i.__dict__['_state']) + "\n" )

其次,您的密钥对、SG 和实例已创建,但如果我们在控制台中查看 SG 定义,您会看到

“来源”是安全组本身的名称。这意味着只有在同一安全组中运行的其他 EC2 实例才能连接到这些端口,而不是您的笔记本电脑。

您不应在authorize API 调用中添加 SG 对象。下面修改后的代码就可以了:

awsSecGroup.authorize('tcp',22,22,'0.0.0.0/0')
awsSecGroup.authorize('tcp',80,80,'0.0.0.0/0')

我刚刚用上面的两个修改测试了你的脚本,它按预期工作。

$ ssh -i ~/AWSAnalysisKeyPairh09m55s41.pem ec2-user@184.72.84.162
Warning: Permanently added '184.72.84.162' (RSA) to the list of known hosts.
[ec2-user@ip-10-151-40-134 ~]$ uname -a
Linux ip-10-151-40-134 2.6.32-358.14.1.el6.x86_64 #1 SMP Mon Jun 17 15:54:20 EDT 2013 x86_64 x86_64 x86_64 GNU/Linux
[ec2-user@ip-10-151-40-134 ~]$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.4 (Santiago)

--Seb
AWS EMEA 技术讲师

【讨论】:

    猜你喜欢
    • 2013-01-06
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多