We’ve been looking at simple API examples that don’t require any authentication. Today let’s take a look at a simple example that does require some authentication, and for that we’ll use the very popular API of Shodan.
If we look at the Python code below, there’s a variable that you would need to enter for your own individual Shodan API key. When the Python code runs, it asks for an IP address to look up. The user would then type in whatever IP address they want information on.
The code then takes that IP address and goes out to visit Shodan using the API. It prints information that there’s really only one of on the system – for instance, one organization, one country, one city, one operating system, etc. Then for things that there could be multiples of, like listening ports, we see that it prints “open ports” and then walks through all the results from ports and prints them using the f-string for printing and pretty printing. If there’s any errors, it should say “error” and then print it out.
Like I said, the examples we’ve been using so far have been unauthenticated. Here is an authenticated example, and tomorrow we’ll take a look at how to make this even easier than we currently are when we’re using Python to query an API.
# First, we need to import the shodan library
# You'll need to install it first using: pip install shodan
import shodan
# Store our API key - remember to never share your real API key publicly!
SHODAN_API_KEY = "YOUR_SHODAN_API_KEY_HERE"
# Create a connection to Shodan using our API key
api = shodan.Shodan(SHODAN_API_KEY)
try:
# Ask the user to input an IP address
print("Please enter an IP address to look up:")
ip_address = input()
# Use Shodan's API to look up information about this IP
# This will return a dictionary containing all the information Shodan has about this IP
results = api.host(ip_address)
# Print out some basic information about the IP
print("\n--- Results for IP:", ip_address, "---")
print("Organization:", results.get('org', 'n/a'))
print("Country:", results.get('country_name', 'n/a'))
print("City:", results.get('city', 'n/a'))
print("Operating System:", results.get('os', 'n/a'))
# Print all open ports found
print("\nOpen Ports:")
for port in results.get('ports', []):
print(f"- Port {port}")
except shodan.APIError as e:
# If something goes wrong (like invalid API key or no results found)
# This will show the error message
print("Error:", e)