Last active
February 22, 2024 03:57
-
-
Save adamz01h/d43690da056abab4ec96aa28ff18df55 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # requires inotify-tools and mailutils and rsync | |
| #echo "fs.inotify.max_user_watches=524288" | sudo tee -a /etc/sysctl.d/99-sysctl.conf | |
| # Directory to be monitored | |
| MONITOR_DIR="/var/www/html" | |
| # Directory to store file backups | |
| BACKUP_DIR="/var/www/filewatcher_backup/html" | |
| mkdir -p "$BACKUP_DIR" | |
| # Directory to store archived versions of files | |
| ARCHIVE_DIR="/var/www/filewatcher_backup/archived" | |
| mkdir -p "$ARCHIVE_DIR" | |
| # Email settings | |
| EMAIL_SUBJECT="File Changes Detected" | |
| EMAIL_TO="[email protected]" | |
| EMAIL_FROM="[email protected]" | |
| # File to log changes | |
| TMP_FILE="/var/log/file_changes.log" | |
| >> "$TMP_FILE" # Clear or create the log file at start | |
| # Archive a file version before it's modified or deleted | |
| archive_file() { | |
| local event_type="$1" | |
| local file="$2" | |
| local timestamp=$(date +%Y%m%d%H%M%S) | |
| local relative_path="${file#$MONITOR_DIR/}" | |
| local archive_path="$ARCHIVE_DIR/$relative_path" | |
| # Create archive subdirectories as needed | |
| mkdir -p "$(dirname "$archive_path")" | |
| # For delete events, just log the action since the file no longer exists | |
| if [[ "$event_type" == *"DELETE"* || "$event_type" == *"MOVED_FROM"* ]]; then | |
| echo "$timestamp: $event_type - $file" >> "$archive_path.$timestamp.log" | |
| else | |
| # Copy the file to the archive with a timestamp | |
| cp "$file" "$archive_path.$timestamp" | |
| echo "$timestamp: $event_type - $file" >> "$TMP_FILE" | |
| fi | |
| } | |
| # Synchronize the backup | |
| sync_backup() { | |
| rsync -a --delete "$MONITOR_DIR/" "$BACKUP_DIR/" | |
| } | |
| # Function to send email and clear log | |
| send_email_if_needed() { | |
| if [ -s "$TMP_FILE" ]; then | |
| mail -s "$EMAIL_SUBJECT" -r "$EMAIL_FROM" "$EMAIL_TO" < "$TMP_FILE" | |
| > "$TMP_FILE" # Clear the file after sending the email | |
| fi | |
| } | |
| # Initial backup synchronization | |
| sync_backup | |
| # Monitor for modifications, deletions, and moves | |
| inotifywait -m -r -e modify -e delete -e move --format '%e %w%f' "$MONITOR_DIR" | while read event file; do | |
| archive_file "$event" "$file" | |
| sync_backup | |
| done & | |
| # Periodically send email updates | |
| while true; do | |
| sleep 600 # 10 minutes | |
| send_email_if_needed | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment