Полноценный виртуальный почтовый сервер/awstats

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Complete Virtual Mail Server/awstats and the translation is 62% complete.
Other languages:

Введение

Even though postfix provides logs, having them graphically displayed and analyzed can give much more insight. www-misc/awstats is a popular log analyzer that can parse logs and setup proper results.

Установка

AWStats is a web-application but no longer relies on webapp-config. If it hasn't emerged already, it needs to be emerged.

root #emerge --ask www-misc/awstats

Once installed, a config file needs to be created, either per domain, or one that handles all domains.

root #cp /etc/awstats/awstats.model.conf /etc/awstats/awstats.example.com.conf

AWStats isn't installed via webapp-config, but rather a simple symlink is used.

root #ln -s /usr/share/awstats/wwwroot /var/www/mail.example.com/htdocs/awstats

Конфигурация

AWStats

AWStats поставляется с разумными настройками по умолчанию, но тем не менее некоторые необходимо изменить.

Во-первых, awstats предполагает, что vhosts не используется. Например, если используется значение по умолчанию для apache журнала combined vhost, awstats не запуститься.

Предположим, что combined LogFormat настроен следующим образом:

КОД Apache LogFormat
LogFormat "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" VLOG=%{VLOG}e" vhost

Затем необходимо сделать следующие изменения:

ФАЙЛ /etc/awstats/awstats.example.com.confСовпадает с форматом журнала Apache.
LogFormat = "%virtualname %host %other %logname %time1 %methodurl %code %bytesd %refererquot %uaquot"

Долее awstats должен знать о доменах и алиасах, чтобы отфильтровать их из журнала:

ФАЙЛ /etc/awstats/awstats.example.com.confMake awstats listen to the domains
SiteDomain="example.com"
 
HostAliases="localhost 127.0.0.1 REGEX[example\.com$] REGEX[example\.(org|net)$]

Также, awstats нужно хранить его базу данных где-то. Gentoo создает каталог /var/lib/awstats для этого, но можно использовать любой другой. Убедитесь, что разрешения установлены так, чтобы пользователь apache мог записывать туда:

ФАЙЛ /etc/awstats/awstats.example.com.confБаза данных AWStats
DirData="/var/lib/awstats"

Любые другие изменения настроек не обязательны, но все же взгляните на них:

Журналирование

awstats needs to process the apache log file to build its database. Once confirmed that it is working manually it can be automated.

Ручная настройка

Сперва awstats должен быть запущен из консоли, чтобы обнаружить любые основные ошибки:

user $awstats.pl -config=stats.example.com -update -showdropped

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

Cron

Если все работает отлично, то можно добавить это в cron.hourly:

ФАЙЛ /etc/cron.hourly/awstatsAWstats задача в cron
#!/bin/sh
awstats.pl -config=stats.example.com -update > /dev/null 2>&1

Не забудьте сделать скрипт исполняемым, если это необходимо.

Logrotate

Awstats will process the log file every hour, but when logrotate rotates apache's log, some entries may be missing. This is easily solved however.

