SSH forwardingを使ってMySQLのDBに接続する方法の例。
- # Set the path of sshpass command to SSHPASS if you have it on your system.
- SSHPASS=
- # Create SSH forwarding setting (to connect to MySQL DB through a SSH tunnel)
- function create_ssh_tunnel {
- local HOST=$1
- local LPORT=$2
- local RPORT=$3
- echo "SSH host is " ${HOST}
- echo "SSH tunnel: local port = " ${LPORT}
- echo "SSH tunnel: remote port = " ${RPORT}
- local PROC_SSH=`ps -a | awk -e '/ssh/{print $1;}'`
- if [ -n "${PROC_SSH}" ]; then
- echo "Kill remained tunnel ..."
- kill ${PROC_SSH}
- fi
- echo "Creating SSH tunnel to ${HOST} ..."
- ${SSHPASS} ssh -f -C -N -L ${LPORT}:localhost:${RPORT} -l ${REMOTE_USER} ${HOST}
- }
- # Delete SSH tunnel
- function delete_ssh_tunnel {
- local PROC_SSH=`ps -a | awk -e '/ssh/{print $1;}'`
- if [ -n "${PROC_SSH}" ]; then
- kill ${PROC_SSH}
- if [ $? -ne 0 ]; then
- echo "Error! - cannot kill SSH tunnel process"
- exit
- fi
- else
- echo "SSH tunnel is not exist."
- fi
- }
- # Create SSH tunnel for DB access SSH forwarding設定 (tunnel作成)
- create_ssh_tunnel ${HOST} ${LPORT} ${RPORT}
- # SQL command is written in $(SQLFILE)
- SQLFILE=my.sql
- # Connect to MySQL database server
- cat ${SQLFILE} | mysql -P ${LPORT} -u ${DB_USER} -h 127.0.0.1 $(DBNAME)
- # Delete SSH tunnel SSH tunnel削除
- delete_ssh_tunnel