Expose a remote mysql socket locally

script security

Originally posted as GitHub Gist on 27 Jul 2017 (details)


Source: https://gist.github.com/paulera/582033379327de63bf7f7d82aaf3d3cc

Description: Exposes a remote mysql socket locally


remote-socket-forwarding.sh

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/bin/bash

# ################################################################
#
# This is a sample script, modify it according to your needs.
# SSH password access won't work, you must have your RSA key
# added to server's authorizedkeys file, or use ssh's -i option.
# 
# https://gist.github.com/paulera/582033379327de63bf7f7d82aaf3d3cc

DIR=$(mktemp -d)
LOCALSOCKET=$DIR"/mysqld.sock"
SSHUSERNAME="myuser"
SSHSERVER="remoteserver.com"
SSHPORT="22"
REMOTESOCKET="/var/run/mysqld/mysqld.sock"

if [ ! -d $DIR ]; then
    echo "Directory $DIR not found"
    echo "Check the script file: "$(readlink -m $0)
    exit 1
fi

echo
echo "Remote socket connection for MySQL client"
echo
echo "Make sure you have rsa-key authentication granted via SSH on the server"
echo "you want to connect to: $SSHSERVER"
echo
echo "Setup this connection in your MySQL client:"
echo
echo "Socket   ...... "$LOCALSOCKET
echo "Database ...... " # fill this in so users know how to setup their clients
echo "Username ...... " # fill this in so users know how to setup their clients
echo "Password ...... " # fill this in so users know how to setup their clients
echo
echo "If you have trouble connecting, check the SSH configuration in this"
echo "script file: "$(readlink -m $0)
echo
echo "Starting socat..."
echo
echo "socat \"UNIX-LISTEN:$LOCALSOCKET,reuseaddr,fork\" EXEC:\"ssh $USERNAME@$SSHSERVER -p $SSHPORT socat STDIO UNIX-CONNECT\:$REMOTESOCKET\""
echo
socat  "UNIX-LISTEN:$LOCALSOCKET,reuseaddr,fork" EXEC:"ssh $USERNAME@$SSHSERVER -p $SSHPORT socat STDIO UNIX-CONNECT\:$REMOTESOCKET"