Squid log analyzer windows

This is the Windows app named Squid-Log-Analyzer whose latest release can be downloaded as squidlog-1.0-pre2.tar.gz. It can be run online in the free hosting provider OnWorks for workstations.

Download and run online this app named Squid-Log-Analyzer with OnWorks for free.

Follow these instructions in order to run this app:

— 1. Downloaded this application in your PC.

— 2. Enter in our file manager https://www.onworks.net/myfiles.php?username=XXXXX with the username that you want.

— 3. Upload this application in such filemanager.

— 4. Start any OS OnWorks online emulator from this website, but better Windows online emulator.

— 5. From the OnWorks Windows OS you have just started, goto our file manager https://www.onworks.net/myfiles.php?username=XXXXX with the username that you want.

— 6. Download the application and install it.

— 7. Download Wine from your Linux distributions software repositories. Once installed, you can then double-click the app to run them with Wine. You can also try PlayOnLinux, a fancy interface over Wine that will help you install popular Windows programs and games.

Wine is a way to run Windows software on Linux, but with no Windows required. Wine is an open-source Windows compatibility layer that can run Windows programs directly on any Linux desktop. Essentially, Wine is trying to re-implement enough of Windows from scratch so that it can run all those Windows applications without actually needing Windows.

Squid-Log-Analyzer

DESCRIPTION

The aim of this project is to provide an easy-to-use log-anlyzer for squid-log-files. There is also a webmin modul, to make the log-file-viewing more fun. Perhaps there will also be support for other logfiles in the future. (No longer actively maintained

Audience

System Administrators

User interface

Web-based

Programming Language

Perl

Categories

Internet, Monitoring

This is an application that can also be fetched from https://sourceforge.net/projects/squidlog/. It has been hosted in OnWorks in order to be run online in an easiest way from one of our free Operative Systems.

Download Windows & Linux apps

  • Linux apps
  • Windows apps
  • 1

    JasperReports Library
    JasperReports Library is the
    world’s most popular open source
    business intelligence and reporting
    engine. It is entirely written in Java
    and it is able to …
    Download JasperReports Library
  • 2

    Frappe Books
    Frappe Books is a free and open source
    desktop book-keeping software that’s
    simple and well-designed to be used by
    small businesses and freelancers. It’…
    Download Frappe Books
  • 3

    Numerical Python
    NEWS: NumPy 1.11.2 is the last release
    that will be made on sourceforge. Wheels
    for Windows, Mac, and Linux as well as
    archived source distributions can be fou…
    Download Numerical Python
  • 4

    CMU Sphinx
    CMUSphinx is a speaker-independent large
    vocabulary continuous speech recognizer
    released under BSD style license. It is
    also a collection of open source tools …
    Download CMU Sphinx
  • 5

    PyScripter
    PyScripter is an open-source Python
    Integrated Development Environment (IDE)
    created with the ambition to become
    competitive in functionality with
    commercial I…
    Download PyScripter
  • 6

    Old Feren OS Repositories
    This was the Official Repository for
    Feren OS. To add the latest one, run
    this command: (16.04-based) echo
    «deb …
    Download Old Feren OS Repositories
  • More »

Linux commands

  • 1

    aarch64-linux-gnu-strip
    strip — Discard symbols from object
    files. …
    Run aarch64-linux-gnu-strip
  • 2

    aasavefont
    aafire, aainfo, aasavefont, aatest —
    aalib example programs …
    Run aasavefont
  • 3

    cps-auth
    cps-auth — Perform OAuth2
    authentication for cloudprint-service …
    Run cps-auth
  • 4

    cpuburn
    cpuburn, burnBX, burnK6, burnK7,
    burnMMX, burnP5, burnP6 — a collection
    of programs to put heavy load on CPU …
    Run cpuburn
  • 5

    gbklatex
    bg5latex — Use LaTeX directly on a Big5
    encodedtex file bg5pdflatex — Use
    pdfLaTeX directly on a Big5 encodedtex
    file bg5+latex — Use LaTeX directly on a
    Big5+…
    Run gbklatex
  • 6

    gbkpdflatex
    bg5latex — Use LaTeX directly on a Big5
    encodedtex file bg5pdflatex — Use
    pdfLaTeX directly on a Big5 encodedtex
    file bg5+latex — Use LaTeX directly on a
    Big5+…
    Run gbkpdflatex
  • More »

Время на прочтение11 мин

Количество просмотров56K

Недавно в нашей компании возникла необходимость перевести прокси-сервера с MS ISA Server на свободное ПО. Прокси-сервер долго выбирать не пришлось (squid). Воспользовавшись несколькими практическими рекомендациями, настроил прокси под наши нужды. Некоторые затруднения возникли при выборе программы для учета трафика.

Требования были такие:

1) свободное ПО
2) возможность обработки логов с различных прокси на одном сервере
3) возможность построения стандартных отчетов с отправкой по почте, либо ссылка на веб-сервере
4) построение отчетов по отдельным подразделениям и рассылка таких отчетов руководителям подразделений, либо предоставление доступа по ссылке на веб-сервере

По программам учета трафика разработчиками представлена весьма скудная информация: лаконичное описание назначение программы плюс необязательным бонусом пара скриншотов. Да, понятно, что любая программа подсчитает количество трафика за сутки/неделю/месяц, а вот дополнительные интересные возможности, отличающую одну программу от других — не описаны.

Я решил написать этот пост, в котором попытаюсь описать возможности и недостатки таких программ, а так же некоторые их ключевые «фишки», чтобы немного помочь в выборе тем, кому его предстоит сделать.

Наши кандидаты:

SARG
free-sa
lightsquid
SquidAnalyzer
ScreenSquid

Отступление

Информация о «возрасте» программы и выходе последнего релиза не является параметром сравнения и приводится только для сведения. Постараюсь сравнить исключительно функционал программы. Так же я намеренно не стал рассматривать слишком старые программы, которые не обновлялись много лет.

Логи передаются на обработку анализатору в том виде, как их создал squid и не будут подвергаться какой-либо предварительной обработке с целью внесения в них изменений. Обработка некорректных записей и всевозможные преобразования полей логов должны вноситься самим анализатором и присутствовать только в отчете. Данная статья не является инструкцией по настройке. Вопросы конфигурирования и использования могут быть освещены в отдельных статьях.

Итак, приступим.

SARG — Squid Analysis Report Generator

Старейшина среди поддерживаемых программ такого класса (разработка начата в 1998 году, прежнее название — sqmgrlog). Последний релиз (версия 2.3.10) — апрель 2015 года. После этого было несколько доработок и исправлений, которые доступны в master-версии (можно скачать с помощью git с sourceforge).

Запуск программы производится вручную либо по cron-у. Запустить можно без параметров (тогда все параметры будут взяты из файла конфигурации sarg.conf), либо можно указать параметры в командной строке или скрипте, например даты, за которые строится отчет.

Отчеты создаются в виде html-страниц и складываются в каталог /var/www/html/squid-reports (по умолчанию). Можно задать параметр, задающий количество хранимых отчетов в каталоге. Например, 10 ежедневных и 20 недельных, более старые будут автоматически удаляться.

Возможно использование несколько config-файлов с разными параметрами для различных вариантов отчетов (например, для ежедневных отчетов можно создать свой конфиг, в котором будет отключена опция создания графиков и будет указан другой каталог для вывода отчета).

Подробно

