expect工具的使用
expect 脚本的后缀名可以为sh、exp、expect
例子1——ssh连接主机
# !/bin/expect
spawn ssh root@centso71
expect {
"yes/no" {send "yes\r";exp_continue}
"password:" {send "123\r"};
}
interact
ssh改进版
# !/bin/expect
set ip 182.168.56.162
set user root
set passwd 123
set timeout 5
spawn ssh $user@$ip
expect{
"yes/no" {send "yes\sr";exp_continue}
"password:" {send "$passwd\r"};
}
interact
使用位置参数
set ip [lindex $argv 0]
set user [lindex $argv 1]
set passwd 123
set timeout 5
spawn ssh $user@$ip
expect{
"yes/no" {send "yes\sr";exp_continue}
"password:" {send "$passwd\r"};
}
# interact 不使用交互模式
expect "#"
send "ls\r"
例子2——获取IP、推送公钥
#!/bin/bash
>ip.txt
passwd=123
# 测试expect是否安装
rpm -q expect &>/dev/null
if [ $? -ne 0 ];then
yum -y install expect
fi
# 测试公钥是否存在,不存在则创建
if [ ! -f ~/.ssh/id_rsa ];then
ssh-keygen -P "" -f ~/.ssh/id_rsa
fi
for i in {2..254}
do
{
ip=192.168.56.$i
ping -c1 -W1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo "$ip" >> ip.txt
expect <<-EOF
spawn ssh-copy-id $ip
expect {
"yes/no" {send "yes\r"; exp_continue}
"password:" {send "$password\r"}
}
expect eof
EOF
fi
}&
done
wait
echo "finish......"