Linux change network interface name

How to Change Network Interface name on Ubuntu

Generally, a Network interface is named as either eth0, eth1, eth2 and etc. The network interface name depends on ethernet connections available and its number should vary from eth0 to eth1. Once Ubuntu 16.04 is installed, the network interface name gets changed from eth0 to ens33. It is quite easy to change the Network Interface name on your Ubuntu machine and this article can help you with that.

Changing the Network Interface name

You can verify your network interface name using ‘ ifconfig’ command or ‘ ip a’ command.

[email protected]:~# ifconfig ens33 Link encap:Ethernet HWaddr 00:0c:29:31:3d:a8 inet addr:192.168.5.152 Bcast:192.168.5.255 Mask:255.255.255.0 inet6 addr: fe80::fde3:373:9789:718f/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:218283 errors:0 dropped:0 overruns:0 frame:0 TX packets:134051 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:328932569 (328.9 MB) TX bytes:9267462 (9.2 MB) lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:241 errors:0 dropped:0 overruns:0 frame:0 TX packets:241 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1 RX bytes:19860 (19.8 KB) TX bytes:19860 (19.8 KB)

Ubuntu has it network interface name as eth0 while in boot time it will automatically renamed to ens33 to verify this on use the below command.

[email protected]:~# dmesg | grep -i eth [ 1.768429] e1000 0000:02:01.0 eth0: (PCI:66MHz:32-bit) 00:0c:29:31:3d:a8 [ 1.768435] e1000 0000:02:01.0 eth0: Intel(R) PRO/1000 Network Connection [ 1.778278] e1000 0000:02:01.0 ens33: renamed from eth0

In order to change Network Interface name we require to edit grub configuration file as shown below.

Add the following lines to it.

GRUB_CMDLINE_LINUX=" net.ifnames=0 biosdevname=0"

Next regenerate grub configuration file.

[email protected]:~# grub-mkconfig -o /boot/grub/grub.cfg Generating grub configuration file . Warning: Setting GRUB_TIMEOUT to a non-zero value when GRUB_HIDDEN_TIMEOUT is set is no longer supported. Found linux image: /boot/vmlinuz-4.4.0-64-generic Found initrd image: /boot/initrd.img-4.4.0-64-generic Found linux image: /boot/vmlinuz-4.4.0-21-generic Found initrd image: /boot/initrd.img-4.4.0-21-generic Found memtest86+ image: /boot/memtest86+.elf Found memtest86+ image: /boot/memtest86+.bin Done

Now open the network interface file by running the following commnad.

Add the following content to it.

auto eth0 iface eth0 inet static address 192.168.5.152 netmask 255.255.255.0 dns-nameservers 8.8.8.8 gateway 192.168.5.1

Now that’ s all just you need to reboot your system and check network interface name once again with ‘ ifconfig’ command

[email protected]:~# ifconfig eth0 Link encap:Ethernet HWaddr 00:0c:29:31:3d:a8 inet addr:192.168.5.152 Bcast:192.168.5.255 Mask:255.255.255.0 inet6 addr: fe80::fde3:373:9789:718f/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:259066 errors:0 dropped:0 overruns:0 frame:0 TX packets:157287 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:390546979 (390.5 MB) TX bytes:10853428 (10.8 MB) lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:245 errors:0 dropped:0 overruns:0 frame:0 TX packets:245 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1 RX bytes:20220 (20.2 KB) TX bytes:20220 (20.2 KB)

The network interface has been changed now. Changing the network interface was quite easy wasn’ t it? Having your network interface changed may help you a lot.

Читайте также:  Изменить язык системы линукс

Источник

Переименовываем интерфейсы в Ubuntu 18.04|20.04|22.04

network-logo

В данной статье расcкажу как можно легко переименовать сетевые интерфейсы в Ubuntu 18.04|20.04|22.04.

Ещё в Ubuntu 16.04 для настройки сети мы использовали файл /etc/network/interfaces и при помощи команды servece networking restart запускали сделанные изменения, в указанном выше файле, в работу. Но уже начиная с Ubuntu 18.04 разработчики внедрили новый тип настройки сети – NetPlan, а также пересмотрели названия сетевых интерфейсов. Это вызвало некоторые неудобства с настройкой сети. Представьте что вы используете USB-modem, который в свою очередь поднимает сетевой интерфейс, и вместо названия eth0 выдает вам что-то вроде этого: nse45trg6504 . Как вы думаете в конфигурационном файле утилиты netplan будет удобно вбивать данное название? Думаю что НЕТ!

Но как изменить название интерфейса на более привычное? Да очень просто.

Переименовываем сетевой интерфейс в Ubuntu 18.04|20.04|22.04

Запускаем терминал на нашей системе. Сделать это можно нажав ctrl+T , ну или при помощи ssh подключения.

Далее смотрим какие интерфейсы присутствуют в нашей системе, для этого вводим следующую команду:

1: lo: mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 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: ens0f1: mtu 1500 qdisc pfifo_fast state DOWN group default qlen 1000 link/ether 4c:ed:fb:da:8c:c9 brd ff:ff:ff:ff:ff:ff 

Альтернатива данной команде может быть старая команда ifconfig -a , но разработчики в сборках удалили её. Если хотите можете установить и её, для меня же она более наглядно выводит результат.