При входе на главную страницу с отчетами можем выбрать период, за который он создан (определяется в параметрах создания отчета), дата его создания, количество уникальных пользователей, суммарный трафик за период, среднее количество трафика на пользователя.

При выборе одного из периодов сможем получить отчет topusers за этот период. Далее приведу описания и примеры всех типов отчетов, которые умеет делать SARG.

1) topusers — суммарный трафик по пользователям. Под пользователем понимается либо имя хоста, которому предоставлен доступ в Интернет, либо логин пользователя. Пример отчета:

Здесь отображаются IP-адреса. При настройке включении соответствующей опции IP-адреса преобразуются в доменные имена.

Используете аутентификацию? Учетные записи преобразуются в реальные имена:

Внешний вид может быть настроен в css-файле. Выводимые столбцы тоже настраиваются, ненужные можно убрать. Поддерживается сортировка столбцов (sorttable.js).

При нажатии на иконку с графиком слева увидим подобный график:

При нажатии на иконку справа получим отчет 5.

2) topsites — отчет по самым популярным сайтам. По умолчанию выводится список из 100 самых популярных сайтов (значение корректируется). С помощью регулярных выражений или задания псевдонимов можно объединить трафик доменов 3-го и более высоких уровней до домена 2-го уровня (как на скриншоте) или задать любое другое правило. Для каждого домена можно задать правило отдельно, например, для yandex.ru и mail.ru объединять до 3-го уровня. Значение полей вполне очевидно.

3) sites_users — отчет о том, кто заходил на определенный сайт. Тут все просто: имя домена и кто к нему обращался. Трафик тут не отображается.

4) users_sites — отчет о посещенных сайтах каждым пользователем.

Тут тоже все понятно. Если нажать на иконку в первом столбце, получим отчет 8).

5) date_time — распределение трафика пользователя по дням и часам.

6) denied — заблокированные squid-ом запросы. Здесь отображается кому, когда и куда в доступе было отказано. Количество записей настраивается (по умолчанию — 10).

7) auth_failures — отказы в аутентификации. HTTP/407.
Количество записей настраивается (по умолчанию — 10).

8) site_user_time_date — показывается в какое время на какой сайт и с какой машины заходил пользователь.

9) downloads — список загрузок.

10) useragent — отчет об используемых программах

В первой части отчета отображается IP-адрес и использованные useragent’ы.

Во второй — общий список useragent’ов с распределением в процентах с учетом версий.

11) redirector — отчет показывает кому был заблокирован доступ средствами блокировщика. Поддерживаются squidguard, dansguardian, rejik, формат логов настраивается.

У SARG более 120 параметров настройки, поддержка языков (на русский язык переведено 100% сообщений), поддержка регулярных выражений, работа с LDAP, возможность предоставления пользователям доступа только к своим отчетам на web-сервере (через .htaccess), возможность преобразования логов в свой формат для экономии места, выгрузка отчетов в текстовый файл для последующего заполнения базы данных, работа с файлами логов squid (разбиение одного или нескольких лог-файлов по дням).

Возможно создание отчетов по определенному набору заданных групп, например, если требуется сделать отдельный отчет по подразделению. В дальнейшем доступ к веб-странице с отчетами подразделения можно предоставить, например, руководителям средствами веб-сервера.

Можно отправлять отчеты по e-mail, правда, пока поддерживается только отчет topusers, а само письмо будет простым текстовым без поддержки HTML.

Можно исключить из обработки определенных пользователей или определенных хосты. Можно задавать псевдонимы для пользователей, объединяя трафик нескольких аккаунтов в один, например, всех аутстафферов. Также можно задать псевдонимы для сайтов, например, объединить в некий псевдоним несколько социальных сетей, в этом случае все параметры по указанным доменам (количество соединений, объем трафика, время обработки) будут просуммированы. Или с помощью регулярного выражения можно «отбросить» домены выше 3-го уровня.
Возможна выгрузка в отдельные файлы списка пользователей, превысивших определенные объемы за период. На выходе будет несколько файлов, например: userlimit_1G.txt — превысившие 1 Gb, userlimit_5G.txt — превысившие 5 Gb и так далее — всего 16 лимитов.

Еще SARG имеет в своем арсенале пару PHP-страниц: просмотра текущих подключений к squid и для внесения доменных имен в списки блокировки squidguard.

В общем, это очень гибкий и мощный инструмент, несложен в освоении. Все параметры описаны в дефолтном конфигурационном файле, в wiki-разделе проекта на sourceforge есть более подробное описание всех параметров в wiki-разделе, разбитое по группам, и примеры их использования.

free-sa

Отечественная разработка. С ноября 2013 года новых версий не было. Заявлено более быстрое создание отчетов по сравнению с конкурирующими программами и меньший объем занимаемого места для готовых отчетов. Проверим!

Ближе всего по логике работы эта программа к SARG (да и автор сам сравнивает с этой программой (например, тут)), поэтому и мы сравнивать будем с ним.

Порадовало наличие нескольких тем оформления. Тема представляет собой 3 css-файла и 4 png-иконки, им соответствующие.

Отчеты действительно делаются быстрее. Дневной отчет создался за 4:30, когда у SARG за 12 минут. Правда, с занимаемым объемом оказалось не так: объем, занимаемый отчетами — 440 МБ (free-sa) и 336 МБ (SARG).

Попробуем дать задание посложнее: обработать лог-файл объемом 3,2 ГБ за 10 дней, в котором 26,3 млн строк.

Free-sa также сделал отчет быстрее, за 46 минут, отчет занимает 3,7 ГБ на диске. SARG потратил 1 час 10 минут, отчет занимает 2,5 ГБ.

Но оба эти отчета будет неудобно читать. Кому, например, захочется вручную считать, какой домен популярнее — vk.com или googlevideo.com и подсчитывать вручную трафик всех их поддоменов? Если в настройках SARG оставить только домены 2-го уровня, то создание отчета займет примерно столько же времени, но теперь уже сам отчет занимает на диске 1,5 ГБ (дневной с 336 МБ уменьшился до 192 МБ).

Подробно

При входе на главную страницу видим примерно следующее (выбрана тема blues):

image

Честно говоря, непонятно назначение вывода года и месяцев, при нажатии на них ничего не происходит. В поле поиска можно что-то написать, но опять же ничего не происходит. Можно выбрать интересующий период.

Список заблокированных URL:

image

Отчет CONNECT metdod:

Отчет PUT/POST metdod:

Отчет о загрузках:

Популярные сайты:

Интересным показался отчет об эффективности прокси-сервера:

image

Отчет по пользователям:

При нажатии на значок графика во второй колонке получим график использования сети Интернет конкретным пользователем:

При нажатии на вторую иконку получим таблицу загрузки интернет-канала по часам:

При выборе IP-адреса получим список сайтов по пользователю в порядке убывания трафика:

Вся статистика отображается в байтах. Для переключения на мегабайты необходимо выставить параметр

reports_bytes_divisor=«M»

Программа не принимает сжатые файлы логов, не принимает больше одного файла с параметром -l, не поддерживает отбор файлов по маске. Автор программы предлагает обойти эти ограничения созданием именованных каналов.

Обнаружен досадный глюк — когда длина строки лога слишком большая, вместо адресов вписываются timestamp’ы:

image

При просмотре трафика этого «пользователя» можно увидеть домен с источником ошибки:

image

Таким образом, количество пользователей возросло в несколько раз.

