使用Python Paramiko exec_command执行时命令未完成 [英] A command does not finish when executed using Python Paramiko exec_command

查看:170
本文介绍了使用Python Paramiko exec_command执行时命令未完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python程序,该程序位于远程服务器上,该服务器在运行时会将文件上传到AWS存储桶.如果我使用ssh进入服务器并使用命令 sudo python3/path/to/backup.py 运行它,它将按预期工作.

I've got a Python program which sits on a remote server which uploads a file to an AWS bucket when run. If I ssh onto the server and run it with the command sudo python3 /path/to/backup.py it works as expected.

我正在编写一个Python程序来自动化一个更大的过程,其中包括运行backup.py.我使用paramiko库创建了一个函数来执行此操作.这是命令运行的地方

I'm writing a Python program to automate a bigger process which includes running backup.py. I created a function to do this using the paramiko library. This is where the command gets run

ssh_stdin, ssh_stdout, ssh_stderr = self.ssh.exec_command('sudo python3 /path/to/backup.py', 1800)
logging.debug(f'ssh_stdout: {ssh_stdout.readline()}')
logging.debug(f'ssh_stderr: {ssh_stderr.readline()}')

我的自动化为我提供了以下输出:

My automation gives me this output:

ssh_stdout: Tue, 19 May 2020 14:36:43 INFO     The COS endpoint is 9.11.200.206, writing to vault: SD_BACKUP_4058

此后该程序不执行任何操作.当我登录到服务器并检查 backup.py 的日志时,我可以看到它仍在运行,并且似乎位于文件上传位置.这是它停留在的代码:

The program doesn't do anything after that. When I log onto the server and check the logs of backup.py, I can see that it is still running and seems to be sitting at the file upload. This is the code it's stuck at:

s3_client.upload_file(
    Filename=BACKUP,
    Bucket=BUCKET_NAME,
    Key=SPLIT_FILE_NAME,
    Callback=pp(BACKUP),
    Config=config)

我不明白为什么当我的自动化程序启动它时会卡在这里,而不是我从终端中的命令行运行它时为什么会卡在这里.我在日志中看不到任何对我有帮助的东西.它似乎只是停留在执行它的那一点上.可能与回调未返回有关吗?

I can't understand why it's getting stuck here when started by my automation program and not when I run it from a command line in the terminal. I can't see anything in the logs which help me. It just seems to be stuck at that point in its execution. Could it be something to do with the callback not getting returned?

推荐答案

您只能读取输出的一行.

You read only one line of the output.

logging.debug(f'ssh_stdout: {ssh_stdout.readline()}')

如果远程程序产生大量输出,则在其输出缓冲区填满后,程序将在下一次尝试写入某些输出时挂起.

If the remote program produces lot of output, as soon as its output buffer fills in, the program hangs on the next attempt to write some output.

如果要结束程序,则必须继续读取输出.

If you want the program to finish, you have to keep reading the output.

最简单的方法是使用 readlines read :

The simplest way is to use readlines or read:

print(stdout.read())

但是对于像您这样的大型输出而言,这效率很低.

But that's inefficient for large outputs like yours.

相反,您可以逐行读取输出:

Instead you can read the output line by line:

for line in stdout:
    print(line.strip())


当命令还产生错误输出时,情况变得更加复杂,因为此时您必须读取两个输出流.参见 Paramiko ssh die/hang大输出.

这篇关于使用Python Paramiko exec_command执行时命令未完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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