ssh+rsync批量管理,批量分發

現在我簡單架設了一個7臺服務器的集群集體如下,架設集群的過程我就省略了…

[nfs存儲一臺]
192.168.42.10
[負載均衡2臺]
192.168.42.40
192.168.42.41
[web服務器2臺]
192.168.42.30
192.168.42.31
[備份1臺]
192.168.42.20
[mysql 1臺]
192.168.42.50

我現在需要批量管理這些服務器,剛開始用xshell一臺,一臺登錄管理,覺得非常痛苦,后來為了方便學到了ssh+rsync 批量管理,現將技術分享一下:

具體思路 : 我用 nfs 存儲做分發機,因為集群的所有的host文件,配置文件都需要統一,所以不可能一臺一臺復制,我是先將nfs的配置,做好,通過ssh+rsync技術實現批量管理,批量分發,其中涉及到三個主要腳本:exe_commond.sh(以root身份執行命令)fenfa.sh(以magedu身份執行命令),ip_hosts.sh(包含所有主機IP信息),為什么需要兩個不同身份的腳本文件呢.聽我詳細介紹其中的奧秘:

1.我現在用xshell連接 分發機一臺機器即可.因為像添加用戶,設置密碼,等超級權限還是得root去做 所有的集群root賬號密碼是一樣的.因此一個腳本即可管理所有機器.

腳本代碼:

#!/bin/bash

# 腳本用來批量創建集群用戶,刪除用戶,分發公鑰,執行命令等.
# 執行命令需要輸入root密碼,一次即可
# 命令參數: "commond" #要執行的命令
# 分發公鑰參數: "fenfa" #即可
# email:626612631@qq.com
# function: remote dis ssh key.
# version:1.1
. /etc/init.d/functions

COMMOND=$1
SCRIPT_DIR="$( cd "$( dirname "$0"  )" && pwd  )"
IP_HOSTS_FILE="ip_hosts.sh"
MANUSER="magedu"
MANUSERPASS="123456"


