远程连接保存密码的PostgreSQL数据库,使用psql从远程机器进行连接。

4

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

我想能够从一个输入文件运行查询并保存结果到输出文件,但是我没有成功自动设置密码,每次运行查询时都需要手动输入密码。

我尝试了以下方法:

  1. Run

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

    with my username, password, hostname, port and database values. This worked OK but I did not find a way to add arguments for input/output files (not needing to go through Postgres interactive environment).

  2. According to another SO question, I created a file ~/.pgpass with the following format: hostname:port:database:username:password

    and then chmod 0600 ~/.pgpass but when connecting as: psql -h hostname -U username -d database -w psql ignored this (I got the following failed authentication message.)

    psql: fe_sendauth: no password supplied.

    Note that my remote machine's name is different than my username, so this might also create a problem when creating the .pgpass file. Is there any other way to do it?

有任何想法吗?

你的远程机器名称与你的用户名有什么关系?顺便说一下,在你第二个 psql 调用中没有指定端口,但我认为在这种情况下这并不重要。 - zb226
根据这个链接[http://serverfault.com/questions/526170/psql-fe-sendauth-no-password-supplied],可能会有所不同。我也尝试指定端口,但正如你所说,这不是问题的原因。 - user90772
这个问题是关于使用 sudo 调用 psql。您是否正在使用 sudo 调用 psql - zb226
不好意思,我不能使用sudo因为这是一台远程机器。我想要创建一个Bash脚本,它会接收两个参数(输入/输出文件),并使用psql自动运行查询。 - user90772
1
我在这个SO问题[https://dev59.com/fGw15IYBdhLWcg3wkcuq]中找到了我想要的解决方案,我在发布之前进行了足够的搜索,但我想重新表达我的问题。解决方案是编写`PGPASSWORD=password psql -h hostname -U username -d database -f inputfile -o outputfile`。 - user90772
1个回答

0
这个方法可以正常工作,但是我没有找到一种添加输入/输出文件参数的方法。
您可以将输入文件重定向到 psql,或在 -f 选项中指定它。
psql < input.sql
psql -f input.sql

关于输出文件,只需将 psql 的输出重定向到它即可:
psql -f input.sql > output.txt

谢谢。在使用psql字符串模式时,这并没有起作用。解决方法是在psql之前添加PGPASSWORD=password,然后按照您所写的操作进行。 - user90772
为什么不呢?psql "host=... dbname=... user=... port=... password=..." < input.sql > output.sql 运行良好。 - Egor Rogov
我没有尝试过这个,我尝试使用了-f -o参数,但是它没有起作用,谢谢。 - user90772

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