Monitor linux memory using python and write it to mongodb

巴扎黑
Release: 2017-09-13 10:02:35
Original
1667 people have browsed it

This article mainly introduces the relevant information about python monitoring Linux memory and writing to mongodb. Friends who need it can refer to

(psutil needs to be installed to obtain server resources and pymongo driver) #pip install psutil


##

#pip install pymongo
#vim memory_monitory.py
Copy after login

The content of the file is as follows


#!/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})
Copy after login

You can modify the file and execute it directly


#chmod +x memory_monitor.py
Copy after login

Use crontab to execute the monitoring program regularly


#vim vim /etc/crontab
Copy after login

Add the following content (execute once every minute)


*/1 * * * * root /usr/local/memory_monitor.py
#service crond reload  //重新载入配置
#service crond restart //重启服务
Copy after login

The above is the detailed content of Monitor linux memory using python and write it to mongodb. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!