psql自动登录数据库可以由psql免密登录,叠加别名实现。
- psql免密
psql 免密基于.pgpass密码文件,它是数据库使用用户家目录下一个隐藏文件。
# 格式
# hostname:port:database:username:password
# 192.168.5.101:23527:postgres:postgres:1qaz@WSX
[pg12@node1 ~]$ vim /home/pg12/.pgpass
[pg12@node1 ~]$ cat .pgpass
192.168.5.101:23527:postgres:postgres:1qaz@WSX
#因为明文记录密码.pgpass权限需要限制为0600, chmod 0600 .pgpass
[pg12@node1 ~]$ chmod 0600 .pgpass
[pg12@node1 ~]$ ls -laitr .pgpass
101230716 -rw------- 1 pg12 pg12 402 Jun 5 12:50 .pgpass
# 查看pg_hba.conf,确认是否符合
[pg12@node1 ~]$ tail -10 data/pg_hba.conf |grep hostssl
hostssl all all 192.168.5.0/24 scram-sha-256
[pg12@node1 ~]$ psql -h 192.168.5.101 -p 23527 -U postgres postgres -c "select version();"
version
----------------------------------------------------------------------------------------------------------
PostgreSQL 12.15 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-36), 64-bit
(1 row)
- 添加alias别名
添加alias别名到数据库管理用户家目录.bash_profile/.bashrc,这样就保证启动后可用。
# vim .bash_profile
# cat .bash_profile
# source .bash_profile
[pg12@node1 ~]$ vim .bash_profile
[pg12@node1 ~]$ tail -2 .bash_profile
alias pg12="psql -h 192.168.5.101 -p 23527 -U postgres postgres"
[pg12@node1 ~]$ source .bash_profile
- 检验自动登录
直接输入别名pg12, 即完成登录数据库postgres。
[pg12@node1 ~]$ pg12 psql (12.15) SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off) Type "help" for help. postgres=# select version(); version ---------------------------------------------------------------------------------------------------------- PostgreSQL 12.15 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-36), 64-bit (1 row) postgres=#
最后修改时间:2023-06-05 14:06:07
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




