Safety CLI

3.7.0 · active · verified Thu Apr 09

Safety CLI (safety) is a Python dependency vulnerability scanner that identifies known security vulnerabilities and malicious packages in your project's dependencies. It integrates into local development, CI/CD pipelines, and production systems, providing actionable remediation recommendations. The current version is 3.7.0, and it maintains an active release cadence with regular updates.

Warnings

Install

Quickstart

This quickstart demonstrates how to programmatically run `safety scan` using Python's `subprocess` module to check a `requirements.txt` file. It includes a dummy vulnerable dependency (requests==2.25.1) to show output with findings. For comprehensive vulnerability data, an API key might be required, which can be passed via `SAFETY_API_KEY` environment variable or configured using `safety auth`.

import subprocess
import os

# Create a dummy requirements.txt for demonstration
with open('requirements.txt', 'w') as f:
    f.write('requests==2.25.1 # known vulnerable version for demo (CVE-2023-32681, fixed in 2.31.0)
')
    f.write('Flask==2.3.2 # non-vulnerable example
')

print('Scanning requirements.txt for vulnerabilities...')

# Run safety scan command. Note: For full, commercial vulnerability database access,
# an API key might be required. Basic scanning may work without explicit auth or prompt for it.
# Use os.environ.get('SAFETY_API_KEY', '') if using a commercial key programmatically.
try:
    # Using check=False to capture output even if safety exits with a non-zero code (vulnerabilities found)
    result = subprocess.run(
        ['safety', 'scan', '-r', 'requirements.txt', '--full-report'],
        capture_output=True,
        text=True,
        check=False
    )
    print('--- Safety Scan Output ---')
    print(result.stdout)
    if result.stderr:
        print('--- Safety Scan Errors ---')
        print(result.stderr)
    print(f'Safety exited with code: {result.returncode}')

except FileNotFoundError:
    print("Error: 'safety' command not found. Ensure Safety CLI is installed and in your PATH.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    # Clean up the dummy file
    if os.path.exists('requirements.txt'):
        os.remove('requirements.txt')

view raw JSON →