Skip to content

SSH setup (tunnel, autossh)

Ezio Melotti edited this page Nov 5, 2024 · 1 revision

SSH tunnel

This section describes how to set up and use an SSH tunnel in the following scenario:

flowchart LR

PC[PC] --ssh--> S[Server] <--ssh tunnel--> R[RPi4]
Loading

Here we want to connect to the RPi4 from a PC. In order to access the RPi4, we need to:

  1. create an SSH tunnel from the RPi4 to the server:
    ssh -R 10000:localhost:22 user@server_address
    (user must exist on the server, and you need to know the password.)
  2. From your PC, connect to the server normally:
    ssh user@server_address
    (user must exist on the server, and you need to know the password. It can be a different user.)
  3. From the server, connect to the RPi4:
    ssh user@localhost -p 10000

Automate SSH tunnel creation with autossh

In order to automatically set up the tunnel when the RPi4 boots:

  1. Install autossh

    sudo apt install autossh
  2. Generate an SSH key:

    ssh-keygen -t rsa
  3. Copy it to the server:

    ssh-copy-id user@server_address

    (user must exist on the server, and you need to know the password.)

  4. Create the following systemd service:

    sudo vim /etc/systemd/system/autossh-tunnel.service
    [Unit]
    Description=AutoSSH Tunnel Service
    After=network.target
    
    [Service]
    User=pi
    Environment="AUTOSSH_GATETIME=0"
    ExecStart=/usr/bin/autossh -M 0 -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -N -R 10000:localhost:22 user@server_address
    Restart=always
    RestartSec=10
    
    [Install]
    WantedBy=multi-user.target

    (Remember to update the user and server_address.)

  5. Enable, start, and check the status of the service:

    sudo systemctl daemon-reload
    sudo systemctl enable autossh-tunnel
    sudo systemctl start autossh-tunnel     
    sudo systemctl status autossh-tunnel
  6. Reboot and hope that it works:

    sudo reboot
  7. If everything worked you will be able to connect to the RPi4 from the server using:

    ssh user@localhost -p 10000

    as described in the previous section.