Reputation: 1904
I am trying to build an api using django which should alter iptables using POST parameters. I am using django 1.4, djangorestframework, python-iptables. The problem I am facing is that python-iptables need root access to change iptables rules. I can change the iptables rules by doing $ sudo python
and from the python shell I can change those rules. Also I can change those rules by using iptdump module which takes in iptables parameters and create those rules which I can later save in a file (iptables.rules.txt) and use fabric's local('sudo iptables-restore < iptables.rules.txt')
. But this will always prompt the user for a root password. Is there a way I can give django app root privileges so that I can bypass sudo password prompt.
Upvotes: 2
Views: 2310
Reputation: 6701
If you really need a part of the application to run as root, you could rewrite it as a daemon, and communicate with it from the main Django application as suggested in this answer. I would only recommend it if the alternative below does not suit your requirements.
The alternative sudo iptables-restore < iptables.rules.txt
is much simpler, just tell sudo not to ask for the password for just this command by adding this to your /etc/sudoers file:
djangouser ALL=(ALL) NOPASSWD: /sbin/iptables-restore
Where djangouser
is the user the Django process is running as.
EDIT: You can avoid writing an intermediate file by sending the new iptables directly to the iptables-restore
process:
import iptdump
import subprocess
ipt = iptdump.Iptables()
proc = subprocess.Popen(['sudo', '/sbin/iptables-restore'],
stdin=subprocess.PIPE)
proc.communicate(ipt.dump())
Upvotes: 4