1. 程式人生 > >將ansible執行結果進行處理,變成excel

將ansible執行結果進行處理,變成excel

ansible輸出結果,統計起來很麻煩,將結果變為excel,並且按照結果統計彙總,可讀性會強很多

ansible輸出結果:

ansible輸出結果
192.168.250. 250| SUCCESS | rc=0 >>
Selinux check success!This gbase01's selinux is Disabled and selinux config is SELINUX=disabled.
Swappiness check failed! This gbase01's swappiness is 60.
Ulimit check success! This gbase01's ulimit is 655360.
Hugepage check failed! This gbase01's hugepage status is never.
Timezone check success! This gbase01's timezone is +0800.
This gbase01's kernel is 2.6.32-431.el6.x86_64.
This gbase01's openssl is openssl-1.0.1e-30.el6.x86_64.
CPU check success! This gbase01's CPU number is 4.
Mem check success! This gbase01's Mem size is 16GB.
Hostname check success! This gbase01 is right.
192.168.152.222 | UNREACHABLE! => {
    "changed": false, 
    "msg": "mkdir: cannot create directory `/root/.ansible/tmp/ansible-tmp-1536203934.77-45972825051570': No space left on device\n", 
    "unreachable": true
}

使用程式碼將ansible輸出結果進行處理

import pandas as pd
import re
import numpy as np
#開啟檔案
with open(r'F:\python教程\練手程式\a.txt','r') as f:
    text=f.read()
    data = text.strip()
    data=data.replace("|","\n").replace(">>","\n").replace("{","\n").replace("}","\n").replace(r"\r\n","\n")#處理文字中的特殊字元

    data1 =data.split("\n")
    data2 = [i for i in data1 if i != '']


rs = []
#將ip匹配出來,放在列表中
ip = ""
state=['SUCCESS','FAILED','UNREACHABLE']
status=''
result=''
info=''
for d in data2:
    if re.findall('\d+\.\d+\.\d+\.\d', d):#如果在行中找到ip地址
        ip = d
        #print(d)
    elif d.strip() in state:#輸出狀態值
        status=d
    else:
        if len(d.split('!'))==2:
            result=d.split('!')[0]
            info=d.split('!')[1]
            rs.append((ip,status, result,info))#以ip,每行內容,作為元素加到列表中
        else:
            result=d
            info=''
            rs.append((ip,status, result,info))
df = pd.DataFrame(rs, columns=["ip","status","result", "info"])#從列表建立DataFrame,指定data和columns
df = df.groupby(["ip","status"]).apply(lambda x: x["info"])#apply函式 會自動遍歷每一行DataFrame的資料,最後將所有結果組合成一個Series資料結構並返回。
df.to_excel("test2.xlsx")#將結果輸出變成excel

輸出結果手動調整一下,如上,over