How can I filter ports by country?

1.2k Views Asked by At

This is my code:

I import the modules

import shodan
import json

I create my key,

SHODAN_API_KEY = ('xxxxxxxxxxxxxxxxxxxx')
api = shodan.Shodan(SHODAN_API_KEY)

I open my json file,

with open('Ports.json', 'r') as f:
    Ports_dict = json.load(f)
    #I loop through my dict,
    for Port in Ports_dict:
        print(Port['Port_name'])
       
        try:
            results = api.search(Port['Port_name']) # how can I filter ports by country??
            #and I print the content.
            print('Results found: {}'.format(results['total']))
            for result in results['matches']:
                print('IP: {}'.format(result['ip_str']))
                print(result['data'])
                print('')
                print ('Country_code: %s' % result['location']['country_code'])
            
        except shodan.APIError as e:
                print(' Error: %s' % e)

But how can I filter ports by country?

1

There are 1 best solutions below

0
On

In order to filter the results you need to use a search filter. The following article explains the general search query syntax of Shodan:

https://help.shodan.io/the-basics/search-query-fundamentals

Here is a list of all available search filters:

https://beta.shodan.io/search/filters

And here is a page full of example search queries:

https://beta.shodan.io/search/examples

In your case, you would want to use the port and country filter. For example, the following search query returns the MySQL and PostgreSQL servers in the US:

https://beta.shodan.io/search?query=port%3A3306%2C5432+country%3AUS

I would also recommend using the Shodan CLI for downloading data as it will handle paging through results for you:

https://help.shodan.io/guides/how-to-download-data-with-api

If you need to do it yourself within Python then you would also need to loop through the search results either by providing a page parameter or by simply using the Shodan.search_cursor() method (instead of Shodan.search() as you did in your code). The above article also shows how to use the search_cursor() method.