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

时间:2017-03-22 05:23:18

标签: python paramiko

我有一些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进行交互?上面的工作,但它有两个提示(matt @ kali:〜$和来自raw_input的$)的丑陋,如使用交互式shell的测试运行的屏幕截图所示。我想我需要帮助写入shell的stdin?对不起,我的代码不多。提前致谢! enter image description here

2 个答案:

答案 0 :(得分:4)

我导入了一个在Paramiko的GitHub上找到的interactive.py文件。导入后,我只需将代码更改为:

try:
    import interactive
except ImportError:
    from . import interactive

...
...

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

答案 1 :(得分:1)

您可以在调用远程shell后尝试禁用 echo

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

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