how to interact with Paramiko's interactive shell session?

你说的曾经没有我的故事 提交于 2019-11-27 04:40:35

问题


I have some Paramiko code where I use the invoke_shell method to request an interactive ssh shell session on a remote server. Method is outlined here: invoke_shell()

Here's a summary of the pertinent code:

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()

My question is: is there a better way to interact with the shell? The above works, but it's ugly with the two prompts (the matt@kali:~$ and the $ from raw_input), as shown in the screenshot of a test run with the interactive shell. I guess I need help writing to the stdin for the shell? Sorry, I don't code much. Thanks in advance!


回答1:


I imported a file, interactive.py, found on Paramiko's GitHub. After importing it, I just had to change my code to this:

try:
    import interactive
except ImportError:
    from . import interactive

...
...

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



回答2:


You can try disabling echo after invoking the remote shell:

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

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


来源:https://stackoverflow.com/questions/42943385/how-to-interact-with-paramikos-interactive-shell-session

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!