开发者

Binding MySQL to local port over SSH - works in console, not via PHP shell_exec() in Mac OSX

I am running OSX 10.6.7 and trying to connect to a remote MySQL server via ssh to run some PHP scripts. Currently, I run the following commands with no problem:

ssh -i /Users/xxxx/key.pem user@data.server.com -L 53306:localhost:3306 -f sleep 60 >> logfile
mysql -u user -p -h 127.0.0.1 -P 53306

After I authenticate with a password, it works perfectly. (So long as it's before the sleep timeout, of cou开发者_如何学Gorse.)

When I run this PHP script, however...

$shell = shell_exec("ssh -i /Users/xxxx/key1.pem user@data.server.com -L 53306:localhost:3306 -f sleep 60 >> logfile");

$mysqli = mysqli_connect('127.0.0.1', 'user', 'password', 'database', 53306);

I get connection refused. When I omit the shell_exec(), I get the same error. When I echo $shell, nothing is outputted.

key1.pem has chmod 400 permission, is a copy of the key.pem, and I ran chown _www on it. I get the same errors if I try to use key.pem or key1.pem. I also tried 440 permissions as well with no luck.

Thanks for the help; this is driving me nuts.


Why do you need a password if you're using a private key? Do you mean a password for the key file? I think it could be the problem because ssh accept authentication using passwords only in tty and php *exec functions hasn't it.

For the sleep question you can try the -N option of ssh, which is useful for tunnels and it doesn't require a remote command to be executed. Try to establish a tunnel using the shell and then simply connect to that tunnel with php.

Update:

I tried this and it does work on my Mac

<?
exec('ssh -f -N -n -L 5500:localhost:3306 your-host-name &> /dev/null');
var_dump(mysql_connect('127.0.0.1:5500', 'root'));

you should add your -i option and replace your hostname.

This is the output on my computer

resource(9) of type (mysql link)

But keep in mind that you'll have a couple of problems with this. The &> /dev/null statement makes the exec function return immediately, but it will suppress any output (mostly errors) when you execute the script multiple times, because every new request will try to open a new connection, it will succeed but it cannot setup the tunnel because port 5500 is already in use. After a while you'll have a lot of ssh process pending on your machine.

To avoid this you should try to connect to mysql before the ssh call and if you can't then setup the tunnel and redo the mysql connect call. In this way you can solve the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