Skip to content

Instantly share code, notes, and snippets.

@ericwastaken
Last active May 2, 2023 17:18
Show Gist options
  • Save ericwastaken/1ab7ed2585a805e40e704c549f11af50 to your computer and use it in GitHub Desktop.
Save ericwastaken/1ab7ed2585a805e40e704c549f11af50 to your computer and use it in GitHub Desktop.
Shell script to start up an SSH Port Forward to a remote
#!/bin/bash
# *********************************************************************
# script: ssh-forward-start.sh
# summary: Starts an SSH Port Forward process, forwarding a localhost
# port to a remote host. The PID of the SSH process will be saved to
# the file defined in the pid_filename variable.
# See the companion script ssh-forward-stop.sh, which stops the tunnel
# using the process information in the PID file.
#
# Tested on macOS Sierra.
#
# dependencies:
# - The local port must not be in use by another process
# - The remote must be set listening on the port
#
# *********************************************************************
pid_filename="ssh-forward.pid"
ssh_username="" # Will be prompted
# set your host name here
ssh_host="some.remote.host.net"
# set the local port to map
local_port=1234
# set the remote port to map
remote_port=1234
# If your private key is not properly registered with SSH or if you
# don't use ssh's CONFIG, you might need to explicitly include the
# path to your key!
#ssh_more_options="-i /path/to/private/key"
echo ""
echo "ssh-forward-start.sh"
echo "Starts an SSH Port Forward Session."
echo "Assumes you have the proper private key for SSH."
echo ""
if [[ ! -f ${pid_filename} ]]; then
if [[ -z "${ssh_username}" ]]; then
read -p 'Please enter a username on the remote host: ' ssh_username
fi
if [[ -z "${ssh_username}" ]]; then
echo "error: username is required!"
echo ""
exit 1
fi
echo "Will forward local port ${local_port} to port ${remote_port} on ${ssh_username}@${ssh_host}"
read -n1 -rsp $'Press any key to continue or Ctrl+C to exit...\n'
# perform the ssh tunnel / port redirect (and background it)
ssh -nNT ${ssh_more_options} -L ${local_port}:localhost:${remote_port} ${ssh_username}@${ssh_host} &
ssh_pid=$!
echo ${ssh_pid} > ${pid_filename}
echo "done: ssh fw started!"
else
echo "error: ssh fw process already started! Use ssh-forward-stop.sh to stop it first."
fi
echo ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment