[ 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?
Answer 1
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.
Answer 2
Here is the code I use for launching process from my one of my django app:
import subprocess
process = subprocess.Popen(['python', 'manage.py', 'some_command'])
In your case it would be:
import subprocess
process = subprocess.Popen(['service', 'httpd', 'restart'])
(also you need to handle stdout and stderr - not sure if adding '1>$HOME/out') would work with Popen. There is doucmentation for subprocess
Answer 3
Try run the command in Shell:
import subprocess
r = subprocess.call("service httpd restart 1>$HOME/out 2>$HOME/error",Shell=True)