Настройка сети в CentOS Linux | XaXaTyXa

Oracle® linux 7 setting up networking

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

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:

# cd /etc/sysconfig/network-scripts# ls ifcfg-*ifcfg-em1 ifcfg-em2 ifcfg-lo

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):

DEVICE="em1"
NM_CONTROLLED="yes"
ONBOOT=yes
USERCTL=no
TYPE=Ethernet
BOOTPROTO=dhcp
DEFROUTE=yes
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
NAME="System em1"
UUID=5fb06bd0-0bb0-7ffb-45f1-d6edd65f3e03
HWADDR=08:00:27:16:C3:33
PEERDNS=yes
PEERROUTES=yes

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

DEVICE="em1"
NM_CONTROLLED="yes"
ONBOOT=yes
USERCTL=no
TYPE=Ethernet
BOOTPROTO=none
DEFROUTE=yes
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
NAME="System em1"
UUID=5fb06bd0-0bb0-7ffb-45f1-d6edd65f3e03
HWADDR=08:00:27:16:C3:33
IPADDR=192.168.1.101
NETMASK=255.255.255.0
BROADCAST=192.168.1.255
PEERDNS=yes
PEERROUTES=yes

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

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:

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:

oN

Onboard device with index number
N.

pBsS[fF][dD]

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

pBsS[fF][uP]…[cC][iI]

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

sS[fF][dD]

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

xM

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
(ethN and
wlanN) 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.

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

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:

127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6

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.

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) :

hosts: files dns nisplus

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

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:

search us.mydomain.com mydomain.com
nameserver 192.168.154.3
nameserver 192.168.154.4
nameserver 10.216.106.3

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.

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:

NETWORKING=yes
NETWORKING_IPV6=no
HOSTNAME=host20.mydomain.com
GATEWAY=192.168.1.1

Note

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.

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:

# nmcli device statusDEVICE TYPE STATE
em1 ethernet connected
em2 ethernet connected
lo loopback unmanaged 

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:

# ip addr show1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo inet6 ::1/128 scope host valid_lft forever preferred_lft forever
2: em1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000 link/ether 08:00:27:16:c3:33 brd ff:ff:ff:ff:ff:ff inet 10.0.2.15/24 brd 10.0.2.255 scope global em1 inet6 fe80::a00:27ff:fe16:c333/64 scope link valid_lft forever preferred_lft forever

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:

# ip addr show dev em12: em1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000 link/ether 08:00:27:16:c3:33 brd ff:ff:ff:ff:ff:ff inet 10.0.2.15/24 brd 10.0.2.255 scope global em1 inet6 fe80::a00:27ff:fe16:c333/64 scope link valid_lft forever preferred_lft forever

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:

# ip addr add 10.1.1.1/24 dev em2# ip link set em2 up

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:

# systemctl restart network

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:

# ifdown em1# ifup em1Connection successfully activated
(D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/5)

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

# ip link set em1 down# ip link set em1 up

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.

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:

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.

:/>  34 совета по оптимизации и настройке windows

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.

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.

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:

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:

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.

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:

  1. 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.

    { "device": "team0", "runner": {"name": "activebackup"}, "link_watch": {"name": "ethtool"}, "ports": { "em3": { "prio": -10, "sticky": true }, "em4": { "prio": 100 } }
    }
  2. Use the ip command to bring down the
    component ports:

    # ip link set em3 down# ip link set em4 down

    Active interfaces cannot be added to a team.

  3. 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):

    # teamd -g -f /root/team_config/team0.conf -dUsing team device "team0".
    Using PID file "/var/run/teamd/team0.pid"
    Using config file "/root/team_config/team0.conf"

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

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

    # ip addr add 10.0.0.5/24 dev team0

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

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

# teamdctl team0 port add em5

To remove a port from a team:

# teamdctl team0 port remove em5

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

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

# teamdctl team0 port config update em3 '{"prio": -10, "sticky": false}'

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.

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

# teamd -t team0 -k

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

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

# ip addr show dev team07: team0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP link/ether 08:00:27:15:7a:f1 brd ff:ff:ff:ff:ff:ff inet 10.0.0.5/24 scope global team0 valid_lft forever preferred_lft forever inet6 fe80::a00:27ff:fe15:7af1/64 scope link valid_lft forever preferred_lft forever

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

# teamnl team0 ports 5: em4: up 1000Mbit FD 4: em3: up 1000Mbit FD 

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

# teamdctl team0 statesetup: runner: activebackup
ports: em3 link watches: link summary: down instance[link_watch_0]: name: ethtool link: down em4 link watches: link summary: up instance[link_watch_0]: name: ethtool link: up
runner: active port: em4

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

# teamdctl team0 config dump{ "device": "team0", "link_watch": { "name": "ethtool" }, "mcast_rejoin": { "count": 1 }, "notify_peers": { "count": 1 }, "ports": { "em3": { "prio": -10, "sticky": true }, "em4": { "prio": 100 } }, "runner": { "name": "activebackup" }
}

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

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:

# nmcli con add type vlan con-name bond0-pvid10 ifname bond0-pvid10 dev bond0 id 10

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 can also use the command to set up a VLAN device for a
non-bonded interface, for example:

# nmcli con add type vlan con-name em1-pvid5 ifname em1-pvid5 dev em1 id 5

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

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:

# ip link add link em1 name em1.5 type vlan id 5

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

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:

GATEWAY=192.0.2.1

If your system has more than one network interface, you can
specify which interface should be used:

GATEWAY=192.0.2.1
GATEWAYDEV=em1

A single statement is usually sufficient to define the gateway for
IPv6 packets, for example:

:/>  Как найти драйвер для неизвестного устройства

IPV6_DEFAULTGW="2001:db8:1e10:115b::2%em1"

Any changes that you make to
/etc/sysconfig/network do not take effect until
you restart the network service:

# systemctl restart network

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

# ip route show10.0.2.0/24 dev em1 proto kernel scope link src 10.0.2.15
default via 10.0.2.2 dev em1 proto static 

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 can also use the netstat -rn command to
display this information:

Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
10.0.2.0 0.0.0.0 255.255.255.0 U 0 0 0 em1
0.0.0.0 10.0.2.2 0.0.0.0 UG 0 0 0 em1

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:

# ip route del default# ip route show10.0.2.0/24 dev em1 proto kernel scope link src 10.0.2.15
# ip ro add default via 10.0.2.1 dev em1 proto static# ip route show10.0.2.0/24 dev em1 proto kernel scope link src 10.0.2.15
default via 10.0.2.1 dev em1 proto static 

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:

# ip route add 10.0.4.0/24 via 10.0.2.1 dev em2# ip route show10.0.2.0/24 dev em1 proto kernel scope link src 10.0.2.15
10.0.3.0/24 via 10.0.3.1 dev em2
default via 10.0.2.2 dev em1 proto static
# ip route del 10.0.3.0/24# ip route show10.0.2.0/24 dev em1 proto kernel scope link src 10.0.2.15
default via 10.0.2.2 dev em1 proto static 

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:

# ip route get 23.6.118.14023.6.118.140 via 10.0.2.2 dev em1 src 10.0.2.15 cache mtu 1500 advmss 1460 hoplimit 64

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:

default via 10.0.2.1 dev em1

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

10.0.3.0/24 via 10.0.3.1 dev 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.

Настройка сети в 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 и заслужила (на мой взгляд) более пристального внимания 🙂

Сетевые настройки на сервере centos

Первый раз с сетевыми настройками сервера CentOS 7 или 8 мы сталкиваемся, когда производим установку. На экране первоначальной настройки есть отдельный пункт, касающийся настройки сетевых интерфейсов:

Зайдя в него мы видим список подключенных сетевых карт. Каждую из них можно включить соответствующим ползунком (пункт 1 на картинке). При активировании интерфейса он автоматически получает настройки по dhcp. Результат работы dhcp можно посмотреть тут же.

