
virustotal是一个免费的在线服务,用于分析可疑文件和url,以检测病毒、蠕虫、木马和其他类型的恶意软件。其api允许开发者集成virustotal的功能到自己的应用程序中,实现自动化扫描和报告检索。
使用VirusTotal API扫描URL通常包括两个主要步骤:
在实际操作中,许多开发者在第二步获取扫描结果时会遇到Wrong URL id的错误,这通常是因为对ID的处理方式存在误解。
首先,我们需要使用POST请求将URL提交给VirusTotal。以下是使用Python requests 库实现此操作的示例代码:
import requests
import json
def submit_url_for_scan(scan_url, api_key):
"""
提交URL到VirusTotal进行扫描。
:param scan_url: 待扫描的URL字符串。
:param api_key: 您的VirusTotal API密钥。
:return: 扫描任务的分析ID (analysis_id) 或 None。
"""
url = "https://www.virustotal.com/api/v3/urls"
payload = {"url": scan_url}
headers = {
"accept": "application/json",
"x-apikey": api_key,
}
try:
response = requests.post(url, data=payload, headers=headers)
response.raise_for_status() # 检查HTTP响应状态码,如果不是2xx则抛出异常
response_json = response.json()
# 从响应中提取分析ID
analysis_id = response_json.get('data', {}).get('id')
if analysis_id:
print(f"成功提交URL: {scan_url},分析ID: {analysis_id}")
return analysis_id
else:
print(f"提交URL失败或未获取到分析ID: {response_json}")
return None
except requests.exceptions.RequestException as e:
print(f"提交URL时发生网络或HTTP错误: {e}")
return None
except json.JSONDecodeError:
print(f"提交URL时响应内容不是有效的JSON: {response.text}")
return None
# 示例调用 (请替换为您的实际API密钥)
# api_key = "YOUR_VIRUSTOTAL_API_KEY"
# analysis_id_example = submit_url_for_scan("https://www.youtube.com/", api_key)
# print(f"获得的分析ID: {analysis_id_example}")执行上述代码后,如果成功,您将获得一个类似 u-dbae2d0204aa489e234eb2f903a0127b17c712386428cab12b86c5f68aa75867-1701503514 的字符串。这个字符串是VirusTotal为您的提交任务生成的“分析ID”或“提交ID”。
许多用户会直接将上述获得的 analysis_id 用于查询URL扫描结果的GET请求,从而导致 Wrong URL id 错误。这是因为VirusTotal的URL分析结果查询API(/api/v3/urls/{id})所需的{id}并不是完整的分析ID,而是分析ID中的一个特定部分——通常是去除前缀和时间戳的哈希值部分。
问题根源: 提交URL后返回的分析ID格式通常是 u-{哈希值}-{时间戳}。例如:u-dbae2d0204aa489e234eb2f903a0127b17c712386428cab12b86c5f68aa75867-1701503514。 然而,用于查询具体URL报告的GET请求,其URL路径中的ID部分(即{id})需要的是中间的哈希值部分,而不是完整的分析ID。
解决方案: 我们需要从完整的分析ID中提取出中间的哈希值部分。一种简单有效的方法是使用字符串的 split('-') 方法,并取其第二个元素(索引为1)。
# 假设我们获得的分析ID是
full_analysis_id = 'u-dbae2d0204aa489e234eb2f903a0127b17c712386428cab12b86c5f68aa75867-1701503514'
# 正确提取用于查询的URL ID
url_id_for_query = full_analysis_id.split('-')[1]
# 此时 url_id_for_query 将是 'dbae2d0204aa489e234eb2f903a0127b17c712386428cab12b86c5f68aa75867'结合上述提交和ID处理逻辑,以下是一个完整的Python函数,用于提交URL并获取其VirusTotal扫描报告:
import requests
import json
import time
def scan_and_get_url_report(scan_url, api_key, wait_time=10, max_retries=5):
"""
提交URL到VirusTotal进行扫描,并获取其报告。
:param scan_url: 待扫描的URL字符串。
:param api_key: 您的VirusTotal API密钥。
:param wait_time: 每次重试之间的等待时间(秒)。
:param max_retries: 最大重试次数。
:return: URL扫描报告的JSON数据,如果失败则为None。
"""
# 1. 提交URL进行扫描
submit_url = "https://www.virustotal.com/api/v3/urls"
payload = {"url": scan_url}
headers = {
"accept": "application/json",
"x-apikey": api_key,
}
print(f"正在提交URL '{scan_url}' 进行扫描...")
try:
post_response = requests.post(submit_url, data=payload, headers=headers)
post_response.raise_for_status()
post_response_json = post_response.json()
full_analysis_id = post_response_json.get('data', {}).get('id')
if not full_analysis_id:
print(f"提交URL失败或未获取到分析ID: {post_response_json}")
return None
print(f"成功获取分析ID: {full_analysis_id}")
# 2. 从分析ID中提取用于查询的URL ID
# 格式通常为 u-{哈希值}-{时间戳}
# 我们需要的是中间的哈希值部分
try:
url_id_for_query = full_analysis_id.split('-')[1]
print(f"提取出用于查询的URL ID: {url_id_for_query}")
except IndexError:
print(f"无法从分析ID '{full_analysis_id}' 中正确提取URL ID。ID格式可能不符合预期。")
return None
except requests.exceptions.RequestException as e:
print(f"提交URL时发生网络或HTTP错误: {e}")
return None
except json.JSONDecodeError:
print(f"提交URL时响应内容不是有效的JSON: {post_response.text}")
return None
# 3. 循环查询扫描结果
get_report_url = f"https://www.virustotal.com/api/v3/urls/{url_id_for_query}"
for attempt in range(max_retries):
print(f"尝试获取报告 (第 {attempt + 1}/{max_retries} 次)...")
try:
get_response = requests.get(get_report_url, headers=headers)
get_response.raise_for_status()
report_json = get_response.json()
# 检查报告中是否存在错误,特别是BadRequestError
if 'error' in report_json:
error_message = report_json['error'].get('message', '未知错误')
error_code = report_json['error'].get('code', '未知代码')
print(f"获取报告时API返回错误: {error_code} - {error_message}")
# 如果是 Wrong URL id 错误,通常是ID处理问题,但我们已经处理了
# 可能是报告尚未生成,或URL本身的问题
if error_code == "BadRequestError" and "Wrong URL id" in error_message:
print("尽管已尝试正确处理ID,但仍收到 'Wrong URL id' 错误。请检查原始分析ID是否有效或VirusTotal是否已处理此URL。")
# 对于某些错误,可能需要重试,但对于Wrong URL id,重试意义不大
# 对于报告未就绪的情况,可以继续等待
if "Not found" in error_message or "still processing" in error_message.lower():
print(f"报告尚未就绪或正在处理中,等待 {wait_time} 秒后重试...")
time.sleep(wait_time)
continue # 继续下一次循环尝试
else:
return None # 其他错误直接退出
# 如果报告成功返回且没有错误,则返回报告
print("成功获取URL扫描报告。")
return report_json
except requests.exceptions.RequestException as e:
print(f"获取报告时发生网络或HTTP错误: {e}")
except json.JSONDecodeError:
print(f"获取报告时响应内容不是有效的JSON: {get_response.text}")
print(f"等待 {wait_time} 秒后重试...")
time.sleep(wait_time)
print("达到最大重试次数,未能获取URL扫描报告。")
return None
# --- 示例调用 ---
# 请替换为您的实际API密钥
VIRUSTOTAL_API_KEY = "YOUR_VIRUSTOTAL_API_KEY"
TARGET_URL = "https://www.youtube.com/" # 替换为您想要扫描的URL
if VIRUSTOTAL_API_KEY == "YOUR_VIRUSTOTAL_API_KEY":
print("请将 'YOUR_VIRUSTOTAL_API_KEY' 替换为您的实际VirusTotal API密钥。")
else:
report = scan_and_get_url_report(TARGET_URL, VIRUSTOTAL_API_KEY)
if report:
# 打印部分报告内容,例如检测引擎数量
print("\n--- 扫描报告摘要 ---")
attributes = report.get('data', {}).get('attributes', {})
last_analysis_stats = attributes.get('last_analysis_stats', {})
print(f"URL: {TARGET_URL}")
print(f"恶意检测数: {last_analysis_stats.get('malicious', 0)}")
print(f"可疑检测数: {last_analysis_stats.get('suspicious', 0)}")
print(f"无害检测数: {last_analysis_stats.get('harmless', 0)}")
print(f"未检测数: {last_analysis_stats.get('undetected', 0)}")
# print(json.dumps(report, indent=2)) # 打印完整报告
else:
print(f"未能获取 {TARGET_URL} 的扫描报告。")
通过本教程,我们深入探讨了使用Python与VirusTotal API进行URL扫描的关键步骤,特别是解决了在获取扫描结果时常见的Wrong URL id错误。核心在于理解VirusTotal返回的“分析ID”与查询报告所需的“URL ID”之间的差异,并学会通过字符串处理(split('-')[1])正确提取后者。遵循这些指导和最佳实践,开发者可以更有效地利用VirusTotal API,构建稳定可靠的恶意URL检测系统。
以上就是VirusTotal API URL扫描结果获取:正确处理ID的关键的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号