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

这是我所拥有的:

psql -Umyuser < myscript.sql

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


当前回答

在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的建议,在输入密码之前让文件变得不可读。这就弥补了一个小小的安全漏洞。 谢谢!

其他回答

8年后……

在我的mac上,我必须在文件中添加一行 ~ /。pgpass:

<IP>:<PORT>:<dbname>:<user>:<password>

还看到: https://www.postgresql.org/docs/current/libpq-pgpass.html https://wiki.postgresql.org/wiki/Pgpass

这可能是一个老问题了,但是你可以使用一个没有人提到过的替代方法。可以在连接URI中直接指定密码。文档可以在这里找到,也可以在这里。

你可以在提供给psql的连接URI中直接提供你的用户名和密码:

# postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
psql postgresql://username:password@localhost:5432/mydb

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

如果您打算拥有多个主机/数据库连接,则~/。Pgpass文件是可行的。

步骤:

Create the file using vim ~/.pgpass or similar. Input your information in the following format: hostname:port:database:username:password Do not add string quotes around your field values. You can also use * as a wildcard for your port/database fields. You must chmod 0600 ~/.pgpass in order for it to not be silently ignored by psql. Create an alias in your bash profile that runs your psql command for you. For example:alias postygresy='psql --host hostname database_name -U username' The values should match those that you inputted to the ~/.pgpass file. Source your bash profile with . ~/.bashrc or similar. Type your alias from the command line.

注意,如果设置了export PGPASSWORD= "变量,它将优先于文件。

在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的建议,在输入密码之前让文件变得不可读。这就弥补了一个小小的安全漏洞。 谢谢!