經過SSH通道來訪問MySQL

 許多時候當要使用Mysql時,會遇到以下狀況:

1. 信息比較重要,但願通訊被加密。
2. 一些端口,好比3306端口,被路由器禁用。php

對第一個問題的一個比較直接的解決辦法就是更改mysql的代碼,或者是使用一些證書,不過這種辦法顯然不是很簡單。mysql

這裏要介紹另一種方法,就是利用SSH通道來鏈接遠程的Mysql,方法至關簡單。sql

一 創建SSH通道數據庫

只須要在本地鍵入以下命令:ssh

ssh -fNg -L 3307:127.0.0.1:3306 myuser@remotehost.comui

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.this

二 鏈接Mysql加密

如今,你就能夠經過本地鏈接遠程的數據庫了,就像訪問本地的數據庫同樣。spa

mysql -h 127.0.0.1 -P 3307 -u dbuser -p dbserver

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.

相關文章
相關標籤/搜索