参考 :
shell一键生成密钥脚本_mrxyy的博客-CSDN博客_密钥脚本
https://blog.csdn.net/qq_42591334/article/details/109604093
expect安装包
>tcl-8.5.7-6.el6.x86_64.rpm
百度网盘 请输入提取码
>expect-5.44.1.15-5.el6_4.x86_64.rpm
百度网盘 请输入提取码
注 : 生成ssh公钥路径必须为/root/.ssh目录,其他目录传输过去无效
生成[/root/send_ssh_pub.sh]文件,内容如下
#!/usr/bin/bash
while read line
do
ip=`echo $line |awk '{print $1}'`
pass=`echo $line |awk '{print $2}'`
expect <<EOF
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@$ip
expect {
"yes/no" { send "yes\n";exp_continue}
"password" { send "$pass\n"}
}
expect eof
EOF
done < /root/serverInfo.txt
注 : ssh-copy-id无法执行可以参考
cat /root/.ssh/id_rsa.pub | ssh root@192.168.1.1 'cat >> .ssh/authorized_keys'
生成run.sh
#!/bin/sh
# 报错停止运行
set -e
# 修改 /etc/hosts
cat >> /etc/hosts << 'EOF'
192.168.1.1 localhost
192.168.1.1 master
192.168.1.2 slave1
192.168.1.3 slave2
EOF
# 生成公钥
ssh-keygen -t rsa -N '' <<EOF
/root/.ssh/id_rsa
yes
EOF
# 生成账号信息txt
cat > /root/serverInfo.txt << 'EOF'
192.168.1.1 passwd
192.168.1.2 passwd
192.168.1.3 passwd
EOF
# 安装expect
rpm -ivh tcl-8.5.7-6.el6.x86_64.rpm
rpm -ivh expect-5.44.1.15-5.el6_4.x86_64.rpm
# 发送公钥
chmod +x /root/send_ssh_pub.sh
/root/send_ssh_pub.sh
# 测试
ssh root@192.168.1.2 "date"
# 清除
rm -rf /root/serverInfo.txt
rm -rf /root/send_ssh_pub.sh
echo "ssh免密配置完成"
执行
sh run.sh
注 : ssh端口不是默认的22时发送公钥得指定端口,如下
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub "-p 23 root@$ip"