shell 使用OCNOS时未从路由器获得所需的响应,在Python中

9gm1akwq  于 2023-10-23  发布在  Shell
关注(0)|答案(2)|浏览(98)

如响应中所述,命令在路由器上成功执行。但答案不完整或不正确。我可能没有阅读正确的答案。我怎样才能读到正确的答案?

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。

iszxjhcz

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

svgewumm

svgewumm2#

下面是更新后的代码。

for command in commands:
    # Send command and wait for the shell prompt before sending the next command
    shell.send(command + '\n')

    while not shell.recv_ready():
        time.sleep(3)

    response = shell.recv(65535).decode()
    responses.append(response)

相关问题