如何从远程计算机上获取控制台输出(SSH +蟒蛇)
题
我一派 “蟒SSH”。有一个精彩模块 pexpect
,该可访问远程计算机使用的ssh(带密码)。
远程计算机连接后,我可以执行其他命令。不过,我不能再拿到结果蟒蛇。
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
的结果在我的情况?
解决方案
您可能还需要调查的paramiko 这是Python的另一个SSH库。
其他提示
您是否尝试过一个更简单的方法呢?
>>> from subprocess import Popen, PIPE
>>> stdout, stderr = Popen(['ssh', 'user@remote_computer', 'ps -ef'],
... stdout=PIPE).communicate()
>>> print(stdout)
当然,这只是工作,因为我已经ssh-agent
运行预装与远程主机知道的私钥。
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..
尝试发送
p.sendline("ps -ef\n")
IIRC,你发送的文本被逐字解释,因此其他计算机可能是等着你去完成该命令。
不隶属于 StackOverflow