expect交互脚本用法

expect的常用命令

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

脚本实例

该脚本主要用于登录交互(expectLogin.sh)

#!/usr/bin/expect
 set timeout 5
 set server [lindex $argv 0]
 set user [lindex $argv 1]
 set passwd [lindex $argv 2]
 spawn ssh -l $user $server
 expect {
     "(yes/no)" { send "yes\r"; exp_continue }
     "password:" { send "$passwd\r" }
  }
 expect "*Last login*" interact

添加执行权限后可以直接使用:./expectLogin.sh 172.16.6.100 root 123456

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

通过shell调用expect进行交互,其中还用到了read命令来获取屏幕输入 

#!/bin/bash
 ​
 ip="172.16.6.100"
 username="root"
 read -p "请输入$username用户的密码:" 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

read命令后的password即为定义变量,后面可以直接用该变量名

猜你喜欢

转载自blog.csdn.net/tl4832194/article/details/112202147