I am sshing to a system and rebooting it in a while loop, however the ssh session does not close so the the script is just hanging after the first reboot. I have tried various ways to close it, any idea? I never get to the echo "test".

while true
echo "Executing SSH session to"
sshpass -p "pass" ssh -o StrictHostKeyChecking=no root@ << ! 
echo "test"
sleep 20


#! /bin/sh
if [  -e /dev/ttyUSB2 ]  && [  -e /dev/ttyUSB5 ]; then {
reboot -f
  • @RuiFRibeiro added reset.sh basically just reboots the system (the usb's are always there), I'll try replacing !
    – Paul
    Apr 13 '17 at 12:09
  • 3
    What happens if you just login manually on the command line and say reboot -f? Does the SSH session close nicely or is it left hanging? If the ssh client doesn't get any indication of the session closing when the server shuts down, it waits a potentially long time before noticing the connection is dead.
    – ilkkachu
    Apr 13 '17 at 12:22
  • @ilkkachu It's left hanging, I guess it is just waiting.
    – Paul
    Apr 13 '17 at 12:30

What can be happing is the remote session being lost as you are asking for a reboot, and so the system will hang some time waiting for the remote system to answer.

I would introduce before that sshpass a timeout command, like timeout or timelimit as in:

timeout 10s sshpass ...

As for ssh services, try to avoid using passwords, and instead use RSA certificate authentication. Not sure about that particular sshpass command, but often, if the binary being called does not takes precautions, the password can be seen with ps when used in the command line.

  • 1
    The word used in a here-document may be !, that's not a problem (other than being an odd choice of delimiter).
    – Kusalananda
    Apr 13 '17 at 12:15
  • 1
    I think ! is only special with history expansion, and that shouldn't be on by default in a noninteractive shell
    – ilkkachu
    Apr 13 '17 at 12:19
  • 1
    Thanks, timeout will do as ssh is just not getting a message to close.
    – Paul
    Apr 13 '17 at 12:32
  • 1
    Another option would be to use ServerAliveInterval and ServerAliveCountMax on the SSH client to ask it to check that the server stays responsive. ssh -oServerAliveInterval=1 ... would cut the connection after about 3 seconds of the server going silent, since the max count is 3 by default.
    – ilkkachu
    Apr 13 '17 at 12:43
  • 1
    sshpass's man page explicitly warns against using -p: "Sshpass makes a minimal attempt to hide the password, but such attempts are doomed to create race conditions without actually solving the problem.". Luckily, it also supports passing the password through the environment, or a file.
    – ilkkachu
    Apr 13 '17 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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