zoukankan      html  css  js  c++  java
  • expect工具实现脚本的自动交互

    1 安装expect工具

    expect是建立在tcl基础上的一个自动化交互套件, 在一些需要交互输入指令的场景下, 可通过脚本设置自动进行交互通信. 其交互流程是:
    spawn启动指定进程 -> expect获取指定关键字 -> send想指定进程发送指定指令 -> 执行完成, 退出.
    由于expect是基于tcl的, 所以需要确保系统中安装了tcl:
    检查是否安装了tcl:

    whereis tcl
    tcl: /usr/lib64/tcl8.5 /usr/include/tcl.h /usr/share/tcl8.5
    

    如果没有安装, 使用yum安装tcl和expect:

    yum install -y tcl
    yum install -y expect
    

    查看expect的安装路径:

    command -v expect
    /usr/bin/expect
    

    2 expect的常用命令

    3 作用原理简介

    3.1 示例脚本

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

    #!/usr/bin/expect
    set timeout 10
    spawn ssh -l root 192.168.6.10
    expect "password*"
    send "password
    "
    interact
    

    4 其他脚本使用示例

    4.1 直接通过expect执行多条命令

    #!/usr/bin/expect
    set timeout 10
    spawn su - root
    expect "Password*"
    send "password
    "
    expect "]*"
    send "ls
    "
    expect "#*"
    send "df -Th
    "
    send "exit"
    expect eof
    

    4.2 通过shell调用expect执行多条命令

    #!/bin/bash
    ip="192.168.6.10"
    username="root"
    password="password"
    /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
    
  • 相关阅读:
    Leetcode: K-th Smallest in Lexicographical Order
    Leetcode: Minimum Number of Arrows to Burst Balloons
    Leetcode: Minimum Moves to Equal Array Elements
    Leetcode: Number of Boomerangs
    Leetcode: Arranging Coins
    Leetcode: Path Sum III
    Leetcode: All O`one Data Structure
    Leetcode: Find Right Interval
    Leetcode: Non-overlapping Intervals
    Socket网络编程--简单Web服务器(3)
  • 原文地址:https://www.cnblogs.com/kylingx/p/11638446.html
Copyright © 2011-2022 走看看