当前位置: 首页 > python > 正文

run or spawn in pexpect

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 [email protected]’)
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’})

本文固定链接: http://2hei.net/run-or-spawn-in-pexpect.html | 2hei's site

该日志由 2hei 于2012年08月10日发表在 python 分类下,
原创文章转载请注明: run or spawn in pexpect | 2hei's site
关键字:

报歉!评论已关闭.