如何与Paramiko的交互式Shell会话进行交互?

6

我有一些 Paramiko 代码,其中使用 invoke_shell 方法请求在远程服务器上进行交互式 SSH shell 会话。该方法概述如下:invoke_shell()

以下是相关代码的摘要:

sshClient = paramiko.SSHClient()
sshClient.connect('127.0.0.1', username='matt', password='password')
channel = sshClient.get_transport().open_session()
channel.get_pty()
channel.invoke_shell()

while True:
    command = raw_input('$ ')
    if command == 'exit':
        break

    channel.send(command + "\n")

    while True:
        if channel.recv_ready():
            output = channel.recv(1024)
            print output
        else:
            time.sleep(0.5)
            if not(channel.recv_ready()):
                break

sshClient.close()

我的问题是:是否有更好的与shell交互的方法?上述方法可行,但在交互式shell中会出现两个提示符(matt@kali:~$和来自raw_input的$),如测试运行的屏幕截图所示,这很丑陋。我想知道如何写入shell的stdin?抱歉,我不怎么编程。提前感谢! enter image description here

感谢@whjm。没有其他目的,只是为了好玩写一个SSH客户端。我更喜欢使用Paramiko。 - Matt
2个回答

7

我导入了一个名为interactive.py的文件,该文件可以在 Paramiko 的 GitHub 上找到。导入后,我只需要将我的代码更改为以下内容:

try:
    import interactive
except ImportError:
    from . import interactive

...
...

channel.invoke_shell()
interactive.interactive_shell(channel)
sshClient.close()

1
在Windows上:TypeError: write() argument must be str, not bytes。应该更改interactive.py中的第87行为:sys.stdout.write(data.decode("utf8", "ignore")) - WhyWhat
我在使用zsh自动补全时遇到了控制字符和换行引起的意外行为问题。我已经修改了演示以支持此功能,链接在这里:https://gist.github.com/mvanderlee/c6fb0bf7611565e43813bfa503f2afc1 - M.Vanderlee

3

在调用远程 shell 后,您可以尝试禁用 回显(echo)

channel.invoke_shell()
channel.send("stty -echo\n")

while True:
    command = raw_input() # no need for `$ ' anymore
    ... ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接