python - 接受 Linux 命令以返回服务器运行状况的 Python 脚本
问题描述
对于我的工作,我正在开发一个小脚本,用户可以运行它来检查日志文件中的错误。我熟悉 Python 和 cmd 提示,但不会在另一个中运行。
我读了很多,但真的找不到最好的过程。对于我的意图,许多似乎有点复杂。
理想情况下,我想要构建一个遵循此过程的程序:
对于主机中的所有目录:
- cd 进入目录,然后 grep 某个字符串的日志文件
-print errors
-return back to a dir
- 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
可能更复杂的思考方式。我只是想看看那些以前尝试做类似事情的人是否有任何有用的讨论。
解决方案
看起来你尝试用 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('/')
推荐阅读
- android - Flutter(或 Dart)的 QR 扫描插件
- cmake - 构建openpose库时Cmake在生成期间抛出错误
- php - 为什么我在 Symfony 5 上使用 DateTime 约束时会收到“这个值应该是字符串类型”?
- blazor - Blazor - 绑定数据而不使用任何事件(onChange,onInput ...)
- testing - kubernetes e2e 测试因 spec.configSource 失败:值无效
- python - 为什么 Flask 应用程序没有第二次运行?
- c# - GroupJoin,一个窗口在流完成时结束
- networking - 外部 SNMP 管理器无法访问 k8s 上的 snmp 客户端
- linux - Linux中需要根据文件名的最后两个字符将文件移动到特定目录
- vba - 您可以使用复选框的名称来访问其值吗?