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\r"
interact

4 其他脚本使用示例

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

#!/usr/bin/expect
set timeout 10
spawn su - root
expect "Password*"
send "password\r"
expect "]*"
send "ls\r"
expect "#*"
send "df -Th\r"
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\r"; exp_continue }
"*password:" { send "$password\r" }
}
expect eof
EOF

最新文章

  1. bzoj1078【SCOI2008】斜堆
  2. UITabBarButton 点击失效问题
  3. [c++] Basic ideas and Style Guide
  4. Auto generating Entity classes with xsd.exe for XML Serialization and De-Serialization
  5. 转】Mahout推荐算法API详解
  6. 浅谈sqlserver数据库优化(一)----开光篇
  7. const type&amp; 与 type&amp; 的区别
  8. bzoj3272 3638
  9. ABAP提示信息对话框
  10. iOS WebView的用法
  11. UVa 507 - Jill Rides Again
  12. BZOJ 3998: [TJOI2015]弦论 [后缀自动机 DP]
  13. PHP代码审计
  14. docker~aspnetcore2.0镜像缺少libgdiplus问题
  15. Bootstrap -- 初见 Bootstrap
  16. CentOS设置服务开机启动的两种方法
  17. [C++]PAT乙级1004. 成绩排名 (20/20)
  18. mod_conference ESL控制二(事件)
  19. pta l3-1(凑零钱)
  20. 从JavaWeb的角度认识Nginx

热门文章

  1. 不同版本的ArcMap在Oracle中创建镶嵌数据集的不同行为
  2. Java 中不允许使用静态局部变量
  3. Python实现堆
  4. C++工程师养成 每日一题(string使用)
  5. 基于DigitalOcean+LAMP+WordPress搭建个人网站
  6. Jupyter notebook 安装
  7. 【题解】Luogu P5290 [十二省联考2019]春节十二响
  8. Maven聚合项目的创建
  9. Actions require unique method/path combination for Swagger
  10. kube-state-metrics 详解