2

I have a hostlist and there are several hosts. I want to use ssh to connect to them. I want to see whether the host is available or not by the time length of ssh takes. If it take long than 5s (which means it is not available). Then stop it, and ssh to next host. Once a host is available, then output the name of host. I previously use nmap, but the IT security told it is not allowed to install it on the desktop on campus.

HOSTS=`cat $host_list`
for line in $HOSTS
do 
ssh -o ConnectTimeout=5s $line true >> /dev/null
RESULT=$?
if [ $RESULT -eq 0 ]
then
echo $line > succeed.txt
else
echo $line > fail.txt
fi
done

The above script is all I can do. The problem is when it is failed, I want to redirect the error message ssh: connect to host c28-0112-05.ad.mtu.edu port 22: No route to host. But I still get the error message.

2 Answers 2

0

Close enough:

timeout -5s "ssh $line true"

That is:

  1. Use correct quotes. timeout `ssh …` cannot possibly work here, because it means "run 'ssh', capture its output, then give the output to 'timeout'."

  2. Run ssh in "batch" mode, that is, give it a command to run. Without it, ssh will run in interactive mode, and will hang forever even on successful connections.

You could also try:

ssh -o ConnectTimeout=5s $line true
1
  • Thanks. I tried ssh -o ConnectionTimeout=5s c15-0330-01.ad.mtu.edu true. It works and nothing is returned. But how can it return the name of host(I am new about Linux). And when I connect to a host (I know it is offline), it returns ssh: connect to host c15-0331-01.ad.mtu.edu port 22: No route to host. I want make it as: when ssh succeeds, then echo $line > host_available.
    – Ben
    May 24, 2015 at 20:48
0

ssh has the -o switch, which allows you to provide additional options. Of particular use here is the ConnectTimeout option, which takes an arguement specified in seconds:

ssh -o ConnectTimeout=5 123.123.123.123

In addition, ConnectionAttempts might also be useful to you.

1
  • Thanks. I tried ssh -o ConnectionTimeout=5s c15-0330-01.ad.mtu.edu true. It works and nothing is returned. But how can it return the name of host(I am new about Linux). And when I connect to a host (I know it is offline), it returns ssh: connect to host c15-0331-01.ad.mtu.edu port 22: No route to host. I want make it as: when ssh succeeds, then echo $line > host_available.
    – Ben
    May 24, 2015 at 20:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .