10
November
2022
17:00

Script for removing advertisements from web pages based on the hosts file

10 November 2022 17:00

On my smartphone I use a program to block ads AdAway. For a Linux computer, I wrote a short script in sh to create a hosts file from 4 sources (3 of which are downloaded from www, one of which is my own).

The essence of the script is loading special hosts from url and file to block ads, then combining them into a single file and copying them over the /etc/hosts file.

I am attaching the script in a ZIP archive (updated 01/16/2025).

gethosts.zip

Before running the script, you need to make a backup copy of the /etc/hosts file.

The advantage of the script is that it can be run only occasionally; frequent launch is contraindicated.
After replacing the hosts file, not only advertising is removed, but also the time it takes to load web pages is reduced.

Addition from 01/15/2025:

For ad blocking to work correctly, there should be no services running on the local PC that listen on ports 80 and 443.

Perform check. You can check that no services are running on ports 80 and 443 with the command:
sudo netstat -tlpn | grep -E ':80|:443'

If Apache2 is installed, you should change its port 80 to another, for example, 82, in the files:

  • /etc/apache2/ports.conf
  • /etc/apache2/sites-enabled/000-default.conf
    After editing the configuration files, you need to restart the web server:sudo service apache2 restart

Update from 01/23/2025:

To clear records that are in the cache of the local DNS server of the resolved service after updating the hosts file, I recommend resetting the local DNS cache using the command:
sudo resolvectl flush-caches
Made the appropriate change to the gethosts.sh command file.