How to check if SSH connection was established with AWS instance
The message "SSH Connection refused, will retry in 5 seconds" is coming from boto: http://code.google.com/p/boto/source/browse/trunk/boto/manage/cmdshell.py
Initially, 'running' just implicates that the instance has started booting. As long as sshd
is not up, connections to port 22 are refused. Hence, what you observe is absolutely to be expected if sshd
does not come up within the first 25 seconds of 'running' state.
Since it is not predictable when sshd
comes up exactly and in case you do not want to waste time by just defining a constant long waiting period, you could implement your own polling code that in e.g. 1 to 5 second intervals checks if port 22 is reachable. Only if it is invoke boto.manage.cmdshell.sshclient_from_instance()
.
A simple way to test if a certain TCP port of a certain host is reachable is via the socket
module:
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()