这篇文章上次修改于 422 天前,可能其部分内容已经发生变化,如有疑问可询问作者。
介绍
- expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。
expect自动交互流程
- spawn启动指定进程---expect获取指定关键字---send向指定程序发送指定字符---执行完成退出.
- 注意该脚本能够执行的前提是安装了expect
- expect 如果只交互一次如拷贝文件 结尾就使用
expect eof
- 如果需要连续交互如登录远程主机执行各种命令结尾就需使用
interact
安装
yum -y install expect
常用命令
spawn 交互程序开始后面跟命令或者指定程序
expect 获取匹配信息匹配成功则执行expect后面的程序动作
send exp_send 用于发送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用来打印输出 相当于shell中的echo
exit 退出expect脚本
eof expect执行结束 退出
set 定义变量
puts 输出变量
set timeout 设置超时时间
示例一
# 主机清单
[root@k8s-master ~]# vi hosts
192.168.1.8 root rootpwd
192.168.1.9 root rootpwd
# 脚本
[root@k8s-master ~]# vi copyssh.sh
#!/bin/bash
if [ ! -f ~/.ssh/id_rsa ];then
ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa
else
echo "id_rsa has created ..."
fi
#分发到各个节点
while read line
do
user=`echo $line | cut -d " " -f 2`
ip=`echo $line | cut -d " " -f 1`
passwd=`echo $line | cut -d " " -f 3`
expect <<EOF
set timeout 10
spawn ssh-copy-id $user@$ip
expect {
"yes/no" { send "yes\n";exp_continue }
"password" { send "$passwd\n" }
}
expect "password" { send "$passwd\n" }
EOF
done < hosts
[root@k8s-master ~]# chmod +x copyssh.sh
[root@k8s-master ~]# ./copyssh.sh
id_rsa has created ...
spawn ssh-copy-id root@192.168.1.8
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.1.8's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.1.8'"
and check to make sure that only the key(s) you wanted were added.
spawn ssh-copy-id root@192.168.1.9
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.1.9's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.1.9'"
and check to make sure that only the key(s) you wanted were added.
没有评论
博主关闭了评论...