Guida alla gestione dei repository dei pacchetti APT

Introduzione

Sapere da dove arrivano i pacchetti che hai installato è fondamentale per la manutenzione del sistema, per gli audit di sicurezza e per la ricerca dei guasti. Questa guida mostra come individuare l’origine dei pacchetti, gestire i repository, elencare i pacchetti per provenienza e fare l’audit della tua installazione APT su sistemi Debian/Ubuntu.

Cosa sono i repository dei pacchetti?

I repository dei pacchetti sono server che ospitano i pacchetti software da installare tramite APT (Advanced Package Tool). Conoscere l’origine dei repository ti aiuta in questi ambiti:

  • Sicurezza: individuare i pacchetti che arrivano da fonti non fidate
  • Manutenzione: tenere traccia delle dipendenze dai PPA
  • Ricerca dei guasti: trovare le fonti di pacchetti in conflitto
  • Pulizia del sistema: togliere i repository che non usi più
  • Documentazione: tenere un registro di cosa è stato installato

Tipi di repository

TipoDescrizioneEsempio
UfficialeRepository principali di Ubuntu/Debianarchive.ubuntu.com
PPAPersonal Package Archives (Ubuntu)ppa.launchpadcontent.net/user/repo
Terze partiRepository esternidownload.docker.com
LocalePacchetti installati in locale/var/lib/dpkg/status

Prerequisiti

  • Un sistema basato su Debian o Ubuntu
  • Conoscenze di base del terminale
  • apt, dpkg e perl installati (di solito ci sono già)

🚀 Comandi rapidi

Elencare tutti i pacchetti con il loro repository

dpkg --get-selections | awk '!/deinstall$/ {print $1}' | \
xargs -I{} sh -c 'echo "=== $1 ===" && apt-cache policy "$1" | grep -E "^\s+\*\*\*" | head -1' -- {} | \
paste - - | sed 's/=== \([^ ]*\) ===/\1:/' | \
perl -pe 's/:\s+\*\*\*[^5]*500\s+/: /' | \
sed 's/\s\[.*\]$//'

Elencare solo i pacchetti dei PPA

dpkg --get-selections | awk '!/deinstall$/ {print $1}' | \
xargs apt-cache policy 2>/dev/null | \
awk '/^[^ ]/ {pkg = $1} /^ \*\*\*/ {getline; if ($2 ~ /ppa\.launchpad(content)?\.net/) {split($2, u, "/"); print pkg " " u[4]}}'

Contare i pacchetti per repository

dpkg --get-selections | awk '!/deinstall$/ {print $1}' | \
xargs apt-cache policy 2>/dev/null | \
awk '/^ \*\*\*/ {getline; if ($2 ~ /^https?:/) n[$2]++}
     END { for (r in n) print r ": " n[r] " packages" }' | sort

📦 Script completo per l’audit dei pacchetti

Script bash completo, con diverse opzioni

Salvalo come package-audit.sh:

#!/bin/bash

# Script to show installed packages and their repository origins
# Enhanced version with options and clearer output

show_help() {
    cat << EOF
Usage: $0 [OPTIONS]

OPTIONS:
    -h, --help          Show this help
    -p, --ppa-only      Show only PPA packages
    -a, --all           Show all packages with repositories (default)
    -f, --format FORMAT Output format (default|json|csv)
    -s, --sort          Sort by repository
    -c, --count         Show count per repository
    -o, --output FILE   Save output to file

EXAMPLES:
    $0                  # List all packages with repositories
    $0 -p               # Only PPA packages
    $0 -f json          # JSON output
    $0 -c               # Count per repository
    $0 -p -o ppa.txt    # Save PPA list to file

REPOSITORY TYPES:
    - PPA: Personal Package Archives (Ubuntu)
    - Official: Ubuntu/Debian main repositories
    - Third-party: External repositories
    - Local: Locally installed packages
EOF
}

# Function to get package information
get_package_info() {
    local format="$1"
    local ppa_only="$2"
    local sort_by_repo="$3"
    
    # Get list of installed packages
    local packages=$(dpkg --get-selections | grep -v deinstall$ | awk '{print $1}')
    
    # Arrays to store results
    declare -A results
    declare -A repo_counts
    
    echo "Processing packages..." >&2
    
    local total=0
    local processed=0
    
    # Count total packages
    total=$(echo "$packages" | wc -l)
    
    # Process each package
    while IFS= read -r package; do
        if [[ -n "$package" ]]; then
            ((processed++))
            
            # Show progress
            if (( processed % 50 == 0 )); then
                echo "Processed $processed/$total packages..." >&2
            fi
            
            # Get package policy
            local policy_output=$(apt-cache policy "$package" 2>/dev/null)
            
            if [[ -n "$policy_output" ]]; then
                # Extract main repository
                local repo=$(echo "$policy_output" | grep -A1 -E '^\s+\*\*\*' | tail -1 | \
                           perl -ne 'if (/^\s+[0-9]+\s+(.*)/) { 
                               $repo = $1; 
                               $repo =~ s/\s+\[.*?\]$//;  # remove architecture
                               if ($repo =~ /https?:\/\/ppa\.launchpad(?:content)?\.net\/([^\/\s]+\/[^\/\s]+)/) {
                                   print "PPA: $1\n";
                               } elsif ($repo =~ /https?:\/\/([^\/\s]+)/) {
                                   print "Repository: $1\n";
                               } elsif ($repo =~ /\/var\/lib\/dpkg\/status/) {
                                   print "Local\n";
                               } else {
                                   print "Other: $repo\n";
                               }
                           }')
                
                if [[ -n "$repo" ]]; then
                    # Filter PPA if requested
                    if [[ "$ppa_only" == "true" && ! "$repo" =~ ^PPA: ]]; then
                        continue
                    fi
                    
                    results["$package"]="$repo"
                    repo_counts["$repo"]=$((${repo_counts["$repo"]} + 1))
                fi
            fi
        fi
    done <<< "$packages"
    
    echo "Done! Found ${#results[@]} packages." >&2
    echo "" >&2
    
    # Output based on requested format
    case "$format" in
        "json")
            echo "{"
            local first=true
            for package in $(printf '%s\n' "${!results[@]}" | sort); do
                if [[ "$first" == "true" ]]; then
                    first=false
                else
                    echo ","
                fi
                printf '  "%s": "%s"' "$package" "${results[$package]}"
            done
            echo ""
            echo "}"
            ;;
        "csv")
            echo "Package,Repository"
            for package in $(printf '%s\n' "${!results[@]}" | sort); do
                echo "$package,${results[$package]}"
            done
            ;;
        "count")
            echo "================================================"
            echo "  Packages per Repository"
            echo "================================================"
            echo ""
            printf "%-60s\t%s\n" "Repository" "Count"
            echo "------------------------------------------------"
            for repo in "${!repo_counts[@]}"; do
                printf "%-60s\t%s\n" "$repo" "${repo_counts[$repo]}"
            done | sort -t$'\t' -k2 -nr
            echo ""
            echo "Total repositories: ${#repo_counts[@]}"
            echo "Total packages: ${#results[@]}"
            ;;
        *)
            echo "================================================"
            echo "  Installed Packages by Repository"
            echo "================================================"
            echo ""
            if [[ "$sort_by_repo" == "true" ]]; then
                # Sort by repository
                local current_repo=""
                for package in "${!results[@]}"; do
                    echo "${results[$package]}|$package"
                done | sort | while IFS='|' read -r repo package; do
                    if [[ "$repo" != "$current_repo" ]]; then
                        echo ""
                        echo "[$repo]"
                        echo "---"
                        current_repo="$repo"
                    fi
                    echo "  - $package"
                done
            else
                # Sort by package name
                printf "%-40s -> %s\n" "Package" "Repository"
                echo "------------------------------------------------"
                for package in $(printf '%s\n' "${!results[@]}" | sort); do
                    printf "%-40s -> %s\n" "$package" "${results[$package]}"
                done
            fi
            echo ""
            echo "Total packages: ${#results[@]}"
            ;;
    esac
}

# Parse arguments
format="default"
ppa_only=false
sort_by_repo=false
output_file=""

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        -p|--ppa-only)
            ppa_only=true
            shift
            ;;
        -a|--all)
            # Default behavior
            shift
            ;;
        -f|--format)
            format="$2"
            shift 2
            ;;
        -s|--sort)
            sort_by_repo=true
            shift
            ;;
        -c|--count)
            format="count"
            shift
            ;;
        -o|--output)
            output_file="$2"
            shift 2
            ;;
        *)
            echo "Unknown option: $1" >&2
            show_help
            exit 1
            ;;
    esac
done

# Check dependencies
if ! command -v apt-cache &> /dev/null; then
    echo "Error: apt-cache not found. This script works only on Debian/Ubuntu systems." >&2
    exit 1
fi

if ! command -v dpkg &> /dev/null; then
    echo "Error: dpkg not found." >&2
    exit 1
fi

# Execute main function
if [[ -n "$output_file" ]]; then
    get_package_info "$format" "$ppa_only" "$sort_by_repo" > "$output_file"
    echo "Output saved to: $output_file" >&2
else
    get_package_info "$format" "$ppa_only" "$sort_by_repo"
fi

Rendilo eseguibile:

chmod +x package-audit.sh

💡 Esempi d’uso

Uso di base

# List all packages with their repositories
./package-audit.sh

# List only PPA packages
./package-audit.sh -p

# Sort packages by repository
./package-audit.sh -s

# Show count per repository
./package-audit.sh -c

Uso avanzato

# Export to JSON
./package-audit.sh -f json > packages.json

# Export to CSV
./package-audit.sh -f csv > packages.csv

# Save PPA list to file
./package-audit.sh -p -o ppa-packages.txt

# Get PPA count only
./package-audit.sh -p -c

# Combine options
./package-audit.sh -p -s -o ppa-sorted.txt

🔍 Capire da dove arrivano i pacchetti

Controllare un singolo pacchetto

# Show package policy
apt-cache policy package-name

# Example output:
# package-name:
#   Installed: 1.2.3-1
#   Candidate: 1.2.3-1
#   Version table:
#  *** 1.2.3-1 500
#         500 https://ppa.launchpadcontent.net/user/repo/ubuntu noble/main amd64 Packages
#         100 /var/lib/dpkg/status

Trovare il repository di un pacchetto

# Which repository provides a package?
apt-cache policy package-name | grep -A1 "Installed:"

# List all available versions
apt-cache madison package-name

# Show package origin
apt-cache show package-name | grep -E "^(Package|Version|Origin):"

📊 Analisi dei repository

Analizzare la distribuzione dei repository
#!/bin/bash
# Analyze repository distribution

echo "Repository Distribution Analysis"
echo "================================="
echo ""

# Count by type
echo "By Type:"
./package-audit.sh -c | grep -E $'\t[0-9]+$' | \
    awk -F'\t' '{split($1, a, /[: ]/); types[a[1]] += $2} END {
        for (t in types) print t": "types[t]
    }' | sort -t: -k2 -nr

echo ""
echo "Top 10 Repositories:"
./package-audit.sh -c | grep -E $'\t[0-9]+$' | head -10
Trovare i pacchetti di un PPA specifico
# List packages from specific PPA
PPA_NAME="ppa-owner/ppa-name"

dpkg --get-selections | awk '!/deinstall$/ {print $1}' | \
while read package; do
    apt-cache policy "$package" | grep -q "$PPA_NAME" && echo "$package"
done
Confrontare due sistemi
# Generate package list on system 1
./package-audit.sh -f csv > system1.csv

# Generate package list on system 2
./package-audit.sh -f csv > system2.csv

# Compare
diff <(sort system1.csv) <(sort system2.csv)

# Or use comm for better comparison
comm -3 <(sort system1.csv) <(sort system2.csv)

🛠️ Gestione dei repository

Elencare i repository attivi

# List all configured repositories (one-line .list and deb822 .sources files)
grep -rE --include '*.list' --include '*.sources' '^(deb |URIs:|Suites:)' /etc/apt/sources.list /etc/apt/sources.list.d/

# List only PPAs
grep -rE --include '*.list' --include '*.sources' '^(deb |URIs:)' /etc/apt/sources.list.d/ | grep -E 'ppa\.launchpad(content)?\.net'

# Show repository keys (apt-key is deprecated: keys are plain files now)
ls -l /etc/apt/trusted.gpg.d/ /etc/apt/keyrings/ /usr/share/keyrings/ 2>/dev/null

Aggiungere e togliere repository

# Add PPA
sudo add-apt-repository ppa:user/repo
sudo apt update

# Remove PPA
sudo add-apt-repository --remove ppa:user/repo
sudo apt update

# Add third-party repository
echo "deb [signed-by=/usr/share/keyrings/repo.gpg] https://repo.url distribution component" | \
    sudo tee /etc/apt/sources.list.d/repo.list

# Remove third-party repository
sudo rm /etc/apt/sources.list.d/repo.list
sudo apt update

Pulire i repository inutilizzati

Trovare e togliere i PPA inutilizzati
#!/bin/bash
# Find PPAs with no installed packages

echo "Checking for unused PPAs..."

# Get list of PPAs
ppas=$(grep -rhE --include '*.list' --include '*.sources' '^(deb |URIs:)' /etc/apt/sources.list.d/ | \
       grep -oE 'ppa\.launchpad(content)?\.net/[^/ ]+/[^/ ]+' | \
       sed -E 's#ppa\.launchpad(content)?\.net/##' | \
       sort -u)

# Check each PPA
while IFS= read -r ppa; do
    count=$(dpkg --get-selections | awk '!/deinstall$/ {print $1}' | \
            xargs -I{} apt-cache policy {} 2>/dev/null | \
            grep -cE "ppa\.launchpad(content)?\.net/$ppa/")
    
    if [ "$count" -eq 0 ]; then
        echo "Unused PPA: $ppa (0 packages)"
        echo "  Remove with: sudo add-apt-repository --remove ppa:$ppa"
    else
        echo "Active PPA: $ppa ($count packages)"
    fi
done <<< "$ppas"

🔐 Audit di sicurezza

Individuare le fonti non fidate

# List packages from non-official repositories
./package-audit.sh | grep -v "Repository: archive.ubuntu.com" | \
                      grep -v "Repository: security.ubuntu.com" | \
                      grep -v "Local"

# Check for repositories without GPG verification
# (apt-cache policy does not show this, so look at the source files)
grep -rEi 'trusted=yes|^Trusted: *yes' /etc/apt/sources.list /etc/apt/sources.list.d/ 2>/dev/null

Audit dei pacchetti di terze parti

Generare un report dell'audit di sicurezza
#!/bin/bash
# Security audit report for packages

cat > security-audit.sh << 'EOF'
#!/bin/bash

echo "================================================"
echo "  Package Security Audit Report"
echo "  Generated: $(date)"
echo "================================================"
echo ""

echo "1. Packages from PPAs:"
echo "----------------------"
./package-audit.sh -p -c
echo ""

echo "2. Packages from Third-party Repositories:"
echo "-----------------------------------------"
./package-audit.sh | grep "Repository:" | \
    grep -v "archive.ubuntu.com" | \
    grep -v "security.ubuntu.com" | \
    grep -v "ppa.launchpad.net" | \
    sort -u
echo ""

echo "3. Locally Installed Packages:"
echo "------------------------------"
./package-audit.sh | grep "^Local" | wc -l
echo ""

echo "4. Unsigned Repositories:"
echo "------------------------"
grep -rEi 'trusted=yes|^Trusted: *yes' /etc/apt/sources.list /etc/apt/sources.list.d/ 2>/dev/null
echo ""

