Linux network scripts networking

Содержание
  1. Настройка сети в Linux через конфиг-файлы, ч.1
  2. Ручная настройка сети в Linux
  3. Привязка интерфейса к карте
  4. ifcfg
  5. route
  6. Ручная настройка сети в ArchLinux
  7. Ручная настройка сети в Ubuntu
  8. Ручная настройка сети в CentOS 6
  9. Общие настройки сети
  10. Конфигурация интерфейса
  11. Настройка DNS
  12. Настройка брандмауэра
  13. 60 Linux Networking commands and scripts
  14. Linux Networking commands and scripts
  15. Tags: scripts, sysadmins
  16. Download my free 101 Useful Linux Commands (PDF).
  17. ChapterВ 1В Configuring the System’s Network
  18. 1.1В About Network Interface Names
  19. 1.2В About Network Interface Names
  20. 1.3В About Network Configuration Files
  21. 1.3.1В About the /etc/hosts File
  22. 1.3.2В About the /etc/nsswitch.conf File
  23. 1.3.3В About the /etc/resolv.conf File
  24. 1.3.4В About the /etc/sysconfig/network File
  25. 1.4В Command-Line Network Configuration Interfaces
  26. 1.5В Configuring Network Interfaces Using Graphical Interfaces
  27. 1.6В About Network Interface Bonding
  28. 1.6.1В Configuring Network Interface Bonding
  29. 1.7В About Network Interface Teaming
  30. 1.7.1В Configuring Network Interface Teaming
  31. 1.7.2В Adding Ports to and Removing Ports from a Team
  32. 1.7.3В Changing the Configuration of a Port in a Team
  33. 1.7.4В Removing a Team
  34. 1.7.5В Displaying Information About Teams
  35. 1.8В Configuring VLANs with Untagged Data Frames
  36. 1.8.1В Using the ip Command to Create VLAN Devices
  37. 1.9В Configuring Network Routing

Настройка сети в Linux через конфиг-файлы, ч.1

Первое моё общение с Линуксом состоялось около шести лет назад. Тогда это был какой-то свежевышедший Red Hat, который мы с другом смогли установить, но при этом войти в него у нас так и не получилось.
Однако статья не об этом. Позже через мои руки и голову прошли почти все семейства дистрибутивов Linux, и везде я замечал свои подходы к автонастройке сети. И в этом цикле статей я постараюсь осветить наиболее популярные из них. Надеюсь, они будут полезны тем пользователям, которые пока ещё нажимают на кнопки и проставляют галочки в графических менеджерах настройки, но уже понимают, что это не true 🙂
Возможно познавательными эти статьи будут и тем, кто (не от большого знания) пишет свои скрипты управления сетью и помещает их в какой-нибудь rc.local

Итак, в первой части речь пойдёт о семействе номер один, одном из самых обширных по числу дистрибутивов, Red Hat based.

Сюда, например, относятся такие используемые сейчас дистрибутивы, как:

  • Fedora
  • RHEL/CentOS
  • Mandriva
  • ASPLinux

Служебные скрипты для настройки сети и сами конфиг-файлы в этих дистрибутивах хранятся по традиции в каталоге /etc/sysconfig/network-scripts/
Там вы найдёте несколько скриптов ifup-* и столько же ifdown-*, которые, соответственно, поднимают или опускают определённый тип интерфейса, а также ifcfg-* (звёздочка — это имя), где хранятся настройки этих самых интерфейсов.
Если сеть ещё не настроена, то вы обнаружите там ifcfg-lo, описывающий интерфейс loopback. В имеющейся у меня под рукой Fedora Core 7 этот файл выглядит следующим образом: (комментарии из файла удалены)

DEVICE=lo
IPADDR=127.0.0.1
NETMASK=255.0.0.0
NETWORK=127.0.0.0
BROADCAST=127.255.255.255
ONBOOT=yes
NAME=loopback

