一台linux机器需要无密码登录到N台linux机器;
具体用法请参考usage(注:yourpasswd为你需要创建信任关系机器的登录密码);
该脚本首先会去检查无密码认证是否ok,如果不ok,那就创建信任关系,并再次检查无密码认证是否ok。
-
#!/bin/bash
-
-
function usage()
-
{
-
cat <<EOF
-
usage:
-
auth-check.sh IpList Password
-
examle:
-
auth-check.sh 192.168.1.1..100,192.168.99.22..99,192.168.9.10 yourpasswd
-
EOF
-
}
-
#检查机器是否能无密码登录
-
function check()
-
{
-
ret=`ssh -o ConnectTimeout=3 -o PasswordAuthentication=no -o KbdInteractiveDevices=no -o StrictHostKeyChecking=no $1 date 2>/dev/null
-
`
-
if [[ -z $ret ]]
-
then
-
ssh-keygen -R $1 &>/dev/null
-
return 1
-
else
-
echo "check ssh ok:$1"
-
return 0
-
fi
-
}
-
#本机生成公钥私钥
-
function create_key()
-
{
-
umask 077; test -d ${HOME}/.ssh || mkdir ${HOME}/.ssh
-
/usr/bin/expect <<-EOF
-
spawn ssh-keygen -t rsa -P "" -f ${HOME}/.ssh/id_rsa
-
expect {
-
"Overwrite (y/n)?" {
-
send -- "n\r"
-
} eof {
-
puts ">> generate id_rsa and id_rsa.pub ... ...\n"
-
} timeout {
-
exit 1
-
}
-
}
-
expect eof
-
EOF
-
}
-
#上传公钥到目标机器
-
function auth()
-
{
-
/usr/bin/expect <<-EOF
-
spawn ssh-copy-id -i ${HOME}/.ssh/id_rsa.pub $1
-
expect {
-
"Are you sure you want to continue connecting (yes/no)?" {
-
send -- "yes\r"
-
exp_continue
-
}
-
"*word:" {
-
send -- "${password}\r"
-
} eof {
-
exit 0
-
} timeout {
-
exit 1
-
}
-
}
-
expect eof
-
EOF
-
}
-
#做无密码认证后重新检查无密码登录是否成功
-
function recheck()
-
{
-
echo
-
echo -e "\e[33mre-auth:$1 \e[0m"
-
check $1
-
if [[ $? -eq 0 ]]
-
then
-
echo -e "\e[33mauthority sucess:$1 \e[0m"
-
else
-
echo -e "\e[31mauthority failed! please check machine:$1 \e[m"
-
fi
-
}
-
#主函数
-
function main()
-
{
-
if [[ $# -ne 2 ]];then
-
usage
-
exit 2
-
-
fi
-
password=$2
-
create_key &>/dev/null
-
iparry=`echo $1|sed 's/,/ /g'`
-
echo "IpList:$iparry"
-
for ip in ${iparry}
-
do
-
if grep -Ex "([0-9]{1,3}\.){3}[0-9]{1,3}" <<<"$ip" &>/dev/null;then
-
check $ip
-
if [[ $? -ne 0 ]];then
-
auth $ip &>/dev/null
-
recheck $ip
-
fi
-
-
elif grep -Ex "([0-9]{1,3}\.){3}[0-9]{1,3}\.\.[0-9]{1,3}" <<<"$ip" &>/dev/null ;then
-
ip_pre=`echo $ip |cut -d '.' -f -3`
-
ip_start=`echo $ip|cut -d '.' -f 4`
-
ip_end=`echo $ip|cut -d '.' -f 6`
-
for ((i= ${ip_start};i<=${ip_end};i++))
-
do
-
ip_dst="${ip_pre}.$i"
-
check $ip_dst
-
if [[ $? -ne 0 ]];then
-
auth $ip_dst &>/dev/null
-
recheck $ip_dst
-
fi
-
done
-
else
-
echo -e "\e[31m please check IP parameter \e[0m"
-
fi
-
done
-
exit 0
-
-
}
-
- main "$@"