Created
November 20, 2023 12:48
-
-
Save aliharirian/0e6ec38712bdcda1c5b64ffc82210b9f to your computer and use it in GitHub Desktop.
This script sets up an SSH tunnel as a systemd service.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
####################################################################### | |
# Script: setup_ssh_tunnel.sh | |
# Description: This script sets up an SSH tunnel as a systemd service. | |
# Author: Ali Haririan | |
# Date: November 20, 2023 | |
# License: MIT License | |
####################################################################### | |
# Environment File Configuration | |
ENV_FILE_PATH="/etc/default/ssh-tunnel" | |
# This section creates the environment file containing configuration variables. | |
cat > "$ENV_FILE_PATH" <<EOL | |
LOCAL_PORT=<changeme; example: 22222> | |
TARGET_HOST=<changeme; example: 192.168.1.110> | |
TARGET_PORT=<changeme; example: 22> | |
TARGET_USERNAME=<changeme; example: joe> | |
TARGET_SSH_KEY_PATH=<changeme; example: /home/joe/.ssh/id_rsa> | |
EOL | |
# Systemd Service Configuration | |
SERVICE_FILE_PATH="/etc/systemd/system/ssh-tunnel.service" | |
# This section creates the systemd service file using the provided configuration. | |
cat > "$SERVICE_FILE_PATH" <<EOL | |
[Unit] | |
Description=SSH Tunnel Service | |
After=network.target | |
[Service] | |
EnvironmentFile=$ENV_FILE_PATH | |
ExecStart=/usr/bin/ssh -NT -o ExitOnForwardFailure=yes -o StrictHostKeyChecking=no -D \${LOCAL_PORT} -p \${TARGET_PORT} -i \${TARGET_SSH_KEY_PATH} \${TARGET_USERNAME}@\${TARGET_HOST} | |
RestartSec=5 | |
Restart=always | |
[Install] | |
WantedBy=multi-user.target | |
EOL | |
# Reload systemd to apply changes | |
sudo systemctl daemon-reload | |
# Enable and start the SSH tunnel service | |
sudo systemctl enable ssh-tunnel.service | |
sudo systemctl start ssh-tunnel.service | |
# Completion Message | |
echo "SSH tunnel service configured and started successfully." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment