#! /bin/sh
# 因为数组在shell函数中传递实在蛋疼,尤为是还包括其余参数时,因此干脆变量所有用全局变量
random_v=$RANDOM
trap "rm -f /tmp/$$.$random_v.http_code.out" EXIT
function curl_url(){
url_line="http://$url_host/$line"
/usr/bin/curl -s -o /dev/null --connect-timeout $time_out -m $time_out -w %{http_code} $url_line > /tmp/$$.$random_v.http_code.out
return $?
}
function deal_url(){
error_status=7
n=0
max_fail=30
ips_length=${#ips[@]}
url_host=${ips[$n]}
cat $urls_txt | while read line;
do
curl_url
if [ $? -eq $error_status ];then
echo "当前IP:${url_host}没法连通,尝试下一个IP链接$line"
if [ $n -lt $max_fail ];then
n=$(( $n+1 ))
visit_ip=$(( $n % $ips_length )) #应该使用哪个ips数组下标
url_host=${ips[$visit_ip]}
curl_url
while [ $? -eq $error_status ]
do
echo "当前IP:${url_host}没法连通,尝试下一个IP链接$line"
n=$(( $n+1 ))
visit_ip=$(( $n % $ips_length ))
url_host=${ips[$visit_ip]}
if [ $n -ge $max_fail ];then
echo "尝试次数达到最大值,放弃链接"
exit
fi
curl_url
done
else
echo "尝试次数达到最大值,放弃链接"
exit
fi
fi
echo "经过IP:${url_host}完成对${line}的访问,返回状态为$(cat /tmp/$$.$random_v.http_code.out)"
done
}
work_dir=''
cd $work_dir
ips=( '10.12.12.11:8090' '10.12.12.12:8080' '10.12.12.13:8080' '10.12.12.14:8080' '10.12.12.15:8080' )
urls_txt="$work_dir/url.list"
time_out=5
deal_url
一次输出可能以下所示:
当前IP:10.120.12.11:8090没法连通,尝试下一个IP链接/
当前IP:10.120.12.12:8080没法连通,尝试下一个IP链接/
当前IP:10.120.12.13:8080没法连通,尝试下一个IP链接/
经过IP:10.120.12.14:8080完成对/的访问,返回状态为200
经过IP:10.120.12.14:8080完成对/a.html的访问,返回状态为200
经过IP:10.120.12.14:8080完成对/b.html的访问,返回状态为200
经过IP:10.120.12.14:8080完成对/c.html的访问,返回状态为200
"""
此时14中断
"""
当前IP:10.120.12.14:8080没法连通,尝试下一个IP链接/
经过IP:10.120.12.15:8080完成对/d.html的访问,返回状态为200
经过IP:10.120.12.15:8080完成对/e.html的访问,返回状态为200
经过IP:10.120.12.15:8080完成对/f.html的访问,返回状态为200
经过IP:10.120.12.15:8080完成对/g.html的访问,返回状态为200
经过IP:10.120.12.15:8080完成对/h.html的访问,返回状态为200
""""
此时15中断,13恢复
"""
当前IP:10.120.12.15:8080没法连通,尝试下一个IP链接/
当前IP:10.120.12.11:8090没法连通,尝试下一个IP链接/
当前IP:10.120.12.12:8080没法连通,尝试下一个IP链接/ 经过IP:10.120.12.13:8080完成对/i.html的访问,返回状态为200 经过IP:10.120.12.13:8080完成对/j.html的访问,返回状态为200 最大没法连通次数由max_fail变量控制,达到最大失败次数,脚本终止