Skip to content

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?

0 points10 comments
Open on Reddit
About this post
Posted
Archived
Score
0 · 100% up
Kind
Text
ID
8v09mt

Author

7
posts
12
comments
0
media
View profile

10 comments

I'd go with crontab -u root -e which would run your cron job as root.

Seems appropriate for modifying the hosts file.

7 points

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.

7 points

But why though?

1 points
unknown author

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.

2 points

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.

3 points

Thanks a lot! Most of the times I'm missing the simplest solutions :)

1 points

Keyboard shortcuts

Move and act

jork
Next / previous post or comment
Enteroro
Open the post
f
Open the media viewer
s
Save
h
Hide (the toast has Undo)
Tab
Right after an action: the toast's Undo
x
Collapse the comment
v
Next layout: cards, compact, grid

Go to

/
Search
gthenh
Home
gthena
All
gthens
Subreddits
gthenl
Library
?
This list
Esc
Close a menu or this list

In the viewer

←or→
Previous / next file
↑or↓
Previous / next post
korj
Previous / next post
Space
Play / pause
m
Mute
z
Zoom
s
Save
o
Open the post (on its own page: back to it)
Esc
Close

Keys do nothing while you type in a box.