一、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