簡體   English   中英

使用 python 模塊子進程的 pg_dump & pg_restore 密碼

[英]pg_dump & pg_restore password using python module subprocess

問題:在 Python 腳本中使用 PSQL pg_dumppg_restore並使用subprocess模塊。

背景:我使用來自本地主機(即Ubuntu 14.04.5 LTS )的以下python 2.7腳本在 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()函數返回以下錯誤:

('', '密碼:\\npg_restore: [archiver (db)] 到數據庫“database_name”的連接失敗:致命:用戶“用戶名”的密碼驗證失敗\\n致命:用戶“用戶名”的密碼驗證失敗\\n')*

我通過在 shell 中執行pg_restore的命令檢查了憑據和輸出,並且我還將憑據包含在 .pgpass 中(盡管不相關,因為我在p.communicate()傳遞了密碼)

有沒有人有類似的經歷? 我幾乎被困住了!

問候,D。

對以下作品和所做的更改進行了評論。

我不確定為什么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()

您可以使用環境變量https://www.postgresql.org/docs/11/libpq-envars.html和 pg_dump 的“--no-password”選項。

    def dump_schema(host, dbname, user, password, **kwargs):
        command = f'pg_dump --host={host} ' \
            f'--dbname={dbname} ' \
            f'--username={user} ' \
            f'--no-password ' \
            f'--format=c ' \
            f'--file=/tmp/schema.dmp '

        proc = Popen(command, shell=True, env={
            'PGPASSWORD': password
        })
        proc.wait()

這是一個用於獲取 postgres 轉儲並將其恢復到新數據庫的 python 腳本。

import subprocess

DB_NAME = 'PrimaryDB'  # your db name

DB_USER = 'postgres' # you db user
DB_HOST = "localhost"
DB_PASSWORD = 'sarath1996'# your db password
dump_success = 1
print ('Backing up %s database ' % (DB_NAME))
command_for_dumping = f'pg_dump --host={DB_HOST} ' \
            f'--dbname={DB_NAME} ' \
            f'--username={DB_USER} ' \
            f'--no-password ' \
            f'--file=backup.dmp '
 try:
     proc = subprocess.Popen(command, shell=True, env={
                   'PGPASSWORD': DB_PASSWORD
                   })
     proc.wait()

 except Exception as e:
        dump_success = 0
        print('Exception happened during dump %s' %(e))


 if dump_success:
    print('db dump successfull')
 print(' restoring to a new database database')

 """database to restore dump must be created with 
the same user as of previous db (in my case user is 'postgres'). 
i have #created a db called ReplicaDB. no need of tables inside. 
restore process will #create tables with data.
"""

backup_file = '/home/Downloads/BlogTemplate/BlogTemplate/backup.dmp' 
"""give absolute path of your dump file. This script will create the backup.dmp in the same directory from which u are running the script """



if not dump_success:
    print('dump unsucessfull. retsore not possible')
 else:
    try:
        process = subprocess.Popen(
                        ['pg_restore',
                         '--no-owner',
                         '--dbname=postgresql://{}:{}@{}:{}/{}'.format('postgres',#db user
                                                                       'sarath1996', #db password
                                                                       'localhost',  #db host
                                                                       '5432', 'ReplicaDB'), #db port ,#db name
                         '-v',
                         backup_file],
                        stdout=subprocess.PIPE
                    )
        output = process.communicate()[0]

     except Exception as e:
           print('Exception during restore %e' %(e) )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM