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

2024-05-19 00:23:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些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:~$和$from raw_input)的话就很难看了,如交互式shell的测试运行截图所示。我想我需要帮忙写信给stdin要贝壳吗?对不起,我不怎么编码。提前谢谢!enter image description here


Tags: 方法代码truegetrawifchannelpassword
2条回答

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

try:
    import interactive
except ImportError:
    from . import interactive

...
...

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

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

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

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

相关问题 更多 >

    热门问题