【问题标题】:Python Paramiko doesn't show commands output in the right orderPython Paramiko 未按正确顺序显示命令输出
【发布时间】:2020-02-12 08:58:51
【问题描述】:

当我运行以下代码时,我得到一个扭曲的结果:

######## Make connection

remote_conn_pre=paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_conn_pre.connect(ip, port=22, username=username,
                        password=password,
                        look_for_keys=False, allow_agent=False)

remote_conn = remote_conn_pre.invoke_shell()

######## commands read from JSON file (commands)

for command in commands["normal"]:
    print("-- command: " + command)
    remote_conn.send(command + "\n")
    while not remote_conn.recv_ready():
        time.sleep(0.300)
    output = remote_conn.recv(buffersize)
    print(output.decode())

输出结果:

-- command: sh run | section dhcp
sh run | sec dhcp

-- command: sh run | i ip route
ip dhcp bootp ignore 
sh run | i ip route
ip route 0.0.0.0 0.0.0 vlan 1

如您所见,ip dhcp bootp ignoreresult 应该在 “DHCP 部分” 下,而不是在 “路由部分” 下。

正确的结果应该是:

-- command: sh run | section dhcp
sh run | sec dhcp
ip dhcp bootp ignore 

-- command: sh run | i ip route
sh run | i ip route
ip route 0.0.0.0 0.0.0 vlan 1

这里出了什么问题?我想到命令没有准备好,所以我内置了睡眠定时器。然而,在此之后缓冲区似乎不是空的或准备好的。

【问题讨论】:

    标签: python ssh paramiko


    【解决方案1】:

    因为在发送另一个命令之前,您不会等待命令完成。实际上,SSHClient.invoke_shell(SSH“shell”通道)无法做到这一点。 “shell”通道不适用于命令自动化。

    改为使用SSHClient.exec_command(SSH“执行”通道)。
    Wait until task is completed on Remote Machine through Python


    如果您的某些 命令 实际上不是顶级 shell 命令,而是顶级命令的子命令,另请参阅:
    Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko

    【讨论】:

      猜你喜欢
      • 2023-01-17
      • 2017-02-09
      • 1970-01-01
      • 2015-04-17
      • 1970-01-01
      • 2012-06-29
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多