3

在不存在数据库的情况下,如何验证 postgresql 用户和密码是否有效?

我正在创建一个自动安装,它将创建一个数据库并运行 sql 脚本来创建表。安装需要在运行脚本之前验证用户和密码。自动安装调用 Windows 批处理文件。首先我设置密码,设置PGPASSWORD=mypassword

设置密码后,什么命令可以验证用户和密码并返回错误代码或消息?

其他数据库程序(如 IBM 和 db2)有一个附加命令,允许用户附加到服务器或实例,而无需指定 db 名称。我找不到 PostgreSQL 的等价物。

如何在不指定数据库名称的情况下在命令行上登录 PostgreSQL?

4

3 回答 3

3

使用系统表 pg_roles

Postgres 总是安装一个名为“postgres”的数据库。postgres 是您未连接到数据库时连接到的数据库。里面有一张桌子叫pg_roles

使用这个命令:

psql -U pgadmin -d postgres -c 'select * from pg_roles'

这会返回:

 rolname  | rolsuper | rolinherit | rolcreaterole | rolcreatedb | rolcatupdate | rolcanlogin | rolreplication | rolconnlimit | rolpassword | rolvaliduntil | rolconfig |  oid
----------+----------+------------+---------------+-------------+--------------+-------------+----------------+--------------+-------------+---------------+-----------+-------
 postgres | t        | t          | t             | t           | t            | t           | t              |           -1 | ********    |               |           |    10
 pgadmin  | t        | t          | t             | t           | t            | t           | t              |           -1 | ********    |               |           | 16384

(2 行)

请参阅此答案:如何检查 postgres 用户是否存在?

通过登录测试它

只需尝试使用提供的用户名/密码登录并用 try/catch 包围它,如果您可以登录,则它是有效的,否则它是无效的。

改变用户

如果您更改不存在的用户,您可能会收到错误消息:http ://www.postgresql.org/docs/8.0/static/sql-alteruser.html

ALTER USER postgres WITH PASSWORD 'tmppassword';

删除并重新添加用户

如果您尝试删除并重新添加用户,您可能会收到错误消息。因此,如果它无效,那么当您尝试删除非用户时它会引发错误。 http://www.postgresql.org/docs/8.0/static/sql-createuser.html

于 2013-04-10T13:35:05.600 回答
1

这是从命令行检查用户名/密码组合是否有效的便捷方法。这是从 puppetlabs-postgresql 模块中提取的:

su - username
env PGPASSWORD=somepass psql -h localhost -c 'select 1'
echo $?

...其中“somepass”是被测试的密码,“用户名”是被测试的帐户(通常是 postgres 用户本身)。

如果 $? 为 0,用户/密码组合有效。如果 $? 为1,密码错误或用户不存在。无论哪种方式,都有问题。

这就是 Linux/bash 的方式。Windows 方式大致如下:

(run under the user account you're interested in)

set PGPASSWORD=somepass
psql -h localhost -c 'select 1'

if errorlevel 1 (
    echo Failure Reason Given is %errorlevel%
    exit /b %errorlevel%
)

psql 上的 -h 强制建立基于 TCP 的本地连接,默认情况下(来自 pg_hba.conf)强制进行密码检查,无密码用户不可能绕过。

对于没有发布经过全面测试的 Windows 解决方案,我深表歉意,但上面的代码很有可能会直接运行,或者只需稍作修复即可。

于 2014-02-04T21:12:35.840 回答
-2

只需在终端中使用此命令:

psql postgres
于 2017-11-16T04:59:31.570 回答