Scripting

Systemd Ssh

Setup systemd service file for keeping ssh reverse tunnel open

Prereqs

  • You will need working ssh key
  • You will need to have logged in and accepted host keys (this is possible to override but better to just specify the user in this file instead.
  • This example connects to secure.example.com

Create Service File

sudo vi /etc/systemd/system/secure-tunnel@.service

[Unit]
Description=Setup a secure tunnel to %I
After=network.target

[Service]
User=PUT_YOUR_LOCAL_USERNAME_HERE
Environment="LOCAL_ADDR=localhost"
EnvironmentFile=/etc/default/secure-tunnel@%i
ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -R ${LISTEN_ADDR}:${LISTEN_PORT}:${LOCAL_ADDR}:${LOCAL_PORT} -l ${TARGET_USER} -p ${TARGET_PORT} -i ${LOCAL_ID_FILE} ${TARGET}

RestartSec=5
Restart=always

[Install]
WantedBy=multi-user.target

Then create the variables file: sudo vi /etc/default/secure-tunnel@secure.example.com

TARGET=secure.example.com
TARGET_PORT=2222
TARGET_USER=jumpboxuser
LOCAL_USER=myuser
LOCAL_PORT=22
LOCAL_ADDR=127.0.0.1
LISTEN_ADDR=127.0.0.1
LISTEN_PORT=12345
LOCAL_ID_FILE=/home/myuser/.ssh/id_rsa

Start service: sudo systemctl daemon-reload sudo systemctl start secure-tunnel@secure.example.com.service

Debug with: sudo journalctl -f -u secure-tunnel@secure.example.com.service

Enable on reboot with:

sudo systemctl enable secure-tunnel@secure.example.com.service