需要用python脚本模拟登录交换机或者路由器,去执行ping命令,最终返回结果true和false
import paramikodef 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 Falseelse:return Trueexcept Exception as e:print(f"执行过程中出现错误: {e}")return Falsefinally: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 paramikodef 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 Falseif "100% packet loss" in output or "100.00% packet loss" in output:print(f"{target_ip} ping不通。")return Falseelse:print(f"{target_ip} ping通了。")return Trueexcept Exception as e:print(f"建立SSH连接或执行命令时出现错误: {e}")return Falsefinally: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)