echo "5. Outdated Package Keys:"
echo "------------------------"
for k in /etc/apt/trusted.gpg.d/*.gpg /etc/apt/keyrings/*.gpg /usr/share/keyrings/*.gpg; do
    [ -f "$k" ] && gpg --show-keys "$k" 2>/dev/null | grep -q "expired" && echo "$k"
done
EOF

chmod +x security-audit.sh
./security-audit.sh

📋 Operazioni comuni

Esportare l’elenco dei pacchetti per il backup

# Save complete package list with sources
./package-audit.sh -f csv > package-backup-$(date +%Y%m%d).csv

# Save only package names
dpkg --get-selections | grep -v deinstall > packages-$(date +%Y%m%d).txt

# Save with versions
dpkg -l | grep ^ii > packages-versioned-$(date +%Y%m%d).txt

Ripristinare i pacchetti su un sistema nuovo

# From package-audit.sh CSV
# 1. Add repositories first (manually or script)
# 2. Install packages
cut -d, -f1 package-backup.csv | tail -n +2 | \
    xargs sudo apt install -y

# From dpkg list
sudo dpkg --set-selections < packages.txt
sudo apt-get dselect-upgrade

Trovare le dipendenze di un pacchetto

# Show dependencies
apt-cache depends package-name

# Show reverse dependencies
apt-cache rdepends package-name

# Show all dependency chain
apt-cache depends --recurse --no-recommends --no-suggests --no-conflicts \
    --no-breaks --no-replaces --no-enhances package-name

🔧 Risoluzione dei problemi

Lo script è lento

Problema: lo script ci mette troppo sui sistemi con molti pacchetti

Soluzione:

# Cache apt-cache policy output
dpkg --get-selections | awk '!/deinstall$/ {print $1}' | \
    xargs apt-cache policy > /tmp/apt-policy-cache.txt

# Then process the cache file instead of calling apt-cache repeatedly
# This speeds up processing significantly
Manca perl o qualche dipendenza

Problema: comando perl non trovato

Soluzione:

sudo apt install perl

# Alternative without perl
dpkg --get-selections | awk '!/deinstall$/ {print $1}' | \
while read pkg; do
    repo=$(apt-cache policy "$pkg" | grep -m1 "500 http" | \
           awk '{print $2}')
    echo "$pkg: $repo"
done
Non si riesce a capire l'origine di alcuni pacchetti

Problema: per alcuni pacchetti il repository risulta «Other» oppure vuoto

Soluzione:

# Check package files directly
dpkg -L package-name | head -5

# Check package origin
dpkg -s package-name | grep -E "^(Package|Version|Status|Origin):"

# Check if it's a manually installed .deb
grep "Package: package-name" /var/lib/dpkg/status -A20 | grep "Origin"

💡 Casi d’uso avanzati

Tenere d’occhio i cambiamenti dei repository

Tracciare nel tempo i cambiamenti dei repository
#!/bin/bash
# Track repository changes

LOGDIR="$HOME/package-logs"
mkdir -p "$LOGDIR"

LOGFILE="$LOGDIR/packages-$(date +%Y%m%d-%H%M%S).csv"

# Generate current snapshot
./package-audit.sh -f csv > "$LOGFILE"

echo "Snapshot saved: $LOGFILE"

# Compare with previous
PREVIOUS=$(ls -t "$LOGDIR"/packages-*.csv | sed -n '2p')

if [ -n "$PREVIOUS" ]; then
    echo ""
    echo "Changes since last snapshot:"
    echo "----------------------------"
    
    # Added packages
    echo "Added:"
    comm -13 <(sort "$PREVIOUS") <(sort "$LOGFILE") | head -10
    
    # Removed packages
    echo "Removed:"
    comm -23 <(sort "$PREVIOUS") <(sort "$LOGFILE") | head -10
fi

Da impostare come job di cron:

# Run weekly
0 0 * * 0 /path/to/track-repos.sh

Generare la documentazione dell’installazione

Creare la documentazione in markdown del software installato
#!/bin/bash
# Generate installation documentation

cat > system-documentation.md << EOF
# System Package Documentation
Generated: $(date)
Hostname: $(hostname)

## Package Summary

$(./package-audit.sh -c)

## Packages by Repository

$(./package-audit.sh -s)

## PPA Packages

$(./package-audit.sh -p)

## Repository Configuration

\`\`\`
$(grep -rE --include '*.list' --include '*.sources' '^(deb |URIs:|Suites:)' /etc/apt/sources.list /etc/apt/sources.list.d/)
\`\`\`

## System Information

- OS: $(lsb_release -d | cut -f2-)
- Kernel: $(uname -r)
- Architecture: $(dpkg --print-architecture)

EOF

echo "Documentation generated: system-documentation.md"

📚 Riferimento dei comandi

Comandi essenziali

ComandoA cosa serve
dpkg --get-selectionsElenca i pacchetti installati
apt-cache policy PKGMostra le fonti del pacchetto
apt-cache madison PKGElenca le versioni disponibili
apt-cache show PKGMostra i dettagli del pacchetto
apt-cache depends PKGMostra le dipendenze
apt-cache rdepends PKGMostra le dipendenze inverse
dpkg -L PKGElenca i file del pacchetto
dpkg -S /path/to/fileTrova il pacchetto a cui appartiene un file

Gestione dei repository

ComandoA cosa serve
add-apt-repository ppa:user/repoAggiunge un PPA
add-apt-repository --remove ppa:user/repoToglie un PPA
ls /etc/apt/keyrings/ /etc/apt/trusted.gpg.d/Elenca le chiavi dei repository (apt-key è deprecato)
apt updateAggiorna gli elenchi dei pacchetti
apt-cache search TERMCerca tra i pacchetti

🎯 Buone pratiche

  1. Audit regolari: fai l’audit dei pacchetti una volta al mese
  2. Documenta i cambiamenti: tieni un registro dei repository che aggiungi
  3. Pochi PPA: usa solo PPA fidati
  4. La sicurezza prima di tutto: controlla regolarmente le fonti di terze parti
  5. Elenchi di backup: salva l’elenco dei pacchetti prima di ogni modifica importante
  6. Pulizia regolare: togli i repository che non usi
  7. Blocca le versioni: blocca i pacchetti critici sulla versione installata (per un vero pinning usa /etc/apt/preferences.d/)

Esempio di blocco della versione

# Hold package at the installed version (not real pinning: see /etc/apt/preferences)
sudo apt-mark hold package-name

# Show held packages
apt-mark showhold

# Unhold package
sudo apt-mark unhold package-name

🔄 Operazioni collegate

Pulire la cache dei pacchetti

# Remove downloaded package files
sudo apt clean

# Remove orphaned packages
sudo apt autoremove

# Remove cached .deb files that can no longer be downloaded
sudo apt-get autoclean

Sistemare i pacchetti rotti

# Fix broken dependencies
sudo apt --fix-broken install

# Reconfigure packages
sudo dpkg --configure -a

# Force reinstall package
sudo apt install --reinstall package-name

Padroneggia la gestione dei pacchetti, per un sistema pulito e sicuro!