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.

$ sudo tail -n 1 /etc/sudoers
#includedir /etc/sudoers.d

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.

ibrahim	ALL=(ALL:ALL) NOPASSWD: ALL

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.

ibrahim ALL=(root,bin : operator,system) NOPASSWD: /usr/sbin/adduser, /bin/kill

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:

$ sudo -u bin -g system /bin/kill 1000

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

%wheel	ALL=(ALL:ALL) NOPASSWD: ALL

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.

ibrahim	ALL=(ALL:ALL) NOPASSWD: ALL
%sudo   ALL=(ALL:ALL) ALL

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

%sudo   ALL=(ALL:ALL) ALL
ibrahim	ALL=(ALL:ALL) NOPASSWD: ALL

Ibrahim is a technology enthusiast with a keen interest in *NIX (Unix, Linux) systems, Android, open source and other tech related stuff. When his cpu load is low, you can probably find him online playing on his Xbox or PlayStation.