您当前的位置:易学堂 > 日志记录

在python中使用linux命令写一个监控脚本

时间:2022-05-12 14:47:42

编写python监控脚本,监控/和/boot分区的使用率,/ 大于60%就告警,在屏幕上输出内容,具体自己定义

/boot分区大于50%就告警

脚本名monitor_partition.py

将磁盘的使用率写到日志文件里到/var/log/root_boot_partition.txt,具体内容自己定义

2022-4-26 22:01:01 /boot used 45%

2022-4-26 22:01:01 / used 70%

软件工程:

1.需求分析

monitor_partition.py

1.1.如何在python里执行linux命令?

模块: os subprocess

标准库: 自带的不需要安装

pip install **

1.2 如果将内容保存到文件 open()

1.3 如何在python里获得当前的时间?

datetime

时间的格式化输出: 按照我需要的格式输出,或者指定格式输出

date +%Y%m%d

2.写文档

3.设计

python

1. 执行linux命令df

2. 判断

3.写日志

4.开发


datetime模块

>>> import datetime
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2022-05-07 20:46:00' 

subprocess

subprocess 执行系统(linux,windows、mac os)的命令

>>> import subprocess导入库(模块)
>>> subprocess.run('ls',shell=True)--》run方法去执行ls命令
monitor_partition.sh
>>> num=subprocess.run('ls',shell=True).returncode将命令的返回值赋值给num
monitor_partition.sh 
>>> root_part = subprocess.run("df |grep /$|awk '{print $5}'|tr -d % ",shell=True)
83
>>> root_part = subprocess.run("df |grep /$|awk '{print $5}'|tr -d % ",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> root_part.
root_part.args root_part.stderr
root_part.check_returncode(root_part.stdout
root_part.returncode 
>>> root_part.stdout
b'83\n' 

stdout:标准输出

>>> lei = subprocess.run('ls /lianxi',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> lei.stdout
b'410\n412\n417\n419\n426\n57\nchen.yaml\ndy.yaml\nfeng\nfeng2.yaml\nfeng.yaml.xz\nhejin.yaml.gz\niptables.rules\nluoyawei\npod+service\nsanchuang\nscfeng.py\nservice.yaml\ntang.yaml\ntangyuhao.yaml\nwang.yaml\nxiong.yaml\n'
>>> print(lei.stdout)
b'410\n412\n417\n419\n426\n57\nchen.yaml\ndy.yaml\nfeng\nfeng2.yaml\nfeng.yaml.xz\nhejin.yaml.gz\niptables.rules\nluoyawei\npod+service\nsanchuang\nscfeng.py\nservice.yaml\ntang.yaml\ntangyuhao.yaml\nwang.yaml\nxiong.yaml\n'
>>> 

stdout=subprocess.PIPE 定义subprocess执行命令的标准输出到subprocess.PIPE里

标准输入 stdinput standard input -->从键盘 标准输出 stdoutput standard output --》屏幕 标准错误输出 stderr standard error output --》屏幕

在这里插入图片描述

脚本:

import datetime

num_root = subprocess.run("df -h|grep '/$'|awk '{print $5}'|tr -d % ", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

num_boot = subprocess.run("df -h|grep 'boot$'|awk '{print $5}'|tr -d % ", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

ctime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

num_root.stdout = int(num_root.stdout)
num_boot.stdout = int(num_boot.stdout)

if (num_root.stdout > 60):
	print("root usage is not enough!")
	print("root_usage:", num_root.stdout)
if (num_boot.stdout > 50):
	print("boot usage is not enough!")
	print("root_usage:", num_boot.stdout)

with open("/var/log/root_boot_partition.txt", "a+") as fp:
	fp.write(f"{ctime} /boot used {num_boot.stdout}%\n")
	fp.write(f"{ctime} /root used {num_root.stdout}%\n") 
标签: LinuxPython