ssh tunnel via userspace systemd service

Post navigation

[image above is a screenshot of 0pointer.de – in place of a systemd logo]

This is short how-to on setting up a systemd service that is run from a user account.

In the /etc/systemd/system directory:

a) create a service file that implements the service. In my case, I wanted to set up a service that would be started at boot and run under my userid. This service is to set up a ssh tunnel to a system that is on another, external network.

b) This is a service that is to be started after the network.target is reached – obviously, no network, nothing happens. Then the section [Service] has details as to who’s UID it is to be invoked. Included are the User, Group, and WorkingDirectory details. The file that is to be run when this service is started is called sshpipe.sh and that is also indicated.

c) As can be seen above, the sshpipe.sh is invoked under my UID and in this case, because I am have set it up as passwordless ssh connection (which you have set up earlier), the command will work seamlessly.

Essentially, the command says that is run (in my case a Red Hat Enterprise Linux 7.5 system running in an Intel NUC RYBDWi35) is connecting to port 2048 on the remote host 10.10.10.10 under my UID and linking back up port 22 on this NUC. So, when I log into 10.10.10.10, I can run:

$ ssh -p 2048 localhost

and I am back into the NUC.

e) So, once the systemd service file, in this case, ssh-tunnel.service is created, you will have to enable it and start it.

The reason I had the script was because it was something I have been using for a long time – predates systemd and since I wanted to make sure that I could work this tunnel with systemd, I just kept the script.