Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to interact with Paramiko's interactive shell session?

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! enter image description here

like image 477
Matt Avatar asked Jan 04 '23 07:01

Matt


2 Answers

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()
like image 102
Matt Avatar answered Jan 06 '23 21:01

Matt


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
    ... ...
like image 21
pynexj Avatar answered Jan 06 '23 22:01

pynexj