segunda-feira, julho 04, 2011

Script de Backup de OpenLDAP - ldapsearch


Introdução


Para realizar backups de bases LDAP existem muitas ferramentas que podem ser utilizadas. Uma maneira de realizar um backup simples e remoto é utilizando o comando ldapsearch.

Neste post será apresentado o script bkp-ldap.sh e de todas as configurações necessárias para seu funcionamento.

Pacotes Necessários


Para utilizar o comando ldapsearch é necessário ter instalado o seguinte pacote:


[root@horus ~]# yum info openldap-clients
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: centos.pop.com.br
* extras: centos.pop.com.br
* updates: centos.pop.com.br
Installed Packages
Name       : openldap-clients
Arch       : i386
Version    : 2.3.43
Release    : 12.el5_6.7
Size       : 367 k
Repo       : installed
Summary    : Client programs for OpenLDAP.
URL        : http://www.openldap.org/
License    : OpenLDAP
Description: OpenLDAP is an open-source suite of LDAP (Lightweight Directory Access
          : Protocol) applications and development tools. LDAP is a set of
          : protocols for accessing directory services (usually phone book style
          : information, but other information is possible) over the Internet,
          : similar to the way DNS (Domain Name System) information is propagated
          : over the Internet. The openldap-clients package contains the client
          : programs needed for accessing and modifying OpenLDAP directories.


Verificando quais binários e manuais foram instalados pelo pacote openldap-clients:


[root@horus base-ldap-neptuno]# rpm -ql openldap-clients
/usr/bin/ldapadd
/usr/bin/ldapcompare
/usr/bin/ldapdelete
/usr/bin/ldapmodify
/usr/bin/ldapmodrdn
/usr/bin/ldappasswd
/usr/bin/ldapsearch
/usr/bin/ldapwhoami
/usr/share/man/man1/ldapadd.1.gz
/usr/share/man/man1/ldapcompare.1.gz
/usr/share/man/man1/ldapdelete.1.gz
/usr/share/man/man1/ldapmodify.1.gz
/usr/share/man/man1/ldapmodrdn.1.gz
/usr/share/man/man1/ldappasswd.1.gz
/usr/share/man/man1/ldapsearch.1.gz
/usr/share/man/man1/ldapwhoami.1.gz


O cliente ldap também precisa estar instalado no sistema operacional LINUX (distribuição CENTOS 5.6).


Verificando a instalação do pacote openldap:


[root@horus base-ldap-neptuno]# yum info openldap
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: centos.pop.com.br
* extras: centos.pop.com.br
* updates: centos.pop.com.br
Installed Packages
Name       : openldap
Arch       : i386
Version    : 2.3.43
Release    : 12.el5_6.7
Size       : 593 k
Repo       : installed
Summary    : The configuration files, libraries, and documentation for OpenLDAP.
URL        : http://www.openldap.org/
License    : OpenLDAP
Description: OpenLDAP is an open source suite of LDAP (Lightweight Directory Access
          : Protocol) applications and development tools. LDAP is a set of
          : protocols for accessing directory services (usually phone book style
          : information, but other information is possible) over the Internet,
          : similar to the way DNS (Domain Name System) information is propagated
          : over the Internet. The openldap package contains configuration files,
          : libraries, and documentation for OpenLDAP.


Verificando quais arquivos e bibliotecas foram instaladas pelo pacote openldap:


[root@horus base-ldap-neptuno]# rpm -ql openldap
/etc/openldap
/etc/openldap/cacerts
/etc/openldap/ldap.conf
/usr/lib/liblber-2.3.so.0
/usr/lib/liblber-2.3.so.0.2.31
/usr/lib/libldap-2.3.so.0
/usr/lib/libldap-2.3.so.0.2.31
/usr/lib/libldap_r-2.3.so.0
/usr/lib/libldap_r-2.3.so.0.2.31
/usr/share/doc/openldap-2.3.43
/usr/share/doc/openldap-2.3.43/ANNOUNCEMENT
/usr/share/doc/openldap-2.3.43/CHANGES
/usr/share/doc/openldap-2.3.43/COPYRIGHT
/usr/share/doc/openldap-2.3.43/LICENSE
/usr/share/doc/openldap-2.3.43/README
/usr/share/man/man5/ldap.conf.5.gz
/usr/share/man/man5/ldif.5.gz
/usr/share/openldap



