Zimbra – основные команды в консоли

  • Михаил
  • 12 мин. на прочтение
  • 107
  • 24 Jan 2019
  • 24 Jan 2019

Все выполняется от пользователя zimbra, т.е. сперва всегда

su zimbra

Запуск/перезапуск

zmcontrol start|stop|restart|status

Перезапуск postfix (например, если правили конфиг)

zmmtactl reload

Проверка запущенных сервисов

zmprov gs `zmhostname` zimbraServiceEnabled

Информация о почтовом ящике

zmprov getMailboxInfo user@domain.com

Блокировка учетной записи ( возможные статусы: active, maintenance, locked, closed, lockout, pending )

zmprov ma user@domain.com zimbraAccountStatus locked

Переиндексировать ящик

zmprov reIndexMailbox user@domain.com start|status|stop

Посчитать количество писем в Inbox (getAllFolders)

zmmailbox -z -m user@domain.com gaf | grep Inbox | awk '{print $4}'

Список админских учетных записей

zmprov gaaa

Сменить пароль учетной записи

zmprov sp имя@домен НовыйПароль

Если нужно восстановить удаленные сообщения, сначала выполняется поиск в корзине, например: Только сообщения размером более 1 КБ (означает все)

zimbra@mail:/home/oper$ zmmailbox -z -m user@example.com s --dumpster -l 30 --types message larger:1kb

Восстановить определенные элементы (Синтаксис должен содержать идентификатор элемента для восстановления)

zmmailbox -z -m admin@mail.zimbra.io recoverItem 287 Inbox

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

zmprov gqu имя_сервера|sort -k 3 -n|column -t

gqu -- GetQuoteUsage
-k 3 -- сортировать по третьему столбцу
-n -- сортировать числа как числа, чтобы 20 шло после 19, а не после 10
-t -- подобрать подходящие для красивой таблички ширины столбцов

Если в логах сообщения со словами NO_SUCH_BLOB, то это значит, что произошло рассогласование между метаданными ящика и физическими файлами с письмами. Т.е. в метаданных есть ссылки на письма, а по факту файлов уже нет. Устраняется путем перестроения метаданных на основе существующих файлов с письмами в ящике. Для того, что бы найти ящики, у которых проблема:

grep -B2 NO_SUCH_BLOB /opt/zimbra/log/mailbox.lo* |grep mailbox= |sed -r 's/.*mailbox=([0-9]*).*$/\1/' |sort -u

Пофиксить:

zmblobchk --mailboxes 6919 --export-dir /tmp --missing-blob-delete-item start|status|stop
zmblobchk --mailboxes 4600 --export-dir /tmp/3 --missing-blob-delete-item --unexpected-blob-list /tmp/3/blob-list start

Работа с аккаунтом galsync

Информация об источниках данных (getDataSources)

zmprov gds galsync@domain.com

Удалить аккаунт galsync

zmgsautil deleteAccount -a galsync@domain.com

Узнать аккаунт (user account) по номеру ящика (MailboxId)

su - zimbra
mysql
use zimbra;
select comment from mailbox where id=257;

+----------------------+
| comment |
+----------------------+
| user@domain.com |
+----------------------+
1 row in set (0.00 sec)

Обновление правил spamassasin

zimbramon /bin/sa-update

Очистка ящиков от удаленных писем – Зимбра производит операцию purge_mailbox только для тех ящиков, которые находятся в момент выполнения операции в памяти (т.е. к ним кто то подключен). По этому для редко используемых ящиков очистка не срабатывает. В ручном режиме:

#Получаем ZimbraID ящика
zmprov -l ga user@domain.com zimbraId

# name letterbackup@propertyminder.com
# zimbraId: 1ab5cf73-b393-4ae0-9723-05ee92131980

#Загружаем ящик в память выполнив пустую операцию
zmmailbox -z -m user@domain.com noOp

#Очищаем ящик
zmsoap -v -z PurgeMessagesRequest/mbox @id=1ab5cf73-b393-4ae0-9723-05ee92131980

<PurgeMessagesRequest xmlns="urn:zimbraAdmin">
<mbox id="1ab5cf73-b393-4ae0-9723-05ee92131980"/>
</PurgeMessagesRequest>
<PurgeMessagesResponse xmlns="urn:zimbraAdmin">
<mbox id="1ab5cf73-b393-4ae0-9723-05ee92131980" mbxid="6867" s="3030290"/>
</PurgeMessagesResponse>

Можно пройтись по всем ящикам вот таким скриптом purge-all.sh

#!/bin/bash
# purge-all.sh
# run as user zimbra
# $ ./purge-all.sh
# or crontab monthly/weekly
# 0 1 1 * * /usr/local/bin/purge-all.sh

# config
TMPDIR="/var/tmp"
LOGDIR="/opt/zimbra/log"
SLEEP=10

if [ "$USER" != "zimbra" ]; then
 echo "Error: Must be run as user zimbra"
 exit 1
fi

DATE="`date '+%Y%m%d-%H%M%S'`"
exec >> $LOGDIR/purgeall-$DATE.log

echo "`date`: START $0"
zmprov -l gaa -s `zmhostname` > $TMPDIR/purgeall-list.out

for MYUSER in `cat $TMPDIR/purgeall-list.out`
do
 echo "`date`: Starting user: $MYUSER"
 ACCOUNT_ID="`zmprov -l ga $MYUSER zimbraId | awk '/^zimbraId:/ {print $2}'`"
 if [ -n "$ACCOUNT_ID" ]; then
 zmmailbox -z -m $MYUSER noOp && \
 zmsoap -v -z PurgeMessagesRequest/mbox @id=$ACCOUNT_ID
 if [ $? = 0 ]; then
 echo "`date`: Finished user: $MYUSER"
 else
 echo "`date`: Error: $MYUSER"
 fi
 fi
 sleep $SLEEP
done

echo "`date`: END $0"
exit 0

Отсылка уведомлений админу о свободном месте на дисках

zmlocalconfig zmdisklog_warn_threshold
zmlocalconfig zmdisklog_critical_threshold

Изменим дефолтные значения на 90 и 98% соответственно
zmlocalconfig -e zmdisklog_warn_threshold=90
zmlocalconfig -e zmdisklog_critical_threshold=98

С какого адреса отправляются уведомления

zmlocalconfig smtp_source

Изменим адрес отправителя
zmlocalconfig -e smtp_source=mailsrv@domain.ru

На какой адрес отправляются уведомления

zmlocalconfig smtp_destination

Изменим адрес получателя
zmlocalconfig -e smtp_destination=support@domain.ru

Интервал отправки уведомлений (по дефолту – 600сек., максимально 86400сек.)

zmlocalconfig -e zmstat_disk_interval=3600

Для применения изменений необходимо перезапустить службу

zmstatctl stop
zmstatctl start

Отчет daily mail report в zimbra

Для просмотра статистики в консоли 
/opt/zimbra/libexec/zmdailyreport

Для получения письма на почту админа 
/opt/zimbra/libexec/zmdailyreport -m

CLI

Description

ldap

Start, stop, or find the status of Zimbra LDAP

ldapsearch

Perform a search on an LDAP server

logmysqladmin

Send myslqadmin commands to the logger mysql

mailboxd

Start, stop, find the status of the mailboxd server

mysql

Enters interactive command-line MySQL session with the mailbox mysql

mysql.server

Start, stop the SQL instance for the mailbox package

mysqladmin

Send admin commands to MySQL

postconf

Postfix command to view or modify the postfix configuration

postfix

Start, stop, reload, flush, check, upgrade-configuration of postfix

qshape

Examine postfix queue in relation to time and sender/recipient domain

zmaccts

Lists the accounts and gives the status of accounts on the domain

zmamavisdctl

Start, stop, restart, or find the status of the Amavis-D New

zmantispamctl

Start, stop, reload, status for anti-spam service

zmantivirusctl

