Soumya Simanta
Soumya Simanta

Reputation: 11741

Invoking shell script from a python script using root privileges

I'm trying to invoke a shell script shell_script.sh from a python script (python_script.py) using the call command. The shell_script.sh invokes a executable that requires root access to execute.

The python_script.py invokes shell_script.sh using subprocess.call().

See below: subprocess.call(['/complete_path/shell_script.sh', 'param1', 'param2', 'param3'], shell=True)

When I try to execute the python script python_script.py it gives me permission denied.

I've tried different ways.

a) Invoke python with sudo - sudo python python_script.py

b) Invoke sudo into inside the call method - subprocess.call(['sudo' '/complete_path/shell_script.sh', 'param1', 'param2', 'param3'], shell=True)

What's the best way to resolve this.

Thanks.

Upvotes: 1

Views: 2765

Answers (1)

tMC
tMC

Reputation: 19315

I'd put logic in the python_script.py to check its UID and fail if is not executed as root. if os.getuid() != 0:. That will ensure it only runs as root, ether by a root login, or sudo.

If you're getting permission denied when trying to execute the python_script.py, you need to set the execute bit on it. chmod +x python_script.py

Upvotes: 1

Related Questions