python - 运行远程 python 脚本时具有连续标准输出的 Paramiko
问题描述
我正在尝试使用 Paramiko 运行远程 Python 脚本,并让它将 Python 打印的任何内容实时转发回客户端(即连续标准输出)。我通过以下方式调用我的类来连接到我的服务器:
class SSH:
client = None
def __init__(self, address, username, password):
self.client = client.SSHClient()
self.client.set_missing_host_key_policy(client.AutoAddPolicy())
self.client.connect(address, username=username, password=password, look_for_keys=False)
然后我通过我的send_command
函数向服务器发送命令:
def send_command(self, command):
if(self.client):
stdin, stdout, stderr = self.client.exec_command(command)
for i in range(5): # just print 5 bytes
print(stdout.channel.recv(1))
time.sleep(0.1)
else:
print("Connection not opened.")
通常,这适用于任何在循环时填充标准输出缓冲区的连续/循环命令。我的问题是,由于某种原因,stdout 仅在 Python 脚本完成运行时才被填充,而 Python 输出的任何内容只有在脚本完成后才会出现。我希望它在脚本运行时打印。这是我正在使用的测试脚本:
from time import sleep
print("Test.")
sleep(1)
print("Test again.")
sleep(2)
print("Final test.")
有没有办法解决这个问题或者我做错了什么?提前致谢。
解决方案
问题解决了。解决方案实际上非常简单。command
运行 Python 脚本 ( = 'python3.6 test.py'
)时,我必须从服务器请求一个伪终端。这在 Paramiko 中只需将get_pty
bool 标志设置为True
. 见下文(注意get_pty
in exec_command
):
class SSH:
client = None
def __init__(self, address, username, password):
self.client = client.SSHClient()
self.client.set_missing_host_key_policy(client.AutoAddPolicy())
self.client.connect(address, username=username, password=password, look_for_keys=False)
def send_command(self, command):
if(self.client):
stdin, stdout, stderr = self.client.exec_command(command, get_pty=True)
while not stdout.channel.exit_status_ready():
OUT = stdout.channel.recv(1024)
print(OUT)
else:
print("Connection not opened.")
我现在成功地实时连续打印 Python 脚本的输出。
推荐阅读
- php - 正则表达式匹配从右到左
- javascript - 在 postgres 中动态更新字段而不使用 || 操作员
- c++ - 复制二维结构数组c ++
- microsoft-graph-api - 将应用程序连接到 OneDrive for Business 中国
- php - Laravel 数组和 JSON 转换
- javascript - 如何从 javascript 中的 base 64 字符串获取图像文件大小?
- mysql - mysql数据库复合键问题
- autofac - Autofac在ResolvedParameter valueAccessor中获取服务类型
- r - 试图从我的数据 R 中删除特殊字符和非英语单词
- solr - 在 Dotdeb 上安装 php-solr 包 PECL 扩展