方法一:.pgpass
查看postgres家目录
grep postgres /etc/passwd
postgres:x:114:119:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
创建.pgpass
touch /var/lib/postgresql/.pgpass
chown -R postgres.postgres /var/lib/postgresql/.pgpass
chmod 0600 /var/lib/postgresql/.pgpass
文件格式
hostname::::port_ database_ username_password
示例
echo "192.168.1.23:5432:postgres:postgres:postgres" >> /var/lib/postgresql/.pgpass
连接测试
su - postgres -c "psql -U postgres -h 192.168.1.23 -p 5432 -w "
psql (15.2 (Ubuntu 15.2-1.pgdg20.04+1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
Type "help" for help.
postgres=#
方法二:设置环境变量 PGPASSWORD
su - postgres -c " export PGPASSWORD="postgres" && psql -U postgres -h 192.168.1.23 -p 5432 "
psql (15.2 (Ubuntu 15.2-1.pgdg20.04+1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
Type "help" for help.
postgres=#
方法三:auth-method trust
pg_hba.conf
echo "host postgres postgres 0.0.0.0/0 trust" >> /etc/postgresql/15/main/pg_hba.conf
重启服务
systemctl restart postgresql.service
测试远程连接
su - postgres -c " psql -U postgres -h 192.168.1.23 -p 5432 "
psql (15.2 (Ubuntu 15.2-1.pgdg20.04+1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
Type "help" for help.
postgres=#
注意事项
host postgres postgres 0.0.0.0/0 trust
host all all 0.0.0.0/0 scram-sha-256
# trust 认证规则需要在scram-sha-256规则之前,否则trust不生效