脚本实现功能:批量或单个SSH免交互登录认证
脚本应用场景:当部署集群时,大多数实现要配置好管理节点与从节点的SSH免交互登录,针对这样的情况,写了下面脚本,简化工作。
#!/bin/bash # blog:http://lizhenliang.blog.51cto.com color_echo() { if [ $1 == "green" ]; then echo -e "\033[32;40m$2\033[0m" elif [ $1 == "red" ]; then echo -e "\033[31;40m$2\033[0m" fi } check_ssh_auth() { ssh $INFO ‘echo yes >/dev/null‘ if [ $? -eq 0 ]; then color_echo green "Host $IP SSH authentication successfully." else color_echo red "Host $IP SSH authentication failure!" exit fi } os_version() { OS_V=$(cat /etc/issue |awk ‘NR==1{print $1}‘) if [ $OS_V == "\S" -o $OS_V == "CentOS" ]; then echo "CentOS" elif [ $OS_V == "Ubuntu" ]; then echo "Ubuntu" fi } if ! $(which expect >/dev/null); then if [ $(os_version) == "CentOS" ]; then yum install expect -y [ $? -ne 0 ] && color_echo red "The expect installation failure!" && exit 1 elif [ $(os_version) == "Ubuntu" ]; then apt-get install expect -y if [ $? -ne 0 ]; then apt-get install expect --force-yes -y [ $? -ne 0 ] && color_echo red "The expect installation failure!" && exit 1 fi fi fi if [ ! -e ~/.ssh/id_rsa.pub ]; then color_echo green "The public/private rsa key pair not exist, start Generating..." expect -c " spawn ssh-keygen expect { \"ssh/id_rsa):\" {send \"\r\";exp_continue} \"(empty for no passphrase):\" {send \"\r\";exp_continue} \"again:\" {send \"\r\";exp_continue} } " >/dev/null 2>&1 if [ -e ~/.ssh/id_rsa.pub ]; then color_echo green "Generating public/private rsa key pair successfully." else color_echo red "Generating public/private rsa key pair failure!" fi fi if [[ $1 =~ ^[a-z]+@[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}@.* ]]; then for i in $@; do USER=$(echo $i|cut -d@ -f1) IP=$(echo $i|cut -d@ -f2) PASS=$(echo $i|cut -d@ -f3) INFO=$USER@$IP expect -c " spawn ssh-copy-id $INFO expect { \"(yes/no)?\" {send \"yes\r\";exp_continue} \"password:\" {send \"$PASS\r\";exp_continue} } " >/dev/null 2>&1 check_ssh_auth done elif [[ $1 =~ ^[a-z]+@[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}-[0-9]{1,3}@.* ]]; then START_IP_NUM=$(echo $1|sed -r ‘s/.*\.(.*)-(.*)@.*/\1/‘) END_IP_NUM=$(echo $1|sed -r ‘s/.*\.(.*)-(.*)@.*/\2/‘) for ((i=$START_IP_NUM;i<=$END_IP_NUM;i++)); do USER=$(echo $1|cut -d@ -f1) PASS=$(echo $1|cut -d@ -f3) IP_RANGE=$(echo $1|sed -r ‘s/.*@(.*\.).*/\1/‘) IP=$IP_RANGE$i INFO=$USER@$IP_RANGE$i expect -c " spawn ssh-copy-id $INFO expect { \"(yes/no)?\" {send \"yes\r\";exp_continue} \"password:\" {send \"$PASS\r\";exp_continue} } " >/dev/null 2>&1 check_ssh_auth done else echo "Example1: $0 <root@192.168.1.10-15@password>" echo "Example2: $0 [root@192.168.1.10@password root@192.168.1.11@password root@192.168.1.12@password ...]" fi
本文出自 “李振良的技术博客” 博客,请务必保留此出处http://lizhenliang.blog.51cto.com/7876557/1736179
原文地址:http://lizhenliang.blog.51cto.com/7876557/1736179