首页 > 解决方案 > 使用 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)

我希望收到包含 first_name、last_name 和 location 的数据集,但我得到了错误 108。

标签: pythonsshparamiko

解决方案


如果一个命令不起作用,当使用 Paramiko 执行时,通过读取它的错误输出来调试它。

为此使用stderr.readlines()


如果相同的命令在常规 shell 中有效,但在 Paramiko 中无效,则问题通常与 SSH“exec”通道使用的不同环境有关,该通道由SSHClient.exec_command. 看:


推荐阅读