Auto-updating hosts file using cronjob
In this post I will show you how you can easily set your hosts file in “/etc/hosts” to automatically update with the help of cron.
What is cron?
cron is the time-based job scheduler in Unix-like computer operating systems. cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times, dates or intervals. It is commonly used to automate system maintenance or administration.
Installing Cron on Your System
You can use package manager on the distro of your choice to install cron.
For Ubuntu/Debian based distros:
sudo apt install cron
For Arch Linux:
sudo pacman -S cronie
sudo dnf install cronie
Enabling cron daemon to run on boot
sudo systemctl enable cronie
For Ubuntu/Debian based:
sudo systemctl enable cron
The basic format for a crontab is:
minute hour day_of_month month day_of_week command
minutevalues can be from 0 to 59.
hourvalues can be from 0 to 23.
day_of_monthvalues can be from 1 to 31.
monthvalues can be from 1 to 12.
day_of_weekvalues can be from 0 to 6, with 0 denoting Sunday.
Now if we want to run a command every Monday at 5:00pm we use:
0 17 * * 1 command ( 17 is 5pm in 24 hour clock format ).
You can use cron.help for more help to understand the syntax.
Setting up your cronjob using crontab
We will use sudo for this since it requires root privilege to edit “/etc/hosts” file.
sudo crontab -e
I personally use StevenBlack's hosts file to block advertisements and malicious domains so I would use:
0 17 * * 1 curl https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts > /etc/hosts
The above command will fetch the updated hosts file every Monday at 5:00pm using curl from the above URL and overwrite the current “/etc/hosts” file.
After adding the above command, save and exit crontab editor.
~ spignelon | Ujjawal Saini