Search code examples
phpnmap

How to use Nmap in PHP exec


I would like to call Nmap from PHP.

IF I do that :

exec('nmap', $output);
var_dump( $output );

It works, I get the classic "Usage of Nmap" text.

But as soon as I tried to run an UDP check like

exec('nmap -p 586 -sU xx.xx.xx.xx', $output);
var_dump( $output );

It don't work anymore, with no output.

What am I missing?

Regards


Solution

  • Important notice: NMAP is not fully functional with the webservers user (apache, www-data, ...). Only root can do everything with NMAP.

    I'd use popen().

    $stream = popen('/usr/bin/nmap -p 586 -sU xx.xx.xx.xx', 'r');
    
    while (!feof($stream)) {
        //Make sure you use semicolon at the end of command
        $buffer = fread($stream, 1024);
        echo $buffer, PHP_EOL;
    }
    
    pclose($stream);
    

    Or worth trying:

    // Start output buffering
    ob_start();
    // Flush COMPLETE output of nmap
    fpassthru('/usr/bin/nmap -p 586 -sU xx.xx.xx.xx');
    // Capture output buffer contents
    $output = ob_get_contents();
    // Shutdown output buffers
    ob_end_clean();