expect 免交互
expect(伊克斯拜可特)
vim test.exp
#!/usr/bin/expect -f
set timeout 10
spawn ssh root@192.168.10.18
expect {
"yes/no" { send "yes\r"; exp_continue}
"*password:" { send "123456\r"}
timeout {puts "expeck connect timeout,pls contact admin_tao."; return}
}
interact
语句解析
set timeout 10 等待退出时间10秒
spawn 执行一条语句(脚本或命令)
expect 等待一个进程的反馈,接收一个字符参数"冒号中的参数" 可以接收正则匹配
send 接收一个参数“冒号中的参数”并将该参数发给进程
\r 回车
\n 换行
\t TAB
exp_continue 重新从当前expect
安装
yum install expect
apt install expect
结合入脚本
vim test.exp
#!/bin/bash/expect -f
if { $argc != 2 } {
send_user "usage: expect test.exp MBC_IP PASSWORD\n "
exit
}
set BMC_IP [ lindex $argv 0 ]
set password [ lindex $argv 1 ]
set timeout 10
spawn ssh sysadmin@$BMC_IP
expect {
"yes/no" { send "yes\r"; exp_continue}
"*password:" { send "$password\r"}
timeout {puts " boss timeout !!!!!!!!!! "; return}
}
expect eof
exit -onexit {
send_user "admin_tao good bye to you !\n"
}
解析语句
if { $argc != 2 } { #判断接的参数如果不等于2个
send_user "usage: expect test.exp file host\n " #则输出usage: expect test.exp BMC_IP PASS 用法
exit #并退出
}
set BMC_IP [ lindex $argv 0 ] # 脚本后跟的第一个参数 (类似 BMC_IP=$1)
set password [ lindex $argv 1 ] # 脚本后跟的第二个参数(类似 password=$2)
set timeout 10 # 10秒超时
spawn ssh sysadmin@$BMC_IP # 后跟要执行的交互命令 ,ssh 用户名@$BMC_IP $BMC_IP是$1
expect { # 固定格式
"yes/no" 匹配的内容 { send "yes\r" 匹配后输入的内容YES ; exp_continue} 连续匹配内容就要用到
"*password:" 匹配的内容 { send "$password\r"} 匹配后输入的内容YES(可以是变量)
timeout {puts " boss timeout !!!!!!!!!! "; return} 超时打印信息
}
expect eof 固定格式结束
实例1:免交互分发秘钥脚本
# 1 fenfa_sshkey.exp
vim fenfa_sshkey.exp
if { $argc != 3 } {
send_user "usage: expect fenfa_key.exp file host\n "
exit
}
set file [ lindex $argv 0 ]
set host [ lindex $argv 1 ]
set password "zoomtech"
set timeout 10
spawn ssh-copy-id -i $file "-p 22 dev@$host"
expect {
"yes/no" { send "yes\r";exp_continue}
"*password:" { send "$password\r"}
timeout {puts "expeck connect timeout,pls contact admin_tao."; return}
}
expect eof
# 2 fenfa_sshkey.sh
vim fenfa_sshkey.exp
#!/bin/sh
cd /server/scripts
. /etc/init.d/functions
for iplist in `cat iplist.txt`
do
expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub $iplist >/dev/null
if [ $? -eq 0 ]
then
action "$iplist" /bin/true
else
action "$iplist" /bin/false
fi
done
# 3 iplist.txt
192.168.1.200
192.168.1.201
# 4 清除ssh记录
>~/.ssh/known_hosts
本文来自博客园,站在巨人的肩膀上,坚持开源精神,遵循开源协议:Apache Licene 2.0协议。
浙公网安备 33010602011771号