这段 Python 脚本,可自动扫描项目中是否存在已知漏洞的依赖组件(支持 pip 项目)。
✅ 适用于:Python 项目(
requirements.txt或pyproject.toml) 🔍 扫描来源:Snyk Vulnerability Database(通过公开 API) 📦 无需安装额外工具,仅需requests和pip依赖文件
📦 一、Python 扫描脚本(scan_python_vulnerabilities.py)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
🔧 Python 依赖漏洞自动扫描脚本
支持:requirements.txt / pyproject.toml
使用 Snyk API 查询已知漏洞(CVE)
"""
import sys
import json
import requests
from pathlib import Path
from typing import List, Dict, Optional
class VulnerabilityScanner:
def __init__(self, api_key: str = None):
self.api_key = api_key or "SNYK-KEY-PLACEHOLDER"
self.base_url = "https://snyk.io/api/v1"
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"token {self.api_key}",
"Content-Type": "application/json",
"User-Agent": "OWASP-Scanner/1.0"
})
def () -> [[, ]]:
packages = []
:
(req_file, , encoding=) f:
line f:
line = line.strip()
line line.startswith():
parts = line.split()
(parts) == :
name, version = parts
:
name = line
version =
packages.append({: name.strip(), : version.strip()})
Exception e:
()
packages
() -> [[, ]]:
:
toml
(pyproject_file, , encoding=) f:
data = toml.load(f)
packages = []
deps = data.get(, {}).get(, [])
dep deps:
dep:
name, version = dep.split(, )
:
name = dep
version =
packages.append({: name.strip(), : version.strip()})
packages
Exception e:
()
[]
() -> []:
url =
:
response = .session.get(url, timeout=)
response.status_code == :
[]
response.status_code != :
()
[]
data = response.json()
vulns = []
version_info data.get(, []):
version_info[] == version:
vuln version_info.get(, []):
vulns.append({
: vuln.get(),
: vuln.get(),
: vuln.get(),
: vuln.get(, {}).get(),
: vuln.get(),
: vuln.get()
})
vulns
Exception e:
()
[]
():
()
found_vulnerabilities = []
req_file = project_root /
req_file.exists():
()
packages = .parse_requirements(req_file)
:
packages = []
packages:
pyproject_file = project_root /
pyproject_file.exists():
()
packages = .parse_pyproject(pyproject_file)
:
()
pkg packages:
name = pkg[]
version = pkg[]
()
vulns = .get_vulnerabilities(name, version)
vulns:
()
v vulns:
()
found_vulnerabilities.extend(vulns)
:
()
found_vulnerabilities:
( + * )
()
( * )
v found_vulnerabilities:
()
( * )
()
:
()
(found_vulnerabilities) >
():
argparse
parser = argparse.ArgumentParser(description=)
parser.add_argument(, nargs=, default=, =)
parser.add_argument(, =)
args = parser.parse_args()
project_root = Path(args.project_root).resolve()
project_root.exists():
()
sys.exit()
scanner = VulnerabilityScanner(api_key=args.api_key)
scanner.scan_project(project_root)
__name__ == :
main()

