SSH forwardingを使ってMySQLのDBに接続する方法の例。

Format
Shell
Post date
2016-01-14 13:15
Publication Period
Unlimited
  1. # Set the path of sshpass command to SSHPASS if you have it on your system.
  2. SSHPASS=
  3. # Create SSH forwarding setting (to connect to MySQL DB through a SSH tunnel)
  4. function create_ssh_tunnel {
  5. local HOST=$1
  6. local LPORT=$2
  7. local RPORT=$3
  8. echo "SSH host is " ${HOST}
  9. echo "SSH tunnel: local port = " ${LPORT}
  10. echo "SSH tunnel: remote port = " ${RPORT}
  11. local PROC_SSH=`ps -a | awk -e '/ssh/{print $1;}'`
  12. if [ -n "${PROC_SSH}" ]; then
  13. echo "Kill remained tunnel ..."
  14. kill ${PROC_SSH}
  15. fi
  16. echo "Creating SSH tunnel to ${HOST} ..."
  17. ${SSHPASS} ssh -f -C -N -L ${LPORT}:localhost:${RPORT} -l ${REMOTE_USER} ${HOST}
  18. }
  19. # Delete SSH tunnel
  20. function delete_ssh_tunnel {
  21. local PROC_SSH=`ps -a | awk -e '/ssh/{print $1;}'`
  22. if [ -n "${PROC_SSH}" ]; then
  23. kill ${PROC_SSH}
  24. if [ $? -ne 0 ]; then
  25. echo "Error! - cannot kill SSH tunnel process"
  26. exit
  27. fi
  28. else
  29. echo "SSH tunnel is not exist."
  30. fi
  31. }
  32. # Create SSH tunnel for DB access SSH forwarding設定 (tunnel作成)
  33. create_ssh_tunnel ${HOST} ${LPORT} ${RPORT}
  34. # SQL command is written in $(SQLFILE)
  35. SQLFILE=my.sql
  36. # Connect to MySQL database server
  37. cat ${SQLFILE} | mysql -P ${LPORT} -u ${DB_USER} -h 127.0.0.1 $(DBNAME)
  38. # Delete SSH tunnel SSH tunnel削除
  39. delete_ssh_tunnel
다운로드 Printable view

URL of this paste

Embed with JavaScript

Embed with iframe

Raw text