API

Shodan Python API

This code can be used to monitor a list of IPs exposure on Shodan.

You need to add your API Key for it to work.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/python
# -*- coding: utf-8 -*-
import openpyxl
import ipaddress
import sys
import time
import traceback
import shodan

if __name__ == '__main__':
    try:
        API_KEY = ''
        api = shodan.Shodan(API_KEY)

        time_str = time.strftime('%Y%m%d%H%M%S')
        output_path = r"D:\shodan_{0}.xlsx".format(time_str)
        file_path = r"D:\ip_list.txt"
        with open(file_path, 'r') as f:
            lines = f.readlines()
        ip_list = []
        for line in lines:
            for ip in [str(ips) for ips in
                       ipaddress.IPv4Network(line[:-1])]:
                if not ip.endswith('.0') and not ip.endswith('.255'):
                    ip_list.append(ip.strip())
        ip_list = list(set(ip_list))
        ip_list.sort()

        secs = 5
        header = (
            'IP',
            'Hostname',
            'Timestamp',
            'OS',
            'Protocol',
            'Port',
            'Service',
            'Data',
            'CVEs',
            )
        wb = openpyxl.Workbook()
        sheet = wb.active
        sheet.append(header)
        wb.save(output_path)
        for ip in ip_list:
            rows = []
            print 'Checking IP address: {IP}'.format(IP=ip)
            try:
                host = api.host(ip, history=False)
                for item in host['data']:
                    rows.append([
                        item.get('ip_str', ''),
                        item['hostnames'][0],
                        item.get('timestamp', ''),
                        item.get('os', 'n/a'),
                        item.get('transport', ''),
                        item.get('port', ''),
                        item['_shodan'].get('module', ''),
                        item.get('data', ''),
                        str(item.get('vulns', '')),
                        ])

                for row in rows:
                    sheet.append(row)
                wb.save(output_path)
            except shodan.APIError, e:
                print 'Error: {}'.format(e)
            finally:
                time.sleep(secs)
    except:
        print ('Unexpected error:', sys.exc_info())
        print traceback.format_exc()
        raise
    finally:
        exit(0)