0

I have a python script that uses a function from an imported module. the function I'm calling cannot be run without superuser privilege, and I do not intend on using sudo python myscript.py every time.

import mymodule
import subprocess, sys

#some code here...
value_returned = subprocess.call(['sudo', sys.executable, mymodule.myrootfunction()])
#more code here

This still requires root privilege and does not allow me to execute my function. I have tried many different variations of subprocess.call including subprocess.call(['sudo',sys.executable,"mymodule.py"]) but still no success. Is there any way to call a method that requires root without explicitly running the script as root in python?

I have tried changing permissions of the file that my script will access (/dev/mem) using chmod and chown, but the only thing that works is to actually run my script as superuser, which is not what I want.

How can I call a function from a module as root from within python? my goal is not to call an external shell command from within python, but to call a method. Is this doable?

ramez
  • 321
  • 1
  • 18
  • 2
    `subprocess.call` doesn't work like that. – kindall May 27 '16 at 00:55
  • If you want that add your user to special group and allow to users from this group execute program. – Serenity May 27 '16 at 01:10
  • replace `mymodule.myrootfunction()` with `'-c', 'import json, mymodule; print(json.dumps(mymodule.myrootfunction()))'` and use `value = json.loads(check_output().decode())` to return the result. Related: [Call python script with input with in a python script using subprocess](http://stackoverflow.com/q/30076185/4279) – jfs May 27 '16 at 09:58
  • Have you seen [the `@sudo` decorator](https://www.reddit.com/r/Python/comments/4enqb7/sudo_decorator_an_evil_hack/)? – Eric May 27 '16 at 10:00

0 Answers0