bashsshopensshsshdautossh

How can i exit, stop, kill autossh if connection timed out, ip, port not exists or response without using ssh and sshd config files?


I run autossh in a script for remote port forwarding and i need to exit, kill, stop the script if connection timed out, ip, port not exists or response, without the using of the ssh, sshd config files, is this possible? No answer, found on stacksites or the manpage of autossh.

Example 1:

myautossh script

#!/bin/bash

/usr/bin/autossh -NT -o "ExitOnForwardFailure=yes" -R 5555:localhost:443 -l user 1.1.1.1
if [ $? -eq 0 ]; then
  echo "SUCCESS" >> errorlog
else
  echo "FAIL" >> errorlog
fi

Example 2:

myautossh script

#!/bin/bash

/usr/bin/autossh -f -NT -M 0 -o "ServerAliveInterval=5" -o "ServerAliveCountMax=1" -o "ExitOnForwardFailure=yes" -R 5555:localhost:443 -l user 1.1.1.1 2>> errorlog
if [ $? -eq 0 ]; then
  echo "SUCCESS" >> errorlog
else
  echo "FAIL" >> errorlog
  kill $(ps aux | grep [m]yautossh | awk '{print $2}')
fi

IP 1.1.1.1 not exists in my network so it get a connection timeout, but the script and autossh is still running, checked with:

ps aux | grep [m]yautossh

or

ps x | grep [a]utossh

Can only terminate the script with ctrl+c

I want to run autossh in a script, try to connect to a not existing ip or port and terminate, exit, kill the process of autossh to continue my script, without config ssh & sshd config files, only with the options/commands of autossh and the using of -f for background, is this possible?


Solution

  • the use of timeout with --preserve-status is what you need

    timeout allows you to run a cmmand with a time limit

    Preserving the Exit Status, timeout with --preserve-status returns 124 when the time limit is reached. Otherwise, it returns the exit status of the managed command

    this will terminate the command after 2 seconds and returns the exit status of your command if not equal 0, command not success, you could not establish a successful conection

    #!/bin/bash
    timeout --preserve-status 2 /usr/bin/autossh -NT -o "ExitOnForwardFailure=yes" -R 33333:localhost:443 -l user 1.1.1.1 
    if [ $? -eq 0 ]; then
      echo "Connection success"
    else
      echo "Connection fail"
    fi 
    
    

    https://linuxize.com/post/timeout-command-in-linux/