Skip to content

Instantly share code, notes, and snippets.

@ivanmorenoj
Last active May 5, 2023 09:07
Show Gist options
  • Save ivanmorenoj/c34aaf2a782278fa245d4dac00df0975 to your computer and use it in GitHub Desktop.
Save ivanmorenoj/c34aaf2a782278fa245d4dac00df0975 to your computer and use it in GitHub Desktop.
Systemd template for local ssh port forwarding at startup
[Unit]
Description=Setup a dynamic tunnel to %I
After=network.target
[Service]
EnvironmentFile=/etc/default/dynamic-tunnel@%i
ExecStart=/usr/bin/ssh -i ${PATH_TO_KEY} -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -nNT -D ${LOCAL_PORT} ${REMOTE_USER}@${REMOTE_HOST}
RestartSec=15
Restart=always
KillMode=mixed
[Install]
WantedBy=multi-user.target
PATH_TO_KEY=/home/remote_user/.ssh/key-remote-server
LOCAL_PORT=6789
REMOTE_USER=remote_user
REMOTE_HOST=remote_server
[Unit]
Description=Setup a local tunnel to %I
After=network.target
[Service]
EnvironmentFile=/etc/default/local-tunnel@%i
ExecStart=/usr/bin/ssh -i ${PATH_TO_KEY} -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -nNT -L ${LOCAL_PORT}:${REMOTE_ADDR}:${REMOTE_PORT} ${REMOTE_USER}@${REMOTE_HOST}
RestartSec=15
Restart=always
KillMode=mixed
[Install]
WantedBy=multi-user.target
PATH_TO_KEY=/home/db_user/.ssh/key-db-server
LOCAL_PORT=8080
REMOTE_ADDR=localhost
REMOTE_PORT=9090
REMOTE_USER=db_user
REMOTE_HOST=db-server
[Unit]
Description=Setup a remote tunnel to %I
After=network.target
[Service]
EnvironmentFile=/etc/default/remote-tunnel@%i
ExecStart=/usr/bin/ssh -i ${PATH_TO_KEY} -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -nNT -R ${REMOTE_PORT}:${LOCAL_ADDR}:${LOCAL_PORT} ${REMOTE_USER}@${REMOTE_HOST}
RestartSec=15
Restart=always
KillMode=mixed
[Install]
WantedBy=multi-user.target
PATH_TO_KEY=/home/gtw_user/.ssh/key-gtw-server
LOCAL_ADDR=localhost
LOCAL_PORT=80
REMOTE_PORT=80
REMOTE_USER=gtw-user
REMOTE_HOST=gtw-server
@andycol
Copy link

andycol commented May 5, 2023

Greetings colleagues. Tell me what I need to add in the config. to make my unit work. I'm setting up ssh sock-proxy. In the terminal, the command looks like this: ssh -D 0.0.0.0:8080 user@remoteserver -i /home/user/.ssh/id_rsa

easy just change
ExecStart=/usr/bin/ssh -i ${PATH_TO_KEY} -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -nNT -R ${REMOTE_PORT}:${LOCAL_ADDR}:${LOCAL_PORT} ${REMOTE_USER}@${REMOTE_HOST}

to
ExecStart=/usr/bin/ssh -i ${PATH_TO_KEY} -D 0.0.0.0:${REMOTE_PORT} ${REMOTE_USER}@${REMOTE_HOST} then set variables accordingly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment