如何在pg_dump时传入密码

在做postgres的备份时,需要定时执行pg_dump命令,这就需要在人不介入的情况传入密码,有两种方式可以实现。
一是使用环境变量PGPASSWORD,二是使用.pgpass文件。

使用环境变量PGPASSWORD

使用crontab执行shell脚本,在pg_dump之前,设置环境变量。
示例:

1
2
export PGPASSWORD="$pg_password"
pg_dump -p 7432 -U scm > pg.dump

或者在一行命令中

1
PGPASSWORD="$pg_password" pg_dump -p 7432 -U scm > pg.dump

注意:这种方法因为安全性问题,所以不推荐使用。

PGPASSWORD behaves the same as the password connection parameter. Use of this environment variable is not recommended for security reasons, as some operating systems allow non-root users to see process environment variables via ps; instead consider using the ~/.pgpass file

@https://www.postgresql.org/docs/current/static/libpq-envars.html

使用.pgpass文件

参考https://www.postgresql.org/docs/current/static/libpq-pgpass.html

在主目录下新建~/.pgpass文件,并赋权限为600,文件内容为

1
hostname:port:database:username:password