Sunday, March 7, 2010

Web traffic script

Web traffic script



The Web pages are hosted on a FreeBSD Web server. FreeBSD's date command makes determining yesterday's date easy. The script is run via the cron daemon every morning to email me the results.

#!/bin/sh

# Get yesterday's date in dd/mmm/yyyy format
YESTERDAYS_DATE=`date -v -1d +%d/%b/%Y`

# Get yesterday's access_log information in a temporary file
grep $YESTERDAYS_DATE /www/logs/access_log > /tmp/access_log

# For each Web page, count the number of hits
for i in `cd /www/htdocs/brandonhutchinson; ls *.html`
do
echo -e "`grep $i /tmp/access_log | sort -u | wc -l` $i" >> /tmp/web_traffic.txt
done

# Tally and print the total number of visitors; mail results
(echo -e "Total visitors: `awk '{ hits += $1 } END { print hits }' < /tmp/web_traffic.txt`\n" && sort -rn /tmp/web_traffic.txt) | mail -s "brandonhutchinson.com Web traffic" brandonhutchinson@hotmail.com

# Remove temporary files
rm /tmp/access_log
rm /tmp/web_traffic.txt

No comments: