2014/10/21

Apostila - Nagios Aplicado

Após muitos anos trabalhando com monitoramento de rede através do Nagios, nos mais variados cenários, venho contribuir com essa apostila que trata de explicar como o Nagios funciona, como efetuar uma implantação e criar seus próprios plugins.

Nagios Aplicado - Marcio José Atanásio

2014/02/03

Incremental backup Zimbra via shell script

This script do a backup of only one day. This way, we can do incremental backups.
Pay attention to variables DOMAINS, ADMIN and PASSWD

Sorry by my english.
Hope that could be understandable.

#!/bin/bash
# Incremental backup from Zimbra based in date.
# Create the backup folder with the actual date and create files tgz with emails of before day.
#
# Marcio Jose Atanasio
# marcio.jose@atanasio.com.br

#
# Version 20131008

# LOCAL
BCKDIR="/opt/zimbra/backup"
LOGFILE="/var/log/zmbackupin.log"

# Mount CIFS
REMOTE_BACKUP="0"
MNTREMOTE=""
USER=""
MNTPASSWD=""
# Use "all" to backup all domains accounts or put the domains that you want backup with space between.
DOMAINS="YOURDOMAIN.COM.BR"

# Administrator Login
ZIMBRAURL="https://127.0.0.1"
ADMIN="admin"
PASSWD="xxxxxxx"

ZMBACKUPPREFIX="INC"
RETENTION="5"

# ENVIROMENT                   
DT=`date +%Y"-"%m"-"%d`
DTBCK=`date -d "-2 days" +%m"/"%d"/"%Y`

function put_logger {
        echo `date +%Y"-"%m"-"%d" - "%H":"%M`" - $1" >> $LOGFILE
}