Не все параметры, перечисленные здесь являются обязательными. Зачастую чтобы задать интерфейс достаточно указать IPADDR и NETMASK. Параметр DEVICE необходим, если вы хотите, чтобы в имени скрипта после «ifcfg-» стояло не имя интерфейса, а какое-нибудь другое слово. Здесь же можно указывать такие параметры как GATEWAY, BOOTPROTO (static или dhcp), HWADDR (если есть желание изменить mac-адрес интерфейса) и так далее. Полный список возможных параметров зависит от типа поднимаемого интерфейса и дистрибутива. А, учитывая скудность официальной информации, его можно узнать и познать только перелопатив скрипты.

Такими конфиг-файлами можно задавать различные ppp-интерфейсы, ip-туннели, vlan’ы и так далее.

Следующий пример показывает настройку ipip-туннеля (ifcfg-tun0):
DEVICE=tun0
MY_OUTER_IPADDR=172.16.0.2
PEER_OUTER_IPADDR=192.168.0.1
MY_INNER_IPADDR=10.0.0.2
PEER_INNER_IPADDR=10.0.0.1
TYPE=IPIP
TTL=255

В этом примере мы, имея адрес 172.16.0.2, создаём туннель с машиной 192.168.0.1, указывая TTL=255, и присваиваем туннелю адрес 10.0.0.2 peer 10.0.0.1.

Не все знают, что помимо файлов ifcfg-* в этом же каталоге можно помещать соответствующие им файлы rule-* и route-*
Они нужны, соответственно, чтобы прописывать правила маршрутизации и сами маршруты ( ip rule, ip route ), например при использовании source-policy routing.

Для указанного выше туннеля эти файлы могут выглядеть так.

rule-tun0:
from 10.0.0.2 lookup mytable

route-tun0:
default dev tun0 table mytable
192.168.0.0/24 dev tun0

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

Ещё одна интересная возможность — автоматическое создание алиасов. Если у вас есть интерфейс eth0 с адресом 192.168.0.1, а вы хотите повесить ещё и 192.168.0.2, то достаточно создать файл ifcfg-eth0:1, куда вписать помимо вышеперечисленных параметров (IPADDR, NETMASK и так далее), ещё один — REALDEVICE=eth0.
Если же вдруг возникла необходимость в создании большого числа алиасов, а отдельные файлы для каждого создавать не хочется, то и тут есть выход: нас спасёт ifcfg-eth0-range, который может выглядеть так:
IPADDR_START=192.168.0.5
IPADDR_END=192.168.0.15
CLONENUM_START=3

Этот пример создаст интерфейсы eth0:3 — eth0:13 с адресами от 192.168.0.5 до 192.168.0.15.

Ну и, наконец, нельзя не упомянуть о каталогах ifup.d и ifdown.d, лежащих там же (в /etc/sysconfig/network-scripts).
В эти каталоги вы можете поместить свои файлы, которые будут выполняться при поднятии и опускании интерфейса. Вашим скриптам будет передан один параметр $1 — это имя интерфейса, который был поднят или опущен.

Имея сеть, настроенную по этим принципам, вы всегда можете поднять/опустить отдельный интерфейс командой ifup name (ifdown name), где name — это ваш интерфейс. Чтобы перезагрузить всю сеть, достаточно набрать service network reload.

Следующая часть будет посвящена не семейству, а одному дистрибутиву — Alt Linux. Несмотря на его прямые RedHat-корни, разработчики практически полностью заново написали всю систему управления сетью, которая получила имя etcnet и заслужила (на мой взгляд) более пристального внимания 🙂

Источник

Ручная настройка сети в Linux

Для доступа к сетевым картам в Linux используются так называемые интерфейсы. Интерфейсы это не файлы устройств и их нет в каталоге /dev. Интерфейсы создаются динамически и не всегда связаны с сетевыми картами. Например интерфейс ppp0 — это интерфейс VPNа, организованного по протоколу PPTP, а интерфейс lo это виртуальная сетевая карта с адресом localhost (127.0.0.1). В Linux имена интерфейсов традиционно состоят из мнемонического типа интерфейса и его порядкового номера. Карты ethernet доступны через интерфейсы eth0, eth1 и т.д. В системах, использующих systemd способ именования другой — интерфейсы имеют имена вида enp2s0 (en -Ethernet, p — PCI, 2 — номер на шине) Список всех интерфейсов можно посмотреть командой ifconfig -a или ip link .

Привязка интерфейса к карте

При наличии нескольких сетевых карт возникает вопрос о порядке их нумерации. В CentOS 6 эта задача возложена на подсистему обнаружения и конфигурации устройств — udev. В системах с systemd правила именования встроены в udev, но могот быть переопределены, как написано ниже.

Конфигурационный файл переименования интерфейсов обновляется автоматически при первом обнаружении очередной сетевой карты и находится в файле /etc/udev/rules.d/70-persistent-net.rules. Файл состоит из строк такого содержания:

Видно, что нумерация опирается на аппаратный (MAC) адрес карты. Если в компьютере заменить карту, то интерфейс eth0 станет недоступным, а новая карта получит имя eth1. Если есть желание вручную назначить имена картам, то можно отредактировать этот файл, выставив желаемые соответствия между MAC адресами именами интерфейсов (возможно потребуется перезагрузка).

ifcfg

Классическая утилита конфигурации сетевых интерфейсов ifcfg

route

Настройка таблицы маршрутизации route

В современных дистрибутивах линукса на смену ifconfig и route приходит универсальная утилита ip

Адреса серверов DNS и имя локального домена вписываются в файл /etc/resolv.conf

Ручная настройка сети в ArchLinux

Для просмотра доступных сетевых интерфейсов используется команда ip link

ArchLinux использует для настройки сети systemd/netctl . Для конфигурации используются файлы профилей, которые хранятся в /etc/netctl/ . В данном каталоге есть подкаталог examples/ из которого можно копировать файлы с образцами профилей в /etc/netctl/ . Например:

Содержимое enp1s0-work после редактирования

Базовые команды netctl

Ручная настройка сети в Ubuntu

Просмотр доступных интерфейсов — ifcfg -a

Файл конфигурации интерфейсов — /etc/network/interfaces . auto — говорит о том, что интерфейс надо конфигурировать при старте системы.

После смены настроек в /etc/network/interfaces , необходимо отключить и снова включить интерфейс.

Ручная настройка сети в CentOS 6

Общие настройки сети

Файл /etc/sysconfig/network используется стартовыми скриптами и содержит ключевые параметры — нужна ли сеть, нужно ли конфигурировать IP v6, имя компьютера. Сюда можно вписать шлюз по умолчанию, но CentOS 6 ориентируется на динамическое подкючение к сетям через WiFi и вписывает его в конфигурацию подходящего интерфейса.

Конфигурация интерфейса

Файлы в каталоге /etc/sysconfig/network-scripts с именами вида ifcfg-eth0

Интерфейс, получающий адрес по DHCP

Дополнительный IP адрес на интерфейсе eth1

Инициализация VLAN на eth1

Настройка DNS

Файл /etc/resolv.conf

Ручная настройка имен хостов файл /etc/hosts

Настройка брандмауэра

Файл /etc/sysconfig/system-config-firewall правила для настройки программой system-config-firewall

Файл /etc/sysconfig/iptables текущие правила, сохраненные на случай перезагрузки.

После ручного изменения правил их можно сохранить командой service iptables save

Источник

60 Linux Networking commands and scripts

Recently, I wanted to test network throughput via command line with at least 3 tools. For the life of me, I could not remember iperf. Not being able to remember previously used command line tools is frustrating and something we can all relate to. So I created a go-to-list of network tools for myself. Then, I thought, why not turn this list into a blog post? So I spent another hour or two compiling this ongoing list of Linux Networking Commands and Scripts. I look forward mostly to suggestions, because I know there’s always something missing or new scripts out there to try.

Читайте также:  Enable speaker fill windows 10 как включить

Linux Networking commands and scripts

This list of Linux Networking commands and scripts will receive ongoing updates, similar to the other lists on this blog…

  1. aria2 – downloading just about everything. Torrents included.
  2. arpwatch – Ethernet Activity Monitor.
  3. bmon – bandwidth monitor and rate estimator.
  4. bwm-ng – live network bandwidth monitor.
  5. curl – transferring data with URLs. (or try httpie)
  6. darkstat – captures network traffic, usage statistics.
  7. dhclient – Dynamic Host Configuration Protocol Client
  8. dig – query DNS servers for information.
  9. dstat – replacement for vmstat, iostat, mpstat, netstat and ifstat.
  10. ethtool – utility for controlling network drivers and hardware.
  11. gated – gateway routing daemon.
  12. host – DNS lookup utility.
  13. hping – TCP/IP packet assembler/analyzer.
  14. ibmonitor – shows bandwidth and total data transferred.
  15. ifstat – report network interfaces bandwidth.
  16. iftop – display bandwidth usage.
  17. ip (PDF file) – a command with more features that ifconfig (net-tools).
  18. iperf3 – network bandwidth measurement tool. (above screenshot Stacklinux VPS)
  19. iproute2 – collection of utilities for controlling TCP/IP.
  20. iptables – take control of network traffic.
  21. IPTraf – An IP Network Monitor.
  22. iputils – set of small useful utilities for Linux networking.
  23. iw – a new nl80211 based CLI configuration utility for wireless devices.
  24. jwhois (whois) – client for the whois service.
  25. “lsof -i” – reveal information about your network sockets.
  26. mtr – network diagnostic tool.
  27. net-tools – utilities include: arp, hostname, ifconfig, netstat, rarp, route, plipconfig, slattach, mii-tool, iptunnel and ipmaddr.
  28. ncat – improved re-implementation of the venerable netcat.
  29. netcat – networking utility for reading/writing network connections.
  30. nethogs – a small ‘net top’ tool.
  31. Netperf – Network bandwidth Testing.
  32. netplan – Netplan is a utility for easily configuring networking on a linux system.
  33. netsniff-ng – Swiss army knife for daily Linux network plumbing.
  34. netwatch – monitoring Network Connections.
  35. ngrep – grep applied to the network layer.
  36. nload – display network usage.
  37. nmap – network discovery and security auditing.
  38. nmcli – a command-line tool for controlling NetworkManager and reporting network status.
  39. nmtui – provides a text interface to configure networking by controlling NetworkManager .
  40. nslookup – query Internet name servers interactively.
  41. ping – send icmp echo_request to network hosts.
  42. route – show / manipulate the IP routing table.
  43. slurm – network load monitor.
  44. snort – Network Intrusion Detection and Prevention System.
  45. smokeping – keeps track of your network latency.
  46. socat – establishes two bidirectional byte streams and transfers data between them.
  47. speedometer – Measure and display the rate of data across a network.
  48. speedtest-cli – test internet bandwidth using speedtest.net
  49. ss – utility to investigate sockets.
  50. ssh – secure system administration and file transfers over insecure networks.
  51. tcpdump – command-line packet analyzer.
  52. tcptrack – Displays information about tcp connections on a network interface.
  53. telnet – user interface to the TELNET protocol.
  54. tracepath – very similar function to traceroute.
  55. traceroute – print the route packets trace to network host.
  56. vnStat – network traffic monitor.
  57. websocat – Connection forwarder from/to web sockets to/from usual sockets, in style of socat.
  58. wget – retrieving files using HTTP, HTTPS, FTP and FTPS.
  59. Wireless Tools for Linux – includes iwconfig, iwlist, iwspy, iwpriv and ifrename.
  60. Wireshark – network protocol analyzer.

Tags: scripts, sysadmins

Download my free 101 Useful Linux Commands (PDF).

Also, I’ll notify you when new Linux articles are published. — Subscribe now and receive my free PDF.
(Average of 1 or 2 emails per month, sent only on Mondays.)

Источник

ChapterВ 1В Configuring the System’s Network

This chapter describes how to configure a system’s network interfaces and network routing.

1.1В About Network Interface Names

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, where interface is the name of the interface. For example:

In this example, there are two configuration files for motherboard-based Ethernet interfaces, ifcfg-em1 and ifcfg-em2 , and one for the loopback interface, ifcfg-lo . The system reads the configuration files at boot time to configure the network interfaces.

On your system, you might see other names for network interfaces. See Section 1.2, “About Network Interface Names”.

The following are sample entries from an ifcfg-em1 file for a network interface that obtains its IP address using the Dynamic Host Configuration Protocol (DHCP):

If the interface is configured with a static IP address, the file contains entries such as the following:

The following configuration parameters are typically used in interface configuration files:

How the interface obtains its IP address:

Bootstrap Protocol (BOOTP).

Dynamic Host Configuration Protocol (DHCP).

Statically configured IP address.

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. For example: IPV6_DEFAULTGW=2001:0daa::2%em1 .

Whether the device is disabled if IPv6 configuration fails.

IPv6 address of the interface in CIDR notation, including the network mask prefix length. For example: IPV6ADDR=»2001:0db8:1e11:115b::1/32″

Whether to enable IPv6 for the interface.

Specifies the name of the primary bonded interface, of which this interface is 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.2В About Network Interface Names

Network interface names are based on information derived from the system BIOS or alternatively from a device’s firmware, system path, or MAC address. This feature ensures that interface names persist across system reboots, hardware reconfiguration, and updates to device drivers and the kernel.

If you enable the biosdevname boot option ( biosdevname=1 ), the biosdevname plugin to the udev device manager assigns names to network interfaces as follows:

Ethernet interfaces on the motherboard are named em N , where N is the number of the interface starting from 1.

Network interfaces on a PCI card are named p S p P , where S is the slot number and P is the port number.

Virtual interfaces are named p S p P _ V , where S is the slot number, P is the port number, and V is the virtual interface number.

If biosdevname is set to 0 (the default), systemd naming assigns the prefixes, en , wl , and ww to Ethernet, wireless LAN, and wireless WAN interfaces respectively. The prefix is followed by a suffix based on the hardware configuration, system bus configuration, or MAC address of the device:

Onboard device with index number N .

PCI device with bus number B , slot number S , function number F , and device ID D .

USB device with bus number B , slot number S , function number F , port number P , configuration number C , and interface number I .

Hot-plug device with slot number S , function number F , and device ID D .

Device with MAC address M .

For example, an Ethernet port on the motherboard might be named eno1 or em1 , depending on whether the value of biosdevname is 0 or 1.

The kernel assigns a legacy, unpredictable network interface name ( eth N and wlan N ) only if it cannot discover any information about the device that would allow it to disambiguate the device from other such devices. You can use the net.ifnames=0 boot parameter to reinstate the legacy naming scheme.

Using the net.ifnames or biosdevname boot parameters to change the naming scheme can rendering existing firewall rules invalid. Changing the naming scheme can also affect other software that refers to network interface names.

Читайте также:  Календарь дни рождения для windows

1.3В About Network Configuration Files

The following sections describe additional network configuration files that you might need to configure on a system.

1.3.1В About the /etc/hosts File

The /etc/hosts file associates host names with IP addresses. It allows the system to look up ( resolve ) the IP address of a host given its name, or the name given the IP address. Most networks use DNS (Domain Name Service) to perform address or name resolution. Even if your network uses DNS, it is usual to include lines in this file that specify the IPv4 and IPv6 addresses of the loopback device, for example:

The first and second column contains the IP address and host name. Additional columns contain aliases for the host name.

For more information, see the hosts(5) manual page.

1.3.2В About the /etc/nsswitch.conf File

The /etc/nsswitch.conf file configures how the system uses various databases and name resolution mechanisms. The first field of entries in this file identifies the name of the database. The second field defines a list of resolution mechanisms in the order in which the system attempts to resolve queries on the database.

The following example hosts definition from /etc/nsswitch.conf indicates that the system first attempts to resolve host names and IP addresses by querying files (that is, /etc/hosts ) and, if that fails, next by querying a DNS server, and last of all, by querying NIS+ (NIS version 3) :

For more information, see the nsswitch.conf(5) manual page.

1.3.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 usually contains a line specifying the search domains and up to three lines that specify the IP addresses of DNS server. The following entries from /etc/resolv.conf configure two search domains and three DNS servers:

If your system obtains its IP address from a DHCP server, it is usual for the system to configure the contents of this file with information also obtained using DHCP.

For more information, see the resolv.conf(5) manual page.

1.3.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. The following entries from /etc/sysconfig/network define that IPv4 networking is enabled, IPv6 networking is not enabled, the host name of the system, and the IP address of the default network gateway:

In previous releases of Oracle Linux, the host name of the system was defined in /etc/sysconfig/network . The host name is now defined in /etc/hostname and can be changed by using the hostnamectl command. The host name must be a fully qualified domain name (FQDN), for example, host20.mydomain.com , instead of a simple short name.

Additionally, system-wide default localization settings such as the default language, keyboard, and console font were defined in /etc/sysconfig/i18n . These settings are now defined in /etc/locale.conf and /etc/vconsole.conf .

For more information, see the hostname(5) , hostnamectl(1) , locale.conf(5) , and vconsole.conf(5) manual pages.

1.4В Command-Line Network Configuration Interfaces

If the NetworkManager service is running, you can use the nmcli command to display the state of the system’s physical network interfaces, for example:

You can use the ip command to display the status of an interface, for debugging, or for system tuning. For example, to display the status of all active interfaces:

For each network interface, the output shows the current IP address, and the status of the interface. To display the status of a single interface such as em1 , specify its name as shown here:

You can also use ip to set properties and activate a network interface. The following example sets the IP address of the em2 interface and activates it:

You might be used to using the ifconfig command to perform these operations. However, ifconfig is considered obsolete and will eventually be replaced altogether by the ip command.

Any settings that you configure for network interfaces using ip do not persist across system reboots. To make the changes permanent, set the properties in the /etc/sysconfig/network-scripts/ifcfg- interface file.

Any changes that you make to an interface file in /etc/sysconfig/network-scripts do not take effect until you restart the network service or bring the interface down and back up again. For example, to restart the network service:

To restart an individual interface, you can use the ifup or ifdown commands, which invoke the script in /etc/sysconfig/network-scripts that corresponds to the interface type, for example:

Alternatively, you can use the ip command to stop and start network activity on an interface without completely tearing down and rebuilding its configuration:

The ethtool utility is useful for diagnosing potentially mismatched settings that affect performance, and allows you to query and set the low-level properties of a network device. Any changes that you make using ethtool do not persist across a reboot. To make the changes permanent, modify the settings in the device’s ifcfg- interface file in /etc/sysconfig/network-scripts .

For more information, see the ethtool(8) , ifup(8) , ip(8) , and nmcli(1) manual pages.

1.5В Configuring Network Interfaces Using Graphical Interfaces

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.

The NetworkManager service dynamically detects and configures network connections. You can click on the network icon in the GNOME notification area to obtain information about the status of the network interfaces and to manage network connections:

To enable or disable a network interface from the pull-down menu, use the On/Off toggle.

To display the Settings window, select Network Settings from the drop-down menu.

FigureВ 1.2 shows the Network Settings editor.

To edit an existing interface, select it from the list and click the gear icon. You can add a profile to any interface to provide alternate configurations that you can use at any point in time. You can equally use this window to configure a network proxy or add an enable a Virtual Private Network (VPN) connection.

To perform more complex configuration and to add additional connection types, use the Network Connections editor. This tool allows you to configure wired, wireless, mobile broadband, VPN, Digital Subscriber Link (DSL), and virtual (bond, bridge, team, and VLAN) interfaces. You can open this window by using the nm-connection-editor command. FigureВ 1.2 shows the Network Connections editor.

To create a new network interface, click the + icon, select the type of interface (hardware, virtual, or VPN) and click Create . To edit an existing interface, select it from the list and click the gear icon. To remove a selected interface, click the icon.

