How to stop/kill an autossh tunnel?
Now that I have a autossh tunnel, what is correct way to stop it?
There seems to be no easy way to do this. Documentation is unclear on this part.
The easy way seems to be to reboot the machine? Is this correct?
No, the proper way to kill autossh
is simply to kill the process autossh
, nothing else.
The reason is
# file $(which autossh)
/usr/bin/autossh: POSIX shell script, ASCII text executable
that autossh
is simply a shell script, not a service. It starts a new program, in its very last line,
exec /usr/lib/autossh/autossh "$@"
again not a service. As for exec
(you can double-check it in the wiki of the Bash hackers), it is a shell-builtin command which replaces the current shell with the following command (/usr/lib/autossh/autossh "$@"
in this case) without starting a new process. So, the only way to stop autossh
is to kill the calling script, for instance
pkill -3 autossh
(thanks to dviljoen for pointing out the importance of using the -3 flag, see below). Incidentally, killing the ssh
connection will not work, because the calling command (i.e., the one above) will simply start a new connection as soon as it realizes the old one has been dropped.
run auto ssh with:
AUTOSSH_PIDFILE=/var/run/tunnel.pid autossh
kill it with:
kill pid
BTW
pkill -9 autossh
is a wrong
-9
makes sure the process not exiting gracefully, so ssh
process is still there when the autossh
process is killed
without -9
is still bad, if you have multiple tunnels running, pkill
will kill them all
correct way is to set AUTOSSH_PIDFILE
env var then kill
that pid only