[英]Nested SSH with Paramiko exit while loop
I am trying to create a solution using Paramiko that allows to grab first line in output with matching criteria.我正在尝试使用 Paramiko 创建一个解决方案,该解决方案允许使用匹配条件获取输出中的第一行。 I added while loop to wait until output will be available (some times command will be run for more them an hour).我添加了 while 循环以等待输出可用(有时命令会在一小时内运行更多)。 Currently I have:目前我有:
But I have problem with breaking while loop after required output is available.但是我在需要的输出可用后中断 while 循环时遇到问题。
Here is my code.这是我的代码。
import paramiko
from time import sleep
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('jumphost', username='User', password='Passw')
sleep(2)
channel = ssh.invoke_shell()
channel.send('ssh secondHost\n')
sleep(2)
channel.send('Command1\n')
#sleep(2)
buff=''
while channel.recv_ready():
while not buff.endswith('$ '):
resp = channel.recv(9999)
for line in resp.split('\n'):
if line.startswith('Line1'):
print(line)
buff+=line
break
break
print 'buff', buff
ssh.close()
SSHClient.invoke_shell
is for implementing an interactive terminal sessions (like if you are implementing your own SSH terminal client), not for automating a command execution. SSHClient.invoke_shell
用于实现交互式终端会话(就像您正在实现自己的 SSH 终端客户端),而不是用于自动执行命令。 A terminal is a black box with input and output.终端是一个带有输入和输出的黑盒子。 It does not have any API to execute a command and wait for it to complete.它没有任何 API 来执行命令并等待它完成。
Use SSHClient.exec_command
to execute the command and Channel.recv_exit_status
or Channel.exit_status_ready
to wait for it to complete.使用SSHClient.exec_command
执行命令和Channel.recv_exit_status
或Channel.exit_status_ready
等待它完成。
See Wait until task is completed on Remote Machine through Python .请参阅等待任务通过 Python 在远程机器上完成。
As you are executing a command within command ( Command1
within ssh
), you need to send Command1
to the ssh
input.当您在 command 中执行命令( ssh
Command1
)时,您需要将Command1
发送到ssh
输入。
See Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko .请参阅在 Python Paramiko 中的 SSH 服务器上的辅助 shell/命令中执行(子)命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.