一个简单的、小小的系统监控
开发环境
python2.7
运行在Linux机器上
python代码
使用的包
- psutil==5.9.1 :获取内存,CPU,磁盘
- kafka-python==2.0.2 :将获取到的信息发送到kafka
- python-crontab==2.5.1 :利用crontab启动一个系统定时任务获取相关信息,前提是系统得有crontab
python监控代码
# coding=utf-8
import json
import psutil
# pip install kafka-python
from kafka import KafkaProducer
from crontab import CronTab
import argparse
def sys_state(host, kafka):
cpu_percent = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()
disk = psutil.disk_usage("/")
state = {
"host": host,
"cpu_percent": cpu_percent,
"memory": {
"total": memory.total,
"available": memory.available,
"used": memory.used,
"free": memory.free,
"percent": memory.percent
},
"disk": {
"total": disk.total,
"used": disk.used,
"free": disk.free,
"percent": disk.percent
}
}
# 发送到kafka
state_str = json.dumps(state)
producer = KafkaProducer(bootstrap_servers=kafka)
producer.send(topic="topic", key=b'%s' % host, value=b'%s' % state_str)
# 设置周期执行
def set_scheduled(ip, kafka, z_time):
with CronTab(user='root') as crontab:
job = crontab.new(command='sysmonitor -model="now" -ip="%s" -kafka="%s"' % (ip, kafka))
job.minute.every(z_time)
print("使用crontab创建定时成功")
def main():
parser = argparse.ArgumentParser(description="传入命令参数")
parser.add_argument("-model", "--model", type=str, help="运行模式:scheduled 周期执行。now 立即执行一次")
parser.add_argument("-z_time", "--z_time", type=int, required=False, help="周期执行时间,单位分钟")
parser.add_argument("-ip", "--ip", type=str, help="ip地址")
parser.add_argument("-kafka", "--kafka", type=str, help="kafka地址")
args = parser.parse_args()
model = args.model
sys_state(args.ip, args.kafka)
if model == 'scheduled':
set_scheduled(args.ip, args.kafka, args.z_time)
if __name__ == '__main__':
main()
setup.py
from setuptools import setup
setup(
name='sysmonitor',
version='1.0.0',
description='This is a simple monitoring tool',
long_description='This is a simple monitoring tool',
author='sunrd',
author_email='sunrdd@126.com',
packages=['core'],
entry_points='''
[console_scripts]
sysmonitor = core.monitor:main
''',
license='MIT',
include_package_data=True,
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
install_requires=[
'kafka-python==2.0.2',
'psutil==5.9.1',
'python-crontab==2.5.1',
],
)