PHP使用ssh2_tunnel连接到PostgreSQL

时间:2015-11-03 08:53:57

标签: php postgresql debugging ssh remote-access

在为该服务器创建ssh2_tunnel之后,我正忙着尝试连接到PostgreSQL数据库(在不同的服务器上运行)。

ssh2_tunnel似乎工作正常,但我的pg_connect无效,我希望我能错过一些小事

<?php


ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);


echo "<span>test script<br /></span>";


$connection = ssh2_connect('xxx.xx.xx.xx', 22);


if (ssh2_auth_pubkey_file($connection, 'usname', './ssh_key.pub', './ssh_key', 'psword')) {
    echo "<span>Public Key Authentication Successful<br /></span>";
} else {
    die('Public Key Authentication Failed');
}


if ($tunnel = ssh2_tunnel($connection, '127.0.0.1', 5432)) {
    echo "<span>Tunnel Successful<br /></span>";
} else {
    die('Tunnel Failed');
};


// this is where it is failing and I'm not sure why
$string = "host=127.0.0.1 port=5432 dbname=dbname user=dbuser password=dbpass";
$pgsqlcon = pg_connect($string) or die('Could not connect: ' . pg_last_error());


?>

它给了我以下错误

Warning: pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?

pg_last_error的另一个错误

Warning: pg_last_error(): No PostgreSQL link opened yet in /home/shoepack/public_html/admin_php_ssh/notused.php on line 26

1 个答案:

答案 0 :(得分:2)

抱歉,它不会以这种方式工作。 ssh2_tunnel创建一个远程文件指针,也就是资源,用于fgets()fwrite()等php函数。它与ssh端口转发不一样。

您可以尝试在shell上运行php服务器上的ssh隧道:ssh usname@xxx.xx.xx.xx -i ./ssh_key -L 5555:localhost:5432。当会话处于活动状态时,您应该能够从php脚本连接到数据库pg_connect("host=127.0.0.1 port=5555 dbname=dbname user=dbuser password=dbpass");

当然不适合生产使用。生产所需要的是允许从php应用程序服务器访问数据库。您可能需要编辑postgresql.conf以确保服务器绑定到正确的接口,并pg_hba.conf允许来自您的php主机的连接。