zoukankan      html  css  js  c++  java
  • Linux Expect 用法

    Linux Expect 用法

    1. 基本介绍

    expect是建立在tcl基础上的一个自动化交互套件, 在一些需要交互输入指令的场景下, 可通过脚本设置自动进行交互通信. 其交互流程是:

    spawn启动指定进程 -> expect获取指定关键字 -> send想指定进程发送指定指令 -> 执行完成, 退出.

    2. 安装expect工具

    在ubuntu1804 上安装

    sudo apt install expect -y
    

    查看expect的安装路径:

    ~ command -v expect
    /usr/bin/expect
    

    3. expect的常用命令

    命 令 说 明
    spawn 启动新的交互进程, 后面跟命令或者指定程序
    expect 从进程中接收信息, 如果匹配成功, 就执行expect后的动作
    send 向进程发送字符串
    send exp_send 用于发送指定的字符串信息
    exp_continue 在expect中多次匹配就需要用到
    send_user 用来打印输出 相当于shell中的echo
    interact 允许用户交互
    exit 退出expect脚本
    eof expect执行结束, 退出
    set 定义变量
    puts 输出变量
    set timeout 设置超时时间

    4. 脚本使用示例

    这里以ssh远程登录某台服务器的脚本为例进行说明, 假设此脚本名称为remote_login.sh:

    #!/usr/bin/expect
    
    set timeout 30
    spawn ssh -l root 172.16.22.131
    expect "password*"
    send "123456
    "
    interact
    

    interact
    expect执行完成后保持用户的交互状态, 这个时候用户就可以手工操作了.
    如果没有这一句, expect执行完成后就会退出脚本刚刚远程登录过去的终端, 用户也就不能继续操作了.

    直接通过expect执行多条命令

    #!/usr/bin/expect -f
    
    set timeout 10
    # 切换到root用户, 然后执行ls和df命令:
    spawn su - root
    expect "Password*"
    send "123456
    "
    expect "]*"         # 通配符
    send "ls
    "
    expect "#*"         # 通配符的另一种形式
    send "df -Th
    "
    send "exit
    "       # 退出spawn开启的进程
    
    expect eof          # 退出此expect交互程序
    

    通过shell调用expect执行多条命令
    注意首行内容, 这种情况下可通过sh script.sh、bash script.sh 或./script.sh, 都可以执行这类脚本:

    #!/bin/bash
    
    ip="172.16.22.131"
    username="root"
    password="123456"
    
    # 指定执行引擎
    /usr/bin/expect <<EOF
        set time 30
        spawn ssh $username@$ip df -Th
        expect {
            "*yes/no" { send "yes
    "; exp_continue }
            "*password:" { send "$password
    " }
        }
        expect eof
    EOF
    

    https://www.cnblogs.com/saneri/p/10819348.html
    http://xstarcd.github.io/wiki/shell/expect.html
    http://xstarcd.github.io/wiki/shell/expect_handbook.html
    http://xstarcd.github.io/wiki/shell/expect_description.html

  • 相关阅读:
    Linux imooc learning
    有用的生活有关的website
    ps -ef | grep java
    2.3. Configuring sudo Access-RedHat
    How to change java version in Linux
    文档记录工具
    Jmeter 学习imooc
    Linux 用户管理
    Builder模式(设计模式)
    Prototype模式(设计模式)
  • 原文地址:https://www.cnblogs.com/michaelcjl/p/14900537.html
Copyright © 2011-2022 走看看