在 Paramiko 的 Windows SSH 服务器上执行命令 (pg_dump) 之前设置环境变量 (PGPASSWORD) [英] Set environment variable (PGPASSWORD) before executing a command (pg_dump) on Windows SSH server in Paramiko

查看:92
本文介绍了在 Paramiko 的 Windows SSH 服务器上执行命令 (pg_dump) 之前设置环境变量 (PGPASSWORD)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 SSH 连接到 Windows Server 2019 来创建我的 postgres 数据库的备份.我使用 Paramiko Python 库来执行此操作,但不幸的是 sql 文件不包含任何数据(文件大小为 0并且文件不能删除,因为它们仍然在 cmd 中打开).因此,我怀疑我的命令的执行还没有完成......这是我的功能:

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()

顺便说一句:在 PuTTY 中执行命令会产生所需的输出.有谁知道如何解决这个问题?感谢您的帮助!

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

推荐答案

这基本上就是这个问题:
在Paramiko中执行多个命令,使命令受其前任影响.

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

唯一的区别是您使用的是 Windows,其中 set 甚至包括变量值的训练空间.因此,请确保密码和 && 之间没有空格:

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

这篇关于在 Paramiko 的 Windows SSH 服务器上执行命令 (pg_dump) 之前设置环境变量 (PGPASSWORD)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