如响应中所述,命令在路由器上成功执行。但答案不完整或不正确。我可能没有阅读正确的答案。我怎样才能读到正确的答案?
import paramiko
import logging
# Enable debug-level logging
logging.basicConfig(level=logging.DEBUG)
hostname = '10.1.1.86'
port = 22
username = '***'
password = '***'
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# Enable logging to a file
paramiko.util.log_to_file("paramiko.log")
ssh_client.connect(hostname=hostname, port=port, username=username, password=password)
shell = ssh_client.invoke_shell()
#shell.send("show version\n")
#output = shell.recv(65535).decode()
commands = [
'enable',
'show version',
'show ip route',
]
for command in commands:
shell.send(command)
output = shell.recv(65535).decode()
print("Command Output:")
print(output)
print("--- COMMAND EXECUTION FINISHED ---")
except paramiko.AuthenticationException:
print("Authentication failed, please verify your credentials.")
except paramiko.SSHException as e:
print("SSH connection failed:", str(e))
except Exception as e:
print("An error occurred:", str(e))
finally:
ssh_client.close()
这是路由器的响应.
Command Output:
Linux CSGW-N1 4.19.91-g1790faa27 #1 SMP Mon Mar 7 15:51:25 UTC 2022 x86_64
Last login: Tue Oct 8 11:15:28 2019 from 10.1.1.88
--- COMMAND EXECUTION FINISHED ---
Command Output:
enable
--- COMMAND EXECUTION FINISHED ---
Command Output:
show version
--- COMMAND EXECUTION FINISHED ---
DEBUG:paramiko.transport:EOF in transport thread
大多数帮助都可用于CISCO设备,但这使用OCNOS。
2条答案
按热度按时间iszxjhcz1#
命令后缺少Enter键。
也就是说,取决于远程系统,
\n
或\r
(甚至\r\n
)。还要注意,您的代码几乎不读取单个命令的输出。这是不可能的
invoke_shell
。您的代码在recv
返回后错误地声明 “命令执行完成”。How to detect if command executed using Paramiko invoke_shell has finished
Execute several commands on Cisco switch via Paramiko - improve performance
invoke_shell
,但我知道你的设备可能不支持正确的exec_command
。svgewumm2#
下面是更新后的代码。