Windows sobre Linux sin perder GRUB

Nota: Este procedimiento es idéntico en cualquier otra distribución linux, siempre y cuando tenga instalado GRUB. Lo que aqui se explica se debe hacer antes de reinstalar windows para no perder GRUB.
Si ya instalo windows y perdio GRUB debe leer Como Recuperar GRUB

Instalar Windows sobre Linux sin perder Grub


Un problema muy comun es que al reinstalar Windows, perdemos nuestro sector de arranque (GRUB)

Arranque dual Linux


La solución más sencilla a este problema pasa por crear un disquete de arranque con Grub, y volver a instalar Grub en el MBR después de instalar Windows.
Los pasos a seguir son:

Iniciamos Ubuntu Linux normalmente y abrimos un terminal con permisos de superusuario: Menu Aplicaciones -> Herramientas del sistema -> Root Terminal.

Editamos el fichero /boot/grub/device.map, por ejemplo con nano:
# nano /boot/grub/device.map
y añadimos la línea:
(fd0) /dev/fd0

Introducimos un disquete y le damos formato FAT:
# mkfs.vfat /dev/fd0

Lo montamos:
# mount -t vfat /dev/fd0 /media/floppy
donde /media/floppy es el directorio en el que queremos montar el disquete.

Ahora tenemos que instalar Grub en el disquete, ejecutando:
# cp -fr --parents /boot/grub/ /media/floppy
# umount /media/floppy
# grub-install /dev/fd0
Si no hubiésemos añadido la línea (fd0) /dev/fd0 en /boot/grub/device.map ahora obtendríamos el siguiente error:
/dev/fd0 does not have any corresponding BIOS drive

En este momento ya podemos instalar Windows sobre Linux sin miedo a perder Grub. Es conveniente probar antes si arrancar con el disquete. Debemos tener configurada la BIOS para que intente arrancar desde la disquetera antes de arrancar desde el disco duro.

Cuando acabemos de instalar Windows simplemente reiniciamos con el disquete que hemos creado, entramos en Ubuntu Linux y abrimos de nuevo un terminal con permisos de root. En él ejecutamos:
# grub-install /dev/hda
y ya tenemos de nuevo nuestro Grub, configurado exactamente de la misma forma que antes. Con este procedimiento tenemos nuevamente nuestro arranque dual linux.

How to install windows and not lose grub

Note: This procedure is identical in all other distributions, if you have installed GRUB. What is described here should do before installing windows in order not to lose GRUB.
If you install windows and lost GRUB should read How to recover GRUB

A very common problem is that when you install or reinstall Windows, we lose our boot sector (GRUB)
The simplest solution to this problem involves creating a boot disk with Grub, and reinstalling Grub in the MBR after installing Windows.
The steps to follow are:

Ubuntu started normally and opened a terminal permit root: Applications menu-> System Tools -> Root Terminal

Edit the file /boot/grub/device.map, for example using nano:
# nano /boot/grub/device.map
And add the line:
(fd0) /dev/fd0

We introduce a diskette and we FAT format:
# mkfs.vfat /dev/fd0

We mount:
# mount -t vfat /dev/fd0 /media/floppy
Where /media/floppy is the directory in which you want to mount the disk.

Now we have to install Grub on the diskette, running:
# cp -fr --parents /boot/grub/ /media/floppy
# umount /media/floppy
# grub-install /dev/fd0
If we had not added the line (fd0) /dev/fd0 en /boot/grub/device.map now get the following error:
/dev/fd0 does not have any corresponding BIOS drive

At this moment we can install Windows without fear of losing Grub. It is desirable if test before starting with the diskette. We have the BIOS to try booting from the floppy drive before booting from the hard drive.

When we finish installing Windows simply reboot with the floppy that we have created, we go into Ubuntu and again opened a terminal with root permissions. It ran:
# grub-install /dev/hda
And we already have our back Grub, configured exactly the same way as before.

Recuperar GRUB

Nota: si aun no instalaste otro sistema operativo y no quieres perder GRUB al hacerlo puedes leer: Como instalar Windows y no perder Grub

Uno de los problemas más comunes a lo que se enfrenta un usuario de GNU/Linux es que en caso de instalar o reinstalar un sistema operativo distinto (por ejemplo, Windows), el MBR (Master Boot Record) es reescrito por el del último sistema instalado, borrándonos el GRUB.

Recuperar Grub

Hay dos maneras de recuperar el GRUB: usando Super Grub Disk, o usando una distribución Live que contenga al GRUB.

Recuperar Grub con Super Grub Disk

Super Grub Disk es un restaurador del GRUB que se puede instalar en un dispositivo de almacenamiento portátil o externo (disquete, CD, DVD, USB, etc.). Incluye un manual integrado y es muy fácil de usar.
Es una imagen de disco ISO comprimida bajo GZip, necesitarás descomprimirla y luego copiar el contenido de la imagen a un disco externo, se recomienda un disquete de 3 1/2" por su reducido tamaño (para hacerlo en un CD o DVD, puedes usar un quemador de discos como K3b o GnomeBaker).

Al arrancarlo, las opciones que debemos seguir son las siguientes:

1. Idioma: español
2. Sistema operativo: Linux
3. Tarea: Arreglar arranque de Linux (GRUB)

Recuperar Grub con una distribución Live CD

Consiste en usar una distribución en modo LiveCD para instalar nuevamente el GRUB. Usaremos el LiveCD de Ubuntu Linux (debe ser la versión Live o Desktop), aunque puede ser cualquier otra distribución que use GRUB como gestor de arranque y no LILO.

En modo de resumen, los pasos que hay que seguir son los siguientes:

1. Arrancar una distribución LiveCD
2. Montar la partición donde se encuentra instalado Ubuntu
3. Instalar el GRUB en esa partición

A continuación se explica, en unos sencillos pasos, cómo hacerlo:

1. Iniciamos el ordenador y arrancamos desde el CD
2. Arrancamos Ubuntu (o la distribución escogida) en modo LiveCD
3. Abrimos una terminal o consola (no es necesario si tenemos una interfaz de línea de comandos, es decir, en modo texto)
4. Creamos una carpeta donde montar la partición de Ubuntu (la podemos crear en /media, por ejemplo: /media/ubuntu/)
5. Montamos la partición donde se encuentra instalado Ubuntu, usando el comando mount.
6. Aquí hay dos soluciones posibles:

Mediante el intérprete de comandos GRUB

Opción 1

1. Ejecutamos los siguientes comandos:

$ sudo grub --> ejecutamos el intérprete de comandos del GRUB
> root (hdX,Y) --> indicamos dónde está ubicada la partición de Ubuntu
> setup (hdX) --> instalamos el GRUB en esa partición
> quit --> salimos del intérprete de comandos del GRUB

Donde X es el número de disco rígido, y Y es el número de partición. Este sistema difiere un poco del usado para montar las particiones en GNU/Linux; ambos son un único número decimal y comienzan en 0; por ejemplo:

* hd0: es el primero disco duro completo, al igual que hda o sda
* hd0,0: es la primera partición del primer disco duro, al igual que hda1 o sda1
* hd0,1: es la segunda partición del primer disco duro, al igual que hda2 o sda2
* hd1,2: es la tercera partición del segundo disco duro, al igual que hdb3 o sdb3

El primer disco duro del GRUB es el primer disco duro maestro, el segundo es el primer disco duro esclavo, el tercero es el segundo disco duro maestro, y así sucesivamente.

Opción 2

1. Desde una consola ejecutamos los siguientes comandos:

$ sudo grub --> ejecutamos el interprete de comando de grub
> find /boot/grub/stage1 --> busca donde esta la partición de ubuntu
> root (hdX,Y) --> poner el valor devuelto anterior
> setup (hd0) --> instala grub en nuestro primer disco duro (hd0),
que es con el que inicia la computadora
> quit --> salimos del interprete de comando de grub

Cambiando el origen de la carpeta raíz

1. Cambiamos el origen de la carpeta raíz de nuestro sistema de archivos al directorio en el que hemos montado la partición de Ubuntu, para que al instalar GRUB interprete que la raíz del sistema está ahí. El comando necesario para ello es:

$ sudo chroot /home/ubuntu/

2. Ahora instalamos el GRUB en el MBR del primer disco duro, que normalmente estará configurado como Primary Master (hda):

$ sudo grub-install /dev/hda

How to recover GRUB

Note: if not installed another operating system and does not want to lose GRUB by doing so you can read: How to install windows and not lose Grub

One of the most common problems facing as a user of GNU / Linux is that if you install or reinstall a different operating system (such as Windows), the MBR (Master Boot Record) is rewritten by the last system installed, erasing the GRUB.

There are two ways to recover GRUB: using Super Grub Disk, or using a distribution Live containing at GRUB.

Using Super Grub Disk

