homepage
Open menu
Go one level top
  • Train and Certify
    Train and Certify

    Immediately apply the skills and techniques learned in SANS courses, ranges, and summits

    • Overview
    • Courses
      • Overview
      • Full Course List
      • By Focus Areas
        • Cloud Security
        • Cyber Defense
        • Cybersecurity and IT Essentials
        • DFIR
        • Industrial Control Systems
        • Offensive Operations
        • Management, Legal, and Audit
      • By Skill Levels
        • New to Cyber
        • Essentials
        • Advanced
        • Expert
      • Training Formats
        • OnDemand
        • In-Person
        • Live Online
      • Free Course Demos
    • Training Roadmaps
      • Skills Roadmap
      • Focus Area Job Roles
        • Cyber Defense Job Roles
        • Offensive Operations Job Roles
        • DFIR Job Roles
        • Cloud Job Roles
        • ICS Job Roles
        • Leadership Job Roles
      • NICE Framework
        • Security Provisionals
        • Operate and Maintain
        • Oversee and Govern
        • Protect and Defend
        • Analyze
        • Collect and Operate
        • Investigate
        • Industrial Control Systems
      • European Skills Framework
    • GIAC Certifications
    • Training Events & Summits
      • Events Overview
      • Event Locations
        • Asia
        • Australia & New Zealand
        • Latin America
        • Mainland Europe
        • Middle East & Africa
        • Scandinavia
        • United Kingdom & Ireland
        • United States & Canada
      • Summits
    • OnDemand
    • Get Started in Cyber
      • Overview
      • Degree and Certificate Programs
      • Scholarships
      • Free Training & Resources
    • Cyber Ranges
  • Manage Your Team
    Manage Your Team

    Build a world-class cyber team with our workforce development programs

    • Overview
    • Why Work with SANS
    • Group Purchasing
    • Build Your Team
      • Team Development
      • Assessments
      • Private Training
      • Hire Cyber Professionals
      • By Industry
        • Health Care
        • Industrial Control Systems Security
        • Military
    • Leadership Training
      • Leadership Courses
      • Executive Cybersecurity Exercises
  • Security Awareness
    Security Awareness

    Increase your staff’s cyber awareness, help them change their behaviors, and reduce your organizational risk

    • Overview
    • Products & Services
      • Security Awareness Training
        • EndUser Training
        • Phishing Platform
      • Specialized
        • Developer Training
        • ICS Engineer Training
        • NERC CIP Training
        • IT Administrator
      • Risk Assessments
        • Knowledge Assessment
        • Culture Assessment
        • Behavioral Risk Assessment
    • OUCH! Newsletter
    • Career Development
      • Overview
      • Training & Courses
      • Professional Credential
    • Blog
    • Partners
    • Reports & Case Studies
  • Resources
    Resources

    Enhance your skills with access to thousands of free resources, 150+ instructor-developed tools, and the latest cybersecurity news and analysis

    • Overview
    • Webcasts
      • Webcasts Listings
      • Live Streams
        • Wait Just An Infosec
        • Cybersecurity Leadership
        • SANS Threat Analysis Rundown (STAR)
    • Free Cybersecurity Events
      • Free Events Overview
      • Summits
      • Solutions Forums
      • Community Nights
    • Content
      • Newsletters
        • NewsBites
        • @RISK
        • OUCH! Newsletter
      • Blog
      • Podcasts
        • Blueprint
        • Trust Me, I'm Certified
        • Cloud Ace
        • Wait Just an Infosec
      • Summit Presentations
      • Posters & Cheat Sheets
    • Internet Storm Center
    • Research
      • White Papers
      • Security Policies
    • Tools
    • Focus Areas
      • Cyber Defense
      • Cloud Security
      • Digital Forensics & Incident Response
      • Industrial Control Systems
      • Cyber Security Leadership
      • Offensive Operations
      • Open-Source Intelligence (OSINT)
  • Get Involved
    Get Involved

    Help keep the cyber community one step ahead of threats. Join the SANS community or begin your journey of becoming a SANS Certified Instructor today.

    • Overview
    • Join the Community
    • Work Study
    • Teach for SANS
    • CISO Network
    • Partnerships
    • Sponsorship Opportunities
  • About
    About

    Learn more about how SANS empowers and educates current and future cybersecurity practitioners with knowledge and skills

    • SANS
      • Overview
      • Our Founder
      • Awards
    • Instructors
      • Our Instructors
      • Full Instructor List
    • Mission
      • Our Mission
      • Diversity
      • Scholarships
    • Contact
      • Contact Customer Service
      • Contact Sales
      • Press & Media Enquiries
    • Frequent Asked Questions
    • Customer Reviews
    • Press
    • Careers
  • Contact Sales
  • SANS Sites
    • Brazil
    • France
    • Japan
    • United Kingdom
  • Search
  • Log In
  • Join
    • Account Dashboard
    • Log Out
  1. Home >
  2. Blog >
  3. PowerShell Script To Parse nmap XML Files