Configurações do Sistema


A configuração do cliente ldap será feita no arquivo /etc/openldap/ldap.conf.



[root@horus ~]# vim /etc/openldap/ldap.conf

#####################################
#                                                             #
#  Configurações do Cliente LDAP            #
#                                                             #
#####################################
#
# LDAP Defaults
#
# See ldap.conf(5) for details
# This file should be world readable but not world writable.
#
# Specifies the default base DN to use when performing ldap operations.
BASE dc=ufcspa,dc=edu,dc=br
#
# Specifies the default bind DN to use when performing ldap operations.
BINDDN  cn=qualquer,dc=ufcspa,dc=edu,dc=br
#
# Specifies the URI(s) of an LDAP server(s) to which the LDAP library should connect.
# The URI scheme may be either ldap or ldaps which refer to LDAP over TCP and LDAP over SSL (TLS)
# respectively.
URI ldap://192.168.1.1/
#
# Specifies the name(s) of an LDAP server(s) to which the LDAP library should connect.
HOST qualquer.ufcspa.edu.br
#
# Specifies if the client should automatically follow referrals returned by LDAP servers.
REFERRALS off
#
# Specifies a size limite to use when performing searches. A zero (0) means unlimited.
SIZELIMIT   0
#
# Specifies a time limit to use when performing searches. A zero (0) means unlimited.
TIMELIMIT   0
#
# Specifies how alias dereferencing is done when performing a search.
# If it is configured never then aliases are never dereferenced. This is the default.
DEREF           never
#
# TLS
#TLS_CACERT /etc/openldap/cacerts/myca-key-cert.pem
#
#  Specifies what checks to perform on server certificates in a TLS session
#  The value "never" means that the client will not request or check any server certificate.
TLS_REQCERT never
#
#TLS_CACERTDIR /etc/openldap/cacerts



Implementação do Script bkp-ldap.sh



#!/bin/bash
#
#
#################################
#                                                      #
# Script de Backup da Base LDAP     #
#                                                      #
#################################
#
#
# ============
# Dependências
# ============
#
# O comando ldapsearch utiliza configurações do cliente ldap do sistema
# operacional configurado em /etc/openldap/ldap.conf
#
#
# =================
# Variáveis Globais
# =================
#
# Senha para se conectar no Servidor LDAP
SENHA='segredo”'
#
#
# Servidor LDAP
HOST='qualquer.ufcspa.edu.br'
#
#
# Repositorio para deixar os arquivos de backup
REPOSITORIO='/backup/base-ldap-neptuno'
#
#
# Registra o momento em que o arquivo foi criado. Formato: ano-mes-dia-hora-minuto-segundo
HORARIO=$( date +%F-%H-%M-%S )
#
#
# ==================
# Execução do backup
# ==================
#
# Os seguintes parâmetros são utilizados:
#     -w    (solicita senha)
#     -D    (indica qual será o binddn a ser utilizado na conexão com a base)
#     -x    (indica auteticação simples e não por SASL)
#     -LLL  (indica que o OUTPUT do comando será no formato LDIF)
#
ldapsearch -w "$SENHA" -D"cn=qualquer,dc=ufcspa,dc=edu,dc=br" -x -LLL >> "$REPOSITORIO"/baseLDAP-"$HORARIO".ldif
#
#
#
# =================
# Validação de erro
# =================
#
if [ $? -ne 0 ]; then
{
  echo -ne "Erro - Nao foi realizado o Backup da base LDAP em $HOST" | mail -s"Erro - Backup Base LDAP $HOST" qualquer@ufcspa.edu.br
  exit 1
}
fi
#
#
#
# ========================================
# Geração de relatório de status do backup
# ========================================

RELATORIO=$( /usr/bin/find "$REPOSITORIO" -atime +5 )

/usr/bin/find "$REPOSITORIO" -atime +5 -exec rm -f {} \;

echo -ne "Foram removidos os seguintes arquivos antigos:\n\n$RELATORIO\n" | mail -s"Backup Base LDAP $HOST" qualquer@ufcspa.edu.br

exit 0        



Configuração da CRON


Para poder agendar a realização periódica do script é necessário fazer as seguintes configurações na CRON.



[root@horus ~]# crontab -e
0 3 * * * /root/bin/bkp-ldap.sh 2>&1 > /dev/null