27/01/2018

Migración de Servidor con TAR

En esta guía realizaremos una migración entre dos servidores, con un procedimiento artesanal usado normalmente para pasar maquinas físicas a virtuales, en este caso trabajaremos con 2 VM montadas en VBox, y serán migradas con el comando TAR de linux.

  • VM 1 : Ubuntu 16.04 // HDD 10GB
  • VM 2 : Maquina sin sistema operativo // HDD 10GB
  • Adicional : Usaremos una imagen booteable del S.O finnix

Link de descarga

Ubuntu 16.04 server 64Bits

Finnix Linux 64Bits

Lo primero ser instalar nuestro servidor principal que se duplicara a uno nuevo, esta instalación se las dejare a ustedes ya que es una instalación común y corriente de linux que la pueden encontrar en cualquier vídeo de youtube.

Configuración VM1

Configuración VM2

Ahora Sacaremos la información Básica de la maquina origen para replicar en la maquina que se migrara.

1.- Instalación de SSH y habilitación de acceso root

apt installl sshsystemctl start service.ssh

Para habilitar el acceso de root, editaremos el archivo de configuración de ssh y modificaremos el parámetro PermitRootLogin

cambiamos la variable prohibit-password por el valor yes y reiniciamos ssh

systemctl restart service.ssh

Les dejo un pequeño código escrito por tecmint y modificado por mi para obtener la información que requerida para la migración

vim dumpOS.sh

Pegan el Contenido

#!/bin/bash##################################################################                                                               ##       Script de Volcado de informacion de S.O                 ##       Escrito Por Tecmint y Modificado por Jorge Romero       ##       Santiago de Chile 27-01-2018                            ##                                                               ################################################################### Limpieza de pantallaclear# Definicion de variablesreset=$(tput sgr0)os=$(uname -o)arch=$(uname -m)kernel=$(uname -r)# Sistema Operativoecho -e '\E[32m'"El tipo de sistema Operativo es :" $reset $os# Check OS Release Version and Namecat /etc/os-release | grep 'NAME\|VERSION' | grep -v 'VERSION_ID' | grep -v 'PRETTY_NAME' > /tmp/osreleaseecho -n -e '\E[32m'"Nombre del S.O :" $reset  && cat /tmp/osrelease | grep -v "VERSION" | cut -f2 -d\"echo -n -e '\E[32m'"Version del S.O :" $reset && cat /tmp/osrelease | grep -v "NAME" | cut -f2 -d\"# Check Architectureecho -e '\E[32m'"Architecture :" $reset $arch# Check Kernel Releaseecho -e '\E[32m'"Kernel Release :" $reset $kernel# Check hostnameecho -e '\E[32m'"Hostname :" $reset $HOSTNAME# Check RAM and SWAP Usagesfree -h | grep -v + > /tmp/ramcacheecho -e '\E[32m'"Ram Usada :" $resetcat /tmp/ramcache | grep -v "Swap"echo -e '\E[32m'"Swap Usada :" $resetcat /tmp/ramcache | grep -v "Mem"# Check Disk Usagesdf -h| grep 'Filesystem\|/dev/sda*' > /tmp/diskusageecho -e '\E[32m'"Discos Usados :" $reset cat /tmp/diskusagefdisk -l | grep "/dev"# Check Particiones LVMecho -e '\E[32m'"---- Particiones LVM ----"echo -e '\E[32m'"PV :" $reset && pvdisplay | grep "PV Name"echo -e '\E[32m'"VG :" $reset && vgdisplay | grep "VG Name"echo -e '\E[32m'"LV :" $reset && lvdisplay | grep "LV Path\|LV Name\|VG Name\|LV Size"# UUID particionesecho -e '\E[32m'"UUID :" $reset && blkid# Limpieza de temporalesrm /tmp/osrelease /tmp/ramcache /tmp/diskusage

Le dan permisos de ejecución y ejecutan

chmod +x dumpOS.sh./dumpOS.sh

2.- Ahora crearemos el Backup completo del S.O, en el caso de no tener espacio lo ideal seria hacerlo con un disco USB o por red, yo lo haré directo en la maquina

cd /tar -cvpzf backup.tar.gz --exclude=/backup.tar.gz --one-file-system /

Explicación :

tar = es el comando que crea el archivo del sistema comprimido. Se cambian los argumentos del archivo por cada letra que se le agrega al comando.

  • c = crear un nuevo archivo de copia de seguridad.
  • v = Modo verbose, muestra por pantalla lo que esta haciendo el comando
  • p = Conserva los permisos de los archivos originales
  • z = Comprimir el archivo en formato gzip para reducir su tamaño
  • f = (nombre del archivo) especifica donde se guardara el archivo
  • –exclude = Directorios a los cuales no se les realizara copia de seguridad
  • –one file-system = No incluir archivos en un sistema de archivos diferente. Si desea que otros sistemas de archivos, tal como un la partición /home o medios externos montados en /media o /mnt se copien hay que hacer copias de ellos por separado, u omitir esta bandera.  Si se omite, tendrá que añadir varios argumentos más a –exclude= para evitar los sistemas de ficheros que no se desean mover.  Estos serían /proc , /sys , /mnt , /media , /run y /dev directorios en la raíz. /proc y /sys sistemas de archivos virtuales que proporcionan ventanas en variables del núcleo por ejecución, por lo que no se requieren tratar como copia de seguridad al restaurarlos ya que son creados y eliminados de forma dinámica por udev, por lo que también no se requieren hacer copias de seguridad o restaurarlo. Del mismo modo,  /run es un tmpfs que mantiene las variables sobre el sistema de ejecución que no necesita una copia de seguridad.  Es importante recalcar que las exclusiones son recursivas, esto significa que cada directorio ubicado dentro también sera excluido.

