Продление срока аренды dhcp в centos 7. Как получить сетевые настройки по DHCP

В данной заметке я хочу рассмотреть простой и быстрый вариант настройки шлюза для организации доступа в интернет из локальной сети на базе CentOS 7. Не будет никакого дополнительного функционала, только самое необходимое для доступа к интернету компьютеров за шлюзом.

Данная статья является частью единого цикла статьей про сервер .

Введение

В нашем распоряжении будет следующий сервер для настройки шлюза:

# cat /etc/redhat-release CentOS Linux release 7.1.1503 (Core)

Предварительная настройка сервера

# yum -y update

После этого я устанавливаю mc, так как привык к нему и постоянно пользуюсь:

# mcedit /etc/sysconfig/selinux

Приводим строку с соответствующим параметром к следующему виду:

SELINUX=disabled

Чтобы применить изменения, перезагружаем сервер:

# reboot # yum -y install epel-release

Устанавливаем iftop на CentOS 7:

# yum -y install iftop

Теперь мы можем смотреть загрузку сети на шлюзе в режиме реального времени. Чтобы увидеть сетевую активность, достаточно запустить iftop:

По-умолчанию она слушает интерфейс eth0. Это внешний интерфейс шлюза, на нем все подключения будут отображены от имени самого шлюза и определить, кто же в сети занимает канал мы не сможем. Чтобы это увидеть, необходимо запустить просмотр сетевой активности на локальном интерфейсе. Сделать это не сложно, достаточно запустить iftop с параметром:

# iftop -i eth1 -P

В моем случае это пользователь с ip 192.168.10.98, на котором я запустил проверку скорости интернета с серверов Яндекса.

Если у вас не большая сеть и не много пользователей, то с помощью этой простой и эффективной утилиты вы сможете легко определить, кто, к примеру, качает торренты или чем-то еще загружает канал.

Заключение

С помощью бесплатного дистрибутива Linux мы смогли за считанные минуты настроить шлюз для организации доступа в интернет компьютеров из локальной сети. У меня ушло минут 10 на настройку шлюза по этой инструкции. Если вы делаете это первый раз, то конечно у вас уйдет гораздо больше времени. Нужно будет разобраться в нюансах, к тому же я дал много ссылок на дополнительный материал.

Давайте разберемся в том, что мы сделали:

  1. Выполнили предварительную настройку сервера, подготовили его к работе.
  2. Включили маршрутизацию.
  3. Настроили firewall.
  4. Включили NAT.
  5. Установили и настроили dnsmasq для организации служб dns и dhcp.
  6. Проанализировали сетевую активность шлюза, узнали кто загружает канал интернета.

Это минимально необходимый функционал для организации работы шлюза на CentOS 7. Следующим этапом может быть настройка прокси сервера, шейпера траффика, настройка 2-х и более провайдеров и много другое. Что-то из этого я рассмотрю в своих будущих статьях.

Напоминаю, что данная статья является частью единого цикла статьей про сервер .

Онлайн курс по Linux

Если у вас есть желание научиться строить и поддерживать высокодоступные и надежные системы, рекомендую познакомиться с онлайн-курсом «Администратор Linux» в OTUS. Курс не для новичков, для поступления нужны базовые знания по сетям и установке Linux на виртуалку. Обучение длится 5 месяцев, после чего успешные выпускники курса смогут пройти собеседования у партнеров. Что даст вам этот курс:
  • Знание архитектуры Linux.
  • Освоение современных методов и инструментов анализа и обработки данных.
  • Умение подбирать конфигурацию под необходимые задачи, управлять процессами и обеспечивать безопасность системы.
  • Владение основными рабочими инструментами системного администратора.
  • Понимание особенностей развертывания, настройки и обслуживания сетей, построенных на базе Linux.
  • Способность быстро решать возникающие проблемы и обеспечивать стабильную и бесперебойную работу системы.
Проверьте себя на вступительном тесте и смотрите подробнее программу по.

Dynamic Host Configuration Protocol is a network protocol used to dynamically distribute network configuration parameters, such as IP addresses, gateway, and DNS for network interfaces. DHCP Server assigns IP addresses automatically to all systems, so system admin need not assign IP addresses manually to client machines in the network. DHCP is the best option for bigger environments, holds thousands of systems.

Environment

Make sure to have only one DHCP server in your environment. If you have a router/switch which provides the functionality of DHCP, then you need to disable it.

  1. CentOS 7 64bit Minimal server (DHCP Server) OR Ubuntu 18.04 /16.04 / Debian 9 64bit (DHCP Server)
  2. CentOS 7 64bit Minimal server (DHCP Client) OR Ubuntu 18.04 / 16.04 Desktop (DHCP Client)

Note: You must a assign a static IP address to your DHCP server.

Install and configure DHCP server on CentOS 7

First, let us see how to install and configure DHCP server on CentOS 7 64bit. The should also work on CentOS 6.x and other older versions.

# yum install dhcp

Once the packages are installed, copy the sample configuration file to /etc/dhcp directory.

# cp /usr/share/doc/dhcp-4.2.5/dhcpd.conf.example /etc/dhcp/dhcpd.conf

Now, edit dhcpd.conf file.

# vi /etc/dhcp/dhcpd.conf

[...] # Specify Domain Name # Default Gateway

192.168.12.110

# systemctl restart dhcpd # systemctl enable dhcpd

If you face any issues in restarting the DHCP service, then consider updating the SELinux context or .

