Изменить название сетевого интерфейса linux

CentOS 7 — Rename network interface without rebooting

The content of the network scripts looks like this, after modification:

# cat /etc/sysconfig/network-scripts/ifcfg-nic0 DEVICE=nic0 BOOTPROTO=static ONBOOT=yes HWADDR=xx:xx:xx:xx:xx:xx USERCTL=no IPV6INIT=no MASTER=bond0 SLAVE=yes 

A reboot activates the new config. But how do I activate this configuration without rebooting?

A systemctl restart network doesn’t do the trick.

I can shut down one interface by its old name ( ifdown eth0 ) but ifup results in below message no matter if the old or new name was provided:

ERROR : [/etc/sysconfig/network-scripts/ifup-eth] Device nic0 does not seem to be present, delaying initialization.

/etc/init.d/network status shows this output:

Configured devices: lo bond0 nic0 nic1 Currently active devices: lo eth0 eth1 bond0 

Both, ifconfig and ip a show the old interface names.

You might try removing and reloading the network device drivers, if they’re compiled as kernel modules.

6 Answers 6

You can rename the device using the ip command:

/sbin/ip link set eth1 down /sbin/ip link set eth1 name eth123 /sbin/ip link set eth123 up 

I am leaving the below for the sake of completeness and posterity (and for informational purposes,) but I have confirmed swill’s comment and Marco Macuzzo’s answer that simply changing the name and device of the interface /etc/sysconfig/network-scripts/ifcfg-eth0 (and renaming the file) will cause the device to be named correctly as long as the hwaddr= field is included in the configuration file. I recommend using this method instead after the referenced update.

You may also want to make sure that you configure a udev rule, so that this will work on the next reboot too. The path for udev moved in CentOS 7 to /usr/lib/udev/rules.d/60-net.rules but you are still able to manage it the same way. If you added «net.ifnames=0 biosdevname=0» to your kernel boot string to return to the old naming scheme for your nics, you can remove

ACTION=="add", SUBSYSTEM=="net", DRIVERS=="?*", ATTR=="1", PROGRAM="/lib/udev/rename_device", RESULT=="?*", NAME="$result" 
ACTION=="add", SUBSYSTEM=="net", DRIVERS=="?*", ATTR=="00:50:56:8e:3f:a7", NAME="eth123" 

You need one entry per nic. Be sure to use the correct MAC address and update the NAME field. If you did not use «net.ifnames=0 biosdevname=0», be careful as there could be unintended consequences.

Just a note on this. If you are using CentOS 7.3, then this does not work. This is because of this issue (access.redhat.com/solutions/2592561). You will have to override the file at /etc/udev/rules.d/90-eno-fix.rules because it overrides all previously working solutions to rename the network devices.

Читайте также:  Linux string to lowercase

Looking at the advisory you referenced, it notes «This issue can be avoided by updating installation repositories to include the systemd-219-30.el7_3.6 or later package. With this newer systemd release, affected interfaces are identified upon the package install and a udev rule is automatically generated so the renaming issue is entirely avoided.»

That is a different rename issue they are referring to. They are talking about the name being shortened because it is too long (I think). The udev rule that is mentioned hard codes the interface name to an eno######## value which overrides all of these attempts to rename it to something like eth0 . Does that make sense? I will have to verify on my machine which version I am using, but I upgraded to the latest CentOS 7.3 yesterday, so I think I will have the version mentioned.

This method was useful for me to solve a different but related problem — a container crashed while starting because of an unrelated configuration error, and left the interface renamed from the system name ensXfY to the container name of eth1. It then wasn’t possible to re-attempt starting the container because it couldn’t find the interface until it was renamed back

This warning should be obvious, but perform this procedure from console. If connected through the very same interface via ssh, you will lock yourself out once giving the ip down command!

Actually, the best answer I believe is the combination of the two answers already posted. In order to change the device name without restarting network services, use the ip link commands suggested by James Shewey ( ip link set name ).

To make the changes survive a reboot in Red Hat Linux, modify the relevant file in /etc/sysconfig/network-scripts/ . Rename the file ifcfg_ to ifcfg_ and change the DEVICE variable inside to . Also, make sure the HWADDR variable is set and is correct. There is no need to touch udev rules, since 60-net.rules is actually there to read the ifcfg configuration files in /etc/sysconfig/network-scripts .

ip link set ens33 down ip link set ens33 name eth0 ip link set eth0 up mv /etc/sysconfig/network-scripts/ifcfg- sed -ire "s/NAME=\"ens33\"/NAME=\"eth0\"/" /etc/sysconfig/network-scripts/ifcfg-eth0 sed -ire "s/DEVICE=\"ens33\"/DEVICE=\"eth0\"/" /etc/sysconfig/network-scripts/ifcfg-eth0 MAC=$(cat /sys/class/net/eth0/address) echo -n 'HWADDR="'$MAC\" >> /etc/sysconfig/network-scripts/ifcfg-eth0 

To restore the old naming convention, you need to edit the /etc/default/grub file and add the following

at the end of the GRUB_CMDLINE_LINUX variable

I’m seeing in RHEL/CENTOS 7.7 where (1) net.ifnames=0 doesn’t actually work as such, and (2) biosdevname=0 results in a semi-hung system on shutdown.

Читайте также:  Astra linux dpkg remove

The Answer given by @James Shewey seems to be the right way to do it.

If you want to just work with the config files in /etc/sysconfig/network-scripts and then trigger a reload, unloading and loading the kernel module as mentioned by @Tom Hunt in the comments also works:

service network stop modprobe -r igb modprobe igb service network start 