3.- Armar el servidor donde volcaremos el sistema operativo

3.1 Iniciar la VM con el disco de finnix como boot

3.2 Establecer una password a root e iniciar ssh

passwd root/etc/init.d/ssh start

4.- Configurar las particiones

root@0:~# fdisk -lDisk /dev/loop0: 146 MiB, 153083904 bytes, 298992 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk /dev/sda: 10 GiB, 10737418240 bytes, 20971520 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytes

4.1 Creación de la partición de sistema

root@0:~# fdisk /dev/sdaWelcome to fdisk (util-linux 2.26.2).Changes will remain in memory only, until you decide to write them.Be careful before using the write command.Device does not contain a recognized partition table.Created a new DOS disklabel with disk identifier 0x5cc45e73.Command (m for help): nPartition type   p   primary (0 primary, 0 extended, 4 free)   e   extended (container for logical partitions)Select (default p): pPartition number (1-4, default 1): First sector (2048-20971519, default 2048): Last sector, +sectors or +size{K,M,G,T,P} (2048-20971519, default 20971519): +500MCreated a new partition 1 of type 'Linux' and of size 500 MiB.Command (m for help): tSelected partition 1Partition type (type L to list all types): aChanged type of partition 'Linux' to 'OS/2 Boot Manager'.Command (m for help): wThe partition table has been altered.Calling ioctl() to re-read partition table.Syncing disks.

4.2 Creación de la partición extendida para el LVM

root@0:~# fdisk /dev/sdaWelcome to fdisk (util-linux 2.26.2).Changes will remain in memory only, until you decide to write them.Be careful before using the write command.Command (m for help): nPartition type   p   primary (1 primary, 0 extended, 3 free)   e   extended (container for logical partitions)Select (default p): ePartition number (2-4, default 2): First sector (1026048-20971519, default 1026048): Last sector, +sectors or +size{K,M,G,T,P} (1026048-20971519, default 20971519): Created a new partition 2 of type 'Extended' and of size 9.5 GiB.Command (m for help): wThe partition table has been altered.Calling ioctl() to re-read partition table.Syncing disks.

4.3 Creación de la particicion LVM

root@0:~# fdisk /dev/sdaWelcome to fdisk (util-linux 2.26.2).Changes will remain in memory only, until you decide to write them.Be careful before using the write command.Command (m for help): nAll space for primary partitions is in use.Adding logical partition 5First sector (1028096-20971519, default 1028096): Last sector, +sectors or +size{K,M,G,T,P} (1028096-20971519, default 20971519): Created a new partition 5 of type 'Linux' and of size 9.5 GiB.Command (m for help): tPartition number (1,2,5, default 5): Partition type (type L to list all types): 8eChanged type of partition 'Linux' to 'Linux LVM'.Command (m for help): wThe partition table has been altered.Calling ioctl() to re-read partition table.Syncing disks.

4.4 Configurar el LVM

4.4.1 Creación del PV

root@0:~# pvcreate /dev/sda5  Physical volume "/dev/sda5" successfully created

4.4.2 Creación del VG

root@0:~# vgcreate ubuntuvm1-vg /dev/sda5  /proc/devices: No entry for device-mapper found  Volume group "ubuntuvm1-vg" successfully created

4.4.3 Creación de los volúmenes

root@0:~# lvcreate -L 8.50G -n root ubuntuvm1-vg  Logical volume "root" createdroot@0:~# lvcreate -l 100%FREE -n swap_1 ubuntuvm1-vg  Logical volume "swap_1" created

4.4.5 Formatear las particiones

