集羣部署腳本

Linux報錯:“/bin/bash^M: 壞的解釋器

原因是linux下的文件,在windows下面編輯過。在win下編輯的時候,換行結尾是\n\r , 而在linux下 是\n

解決方法,將文件裏面的內容做替換即可

sed -i 's/\r$//' build.sh  

免密登錄

#!/bin/bash
#ssh免密登錄shell腳本
#配置免密登錄的所有機子都要運行該腳本
 
#修改/etc/ssh/sshd_config配置文件
#sed -i 's/被替換的內容/替換成的內容/'  /配置文件地址
#sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config
#cat >> /etc/ssh/sshd_config <<EOF
#RSAAuthentication yes
#EOF
 
yum install expect  #安裝expect
echo "按enter鍵3次即可"
ssh-keygen -t rsa   #生成祕鑰(按enter鍵3次即可生成)
SERVERS="spark12 spark13 spark14"   #需要配置的主機名
PASSWORD=123   #需要配置的主機登錄密碼
 
#將本機生成的公鑰複製到其他機子上
#如果(yes/no)則自動選擇yes繼續下一步
#如果password:怎自動將PASSWORD寫在後面繼續下一步
auto_ssh_copy_id(){
        expect -c "set timeout -1;
        spawn ssh-copy-id $1;                                
        expect {
                *(yes/no)* {send -- yes\r;exp_continue;}
                *password:* {send -- $2\r;exp_continue;}  
                eof        {exit 0;}
        }";
}
 
ssh_copy_id_to_all(){
        for SERVER in $SERVERS #遍歷要發送到各個主機的ip
        do
                auto_ssh_copy_id $SERVER $PASSWORD
        done
}
ssh_copy_id_to_all

 分發文件

#!/bin/bash
#查出參數個數
pcount=$#
if((pount<1)) ; then
echo no args;
exit;
fi
#取出第一個參數
p1=$1;
fname=`basename $p1`
#echo fname=$fname;
#取出文件的絕對路徑
pdir=`cd  -P $(dirname $p1) ; pwd`
cuser=`whoami`
#for((host=100;host<102;host=host+1)); do
#echo ---------- s$host -------------
#rsync -rvl $pdir/$fname $cuser@s$host:$pdir
#done
start_x(){
        for SERVER in $SERVERS #遍歷要發送到各個主機的ip
        do
                rsync -rvl $pdir/$fname $SERVER:$pdir
        done
}
start_x

 

命令分發

#!/bin/bash
if [ "$#" -ne 2 ] ; then
    echo "USAGE: $0 -f server_list_file cmd"
    exit -1
fi
 
file_name=$1
cmd_str=$2
 
cwd=$(pwd)
cd $cwd
serverlist_file="$cwd/$file_name"
 
if [ ! -e $serverlist_file ] ; then
    echo 'server.list not exist';
    exit 0
fi
 
while read line
do
    #echo $line
    if [ -n "$line" ] ; then
        echo "DOING--->>>>>" $line "<<<<<<<"
        ssh $line $cmd_str < /dev/null > /dev/null
        if [ $? -eq 0 ] ; then
            echo "$cmd_str done!"
        else
            echo "error: " $?
        fi
    fi
done < $serverlist_file

使用方法:

1. 新建一個文件host_file_list,文件中爲服務器的地址,每個一行;

2. 保存上面shell 腳本, 如保存爲 allcmd.sh,注意使用 chmod +x allcmd.sh 使之成爲可執行腳本;

3. 運行 allcmd.sh  host_file_list md 即可, host_file_list 是第1步的文件名(記得和 allcmd.sh 放在相同目錄下), cmd 就是要執行的命令,用單引號包起來,例如:刪除/home/nuaazdh/下面的一個 tmp.txt 文件:  allcmd.sh host_file_list  'rm /home/nuaazdh/tmp.txt' 

4. done!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章