How to Run Sudo Command Without Password.

How To Run Sudo Command Without Password.

The sudo command allows trusted users to run programs as another user, by default the root user. If you spend a lot of time on the command line, sudo is one of the commands you will use on a frequent basis.

Adding User to the Sudoers File

The sudoers file contains information that determines a user’s and group’s sudo privileges.

You can configure the user sudo access by modifying the sudoers file or by adding a configuration file to the /etc/sudoers.d directory. The files created inside this directory will be included in the sudoers file.

Before making any changes, it is a good idea to back up the current file:

sudo cp /etc/sudoers{,.backup_$(date +%Y%m%d)}

The date command will append the current date to the backup file name.

Open the /etc/sudoers file with the visudo command:

sudo visudo

When making changes to the sudoers file always use visudo. This command checks the file after editing, and if there is a syntax error it will not save the changes. If you open the file with a text editor, a syntax error will result in losing the sudo access.

On most systems, the visudo command opens the /etc/sudoers file with the vim text editor. If you don’t have experience with vim you can use another text editor. For example, to change the editor to GNU nano you would run:

sudo EDITOR=nano visudo

Scroll down to the end of the file and add the following line that will allow the user “nexonhost” to run any command with sudo without being asked for a password:

nexonhost  ALL=(ALL) NOPASSWD:ALL

Do not forget to change “nexonhost” with the username you want to grant access to.

If you want to allow the user to run only specific commands without entering password specify the commands after the NOPASSWD keyword.

For example, to allow only the mkdir and mv commands you would use:

nexonhost ALL=(ALL) NOPASSWD:/bin/mkdir,/bin/mv

Once done, save the file and exit the editor .

Using /etc/sudoers.d

Instead of editing the sudoers file you can create a new file with the authorization rules in the /etc/sudoers.d directory. This approach makes the management of the sudo privileges more maintainable.

Open your text editor and create the file:

sudo nano /etc/sudoers.d/nexonhost

You can name the file as you want, but usually, it is a good idea to use the user name as the name of the file.

/etc/sudoers.d/nexonhost

Add the same rule as you would add to the sudoers file:

nexonhost  ALL=(ALL) NOPASSWD:ALL

 

Finally, save the file and close the editor.

Conclusion

We have shown you how to edit the /etc/sudoers so you can run sudo commands without entering a password. This is useful when you have scripts where a non-root user needs to execute administrative tasks.