VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > python入门教程 >
  • [Python自动化]使用Python Pexpect模块实现自动化交互脚本使用心得

使用Python Pexpect模块实现自动化交互脚本使用心得

参考文档:https://pexpect.readthedocs.io/en/stable/

前言

在最近的工作中,需要使用DockerFile构建镜像。在构建镜像的过程中,有一些执行的命令是需要交互的。例如安装tzdata(apt install tzdata),不过在使用apt安装时,可以直接使用DEBIAN_FRONTEND=noninteractive 前缀来取消交互(至于是禁止交互还是选择交互的默认值,这一点就不太清楚了,TODO)。具体的命令行就是DEBIAN_FRONTEND=noninteractive apt install -y tzdata。在Dockerfile中也可以使用ARG进行统一设置。不过这种前缀设置方法仅仅适用于apt(大概TODO)。还有另一种我一开始就想到的方法,也就是利用类Unix自带的管道(pipe)功能,实现进程间通信,或是将stdin文件描述符重定向为某个文本或是字符串。按道理这是可行的,但是经过我的测试,不知道为啥行不通(等待探索TODO)。

Docker镜像中需要构建一个rust环境,因此需要安装rust。安装rust的方法一般有两种

  • 使用官方推荐的 curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh 命令进行操作,这个命令首先下载脚本,然后将输出的脚本通过管道作为sh进程的输入(pipe,fork,exec,dup)。sh执行脚本的过程中会遇到一些交互,如果这时候将sh的stdin重定向到预定好的文件或是字符串,按道理是可以直接进行自动化交互的,至于为啥没能成功。。咱也不知道 (curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh) < in.in 为啥不能成功捏。
  • 直接使用apt install rust-all。这种方法确实方便,也没有任何交互,但是很多配置因为由于和rust官方可能不一样,很多环境变量没有设置($CARGO_HOME),有些时候还需要自己配置,属实是麻烦得很。

因此我迫切需要一个可以自动化交互的方法。在网上找了很久答案后,发现pexpect可以实现这种自动化交互。因此在这里需要学习pexpect的相关用法。(shell脚本中也有expect相关概念,但是由于shell脚本我用起来感觉有点不太适应,因此就用python了)。

Pexpect简介

Pexpect allows your script to spawn a child application and control it as if a human were typing commands.

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.

一个中心:自动化,各种需要交互,需要输入都可以自动化。

安装

使用pip包管理进行安装

pip install pexpect -i https://pypi.tuna.tsinghua.edu.cn/simple/

在这里用清华源进行加速。

This version of Pexpect requires Python 3.3 or above, or Python 2.7.

以下的流程均在Ubuntu上进行,Windows等系统使用pexpect请参考:https://pexpect.readthedocs.io/en/stable/overview.html#windows

基本操作

在py脚本中,定义想要匹配的提示,然后进行对应的输出。其中匹配可以是字符串完全匹配也可以是正则表达式状态机匹配。

  • 通过pexpect.spawn方法进行脚本的执行
  • 配置expect,从而捕获匹配的字符串
  • 配置对应expect的响应

example

# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
import pexpect
child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('Name .*: ')
child.sendline('anonymous')
child.expect('Password:')
child.sendline('noah@example.com')
child.expect('ftp> ')
child.sendline('lcd /tmp')
child.expect('ftp> ')
child.sendline('cd pub/OpenBSD')
child.expect('ftp> ')
child.sendline('get README')
child.expect('ftp> ')
child.sendline('bye')

注意事项

  1. 惊天巨坑

    由于匹配的字符串可以是正则表达式也可以是普通字符串,因此有些符号是需要转义的。
    比如我下面这个脚本

    import pexpect
    import sys
    child = pexpect.spawn('bash -c \'curl --proto \'=https\' --tlsv1.2 -sSf https://sh.rustup.rs | sh\'')
    child.expect("Continue\? \(y\/N\)")
    print("get 1")
    child.sendline("y")
    child.expect('>')
    print("get 2")
    child.sendline('1')
    child.expect(pexpect.EOF)
    

    如果child.expect("Continue\? \(y\/N\)")这句代码没有使用转义符号,那么就将卡死,这玩意卡了我半小时,属实是折磨了。

    惊天巨坑

  2. 当命令行中使用(>>,<<,|)等符号的时候,直接spwan+命令行是不起作用的,需要额外调用shell进行操作

    child = pexpect.spawn('bash -c \'curl --proto \'=https\' --tlsv1.2 -sSf https://sh.rustup.rs | sh\'')
    

    对应:curl --proto \'=https\' --tlsv1.2 -sSf https://sh.rustup.rs | sh

  3. If you wish to read up to the end of the child’s output without generating an EOF exception then use the expect(pexpect.EOF) method.

    正如文档中所说,不管怎么样,尽量都整一个expect(pexpect.EOF)来把EOF给吞掉

探索

有个问题,expect是顺序执行的还是随机匹配的呢?
可以使用一个没有安装rust的机器进行测试。没有安装rust的机器不会出现Continue\? \(y\/N\)这一提示。查看expect是否会跳过。实测不会跳过,会卡住。

经过文档的查看,使用

index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
    do_something()
elif index == 1:
    do_something_else()
elif index == 2:
    do_some_other_thing()
elif index == 3:
    do_something_completely_different()

index的操作,输入多个可匹配字符串,进行匹配,遇到哪个就执行哪个。

所以对于无序乱序输出的程序,可以使用一个循环,然后任意匹配。可以自定义一个状态机,通过输入的顺序决定执行的流程。

try:
    index = p.expect(['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()

在上面这段代码中,EOF就可能是终止这个状态机,TIMEOUT也有可能会中止状态机。

最终Rust自动化无交互安装脚本如下

import pexpect
child = pexpect.spawn('bash -c \'curl --proto \'=https\' --tlsv1.2 -sSf https://sh.rustup.rs | sh\'')
try:
    while True:
        index = child.expect(['Continue\? \(y\/N\)','>'])
        if index == 0:
            child.sendline('y')
            print("Continue? (y/N) y")
        elif index == 1:
            child.sendline('1')
            print("> 1")
except pexpect.EOF:
    exit
except pexpect.TIMEOUT:
    print("timeout")

如果timeout了,可以适当将timeout变大一些,毕竟下载安装rust还是需要一定时间的

碎碎念

在我寻找答案的过程中,还发现了这么一个答案

curl https://sh.rustup.rs -sSf | sh -s -- -y

使用这个方法可以直接无交互自动化安装,但是这是一个特解。应用程序千千万万,如果每个应用程序都有特殊的无交互方式,那么需要了解所有的相关操作,这不免有点太累了。好处呢,就是这个方案基本上是永久有效,能够跟着应用程序更新。坏处呢也就是这只是一个特解,pexpect这个通解还是需要的。

 


相关教程