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?

6/14/2010 12:09:54 PM

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.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
chmod u+s
chmod a+x

That should do it. In your Django app you can now call os.system('') 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.

6/14/2010 12:38:26 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow