How to script a database migration using an SSH tunnel?

Just pull the dump with one command:

ssh user@host 'mysqldump -u -p databasename' > /path/to/local/file.sql

You can also compress these as well if your database is big:

ssh user@host 'mysqldump -u -p databasename | gzip' > /path/to/local/file.sql.gz

and then gunzip it after.


The ssh -L 3307:remote:3306 user@remote command will never return, because it will just open a shell and keep it open.

SSH behaves as follows: It keeps the connection open as long as either a command is executed or the tunnel is used. So what you want to do is ssh user@remote sleep 10 &. This gives the mysqldump command enough time to open the connection, but as soon as mysqldump closes that connection, the tunnel is unused and SSH exits.

btw, you may have to use 3307:localhost:3306, if the server does not allow external connections. (This works because the host name is resolved on the server side, not on your client)