Формирование отчетов с использованием sarg

Задача на сегодня стоит следующая - организовать ежемесячный сбор статистики о работе пользователей в интернет с отправкой отчета на email. Предполагается, что squid настроен и работает правильно. :) Используемая ОС:
  1. # uname -a
  2. FreeBSD srv-home 6.4-RELEASE-p7 FreeBSD 6.4-RELEASE-p7 #0: Sat Oct  3 20:59:38 YEKST 2009 root@home.ru:/usr/obj/usr/src/sys/HAUNTED  i386
Идем в порты ставить sarg:
  1. # cd /usr/ports/www/sarg
  2. # make install clean
Из предложенных опций я ничего не выбрал. После установки идем править конфиг sarg - /usr/local/etc/sarg/sarg.conf. У меня он получился такого содержания:
  1. # sarg.conf
  2. #
  3. # TAG:  language 
  4. #	Доступные языки:
  5. #		Bulgarian_windows1251
  6. #		Catalan
  7. #		Czech
  8. #		Czech_UTF8
  9. #		Dutch
  10. #		English
  11. #		French
  12. #		German
  13. #		Greek
  14. #		Hungarian
  15. #		Indonesian
  16. #		Italian
  17. #		Japanese
  18. #		Latvian
  19. #		Polish
  20. #		Portuguese
  21. #		Romanian
  22. #		Russian_koi8
  23. #		Russian_UFT-8
  24. #		Russian_windows1251
  25. #		Serbian
  26. #		Slovak
  27. #		Spanish
  28. #		Turkish
  29. #
  30. language Russian_koi8
  31.  
  32. # TAG:  access_log file
  33. #       Где находится access.log squid,а
  34. #       sarg -l file
  35. #
  36. access_log /usr/local/squid/logs/access.log
  37.  
  38. # TAG: graphs yes|no
  39. #	Использовать графики, где это возможно.
  40. #           graph_days_bytes_bar_color blue|green|yellow|orange|brown|red
  41. #
  42. #graphs yes
  43. #graph_days_bytes_bar_color orange
  44.  
  45. # TAG:	title
  46. # 	Название html страницы.
  47. #
  48. title "Squid User Access Reports"
  49.  
  50. # TAG:	font_face
  51. # 	Шрифт используемый в html странице.
  52. #
  53. #font_face Tahoma,Verdana,Arial
  54.  
  55. # TAG:	header_color
  56. # 	Цвет заголовка
  57. #
  58. #header_color darkblue
  59.  
  60. # TAG:	header_bgcolor
  61. # 	Цвет фона в заголовке
  62. #
  63. #header_bgcolor blanchedalmond
  64.  
  65. # TAG:	font_size
  66. # 	Размер шрифта
  67. #
  68. #font_size 9px
  69.  
  70. # TAG:	header_font_size
  71. # 	Размер шрифта в заголовке
  72. #
  73. #header_font_size 9px
  74.  
  75. # TAG:	title_font_size
  76. # 	Размер шрифта названия
  77. #
  78. #title_font_size 11px
  79.  
  80. # TAG:	background_color
  81. # TAG:	background_color
  82. #	Фоновый цет html страницы
  83. #
  84. # background_color white
  85.  
  86. # TAG:	text_color
  87. #	Цвет шрифта html страницы
  88. #
  89. #text_color #000000
  90.  
  91. # TAG:	text_bgcolor
  92. #	Фоновый цвет текста html страницы
  93. #
  94. #text_bgcolor lavender
  95.  
  96. # TAG:	title_color
  97. #	Звет названия html страницы
  98. #
  99. #title_color green
  100.  
  101. # TAG:	logo_image
  102. #	Логотип.
  103. #
  104. #logo_image none
  105.  
  106. # TAG:	logo_text
  107. #	Текст логотипа.
  108. #
  109. #logo_text ""
  110.  
  111. # TAG:	logo_text_color
  112. #	Html page logo texti color.
  113. #
  114. #logo_text_color #000000
  115.  
  116. # TAG:	logo_image_size
  117. #	Html page logo image size. 
  118. #       width height
  119. #
  120. #image_size 80 45
  121.  
  122. # TAG:	background_image
  123. #	Фоновая картика на html странице
  124. #
  125. #background_image none
  126.  
  127. # TAG:  password
  128. #       Файл с паролями пользователей используемый squid для утентификации.
  129. #       Если используется, то генерируется отчет только для этих пользователей.
  130. #
  131. #password none
  132.  
  133. # TAG:  temporary_dir
  134. #       Директория для хранения временных файлов
  135. #       sarg -w dir
  136. #
  137. temporary_dir /tmp
  138.  
  139. # TAG:  output_dir
  140. #       Директория, в которую sarg будет сохранять отчеты
  141. #       sarg -o dir
  142. #
  143. output_dir /usr/local/www/sarg_reports
  144.  
  145. # TAG:  output_email
  146. #       Мыло, на которое будут отправяться отчеты. Если используется этот параметр, то html отчеты не будут генерироваться.
  147. #       sarg -e email
  148. #
  149. output_email admin@home.ru
  150.  
  151. # TAG:  resolve_ip yes/no
  152. #       Преобразовывать ip адреса в имена
  153. #       sarg -n
  154. resolve_ip no
  155.  
  156. # TAG:  user_ip yes/no
  157. #       Использовать ip адрес вместо идентификатора пользователя в отчетах.
  158. #       sarg -p
  159. #user_ip no
  160.  
  161. # TAG:  topuser_sort_field field normal/reverse
  162. #       Сортировать по колонке для создания рэйтинга самых активных пользователей.
  163. #       Allowed fields: USER CONNECT BYTES TIME
  164. #
  165. #topuser_sort_field BYTES reverse
  166.  
  167. # TAG:  user_sort_field field normal/reverse
  168. #       Сортировать по колонке в отчете о пользователях.
  169. #       Allowed fields: SITE CONNECT BYTES TIME
  170. #
  171. #user_sort_field BYTES reverse
  172.  
  173. # TAG:  exclude_users file
  174. #       Пользователи присутствующие в этом файле не будут включены в отчет.
  175. #       you can use indexonly to have only index.html file.
  176. #
  177. exclude_users none
  178.  
  179. # TAG:  exclude_hosts file
  180. #       Хосты, домены, подсети присутствующие в файле будут исключены из отчета.
  181. #
  182. #       Eg.: 192.168.10.10 - исключить только ip адрес
  183. #            192.168.10.0  - исключить подсеть
  184. #            s1.acme.foo   - исключить только хост
  185. #            acme.foo      - исключаем весь домен
  186. #
  187. exclude_hosts none
  188.  
  189. # TAG:  useragent_log file
  190. #       Путь до файла useragent.log для генерации отчета о используемых браузеров.
  191. #
  192. #useragent_log none
  193.  
  194. # TAG:  date_format
  195. #       Формат даты в отчетах: e (European=dd/mm/yy), u (American=mm/dd/yy), w (Weekly=yy.ww)
  196. #       
  197. #date_format u
  198.  
  199. # TAG:  per_user_limit file MB
  200. #       Saves userid on file if download exceed n MB.
  201. #       This option allow you to disable user access if user exceed a download limit.
  202. #       
  203. #per_user_limit none
  204.  
  205. # TAG: lastlog n
  206. #      Как много файлов-отчетов должно хранится в директории с отчетами.
  207. #      The oldest report file will be automatically removed.
  208. #      0 - не ограничено.
  209. #
  210. #lastlog 0
  211.  
  212. # TAG: remove_temp_files yes
  213. #      Удалять временные файлы: geral, usuarios, top, periodo из главной директории(это где лежат отчеты).
  214. #
  215. remove_temp_files yes
  216.  
  217. # TAG: index yes|no|only
  218. #      Создавать основной index.html.
  219. #      only - создавать только основной index.html
  220. #
  221. index yes
  222.  
  223. # TAG: index_tree date|file
  224. #      How to generate the index.
  225. #
  226. #index_tree file
  227.  
  228. # TAG: overwrite_report yes|no
  229. #      yes - если отчет с такой датой уже существует, то он будет перезаписан.
  230. #       no - если отчет с такой датой уже существует, то он будет переименован в filename.n, filename.n+1
  231. #
  232. overwrite_report no
  233.  
  234. # TAG: records_without_userid ignore|ip|everybody
  235. #      What can I do with records without user id (no authentication) in access.log file ?
  236. #
  237. #      ignore - This record will be ignored.
  238. #          ip - Use ip address instead. (default)
  239. #   everybody - Use "everybody" instead.
  240. #
  241. #records_without_userid ip
  242.  
  243. # TAG: use_comma no|yes
  244. #      Use comma instead point in reports.
  245. #      Eg.: use_comma yes => 23,450,110
  246. #           use_comma no  => 23.450.110
  247. #
  248. #use_comma no
  249.  
  250. # TAG: mail_utility mail|mailx
  251. #      Команда, используемая для отправвки почты через SMTP
  252. #
  253. mail_utility mail
  254.  
  255. # TAG: topsites_num n
  256. #      How many sites in topsites report.
  257. #
  258. #topsites_num 100
  259.  
  260. # TAG: topsites_sort_order CONNECT|BYTES A|D
  261. #      Sort for topsites report, where A=Ascendent, D=Descendent
  262. #
  263. #topsites_sort_order CONNECT D
  264.  
  265. # TAG: index_sort_order A/D
  266. #      Sort for index.html, where A=Ascendent, D=Descendent
  267. #
  268. #index_sort_order D
  269.  
  270. # TAG: exclude_codes file
  271. #      Ignore records with these codes. Eg.: NONE/400
  272. #
  273. exclude_codes /usr/local/etc/sarg/exclude_codes
  274.  
  275. # TAG: replace_index string
  276. #      Replace "index.html" in the main index file with this string
  277. #      If null "index.html" is used 
  278. #
  279. #replace_index <?php echo str_replace(".", "_", $REMOTE_ADDR); echo ".html"; ?>
  280.  
  281. # TAG: max_elapsed milliseconds
  282. #      If elapsed time is recorded in log is greater than max_elapsed use 0 for elapsed time.
  283. #      Use 0 for no checking 
  284. #
  285. #max_elapsed 28800000
  286. # 8 Hours
  287.  
  288. # TAG: report_type type
  289. #      What kind of reports to generate.
  290. #      topusers            - users, sites, times, bytes, connects, links to accessed sites, etc
  291. #      topsites		   - site, connect and bytes report
  292. #      sites_users	   - users and sites report
  293. #      users_sites	   - accessed sites by the user report
  294. #      date_time	   - bytes used per day and hour report
  295. #      denied		   - denied sites with full URL report
  296. #      auth_failures       - autentication failures report
  297. #      site_user_time_date - sites, dates, times and bytes report
  298. #      downloads           - downloads per user report
  299. #
  300. #      Eg.: report_type topsites denied 
  301. #
  302. report_type topusers topsites sites_users users_sites date_time denied auth_failures site_user_time_date downloads
  303.  
  304. # TAG: usertab filename
  305. #      You can change the "userid" or the "ip address" to be a real user name on the reports.
  306. #      Table syntax:
  307. # 		userid name   or   ip address name
  308. #      Eg:
  309. #		SirIsaac Isaac Newton
  310. #		vinci Leonardo da Vinci
  311. #		192.168.10.1 Karol Wojtyla
  312. #      
  313. #      Each line must be terminated with '\n'
  314. #
  315. #usertab none
  316.  
  317. # TAG: long_url yes|no
  318. #      If yes, the full url is showed in report.
  319. #      If no, only the site will be showed
  320. #
  321. #      YES option generate very big sort files and reports.
  322. #
  323. long_url no
  324.  
  325. # TAG: date_time_by bytes|elap
  326. #      Date/Time reports will use bytes or elapsed time?
  327. #
  328. #date_time_by elap
  329.  
  330. # TAG: charset name
  331. #      ISO 8859 is a full series of 10 standardized multilingual single-byte coded (8bit)
  332. #      graphic character sets for writing in alphabetic languages
  333. #      You can use the following charsets:
  334. #		Latin1 		- West European
  335. #		Latin2 		- East European 
  336. #		Latin3 		- South European 
  337. #		Latin4 		- North European 
  338. #		Cyrillic 
  339. #		Arabic 
  340. #		Greek 
  341. #		Hebrew 
  342. #		Latin5 		- Turkish 
  343. #		Latin6
  344. #		Windows-1251
  345. #		Japan
  346. #		Koi8-r
  347. #		UTF-8
  348. #
  349. charset Koi8-r
  350.  
  351. # TAG: user_invalid_char "&/"
  352. #      Records that contain invalid characters in userid will be ignored by Sarg.
  353. #
  354. #user_invalid_char "&/"
  355.  
  356. # TAG: privacy yes|no
  357. #      privacy_string "***.***.***.***"
  358. #      privacy_string_color blue
  359. #      In some countries the sysadm cannot see the visited sites by a restrictive law.
  360. #      Using privacy yes the visited url will be changes by privacy_string and the link
  361. #      will be removed from reports.
  362. #
  363. #privacy no
  364. #privacy_string "***.***.***.***"
  365. #privacy_string_color blue
  366.  
  367. # TAG: include_users "user1:user2:...:usern"
  368. #      Reports will be generated only for listed users.
  369. #
  370. #include_users none
  371.  
  372. # TAG: exclude_string "string1:string2:...:stringn"
  373. #      Records from access.log file that contain one of listed strings will be ignored.
  374. #
  375. #exclude_string none
  376.  
  377. # TAG: show_successful_message yes|no
  378. #      Shows "Successful report generated on dir" at end of process.
  379. #
  380. #show_successful_message yes
  381.  
  382. # TAG: show_read_statistics yes|no
  383. #      Shows some reading statistics.
  384. #
  385. #show_read_statistics yes
  386.  
  387. # TAG: topuser_fields
  388. #      Which fields must be in Topuser report.
  389. #
  390. topuser_fields NUM DATE_TIME USERID CONNECT BYTES %BYTES IN-CACHE-OUT USED_TIME MILISEC %TIME TOTAL AVERAGE
  391.  
  392. # TAG: user_report_fields
  393. #      Which fields must be in User report.
  394. #
  395. user_report_fields CONNECT BYTES %BYTES IN-CACHE-OUT USED_TIME MILISEC %TIME TOTAL AVERAGE
  396.  
  397. # TAG: bytes_in_sites_users_report yes|no
  398. #      Bytes field must be in Site & Users Report ?
  399. #
  400. #bytes_in_sites_users_report no
  401.  
  402. # TAG: topuser_num n
  403. #      How many users in topsites report. 0 = no limit
  404. #
  405. #topuser_num 0
  406.  
  407. # TAG: site_user_time_date_type list|table
  408. #      generate reports for site_user_time_date in list or table format
  409. #
  410. #site_user_time_date_type table
  411.  
  412. # TAG: datafile file
  413. #      Save the report results in a file to populate some database
  414. #
  415. #datafile none
  416.  
  417. # TAG: datafile_delimiter ";"
  418. #      ascii character to use as a field separator in datafile
  419. #
  420. #datafile_delimiter ";"
  421.  
  422. # TAG: datafile_fields all
  423. #      Which data fields must be in datafile
  424. #      user;date;time;url;connect;bytes;in_cache;out_cache;elapsed
  425. #
  426. #datafile_fields user;date;time;url;connect;bytes;in_cache;out_cache;elapsed
  427.  
  428. # TAG: datafile_url ip|name
  429. #      Saves the URL as ip or name in datafile
  430. #
  431. #datafile ip
  432.  
  433. # TAG: weekdays
  434. #      The weekdays to take account ( Sunday->0, Saturday->6 )
  435. # Example:
  436. #weekdays 1-3,5
  437. # Default:
  438. #weekdays 0-6
  439.  
  440. # TAG: hours
  441. #      The hours to take account
  442. # Example:
  443. #hours 7-12,14,16,18-20
  444. # Default:
  445. #hours 0-23
  446.  
  447. # TAG: dansguardian_conf file
  448. #      DansGuardian.conf file path
  449. #      Generate reports from DansGuardian logs.
  450. #      Use 'none' to disable it.
  451. #      dansguardian_conf /usr/dansguardian/dansguardian.conf
  452. #
  453. dansguardian_conf none
  454.  
  455. # TAG: dansguardian_ignore_date on|off
  456. #      'on'  must use the record even the date range is different from the used in squid access.log file.
  457. #      'off' must use the record only if the date range is in the irange used in squid access.log file.
  458. #
  459. #dansguardian_ignore_date off
  460.  
  461. # TAG: squidguard_conf file
  462. #      path to squidGuard.conf file
  463. #      Generate reports from SquidGuard logs.
  464. #      Use 'none' to disable.
  465. #      You can use sarg -L filename to use an alternate squidGuard log.
  466. #      squidguard_conf /usr/local/squidGuard/squidGuard.conf
  467. #
  468. squidguard_conf none
  469.  
  470. # TAG: squidguard_ignore_date on|off
  471. #      Use 'on'  use the record even the date range is different from the used squid access.log file.
  472. #      Use 'off' use the record only if the date range is in the used squid access.log file.
  473. #
  474. #squidguard_ignore_date off
  475.  
  476. # TAG: squidguard_log_format
  477. #      Format string SquidGuard logs.
  478. #      REJIK       #year#-#mon#-#day# #hour# #list#:#tmp# #ip# #user# #tmp#/#tmp#/#url#/#end#
  479. #      SQUIDGUARD  #year#-#mon#-#day# #hour# #tmp#/#list#/#tmp#/#tmp#/#url#/#tmp# #ip#/#tmp# #user# #end#
  480. #squidguard_log_format #year#-#mon#-#day# #hour# #tmp#/#list#/#tmp#/#tmp#/#url#/#tmp# #ip#/#tmp# #user# #end#
  481.  
  482. # TAG: show_sarg_info yes|no
  483. #      shows sarg information and site path on each report bottom
  484. #
  485. #show_sarg_info yes
  486.  
  487. # TAG: show_sarg_logo yes|no
  488. #      shows sarg logo
  489. #
  490. show_sarg_logo yes
  491.  
  492. # TAG: parsed_output_log directory
  493. #      Saves the processed log in a sarg format after parsing the squid log file.
  494. #      This is a way to dump all of the data structures out, after parsing from 
  495. #      the logs (presumably this data will be much smaller than the log files themselves),
  496. #      and pull them back in for later processing and merging with data from previous logs.
  497. #
  498. #parsed_output_log none
  499.  
  500. # TAG: parsed_output_log_compress /bin/gzip|/usr/bin/bzip2|nocompress
  501. #      sarg logs compress util
  502. #
  503. #parsed_output_log_compress /bin/gzip
  504.  
  505. # TAG: displayed_values bytes|abbreviation
  506. #      how the values will be displayed in reports.
  507. #      eg. bytes  	-  209.526
  508. #          abbreviation -  210K
  509. #
  510. displayed_values abbreviation
  511.  
  512. # Report limits
  513. # TAG: authfail_report_limit n
  514. # TAG: denied_report_limit n
  515. # TAG: siteusers_report_limit n
  516. # TAG: squidguard_report_limit n
  517. # TAG: user_report_limit n
  518. # TAG: dansguardian_report_limit n
  519. # TAG: download_report_limit n
  520. #      report limits (lines).
  521. #      '0' no limit
  522. #
  523. #authfail_report_limit 10
  524. #denied_report_limit 10
  525. #siteusers_report_limit 0
  526. #squidguard_report_limit 10
  527. #dansguardian_report_limit 10
  528. #user_report_limit 10
  529. #user_report_limit 50
  530.  
  531. # TAG: www_document_root dir
  532. #     Where is your Web DocumentRoot
  533. #     Sarg will create sarg-php directory with some PHP modules:
  534. #     - sarg-squidguard-block.php - add urls from user reports to squidGuard DB
  535. #
  536. www_document_root /usr/local/www/sarg_reports
  537.  
  538. # TAG: block_it module_url
  539. #     This tag allow you to pass urls from user reports to a cgi or php module,
  540. #     to be blocked by some Squid acl
  541. #
  542. #     Eg.: block_it /sarg-php/sarg-block-it.php
  543. #     sarg-block-it is a php that will append a url to a flat file.
  544. #     You must change /var/www/html/sarg-php/sarg-block-it to point to your file
  545. #     in $filename variable, and chown to a httpd owner.
  546. #
  547. #     sarg will pass http://module_url?url=url
  548. #
  549. #block_it none
  550.  
  551. # TAG: external_css_file path
  552. #     This tag allow internal sarg css override.
  553. #     Sarg use theses style classes:
  554. #     	.body		body class
  555. #	.info		sarg information class, align=center
  556. #	.title		title class, align=center
  557. #	.header		header class, align:left
  558. #	.header2	header class, align:right
  559. #	.header3	header class, align:right
  560. #	.text		text class, align:left
  561. #	.data		table text class, align:right
  562. #	.data2		table text class, align:right, border colors
  563. #	.link  		link class
  564. #
  565. #     There is a sample in /usr/local/sarg/etc/css.tpl
  566. #
  567. #external_css_file none
  568.  
  569. # TAG: user_authentication yes|no
  570. #     Allow user authentication in User Reports using .htaccess
  571. #     Parameters:  
  572. #	AuthUserFile 	- where the user password file is
  573. #	AuthName	- authentication realm. Eg "Members Only"
  574. #	AuthType	- authenticaion type - basic
  575. #	Require		- authorized users to see the report.
  576. #                                          %u - user report
  577. #
  578. # user_authentication no
  579. # AuthUserFile /usr/local/sarg/passwd
  580. # AuthName "SARG, Restricted Access"
  581. # AuthType Basic
  582. # Require user admin %u
  583.  
  584. # TAG: download_suffix "suffix,suffix,...,suffix"
  585. #    file suffix to be considered as "download" in Download report.
  586. #    Use 'none' to disable.    
  587. #
  588. download_suffix "zip,arj,bzip,gz,ace,doc,iso,adt,bin,cab,com,dot,drv$,lha,lzh,mdb,mso,ppt,rtf,src,shs,sys,exe,dll,mp3,avi,mpg,mpeg"
  589.  
  590. # TAG: ulimit n
  591. #    The maximum number of open file descriptors to avoid "Too many open files" error message.
  592. #    You need to run sarg as root to use ulimit tag.
  593. #    If you run sarg with a low privilege user, set to 'none' to disable ulimit
  594. #
  595. #ulimit 20000
  596.  
  597. # TAG: ntlm_user_format username|domainname+username
  598. #      NTLM users format.
  599. #
  600. #ntlm_user_format domainname+username
  601.  
  602. # TAG: realtime_refresh_time num sec
  603. #      How many time to auto refresh the realtime report
  604. #      0 = disable
  605. #
  606. # realtime_refresh_time 3
  607.  
  608. # TAG: realtime_access_log_lines num
  609. #      How many last lines to get from access.log file 
  610. #
  611. # realtime_access_log_lines 1000
  612.  
  613. # TAG: realtime_types: GET,PUT,CONNECT,ICP_QUERY,POST
  614. #      Which records must be in realtime report.
  615. #
  616. # realtime_types GET,PUT,CONNECT  
  617.  
  618. # TAG: realtime_unauthenticated_records: ignore|show
  619. #      What to do with unauthenticated records in realtime report.
  620. #
  621. # realtime_unauthenticated_records: show
  622.  
  623. # TAG: byte_cost value no_cost_limit
  624. #      Cost per byte.
  625. #      Eg. byte_cost 0.01 100000000
  626. #           per byte cost      = 0.01
  627. #           bytes with no cost = 100 Mb
  628. #      0 = disable
  629. #
  630. # byte_cost 0.01 50000000
  631.  
  632. # TAG: squid24 on|off
  633. #      Compatilibity with squid version <= 2.4 when using emulate_http_log on
  634. #
  635. # squid24 off
После того как конфиг готов можно приступить к написанию скрипта:
  1. #!/bin/sh
  2.  
  3. SARG_BIN="/usr/local/bin/sarg"
  4. SQUID_LOGDIR="/usr/local/squid/logs"
  5. TMPDIR="/var/tmp"
  6.  
  7. if [ ! -f "${SQUID_LOGDIR}/access.log" ]; then
  8.         echo "Not found squid access.log file"
  9.         exit 1
  10. fi
  11.  
  12. cp "${SQUID_LOGDIR}/access.log" "${TMPDIR}/squid-access.log"
  13. cat /dev/null > "${SQUID_LOGDIR}/access.log"
  14. ${SARG_BIN} -w ${TMPDIR} -l "${TMPDIR}/squid-access.log" > /dev/null 2>&1
  15. rm -f "${TMPDIR}/squid-access.log"
  16.  
  17. exit 0
Я разместил его в /etc/periodic/monthly/300.sarg-report. Не забываем дать права на исполнение. Ну и на этом все, можно пользоваться.

Добавить комментарий

Filtered text

CAPTCHA
Этот вопрос предназначен для предотвращения автоматизированной обработки форм.
Fill in the blank.