update_hosts.sh 1.8 KB

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