ФАЙЛ /etc/logrotate.d/apache2Diff of pre-init script
# Apache2 logrotate snipet for Gentoo Linux
# Contributes by Chuck Short
#
/var/log/apache2/*log {
  missingok
  notifempty
  sharedscripts
+  prerotate
+  /etc/cron.hourly/awstats > /dev/null 2>&1
+  endscript
  postrotate
  /etc/init.d/apache2 reload > /dev/null 2>&1 || true
  endscript
}

Apache

For awstats to be used from apache, the webhost needs to properly setup. In the alias section, the following needs to be added:

ФАЙЛ /etc/apache2/vhosts.d/stats.example.comАлиасы для awstats
Alias /awstats/classes "/usr/share/awstats/wwwroot/classes"
Alias /awstats/css "/usr/share/awstats/wwwroot/css"
Alias /awstats/icon "/usr/share/awstats/wwwroot/icon"
Alias /awstats/js "/usr/share/awstats/wwwroot/js"
ScriptAlias /awstats/ "/usr/share/awstats/wwwroot/cgi-bin/"

Наконец, awstats нуждается в правильных разрешениях, чтобы быть доступным:

ФАЙЛ /etc/apache2/vhosts.d/stats.example.comАлиасы для awstats
<Directory "/usr/share/awstats/wwwroot">
        Options None
        Require all granted
</Directory>

After a restart of apache, awstats should be available via http://stats.example.com/awstats/awstats.pl?config=stats.example.com. If no config option is passed to awstats, it uses the current hostname, which means in this case could have been omitted.

Awstats for mail log

AWStats is known for being an apache log parser. However it can also be used to parse mail logs.

Конфигурация

After copying awstats.stats.example.com.conf to awstats.mail.example.com.conf quite a few changes are required to turn awstats into a mail log parser.

ФАЙЛ /etc/awstats.mail.example.com.confLog mail.log instead of access.log (diff -u, only additions and deletions)
-LogFile="/var/log/apache2/access_log"
+LogFile="perl /usr/bin/awstats_maillogconvert.pl standard < /var/log/mail.log |"
 
-LogType=W
+LogType=M
 
-LogFormat=1
+LogFormat="%time2 %email %email_r %host %host_r %method %url %code %bytesd"
 
-SiteDomain="localhost"
+SiteDomain="example.com"
 
 
-HostAliases="localhost 127.0.0.1 REGEX[myserver\.com$]"
+HostAliases="localhost 127.0.0.1 REGEX[example\.(net|org)$]"
 
-DirData="."
+DirData="/var/lib/awstats"
 
-LevelForBrowsersDetection=2         # 0 disables Browsers detection.
+LevelForBrowsersDetection=0         # 0 disables Browsers detection.
                                     # 2 reduces AWStats speed by 2%
                                     # allphones reduces AWStats speed by 5%
-LevelForOSDetection=2               # 0 disables OS detection.
+LevelForOSDetection=0               # 0 disables OS detection.
                                     # 2 reduces AWStats speed by 3%
-LevelForRefererAnalyze=2            # 0 disables Origin detection.
+LevelForRefererAnalyze=0            # 0 disables Origin detection.
                                     # 2 reduces AWStats speed by 14%
-LevelForRobotsDetection=2           # 0 disables Robots detection.
+LevelForRobotsDetection=0           # 0 disables Robots detection.
                                     # 2 reduces AWStats speed by 2.5%
-LevelForSearchEnginesDetection=2    # 0 disables Search engines detection.
+LevelForSearchEnginesDetection=0    # 0 disables Search engines detection.
                                     # 2 reduces AWStats speed by 9%
-LevelForKeywordsDetection=2         # 0 disables Keyphrases/Keywords detection.
+LevelForKeywordsDetection=0         # 0 disables Keyphrases/Keywords detection.
                                     # 2 reduces AWStats speed by 1%
-LevelForFileTypesDetection=2        # 0 disables File types detection.
+LevelForFileTypesDetection=0        # 0 disables File types detection.
                                     # 2 reduces AWStats speed by 1%
 LevelForWormsDetection=0            # 0 disables Worms detection.
                                     # 2 reduces AWStats speed by 15%
 
-ShowRobotsStats=HBL
+ShowRobotsStats=0
 
-ShowEMailSenders=0
+ShowEMailSenders=HBML
 
-ShowEMailReceivers=0
+ShowEMailReceivers=HBML
 
-ShowSessionsStats=1
+ShowSessionsStats=0
 
-ShowPagesStats=PBEX
+ShowPagesStats=0
 
-ShowFileTypesStats=HB
+ShowFileTypesStats=0
 
-ShowFileSizesStats=0
+ShowFileSizesStats=1
 
-ShowDownloadsStats=HB
+ShowDownloadsStats=0
 
-ShowOSStats=1
+ShowOSStats=0
 
-ShowBrowsersStats=1
+ShowBrowsersStats=0
 
-ShowOriginStats=PH
+ShowOriginStats=0
 
-ShowKeyphrasesStats=1
+ShowKeyphrasesStats=0
 
-ShowKeywordsStats=1
+ShowKeywordsStats=0
 
-ShowMiscStats=a
+ShowMiscStats=0
 
-ShowHTTPErrorsStats=1
+ShowHTTPErrorsStats=0
 
-ShowSMTPErrorsStats=0
+ShowSMTPErrorsStats=1

With those changes in place, a manual run should work without any issues:

user $awstats.pl -config=mail.example.com -showcorrupted -showdropped

Журналирование

To scan the mail log every hour, the existing awstats script in cron.hourly can be appended with the following:

ФАЙЛ /etc/cron.hourly/awstatsAdd parsing of the mail log
awstats.pl -config=mail.example.com -update > /dev/null 2>&1

Also syslog is getting rotated and thus awstats needs to parse the mail log file before the mail log is being rotated:

ФАЙЛ /etc/logrotate.d/syslog-ngModify mail log entry in syslog
# Mail system
/var/log/mail.log /var/log/mail.info /var/log/mail.err /var/log/mail.warn {
    sharedscripts
    missingok
    prerotate
        /etc/cron.hourly/awstats
    endscript
    postrotate
        /etc/init.d/syslog-ng reload &gt; /dev/null 2&gt;&1 || true
    endscript
}
Заметка
The /var/log/mail.log file does not have to be on the same server. AWStats will have to have access to it. This could be via NFS, or having syslog do remote logging.

If logging of apache files is not desired, or webmail resides on a different server, the webserver log parsing can be removed from cron jobs.