如何使用非交互式的登录PostgreSQL数据库?

数据库关系型数据库技术服务知识库
问题描述

用psql客户端命令连接远程的 PostgreSQL 数据库需要交互的输入密码,这样在一些备份或者定时任务中无法实现一些自动化功能,本文将介绍如何使用非交互式的方法登录 PostgreSQL 数据库

问题分析

通过 PostgreSQL 的内置环境变量 PGPASSWORD,URL 地址方法,conninfo string 方法,配置 pgpass file 的方式均可以实现。

解决方案

PostgreSQL 的内置环境变量 PGPASSWORD

[postgres@iv-ebgymdaodpe2tgjofpe5 pgdata]$ export PGPASSWORD='xxxx'; 

[postgres@iv-ebgymdaodpe2tgjofpe5 pgdata]$ psql -h 'xxx.xx.xx.xx' -U 'postgres' -d 'postgres' -c 'select version();'                                                 version                                                  
----------------------------------------------------------------------------------------------------------
 PostgreSQL 12.10 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44), 64-bit
(1 row)

URL 地址方式连接数据库

postgres@iv-ebgymdaodpe2tgjofpe5 ~]$ psql "postgresql://postgres:xxxxxx@xx.xx.xx.xx:5432/postgres"
psql (12.10)
Type "help" for help.

postgres=# \q

conninfo string 连接数据库

[postgres@iv-ebgymdaodpe2tgjofpe5 ~]$ psql "host=xx.xx.xx.xx port=5432 dbname=postgres password=xxxxxx"
psql (12.10)
Type "help" for help.

postgres=# \q

pgpass file 的方式连接数据库


[postgres@iv-ebgymdaodpe2tgjofpe5 ~]$ cat ~/.pgpass
xx.xx.xx.xx:5432:postgres:postgres:xxxxxx



#登录host为localhost的时候就可以免密登录了。
[postgres@iv-ebgymdaodpe2tgjofpe5 ~]$ psql -h xx.xx.xx.xx
psql (12.10)
Type "help" for help.

postgres=# \q

参考文档

https://www.postgresql.org/docs/12/app-psql.html https://www.postgresql.org/docs/12/libpq-pgpass.html https://www.postgresql.org/docs/12/libpq-envars.html https://www.postgresql.org/docs/12/libpq-connect.html#LIBPQ-CONNSTRING 如果您有其他问题,欢迎您联系火山引擎技术支持服务

37
0
0
0
相关产品
评论
未登录
看完啦,登录分享一下感受吧~
暂无评论