Usando Linux para muchas cosas y disfrutando de videojuegos, en dispositivos moviles, consolas y pc. Using Linux for many things and enjoying video games, mobile devices, consoles and pc

Como hacer backup de equipos en tu LAN

A la hora de sacar backup de los equipos en nuestra LAN encontramos muchas opciones, la mayoría con un alto costo sin contar con el hardware que necesitamos para poder explotarlo.
Hoy les mostrare como instalar y configurar BackupPC para tomar backups de los pc, servidores de su red LAN y equipos a los que tengamos acceso vía internet.
Usaremos Centos 6 virtualizado actualizado a la fecha para esto.
Necesitaremos un disco o filesystem únicamente para la tarea de almacenar los backup, no es recomendado que este en el mismo filesystem /

-Para este server tengo 2 discos, sda y sdb, dejando este ultimo solo para backup's. Si cuando instalamos Centos ya teníamos el disco podemos configurar el montaje directo sobre /data y no necesitaremos los comandos mostrados debajo

mkdir /data
mount /dev/sdb /data
vi /etc/fstab
/dev/sdb                /data                   ext3    defaults        1 2

Salimos guardando

-Deshabilitamos SELinux, herramienta útil, pero que muchas veces nos da buenos dolores de cabeza.

vi /etc/selinux/config
SELINUX=disabled

Salimos guardando y reiniciamos el server.

-Instalamos dependencias
yum install perl-CPAN gcc make samba-client httpd

-Descargamos el tgz del BackupPC

wget -c http://downloads.sourceforge.net/project/backuppc/backuppc/3.2.1/BackupPC-3.2.1.tar.gz

-Descomprimimos el tgz y entramos en su directorio
tar xzvf BackupPC-3.2.1.tar.gz

-Instalamos módulos de perl necesitados contestando Y si nos pide instalar otro módulo

perl -MCPAN -e shell
install CPAN::DistnameInfo
install Compress::Zlib Archive::Zip XML::RSS File::RsyncP Net::FTP Net::FTP::AutoReconnect Digest::MD5


-Creamos un usuario sin privilegios para backuppc y le colocamos una contraseña. Recuerden que su información sera tan segura como tan segura sea su contraseña entre otras políticas de seguridad a seguir.
adduser backuppc
passwd backuppc
chown backuppc.backuppc /data

-Comenzamos a configurar BackupPC
cd BackupPC-3.2.1

perl configure.pl
Is this a new installation or upgrade for BackupPC?  If this is
an upgrade please tell me the full path of the existing BackupPC
configuration file (eg: /etc/BackupPC/config.pl).  Otherwise, just
hit return.

--> Full path to existing main config.pl []?

I found the following locations for these programs:

    bzip2        => /usr/bin/bzip2
    cat          => /bin/cat
    df           => /bin/df
    gtar/tar     => /bin/gtar
    gzip         => /bin/gzip
    hostname     => /bin/hostname
    nmblookup    => /usr/bin/nmblookup
    par2         =>
    perl         => /usr/bin/perl
    ping         => /bin/ping
    rsync        => /usr/bin/rsync
    sendmail     => /usr/sbin/sendmail
    smbclient    => /usr/bin/smbclient
    split        => /usr/bin/split
    ssh/ssh2     => /usr/bin/ssh

--> Are these paths correct? [y]?y
Please tell me the hostname of the machine that BackupPC will run on.

--> BackupPC will run on host [bck.test.com]?

BackupPC should run as a dedicated user with limited privileges.  You
need to create a user.  This user will need read/write permission on
the main data directory and read/execute permission on the install
directory (these directories will be setup shortly).

The primary group for this user should also be chosen carefully.
The data directories and files will have group read permission,
so group members can access backup files.

--> BackupPC should run as user [backuppc]?

Please specify an install directory for BackupPC.  This is where the
BackupPC scripts, library and documentation will be installed.

--> Install directory (full path) [/usr/local/BackupPC]? /home/backuppc
Please specify a data directory for BackupPC.  This is where all the
PC backup data is stored.  This file system needs to be big enough to
accommodate all the PCs you expect to backup (eg: at least several GB
per machine).

--> Data directory (full path) [/data/BackupPC]?