lo: flags=73 mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 inet6 ::1 prefixlen 128 scopeid 0x10 loop txqueuelen 1000 (Local Loopback) RX packets 35 bytes 4950 (4.8 KiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 35 bytes 4950 (4.8 KiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 ens0f1: flags=4099 mtu 1500 ether 4c:ed:fb:da:8c:c9 txqueuelen 1000 (Ethernet) RX packets 0 bytes 0 (0.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 

Как видно из вывода у меня в системе присутствует всего два интерфейса – это локальная петля lo и сетевой интерфейс ens0f1 . Вот как раз второй интерфейс мы и будем переименовывать.

Для этого запоминаем или скопируйте у данного интерфейса его MAC-адрес (информация в выводе выше). У меня он следующий: 4c:ed:fb:da:8c:c9

Читайте также:  Смена пользователя линукс терминал

Далее открываем файл настроек утилиты netplan:

sudo nano /etc/netplan/00-installer-config.yaml

Вот теперь внесем изменения в данный файл.

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

# This is the network config written by 'subiquity' network: version: 2 ethernets: ens0f1: dhcp4: true
# This is the network config written by 'subiquity' network: version: 2 ethernets: eth0: dhcp4: true match: macaddress: 4c:ed:fb:da:8c:c9 set-name: eth0 

После изменений вводим команду для проверки и применении настроек

если ошибок в файле не было, то должно появится вот такое окно с отчетом в 120 секунд:

 Warning: Stopping systemd-networkd.service, but it can still be activated by: systemd-networkd.socket Do you want to keep these settings? Press ENTER before the timeout to accept the new configuration Changes will revert in 120 seconds

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

Если есть вопросы, то пишем в комментариях.

Также можете вступить в Телеграм канал, ВКонтакте или подписаться на Twitter. Ссылки в шапке страницы.
Заранее всем спасибо.

RSS

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

dns_bind9

Начиная с сентября 2017 года удостоверяющим центрам предписано обязательно проверять CAA-записи в DNS перед генерацией сертификата

Сегодня установим и настроим наш файловый сервер Samba на Ubuntu Server 20.04. Расшарим директории для нашего сервера и установим на Читать

linux-logo

В этой статье я вам расскажу как изменить hostname в Debian/Ubuntu (обычно имя компьютера в сети). Существует два способа изменения Читать

network-logo

В этой статье рассмотрим пример как можно переименовать сетевые интерфейсы в дистрибутивах Linux. После обновления systemd (частью которого является udev) Читать

Источник

Persistently rename a Linux network interface without Udev / Reboot

I’ve come up with one reason to avoid udev: You’re bringing up a VM by cloning, on the first boot NICS have already been detected (named), you’ve got a couple of NICs and they came up in the wrong order. You need to rename them. You add the udev rules, but that’s just for the second boot. So you resort to the ip command. However now you have a set of udev rules that were never tested. How do you know they are right without rebooting? This is one edge-case where putting the ip commands in rc.local may be better.

3 Answers 3

Thanks to netplan (default in ubuntu 18.04) this is now particularly easy. You can set the interface name based on macaddress or driver:

Читайте также:  Linux заполнить файл нулями

Edit an existing .yaml configuration file in /etc/netplan/ or create a new one:

sudo nano /etc/netplan/config.yaml 

Here is an example with MAC address matching. Names are set with ‘set-name’ and matched by the MAC address of the interface:

network: ethernets: wan: match: macaddress: 00:ab:cd:ef:12:34 addresses: - 10.5.1.2/16 dhcp4: true optional: true set-name: wan0 lan: match: macaddress: 00:ab:cd:ef:12:45 addresses: - 10.6.1.1/16 optional: true set-name: eth0 version: 2 

Save the .yaml file and apply the configuration with:

A reboot may be required to apply the name change.

Keep in mind that netplan is just talking to udev for you. And like many of Canonical’s other really bad ideas, netplan will likely go away. I wouldn’t put too much effort into learning it.

Likely go away ? I think it is the best replacement I have ever seen for configuration. It would be a shame. Especially that the learning curve is quite flat.

@MichaelHampton just curious — do you have a specific reason to say that Netplan is going away (like a thread in a mailing list), or just commentary on Canonical’s whimsy?

Knowing the ip command is nice, but there are persistent ways to configure using existing scripts, and yes, udev.

One thing you can dois map a NIC of a specific MAC address to a name. Append something like this to /etc/udev/rules.d/70-persistent-net.rules

SUBSYSTEM=="net", ACTION=="add", ATTR=="xx:xx:xx:xx:xx:xx", NAME="eth0" 

As of 2021 there is a move away from udev rules (although they still work fine) and a move towards doing it in systemd, to keep all the network configuration in one place.

To set a persistent network device, create /etc/systemd/network/10-eth0.link with the following contents. The filename must start with a number and end with .link but the rest is not important and up to you. You need one file for each network interface you want to rename.

[Match] # This is the MAC address of the card to change. You can also # match against other properties like PCI/USB slot. MACAddress=00:11:22:33:44:55 [Link] # This is the name to assign. It must not conflict with any existing # device, so be careful if you use a name like eth0 which can fail # unexpectedly if you plug in another device that ends up on eth0 first. Name=lan0 # You can also change the MAC address at the same time if you like. # Make sure you follow the MAC address numbering rules or you can run # into problems, e.g. if you assign a broadcast MAC address by mistake. MACAddress=02:00:00:00:00:10 

At the time of writing systemd will not re-apply .link files once the system is up and running (even if you restart systemd-networkd ), so you’ll need to reboot in order to confirm it can apply the change successfully.

Источник

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