这是我目前所拥有的:
#!/usr/bin/python
import sys
import os
import subprocess
from subprocess import check_output
import time
import sh
from sh import sshpass
import re
import time, datetime
check_time = 0
with open("log.txt", "a") as f:
while 1:
#out = check_output(["sshpass", "-p", "pass", "ssh",
# "theo@localhost", "\"/usr/bin/cat",
# "/proc/uptime\""])
#print (out)
#out = str(out)
uptime = sh.Command("/usr/bin/sshpass")
result = uptime("-p", "pass", "ssh", "theo@localhost", "\"cat",
"/proc/uptime\"")
result = str(result)
print (result)
result = result.split(' ', 1)[0]
print (result)
f.write(result)
result_int = int(result)
if result_int > check_time:
print("it rebooted", result_int, "minutes ago")
time.sleep(5)
结果:
checking uptime
Traceback (most recent call last):
File "./uptime.py", line 23, in <module>
result = uptime("-p", "pass", "ssh", "theo@localhost", "\"cat", "/proc/uptime\"")
File "/usr/lib/python3.5/site-packages/sh.py", line 1021, in __call__
return RunningCommand(cmd, call_args, stdin, stdout, stderr)
File "/usr/lib/python3.5/site-packages/sh.py", line 486, in __init__
self.wait()
File "/usr/lib/python3.5/site-packages/sh.py", line 500, in wait
self.handle_command_exit_code(exit_code)
File "/usr/lib/python3.5/site-packages/sh.py", line 516, in handle_command_exit_code
raise exc(self.ran, self.process.stdout, self.process.stderr)
sh.ErrorReturnCode_127:
RAN: '/usr/bin/sshpass -p pass ssh theo@localhost "cat /proc/uptime"'
STDOUT:
STDERR:
zsh:1: no such file or directory: cat /proc/uptime
你可以看到我有两次尝试,一次使用 sh
库,一次使用 check_output,两者都导致相同的错误,即无法运行 /usr/bin/cat/过程/正常运行时间
。
然而,正如您在回溯的末尾所看到的:
RAN: '/usr/bin/sshpass -p pass ssh theo@localhost "cat /proc/uptime"'
这似乎是一个完全有效的行,如果我将它复制粘贴到终端中,它就可以工作。
有什么想法吗?如果我只是输入“正常运行时间”,该命令确实有效,而不是编辑它的输出以获取以秒为单位的时间,我认为这样做会更容易(至少我认为 应该是):)
我正在使用 python 3.5.2
最佳答案
根据输出,您需要将正常运行时间线修改为如下所示:
result = uptime("-p", "pass", "ssh", "theo@localhost", "cat",
"/proc/uptime")
看起来“cat/proc/uptime”在您的原始代码中被 ssh 解释为一个参数。
关于python - 在远程服务器上运行命令以秒为单位查找正常运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39809487/