1. 程式人生 > >20181225-Linux Shell Bash環境下自動化建立ssh互信指令碼

20181225-Linux Shell Bash環境下自動化建立ssh互信指令碼

20181225-Linux Shell Bash環境下自動化建立ssh互信指令碼

我的Blog

部落格園 https://www.cnblogs.com/piggybaba/
個人網站 http://piggybaba.cn
GitHub https://github.com/AndyYHM/Writing/

簡介資訊

摘要:Linux下,自動化建立SSH互信指令碼
Author: [email protected]
Date: 20181225
關鍵字:Shell指令碼, ssh, ssh trust ,auto,SSH互信,/bin/bash

指令碼輸出效果

單一節點上,使用者python,執行指令碼後,輸入三臺節點python使用者密碼,自動化建立SSH互信關係

$ sh SSH_Trust.sh
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password:
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]
's password: /bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys [email protected]'s password: Transfer authorized_keys authorized_keys 100% 1185 1.2KB/s 00:00 known_hosts 100% 537 0.5KB/s 00:00 authorized_keys 100% 1185 1.2KB/s 00:00 known_hosts 100% 537 0.5KB/s 00:00

功能說明

  • 預設支援3節點自動化建立SSH互信關係
  • 支援多節點自動化建立SSH互信關係

使用說明

  • 需要提前編輯好/etc/hosts檔案
  • 使用者名稱所有主機設定為一致
  • 使用前編輯指令碼"config to do"部分,節點hostname和使用者名稱
  • othernodes引數需以空格” “隔開;
  • 執行指令碼後,需逐一輸入節點使用者的密碼
  • 若主機節點數規模龐大,建議使用expect工具,另行編輯指令碼;

指令碼內容

#!/usr/bin/env bash


#########################################
# Author: [email protected]
# Date: 20181225
# Key Word : Shell指令碼, ssh, ssh trust ,auto,SSH互信,/bin/bash
#########################################
#
## Config to do
#
node1=node11
node2=node12
node3=node13
othernodes=
user=test

#
## Please Don't edit content below
#
ssh-keygen  -q -P ""  -f $HOME/.ssh/id_rsa > /dev/null
for node in ${node1} ${node2} ${node3} ${othernodes}
do
    if [ "`hostname`" == "$node" ]; then
        ssh-copy-id -o stricthostkeychecking=no [email protected]$node > /dev/null
    else
        ssh-copy-id -o stricthostkeychecking=no [email protected]$node > /dev/null
        ssh $node 'ssh-keygen  -q -P ""  -f $HOME/.ssh/id_rsa' > /dev/null
        scp -rp $node:$HOME/.ssh/id_rsa.pub ./auth.$node > /dev/null
    fi
done

cat ./auth.* >> $HOME/.ssh/authorized_keys
rm -rf ./auth.*

echo "Transfer authorized_keys"
for node in ${node1} ${node2} ${node3} ${othernodes}
do
  if [ "`hostname`" != "$node" ]; then
        scp -rp $HOME/.ssh/authorized_keys $node:$HOME/.ssh/authorized_keys
        scp -rp $HOME/.ssh/known_hosts $node:$HOME/.ssh/known_hosts

  fi

done

exit 0