PDO and SSH2 tunnel
Is there any way to connect to database using PDO and SSH tunnel and do 开发者_Go百科not execute any code at command line like in the topic below?
Zend_Db: How to connect to a MySQL database over SSH tunnel?
Thanks in advance for your answer.
I was able to do this using a combination of ssh2_tunnel
, socket_create_listen()
, and pcntl_fork
. Basically the tunnel is what we want to use to connect to the port on the MySQL box, but because PDO doesn't support connecting via a socket we have to create a port via socket_create_listen
on a dedicated php fork that just pumps data from the unix socket to the ssh tunnel.
PDO (php main proc) -> random socket port on 127.0.0.1 -> data proxy (php fork proc) -> ssh2_tunnel resource -> ssh server -> mysql process.
Without invoking the ssh tunnel within a seperate process, that means you will have to create a new tunnel for each invocation of the script - and you can't share an tunnel created by another instance since you don't know when it will terminate. So in addition to the connection overhead you need to manage a pool of local sockets.
The short answer is that it's just not feasible.
A longer answer is that you can start daemons/long running processes from within PHP but there are a few caveats. So if you can use the program execution functions and have access to a set of POSIX tools using the command line tools then it is possible. It'll be a lot simpler to implement this if you can set up a key pair (with an necryted private key) to avoid having to parse the I/O to the program to inject the password at the right point (or use something like 'expect' to handle it).
If you have php with ssh2 extension, it should be possible.
http://php.net/manual/en/function.ssh2-tunnel.php
精彩评论