存档

2012年8月 的存档

run or spawn in pexpect

2012年8月10日 评论已被关闭

Pexpect is a Python module for spawning child applications and controlling
them automatically. Pexpect can be used for automating interactive applications
such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
scripts for duplicating software package installations on different servers. It
can be used for automated software testing. Pexpect is in the spirit of Don
Libes’ Expect, but Pexpect is pure Python. Other Expect-like modules for Python
require TCL and Expect or require C extensions to be compiled. Pexpect does not
use C, Expect, or TCL extensions. It should work on any platform that supports
the standard Python pty module. The Pexpect interface focuses on ease of use so
that simple tasks are easy.

There are two main interfaces to Pexpect — the function, run() and the class,
spawn. You can call the run() function to execute a command and return the
output. This is a handy replacement for os.system().
I was failed when using spawn() to get output of remote ssh command,

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# filename: pexpect_2hei_spawn.py

import pexpect
if __name__ == ‘__main__’:

child = pexpect.spawn(‘ssh -oStrictHostKeyChecking=no myname@host.example.com’)
child.expect (‘Password:’)
child.sendline (mypassword)
child.expect (‘$’)
child.sendline (‘hostname’)
print child.before
print child.after

Function run() worked for me,that’s great!

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# filename: pexpect_2hei.py

from pexpect import *

if __name__ == ‘__main__’:

User = ‘myuser’
Host = ‘www.2hei.net’
Pwd = ‘mypwd’
print run (“ssh -oStrictHostKeyChecking=no ” +User+”@”+Host+” ‘hostname;uptime'”, events={‘(?i)password’:Pwd+’\n’})

分类: python 标签: