Python巡检关于Excel表格操作

import psutil
import time
import xlwt
import platform
from subprocess import Popen, PIPE


def getoutput(command):
    print("开始执行命令:%s" %command)
    comm = Popen(command, stdout=PIPE, stdin=PIPE, stderr=PIPE, shell=True)
    out, err = comm.communicate()
    if err:
        print("执行命令失败:%s"% command)
    else:
        return out


def get_os_info():
    sys = platform.system()
    ip = getoutput("ifconfig eth0 |awk -F '[ :]+' 'NR==2{print $4}'")
    ip = str(ip, encoding='utf-8').strip()
    return sys, ip


def get_time():
    now_time = time.strftime('%Y-%m-%d %H:%M:%S')
    return now_time


def get_CPU():
    cpu = "CPU:%s" % int(psutil.cpu_percent(interval=0)) + "%"
    return cpu


def get_memory():
    data = psutil.virtual_memory() #获取内存完整信息
    memory = "Memory:%s" % (int((data.percent))) + "%"
    return memory


def get_dick():
    dick_1 = []
    dick1 = getoutput("df -h |grep '%'| awk -F ' ' 'NR>2{print $5, $6}'")
    #print(type(dick1))
    str1 = str(dick1, encoding='utf-8')
    dick1 = str1.strip().split('\n')
    #['Use% Mounted', '/ ', '0% /dev/shm', '9% /boot', '100% /mnt', '']
    return dick1


def get_process():
    com = getoutput('ps -ef |grep ssh |wc -l' )
    return com

def dict():
    info = []
    info_content = []
    # get_time = get_time()
    get_info = get_os_info()
    # interval=1
    os_sys = list(get_info)[0]
    os_ip = list(get_info)[1]
    info.append(os_sys)
    info_content.append(os_ip)

    CUP = get_CPU()
    # print(CUP.split(':')[0])
    info.append(CUP.split(':')[0])
    info_content.append(CUP.split(':')[1])

    MEM = get_memory()
    info.append(MEM.split(':')[0])
    info_content.append(MEM.split(':')[1])
    # print(info_content)
    # print(info)

    Dick = get_dick()
    dick = int(len(Dick))
    for i in range(dick):
        info.append(Dick[i].split(' ')[1])
        info_content.append(Dick[i].split(' ')[0])

    dict = {}
    for i in range(len(info)):
        dict[info[i]] = info_content[i]
    return  dict, info, info_content
# 百分数转为int
def compare_int(string):
    if "%" in string:
        newint = int(string.strip("%")) / 100
        return newint
    else:
        print("你输入的不是百分比!")

