如何通过Python批量获取GitLab中SpringBoot项目的微服务端点列表
用Python批量提取GitLab中SpringBoot项目的API端点
当然可以通过Python实现批量提取,核心思路是:先批量克隆GitLab上的SpringBoot项目到本地,再遍历项目中的控制器文件,用正则匹配提取API注解里的路径和请求方法,最后整理输出。
具体步骤及代码实现
1. 批量克隆GitLab项目
先整理好目标项目的仓库地址,用Python调用git命令批量克隆(私有项目需提前配置Git SSH密钥,或在克隆URL中带上个人访问令牌)。
示例代码:
import subprocess import os # 替换为你的GitLab项目仓库地址列表 git_repos = [ "git@gitlab.com:your-group/project1.git", "git@gitlab.com:your-group/project2.git" ] # 克隆项目的本地存储目录 clone_dir = "./springboot_projects" os.makedirs(clone_dir, exist_ok=True) for repo_url in git_repos: repo_name = repo_url.split("/")[-1].replace(".git", "") target_path = os.path.join(clone_dir, repo_name) if not os.path.exists(target_path): print(f"正在克隆项目:{repo_name}") subprocess.run(["git", "clone", repo_url, target_path], check=True) else: print(f"项目{repo_name}已存在,跳过克隆")
2. 遍历控制器文件提取API端点
遍历每个项目的src/main/java目录,筛选带@RestController或@Controller注解的Java文件,用正则匹配提取请求方法和路径。
示例代码:
import re from pathlib import Path # 匹配@GetMapping/@PostMapping这类直接注解的正则 method_annot_re = re.compile(r'@(Get|Post|Put|Delete|Patch)Mapping\("(.*?)"\)') # 匹配带method属性的@RequestMapping注解的正则 request_mapping_re = re.compile(r'@RequestMapping\(.*?value\s*=\s*"(.*?)".*?method\s*=\s*RequestMethod\.(\w+).*?\)') def extract_endpoints(file_path): endpoints = [] with open(file_path, "r", encoding="utf-8", errors="ignore") as f: content = f.read() # 提取直接方法注解的端点 direct_matches = method_annot_re.findall(content) for method, path in direct_matches: endpoints.append({"path": path, "method": method.upper()}) # 提取@RequestMapping带method的端点 rm_matches = request_mapping_re.findall(content) for path, method in rm_matches: endpoints.append({"path": path, "method": method.upper()}) return endpoints # 遍历所有克隆项目收集端点 all_endpoints = [] for repo_path in Path(clone_dir).iterdir(): if not repo_path.is_dir(): continue # 查找所有Java文件 java_files = list(repo_path.rglob("src/main/java/**/*.java")) for java_file in java_files: with open(java_file, "r", encoding="utf-8", errors="ignore") as f: content = f.read() # 判断是否为控制器类 if "@RestController" in content or "@Controller" in content: endpoints = extract_endpoints(java_file) for ep in endpoints: all_endpoints.append({ "project": repo_path.name, "endpoint": ep["path"], "method": ep["method"] }) # 按要求格式输出结果 print("所有项目API端点列表:") for idx, item in enumerate(all_endpoints, start=1): print(f"{idx}. 项目-{item['project']} Endpoint-{item['endpoint']} method-{item['method']}")
补充说明
- 正则可根据实际场景扩展,比如处理不带引号的路径、
@RequestMapping简化写法(仅指定value)等情况。 - 私有仓库优先用SSH密钥认证,避免代码硬写令牌泄露风险。
- 可修改输出逻辑,将结果导出为CSV或JSON文件方便后续处理。
内容的提问来源于stack exchange,提问作者Heng SiewChean
相关产品推荐
相关产品推荐

