首页 > 解决方案 > 如何按国家/地区过滤端口?

问题描述

这是我的代码:

我导入模块

import shodan
import json

我创造我的钥匙,

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

我打开我的 json 文件,

with open('Ports.json', 'r') as f:
    Ports_dict = json.load(f)

我遍历我的字典,

    for Port in Ports_dict:
            print(Port['Port_name'])
   
            try:
                    results = api.search(Port['Port_name']) # how can I filter ports by country??

我打印内容。

                    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)

但是如何按国家/地区过滤端口?

标签: pythonshodan

解决方案


为了过滤结果,您需要使用搜索过滤器。以下文章解释了 Shodan 的一般搜索查询语法:

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

以下是所有可用搜索过滤器的列表:

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

这是一个充满示例搜索查询的页面:

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

在您的情况下,您可能希望使用端口国家/地区过滤器。例如,以下搜索查询返回美国的 MySQL 和 PostgreSQL 服务器:

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

我还建议使用 Shodan CLI 下载数据,因为它会为您处理结果分页:

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

如果您需要在 Python 中自己执行此操作,那么您还需要通过提供page参数或简单地使用该Shodan.search_cursor()方法(而不是Shodan.search()像您在代码中所做的那样)来循环搜索结果。上面的文章还展示了如何使用该search_cursor()方法。


推荐阅读