python - 在远程服务器上运行命令以秒为单位查找正常运行时间

标签 python linux python-3.x

这是我目前所拥有的:

#!/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/

相关文章:

Python 类型错误 : __init__() got multiple values for argument 'master'

python - Tensorflow 2.1.0 - DLL 加载失败 - Windows CPU

python - 用 numpy 的 eigh 和 svd 计算的特征向量不匹配

linux - Linux 上的 grep 命令(特别是 grep --exclude)

linux - 千个并发请求 - EAI_AGAIN/ECONNRESET 错误

regex - 使用正则表达式列表文件搜索文件仅包含单引号

python - 如何在保留列表的同时通过某个索引从矩阵中 heappush 列表?

python - 关于接受 zip 文件进行处理的守护进程的建议

python - 通过 ctypes 将 Unicode 字符串传递给 printf

qt - PyQt 中的半可调整大小的小部件