2

我正在使用libssh2 的 python 绑定以编程方式连接到 SSH2 服务器。接收到的输出应转发到远程服务器并在那里显示。

下面的代码可以正常工作,但它以单色显示结果。如何显示颜色或至少获得 VT100 终端控制转义序列,以便我可以用 HTML 标记替换它们?

import socket
import libssh2
import os

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 22))
session = libssh2.Session()
session.startup(sock)
session.userauth_password("test", "test")
channel = session.channel()
channel.execute('ls -al /')

stdout = []
stderr = []
while not channel.eof:
    data = channel.read(1024)
    if data:
        stdout.append(data)

    data = channel.read(1024, libssh2.STDERR)
    if data:
        stderr.append(data)

print (''.join(stdout))
print (''.join(stderr))

如果需要,我可以使用另一个 ssh 库,我只是喜欢 libssh2 绑定的简单性和文档...我愿意接受其他建议。

4

1 回答 1

2

You can look into the paramiko python library. A good blog post going over details, with links to various python info is here. I'm not sure how paramiko would handle the control codes, but in theory, it will at least allow you to see them in its return data.

If you check the section of the docs dealing with invoking a shell, it allows you to set the terminal emulation.

于 2011-10-03T14:46:08.323 回答