Paramiko没有接收到来自Channel的所有数据



我已经完成了一个脚本来配置几个ASA设备。它完美地完成了这项工作,但我无法从我正在配置的设备中获得全部输出,在某个时候数据会被卡住,没有更多的输出。我想用它来检查问题或错误配置等。我正在从ASA防火墙上的文件中配置大约500个IP、对象、组等。。。我不知道该怎么办,我还没有找到任何清理或擦除Paramiko缓冲区的命令:(

有什么想法吗?这是我的代码:

import paramiko
import re
import time
from tqdm.auto import tqdm
from io import StringIO
device_ip = 'X.X.X.X'
ssh = paramiko.SSHClient()                               # Connection
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname = device_ip, username = username, password = password) 
connection = ssh.invoke_shell()
output_data = StringIO()
connection.send("conf tn")                              # Enter configuration mode
time.sleep(1)                                         
file = open(file_name, 'r')                        # IP list file
lines = file.readlines()
objects = []
ip_subnet = re.compile(r'([0-9]+.[0-9]+.[0-9]+.[0-9]+)/([0-9]+)')
group_name = "GRP-OBJ-EU-Blablabla"
for line in tqdm(lines):
match = ip_subnet.findall(line.strip())
ip = match[0][0]
subnet = match[0][1]                               # Not used, for future use may be...
object_name = "obj-"+ip
object_configuration = "object network "+object_name
object_network = "host "+ip
object_description = "description whatever"
objects.append(object_name)
connection.send(object_configuration+"n")
time.sleep(1)
connection.send(object_network+"n")
time.sleep(1)
connection.send(object_description+"n")
time.sleep(1)
received_data = connection.recv(5000).decode(encoding='utf-8')
if received_data:
output_data.write(received_data)
group_command = "object-group network "+group_name
connection.send(group_command+"n")
time.sleep(1)
for object_host in tqdm(objects):
connection.send("network-object object "+object_host+"n")
time.sleep(1)
received_data = connection.recv(5000).decode(encoding='utf-8')
if received_data:
output_data.write(received_data)
connection.send("end n")
time.sleep(1)
connection.send("wr n")
time.sleep(5)
connection.close()
ssh.close()
file.close()
print(output_data)

我试过下面这样一条线,但也不起作用:

device_output = connection.recv(1000000000000).decode(encoding='utf-8')

我找到了解决方案。。。这太愚蠢了。我没有退出启用模式。。。似乎就是这样!哈哈,我不明白这个关系,但不管怎样,下面的行。。。感谢大家的帮助!

....
connection.send("end n")
time.sleep(1)
connection.send("wr n")
time.sleep(5)
device_output = connection.recv(10000000).decode(encoding='utf-8') 
connection.close()
ssh.close()
file.close()
print(device_output)

我无法直接测试您的代码,但我过去也遇到过类似的问题,并找到了一个实用的解决方案。要一次获取所有数据,您可以打开记事本并在其中打印received_data数据。您也可以在encoding='utf-8'方法之外使用ascii。

示例代码:

received_data = remote_connection.recv(99999999)
result = received_data.decode('ascii').strip("n")
LOGfile = "log.txt" 
log = open(LOGfile, 'a')
log.write(result )
log.close()

我建议Netmiko TTP库解析除Paramiko库之外的所有数据。我在下面给出了一个示例代码链接。我希望这将是有用的。

https://github.com/MertKulac/Nokia--TTP--Template--Command--Set/blob/main/show%20system%20informtaion.py

相关内容

最新更新