————————————————

Python实现监控网络设备状况并发送邮件

import paramiko
import datetime 
import time
from email.mime.text import MIMEText
import smtplib

#定义发送邮箱函数

def send_email(title):
   title=title
   sender='xxx@qq.com'  #发送者邮箱
   receiver='xxx@qq.com' #接收者邮箱

   mail=MIMEText(title,'plain','utf-8') 
   mail['Subject']=title
   mail['From']=sender    #邮箱部分信息
   mail['To']=receiver
   print(mail.as_string())

   server=smtplib.SMTP()
   server.connect('smtp.qq.com',465)
   server.login('xxx@qq.com','邮箱授权码')
   server.sendmail('xxx@qq.com','xxx@qq.com',mail.as_string()) #邮箱授权发送
   server.quit()
   print('email had been sent!!!')
   return True

 #连接登录网络设备
ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname='192.168.99.10',username='python',password='123456') 
print('Sucessfully conneted to ','192.168.99.10')

 #执行查看计算资源命令
cmd=ssh_client.invoke_shell()
cmd.send('dis cpu-usage\n') 
time.sleep(2)

 #对返回信息解码提取

result=cmd.recv(66666)
result=result.decode('ascii')
items=result.splitlines()  

 #根据与阈值比对判断是否资源利用率过高
for item in items:
    item=item.strip()
    if item.startswith('CPU utilization'):
        
        data=item.split(':')[3]   
       
        percent=data[-2].strip()
       
        if int(percent)==1: 
            warnings='SW1 overloaded!!!'  
            print(warnings)
            send_email(warnings) #如果过高调用发邮件函数
        else:
             print('the SW1 is ok') #否则就显示正常
   
ssh_client.close()
posted @   Tjane'Blogs  阅读(339)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
点击右上角即可分享
微信分享提示