Before you begin
- Python 3.12 or later.
- Read access to the selected inputs.
Set up your example
- Save as security-secret-pattern-report.py.
- Open a terminal in its folder.
- Run python "security-secret-pattern-report.py" --help and prepare the listed input files.
This recipe uses your own local input or creates its own example output. Follow the setup steps below.
Download the ZIP, extract it, and open a terminal inside the extracted folder. The source file is security-secret-pattern-report.py.
Run the script
python "security-secret-pattern-report.py" "." --maximum-mib 1If your system uses python3 instead of python, use that command for Python examples. Keep paths containing spaces in quotes. Required inputs and optional settings are described in the code and setup steps.
What to expect
A likely password assignment produces path, line, and rule only; test fixtures can create false positives.
The complete script
#!/usr/bin/env python3
"""Report filenames and line numbers for likely credential declarations without printing matching values."""
import argparse
import sys
import json
from pathlib import Path
import os
import stat
import hashlib
import re
def files(root,limit=10000):
root=root.expanduser().resolve()
if not root.is_dir():raise ValueError('Input must be an existing directory')
count=0
for directory,dirs,names in os.walk(root,followlinks=False):
dirs[:]=[name for name in dirs if not (Path(directory)/name).is_symlink()]
for name in names:
path=Path(directory)/name
if not path.is_file() or path.is_symlink():continue
count+=1
if count>limit:raise ValueError(f'File limit {limit} exceeded; select a smaller directory')
yield path
def sha(path):
with path.open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()
def main():
parser = argparse.ArgumentParser(description='Report filenames and line numbers for likely credential declarations without printing matching values.')
parser.add_argument('directory',type=Path)
parser.add_argument('--maximum-mib',type=float,default=1)
args = parser.parse_args()
if args.maximum_mib<=0:raise ValueError('--maximum-mib must be positive')
patterns={'credential_assignment':re.compile(r'(?i)\b(api[_-]?key|secret|password|access[_-]?token)\b\s*[:=]\s*[\"\x27]?[A-Za-z0-9_+/=-]{8,}'),'private_key_header':re.compile(r'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----')}
for p in files(args.directory):
if p.stat().st_size>args.maximum_mib*1024**2:continue
data=p.read_bytes()
if b'\0' in data:continue
for number,line in enumerate(data.decode('utf-8','replace').splitlines(),1):
for label,pattern in patterns.items():
if pattern.search(line):print(json.dumps({'path':str(p),'line':number,'rule':label}))
if __name__ == '__main__':
try:
main()
except (OSError, ValueError, RuntimeError) as exc:
print(f'Error: {exc}', file=sys.stderr)
sys.exit(1)
Open source as plain text · Download source and sample files
How it works
- Report filenames and line numbers for likely credential declarations without printing matching values.
- Arguments are explicit and expected input errors produce a message with a nonzero exit code.
- Results reflect your selected local data or the specific endpoint you choose; the example illustrates the result shape.
Make it your own
Adapt the task
Change --maximum-mib or edit patterns for your naming conventions. Review privately and rotate real exposed secrets through the relevant service.
Adjust presentation
Edit final print statements or json.dumps indentation to adjust the report layout. Keep input validation and exclusive-create file modes intact.
Change one setting at a time, run it again on sample data, and compare the output. The customization guide walks through this process.
If something goes wrong
An input or dependency is unavailable.
Check the path, quote paths with spaces, and use --help to inspect required arguments.
Actual results differ from the example.
Inputs and system state determine values. Review each finding in context; a report is not proof of system health or a complete security assessment.
Reference & next steps
These official references explain the underlying tools. The Scriptage example and guide are original instructional content. See verification notes for what has been checked and the limits of those checks.
Copies a template for your own notes. It does not send anything.