Start, stop, reload, status for the anti-virus service

zmapachectl

Start, stop, reload, or check status of Apache service (for spell check)

zmauditswatchctl

Start, stop, restart, reload, status of the auditswatch

zmcalchk

Check consistency of appointments and attendees in the Zimbra calendar

zmcertmgr

Manage self-signed and commercial certificates

zmclamdctl

Start, stop, or find the status of Clam AV

zmcleaniplanetics

Clean iPlanet ICS calendar files

zmcontrol (Start/Stop Service)

Start, stop, status of the Zimbra servers. Also can use to find the Zimbra version installed.

zmconvertctl

Start, stop, the conversion server or find the status of the converted attachments conversion/indexing

zmdumpenv

General information about the server environment is displayed

zmgsautil

Create, delete the GAL sync account and initiate manual syncs.

zmhostname

Find the hostname of the Zimbra server

zmitemdatafile

Extracts and packs tgz files that ZCS uses for REST import/export

zmjava

Execute Java with Zimbra-specific environment settings

zmldappasswd

Changes the LDAP password

zmlmtpinject

Testing tool

zmlocalconfig

Used to set or get the local configuration of a Zimbra server

zmloggerctl

Start, stop, reload, or find the status of the Zimbra logger service

zmloggerhostmap

Used to manually map a DNS hostname to a zmhostname.

zmlogswatchctl

Start, stop, status of the swatch that is monitoring logging

zmmailbox

Performs mailbox management tasks

zmmailboxdctl

Start, stop, reload, or find the status of the mailbox components (mailboxd, MySQL, convert)

zmmetadump

Support tool that dumps an item’s metadata in a human-readable form

zmmtaconfigctl

Start, stop, or find the status of the MTA configuration daemon

zmmtactl

Start, stop, or find the status of the MTA

zmmypasswd

Trace messages

zmmypasswd

Change MySQL passwords

zmmysqlstatus

Status of mailbox SQL instance

zmperditionctl

Start, stop, or find the status of the perdition IMAP proxy

zmprov (Provisioning)

Performs all provisioning tasks in Zimbra LDAP, including creating accounts, domains, distribution lists and aliases

zmproxyconfgen

Generates configuration for the nginx proxy

zmproxyctl

Start, stop, restart, and find the status of the IMAP proxy service

zmproxypurge

Purges POP/IMAP routing information from one or more memcached servers

zmpython

Ability to write Python scripts that access Zimbra Java libraries. It sets the ZCS class path and starts the Jython interpreter.

zmsaslauthdctl

Start, stop, or find the status of saslauthd (authentication)

zmshutil

Used for other zm scripts, do not use

zmskindeploy

Deploy skins for accounts from the command line

zmsoap

Print mail, account, and admin information in the SOAP format

zmspellctl

Start, stop, or find the status of the spell check server

zmsshkeygen

Generate Zimbra’s SSH encryption keys

zmstat-chart

Generate charts from zmstat data collected in a directory

zmstat-chart-config

Generate an .xml file with data included from the account setup

zmstat-chart-config

Outputs an XML configuration that describes the current state of the data gathered from zmstat-chart to generate charts on the administration console.

zmstatctl

Start, stop, check status, or rotate logs of zmstat data collectors

zmstorectl

Start, stop, or find the status of Zimbra store services

zmswatchctl

Start, stop, or find the status of the Swatch process, which is used in monitoring

zmsyslogsetup

Used to setup system log config file

zmthrdump

Initiate a thread dump and save the data to a file with a timestamp

zmtlsctl

Set the Web server mode to the communication protocol options: HTTP, HTTPS or mixed

zmtrainsa

Used to train the anti-spam filter to recognize what is spam or ham

zmtzupdate

Provides mechanism to process timezone changes from the command line

zmupdateauthkeys

Used to fetch the ssh encryption keys created by zmsshkeygen

zmvolume

Manage storage volumes on your Zimbra Mailbox server

zmzimletctl

Deploy and configure Zimlets