/sbin/restorecon -v /etc/dhcp/dhcpd.conf

That’s it. Now, skip to ‘ ’ section and configure your clients to get IP addresses automatically from the DHCP server.

Install and configure DHCP server on Ubuntu 18.04 / 16.04 / Debian 9

First, let us see how to install and configure DHCP server on Ubuntu 14.04. The should also work on Ubuntu 15.04 / 14.10 / 13.04 / 13.10 and other older versions.

Install DHCP server and client using the below command.

$ sudo apt-get install isc-dhcp-server

Once the packages are installed, we have to assign on what interfaces should the DHCP server (dhcpd ) serve DHCP requests. In our case, have only one Interface on my system (eth0 ), so we will assign eth0 .

Edit file /etc/default/isc-dhcp-server .

$ sudo nano /etc/default/isc-dhcp-server

Mention eth0 in the file.

# Separate multiple interfaces with spaces, e.g. "eth0 eth1". INTERFACES="eth0"

Now, edit dhcpd.conf file,

$ sudo nano /etc/dhcp/dhcpd.conf

Do the changes as shown below.

Define the subnet, range of IP addresses, domain and domain name servers as below:

[...] # Configuring subnet and iprange subnet 192.168.12.0 netmask 255.255.255.0 { range 192.168.12.100 192.168.12.200; # Specify DNS server ip and additional DNS server ip option domain-name-servers 8.8.8.8, 8.8.4.4; # Specify Domain Name option domain-name "itzgeek.local"; # Default Gateway option routers 192.168.12.2; option broadcast-address 192.168.12.255; # Specify Default and Max lease time default-lease-time 600; max-lease-time 7200; } [...]

If you want to assign a fixed IP address to your client, you have to enter it’s MAC id and the IP address in the following stanza. For example, to assign a fixed IP address 192.168.12.110 to the client, stanza will look like below.

[...] host mywindows-client { hardware ethernet 00:0C:29:05:A7:CB; fixed-address 192.168.12.110; } [...]

Now, start the dhcpd service and make it start automatically on system reboot.

# sudo service isc-dhcp-server restart

Configure DHCP Clients

Now, you need to configure client machines to get IP address automatically from DHCP server. You can go through below articles.

) is a network protocol used for assigning IP address to network clients dynamically from a predefined IP pool. It is useful for LAN network, but not generally used for production servers. This article will help you for Configuring DHCP Server on CentOS, Red Hat System. Read more about dhcp .

Install DHCP Package

First install DHCP packages using yum package manager on CentOS, Red Hat systems. DHCP rpms are available under base repositories, so we don’t need to add an extra repository.

Yum install dhcp

Update /etc/sysconfig/dhcpd File

Firstly we need to set ethernet interface name as DHCPDARGS in /etc/sysconfig/dhcpd file. Edit this configuration file and update the ethernet name.

DHCPDARGS=eth1

Configure DHCP Server

DHCP creates an empty configuration file /etc/dhcp/dhcpd.conf . Also it provides a sample configuration file at /usr/share/doc/dhcp*/dhcpd.conf.sample , which is very useful for configuring the DHCP server.

So as a first part, copy the content of sample configuration file to the main configuration file. Sample configuration file may be changed as perversion you have installed on your system.

# cp /usr/share/doc/dhcp-4.1.1/dhcpd.conf.sample /etc/dhcp/dhcpd.conf

3.1 – Parameter Configuration

First configure the basic options which is common to all supported networks.

Сайт, ns2.сайт; default-lease-time 600; max-lease-time 7200; authoritative; log-facility local7;

3.2 – IP Subnet Declaration

First, edit DHCP configuration file and update subnet details as per your network. For this example we are configuring DHCP for 192.168.1.0/24 LAN network.

Subnet 192.168.1.0 netmask 255.255.255.0 { option routers 192.168.1.254; option subnet-mask 255.255.255..168.1.1; option time-offset -18000; # Eastern Standard Time range 192.168.1.10 192.168.1.100; }

3.3 -Assign Static IP Address to Host

In some cases, we need to assign a fixed IP to an interface each time it requested from dhcp. We can also assign a fixed IP on basis of MAC address (hardware ethernet) of that interface. Setup host-name is optional to set up.

Host station1 { option host-name "station1.example.com"; hardware ethernet 00:11:1A:2B:3C:AB; fixed-address 192.168.1.100; }

Start DHCP Service

After making all above changes, let’s start dhcp service using following commands as per your operating system version.

For CentOS/RHEL 7 systemctl start dhcp For CentOS/RHEL 6/5 service dhcp start

Similarly to stop and restart dhcp service use following commands.

For CentOS/RHEL 7 systemctl stop dhcp ystemctl restart dhcp For CentOS/RHEL 6/5 service dhcp stop service dhcp restart

Step 5: Setup Client System

At this stage we have a running dhcp server which is ready for accepting requests and assign them a proper ip. but to verify I have another CentOS machine running on same LAN. Now login to that client machine and edit Ethernet configuration file.

Vim /etc/sysconfig/network-scripts/ifcfg-eth1 DEVICE=eth1 BOOTPROTO=dhcp TYPE=Ethernet ONBOOT=yes

Make sure BOOTPROTO is set to dhcp .

Let’s restart network services on the client machine. You will get that dhcp server assigned an ip address from the defined subnet. If you have connected to client pc from remote login, Your session can be disconnected.

For CentOS/RHEL 7 systemctl restart network For CentOS/RHEL 6/5 service network restart