python3巡检华为交换机并把结果通过邮件发送到自己邮箱

18年写的脚本,当时是练习用的,现在翻出来看看,好多东西都忘记了,贴出来给有需要的人使用,代码也是在论坛东一块西一块凑出来的。代码很乱,没有注释,将就看吧
环境是:centos7.4 +python3+python各种库,这个自己自行安装,其实windows环境也可以,只是centos看起来比较装13 。。。。。
因为交换机比较多,我删除只剩下一个了,需要多个的,自己按照着添加就行

import datetime
import smtplib
import re
import xlwt
from xlwt import *
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
today=datetime.date.today().strftime('%Y%m%d')
from netmiko import ConnectHandler
import os
import subprocess

def test1():
    global device1
    global device2
    global device3
    global temperature
    global memory
    global time1
    global cpu1
    global trapbuffer
    global huaweizhu
    global output2

    fnull = open(os.devnull, 'w')
    return1 = subprocess.call('ping -c 2 192.168.0.254', shell=True, stdout=fnull, stderr=fnull)
    if return1:
        print('ping不通')

    else:
        print('ping通的')
        huawei = {
            'device_type': 'huawei',
            'host': '192.168.0.254',
            'username': '这里填写自己的交换机账号',
            'password': '这里填写自己的交换机密码'
        }
        net_connect = ConnectHandler(**huawei)
        huaweizhu = net_connect.find_prompt()
        print(huaweizhu)
        output = net_connect.send_command('display device')#看自己的交换机命令支持不支持,不支持改成支持自己交换机的
        output1 = net_connect.send_command('display temperature all')#同上
        output2 = net_connect.send_command('display alarm urgent')
        output3 = net_connect.send_command('display memory-usage')
        output4 = net_connect.send_command('display version')
        output5 = net_connect.send_command('display cpu-usage')
        output6 = net_connect.send_command('display trapbuffer')

        f = open('/python/txt/254/%ssw-zy-zjh.txt' % today, 'w')#这个路径必须真实存在的,不然会报错
        f.write(output)
        f.write(output1)
        f.write(output3)
        f.write(output4)
        f.write(output5)
        f.write(output6)

        f.close()

        file = open(r'/python/txt/254/%ssw-zy-zjh.txt' % today, 'r+')#这个路径必须真实存在的,不然会报错

#打开上面创建的zy-zjh.txt,看看自己配置排列的情况,然后改下面的数据对应自己的位置
        listlist = file.readlines()  
        i = 1
        for line in listlist: 

            if 'S5720-36C-EI          Present' in line:    #我自己的交换机是s5720-36,然后想要内容位置是63置70字符位置,提取该段内容赋给device1,下面的也一样
                device1 = line[63:70].rstrip()  
                print(device1)  
            if 'PWR1 POWER' in line:
                device2 = line[63:70].rstrip()
                print(device2)
            if 'FAN1 FAN' in line:
                device3 = line[63:70].rstrip()
                print(device3)
            if 'Slot  Card  Sensor Status' in line:
                temperature = listlist[i + 2][19:36].rstrip()  
                print(temperature)
            if 'Memory Using Percentage' in line:
                memory = line[28:31].rstrip()  
                print(memory)
            if 'Routing Switch uptime' in line:
                time1 = line[47:86].rstrip()  
                print(time1)
            if 'CPU Usage            :' in line:  
                cpu1 = line[22:27].rstrip()
                print(cpu1)
            if 'Current messages :' in line:
                trapbuffer = line[18:25].rstrip()  
                print(trapbuffer)

            i += 1
        file.close()

    fnull.close()
if __name__ == '__main__':
    test1()




#下面部分是创建excel表格,并把上面收集到的数据填入表格内


workbook = xlwt.Workbook()#创建表格

style = XFStyle()#初始化样式,此样式包含了单元格背景颜色和单元格边框两个属性。
pattern = Pattern()
pattern.pattern = Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = Style.colour_map['blue'] #设置单元格背景色为蓝色
style.pattern = pattern
borders = xlwt.Borders()#设置表格的边框,1是默认实线黑色。
borders.left = 1
borders.right = 1
borders.top = 1
borders.bottom = 1
style.borders = borders


style1 = XFStyle()#只有边框
borders = xlwt.Borders()
borders.left = 1
#borders.left = xlwt.Borders.THIN
borders.right = 1
borders.top = 1
borders.bottom = 1
style1.borders = borders
a3 = xlwt.Alignment()
a3.horz = 0x01      # 设置水平居中
a3.vert = 0x01      # 设置垂直居中
style1.alignment = a3

style3 = XFStyle()#初始化样式,带边框和表格内容居中。
borders = xlwt.Borders()
borders.left = 1
#borders.left = xlwt.Borders.THIN
borders.right = 1
borders.top = 1
borders.bottom = 1
style3.borders = borders
al = xlwt.Alignment()
al.horz = 0x02      # 设置水平居中
al.vert = 0x01      # 设置垂直居中
style3.alignment = al

style4 = XFStyle()#初始化样式,带边框和表格内容居中。
borders = xlwt.Borders()
borders.left = 1
#borders.left = xlwt.Borders.THIN
borders.right = 1
borders.top = 1
borders.bottom = 1
style4.borders = borders
a2 = xlwt.Alignment()
a2.horz = 0x01      # 设置水平居中
a2.vert = 0x00      # 设置垂直居中
a2.wrap = 1
style4.alignment = a2



