开发学院软件开发Python 探索 Pexpect,第 1 部分:剖析 Pexpect 阅读

探索 Pexpect,第 1 部分:剖析 Pexpect

 2009-08-29 00:00:00 来源:WEB开发网   
核心提示: 该程序与 ftp 做交互,登录到 ftp.openbsd.org ,探索 Pexpect,第 1 部分:剖析 Pexpect(6),当提述输入登录名称和密码时输入默认用户名和密码,当出现 “ftp>” 这一提示符时切换到 pub/OpenBSD 目录并下载 READ

该程序与 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 

上一页  1 2 3 4 5 6 7 8 9  下一页

Tags:探索 Pexpect 部分

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接