探索 Pexpect,第 1 部分:剖析 Pexpect
2009-08-29 00:00:00 来源:WEB开发网该程序与 ftp 做交互,登录到 ftp.openbsd.org ,当提述输入登录名称和密码时输入默认用户名和密码,当出现 “ftp>” 这一提示符时切换到 pub/OpenBSD 目录并下载 README 这一文件。
以下实例是上述方法的综合应用,用来建立一个到远程服务器的 telnet 连接,并返回保存该连接的 pexpect 对象。
清单 19. 登录函数:
import re,sys,os
from pexpect import *
def telnet_login(server,user, passwd,shell_prompt= “#|->”):
"""
@summary: This logs the user into the given server.
It uses the 'shell_prompt' to try to find the prompt right after login.
When it finds the prompt it immediately tries to reset the prompt to '#UNIQUEPROMPT#'
more easily matched.
@return: If Login successfully ,It will return a pexpect object
@raise exception: RuntimeError will be raised when the cmd telnet failed or the user
and passwd do not match
@attention:1. shell_prompt should not include '$',on some server, after sendline
(passwd) the pexpect object will read a '$'.
2.sometimes the server's output before its shell prompt will contain '#' or
'->' So the caller should kindly assign the shell prompt
"""
if not server or not user \
or not passwd or not shell_prompt:
raise RuntimeError, "You entered empty parameter for telnet_login "
child = pexpect.spawn('telnet %s' % server)
child.logfile_read = sys.stdout
index = child.expect (['(?i)login:', '(?i)username', '(?i)Unknown host'])
if index == 2:
raise RuntimeError, 'unknown machine_name' + server
child.sendline (user)
child.expect ('(?i)password:')
child.logfile_read = None # To turn off log
child.sendline (passwd)
while True:
index = child.expect([pexpect.TIMEOUT,shell_prompt])
child.logfile_read = sys.stdout
if index == 0:
if re.search('an invalid login', child.before):
raise RuntimeError, 'You entered an invalid login name or password.'
elif index == 1:
break
child.logfile_read = sys.stdout # To tun on log again
child.sendline(“PS1=#UNIQUEPROMPT#”)
#This is very crucial to wait for PS1 has been modified successfully
#child.expect(“#UNIQUEPROMPT#”)
child.expect("%s.+%s" % (“#UNIQUEPROMPT#”, “#UNIQUEPROMPT#”))
return child
- ››探索 ConcurrentHashMap 高并发性的实现机制
- ››探索Asp.net mvc 的文件上传(由浅入深)
- ››探索博客发展之路:给博客一个明确的定位
- ››部分 WM6.5 手机有望升级到 Windows Phone 7
- ››探索 Eclipse JDT 中的重构功能
- ››探索 Eclipse 的 Ajax Toolkit Framework
- ››探索 Eclipse V3.1 的新特性:更高的可用性、更广...
- ››探索 Flex 和 CSS 的强大功能
- ››探索 Pexpect,第 1 部分:剖析 Pexpect
- ››探索 Pexpect,第 2 部分:Pexpect 的实例分析
- ››部分英特尔芯片不支持Windows 7“XP模式”
- ››探索 AIX 6:在 AIX 6 上配置 iSCSI Target
更多精彩
赞助商链接