update_hosts.sh 1.9 KB

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