You can also use the nmcli command to manage network connections through NetworkManager . For more information, see the nmcli(1) manual page.

1.6В About Network Interface Bonding

Network interface bonding combines multiple network connections into a single logical interface. A bonded network interface can increase data throughput by load balancing or can provide redundancy by allowing failover from one component device to another. By default, a bonded interface appears like a normal network device to the kernel, but it sends out network packets over the available secondary devices by using a simple round-robin scheduler. You can configure bonding module parameters in the bonded interface’s configuration file to alter the behavior of load-balancing and device failover.

Basic load-balancing modes ( balance-rr and balance-xor ) work with any switch that supports EtherChannel or trunking. Advanced load-balancing modes ( balance-tlb and balance-alb ) do not impose requirements on the switching hardware, but do require that the device driver for each component interfaces implement certain specific features such as support for ethtool or the ability to modify the hardware address while the device is active. For more information see /usr/share/doc/iputils-*/README.bonding .

1.6.1В Configuring Network Interface Bonding

The bonding driver that is provided with the Oracle Linux kernel allows you to aggregate multiple network interfaces, such as em1 and em2 , into a single logical interface such as bond0 . You can use the Network Settings editor to create the bond and then add network interfaces to this bond. Alternatively, you can use the nmcli command to create and configure the bond.

To create and configure a bonded interface from the command line:

Create the bond:

This example sets the name of the bond to bond0 and its mode to balance-rr . For more information about the available options for load balancing or ARP link monitoring, see /usr/share/doc/iputils-*/README.bonding and the nmcli(1) manual page.

Add each interface to the bond:

These commands add the em1 and em2 interfaces to bond0 .

Читайте также:  Драйвер rx560 windows 10

Restart the NetworkManager service:

After restarting the service, the bonded interface is available for use.

1.7В About Network Interface Teaming

Network interface teaming requires Unbreakable Enterprise Kernel Release 3 (UEK R3) Quarterly Update 7 or later.

Network interface teaming is similar to network interface bonding and provides a way of implementing link aggregation that is relatively maintenance-free, as well as being simpler to modify, expand, and debug as compared with bonding.

A lightweight kernel driver implements teaming and the teamd daemon implements load-balancing and failover schemes termed runners . The following standard runners are defined:

Monitors the link for changes and selects the active port that is used to send packets.

Sends packets on all member ports.

Provides load balancing by implementing the Link Aggregation Control Protocol 802.3ad on the member ports.

In passive mode, uses the BPF hash function to select the port that is used to send packets.

In active mode, uses a balancing algorithm to distribute outgoing packets over the available ports.

Selects a port at random to send each outgoing packet.

UEK R3 does not currently support this runner mode.

Transmits packets over the available ports in a round-robin fashion.

For specialized applications, you can create customized runners that teamd can interpret. The teamdctl command allows you to control the operation of teamd .

For more information, see the teamd.conf(5) manual page.

1.7.1В Configuring Network Interface Teaming

You can configure a teamed interface by creating JSON-format definitions that specify the properties of the team and each of its component interfaces. The teamd daemon then interprets these definitions. You can use the JSON-format definitions to create a team interface by starting the teamd daemon manually, by editing interface definition files in /etc/sysconfig/network-scripts , by using the nmcli command, or by using the Network Configuration editor ( nm-connection-editor ). This section describes the first of these methods.

To create a teamed interface by starting teamd manually:

Create a JSON-format definition file for the team and its component ports. For sample configurations, see the files under /usr/share/doc/teamd-*/example_configs/ .

The following example, which is based on the contents of the file activebackup_ethtool_1.conf , defines an active-backup configuration where em4 is configured as the primary port and em3 as the backup port and these ports are monitored by ethtool .

Use the ip command to bring down the component ports:

Active interfaces cannot be added to a team.

Start an instance of the teamd daemon and have it create the teamed interface by reading the configuration file (in this example, /root/team_config/team0.conf) :

