一、简介
现代的Shell对程序提供了最小限度的控制(开始,停止,等等),而把交互的特性留给了用户。这意味着有些程序,你不能非交互的运行,比如说 passwd。有一些程序可以非交互的运行,但在很大程度上丧失了灵活性,比如说fsck。这表明Unix的工具构造逻辑开始出现问题。Expect恰恰 填补了其中的一些裂痕,解决了在Unix环境中长期存在着的一些问题。
Expect使用Tcl作为语言核心。不仅如此,不管程序是交互和还是非交互的,Expect都能运用。这是一个小语言和Unix的其他工具配合起来产生强大功能的经典例子。
二、互信脚本
###################################################################
#!/bin/bash
# 定位脚本当前位置
parent_path=$( cd "$(dirname "${BASH_SOURCE}")" ; pwd -P )
cd "$parent_path"
rpm -q --qf '%{NAME}-%{VERSION}-%{RELEASE}(%{ARCH})\n' tcl expect >/dev/null 2>&1
if [ $? -ne 0 ]; then
rpm -ivh tcl-8.5.13-8.el7.x86_64.rpm
rpm -ivh expect-5.45-14.el7_1.x86_64.rpm
fi
# ip列表,用英文逗号隔开
ipList="xx.xx.xx.xx,xx.xx.xx.xx,xx.xx.xx.xx"
pwd="XXX"
rm -f ~/.ssh/id_rsa
rm -f ~/.ssh/id_rsa.pub
ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
arr=$(echo ${ipList} | tr "," "\n")
for ip in ${arr[@]}
do
expect -c "
set timeout 120
spawn ssh-copy-id root@"$ip"
expect {
*yes/no* {send "yes"\r;exp_continue;}
*assword* {send "${pwd}"\r;}
}
expect -re \](\$|#)
exit
"
done
####################################################################
三、参考
expect教程中文版
http://xstarcd.github.io/wiki/shell/expect_handbook.html
expect - 自动交互脚本
http://xstarcd.github.io/wiki/shell/expect.html
linux expect详解(ssh自动登录)
https://www.cnblogs.com/lzrabbit/p/4298794.html
关于shell和expect和ssh
https://segmentfault.com/a/1190000002564816
expect实现scp/ssh-copy-id非交互