I would like to create a shell script for rebooting a linux machine in a way that the script just ends when the machine is up and running again (by up and running I mean accepting ssh connections).
The script should perform like (pseudocode):
reboot machine #sth like 'ssh root@MACHINE reboot'
respecting a timeout of 120 secods do:
try to connect to machine by ssh
sleep one second if it could not connect
return an error if timed out
return ok if machine is ready for ssh connections
The thing is that I would really like to avoid long sleep commands so that my reboot script gives a result as soon as possible (if it is not a timeout, of course).
Anyone has done something like that?
UPDATE: Starting from adamo's idea I did:
timeout=120
start=$(date +%s)
ssh root@$FAST_HOST reboot
do
nc -z $1 22
if [ $? eq 0]; then
echo host is ready
exit 0
fi
end=$(date +%s)
diff=$(( $end - $start ))
if [ $diff -gt timeout ]
echo timeout
exit 1
fi
sleep 1
done
My problem is that the nc command takes a long while to return when it can not connect. Any way just to check if the port is open with a very short timeout?