pythonsh脚本提取Cisco交换机信息,为网络迁移做准备

2024-03-29 10:32:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

IP名称端口号端口描述端口类型VLAN光纤类型介质类型 172.x.x.x hqcr1-swx-x E1/x实际端口描述(接入或中继)300-3052276,…1g sr、10g sr、1g glct(铜缆或双轴)

到目前为止,我得到的是:

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()

非常感谢。在


Tags: 端口ipparamiko类型newforoutputtime
1条回答
网友
1楼 · 发布于 2024-03-29 10:32:44

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

我会做一些类似的事情:

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)

这对以下方面很有用:

^{pr2}$

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

相关问题 更多 >