如何让普通的Linux用户在没有sudo访问权限的情况下访问PostgreSQL数据库?

3
我们在Centos7上安装了一个PostgreSQL数据库服务器(版本为10.3),并创建了一个名为"db_name"的数据库。我们拥有对该数据库的访问权限。在pg_hba.conf文件中,设置如下:
# "local" is for Unix domain socket connections only
local   all             all                                     trust
host    all             all             127.0.0.1/32            trust
host    all             all             ::1/128                 trust
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            ident
host    replication     all             ::1/128                 ident

当我拥有sudo权限时,我可以访问数据库"db_name"。

[root@localhost bin]# sudo -s       
[root@localhost bin]# psql -U db_name db_user
psql (10.3)
Type "help" for help.

db_name=>

当我尝试以普通Linux用户的身份访问数据库时,出现了以下错误:
[linuxuser@localhost bin]# psql -U db_name db_user
psql: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

我们想要限制某些用户的sudo访问权限,是因为我们的报表专员需要访问数据库“db_name”,但我们不希望他们有sudo权限来执行其他操作。

为了使其生效,我应该进行哪种设置? 谢谢!


尝试建立TCP连接:psql -h -U username dbname。另外,您没有提到创建用户,只是数据库而已。当您创建一个数据库时,Postgres并不会自动为您创建一个用户。 - user330315
2个回答

2
我找到了解决方案。 问题的原因是/var/run/postgresql/.s.PGSQL.5432文件不存在。 默认情况下,unix_socket_directories设置在postgresql.conf中的“/tmp”目录下。
由于某些原因,常规Linux用户未查看/tmp/.s.PGSQL.5432,而是查看/var/run/postgresql/.s.PGSQL.5432文件。
因此,修复方法如下:
cd /var/run
mkdir postgresql 
cd postgresql/ 
ln -s /tmp/.s.PGSQL.5432 .s.PGSQL.5432 

以下命令同样有效。
psql -h /tmp -U db_user db_name 

你救了我的一天。 - Kiruahxh
sudo mkdir -p /var/run/postgresql && sudo ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432短版本: - Kiruahxh

1
在PostgreSQL中,您需要创建一个角色来访问数据库。
为此,您需要执行以下操作:
  1. Change to postgres account (Created during installation of postgresql)

    $ sudo -i -u postgres
    
  2. Create a new role

    postgres@server createuser --interactive
    
    Output
    Enter name of role to add: DB_Name
    Shall the new role be a superuser? (y/n) y
    
  3. Create Database

    postgres@server createdb DB_Name
    
  4. Create user, change to user and access to database

    $ sudo adduser DB_Name
    $ sudo -i -u DB_Name
    $ psql
    DB_Name=# \conninfo
    

参考资料:

如何在CentOS 7上安装和使用PostgreSQL


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接