代码之家  ›  专栏  ›  技术社区  ›  stanleyxu2005

如何从远程计算机(ssh+python)获取控制台输出

  •  7
  • stanleyxu2005  · 技术社区  · 15 年前

    我在谷歌上搜索了“python ssh”。有一个很棒的模块 pexpect 可以使用ssh(带密码)访问远程计算机。

    远程计算机连接后,我可以执行其他命令。但是,我不能在python中再次得到结果。

    p = pexpect.spawn("ssh user@remote_computer")
    print "connecting..."
    p.waitnoecho()
    p.sendline(my_password)
    print "connected"
    p.sendline("ps -ef")
    p.expect(pexpect.EOF) # this will take very long time
    print p.before
    

    如何获得 ps -ef 依我看?

    4 回复  |  直到 11 年前
        1
  •  1
  •   JJ Geewax    15 年前

    你可能还想调查 paramiko 这是另一个针对python的ssh库。

        2
  •  8
  •   Pavel Repin    15 年前

    你尝试过更简单的方法吗?

    >>> from subprocess import Popen, PIPE
    >>> stdout, stderr = Popen(['ssh', 'user@remote_computer', 'ps -ef'],
    ...                        stdout=PIPE).communicate()
    >>> print(stdout)
    

    当然,这只是因为我 ssh-agent 使用远程主机知道的私钥运行预加载。

        3
  •  3
  •   avasal    13 年前
    child = pexpect.spawn("ssh user@remote_computer ps -ef")
    print "connecting..."
    i = child.expect(['user@remote_computer\'s password:'])
    child.sendline(user_password)
    i = child.expect([' .*']) #or use i = child.expect([pexpect.EOF])
    if i == 0:
        print child.after # uncomment when using [' .*'] pattern
        #print child.before # uncomment when using EOF pattern
    else:
        print "Unable to capture output"
    
    
    Hope this help..
    
        4
  •  1
  •   Aaron Digulla    15 年前

    尝试发送

    p.sendline("ps -ef\n")
    

    IIRC,您发送的文本是逐字解释的,所以另一台计算机可能正在等待您完成该命令。