如何调用psql以使它不提示输入密码?

这是我所拥有的:

psql -Umyuser < myscript.sql

但是,我找不到传递密码的参数,所以psql总是提示输入这个参数。


当前回答

您可能希望阅读PostgreSQL身份验证方法的摘要。

为了回答你的问题,有几种方法为基于密码的身份验证提供密码:

Via the password prompt. Example: psql -h uta.biocommons.org -U foo Password for user foo: In a pgpass file. See libpq-pgpass. Format: <host>:<port>:<database>:<user>:<password> With the PGPASSWORD environment variable. See libpq-envars. Example: export PGPASSWORD=yourpass psql ... # Or in one line for this invocation only: PGPASSWORD=yourpass psql ... In the connection string The password and other options may be specified in the connection string/URI. See app-psql. Example: psql postgresql://username:password@dbmaster:5433/mydb?sslmode=require

其他回答

考虑到使用PGPASSWORD环境变量的安全问题,我认为最佳的整体解决方案如下:

用您想使用的密码编写自己的临时pgpass文件。 使用PGPASSFILE环境变量告诉psql使用该文件。 删除临时pgpass文件

这里有几点需要注意。步骤1是为了避免混淆用户的~/。Pgpass文件可能存在。您还必须确保该文件的权限为0600或更小。

一些人建议使用bash来实现如下的快捷方式:

PGPASSFILE=<(echo myserver:5432:mydb:jdoe:password) psql -h myserver -U jdoe -p 5432 mydb

它使用<()语法来避免将数据写入实际文件。但它不起作用,因为psql检查正在使用的文件,并抛出如下错误:

WARNING: password file "/dev/fd/63" is not a plain file

您可能希望阅读PostgreSQL身份验证方法的摘要。

为了回答你的问题,有几种方法为基于密码的身份验证提供密码:

Via the password prompt. Example: psql -h uta.biocommons.org -U foo Password for user foo: In a pgpass file. See libpq-pgpass. Format: <host>:<port>:<database>:<user>:<password> With the PGPASSWORD environment variable. See libpq-envars. Example: export PGPASSWORD=yourpass psql ... # Or in one line for this invocation only: PGPASSWORD=yourpass psql ... In the connection string The password and other options may be specified in the connection string/URI. See app-psql. Example: psql postgresql://username:password@dbmaster:5433/mydb?sslmode=require

你可能会发现这很有用:Windows PSQL命令行:是否有一种方法允许无密码登录?

PGPASSWORD=[your password] psql -Umyuser < myscript.sql

在mightybyte为那些不熟悉*nix shell脚本的人提供的答案的基础上,这里有一个工作脚本:

#!/bin/sh
PGPASSFILE=/tmp/pgpasswd$$
touch $PGPASSFILE
chmod 600 $PGPASSFILE
echo "myserver:5432:mydb:jdoe:password" > $PGPASSFILE
export PGPASSFILE
psql mydb
rm $PGPASSFILE

在/tmp/pgpasswd$$的第2行中,双美元符号($$)将进程ID号附加到文件名,这样该脚本可以多次运行,甚至同时运行,而不会产生副作用。

请注意在第4行使用chmod命令——就像mightybyte描述的“不是普通文件”错误一样,如果不这样做,还会出现“权限”错误。

在第7行,如果使用默认值(localhost: 5432)并且只有一个数据库用户,则不必使用-hmyserver、-pmyport或-Ujdoe标志。对于多个用户,(但默认连接)将该行更改为

psql mydb jdoe

不要忘记使脚本可执行

Chmod +x runpsql(或其他脚本文件)

更新:

我采纳了RichVel的建议,在输入密码之前让文件变得不可读。这就弥补了一个小小的安全漏洞。 谢谢!