We have a script that is executed by "nobody" user but it needs to access a shell command that requires "root" user permission. This article will show an example how to deal with this. The following guides are tested on my Linode server running Centos 7 64-bit Linux distribution.
Below is a simple Python script:
#!/usr/bin/python
import sys
from commands import getstatusoutput
status, output = getstatusoutput("monit status")
print "%s" % (output)
if status != 0:
sys.exit(status)
This script should display the output of monit status
command. Because monit
requires to be executed by "root" user, we will get the following error if Python script runs:
Cannot open the control file '/etc/monitrc' -- Permission denied
The following steps should solve the issue:
-
Create a bash script that will serve like a wrapper that contains the shell command that we need to execute in our Python script.
vi /opt/monit_status
Copy the following script as its content:
#!/usr/bin/bash /usr/bin/monit status
-
Set the following permission to our bash script:
chown root:root /opt/monit_status chmod 755 /opt/monit_status
-
Lets allow the user of our Python script which is "nobody" to execute the bash script we created without password prompt:
vi /etc/sudoers.d/monit
Copy the following as its content:
nobody ALL = NOPASSWD: /opt/monit_status
-
Now, modify the Python script to replace the shell command with the bash script we created prefixed with
sudo
:#!/usr/bin/python import sys from commands import getstatusoutput status, output = getstatusoutput("sudo /opt/monit_status") print "%s" % (output) if status != 0: sys.exit(status)