Guest User

Adblock from /etc/hosts - mac or linux

a guest
Aug 14th, 2014
775
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.17 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # If this is our first run, save a copy of the system's original hosts file and set to read-only for safety
  4. if [ ! -f ~/.hosts-system ]
  5. then
  6.  echo "Saving copy of system's original hosts file..."
  7.  cp /etc/hosts ~/.hosts-system
  8.  chmod 444 ~/.hosts-system
  9. fi
  10.  
  11. # Perform work in temporary files
  12. temphosts1=~/.temphosts1
  13. temphosts2=~/.temphosts2
  14.  
  15. # Obtain various hosts files and merge into one
  16. echo "Downloading ad-blocking hosts files..."
  17. wget -nv -O - http://winhelp2002.mvps.org/hosts.txt >> "$temphosts1"
  18. wget -nv -O - http://hosts-file.net/ad_servers.asp >> "$temphosts1"
  19. wget -nv -O - http://someonewhocares.org/hosts/hosts >> "$temphosts1"
  20. wget -nv -O - "http://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&mimetype=plaintext" >> "$temphosts1"
  21.  
  22. # Do some work on the file:
  23. # 1. Remove MS-DOS carriage returns
  24. # 2. Delete all lines that don't begin with 127.0.0.1
  25. # 3. Delete any lines containing the word localhost because we'll obtain that from the original hosts file
  26. # 4. Replace 127.0.0.1 with 0.0.0.0 because then we don't have to wait for the resolver to fail
  27. # 5. Scrunch extraneous spaces separating address from name into a single tab
  28. # 6. Delete any comments on lines
  29. # 7. Clean up leftover trailing blanks
  30. # Pass all this through sort with the unique flag to remove duplicates and save the result
  31. echo "Parsing, cleaning, de-duplicating, sorting..."
  32. sed -e 's/\r//' -e '/^127.0.0.1/!d' -e '/localhost/d' -e 's/127.0.0.1/0.0.0.0/' -e 's/ \+/\t/' -e 's/#.*$//' -e 's/[ \t]*$//' < "$temphosts1" | sort -u > "$temphosts2"
  33.  
  34. # Combine system hosts with adblocks
  35. echo Merging with original system hosts...
  36. echo -e "\n# Ad blocking hosts generated" "$date" | cat ~/.hosts-system - "$temphosts2" > ~/.hosts-block
  37.  
  38. # Clean up temp files and remind user to copy new file
  39. echo "Cleaning up..."
  40. rm "$temphosts1" "$temphosts2"
  41. echo "Done."
  42. echo
  43. echo "Copy ad-blocking hosts file with this command:"
  44. echo "sudo cp ~/.hosts-block /etc/hosts"
  45. echo
  46. echo "You can always restore your original hosts file with this command:"
  47. echo "sudo cp ~/.hosts-system /etc/hosts"
  48. echo "so don't delete that file! (It's saved read-only for your protection.)"
Advertisement
Add Comment
Please, Sign In to add comment