BackupPC can compress pool files, providing around a 40% reduction in pool
size (your mileage may vary). Specify the compression level (0 turns
off compression, and 1 to 9 represent good/fastest to best/slowest).
The recommended values are 0 (off) or 3 (reasonable compression and speed).
Increasing the compression level to 5 will use around 20% more cpu time
and give perhaps 2-3% more compression.

--> Compression level [3]?7
BackupPC has a powerful CGI perl interface that runs under Apache.
A single executable needs to be installed in a cgi-bin directory.
This executable needs to run as set-uid backuppc, or
it can be run under mod_perl with Apache running as user backuppc.

Leave this path empty if you don't want to install the CGI interface.

--> CGI bin directory (full path) []? /var/www/cgi-bin

BackupPC's CGI script needs to display various PNG/GIF images that
should be stored where Apache can serve them.  They should be placed
somewhere under Apache's DocumentRoot.  BackupPC also needs to know
the URL to access these images.  Example:

    Apache image directory:  /var/www/htdocs/BackupPC
    URL for image directory: /BackupPC

The URL for the image directory should start with a slash.

--> Apache image directory (full path) []? /var/www/icons
--> URL for image directory (omit http://host; starts with '/') []? /icons

Ok, we're about to:

  - install the binaries, lib and docs in /home/backuppc,
  - create the data directory /data/BackupPC,
  - create/update the config.pl file /etc/BackupPC/config.pl,
  - optionally install the cgi-bin interface.

--> Do you want to continue? [y]?y
Created /home/backuppc/bin
Created /home/backuppc/doc
Created /home/backuppc/lib/BackupPC/CGI
Created /home/backuppc/lib/BackupPC/Config
Created /home/backuppc/lib/BackupPC/Lang
Created /home/backuppc/lib/BackupPC/Storage
Created /home/backuppc/lib/BackupPC/Xfer
Created /home/backuppc/lib/BackupPC/Zip
Created /home/backuppc/lib/Net/FTP
Created /data/BackupPC
Created /data/BackupPC/pool
Created /data/BackupPC/cpool
Created /data/BackupPC/pc
Created /data/BackupPC/trash
Created /etc/BackupPC
Created /var/log/BackupPC
Installing binaries in /home/backuppc/bin
Installing library in /home/backuppc/lib
Installing images in /var/www/icons
Making init.d scripts
Making Apache configuration file for suid-perl
Installing docs in /home/backuppc/doc
Installing config.pl and hosts in /etc/BackupPC
PING localhost.localdomain (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=1 ttl=64 time=0.029 ms

--- localhost.localdomain ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.029/0.029/0.029/0.000 ms
Installing cgi script BackupPC_Admin in /var/www/cgi-bin

Ok, it looks like we are finished.  There are several more things you
will need to do:

  - Browse through the config file, /etc/BackupPC/config.pl,
    and make sure all the settings are correct.  In particular,
    you will need to set $Conf{CgiAdminUsers} so you have
    administration privileges in the CGI interface.

  - Edit the list of hosts to backup in /etc/BackupPC/hosts.

  - Read the documentation in /home/backuppc/doc/BackupPC.html.
    Please pay special attention to the security section.

  - Verify that the CGI script BackupPC_Admin runs correctly.  You might
    need to change the permissions or group ownership of BackupPC_Admin.
    If this is an upgrade and you are using mod_perl, you will need
    to restart Apache.  Otherwise it will have stale code.

  - BackupPC should be ready to start.  Don't forget to run it
    as user backuppc!  The installation also contains an
    init.d/backuppc script that can be copied to /etc/init.d
    so that BackupPC can auto-start on boot.  This will also enable
    administrative users to start the server from the CGI interface.
    See init.d/README.

Enjoy!

-Modificamos el default config.pl. Las lineas que comienzan con # son comentarios y las $Conf son variables con valores

cd /etc/BackupPC
vi config.pl
$Conf{MaxBackupPCNightlyJobs} = 4;
$Conf{MaxOldLogFiles} = 5;
# Rango ip manejado dentro nuestra LAN
$Conf{DHCPAddressRanges} = [
  {
    'first' => 2,
    'ipAddrBase' => '192.168.1',
    'last' => 254
  }
];
$Conf{ServerInitdPath} = '/etc/init.d/backuppc';

$Conf{ServerInitdStartCmd} = '$sshPath -q -x -l root $serverHost $serverInitdPath start < /dev/null >& /dev/null';

$Conf{FullKeepCnt} = 4;
#Dias que se guardara un backup completo
$Conf{FullAgeMax}     = 30;
$Conf{RestoreInfoKeepCnt} = 5;
$Conf{ArchiveInfoKeepCnt} = 5;
$Conf{XferMethod} = 'rsyncd';
#Nombre del recurso compartido para copiar por rsync
$Conf{RsyncShareName} = 'docs';
#usuario
$Conf{RsyncdUserName} = 'backup';
#Contraseña, cambiarlo a algo mas seguro
$Conf{RsyncdPasswd} = 'contraseña';
$Conf{ArchiveComp} = 'bzip2';
$Conf{PingMaxMsec} = 80;
$Conf{MaxOldPerPCLogFiles} = 5;
#email al que enviar notificaciones, administrador
$Conf{EMailAdminUserName} = 'administrador@email.com';
#dominio que se sumara a una cuenta para crear un email para un usuario que se le este tomando backup, ejemplo, pepito@email.com seria para el usuario pepito
$Conf{EMailUserDestDomain} = '@email.com';
$Conf{EMailHeaders} = <<EOF;
MIME-Version: 1.0
Content-Type: text/plain; charset="iso-8859-1"
EOF
#usuarios administradores
$Conf{CgiAdminUsers}     = 'cabrera';
#En caso de resolverse el domain dentro de la LAN, colocar el hostname del server, sino, como en este caso, la ip
$Conf{CgiURL} = 'http://192.168.3.1/cgi-bin/BackupPC_Admin';
$Conf{CgiDateFormatMMDD} = 0;

Salimos guardando

-Modificamos hosts. Los campos de izquierda a derecha son, hostname del equipo (en el caso de equipos windows, el nombre que se ve cuando vamos por entorno de red), 0 si es ip estática fija o 1 si es DHCP y la ultima columna son los nombres de los administradores del backup de ese equipo. El primer usuario listado sera el que recibirá los emails de notificaciones sobre ese backup

vi hosts
pc1   0    pepito cabrera
pc2   1    pepe cabrera

Salimos guardando

-Los equipos que tengamos con ip estatica debemos colocarlos en /etc/hosts
vi /etc/hosts
192.168.3.2 pc1

Salimos guardando

-Hacemos un link a cgi-bin
ln -s /var/www/cgi-bin/ /var/www/html/BackupPC

-Creamos un grupo para los admin y aseguramos el directorio
cd /var/www/cgi-bin
vi group
admin: cabrera,admin2

Salimos guardando

vi .htaccess
AuthGroupFile /var/www/cgi-bin/group
AuthUserFile /var/www/cgi-bin/.htpasswd
AuthType basic
AuthName "access"
require valid-user

Salimos guardando

-Creamos nuestro fichero de contraseñas. La primera vez usamos el parámetro c para crear el archivo, después solo m para agregar con MD5

htpasswd -cm /var/www/cgi-bin/.htpasswd cabrera

htpasswd -m /var/www/cgi-bin/.htpasswd admin2

-Copiamos el script de inicio y lo activamos
cd /root/BackupPC-3.2.1/init.d
cp linux-backuppc /etc/init.d/backuppc
chmod 755 /etc/init.d/backuppc
chkconfig backuppc on

-Modificamos apache para que ejecute con permisos de backuppc

vi /etc/httpd/conf/httpd.conf
Timeout 120
StartServers         2
MaxClients         150
User backuppc
Group backuppc
#email del admin
ServerAdmin cabrera@test.com

<Directory />
    Options FollowSymLinks
    AllowOverride all
</Directory>
DirectoryIndex index.html index.htm index.html.var
<Directory "/var/www/icons">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
#<Directory "/var/www/cgi-bin">
#    AllowOverride None
#    Options None
#    Order allow,deny
#    Allow from all
#</Directory>
<Directory /var/www/cgi-bin/>
    SetHandler perl-script
    PerlResponseHandler ModPerl::Registry
    PerlOptions +ParseHeaders
    Options +ExecCGI
    AllowOverride Indexes AuthConfig


    Order deny,allow
#    Deny from all
#    Allow from 192.168.1.
    AuthName "Backup Admin"
    AuthType Basic
    AuthUserFile /var/www/cgi-bin
    Require valid-user
</Directory>
IndexOptions FancyIndexing VersionSort NameWidth=* HTMLTable

Salimos guardando y reiniciamos el servicio

service httpd restart

-Creamos un directorio para los conf de cada equipo. En la medida que vayamos agregando equipos para sacarle backups, debemos crear un config.pl para ese equipo.

cd /etc/BackupPC
mkdir pc

cp config.pl pc/pc1
cp config.pl pc/pc2
chown -R backuppc.backuppc /etc/BackupPC/

-Configuramos samba para encontrar a los pc windows en la LAN
cd /etc/samba
vi smb.conf
 [global]
        workgroup = test
        netbios name = bck
        server string = bck
        obey pam restrictions = Yes
        pam password change = Yes
        passwd program = /usr/bin/passwd %u
        passwd chat = *New*password* %n\n *Retype*new*password* %n\n *passwd:*all*authentication*tokens*updated*successfully*
        unix password sync = Yes
        log file = /var/log/samba/%m.log
        max log size = 0
        socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192
        os level = 70
        local master = no
        preferred master = no
        domain master = no
        dns proxy = No
;       wins support = Yes
;       remote browse sync = 192.168.2.255
        hosts allow = 192.168. 127.
        password server = None
        security = SHARE
;       printing = cups

Salimos guardando e iniciamos el servicio
service smb restart
chkconfig smb on

-Iniciamos el servicio de backuppc
service backuppc start

-Probamos la interfaz web
http://192.168.3.1/cgi-bin/BackupPC_Admin
-Elegimos un equipo desde el combobox de la izquierda y vemos los backups que tenga, en este caso, aun no tiene ninguno



-Volvemos a la consola y probamos un backup desde el usuario backuppc

su -l backuppc
cd bin
./BackupPC_dump -fv pc1
Name server doesn't know about pc1; trying NetBios
cmdSystemOrEval: about to system /usr/bin/nmblookup pc1
cmdSystemOrEval: finished: got output querying pc1 on 192.168.3.255
192.168.3.222 pc1<00>

NetBiosHostIPFind: found IP address 192.168.3.222 for host pc1
cmdSystemOrEval: about to system /bin/ping -c 1 -w 3 192.168.3.222
cmdSystemOrEval: finished: got output PING 192.168.3.222 (192.168.3.222) 56(84) bytes of data.
64 bytes from 192.168.3.222: icmp_seq=1 ttl=128 time=1.33 ms

--- 192.168.3.222 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 1ms
rtt min/avg/max/mdev = 1.337/1.337/1.337/0.000 ms

cmdSystemOrEval: about to system /bin/ping -c 1 -w 3 192.168.3.222
cmdSystemOrEval: finished: got output PING 192.168.3.222 (192.168.3.222) 56(84) bytes of data.
64 bytes from 192.168.3.222: icmp_seq=1 ttl=128 time=1.24 ms

--- 192.168.3.222 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 1ms
rtt min/avg/max/mdev = 1.245/1.245/1.245/0.000 ms

CheckHostAlive: returning 1.245
cmdSystemOrEval: about to system /usr/bin/nmblookup -A 192.168.3.222
cmdSystemOrEval: finished: got output Looking up status of 192.168.3.222
    PC1         <20> -         M <ACTIVE>
    PC1         <00> -         M <ACTIVE>
    TEST          <00> - <GROUP> M <ACTIVE>
    TEST          <1e> - <GROUP> M <ACTIVE>

    MAC Address = 68-A3-C4-75-54-06


NetBiosInfoGet: success, returning host pc1, user
full backup started for directory docs
started full dump, share=docs

....

Y listo, ya tenemos nuestro servidor de BackupPC funcionando, en la medida que pasen los dias podremos ver la lista de backups completos y parciales.
Disfrutenlo
Share/Bookmark