Create persistent SSH proxy with autossh

This one is similar to persistent local SSH server forwarding setup (although much more simple). Preparation part is exactly the same, so if you've already done that, you may skip it and go straight to persistent SSH proxy configuration.

After each file and command there will be a location label: @computer for your local computer, @server for remote server — so that you don't get confused what to do/get/put where.

Preparation

  1. Create proxy user on the server:
    sudo adduser ergo-proxy @server

  2. Set up key based authentication for ergo-proxy@example.com.
    We will assume that you private key is ~/.ssh/id_rsa_proxy @computer and that you can successfully connect (thus example.com is in known hosts list).

  3. Install autossh:
    sudo apt install autossh @computer

  4. Create a systemd service for keeping connection alive with autossh:
    mkdir -p ~/.config/systemd/user && touch $_/autossh@.service @computer
    And copy this to ~/.config/systemd/user/autossh@.service @computer:

    [Unit]
    Description = Keeps a '%i' tunnel alive
    After = network-online.target
    Conflicts = shutdown.target
    
    [Service]
    ExecStart = /usr/bin/env autossh -M 0 -NTq %i
    Restart = always
    RestartSec = 60
    
    [Install]
    WantedBy = default.target
    
  5. Disable shell for proxy user:
    sudo chsh -s /usr/sbin/nologin ergo-proxy @server

Create persistent proxy

  1. Edit SSH client config (~/.ssh/config @computer), adding this section:

    Host proxy
        Hostname example.com
        User ergo-proxy
        IdentityFile ~/.ssh/id_rsa_proxy
        DynamicForward localhost:8888
        ServerAliveInterval 30
        ServerAliveCountMax 3
    
  2. Enable and start persistent proxy service:
    systemctl --user --now enable autossh@proxy @computer

  3. That's it! You now have a proxy listening on localhost:8888