朋友用ansible导出了一个文件,文件中包含上千台机器的磁盘信息,他想要知道哪些机器最需要赶紧扩磁盘。思路是,按剩余磁盘空间百分数,从小到大对文本内容重新排序。下面是具体实现。
源文件ip.txt的格式是这样的:
10.1.2.1 | success | rc= >>
/dev/sda1 .1T 28G 982G % /export 10.1.2.1 | success | rc= >>
/dev/sda2 .6T 15G .5T % /export
下面是.py文件。运行这个python脚本后,可以生成ip_sorted.txt文件,是经过重排的文件,磁盘剩余空间越小,其机器信息会排在越前面。
#!/bin/bash
# -*- coding:utf-8 -*- import os
import collections with open('ip.txt','r') as f:
file_dic_ip = {}
file_dic_info = {}
i = 0
for line in f:
count = int(os.popen("grep -c '^/dev' ip.txt").read())
while i < count:
lines_ip = os.popen("grep -v '^/dev' ip.txt | grep -v '^$' ").read().split('\n')
lines_info = os.popen("grep -n '^/dev' ip.txt | awk -F ':' '{print $2}'").read().split('\n')
file_dic_ip[lines_info[i]] = lines_ip[i]
lines_info_percent = os.popen("grep -n '^/dev' ip.txt | awk -F ' ' '{print $5}'").read().split('%\n')
file_dic_info[lines_info_percent[i]] = lines_info[i]
i += 1 od = collections.OrderedDict(sorted(file_dic_info.items()))
with open('ip_sorted.txt','w') as f:
for items in od.items():
f.write(file_dic_ip[items[1]] + '\n' + items[1] + '\n\n')
流程图不太对,将就看看文字讲解吧