Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a shell command from Django

I'm developing a web page in Django (using apache server) that needs to call a shell command to enable/dissable some daemons. I'm try to do it with

os.system(service httpd restart 1>$HOME/out 2>$HOME/error)

and this command doesn't return anything. Any idea how can i fix this?

like image 851
Badifunky Avatar asked Jun 14 '10 12:06

Badifunky


People also ask

Can you run a shell script from Python?

If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.

How do I run a shell in Python?

To run the Python Shell, open the command prompt or power shell on Windows and terminal window on mac, write python and press enter. A Python Prompt comprising of three greater-than symbols >>> appears, as shown below. Now, you can enter a single statement and get the result.


1 Answers

I'll skip the part where I strongly advise you about the implications of having a web application starting and stopping system processes and try to answer the question.

Your django application shouldn't run with root user, which should probably be needed to start and stop services. You can probably overcome this by:

  • creating a script that uses seteuid
  • give that file the set uid attribute

The script would be something like

#!/usr/bin/python <- or wherever your python interpreter is
import os
os.seteuid(0)
os.system("service httpd restart 1>$HOME/out 2>$HOME/error")

To allow setting the effective UID to root (0), you have to run, in a shell, as root:

chown root yourscript.py
chmod u+s yourscript.py
chmod a+x yourscript.py

That should do it. In your Django app you can now call os.system('yourscript.py') to run the command with root permissions.

Finally, I believe that the command you're passing to os.system() isn't what you're looking for, since you talk about enabling and disabling daemons and all you're doing is restarting apache... which in turn seems to be where your django is running, so in practice you'll be killing your own webapp.

like image 65
Miguel Ventura Avatar answered Sep 22 '22 13:09

Miguel Ventura