370x370_Jason-Fossen.jpg
Jason Fossen

PowerShell Script To Parse nmap XML Files

June 11, 2009

The nmap port scanner can produce XML output of the results of its scanning and OS fingerprinting work. But how can these XML files be conveniently handled from the command line when you want to query and extract specific data or to convert that data into other formats like CSV or HTML files?

PowerShell has great XML handling capabilities. Here is a PowerShell script (Parse-Nmap.ps1) that takes an nmap XML file as input and outputs objects, where each object represents a host on the network that was scanned. The properties of each object contain the information collected from the scanning, including the output of any NSE nmap scripts that were run. Once you have your scan results as an array of PowerShell objects, it is easy to pipe those objects into other PowerShell commands and scripts for analysis, inventory, threat hunting or other security purposes.

To follow along with the examples below, get the SampleScan.xml file and the Parse-Nmap.ps1 script from the SEC505 zip file at BlueTeamPowerShell.com (look in the \Day1 folder of the zip). The script is from my six-day Securing Windows and PowerShell Automation (SEC505) course at SANS. All my PowerShell scripts are in the public domain.

Examples

To process just one XML log file

parse-nmap.ps1 samplescan.xml

And then the output will look like the following, but remember, this output is not really text, the output is an array of .NET objects with properties!

FQDN           : srv-4mm1vr3.sans.org
HostName       : srv-4mm1vr3
Status         : up
IPv4           : 10.54.23.2
IPv6           : <no-ipv6>
MAC            : <no-mac>
Ports          : open:TCP:135:msrpc
                 open:TCP:139:netbios-ssn
Services       : TCP:135:msrpc:Microsoft Windows RPC <100%-confidence>
OS             : Microsoft Windows 7 <95%-accuracy>
Script         : <no-script>

FQDN           : wks-88d70.sans.org
HostName       : wks-88d70
Status         : up
IPv4           : 10.54.23.3
IPv6           : <no-ipv6>
MAC            : <no-mac>
Ports          : open:TCP:135:msrpc
                 open:TCP:139:netbios-ssn
Services:      : open:TCP:135:msrpc:Microsoft Windows RPC <100%-confidence>
OS             : Microsoft Windows Server 2008-R2 <93%-accuracy>
Script         : <no-script>

FQDN           : srv-9ryc3.sans.org
HostName       : srv-9ryc3
Status         : up
IPv4           : 10.54.23.4
IPv6           : <no-ipv6>
MAC            : <no-mac>
Ports          : open:TCP:135:msrpc
                 open:TCP:139:netbios-ssn
Services       : open:TCP:135:msrpc:Microsoft Windows RPC <100%-confidence>
OS             : Microsoft Windows XP SP2 <100%-accuracy>
Script         : <no-script>

To process a bunch of XML log files and consolidate their output:

parse-nmap.ps1 *.xml 

dir *.xml | parse-nmap.ps1

To extract the IP addresses and hostnames of the machines fingerprinted as running Windows XP:

parse-nmap.ps1 samplescan.xml | 
where {$_.OS -like "*Windows XP*"} |
select-object IPv4,HostName,OS

To find the hosts listening on TCP/23 for telnet:

parse-nmap.ps1 samplescan.xml | 
where {$_.Ports -like "*open:tcp:23*"}

The "-like" operator is for simple wildcard matching, while the "-match" operator is for regular expression matching. You have the full .NET Framework regular expression engine available to you. Also, note that the Ports property is a space-character-delimited list of scanned ports in the format of state:protocol:portnumber:servicename (see the nmap documentation) for each port in the list.

To find the hosts listening on either TCP/80 or TCP/443 or both:

parse-nmap.ps1 samplescan.xml |
where {$_.Ports -match "open:tcp:80|open:tcp:443"}

Export to CSV or HTML (-OutputDelimiter)

The script uses a parameter named "-OutputDelimiter" to separate the strings in the Ports, Services, OS and Script properties. The default is a newline, but you will want to change the delimiter to a space character or some other symbol when exporting to a comma-delimited file or HTML report (whatever is best for how you intend to save, parse or print the data). The default is a newline to make the output easier to read within the shell.

