How to run from any scripting language a shell command under root user

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:

  1. 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
      
    
  2. Set the following permission to our bash script:

      
    chown root:root /opt/monit_status
    chmod 755 /opt/monit_status
      
    
  3. 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
      
    
  4. 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)
      
    
Tags

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.