Can I edit hosts without sudo?
You can, but it's a bad idea. The whole point of the permissions system is preventing non-privileged users and attackers from doing stuff like writing to system files, running hostile code, and so on. By far the best thing to do is just keep on using sudo
when you need to edit system files. That's best practice and it's the reason we have sudo
I don't recommend either of the following methods, but they are safer than the dreaded chmod 777
. You could, for example, change the group ownership of /etc/hosts
and give the group write permission:
sudo addgroup editors #make a new group
sudo adduser $USER editors #add yourself to it
sudo chown :editors /etc/hosts #change the group ownership
sudo chmod 664 /etc/hosts #give the group write permission
You would now be able to edit the file without sudo
. Or, you could use ACLs, if you have the acl
package (installed for sure in 15.04 and later)
sudo setfacl -m $USER:rw /etc/hosts
But, again, I don't recommend either of those actions. Just use sudo
.
I wouldn't adjust the permissions of any system related file
What you can do is make a basic script
#!/bin/bash
sudo nano /etc/hosts
Call it whatever you want, for example, edithosts.sh and put it in a scripts folder inside your home folder.
chmod 700 /path/to/script/file/edithosts.sh
This will prevent unauthorised reading or writing to the file because ss TripeHound said, the contents of this file are now run with root permissions with no password.
Then add the following line to /etc/sudoers
tom ALL = (root) NOPASSWD: /path/to/script/file/edithosts.sh
That will allow you to sudo sh /path/to/script/file/edithosts.sh
without having to enter a password
Recommended solution
As @paul pointed out in the comments, sudoedit
could be a better solution.
tom ALL = (root) NOPASSWD: sudoedit /etc/hosts
Because this solely allows editing of /etc/hosts
and doesn't leave you running an elevated text editor