Bienvenido, Invitado
Nombre de Usuario Contraseña: Recordarme

Backup y restauración de postgres
(1 viendo) (1) Invitado
  • Página:
  • 1

TEMA: Backup y restauración de postgres

Backup y restauración de postgres hace 1 año, 8 meses #16

  • chencho
  • DESCONECTADO
  • Moderador
  • Temas: 110
  • Karma: 0
Buenas a todos.

A pesar de que las interfaces gráficas funcionan cada vez mejor, hay veces que tenemos problemas y nos hace falta recurrir a la consola (que esta si que no falla).

Después de perder casi una hora para hacer un backup de una base de datos y restaurarla en otra máquina, os comento cómo lo he conseguido.

Para comenzar, necesitamos acceso a la consola del servidor A.

Una vez ahí, accedemos a un directorio con permisos de escritura, en mi caso:

cd /tmp


Nos logueamos como postgres

su postgres


Ahora ya podemos hacer el backup; yo lo hago y comprimo:

pg_dump gestion | gzip > /var/backup/postgres/gestion.gz


Esto nos guarda una copua en /var/backup/postgres/, podéis ponerla donde queráis.

Para acabar, la muevo un directorio accesible desde el servidor B

cp /var/backup/postgres/gestion.gz /var/www/vhosts/dominio.com/httpdocs/tmp/


Entramos en el servidor B

Lo primero es descargar la copia de la base de datos:

cd /tmp
wget http://midominio.com/tmp/gestion.gz


Lueg descomprimimos

gzip -d gestion.gz


Entramos como usuario postgres

su postgres


Importante! Debemos tener un usuario igual que en la máquina A para trabajar con la base de datos

Importamos la base de datos

psql -U usuario -d gestion -f gestion


La base de datos "gestion" NO debe existir antes de esto en el servidor B.

Script automático sin contraseña para postgres hace 1 año, 8 meses #21

  • chencho
  • DESCONECTADO
  • Moderador
  • Temas: 110
  • Karma: 0
Podemos crearnos un script para automatizar las copias de seguridad en postgres.

Al hacerlo me encontraba con el problema de las contraseñas, ya que me pedía la contraseña al ejecutar el script y de esta forma no es desatendida y automática.

Buscando he encontrado un script muy interesante:

#!/bin/sh
##############################
#Script by Anas V
##############################

#Substitute your postgresql root username in the below given line
PGUSER=postgres
#Substitute your postgresql root password in the below given line
#PGPASSWORD=mypostgre
PGPASSWORD=
export PGUSER PGPASSWORD

tdate=`date +%d-%b-%Y`

