Proxmox: spegnere (e riaccendere) LXC e VM via script Bash (Aggiornato)

| |

Milano, estate, vorrei poterti dire che le mancanze di corrente sono una novità degli ultimi tempi ma no, mentirei spudoratamente.
È un appuntamento estivo quasi puntuale tanto quanto le tasse o peggio. Fortunato chi può vantarsi di ricevere preavvisi in grado di anticipare di qualche giorno l’evento, generalmente lasciati attaccati alla “meno peggio” in bacheca condominiale.

Spegnere correttamente le macchine virtuali e gli LXC in Proxmox diventa quindi fondamentale tanto quanto programmare spegnimento e accensione dei NAS di casa. L’idea è quella di usare i comandi qm/pct nativi di Proxmox (e, possibilmente, tracciare le operazioni eseguite all’interno di in un file di log).

Ho messo in piedi due script Bash che girano via Crontab sul nodo Proxmox. Ho caricato gli script su Gist, te li propongo di seguito perché – magari – potrebbero tornarti utili:

#!/bin/bash
# Proxmox: Shutdown VMs and LXCs (GSolone, 2025)
# This script stops all running VMs and LXC containers, excluding specified IDs, and logs the operation.
# In DEBUG mode, it only stops one VM and one LXC container for testing purposes, ignoring exclusions.
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
logfile="/var/log/proxmox_shutdown.log"
LOCKFILE="/tmp/proxmox_shutdown.lock"
# Timestamp helper
timestamp() {
date +"%Y-%m-%d %H:%M:%S"
}
# Check for existing lock
if [ -e "$LOCKFILE" ]; then
echo "[$(timestamp)] Lockfile exists, exiting ..." >> $logfile
exit 1
fi
touch "$LOCKFILE"
trap "rm -f $LOCKFILE" EXIT
# === Config ===
EXCLUDED_VMS=""
EXCLUDED_LXCS=""
DEBUG=false
DEBUG_VM_ID="" # Replace with a test VM ID
DEBUG_LXC_ID="" # Replace with a test LXC ID
if [[ "$1" == "--debug" ]]; then
DEBUG=true
fi
IFS=',' read -ra SKIP_VMS <<< "$EXCLUDED_VMS"
IFS=',' read -ra SKIP_LXCS <<< "$EXCLUDED_LXCS"
echo "[$(timestamp)] Shutdown script started (DEBUG=$DEBUG)" >> $logfile
# === Shutdown VMs ===
for vmid in $(qm list | awk 'NR>1 && $3 == "running" {print $1}'); do
if [[ "$DEBUG" == true ]]; then
if [[ "$vmid" == "$DEBUG_VM_ID" ]]; then
echo "[$(timestamp)] [DEBUG] Shutting down test VM ID $vmid" >> $logfile
qm stop $vmid
break
else
continue
fi
fi
if [[ " ${SKIP_VMS[@]} " =~ " $vmid " ]]; then
echo "[$(timestamp)] Skipping VM ID $vmid" >> $logfile
continue
fi
echo "[$(timestamp)] Shutting down VM ID $vmid" >> $logfile
qm stop $vmid
done
# === Shutdown LXC ===
for ct in $(pct list | awk 'NR>1 && $2 == "running" {print $1}'); do
if [[ "$DEBUG" == true ]]; then
if [[ "$ct" == "$DEBUG_LXC_ID" ]]; then
echo "[$(timestamp)] [DEBUG] Shutting down test LXC Container ID $ct" >> $logfile
pct stop $ct
break
else
continue
fi
fi
if [[ " ${SKIP_LXCS[@]} " =~ " $ct " ]]; then
echo "[$(timestamp)] Skipping LXC Container ID $ct" >> $logfile
continue
fi
echo "[$(timestamp)] Shutting down LXC Container ID $ct" >> $logfile
pct stop $ct
done
echo "[$(timestamp)] Shutdown script completed" >> $logfile
#!/bin/bash
# Proxmox: Start VMs and LXCs (GSolone, 2025)
# This script starts all stopped VMs and LXC containers, excluding specified IDs, and logs the operation.
# In DEBUG mode, it only starts one VM and one LXC container for testing purposes, ignoring exclusions.
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
logfile="/var/log/proxmox_startup.log"
LOCKFILE="/tmp/proxmox_startup.lock"
# Timestamp helper
timestamp() {
date +"%Y-%m-%d %H:%M:%S"
}
# Check for existing lock
if [ -e "$LOCKFILE" ]; then
echo "[$(timestamp)] Lockfile exists, exiting ..." >> $logfile
exit 1
fi
touch "$LOCKFILE"
trap "rm -f $LOCKFILE" EXIT
# === Config ===
EXCLUDED_VMS=""
EXCLUDED_LXCS=""
DEBUG=false
DEBUG_VM_ID="" # Replace with a test VM ID
DEBUG_LXC_ID="" # Replace with a test LXC ID
if [[ "$1" == "--debug" ]]; then
DEBUG=true
fi
IFS=',' read -ra SKIP_VMS <<< "$EXCLUDED_VMS"
IFS=',' read -ra SKIP_LXCS <<< "$EXCLUDED_LXCS"
echo "[$(timestamp)] Startup script started (DEBUG=$DEBUG)" >> $logfile
# === Start VMs ===
for vmid in $(qm list | awk 'NR>1 && $3 == "stopped" {print $1}'); do
if [[ "$DEBUG" == true ]]; then
if [[ "$vmid" == "$DEBUG_VM_ID" ]]; then
echo "[$(timestamp)] [DEBUG] Starting test VM ID $vmid" >> $logfile
qm start $vmid
break
else
continue
fi
fi
if [[ " ${SKIP_VMS[@]} " =~ " $vmid " ]]; then
echo "[$(timestamp)] Skipping VM ID $vmid" >> $logfile
continue
fi
echo "[$(timestamp)] Starting VM ID $vmid" >> $logfile
qm start $vmid
done
# === Start LXC ===
for ct in $(pct list | awk 'NR>1 && $2 == "stopped" {print $1}'); do
if [[ "$DEBUG" == true ]]; then
if [[ "$ct" == "$DEBUG_LXC_ID" ]]; then
echo "[$(timestamp)] [DEBUG] Starting test LXC Container ID $ct" >> $logfile
pct start $ct
break
else
continue
fi
fi
if [[ " ${SKIP_LXCS[@]} " =~ " $ct " ]]; then
echo "[$(timestamp)] Skipping LXC Container ID $ct" >> $logfile
continue
fi
echo "[$(timestamp)] Starting LXC Container ID $ct" >> $logfile
pct start $ct
done
echo "[$(timestamp)] Startup script completed" >> $logfile

Prossimo step: vorrei integrare uno switch di debug per permettere di usare entrambi gli script puntando a una macchina VM e un LXC da “sacrificare” per effettuare un test. E poi mi piacerebbe prevedere la possibilità di ruotare i log nel caso in cui questi diventino un pelo troppo “in carne“. Nulla che non si possa fare con un attimo di calma, aggiornerò la pubblicazione su GitHub non appena ne avrò modo.

Aggiornato

L’ho fatto, ho aggiornato entrambi gli script. Quello che hai a disposizione adesso rispetto alla prima versione:

  • Gestione PATH: compatibilità con il Crontab, ho avuto problemi durante l’esecuzione programmata e mi sono accorto che mancava l’export del PATH!
  • Lockfile anti-esecuzione multipla: puoi avviare una sola istanza dello script alla volta, al termine potrai farlo ancora.
  • Timestamp aggiornato dinamicamente per ogni log: più per estetica che altro, ma così il log diventa più preciso.
  • Modalità debug per test sicuri: puoi includere gli ID di VM e LXC da sacrificare all’altare dei tuoi test.
  • Esclusione VM/LXC personalizzata: così da evitare che vengano spenti insieme agli altri.

Se hai dubbi, l’area commenti è a tua totale disposizione! 🙂👋

#KeepItSimple

Correzioni, suggerimenti? Lascia un commento nell'apposita area qui di seguito o contattami privatamente.
Ti è piaciuto l'articolo? Offrimi un caffè! ☕ :-)

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Commenti
Oldest
Newest Most Voted
Inline Feedbacks
View all comments