使用ssh2_tunnel连接PHP到PostgreSQL

8

我正在忙于尝试连接到一个PostgreSQL数据库(运行在不同的服务器上),之前创建了一个ssh2_tunnel到那个服务器。

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个回答

7
抱歉,这种方法行不通。ssh2_tunnel创建一个远程文件指针(即资源),可用于PHP函数(如fgets()、fwrite()等)。它与ssh端口转发不同。
您可以尝试从shell在php服务器上打开ssh隧道:ssh usname@xxx.xx.xx.xx -i ./ssh_key -L 5555:localhost:5432。只要会话保持活动状态,您就应该能够像pg_connect("host=127.0.0.1 port=5555 dbname=dbname user=dbuser password=dbpass")一样从您的php脚本连接到数据库。
当然,这不适用于生产环境。对于生产环境,您需要允许从php应用程序服务器访问数据库。您可能需要编辑postgresql.conf以确保服务器绑定到正确的接口,以及pg_hba.conf以允许来自php主机的连接。

不是我期望的答案,但是去除SSH可访问性并直接转发postgresql端口似乎可以正常工作,你有什么关于使postgresql连接更安全的建议吗? - TheLovelySausage
1
这取决于您现在拥有什么,您的向量以及您准备走多远。一些一般建议:尽可能允许少量主机连接,启用ssl,使用pgcrypto。值得阅读:http://www.postgresql.org/docs/9.4/static/auth-pg-hba-conf.html - Alex Blex
1
这看起来非常有用,我真的很感激你的帮助。 - TheLovelySausage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接