自学内容网 自学内容网

Zabbix利用python脚本监控专线状态

需要用python脚本模拟登录交换机或者路由器,去执行ping命令,最终返回结果true和false

import paramiko

def ssh_ping(host, port, username, password, target_ip):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    try:
        client.connect(hostname=host, port=port, username=username, password=password)
        
        command = f'ping -c 4 {target_ip}'
        stdin, stdout, stderr = client.exec_command(command)
        output = stdout.read().decode()

        print("STDOUT:", output)
        
        # 检查ping命令的输出是否包含“100% packet loss”
        if "100% packet loss" in output or "100.00% packet loss" in output:
            return False
        else:
            return True
    except Exception as e:
        print(f"执行过程中出现错误: {e}")
        return False
    finally:
        client.close()

host = "192.168.8.254"
port = 22
username = "admin"
password = "HuaWei"
target_ip = "192.99.1.1"

result = ssh_ping(host, port, username, password, target_ip)
print(result)

这个脚本会返回true和false


下面这个脚本会返回多个值

import paramiko

def ssh_ping_one(host, port, username, password, target_ip):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        client.connect(hostname=host, port=port, username=username, password=password)
        print(f"正在ping {target_ip}...")
        command = f'N'
        command = f'ping -c 4 {target_ip}'
        stdin, stdout, stderr = client.exec_command(command)
        output = stdout.read().decode()
        error = stderr.read().decode()
        if error:
            print(f"执行ping {target_ip} 时出错: {error}")
            return False
        if "100% packet loss" in output or "100.00% packet loss" in output:
            print(f"{target_ip} ping不通。")
            return False
        else:
            print(f"{target_ip} ping通了。")
            return True
    except Exception as e:
        print(f"建立SSH连接或执行命令时出现错误: {e}")
        return False
    finally:
        client.close()

def ssh_ping_all(host, port, username, password, target_ips):
    unreachable_ips = [ip for ip in target_ips if not ssh_ping_one(host, port, username, password, ip)]
    if unreachable_ips:
        print("以下IP地址ping不通:")
        for ip in unreachable_ips:
            print(ip)
    else:
        print("所有IP地址都可以ping通。")

# 使用示例
host = "192.168.8.254"
port = 22
username = "admin"
password = "HuaWei"
target_ips = ["10.65.16.122", "192.99.1.2", "192.168.1.140"]

ssh_ping_all(host, port, username, password, target_ips)


原文地址:https://blog.csdn.net/u011197085/article/details/136150639

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!