update_hosts.sh 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #!/bin/bash
  2. if [ $# -ne 2 ]; then
  3. echo -e "Usage:"
  4. echo -e " $ ./update_hosts.sh hosts new_hosts\n"
  5. exit 1
  6. fi
  7. hosts_file=$1
  8. new_hosts_file=$2
  9. if [ ! -f "$hosts_file" ]; then
  10. echo -e $1" doesn't exists, plz retry!\n"
  11. exit 1
  12. fi
  13. if [ -f $new_hosts_file ]; then
  14. new_hosts_file=${new_hosts_file}".new"
  15. printf "" > $new_hosts_file
  16. fi
  17. he_net="2001:470:20::2"
  18. lax1_he_net="2001:470:0:9d::2"
  19. google_a="2001:4860:4860::8888"
  20. google_b="2001:4860:4860::8844"
  21. jp="203.112.2.4"
  22. dns=$lax1_he_net
  23. blackhole=(
  24. '10::2222'
  25. '101::1234'
  26. '21:2::2'
  27. '2001::212'
  28. '2001:da8:112::21ae'
  29. '2003:ff:1:2:3:4:5fff:6'
  30. '2003:ff:1:2:3:4:5fff:7'
  31. '2003:ff:1:2:3:4:5fff:8'
  32. '2003:ff:1:2:3:4:5fff:9'
  33. '2003:ff:1:2:3:4:5fff:10'
  34. '2003:ff:1:2:3:4:5fff:11'
  35. '2003:ff:1:2:3:4:5fff:12'
  36. '2123::3e12')
  37. num=1
  38. while read line
  39. do
  40. {
  41. #delete CR
  42. line=$(printf "$line"|tr -d '\r')
  43. #printf "$line"|od -tx1
  44. if [[ $line == "" ]]; then
  45. printf "\r\n" >> $new_hosts_file
  46. continue
  47. fi
  48. if [ "${line:0:2}" == "##" ]; then
  49. printf "$line\r\n" >> $new_hosts_file
  50. continue
  51. fi
  52. if [ "${line:0:1}" == "#" ]; then
  53. line=${line#'#'}
  54. fi
  55. url=$(printf "$line"|cut -d" " -f2)
  56. result=$(nslookup -querytype=AAAA "$url" "$dns"|grep 'AAAA address'|head -1)
  57. name=$(printf "$result"|cut -f1)
  58. ip=$(printf "$result"|cut -d' ' -f4)
  59. for var in "${blackhole[@]}"; do
  60. if [[ $ip == "$var" && $ip != "" ]]; then
  61. ip=$(nslookup -vc -querytype=AAAA "$url" "$dns"|grep 'AAAA address'|cut -d' ' -f4)
  62. break
  63. fi
  64. done
  65. if [[ $ip == "" ]]; then
  66. printf "#$line\r\n" >> $new_hosts_file
  67. continue
  68. fi
  69. if [[ $name != $url && $name != "" ]]; then
  70. url=${url}" #"${name}
  71. fi
  72. printf "$ip $url\r\n" >> $new_hosts_file
  73. #print log to stdio
  74. echo "$num" "$ip" "$url"
  75. num=$((num+1))
  76. }
  77. done < $hosts_file
  78. exit 0