簡體   English   中英

Amazon EC2 Python Boto,產生並連接到服務器實例,無法ssh進入產生的實例

[英]Amazon ec2 python boto, spawning and connecting to server instance, cannot ssh into spawned instances

我正在生成python代碼,以分析Amazon EC2提供的各種服務器AMI的性能。 我目前在嘗試進入生成的實例時遇到問題。 我已經通過他們的Web界面成功完成了此操作,但是無法通過編程方式進行。

下面的代碼生成帶有編程生成的安全組和密鑰對(存儲在本地)的單個Red hat AMI。 實例運行后,我嘗試使用已保存的密鑰對ssh進入實例(在chmod 400之后),但是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訪問機器實例,因為我可以成功地做到這一點,方法是從Web界面生成實例並ssh進入它們。

我剛剛測試了您的腳本,確實-它無法按預期工作:-)

首先,它在最后一行崩潰。 現在,在名為“ _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技術講師

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM