如何从远程计算机获取控制台输出(ssh + python)
我在网上搜索了“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 个回答
3
当然可以!请看下面的内容:
在编程中,有时候我们需要让程序做一些重复的事情。为了实现这个目的,我们可以使用“循环”。循环就像是一个指令,让程序不断地执行同样的操作,直到满足某个条件为止。
比如说,如果你想让程序数数,从1数到10,你可以用循环来实现。程序会从1开始,然后依次加1,直到它达到10为止。这样,你就不需要手动写出每一个数字,而是通过循环让程序自动完成。
循环有几种不同的类型,比如“for循环”和“while循环”。“for循环”通常用于知道要执行多少次的情况,而“while循环”则是在不知道具体次数的情况下使用,直到某个条件不再满足为止。
总之,循环是编程中一个非常重要的工具,它可以帮助我们简化代码,让程序更高效地完成任务。
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..
12
你有没有试过一种更简单的方法呢?
>>> from subprocess import Popen, PIPE
>>> stdout, stderr = Popen(['ssh', 'user@remote_computer', 'ps -ef'],
... stdout=PIPE).communicate()
>>> print(stdout)
当然,这种方法之所以有效,是因为我已经启动了 ssh-agent
,并且里面预先加载了一个远程主机知道的私钥。
1
你可能还想了解一下 paramiko,这是另一个用于Python的SSH库。