2017-04-12 41 views
0

问题:使用PSQL pg_dumppg_restore在Python脚本,并使用subprocess模块。的pg_dump和使用Python模块子pg_restore的密码

背景:我使用以下python 2.7脚本从本地主机(即Ubuntu 14.04.5 LTS),以在PSQL服务器上创建一个表的备份(即PostgreSQL 9.4.11),并将其恢复到远程主机(即Ubuntu 16.04.2 LTS)在更新版本的PSQL服务器(即PostgreSQL 9.6.2)。

#!/usr/bin/python 

from subprocess import PIPE,Popen 

def dump_table(host_name,database_name,user_name,database_password,table_name): 

    command = 'pg_dump -h {0} -d {1} -U {2} -p 5432 -t public.{3} -Fc -f /tmp/table.dmp'\ 
    .format(host_name,database_name,user_name,table_name) 

    p = Popen(command,shell=True,stdin=PIPE) 

    return p.communicate('{}\n'.format(database_password)) 

def restore_table(host_name,database_name,user_name,database_password): 

    command = 'pg_restore -h {0} -d {1} -U {2} < /tmp/table.dmp'\ 
    .format(host_name,database_name,user_name) 

    p = Popen(command,shell=True,stdin=PIPE) 

    return p.communicate('{}\n'.format(database_password)) 

def main(): 
    dump_table('localhost','testdb','user_name','passwd','test_tbl') 
    restore_table('remotehost','new_db','user_name','passwd') 

if __name__ == "__main__": 
    main() 

当我使用的功能的顺序与上述dump_table()函数成功完成,并创建/tmp/table.sql文件,但restore_table()函数返回以下错误:

('', 'Password: \npg_restore: [archiver (db)] connection to database "database_name" failed: FATAL: password authentication failed for user "username"\nFATAL: password authentication failed for user "username"\n')*

我已经通过执行检查凭证&输出在shell中的pg_restore的命令,我也包括凭证.pgpass(虽然不相关,因为我在p.communicate()通过密码)

任何人都有类似的经历?我几乎卡住了!

问候, D.

回答

1

以下工作并取得被注释掉的变化。

我不知道但为什么pg_restore使用了全命令(即未在列表中拆分),并在Popen使用shell=True时产生密码验证错误,但pg_dump,另一方面工作正常使用shell=True &完整的命令。 <必须做任何事情吗?

#!/usr/bin/python 

from subprocess import PIPE,Popen 
import shlex 

def dump_table(host_name,database_name,user_name,database_password,table_name): 

    command = 'pg_dump -h {0} -d {1} -U {2} -p 5432 -t public.{3} -Fc -f /tmp/table.dmp'\ 
    .format(host_name,database_name,user_name,table_name) 

    p = Popen(command,shell=True,stdin=PIPE,stdout=PIPE,stderr=PIPE) 

    return p.communicate('{}\n'.format(database_password)) 

def restore_table(host_name,database_name,user_name,database_password): 

    #Remove the '<' from the pg_restore command. 
    command = 'pg_restore -h {0} -d {1} -U {2} /tmp/table.dmp'\ 
       .format(host_name,database_name,user_name) 

    #Use shlex to use a list of parameters in Popen instead of using the 
    #command as is. 
    command = shlex.split(command) 

    #Let the shell out of this (i.e. shell=False) 
    p = Popen(command,shell=False,stdin=PIPE,stdout=PIPE,stderr=PIPE) 

    return p.communicate('{}\n'.format(database_password)) 

def main(): 
    dump_table('localhost','testdb','user_name','passwd','test_tbl') 
    restore_table('localhost','testdb','user_name','passwd') 

if __name__ == "__main__": 
    main()