mysqldump and socks tunnel

Updated: 22 May 2023

The following bash script will open a socks tunnel ti a remote host and use mysqldump locally to backup a mysql database.

#!/bin/sh
DT=$(date '+%Y-%m-%dT%H:%M:%S')
SUFFIX=
FILENAME=$DT$SUFFIX
BACKUPSPATH=
USER=
IP=
PORT=
DBUSER=
DBPASS=
DBNAME=
echo "Opening socks tunnel to $IP"
echo "Writing $FILENAME"
ssh -f -L $PORT:127.0.0.1:$PORT $USER@$IP sleep 10; \
mysqldump -u $DBUSER -h 127.0.0.1 -p$DBPASS -P $PORT --routines $DBNAME > $BACKUPSPATH/$FILENAME

ssh

Updated: 10 May 2025

Prefer password authentication over public key

ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no user@example.com

Use one specific private key

ssh -o "IdentitiesOnly=yes" -i /home/me/path/to/private/key/id_rsa user@host

Use a non-standard port

ssh user@192.168.1.1 -p 26

Kill a ssh session

ps -A | grep ssh
kill PID # the process id from previous command

Kill a ssh session

ps -aux | grep ssh
kill PID # the process id from previous command

Socks tunnel

# -D: Tells SSH that we want a SOCKS tunnel on the specified port number
# -f: Forks the process to the background
# -C: Compresses the data before sending it
# -q: Uses quiet mode
# -N: Tells SSH that no command will be sent once the tunnel is up

ssh -D 8123 -f -C -q -N user@example.com

Verify that the tunnel is up and running

ps aux | grep ssh

If using -f, close the tunnel when finished

kill <process id>

Port forwarding

-R Specifies that connections to the given TCP port or Unix socket on the remote (server) host are to be forwarded to the local side.
-L Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side.

See What’s the difference between ssh local and remote port forwarding
See https://iximiuz.com/ssh-tunnels/ssh-tunnels.png

Check port forwarding is working

Step 1. Forward traffic connecting to port 8000 on your local machine to port 8123 on the remote machine

ssh -L 127.0.0.1:8000:127.0.0.1:8123 the_user@remote_machine

Step 2. On the remote machine, start a python http server which is listening for connections on port 8123 of it’s own localhost

python3 -m http.server 8123

Step 3. On the local machine, visit http://127.0.0.1:8000 and you should see the directory listing for the remote directory where the python http server was started.