You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python判断网站是否开启index of目录浏览模式

Python检测站点index of目录索引开启状态的实现方法

完全可以通过发送HTTP请求实现该检测,核心逻辑是匹配目录索引页面的固有特征即可,具体实现方案如下:

实现原理

  • 服务器开启目录索引功能后,当访问没有默认首页(如index.html、index.php)的目录路径时,会返回状态码200,页面标题固定包含Index of /[目录路径]格式内容
  • 页面默认会包含「Parent Directory」、「Last modified」、「Size」、「Description」这类目录列表的通用字段,可作为辅助判断特征避免误判

代码实现

首先安装依赖库:
pip install requests beautifulsoup4

完整检测代码示例:

import requests
from bs4 import BeautifulSoup

def check_index_of(url, timeout=10):
    # 构造请求头避免被反爬拦截
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
    }
    try:
        resp = requests.get(url, headers=headers, timeout=timeout, allow_redirects=True)
        if resp.status_code != 200:
            return False
        # 匹配特征1:页面标题包含Index of
        soup = BeautifulSoup(resp.text, "html.parser")
        title = soup.title.string.strip() if soup.title else ""
        if not title.startswith("Index of /"):
            return False
        # 匹配特征2:页面包含目录列表通用字段
        feature_keywords = ["Parent Directory", "Last modified", "Size", "Name"]
        match_count = 0
        for keyword in feature_keywords:
            if keyword in resp.text:
                match_count +=1
        # 至少匹配2个以上特征才算开启
        return match_count >=2
    except Exception as e:
        print(f"请求出错:{e}")
        return False

# 调用示例
if __name__ == "__main__":
    target_url = "https://example.com/test/" # 要检测的目录路径,注意末尾要加/
    result = check_index_of(target_url)
    if result:
        print(f"站点{target_url}已开启index of目录索引")
    else:
        print(f"站点{target_url}未开启index of目录索引")

注意事项

  • 如果不想引入BeautifulSoup依赖,可以用正则匹配<title>Index of .*</title>来提取标题判断
  • 部分站点会自定义目录索引页面样式,可根据实际情况调整特征关键词列表,提高检测准确率
  • 请勿对未授权站点批量发起检测请求,避免违反相关法律法规和站点使用协议

内容的提问来源于stack exchange,提问作者norivotset

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 07:57:03