如何使用paramiko与远程应用进行交互?

3 投票
1 回答
1696 浏览
提问于 2025-04-17 08:03

我正在尝试使用paramiko与一个命令行应用程序进行交互,但我好像做错了什么。

# that's the echo.py, the script I am connecting to via SSH
import sys, time
while 1:
    x = sys.stdin.readline()
    sys.stdout.write("got-" + x) # x already contains newline



# client.py
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('127.0.0.1', username='user', password='pass')

(stdin, stdout, stderr) = ssh.exec_command(r"python C:\test\echo.py")

stdin.write("xxx\n")
print "got back [%s]" % stdout.read()  # <<< here the code got stuck, getting nothing back

注意:唯一对我有效的情况是让echo.py退出,然后在客户端上使用stdout.readlines(),但显然这不是我想要的。

我需要能够通过标准输入和标准输出发送和接收消息,最好还能支持某种超时功能。

1 个回答

2

我认为问题出在,当你运行 sys.stdout.write 时,它会把内容写入一个叫做STDOUT的缓冲区,但这个缓冲区不会自动清空,除非你手动清空或者关闭它(stdout是一个 文件对象,你可以通过 type(sys.stdout) 来确认)。因为你的循环是无限的,所以这个缓冲区一直没有被清空。

把你的echo.py中的循环改成这样应该就能解决问题:

while 1:
    x = sys.stdin.readline()
    sys.stdout.write("got-" + x) # x already contains newline
    sys.stdout.flush() # flush the buffer

撰写回答