[英]Running a command on a remote server to find the uptime in seconds
這是我到目前為止的內容:
#!/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 /proc/uptime
的相同錯誤。
但是,如您在回溯末尾所看到的:
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解釋為一個參數。
IRC上有人建議我使用command_string = "cat /proc/cpu/"
並
result = uptime("-p", "pass", "ssh", "theo@localhost", command_string)
哪個有效!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.