Opening SSH Tunnel in Script

Ever wanted to access a process on a remote server in a #bash script, but didn’t want to open it up for the whole internet?

You can do this cleanly with an ssh ‘control socket’. To talk to an already-running SSH process and get it’s pid, kill it etc.
Use the ‘control socket’ (-M for master and -S for socket) as follows:

# Setup the tunnel
$ ssh -M -S my-ctrl-socket -fnNT -L 50000:localhost:3306 user@sshtarget.com
# Check the connection
$ ssh -S my-ctrl-socket -O check user@sshtarget.com
# Exit when done
$ ssh -S my-ctrl-socket -O exit user@sshtargetcom
# Note that my-ctrl-socket will be an actual file that is created.

I used this recently to insert data into a #postgres database I had running on a remote server. What alternative methods have you seen?

--

--

A daily programming newsletter (https://abyteofcoding.com). Twitter: https://twitter.com/AByteOfCoding

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store