Aller au contenu

Commandes Snyk

Commandes Snyk CLI complètes et flux de travail pour l’analyse de sécurité à travers les dépendances open source, le code, les conteneurs et l’infrastructure as code.

Installation

npm (Node.js)

# Install globally
npm install -g snyk

# Install in project
npm install --save-dev snyk

# Verify installation
snyk --version

macOS (Homebrew)

# Install via Homebrew
brew install snyk

# Update Snyk
brew upgrade snyk

# Verify installation
snyk --version

Windows (Scoop)

# Install via Scoop
scoop install snyk

# Verify installation
snyk --version

Binaire autonome

# Download standalone CLI (Linux/macOS)
curl https://static.snyk.io/cli/latest/snyk-linux -o snyk
chmod +x ./snyk
./snyk --version

# Or macOS
curl https://static.snyk.io/cli/latest/snyk-macos -o snyk
chmod +x ./snyk

Authentification

Authentifier via le navigateur

# Open browser for authentication
snyk auth

# Default: opens browser and creates auth token
snyk auth --token <token>

Méthodes de jeton API

# Authenticate with explicit token
snyk auth --token <your-api-token>

# Set token via environment variable
export SNYK_TOKEN=<your-api-token>
snyk test

# Check current authentication
snyk config get api

# Set organization
snyk config set org=<org-id>

Déconnexion

# Clear stored credentials
snyk logout

# Clear all authentication
rm ~/.snyk

Analyse des dépendances open source (SCA)

Test de base

# Scan current project for vulnerabilities
snyk test

# Scan with minimal output
snyk test --quiet

# Scan and show detailed info
snyk test --verbose

# Scan specific file
snyk test --file=package.json

# Scan with all vulnerability levels
snyk test --severity-threshold=low

Filtrage par sévérité

# Only show critical vulnerabilities
snyk test --severity-threshold=critical

# Show critical and high
snyk test --severity-threshold=high

# Show critical, high, and medium
snyk test --severity-threshold=medium

# Show all (critical, high, medium, low)
snyk test --severity-threshold=low

Support multilingue

# Scan npm/Node.js projects
snyk test

# Scan Python projects
snyk test --file=requirements.txt

# Scan Java (Maven)
snyk test --file=pom.xml

# Scan Java (Gradle)
snyk test --file=build.gradle

# Scan .NET (NuGet)
snyk test --file=packages.config

# Scan Ruby
snyk test --file=Gemfile.lock

# Scan PHP/Composer
snyk test --file=composer.lock

# Scan Go
snyk test --file=go.mod

Suivi des projets

# Create snapshot of vulnerabilities for monitoring
snyk monitor

# Monitor with custom name
snyk monitor --project-name=my-app

# Monitor specific organization
snyk monitor --org=<org-id>

# Monitor with tags
snyk monitor --tags=production,critical

Analyse du code (SAST)

Analyse de code de base

# Scan code for vulnerabilities (security issues)
snyk code test

# Scan with minimal output
snyk code test --quiet

# Scan with verbose output
snyk code test --verbose

# Scan specific directory
snyk code test --scan-unmanaged

Filtrage de sévérité du code

# Only critical issues
snyk code test --severity-threshold=critical

# Critical and high
snyk code test --severity-threshold=high

# All severities
snyk code test --severity-threshold=low

Analyse des conteneurs

Test d’images

# Scan Docker image for vulnerabilities
snyk container test <image-name>

# Test with tag
snyk container test myapp:latest

# Test from registry
snyk container test docker.io/node:16

# Test local image by ID
snyk container test --image=<image-id>

Suivi des conteneurs

# Create snapshot of container vulnerabilities
snyk container monitor <image-name>

# Monitor with organization
snyk container monitor <image-name> --org=<org-id>

# Monitor multiple images
snyk container monitor myapp:v1.0
snyk container monitor myapp:v1.1

Options avancées pour les conteneurs

# Show all vulnerabilities (including unfixed)
snyk container test <image> --show-vulnerable-paths

# Include base image vulnerabilities
snyk container test <image> --detect-scan-errors

# Test without uploading to Snyk
snyk container test <image> --skip-unresolved

Analyse de l’infrastructure as Code (IaC)

Analyse Terraform

# Scan Terraform files
snyk iac test

# Scan specific file
snyk iac test main.tf

# Scan with severity filter
snyk iac test --severity-threshold=high

# Test with framework
snyk iac test --framework=terraform

# Generate human-readable report
snyk iac test --report

Autres formats IaC

# Scan CloudFormation
snyk iac test --framework=cloudformation template.yaml

# Scan Kubernetes manifests
snyk iac test --framework=k8s deployment.yaml

# Scan ARM templates
snyk iac test --framework=arm

# Scan Dockerfile
snyk iac test Dockerfile

# Scan Helm charts
snyk iac test --framework=helm chart/

Suivi IaC

# Monitor IaC configuration
snyk iac describe

# Get compliance information
snyk iac describe --framework=terraform

# Show detailed configuration
snyk iac describe --nested

Correction et remédiation

Correction automatique des vulnérabilités

# Auto-fix vulnerabilities
snyk fix

# Dry-run to preview changes
snyk fix --dry-run

# Fix for specific severity
snyk fix --severity-threshold=high

# Force overwrite existing changes
snyk fix --force

Protection des dépendances

# Apply Snyk protect (adds security patches to dependencies)
snyk protect

# Verify protection is applied
snyk protect --verbose

# Remove protection
snyk protect --uninstall

Ignorer les vulnérabilités

Ignorer des vulnérabilités spécifiques

# Ignore a vulnerability interactively
snyk ignore

# Ignore with specific reason and expiry
snyk ignore --id=<vuln-id> --reason=<reason> --expiry=<date>

# Example: ignore for 30 days
snyk ignore --id=SNYK-JS-123456 --expiry=2026-04-30

# Set permanent ignore
snyk ignore --id=SNYK-JS-123456 --permanent

Fichiers de politique

# Create .snyk policy file
snyk policy --create

# Test with policy
snyk test --policy-path=.snyk

# View policy
cat .snyk

# Update policy
snyk ignore --id=SNYK-JS-123456 --reason="False positive"

Génération SBOM

Nomenclature des logiciels

# Generate SBOM in JSON format
snyk sbom

# Generate SBOM for Docker image
snyk sbom --format=json <image-name>

# Output to file
snyk sbom > sbom.json

# Generate SPDX format
snyk sbom --format=spdx

# Show in table format
snyk sbom --format=table

Formats de sortie

Sortie JSON

# Test and output as JSON
snyk test --json > results.json

# Pretty-print JSON
snyk test --json-file-output=results.json

# Code test as JSON
snyk code test --json

Sortie SARIF

# Generate SARIF format (for GitHub Code Scanning)
snyk test --sarif > results.sarif

# SARIF for code scanning
snyk code test --sarif > code-results.sarif

# Container SARIF
snyk container test <image> --sarif > container.sarif

Rapports HTML

# Generate HTML report
snyk test --html > report.html

# Open in browser
snyk test --html > report.html && open report.html

Configuration et paramètres

Commandes de configuration

# Show current configuration
snyk config show

# Set API endpoint
snyk config set api=https://api.snyk.io

# Set organization
snyk config set org=<org-id>

# Get specific setting
snyk config get api

# Unset configuration
snyk config unset org

Variables d’environnement

# Set token via env var
export SNYK_TOKEN=<your-token>

# Set organization
export SNYK_ORG=<org-id>

# Set API endpoint
export SNYK_API=https://api.snyk.io

# Set custom CA certificate
export NODE_EXTRA_CA_CERTS=/path/to/ca.crt

# Disable SSL verification (use with caution)
export NODE_TLS_REJECT_UNAUTHORIZED=0

Fichier de politique .snyk

# .snyk file for ignoring vulnerabilities
version: v1.25.0
ignore:
  SNYK-JS-123456:
    - '*':
        reason: False positive
        expires: 2026-04-30
  SNYK-PY-789012:
    - '*':
        reason: Not applicable to our use case
        expires: 2026-06-30
patch:
  SNYK-JS-111111:
    - '*':
        patched: '2024-03-15'

Filtrage et organisation

Filtrage des vulnérabilités

# Include unpatched vulnerabilities
snyk test --show-vulnerable-paths

# Show only patchable
snyk test --show-vulnerable-paths=false

# Filter by project
snyk test --project-name=<name>

# Filter by tags
snyk monitor --tags=team:backend,env:prod

Contexte organisationnel

# Test within specific org
snyk test --org=<org-id>

# Set default organization
snyk config set org=<org-id>

# Show org ID
snyk org

# List organizations
snyk org list

Intégration CI/CD

GitHub Actions

# .github/workflows/snyk.yml
name: Snyk Security Scan
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  snyk:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: snyk/actions/setup@master
      - env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
        run: snyk test --severity-threshold=high

      - name: Upload SARIF
        uses: github/codeql-action/upload-sarif@v2
        with:
          sarif_file: results.sarif

GitLab CI

# .gitlab-ci.yml
snyk_scan:
  image: snyk/snyk:latest
  script:
    - snyk auth --token $SNYK_TOKEN
    - snyk test --severity-threshold=high --json > results.json
  artifacts:
    reports:
      sast: results.json

Pipeline Jenkins

pipeline {
    agent any
    environment {
        SNYK_TOKEN = credentials('snyk-token')
    }
    stages {
        stage('Snyk Test') {
            steps {
                sh 'npm install -g snyk'
                sh 'snyk auth $SNYK_TOKEN'
                sh 'snyk test --severity-threshold=high --json > results.json'
            }
        }
    }
    post {
        always {
            publishHTML target: [
                reportDir: '.',
                reportFiles: 'results.json',
                reportName: 'Snyk Report'
            ]
        }
    }
}

Combinaisons de commandes utiles

Flux de travail d’analyse complète

# 1. Authenticate
snyk auth

# 2. Test open source dependencies
snyk test --severity-threshold=high

# 3. Scan code for security issues
snyk code test --severity-threshold=high

# 4. Scan containers
snyk container test myapp:latest

# 5. Scan Infrastructure as Code
snyk iac test terraform/

# 6. Generate SBOM
snyk sbom > sbom.json

# 7. Create monitoring snapshot
snyk monitor --org=<org-id>

Flux de travail CI/CD

# Install dependencies
npm install

# Authenticate
snyk auth --token $SNYK_TOKEN

# Run all scans with strict threshold
snyk test --severity-threshold=critical --fail-on=all
snyk code test --severity-threshold=critical
snyk container test $DOCKER_IMAGE --severity-threshold=critical

# Generate reports
snyk test --json > sca-results.json
snyk code test --sarif > code-results.sarif
snyk container test $IMAGE --json > container.json

# Monitor for continuous tracking
snyk monitor --org=$SNYK_ORG --project-name=$CI_PROJECT_NAME

Flux de travail de correction et déploiement

# Test current state
snyk test

# Auto-fix what can be fixed
snyk fix

# Review changes
git diff

# Test after fixes
snyk test

# Commit and push
git commit -am "chore: fix security vulnerabilities"
git push

Débogage et résolution des problèmes

Mode débogage

# Verbose output for debugging
snyk test --verbose

# Debug mode (very detailed logging)
snyk test --debug

# Check authentication
snyk auth --debug

# Verify installed packages
snyk test --print-deps

Problèmes courants

# Clear cache
rm -rf ~/.snyk

# Force re-authentication
snyk logout && snyk auth

# Test without uploading results
snyk test --skip-unresolved

# Check Snyk CLI version
snyk --version

# Update to latest version
npm install -g snyk@latest

Résumé du test

# Show summary only
snyk test --quiet

# Count vulnerabilities
snyk test --json | jq '.vulnerabilities | length'

# Get highest severity
snyk test --json | jq '.metadata.severityHeader'

Référence des variables d’environnement

VariableObjectifExemple
SNYK_TOKENJeton d’authentification APIexport SNYK_TOKEN=abc123
SNYK_ORGID d’organisation par défautexport SNYK_ORG=org-id
SNYK_APIPoint de terminaison API personnaliséexport SNYK_API=https://custom.snyk.io
SNYK_INTEGRATION_NAMEIdentifiant d’intégration en CI/CDexport SNYK_INTEGRATION_NAME=github-actions
NODE_EXTRA_CA_CERTSCertificat CA personnaliséexport NODE_EXTRA_CA_CERTS=/path/ca.crt
HTTP_PROXYParamètres de proxy HTTPexport HTTP_PROXY=http://proxy:8080
HTTPS_PROXYParamètres de proxy HTTPSexport HTTPS_PROXY=https://proxy:8080

Meilleures pratiques

Sécurité

  • Authentifiez-vous toujours avec un jeton API sécurisé (ne commitez jamais les jetons)
  • Utilisez --severity-threshold=critical dans les pipelines CI/CD de production
  • Mettez à jour régulièrement Snyk CLI vers la dernière version
  • Examinez et approuvez les corrections automatiques avant la fusion
  • Conservez les fichiers de politique .snyk sous contrôle de version
  • Utilisez des stratégies au niveau de l’organisation pour la cohérence
  • Surveillez continuellement les vulnérabilités avec snyk monitor

Performance

  • Utilisez le flag --quiet en CI/CD pour réduire la sortie
  • Mettez en cache les dépendances entre les exécutions si possible
  • Exécutez les analyses de conteneurs sur des balises spécifiques, pas toutes
  • Utilisez --skip-unresolved pour ignorer les problèmes non corrigeables
  • Filtrez par sévérité pour vous concentrer sur les problèmes actionnables
  • Analysez uniquement les chemins affectés si possible

Flux de travail

  • Intégrez les vérifications des PR pour éviter la fusion de code non sécurisé
  • Utilisez snyk fix pour automatiser les corrections
  • Examinez les décisions snyk ignore avant de committer
  • Utilisez snyk monitor pour un suivi continu
  • Configurez les alertes pour les nouvelles vulnérabilités
  • Documentez les exceptions avec des raisons et des dates d’expiration
  • Examinez régulièrement les vulnérabilités ignorées

Ressources

Documentation officielle

Communauté et support

Outils connexes

  • Docker - Intégration de l’analyse des conteneurs
  • Kubernetes - Analyse IaC pour K8s
  • Terraform - Sécurité de l’infrastructure as Code

Dernière mise à jour : 2026-03-30