Python脚本实现交换机状态信息获取

Python脚本实现交换机状态信息获取

简述

通过paramiko(python ssh包)ssh连接交换机并执行状态信息命令,将结果通过正则清洗后以邮件形式推送给目标邮箱,过程中涉及包导入、SMTP协议、正则表达式、ssh协议

步骤

安装ssh包并连接交换机

pip install paramiko
github

    def ssh_result(self, cmd):
        t = paramiko.Transport(self.ip, self.port)
        t.connect(username=self.username, password=self.password)
        chan = t.open_session()
        chan.settimeout(timeout=15)
        chan.get_pty()
        chan.invoke_shell()
        time.sleep(5)
        i = 1
        while i < 10:
            chan.send(cmd)
            i += 1
        time.sleep(2)
        result = chan.recv(65535)
        result = str(result, encoding='utf-8')
        return result

清洗数据

返回列表类型

class Regule:
    def __init__(self, string):
        self.string = string

    def PwrStatus(self):
        pattern = re.compile(r'PWR1.*')
        listP = pattern.findall(self.string)[0][:-2].split()  # split以空格分词
        return listP

    def FanStatus(self):
        pattern = re.compile(r'FAN1.*')
        listF = pattern.findall(self.string)[0][:-2].split()
        return listF

    def SwitchStatus(self):
        pattern = re.compile(r'-.*S5730.*')
        listS = pattern.findall(self.string)[1][:-2].split()
        return listS

    def Temperature(self):
        pattern = re.compile(r'NA.*[0-9]')
        # listTem = pattern.findall(string)[2:][2:].split()
        listTem = pattern.findall(self.string)[0][6:].split()
        return listTem

邮件发送

借用QQ邮箱的邮件服务器

class mail:
    def __init__(self):
        value = config.Mailvalue()
        self.mail_user = value.mail_user
        self.mail_host = value.mail_host
        self.mail_pass = value.mail_pass

    def sendmail(self, receivers,context):
        sender = '631643983@qq.com'
        # receivers = ['fralychen@gmail.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

        message = MIMEText(context, 'plain', 'utf-8')
        message['From'] = Header("info_center", 'utf-8')
        message['To'] = Header("administrator", 'utf-8')

        subject = 'Switch_info'
        message['Subject'] = Header(subject, 'utf-8')
        try:
           smtpObj = smtplib.SMTP()
           smtpObj.connect(self.mail_host, 25)    # 25 为 SMTP 端口号
           smtpObj.login(self.mail_user, self.mail_pass)
           smtpObj.sendmail(sender, receivers, message.as_string())
           print("邮件发送成功")
        except smtplib.SMTPException:
           print("Error: 无法发送邮件")

完整代码地址

github:https://github.com/PyMt/Mm

Python脚本实现交换机状态信息获取:[https://www.aliyun.com/activity/daily/cloud?userCode=tblliy78]

上一篇:Docker编排工具RANCHER安装


下一篇:第二章-数据通信基础【网络工程师第五版】