Tag Archives: backup

Python script to backup and restore rpm packages

I’ve written a simple Python script to backup and restore installed rpm packages.

On Ubuntu, I used APTonCD for this matter, but in this case, for Fedora I decided to use my own script.

The usage is quite simple, only two parameters:

Backup:

python rpm-backup.py --backup

Restore:

python rpm-backup.py --restore

 

This is source code, although you can download it from my github (link to the gh-page of the entire repository)

#!/usr/bin/python

''' Backup script for installed packages.
Only RPM.
Tested under Fedora
Error list:
Code 1: Missing modules
Code 2: Not root
Code 3: Tried to restore without backup file'''

print "     ____  ____  __  ___"
print "    / __ \/ __ \/  |/  /"
print "   / /_/ / /_/ / /|_/ / "
print "  / _, _/ ____/ /  / /  "
print " /_/ |_/_/   /_/  /_/   "


print "        ____  ___   ________ ____  ______ "
print "       / __ )/   | / ____/ //_/ / / / __ \ "
print "      / __  / /| |/ /   / ,< / / / / /_/ /"
print "     / /_/ / ___ / /___/ /| / /_/ / ____/ "
print "    /_____/_/  |_\____/_/ |_\____/_/      "

#Import modules
try:
    import os
    import argparse
except ImportError:
    print "Could not find required modules. Exiting..."
    exit(1)

# Create parser
parser = argparse.ArgumentParser(description='Backup your installed packages.', epilog="Written by Adrian Espinosa (aesptux).")


# if user types --backup it will be stored as true in variable backup
#if user types --restore it will be stored as true in variable backup
parser.add_argument('--backup', action='store_true', dest='backup', help='Backup your packages.')
parser.add_argument('--restore',  action='store_true', dest='restore', help='Restore your packages.')


args = parser.parse_args()
#print args
#print(args.option(args.integers))

#variables
userlogged = os.environ['LOGNAME']
directory = '/%s' % (userlogged)
filename = 'packages-installed.bak'
path = directory + '/' + filename
rpm_list = []
print " "
print "Hello %s!" % (userlogged)
print "If you are having troubles using the script, use the argument '--help'"


def dobackup():

    ''' Create backup '''
    print "Starting copy..."
    command = 'rpm -qa > ' + path
    #os.system('touch '+path)
    os.system(command)
    os.system('echo Total packages: ; cat ' + path + ' | wc -l ')
    print "Done."


def dorestore():

    ''' Restore packages'''
    print "Starting restore..."
    global rpm_list
    # try, except, to see if the backup file exists
    try:
        for line in open(path, 'r'):
            rpm_list.append(line)
    except IOError:
        print "The backup file does not exist. Please, create a backup first. "
        exit(3)
    # take the list and join it
    rpm_list = ''.join(rpm_list)
    # remove \n
    rpm_list = rpm_list.replace('\n', ' ')
    os.system('yum install ' + rpm_list)


#This script must be run as root
if userlogged != 'root':
    print "You have to run the script as root"
    exit(2)


# if backup is true, dobackup. Else if restore is true, dorestore
if args.backup == True:
    dobackup()
elif args.restore == True:
    dorestore()

 

Then, you can set up a cron job like this:

0 22 * * * /usr/bin/python /root/rpm-backup.py --backup

 

Nuevo script para realizar backups

Ayer estuve escribiendo un nuevo script para realizar los backups en mi sistema, ya que mis necesidades han cambiado.

El script está adaptado a mi sistema y como digo, mis necesidades, pero quizás os pueda servir a vosotros.

#!/bin/bash
#    Backup for my system.
#    Copyright (C) <2011>  <Adrian 'aesptux' Espinosa>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

#    Check if the folder with the ID name exists
#    Mount the device
#    Backup our files
#    Unmount the device
NOW=$(date +%Y-%m-%d)
LOGPATH="/root/backup/"
LOGFILE="$NOW.backup.log"
ERRORMSG="zenity --error --title Error --text "
INFOMSG="zenity --info --title Information --text "
RSYNC="rsync -avuz --progress --delete "
# Device info
DEV1="/dev/sda2/"
LABEL1="Multimedia"
ID1="A61052121051EA37"
PATH1="Backup/actual"

clear
if [ $UID -ne 0 ]; then
	$ERRORMSG "Sorry you have to run this script as root"
	exit 1
else
	if [ ! -d /media/$ID1 ]; then
		mkdir /media/$ID1
		if [ $? -eq 0 ]; then
			echo "Folder created" | tee -a $LOGPATH$LOGFILE
		else
			$ERRORMSG "Error creating folder. Exiting"
			echo "Error creating folder. Exiting" | tee -a $LOGPATH$LOGFILE
			exit 2
		fi
	fi
	mount $DEV1 /media/$ID1
	if [ $? -eq 0 ]; then
		echo "Disk mounted." | tee -a $LOGPATH$LOGFILE
		$INFOMSG "Backup started"
		$RSYNC /etc /media/$ID1/$PATH1 2>> $LOGPATH$LOGFILE
		$RSYNC /var /media/$ID1/$PATH1 --exclude "/var/cache/*" 2>> $LOGPATH$LOGFILE
		$RSYNC /home /media/$ID1/$PATH1 --exclude "/home/mortuus/Downloads/*" --exclude "/home/mortuus/Videos/*" --exclude "/home/mortuus/.VirtualBox/HardDisks/*" --exclude "/home/mortuus/.local/share/Trash/*" --exclude "/home/mortuus/.cache/*" --exclude "/home/mortuus/.thumbnails/*" --exclude "/home/mortuus/Dropbox" 2>> $LOGPATH$LOGFILE
		###### MYSQL DATABASES DUMP
		mysqldump --all-databases -u root -p123456789a > /media/$ID1/$PATH1/$NOW.mysqldump.sql 2>> $LOGPATH$LOGFILE
		umount $DEV1
		$INFOMSG "Backup finished"
	else
		$ERRORMSG "Disk failed to mount. Exiting" 
		echo "Disk failed to mount. Exiting" | tee -a $LOGPATH$LOGFILE
		exit 3
	fi
fi

También podéis encontrarlo en mi Github

Herramienta rsync.

Rsync es una herramienta fascinante para sincronizar carpetas y crear copias de seguridad.

Un uso básico podría ser el siguiente:

rsync -avuz “/media/pendrive/clase” “/home/usuario/materias”

  • -a: Mantener permisos, propietarios, etc.
  • -v: Verbose.
  • -u: Saltarse archivos que sean más recientes en el destino (actualizaciones)
  • -z: Comprimir durante la transferencia

rsync -e ssh -avuz user@192.168.1.2:/home/user/imagenes /media/pendrive

El comando anterior sirve para transmitir vía SSH.

Luego mediante crontab podemos automatizarlo, por ejemplo para que cada día a las 23.00 haga una copia:

crontab -e

* 23 * * * usuario rsync -avuz /home/user/fotos /media/pendrive/fotos 2>&1  > /var/rsync.log

Hacer backup de los programas en Linux

APTonCDEs un palo que al formatear tengamos que descargar e instalar todo otra vez. Y todo esto, contando con que tengamos conexión a Internet.

Hay una aplicación que nos facilitará las cosas, se llama APTonCD.

Esta aplicación nos hará un backup de nuestros programas en un CD/DVD o si lo deseamos en una imagen iso, para luego restaurarlo desde ahí.

Para instalarlo:

sudo apt-get install aptoncd

Después nos dirigimos a Sistema-> Administración->APTonCD

Es un programa muy bueno, con una interfaz sencilla e intuitiva que no dará problemas.