当我运行以下代码时,我得到了扭曲的结果:
######## 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 ignore
结果应位于“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
这里出了什么问题?我认为命令还没有准备好,所以我内置了睡眠计时器。然而,此后缓冲区似乎未空或未准备好。
因为您不会等待命令完成后再发送另一个命令。实际上,使用
SSHClient.invoke_shell
(SSH“shell”通道)无法做到这一点。 “shell”通道不适用于命令自动化。
SSHClient.exec_command
(SSH“exec”通道)。如果您的某些命令实际上不是顶级 shell 命令,而是顶级命令的子命令,另请参阅:
在 Python Paramiko 中的 SSH 服务器上的辅助 shell/命令中执行(子)命令