Wednesday, October 1, 2008

pexpectでコマンドの出力を取得する

spawn の logfile_read を StringIO にリダイレクトすればいける。


import StringIO
import pexpect, getpass

prompt = "[#$%]"
process = "httpd"

# login
password = getpass.getpass("password?")
child = pexpect.spawn("ssh -l ento bmw", timeout=60)
child.expect("[Pp]assword:")
child.sendline(password)
child.expect(prompt)

# redirect
old_read = child.logfile_read
buffer = StringIO.StringIO()
child.sendline("stty -echo")
child.expect(prompt)
child.logfile_read = buffer
child.logfile = None

# send command
child.sendline("ps aux | grep %s | grep -v grep" % process)
child.expect(prompt)
res = buffer.getvalue()

# un-redirect
child.sendline("stty echo")
child.logfile_read = old_read
buffer.close()

# do whatever
print res

No comments: