3jy/iptables

管理iptables条目的类。

维护者

详细信息

github.com/3jy/iptables

源代码

1.2 2018-01-30 14:14 UTC

This package is not auto-updated.

Last update: 2024-09-29 05:01:48 UTC


README

iptable 库允许您通过PHP快速轻松地解析和操作iptables记录。其主要功能是解析原始iptables转储并构建包含链和规则的完整对象树。它几乎将iptables提供的所有功能都移动到了这里。

并非所有补丁都已实现 - 对于我的目的来说,没有必要这么做 - 但对于大多数用例来说,应该足够了。

安装

安装iptables最简单的方式是通过composer。

composer require 3jy/iptables

当然,您也可以下载该存储库,并将所有类从src加载到您的项目中(别忘了加载所有所需的文件)。

用法

解析原始iptables转储,构建与iptables中的一个默认表相连的链树。

use plugowski\iptables\IptablesService;
use plugowski\iptables\Table\Table;
use plugowski\iptables\Table\TableFactory;

$iptables = new IptablesService();
$table = (new TableFactory())->build(Table::TABLE_MANGLE);
$table->setRaw(shell_exec('iptables -nL --line-numbers -t ' . Table::TABLE_MANGLE));

$result = $iptables->parseIptablesChains($table);

上述代码的结果应该是包含Chain集合的Table对象

$chains = $iptables->getChainsList();

连接

每个Table都有Chains,每个Chain都有描述所有选定选项的Rules。使用iptables类,您可以简单地找到指定的链并获取其中所有规则的列表。

示例

您可以直接在测试中查看一些示例。但为了快速查看,我也把它们放在这里。

让我们获取iptables设置,并想要编辑第一条记录 - 设置源为127.0.0.1

Chain INPUT (policy DROP) 
num  target     prot opt source               destination
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
2    DROP       all  --  0.0.0.0/0            0.0.0.0/0           state INVALID
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
4    DROP       tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:22 state NEW
5    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           MAC 00:00:00:00:11:22

我假设我们已经在$result变量下解析了表格,所以最简单的方法是

$newRule = new Rule('ACCEPT', 'tcp', '127.0.0.1');
$cmd = $result->getChainByName('INPUT')->replaceRule($newRule, 1);

对象中的第一条规则已被更改,并且我们得到了$cmd中的命令

iptables -R INPUT 1 -t mangle  --proto tcp --source 127.0.0.1 --jump ACCEPT

命令

命令类允许您生成用于管理iptables的纯shell命令(仅返回作为字符串,不执行!)。

// To create shell comand like that:
// iptables -A INPUT -t mangle --match mac --mac-source 11:22:33:aa:bb:cc --jump RETURN

$command = new Command(Table::TABLE_MANGLE);
$cmd = $command->setMatch('mac', ['source' => '11:22:33:aa:bb:cc'])
        ->setJump('RETURN')
        ->append('INPUT');

请确保您首先设置所有选项(如setMatch()setProtocol()等设置器),然后调用操作方法,因为这些方法返回字符串,所以无法链式调用。