The script shown below can be run via a CRON job (we run it every 15 minutes). It checks the Nextcloud apache2 log and sends out an email if a Share has been accessed since the last time the CRON job ran. The curl command which sends out the email uses the free Twillo SendGrid service,
#!/usr/bin/env bash
#
FILE="/home/karmst/Documents/nextcloud_access.log"
mapfile -t my_array < <( grep -E "^.+GET /s/.+" /var/log/apache2/sites/nextcloud_access.log )
counter=0
for value in "${my_array[@]}"
do
to_check=$(echo "$value" | sed -E 's/(^.+\[.+\].+)( .+)$/\1/')
share_name=$(echo "$value" | sed -E 's/(^.+GET )(.+) (HTTP.+)$/\2/')
result=$(echo "$value" | sed -E 's/(^.+GET )(.+?) (HTTP.+?)"\s([0-9]{3})(.+$)/\4/')
to_check_replace_1=${to_check//[/\\[}
to_check_replace_2=${to_check_replace_1//]/\\]}
downloads_file_check=$( grep "$to_check_replace_2" $FILE)
if [ -z "$downloads_file_check" ]; then
counter=$((counter+1))
downloads_to_file=$( echo "$value" >> $FILE )
IP=$(echo "$value" | sed -E 's/(^.+) - - (.+)$/\1/')
DATE=$(echo "$value" | sed -E 's/^.+(\[.+\])(.+)$/\1/')
LOCATION=$(curl ipinfo.io/"$IP"/city)
THECONTENT+=$(echo Date : $DATE"<br>"Location : $LOCATION"<br>"Address : $IP"<br>"Share : $share_name"<br>"Result : $result"<br><br>")
fi
done
SUBJECT=$(echo Belkast fileshare was accessed $counter time\(s\))
if [ -n "$THECONTENT" ]; then
curl --request POST \
--url https://api.sendgrid.com/v3/mail/send \
--header 'Authorization: Bearer API-KEY' \
--header 'Content-Type: application/json' \
--data '{"personalizations": [{"to": [{"email": "test@example.com"}]}],"from": {"email": "admin@example.com"},"subject": '\""$SUBJECT\""',"content": [{"type": "text/html", "value": '\""$THECONTENT\""'}]}'
fi
exit 0;
The content of the email is shown below. Only one email is sent, regardless of how many times the Share was accessed.
Date : [22/Oct/2024:13:33:50 +0100]
Location : Boston
Address : 172.172.172.1
Share : /s/36Tm5RS38bJ5D5wfgB
Result : 404
Date : [22/Oct/2024:15:58:53 +0100]
Location : Boston
Address : 172.172.172.1
Share : /s/36Tm5RS38bJ5D5wfgB
Result : 404
Date : [22/Oct/2024:16:36:50 +0100]
Location : Boston
Address : 172.172.172.1
Share : /s/36Tm5RS38bJ5D5wfgB
Result : 404