Linux except 实现自动化交互

        expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。

1. 交互流程

        spawn启动指定进程 --> expect获取指定关键字 --> send向指定程序发送指定字符 --> 执行完成退出。

备注:需要先安装expect。

2. 常用命令总结

spawn               交互程序开始后面跟命令或者指定程序
expect              获取匹配信息匹配成功则执行expect后面的程序动作
send exp_send       用于发送指定的字符串信息
exp_continue        在expect中多次匹配就需要用到
send_user           用来打印输出 相当于shell中的echo
exit                退出expect脚本
eof                 expect执行结束 退出
set                 定义变量
puts                输出变量
set timeout         设置超时时间

3. 实验举例

3.1 ssh登录远程主机执行命令

执行方法 expect 1.sh 或者 ./1.sh

# vim 1.sh 

#!/usr/bin/expect

set timeout -1

spawn ssh user@192.168.0.12 df -Th
# spawn bash -c "scp ./aa/tt_* user@IP:/home/bb/data"

expect "*password"
send "123456\r"

expect eof

在shell脚本中执行expect命令,执行方法bash 2.sh 或./2.sh都可以执行.

#!/bin/bash

passwd='123456'
/usr/bin/expect <<-EOF

set time 30
spawn ssh saneri@192.168.56.103 df -Th
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$passwd\r" }
}
expect eof
EOF

3.2 删除远程主机指定目录的文件

expect执行多条命令

#!/usr/bin/expect
set timeout 30

spawn ssh user@IP
expect "Password:"
send "123456\r"
expect "*]$"
send "cd data_transfer\r"
expect "*]$"
send "rm /home/bb/data_transfer/tt_*\r"
expect eof

 

3.3 shell调用expect执行多行命令

#!/bin/bash 
ip=$1  
user=$2 
password=$3 

expect <<EOF  
    set timeout 10 
    spawn ssh $user@$ip 
    expect { 
        "yes/no" { send "yes\n";exp_continue } 
        "password" { send "$password\n" }
    } 
    expect "]#" { send "useradd hehe\n" } 
    expect "]#" { send "touch /tmp/test.txt\n" } 
    expect "]#" { send "exit\n" } expect eof 
 EOF  
 #./ssh5.sh 192.168.1.10 root 123456 

3.4 使用bash -c 解决expect下命令不能解析通配符*的问题

#!/usr/bin/expect -f
set HOST "192.168.102.1"
set USER "codefor"
set PASS "codefor"
set BOOKFILE "/home/codefor"

#upload
spawn bash -c "scp *.zip $USER@$HOST:$BOOKFILE"
expect {
    "*password*" {send "$PASS\r";}
}
expect eof;

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值