Paul's Blog

It only gets better

How to add specific commands to run with sudo permissions on a non-sudo user on Linux

For starters, say we have a user named notroot and we’d like them to run the command do something majestic on this instance . However, each time, do something majestic on this instance is run, we are prompted for the sudo password. This becomes a bother especially when do something majestic on this instance is run by notroot heedlessly or when automated with Ansible.

To ensure we are not prompted by the password for headless or automated execution, we have to know which path do something majestic on this instance is being called from. We will use the which command on Linux to get the path, so on teh terminal we will write which do something majestic on this instance and a possible result would be /usr/bin/do something majestic on this instance

At this point, we have to log into the root account and attach this command ( do something majestic on this instance ) to our nonroot user.

Once logged into the root account, we’ll run sudo visudo where a nano editor as the one bellow will open

#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "@include" directives:

@includedir /etc/sudoers.d

At this point, just after the last line in the visudo output, we’ll add our user and the command we’d like to execute without being prompted for the password. The entry will be as follows,


# Add specific commands for nonroot user to run
nonroot ALL=(ALL) NOPASSWD:/usr/bin/do something majestic on this instance

After adding a change like the one above, exit from the editor and save changes.

Finally, log out from the root account, back to the nonroot user and try running do something majestic on this instance

Did it ask for the sudo password?

Leave a comment

About

This website is my own personal scrap book. It captures thoughts, ideas, ramblings, successes and failures. Beware, for there might be dragons. :)