permission denied when modifying /etc/hosts by script
I have a script that removes ads by adding addresses to /etc/hosts file. When I execute it, the script needs to modify the /etc/hosts file, which is owned by root.
I could run the script using the root profile, but my idea is to run this file once a month using cron to update the list of hosts to block.
I could change ownership to /etc/hosts file, but I think it's not a good idea.
Any suggestions?
About this post
- Posted
- Archived
- Score
- 0 · 100% up
- Kind
- Text
- ID
- 8v09mt
10 comments
I'd go with
crontab -u root -ewhich would run your cron job as root.Seems appropriate for modifying the hosts file.
Does this solution require to type root passwd everytime the task will be executed?
Nope
Frankly, I say don't bother with cron. Make a systemd service that runs your script and setup a systemd timer. I have completely moved away from cron.
But why though?
Personal preference mostly. There's also the advantage of all your management, maintenance and logging being done in one place.
Also, I think a lot of people don't really understand systemd very well, and I think knowing systemd is more useful than knowing cron since it can do so much more. To use cron, you write a script and tell cron to run it. To use a systemd service and timer you need to write the script, write a service and write a timer. You learn a lot more, and those things you learn apply to many other parts of system maintenance. If you do it enough, you'll probably run in to trouble and get better at using the systemd journal too. I honestly just think it's a win/win.
But again... that's mostly personal preference.
Three ideas from simple to cumbersome/roundabout.
Run the cron tab as root. Does anything speak against that? Would be very simple.
You could add a no password Sudo entry for just this one command
Otherwise you could make the script owned by root but executable by others and set the setuid flag. But that's usually not best practice.
Thanks a lot! Most of the times I'm missing the simplest solutions :)
No, as it directly runs as root, there is no sudo needed.
buildhosts from the AUR has solved this well.