Comandos Snyk
Comandos abrangentes da CLI do Snyk e fluxos de trabalho de segurança para varredura em código aberto, código, contêineres e infraestrutura como código.
Instalação
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
Binário Autônomo
# 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
Autenticação
Autenticar com Navegador
# Open browser for authentication
snyk auth
# Default: opens browser and creates auth token
snyk auth --token <token>
Métodos de Token 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>
Logout
# Clear stored credentials
snyk logout
# Clear all authentication
rm ~/.snyk
Varredura de Código Aberto (SCA)
Testes Básicos
# 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
Filtragem por Severidade
# 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
Suporte a Múltiplas Linguagens
# 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
Monitorando Projetos
# 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
Varredura de Código (SAST)
Varredura de Código Básica
# 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
Filtragem de Severidade do Código
# 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
Varredura de Contêineres
Testes de Imagem
# 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>
Monitoramento de Contêineres
# 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
Opções Avançadas de Contêiner
# 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
Varredura de Infraestrutura como Código (IaC)
Varredura de 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
Outros Formatos de 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/
Monitoramento de IaC
# Monitor IaC configuration
snyk iac describe
# Get compliance information
snyk iac describe --framework=terraform
# Show detailed configuration
snyk iac describe --nested
Correção e Remediação
Corrigir Vulnerabilidades Automaticamente
# 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
Proteção de Dependências
# Apply Snyk protect (adds security patches to dependencies)
snyk protect
# Verify protection is applied
snyk protect --verbose
# Remove protection
snyk protect --uninstall
Ignorando Vulnerabilidades
Ignorar Vulnerabilidades Específicas
# 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
Arquivos de Política
# 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"
Geração de SBOM
Lista de Materiais de Software
# 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
Formatos de Saída
Saída 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
Saída 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
Relatórios HTML
# Generate HTML report
snyk test --html > report.html
# Open in browser
snyk test --html > report.html && open report.html
Configuração e Configurações
Comandos de Configuração
# 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
Variáveis de Ambiente
# 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
Arquivo de Política .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'
Filtragem e Organização
Filtrando Vulnerabilidades
# 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
Contexto da Organização
# 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
Integração 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
Jenkins Pipeline
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'
]
}
}
}
Combinações Úteis de Comandos
Fluxo de Trabalho de Varredura Abrangente
# 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>
Fluxo de Trabalho 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
Fluxo de Trabalho de Correção e Implantação
# 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
Depuração e Solução de Problemas
Modo de Depuração
# 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
Problemas Comuns
# 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
Resumo de Teste
# Show summary only
snyk test --quiet
# Count vulnerabilities
snyk test --json | jq '.vulnerabilities | length'
# Get highest severity
snyk test --json | jq '.metadata.severityHeader'
Referência de Variáveis de Ambiente
| Variável | Propósito | Exemplo |
|---|---|---|
SNYK_TOKEN | Token de autenticação de API | export SNYK_TOKEN=abc123 |
SNYK_ORG | ID de organização padrão | export SNYK_ORG=org-id |
SNYK_API | Ponto de extremidade de API personalizado | export SNYK_API=https://custom.snyk.io |
SNYK_INTEGRATION_NAME | Identificador de integração em CI/CD | export SNYK_INTEGRATION_NAME=github-actions |
NODE_EXTRA_CA_CERTS | Certificado de CA personalizado | export NODE_EXTRA_CA_CERTS=/path/ca.crt |
HTTP_PROXY | Configurações de proxy HTTP | export HTTP_PROXY=http://proxy:8080 |
HTTPS_PROXY | Configurações de proxy HTTPS | export HTTPS_PROXY=https://proxy:8080 |
Melhores Práticas
Segurança
- Sempre autentique com um token de API seguro (nunca confirme tokens)
- Use
--severity-threshold=criticalem CI/CD de produção - Atualize regularmente a CLI do Snyk para a versão mais recente
- Revise e aprove correções automáticas antes de mesclar
- Mantenha arquivos de política
.snyksob controle de versão - Use políticas de nível organizacional para consistência
- Monitore vulnerabilidades continuamente com
snyk monitor
Performance
- Use o sinalizador
--quietpara CI/CD para reduzir a saída - Cache de dependências entre execuções quando possível
- Executar varreduras de contêiner em tags específicas, não em todas
- Use
--skip-unresolvedpara pular problemas não corrigíveis - Filtre por severidade para focar em problemas acionáveis
- Verifique apenas caminhos afetados quando possível
Fluxo de Trabalho
- Integre nas verificações de PR para evitar a mesclagem de código inseguro
- Use
snyk fixpara automatizar a correção - Revise as decisões
snyk ignoreantes de confirmar - Use
snyk monitorpara rastreamento contínuo - Configure alertas para novas vulnerabilidades
- Documente exceções com motivos e datas de validade
- Revisão regular de vulnerabilidades ignoradas
Recursos
Documentação Oficial
- Snyk Documentation
- CLI Commands Reference
- Snyk Code Documentation
- Container Scanning
- IaC Scanning
- API Reference
Comunidade e Suporte
Ferramentas Relacionadas
- Docker - Integração de varredura de contêineres
- Kubernetes - Varredura IaC para K8s
- Terraform - Segurança de infraestrutura como código
Última atualização: 2026-03-30