运行数据库脚本并将结果发送到文件

时间:2019-05-28 20:32:37

标签: python ssh paramiko

在数据库结果可用之前创建输出文件。

传递一个简单的os命令可以正常工作:

# command = "whoami > result.txt"

工作正常。打开result.txt文件时,我会得到用户名。问题是等待数据库返回结果。即使有实际查询返回的数据,它还是空的

import paramiko


def get_report(command):
    # reference: https://stackoverflow.com/questions/5193886/python-paramiko-issue-while-closing-the-connection.
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('server123', username='username', password='password')

    stdin, stdout, stderr = client.exec_command(command)
    exit_status = stdout.channel.recv_exit_status()

    if exit_status == 0:
        print("File processed")
    else:
        print("Error", exit_status)
    client.close()

command = "sql_query.script > result.txt"
get_report(command=command)

我希望收到名字,姓氏和位置的数据集,但出现错误108。

1 个答案:

答案 0 :(得分:0)

如果命令不起作用,则在使用Paramiko执行该命令时,请通过读取其错误输出对其进行调试。

为此使用stderr.readlines()


如果同一命令在常规Shell中有效,但在Paramiko中无效,则该问题通常与SSHClient.exec_command使用的SSH“ exec”通道所使用的不同环境有关。参见:

相关问题