這是一個 shell 指令碼,所以首先你需要安裝一個基本的 Cygwin 環境,當然還有 curl。
原理很簡單,先從 cygwin.com 下載最新的 mirrors.lst 鏡像列表,簡單處理一下後,利用 curl 以此檢測每個網站的連線速度,並將結果記錄下來,最後再排個序,顯示出最快的幾個網站。
在使用的過程中,我發現檢測到的最快的 mirror,實際上使用速度並不一定是最快的,這可能和伺服器有關係,畢竟 curl 檢測的時間只是讀取 mirror 首頁的時間。不過每個 mirror 一般都有兩組伺服器——http & ftp,如果其中一個速度不怎麼樣,那麼可以選擇另外一個試試看。
 複製代碼 代碼如下:
 
#!/bin/sh
 
 
 
# cygwin-mirrors.sh
 
# 該指令碼用於尋找 Cygwin 的最快鏡像
 
 
 
timeout=5           # 逾時時間
 
mirrors_count=5     # 顯示最快的幾個鏡像
 
PROG=`basename $0`  # 程式名稱
 
 
 
## 顯示 usage
 
_usage() {
 
    echo "Usage: ${PROG} [-t <timeout>] [-p <mirrors_count>] [-h]"
 
    exit
 
}
 
 
 
## 檢查參數並賦值
 
_assign() {
 
    if [ "$1" == "timeout" -o "$1" == "mirrors_count" ]; then
 
        if [[ "$2" =~ ^[[:digit:]]+$ ]]; then
 
            let $1=$2
 
        else
 
            echo "$1 should be a number"
 
            exit 1
 
        fi
 
    fi
 
}
 
 
 
## 處理參數
 
while getopts ":t:p:h-:" optval
 
do
 
    case "$optval" in
 
        t)   _assign timeout ${OPTARG} ;;
 
        p)   _assign mirrors_count ${OPTARG} ;;
 
        h)   _usage ;;
 
        "-") echo "Unknown option: '--${OPTARG}'" >&2;            _usage ;;
 
        ":") echo "Option '-${OPTARG}' requires an argument" >&2; _usage ;;
 
        "?") echo "Unknown option: '-${OPTARG}'" >&2;             _usage ;;
 
        ## Should not occur
 
        *)   echo "Unknown error while processing options" >&2;   _usage ;;
 
    esac
 
done
 
shift $(expr ${OPTIND} - 1)
 
 
 
## 檢查使用者是否安裝了 curl
 
CURL=`which curl 2> /dev/null`
 
[ -z "$CURL" ] && (echo "Need to install the curl package."; exit 1)
 
 
 
## 讀取鏡像網站
 
mirrors=`curl --silent http://cygwin.com/mirrors.lst | cut -d';' -f1`
 
 
 
## 使用 CURL 依次檢測時間
 
results=''
 
for mirror in $mirrors; do
 
    echo -n "Checking ${mirror} ... "
 
    time=`curl -m $timeout -s -o /dev/null -w %{time_total} $mirror`
 
    if [ "$time" = "0.000" ]; then
 
        echo -e "\e[31mfail\e[0m"
 
    else
 
        echo -e "\e[32m$time\e[0m"
 
        results="${results}\e[32m${time}\e[0m - ${mirror}\n"
 
    fi
 
done
 
 
 
echo -e "\n檢測結果:"
 
echo -e $results | sort -n | sed '1d' | head -$mirrors_count
 
 
 
# vim: set expandtab tabstop=4 shiftwidth=4: