Surveiller les changements dans des répertoires critiques conditionne la sécurité et la maintenance d'un serveur. Avec inotify-tools, vous détectez en temps réel la création, la suppression ou la modification de fichiers et déclenchez des alertes email. Alternativement, découvrez comment utiliser les path units systemd pour une approche native.
Prérequis
- Serveur Linux (Debian, Ubuntu, RHEL, CentOS)
- inotify-tools installé
- Un agent mail configuré (postfix, msmtp, etc.)
Installation d'inotify-tools
sudo apt update
sudo apt install inotify-tools -y
Script de surveillance
Créez un script bash watch_and_alert.sh :
#!/bin/bash
# Répertoire à surveiller
WATCH_DIR="/path/to/directory"
# Email de notification
ALERT_EMAIL="admin@example.com"
inotifywait -m -r -e create,modify,delete "$WATCH_DIR" --format '%T %w %f %e' --timefmt '%F %T' | while read TIMESTAMP DIR FILE EVENT; do
echo -e "Sujet: Alerte inotify\n\nFichier: $DIR$FILE\nÉvénement: $EVENT\nDate: $TIMESTAMP" | mail -s "Alerte inotify: $FILE $EVENT" "$ALERT_EMAIL"
done
Rendez-le exécutable :
chmod +x watch_and_alert.sh
Exécution en arrière-plan
Utilisez screen, tmux ou un service systemd :
Exemple service systemd :
Pour créer des services systemd personnalisés, créez /etc/systemd/system/inotify-alert.service :
[Unit]
Description=Surveillance inotify avec alertes email
[Service]
ExecStart=/usr/local/bin/watch_and_alert.sh
Restart=always
[Install]
WantedBy=multi-user.target
Activez et démarrez :
sudo systemctl daemon-reload
sudo systemctl enable --now inotify-alert.service
Tests
Ajoutez, modifiez ou supprimez un fichier dans le répertoire surveillé et vérifiez la réception de l'email.
Conclusion
Avec inotify-tools et un simple script bash, vous surveillez vos fichiers et recevez des alertes instantanées. De quoi réagir plus vite et fermer une porte de plus sur votre infrastructure.


