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?

--

--