Shodan API Python example

I’ve advocated learning Python, and the best way to learn it is with a useful example. Here’s a very simple Python program that does something useful. It queries the Shodan API to tell you who owns an IP address.

This program has tons of room for improvement. Start with this, then make improvements to make it more useful to you. It’s a useful example for a couple of reasons. It accesses an API, then pulls JSON data for you to extract. I extract just one element from the data. I do this stuff with other APIs in the course of my day job almost every day.

import shodan
import sys

apikey = "zzz"
ip = "9.9.9.9"

try:
   api = shodan.Shodan(apikey)
   result = api.host(ip)
   print(ip, result['org'])
except Exception as e:
   print('Error: %s' % e)
   sys.exit(1)

Get an API key from Shodan and store it in line 3, and store your IP in line 4. Modifying this to use command-line arguments or prompt you for the IP would be one possible improvement. My goal here is to provide something useful that’s easy to understand.

Also, before you run the program, you’ll need to run the command pip install shodan to install the Shodan library.

How it works

This is a super simple program. The first two lines import the two libraries that do 90% of the work.Python is largely about using libraries that someone else already wrote that do most of the work.

Line 3 defines the API key so you can access Shodan. Open a free account, and you can get an API key. The fourth line defines the IP address we want to look for. Defining a variable makes life easier since we reference it twice and you likely will reference it again if you ever improve the program.

Line 5 defines error handling. Line 6 calls the Shodan API with the IP address. Super simple. Line 7 prints the IP address and owner. If something goes wrong, line 8 takes over and prints the error message the API returns.

We could do this in four lines if we dispensed with the variables and error handling. But if Shodan doesn’t have the information you want, you get an error. That’s true of most APIs, so error handling is good form. And building it out a bit more than that makes extending it easier. I really don’t want you to just use this as-is. I want you to improve it.

Improving the Shodan API Python example

The most obvious way to improve the program is to print more information. The variable result contains lots more information than just the owner. It’s a whole mess of json full of potentially useful information about that IP address.

Try my trick to pretty print json on the variable result. This will tell you what data is available besides just the organization who owns it. Then you can pull out the elements you want and print them the same way I do in line 7 to make this script more useful.

If you found this post informative or helpful, please share it!