Here's a handy BASH script I wrote to pull down one copy of a database to a local version using an SSH tunnel. It's not super-secure, so it kind of assume that you have the script hosted on a local machine, securely (the DB password is in the script!).
First, go put a host named "tunnel" in your hosts file (usually /etc/hosts on *nix-type environments), that points to localhost 127.0.0.1 (mysql can get cranky when you try to connect to "localhost" - it always tries to use a local socket when you say that, so this is a bit of a workaround to make it work through the tunnel.
The script is below, just put it somewhere in your path and chmod it +x. (If you don't want to put it in your path, like in /usr/bin, just put it in your home folder and run the script from within that folder or by fully qualifying its path.
It uses your home folder as a temporary area (that's what ~ is), but feel free to change the paths. Invoke the script by passing it the remote db name you want to copy, like "dbmigrate.sh somedb" if you named the script dbmigrate.sh).
#!/bin/bash
echo 'Opening a tunnel (10101 => 3306) for 60 seconds or until done, whichever is longer...'
ssh -f USER@REMOTE.HOST -L10101:localhost:3306 sleep 60
echo 'Dumping db via tunnel to your home directory...'
mysqldump -u REMOTEDBUSER -pYOURREMOTEDBPASSWORD -P10101 -h tunnel $1 > ~/$1.sql
rm ~/temp.sql 2>/dev/null
echo "CREATE DATABASE IF NOT EXISTS $1;" > ~/temp.sql
echo 'Creating database if not exists...'
mysql -u LOCALDBUSER -pYOURLOCALDBPASSWORD < ~/temp.sql
echo 'Importing that file into mysql...'
mysql -u LOCALDBUSER -pYOURLOCALDBPASSWORD $1 < ~/$1.sql
echo 'Removing files...'
rm ~/$1.sql
#rm ~/temp.sql
echo 'Done.'
Of course, replace the necessary credentials, users, hosts (all in CAPS) with the correct values for your configuration. Happy migrating!
Post new comment