- ChapterВ 2В Configuring Network Addressing
- 2.1В About the Dynamic Host Configuration Protocol
- Настройка сети в Oracle Linux
- ChapterВ 1В Configuring the System’s Network
- 1.1В About Network Interface Names
- 1.2В About Network Configuration Files
- 1.2.1В About the /etc/hosts File
- 1.2.2В About the /etc/nsswitch.conf File
- 1.2.3В About the /etc/resolv.conf File
- 1.2.4В About the /etc/sysconfig/network File
- 1.3В About Network Interface Configuration Files
- 1.4В Network Configuration Tools
- 1.5В Configuring Network Interfaces
- How to Use the Network Connections Editor
- How to Use the Text Based User Interface
- How to Use the Command Line
- 1.6В Configuring Network Routing
ChapterВ 2В Configuring Network Addressing
This chapter describes how to configure a DHCP server, DHCP client, and Network Address Translation.
2.1В About the Dynamic Host Configuration Protocol
The Dynamic Host Configuration Protocol (DHCP) enables client systems to obtain network configuration information from a DHCP server each time that they connect to the network. The DHCP server is configured with a range of IP addresses and other network configuration parameters that clients need.
When you configure an Oracle Linux system as a DHCP client, the client daemon, dhclient , contacts the DHCP server to obtain the networking parameters. As DHCP is broadcast-based, the client must be on the same subnet as either a server or a relay agent. If a client cannot be on the same subnet as the server, a DHCP relay agent can be used to pass DHCP messages between subnets.
The server provides a lease for the IP address that it assigns to a client. The client can request specific terms for the lease, such as the duration. You can configure a DHCP server to limit the terms that it can grant for a lease. Provided that a client remains connected to the network, dhclient automatically renews the lease before it expires. You can configure the DHCP server to provide the same IP address to a client based on the MAC address of its network interface.
The advantages of using DHCP include:
centralized management of IP addresses
ease of adding new clients to a network
reuse of IP addresses reducing the total number of IP addresses that are required
simple reconfiguration of the IP address space on the DHCP server without needing to reconfigure each client
For more information about DHCP, see RFC 2131.
Источник
Настройка сети в Oracle Linux
В данном посте будет рассказано про базовую настройку сети в операционных сетях на базе ОС Linux. Будут рассмотрены следующие вопросы:
- Файлы, в которых прописываются сетевые настройки
- Настройка сети на примере – связь двух виртуальных машин
В Oracle Enterprise Linux есть несколько способов настройки сети. Она производится либо через пользовательские интерфейсы, которые записывают введенные значения в необходимые конфигурационные файлы либо изменения можно вносить напрямую в необходимые конфигурационные файлы. После внесения любых изменений в файл необходимо перезагрузить ОС, либо перезапустить сервис сети (см. ниже), либо отключить сетевой интерфейс, а затем снова включить его, чтобы изменения вступили в силу. В большинстве систем Linux для этой цели можно использовать команды ifdown интерфейс или ifup интерфейс (см. ниже). Все настройки и файлы, описанные ниже, актуальны для операционной системы Oracle Linux 7.
Файлы, в которых прописываются сетевые настройки
Для начала рассмотрим файл /etc/sysconfig/network. В нем описываются сетевые настройки, касающиеся сетевого имени хоста и шлюза по умолчанию. Сетевое имя хоста прописывается в HOSTNAME, шлюз по умолчанию – в GATEWAY. Редактирование всех сетевых файлов должно осуществляться с привилегированными полномочиями (root или sudo).
Другой важный файл – /etc/sysconfig/network-scripts/ifcfg-интерфейс. В нем прописываются сетевые настройки для адаптера интерфейс (например, ifcfg-enp0s3). В случае, если в системе используется несколько сетевых адаптеров, стоит ожидать дополнительные конфигурационные файлы, для каждого из адаптеров (enp0s4, где en – ethernet, p – номер шины, s – номер слота. Такая наименование действительно для PCI-устройств). Ниже приведен пример конфигурации адаптера ifcfg-enp0s3, использующим DHCP.
Далее пример конфигурации адаптера ifcfg-enp0s3 со статическим IP-адресом. Для того, чтобы настроить адаптер ifcfg-enp0s3 для работы со статическим IP-адресом, надо с помощью текстового редактора (например, nano или vi) изменить файл /etc/sysconfig/network-scripts/ifcfg-enp0s3. А именно, добавить строки с указанием нужного IP-адреса, маски подсети, шлюза и DNS (IPADDR, PREFIX, GATEWAY, DNS1). Также, необходимо изменить значение параметра BOOTPROTO с dhcp на none. Параметр BOOTPROTO отвечает за то, как интерфейс получит IP-адрес.
Файл /etc/hosts содержит информацию, помогающую при локальном преобразовании имен.
В файле /etc/resolv.conf находится расположение DNS сервера(ов) для преобразования имен.
После всех настроек, необходимо перезапустить интерфейс, чтобы изменения вступили в силу. Делаем это командами ifdown и ifup.
Альтернативный вариант – перезапуск сервиса сети, отвечающего за сеть:
Далее проверяем новые настройки сети командой ifconfig. Команда выведет на экран несколько интерфейсов, нас интересует только лишь наш enp0s3.
Настройка сети на примере – связь двух виртуальных машин
Далее, настроим сетевое соединение между двумя виртуальными машинами. Для этого необходимо проделать вышеописанные настройки сетевых интерфейсов на двух виртуальных машинах, распределив между ними IP-адреса и маски подсети так, чтобы они оказались в одной логической подсети.
После того, как адресация и интерфейсы машин в ОС настроены, перейдем к настройке непосредственного соединения виртуальных машин через интерфейс гипервизора – в нашем случае, используя настройки Virtual Box.
Как видно по скриншотам ниже, надо переключить тип соединения в режим “Сетевой мост”. Сделав это в настройках обеих машин, они получат возможность увидеть друг друга в сети.
Изменение типа подключения с NAT на Сетевой мост для первой машины.
Изменение типа подключения с NAT на Сетевой мост для второй машины.
Проверка сетевых настроек командой ifconfig.
Проверка связи командой ping. Обе машины видят друг друга в локальной сети.
Источник
ChapterВ 1В Configuring the System’s Network
Systems connect to the network through different network components, particularly network interface cards (NICs) and multiple configuration files. Network configuration files define how these interfaces function in the system, as well as how the interfaces interact with other devices and systems on the wider network.
This chapter describes how to configure a system’s network interfaces and network routing.
1.1В About Network Interface Names
Traditionally, early kernel versions assigned names to network interface devices by assigning a prefix, which is typically based on the device driver, and a number, such as eth0 . With the availability of different types of devices, this naming schema is no longer efficient. The names do not necessarily correspond to the chassis labels and the names themselves might be inconsistent across existing network interfaces. The inconsistency would affect embedded adapters on the system as well as add-in adapters. Consequently, server platforms with multiple network adapters could encounter problems managing these interfaces.
Oracle Linux implements a consistent naming scheme for all network interfaces through the udev device manager. The scheme offers the following advantages:
The names of the devices are predictable.
Device names persist across system reboots or after changes are made to the hardware.
Defective hardware can easily be identified and thus replaced.
The feature that implements consistent naming on devices is enabled in Oracle Linux 8 by default. Network interface names are based on information that is derived from the system BIOS; or, alternatively from a device’s firmware, system path, or MAC address.
Network interfaces are identified by a name that combines a prefix and a suffix. The prefix depends on the type of network interface:
Ethernet network interfaces: en
Wireless local area network (LAN) interfaces: wl
Wireless wide area network (WAN) interfaces: ww
The suffix contains any of the following information:
An on-board index number o n , and thus, eno0 .
A hot-plug slot index number s n , and thus, ens1 .
This naming schema can also include f function and d device-id that are added to the suffix.
The bus and slot number p bus s n , and thus. enp0s8 .
This naming schema can also include f function and d device-id that are added to the suffix.
The MAC address x MAC-addr , and thus, enx0217b08b .
Note that this naming format is not used by Oracle Linux by default. However, administrators can implement it as an option.
1.2В About Network Configuration Files
The following are additional network configuration files that you might need to configure on a system.
1.2.1В About the /etc/hosts File
The /etc/hosts file is a database that contains host names and their corresponding IP addresses. The system uses the file as one of the sources to perform name and address resolution. If the network uses DNS (Domain Name Service), then the file would contain at least IP address information of the loopback interface.
For more information, see the hosts(5) manual page.
1.2.2В About the /etc/nsswitch.conf File
The /etc/nsswitch.conf file configures how the system uses various databases and name resolution mechanisms. One significant parameter in the file is hosts , which refers to the sources for resolving names and addresses.
In the example, the system uses 3 sources for name and address resolution. files refers to the /etc/hosts file. dns and nis refer to servers. With this definition, the system resolves names and IP addresses by first querying files . If unsuccessful, the system then queries a DNS server and a finally NIS server.
Do not modify /etc/nsswitch.conf directly. To revise the file, do the following:
Enter the changes in /etc/authselect/user-nsswitch.conf .
Run authselect apply-changes .
For more information, see the nsswitch.conf(5) and the authselect(8) manual pages. See also Oracle В® Linux 8: Setting Up System Users and Authentication.
1.2.3В About the /etc/resolv.conf File
The /etc/resolv.conf file defines how the system uses DNS to resolve host names and IP addresses. This file contains a line specifying the search domains and up to three lines that specify the IP addresses of DNS server, for example:
If your system obtains its IP address from a DHCP server, the file would also contain information obtained from DHCP.
For more information, see the resolv.conf(5) manual page.
1.2.4В About the /etc/sysconfig/network File
The /etc/sysconfig/network file specifies additional information that is valid to all network interfaces on the system, as shown in the following example:
For more information, see /usr/share/doc/initscripts*/sysconfig.txt .
1.3В About Network Interface Configuration Files
Each physical and virtual network device on an Oracle Linux system has an associated configuration file named ifcfg- interface in the /etc/sysconfig/network-scripts directory, for example:
The following output might be displayed:
In this example, the configuration files for en0 and en1 are ifcfg-en0 and ifcfg-en1 , respectively. The system reads these configuration files at boot time to configure the network interfaces.
In Oracle Linux 8, network scripts are deprecated. Previous ifup and ifdown scripts have been modified to work through the NetworkManager utility.
For an interface en1 that uses the Dynamic Host Configuration Protocol (DHCP) to obtain its IP address, the corresponding ifcfg-en1 file might appear as follows:
If the interface is configured with a static IP address, the file would contain entries similar to the following:
The following selected configuration parameters are typically used in interface configuration files:
How the interface obtains its IP address. Its values can be dhcp for DHCP-assigned addresses or none for static addresses.
IPv4 broadcast address.
Whether this interface is the default route.
Name of the physical network interface device (or a PPP logical device).
IPv4 gateway address for the interface. As an interface can be associated with several combinations of IP address, network mask prefix length, and gateway address, these are numbered starting from 0.
Media access control (MAC) address of an Ethernet device.
IPv4 address of the interface.
Whether the device is disabled if IPv4 configuration fails.
IPv6 gateway address for the interface.
Whether the device is disabled if IPv6 configuration fails.
IPv6 address of the interface in CIDR notation, including the network mask prefix length.
Whether to enable IPv6 for the interface.
Specifies the name of the primary bonded interface, of which this interface is a backup.
Name of the interface as displayed in the Network Connections GUI.
IPV4 address of the network.
Whether the network interface device is controlled by the network management daemon, NetworkManager .
Whether the interface is activated at boot time.
Whether the /etc/resolv.conf file used for DNS resolution contains information obtained from the DHCP server.
Whether the information for the routing table entry that defines the default gateway for the interface is obtained from the DHCP server.
Length of the IPv4 network mask prefix for the interface.
Specifies that this interface is a backup of a bonded interface.
Whether users other than root can control the state of this interface.
Universally unique identifier for the network interface device.
1.4В Network Configuration Tools
Different tools are available to configure the network. All of them generally perform the same functions. You can select any tool or a combination of tools to manage the network.
Cockpit is a web-based configuration tool for managing network configuration, including network interfaces, bonds, teams, bridges, virtual VLANs and the firewall.
Networks Connection Editor is a graphical user interface (GUI) that is GNOME-based. The Networks Connection Editor is a subset of the GNOME settings application and is launched by using the nm-connection-editor command.
The GNOME settings application enables you to perform other system configurations, aside from networking. To access, select the network icon at the top right of the desktop, then select Settings. Alternatively, you can click Activities, select Show Applications, and then select Settings.
NetworkManager is a text-based user interface (TUI) that is launched with the nmtui command. While it performs the same functions as the other tools, you navigate the TUI by using the keyboard rather than the mouse device.
NetworkManager command line, which consists of the nmcli command and its options. Other commands such as ip and ethtool complement nmcli in configuring and managing networks.
For more information, see the nmcli(1) , ip(8) , and ethtool(8) man pages.
The NetworkManager service and the nmcli command are included in the NetworkManager package. The Network Connections editor is included in the nm-connection-editor package. Depending on the type of environment you selected when you installed Oracle Linux 8, you might need to manually install the NetworkManager package by running the dnf install NetworkManager command.
1.5В Configuring Network Interfaces
The following information describes how to configure a NIC by using the tools that were previously described.
Because using Cockpit is intuitive, the following tasks focus on the other tools that are used to configure NICs on an Oracle Linux system. For a tutorial on using Cockpit to configure network interfaces, see https://docs.oracle.com/en/operating-systems/oracle-linux/8/obe-cockpit-network/index.html.
How to Use the Network Connections Editor
Launch the editor:
NetworkManager detects the network devices that are on the system and lists them as well as their current states:
To add or remove a connection, use the plus (+) or minus (-) buttons located at the bottom of the editor window.
If you add a connection, a window that prompts you for the connection type opens. Select a type, such as Ethernet, from the drop-down list then click Create . The Interface Editor window opens.
The same window opens if you edit an existing connection.
On each tab, enter the necessary information about the interface.
Click Save after you have completed the configuration.
You must specify all of the required information. Otherwise, the settings cannot be saved and the editor’s background terminal window would display messages that indicate the errors.
How to Use the Text Based User Interface
Open the text-based user interface.
To navigate the tool, use the up and down arrow keys, then press Enter to make a selection
To add a connection, select Edit a connection , then click Add .
After selecting a connection type, the Edit Connection window opens.
As an option, specify a preferred profile name, as well as the name of the device.
By default, IPv4 and IPv6 configurations are set to Automatic. To change the setting, select the Automatic field and press Enter. From the drop-down list, select the type of IP configuration that you want to implement, such as Manual. Then, select the corresponding Show field.
The fields that are displayed depend on the type of IP configuration that is selected. For example, if you want to manually configure an IP address, selecting Show displays an address field, where you would enter an IP addresses for the interface, as the following figure illustrates.
Navigate through all of the fields on the screen to ensure that the required information is specified.
After you have edited the connection, select OK .
How to Use the Command Line
To illustrate the different uses of the nmcli command, this procedure describes an example of adding and configuring a new Ethernet connection for the enp0s2 device. For more information about the command, see the nmcli(1) manual page.
Before adding the connection, prepare the information you would for the configuration, such as the following:
Connection name, for example, My Work Connection . The nmcli command works by referring to the connection name rather than the device name. If you do not set a connection name, then the device’s name is used as the connection name.
IP addresses (IPv4 and, if needed, IPv6)
Other relevant data you want to set for the connection
(Optional): Display the network devices on the system.
The following output is displayed:
The command shows whether a device is connected or disconnected, and whether managed or unmanaged.
(Optional) Display the connection information about the network devices.
Output similar to the following is displayed:
The con subcommand is the short form of connection , and can be further shortened to c . Specifying the —active option would display only active devices.
Note that in the output, NAME represents the connection ID.
Add a new connection.
The connection name as specified by the con-name argument, the type of connection as specified by the type argument, and the interface name as specified by the ifname argument.
The IPv4 or IPv6 address as specified by either the ip4 or ip6 argument. The address must be in the format address/netmask . The IPv4 address can be in CIDR form, for example, 1.2.3.4/24 .
The gateway IPv4 or IPv6 address as specified by either the gw4 or gw6 argument.
For example, to add the connection with the information at the beginning of this procedure, you would type:
The output would acknowledge that the connection is successfully completed.
Activate the interface.
(Optional) Display the configuration properties of the new connection.
The displayed information might appear as follows:
Specifying the -o option displays only properties that have configured values.
After you have created the connection, a corresponding configuration file is created in the /etc/sysconfig/networking-scripts directory. If you run the command ls -lrt /etc/sysconfig/network-scripts/ifcfg* , the output would list the new connection, for example:
1.6В Configuring Network Routing
A system uses its routing table to determine which network interface to use when sending packets to remote systems. For a system with only a single interface, it is sufficient to configure the IP address of a gateway system on the local network that routes packets to other networks.
To create a default route for IPv4 network packets, include an entry for GATEWAY in the /etc/sysconfig/network file. For example, the following entry configures the IP address of the gateway system:
If your system has more than one network interface, you can specify which interface should be used as follows:
A single statement is usually sufficient to define the gateway for IPv6 packets, for example:
Any changes that you make to /etc/sysconfig/network do not take effect until you restart the network service:
Display the routing table.
The following output might be displayed:
The sample output shows that packets destined for the local network ( 10.0.2.0/24 ) do not use the gateway. The default entry means that any packets destined for addresses outside the local network are routed through the gateway ( 10.0.2.2 ).
If you previously used the route command to configure routing, note that this command is considered obsolete. Using the ip command is preferred over the route command.
You can also use the netstat -rn command to display this information, for example:
To add or delete a route from the table, use the ip route add or ip route del commands. In the following example, the default route is first deleted, then a new route is added.
The newly added route is listed when you run ip route show .
The ip route get command is useful for querying on which route the system will send packets to reach a specified IP address, for example:
The following output might be displayed:
In this example, packets to 23.6.118.140 are sent out of the en1 interface via the gateway 10.0.2.2 .
Note that any changes you make to the routing table by using the ip route command do not persist across system reboots. To configure static routes that persist over system reboots, you can create a route- interface file in /etc/sysconfig/network-scripts for the interface. For example, you would configure a static route for the en1 interface in a file named route-en1 . An entry in these files can take the same format as the arguments to the ip route add command.
For example, you would define a default gateway entry for en1 by creating an entry similar to the following in route-en1 :
The following entry in route-en2 defines a route to 10.0.3.0/24 via 10.0.3.1 over en2 :
Any changes that you make to a route- interface file do not take effect until you restart either the network service or the interface.
For more information, see the ip(8) and netstat(8) manual pages.
Copyright В© 2019, 2021 Oracle and/or its affiliates. Legal Notices
Источник