The -g option displays debugging messages and can be omitted.

Use the ip command to set the IP address and network mask prefix length of the teamed interface:

For more information, see the teamd(8) manual page.

1.7.2В Adding Ports to and Removing Ports from a Team

To add a port to a team, use the teamdctl command, for example:

To remove a port from a team:

For more information, see the teamdctl(8) manual page.

1.7.3В Changing the Configuration of a Port in a Team

You can use the teamdctl command to update the configuration of a constituent port of a team, for example:

Enclose the JSON-format definition in single quotes and do not split it over multiple lines.

For more information, see the teamdctl(8) manual page.

1.7.4В Removing a Team

To remove a team, use the following command to kill the teamd daemon:

For more information, see the teamd(8) manual page.

1.7.5В Displaying Information About Teams

To display the network state of the teamed interface, use the ip command:

You can use the teamnl command to display information about the component ports of the team:

To display the current state of the team, use the teamdctl command, for example:

You can also use teamdctl to display the JSON configuration of the team and each of its constituent ports:

For more information, see the teamdctl(8) and teamnl(8) manual pages.

1.8В Configuring VLANs with Untagged Data Frames

A virtual local area network (VLAN) consists of a group of machines that can communicate as if they were attached to the same physical network. A VLAN allows you to group systems regardless of their actual physical location on a LAN. In a VLAN that uses untagged data frames, you create the broadcast domain by assigning the ports of network switches to the same permanent VLAN ID or PVID (other than 1, which is the default VLAN). All ports that you assign with this PVID are in a single broadcast domain. Broadcasts between devices in the same VLAN are not visible to other ports with a different VLAN, even if they exist on the same switch.

You can use the Network Settings editor or the nmcli command to create a VLAN device for an Ethernet interface.

To create a VLAN device from the command line, enter:

This example sets up the VLAN device bond0-pvid10 with a PVID of 10 for the bonded interface bond0 . In addition to the regular interface, bond0 , which uses the physical LAN, you now have a VLAN device, bond0-pvid10 , which can use untagged frames to access the virtual LAN.

You do not need to create virtual interfaces for the component interfaces of a bonded interface. However, you must set the PVID on each switch port to which they connect.

You can also use the command to set up a VLAN device for a non-bonded interface, for example:

To obtain information about the configured VLAN interfaces, view the files in the /proc/net/vlan directory.

1.8.1В Using the ip Command to Create VLAN Devices

The ip command provides an alternate method of creating VLAN devices. However, such devices do not persist across system reboots.

To create a VLAN interface em1.5 for em1 with a PVID of 5:

For more information, see the ip(8) manual page.

1.9В Configuring Network Routing

A system uses its routing table to determine which network interface to use when sending packets to remote systems. If a system has 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:

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:

To display the routing table, use the ip route show command, for example:

This example 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 via the gateway 10.0.2.2.

You might be used to using the route command to configure routing. However, route is considered obsolete and will eventually be replaced altogether by the ip command.

You can also use the netstat -rn command to display this information:

To add or delete a route from the table, use the ip route add or ip route del commands. For example, to replace the entry for the static default route:

To add a route to the network 10.0.3.0/24 via 10.0.3.1 over interface em2 , and then delete that route:

The ip route get command is a useful feature that allows you to query the route on which the system will send packets to reach a specified IP address, for example:

In this example, packets to 23.6.118.140 are sent out of the em1 interface via the gateway 10.0.2.2.

Any changes that you make to the routing table using ip route do not persist across system reboots. To permanently configure static routes, you can configure them by creating a route- interface file in /etc/sysconfig/network-scripts for the interface. For example, you would configure a static route for the em1 interface in a file named route-em1 . An entry in these files can take the same format as the arguments to the ip route add command.

For example, to define a default gateway entry for em1 , create an entry such as the following in route-em1 :

The following entry in route-em2 would define a route to 10.0.3.0/24 via 10.0.3.1 over em2 :

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 В© 2020, 2021, Oracle and/or its affiliates. Legal Notices

Источник

Оцените статью