一般postgresql数据库,通过客户端工具(pgdump,psql等)连接,默认会通过交互的方式输入密码(配置md5认证方式),例如:
[postgres@localhost ~]$ psql -U backup -d postgres -p 5432 --host 192.168.56.117
Password for user backup:
psql (9.6.20)
Type "help" for help.
postgres=>
复制
但是在shell脚本自动化场景中(获取数据库信息,数据导入导出,备份恢复等)
以交互方式传递密码难以实现,那么如何实现非交互方式的脚本调用呢?
本次测试脚本:
[postgres@localhost postgresql]$ cat test.sh
#!/bin/bash
echo `psql -U backup -d postgres -p 5432 --host 192.168.56.117 -c "select version()"`
复制
在不进行任何处理的情况下,需要交互传递密码:
[postgres@localhost postgresql]$ sh test.sh
Password for user backup:
复制
本文汇总三个非交互方式:
非交互方法1:
https://www.postgresql.org/docs/9.6/libpq-pgpass.html
编辑~/.pgpass,添加以下配置,可以避免定期输入密码
hostname:port:database:username:password
su - postgres
vi ~/.pgpass
192.168.56.117:5432:postgres:backup:123456
复制
执行脚本,发现无需交互传递密码:
[postgres@localhost postgresql]$ sh test.sh
version -----------------------------------------------------------------------------------------------------------
PostgreSQL 9.6.20 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44), 64-bit (1 row)
复制
非交互方法2:
在调用psql之前,在脚本内设置PGPASSWORD变量
修改shell脚本:
vi test.sh
#!/bin/bash
echo `PGPASSWORD="123456" psql -U backup -d postgres -p 5432 --host 192.168.56.117 -c "select version()"`
复制
修改后执行,发现无需交互传递密码:
[postgres@localhost postgresql]$ sh test.sh
version -----------------------------------------------------------------------------------------------------------
PostgreSQL 9.6.20 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44), 64-bit (1 row)
复制
PS:使用该方法存在安全风险,因为当其他用户查看正在运行的进程的命令行(例如,使用ps(Linux),ProcessExplorer(Windows)或类似工具)时,密码以纯文本形式可见,不建议使用
非交互方法3:
设置环境变量:
export PGPASSWORD='123456'
然后正常调用脚本即可
[postgres@localhost postgresql]$ export PGPASSWORD='123456'
[postgres@localhost postgresql]$ sh test.sh
version -----------------------------------------------------------------------------------------------------------
PostgreSQL 9.6.20 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44), 64-bit (1 row)
复制
类似案例可以参考stack overflow:
https://stackoverflow.com/questions/6405127/how-do-i-specify-a-password-to-psql-non-interactively
END...................................
文章转载自数据库笔记,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。
评论
相关阅读
外国CTO也感兴趣的开源数据库项目——openHalo
小满未满、
551次阅读
2025-04-21 16:58:09
9.9 分高危漏洞,尽快升级到 pgAdmin 4 v9.2 进行修复
严少安
358次阅读
2025-04-11 10:43:23
3月“墨力原创作者计划”获奖名单公布
墨天轮编辑部
337次阅读
2025-04-15 14:48:05
openHalo问世,全球首款基于PostgreSQL兼容MySQL协议的国产开源数据库
严少安
313次阅读
2025-04-07 12:14:29
转发有奖 | PostgreSQL 16 PGCM高级认证课程直播班招生中!
墨天轮小教习
152次阅读
2025-04-14 15:58:34
墨天轮PostgreSQL认证证书快递已发(2025年3月批)
墨天轮小教习
133次阅读
2025-04-03 11:43:25
SQL 优化之 OR 子句改写
xiongcc
97次阅读
2025-04-21 00:08:06
融合Redis缓存的PostgreSQL高可用架构
梧桐
91次阅读
2025-04-08 06:35:40
PostgreSQL拓展PGQ实现解析
chirpyli
89次阅读
2025-04-07 11:23:17
Mysql/Oracle/Postgresql快速批量生成百万级测试数据sql
hongg
78次阅读
2025-04-07 15:32:54