Super Grub Disk is a restaurateur GRUB that can be installed on a portable storage device or external (floppy, CD, DVD, USB, etc..). Includes a manual integrated and is very easy to use.

You can download it from the following link:

Super Grub Disk 0.9598 (394 kB)

A disk image is compressed under ISO GZip, need to decompress and then copy the content of the image to an external disk is recommended disk 3 1 / 2 "by its small size (to do it on a CD or DVD, you can use a burner albums like K3b or GnomeBaker).

At the start, the options that we follow are:

1. Language: English
2. Operating System: Linux
3. Task: Fix Linux boot (GRUB)

Using a distribution Live

It consists of using a distribution mode LiveCD to re-install the GRUB. We will use the Ubuntu LiveCD (must be the version Live or Desktop), but can be any other distribution to use GRUB as boot loader and not LILO.

In way of summary, the steps to be followed are as follows:

1. Starting a distribution LiveCD
2. Mounting the partition where it is installed Ubuntu
3. Install the GRUB on that partition

The following explains, in a few easy steps, how to do it:

1. We started the computer and start from the CD
2. Boot Ubuntu (or distribution chosen) mode LiveCD
3. Open up a terminal or console (it is not necessary if we have a command line interface in text mode)
4. Create a folder where you mount the partition of Ubuntu (we can create / media, for example: / media / ubuntu /)
5. Mount partition where it is installed Ubuntu, using the mount command.
6. Here are two possible solutions:

Through the shell GRUB

Option 1

1. We execute the following commands:

$ sudo grub --> run the shell GRUB
> root (hdX,Y) --> indicate where it is located partition Ubuntu
> setup (hdX) --> install the GRUB on that partition
> quit --> exit the shell GRUB

Where X is the number of hard drives, and Y is the number of partition. This system differs somewhat used to mount the partitions in GNU / Linux; are a single decimal number and starts at 0, for example:

* Hd0: is the first full disk, like hda or sda
* Hd0, 0: is the first partition of the first hard drive, like hda1 or sda1
* Hd0, 1: is the second partition on the hard drive first, like hda2 or sda2
* Hd1, 2: is the third partition of the second hard drive, like hdb3 or sdb3

The first disk of GRUB is the first master hard drive, the second is the first hard drive slave, the third is the second hard disk master, and so on.

Option 2

1. From a console execute the following commands:

$ sudo grub --> run the command interpreter grub
> find /boot/grub/stage1 --> looking where this partition of ubuntu
> root (hdX,Y) --> put the value returned earlier
> setup (hd0) --> install grub in our first drive (hd0). That is where the computer starts
> quit --> leave the command interpreter grub

Changing the origin of the root folder

1. We changed the origin of the root folder to the directory in which we mounted the partition of Ubuntu, for GRUB interpreted that the root system is there. The command for this is necessary:

$ sudo chroot /home/ubuntu/

2. Now install the GRUB in the MBR on the first drive, that is normally configured as Primary Master (hda):

$ sudo grub-install /dev/hda

Iptables Ubuntu Linux: configuracion basica

Aquí tenemos una forma simple de instalar un firewall en Ubuntu linux. Lo que aquí se explica es una configuración básica de iptables que puede ser modificada a gusto de cada usuario.

Instalar y configurar iptables en Ubuntu

Primero verifica si tienes iptables instalado. Si no esta instalado abrir un terminal y ejecutar:

sudo apt-get install iptables

Después usando el editor (nano, pico, vi, gedit etc.) hacemos un script y lo ponemos en “/opt/scripts”. Al script lo llamamos “iptables.script”. Desde línea de comandos ejecutamos:

sudo gedit /opt/scripts/iptables.script

El código que tendra el script que creamos sera:

#!/bin/bash
# descarga todos los enlaces

iptables -F

# prepara las reglas de cada enlace pre-definido

iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP

# permite coneccion establecidas por paquetes que vienen de otras computadoras

iptables -A INPUT -m state –state RELATED,ESTABLISHED -j ACCEPT

# no permite que nada mas entre

iptables -A INPUT -i eth+ -p udp -j DROP
iptables -A INPUT -i eth+ -p tcp -m tcp –syn -j DROP

# acepta todo de localhost

iptables -A INPUT -i lo -j ACCEPT

Después que este guardado activamos el iptables y sabremos si esta funcionando. Desde linea de comandos de linux ejecutamos:

sudo iptables -L -V

Después creamos otro pequeño script para poder activarlo en “/etc/init.d/firewall”. Desde linea de comandos de linux ejecutamos:

