问题描述
我写了一个 Python 脚本.我为给定的 IP 创建了一个 Python 脚本,将通过 Paramiko 连接到服务器以执行另一个 Python 脚本.
I dry on a Python script. I create a python script for a given IP will connect via Paramiko to a server to execute another Python script.
这是一些代码:
self._client = paramiko.SSHClient()
self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self._client.connect(self._ip, username=self._server['username'], password=self._server['password'])
channel = self._client.get_transport().open_session()
channel.exec_command('python3 /tmp/scrap.py /tmp/' + self._ip + '.txt 0 1')
脚本scrap.py"每 X 秒在远程机器的控制台中返回一行,但是我无法恢复上面脚本中的这些行(在 exec_command (. ..) 退出时).
The script "scrap.py" returns every X seconds a line in the console of the remote machine, but I can not recover as and when these lines in the script above (at the exit of exec_command (. ..)).
这可能吗,如果有,你知道怎么做吗?
Is this possible, and if so have you any idea how?
提前致谢.
推荐答案
这应该可以解决问题:
stdin, stdout, stderr = channel.exec_command("python myScript.py")
stdin.close()
for line in iter(lambda: stdout.readline(2048), ""):
print(line, end="")
如 read([size]) 文档中所述,如果您不指定大小,它会一直读取到 EOF,这使得脚本在从 read() 返回并打印任何输出之前等待命令结束.
As specified in the read([size]) documentation, if you don't specify a size, it reads until EOF, that makes the script wait until the command ends before returning from read() and printing any output.
这篇关于Paramiko, exec_command 连续获取输出流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!