采集容器内存并写到excel

 1 # coding=utf-8
 2 import os
 3 import commands
 4 import re
 5 from pyExcelerator import *
 6 
 7 
 8 def execute(cmd):
 9     status, output = commands.getstatusoutput(cmd)
10     if status != 0:
11         raise Exception('status is %s, output is %s' % (status, output))
12     return output
13 
14 
15 def get_docker_name():
16     infos = execute("docker ps |awk '{print $1, $NF}'").split('\n')
17     regex = re.compile('\s+')
18     id_name = {}
19     for info in infos:
20         docker_id, docker_name = regex.split(info)
21         id_name[docker_id] = docker_name
22     return id_name
23 
24 
25 def get_docker_mem():
26     regex = re.compile('\s+')
27     ret = execute('docker stats --no-stream').split('\n')
28     result_name = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'docker_res.xlsx')
29     id_name = get_docker_name()
30     w = Workbook()
31     ws = w.add_sheet('node_1_data')
32     ws.write(0, 0, 'docker_id')
33     ws.write(0, 1, 'docker_name')
34     ws.write(0, 2, 'mem(MB)')
35     index = 1
36     for docker in ret:
37         info = regex.split(docker)
38         docker_id = info[0]
39         mem = info[2]
40         unit = info[3]
41         if unit.startswith('G'):
42             mem = float(mem) * 1024
43         if unit.startswith('K'):
44             mem = float(mem) / 1024
45         try:
46             mem = float(mem)
47         except:
48             pass
49         name = id_name[docker_id]
50         ws.write(index, 0, docker_id)
51         ws.write(index, 1, name)
52         ws.write(index, 2, mem)
53         index += 1
54     w.save(result_name)
55 
56 
57 if __name__ == '__main__':
58     get_docker_mem()

 

posted @ 2018-10-30 15:08  Small_office  阅读(195)  评论(0编辑  收藏  举报