sudo gedit /etc/init.d/firewall

Dentro de este archivo ponemos el siguiente codigo:

#!/bin/bash

if [[ $1 == start ]] ; then
sudo /opt/scripts/iptables.script
else
sudo iptables -F
fi

Por ultimo lo sincronizas con /etc/rc.* usando las herramientas de “update-rc.d” para que el firewall se active antes que el network:

update-rc.d firewall start 20 2 3 4 5 . stop 99 0 1 6

Y asi tenemos un firewall simple para que nuestro sistema operativo Linux Ubuntu este mas segura (no es recomendable para los servidores ya que no dejara que ningún paquete entre).


Tambien puede leer:

Ubuntu Security: Basic iptables configuration

Here is a simple way to install a firewall. What is explained here is a basic configuration that can be modified to taste each user.
First check if you have iptables installed. If not installed open a terminal and run:

sudo apt-get install iptables

After using the editor (nano, pico, vi, gedit etc.) do a script and what we "/ opt / scripts." When the script call "iptables.script." From the command line run:

sudo gedit /opt/scripts/iptables.script

The code will have a script that will create:

#!/bin/bash
# Download all links

iptables -F

# Prepares the rules of each pre-defined link

iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP

# Allows connection established by packages that come from other computers

iptables -A INPUT -m state –state RELATED,ESTABLISHED -j ACCEPT

# Not allowed to do anything but between

iptables -A INPUT -i eth+ -p udp -j DROP
iptables -A INPUT -i eth+ -p tcp -m tcp –syn -j DROP

# All agree on localhost

iptables -A INPUT -i lo -j ACCEPT

After this saved activate iptables and we will know whether this function. From the command line run:

sudo iptables -L -V

Next, we create another small script to be able to turn it into "/ etc / init.d / firewall. From the command line run:

sudo gedit /etc/init.d/firewall

Within this file put the following code:

#!/bin/bash

if [[ $1 == start ]] ; then
sudo /opt/scripts/iptables.script
else
sudo iptables -F
fi

Finally you sync with / etc / rc .* using the tools of "update-rc.d" so that the firewall is activated before the network:

update-rc.d firewall start 20 2 3 4 5 . stop 99 0 1 6

And so we have a single firewall for our computer this more secure (it is not recommended for servers as not allowing any package between).

Descomprimir Archivos en Linux - Unp


Un
p es un pequeño script escrito en Perl que permite descomprimir los tipos de archivo comprimido más populares (tar.gz, tar.bz2, rmp, deb, zip, rar…) desde la linea de comandos.
Para instalar unp debemos ejecutar:
  • sudo aptitude install unp
Para descomprimir un archivo, ejecutamos:
  • unp nombre_archivo
Si lo ejecutamos con:
  • sudo unp nombre_archivo
descomprimimos el archivo con permisos para root unicamente.




posicionamiento en google

Decompress Archives at Ubuntu - Unp


Unp
is a small script written in Perl that allows decompress compressed file types most popular (tar.gz, tar.bz2, rmp, deb, zip, rar…) from the command line.
To install unp we execute:

* Sudo aptitude install unp

To decompress a file, run:

* Unp filename

If you run with:

* Sudo unp filename

unpack the file permissions to root only.

Almacenar datos binarios en base de datos MySQL desde PHP

Un tema interesante en Mysql es usar la base de datos para guardar, además de datos de tipo texto, datos binarios como por ejemplo código html o imágenes.

Almacenamiento de datos binarios (imagenes, codigo, etc.) en la base de datos MySQL con programación PHP



El primer paso es crear la base de datos:

CREATE TABLE binary_data (

id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY,

descripction CHAR(50),

bin_data LONGBLOB,

filename CHAR(50),

filesize CHAR(50),

filetype CHAR(50)

);


Almacenar datos binarios en base de datos Mysql



El siguiente script puede usarse para insertar objetos binarios en la base de datos desde un browser. Notar que se usa el tag input type=”file” de un form html para subir un archivo.

<HTML>

<HEAD><TITLE>Almacenamiento de datos binarios en una base

de datos MySql</TITLE></HEAD>

<BODY>

<?php

