2009-08-21 83 views
7

我已经使用了“python ssh”。有一个很好的模块pexpect,它可以使用ssh(带密码)访问远程计算机。如何从远程计算机获取控制台输出(ssh + python)

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

p = pexpect.spawn("ssh [email protected]_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的结果?

+0

hmm? p.before应该给出输出 – 2009-08-21 12:56:09

+0

python返回“None” – stanleyxu2005 2009-08-21 13:27:40

回答

1

您可能还想调查paramiko这是另一个用于Python的SSH库。

+0

在尝试了很多不同的解决方案后,我认为这个库是目前的最佳实践。我甚至不需要配置非密码登录来通过LAN在外部节点上运行任何脚本。 – stanleyxu2005 2014-03-07 03:20:04

1

尝试发送

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

IIRC,你发送的文本逐字解释,因此其他计算机可能是等着你去完成该命令。

8

您是否尝试过更简单的方法?

>>> from subprocess import Popen, PIPE 
>>> stdout, stderr = Popen(['ssh', '[email protected]_computer', 'ps -ef'], 
...      stdout=PIPE).communicate() 
>>> print(stdout) 

当然,这只是工作,因为我有ssh-agent运行预装与远程主机知道的私钥。

+1

感谢您的提示。有没有简单的方法来配置许多客户端的私钥?我必须每周检查20台机器的日志文件。这是编写python脚本的动机。 – stanleyxu2005 2009-08-22 20:49:27

+0

那么......你只需要在每台机器上附加你的公钥到〜/ .ssh/authorized_keys。也许,如果你的工作机器没有太大变化,这将是一次性练习。 顺便说一句,这是一个非常整洁的文章关于设置SSH代理和更多: http://unixwiz.net/techtips/ssh-agent-forwarding.html – 2009-08-22 21:18:39

3
child = pexpect.spawn("ssh [email protected]_computer ps -ef") 
print "connecting..." 
i = child.expect(['[email protected]_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.. 
相关问题