運維之自動化SHELL腳本

由於最近新工作忙碌的原因沒有時間寫個博文,今天抽出了點時間把在以前公司的自動化的一個小腳本給大家分享一下:

歡迎大家吐槽:

腳本運行的基礎:

1:一個機器爲主和所有你要管理的機器建立信任關係(ssh方式的網上有很多建立的方法我在這裏就不說了);

2:最好有個nginx服務配置一個支持下載配置文件的文件夾,(可以放一些需要分發的軟件包);

3:按照腳本的運行必要條件在用戶的家目錄建立【.lshost/serverlist】,serverlis可以和公司的資產管理平臺結合;

腳本代碼:



#!/bin/bash
exit_with_help()
{
    echo "Usage: lshost [OPTION] PATTERN
        Options:
            -u 每臺機器發送一條命令;
            -c 遠程執行的命令行;
            -e 擴展模式,將遠程命令中的\${flag}字符串替換爲服務器標誌(eg:jw_1)
            -s 不更新服務器列表
            -h 打印本幫助信息;
        eg:     lshost -u -c 'ls' 'jw_.*'
        eg2:    lshost -e -c 'grep '\''jw'\'' /home/jw'  'wsw_1'
        "
    exit 0
}
#默認參數
uniq="false"
expand="false"
cmd=""
pattern=""
static="false"
while getopts ":usec:h" optname
    do
        case "$optname" in
            "u")
                uniq="true";
                ;;
            "c")
                cmd="$OPTARG"
                ;;
            "e")
                expand="true"
                ;;
            "s")
                static="true";
                ;;
            "?")
                echo "Unkown option $OPTARG"
                exit_with_help;
                ;;
            ":")
                echo "No arugument value for option $OPTARG"
                exit_with_help;
                ;;
            "h")
                exit_with_help;
                ;;
            "*")
                echo "Unsupported option [$optname]"
                exit_with_help;
                ;;
        esac
    done
pattern=${@:$OPTIND}
if [ -z "$pattern" ];
then
    echo "Pattern must be given"
    exit_with_help;
fi
if [ -f ~/.lshost/serverlist  -a $static == "false" ];
then
    rm -f ~/.lshost/serverlist
   wget -q 'http://{IP}/serverlist' -P ~/.lshost
fi
servers=`grep -E "$pattern" ~/.lshost/serverlist `
if [ $uniq == "true" ];
then
    servers=`echo $servers|awk -F '@' 'BEGIN{RS=" "}{dict[$2]=$1}END{for(i in dict){print dict[i]"@"i}}'`
fi
if [ -z "$cmd" ];
then
    for i in $servers;
    do
        echo $i
    done
else
    for i in $servers;
    do
        host=`echo $i |awk -F'@' '{print $2}'`
        server=`echo $i |awk -F'@' '{print $1}'`
        if [ $expand == "true" ];
        then
            real_cmd=`echo "${cmd}"|sed 's/${flag}/'${server}'/g'`
        else
            real_cmd=$cmd
        fi
        echo -n $i":    "
        echo -e "\e[0;34;1m[$real_cmd]\e[0m"
        ssh -p 22 root@$host   "$real_cmd" &>~/.lshost/stdout
        if [ $?  -ne 0 ];
        then
            echo -e "\e[0;31;1m[FAIL]\e[0m";
        else
            echo -e "\e[0;32;1m[OK]\e[0m";
        fi
        cat ~/.lshost/stdout
        echo "=============================================="
    done
fi


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