function purge_old {
        find $BCKDIR/*$ZMBACKUPPREFIX -type d -mtime +$RETENTION -exec rm -rf {} \;
}

function backup_dir {
        if [ "$1" = "mount" ]; then
                if [ "$REMOTE_BACKUP" = "1" ]; then
                        /bin/mount.cifs $MNTREMOTE $BCKDIR -o user=$USER,password=$MNTPASSWD
                        if [ "$?" = "0" ]; then
                                put_logger "Mount of $MNTREMOTE sucessfull."
                        else
                                put_logger "Mount of $MNTREMOTE fail. Backup failed."
                                exit 0
                        fi
                fi
                if [ -d $BCKDIR/$DT-$ZMBACKUPPREFIX ]; then
                    rm -rf $BCKDIR/$DT-$ZMBACKUPPREFIX
                fi
                /bin/mkdir $BCKDIR/$DT-$ZMBACKUPPREFIX > /dev/null  2>&1
        fi
        if [ "$1" = "umount" ]; then
                if [ "$REMOTE_BACKUP" = "1" ]; then
                        /bin/umount $BCKDIR
                        put_logger "Unmount of $MNTREMOTE sucessfull."
                fi
        fi
}

function get_domains {
    if [ "$DOMAINS" = "all" ]; then
            DOMAINS=`/opt/zimbra/bin/zmprov gad | sort`
                echo $DOMAINS | sed s/" "/"\n"/g >> $BCKDIR/$DT-$ZMBACKUPPREFIX/domains.txt
    fi
        put_logger "Domain lists from $DOMAINS saved."

}

function get_lists {
    for DOM in `echo $DOMAINS`; do
            for LST in `/opt/zimbra/bin/zmprov gadl $DOM` ; do
            echo "Lista "$LST >> $BCKDIR/$DT-$ZMBACKUPPREFIX/$DOM.lists.txt
                    echo "/opt/zimbra/bin/zmprov gdl $LST | grep zimbraMailForwardingAddress | cut -d" " -f2 >> $BCKDIR/$DT-$ZMBACKUPPREFIX/$DOM.lists.txt"
            echo "" >> $BCKDIR/$DT-$ZMBACKUPPREFIX/$DOM.lists.txt
                done
                        put_logger "Distribuition list from $DOM saved."
    done
}

function backup_accounts_aliases {
    for DOM in `echo $DOMAINS`; do
            put_logger "Stated backup of account and alias from
$DOM."
                for ACC in `/opt/zimbra/bin/zmprov -l gaa $DOM | sort`; do
            wget -q -t 1 -T 1 -O $BCKDIR/$DT-$ZMBACKUPPREFIX/$ACC.tgz --auth-no-challenge --user=$ADMIN --password=$PASSWD --no-check-certificate $ZIMBRAURL:7071/home/$ACC/\?fmt=tgz\&query=after:$DTBCK
                        put_logger "$ACC was made backup."
                        ALIASES=`/opt/zimbra/bin/zmprov ga $ACC | grep zimbraMailAlias | cut -d: -f2`
                        if [ ! -z "$ALIASES" ]; then
                            echo $ACC" - >"$ALIASES  >> $BCKDIR/$DT--$ZMBACKUPPREFIX/$ACC.alias.txt
                                put_logger "$ACC have saved alias."
                        fi
                done
                        put_logger "$DOM backup account and alias finalized."
    done

}

# START
put_logger "Backup started"
put_logger "Mounting..."
backup_dir mount
put_logger "Deleting backups with more than $RETENTION days."
purge_old
put_logger "Verifing domains to backup"
get_domains
put_logger "Making backup of distribuition lists"
get_lists
put_logger "Making backup of account and alias"
backup_accounts_aliases
put_logger "Umounting..."
backup_dir umount
put_logger "End of backup"

2013/10/07

Zimbra - Configuring Fail2ban to blocking relay tries

Zimbra server is configured to avoid relay access. But, I see a lot of tries to do this.
So, I decided to use Fail2ban to block this hosts.

The enviroment that I have installed the Zimbra Mail Server is:
CentOS 6.4 x64
EPEL and RPMForge repositories
Zimbra 7

First, we install Fail2ban service:
# yum install fail2ban

After, we create a filter:
# vi /etc/fail2ban/filter.d/zimbra-relay.conf
Content:
[Definition]
failregex = \[(?P\S*)\]: 554 5\.7\.1


Finally, we enable the filter in jail.conf file adding the following lines:
[zimbra-relay]
enabled         = true
filter          = zimbra-relay
logpath         = /var/log/zimbra.log
action          = iptables-allports[name = zimbra-relay]
maxretry        = 3
bantime         = 2800

Restart the service:
# service fail2ban restart

That's all folks.

2013/07/26

Bloqueio de conta de email agendado Zimbra

Há regras trabalhistas em que o colaborador não deve usar o email fora do horário de trabalho, pois isso caracteriza hora extra.

Em meu ambiente, não tenho um serviço de diretório (LDAP, Active Directory, etc) em que possa fazer esse bloqueio por horário.

Sendo assim, criei esse script para poder efetuar a alteração do status da conta diretamente no Zimbra. Segue o passo-a-passo.

Com o usuário root, crie o script em /opt/zimbra/bin:
# vi /opt/zimbra/bin/zmschedulestatus 

Coloque o seguinte conteúdo:
#!/bin/bash
# zmschedulestatus - Change status of email account via crontab
#
# Marcio Jose Atanasio
# Version 20130726

CONF="/opt/zimbra/zmschedulestatus_accounts"

ZMPROV="/opt/zimbra/bin/zmprov"
if [ -f $CONF ]; then
        if [ "$1" = "active" ] || [ "$1" = "maintenance" ] || [ "$1" = "locked" ] || [ "$1" = "closed" ] || [ "$1" = "lockout" ] || [ "$1" = "pending" ]; then
                for ACCOUNT in `cat $CONF`; do
                        $ZMPROV ma $ACCOUNT zimbraAccountStatus $1
                done
        else
                echo "Necessary state account to change. Valid modes are active,maintenance,locked,closed,lockout,pending"
        fi
else
        echo "Create a configuration file with email accounts in $CONF"
fi


Crie o arquivo de configuração com as contas de email que deseja alterar o status:
# vi  /opt/zimbra/zmschedulestatus_accounts

Adicione as contas que deseja efetuar a alteração do status:
email@dominio.com.br

Como usuário zimbra, adicione ao crontab o agendamento:
# crontab -e

Ao final, configure:
# Efetuar bloqueio às 18 horas de segunda a sexta
0 18 * * 1-5 /opt/zimbra/bin/zmschedulestatus locked
# Desbloquear às 8 horas de segunda a sexta
0 8 * * 1-5 /opt/zimbra/bin/zmschedulestatus active


Observações: Quando no estado locked a conta de email continua a receber mensagens. Há vários estados que estão descritos em Zimbra Account Status.

2013/05/14

Restaurar Backup do Zimbra

Este script funciona para a restauração de backups efetuados pelo script que postei zmbackup.sh.

Para backups acima de 2GB, é necessário descompactar a pasta, excluir os meta dados e através do zmprov, ir salvando cada arquivo .msg nas pastas específicas.

#!/bin/bash
# Marcio Jose Atanasio
# marcio.atanasio@gmail.com
#

if [ -z $1 ]; then
    echo " "
    echo "Para qual conta de email para restaurar?"
    echo " "
    echo "Sintaxe: ./zmrestore.sh "
    echo ""
else
    if [ -z $2 ]; then
        echo " "
        echo "Qual o arquivo restaurar para conta $1?"
        echo ""
        echo "Sintaxe: ./zmrestore.sh "
        echo ""
    else
        echo "Restaurando email $1 de $2..."
        echo `/opt/zimbra/bin/zmmailbox -z -m $1 postRestURL "//?fmt=tgz&resolve=skip" $2`
    fi
fi