Python执行远程ssh命令

2024-09-29 01:33:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个python-nagios检查来检查文件上次更新时的时间戳,但是我需要检查脚本中的两个独立主机,所以我想使用一个远程ssh命令将时间戳返回到stdout,并使用它来确保脚本在过去24小时内完成,因为当脚本完成时,它会碰到文件。在

当我从命令提示符运行命令时,它可以工作,但是当我从python代码运行它时,它不会将输出返回到我的程序。在

Grants-MacBook-Pro:test GrantZukel$ ssh ubuntu@hostname sudo ls -la /home/ubuntu/ | grep code_regen_complete

The authenticity of host 'ec2-54-144-160-238.compute-1.amazonaws.com (54.144.160.238)' can't be established.

RSA key fingerprint is hidden.

Are you sure you want to continue connecting (yes/no)? yes

Failed to add the host to the list of known hosts (/Users/GrantZukel/.ssh/known_hosts).

-rw-r--r-- 1 root   root       0 Jan 29 17:23 code_regen_complete

Grants-MacBook-Pro:test GrantZukel$ 

Python是:

^{pr2}$

但是,当我使用调试器时,out或err变量是完全空的。有什么想法吗?在


Tags: 文件totest命令脚本ubuntu时间code
2条回答

您需要在命令中传递shell=True

p = subprocess.Popen(['ssh','ubuntu@hostname', '"sudo ls -la /home/ubuntu/ | grep code_regen_complete"'], stdout=subprocess.PIPE,shell=True)

去掉ls命令前后的双引号:

p = subprocess.Popen(['ssh','ubuntu@hostname', 'sudo ls -la /home/ubuntu/code_regen_complete'], stdout=subprocess.PIPE)

您可能还想试试Fabric。在

相关问题 更多 >