码迷,mamicode.com
首页 > 其他好文 > 详细

用pexpect做简单的输出判断

时间:2016-11-03 11:32:32      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:test   manually   tin   new   class   特定   style   stack   匹配   

之前用pexpect实现过一些简单的交互式操作,比如下边的登录操作:

import pexpect

simulators={‘10.10.10.10‘: ‘root‘}
users={‘testuser‘:‘1101‘}

child = pexpect.spawn(ssh root@ + simulator) i = child.expect([[Pp]assword:,continue connecting (yes/no)?,#]) if i == 0: child.sendline(simulators[simulator]) elif i == 1: child.sendline(yes) child.expect([Pp]assword:) child.sendline(simulators[simulator]) elif i == 2: pass else: print(Login failed)

expect方法可以用于等待子程序中产生特定输出,然后做出特定的响应,如果没有出现想要的字符串就会抛出pexpect.TIMEOUT异常。

假如我想添加一个组或者用户,我想先判断系统中是否已经有组存在,如果有,我就去给这个组添加用户;如果没有,我就创建,然后再添加用户:

child.sendline(cat /etc/group | grep teams:)
child.expect(teams:)
child.expect(#)
if teams: in child.before:
    print(Group teams existed, continue to add users)
else:
    child.sendline(groupadd -g 1100 teams)
    child.expect(#)
    child.sendline(cat /etc/group | grep teams:)
    child.expect(teams:)
    child.expect(#)
    if teams: in child.before:
        print(Group teams added for %s successfully %(simulator))
    else:
        print(Group teams added failed, check on simulator %s manually, go to next simulator %simulator)
        continue


‘‘‘命令在linux中的输出
openstack12:/ # cat /etc/group | grep  teams
teams:!:1100:
openstack12:/ #
‘‘‘

说明:
child.expect(teams:)会匹配命令以及命令说出中的第一个teams,也就是‘cat /etc/group | grep  teams’中的teams,此时的child.before是第一行中的‘ cat /etc/group | grep ’,所以我继续做一个child.expect(#),‘#’匹配的是最后一行的‘#’,此时的child.before包含的内容是,第一行teams后边的回车以及第二行和第三行全部,然后对这个child.before做出判断即可:)
 

 

用pexpect做简单的输出判断

标签:test   manually   tin   new   class   特定   style   stack   匹配   

原文地址:http://www.cnblogs.com/jason7201/p/6025845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!