如果读者对expect和ssh认识比较清晰,可以直接跳转到下面代码部分
预备知识
expect中关键命令:send,expect,spawn,eof。
1、expect:从进程接收字符串。
expect -c 是将终端操作变成命令操作。
2、send:用于向进程发送字符串。
一般用于向停滞不懂的命令行发送指令,从而能进行下一步操作。
3、spawn:启动新的进程,之后所有expect操作都在这个进程中进行。
在本文中通常与ssh命令进行组合使用,意味着开启一个新的ssh操作。
4、eof:匹配文本结束。
通常在expect接收字符串结尾处使用,与exit 0 组合使用可以退出进程。
ssh部分命令解释:
ssh-keygen-t [tsa/dsa]:在~/.ssh目录下生成tsa/dsa协议的公钥和私钥。
ssh-copy-id user@server:将本机的公钥发送到目标机器中。‘
’
expect中细节解读:
*内容*:该部分是正则匹配,当匹配到正则内容部分后进行后面操作。
exp_continue:正常情况下如果匹配到规则进行send操作后就会结束后面匹配内容,而exp_continue会让后续操作继续进行规则匹配。
exit 0:退出进程。
auto_ssh_keygen(){
expect -c "set timeout -1;
spawn ssh-keygen -t dsa;
expect {
*id_dsa)* {send -- \r;exp_continue;}
*passphrase)* {send -- \r;exp_continue;}
*again:* {send -- \r;exp_continue;}
eof {exit 0;}
}";
}
代码部分
1、安装expect:
本文直接应用yum仓库进行安装
yum install expect
2、创建需要远程连接的配置文件
touch ssh.conf
我们再ssh.conf中配置需要进行远程连接的IP/DNS,用户名,密码。
192.168.20.10 hadoop 123456
192.168.20.11 hadoop 123456
192.168.20.12 hadoop 123456
或者
hadoop1 hadoop 123456
hadoop2 hadoop 123456
hadoop3 hadoop 123456
3、创建免密登录脚本
其中脚本会将配置文件的路径作为第一参数传递进去
#!/bin/bash
# 生成本机公钥私钥
auto_ssh_keygen(){
expect -c "set timeout -1;
spawn ssh-keygen -t dsa;
expect {
*id_dsa)* {send -- \r;exp_continue;}
*passphrase)* {send -- \r;exp_continue;}
*again:* {send -- \r;exp_continue;}
eof {exit 0;}
}";
}
# 执行生成公钥私钥脚本
auto_ssh_keygen
# 实现将本机的公钥发送到其他机器的功能
# 需要将其他机器的用户名,密码,IP或DNS传入
# ssh-copy-id user@server 将本机公钥发送到其他机器
auto_ssh_copy_id(){
expect -c "set timeout -1;
spawn ssh-copy-id $2@$1;
expect {
*(yes/no)* {send -- yes\r;exp_continue;}
*password* {send -- $3\r;exp_continue;}
eof {exit 0;}
}";
}
# 根据配置文件,将公钥依次发送到各个机器中
ssh_copy_id_to_all(){
cat $1 | while read line
do
IP=`echo $line | cut -d ' ' -f 1`
USERNAME=`echo $line | cut -d ' ' -f 2`
PASSWORD=`echo $line | cut -d ' ' -f 3`
auto_ssh_copy_id $IP $USERNAME $PASSWORD
done
}
# 执行将公钥私钥发送到各个机器函数
ssh_copy_id_to_all $1
4、执行脚本
其中参数为配置文件路径
sh ssh.sh ssh.conf
5、测试效果图
ssh-keygen -t dsa生成图,方块为命令行输入内容部分。
ssh-copy-id user@server 生成图,方块为命令行输入内容部分。
链接测试,通过hadoop1连接到hadoop2
脚本测试成功。