1.准备
新建一个ip.txt文件,按照四列写好集群的IP地址,主机名,账号,密码:
| ip | hostname | user | password |
|---|---|---|---|
| 192.168.1.100 | test01 | root | passwd |
| 192.168.1.100 | test02 | root | passwd |
2.代码
#!/bin/bash
#install expect module
rpm -q expect &>/dev/null
if [ $? -ne 0 ];then
yum -y install expect
fi
#generate key
if [ ! -f ~/.ssh/id_rsa ];then
ssh-keygen -P "" -f ~/.ssh/id_rsa
fi
while read line
do
{
ip=`echo $line |awk '{print $1}'`
user=`echo $line |awk '{print $3}'`
passwd=`echo $line |awk '{print $4}'`
/usr/bin/expect <<-EOF
set timeout 10
spawn ssh-copy-id $user@$ip
expect {
"connecting (yes/no)" { send "yes\r"; exp_continue }
"password:" { send "$passwd\r" }
}
expect eof
EOF
} &
done < ip.txt
wait
echo "all finish..."
本文介绍了一种使用Shell脚本和Expect模块批量进行SSH密钥部署的方法,通过读取包含IP地址、主机名、账号及密码的文本文件,实现自动化SSH免密码登录配置,适用于集群管理和批量任务执行。
288

被折叠的 条评论
为什么被折叠?



