简体   繁体   中英

KeyError: 0 when iterating json through python-nmap

I'm trying to parse out specfic values from my dictionary. Having worked with dictionaries before, I was certain you could iterate through a length of results using integers.

Below is an edited example of my nmap scan (using fake IPs). I'm trying to access the ipv4 values.

{'165.19.100.145': {'addresses': {'ipv4': '165.19.100.145'}}, '165.19.100.200': {'addresses': {'ipv4': '165.19.100.200'}}}

I'm trying to iterate through the dictionary like so:

#!/usr/bin/env python3
import nmap
import json
nm = nmap.PortScanner()
results = nm.scan(hosts='165.19.100.0/24', arguments='-sP')

results_json = json.dumps(results['scan'], indent=4, sort_keys=True, ensure_ascii=False)
json_data = json.loads(results_json)

scan_len = len(json_data)

for x in range(0, scan_len):
    ip_address = json_data[x]['addresses']['ipv4']
    print(ip_address)

When I run this script, I get a KeyError: 0 . I have no idea why I might be getting this error. Wouldn't the 0 refer to the first 165.19.100.145 ? What am I doing wrong here?

Because you are not iterating over a list but over a dictionary. there are no indexes in a dictionary afaik. rather do this:

for key, value in json_data.iteritems():
    print json_data[key]['addresses']['ipv4']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM