How can I send single ssh command to get result string with pexpect?

荒凉一梦 提交于 2019-12-08 11:14:42

问题


I am trying to make my code as efficient and simple as possible. I would like to make my pexpect command into 1 line:

Current command (simplified):

import pexpect
...
session=pexpect.spawn( 'ssh  %s@%s'%(un,ip), timeout)
session.expect(prompt, timeout)
session.sendline('ls')
session.expect(prompt)
print session.before

I would like to do this all in my ssh command but I am returning a pexpect object, is there a way to return just the output string?

import pexpect
    ...
    print str(pexpect.spawn( 'ssh  %s@%s ls'%(un,ip), timeout))

Is there a possible way to change the code above to work?

I have to use pexpect or standard python 2.4, not paramiko :(


回答1:


You want the read() method:

p = pexpect.spawn('ssh  %s@%s ls'%(un,ip), timeout)
print(p.read())


来源:https://stackoverflow.com/questions/19915264/how-can-i-send-single-ssh-command-to-get-result-string-with-pexpect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!