p1=pexpect.spawn('/usr/bin/ssh ' + ' -o HostKeyAlias=' + source_server_ip + ' ' + source_server_user + '@'+ source_server_ip )
now you can expect output returns as follows and handle those situation:
try:
i=p1.expect(['password:',pexpect.TIMEOUT,pexpect.EOF,'continue connecting (yes/no)?','Host key verification failed.','Connection refused','Connection timed out'],timeout=120)
if i==1:
logging.error('Timeout')
logging.debug(p1.before)
sys.exit()
if i==2:
logging.error('Reached EOF')
logging.debug(p1.before)
sys.exit()
if i==3:
p1.sendline('yes')
logging.info('RSA Key added')
p1.expect('password:',timeout=MIN_TIMEOUT_TIME)
if i==4:
logging.info('Host key Changed,calling edit_known_hosts('+ip+')')
edit_known_hosts(ip)
logging.info(ip + " removed from known_hosts,calling Connect() again")
Connect()
if i==5:
logging.error('Connection refused by server')
sys.exit()
if i==6:
logging.error('Connection timed out')
sys.exit()
logging.info('sending password:' + password)
p1.sendline(password) ## here you can specify password if everything went fine you are logged in to remote system.
except Exception,e:
print ('error:',str(e))
you can explore more from Python Official documentation it was just a snapshot. Peexpect provides a simple and quite effective situation handling.
Note : peexpect module is not yet available for windows systems you can only use it in Linux flavors.