Set environment variable (PGPASSWORD) before executing a command (pg_dump) on Windows SSH server in Paramiko

妖精的绣舞 提交于 2021-02-16 15:14:28

问题


I want to create a backup of my postgres database via SSH connecting to a Windows Server 2019. I use the Paramiko Python library in order to do this, but unfortunately the sql-file does not contain any data (file size is 0 and files cannot not deleted as they are still opened in cmd). Thus, I suspect the execution of my command hasn't finished ... This is my function:

def ssh_server(server, username, password, pg_pass, ps_user, database):

    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    client.connect(hostname=server, username=username, password=password)

    stdin_2, stdout_2, stderr_2 = client.exec_command("SET PGPASSWORD=secret_pw")

    stdin, stdout, stderr = client.exec_command(
        "pg_dump -U {} {} > kp_{}.sql\n".format(
            ps_user, database, ts_str), get_pty=True)

    client.close()

BTW: Executing the commands in PuTTY yields the desired output. Does anyone have an idea how to fix this issue? Thanks for your help!


回答1:


This is basically this question:
Execute multiple commands in Paramiko so that commands are affected by their predecessors.

The only difference, is that you are on Windows, where set includes even training spaces to the value of the variable. So make sure there are no spaces between the password and the &&:

SET PGPASSWORD=secret_pw&&pw_dump


来源:https://stackoverflow.com/questions/60549576/set-environment-variable-pgpassword-before-executing-a-command-pg-dump-on-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!