很多次當要使用Mysql時,會遇到以下情況:
1. 資訊比較重要,希望通訊被加密。
2. 一些端口,例如3306端口,被路由器禁用。
對第一個問題的一個比較直接的解決方法就是更改mysql的程式碼,或是使用一些證書,不過這種方法顯然不是很簡單。
相關學習影片教學推薦:mysql影片教學
這裡要介紹另一個方法,就是利用SSH通道來連接遠端的Mysql,方法相當簡單。
一、建立SSH通道
只需要在本機鍵入以下指令:
ssh -fNg -L 3307:127.0.0.1:3306 myuser@remotehost.com The command tells ssh to log in to remotehost.com as myuser, go into the background (-f) and not execute any remote command (-N), and set up port-forwarding (-L localport:localhost:remoteport ). In this case, we forward port 3307 on localhost to port 3306 on remotehost.com.
二、連線Mysql
#現在,你就可以透過本地連線遠端的資料庫了,就像存取本地的資料庫一樣。
mysql -h 127.0.0.1 -P 3307 -u dbuser -p db The command tells the local MySQL client to connect to localhost port 3307 (which is forwarded via ssh to remotehost.com:3306). The exchange of data between client and server is now sent over the encrypted ssh connection.
或用Mysql Query Brower來存取Client的3307埠。
類似的,用PHP存取:
<?php $smysql = mysql_connect( "127.0.0.1:3307", "dbuser", "PASS" ); mysql_select_db( "db", $smysql ); ?> Making It A Daemon A quick and dirty way to make sure the connection runs on startup and respawns on failure is to add it to /etc/inittab and have the init process (the, uh, kernel) keep it going. Add the following to /etc/inittab on each client: sm:345:respawn:/usr/bin/ssh -Ng -L 3307:127.0.0.1:3306 myuser@remotehost.com And that should be all you need to do. Send init the HUP signal ( kill -HUP 1 ) to make it reload the configuration. To turn it off, comment out the line and HUP init again.
以上是詳解如何透過SSH通道來存取MySQL的詳細內容。更多資訊請關注PHP中文網其他相關文章!