if [ $# -lt 1 ]

# Check if there is atleast one argument [i.e the database whose dump is to be taken]
#First argument is mandatory - Databse name
#Second argument is optional - Destination path to save dump
then

        echo "Bad Arguments"
        echo "-----------------------------------"
        echo "USAGE : pg_dmp.sh <databasename> [outputfile]"
        echo "-----------------------------------"
        exit 1
else

#if one or more arguments were provided
        if [ $# -ge 2 ]
        #if arguments provided is greater than or equal to 2
        then
		#Comment out the below given file exist check and it's associated messages
		# if you want to run the pg_dmpsh script to run silently. i.e from a cron or at job
		# without any user interaction. Then the output dump file will be rewritten if a file
		# already exists. 
                if [ -f $2  ]
                # if destination file ie argument 2 is already existing
                then
                        #Show confirmation message to confirm whether replace file with new one or exit
                        dialog --title "Confirm File Replace" --backtitle "pg_dmp.sh"\
                        --yesno "\nFile already exist, Do you want to replace it with '$2' file" 7 90
                        sel=$?
                        case $sel in
                        #if Yes then take dump and replace the existing file with new dump
                        0)  pg_dump $1 -f $2 -i -x -O -R;;
                        #if No then exit
                        1) exit 1 ;;
                        #if escape then exit
                        255) exit 1;;
                        esac
                else
                        #if destination file does not exist then create and save the dump in destination path
                         pg_dump $1 -f $2 -i -x -O -R
                fi
        else
                if [ $# -eq 1 ]
                #if arguments provided is equal to 1
                then
                        if [ -d $HOME/pg_backup_$1 ]
                        #if folder name pg_backup_'databsename' exist in the current users home directory
                        then
                                if [ -f $HOME/pg_backup_$1/$1_$tdate ]
                                #if destination file name exist in pg_backup_'databasename' folder in current users home dierectory
                                then
                                #Show confirmation message for replacing the file with new dump
                                        dialog --title "Confirm File Replace" --backtitle "pg_dump.sh"\
                                        --yesno "\nFile already exist, Do you want to replace it with '$HOME/pg_backup_$1/$1_$tdate' file" 7 90
                                        sel=$?
                                        case $sel in
                                        #if Yes then replace the file with new dump file
                                        0) pg_dump $1 -f $HOME/pg_backup_$1/$1_$tdate -i -x -O -R;;
                                        #if No then exit
                                        1) exit 1 ;;
                                        #if escape thenexit
                                        255) exit 1;;
                                        esac
                                else
                                        #if destination file does not exist then create and save the dump
                                        pg_dump $1 -f $HOME/pg_backup_$1/$1_$tdate -i -x -O -R
                                fi
                        else
                                #if folder pg_backup_'databsename' does not exist in the current users home dierectory then
                                #Create a new folder
                                mkdir $HOME/pg_backup_$1
                                #then create dump and save it
                                pg_dump $1 -f $HOME/pg_backup_$1/$1_$tdate -i -x -O -R
                                #if databse to take does not exist then Delete the folder created
                                if [ $? -ne 0 ]
                                then
                                        rmdir $HOME/pg_backup_$1
                                fi
                        fi
                fi
        fi
        if [ $# -gt 2 ]
        #if arguments passed where greater than 2 then  show message
        then
                echo "Extra Arguments ignored"
        fi
fi

#reset PGUSER and PGPASSWORD
PGUSER=""
PGPASSWORD=""
export PGUSER PGPASSWORD
#End



Hay que incluir el nombre de usuario y contraseña adecuados al comienzo del script.

Yo lo he llamado bck_postgres.sh pero podéis llamarlo como queráis.

Hay que darle permisos de ejecución

chmod +x bck_postgrees.sh


Y la ejecución es tan sencilla como esto:

sh bck_postgres.sh nombreBaseDeDatos


Así te creará un directorio en /home/usuario llamado "pg_backup_NombreBaseDeDatos" y dentro los diferentes backups con su fecha al final del nombre del fichero (comprimido ocn gz)

También puedes decirle donde quieres guardar el backup así:

sh bck_postgres.sh nombreBaseDeDatos /ruta/del/backup/BaseDeDatos.gz


Para automatizar, lo añades al crontab y listos.

Bases de datos accesibles solo por propietario hace 1 año, 8 meses #22

  • chencho
  • DESCONECTADO
  • Moderador
  • Temas: 110
  • Karma: 0
Me he topado con un problema con las bases de datos en postgres.

A pesar de crear una base de datos y tener un único usuario como propietario, otros usuarios podían listar las tablas de la base de datos.

Para cortar el acceso desde public a una bse de datos ya creada:

REVOKE ALL ON DATABASE nombre_bd FROM public;


Para que por defecto una base de datos sea sólo accesible por su propietario, hay que declararla como sigue:

CREATE DATABASE nombre_bd
WITH OWNER = nombre_propietario;
GRANT ALL ON DATABASE nombre_bd TO nombre_propietario;
REVOKE ALL ON DATABASE nombre_bd FROM public;


Info posteada por ivanmh en otro foro.
  • Página:
  • 1
Página generada en 0.24 segundos