0

Im building a scanner using python-nmap libary. Here's the code :

import nmap
import json

def Nmap_Recon(host, port):
   nm = nmap.PortScanner()
   lol = nm.scan(host, '22-443')
   print(lol['scan'])
Nmap_Recon('www.stuxnoid.org',80)

Output :

{'77.72.0.90': {'hostnames': [{'name': 'www.stuxnoid.org', 'type': 'user'}, {'name': 'carbon.cloudhosting.co.uk', 'type': 'PTR'}], 'addresses': {'ipv4': '77.72.0.90'}, 'vendor': {}, 'status': {'state': 'up', 'reason': 'syn-ack'}, 'tcp': {25: {'state': 'open', 'reason': 'syn-ack', 'name': 'smtp', 'product': '', 'version': '', 'extrainfo': '', 'conf': '3', 'cpe': ''}, 80: {'state': 'open', 'reason': 'syn-ack', 'name': 'http', 'product': 'imunify360-webshield/1.6', 'version': '', 'extrainfo': '', 'conf': '10', 'cpe': ''}, 443: {'state': 'open', 'reason': 'syn-ack', 'name': 'https', 'product': 'imunify360-webshield/1.6', 'version': '', 'extrainfo': '', 'conf': '10', 'cpe': ''}}}}

I guess the output is in dictionary format. The problem is, I want to display only the open port details. But the port details are nested inside the dict_key IP address (77.72.0.90) and It keeps changing with the domain I pass. How to access those Open port details and display them?

Adithyan AK
  • 1
  • 1
  • 1
  • Im asking a way to access those open port values via index because, the I cannot access the dict_values through the IP address – Adithyan AK Mar 08 '19 at 12:39
  • 2
    This is a programming question of how to access to a python struct, nothing related to security, please ask in a programing forum – camp0 Mar 08 '19 at 12:53
  • @camp0 yea I knw that. But most other programmers dont know how the Python-nmap works. They're not sure of whether the output is in json or dictionary. Just because Nmap is involved and im developing a tool related to security, Im raising this question in Security forum. Security researchers are better programmers na ? :v – Adithyan AK Mar 08 '19 at 13:08
  • This for free: assign your output to a variable a and then a["77.72.0.90"]["tcp"].items(). Still a programing question – camp0 Mar 08 '19 at 13:29
  • Programmers do not have to know how python-nmap works in order to answer your basic question of how to parse structured data in a string – schroeder Mar 08 '19 at 14:00
  • Possible duplicate of [Access an arbitrary element in a dictionary in Python](https://stackoverflow.com/questions/3097866/access-an-arbitrary-element-in-a-dictionary-in-python) – Spencer Wieczorek Mar 08 '19 at 14:30
  • @AdithyanAK To access the first object's value in a dictionary see the dup link, then the `tcp` key you can do: `next(iter(lol['scan'].values()))['tcp']`. – Spencer Wieczorek Mar 08 '19 at 14:32

1 Answers1

0

if your question is how to get first item out of a dictionary (arbitrary item prior to python 3.6) it can be done so:

next(iter(lol['scan'].values()))

or, destructively (this will return last item):

lol['scan'].popitem()[1]
panda-34
  • 4,089
  • 20
  • 25