[英]NOT root user execute iptables shell by python
I write some code to execute iptables command
by python. 我写一些代码来通过python执行
iptables command
。 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. 当我由root用户运行代码时,一切正常。 But it fails when I use user
apache
to execute the above code. 但是,当我使用用户
apache
执行上述代码时,它失败了。 What should I do if I want to execute the code by user apache
rather than root
? 如果我想通过用户
apache
而非root
执行代码,该怎么办? I think iptables command
must execute by root user
. 我认为
iptables command
必须由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. apache用户不是一般用途,其设计和限制只能由Apache进程使用。
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. 相反,使用您的Web应用程序触发或安排任务,并以不同的非root用户身份运行另一个进程 ,并从此队列中读取任务并执行它们。
Using sudo
you can then only allow certain commands to be executed by this separate user. 然后,使用
sudo
只能允许某些命令由该单独的用户执行。 This way, your apache user is not privileged to run commands, and you are utilizing the security roles your operating system to isolate actions. 这样,您的apache用户就没有运行命令的特权,并且您正在利用操作系统的安全角色来隔离操作。
There is a reason why some commands are restricted for root users only :) 某些命令仅限于root用户是有原因的:)
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. 您可以使用
sudo
命令,该命令允许任何用户执行一些root
命令,请在此处查看如何配置sudo
以供您使用。
I would advise that you try https://unix.stackexchange.com/ if you have further questions on root
executions. 如果您对
root
执行有其他疑问,我建议您尝试https://unix.stackexchange.com/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.