非root用户通过Python执行iptables命令
我写了一些代码,用Python来执行iptables命令
。这段代码是:
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)
当我用root用户运行这段代码时,一切都很顺利。但是当我用用户apache
来执行这段代码时,就失败了。如果我想用用户apache
来执行这段代码,而不是root
,我该怎么办呢?我觉得iptables命令
必须由root用户
来执行。有人能给点建议吗?非常感谢!
2 个回答
0
你可以使用 sudo
命令,这个命令可以让任何用户执行一些 root
权限的命令。如果你想知道怎么设置 sudo
,可以查看这里。
如果你对 root
权限的执行还有其他问题,我建议你去https://unix.stackexchange.com/看看。
2
别这么做。你的服务器现在容易受到攻击。
apache用户不是给大家随便使用的,它是专门为Apache程序设计和限制使用的。
相反,你可以通过你的网页应用程序来触发或安排一个任务,然后让一个不同的进程,这个进程是以非根用户的身份运行,来从这个队列中读取任务并执行它们。
通过使用sudo
,你可以只允许这个单独的用户执行某些特定的命令。这样一来,apache用户就没有权限去运行命令,而你也在利用操作系统的安全角色来隔离不同的操作。
有些命令之所以只限制给根用户使用,是有原因的哦 :)