ssh免密码登录自动设置脚本_ITBOOK.COM

1 篇文章 0 订阅

本文来源:IT书 - itbook.com

目的

一键式配置集群节点间免密码登录。前提是所有节点的密码是一致的!

实现

vim ~/nonpassword

脚本内容:

#!/bin/sh

# all node names
NODES=()  
# all node password 
PASS=$1 
###### Validation args length
nodes_length=$(($# - 1))
if [[ ss -gt 0 ]];then
  echo "Exit: At least two parameters, eg: your_password, node1"
  exit 2 
fi
###### Get all node name 
i=0
for node in $*
do
   if [[ i -gt 0 ]]; then
     j=$((i - 1)) 
     NODES[j]=$node
   fi
   let i++
done
MASTER=`hostname`

yum -y install expect

###################################
function ssh_cmd0(){
user_and_host=$1
password=$2
cmd=$3
/usr/bin/expect <<-EOF
set timeout 5
spawn ssh $user_and_host
expect {
"yes/no" { send "yes\r";exp_continue }
"password" { send "$password\r" }
}
expect "#"  
send "$cmd\r"
expect "#" 
exit 0
interact
EOF
}

function ssh_cmd(){
    ssh_cmd0 "$1" "$2" "echo 'start_mark';$3 ;echo 'end_mark'" | sed -n '/^start_mark/,/^end_mark/p'|grep -Ev '(^start_mark|^end_mark)'
}

###### Create all nodes authorized_keys, And collection to master.
echo "" > ~/.ssh/authorized_keys
echo "" > ~/.ssh/known_hosts

for s in ${NODES[@]}
do
  echo -e "\nSTART:: Slave node ($s) generates id_rsa.pub and sends master node ($MASTER)"
  
  ssh_cmd "root@$s" "$PASS" "rm -f ~/.ssh/id_rsa; ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa"
  ssh_cmd "root@$s" "$PASS" "cat ~/.ssh/id_rsa.pub"  >> ~/.ssh/authorized_keys
  
  echo "DONE:: Slave node ($s) generates id_rsa.pub and send to master node ($MASTER)" 
done
###### Copy collectioned authorized_keys to all nodes.
echo -e "\n######################### SENDING authorized_keys TO ALL NODE #########################"
for s in ${NODES[@]}
do
    echo -e "\nSTART:: Master node ($MASTER)  send ALL id_rsa.pub(authorized_keys) to slave node ($s)"    
	
    ssh_cmd "root@$s" "$PASS" "echo '`cat  ~/.ssh/authorized_keys`' > ~/.ssh/authorized_keys"
    
    echo -e "DONE:: Master node ($MASTER)  send ALL id_rsa.pub(authorized_keys) to slave node ($s)\n"   
done
echo "Complete!"
chmod +x ~/nonpassword

用法

脚本用法:

~/nonpassword <password> <node1> <node2> <node...>

password:所有的节点必须是相同的密码。

具体用例:

请参见原文:IT书 - https://itbook.com/article/1550832877722

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值