chunjihong 发表于 2018-8-4 09:25:59

python pexpect 模块

  Pexpect 模块
  两个主要接口
  pexpect.run('ls -la')
  child = pexpect.spawn('scp foo myname@host.example.com:.')
  child.expect ('Password:')
  ##在这个地方会阻塞,直到出现password或者超时推出
  child.sendline (mypassword)
  管道符的特殊处理
  shell_cmd = 'ls -l | grep LOG > log_list.txt'
  child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
  child.expect(pexpect.EOF) #等待断开
  将log日志重定向到某个文件或者标准输出
  fout = open('filename','w+')
  child.logfile = fout
  child.logfile = sys.stdout
  fout.close()
  如果是仅仅看child返回的信息,而不看你写给child的信息,那么
  child.logfile_read = sys.stdout
  写给child的信息则是
  child.logfile_send = sys.stdout
  try:
  child.sendline('ls -l')
  child.expect(pexpect.EOF)
  #child.prompt()
  print child.before
  except:
  expect不断的读入缓冲区内容等待匹配结束,before代表匹配前的内容,即ls的执行结果,after代表匹配之后的内容
  child.before child.buffer
  


[*]try:
[*]    index = pexpect (['good', 'bad'])
[*]      if index == 0:
[*]            do_something()
[*]      elif index == 1:
[*]            do_something_else()
[*]    except EOF:
[*]      do_some_other_thing()
[*]except TIMEOUT:
[*]    do_something_completely_different()
  

  另外在pexpect中,有一个很好用的接口,就是sendcontrol(),比如说sendcontrol('c'),向目标机器发送一个中断符号,主要用在前面的命令执行时间过长,退出当前命令,并使当前命令对后续命令没有影响,比如说expect('~#', 3),此时发生了超时,后续再发送命令,可能那个超时的命令的结果还将输出,就会对当前的结果有影响,发送sendcontrol('c'),则好的多,再expect()一下就ok啦
  sendeof(),只能用在开头处,另外对于某些平台是发送ctrl+d命令,所以还是不是很好用

参考文献:
http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect1/
http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect2/
页: [1]
查看完整版本: python pexpect 模块