To export the data to a CSV file for grepping, import into a spreadsheet, etc.:

parse-nmap.ps1 samplescan.xml -outputdelimiter " " |
where {$_.Ports -match "open:tcp:80"} |
export-csv weblisteners.csv

Then you could later re-import from the CSV file into a new array, keeping the same properties as before for the sake of further processing:

$data = import-csv weblisteners.csv

$data | where {($_.IPv4 -like "10.57.*") -and ($_.Ports -match "open:tcp:22")}

To export the processed data to an HTML file for viewing in a browser:

parse-nmap.ps1 samplescan.xml -outputdelimiter " " |
select-object IPv4,HostName,OS |
ConvertTo-Html | out-file \serversharereport.html

View RunStats Information (-RunStatsOnly)

The script has a -RunStatsOnly switch which shows general information about the scan instead of information about each scanned host; for example, the runstats output includes the scan's start time, end time, command-line arguments when the scan was run, etc. Keep in mind that different versions of nmap have different XML output formats, so not every field can be shown from every scan file.

Performance

The script is slower than C/C++ or Julia of course. On an Intel Core i7 4790 at 3.6GHz with PowerShell 7.1, for example, the script can process host records in the XML file at a rate of about 1300 records per second, which isn't blazing fast, but hopefully fast enough. I'm sure there are other inefficiencies and shortcomings in the script too, so feel free to modify the script as you wish, it's in the public domain (or let me know how to improve it).

To Learn More

Get the latest version of PowerShell for free from https://www.microsoft.com/powershell/

Get the nmap scanner for free from nmap.org, and see the documentation.

History

[Updated: 9.July.2009, and script edited to increase performance.]

[Updated: 18.July.2009, the -runstatsonly switch added.]

[Updated: 30.Jan.2010, fixed output issue with the -runstatsonly switch.]

[Updated: 23.May.2010, support for nmap script output added.]

[Updated: 1.Nov.2010, fixed bug for FQDN output.]

[Updated: 16.Nov.2010, removed a PowerShell 2.0 dependency]

[Updated: 14.Mar.2014, fixed an FQDN parsing bug.]

[Updated: 6.Jun.2015, improved performance, added the -Verbose switch.]

[Updated: 18.May.2021, fixed download link.]

Share:
TwitterLinkedInFacebook
Copy url Url was copied to clipboard
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Recommended Training

  • SEC460: Enterprise and Cloud | Threat and Vulnerability Assessment
  • SEC580: Metasploit for Enterprise Penetration Testing
  • SEC555: SIEM with Tactical Analytics

Tags:
  • Cyber Defense

Related Content

Blog
CD_Blog_HowtoautomateinAzure_Part2_2.jpg
Cyber Defense, Cloud Security
March 2, 2023
How to Automate in Azure Using PowerShell - Part 2
In this post, we will discuss automation approaches to mitigating risks identified in Part 1 of the How to Automate in Azure Using PowerShell series.
370x370_josh-johnson.jpg
Josh Johnson
read more
Blog
CD_Blog_HowtoautomateinAzure_Part1_2.jpg
Cyber Defense, Cloud Security
October 11, 2022
How to Automate in Azure Using PowerShell - Part 1
In this post, we’ll cover how to automate the assessment and reporting of your cloud security configuration opportunities.
370x370_josh-johnson.jpg
Josh Johnson
read more
Blog
powershell_option_340x340.jpg
Cybersecurity and IT Essentials, Cyber Defense, Penetration Testing and Red Teaming
August 4, 2022
Month of PowerShell - Discoveries from the Month of PowerShell
A final wrap-up from the Month of PowerShell: discoveries, recommendations, complaints, and successes.
370x370_Joshua-Wright.jpg
Joshua Wright
read more
  • Register to Learn
  • Courses
  • Certifications
  • Degree Programs
  • Cyber Ranges
  • Job Tools
  • Security Policy Project
  • Posters & Cheat Sheets
  • White Papers
  • Focus Areas
  • Cyber Defense
  • Cloud Security
  • Cybersecurity Leadership
  • Digital Forensics
  • Industrial Control Systems
  • Offensive Operations
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
  • © 2023 SANS™ Institute
  • Privacy Policy
  • Terms and Conditions
  • Contact
  • Careers
  • Twitter
  • Facebook
  • Youtube
  • LinkedIn