linux批量免密登陆

运用ansible进行自动化运维之前,我们需要对所有机器进行SSH认证,运用下面脚本一键实现机器批量SSH免密登录,务必保证批量机器为同一用户同一密码。

#!/bin/bash
#批量实现SSH免密登录

#没有则安装expect
if  ! rpm -q expect > /dev/null
then
    echo "###expect 未安装,现在安装###"
    yum install -y expect &>/dev/null
    if [ $? -ne 0 ]
    then
        echo "###expect 安装失败###"
        exit 1
    fi
fi

#本机没有SSH密钥则生成
if [ ! -f ~/.ssh/id_rsa ]
then
    echo "###请按3次enter键###"
    ssh-keygen -t rsa
fi

ssh_expect () {
    expect -c "set timeout -1;
    spawn ssh-copy-id -f $1

    expect {
        "yes/no" { send -- yes
;exp_continue;}
        "password:" { send -- $2
;exp_continue;}
        eof
    }";
}

[ -f hosts.txt ] && rm -rf hosts.txt

#定义 hosts.txt
cat > hosts.txt << EOF
192.168.30.128
192.168.30.129
192.168.30.130
EOF

passwd=123456789

for ip in `cat hosts.txt |awk '{print $1}'`
do
    ssh_expect $ip $passwd
done
原文地址:https://www.cnblogs.com/yueminghai/p/13516048.html