Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I have a script which creates a virtual machine and gives me back an IP address. Then I would like to do something like this:

waitforssh 192.168.2.38 && ssh 192.168.2.38

And it will wait for the machine to be up and ssh to be responding, then ssh into it.

waitforssh is the command I need to find.

Would nmap, netcat, fping or ping do the job? I tried netcat but it gives up in just a couple of seconds if the host is unreachable.

It needs to handle the fact that the machine itself is booting and might take some time to respond to network packets.

share|improve this question

migrated from stackoverflow.com Jun 19 '10 at 16:49

This question came from our site for professional and enthusiast programmers.

2 Answers 2

up vote 4 down vote accepted

I don't have a host that I can ssh to and control whether it's up or not, but this should work:

while ! ssh <ip>
do
    echo "Trying again..."
done

Or a shell script that is more explicit:

#!/bin/sh

ssh $1
while test $? -gt 0
do
   sleep 5 # highly recommended - if it's in your local network, it can try an awful lot pretty quick...
   echo "Trying again..."
   ssh $1
done

Save it as (say) waitforssh.sh and then call it with sh waitforssh.sh 192.168.2.38

share|improve this answer
    
This works pretty good! The sleep 5 won't be necessary as this is all local machines. Thanks! –  Weboide Jun 19 '10 at 19:43
    
Beware IDS/IPS (Intrusion Detection/Prevention Systems) that may see this as a SSH scan or attack. –  Jason Jun 20 '10 at 1:55

The ssh command can be given a command to perform on the remote machine as the last paramater. So call ssh $MACHINE echo in a loop. On success it returns 0 in $?, on failure 255. You must of course use paswordless authentication with certificates.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.