MacOS – Keyboard Maestro: How to write to /etc/hosts file

hostskeyboardmacos

So I have been using an app called Self Control to block certain sites globally on my machine so I'm not distracted when I work. The method this program uses is edit your /etc/hosts file and redirect your blacklist of sites (facebook.com, youtube.com, etc) to 0.0.0.0. This is cool, but I was thinking that I could make a Keyboard Maestro macro for this instead.

I'm new to Keyboard Maestro and it's a bit intimidating to get into. Does anyone have any recommendations for creating a macro that will open, append, save, and then close your system's hosts file?

Best Answer

Have Keyboard Maestro run an AppleScript, which runs a shell script, which changes your hosts file:

do shell script "cp ~/hosts.tmp /etc/hosts" with administrator privileges

Simple! :)

The "with administrator privileges" part will cause it to prompt you for the sudo password.