If you access the machine remotely, make sure you run all commands in a nohup or you will lock yourself out:

nohup sh -c "service network stop && modprobe -r igb && modprobe igb ; service network start" 

The driver to reload of course depends on your interface.

I tried the above with Vagrant / VirtualBox and ansible, but somehow this didn’t work at all on my development environment.

The old interface names were maintained whatever I did until a full restart.

I added the following rules in /etc/udev/rules.d/60-persistent-net.rules (based on: https://access.redhat.com/solutions/112643)

My goal was to give the interface a specified name based on the PCI address.

ACTION=="add", SUBSYSTEM=="net", KERNELS=="0000:00:09.0", NAME:="int0" ACTION=="add", SUBSYSTEM=="net", KERNELS=="0000:00:10.0", NAME:="ext0" 

After adding those rules I executed the following commands:

ip link set eth0 down udevadm control --reload-rules udevadm trigger ip link set int0 up 

The error message was Cannot find device «int0» on the ip link set * up command. And in /var/log/messages I noticed the following messages

Aug 16 17:08:41 localhost ansible-command: Invoked with creates=None executable=None _uses_shell=True strip_empty_ends=True _raw_params=ip link set eth0 down && udevadm control --reload-rules && udevadm trigger && ip link set int0 up#012 removes=None argv=None warn=True chdir=None stdin_add_newline=True stdin=None Aug 16 17:08:41 localhost NetworkManager[6989]: [1565975321.5971] device (eth6): state change: disconnected -> unavailable (reason 'carrier-changed', sys-iface-state: 'managed') Aug 16 17:08:41 localhost systemd-udevd: Network interface NamePolicy= disabled on kernel command line, ignoring. 

But the following did work by accessing the VM through VirtualBox and execute the following commands to remove and re-add the kernel module.

rmmod e1000 modprobe e1000 

The strange thing I noticed was that lsmod gives me (note the Used by )

[vagrant@node-01 ~]$ lsmod Module Size Used by e1000 137586 0 

Источник

Изменить имя сетевого интерфейса в Linux Debian/Ubuntu

Debian-Ubuntu-eth-rename

Доброе время суток. Сегодня расскажу как быстро изменить имя сетевого интерфейса в Linux на желаемое.

Часто так бывает, что по каким то причинам мы не хотим или не можем оставить стандартное имя сетевого интерфейса в Linux Debain/Ubuntu. Например Ubuntu в новых дистрибутивах дает имена такого вида – enp0s3.

Данную операцию будем выполнять через менеджер устройств udev.

udev – управляет файлами всевозможных устройств в каталоге /dev и обработка всех действий. При подключении или отключении периферии. Запускается как демон и принимает через сокет события uevents от ядра, Правила для подключаемых устройств и дополнительные действия находятся в файлах конфигурации. И хранятся в каталоге /etc/udev/rules.d с расширение .rules.

Читайте также:  Linux user group listing

Первое что необходимо сделать это узнать mac-адрес необходимого нам устройства. Это можно сделать с помощью таких команд:

Теперь необходимо создать правило udev и сохранить. Где “enp0s3” – старое имя интерфейса. “08:00:27:47:d2:4e” – mac-адрес интерфейса. “eth0” – новое имя:

sudo nano /etc/udev/rules.d/1-user-network.rules KERNEL=="enp0s3", ,ATTR=="08:00:27:47:d2:4e", NAME="eth0"

Обязательным действием является редактирование файла настроек сетевых интерфейсов:

sudo nano /etc/network/interfaces auto eth0 iface eth0 inet static address 192.168.1.1 netmask 255.255.255.0 network 192.168.1.0 broadcast 192.168.1.255

Теперь смело перезагружаем операционную систему.

Источник

Переименование сетевых интерфейсов в Debian 11

Несколько лет назад писал об изменении имён сетевых интерфейсов, по сути с того времени старый способ работает, но если не повезёт, то до поры до времени. После установки или обновления каких-нибудь пакетов связанных с ядром или драйверами, вы можете очень расстроиться, что .rules’ы больше не работают или работают не полностью.

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

Но, если я захочу переставить карту в другой слот? Если интерфейсов несколько, что тогда начнётся? А уж какой это кайф, писать что-то вроде «enp4s0f3» в конфигах и командах консоли, ммм.

Итак, меняем имена. Для смены имён у меня для вас два проверенных рабочих варианта (kernel 5.10.0-18 на сентябрь 2022).

  1. Передаём ядру net.ifnames=0
  2. Делаем линки для переименования сетевых интерфейсов с помощью systemd.

Теперь подробнее. Первый вариант заключается в добавлении параметра net.ifnames=0 в загрузчик. Идём в /etc/default/grub, делаем так

#grub-mkconfig -o /boot/grub/grub.cfg

Перезагружаемся и получаем имена наших интерфейсов по порядку, вида eth0, eth1, eth2. и т.д.

Второй вариант подходит не только для переименования сетевых интерфейсов, а также для привязки-переименования usb-модемов, создания бриджей и многого другого (подробнее можете почитать по ссылкам ниже). Заключается он в создании файлов с расширением .link в /etc/systemd/network (директория имеет приоритет над другими) с таким содержимым:

Пояснять что тут я думаю не надо. На каждый интерфейс — свой .link, в имени файла нужно выставлять приоритет (как в .rules), например 10-renameint-enp5s0f0-net.link, чтобы он был приоритетнее какого-нибудь 99-default.link.

Для более глубокого погружения и понимания, советую ознакомиться с материалами раз, два, три.

Источник

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