Skip to content

Instantly share code, notes, and snippets.

Last active July 4, 2023 22:14
Star You must be signed in to star a gist
What would you like to do?
Systemd service for autossh
Description=Keeps a tunnel to '' open
# -p [PORT]
# -l [user]
# -M 0 --> no monitoring
# -N Just open the connection and do nothing (not interactive)
ExecStart=/usr/bin/autossh -M 0 -N -q -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -p 22 -l autossh -L 7474: -i /home/autossh/.ssh/id_rsa
Copy link

@jotakar I've been using:

Description=Keep open a reverse tunnel to my computer via the DMZ server

ExecStart=/usr/bin/ssh -NT tunnel


With tunnel defined in /root/.ssh/config as

Host                    tunnel
HostName                <redacted>
User                    <redacted>
IdentityFile    ~/.ssh/id_tunnel
ProxyCommand    ssh bastion -W %h:%p
RemoteForward   <redacted port> localhost:22
ExitOnForwardFailure yes
ServerAliveCountMax 5

And the bastion host also defined in the same file as

Host           bastion
HostName       <redacted>
User           <redacted>
IdentityFile   ~/.ssh/id_tunnel
ForwardAgent yes

I also have

Host *
ServerAliveInterval 60
IdentitiesOnly yes

at the top of my /root/.ssh/config, on the off-chance that's relevant.

I've found this to be very consistent and stable, and easy to test (ssh bastion, ssh -NT tunnel) when setting it up. Perhaps removing autossh and setting it up this way might help?

Copy link

mikkorantalainen commented Mar 22, 2023

For completeness, you should also add:

ExecStop=kill -9 autossh

Without it systemctl stop autossh won't do anything.

I think it would be better idea to add


to the .service file because that will kill everything that was started (recursively) and nothing more. In addition, it will first send SIGTERM and use SIGKILL only if the process will not stop nicely.

If you randomly kill one or all autossh processes in the system, you might kill more than expected if autossh is used for other stuff, too.

See for details

Copy link

MestreLion commented Jun 16, 2023

@jotakar :

What I see is that service stop autossh every few minutes, why? where is the error?

Don't use -f when using autossh as a systemd simple service. It will fork autossh (put in the background) and confuse systemd into thinking it ended.


Of course you do, without it autossh will give up if the very first connection attempt fails.

Systemd's Restart=always and RestartSec=60 can take care of that. You usually want autossh to fail fast if it can't do the first connection, as it usually means misconfiguration or authentication issues, and giving up after first attempt helps highlighting that on the journalctl logs.

Copy link

stokito commented Jul 4, 2023

JFYI: I created an SSH tunnel SystemD service that works without the autossh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment