expect工具实现脚本的自动交互 1 安装expect工具 2 expect的常用命令 3 作用原理简介 3.1 示例脚本 4 其他脚本使用示例 4.1 直接通过expect执行多条命令 4.2 通过shell调用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