繁体   English   中英

以非 root 用户身份运行 python-iptables (iptc)

[英]Run python-iptables (iptc) as non-root user

我正在尝试以非 root 用户身份运行 python-iptables。

我的脚本是test.py:

import iptc
import os

uid = os.getuid()
print("Real user ID of the current process:", uid)

table = iptc.Table(iptc.Table.FILTER)
print("Table is:".format(table))

我试过了:

  1. 将能力 CAP.NET_ADMIN 赋予/usr/bin/python2.7 (结果是: $ getcap /usr/bin/python2.7 /usr/bin/python2.7 = cap.net_admin+eip )并执行/usr/bin/python2.7./test.py描述如下: Python Scapy sniff without root
  2. 使用以下定义的环境功能进行编译和运行: https://gist.github.com/tomix86/32394a43be70c337cbf1e0c0a56cbd8d并执行./ambient -c '12' /usr/bin/python2.7./test.py
  3. 我尚未使用 python-prctl 进行测试,但我很快计划按照以下所述进行测试: 无法让 CAP_CHOWN 和 CAP_DAC_OVERRIDE 为普通用户工作

日志是:

('Real user ID of the current process:', 1000)
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    table = iptc.Table(iptc.Table.FILTER)
  File "/usr/lib64/python2.7/site-packages/iptc/ip4tc.py", line 1566, in __new__
    obj._init(name, autocommit)
  File "/usr/lib64/python2.7/site-packages/iptc/ip4tc.py", line 1582, in _init
    self.refresh()
  File "/usr/lib64/python2.7/site-packages/iptc/ip4tc.py", line 1619, in refresh
    self.strerror()))
iptc.ip4tc.IPTCError: can't initialize filter: Permission denied (you must be root)

我的 kernel 是:

$ uname -r
4.4.224-1.el7.elrepo.x86_64

我的 python 版本是:

Python 2.7.5

我的 python-iptables 版本是:

python-iptables            0.12.0

我可以以非 root 用户身份成功运行“iptables -L”,但无法以非 root 用户身份成功运行 iptc python 命令。

有没有其他方法可以提供我的 python 脚本功能,或者它与 iptc 代码有关?

它会因为需要额外的功能而失败吗?

使用 sudo 运行 python 或在超级用户凭据下运行此 python。 因为 iptables 需要 (sudo) 超级用户凭据。

例如: sudo python test.py

iptc 不是为了运行 iptables 而进行的——它是直接加载 c 绑定。 由于脚本在下面调用 python,因此您必须直接为 python 提供这些功能。

在系统范围内为 python 提供功能不是一个好主意 (tm)。 使 python 的本地副本只能由用户运行,使用 cap_raw.net 的附加功能就可以了。

njl@mymachine:~/myproject $ which python3
/home/njl/bin/python3

njl@mymachine:~/myproject $ getcap ~/bin/python3
/home/njl/bin/python3 cap_net_admin,cap_net_raw=ep

njl@mymachine:~/myproject $ ls -l ~/bin/python3
-rwx------ 1 njl njl 4703672 Jan  7 21:18 /home/njl/bin/python3
njl@mymachine:~/myproject $ ./demo.py
{'INPUT': [], 'FORWARD': [], 'OUTPUT': []}

示例代码:

#!/usr/bin/env python3
import iptc

def dump_iptables():
    return iptc.easy.dump_table('filter',ipv6=False)

print(dump_iptables())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM