如何从远程计算机(ssh + python)获取控制台输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1311697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get console output from a remote computer (ssh + python)
提问by stanleyxu2005
I have googled "python ssh". There is a wonderful module pexpect
, which can access a remote computer using ssh (with password).
我在谷歌上搜索了“python ssh”。有一个很棒的模块pexpect
,它可以使用ssh(带密码)访问远程计算机。
After the remote computer is connected, I can execute other commands. However I cannot get the result in python again.
连接远程计算机后,我可以执行其他命令。但是我无法再次在 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
How to get the result of ps -ef
in my case?
ps -ef
在我的情况下如何获得结果?
采纳答案by JJ Geewax
回答by Pavel Repin
Have you tried an even simpler approach?
您是否尝试过更简单的方法?
>>> from subprocess import Popen, PIPE
>>> stdout, stderr = Popen(['ssh', 'user@remote_computer', 'ps -ef'],
... stdout=PIPE).communicate()
>>> print(stdout)
Granted, this only works because I have ssh-agent
running preloaded with a private key that the remote host knows about.
当然,这只是因为我ssh-agent
预装了远程主机知道的私钥而运行。
回答by avasal
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..
回答by Aaron Digulla
Try to send
尝试发送
p.sendline("ps -ef\n")
IIRC, the text you send is interpreted verbatim, so the other computer is probably waiting for you to complete the command.
IIRC,您发送的文本是逐字解释的,因此另一台计算机可能正在等待您完成命令。