Snyk CLI Python Plugin
The `snyk-python-plugin` is an npm package that serves as a vital extension for the Snyk Command Line Interface (CLI), enabling it to detect and report known vulnerabilities within Python projects. Currently stable at version 3.2.1, this plugin integrates seamlessly with common Python dependency management tools such as `pip` (via `requirements.txt`), `pipenv` (with `Pipfile`), and `poetry` (using `pyproject.toml` and `poetry.lock`). It focuses on providing comprehensive dependency metadata to the Snyk CLI, which then performs vulnerability analysis. The package maintains a frequent release cadence, typically issuing bug fixes and minor feature enhancements multiple times a month, as evidenced by its recent update history. Its key differentiator is the specialized support for various Python ecosystem nuances, offering deep scanning capabilities that complement the Snyk CLI's broader security analysis.
Common errors
-
Node.js version is not supported. Please upgrade to Node.js 20 or higher.
cause Attempting to run `snyk-python-plugin` version 3.0.0 or higher with an older Node.js runtime.fixUpgrade your Node.js environment to version 20 or later. For example, using nvm: `nvm install 20 && nvm use 20`. -
Snyk CLI is not installed or not found in PATH.
cause The `snyk` command is not recognized, indicating the Snyk CLI is missing or not configured correctly.fixInstall the Snyk CLI globally via npm: `npm install -g snyk`. Ensure your system's PATH includes the directory where npm installs global executables. -
Could not detect a package manager or manifest file.
cause Snyk was unable to find `requirements.txt`, `Pipfile`, `poetry.lock`, or `pyproject.toml` in the current directory or the specified path.fixEnsure you are running the `snyk test` command from the root of your Python project, or explicitly specify the target file using the `--file=<path/to/manifest>` option. -
Python executable not found. Please ensure Python is installed and available in your PATH.
cause The plugin could not locate a Python interpreter on the system to resolve dependencies.fixInstall Python and ensure its executable (`python` or `python3`) is added to your system's PATH environment variable. Verify with `python --version`.
Warnings
- breaking Version 3.0.0 of the `snyk-python-plugin` introduced a breaking change, requiring Node.js version 20 or higher to run. Older Node.js versions are no longer supported.
- gotcha This package is a plugin for the Snyk CLI and requires the Snyk CLI to be installed and configured separately. It is not a standalone library for direct programmatic import and execution.
- gotcha The plugin relies on locally installed Python environments and dependency management tools (pip, pipenv, poetry). If these tools are not available in the system's PATH, the plugin may fail to resolve dependencies.
- gotcha While Python 2.7 is generally supported, some past versions of the plugin had specific issues with Python 2.7 string formatting, leading to errors. Newer versions have addressed these, but ensure your Python 2.7 setup is standard.
Install
-
npm install snyk-python-plugin -
yarn add snyk-python-plugin -
pnpm add snyk-python-plugin
Imports
- SnykPythonPlugin
import { SnykPythonPlugin } from 'snyk-python-plugin'; - scanPythonProject
import { scanPythonProject } from 'snyk-python-plugin'; - PythonDependencyTree
import type { PythonDependencyTree } from 'snyk-python-plugin';
Quickstart
import { exec } from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
// This quickstart demonstrates how to use the Snyk CLI with the Python plugin
// to scan a basic Python project for vulnerabilities. First, ensure you have
// Snyk CLI and Python (with pip) installed globally.
// 1. Create a dummy Python project directory
const projectDir = path.join(__dirname, 'temp-python-project');
if (!fs.existsSync(projectDir)) {
fs.mkdirSync(projectDir);
}
// 2. Create a simple requirements.txt with known vulnerable packages
// For demonstration, 'requests==2.25.1' and 'flask==2.0.0' contain known vulnerabilities.
const requirementsContent = 'requests==2.25.1\nflask==2.0.0';
fs.writeFileSync(path.join(projectDir, 'requirements.txt'), requirementsContent);
// 3. Run Snyk CLI with the Python plugin on the created file
console.log(`Scanning Python project in: ${projectDir} using requirements.txt`);
exec(`snyk test --file=${path.join(projectDir, 'requirements.txt')} --json`, { cwd: projectDir }, (error, stdout, stderr) => {
// Snyk CLI typically exits with a non-zero code if vulnerabilities are found,
// so 'error' might contain details even if the scan was successful in finding vulns.
if (error && !stdout.includes('vulnerabilities')) {
console.error(`Snyk CLI execution error: ${error.message}`);
console.error(`Stderr: ${stderr}`);
fs.rmSync(projectDir, { recursive: true, force: true });
return;
}
try {
const jsonOutput = JSON.parse(stdout);
console.log('Snyk scan results (summary):');
if (jsonOutput.vulnerabilities && jsonOutput.vulnerabilities.length > 0) {
console.log(`Found ${jsonOutput.vulnerabilities.length} vulnerabilities.`);
jsonOutput.vulnerabilities.slice(0, 3).forEach((vuln: any) => {
console.log(`- ${vuln.title} in ${vuln.package} (severity: ${vuln.severity})`);
});
} else {
console.log('No vulnerabilities found or parse error occurred.');
}
} catch (parseError) {
console.error('Failed to parse Snyk JSON output:', parseError);
console.error('Raw stdout:', stdout);
} finally {
// Clean up temporary files
fs.rmSync(projectDir, { recursive: true, force: true });
console.log('Cleaned up temporary project.');
}
});