使用保存的密码从远程计算机使用 psql 连接到远程 postgres 数据库

Connect with psql from remote machine to remote postgres database with saved password

我在一台远程 Unix 机器上工作,我从本地机器通过 SSH 连接。另一台主机上有一个 Postgres 数据库,我需要使用 psql 从我的远程机器连接它。

我希望能够 运行 从输入文件查询并将结果保存到输出文件,但是我没有设法自动设置密码,超出了每次都这样做的需要我运行一个查询。

我尝试了以下方法:

  1. 运行

    psql "user=username password=password host=hostname port=port dbname=database"`
    

    与我的 usernamepasswordhostnameportdatabase 值。 这工作正常,但我没有找到为 input/output 文件添加参数的方法(不需要通过 Postgres 交互式环境)。

  2. 根据another SO question,我创建了一个文件~/.pgpass,格式如下:hostname:port:database:username:password

    然后 chmod 0600 ~/.pgpass 但是当连接为: psql -h hostname -U username -d database -w psql 忽略了这个(我收到以下失败的身份验证消息。)

    psql: fe_sendauth: no password supplied.

    请注意,我的远程计算机的名称与我的用户名不同,因此这也可能会在创建 .pgpass 文件时产生问题。还有其他方法吗?

有什么想法吗?

This worked OK but I did not find a way to add arguments for input/output files

您可以将输入文件重定向到 psql,或者在 -f 选项中指定它:

psql < input.sql
psql -f input.sql

至于输出文件,只需将 psql 的输出重定向到它:

psql -f input.sql > output.txt