viernes, 14 de diciembre de 2012

Limitar acceso a un directorio web por la IP

Se debe crear un fichero .htaccess  que debe estar contenido en el mismo directorio a proteger.
Debe contener el siguiente código:


AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName "Control Access"
AuthType Basic
<LIMIT GET>
order deny,allow
deny from all
allow from x.x.x.x
allow from x.x.x.x/24
</LIMIT>
 
Cada IP o rango de IPs se coloca con una nueva línea de "allow from ". El número de "allow" es ilimitado.

Para proteger un fichero en particular
Proteger un fichero en particular
Si quieres proteger un fichero en lugar de un directorio, se hace de forma parecida. En el fichero .htaccess del directorio que contiene el fichero se indica lo siguiente:

<Files fichero.php>
 Order Deny,Allow
 Deny from All
 Allow from x.x.x.x
 </Files>
 

miércoles, 12 de diciembre de 2012

Can't open /dev/null: Permiso denegado

ls -l /dev/null
Los valores correctos deberían de ser:


 crw-rw-rw- 1 root root 1, 3

Si se tiene algo diferente como lo siguiente...


 -rw-r--r-- 1 root root 1, 3 

Como usuario root se debe borrar /dev/null

rm /dev/null

y crear uno nuevo

mknod -m 0666 /dev/null c 1 3

ahora si volvemos a hacer un ls, los permisos deberían ser los correctos



martes, 11 de diciembre de 2012

Comprobar si se ejecuta el cron.daily debug

run-parts --test /etc/cron.daily

Convertir formato científico a formato humano con bc y perl

Este código multiplica el primer número por el segundo usando "bc"
echo "1.234e23 9.876e14" | sed 's/e/*10^/g;s/ /*/' | bc
Este código hace lo mismo pero sacar el valor usando perl
echo "1.5 5.0000e-01" | sed -e 's/ /*/' | perl -nle 'print eval $_' 
Para convertir el número al formato...
echo "5.0000e-01" |  perl -nle 'print eval $_'    -> 0.5
echo "5.0000e+01" |  perl -nle 'print eval $_'    -> 50

miércoles, 5 de diciembre de 2012

diff entre directorios, y listado de ficheros

Ni idea, hasta este momento de que diff también se podía usar para el contenido de los directorios

diff /tmp/dir1 /tmp/dir2


ahora... qué pasa si los ficheros en ambos directorios tienen el mismo nombre, pero uno es de texto y otro es un binario, por ejemplo, una es una fuente de código y otro es el fichero binario, pero queremos saber que binario no se ha compilado...

diff <(ls /tmp/dir1)  <(ls /tmp/dir2) 



Comparar listados de ficheros entre un equipo local y un servidor remoto

ssh user@host  ls /tmp/dir1 | diff - <(ls dir2/) 


viernes, 23 de noviembre de 2012

vbackup - backup ficheros y mysql sencillo + rsync



#apt-get install vbackup
#vbackup-wizard


Welcome to vbackup initial configuration wizard.
Your configuration files will be stored in:
/etc/vbackup

You'll now be asked a series of questions.
Default answers will be shown in brackets. You can accept them by pressing
enter.

Press enter to continue...



pulsamos enter

You can have unlimited number of backup schemes. Each scheme must have a
unique name that will be used to distinguish it. It is possible to have a
blank scheme name which is fine for most cases.

Enter the backup scheme name [] 1mysql


meto el nombre de la configuración de backup, en este caso "1mysql"



You can keep a list of installed packages. This is also known as the dpkg
selections list. This is a small text file that is very usefull for system
restores.

Backup dpkg database? (y/n) [y] y


Introduce "y" para marcar que se quiere hacer un backup de los paquetes instalados


It is possible to backup Master Boot Records from local disks,
LVM information, MD information and some other related information.
This can be of great help whenever something bad happens.

Backup Master Boot Records and other related information? (y/n) [y] n







Introduzco "n" porque no me interesa guardar el MBR (en mi caso)

You can backup your PostgreSQL cluster (if you have one). This will perform
a backup of all databases but only for the 'main' cluster. If you have
multiple clusters you'll have to add more tha one configuration files, one
for each cluster. You'll have to do this by hand

Perform PostgreSQL backup? (y/n) [n]


Introduzco "n" porque no quiero hacer una backup de postgresSQL sino de mysql


You can backup your MySQL database (if you have one). This will backup all
databases.

Perform MySQL backup? (y/n) [y]


Introduzco Y porque quiero hacer el backup de la base de datos mysql


You must enter the password of the root user. You should know that this is
insecure in case of a multiuser system. It is advised to create a .my.cnf
file and enter the password in there. Leave this field empty if you're going
to do this

Enter the password for the root user [] abcd1234


Introduzco el password de root de la base de datos mysql 

It is advised to backup your system configuration. The system configuration
will be backed up using GNU tar

Backup system configuration? (y/n) [y]




Introducimos Y para guardar la configuración de los fichero /etc

On sane systems all configuration files are stored in /etc. It is also a
convenience thing to backup /boot too. Please note that this wizard doesn't
support paths with spaces.

What directories contain configuration files? [/etc /boot]

Se puede poner separado por espacios lo diferentes directorios que se consideren de configuración para que se haga un copia de backup, en mi caso solo uso /etc


For desktop systems, the most important part of the backup is the home
directories. In most cases home directories must be backed up. If you have
an XFS partition for the home directories you should say no here and use
the xfsdump method for backing up the whole partition.
Beware that this will not cross filesystem boundaries. If you have multiple
partitions mounted under /home you should backup each of them seperately!

Backup /home directory? (y/n) [y] y


 Se marca Y para guardar el contendio de los directorios "/home"


If you have other directories that need to be backed up using the tar method
enter them here

Other directories to backup? [] /usr/local/sbin


Y para guardar en un backup otros directorios que no sean ni home, ni etc, se tiene esta opción donde una vez mas se puede poner la ruta separada por espacios.  Por ejemplo yo lo he usado para guardar los scripts locales que de vez en cuando voy creando.


vbackup stores all backups under a common directory prefix. Please enter a
prefix where all backups will be placed under. Be carefull not to use a path
that is been backed up or you will create a backup paradox.

The best place to store backups is an external disk or a remote directory that
is localy mounted

Where to place backups? [] /var/backup



Aqui se pone el directorio destino del backup, en mi caso /var/backup


Done! You can now create level 0 backups by running:

# vbackup 1mysql0

and level 5 backups by running:

# vbackup 1mysql5

Level 5 backups are incremental backups. This means that they only store
differences from the last level 0 backup. This is only possible for filesystem
backups. For all other cases where an incremental backup is not possible (like
database backups) a full backup will be made. To restore a level 5 backup you
also have to have the level 0 backup. This means that you may only delete
older same-level backups.

All configuration options are placed under /etc/vbackup
If you want to further customize the backup procedure you will have to have
a look at the documentation. All configuration options are documented at
plugin help screens and in the sample configuration files. You can get a list
of available plugins by running:

# vbackup --list

You can get further information about each plugin by running

# vbackup --help <plugin name>

After using vbackup don't forget to send some feedback to v13@v13.gr
Since this is a work-in-progress, this will greatly affect the way vbackup
is developed and what new features will be available in the near future.


Se termina el wizard, y ha podriamos probar nuestro backup con el siguiente comando:

#vbackup 1mysql0

Para poder ver en modo debug que es lo que está haciendo el script, yo lo ejecuto de la siguiente forma:

#vbackup -d 14 1mysql0

Ahora podemos hacer algún afinamiento al script para que se pueda copiar el fichero por scp a algún servidor. Para esto, tenemos que ver primero los ficheros de configuración creados en /etc/vbackup

ls -l /etc/vbackup/backup.1mysql0/
total 20
-rw-r--r-- 1 root root  16 nov 23 17:10 20-dpkg.dpkg
-rw-r--r-- 1 root root  15 nov 23 17:10 21-rpm.rpm
-rw-r--r-- 1 root root 119 nov 23 17:10 30-mysql.mysql
-rw-r--r-- 1 root root 145 nov 23 17:10 50-tar.tar
-rw------- 1 root root 259 nov 23 17:12 vbackup.conf


