ssh免密码登录自动设置脚本 - IT书 - https://itbook.com/

Posted itbook-com

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ssh免密码登录自动设置脚本 - IT书 - https://itbook.com/相关的知识,希望对你有一定的参考价值。

原创链接: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
";exp_continue }
"password" { send "$password
" }
}
expect "#"  
send "$cmd
"
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 "
START:: 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 "
######################### SENDING authorized_keys TO ALL NODE #########################"
for s in ${NODES[@]}
do
    echo -e "
START:: 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)
"   
done
echo "Complete!"
chomd +x ~/nonpassword

用法

脚本用法:

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

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

具体用例:

~/nonpassword mypassword node1 node2 node3 

执行成功后,就可以再node1,node2.node3之间免密码登录了,比如已经登上了node1,然后要登录node2,可直接在node1上执行命令:

ssh node2

即可。

以上是关于ssh免密码登录自动设置脚本 - IT书 - https://itbook.com/的主要内容,如果未能解决你的问题,请参考以下文章

linux下怎样设置ssh无密码登录

如何在 CentOS / RHEL 上设置 SSH 免密码登录

ssh 双机互信:免密码登录设置步骤及常见问题

Shell 脚本 ssh免密码 登录 远程服务器 sshpass用法示例

ssh配置免密后依然需要输入密码的问题解决及排查过程

ssh登录自动输入密码