Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
运行远程python脚本时使用连续标准输出的Paramiko_Python_Ssh - Fatal编程技术网

运行远程python脚本时使用连续标准输出的Paramiko

运行远程python脚本时使用连续标准输出的Paramiko,python,ssh,Python,Ssh,我正在尝试使用Paramiko运行一个远程Python脚本,并让它将Python打印的任何内容实时转发回客户端(即连续stdout)。我通过以下方式调用我的类来连接到服务器: class SSH: client = None def __init__(self, address, username, password): self.client = client.SSHClient() self.client.set_missing_host_k

我正在尝试使用Paramiko运行一个远程Python脚本,并让它将Python打印的任何内容实时转发回客户端(即连续stdout)。我通过以下方式调用我的类来连接到服务器:

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脚本完成运行时才会填充stdout,而Python将输出的任何内容都只有在脚本完成后才会出现。我希望它在脚本运行时打印。这是我正在使用的测试脚本:

from time import sleep
print("Test.")
sleep(1)
print("Test again.")
sleep(2)
print("Final test.")

有办法解决这个问题吗?还是我做错了什么?提前感谢。

问题已解决。解决办法其实很简单。在运行Python脚本时,我必须从服务器请求一个psuedo终端(
command
=
'python3.6 test.py'
)。在Paramiko中,只需将
get_pty
bool标志设置为
True
。请参见下文(注意
exec_命令中的
get_pty
):

我现在成功地连续实时打印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)

    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.")