2011年9月30日

[Mac] Lion 下批次更新 hosts 檔的 shell script

2011.11.28 以下 shell script 包裝成 app 囉: Lion 上找主機 IP 並自動更新 hosts 的 app 


用 Air 一段時間了,在公司最頭痛的問題就是很多測試機都只有WINS認識,
雖然可以用 finder 透過 smb://servername 的方式存取檔案,
但對於一個開發網頁程式的工作者來說,相當的痛苦,
因為沒辦法直接 http://servername 進行測試,
在 linux 下可以透過修改 nsswitch 的方式處理,但 Lion 中就不知道該怎麼做了,
最後索性直接改 /private/etc/hosts ,將常用的 Server 與 ip 加進去,
畢竟Server的IP也不是那麼常更換的,
但遇到另一個問題是每次有新的機器,
都要手動下
smbutil lookup servername
再去 /private/etc/hosts 修改內容,過程一整個很繁雜,
於是就寫了幾支 shell script
要新增一台新的機器就在 command line 下

sudo ./hiWins.add.sh SERVERNAME

要從機器清單中匯入就在 command line 下

sudo ./hiWins.import.sh < YOUR_SERVERNAME_LIST_FILE

使用前記得要先備分 /private/etc/hosts ,以免發生意外 :p


(1) findip.sh

#!/bin/bash

# [功能]
# 利用 smbutil lookup 尋找 server 的 ip
# [使用方式]
# echo hrispd-t | ./findip.sh

function getIp(){
    IP=$(smbutil lookup "$1" |grep -i "IP Address" |sed "s/IP.*: //")
}

while read LINE; do             #讀取stdin
    getIp ${LINE}               #取得IP
    if [ ${#IP} != 0 ]; then
        printf "%s\t%s" $IP ${LINE}
    fi
done

(2) hiWins.update.sh
#!/bin/bash

# [功能]
# 更新 /private/etc/hosts 中所有 server 的 ip,輸出並不會直接回寫 hosts 檔,單純 echo 出來
# [使用方式]
# ./hiWins.update.sh SERVERNAME

#讀取原始的 hosts 檔
exec < "/etc/hosts"

#標記是否有相同的ServerName,若無則一律新增
FOUND="N"
result=
while read LINE; do
    #取第一個字
    C1=$(echo ${LINE} | cut -c1-1)
    if [ $C1 != "#" ]; then
        #將空白或tab分隔的字串拆成陣列
        declare -a Array=($LINE)
        if [ "$1" == "${Array[1]}" ]; then
            FOUND="Y"
            out=$(echo "$1" | ./findip.sh)
            if [ ${#out} != 0 ]; then
                printf "%s\n" "$out"
            else
                printf "%s\n" "${LINE}"
            fi
        else
            printf "%s\n" "${LINE}"
        fi
    else
        printf "%s\n" "${LINE}"
    fi
done

if [ $FOUND == "N" ]; then
    out=$(echo "$1" | ./findip.sh)
    if [ ${#out} != 0 ]; then
        printf "%s\n" "$out"
    fi
fi

(3) hiWins.add.sh
#!/bin/bash

# [功能]
# 更新 /private/etc/hosts 中所有 server 的 ip ,並加入指定的 server ip(若已存在則純更新)
# [使用方式]
# ./hiWins.add.sh SERVERNAME
# [注意事項]
# 需要 sudo 權限

if [ $# == 0 ]; then
    echo "Input Server Name please."
else
    out=$(./hiWins.update.sh "$1")
    
    printf "%s\n" "$out" > out.hosts
    
    cp ./out.hosts /etc/hosts
fi

(4) hiWins.import.sh
#!/bin/bash

# [功能]
# 依 YOUR_SERVERNAME_LIST 檔案中,定的 SERVERNAME 清單,
# 逐筆呼叫 hiWins.add.sh 更新(或加入) /private/etc/hosts
# [使用方式]
# ./hiWins.imports.sh < YOUR_SERVERNAME_LIST
# [注意事項]
# 需要 sudo 權限

while read LINE; do             #讀取stdin
    if [ ${#LINE} != 0 ]; then
        ./hiWins.add.sh ${LINE}
    fi
done