Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to make a productivity suite for myself. My first goal is to block Facebook, Gmail and Stackexchange from 0900 to 1600.

As of now, I have edited my /etc/hosts and added www.facebook.com and similar ones for gmail and stackexchange.

But I am a little confused about how to include the blocking duration in my script.

What I thought is having 2 different files (hosts_allow, hosts_block) and then cp hosts_allow hosts or cp hosts_block hosts depending upon time but then this would need to be put in an infinite loop or something which I'm not really sure is the best way of approaching the problem.

Any clues?

share|improve this question
But... But StackExchange improves productivity! :( – kba Jun 24 '12 at 16:07
@KristianBorupAntonsen, not when I'm trying to learn Multivariable Calculus :P – user14517 Jun 24 '12 at 16:22
math.SE is always helpful! :) – kba Jun 24 '12 at 17:01
up vote 17 down vote accepted

Use cron.

Say crontab -e as root — or sudo crontab -e if you have sudo set up — and put the following in the file that comes up in the text editor:

0  9 * * * cp /etc/hosts_worktime /etc/hosts
0 16 * * * cp /etc/hosts_playtime /etc/hosts

This says that on the zeroth minute of the 9th and 16th hours of every day of the month, overwrite /etc/hosts using the shell commands given.

You might actually want something a little more complicated:

0  9 * * 1-5 cp /etc/hosts_worktime /etc/hosts
0 16 * * 1-5 cp /etc/hosts_playtime /etc/hosts

That one change — putting 1-5 in the fifth position — says the change between work and play time happens only on Monday through Friday.

Say man 5 crontab to get a full explanation of what all you can do in a crontab file.

By the way, I changed the names of your hosts files above, because hosts_allow is too close to hosts.allow, used by TCP Wrappers.

share|improve this answer
+1 for changing the filename to reduce tcpwrappers similarity. Also, I'd suggest ln -f, not cp — it's too easy to forget that any changes to /etc/hosts get deleted twice a day, and any software that modifies /etc/hosts won't know anyway. With ln, you'll at least have one persistent copy of the changes (whichever one is active). – Alexios Jun 24 '12 at 8:28
@Alexios: No argument there. – Warren Young Jun 24 '12 at 8:30

If you have 2 different hosts file, you can simply schedule a cron job to overwrite the file in /etc at a specific hour during the day.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.