if __name__ == "__main__":

    dict_1 = dict()  #所有信息
    time = get_time()
    workbook = xlwt.Workbook(encoding='utf-8')
    worksheet = workbook.add_sheet('每日巡检', cell_overwrite_ok=True)
    # 设置字体
    #style = xlwt.XFStyle()  # 初始化样式
    font = xlwt.Font()  # 为样式创建字体
    font.name = '宋体'
    font.bold = True  # 黑体
    # 对其方式
    al = xlwt.Alignment()
    al.horz = 0x02  # 设置水平居中
    al.vert = 0x01  # 设置垂直居中
    # 添加边框
    borders = xlwt.Borders()  # Create Borders
    borders.left = xlwt.Borders.THIN
    borders.right = xlwt.Borders.THIN
    borders.top = xlwt.Borders.THIN
    borders.bottom = xlwt.Borders.THIN
    #背景色红色
    pattern = xlwt.Pattern()
    pattern.pattern = xlwt.Pattern.SOLID_PATTERN
    pattern.pattern_fore_colour = 10 #红色
    #背景色2
    pattern2 = xlwt.Pattern()
    pattern2.pattern = xlwt.Pattern.SOLID_PATTERN
    pattern2.pattern_fore_colour = 23  # 浅色
    # 初始化样式
    style1 = xlwt.XFStyle() #字体
    style1.font = font
    style1.alignment = al

    style2 = xlwt.XFStyle()
    style2.font = font
    style2.alignment = al
    style2.borders = borders
    style2.pattern = pattern2

    style3 = xlwt.XFStyle()
    style3.font = font
    style3.alignment = al
    style3.borders = borders

    #红色
    style4 = xlwt.XFStyle()
    style4.alignment = al
    style4.borders = borders
    style4.pattern = pattern

    result = ['序号', "ip地址", '操作系统版本', 'CPU使用率(<80%)', '内存使用率(<80*)', '/boot使用率(<80%)', '/mnt使用率(<80%)','ssh进程(存活)']
    worksheet.write(0, 0, '%s' %time, style1) # 带样式的写入
    result_1 = len(result)
    #print(result)
    for i in range(result_1):
        #print(result[i])
        # 设置首列的宽度
        fir_col = worksheet.col(i)
        fir_col.width = 300 * 20

        # 设置行高
        tall_style = xlwt.easyxf('font:height 320;')  # 36pt,类型小初的字号
        first_row = worksheet.row(i)
        first_row.set_style(tall_style)
        worksheet.write(1, i, result[i], style2)
        if i == 0:
            worksheet.write(2, i, 1, style3)
        else:
            pass
    res = get_os_info()
    #print(list(res)[0])
    worksheet.write(2, 1, list(res)[1], style3)
    worksheet.write(2, 2, list(res)[0], style3)
    res_1 = list(dict_1)[0]
    cpu_int = res_1.get('CPU')
    cpu_int2 = '80%'
    if compare_int(cpu_int) >= compare_int(cpu_int2):
        worksheet.write(2, 3, res_1.get('CPU'), style4)
    else:
        worksheet.write(2, 3, res_1.get('CPU'), style3)
    mem_int = res_1.get('Memory')
    mem_int2 = '80%'
    if compare_int(mem_int) >= compare_int(mem_int2):
        worksheet.write(2, 4, res_1.get('Memory'), style4)
    else:
        worksheet.write(2, 4, res_1.get('Memory'), style3)
    boot = res_1.get('/boot')
    boot_int2 = '80%'
    if compare_int(boot) >= compare_int(boot_int2):
        worksheet.write(2, 5, res_1.get('/boot'), style4)
    else:
        worksheet.write(2, 5, res_1.get('/boot'), style3)
    mnt = res_1.get('/mnt')
    mnt_int2 = '80%'
    if compare_int(mnt) >= compare_int(mnt_int2):
        worksheet.write(2, 6, res_1.get('/mnt'), style4)
    else:
        worksheet.write(2, 6, res_1.get('/mnt'), style3)

    process = int(get_process())
    if process > 2:
        worksheet.write(2, 7, '存活', style3)
    else:
        worksheet.write(2, 7, '无进程', style4)
    workbook.save('formatting.xls') # 保存文件

 

转载于:https://www.cnblogs.com/QQmini/p/11443821.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python可以使用第三方库openpyxl来操作Excel表格,下面是一些常见的操作: 1.读取Excel表格 ```python from openpyxl import load_workbook # 打开Excel文件 wb = load_workbook(filename='example.xlsx') # 获取所有工作表名 sheet_names = wb.sheetnames # 选择第一个工作表 ws = wb[sheet_names[0]] # 获取工作表的行数和列数 rows = ws.max_row cols = ws.max_column # 读取单元格内容 cell = ws.cell(row=1, column=1).value ``` 2.写入Excel表格 ```python from openpyxl import Workbook # 创建新的Excel文件 wb = Workbook() # 创建新的工作表 ws = wb.active # 写入单元格内容 ws.cell(row=1, column=1, value='Hello') # 保存Excel文件 wb.save('example.xlsx') ``` 3.修改Excel表格 ```python from openpyxl import load_workbook # 打开Excel文件 wb = load_workbook(filename='example.xlsx') # 选择第一个工作表 ws = wb.active # 修改单元格内容 ws.cell(row=1, column=1, value='World') # 保存Excel文件 wb.save('example.xlsx') ``` 4.复制Excel表格 ```python from openpyxl import load_workbook from openpyxl.utils import range_boundaries from openpyxl.utils.cell import get_column_letter # 打开Excel文件 wb = load_workbook(filename='example.xlsx') # 选择第一个工作表 ws = wb.active # 复制工作表 new_ws = wb.copy_worksheet(ws) # 修改工作表名称 new_ws.title = 'Copy' # 修改单元格内容 new_ws.cell(row=1, column=1, value='Copy') # 修改单元格样式 for row in new_ws.iter_rows(min_row=1, max_row=1): for cell in row: cell.font = cell.font.copy(bold=True) # 保存Excel文件 wb.save('example.xlsx') ``` 5.删除Excel表格 ```python from openpyxl import load_workbook # 打开Excel文件 wb = load_workbook(filename='example.xlsx') # 选择要删除的工作表 ws = wb['Sheet1'] # 删除工作表 wb.remove(ws) # 保存Excel文件 wb.save('example.xlsx') ``` 以上是一些常见的操作,openpyxl还支持更高级的操作,如合并单元格、设置单元格样式等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值