python实时监控服务器性能

监控服务器各项性能指标,以下为监控测试流程

1、mysql数据库插入数据

1.1 大家要首先在服务器上安装一个mysql,此项略。。。

1.2 登录mysql新建一个cpu库和cpu表

1.3 连接数据库,代码如下

import pymysql
 class Conn:
     def __init__(self):
         self.connect = pymysql.connect(
             host = "192.168.1.124",
             port = 3306,
             user = "root",
             passwd = "testmysql",
             db = "cpu",
             charset = "utf8"
         )
         self.cur = self.connect.cursor()
 
     def insert(self,data):
         sql = "insert into cpu(cpu_idle,memory_used,memory_free,disk_C_free) values ('%s','%s','%s','%s')"
         self.cur.execute(sql%data)
         # self.connect.close()
         self.connect.commit()

# if __name__ == '__main__':
#     v = Conn()
#     data = (23,45,56,67)
#     print(1)
#     v.insert(data)
#     print(2)

2、收集服务器数据(此测试本机为样本)

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
 import  time
 from TEST.test import Conn
 import psutil
 def Getdata():
     while 1:
         cpu_idle = psutil.cpu_times().idle
         cpu_idle = cpu_idle/1000
 
         memory_used = psutil.virtual_memory().used
         memory_used = memory_used/(1000**3)
 
         memory_free = psutil.virtual_memory().free
         memory_free = memory_free/(1000**3)

         disk_C_free = psutil.disk_usage("C://").free
         disk_C_free = disk_C_free/(1000**3)
 
         date = (round(cpu_idle,2),round(memory_used,2),round(memory_free,2),round(disk_C_free,2))
         v = Conn()
         v.insert(date)
         time.sleep(5)
         print(date)
 Getdata()

3、验证

可以在数据库中查看是否能正常插入数据

你可能感兴趣的:(python)