代码改变世界

python实现多主机多线程监控cpu和内存

2021-04-15 17:05  Tanwheey  阅读(674)  评论(0编辑  收藏  举报
# -*- coding: utf-8 -*-


from paramiko import SSHClient, AutoAddPolicy
from threading import Thread
import time, xlwt


class Resource:

def __init__(self, host, name, duration):

# 系统云主机IP、容器名称以及持续时间
self.host = host
self.name = name
self.duration = duration

# 初始化数据写入的文件名
self.suffix = time.strftime("%Y-%m-%d_%H-%M-%S")
self.record_file = r"%s_%s.xls" % (self.name, self.suffix)

self.client = self.ssh_init()

def ssh_init(self):

# 初始化ssh client
username = '***'
pwd = '***'
client = SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())
client.connect(hostname=self.host, port=22, username=username, password=pwd)
return client

def get_pid(self):

# 获取云主机docker的pid
get_pid_cmd = "docker ps |grep %s|grep -v pause|awk '{print $1}'" % self.name
pid = self.cmd_executor(get_pid_cmd)
return pid

def cmd_executor(self, cmd):

# 命令执行器
stdin, stdout, stderr = self.client.exec_command(cmd)
stdout = stdout.read().strip().decode('utf-8')
return stdout

def get_resource(self):

# 获取容器系统资源利用率
self.duration = int(self.duration / 2.5)
pid = self.get_pid()
book, sheet = self.write_excel()

# 获取利用率命令
cmd = "docker stats --no-stream %s|grep -v CPU|awk '{print strftime(\"%%T\"),$2,$8}'" % pid

i = 1
while i <= self.duration:

# 获取容器CPU、内存利用率
data = self.cmd_executor(cmd).split()

# 将利用率写入文件
col = 0
for d in data:
sheet.write(i, col, d)
col += 1
book.save(self.record_file)
i += 1
self.client.close()

def write_excel(self):

# 创建文件,填充sheet名称以及列名
book = xlwt.Workbook()
sheet = book.add_sheet('系统资源利用率')
title = ['TIME', 'CPU利用率', '内存利用率']
row = 0
for t in title:
sheet.write(0, row, t)
row += 1
book.save(self.record_file)
return book, sheet


def run(hosts):
# 多线程启监控任务
thread_list = []
for k, v in hosts.items():
r = Resource(k, v, duration)
thread = Thread(target=r.get_resource, args=())
thread_list.append(thread)

for t in thread_list:
t.start()
for t in thread_list:
t.join()


if __name__ == "__main__":

# 数据收集持续时间
duration = 60

# 设置监控系统信息:云主机IP:容器名称。可设置多对,同时监控多个容器系统资源利用率
sys_info = {'***.***.***.***': '***',
'***.***.***.***': '***'
}

run(sys_info)