SSH tunnel to Raspberry Pi

3 min read

You may want to be able to connect to your RPi which placed in home without static IP. The simplest solution is the using of the common server.

Raspberry will have stable connection to it by the internal service command. And you as a user can get there by jumping from one ssh connection to another.

The common server needs to know the both public keys of your computer and the RPi.


Firstly you need to generate a new ssh key on the Raspberry.


You will be asked about key name and password. Left these fields with default values.

Then you need to place RPi's public key to the common server to /root/.ssh/authorized_keys file.

Try to connect to that server from RPi.

ssh [email protected]<COMMON_SERVER_IP> -p 22

If it is the first attempt to connect to that server with current machine then you will be asked for adding this destination to known hosts list. Agree it.


Now we are going to create a service which will be started automatically. It creates an SSH session between RPi and common server.


Create a service config.

nano /etc/systemd/system/tunnel.service

Place into this file the following code.

[Unit] Description=SSH Tunnel with target server [Service] ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -R -p 12345 [email protected] RestartSec=5 Restart=always [Install]

And you may need a few comments about the main command.

Request to port 10000 on the common server will be redirected to 22 port on RPi.

Also if you have custom port for SSH connections on that server, you may pass it as -p 12345 option as in example or remove it if you use default.

And the last and the obvious thing — [email protected] — username and IP address of the common server.

You can test this command before running service.

/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -R -p 12345 [email protected]

And on the server's side you can check if the port 10000 was used correctly via netstat -tulpn.

Middleware server


Update config files for services.

systemctl daemon-reload

Start tunnel service.

systemctl start tunnel

Enable run on boot.

systemctl enable tunnel

Check service state.

systemctl status tunnel


Make sure that common server has a public ssh key of the your computer first.

Now you can connect to RPi (you -> server -> RPi) via the following command from everywhere. Of course use your own params for server IP and port.

ssh -J [email protected]:12345 -p 10000 [email protected]


Setup a secure (SSH) tunnel as a systemd service //

SSH tunnel to Pi via my own server //

Creating a Linux service with systemd //