Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 && ssh

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 Jun 19 '10 at 16:49

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

up vote 5 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>
    echo "Trying again..."

Or a shell script that is more explicit:


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

Save it as (say) and then call it with sh

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

Well, I'm not sure what you mean by to be up, but what about:

$ ping | grep --line-buffered "bytes from" | head -1 && ssh

First command ping | ... | head -1 waits for server to sent single ping reply and exists. Then ssh comes into play. Be aware that grep can buffer output, so this is what --line-buffered is for.

You can wrap this command with bash function to use it exactly the way you've described.

$ waitfor() { ping $1 | grep --line-buffered "bytes from" | head -1 }
$ waitfor && ssh
share|improve this answer

Your Answer


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.