通过PYTHON实现主机磁盘的使用情况,使用influxdb+grafana来可是互展示
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import os
import re
import json
import time
from influxdb import InfluxDBClient
def getInfluxdb():
client=InfluxDBClient(host=‘192.168.15.104‘, port=8086, username=‘admin‘, password=‘root123‘, database=‘mydb‘)
return client
def check_hd_use():
cmd_get_hd_use=‘/bin/df‘
try:
fp=os.popen(cmd_get_hd_use)
except:
ErrorInfo=r‘get_hd_use_error‘
# print ErrorInfo
return ErrorInfo
r_search=re.compile(r‘^/dev/.+\s+(?P<Used>\d+)%\s+(?P<Mount>.+)‘)
hd_use={}
for line in fp:
match=re.search(r_search,line)
#print ‘......‘,match,
if match is not None:
hd_use[match.groupdict()[‘Mount‘]]=match.groupdict()[‘Used‘]
fp.close()
#print hd_use
return hd_use
if __name__==‘__main__‘:
disk=check_hd_use()
disk_key=disk.keys()
disk_key1=disk_key[0]
disk_key2=disk_key[1]
disk_value=disk.values()
disk_value1=disk_value[0]
disk_value2=disk_value[1]
current=int(time.time())
json_body=[{
"measurement":"disk_use",
"tags":{"host":"disk_check",
"time":current
},
"fields":{
disk_key1:int(disk_value1),
disk_key2:int(disk_value2)
#‘a‘:disk
}
}]
getInfluxdb().write_points(json_body)
print json_body
总结:
需要注意,目前这个代码获取的是/,/home的2个磁盘的情况,若有跟多直接添加disk_key,disk_value值