proyecto de mayo inicial 5 añitos aprender es bueno para tu niño
21 protocolo de configuración dinámica de hosts dhcp
1. 315
Protocolo de Configuración Dinámica
de Hosts (DHCP)
Dynamic Host Configuration Protocol (DHCP) is a network protocol that automatically assigns TCP/ IP
information to client machines. Each DHCP client connects to the centrally located DHCP server, which
returns that client's network configuration (including the IP address, gateway, and DNS servers).
21.1. Motivos para usar el protocolo DHCP
DHCP es útil para proporcionar de un modo rápido la configuración de la interfaz de red del cliente. Al
configurar el sistema cliente, el administrador puede seleccionar el protocolo DHCP y no especificar
una dirección IP, una máscara de red, una puerta de enlace o servidores DNS. El cliente recupera
esta información desde el servidor DHCP. DHCP también es útil si un administradordesea cambiar
las direcciones IP de muchos sistemas. En lugar de volver a configurar todos los sistemas, puede
modificar un archivo de configuración DHCP en el servidor para establecer el nuevo conjunto de
direcciones IP. Si los servidores DNS de una organización cambian, los cambios son hechos en el
servidor DHCP, no en los clientes DHCP. Una vez que se reinicie la red en los clientes (o se reinicien
los clientes), se aplicarán los cambios.
Si una organización tiene un servidor DHCP funcional conectado correctamente a una red, los
usuarios de portátiles pueden mover estas máquinas de oficina a oficina.
21.2. Configuración de un servidor DHCP
The dhcp package contains an ISC DHCP server. First, install the package as the superuser:
~]# yum install dhcp
Installing the dhcp package creates a file, /etc/dhcpd.conf, which is merely an empty
configuration file:
~]# cat /etc/dhcpd.conf
#
# DHCP Server Configuration file.
# see /usr/share/doc/dhcp*/dhcpd.conf.sample
The sample configuration file can be found at /usr/share/doc/dhcp-<version>/
dhcpd.conf.sample. You should use this file to help you configure /etc/dhcpd.conf, which is
explained in detail below.
DHCP also uses the file /var/lib/dhcpd/dhcpd.leases to store the client lease database. Refer
to Sección 21.2.2, “Base de datos de arrendamiento” for more information.
21.2.1. Archivo de configuración
The first step in configuring a DHCP server is to create the configuration file that stores the network
information for the clients. Use this file to declare options and global options for client systems.
El archivo de configuración puede contener tabulaciones o líneas en blanco adicionales para
facilitar el formato. Las palabras clave no distinguen entre mayúsculas y minúsculas. Las líneas que
empiezan con una almohadilla o símbolo numeral (#) se consideran comentarios.
2. 316
Archivo de configuración
Hay dos tipos de esquemas de actualización DNS implementados actualmente — el modo de
actualización DNS ad-hoc y el modo de actualización intermedio de boceto de interacción DHCP-
DNS. Si y cuando estos dos son aceptados como parte del proceso estándar de IETF, habrá un tercer
modo — el método estándar de actualización DNS. El servidor DHCP tiene que estar configurado
para usar uno de estos dos esquemas actuales. La versión 3.0b2pl11 y las versiones anteriores
usaban el modo ad-hoc, el cual no es utilizado en la actualidad. Si quiere conservar el mismo
comportamiento, añada la siguiente línea al inicio del archivo de configuración:
ddns-update-style ad-hoc;
Para usar el modo recomendado, añada la siguiente línea al inicio del archivo de configuración:
ddns-update-style interim;
Lea la página man de dhcpd.conf para más detalles sobre los diferentes modos.
El archivo de configuración posee dos tipos de información:
• Parámetros — establece cómo se realiza una tarea, si ésta se debe llevar a cabo o las opciones de
configuración de red que se enviarán al cliente.
• Declaraciones — describen la topología de la red, describen los clientes, proporcionan direcciones
para los clientes o aplican un grupo de parámetros a un grupo de declaraciones.
Los parámetros que inician con la palabra clave option son conocidos como opciones. Estas
opciones controlanlas opciones de DHCP mientras que los parámetros configuran valores que no son
opcionales o que controlan el comportamiento del servidor DHCP.
Los parámetros (incluidas las opciones) declarados antes de una sección encerrada entre paréntesis
({ }) se consideran parámetros globales. Los parámetros globales se aplican a todas las secciones
situadas debajo de ellos.
Importante
Si cambia el archivo de configuración, los cambios no se aplicarán hasta reiniciar el
demonio DHCP con el comando service dhcpd restart.
Tip
En vez de cambiar un archivo de configuración DHCP y reiniciar el equipo cada vez,
el comando omshell proporciona una manera interactiva de conectarse, preguntar
y cambiar la configuración de un servidor DHCP. Al utilizar omshell, todos los
cambios pueden realizarse mientras el servidor está en ejecución. Para obtener
mayor información sobre omshell, consulte la página man omshell.
In Ejemplo 21.1, “Ejemplo de declaración de Subred”, the routers, subnet-mask, domain-name,
domain-name-servers, and time-offset options are used for any host statements declared
below it.
Adicionalmente, se puede declarar una subnet. Debe incluir una declaración subnet para cada
subred en la red. Si no lo hace, el servidor DHCP no podrá ser iniciado.
3. 317
Archivo de configuración
En este ejemplo, hay opciones globales para cada cliente DHCP en la subred y un range declarado.
A los clientes se les asigna una dirección IP dentro del range.
subnet 192.168.1.0 netmask 255.255.255.0 {
option routers 192.168.1.254;
option subnet-mask 255.255.255.0;
option domain-name "example.com";
option domain-name-servers 192.168.1.1;
option time-offset -18000; # Eastern Standard Time
range 192.168.1.10 192.168.1.100;
}
Ejemplo 21.1. Ejemplo de declaración de Subred
All subnets that share the same physical network should be declared within a shared-network
declaration as shown in Ejemplo 21.2, “Ejemplo de declaración de red compartida”. Parameters within
the shared-network, but outside the enclosed subnet declarations, are considered to be global
parameters. The name of the shared-network must be a descriptive title for the network, such as
using the title 'test-lab' to describe all the subnets in a test lab environment.
shared-network name {
option domain-name "test.redhat.com";
option domain-name-servers ns1.redhat.com, ns2.redhat.com;
option routers 192.168.0.254;
more parameters for EXAMPLE shared-network
subnet 192.168.1.0 netmask 255.255.252.0 {
parameters for subnet
range 192.168.1.1 192.168.1.254;
}
subnet 192.168.2.0 netmask 255.255.252.0 {
parameters for subnet
range 192.168.2.1 192.168.2.254;
}
}
Ejemplo 21.2. Ejemplo de declaración de red compartida
As demonstrated in Ejemplo 21.3, “Declaración de Group”, the group declaration is used to apply
global parameters to a group of declarations. For example, shared networks,subnets, and hosts can
be grouped.
group {
option routers 192.168.1.254;
option subnet-mask 255.255.255.0;
option domain-name "example.com";
option domain-name-servers 192.168.1.1;
option time-offset -18000; # Eastern Standard Time
host apex {
option host-name "apex.example.com";
hardware ethernet 00:A0:78:8E:9E:AA;
fixed-address 192.168.1.4;
}
4. 318
Archivo de configuración
host raleigh {
option host-name "raleigh.example.com";
hardware ethernet 00:A1:DD:74:C3:F2;
fixed-address 192.168.1.6;
}
}
Ejemplo 21.3. Declaración de Group
To configure a DHCP server that leases a dynamic IP address to a system within a subnet, modify
Ejemplo 21.4, “Parámetro Range (Rango)” with your values. It declares a default lease time, maximum
lease time, and network configuration values for the clients. This example assigns IP addresses in the
range 192.168.1.10 and 192.168.1.100 to client systems.
default-lease-time 600;
max-lease-time 7200;
option subnet-mask 255.255.255.0;
option broadcast-address 192.168.1.255;
option routers 192.168.1.254;
option domain-name-servers 192.168.1.1, 192.168.1.2;
option domain-name "example.com";
subnet 192.168.1.0 netmask 255.255.255.0 {
range 192.168.1.10 192.168.1.100;
}
Ejemplo 21.4. Parámetro Range (Rango)
To assign an IP address to a client based on the MAC address of the network interface card, use the
hardware ethernet parameter within a host declaration. As demonstrated in Ejemplo 21.5,
“Ejemplo de dirección IP estática con DHCP”, the host apex declaration specifies that the network
interface card with the MAC address 00:A0:78:8E:9E:AA always receives the IP address 192.168.1.4.
Tenga en cuenta que también puede usar el parámetro opcional host-name para asignar un nombre
host al cliente.
host apex {
option host-name "apex.example.com";
hardware ethernet 00:A0:78:8E:9E:AA;
fixed-address 192.168.1.4;
}
Ejemplo 21.5. Ejemplo de dirección IP estática con DHCP
Tip
The sample configuration file provided can be used as a starting point and custom
configuration options can be added to it. To copy it to the proper location, use the
following command:
cp /usr/share/doc/dhcp-<version-number>/dhcpd.conf.sample /etc/dhcpd.conf
(where <version-number> is the DHCP version number).
5. 319
Base de datos de arrendamiento
Para obtener una lista completa de sentencias de opciones e información relacionada, consulte la
página del manual de dhcp-options.
21.2.2. Base de datos de arrendamiento
En el servidor DHCP, el archivo /var/lib/dhcp/dhcpd.leases almacena la base de datos de
arrendamiento del cliente DHCP. Este archivo no debe modificarse manualmente. La información
sobre arrendamientode DHCP de cada dirección IP asignada recientemente se almacena de
modo automático en la base de datos de arrendamiento. La información incluye la longitud del
arrendamiento, a quién se ha asignado la dirección IP, las fechas iniciales y finales de la renta y la
dirección MAC de la tarjeta de interfaz de red utilizada para recuperar el arrendamiento.
Todas las horas de la base de datos de arrendamiento se expresan según el Tiempo Universal
Coordinado (UTC por sus siglas en inglés), no con la hora local.
Cada cierto tiempo, la base de datos de arrendamiento es nuevamente creada para controlar su
tamaño. En primer lugar, se guardan todas las concesiones conocidas en una base de datos de renta
temporal. El archivo dhcpd.leases es renombrado a dhcpd.leases~ y la base de datos temporal
se registra en dhcpd.leases.
El demonio DHCP podría ser terminado o el sistema puede fallar después de que la base de datos ha
sido renombrada al archivo de copia de seguridad pero antes de que el nuevo archivo haya sido
escrito. Si ocurre esto, el archivo dhcpd.leases no existirá a pesar de ser requerido para arrancar
el servicio. No cree un nuevo archivo de arrendamiento si esto ocurre. Si lo hace, se perderán las
versiones anteriores del arrendamiento y podrían generarse muchos problemas. La solución correcta
consiste en cambiar el nombre del archivo de copia de seguridad dhcpd.leases~ de nuevo a
dhcpd.leases y, a continuación, arrancar el demonio.
21.2.3. Iniciar y detener el servidor
Importante
Cuando el servidor DHCP arranca por primera vez, fallará si no existe un archivo
dhcpd.leases. Use el comando touch /var/lib/dhcp/dhcpd.leases para
crear el archivo en caso de que no exista.
Si el mismo servidor está utilizando BIND con servidor DNS, este paso no será
necesario, ya que al iniciar el servicio named se revisa automáticamente la existencia
del archivo dhcpd.leases.
Para arrancar el servicio DHCP, use el comando /sbin/service dhcpd start. Para detener el
servidor DHCP, use el comando /sbin/service dhcpd stop.
Si tiene más de una interfaz de red conectada al sistema, pero sólo desea que el servidor DHCP
arranque en una de las interfaces, puede configurar el servidor DHCP para que sólo arranque en ese
dispositivo. En /etc/sysconfig/dhcpd, agregue el nombre de la interfaz a la lista de DHCPDARGS:
# Command line options here
DHCPDARGS=eth0
6. 320
Base de datos de arrendamiento
Esto es útil si tiene una máquina cortafuegos con dos tarjetas de red. Se puede configurar una tarjeta
de red como cliente DHCP para recuperar una dirección IP en Internet y la otra tarjeta de red puede
utilizarse como servidor DHCP para la red interna detrás del cortafuegos. Su sistema será más
seguro si sólo especifica la tarjeta de red conectada a la red interna ya que los usuarios no pueden
conectarse al demonio vía Internet.
Otras opciones de línea de comandos que pueden ser especificadas en /etc/sysconfig/dhcpd
incluyen:
• -p <portnum> — Specifies the UDP port number on which dhcpd should listen. The default is
port 67. The DHCP server transmits responses to the DHCP clients at a port number one greater
than the UDP port specified. For example, if the default port 67 is used, the server listens on port 67
for requests and responses to the client on port 68. If a port is specified here and the DHCP relay
agent is used, the same port on which the DHCP relay agent should listen must be specified. Refer
to Sección 21.2.4, “Agente de transmisión DHCP” for details.
• -f — Ejecuta el demonio como un proceso en primer plano. Casi siempre se usa para la
depuración.
• -d — Registra el demonio del servidor DCHP en el descriptor de errores estándar. Casi siempre se
usa para el depurado. Si no está especificado, el registro será escrito en /var/log/messages.
• -cf <filename> — Specifies the location of the configuration file. The default location is /etc/
dhcpd.conf.
• -lf <filename> — Specifies the location of the lease database file. If a lease database file
already exists, it is very important that the same file be used every time the DHCP server is started.
It is strongly recommended that this option only be used for debugging purposes on non-production
machines. The default location is /var/lib/dhcpd/dhcpd.leases.
• -q — No imprima el mensaje de copyright entero cuando inicie el demonio.
21.2.4. Agente de transmisión DHCP
El Agente de transmisión DHCP (dhcrelay) le permite transmitir las peticiones DHCP y BOOTP
desde una subred sin un servidor DHCP a uno o más servidores DHCP en otras subredes.
Cuando un cliente DHCP pide información, el agente de transmisión DHCP reenvía la petición a la
lista de servidores DHCP especificada cuando se inicia el agente de transmisión DHCP. Cuando un
servidor DHCP devuelve una respuesta, la respuesta puede ser broadcast o unicast en la red que ha
enviado la petición original.
El agente de transmisión escucha las peticiones DHCP en todas las interfaces a menos que las
interfaces estén especificadas en /etc/sysconfig/dhcrelay con la directiva INTERFACES.
Para iniciar el agente de transmisión DHCP, use el comando service dhcrelay start.
21.3. Configuración de un cliente DHCP
Para configurar un cliente DHCP manualmente, debe modificar el archivo /etc/sysconfig/
network para habilitar redes y el uso del archivo de configuración para cada dispositivo de red en el
directorio /etc/sysconfig/network-scripts. En este directorio, cada dispositivo debería tener
un archivo de configuración llamado ifcfg-eth0 donde eth0 es el nombre del dispositivo de red.
El archivo /etc/sysconfig/network debería contener la línea siguiente:
7. 321
Configuring a Multihomed DHCP Server
NETWORKING=yes
Si quiere que se inicie la red en el momento de arranque debe asegurarse de que la variable
NETWORKING sea yes.
El archivo /etc/sysconfig/network-scripts/ifcfg-eth0 debería contener las líneas
siguientes:
DEVICE=eth0
BOOTPROTO=dhcp
ONBOOT=yes
Necesita un archivo de configuración para cada dispositivo que desee configurar para el uso de
DHCP.
Otras opciones para el script de la red incluyen:
• DHCP_HOSTNAME — Utilice esta opción solamente si el servidor DHCP requiere que el cliente
especifique un nombre de host antes de recibir una dirección IP. (El demonio del servidor DHCP en
Red Hat Enterprise Linux no soporta esta característica.)
• PEERDNS=<answer> , where <answer> is one of the following:
• yes — Modifica /etc/resolv.conf con información desde el servidor. Si se está usando
DHCP, entonces yes es el valor por defecto.
• no — No modifica /etc/resolv.conf.
• SRCADDR=<address> , where <address> is the specified source IP address for outgoing
packets.
• USERCTL=<answer> , where <answer> is one of the following:
• yes — Los usuarios que no sean root pueden modificar este dispositivo.
• no — Los usuarios no root no tienen derecho a controlar este dispositivo.
If you prefer using a graphical interface, refer to Capítulo 15, Configuración de la red for instructions
on using the Network Administration Tool to configure a network interface to use DHCP.
Tip
Para configurar opciones avanzadas de clientes DHCP tal como tiempo del
protocolo, requerimientos y peticiones de asignación, soporte dinámico DNS, aliases
y una amplia gama de valores para sobreescribir o añadir a la configuración del lado
del cliente, consulte dhclient y las páginas man de dhclient.conf
21.4. Configuring a Multihomed DHCP Server
A multihomed DHCP server serves multiple networks, that is, multiple subnets. The examples in these
sections detail how to configure a DHCP server to serve multiple networks, select which network
interfaces to listen on, and how to define network settings for systems that move networks.
8. 322
Configuring a Multihomed DHCP Server
Before making any changes, back up the existing /etc/sysconfig/dhcpd and /etc/dhcpd.conf
files.
The DHCP daemon listens on all network interfaces unless otherwise specified. Use the /etc/
sysconfig/dhcpd file to specify which network interfaces the DHCP daemon listens on. The
following /etc/sysconfig/dhcpd example specifies that the DHCP daemon listens on the eth0
and eth1 interfaces:
DHCPDARGS="eth0 eth1";
If a system has three network interfaces cards -- eth0, eth1, and eth2 -- and it is only desired that
the DHCP daemon listens on eth0, then only specify eth0 in /etc/sysconfig/dhcpd:
DHCPDARGS="eth0";
The following is a basic /etc/dhcpd.conf file, for a server that has two network interfaces, eth0
in a 10.0.0.0/24 network, and eth1 in a 172.16.0.0/24 network. Multiple subnet declarations allow
different settings to be defined for multiple networks:
ddns-update-style interim;
default-lease-time 600;
max-lease-time 7200;
subnet 10.0.0.0 netmask 255.255.255.0 {
option subnet-mask 255.255.255.0;
option routers 10.0.0.1;
range 10.0.0.5 10.0.0.15;
}
subnet 172.16.0.0 netmask 255.255.255.0 {
option subnet-mask 255.255.255.0;
option routers 172.16.0.1;
range 172.16.0.5 172.16.0.15;
}
subnet 10.0.0.0 netmask 255.255.255.0
A subnet declaration is required for every network your DHCP server is serving. Multiple subnets
require multiple subnet declarations. If the DHCP server does not have a network interface in a
range of a subnet declaration, the DHCP server does not serve that network.
If there is only one subnet declaration, and no network interfaces are in the range of that subnet,
the DHCP daemon fails to start, and an error such as the following is logged to /var/log/
messages:
dhcpd: No subnet declaration for eth0 (0.0.0.0).
dhcpd: ** Ignoring requests on eth0. If this is not what
dhcpd: you want, please write a subnet declaration
dhcpd: in your dhcpd.conf file for the network segment
dhcpd: to which interface eth1 is attached. **
dhcpd:
dhcpd:
9. 323
Host Configuration
dhcpd: Not configured to listen on any interfaces!
option subnet-mask 255.255.255.0;
The option subnet-maskoption defines a subnet mask, and overrides the netmask value in
the subnet declaration. In simple cases, the subnet and netmask values are the same.
option routers 10.0.0.1;
The option routers option defines the default gateway for the subnet. This is required for
systems to reach internal networks on a different subnet, as well as external networks.
range 10.0.0.5 10.0.0.15;
The range option specifies the pool of available IP addresses. Systems are assigned an address
from the range of specified IP addresses.
For further information, refer to the dhcpd.conf(5) man page.
Alias Interfaces
Alias interfaces are not supported by DHCP. If an alias interface is the only interface,
in the only subnet specified in /etc/dhcpd.conf, the DHCP daemon fails to start.
21.4.1. Host Configuration
Before making any changes, back up the existing /etc/sysconfig/dhcpd and /etc/dhcpd.conf
files.
Configuring a single system for multiple networks
The following /etc/dhcpd.conf example creates two subnets, and configures an IP address for the
same system, depending on which network it connects to:
ddns-update-style interim;
default-lease-time 600;
max-lease-time 7200;
subnet 10.0.0.0 netmask 255.255.255.0 {
option subnet-mask 255.255.255.0;
option routers 10.0.0.1;
range 10.0.0.5 10.0.0.15;
}
subnet 172.16.0.0 netmask 255.255.255.0 {
option subnet-mask 255.255.255.0;
option routers 172.16.0.1;
range 172.16.0.5 172.16.0.15;
}
host example0 {
hardware ethernet 00:1A:6B:6A:2E:0B;
fixed-address 10.0.0.20;
}
host example1 {
hardware ethernet 00:1A:6B:6A:2E:0B;
10. 324
Host Configuration
fixed-address 172.16.0.20;
}
host example0
The host declaration defines specific parameters for a single system, such as an IP address. To
configure specific parameters for multiple hosts, use multiple host declarations.
Most DHCP clients ignore the name in host declarations, and as such, this name can anything,
as long as it is unique to other host declarations. To configure the same system for multiple
networks, use a different name for each host declaration, otherwise the DHCP daemon fails
to start. Systems are identified by the hardware ethernet option, not the name in the host
declaration.
hardware ethernet 00:1A:6B:6A:2E:0B;
The hardware ethernet option identifies the system. To find this address, run the ifconfig
command on the desired system, and look for the HWaddr address.
fixed-address 10.0.0.20;
The fixed-address option assigns a valid IP address to the system specified by the hardware
ethernet option. This address must be outside the IP address pool specified with the range
option.
If option statements do not end with a semicolon, the DHCP daemon fails to start, and an error such
as the following is logged to /var/log/messages:
/etc/dhcpd.conf line 20: semicolon expected.
dhcpd: }
dhcpd: ^
dhcpd: /etc/dhcpd.conf line 38: unexpected end of file
dhcpd:
dhcpd: ^
dhcpd: Configuration file errors encountered -- exiting
Configuring systems with multiple network interfaces
The following host declarations configure a single system, that has multiple network interfaces, so
that each interface receives the same IP address. This configuration will not work if both network
interfaces are connected to the same network at the same time:
host interface0 {
hardware ethernet 00:1a:6b:6a:2e:0b;
fixed-address 10.0.0.18;
}
host interface1 {
hardware ethernet 00:1A:6B:6A:27:3A;
fixed-address 10.0.0.18;
}
For this example, interface0 is the first network interface, and interface1 is the second
interface. The different hardware ethernet options identify each interface.
If such a system connects to another network, add more host declarations, remembering to:
11. 325
Recursos adicionales
• assign a valid fixed-address for the network the host is connecting to.
• make the name in the host declaration unique.
When a name given in a host declaration is not unique, the DHCP daemon fails to start, and
an error such as the following is logged to /var/log/messages:
dhcpd: /etc/dhcpd.conf line 31: host interface0:
already exists dhcpd: }
dhcpd: ^
dhcpd: Configuration file errors encountered -- exiting
This error was caused by having multiple host interface0 declarations defined in /etc/
dhcpd.conf.
21.5. Recursos adicionales
Para obtener mayor información sobre otras opciones, consulte los recursos siguientes.
21.5.1. Documentación instalada
• La página del manual dhcpd — describe cómo funciona el demonio DHCP
• La página del manual dhcpd.conf — explica cómo configurar el archivo de configuración
de
DHCP; incluye algunos ejemplos.
• La página del manual dhcpd.leases — explica cómo configurar el archivo de
arrendamiento
DHCP; incluye también algunos ejemplos.
• La página del manual dhcp-options — explica la sintaxis para la declaración de opciones
DHCP
en dhcpd.conf; incluye ejemplos.
• La página del manual dhcrelay — explica el Agente de transmisión DHCP y sus
opciones de configuración.
• /usr/share/doc/dhcp-<version>/ — Contains sample files, README files, and
release notes for current versions of the DHCP service.