用于提取Cisco交换机信息以准备网络迁移的Python SSH脚本
我有一个Cisco Nexus5548 IP地址和FQDN的列表。请您使用Python脚本帮助SSH到每个,并提取以下内容,以便将其导入Excel列格式: IP名称端口号端口描述端口类型VLAN光学类型介质类型 172.x.x hqcr1-swx-x E1/x实际端口描述(接入或中继)300-3052276,…1g sr、10g sr、1g glct(铜缆或双轴) 这就是我到目前为止所做的:用于提取Cisco交换机信息以准备网络迁移的Python SSH脚本,python,ssh,Python,Ssh,我有一个Cisco Nexus5548 IP地址和FQDN的列表。请您使用Python脚本帮助SSH到每个,并提取以下内容,以便将其导入Excel列格式: IP名称端口号端口描述端口类型VLAN光学类型介质类型 172.x.x hqcr1-swx-x E1/x实际端口描述(接入或中继)300-3052276,…1g sr、10g sr、1g glct(铜缆或双轴) 这就是我到目前为止所做的: import paramiko, getpass, time devices = {'device1'
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()
非常感谢。您尝试过在
SSHClient
上使用exec\u命令吗?不确定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)
这对以下情况很有用:
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\u设备
的输出直接放入dict
中,如果您愿意,它是一个迭代器,可以返回适当的对您能描述一下您到目前为止尝试了什么吗?开关列表来自哪里?子流程
模块适合调用ssh
,或者如果您想要/需要更多控制,可以使用paramiko
。IP和FQDN列表来自Cisco Prime Infrastructure。这就是我所拥有的,我想在某种字典中跟踪每个交换机的所有期望参数。IP列表来自Cisco Prime Infrastructure。我正在使用paramiko,目前有一个脚本,但注释字段太小,无法覆盖整个脚本。是否可以使用类似SNMP的内容?如果您想使用pythonyes,有一个pysnmp
库,python会允许您这样做。我不会为你写代码的!如果你想学习,网上有很多教程…