繁体   English   中英

用于提取 Cisco 交换机信息以准备网络迁移的 Python SSH 脚本

[英]Python SSH script to extract Cisco switches information in preparation for network migration

我有一份 Cisco Nexus5548 IP 地址和 FQDN 的列表。 能否请您使用 Python 脚本通过 SSH 连接到每个脚本并提取以下内容,以便将其导入 Excel 列格式:

IP 名称 端口号 端口描述 端口类型 Vlans 光纤类型 介质类型 172.xxx hqcr1-swx-x E1/x 实际端口描述(接入或中继) 300-305,2276,... 1g-sr, 10g-sr, 1g- glct(铜纤维,或 twinax)

这是我到目前为止:

import paramiko, getpass, time

devices = {'device1': {'ip': 'xx.xx.xx.xx'}} 
           'device2': {'ip': 'xx.xx.xx.xx'}}
commands = ['show version\n', 'show run\n']

username = input('Username: ')
password = getpass.getpass('Password: ')

max_buffer = 65535

def clear_buffer(connection):
    if connection.recv_ready():
        return connection.recv(max_buffer)

# Starts the loop for devices
for device in devices.keys(): 
    outputFileName = device + '_output.txt'
    connection = paramiko.SSHClient()
    connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    connection.connect(devices[device]['ip'], username=username, password=password, look_for_keys=False, allow_agent=False)
    new_connection = connection.invoke_shell()
    output = clear_buffer(new_connection)
    time.sleep(2)
    new_connection.send("terminal length 0\n")
    output = clear_buffer(new_connection)
    with open(outputFileName, 'wb') as f:
        for command in commands:
            new_connection.send(command)
            time.sleep(2)
            output = new_connection.recv(max_buffer)
            print(output)
            f.write(output)

new_connection.close()

非常感谢。

您是否尝试过在exec_command上使用SSHClient 不确定 Cisco 盒子如何打开/关闭多个通道,但似乎它可能有助于将每个命令的输出分开。

我会做这样的事情:

from paramiko import SSHClient, AutoAddPolicy

def process_devices(devices, connect_args, commands):
    with SSHClient() as client:
        client.set_missing_host_key_policy(AutoAddPolicy())

        for device in devices:
            client.connect(device, **connect_args)

            cmdout = []
            for cmd in commands:
                stdin, stdout, stderr = client.exec_command(cmd, timeout=10)
                cmdout.append((stdout.read(), stderr.read()))

            yield (device, cmdout)

这对以下内容很有用:

from getpass import getpass

devices = [
    '127.0.0.1',
]

connect_args = dict(
    username='smason',
    password=getpass("Password: "),
)

commands = [
    "echo hello world",
    "date",
]

for dev, cmdout in process_devices(devices, connect_args, commands):
    print(f"{dev}: {cmdout}")

如果需要,您当然可以将process_devices的输出直接放入dict ,它是一个返回适当对的迭代器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM