How to enable a non root user to substitute the file /etc/hosts by cp command, without the sudo command?

On my lubuntu 22.04 I need to change the file /etc/hosts. To do that I would to execute the command:

> /usr/bin/cp /path/to/new_hosts /etc/hosts

by a non root user without the sudo command. To do this I have add the following line to the file /etc/sudoers:

<username> ALL = (root) NOPASSWD: /usr/bin/cp /path/to/new_hosts /etc/hosts

I have checked the correct syntax of /etc/sudoers by the command:

> sudo visudo -c /etc/sudoers

The output of the command is:

/etc/sudoers: parsed OK
/etc/sudoers.d/10-installer: parsed OK
/etc/sudoers.d/README: parsed OK
/etc/sudoers.d/kdesu-sudoers: parsed OK

The message /etc/sudoers: parsed OK assures me that the syntax of /etc/sudoers is correct.

When I execute the cp command by a terminal the result is Permission denied.

Where is the mistake?

Asked By: frankfalse


You will need to run your command with sudo:

sudo /usr/bin/cp /path/to/new_hosts /etc/hosts

Otherwise, the sudoers file won’t be considered.

Answered By: pLumo