2013-03-21 61 views
9

我试图通过SSH连接到Amazon EC2实例,使用boto。我知道ssh连接可以在实例创建一段时间后建立。所以我的问题是:如何检查是否与AWS实例建立SSH连接

  • 我能以某种方式检查SSH是否在实例上? (如果是这样,怎么办?)
  • 或者我该如何检查boto.manage.cmdshell.sshclient_from_instance()的输出?例如,如果输出打印出Could not establish SSH connection,则比再试一次。

这就是我想,到目前为止,但没有运气:

if instance.state == 'running': 
    retry = True 
    while retry: 
     try: 
      print 'Connecting to ssh' 
      key_path = os.path.join(os.path.expanduser('~/.ssh'), 'secret_key.pem') 
      cmd = boto.manage.cmdshell.sshclient_from_instance(instance, 
                   key_path, 
                   user_name='ec2-user') 

      print instance.update() 
      if cmd: 
       retry = False 
     except: 
      print 'Going to sleep' 
      time.sleep(10) 

SSH Connection refused, will retry in 5 seconds 
SSH Connection refused, will retry in 5 seconds 
SSH Connection refused, will retry in 5 seconds 
SSH Connection refused, will retry in 5 seconds 
SSH Connection refused, will retry in 5 seconds 
Could not establish SSH connection 

当然,一切工作正常,因为我可以在一段时间后推出相同的代码,并会得到一个连接,将能够使用cmd.shell()

回答

7

消息“SSH连接被拒绝,将在5秒后重试”从博托来:http://code.google.com/p/boto/source/browse/trunk/boto/manage/cmdshell.py

最初,“跑步”只是小鬼实例已启动引导的许可证。只要sshd没有启动,连接到端口22就会被拒绝。因此,如果sshd在“跑步”状态的前25秒内没有出现,您所观察到的绝对是可以预料的。

由于当sshd刚刚出现时无法预测,并且如果您不想通过定义恒定的长时间等待时间来浪费时间,则可以实现自己的轮询代码。 1到5秒间隔检查端口22是否可到达。只有当它调用boto.manage.cmdshell.sshclient_from_instance()

一个简单的方法来测试,如果某台主机的某个TCP端口可达是通过socket模块:

import socket 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
try: 
    s.connect(('hostname', 22)) 
    print "Port 22 reachable" 
except socket.error as e: 
    print "Error on connect: %s" % e 
s.close() 
+0

谢谢你,这是很聪明的。 – Vor 2013-07-15 14:32:43