通过SSH通道来访问MySQL
1. 信息比较重要,希望通信被加密。
2. 一些端口,比如3306端口,被路由器禁用。
对第一个问题的一个比较直接的解决办法就是更改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访问:
$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.
上一篇: Android 自定义吐司通知
下一篇: 巧用递归解决矩阵最大序列和问题