trap、expect脚本练习

一、trap

1、trap测试

#!/bin/bash
trap 'echo "singal:Press Ctrl+c"' int
for i in {1..10};do
    sleep 1
    echo $i
done
trap '' int
for i in {11..20};do
   sleep 1
   echo $i
done
trap '-' int
for i in {21..30};do
    sleep 1
    echo $i
done

2、finish函数测试

#!/bin/bash
a(){
    echo -e "\e[1;33maaaaaa\e[0m"
}
trap a  exit
while true;do
    echo running
    sleep 1
done

二、expect

1、expect脚本

①、ssh

#!/usr/bin/expect
spawn ssh 10.0.0.203
expect {
    "yes/no" {send "yes\n";exp_continue}
    "password" {send "123456\n"}                                         
    }
interact

②、scp

#!/usr/bin/expect
spawn scp /data/reset.sh root@10.0.0.203:/data
expect {
"yes/no" {send "yes\n";exp_continue}
"password" {send "123456\n"}
}
expect eof

③、变量引用

#!/usr/bin/expect
set ip 10.0.0.203
set user root
set password 123456
set timeout 10
spawn scp /data/reset.sh $user@$ip:/data
expect {
"yes/no" {send "yes\n";exp_continue}
"password" {send "$password\n"}
}
expect eof

④、位置参数

#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh $user@$ip
expect {
	"yes/no" {send "yes\n";exp_continue}
	"password" {send "$password\n"}    
}
interact

⑤、多命令执行

#!/usr/bin/expect
set ip 10.0.0.203
set user root
set password 123456
set timeout 10
spawn ssh $user@$ip
expect {
"yes/no" {send "yes\n";exp_continue}
"password" {send "$password\n"}
}
expect "]#" {send "echo hhh\n"}
send "exit\n"
expect eof

2、shell脚本

#!/bin/bash
ip=10.0.0.203
user=root
password=123456
expect <<EOF
set timeout 10
spawn ssh $user@$ip
expect {
"yes/no" {send "yes\n";exp_continue}
"password" {send "$password\n"}
}
expect "]#" {send "echo hhh\n"}
send "exit\n"
expect eof
EOF
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值