Python and nmap: Controlling The Output (Python)

In my previous post I looked at the ways of using nmap and Python to scan hosts, and in this post I am going to look at outputting the results.

But first a public service announcement:

DO NOT USE THE BELOW INFORMATION TO ATTACK, MONITOR OR BREAK INTO ANY COMPUTER / NETWORK / DEVICE THAT DOES NOT BELONG TO YOU. I TAKE NO RESPONSIBILITY FOR YOUR ACTIONS.

By default nmap via Python returns results in JSON format, e.g.

{'192.168.0.28': {'hostnames': [{'name': '', 'type': ''}], 'addresses': {'ipv4': '192.168.0.28'}, 'vendor': {}, 'status': {'state': 'up', 'reason': 'conn-refused'}, 'tcp': {22: {'state': 'open', 'reason': 'syn-ack', 'name': 'ssh', 'product': 'OpenSSH', 'version': '7.9p1 Raspbian 10+deb10u2', 'extrainfo': 'protocol 2.0', 'conf': '10', 'cpe': 'cpe:/o:linux:linux_kernel'}}}}

Which is great if you want JSON but not so great if you want results outputting to the terminal / console window.

nmap scan results
nmap scan results

Thankfully this can be changed with a little Python and some more of the options available to the Python nmap module.

I have placed the previous blog entires code into a function called scanhosts() and now added a function called scanhosts_nicer_output().

def scanhosts_nicer_output():

  scan_range = nm.scan(hosts="192.168.0.1 192.168.0.28 192.168.0.48 192.168.0.38")

 # all hosts found

  nm.all_hosts()

  for host in nm.all_hosts():

     print("Host: %s(%s)" % (host, nm[host].hostname()))

     print("Open TCP Ports: ")

     print("%s" % (nm[host].all_tcp()))

  return()

This function scans the hosts in scan_range and then for each host tries to resolve the hostname and then lists all the open TCP ports on that host.

geektechstuff_nmap_python_outputs_1
Putting the Python nmap into some functions to make it easier

The output from this is now a little bit better for the terminal / console. The empty brackets after the IP address happen if hostname cannot be found.

geektechstuff_nmap_python_outputs_2
Python nmap listing hosts and their open ports

Other options that can be used in the same way as:

print("%s" % (nm[host].all_tcp()))

included:

  • nm[host].state()
    Returns “up”, “down”, “unknown” and “skipped”
  • nm[host].all_udp()
    Returns all UDP ports that were detected as open
  • nm[host].all_ip()
    Returns all IP ports that were detected as open
  • nm[host][tcp/udp/ip][port_number]
    e.g. nm[host][‘tcp’][22] returns information just about TCP port 22 on the host

Welcome to GeekTechStuff

my home away from home and where I will be sharing my adventures in the world of technology and all things geek.

The technology subjects have varied over the years from Python code to handle ciphers and Pig Latin, to IoT sensors in Azure and Python handling Bluetooth, to Ansible and Terraform and material around DevOps.

Let’s connect