Открыв окно дополнительный настроек Ehernet, вы сможете изменить имя сетевого интерфейса, указать настройки IP (пункт 1 на картинке), выбрать ручные настройки (пункт 2 на картинке), назначить ip адрес (пункт 3 на картинке), установить dns сервер (пункт 4 на картинке) и сохранить сетевые настройки (пункт 5 на картинке):

После выполнения остальных настроек начнется установка. После установки у вас будет сервер с указанными вами сетевыми настройками.

Теперь рассмотрим другую ситуацию. Сервер, а соответственно и конфигурацию сети, производили не вы, а теперь вам надо ее посмотреть либо изменить. В вашем распоряжении консоль сервера, в ней и будем работать. Если у вас установка производилась с дистрибутива minimal, то при попытке посмотреть сетевые настройки с помощью команды ifconfig в консоли вы увидите следующее:

-bash: ifconfig: command not found

или в русской версии:

-bash: ifconfig команда не найдена

Для работы с ifconfig и прочими сетевыми утилитами необходимо установить пакет net-tools. Сделаем это:

# yum install net-tools

Теперь можно увидеть настройки сети:

# ifconfig
eno16777728: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.159.129 netmask 255.255.255.0 broadcast 192.168.159.255
inet6 fe80::20c:29ff:fe7d:593f prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:7d:59:3f txqueuelen 1000 (Ethernet)
RX packets 319 bytes 36709 (35.8 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 256 bytes 148817 (145.3 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 0 (Local Loopback)
RX packets 6 bytes 624 (624.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 6 bytes 624 (624.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

Если у вас нет желания устанавливать дополнительный пакет, то можно воспользоваться более простой командой ip с параметрами:

# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eno16777728: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 00:0c:29:7d:59:3f brd ff:ff:ff:ff:ff:ff
inet 192.168.159.129/24 brd 192.168.159.255 scope global dynamic eno16777728
valid_lft 1709sec preferred_lft 1709sec
inet6 fe80::20c:29ff:fe7d:593f/64 scope link
valid_lft forever preferred_lft forever

Мы увидели конфигурацию сети, теперь давайте ее отредактируем. Допустим, нам нужно сменить ip адрес. Для этого идем в директорию /etc/sysconfig/network-scripts и открываем на редактирование файл ifcfg-eth0 или ifcfg-ens18. Название файла будет зависеть от имени сетевого интерфейса.

# yum install network-scripts

Файл ifcfg-eth0 имеет примерно следующее содержание:

:/>  Как установить живые обои на Windows 10 - замена фона рабочего стола

По настройкам из этого файла мы получаем ip адрес по dhcp. Чтобы вручную прописать статический ip, приводим файл к следующему содержанию:

Мы изменили параметры:

BOOTPROTOс dhcp на none
DNS1указали dns сервер
IPADDR0настроили статический ip адрес
PREFIX0указали маску подсети
GATEWAY0настроили шлюз по-умолчанию

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

# systemctl restart network

Проверяем, применилась ли новая конфигурация сети:

# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.159.129 netmask 255.255.255.0 broadcast 192.168.159.255
inet6 fe80::20c:29ff:fe7d:593f prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:7d:59:3f txqueuelen 1000 (Ethernet)
RX packets 672 bytes 71841 (70.1 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 572 bytes 290861 (284.0 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

Все в порядке, новые настройки сетевого интерфейса установлены.

Файлы настроек сети в linux (конфигурационные файлы)

Для понимания работы сети в Linux, я бы обязательно посоветовал ознакомиться со статьей «Этапы загрузки Linux». В целом, вся работа Linux основана на процессе init, который рождается при загрузке ОС и плодит своих потомков, которые в свою очередь и выполняют всю необходимую работу, будь то запуск bash или демона. Да, и вся загрузка Linux основана на скриптах bash, в которых прописана вся последовательность запуска мелких утилит с различными параметрами, которые последовательно запускаются/останавливаются при запуске/остановке системы. Аналогично запускается и сетевая подсистема Linux.
Каждый дистрибутив Linux имеет слегка отличающийся от других механизм инициализации сети, но общая картина, думаю, после прочтения будет ясна. Если просмотреть стартовые скрипты сетевой подсистемы какого-либо дистрибутива Linux, то, как настроить конфигурацию сети с помощью конфигурационных файлов, станет более-менее понятно, например у Debian/Ubuntu (за основу возьмем эту ветвь дистрибутивов) за инициализацию сети отвечает скрипт /etc/init.d/networking, просмотрев содержимое которого:

net-server:~#cat/etc/init.d/networking#!/bin/sh -e### BEGIN INIT INFO# Provides:          networking# Required-Start:    mountkernfs $local_fs# Required-Stop:     $local_fs# Should-Start:      ifupdown# Should-Stop:       ifupdown# Default-Start:     S# Default-Stop:      0 6# Short-Description: Raise network interfaces.### END INIT INFO PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin" [-x/sbin/ifup]||exit0 
. /lib/lsb/init-functions
 
process_options(){    [-e/etc/network/options ]||return0    log_warning_msg "/etc/network/options still exists and it will be IGNORED! Read README.Debian of netbase."} 
check_network_file_systems(){    [-e/proc/mounts ]||return0 
    if[-e/etc/iscsi/iscsi.initramfs ]; then        log_warning_msg "not deconfiguring network interfaces: iSCSI root is mounted."        exit0    fi 
    exec9<&0</proc/mounts
    whileread DEV MTPT FSTYPE REST; do        case$DEVin        /dev/nbd*|/dev/nd[a-z]*|/dev/etherd/e*)            log_warning_msg "not deconfiguring network interfaces: network devices still mounted."            exit0            ;;        esac        case$FSTYPEin        nfs|nfs4|smbfs|ncp|ncpfs|cifs|coda|ocfs2|gfs|pvfs|pvfs2|fuse.httpfs|fuse.curlftpfs)            log_warning_msg "not deconfiguring network interfaces: network file systems still mounted."            exit0            ;;        esac    done    exec0<&99<&-} 
check_network_swap(){    [-e/proc/swaps ]||return0 
    exec9<&0</proc/swaps
    whileread DEV MTPT FSTYPE REST; do        case$DEVin        /dev/nbd*|/dev/nd[a-z]*|/dev/etherd/e*)            log_warning_msg "not deconfiguring network interfaces: network swap still mounted."            exit0            ;;        esac    done    exec0<&99<&-} case"$1"instart)        process_options
 
        log_action_begin_msg "Configuring network interfaces"        ififup-a; then            log_action_end_msg $?        else            log_action_end_msg $?        fi        ;; 
stop)        check_network_file_systems
        check_network_swap
 
        log_action_begin_msg "Deconfiguring network interfaces"        ififdown-a--exclude=lo; then            log_action_end_msg $?        else            log_action_end_msg $?        fi        ;; 
force-reload|restart)        process_options
 
        log_warning_msg "Running $0 $1 is deprecated because it may not enable again some interfaces"        log_action_begin_msg "Reconfiguring network interfaces"        ifdown-a--exclude=lo ||true        ififup-a--exclude=lo; then            log_action_end_msg $?        else            log_action_end_msg $?        fi        ;; *)        echo"Usage: /etc/init.d/networking {start|stop}"        exit1        ;;esac exit0

