在现代网络管理中,远程管理设备变得越来越重要。本文将详细介绍如何使用 Python 的 Paramiko 库通过 SSH 连接到交换机,并执行命令以获取其状态。我们将分析代码的每个部分,以及使用该代码的实际场景。
import paramiko import time import loggingparamiko:用于实现 SSH 连接。
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')这里我们设置了日志级别和格式,使得日志输出更易于阅读和分析。
def send_command(remote_conn, command, timeout=2):该函数的主要任务是向远程设备发送命令并接收其输出。它通过循环检查输出是否准备好,并在必要时实现超时机制,以避免长时间等待。
def get_switch_status(ip, username, password):该函数通过提供的 IP 地址、用户名和密码连接到交换机,并发送命令以获取交换机版本信息。连接失败时会记录错误日志。
switches = [("192.168.249.100", "root", "888888")]在这个例子中,我们只连接了一个交换机,但可以轻松扩展为多个设备。
通过 try-except-finally 块处理可能的异常,确保即使发生错误也能正常关闭 SSH 连接并记录日志。
# -*- coding: utf-8 -*- import paramiko import time import logging # 设置日志 logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def send_command(remote_conn, command, timeout=2): """发送命令并接收响应""" remote_conn.send(command + "\n") time.sleep(1) # 等待命令执行 output = "" # 可能需要多次接收来确保获取完整的输出 while True: if remote_conn.recv_ready(): data = remote_conn.recv(65535).decode('utf-8') if not data: break output += data else: # 设置超时以避免无限等待 time.sleep(0.1) timeout -= 0.1 if timeout <= 0: break return output def get_switch_status(ip, username, password): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: client.connect(ip, username=username, password=password, look_for_keys=False, allow_agent=False, timeout=10) remote_conn = client.invoke_shell() time.sleep(1) # 等待会话稳定 # 发送命令并接收输出 output = send_command(remote_conn, "display version") # 打印输出 logging.info(f"====== {ip} ======") logging.info(output) logging.info("===================") except Exception as e: logging.error(f"Failed to connect to {ip}: {str(e)}") finally: client.close() # 堆代码 duidaima.com # 交换机列表 switches = [ ("192.168.249.100", "root", "888888") ] # 批量检查交换机状态 for ip, username, password in switches: get_switch_status(ip, username, password)五、总结