ubuntusshsystemdsystemctlautossh

Autossh script running as systemctl start SERVICE works but systemctl enable SERVICE failed


We are trying to get autossh to connect to remote server at boot time in Ubuntu 16.04.2. So we use systemctl to do the job. The script is as following:

[Unit]
Description=Keeps a tunnel to 'remote server' open
After=network.target

[Service]
ExecStart=/usr/bin/autossh -NR 83232:localhost:22 -i /home/user/.ssh/id_rsa REMOTE_USER@REMOTE_IP

[Install]
WantedBy=multi-user.target

It would work fine if we start the service by using start

systemctl start SERVICE

But it would fail if we use enable service

systemctl enable SERVICE

The error code is

“ssh: connect to host REMOTE_IP port 22: Network is unreachable”

Can anybody offer any advices?

Many thanks.


Solution

  • Instead of After=network.target, use After=network-online.target.

    More about systemd network targets are documented on the systemd wiki page.