I have a shell script with a bunch of commands, one of them needs root. I want to execute the script without entering passwords at all: neither before script nor in the middle of execution. How can I make it?

  • Is sudo involved?
    – Jeff Schaller
    Mar 16, 2019 at 14:28
  • You can register the script with sudo. See man sudoers Mar 16, 2019 at 14:33
  • @Jeff Schaller Yes
    – Streltsov
    Mar 16, 2019 at 14:34

3 Answers 3


sudo is a common practice , to give privileges to some user .

a simple example with multiple command : i want the user nagios to use a specific command to dump informations.

nagios ALL=(root) NOPASSWD: /usr/bin/dmidecode, /bin/netstat -ntp

Another example , you manage multiple servers , you want to deploy the same sudoers file on each . and the rule will be valid only on one server .

nagios srvpeug1208 =(root) NOPASSWD: /usr/bin/dmidecode, /bin/netstat -ntp

this will allow nagios on srvpeu1208 to execute some commands .

  • 1
    "you can deploy only one sudoers file" This is not entirely accurate. Some *NIX distributions include the /etc/sudoers.d/ directory, which you may configure sudo to read and parse file from, which can contain additional sudo rules.
    – 0xSheepdog
    Mar 16, 2019 at 18:55
  • 1
    @0xSheepdog i rewrote my statement Mar 16, 2019 at 19:17

As others have touched on, the key thing that your script needs is to run the command that requires root permissions as root without requiring a password prompt.
This is a common problem in *nix when a user needs to run a particular command that would normally require root permissions but we don't want to give that user root permissions in general.

Unix has a general solution for this: the setuid bit. When the setuid bit is set/enabled on a binary, that binary will always run as the file owner (so if the owner of the executable file is root, it will execute as root).
To set this, make sure that the binary that requires root permission is owned by root, and then set its permissions to include the setuid bit:

sudo chown root /path-to-binary
sudo chmod 4755 /path-to-binary

That binary will now execute as root, without requiring a password from the calling user. Note that if you have a shell script instead of a binary you'll need to use the workaround described at Why does setuid not work?

This will work regardless of the user who accesses the file, so be careful. If you want to restrict this ability to only one particular user, then you can instead modify the sudoers configuration as others have suggested.


Some options:

  • read man sudoers, and register the script with sudo as not needing a password to run by you. Be careful to read the bit on visudo (and how not to get your self locked out). If you don't you will be back here asking how to edit the file, when sudo is not working.
  • re-write it in golang and use setuid bit.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .