身為網路管理員,日常離不開對流量日誌的檢視。使用者上過哪些站、哪個網段吃掉了最多頻寬、哪台主機行為異常,答案往往就藏在 Squid 的 access.log 裡。問題是,原始日誌實在不太友善——SARG(Squid Analysis Report Generator)正是為了解決這個痛點而生。
Squid 功能強大,但輸出的每一行都是壓縮過的資訊。比如下面這段:
1404788984.429 1162 172.17.1.23 TCP_MISS/302 436 GET https://facebook.com/ - DIRECT/173.252.110.27 text/html 1404788985.046 12416 172.17.1.23 TCP_MISS/200 4169 CONNECT stats.pusher.com:443 - DIRECT/173.255.223.127 - 1404788986.124 174 172.17.1.23 TCP_MISS/200 955 POST https://ocsp.digicert.com/ - DIRECT/117.18.237.29 application/ocsp-response 1404788989.738 342 172.17.1.23 TCP_MISS/200 3890 CONNECT www.google.com:443 - DIRECT/74.125.200.106 - 1404788990.839 3939 172.17.1.23 TCP_MISS/200 78944 CONNECT fbstatic-a.akamaihd.net:443 - DIRECT/184.26.162.35 -
時間戳是 Unix 紀元秒數、耗時以毫秒計、狀態碼夾在協定後面……人工比對簡直是惡夢。SARG 會把這些欄位翻譯成人看得懂的報表:誰在什麼時候造訪了哪個網站、命中還是未命中、下載了多少位元組。
先用 yum 把編譯與服務所需的套件補齊:
# yum install gcc make wget httpd crond
接著啟動 Apache 與排程服務,並設為開機自啟,這樣後續才能用瀏覽器看報表、用 cron 定時產生報表:
# service httpd start; service crond start # chkconfig httpd on; chkconfig crond on
# wget https://downloads.sourceforge.net/project/sarg/sarg/sarg-2.3.8/sarg-2.3.8.tar.gz # tar zxvf sarg-2.3.8.tar.gz # cd sarg-2.3.8
如果你的環境是 64 位元 Linux,直接編譯會在寫入位元組數時出問題,必須先替 log.c 打上型別轉換的補丁:
1506c1506
< if (fprintf(ufile->file, "%s\t%s\t%s\t%s\t%"PRIi64"\t%s\t%ld\t%s\n",dia,hora,ip,url,nbytes,code,elap_time,smartfilter) <=0) {
---
> if (fprintf(ufile->file, "%s\t%s\t%s\t%s\t%"PRIi64"\t%s\t%ld\t%s\n",dia,hora,ip,url,(int64_t)nbytes,code,elap_time,smartfilter) <=0) {
1513c1513
< fprintf(fp_log, "%s\t%s\t%s\t%s\t%s\t%"PRIi64"\t%s\t%ld\t%s\n",dia,hora,user,ip,url,nbytes,code,elap_time,smartfilter);
---
> fprintf(fp_log, "%s\t%s\t%s\t%s\t%s\t%"PRIi64"\t%s\t%ld\t%s\n",dia,hora,user,ip,url,(int64_t)nbytes,code,elap_time,smartfilter);
1564c1564
< printf("LEN=\t%"PRIi64"\n",nbytes);
---
> printf("LEN=\t%"PRIi64"\n",(int64_t)nbytes);
# ./configure # make # make install
安裝完成後,設定檔位於 /usr/local/etc/sarg.conf。以下是一份可直接參考的範例:
# vim /usr/local/etc/sarg.conf access_log /var/log/squid/access.log temporary_dir /tmp output_dir /var/www/html/squid-reports date_format e ## 這裡採用歐洲的 DD-MM-YYYY 格式 ## overwrite_report yes ## 同一天/週/月只保留一份報表 ##
# sarg -x
若一切正常,SARG 會解析 Squid 日誌,並在 /var/www/html/squid-reports 底下生成靜態頁面,用瀏覽器開啟 https://<服務器IP>/squid-reports/ 即可查看。
報表的時間範圍由 -d 參數決定,形式為 day-n、week-n 或 month-n,n 代表往前推的數量。例如 week-1 產生上一週的報表,day-2 則是前兩天。
實務上最常見的做法是每天自動產出昨日報表:
# vim /etc/cron.daily/sarg #!/bin/sh /usr/local/bin/sarg -d day-1 # chmod 755 /usr/local/bin/sarg
設定好之後,系統每天都會自動整理一份流量報告,隨時透過網頁介面調閱即可。對系統管理員來說,這代表不必再逐行解讀時間戳,就能掌握熱門站點、重度使用者與異常連線。