How to do ssh with a timeout in a script?

后端 未结 6 1354
野趣味
野趣味 2020-12-12 11:17

I\'m executing a script connecting via password-less SSH on a remote host. I want to set a timeout, so that if the remote host is taking an infinite time to run, I want to c

6条回答
  •  [愿得一人]
    2020-12-12 11:41

    If all else fails (including not having the timeout command) the concept in this shell script will work:

     #!/bin/bash
     set -u
     ssh $1 "sleep 10 ; uptime" > /tmp/outputfile 2>&1 & PIDssh=$!
     Count=0
     while test $Count -lt 5 && ps -p $PIDssh > /dev/null
     do
        echo -n .
        sleep 1
        Count=$((Count+1))
     done
     echo ""
    
     if ps -p $PIDssh > /dev/null
     then
        echo "ssh still running, killing it"
        kill -HUP $PIDssh
     else
        echo "Exited"
     fi
    

提交回复
热议问题