I write some code to execute iptables command
by python. This is code:
import subprocess
def check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd)
return output
def accept_port(port):
try:
cmd = r"iptables -A INPUT -p tcp --dport {0} -j ACCEPT && iptables -A OUTPUT -p tcp --sport {0} -j ACCEPT".format(port)
output = check_output(cmd, shell=True)
return True
except Exception:
return False
if __name__ == "__main__":
accept_port(1234)
Everything goes okay when I run the code by root user. But it fails when I use user apache
to execute the above code. What should I do if I want to execute the code by user apache
rather than root
? I think iptables command
must execute by root user
. Could someone give some advice?? Thanks a lot!
Don't do this. Your server is now open to exploits.
The apache user is not for general use, its designed and restricted to be used by the Apache process.
Instead, using your web application trigger or schedule a task, and have a different process that is running as a different, non-root user read tasks from this queue and execute them.
Using sudo
you can then only allow certain commands to be executed by this separate user. This way, your apache user is not privileged to run commands, and you are utilizing the security roles your operating system to isolate actions.
There is a reason why some commands are restricted for root users only :)
You can use the sudo
command which allows any user to execute some root
commands, check here for how to configure sudo
for your use.
I would advise that you try https://unix.stackexchange.com/ if you have further questions on root
executions.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.