[ $# -ne 1 ] && echo "Parameter is a command or str {fenfa}" && exit 2

declare -a IP_ARR

if [ ! -e ${SCRIPT_DIR}/${IP_HOSTS_FILE} ]; then
    echo -e  "current path missing \033[31m ${IP_HOSTS_FILE} \033[0m file"
    exit 2
fi

IP_ARR=(`grep -v -E "(^#)|(^$)" ${SCRIPT_DIR}/${IP_HOSTS_FILE} 2>/dev/null`)
if [ ${#IP_ARR[@]} -lt 0 ];then
   echo -e  "error reading file, please confirm IP format"
   exit 2
fi

function show_success(){
  action "Command execution" /bin/true
}

function exe_commond(){

 echo  -n  "please inut root passwd. " 
 read  -s  password
 echo " "

 for ip in ${IP_ARR[@]};do
    /usr/bin/expect -c "
    set timeout -1
    spawn /usr/bin/ssh root@${ip} ${COMMOND} 
    expect {
        \"*yes/no\" { send \"yes\r\"; exp_continue }
        \"*password:\" { send \"${password}\r\" }
    }
    expect eof" >/dev/null 2>&1 ;
    if [ $? -eq 0 ];then
           action "$ip: execute command successfully"   /bin/true
         else
           action "$ip: execute command fail"    /bin/false
    fi

 done


}


if [ "${COMMOND}" != 'fenfa' ];then
 exe_commond
 show_success
 exit 0
fi

#分發公鑰
USERNA=`/usr/bin/whoami`

if [ "${USERNA}"=='root' ];then

  cd /home/magedu

elif [ "${USERNA}"=="${MANUSER}" ];then
  cd ~
else

  echo "Please distribute with ${MANUSER}  user"
  exit 3
fi


for fip in ${IP_ARR[@]};do
    /usr/bin/expect -c "
    set timeout -1
    spawn /usr/bin/ssh-copy-id -i  .ssh/id_dsa.pub   ${MANUSER}@${fip}
    expect {
        \"*yes/no\" { send \"yes\r\"; exp_continue }
        \"*password:\" { send \"${MANUSERPASS}\r\" }
    }
    expect eof" >/dev/null 2>&1 ;
    if [ $? -eq 0 ];then
           action "$fip: execute command successfully" /bin/true
         else
           action "$fip: execute command fail" /bin/false
    fi

done

show_success

腳本執行示例:
批量添加用戶 magedu 添加這個用戶的目的是用這個用戶進行與交互,畢竟root用戶權限太大了,而且用戶密碼也需要在腳本中保存,因此不說,各位都知道

[root@nfs-server script]# bash exec_commond.sh  "useradd magedu"
please inut root passwd.  
192.168.42.40: execute command successfully                [  OK  ]
192.168.42.41: execute command successfully                [  OK  ]
192.168.42.30: execute command successfully                [  OK  ]
192.168.42.31: execute command successfully                [  OK  ]
192.168.42.20: execute command successfully                [  OK  ]
192.168.42.50: execute command successfully                [  OK  ]
Command execution

批量設置magedu密碼 ==設置的密碼必須要和腳本中設置的一樣==

[root@nfs-server script]# bash exec_commond.sh  "echo 123456 | passwd --stdin magedu"
please inut root passwd.  
192.168.42.40: execute command successfully                [  OK  ]
192.168.42.41: execute command successfully                [  OK  ]
192.168.42.30: execute command successfully                [  OK  ]
192.168.42.31: execute command successfully                [  OK  ]
192.168.42.20: execute command successfully                [  OK  ]
192.168.42.50: execute command successfully                [  OK  ]
Command execution

nfs分發也需要一個magedu賬號,后面批量分發需要分發機的magedu和其他機器的magedu對應,為什么不把ip放進去一起執行呢,就怕執行其他的命令,導致分發機出錯

useradd magedu
echo 123456 | passwd --stdin magedu

上面的步驟都做完以后,我們接下來創建密鑰對,創建秘鑰對,需要分發機進去magedu家目錄執行:
一路回車即可
或者

ssh-keygen  -t dsa -P '' -f ~/.ssh/id_dsa &>/dev/null
[magedu@nfs-server ~]$ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/magedu/.ssh/id_dsa): 
Created directory '/home/magedu/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/magedu/.ssh/id_dsa.
Your public key has been saved in /home/magedu/.ssh/id_dsa.pub.
The key fingerprint is:
f2:18:c8:c0:db:bb:4c:38:77:4c:96:a4:6d:b4:dd:2d magedu@nfs-server
The key's randomart image is:
+--[ DSA 1024]----+
|                 |
| .               |
|  o   o          |
|   = * + . .     |
|  . = X S E .    |
|   . * =   .     |
|  o + + .        |
|   = o           |
|    o            |
+-----------------+

秘鑰對創建完成以后,我們需要對所有機器分發公鑰,目的就是為了分發機的magedu連接其他機器不需要再輸入密碼,自動完成分發任務

bash /script/exec_commond.sh "fenfa"
please inut root passwd.  
192.168.42.40: execute command successfully                [  OK  ]
192.168.42.41: execute command successfully                [  OK  ]
192.168.42.30: execute command successfully                [  OK  ]
192.168.42.31: execute command successfully                [  OK  ]
192.168.42.20: execute command successfully                [  OK  ]
192.168.42.50: execute command successfully                [  OK  ]
Command execution

至此分發公鑰的任務完成了,現在我們就在分發機的magedu家目錄下,創建文件a.txt
,利用分發腳本fenfa.sh分發a.txt試試

上腳本:

#!/bin/bash
# 用來分發文件和移動文件(rsync)
# email:626612631@qq.com
# function: remote dis ssh key.
# version:1.1
. /etc/init.d/functions

FILEPATH=$1
COMMOND=$2
SCRIPT_DIR="$( cd "$( dirname "$0"  )" && pwd  )"
IP_HOSTS_FILE="ip_hosts.sh"
MANUSER="magedu"

if [ "${FILEPATH}" == "--commond" ];then
   if [ $# -eq 1 ];then
        echo "Please enter a command to execute." 
        exit 2
   fi
else
   if [ ! -f ${FILEPATH} ]; then
          echo "File or directory does not exist". && exit 2
   fi
fi


if [ ! -e ${SCRIPT_DIR}/${IP_HOSTS_FILE} ]; then
    echo -e  "current path missing \033[31m ${IP_HOSTS_FILE} \033[0m file"
    exit 2
fi

IP_ARR=(`grep -v -E "(^#)|(^$)" ${SCRIPT_DIR}/${IP_HOSTS_FILE} 2>/dev/null`)
if [ ${#IP_ARR[@]} -lt 0 ];then
   echo -e  "error reading file, please confirm IP format"
   exit 2
fi

function  exec_fenfa(){
    expect -c "
    set timeout -1
    spawn $1
    expect {
        \"*yes/no\" { send \"yes\r\"; exp_continue }
    }
    expect eof" >/dev/null 2>&1;
    if [ $? -eq 0 ];then
           action "$2 is fenfa successfully" /bin/true
         else
           action "$2 is fenfa  fail" /bin/false
    fi

}

for ip in ${IP_ARR[@]};do
   if [ "${FILEPATH}" != "--commond" ];then
        #scp -r ${FILEPATH}  ${MANUSER}@${ip}:~  

        exec_fenfa  "scp -r ${FILEPATH}  ${MANUSER}@${ip}:~"  $ip  

   else
      #遠程sudo 加-t  
      if [[ "${COMMOND}" =~ "sudo" ]]; then
        exec_fenfa  "ssh -t ${MANUSER}@${ip} ${COMMOND}" $ip
      else
        exec_fenfa  "ssh ${MANUSER}@${ip} ${COMMOND}"  $ip
      fi

   fi
done

示例:分發a.tx,連上其中一臺的家目錄,你就會看到文件已經在上面了

[magedu@nfs-server ~]$ bash /script/fenfa.sh a.txt
a.txt                              100%    0     0.0KB/s   00:00    
a.txt                              100%    0     0.0KB/s   00:00    
a.txt                              100%    0     0.0KB/s   00:00    
a.txt                              100%    0     0.0KB/s   00:00    
a.txt                              100%    0     0.0KB/s   00:00    
a.txt                              100%    0     0.0KB/s   00:00

但是有一點,如果我先把hosts文件分發到其他機器magedu的家目錄下,但是需要把hosts文件copy到/etc/目錄下,你會發現沒有權限,更何況我們還需要遠程將hosts文件拷貝到/etc/目錄下,這個問題我采用rsync的功能,rsync具有本地復制的功能,而我們的其他機器沒有裝rsync怎么辦呢,不著急,用下面的方法
so easy

bash /script/exec_commond.sh "yum install rsync -y" 

please inut root passwd.  

192.168.42.40: execute command successfully                [  OK  ]
192.168.42.41: execute command successfully                [  OK  ]
192.168.42.30: execute command successfully                [  OK  ]
192.168.42.31: execute command successfully                [  OK  ]
192.168.42.20: execute command successfully                [  OK  ]
192.168.42.50: execute command successfully                [  OK  ]
Command execution

然而我們裝了rsync也不具備root權限,執行rsync /home/magedu/a.txt /etc/失敗,那怎么辦呢,別著急,有辦法 利用sudo提權,怎么提權呢

bash /script/exec_commond.sh "echo 'magedu  ALL=(ALL)  NOPASSWD: /bin/rsync'>>/etc/sudoers"

please inut root passwd.  

192.168.42.40: execute command successfully                [  OK  ]
192.168.42.41: execute command successfully                [  OK  ]
192.168.42.30: execute command successfully                [  OK  ]
192.168.42.31: execute command successfully                [  OK  ]
192.168.42.20: execute command successfully                [  OK  ]
192.168.42.50: execute command successfully                [  OK  ]
Command execution

至此我們的工作都做完了.執行

[magedu@nfs-server ~]$ bash /script/fenfa.sh --commond "sudo rsync /home/magedu/a.txt /etc/"
192.168.42.40: execute command successfully [  OK  ]
192.168.42.41: execute command successfully [  OK  ]
192.168.42.30: execute command successfully [  OK  ]
192.168.42.31: execute command successfully [  OK  ]
192.168.42.20: execute command successfully [  OK  ]
192.168.42.50: execute command successfully [  OK  ]

完了以后,連接其他的服務器進去/etc/查看

[magedu@nginx-lib-1 etc]$ ls | grep a.txt
a.txt

注意一個問題ssh連接慢: 快速更改方法

sed -ir '13 iPort 52113\nPermitRootLogin no\nPermitEmptyPasswords no\nUseDNS no\nGSSAPIAuthentication no' sshd_config

文件順利的被拷貝到/etc/目錄下,后面分發其他文件是不是也很容易了呀,當然我寫的腳本也有不完善的地方,自己根據自己的情況完善即可.

原創文章,作者:srayban,如若轉載,請注明出處:http://www.www58058.com/73880

(1)
sraybansrayban
上一篇 2017-04-22
下一篇 2017-04-22

相關推薦

  • 9、varnish實現動靜分離、負載均衡、后端服務器健康狀態檢測

    varnish 4.0 版本 varnish實現動靜分離 # vim /etc/varnish/varnish.params VARNISH_LISTEN_PORT=80 –> 修改為80端口 # vim /etc/varnish/default.vcl backend html {    .host = “1…

    Linux干貨 2016-11-13
  • 馬哥教育網絡班22期+第11周課程練習

    1、詳細描述一次加密通訊的過程,結合圖示最佳。 Bob先利用單向加密算法提取當前數據的指紋(特征碼),再用自己的私鑰加密數據指紋并附加于數據尾部, 然后利用對稱加密將整個文件加密,之后用Alice的公鑰加密對稱加密密鑰附加于尾部。 Alice收到數據后,先用自己的私鑰解密,得到對稱加密密鑰,之后用對稱加密密鑰解密,然后用Bob的公鑰 解密得到數據指紋,并且驗…

    Linux干貨 2016-11-14
  • 破壞grub實驗之一

    1、刪除grub stage1階段 [root@centos6 ~]# dd if=/dev/zero of=/dev/sda bs=446 count=1 1+0 records in 1+0 records out 446 bytes …

    Linux干貨 2016-09-19
  • 高效運維最佳實踐(03):Redis集群技術及Codis實踐

    前言 誠如開篇文章所言,高效運維包括管理的專業化和技術的專業化。前兩篇我們主要在說些管理相關的內容,本篇說一下技術專業化。希望讀者朋友們能適應這個轉換,謝謝。 互聯網早在幾年前就已進入Web 2.0時代,對后臺支撐能力的要求,提高了幾十倍甚至幾百倍。在這個演化過程中,緩存系統扮演了舉足輕重的角色。 運維進化到今天,已經不是重復造輪子的時代。所以,我們在架構優…

    Linux干貨 2015-04-03
  • ansible 入門與進階

    ansible 入門與進階 Configuration、Command and Control 是什么 ? SSH-based configuration management, deployment, and task execution system 運維工具的分類: agent:基于專用的agent程序完成管理功能,puppet, func, zabb…

    2016-11-09
  • 第一天

    今天講了很多

    Linux干貨 2018-03-26

評論列表(1條)

  • renjin
    renjin 2017-04-28 09:50

    主要介紹了ssh+rsync對主機的批量管理,內容寫的很詳細也比較超前,排版也非常好,繼續努力

欧美性久久久久