можно найти несколько функций, проверяющих наличие подключенных сетевых файловых систем (check_network_file_systems(), check_network_swap()), а так же проверку существования какого-то пока непонятного конфига /etc/network/options (функция process_options()),  а в самом низу, конструкцией case «$1» inпроверяется первый параметр переданный скрипту и в соответствии с введенным параметром (start/stop/force-reload|restart или любое дугое) производит определенные действия. Из этих самых «определенных действий», на примере аргумента start видно, что сначала запускается функция process_options, далее отправляется в лог фраза Configuring network interfaces, и запускается команда ifup -a. Если посмотреть man ifup, то видно что данная команда читает конфиг из файла /etc/network/interfaces и согласно ключу -a запускает все интерфейсы имеющие параметр auto.

The ifup and ifdown commands may be used to configure (or, respectively, deconfigure) network interfaces based on interface definitions in the file /etc/network/interfaces. -a, --all If given to ifup, affect all interfaces marked auto. Interfaces are brought up in the order in which they are defined in /etc/network/interfaces. If given to ifdown, affect all defined interfaces. Interfaces are brought down in the order in which they are currently listed in the state file. Only interfaces defined in /etc/network/interfaces will be brought down.

Соответственно, прочитав man interfaces (rus) или man interfaces (eng), становиться ясно, как же в Debian/Ubuntu настроить какой-либо сетевой интерфейс с помощью конфига /etc/network/interfaces. Ниже, пример данного конфигурационного файла для 3х интерфейсов: петлевой (lo), со статичным IP (eth2) и IP получаемым по dhcp (eth0):

