标签:PostgreSQL postgres 账号 hba pg conf 9.5 local
PostgreSQL数据库中,假如你忘记了postgres账号的密码或者由于工作交接问题,等交接到你手头的时候,没有postgres账号密码,那怎么办呢?其实不用慌,像MySQL、SQL Server等数据库一样,只要你拥有操作系统权限,修改postgres超级账号的密码也非常方便简单。下面测试环境为CentOS Linux release 7.2.1511 (Core), PostgreSQL数据库版本为9.5。其它不同版本的操作其实是一样的,只是略有细微差别。
1:定位pg_hba.conf文件位置
首先找到pg_hba.conf文件的位置,具体有下面这些方法:
方法1:locate定位pg_hba.conf文件的位置
$ locate pg_hba.conf
/usr/pgsql-9.5/share/pg_hba.conf.sample
/var/lib/pgsql/9.5/data/pg_hba.conf
方法2:find命令查找。
$ find / -name "pg_hba.conf" 2>%1 | grep -v "Permission denied"
/var/lib/pgsql/9.5/data/pg_hba.conf
2:修改pg_hba.conf配置文件
修改pg_hba.conf前最好做一个备份,这是一个良好的习惯,避免回滚的时候,你能轻松回撤所有操作。
#cp /var/lib/pgsql/9.5/data/pg_hba.conf /var/lib/pgsql/9.5/data/pg_hba.conf.20210125
在pg_hba.conf中找到类似下面这样的地方:
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all md5
# IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
host all all ::1/128 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local replication postgres peer
#host replication postgres 127.0.0.1/32 ident
#host replication postgres ::1/128 ident
# Allow access from all host to connect to this UAT server
host all all 0.0.0.0/0 md5
关于修改pg_hba.conf,如果你打算以socket方式在本机登录数据库,那么只需修改local这条记录,将pg_hba.conf中的这个选项的的值从md5修改为trust
修改前
# "local" is for Unix domain socket connections only
local all all md5
修改后
# "local" is for Unix domain socket connections only
local all all trust
trust表示允许可信的本地连接。此时连接数据库不用输入密码。
小知识:
TYPE表示主机类型,它的取值有下面这些:
local :表示是unix-domain的socket连接
host :表示TCP/IP socket
hostssl: 表示SSL加密的TCP/IP socket
如果你打算以TCP/IP方式访问数据库,即psql -h127.0.0.1 -Upostgres这样的方式,那么必须修改host的配置。具体如下所示:
修改前:
# IPv4 local connections:
host all all 127.0.0.1/32 md5
修改后:
# IPv4 local connections:
host all all 127.0.0.1/32 trust
3: 重启PostgreSQL服务
重启PostgreSQL服务的方法很多,这里不做过多介绍,选择你常用的方式即可。
# service postgresql-9.5 stop
Redirecting to /bin/systemctl stop postgresql-9.5.service
# service postgresql-9.5 start
Redirecting to /bin/systemctl start postgresql-9.5.service
# service postgresql-9.5 status
Redirecting to /bin/systemctl status postgresql-9.5.service
4:重置账号postgres的密码
使用psql无密码登录,修改用户postgres的密码
alter user postgres with password '新的密码';
方式1:
psql -U postgres
方式2:
psql
关于两者,如果ssh是用postgres用户连接服务器的话,那么直接psql即可,如果是root用户连接服务器的话,必须用psql -U postgres
-bash-4.2$ psql
psql (9.5.6)
Type "help" for help.
postgres=# alter user postgres with password 'xxxxxxxx';
ALTER ROLE
5:恢复pg_hba.conf配置文件的修改
6:重启PostgreSQL服务
标签:PostgreSQL,postgres,账号,hba,pg,conf,9.5,local 来源: https://www.cnblogs.com/kerrycode/p/14324465.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。