Unix / Linux: Run Sudo Without Password

Objective: Run sudo command without a password on Unix or Linux systems.

Some times, you will need to run sudo without any password, especially if you are running a cron job or a script. This can be achieved by modifying the /etc/sudoers file or by adding the sudo configuration to a file in the /etc/sudoers.d directory.

The recommended way is not to modify the /etc/sudoers file but to create sudo security policy files within the /etc/sudoers.d directory. If you notice the last line of the /etc/sudoers file, it has a line to include the directory /etc/sudoers.d. sudo will read each file in /etc/sudoers.d, skipping file names that end in ~ or contain a . character to avoid causing problems with package manager or editor temporary/backup files.

To allow a user to run all commands under sudo without a password, use the following policy. You can place this policy in a file called nopassword under the /etc/sudoers.d directory.

In the above entry, the first word defines the user affected by the policy. In this case, the username is ibrahim. The second field ALL, indicates allowed hostnames. This field is usually left as ALL by default on standard systems. The (ALL:ALL) entry indicates the user and the group privileges that can be used to run the sudo commands.NOPASSWD means that password is not required and the last ALL refers to the commands that can be executed by the user.

Let’s look at a few more examples.

The above sudo policy lets the user ibrahim run the adduser and kill commands as the root or bin user with operator or system group privileges.

So, I can run the kill command as the bin user with system group privileges like this:

If you would like all users within a group to use sudo command without a password, you can use the following policy.

All users under the wheel group will now be able to run all sudo commands without any password.

If your sudo policy is not working, most probably the policy is overwritten or the syntax is wrong. For example, if my user id, ibrahim is under the sudo group and if you look at the policy below, the second policy will actually overwrite the no password policy specified on the first line and sudo without password will not work for my account.

To solve the problem, switch the positions of the sudo policy rules.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }