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?
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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With