我有一个程序,该程序从本地计算机运行,并通过SSH(paramiko程序包)连接到Linux计算机。 我使用以下函数发送命令并获取exit_code以确保已完成。
由于某种原因,有时返回退出代码,而有时则进入无穷循环。 有谁知道为什么会这样以及如何使其稳定?
def check_on_command(self, stdin, stdout, stderr):
if stdout is None:
raise Exception("Tried to check command before it was ready")
if not stdout.channel.exit_status_ready():
return None
else:
return stdout.channel.recv_exit_status()
def run_command(self, command):
(stdin, stdout, stderr) = self.client.exec_command(command)
logger.info(f"Excute command: {command}")
while self.check_on_command(stdin, stdout, stderr) is None:
time.sleep(5)
logger.info(f'Finish running, exit code: {stdout.channel.recv_exit_status()}')
答案 0 :(得分:1)
如果您使用的是Python版本> = 3.6,我建议您使用异步库,该库提供等待功能以优化运行时间和更易管理的简单代码。
例如,您可以使用python随附的asyncssh库,并按要求执行工作。通常,应该像这样替换使用睡眠来等待任务执行的异步代码。
import asyncio, asyncssh, sys
async def run_client():
async with asyncssh.connect('localhost') as conn:
result = await conn.run('ls abc')
if result.exit_status == 0:
print(result.stdout, end='')
else:
print(result.stderr, end='', file=sys.stderr)
print('Program exited with status %d' % result.exit_status,
file=sys.stderr)
try:
asyncio.get_event_loop().run_until_complete(run_client())
except (OSError, asyncssh.Error) as exc:
sys.exit('SSH connection failed: ' + str(exc))
您可以在此处找到更多文档:asyncssh