El primer número marca el orden de ejecución, por lo tanto, si quiero crear una copia por scp, debería de crear un fichero 60-scp.scp con el siguiente contenido:

SOURCE=""
RPREFIX="/var/backup"
RHOST=192.168.1.4   
USERNAME=root
  RDIR="backup_remoto"





  
En este fichero, RHOST sería la ip del servidor remoto, USERNAME el nombre del usuario que ejecutaría el comando "scp", y el directorio destino quedaría así  "/var/backup/backup_remoto"

Es decir, el comando que se ejecutaría automáticamente sería

scp  /var/backup/*  root@192.168.1.4:/var/backup/backup_remoto

y todo esto de forma recursiva. Como está puesto con el prefijo 60, este comando se ejecutará el último, y copiara todo el contenido de /var/backup en el host 192.168.1.4 en el directorio /var/backup/backup_remoto

Obviamente, para hacer el scp sin que se pida pasword hay que establecer relaciones de confianza entre los dos equipos. Esto se puede hacer fácilmente de la siguiente forma:

Paso 1- Ejecutar lo siguiente 
     ssh-keygen -b 4096 -t rsa

En el servidor que va a enviar la copia de seguridad

Paso 2
 En el mismo servidor, hacer  un ssh-copy id a la ip del servidor donde se quiere mandar una copia del backup.
    ssh-copy-id remoto@192.168.1.4



Una vez hecho esto, desde el equipo que esta haciendo la copia de seguridad se podrá conectar con un ssh al host 192.168.1.4 sin introducir password.



Cierto es que para backups grandes, este método de hacerlo por scp, no me convencía mucho, así que dejo aquí un script para hacerlo con copia incremental usando "rsync" que me parece que es mucho mas adecuado:

crea el siguiente fichero  /usr/share/vbackup/scripts/rsync  con tu editor favorito y copia y pega el contenido de abajo.

#!/bin/bash
#
# This file is part of vbackup.
#
# vbackup 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 2 of the License, or
# (at your option) any later version.
#
# vbackup 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 vbackup; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
#
# $Id$
#
# Description
#
#       Perform file copy using scp
#

NAME="rsync"
VERSION="$PACKAGE_VERSION"
DESC="Remote file copy using scp"
LICENSE="GPLv2"
COPYRIGHT="Copyright (c) 2009 Stefanos Harhalakis"
CONTACT=""

# Display help
do_help()
{
        cat << _END
This method copies a file or a tree to a remote host using rsync. It can be
used at the end of a backup to copy the backup to a remote host.

For scp to work you have to setup public key authentication from local host
to the remote host. You also have to to perform an interactive ssh to the
remote host first. This is needed to accept the remote host's key and ensure
that public key authentication works.

NOTE: When doing the interactive login use the exact same hostname as it
is specified in the config file. For ssh "127.0.0.1" and "localhost" are not
the same.

Configuration options:
        SOURCE          The local directory to copy data from (required)
        RHOST           The remote host name (required)
        RPREFIX         A prefix at the remote host that should pre-exist
                        (required)
        RDIR            The directory under prefix that will be used for
                        data to be copyied
        USERNAME        The username to use (required)
        SCPEXTRA        Extra parameters to be passedo to scp (optional)
_END

        if [ -z "$RSYNC" ] ; then
                cat << _END

 !! This method is DISABLED becuase RSYNC was not found
_END
        fi
}

# Check configuration
# return: 0: ok, 1: error
do_check_conf()
{
        [ -z "$RSYNC" ] && h_error "RSYNC was not found" && return 1

#       [ -z "$SOURCE" ] && h_error "Missing SOURCE" && return 1
        [ -z "$RHOST" ] && h_error "Missing RHOST" && return 1
        [ -z "$USERNAME" ] && h_error "Missing USERNAME" && return 1

        return 0
}

# Do backup
do_run()
{
        if [ "x$ABORT" = "x1" ] ; then
                return 0
        fi

        if [ -z "$RSYNC" ] ; then
                h_error "RSYNC was not found"
                return 1
        fi

        # Form destination
        DST="$RPREFIX/$RDIR"

        # Expand special chars
        h_transform "$DST"
        DST="$R"

        # Form source
        h_transform "$SOURCE"
        T="${R:0:0}"
        if ! [ "x$T" = "x/" ] ; then
                SRC="$DESTDIR0/$R"
        else
                SRC="$R"
        fi

        h_msg 6 "$SRC -> $USERNAME@$RHOST:$DST"

        if rsync -av \
                 "$SRC" "$USERNAME@$RHOST:$DST" ; then
                h_msg 6 "RSYNC succeeded"
        else
                h_msg 2 "RSYNC failed"
        fi

        return 0
}




El script, es una modificación del  script de "scp" que va incluida en el paquete.
Se puede ver en el código la línea donde se ejecuta:

rsync -av \
                 "$SRC" "$USERNAME@$RHOST:$DST"



  

Para añadir el script de rsync y que todo funcione (creo), también hay que modificar el siguiente fichero



añadiendo el modulo de rsync    vi /usr/share/vbackup/helpers/common

# Program locations
XFSDUMP=$(h_lookup "/usr/sbin/xfsdump" xfsdump)
GFIND=$(h_lookup "/usr/bin/find" find)
GTAR=$(h_lookup "/bin/tar" tar)
FDISK=$(h_lookup "/sbin/fdisk" fdisk)
SFDISK=$(h_lookup "/sbin/sfdisk" sfdisk)
MDADM=$(h_lookup "/sbin/mdadm" mdadm)
LVDISPLAY=$(h_lookup "/sbin/lvdisplay" lvdisplay)
VGDISPLAY=$(h_lookup "/sbin/vgdisplay" vgdisplay)
PVDISPLAY=$(h_lookup "/sbin/pvdisplay" pvdisplay)
SCP=$(h_lookup "" scp)
RSYNC=$(h_lookup "" rsync)    <-- solo se añade esta línea







Ahora ya podriamos añadir un script en /etc/vbackup/backup.1mysql0/
identico al que se usa con el script scp, pero que ejecuta rsync

cat   /etc/vbackup/backup.1mysql0/70-rsync.rsync
 
SOURCE=""
RPREFIX="/var/backup"
RHOST=192.168.1.4   
USERNAME=root

RDIR="backup_remoto"





miércoles, 21 de noviembre de 2012

Crear nuevo password para root en mysql




#1: Parar servicio de MySQL.
#2: Iniciar MySQL (mysqld) server/daemon con el parámetro  "--skip-grant-tables" asi, no pedirá el password.
#3: Conectar al mysql como root (no pedirá contraseña).
#4: Resetear el password de root.
#5,6: Salir y reiniciar el servicio de MySQ.

# 1 : Parar MySQL server

# /etc/init.d/mysql stop
Output:
Stopping MySQL database server: mysqld.

# 2: Iniciar MySQL server w/o password:

# mysqld_safe --skip-grant-tables &
Output:
Starting mysqld daemon with databases from /var/lib/mysql
mysqld_safe[]: started

# 3: Connectar a mysql usando el cliente mysql:

# mysql -u root
Output:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 4.1.15-Debian_1-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>

# 4: Crear un nuevo password

mysql> use mysql;
mysql> update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit

# 5: Parar el mysql seguro que estaba funcionado sin password

# killall -9 mysqld_safe
Output:
[1]+  Killed                  mysqld_safe --skip-grant-tables

# 6: Iniciar el servicio de MySQL y comprobar que se tiene acceso con el nuevo password

# /etc/init.d/mysql start
# mysql -u root -p

martes, 20 de noviembre de 2012

Show tables en Postgress

mysql: SHOW TABLES
postgresql: \d

mysql: SHOW DATABASES
postgresql: \l

mysql: SHOW COLUMNS
postgresql: \d table
mysql: DESCRIBE TABLE
postgresql: \d+ table

Exportar base de datos en PostgreSQL

 

Para exportar al fichero

# pg_dump -U username  -h 127.0.0.1  base_de_datos > /tmp/base_de_datos.sql

Para importar a la base de datos

# su postgres
$ psql -U postgres -d base_de_datos -f /tmp/base_de_datos.sql