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
    
  • 相关阅读:
    day55---前端基础之BOM操作和DOM操作
    每日作业5/8
    数据库之索引
    数据库之视图、触发器、事务、存储过程、内置函数、流程控制
    每日作业5/7
    数据备份与pymysql模块
    Navicat与MySQL使用
    每日作业5/6
    数据库之多表查询
    数据库之单表查询
  • 原文地址:https://www.cnblogs.com/kylingx/p/11638446.html
Copyright © 2011-2022 走看看