5

Is there any way to connect to database using PDO and SSH tunnel and do 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.

0

3 Answers 3

2

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.
1
  • Can you elaborate on the steps?
    – dokgu
    Apr 11, 2017 at 16:20
1

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

0

If you have php with ssh2 extension, it should be possible.

http://php.net/manual/en/function.ssh2-tunnel.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.