ip-server:~# cat /etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
allow-hotplug eth0
iface eth0 inet dhcp
allow-hotplug eth2
iface eth2 inet static address 192.168.1.1 netmask 255.255.255.0 gateway 192.168.1.254 broadcast 192.168.1.255

В данном конфиге строки allow-hotplug и auto – это синонимы и интерфейсы будут подняты по команде ifup -a. Вот, собственно, и вся цепь работы сетевой подсистемы. Аналогично, в других дистрибутивах: в RedHat и SUSE сеть запускается скриптом /etc/init.d/network. Рассматрев его, аналогично можно найти, где лежит конфигурация сети.

/etc/hosts

Данный файл хранит перечень IP адресов и соответствующих им (адресам) имен хостов.Формат файла ничем не отличается от мастдайного:

ip-server:~# cat /etc/hosts # ip        host.in.domain host 127.0.0.1       localhost 127.0.1.1       ip-server.domain.local  ip-server 192.168.1.1     ip-server.domain.local  ip-server

Исторически, данный файл использовался вместо службы DNS. В настоящее время, файл так же может использоваться вместо службы DNS, но только при условии, что в вашей сети количество машин измеряется в единицах, а не в десятках или сотнях, потому что в таком случае, придется контролировать корректность данного файла на каждой машине.

/etc/networks

Данный файл хранит имена и адреса локальной и других сетей. Пример:

ip-server:~# cat /etc/networks
default         0.0.0.0
loopback        127.0.0.0
link-local      169.254.0.0
home-network 192.168.1.0

При использовании данного файла, сетями можно управлять по имени. Например добавить маршрут не route add 192.168.1.12, а route add home-network.

/etc/nsswitch.conf

Файл определяет порядок поиска имени хоста/сети, за данную настройку отвечают строки:

Для хостов: hosts:          files dns
Для сетей: networks:       files

Параметр files указывает использовать указанные файлы (/etc/hosts и /etc/networks соответственно), параметр dns указывает использовать службу dns.

/etc/resolv.conf

Этот файл определяет параметры механизма преобразования сетевых имен в IP адреса. Пример:

ip-server:~# cat /etc/resolv.conf
nameserver 10.0.0.4
nameserver 10.0.0.1
search domain.local

Первые 2 строчки указывают сервера DNS. Третья строка указывает домены поиска. Если при разрешении имени, имя не будет FQDN-именем, то данный домен подставиться в виде «окончания». Например при выполнении команды ping host, прингуемый адрес преобразуется в host.domain.local. Остальные параметры можно почитать в man resolv.conf.

В современных дистрибутивах Linux используется динамическая генерация данного файла, с помощью утилиты resolvconf. Она является посредником между службами, динамически предоставляющими сервера имен (например DHCP client) и службами, использующими данные сервера имен. Статические адреса DNS серверов, в случае использования resolvconf, задаются внутри /etc/network/interfaces (подробнее об этом – в разделе настройки).