Ubuntu – autossh works as expected by systemd setup for boot fails

sshssh-tunnelsystemdUbuntu

So I setup my ssh variables to do a reverse tunnel in ~/.ssh/config and called the host tunnel_reverse. I tested the following command to create a persisting tunnel with autossh and it worked just as expected:

    autossh -M 0 -N tunnel_reverse

I was able to connect to the remote computer from a laptop after the remote host reverse tunnel was created. However, when I tried to setup a service file so it could autostart at bootup with systemd, it wouldn't work. Here's the /etc/systemd/system/tunnel.service file I created:

    [Unit]
    Description=AutoSSH to reverse tunnel
    After=network.target

    [Service]
    Environment="AUTOSSH_GATETIME=0"
    ExecStart=/usr/bin/autossh -M 0 -v -N tunnel_reverse

    [Install]
    WantedBy=multi-user.target

so I started that with

    systemctl daemon-reload
    systemctl restart tunnel.service
    systemctl status tunnel.service

Viewing the status log, it seems there is an error that reads:

    debug1: Server host key: blah blah blah
    debug1: read_passpphrase: can't open /dev/tty: No such device or address
    Host key verification failed.
    ssh exited with error status 255; restarting ssh

Where did I go wrong?

Best Answer

It looks like the ssh session started by systemd is looking for a password. I am assuming that when you are running autossh manually it uses public key authentication, and that the public key is stored in the home directory of the user who's executing this (your reference to ~/.ssh does not say which user's home directory it is). The autossh executed by systemd should be running as the same user and have access to the same .ssh directory, otherwise it will not be able to use the same username/password combination.

You can specify username the the service should run by adding User= directive to the Service section of tunnel.service file.