python实时监控服务器性能

coding

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

1、mysql数据库插入数据

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

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

1.3  连接数据库,代码如下

 1import pymysql

2class Conn:

3def__init__(self):

4 self.connect = pymysql.connect(

5 host = "192.168.1.124",

6 port = 3306,

7 user = "root",

8 passwd = "testmysql",

9 db = "cpu",

10 charset = "utf8"

11 )

12 self.cur = self.connect.cursor()

13

14def insert(self,data):

15 sql = "insert into cpu(cpu_idle,memory_used,memory_free,disk_C_free) values ('%s','%s','%s','%s')"

16 self.cur.execute(sql%data)

17# self.connect.close()

18 self.connect.commit()

19

20# if __name__ == '__main__':

21# v = Conn()

22# data = (23,45,56,67)

23# print(1)

24# v.insert(data)

25# print(2)

连接mysql代码

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

 1import  time

2from TEST.test import Conn

3import psutil

4def Getdata():

5while 1:

6 cpu_idle = psutil.cpu_times().idle

7 cpu_idle = cpu_idle/1000

8

9 memory_used = psutil.virtual_memory().used

10 memory_used = memory_used/(1000**3)

11

12 memory_free = psutil.virtual_memory().free

13 memory_free = memory_free/(1000**3)

14

15 disk_C_free = psutil.disk_usage("C://").free

16 disk_C_free = disk_C_free/(1000**3)

17

18 date = (round(cpu_idle,2),round(memory_used,2),round(memory_free,2),round(disk_C_free,2))

19 v = Conn()

20 v.insert(date)

21 time.sleep(5)

22print(date)

23 Getdata()

收集服务器数据

3、验证

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

以上是 python实时监控服务器性能 的全部内容, 来源链接: utcz.com/z/509392.html

回到顶部