Skip to content

Instantly share code, notes, and snippets.

@kamikat
Last active August 29, 2015 14:07
Show Gist options
  • Save kamikat/4530b0a9e2ecbf64e984 to your computer and use it in GitHub Desktop.
Save kamikat/4530b0a9e2ecbf64e984 to your computer and use it in GitHub Desktop.
Systemd simple session-level SSH Tunnel Service
#!/bin/bash
_KEY=$1
shift 1
if [ -z "$SSH_AUTH_SOCK" ]
then
SSH_AUTH_SOCK=`ss -xl | grep -o "/run/user/$UID/keyring-.*/ssh"`
if [ -z "$SSH_AUTH_SOCK" ]
then
echo >&2 'Trying GNOME Keyring SSH Agent Service...'
sleep 10
SSH_AUTH_SOCK=`ss -xl | grep -o "/run/user/$UID/keyring-.*/ssh"`
fi
fi
if [ -z "$SSH_AUTH_SOCK" ]
then
echo >&2 'GNOME Keyring SSH Agent Service not started'
exit 1
else
export SSH_AUTH_SOCK
fi
while [ -z "`ssh-add -l | grep $_KEY`" ]
do
echo >&2 'Key is not added, wait 10 seconds before next try...'
sleep 10
done
echo >&2 'Starting autossh command...'
tail -f /dev/null | autossh -M0 $@
echo >&2 'Tunnel service stopped'
[Unit]
Description=SSH Tunnel Service
After=network.target
[Service]
Type=simple
ExecStart=/bin/bash %h/.local/bin/sshtunnel [name-of-ssh-key] -v -g -ND1080 [host]
ExecStopPost=/usr/bin/killall ssh
[Install]
WantedBy=default.target
@kamikat
Copy link
Author

kamikat commented Oct 2, 2014

Setup

  1. Install autossh
  2. Place sshtunnel at ~/.local/bin/sshtunnel
  3. Place sshtunnel.service at ~/.local/share/systemd/user/sshtunnel.service
  4. Open GNOME Keyring (seahorse), import private key (you will be asked for private key password when importing an encrypted private key, and the key will then be encrypted with user's log-in certificate)
  5. Edit sshtunnel.service, fill the placeholders (port 1080 if you prefer any number else)

Monitor

Use journalctl --user -fe to track the logs (with process name of bash)

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