Shodan Python Library

1.31.0 · active · verified Thu Apr 16

The Shodan Python library provides a comprehensive wrapper around the Shodan REST API and the experimental Streaming API, allowing developers to programmatically access information about Internet-connected devices, search for exploits, perform bulk IP lookups, and consume real-time Shodan data. Version 1.31.0 is the latest release, with updates released periodically to add new features and handle API changes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes the Shodan API client using an API key (preferably from an environment variable), retrieves the user's IP, performs a basic search for 'apache' servers, and looks up information for a specific IP address. It includes basic error handling for API-specific exceptions.

import os
from shodan import Shodan
from shodan.exception import APIError

SHODAN_API_KEY = os.environ.get('SHODAN_API_KEY', 'YOUR_SHODAN_API_KEY')

if not SHODAN_API_KEY or SHODAN_API_KEY == 'YOUR_SHODAN_API_KEY':
    print("Please set the SHODAN_API_KEY environment variable or replace 'YOUR_SHODAN_API_KEY'.")
else:
    try:
        api = Shodan(SHODAN_API_KEY)

        # Lookup your current IP address information
        my_ip_info = api.tools.myip()
        print(f"Your IP: {my_ip_info}")

        # Search for servers running Apache
        results = api.search('apache')
        print(f"Results found for 'apache': {results['total']}")
        for result in results['matches']:
            print(f"  IP: {result['ip_str']}, Port: {result['port']}, Org: {result['org']}")
            break # Print only the first result for brevity

        # Lookup a specific host (e.g., Google DNS)
        host_info = api.host('8.8.8.8')
        print(f"\nHost 8.8.8.8 info: {host_info['country_name']}, {host_info['org']}")

    except APIError as e:
        print(f"Error: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

view raw JSON →