root@0:~# mkfs.ext2 /dev/sda1mke2fs 1.42.13 (17-May-2015)Creating filesystem with 512000 1k blocks and 128016 inodesFilesystem UUID: 33454e21-4573-49b1-9a6f-cdef181da43cSuperblock backups stored on blocks: 	8193, 24577, 40961, 57345, 73729, 204801, 221185, 401409Allocating group tables: done                            Writing inode tables: done                            Writing superblocks and filesystem accounting information: done 
root@0:~# mkswap /dev/ubuntuvm1-vg/swap_1 Setting up swapspace version 1, size = 1 GiB (1082126336 bytes)no label, UUID=154ce276-63c4-4d27-81c3-73d457926900
root@0:~# mkfs.ext4 /dev/ubuntuvm1-vg/root mke2fs 1.42.13 (17-May-2015)Creating filesystem with 2228224 4k blocks and 557056 inodesFilesystem UUID: b993c07f-689e-4345-b612-5b5ba67ada72Superblock backups stored on blocks: 	32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632Allocating group tables: done                            Writing inode tables: done                            Creating journal (32768 blocks): doneWriting superblocks and filesystem accounting information: done 
root@0:~# blkid/dev/loop0: TYPE="squashfs"/dev/sr0: UUID="2015-05-31-17-50-05-00" LABEL="Finnix 111" TYPE="iso9660" PTUUID="6b8b4567" PTTYPE="dos"/dev/sda1: PARTUUID="5cc45e73-01"/dev/sda5: UUID="DptfSl-ScsF-9oO1-N4Ag-BD0f-GHrw-jQa0vk" TYPE="LVM2_member" PARTUUID="5cc45e73-05"/dev/mapper/ubuntuvm1--vg-root: UUID="b993c07f-689e-4345-b612-5b5ba67ada72" TYPE="ext4"/dev/mapper/ubuntuvm1--vg-swap_1: UUID="154ce276-63c4-4d27-81c3-73d457926900" TYPE="swap"

5.- Montar la partición root en la maquina destino

root@0:~# mount /dev/ubuntuvm1-vg/root /mnt/

6.- Copiar el backup desde la maquina origen a la maquina destino

root@ubuntuvm1:~# scp /backup.tar.gz root@192.168.0.17:/mntroot@192.168.0.17's password: backup.tar.gz

7.- Montar el disco de sistema en /mnt y crear la carpeta boot.  Maquina de destino

root@0:/# mkdir /mnt/boot && mount /dev/sda1 /mnt/boot

8.- Descomprimir el archivo de backup en /mnt/

cd /mnttar -xvpzf backup.tar.gz -C /mnt --numeric-owner

Explicación :

  • x =  Le dice a tar que extraiga el archivo designado
  • -C <directorio> = Esta opción le dice a tar que cambie a un directorio específico antes de extraerlo. En este ejemplo, estamos restaurando en el directorio de montaje (/mnt)
  • –numeric-owner = Esta opción le dice a tar que restaure los propietarios numéricos de los archivos en el archivo, en lugar de coincidir con los nombres de usuario en el entorno desde el que está restaurando. Esto se debe a que las identificaciones de usuario en el sistema que desea restaurar no coinciden necesariamente con el sistema que utiliza para restaurar (por ejemplo, cuando se restaura desde un liveCD).

9.- Creación de los directorios excluidos

cd /mnt && mkdir proc sys mnt media dev dev/pts

10.- Restaurar el GRUB

Desde el servidor origen sincronizar el directorio /boot

root@ubuntuvm1:# rsync -avp /boot/* root@192.168.0.17:/mnt/boot

Para que el sistema arranque, se debe restaurar GRUB, Para hacer esto necesitaremos reconfigurarlo en un chroot

root@0:/mnt# for i in /dev /dev/pts /proc /sys /run; do sudo mount -B $i /mnt$i; doneroot@0:~# chroot /mntroot@finnix:/# grub-install /dev/sdaInstalling for i386-pc platform.Installation finished. No error reported.root@finnix:/# exitexitroot@0:/mnt#

11.- Reconfigurar FSTAB

root@0:/mnt# blkid/dev/loop0: TYPE="squashfs"/dev/sr0: UUID="2015-05-31-17-50-05-00" LABEL="Finnix 111" TYPE="iso9660" PTUUID="6b8b4567" PTTYPE="dos"/dev/sda1: UUID="33454e21-4573-49b1-9a6f-cdef181da43c" TYPE="ext2" PARTUUID="5cc45e73-01"/dev/sda5: UUID="DptfSl-ScsF-9oO1-N4Ag-BD0f-GHrw-jQa0vk" TYPE="LVM2_member" PARTUUID="5cc45e73-05"/dev/mapper/ubuntuvm1--vg-root: UUID="b993c07f-689e-4345-b612-5b5ba67ada72" TYPE="ext4"/dev/mapper/ubuntuvm1--vg-swap_1: UUID="154ce276-63c4-4d27-81c3-73d457926900" TYPE="swap"
nano /mnt/etc/fstab

Cambiar el UUID del disco de boot

# /etc/fstab: static file system information.## Use 'blkid' to print the universally unique identifier for a# device; this may be used with UUID= as a more robust way to name devices# that works even if disks are added and removed. See fstab(5).## <file system> <mount point>   <type>  <options>       <dump>  <pass>/dev/mapper/ubuntuvm1--vg-root /               ext4    errors=remount-ro 0       1# /boot was on /dev/sda1 during installationUUID=33454e21-4573-49b1-9a6f-cdef181da43c /boot           ext2    defaults        0       2/dev/mapper/ubuntuvm1--vg-swap_1 none            swap    sw              0       0

12.- Apagar la maquina y desatachar el disco de finnix

13.- Iniciar la maquina

Maquina Migrada con éxito, espero que esta guía les sirva para mi fue complicado tuve que leer varias guías pero acá tienen la guía definitiva paso a paso… ÉXITO!! y que viva el código libre y el traspaso de los conocimiento adquirido con la experiencia.

No hay comentarios.:

Publicar un comentario