Tuesday, January 13, 2015

Monitor Incoming Connections (Php, Linux)

I posted this on Spiceworks....

Description

Monitor connections on machine.
this is set to monitor eth3, with destination of 192.168.0.100, just adjust the tcpdump settings to broaden the scope.

Source Code

#!/usr/local/bin/php
<?php
$file = 'source.ips.log';

$cmd = <<<EOF
sudo tcpdump -i eth3 -n -q -e "dst host 192.168.0.100"|awk -F, '{print $3}'|awk -F" " '{print $3 "." $5 "." $6}'|awk -F. '{print $1 "." $2 "." $3 "." $4 " " $5 ">" $10}'
EOF;

$cmd = trim($cmd);

$handle = popen("$cmd", 'r');
$foundIPs = array();
while(!feof($handle)) {
    $buffer = trim(fgets($handle));
    $data = explode(" ",$buffer);
    if(count($data)==2){
        // leave just text?
        $port = preg_replace("/[0-9 ]+/", "", $data[1]);
        if( empty($foundIPs[$data[0]][$data[1]]) ){
            $foundIPs[$data[0]][$port]=1;
            file_put_contents($file,"source port>{destination port}\n".var_export($foundIPs,true));
        } else {
            $foundIPs[$data[0]][$port]++;
        }
    }
    flush();
}
pclose($handle);
file_put_contents($file,"source port>{destination port}\n".var_export($foundIPs,true));

var_dump($foundIPs);