简体   繁体   English

多个密码尝试pg_dump python

[英]Multiple Password attempts pg_dump python

I am trying to allow the user of my script to prompt users to enter the correct password if they have entered an invalid one. 我试图允许我的脚本用户提示用户输入正确的密码,如果他们输入了无效的密码。 I am not sure whether this a psql configuration or if its done by using error handling with python. 我不确定这是一个psql配置还是通过使用python处理错误来完成的。 Which one do I use and how? 我使用哪一个以及如何使用? My current code is as follows: 我目前的代码如下:

 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.

I am running postgresql96 on FreeBSD. 我在FreeBSD上运行postgresql96 When I enter a bad password the return code for pg_dump is 1, rather than 0. 当我输入错误的密码时, pg_dump的返回码是1,而不是0。

A naive solution would be to put your code in a while loop like this: 一个天真的解决方案是将您的代码放在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

The problem is that pg_dump will likely return 1 on any error, including when system calls to allocate memory or disk space fail. 问题是pg_dump可能会在任何错误上返回1,包括系统调用分配内存或磁盘空间失败时。 So it doesn't actually mean that the password input failed, and you might want a hook to exit without a successful return after n tries or using something else. 因此,它实际上并不意味着密码输入失败,并且您可能希望在n次尝试或使用其他内容后退出但没有成功返回。

Another solution might be to check if the dump output file exists and was recently modified. 另一种解决方案可能是检查转储输出文件是否存在并且最近是否已修改。 You might also want to inspect stderr for the error message that talks about a bad password. 您可能还需要检查stderr以查找说明密码错误的错误消息。

I think those solutions are hacky. 我认为这些解决方案很糟糕。

The best solution (AFAICT) is to not use a separate process to do the dump (because then communicating with that process can be a pain in the ass), but use a Python library, like psycopg2 to access the database. 最好的解决方案(AFAICT)是不使用单独的进程来执行转储(因为那时与该进程通信可能会很麻烦),但是使用Python库(如psycopg2来访问数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM