侧边栏壁纸
  • 累计撰写 19 篇文章
  • 累计收到 4 条评论

网络链路监控脚本

eson
2024-08-06 / 0 评论 / 80 阅读 / 正在检测是否收录...

问题

各类网管系统大多只能对核心路由器的设备情况进行实时监控,但是路由出去的链路如果出现问题可能网管系统不能发现,尤其是设置了主备双路由的情况下,如果备路由的链路出现问题,就更难发现了。

思路

既然局域网内无法直接对互联地址进行判断,那么进入路由器后就可以通过ping命令来进行判断了,前提是要打开路由器的SSH,这样更方便。

脚本

# -*- coding: utf-8 -*-
import paramiko
import time
import re

while True:
    count = 3
    size = 50
    
    # 主线路开始测试
    
    # 创建SSH对象
    ssh = paramiko.SSHClient()

    # 允许连接不在know_hosts文件中的主机
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    # 连接服务器
    ssh.connect(hostname='xx.xx.xx.xx', port=22, username='admin', password='xxxxxxxxxxx')

    # 执行命令
    stdin, stdout, stderr = ssh.exec_command(f"ping -c {count} -s {size} -a xx.xx.xx.xx xx.xx.xx.xx")

    # 获取命令结果
    result = stdout.read()

    # 打印结果
    r = result.decode()
    
    tmp = re.findall("time=(.*?) ms", r, re.S)
    
    nowtime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    
    if len(tmp) < 1:
        print(f"[x] warning: --------R1 can't connected----------, time: {nowtime}")
    else:
        print(f"[*] R1 connected, {tmp[0]} ms, time: {nowtime}")
        
    ssh.close()
    time.sleep(180)

        
    # 备用线路开始测试
    
    # 创建SSH对象
    ssh = paramiko.SSHClient()

    # 允许连接不在know_hosts文件中的主机
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # 连接服务器
    ssh.connect(hostname='xx.xx.xx.xx', port=22, username='admin', password='xxxxxxxxxxxxx')

    # 执行命令
    stdin, stdout, stderr = ssh.exec_command(f"ping -c {count} -s {size} -a xx.xx.xx.xx xx.xx.xx.xx")

    # 获取命令结果
    result = stdout.read()

    # 打印结果
    r = result.decode()
    
    tmp = re.findall("time=(.*?) ms", r, re.S)
    
    nowtime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    
    if len(tmp) < 1:
        print(f"[x] warning: --------R2 can't connected----------, time: {nowtime}")
    else:
        print(f"[*] R2 connected, {tmp[0]} ms, time: {nowtime}")
        
    ssh.close()
    time.sleep(180)

结尾

脚本暂时没加入报警功能,因为我使用的电脑上面没装蜂鸣器,打算这两天安装好蜂鸣器之后再把报警功能也加进去。

脚本还是有一些偷懒的地方,因为平时感觉不需要监控那么细致,所以就没写的非常严谨,比如网络延时部分,只取了返回第一条的延时,并没有取平均值以及丢包值。

同时因为开辟的内存空间极小,所以也没写回收机制。

先用用看吧,如果没必要,这些就不完善了,有需要的朋友自行完善。

3

评论 (0)

取消