Если сравнивать эти две программы, то free-sa создает отчет чуть быстрее. 20-кратного увеличения скорости, как заявлено автором, мне не удалось обнаружить. Возможно, ее можно увидеть при каких-то определенных условиях. Думаю, непринципиально сколько займет создание недельного отчета ночью — 30 минут или 50. По объему занимаемого отчетами места у free-sa преимущества нет.

lightsquid

Пожалуй, самая популярная считалка трафика. Работает быстро, отчеты занимают не много дискового пространства. Хоть эта программа и не обновлялась давно, я все же решил в этой статье рассмотреть ее возможности.

Логика работы программы иная: программа считывает журнал и создает набор файлов с данными, которые потом использует для создания веб-страниц. То есть заранее созданных отчетов с данными здесь нет, страницы с данными генерируются «на лету». Плюсы такого решения очевидны: для получения отчета не обязательно парсить все логи за период, достаточно раз в день «скармливать» lightsquid-у накопившийся журнал. Можно по cron-у делать это несколько даже несколько раз в день, чтобы быстро добавить новую порцию информации.

Не обошлось без минусов: невозможно обработать логи с разных серверов и собрать статистику в одном месте: при обработке журнала за какой-нибудь день с другого сервера уже имеющаяся статистика за этот день стирается.

Есть странное ограничением: lightsquid «воспринимает» как несжатые файлы логов, как и сжатые (gz — точно), но во втором случае имя файла должно быть в таком формате: access.log.X.gz, файлы с форматом имени access.log-YYYYMMDD.gz не воспримет.

Путем нехитрых манипуляций преодолеваем это ограничение и смотрим что получилось.

Подробно

Отчет за месяц (суммарный трафик 3 Тб, 110 млн строк) занял на диске 1 Гб.

На начальной странице видим трафик по дням за текущий месяц.

При выборе дня видим отчет за день по всем пользователям:

Если заданы группы, в правой колонке отображается название группы, к которой принадлежит пользователь. Пользователи, не входящие ни в одну группу, объединяются в группу 00 no in group (в данном отчете они помечены вопросительным знаком).

При выборе на главной странице grp на соответствующую дату попадаем на страницу отчета пользователей, разбитых по группам. Сначала перечисляются не входящие ни в какую группу, затем группы по порядку.

При нажатии на название группы в таблице справа переходим ниже на место в странице, где начинается отчет по данной группе:

При нажатии на «Top sites report» получаем отчет по популярным сайтам за день:

Big files report:

Переходим к таблице справа.
Здесь можно получить список топ-сайтов за месяц и за весь год (выглядят они так же, поэтому без скриншота), общую статистику за год и за месяц, а так же статистику за год и за месяц по группам.

Статистика за месяц:

При нажатии на значок с часами сможем увидеть таблицу по сайтам, времени доступа и потребленному в час трафику:

Здесь отображена статистика за день, но за месяц и за год будет выглядеть примерно так же, часовые статистики по доменам просуммируются.

При нажатии на значок графика можем увидеть потребление трафика пользователем в течение месяца:

Столбцы графика кликабельны: при нажатии на столбец переходим на статистику пользователя за другой день.

При нажатии на [M] получим отчет по потреблению трафика пользователем в течение месяца с указанием объёма за каждый день и за полную неделю.

При нажатии на имя пользователя получаем список сайтов, на которые заходил пользователь в порядке убывания трафика:

Ну вот вроде бы и всё. Все просто и лаконично. IP-адреса могут быть преобразованы в доменные имена. С помощью регулярных выражений доменные имена могут быть объединены в домены 2-го уровня, на всякий случай привожу регулярное выражение:

$url =~ s/([a-z]+:\/\/)??([a-z0-9\-]+\.){0,}([a-z0-9\-]+\.){1}([a-z]+)(.*)/$3$4/o;

При навыках в perl можно доработать под себя.

SquidAnalyzer

Схожая с lightsquid программа и тоже написана на Perl. Более симпатичное оформление. Последняя на текущий момент версия 6.4 выпущена в в середине декабря этого года, сделано много улучшений. Сайт программы: squidanalyzer.darold.net.

SquidAnalyzer может использовать несколько процессоров компьютера (параметр -j), благодаря чему отчеты делаются быстрее, но это применимо только к несжатым файлам. Для запакованных (поддерживается формат gz) обработка происходит с использованием одного ядра процессора.

И еще одно сравнение с lightsquid: тот же самый отчет на том же самом сервере делался около суток, на диске занимает 3,7 ГБ.

Так же как и lightsquid, SquidAnalyzer не сможет объединить два и более лог-файла с разных серверов за один и тот же период.

Подробнее

Главная страница — можно выбрать год отчета.

При выборе любого периода (год, месяц, неделя, день) внешний вид веб-страниц будет схожим: сверху меню со следующими отчетами: MIME types, Networks, Users, Top Denied, Top URLs, Top Domains. Чуть ниже статистика прокси за выбранные период: Requests (Hit/Miss/Denied), Megabytes (Hit/Miss/Denied), Total (Requests/Megabytes/Users/Sites/Domains). Далее график по количеству запросов за период и по трафику.

В правом верхнем углу есть календарь. При выборе какого-нибудь месяца можно увидеть краткую статистику и график загрузки по дням:

В календаре есть возможность выбора недели. При выборе увидим похожую статистику:

При выборе дня видим статистику по часам:

Отчет по типу контента:

Отчет по сетям.

Отчет по пользователям.

При выборе пользователя получаем его статистику за период.

Запрещенные ресурсы:

Отчет по доменам 2-го уровня.

От себя бы хотел отметить очень медлительную работу программы по мере накопления информации. С каждым новым логом пересчитывается статистика за неделю, месяц и год. Поэтому рекомендовать эту программу для обработки логов с сервера с большим количеством трафика я бы не стал.

ScreenSquid

У этой программы другая логика: журнал импортируется в базу данных MySQL, затем данные запрашиваются из нее при работе в веб-интерфейсе. База с обработанным десятидневным логом, упомянутым ранее, занимает 1,5 Гб.

Подробнее

Программа не может импортировать файлы логов с произвольным именем, привязка только к access.log.

Главная страница:

Краткая статистика:

Для IP-адресов можно создать псевдонимы:

… а потом их можно объединить в группы:

Переходим к основному — отчетам.

Слева меню с типами отчетов:

Трафик пользователей логины
Трафик пользователей IP адреса
Трафик сайтов
Топ сайтов
Топ пользователей
Топ IP адресов
По времени суток
Трафик пользователей логины расширенный
Трафик пользователей IP адреса расширенный
Трафик IP адреса с резолвом
Популярные сайты
Кто качал большие файлы
Трафик по периодам (дни)
Трафик по периодам (имя дня)
Трафик по периодам (месяцы)
HTTP статусы
IP адреса логинов
Логины с IP адресов

Примеры отчетов.

Трафик пользователей IP адреса:

Трафик сайтов:

Топ сайтов:

… далее, если честно, не хватило терпения для изучения возможностей, поскольку страницы стали генерироваться по 3-5 минут. Отчет «по времени суток» за день, лог за который вообще не импортировался, создавался более 30 секунд. За день с трафиком — 4 минуты:

На этом все. Надеюсь, этот материал кому-нибудь пригодится. Всем спасибо за внимание.

NAME
    SquidAnalyzer - Squid access log report generation tool

