-
Notifications
You must be signed in to change notification settings - Fork 1
SSH setup (tunnel, autossh)
Ezio Melotti edited this page Nov 5, 2024
·
1 revision
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]
Here we want to connect to the RPi4 from a PC. In order to access the RPi4, we need to:
- 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.) - 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.) - From the server, connect to the RPi4:
ssh user@localhost -p 10000
In order to automatically set up the tunnel when the RPi4 boots:
-
Install
autossh
sudo apt install autossh
-
Generate an SSH key:
ssh-keygen -t rsa
-
Copy it to the server:
ssh-copy-id user@server_address
(
user
must exist on the server, and you need to know the password.) -
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
andserver_address
.) -
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
-
Reboot and hope that it works:
sudo reboot
-
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.