多次密码尝试 pg_dump python

Multiple Password attempts pg_dump python

我试图让我的脚本的用户在输入无效密码时提示用户输入正确的密码。我不确定这是一个 psql 配置还是通过使用 python 的错误处理来完成的。我应该使用哪一个以及如何使用?我现在的代码如下:

 backup_ps = subprocess.Popen(
    ['pg_dump','-h', ORIGIN_DB, '-U', ORIGIN_DB_USER, ORIGIN_DB_NAME, '-f', destination, '-c',
     '-t', 'table1',
     '-Fp', '--inserts'],
    stdout=subprocess.PIPE
)

output = backup_ps.communicate()[0]

# if password incorrect, prompt for correct password.

我在 FreeBSD 上 运行 postgresql96。当我输入错误密码时,pg_dump 的 return 代码是 1,而不是 0。

一个天真的解决方案是将您的代码放在一个 while 循环中,如下所示:

while True:
    backup_ps = subprocess.Popen(
        ['pg_dump','-h', ORIGIN_DB, '-U', ORIGIN_DB_USER, ORIGIN_DB_NAME, '-f', destination, '-c',
            '-t', 'table1',
            '-Fp', '--inserts'],
        stdout=subprocess.PIPE
    )

    output = backup_ps.communicate()[0]
    if backup_ps.returncode == 0:
        break

问题是 pg_dump 可能会 return 1 出现任何错误,包括分配内存或磁盘的系统调用 space 失败时。因此,这实际上并不意味着密码输入失败,您可能希望在 n 尝试或使用其他方法后没有成功 return 的情况下退出钩子。

另一个解决方案可能是检查转储输出文件是否存在以及是否最近被修改过。您可能还想检查 stderr 以获取有关错误密码的错误消息。

我认为这些解决方案很老套。

最好的解决方案 (AFAICT) 是不使用单独的进程进行转储(因为与该进程通信可能会很痛苦),而是使用 Python 库,例如 psycopg2访问数据库。