首页 > 解决方案 > 接受 Linux 命令以返回服务器运行状况的 Python 脚本

问题描述

对于我的工作,我正在开发一个小脚本,用户可以运行它来检查日志文件中的错误。我熟悉 Python 和 cmd 提示,但不会在另一个中运行。

我读了很多,但真的找不到最好的过程。对于我的意图,许多似乎有点复杂。

理想情况下,我想要构建一个遵循此过程的程序:

对于主机中的所有目录:

  1. cd 进入目录,然后 grep 某个字符串的日志文件
 -print errors

 -return back to a dir
  1. cd 进入目录:
df -h 

我个人的偏好是这样执行:

def myFirstCheck():
    file_result = cat a/b/c/LogFile.log | awk /ERROR\|/FATAL\
    file0_result = cat a/b/c/LogFile2.log | awk /ERROR\|/FATAL\
    return file_result, file0_result
    
def mySecondCheck():
    print('Server 2 check:')
    file2_result = cat d/e/f/LogFile3.log | awk /ERROR\|/FATAL\
    file3_result = cat d/e/f/LogFile4.log | awk /ERROR\|/FATAL\
    return file2_result, file3_result

file_result, file0_result = myFirstCheck()
print('Server 1 check:')
print('df -h') #I want this to return the output from cmd 'df -h'
print(file_result)
print(file0_result)

file2_result, file3_result = mySecondCheck()
print('Server 2 check:')
print('df -h') #I want this to return the output from cmd 'df -h'
print(file2_result)
print(file3_result)

#exit 

     

我知道这是非常低效的,并且可能是一种simple可能更复杂的思考方式。我只是想看看那些以前尝试做类似事情的人是否有任何有用的讨论。

标签: pythonlinuxhealth-check

解决方案


看起来你尝试用 cmd 做很多事情,但你可以用 pythonicly 来做。

你可以像这样读取文件:

with open("/path/to/log/file", "r") as f:
    data = f.read()
error_lines = [line for line in data.splitlines() if "ERROR" in line]

其次,对于 df -h,您可以简单地执行以下操作:

import subprocess
subprocess.check_output("df -h")

或者,如果你想做 pythonic 并且知道磁盘路径,你可以这样做:

import psutil
hdd = psutil.disk_usage('/')

推荐阅读