Another modification of @mpontes'/@javier's answer that
ssh user@remoteserver -L 9999:localhost:9999 'socat TCP-LISTEN:9999,fork,bind=localhost UNIX-CONNECT:/var/run/mysqld/mysql.sock& pid=$!; trap "kill $pid" 0; while echo -ne " \b"; do sleep 5; done'
Cleaner
ssh user@remoteserver -L 9999:localhost:9999 '
socat TCP-LISTEN:9999,fork,bind=localhost UNIX-CONNECT:/var/run/mysqld/mysql.sock&
pid=$!
trap "kill $pid" 0
while echo -ne " \b"; do
sleep 5
done
'
PROS
- Works on openssh earlier than 6.7 (like CentOS 7)
- Kills socat on ssh termination instead of having to re-ssh into the remote server
- Allows non-public ssh login (unlike ijk solution)
Feature
- Since the
-f
option is not used, you can either use a public key and run in the background via &
or you could log in interactively and use Ctrl+Z and use the same $!
to store the pid.
CONS
- Can't easily use the
-f
ssh option, as you'll lose the pid of ssh that way. This method relies on running in the foreground and Ctrl+C to kill.
- Far more complicated
Explanation
socat ...&
- run socat in background on remote server
pid=$!
- store the pid
trap kill\ $pid 0
- run kill $pid
on bash termination
while :; sleep...
- sit in an infinite loop
echo -ne \ \b
- Echo space followed by backspace. This fails as soon as the ssh is disconnected. With a sleep 5
, this means that socat
can run up to 5 seconds after ssh
Note: Actually tested using docker, port 2375
, /var/run/docker.sock
, and environment variable DOCKER_HOST='tcp://localhost:2375'
, but should work for mysql all the same
Update
Using SSH Controls, you can use the -f
flag using my way, just add the following flags
-f -o ControlPath=~/.ssh/%C -o ControlMaster=auto
And you'll get
ssh -f -o ControlPath=~/.ssh/%C -o ControlMaster=auto user@remoteserver -L 9999:localhost:9999 'set -m; socat TCP-LISTEN:9999,fork,bind=localhost UNIX-CONNECT:/var/run/mysqld/mysql.sock& pid=$!; trap "kill $pid" 0; while echo -ne " \b"; do sleep 5; done'
Now you can terminate all the controlled sessions using
ssh -o ControlPath=~/.ssh/%C -O exit remoteserver
The -o
options can be saved in your .ssh/config
file, or you can use -S instead (but you'll still need -o ControlMaster
)