DESCRIPTION
    SquidAnalyzer parse native access log format of the Squid proxy and
    generate general statistics about hits, bytes, users, networks, top url,
    top second level domain and denied URLs. Common and combined log format
    are also supported. SquidGuard logs can also be parsed and ACL's
    redirection reported into denied URLs report.

    Statistic reports are oriented to user and bandwidth control, this is
    not a pure cache statistics generator. SquidAnalyzer use flat files to
    store data and don't need any SQL, SQL Lite or Berkeley databases.

    This analyzer is incremental so it should be run in a daily cron. Take
    care if you have rotate log enable to run it before rotation is done.

REQUIREMENT
    Nothing is required than a modern perl version 5.8 or higher. Graphics
    are based on the Flotr2 Javascript library so they are drawn at your
    browser side without extra installation required.

CHANGES from https://github.com/darold/squidanalyzer
    SquidAnalyzer.pm can read compressed 'stat_code.dat', so you can compress
    previous years .dat files (e.g.: find 2023 -iname '*.dat' | xargs xz -9).
    You can install SquidAnalyzer.pm into custom LIB directory, so you can
    keep all files together (e.g. /opt/squidanalyzer)
    Hungarian translation

INSTALLATION
  Generic install
    If you want the package to be installed into the Perl distribution just
    do the following:

        perl Makefile.PL
        make
        make install

    Follow the instruction given at the end of install. With this default
    install everything configurable will be installed under
    /etc/squidanalyzer. The Perl library SquidAnalyzer.pm will be installed
    under your site_perl directory and the squid-analyzer Perl script will
    be copied under /usr/local/bin.

    The default output directory for html reports will be
    /var/www/squidanalyzer/.

    On FreeBSD, if make install is freezing and you have the following
    messages:

            FreeBSD: Registering installation in the package database
            FreeBSD: Cannot determine short module description
            FreeBSD: Cannot determine module description

    please proceed as follow:

            perl Makefile.PL INSTALLDIRS=site
            make
            make install

    as the issue is related to an install into the default Perl vendor
    installdirs it will then use Perl site installdirs.

    Note: you may not encountered this issue any more, since v6.6
    SquidAnalyzer use site as default installation directory.

  Custom install
    You can create your fully customized SquidAnalyzer installation by using
    the Makefile.PL Perl script. Here is a sample:

            perl Makefile.PL \
                    LOGFILE=/var/log/squid3/access.log \
                    BINDIR=/usr/bin \
                    CONFDIR=/etc \
                    HTMLDIR=/var/www/squidreport \
                    BASEURL=/squidreport \
                    MANDIR=/usr/share/man/man3 \
                    DOCDIR=/usr/share/doc/squidanalyzer

    Or you can install everything into one directory (e.g.: /opt/squidanalyzer)

            perl Makefile.PL \
                    LOGFILE=/var/log/squid/access.log \
                    BINDIR=/opt/squidanalyzer/bin \
                    CONFDIR=/opt/squidanalyzer/etc \
                    HTMLDIR=/var/www/squidreport \
                    BASEURL=/squidreport \
                    MANDIR=/opt/squidanalyzer/share/man/man3 \
                    DOCDIR=/opt/squidanalyzer/share/doc/squidanalyzer
                    LIB=/opt/squidanalyzer/lib

    If you want to build a distro package, there are two other options that
    you may use. The QUIET option is to tell to Makefile.PL to not show the
    default post install README. The DESTDIR is to create and install all
    files in a package build base directory. For example for Fedora RPM,
    thing may look like that:

            # Make Perl and SquidAnalyzer distrib files
            %{__perl} Makefile.PL \
                INSTALLDIRS=vendor \
                QUIET=1 \
                LOGFILE=/var/log/squid/access.log \
                BINDIR=%{_bindir} \
                CONFDIR=%{_sysconfdir} \
                BASEDIR=%{_localstatedir}/lib/%{uname} \
                HTMLDIR=%{webdir} \
                MANDIR=%{_mandir}/man3 \
                DOCDIR=%{_docdir}/%{uname}-%{version} \
                DESTDIR=%{buildroot} < /dev/null

    See spec file in packaging/RPM for full RPM build script.

  Local install
    You can also have a custom installation. Just copy the SquidAnalyzer.pm
    and the squid-analyzer perl script into a directory, copy and modify the
    configuration file and run the script from here with the -c option.

    Then copy files sorttable.js, squidanalyzer.css and
    logo-squidanalyzer.png into the output directory.

  Post installation
    1. Modify your httpd.conf to allow access to HTML output like follow:

            Alias /squidreport /var/www/squidanalyzer
            <Directory /var/www/squidanalyzer>
                Options -Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order deny,allow
                Deny from all
                Allow from 127.0.0.1
            </Directory>

    2. If necessary, give additional host access to SquidAnalyzer in
    httpd.conf. Restart and ensure that httpd is running.

    3. Browse to http://my.host.dom/squidreport/ to ensure that things are
    working properly.

    4. Setup a cronjob to run squid-analyzer daily or more often:

            # SquidAnalyzer log reporting daily
            0 2 * * * /usr/local/bin/squid-analyzer > /dev/null 2>&1

    or run it manually. For more information, see README file.

    If your squid logfiles are rotated then cron isn't going to give the
    expected result as there exists a time between when the cron is run and
    the logfiles are rotated. It would be better to call squid-analyzer from
    logrotate, create file /etc/logrotate.d/squid with the following
    content:

            /var/log/squid/*.log {
                    daily
                    compress
                    delaycompress
                    rotate 5
                    missingok
                    nocreate
                    sharedscripts
                    postrotate
                            test ! -e /var/run/squid.pid || test ! -x /usr/sbin/squid || /usr/sbin/squid -k rotate
                            /usr/local/bin/squid-analyzer -d -l /var/log/squid/access.log.1
                    endscript
            }

    Be sure that the paths used in this script correspond to your system.

    5. Adjust the configuration

    Make sure that the LogFile path is correct in your squidanalyzer.conf
    file. For instance:

            LogFile /var/log/squid/access.log

    You can also use network name instead of network ip addresses by using
    the network-aliases file. Also if you don't have authentication enable
    and want to replace client ip addresses by some know user or computer
    you can use the user-aliases file to do so.

    See the file squidanalyzer.conf to customized your output statistics and
    match your network and file system configuration.

  Upgrade
    Upgrade to a new release or to last development code is just like
    installation. To install latest development code to use latest
    ehancements process as follow:

            wget https://github.com/darold/squidanalyzer/archive/master.zip
            unzip master.zip
            cd squidanalyzer-master/
            perl Makefile.PL
            make
            sudo make install

    then to apply change to current reports you have to rebuild them using:

            squid-analyser --rebuild

    This command will rebuild all your reports where there is still data
    files I mean not removed by the retention limit. It can takes a very
    long time if you have lot of historic, in this case you may want to use
    option -b or --build_date to limit the rebuild period.

USAGE
    SquidAnalyzer can be run manually or by cron job using the
    squid-analyzer Perl script. Here are authorized usage:

    Usage: squid-analyzer [ -c squidanalyzer.conf ] [logfile(s)]

        -c | --configfile filename : path to the SquidAnalyzer configuration file.
                                     By default: /etc/squidanalyzer/squidanalyzer.conf
        -b | --build_date date     : set the date to be rebuilt, format: yyyy-mm-dd
                                     or yyyy-mm or yyyy. Used with -r or --rebuild.
        -d | --debug               : show debug information.
        -h | --help                : show this message and exit.
        -j | --jobs number         : number of jobs to run at same time. Default
                                     is 1, run as single process.
        -o | --outputdir name      : set output directory. If it does not start
                                     with / then prefixes Output from configfile
        -p | --preserve number     : used to set the statistic obsolescence in
                                     number of month. Older stats will be removed.
        -P | --pid_dir directory   : set directory where pid file will be stored.
                                     Default /tmp/
        -r | --rebuild             : use this option to rebuild all html and graphs
                                     output from all data files.
        -R | --refresh minutes     : add a html refresh tag into index.html file
                                     with a refresh intervalle in minutes. 
        -s | --start HH:MM         : log lines before this time will not be parsed.
        -S | --stop  HH:MM         : log lines after this time will not be parsed.
        -t | --timezone +/-HH      : set number of hours from GMT of the timezone.
                                     Use this to adjust date/time of SquidAnalyzer
                                     output when it is run on a different timezone
                                     than the squid server.
        -v | version               : show version and exit.
        --no-year-stat             : disable years statistics, reports will start
                                     from month level only.
        --no-week-stat             : disable weekly statistics.
        --with-month-stat          : enable month stats when --no-year-stat is used.
        --startdate YYYYMMDDHHMMSS : lines before this datetime will not be parsed.
        --stopdate  YYYYMMDDHHMMSS : lines after this datetime will not be parsed.
        --skip-history             : used to not take care of the history file. Log
                                     parsing offset will start at 0 but old history
                                     file will be preserved at end. Useful if you
                                     want to parse and old log file.
        --override-history         : when skip-history is used the current history
                                     file will be overridden by the offset of the
                                     last log file parsed.

    Log files to parse can be given as command line arguments or as a comma
    separated list of file for the LogFile configuration directive. By
    default SquidAnalyer will use file: /var/log/squid/access.log

    There is special options like --rebuild that force SquidAnalyzer to
    rebuild all HTML reports, useful after an new feature or a bug fix. If
    you want to limit the rebuild to a single day, a single month or year,
    you can use the --build_date option by specifying the date part to
    rebuild, format: yyyy-mm-dd, yyyy-mm or yyyy.

    The --preserve option should be used if you want to rotate your
    statistics and data. The value is the number of months to keep, older
    reports and data will be removed from the filesystem. Useful to preserve
    space, for example:

            squid-analyzer -p 6 -c /etc/squidanalyzer/squidanalyzer.conf

    will only preserve six month of statistics from the last run of
    squidanalyzer.

    If you have a SquidGuard log you can add it to the list of file to be
    parsed, either in the LogFile configuration directive log list, either
    at command line:

            squid-analyzer /var/log/squid3/access.log /var/log/squid/SquidGuard.log

    SquidAnalyzer will automatically detect the log format and report
    SquidGuard ACL's redirection to the Denied Urls report.

MULTIPROCESS
    If you have huges squid access.log you will be interested by using
    multiprocess with SquidAnalyzer. Using the -j or --jobs command line
    option you can force SquidAnalyzer to use as many cores/cpus as wanted.

            squid-analyzer -j 8 -l /var/log/squid3/huge_access.log

    Here SquidAnalyzer will use 8 cpus to parse the file and compute all
    statistics reports. It will also use much more memory at the same time.

LOGFORMAT
    SquidAnalyzer supports the following predefined log format:

        logformat squid %ts.%03tu %6tr %>a %Ss/%03>Hs %<st %rm %ru %un %Sh/%<A %mt
        logformat common %>a %ui %un [%tl] "%rm %ru HTTP/%rv" %>Hs %<st %Ss:%Sh
        logformat combined %>a %ui %un [%tl] "%rm %ru HTTP/%rv" %>Hs %<st "%{Referer}>h" "%{User-Agent}>h" %Ss:%Sh

    The common and combined log format can have one more field to add
    mime-type report like with the native squid log format:

        logformat common %>a %ui %un [%tl] "%rm %ru HTTP/%rv" %>Hs %<st %Ss:%Sh %mt
        logformat combined %>a %ui %un [%tl] "%rm %ru HTTP/%rv" %>Hs %<st "%{Referer}>h" "%{User-Agent}>h" %Ss:%Sh %mt

    Those are the default format used by squid, you can switch to any of the
    three log format by giving the name at end of the access_log directive:

            access_log /var/log/squid3/access.log squid

    or

            access_log /var/log/squid3/access.log common

CONFIGURATION
    Unless previous version customization of SquidAnalyzer is now done by a
    single configuration file squidanalyzer.conf.

    Here follow the configuration directives used by Squid Analyzer.

    Output output_directory
        Where SquidAnalyzer should dump all HTML, data and images files. You
        should give a path that can be read by a Web browser.

    WebUrl
        The URL of the SquidAnalyzer javascript, HTML and images files.
        Default: /squidreport

    CustomHeader
        This directive allow you to replace the SquidAnalyze logo by your
        custom logo. The default value is defined as follow:

                <a href="$self->{WebUrl}">
                <img src="$self->{WebUrl}images/logo-squidanalyzer.png" title="SquidAnalyzer $VERSION" border="0">
                </a> SquidAnalyzer

        Feel free to define your own header but take care to not break
        current design. For example:

                CustomHeader   <a href="http://my.isp.dom/"><img src="http://my.isp.dom/logo.png" title="My ISP link" border="0" width="100" height="110"></a> My ISP Company
                                                                                                   126,1         Bas

    LogFile squid_access_log_file
        Set the path to the Squid log file. This can be a comma separated
        list of files to process several files at the same time. If the
        files comes from different Squid servers, they will be merged in a
        single reports. You can also add to the list a SquidGuard log file,
        SquidAnalyzer will automatically detect the format.

    UseClientDNSName 0
        If you want to use DNS name instead of client Ip address as username
        enable this directive. When you don't have authentication, the
        username is set to the client ip address, this allow you to use the
        DNS name instead. Note that you must have a working DNS resolution
        and that it can really slow down the generation of reports.

    DNSLookupTimeout 100
        If you have enabled UseClientDNSName and have lot of ip addresses
        that do not resolve you may want to increase the DNS lookup timeout.
        By default SquidAnalyzer will stop to lookup a DNS name after 100
        ms. The value must be set in millisecond.

    StoreUserIp 0
        Store and show user different ip addresses used along the time in
        user statistics. Default: no extra storage

    NetworkAlias network-aliases_file
        Set path to the file containing network alias name. Network are show
        as Ip addresses so if you want to display name instead create a file
        with this format:

            LOCATION_NAME IP_NETWORK_ADDRESS

        Separator must be a tabulation this allow the use of space character
        in the network alias name.

        You can use regex to match and group some network addresses. See
        network-aliases file for examples.

    UserAlias user-aliases_file
        Set path to the file containing user alias name. If you don't have
        auth_proxy enable users are seen as ip addresses. So if you want to
        show username or computer name instead, create a file with this
        format:

            FULL_USERNAME IP_ADDRESS

        When 'UseClientDNSName' is enabled you can replace ip address by a
        DNS name.

        If you have auth_proxy enable but want to replace login name by full
        user name for example, create a file with this format:

            FULL_USERNAME LOGIN_NAME

        Separator for both must be a tabulation this allow the use of space
        character in the user alias name.

        You can use regex to match and group some user login or ip
        addresses. See user-aliases file for examples.

    UrlAlias url-aliases_file
        Set path to the file containing url alias name. You may want to
        group URL under a single alias to agregate statistics, in this case
        create a file with this format :

                URL_ALIAS     URL_REGEXP1,URL_REGEXP2,...

        Separator must be a tabulation. See network-aliases file for
        examples.

    AnonymizeLogin 0
        Set this to 1 if you want to anonymize all user login. The username
        will be replaced by an unique id that change at each squid-analyzer
        run. Default disable.

    OrderNetwork bytes|hits|duration
    OrderUser bytes|hits|duration
    OrderUrl bytes|hits|duration
        Used to set how SquidAnalyzer sort Network, User and User detailed
        Urls reports screen. Value can be: bytes, hits or duration. Default
        is bytes. Note that OrderUrl is limited to User detailed Urls
        reports and does not apply to Top Url and Top domain report where
        there is three reports each already ordered.

    OrderMime bytes|hits
        Used to set how SquidAnalyzer sort Mime types report screen Value
        can be: bytes or hits. Default is bytes.

    UrlReport 0|1
        Should SquidAnalyzer display user url details. This will show all
        URL read by user. Take care to have enough space disk for large
        user. Default is 0, no url detail report.

    UserReport 0|1
        Should SquidAnalyzer display user details. This will show statistics
        about user. Default is 1, show user detail report. Disable it to be
        able to remove any user related reports, statistics about URL and
        domains will remain.

    UrlHitsOnly 0|1
        Enable this directive if you don't want the tree Top URL and Domain
        tables. You will just have the table of Url/Domain ordered per hits
        then you can still sort the URL/Domain order by clicking on each
        column. This is useful when you have set a high value to TopNumber.

    QuietMode 0|1
        Run in quiet mode for batch processing or print debug information.
        Default is 0, verbose mode.

    CostPrice price/Mb
        Used to set a cost of the bandwidth per Mb. If you want to generate
        invoice per Mb for bandwidth traffic this can help you. Value 0 mean
        no cost, this is the default value, the "Cost" column is not
        displayed

    Currency currency_abbreviation
        Used to set the currency of the bandwidth cost. Preferably the html
        special character. Default is &euro;

    TopNumber number
        Used to set the number of top url and second level domain to show.
        Default is top 100.

    TopDenied number
        Used to set the number of top denied url to show. Default is top
        100.

    TopStorage number
        Top number of url to preserve on each data file sorted by OrderUrl.
        On huge access log it will improve a lot the performances but you
        will have less precision in the top url. Default to 0, all url will
        be stored.

    TopUrlUser Use this directive to show the top N users that look at an
    URL or a domain. Set it to 0 to disable this feature. Default is top 10.
    Exclude exclusion_file
        Used to set client ip addresses, network addresses, auth login or
        uri to exclude from report.

        You can define one by line exclusion by specifying first the type of
        the exclusion (USER, CLIENT or URI) and a space separated list of
        valid regex.

        You can also use the NETWORK type to define network address with
        netmask using the CIDR notation: xxx.xxx.xxx.xxx/n

        See example below:

                NETWORK        192.168.1.0/24 10.10.0.0/16
                CLIENT         192\.168\.1\.2 
                CLIENT         10\.169\.1\.\d+ 192\.168\.10\..*
                USER           myloginstr
                USER           guestlogin\d+ guestdemo
                URI            http:\/\/myinternetdomain.dom.*
                URI            .*\.webmail\.com\/.*\/login\.php.*

        you can have multiple line of the same exclusion type.

    Include inclusion_file
        Used to set client ip addresses, network addresses or auth login to
        include into the report. All others will not be included. It works
        as the opposite of the Include parameter.

        You can define one by line inclusion by specifying first the type of
        the inclusion (USER or CLIENT) and a space separated list of valid
        regex.

        You can also use the NETWORK type to define network address with
        netmask using the CIDR notation: xxx.xxx.xxx.xxx/n

        See example below:

                NETWORK        192.168.1.0/24 10.10.0.0/16
                CLIENT         192\.168\.1\.2 
                CLIENT         10\.169\.1\.\d+ 192\.168\.10\..*
                USER           myloginstr
                USER           guestlogin\d+ guestdemo
                URI            http:\/\/myinternetdomain.dom.*
                URI            .*\.webmail\.com\/.*\/login\.php.*

        you can have multiple line of the same inclusion type.

    ExcludedMethods
        This directive allow exclusion of some unwanted methods in report
        statistics like HEAD, POST, CONNECT, etc. Can be a comma separated
        list of methods.

    ExcludedMimes
        This directive allow exclusion of some unwanted mimetypes in report
        statistics like text/html, text/plain, or more generally text/*,
        etc. Can be a comma separated list of perl regular expression. Ex:

                ExcludedMimes   text/.*,image/.*

    Lang
        Used to set the translation file to be used. Value must be set to a
        file containing all string translated. See the lang directory for
        translation files. Default is defined internally in English.

    ExcludedCodes
        This directive allow exclusion of some unwanted codes in report
        statistics like TCP_DENIED/403 which are generated when a user
        accesses a page the first time without authentication. Can be a
        comma separated list of methods. Default is none, all codes will be
        parsed.

    DateFormat
        Date format used to display date (year = %y, month = %m and day =
        %d) You can also use %M to replace month by its 3 letters
        abbreviation. Default: %y-%m-%d

    SiblingHit
        Adds peer cache hit (CD_SIBLING_HIT) to be taken has local cache
        hit. Enabled by default, you must disabled it if you don't want to
        report peer cache hit onto your stats.

    TransfertUnit
        Allow one to change the default unit used to display transfert size.
        Default is BYTES, other possible values are KB, MB and GB.

    MinPie
        Minimum percentage of data in pie's graphs to not be placed in the
        others item. Lower values will be summarized into the others item.

    Locale
        Set this to your locale to display generated date in your language.
        Default is to use the current locale of the system. If you want date
        in German for example, set it to de_DE.

                Rapport genere le mardi 11 decembre 2012, 15:13:09 (UTC+0100).

        with a Locale set to fr_FR.

    MaxFormatError
        When SquidAnalyzer find a corrupted line in his data file, it exit
        immediately. You can force him to wait for a certain amount of
        errors before exiting. Of course you might want to remove the
        corrupted line before the next run. This can be useful if you have
        special characters in some fields like mime type.

    TimeZone
        # Adjust timezone to use when SquidAnalyzer reports different time
        than graphs # in your browser. The value must follow format: +/-HH.
        Default is to use local # time. This must be considered as real
        timezone but the number of hours to add # or remove from log
        timestamp. The value can be set to: auto, in this case #
        SquidAnalyzer will autodetect the timezone and apply it.

        Adjust timezone to use when SquidAnalyzer reports different time
        than graphs in your browser. The value must follow format: +/-HH.
        Default is to use local time. This must be considered as real
        timezone but the number of hours to add remove from log timestamp to
        adjust graphs times. For example:

                TimeZone       +01

        will append one hour to all timestamp.

        Additionaly TimeZone can be set to auto:

                TimeZone        auto

        to let SquidAnalyzer auto detect the timezone to use.

    UseUrlPort
        Enable this directive if you want to include port number into Url
        statistics. Default is to remove the port information from the Url.

    UpdateAlias
        Enable this directive if you want to apply immediately the changes
        made in aliases files to avoid duplicates. You still have to use
        --rebuild to recreate previous reports with new aliases. Enabling
        this will imply a lost of performances with huges log files.

    TimeStart and TimeStop
        The two following configuration directive allow you to specify a
        start and stop time. Log line out of this time range will not be
        parsed. The format of the value is HH:MM

    RefreshTime
        Insert a html Refresh tag into all index.html files. The value is
        the refresh intervalle in minutes. Default to 5 minutes. Can be
        overridden at command line with option -R | --refresh

SUPPORT
  Release announcement
    Please follow us on twitter to receive release announcement and latest
    news : https://twitter.com/SquidAnalyzer

  Bugs and Feature requests
    Please report any bugs, patches, discussion and feature request using
    tools on the git repository at https://github.com/darold/squidanalyzer.

  How to contribute ?
    Any contribution to build a better tool is welcome, you just have to
    send me your ideas, features request or patches using the tools on the
    git repository at https://github.com/darold/squidanalyzer

    You can also support the developer by donate some contribution by
    clicking on the "Donate" button on the SquidAnalyzer web site at
    http://squidanalyzer.darold.net/

AUTHOR
    Gilles DAROLD <gilles@darold.net>

COPYRIGHT
    Copyright (c) 2001-2019 Gilles DAROLD

    This package is free software and published under the GPL v3 or above
    license.

Одним из насущных вопросов для системного администратора является получение статистики использования интернета в организации. Располагая такими данными всегда можно ответить на вопрос руководства «куда ушел весь интернет», обосновать необходимость расширения канала, своевременно выявлять и пресекать нежелательный трафик. Сегодня мы рассмотрим такое решение для нашего роутера на платформе Ubuntu Server.

Онлайн-курс по устройству компьютерных сетей
На углубленном курсе «Архитектура современных компьютерных сетей» вы с нуля научитесь работать с Wireshark и «под микроскопом» изучите работу сетевых протоколов. На протяжении курса надо будет выполнить более пятидесяти лабораторных работ в Wireshark.

Основной интересующий нас тип траффика — HTTP, который составляет львиную долю входящего интернет-трафика в организации и наиболее интересен, так как позволяет судить об активности и предпочтениях пользователей (а также о том, как они проводят рабочее время). Все необходимые нам данные имеются в логах прокси-сервера Squid, но не будем же мы просматривать их вручную! Необходим инструмент, позволяющий анализировать и предоставлять отчеты на основе этих логов. Одним из таких инструментов является SARG — Squid Analysis Report Generator, что и отражено в его названии.

Приступим. Прежде чем браться за установку SARG необходимо подготовить сервер, данная утилита выдает отчеты в формате HTML и для работы с ними потребуется установленный веб-сервер. Если вы не собираетесь использовать роутер в качестве полноценного веб-сервера, то будет вполне достаточно легкого сервера lighttpd:

sudo apt-get install lighttpd

Сервер начинает работать сразу после установки, для проверки наберите в браузере адрес сервера и вы увидите стандартную страницу. По умолчанию lighttpd принимает соединения на всех интерфейсах, что нас никоим образом не устраивает, ограничим его работу внутренней сетью. Открываем конфигурационный файл /etc/lighttpd/lighttpd.conf, находим и приводим к следующему виду опцию:

 server.bind = "10.0.0.1"

где 10.0.0.1 — внутренний адрес роутера, также не забудьте раскомментировать эту строку и перезагрузить веб-сервер:

 sudo /etc/init.d/lighttpd restart

Устанавливаем SARG:

sudo apt-get install sarg

Настройка анализатора логов довольно проста и сводится к выбору языка, кодировки и формата отчета, а также пути для его размещения. Все изменения вносим в файл /etc/sarg/sarg.conf:

language Russian_UTF-8 
graphs yes
graph_days_bytes_bar_color orange
output_dir /var/www/squid-reports
charset UTF-8

Также находим и комментируем строку:

#site_user_time_date_type table

Теперь можем проверить работу анализатора:

sudo /usr/bin/sarg

После того как утилита закончит работу набираем в браузере http://10.0.0.1/squid-reports, вы должны увидеть следующую страницу:

SARG-001.png

По умолчанию SARG формирует отчет за весь доступный период, отчет содержит детализацию по пользователям (адресам) и посещенным ими сайтам, использованию трафика и кэша, загрузкам. Отдельно можно просмотреть наиболее посещаемые сайты, данный отчет сортирует сайты не по трафику, а по количеству посещений.

SARG-002.png

По каждому пользователю можно получить исчерпывающую статистику:

SARG-003.png

Можно также просмотреть график потребления трафика и статистику работы по датам и времени.

SARG-004.png

Если есть желание, можете настроить отображение отчетов по собственному вкусу, конфигурация SARG использует для задания параметров вывода отчетов стандартные HTML теги и неплохо документирована. Если вы владеете HTML на базовом уровне, эта операция не должна вызвать у вас затруднений.

Анализатор настроен и работает, это хорошо. Но запускать его каждый раз вручную не очень интересно, поэтому настроим систему на получение ежедневных, еженедельных и ежемесячных отчетов. Для этого откроем файл /etc/sarg/sarg-reports.conf и укажем путь для размещения отчетов, а также адрес и ссылку для логотипа.

HTMLOUT=/var/www/squid-reports 
LOGOIMG=/sqiud-reports/logo.png
LOGOLINK="http://10.0.0.1/squid-reports"

Учтите, что изображение логотипа должно находиться в пределах корневой папки веб-сервера (/var/www) и пути указываются от корня веб-сервера, а не файловой системы.

Теперь зададим расписание для формирования отчетов, которое необходимо добавить в /etc/crontab

00 09-18 * * * root sarg-reports today
00 22 * * * root sarg-reports daily
30 22 * * 0 root sarg-reports weekly
30 23 1 * * root sarg-reports monthly

Данное расписание означает, что каждый час с 9:00 до 18:00 (рабочий день организации) запускается скрипт формирования ежедневной статистики, каждый день в 22:00 формируется статистка за день, в 22:30 Воскресенья — статистка за неделю и первого числа каждого месяца в 23:30 статистика за месяц.

На этом настройку можно считать законченной, вся статистика будет доступна по адресу http://10.0.0.1/squid-reports.

Дополнительные материалы:


  1. Linux. Настройка роутера (NAT + DHCP + Squid)
  2. Ubuntu Server. Настраиваем роутер NAT + DHCP + Squid3
  3. Ubuntu Server. Настраиваем контент-фильтр роутера (DansGuardian)
  4. DansGuardian. Сложности фильтрации русскоязычного контента
  5. Ubuntu Server. Настраиваем антивирусный фильтр роутера (ClamAV)
  6. Ubuntu Server. Дополняем контент-фильтр роутера антивирусом (DansGuardian + ClamAV)
  7. Ubuntu Server. Настраиваем форвардинг портов на роутере
  8. Ubuntu Server. Настраиваем аутентификацию через Squid
  9. Ubuntu Server. Ограничиваем скорость клиентов через Squid
  10. SARG — анализируем логи прокси-севера Squid
  11. SAMS — веб-интерфейс для управления Squid и не только
  12. Squid — настраиваем URL-фильтрацию по спискам
  13. Squid — блокируем потоковое мультимедиа
  14. Как устроена и работает система контроля доступа в Squid
  15. Настраиваем Squid для работы с Active Directory. Часть 1 — базовые настройки
  16. Настраиваем Squid для работы с Active Directory. Часть 2 — Kerberos-аутентификация
  17. Настраиваем Squid для работы с Active Directory. Часть 3 — Авторизация на основе групп AD
  18. WPAD или автоматическая настройка параметров прокси
  19. Устраняем ошибки Windows Update при работе через прокси-сервер Squid
  20. Настраиваем ограничение скорости для пользователей в Squid
  21. Сборка Squid 3.5 с поддержкой SSL из исходных кодов для Debian / Ubuntu
  22. Настраиваем роутер NAT + DHCP + Squid3 с поддержкой фильтрации SSL-трафика

Онлайн-курс по устройству компьютерных сетей
На углубленном курсе «Архитектура современных компьютерных сетей» вы с нуля научитесь работать с Wireshark и «под микроскопом» изучите работу сетевых протоколов. На протяжении курса надо будет выполнить более пятидесяти лабораторных работ в Wireshark.

SARG is an open source tool that allows you to analyse the squid log files and generates beautiful reports in HTML format with informations about users, IP addresses, top accessed sites, total bandwidth usage, elapsed time, downloads, access denied websites, daily reports, weekly reports and monthly reports.

The SARG is very handy tool to view how much internet bandwidth is utilized by individual machines on the network and can watch on which websites the network’s users are accessing.

Install Sarg Squid Log Analyzer

In this article I will guide you on how to install and configure SARGSquid Analysis Report Generator on RHEL/CentOS/Fedora and Debian/Ubuntu/Linux Mint systems.

Installing Sarg – Squid Log Analyzer in Linux

I assume that you already installed, configured and tested Squid server as a transparent proxy and DNS for the name resolution in caching mode. If not, please install and configure them first before moving further installation of Sarg.

Please remember without the Squid and DNS setup, no use of installing sarg on the system it will won’t work at all. So, it’s a request to install them first before heading to Sarg installation.

Step 1: Installing Sarg from Source

The ‘sarg‘ package by default not included in RedHat based distributions, so we need to manually compile and install it from source tarball. For this, we need some additional pre-requisites packages to be installed on the system before compiling it from source.

On RedHat/CentOS/Fedora
# yum install –y gcc gd gd-devel make perl-GD wget httpd

Once you’ve installed all the required packages, download the latest sarg source tarball or you may use the following wget command to download and install it as shown below.

# wget http://garr.dl.sourceforge.net/project/sarg/sarg/sarg-2.3.7/sarg-2.3.7.tar.gz
# tar -xvzf sarg-2.3.7.tar.gz
# cd sarg-2.3.7
# ./configure
# make
# make install
On Debian/Ubuntu/Linux Mint

On Debian based distributions, sarg package can be easily install from the default repositories using apt-get package manager.

$ sudo apt-get install sarg

Step 2: Configuring Sarg

Now it’s time to edit some parameters in SARG main configuration file. The file contains lots of options to edit, but we will only edit required parameters like:

  1. Access logs path
  2. Output directory
  3. Date Format
  4. Overwrite report for the same date.

Open sarg.conf file with your choice of editor and make changes as shown below.

# vi /usr/local/etc/sarg.conf        [On RedHat based systems]
$ sudo nano /etc/sarg/sarg.conf        [On Debian based systems]

Now Uncomment and add the original path to your squid access log file.

# sarg.conf
#
# TAG:  access_log file
#       Where is the access.log file
#       sarg -l file
#
access_log /var/log/squid/access.log

Next, add the correct Output directory path to save the generate squid reports in that directory. Please note, under Debian based distributions the Apache web root directory is ‘/var/www‘. So, please be careful while adding correct web root paths under your Linux distributions.

# TAG:  output_dir
#       The reports will be saved in that directory
#       sarg -o dir
#
output_dir /var/www/html/squid-reports

Set the correct date format for reports. For example, ‘date_format e‘ will display reports in‘dd/mm/yy‘ format.

# TAG:  date_format
#       Date format in reports: e (European=dd/mm/yy), u (American=mm/dd/yy), w (Weekly=yy.ww)
#
date_format e

Next, uncomment and set Overwrite report to ‘Yes’.

# TAG: overwrite_report yes|no
#      yes - if report date already exist then will be overwritten.
#       no - if report date already exist then will be renamed to filename.n, filename.n+1
#
overwrite_report yes

That’s it! Save and close the file.

Step 3: Generating Sarg Report

Once, you’ve done with the configuration part, it’s time to generate the squid log report using the following command.

# sarg -x        [On RedHat based systems]
# sudo sarg -x        [On Debian based systems]
Sample Output
[root@localhost squid]# sarg -x

SARG: Init
SARG: Loading configuration from /usr/local/etc/sarg.conf
SARG: Deleting temporary directory "/tmp/sarg"
SARG: Parameters:
SARG:           Hostname or IP address (-a) =
SARG:                    Useragent log (-b) =
SARG:                     Exclude file (-c) =
SARG:                  Date from-until (-d) =
SARG:    Email address to send reports (-e) =
SARG:                      Config file (-f) = /usr/local/etc/sarg.conf
SARG:                      Date format (-g) = USA (mm/dd/yyyy)
SARG:                        IP report (-i) = No
SARG:             Keep temporary files (-k) = No
SARG:                        Input log (-l) = /var/log/squid/access.log
SARG:               Resolve IP Address (-n) = No
SARG:                       Output dir (-o) = /var/www/html/squid-reports/
SARG: Use Ip Address instead of userid (-p) = No
SARG:                    Accessed site (-s) =
SARG:                             Time (-t) =
SARG:                             User (-u) =
SARG:                    Temporary dir (-w) = /tmp/sarg
SARG:                   Debug messages (-x) = Yes
SARG:                 Process messages (-z) = No
SARG:  Previous reports to keep (--lastlog) = 0
SARG:
SARG: sarg version: 2.3.7 May-30-2013
SARG: Reading access log file: /var/log/squid/access.log
SARG: Records in file: 355859, reading: 100.00%
SARG:    Records read: 355859, written: 355859, excluded: 0
SARG: Squid log format
SARG: Period: 2014 Jan 21
SARG: Sorting log /tmp/sarg/172_16_16_55.user_unsort
......

Note: The ‘sarg -x’ command will read the ‘sarg.conf‘ configuration file and takes the squid ‘access.log‘ path and generates a report in html format.

Step 4: Accessing Sarg Report

The generated reports placed under ‘/var/www/html/squid-reports/‘ or ‘/var/www/squid-reports/‘ which can be accessed from the web browser using the address.

http://localhost/squid-reports
OR

http://ip-address/squid-reports
Sarg Main Window

Squid Log Analyzer

Specific Date

Date Wise Report

User Report

User Bandwidth Report

Top Accessed Sites

Squid Top Accessed Sites

Top Sites and Users

Squid Top Accessed Sites and Users

Top Downloads

Squid Top Downloads

Denied Access

Squid Denied Access

Authentication Failures

Squid Authentication Failures

Step 5: Automatic Generating Sarg Report

To automate the process of generating sarg report in given span of time via cron jobs. For example, let’s assume you want to generate reports on hourly basis automatically, to do this, you need to configure a Cron job.

vi /etc/crontab

Next, add the following line at the bottom of the file. Save and close it.

* */1 * * * /usr/bin/sarg -x

The above Cron rule will generate SARG report every 1 hour.

I also added our company logo to: /var/www/logo.jpg (just remember to add this line:
logo_image http://localhost/logo.jpg
to your /etc/sarg/sarg.conf file.)

Reference:
http://www.tecmint.com/sarg-squid-analysis-report-generator-and-internet-bandwidth-monitoring-tool/

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как поставить php на windows
  • Где находятся сохранения мафия 2 windows 8
  • Hp pavilion g6 1341er драйвера windows 7
  • Какого режима работы калькулятора windows не существует
  • Windows 7 какая лучше по производительности