一、expect交互式工具
1、作用
- 捕获交互式命令的输出,让交互式命令自动执行
[root@node01 ~]# yum install -y expect
[root@node01 ~]# rpm -q expect
expect-5.45-14.el7_1.x86_64
2、expect单独使用
#!/usr/bin/expect
set timeout 10
spawn passwd root
expect "New password:"
send "redhat\n"
expect "Retype new password:"
send "redhat\n"
expect eof
3、expect在shell脚本中的使用
[root@node01 work]# cat test02.sh
#!/bin/bash
#
useradd joker
/usr/bin/expect << eof
set timeout 10
spawn passwd joker
expect "New password:"
send "123456\n"
expect "Retype new password:"
send "123456\n"
expect eof
eof
需求: 配置ssh免密
#!/bin/bash
#
# 判断是否存在密钥
if [ -f ~/.ssh/id_rsa ]; then
rm -rf ~/.ssh/id_rsa*
fi
# 生成密钥对
ssh-keygen -t rsa -f ~/.ssh/id_rsa -P "" &> /dev/null
# 判断known_hosts文件中是否包含对方主机的密钥
> ~/.ssh/known_hosts
for i in 11 12; do
/usr/bin/expect << eof
set timeout 10
spawn ssh-copy-id root@192.168.140.$i
expect "(yes/no)?"
send "yes\n"
expect "password:"
send "redhat\n"
expect eof
eof
done
echo "-------------------------------------------"
# 验证
for i in 11 12; do
ssh root@192.168.140.$i hostname
done