python監控linux內存並寫入mongodb

 

(須要安裝psutil 用來獲取服務器資源,以及pymongo驅動)#pip install psutilpython

#pip install pymongomongodb

#vim memory_monitory.pyvim

文件內容以下服務器

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import psutil
import socket
import time
from pymongo import MongoClient
mongodbIp = '192.168.200.112'
mongodbPort = 27017
hostname = socket.gethostbyname(socket.gethostname())#獲取本地IP地址
def getCurrentTime():
        return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
memoryInfo = psutil.virtual_memory()
conn = MongoClient(mongodbIp,mongodbPort)
db = conn.servermonitor
dbset = db.memory
dbset.insert({
        'time':getCurrentTime(),
        'total':memoryInfo.total,
        'available':memoryInfo.available,
        'percent':memoryInfo.percent,
        'used':memoryInfo.used,
        'free':memoryInfo.free,
        'active':memoryInfo.active,
        'inactive':memoryInfo.inactive,
        'buffers':memoryInfo.buffers,
        'cached':memoryInfo.cached})socket

修改文件能夠直接執行spa

#chmod +x memory_monitor.py

使用crontab 定時執行監控程序rest

#vim vim /etc/crontabserver

添加以下內容(每分鐘執行一次)crontab

*/1 * * * * root /usr/local/memory_monitor.pyip

#service crond reload   //從新載入配置
#service crond restart  //重啓服務
相關文章
相關標籤/搜索