要在 PostgreSQL 中使用 SSH 隧道进行安全的 TCP/IP 连接,你可以按照以下步骤进行操作:

1. 确保已安装 PostgreSQL 和 SSH:
   确保你的系统上已经安装了 PostgreSQL 数据库和 SSH 客户端。

2. 创建 SSH 隧道:
   使用以下命令在本地主机和远程主机之间创建一个 SSH 隧道,将本地端口(比如 5432)映射到远程 PostgreSQL 服务器的相应端口。替换 <username>, <hostname>, <remote_port> 和 <local_port> 分别为你的用户名、远程主机名、远程 PostgreSQL 服务器端口和本地端口。
   ssh -L <local_port>:<hostname>:<remote_port> <username>@<hostname>

   例如:
   ssh -L 5432:localhost:5432 user@your-postgres-server.com

   这将在本地主机的5432端口上创建一个SSH隧道,连接到远程 PostgreSQL 服务器。

3. 修改 PostgreSQL 配置:
   打开 PostgreSQL 服务器上的 postgresql.conf 文件,并确保它监听所有地址。找到 listen_addresses 参数并将其设置为:
   listen_addresses = '*'

   保存并关闭文件。

4. 配置 pg_hba.conf:
   打开 PostgreSQL 服务器上的 pg_hba.conf 文件,确保允许来自本地主机的连接。在文件的末尾添加以下行:
   host    all             all             127.0.0.1/32            md5

   保存并关闭文件。

5. 重启 PostgreSQL 服务:
   在远程服务器上重启 PostgreSQL 服务,以应用新的配置。
   sudo service postgresql restart

6. 连接到 PostgreSQL:
   现在,你应该能够在本地主机上使用正常的 PostgreSQL 客户端连接到本地端口(例如 5432),而这个连接会通过 SSH 隧道安全地转发到远程 PostgreSQL 服务器。

请记住,这只是一种使用 SSH 隧道进行 PostgreSQL 连接的方式,确保你的系统和网络安全性,并适当配置防火墙和其他安全措施。


转载请注明出处:http://www.zyzy.cn/article/detail/8267/PostgreSQL