【grafana+influxdb+python实现监控cpu、内存】grafana和influxdb下载rpm然后yum install *.rpm
influxdb有个web管理界面,不会操作的可以通过这个界面管理数据库,这个web的端口是8083
influxdb:
create database grafana
CREATE USER “grafana” WITH PASSWORD ‘grafana’
grafana:
数据源这部分的配置成功就可以产生图像
数据库地址:http://ip:8086(这个是influxdb的后端端口)
点击panel Title有个Edit可以为这个Panel Title配置一个数据源
数据源可以配置tags和fields,field配置出来显示的就是图形(注意:有些数据要选择合适selectors,不然不显示)
alias是上面线条的名字
python:
安装psutil和influxdb的模块
yum install python-pip -y
yum install gcc python-devel zlib-devel openssl-devel -y#这些安装完了pip install不会报错
pip install psutil
pip install influxdb
python获取信息的脚本
#!/usr/bin/python
# -*- coding: UTF-8 -*-import thread
import time
import socket
import psutil
from influxdb import InfluxDBClientclient=InfluxDBClient('localhost',8086,'root',',','grafana')
#获取本机IP
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 0))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
return IP
ip = get_ip()
#获取cpu信息
def get_cpu(sec):
while True:
time.sleep(sec)
info=psutil.cpu_percent(0)
text=[
{
"measurement":"cpu_info",
"tags":{
"host":ip
},
"fields":{
"percent":info
}
}
]client.write_points(text)
def get_memory(sec):
while True:
time.sleep(sec)
info=psutil.virtual_memory()
text=[
{
"measurement":"memory_info",
"tags":{
"host":ip
},
"fields":{
"mem_percent":info.percent,
"mem_used":info.used,
"mem_free":info.free,
}
}
]
client.write_points(text)def get_disk(sec):
while True:
time.sleep(sec)
info=psutil.disk_usage('/')
text=[
{
"measurement":"disk_info",
"tags":{
"host":ip
},
"fields":{
"disk_used":info.used,
"disk_free":info.free,
"disk_percent":info.percent,
}
}
]
client.write_points(text)def get_network(sec):
while True:
time.sleep(sec)
info = psutil.net_io_counters(pernic=True)['ens192']
text=[
{
"measurement":"network_info",
"tags":{
"host":ip
},
"fields":{
"bytes_sent":info.bytes_sent,
"bytes_recv":info.bytes_recv,
}
}
]
client.write_points(text)
try:
thread.start_new_thread( get_cpu,(1,))
except:
print "ERROR:cpu unable to start thread"
try:
thread.start_new_thread( get_memory, (1,))
except:
print "ERROR:mem_ory unable to start thread"
try:
thread.start_new_thread( get_disk, (1,))
except:
print "ERROR:disk unable to start thread"
try:
thread.start_new_thread( get_network,(1,))
except:
print "ERROR:net unable to start thread"
while 1:
pass