I'm trying to get the current IPTables rules in my Debian server neatly listed up in a database.
To do this, I've written a few steps.
-
First, we get the IPTables output with line number. (Input chain for example)
iptables -L INPUT -nvx --line
I get a neat output, that I want to get in my database the exact same way. For example;
Number, Chain, Protocol, Port, in, out
etcetera.
To get this output to be compatible with importing to the database, I need to get it into a multidimensional array. This is where I'm stuck. It's needs to be like this;
[0] (entry of rule)
[number],[chain],[protocol]...
[1]
[number],[chain],[protocol]
How exactly can I do this the most efficient way?
-- UPDATED CODE --
function getIPTables() {
$processHandle = popen('/usr/bin/sudo /sbin/iptables -L INPUT -nvx --line-numbers | tail -n +3', 'r');
$content = '';
while (!feof($processHandle)) {
$content .= fread($processHandle, 4096);
}
pclose($processHandle);
// break out all new lines into an array
$lines = explode("
", $content);
foreach ($lines as $line) {
$commands = array();
$segments = explode(" ", $line);
$newEntry = array(
'Number' => $segments[0],
'Chain' => $segments[1],
'Protocol' => $segments[2],
'Port' => $segments[3],
'in' => $segments[4],
'out' => $segments[5]
);
array_push($commands, $newEntry);
print_r($commands);
}
}
-- OUTPUT --
root@debian:/home/michael/Documents/PHPCLIFILES# php getAllRules
Local DB rules from users loaded in array
PHP Notice: Undefined offset: 1 in /home/michael/Documents/PHPCLIFILES/getAllRules on line 47
PHP Notice: Undefined offset: 2 in /home/michael/Documents/PHPCLIFILES/getAllRules on line 48
PHP Notice: Undefined offset: 3 in /home/michael/Documents/PHPCLIFILES/getAllRules on line 49
PHP Notice: Undefined offset: 4 in /home/michael/Documents/PHPCLIFILES/getAllRules on line 50
PHP Notice: Undefined offset: 5 in /home/michael/Documents/PHPCLIFILES/getAllRules on line 51