zlg = workbook.add_sheet('总部交换机巡检报告',cell_overwrite_ok=True)#创建表格的某一分页
zlg1 = workbook.add_sheet('分公司交换机巡检报告',cell_overwrite_ok=True)#创建表格第二页
first_col=zlg.col(0)#设置0、1、2、3列的列宽
sec_col=zlg.col(1)
thr_col=zlg.col(2)
for_col=zlg.col(3)
first_col.width=150*50
sec_col.width=100*50
thr_col.width=120*50
for_col.width=480*50

first_col=zlg1.col(0)#设置0、1、2、3列的列宽
sec_col=zlg1.col(1)
thr_col=zlg1.col(2)
for_col=zlg1.col(3)
first_col.width=150*50
sec_col.width=100*50
thr_col.width=120*50
for_col.width=480*50




zlg.write(0,0,'设备名称',style3)
zlg.write(0,1,'管理地址',style3)
zlg.write(0,2,'检查项',style3)
zlg.write(0,3,'检查结果',style3)
zlg.write(1,2,'内存使用率',style1)
zlg.write(2,2,'cpu使用率',style1)
zlg.write(3,2,'交换机状态',style1)
zlg.write(4,2,'电源状态',style1)
zlg.write(5,2,'风扇状态',style1)
zlg.write(6,2,'交换机温度',style1)
zlg.write(7,2,'运行时间',style1)
zlg.write(8,2,'日志条目',style1)


#下面内容是判断能不能连接上交换机的,如果不能连接上则提示网络不通,检查链路或设备,写入excel表格内
def test22():

    fnull = open(os.devnull, 'w')
    return1 = subprocess.call('ping -c 2 192.168.0.254', shell=True, stdout=fnull, stderr=fnull)
    if return1:
        print('ping不通')
        zlg.write_merge(1, 15, 0, 0, '网络不通,检查链路或设备', style3)  
        zlg.write_merge(1, 15, 1, 1, '192.168.0.254', style3)
        zlg.write_merge(9, 15, 2, 2, '警告信息', style1)
        zlg.write_merge(9, 15, 3, 3, '网络不通,检查链路或设备', style4)
        zlg.write(1, 3, '网络不通,检查链路或设备', style1)
    else:
        print('ping通的')
        zlg.write_merge(1, 15, 0, 0, huaweizhu, style3)  
        zlg.write_merge(1, 15, 1, 1, '192.168.0.254', style3)
        zlg.write_merge(9, 15, 2, 2, '警告信息', style1)
        zlg.write_merge(9, 15, 3, 3, output2, style4)

        zlg.write(1, 3, memory, style1)
        zlg.write(2, 3, cpu1, style1)
        zlg.write(3, 3, device1, style1)
        zlg.write(4, 3, device2, style1)
        zlg.write(5, 3, device3, style1)
        zlg.write(6, 3, temperature, style1)
        zlg.write(7, 3, time1, style1)
        zlg.write(8, 3, trapbuffer, style1)

    fnull.close()
if __name__ == '__main__':
    test22()
workbook.save('/python/excel/%ssw-zy-zjh.xls'%today)#这个路径必须真实存在的,不然会报错   
print ('创建excel文件完成!')

#下面内容是创建邮件并发送到邮箱

smtpserver = 'smtp.qq.com'
smtpport = 465
sender = 'xxxxxxx@qq.com'#这里填自己的邮箱账号
sender_pwd = 'xxxxxxxxxxxx'#自己邮箱的授权码,不会的自己百度自己邮箱授权码
rece = 'xxxxxxxxx@qq.com'#这里填自己的邮箱账号
mail_username = 'xxxxxxxx@qq.com'#这里填自己的邮箱账号

# 创建一个带附件的邮件实例
message = MIMEMultipart()
# 编辑邮件的内容

# 往邮件容器中添加内容。这是邮件的主体
mail_title = '交换机巡检结果'
mail_inside = MIMEText(r'巡检的结果,见附件', 'plain', 'utf-8')
# 邮件的其他属性
message['From'] = sender
message['To'] = rece
message['Subject'] = Header(mail_title, 'utf-8')
message.attach(mail_inside)

# 构造附件txt附件1
attr1 = MIMEText(open(r'/python/excel/%ssw-zy-zjh.xls'%today, 'rb').read(), 'base64', 'utf-8')#这个路径必须真实存在的,不然会报错
attr1["content_Type"] = 'application/octet-stream'
attr1["Content-Disposition"] = "attachment; filename='%ssw-zy-zjh.xls'"%today
message.attach(attr1)

smtpobj = smtplib.SMTP_SSL(smtpserver, port=smtpport)
smtpobj.login(sender, sender_pwd)
smtpobj.sendmail(sender, rece, message.as_string())
print('邮件发送成功')
smtpobj.quit()


我保存成test1.py
脚本写好了,然后是每天自己运行一遍
在centos里面输入crontab -e,然后里面填入以下内容

0 8 * * * /usr/local/bin/python3 /python/test1.py

意思是每天的8点运行一遍/usr/local/bin/python3 /python/这个路径下面的test1.py
成果大概是下面这样的
在这里插入图片描述
有不懂的可以给我留言,第一次写博客,不知道有没有哪里没写对的,多多包涵

  • 7
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值