![](/img/trans.png)
[英]Is there a way I can store the output of a terminal command into a file using python?
[英]How can I store the output of a command I ran using SSH from a Python script into a file?
我希望能够将使用SSH在Python脚本中在远程主机上运行的命令的输出(例如top
)存储到文件中。
我知道如何使用SSH(我目前正在使用Paramiko连接到远程设备)。 我需要运行命令,然后将输出存储在文本文件中。
您尝试了什么?
根据您的命令,您可以执行以下操作:
ssh user@machine command > log
日志将保存到您的计算机。 一个真实的例子:
ssh root@192.168.x.x ls > log
如果您的命令不支持stdout的输出,请按以下方式运行它:
ssh root@192.168.x.x "command -o output; cat output" > log
使用python,您可以使用子进程并执行相应的命令,例如:
import subprocess
def yourfunction():
subprocess.call("ssh user@machine command > log",shell=False)
yourfunction()
如果使用paramiko的exec_command方法执行命令,则可以执行以下操作:
stdin, stdout, stderr = your_ssh_client_object.exec_command("top")
with open("out.txt", "w") as f:
f.writelines(stdout.readlines())
如果您也关心错误输出,则需要将其附加到同一文件或存储在单独的文件中。
( 注意 :上面的代码未经测试,也无法单独运行,因为OP本身并没有提供最小的可行示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.