Linux change network interface names

Changing Network Interfaces name Ubuntu 16.04

I tried to change network interfaces name on this new Ubuntu 16.04 LTS version but doesn’t have the /etc/udev/rules.d/70-persistent-net.rules . So, I tried to use /lib/udev/write_net_rules but it not exist. Why do I need this modification? Because I’m using a tool to Simulate virtual platforms that use flex licensing and the authentication need to be in eth0 interface name. Any suggestion? The command ip link returns:

user@laptop:~$ ip link 1: lo: mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: enp6s0: mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT group default qlen 1000 link/ether b8:2a:xx:yy:xx:yy brd ff:ff:ff:ff:ff:ff 3: wlp7s0: mtu 1500 qdisc mq state UP mode DORMANT group default qlen 1000 link/ether 5c:e0:xx:yy:xx:yy brd ff:ff:ff:ff:ff:ff user@laptop:~$ ifconfig enp6s0 Link encap:Ethernet HWaddr b8:2a:xx:yy:xx:yy lo Link encap:Local Loopback wlp7s0 Link encap:Ethernet HWaddr 5c:e0:xx:yy:xx:yy 

4 Answers 4

There is a lot of misleading information about how to change network names in recent versions of Ubuntu. Some information points to systemd.link, which is just wrong because Ubuntu (as of 16.04) does not use this part of systemd.

Actually, changing interface name works nearly like it used to, with two small differences: First, the file /etc/udev/rules.d/70-persistent-net.rules now has to be created manually. This has the advantage that you do not have to worry about any script overwriting this file and can simply add the lines that you need (you do not need any comments either). Second — and this is the change that cost me a lot of time to figure it out — the format changed slightly compared to Ubuntu 14.04 LTS:

The line for fixing the interface name of the NIC with MAC address «02:01:02:03:04:05» to «eth0» is now:

SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR=="02:01:02:03:04:05", ATTR=="0x0", ATTR=="1", NAME="eth0" 

This line looks nearly the same as in Ubuntu 14.04 LTS with one slight difference: In Ubuntu 14.04, there was the additional condition KERNEL==»eth*» . For some reason, this does not work in Ubuntu 16.04 LTS. If this additional condition is present, the whole line is ignored and you are back to the default behavior (as specified in 80-net-setup-link.rules ).

Bingo! I now have enusb01 for my USB Docking Station’s NIC. Thanks! # USB Display Link Docking Station SUBSYSTEM==»net», ACTION==»add», DRIVERS==»?*», ATTR

==»8c:ae:4c:fa:92:bf», ATTR==»0x0″, ATTR==»1″, NAME=»enusb1″

How can I set the name to enp0s1 from enp0s17 ? Is it the same process ? Also, what should I do for virtual network-interfaces like enp0s1:1 or enp0s2 etc. ?

You don’t really need to specify all of that in 16.04. I was able to get away with SUBSYSTEM==»net», ACTION==»add», ATTR

==»xx:xx:xx:xx:xx:xx», NAME=»eth0″

@kbuilds, per Linux From Scratch: DRIVERS==»?*» — This exists so that Udev will ignore VLAN or bridge sub-interfaces (because these sub-interfaces do not have drivers). These sub-interfaces are skipped because the name that would be assigned would collide with their parent devices.

Читайте также:  Linux environment variables home directory

Important: you need to edit /etc/network/interfaces to make sure the renamed interface gets automatically started. Otherwise, if you’re on SSH — you will lose access to that machine, not to mention waste time trying to figure out why it doesn’t work.

On Ubuntu 16.04.1 LTS, Linux plaptop 4.4.0-31-genericx86_64 MATE. step one of @Geancarlo Abich answer and it worked. Ubuntu created a new names directly after reboot:

Edit your /etc/default/grub changing the line from

GRUB_CMDLINE_LINUX="net.ifnames=0 biosdevname=0" 
msa@plaptop:~$ ifconfig eth0 Link encap:Ethernet HWaddr 70:5a:0f:d7:03:38 inet addr:10.67.10.43 Bcast:10.67.10.255 Mask:255.255.255.0 inet6 addr: fe80::8c03:edb5:a3d1:ba21/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:63129 errors:0 dropped:0 overruns:0 frame:0 TX packets:37788 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:51115719 (51.1 MB) TX bytes:5006758 (5.0 MB) Interrupt:16 Memory:f1200000-f1220000 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:255 errors:0 dropped:0 overruns:0 frame:0 TX packets:255 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1 RX bytes:21076 (21.0 KB) TX bytes:21076 (21.0 KB) wlan0 Link encap:Ethernet HWaddr 44:85:00:62:c6:e5 inet addr:10.67.14.106 Bcast:10.67.14.255 Mask:255.255.255.0 inet6 addr: fe80::5844:f9dd:32ff:9b45/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:25 errors:0 dropped:0 overruns:0 frame:0 TX packets:86 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:5320 (5.3 KB) TX bytes:14611 (14.6 KB) 

Источник

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:

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.

Читайте также:  Linux basics for hackers

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

Источник

Переименовываем интерфейсы в 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 . Вот как раз второй интерфейс мы и будем переименовывать.

Читайте также:  Как пользоваться suse linux

Для этого запоминаем или скопируйте у данного интерфейса его 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) Читать

Источник

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