How to use sudo permissions for specific tasks on accounts with nologin or password on Linux

Table of Contents

This guide will help you to setup sudo permissions on your server

Using sudo for root login without password

Step 1 #

Please edit sudoers file with command visudo:

$ visudo

You should get something similar to this content:

# 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.
Defaults env_reset
Defaults mail_badpass
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"

# Host alias specification
# User alias specification
# Cmnd alias specification
# User privilege specification

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command

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

#includedir /etc/sudoers.d


Step 2 #

Find %sudo entry, and add before last ALL NOPASSWD:



Step 3 #

Now add your user to the sudo group:

$ usermod -a -G sudo {your_user_name}

Now you can use:

$ sudo su -

without a password prompt.

Using sudo for specific tasks on accounts with /sbin/nologin or password entry

If you want to run the command as a different account than root, you need to specify it in the command line prompt, eg:

$ sudo -u {account_with_nologin} /usr/local/bin/{some_example_binary}

However, if you want to run the command as a different user from a non-root account, you need to edit your sudoers file:

$ visudo

Add a line with following example content:

jeff ALL=(nobody:nogroup) NOPASSWD:/usr/bin/whoami

Now user jeff can use the command whoami without providing a password as a nobody user.

You can define from which hosts the user can execute commands via sudo. Here’s a small breakdown about sudoers syntax:

[username] [any-hostname]=([run-as-username]:[run-as-groupname]) [commands-allowed]