dnsmasq通过Host文件去除广告
通过host去除广告是比较原始的一种方式,类似于“从源头阻断这样一个思想”,我们会看到广告,是因为加载了广告的地址,那么我们只要找出属于广告的地址把它屏蔽掉,不就看不到广告了吗。而dnsmasq这一款具有dns功能的软件就能够做到这些,它把被界定为广告的网页的域名或者IP地址强制解析到localhost
也就是127.0.0.1
,这样的话我们就加载不出广告来。这一做法的好处是不怎么吃资源,但是坏处也很明显。阻断的很生硬。这个生硬感就好像墙上有个贴纸就直接把墙的那一块直接挖掉一样。不如PC端的adblock来的效果好,但是胜在方便。
以下我目前在使用的一个脚本,它可以生成去除了广告的hosts文件并写入dnsmasq所设置的dns缓存文件中,每次在dnsmasq启动后都会优先读取缓存文件(前提是你已经设置好了),这样的话即使解析到了正确地址也会强制解析到127.0.0.1
,达到一种类似于DNS劫持的效果。
仅个人记录,酌情参考。
#!/bin/bash
TMP_ADBLOCK=/tmp/dnsmasq_adblock_unsorted
ADBLOCK=/etc/dnsmasq.d/adblock.conf
TMP_HOST=/tmp/dnsmasq_adblock_hosts
TMP_HOST_SWP=/tmp/dnsmasq_adblock_hosts_swp
HOST=/etc/dnsmasq_addn_hosts
if [ -f ${TMP_HOST} ]
then
rm ${TMP_HOST} -rf
elif [ -f ${TMP_HOST_SWAP} ]
then
rm ${TMP_HOST_SWAP} -rf
fi
rm /etc/dnsmasq.d/adblock.conf
for URL in \
"https://easylist-downloads.adblockplus.org/easylistchina+easylist.txt" \
"https://easylist.to/easylist/easylist.txt"
do
wget -4 --no-check-certificate -qO - "${URL}" | grep ^\|\|[^\*]*\^$ |sed -e 's:||:address\=\/:' -e 's:\^:/127\.0\.0\.1:' >> ${TMP_ADBLOCK}
#wget -4 --no-check-certificate -qO- "${URL}" | grep -v -e "^#" -e "^\s*$" -e "localhost" -e "^;" -e "^@" -e "^:" -e "^[a-zA-Z]" \
#| sed -E -e "s/#.*$//" -e "s/[[:space:]]*//g" -e "/^$/d" \
#-e "s/^127.0.0.1/server=\/./" -e "s/0.0.0.0/server=\/./" -e "/^[0-9].*$/d" -e "s/$/\/127.0.0.0/" \
#| tr -d "\r" >> ${TMP_ADBLOCK}
done
sort ${TMP_ADBLOCK} | uniq > ${ADBLOCK}
rm -r ${TMP_ADBLOCK}
cat /etc/hosts > ${HOST}
for URL_H in \
"https://raw.githubusercontent.com/vokins/yhosts/master/hosts.txt" \
"http://www.malwaredomainlist.com/hostslist/hosts.txt" \
"https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"
do
wget --no-check-certificate -qO - ${URL_H} >> ${TMP_HOST}
done
sed -i s/0\.0\.0\.0/127\.0\.0\.1/g ${TMP_HOST}
egrep ^127.0.0.1 ${TMP_HOST} | egrep -v *paypal* | egrep -v tv.sohu.com | sort | uniq > ${TMP_HOST_SWP}
dos2unix ${TMP_HOST_SWP}
#合并hosts缓存
sort ${TMP_HOST_SWP} | uniq > ${HOST}
#sed -i '/*paypal*/d' /etc/dnsmasq_addn_hosts
# 删除hosts缓存
rm -r ${TMP_HOST}
rm -r ${TMP_HOST_SWP}
systemctl restart dnsmasq