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

这是我所拥有的:

psql -Umyuser < myscript.sql

但是,我找不到传递密码的参数,所以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= "变量,它将优先于文件。

其他回答

如果您打算拥有多个主机/数据库连接,则~/。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= "变量,它将优先于文件。

在Windows上工作的url字符串和使用psql选项的组合:

> psql -d postgresql://username:password@localhost:5432/mydb -f myscript.sql

传递没有-d的命令没有工作,只是连接到数据库,但没有执行脚本

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

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

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

你必须创建一个密码文件:更多信息请参见http://www.postgresql.org/docs/9.0/interactive/libpq-pgpass.html。

8年后……

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

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

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