【问题标题】:code hangs when running interactive shell using paramiko使用 paramiko 运行交互式 shell 时代码挂起
【发布时间】:2016-10-26 01:24:59
【问题描述】:

我已经编写了下面的代码以交互方式在远程服务器中运行 3 个命令

但是当我检查第 3 个命令从未执行并且卡在这里的代码是我的代码时

def execute():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('ipaddress', username='user', password='pw')

    chan = ssh.invoke_shell()  # start the shell before sending commands

    chan.send('cd /path to folder/test')
    chan.send('\n')
    time.sleep(3)
    chan.send("ls -l")
    chan.send('\n')
    buff = ''
    while not buff.endswith("test >"):
        resp = chan.recv(9999)
        # code stuck here after 'path to folder/test >' comes in shell prompt
        buff += resp
        print resp

    print "test"
    chan.send("ls -lh")
    chan.send('\n')
    time.sleep(5)
    buff = ''
    while not buff.endswith("test >"):
        resp = chan.recv(9999)
        buff += resp
        print resp

if __name__ == "__main__":
    execute()

当我运行时,我得到了 ls -l 的输出,但 ls -lh 从未执行过我的代码,卡在第一个 while 循环中。请任何人帮助解决我的问题

【问题讨论】:

  • 据我所知,您实际上并不需要启动外壳,如果您直接使用外壳就会知道一些安全问题。您在客户端类中尝试过exec_command 吗?
  • 我没试过我认为在 shell 中执行交互式命令 invoke_shell 是正确的 api
  • 不,不是。您应该尝试 exec_command,因为它会将所有 3 个频道返回给您。
  • 我使用了 invoke_shell 因为我需要从特定文件夹一个接一个地执行命令序列,这就是为什么如果我使用 execute_command 则通道在执行第一个命令后关闭
  • exec_command 也可以。你应该阅读文档。

标签: python paramiko


【解决方案1】:

代码有以下2个错误:

  • channel.recv的调用被阻塞,你应该首先检查通道是否有任何数据要读取或没有使用channel.recv_ready()

  • 也不要使用buff.endswith("test >") 作为条件。 file_name 可能并不总是在 buff 中的最后一个。

将while块更改为following,它将按照您想要的方式运行

    while "test >" not in buff:
        if chan.recv_ready():
            resp = chan.recv(9999)    
            # code won't stuck here
            buff+=resp
            print resp

【讨论】:

    最近更新 更多