如何编写PowerShell脚本批量用Trufflehog扫描多目录文件共享
PowerShell批量扫描多目录的Trufflehog脚本
以下是满足需求的PowerShell脚本,支持批量指定目录自动循环执行Trufflehog扫描,结果统一追加到JSON文件:
# 定义需要扫描的目录列表,直接在这里添加/修改路径即可 $targetDirectories = @( "C:\path\to\first\dir", "D:\path\to\second\dir", "\\fileshare\path\to\third\dir" ) # Trufflehog核心命令参数,与需求保持一致 $trufflehogArgs = @( "filesystem", "--no-update", "--json", "--include-detectors='AWS,okta,terraformcloudpersonaltoken,privatekey,nugetapikey,microsoftteamswebhook,ldap,github,githubapp,ftp,azure,auth0oauth,auth0managementapitoken'", "--fail" ) # 循环遍历每个目录执行扫描 foreach ($dir in $targetDirectories) { Write-Host "开始扫描目录: $dir" -ForegroundColor Cyan # 先检查目录是否存在,避免无效路径报错 if (Test-Path -Path $dir -PathType Container) { # 执行扫描命令,结果追加到newnew.json & trufflehog $trufflehogArgs $dir >> "newnew.json" # 根据退出码判断扫描结果 if ($LASTEXITCODE -eq 0) { Write-Host "目录 $dir 扫描完成,未发现敏感信息" -ForegroundColor Green } else { Write-Host "目录 $dir 扫描完成,发现敏感信息(已写入newnew.json)" -ForegroundColor Yellow } } else { Write-Host "警告:目录 $dir 不存在,跳过扫描" -ForegroundColor Red } Write-Host "----------------------------------------`n" } Write-Host "所有目录扫描任务已完成" -ForegroundColor Green
关键说明
- 目录配置:在
$targetDirectories数组中添加所有需要扫描的路径,支持本地目录和网络共享目录(确保当前用户有读取权限)。 - 参数复用:固定参数集中放在
$trufflehogArgs里,后续要调整检测器或其他参数时只需修改这里。 - 路径校验:通过
Test-Path过滤无效目录,避免单个路径错误中断整个批量任务。 - 状态反馈:利用Trufflehog的
--fail参数特性(发现敏感信息时返回非0退出码),直观输出每个目录的扫描结果。 - 结果汇总:用
>>追加写入JSON文件,不会覆盖之前的扫描结果。
注意事项
- 确保Trufflehog已加入系统环境变量,若未添加,需在脚本中指定完整可执行文件路径(例如
& "C:\Tools\trufflehog.exe" $trufflehogArgs $dir)。 - 网络共享目录需要当前用户具备读取权限,否则扫描会失败。
- 若需要格式化JSON文件,可在脚本执行完成后运行以下命令整理:
$jsonContent = Get-Content "newnew.json" | ConvertFrom-Json $jsonContent | ConvertTo-Json -Depth 10 | Set-Content "newnew.json"
内容的提问来源于stack exchange,提问作者Rennoc
相关产品推荐
相关产品推荐