if ($submit) {

//codigo que se ejecuta si se presiono el botón submit

MYSQL_CONNECT( "localhost", "root", "contraseña");

mysql_select_db( "binary_data");

$data = addslashes(fread(fopen($form_data, "r"),

filesize($form_data)));

$result=MYSQL_QUERY( "INSERT INTO binary_data(description,

bin_data,filename,filesize,filetype) ". "VALUES

('$form_description','$data','$form_data_name',

'$form_data_size','$form_data_type')");

$id= mysql_insert_id();

print "<p>Database ID: <b>$id</b>";

MYSQL_CLOSE();

} else {

// sino mostrar el formulario para nuevos datos:

?>

<form method="post" action=" <?php echo $PHP_SELF; ?>"

enctype="multipart/form-data">

File Description:<br>

<input type="text" name="form_description" size="40">

<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="1000000">

<br>Cargar archivo en base de datos:<br>

<input type="file" name="form_data" size="40">

<p><input type="submit" name="submit" value="submit">

</form>

<?php

}

?>

</BODY>

</HTML>

Notar el uso de la variable predefinida $PHP_SELF que tiene el nombre del script de esta forma el formulario se llama a si mismo independientemente del nombre que se le ponga al archivo.

Recuperar datos binarios de base de datos Mysql



El siguiente script (getdata.php) puede usarse para recuperar los datos de la base de datos, notar que el script espera recibir la variable $id con el id del registro a recuperar de la tabla.

<?php

if($id) {

@MYSQL_CONNECT( "localhost", "root", "contraseña");

@mysql_select_db( "binary_data");

$query = "select bin_data,filetype from binary_data where id=$id";

$result = @MYSQL_QUERY($query);

$data = @MYSQL_RESULT($result,0, "bin_data");

$type = @MYSQL_RESULT($result,0, "filetype");

Header( "Content-type: $type");

echo $data;

};

?>

Imagenes en base de datos Mysql



Para usar una imagen que se obtiene de la base de datos se puede usar:

<img src="getdata.php?id=3">

Notar como se le pasa la variable id al script para saber cual es el registro a recuperar de la base de datos.

Como vemos, mediante programación Php podemos almacenar datos binarios en una base de datos Mysql y luego recuperarlos mediante una consulta para ser utilizadas en nuestro código Php.

Store and saving binary data (images, coding, etc.) into MySql Database with PHP

An interesting topic in Mysql is to use the database to store binary data, such as images or html code. The first step is to create the database:

CREATE TABLE binary_data (
id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY,
descripction CHAR(50),
bin_data LONGBLOB,
filename CHAR(50),
filesize CHAR(50),
filetype CHAR(50)
);


The following script can be used to insert binary objects in the database from a browser. Note that the tag is used input type = "file" a form html to upload a file.


<HTML>
<HEAD><TITLE>Store and saving binary data (images, coding,
etc.) into MySql Database with PHP
</TITLE></HEAD>
<BODY>
<?php
if ($submit) {
//
Code that runs if I press the submit button
MYSQL_CONNECT( "localhost", "root", "password");
mysql_select_db( "binary_data");
$data = addslashes(fread(fopen($form_data, "r"),
filesize($form_data)));
$result=MYSQL_QUERY( "INSERT INTO binary_data(description,
bin_data,filename,filesize,filetype) ". "VALUES
('$form_description','$data',
'$form_data_name',
'$form_data_size','$form_data_type')");
$id= mysql_insert_id();
print "<p>Database ID: <b>$id</b>";
MYSQL_CLOSE();
} else {
// else
bring up the form for new data:
?>
<form method="post" action=" <?php echo $PHP_SELF; ?>"
enctype="multipart/form-data">
File Description:<br>
<input type="text" name="form_description" size="40">
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="1000000">
<br>
Upload file to the database:<br>
<input type="file" name="form_data" size="40">
<p><input type="submit" name="submit" value="submit">
</form>
<?php
}
?>
</BODY>
</HTML>

Note the use of $ PHP_SELF predefined variable that contains the name of the script. This form is called himself regardless of the name that comes to the file.

The following script (getdata.php) can be used to recover data from the database, noting that the script expects to receive the variable $ id with id register to recover from the table.

<?php
if($id) {
@MYSQL_CONNECT( "localhost", "root", "contraseña");
@mysql_select_db( "binary_data");
$query = "select bin_data,filetype from binary_data where id=$id";
$result = @MYSQL_QUERY($query);
$data = @MYSQL_RESULT($result,0, "bin_data");
$type = @MYSQL_RESULT($result,0, "filetype");
Header( "Content-type: $type");
echo $data;
};
?>

To use an image that is obtained from the database can be used:


<img src="getdata.php?id=3">

Note as he passes the variable id to script to know what is the record to retrieve the base.