简述

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

步骤

安装ssh包并连接交换机

pip install paramiko
github

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

清洗数据

返回列表类型

  1. class Regule:
  2. def __init__(self, string):
  3. self.string = string
  4. def PwrStatus(self):
  5. pattern = re.compile(r'PWR1.*')
  6. listP = pattern.findall(self.string)[0][:-2].split() # split以空格分词
  7. return listP
  8. def FanStatus(self):
  9. pattern = re.compile(r'FAN1.*')
  10. listF = pattern.findall(self.string)[0][:-2].split()
  11. return listF
  12. def SwitchStatus(self):
  13. pattern = re.compile(r'-.*S5730.*')
  14. listS = pattern.findall(self.string)[1][:-2].split()
  15. return listS
  16. def Temperature(self):
  17. pattern = re.compile(r'NA.*[0-9]')
  18. # listTem = pattern.findall(string)[2:][2:].split()
  19. listTem = pattern.findall(self.string)[0][6:].split()
  20. return listTem

邮件发送

借用QQ邮箱的邮件服务器

  1. class mail:
  2. def __init__(self):
  3. value = config.Mailvalue()
  4. self.mail_user = value.mail_user
  5. self.mail_host = value.mail_host
  6. self.mail_pass = value.mail_pass
  7. def sendmail(self, receivers,context):
  8. sender = '631643983@qq.com'
  9. # receivers = ['fralychen@gmail.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
  10. message = MIMEText(context, 'plain', 'utf-8')
  11. message['From'] = Header("info_center", 'utf-8')
  12. message['To'] = Header("administrator", 'utf-8')
  13. subject = 'Switch_info'
  14. message['Subject'] = Header(subject, 'utf-8')
  15. try:
  16. smtpObj = smtplib.SMTP()
  17. smtpObj.connect(self.mail_host, 25) # 25 为 SMTP 端口号
  18. smtpObj.login(self.mail_user, self.mail_pass)
  19. smtpObj.sendmail(sender, receivers, message.as_string())
  20. print("邮件发送成功")
  21. except smtplib.SMTPException:
  22. print("Error: 无法发送邮件")

完整代码地址

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

108X108.jpg