Search code examples
pythonsubprocesssudo

How to run root user commands as non root user using python in Ubuntu


I am working on a python project which involves running some of the sudo commands. In the project, I have to run, systemctl commands to get the status of running services. For this I have below code:

cmd = "sudo service mongodb status > " + status_logs
subprocess.call(cmd, shell=True)
cmd = "grep \'" + search_tag + "\' " + status_logs
status_string = str(subprocess.check_output(cmd, shell=True))

start = status_string.index(":") + len(":")
end = status_string.index(')', start)
status = status_string[start:end]
status = status + ")"
status = status.replace(" ", "")

If I run above code as sudo python3 app.py then I am getting proper response as active(running) or inactive(dead). But I need to run the code without sudo i.e. python3 app.py.

In this case, it keeps on asking the password of the current user in terminal. How can I remove this and proceed further. Please help. Thanks.

Contents of /etc/sudoers

#
# 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
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin 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

Solution

  • @alani comment on OP is good, specifically I would try to clamp down as much as possible so that issues with your program do not have disasterous consequences. For example, if you program will be running under the group mongo_checkers, something like this would enable it do check the status only:

    %mongo_checkers ALL= NOPASSWD: /usr/sbin/service mongodb status
    

    This should be relatively harmless.

    [edit: as per @alani comment on this answer, have specified full path to service. ty!]