- 6 different commands to restart network in RHEL/CentOS 7/8
- Some Background and Changes with RHEL/CentOS 8
- How to check if interface is configured with NetworkManager
- Method 1: Using systemctl restart NetworkManager
- Method 2: Using ifup and ifdown
- On RHEL/CentOS 8 with NetworkManager
- On RHEL/CentOS 8 without NetworkManager
- Method 3: Using nmcli networking
- Method 4: using nmcli con up and down
- Method 5: Using nmtui
- Method 6: Using systemctl restart network
- Conclusion
- Related Posts
- 2 thoughts on “6 different commands to restart network in RHEL/CentOS 7/8”
- Не стартует Netwokring на Debian9
- Cет между win7 и Debian10 Buster
6 different commands to restart network in RHEL/CentOS 7/8
Table of Contents
In this tutorial I will share different methods you can use to restart your network with RHEL/CentOS environment. I will cover both RHEL/CentOS 7 and 8 releases as with RHEL/CentOS 8 there are some major changes in terms of how networking is handled. Now Red Hat is completely moving towards Network Manager and is trying to ditch the legacy initscripts.
Some Background and Changes with RHEL/CentOS 8
If you are coming from RHEL/CentOS 5 or 6 then you will be familiar with SysV scripts to restart any service i.e.
With RHEL/CentOS 7 the SysV scripts are deprecated (although you may still use these commands but they can be removed any time and shouldn’t be used). Now all the system services, partitions, sockets are handled by systemd. But that is a different topic altogether, now with RHEL/CentOS 7 we used
But with RHEL/CentOS 8 we get below error for this command
This is because with RHEL/CentOS 7, the network scripts were part of initscripts rpm, which is removed as part of RHEL/CentOS 8 and is migrated to network-scripts rpm
I have already written a detailed guide on this topic and the steps to use legacy network restart commands.
Now considering all these changes, we have multiple methods which we can use to restart network in RHEL/CentOS release. But before we jump there, let us understand if our interface is managed by NetworkManager or not as your command and steps to restart network would vary accordingly.
How to check if interface is configured with NetworkManager
There are couple of methods to verify if your Ethernet is configured via NetworkManager or manually using ip command or some other method:
Use nmcli con show to list the active connections
If you can see your interface in the output then it means that the interface is configured with NetworkManager
Alternatively grep for NM_CONTOLLED in /etc/sysconfig/network-scripts/ifcfg-ethXX
It is also possible you get a blank output, in such case you can use nmcli to verify but most likely the interface was configured with NetworkManager which is why you don’t see any entry for NM_CONTROLLED .
So now you know if your interface is configured via NetworkManager or not.
Method 1: Using systemctl restart NetworkManager
You can use nmcli or nmtui to configure your network. Once the network configuration is done, you can use systemctl to restart the NetworkManager service
This should update your network changes. But if your network is not managed by NetworkManager , this command will do no change to your interface configuration.
Method 2: Using ifup and ifdown
Use this command with precaution as this can bring down your active interface which you may be using for SSH connections locking you out of the system. The only way to recover the network access by connecting to your server via console.
On RHEL/CentOS 8 with NetworkManager
With RHEL/CentOS 8, the ifup and ifdown commands are part of NetworkManager rpm unlike older releases where these were part of initscripts rpm.
So since you are using NetworkManager , you can also use ifup and ifdown to refresh the network configuration of any interface. For example you did some changes for eth1 , so to refresh the changes first bring down the interface and then bring it up
This should update your network configuration.
On RHEL/CentOS 8 without NetworkManager
On RHEL/CentOS 8 if your network interface is not managed by NetworkManager then you must install network-scripts to be able to use ifup and ifdown command.
Next you can check the rpm ownership for ifup
Now ifup is part of both NetworkManager and network-scripts rpm. Next you can use ifdown eth1 && ifup eth1
Similar WARN is visible for ifup action.
Since network-scripts is added just to support fallback behaviour, it throws WARNING every time you use ifup or ifdown without NetworkManager .
Method 3: Using nmcli networking
We can also use the command-line tool » nmcli networking » for controlling NetworkManager to restart network and update network configuration.
This command will bring down all the NetworkManager interfaces and then will bring them up.
IMPORTANT: It is important that you execute the command in this format as if you try to execute separately then your server may become unreachable as the first command will bring down all the NetworkManager managed interfaces
Method 4: using nmcli con up and down
With nmcli we can also use nmcli con up or con down similar to traditional ifup and ifdown to de-activate and activate individual network interface instead of restarting all the networking interfaces on the server.
IMPORTANT: It is important that you execute the command in this format as if you try to execute separately then your server may become unreachable as the first command will bring down all the NetworkManager managed interfaces
Method 5: Using nmtui
We also have NetworkManager TUI which is an alternative to nmcli command. Users who are not comfortable with nmcli command line, they can use nmtui to manage their network
To de-activate or activate a network interface using nmtui , execute nmtui as root user on the Linux server terminal
This should open a window, next select «Activate a Connection» to update the network configuration
Select the interface which you would wish to deactivate and re-activate.
Next Activate the respective interface
Once your interface is active, you can come back and exit the nmtui session.
Method 6: Using systemctl restart network
With RHEL/CentOS 8, the initscripts rpm has been deprecated hence this command will not work by default. We must manually install network-scripts rpm from the RHEL/CentOS 8 repository to be able to restart network using this command.
Next you should be able to use the legacy command even on RHEL/CentOS 8 to restart your network interface
Conclusion
In this tutorial I shared different possible methods to restart network service and individual network cards on different Red Hat and CentOS distributions. Red Hat is now pushing the usage of NetworkManager and legacy initscripts is already deprecated. We can expect the network-scripts support to also be dropped in near future so you should already start switching to NetworkManager in your environment.
Lastly I hope the steps from the article to restart network on RHEL/CentOS 7/8 Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
2 thoughts on “6 different commands to restart network in RHEL/CentOS 7/8”
How do I configure 2 different networks on one NIC and avoid the reverse path filtering nightmare? On my laptop I have one onboard NIC. I have 2 networks I have to push data across: 192.168.9.x/24 w/gtwy and 22.142.4.x/26 w/ no gtwy as a second address in NetworkManager. But it dies not work. I have set net.ipv4.all.rp_filter=2 (loose)
I am not sure if I understand your question. If you want to create two networks using single interface then you would need virtual LAN
Источник
Не стартует Netwokring на Debian9
Всем привет! Вчера вечером я не успел(забыл) продлить месячную оплату и сервер был отключен, а сегодня утром оплатил и сервак стал активным. Однако, как обнаружилось 4 из 6-ти дополнительных IPv4 не пингуются из внешних источников.
Не помогает ни одна команда:
Зачем конфиги? Вы смотрите ip-адреса на интерфейсах. Если они (все шесть) назначены, значит networking.service отработал и проблема где-то ещё.
Если надо, то выложу конфиг /etc/network/interfaces
Покажите
и заодно выхлоп ip a
хочу сказать, что вполне вероятно конфиг написан с некоторыми ошибками, однако в таком виде все работало более полгода. И за эти полгода были такие же случаи отключения за неуплату, а потом активация после оплаты, и все работало хорошо
хочу сказать, что вполне вероятно конфиг написан с некоторыми ошибками, однако в таком виде все работало более полгода.
Мы не знаем что у вас работало там «полгода». И как оно работало.
Но ругань в логах идет на defgw
Если вам действительно нужно разные defgw то используйте pbr. Но раз вы написали про хостинг, то думаю оно должно робить через первый выданный. Если нет, то это странный хостинг.
Ребята, прошу помочь!
Действительно, на этом хостинге шлюзы для разных Ай Пи разные.
194.93.0.19 — 255.255.255.0 — 194.93.0.1
193.47.33.12 — 255.255.255.0 — 193.47.33.1
91.188.222.249 — 255.255.255.0 — 91.188.222.1
2.58.98.234 — 255.255.255.0 — 2.58.98.1
2.58.98.191 — 255.255.255.0 — 2.58.98.1
2.58.98.29 — 255.255.255.0 — 2.58.98.1
Вот сейчас из 4-х ошибок осталось 2
Вот новый конфиг
Ты не можешь добавить в одну таблицу маршрутизации несколько маршрутов default, только если с разными метриками. Но работать это будет не совсем так, как тебе, скорее всего, нужно.
Для того, что бы пакеты с разных IP ходили через свой шлюз тебе нужно создать несколько таблицы маршрутизации, в каждой описать нужный шлюз и далее написать ip rule правила для перенаправления нужных тебе пакетов в нужную таблицу маршрутизации.
А то сейчас ты говоришь добавь маршрут default в main через один шлюз, далее добавляешь опять же в main маршрут default через другой шлюз, но в main запись default уже есть и это приводит к ошибке.
address 172.16.1.113/32 — не уверен что так можно писать нужно отдельно писать address и отдельно netmask.
В правилах мог ошибиться читай сам.
/sbin/ip route add default via 2.58.98.1 metric 1
/sbin/ip route add default via 2.58.98.1 metric 1
/sbin/ip route add default via 193.47.33.1 metric 2
И? Чего достичь хотим-то ? Прежде чем «прыгать» хотя бы основы изучите.
Эх вот оно. Даже ЕГЭ и то отменили. Куда катиться мир.
Действительно, на этом хостинге шлюзы для разных Ай Пи разные.
Это вам честно хостер сказал? Или вы так подумали?
Эх вот оно… Даже ЕГЭ и то отменили. Куда катиться мир…
И я не знаю куда он может катиться, но в предложении «Куда катится мир…» мягкого знака в глаголе нет. 😉
А я и не скрывал и не скрываю, что у меня ещё с детсада, по русскому минус один.
да-да у меня был ылитный детсад в ссср, нас ещё дошколят учили 🙂 По математике 5 а русский на уровне -1. Хотя сочинения на 5. У меня потом в школе стандартно было 5 за изложение и 1 за русский 🙂
БЛЕ. ТЬ. Все работает. Работает мой первоначальный конфиг!
Оказывается все дело было в порядке следования, сначала все IPv4 eth0, а потом все IPv6 eth0
sudo /etc/init.d/networking restart
# sudo service networking restart
Пффф, а когда это работало дебиан? Ifdwn, ifup
Я нажал на кнопку А и заработало Б.
Вот потом от таких спамерюг весь инет и страдает. (
Спасибо, г-н infomeh за дельный совет.
Cет между win7 и Debian10 Buster
В локалке не было сети между win7 и Debian10 Buster. Интернет работал отлично на всех машинах. Компы в сети видели только себя
Настраивал сеть на debiane
/etc/network/interfaces был пуст
sudo systemctl restart networking Выдавал ошибку
$ systemctl restart networking Job for networking.service failed because the control process exited with error code. See «systemctl status networking.service» and «journalctl -xe» for details.
systemctl status networking.service показал что сервис не активен
$ systemctl status networking.service ● networking.service — Raise network interfaces Loaded: loaded (/lib/systemd/system/networking.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2020-11-12 16:14:04 MSK; 1min 20s ago Docs: man:interfaces(5) Process: 1967 ExecStart=/sbin/ifup -a —read-environment (code=exited, status=1/FAILURE) Main PID: 1967 (code=exited, status=1/FAILURE)
Вписал в пустой /etc/network/interfaces
# interfaces(5) file used by ifup(8) and ifdown(8) # Include files from /etc/network/interfaces.d: source-directory /etc/network/interfaces.d
# The loopback network inteface auto lo iface lo inet loopback
# The primary network interface auto enp3s0 iface enp3s0 inet dhcp
enp3s0 это новое название интерфейса eth0. когда в инете нарыл, что в новом дебиане изменились имена вписал в iface имя которое было в статье enp0s3. Но сеть не запустилась. Проверил имя
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: enp3s0:
mtu 1500 qdisc mq state UP group default qlen 1000 link/ether d4:3d:7e:ea:7b:cf brd ff:ff:ff:ff:ff:ff inet 10.0.0.3/24 brd 10.0.0.255 scope global dynamic noprefixroute enp3s0 valid_lft 86143sec preferred_lft 86143sec inet6 fe80::d9bb:b9b2:cc4d:f835/64 scope link noprefixroute valid_lft forever preferred_lft forever
Увидел что на моём компе название интерфейса enp3s0 (Интересно, у каждого компа своё?) Исправил имя в /etc/network/interfaces на правильное. И Ура! Сеть заработала!Компы вмдятся, папки шарятся! Простите, если написал скомкано. Первый раз на техфоруме выкладываю текст. Лет 8 на дебиане. Больших проблем не было, вернее инфы было много. А вот с новой 10 версией проблемка была. Лопатил инфу неделю пока запустил сеть, думаю другим пригодиться!
Источник