Search code examples
windowsbatch-filecmdnmap

Windows batch file to insert a blank line / remove single lines - nmap output


I'm trying to clean up nmap results and get a cleaner/easier to work with file, that has just the data I need - basically, IP and open ports.

(no need to integrate it into a solution, I can get them to work together)

This line cleans up the initial output:

findstr "Nmap open"|findstr /v "no-response"

It keeps lines with the txt Nmap, and the ports that are open. It then removes the lines that include "no-response" (that also have "Nmap" in them)

Here is resultant output:

Nmap scan report for 1.1.1.1
21/tcp   open  
22/tcp   open  
80/tcp   open   
Nmap scan report for 1.1.1.2
Nmap scan report for 1.1.1.3
22/tcp  open     
Nmap scan report for 1.1.1.4
80/tcp  open     
443/tcp open     
Nmap scan report for 1.1.1.5
80/tcp    open     
554/tcp   open     

I'd like that output to include blank lines, and omit lines with no subsequent open ports, i.e.:

Nmap scan report for 1.1.1.1
21/tcp   open  
22/tcp   open  
80/tcp   open   

Nmap scan report for 1.1.1.3
22/tcp  open     

Nmap scan report for 1.1.1.4
80/tcp  open     
443/tcp open 

Nmap scan report for 1.1.1.5 
80/tcp    open     
554/tcp   open  

Not sure if that's doable -- seems like it should be...


Solution

  • Give this a try, after modifying only the doublequoted path to your text file, on line 5:

    @(Set LF=^
    % 0x0A %
    )
    @For /F %%# In ('Copy /Z "%~f0" NUL')Do @Set "CR=%%#"
    @Call :Sub "%UserProfile%\Desktop\dummy.txt"
    @GoTo :EOF
    :Sub
    @Set "#=#"
    @(For /F Delims^=^ EOL^= %%# In ('^""%__AppDir__%cmd.exe"/V/U/D/C""%%__AppDir__%%findstr.exe"/I "^^^^Nmap ^^^^[0-9]*/.*open\^^^>" "%~1"|"%%__AppDir__%%findstr.exe"/IV "^^^^Nmap.*!CR!!LF!Nmap.*"|"%%__AppDir__%%findstr.exe"/IV "^^^^[0-9N].*!CR!!LF![^^^^\ ]""^"')Do @Echo("%%#"|"%__AppDir__%findstr.exe"/I "^.N">NUL&&(If Not Defined # (Echo(&Echo(%%#)Else Echo(%%#&Set "#=")||Echo(%%#)>"%~dpn1_filtered%~x1"
    

    The last line looks extremely long because I have included the full paths to files which should normally be available using the %PATH% and %PATHEXT% variables. This simply prevents it failing should something have happened to those important variables.