- How to Restart Network Interface in Linux
- Restart Network Interface Using Command Lines in Linux (generic method)
- Debian / Ubuntu Linux restart network interface
- Redhat (RHEL) / CentOS / Fedora / Suse / OpenSuse Linux – Restart network interface in Linux
- Slackware Linux restart commands
- How to see status of network/networking service
- Перезапуск сети в Ubuntu
- Перезагрузка сети в Ubuntu
- Перезапуск сети в NetworkManager
- Команды ifup и ifdown
- Выводы
- How To Start / Stop / Restart / Enable / Reload The Network Service In Linux?
- What Is Network Manager?
- 1) How To Start The Network Service In Linux?
- 2) How To Stop The Network Service In Linux?
- 3) How To Restart The Network Service In Linux?
- 4) How To Reload The Network Service In Linux?
- 5) How To View The Network Service Status In Linux?
- 6) How To Enable The Network Service On Boot In Linux?
- 3 ways to configure a network interface in Linux
- More Linux resources
- At installation time
- Настройка сети в Linux через конфиг-файлы, ч.1
How to Restart Network Interface in Linux
Restart Network Interface Using Command Lines in Linux (generic method)
The procedure to to turn off eth0 interface is as follows. Run:
# ifdown eth0
To turn on eth0 interface run:
# ifup eth0
See ip address info using the ip command:
# ip a show eth0
Debian / Ubuntu Linux restart network interface
To restart network interface, enter:
sudo /etc/init.d/networking restart
To stop and start use the following option (do not run them over remote ssh session as you will get disconnected):
sudo /etc/init.d/networking stop
sudo /etc/init.d/networking start
Debian/Ubuntu Linux with systemd, run:
$ sudo systemctl restart networking
Redhat (RHEL) / CentOS / Fedora / Suse / OpenSuse Linux – Restart network interface in Linux
To restart network interface, enter:
# /etc/init.d/network restart
To stop and start use the following option (do not run them over remote ssh session as you will get disconnected):
# /etc/init.d/network stop
# /etc/init.d/network start
Fedora/RHEL/CentOS/Suse Linux with systemd, run:
$ sudo systemctl restart network
Slackware Linux restart commands
Type the following command:
/etc/rc.d/rc.inet1 restart
You can take down or restart particular interface such as eth1 as follows:
# /etc/rc.d/rc.inet1 eth1_restart
# /etc/rc.d/rc.inet1 eth1_start ### start eth1 ###
# /etc/rc.d/rc.inet1 eth1_stop ### stop eth1 ###
How to see status of network/networking service
Run command:
$ sudo systemctl status network #CentOS/RHEL/Fedora/Suse
$ sudo systemctl status network #Debian/Ubuntu
Sample outputs:
Источник
Перезапуск сети в Ubuntu
В Ubuntu и Debian инициализацией сетевых интерфейсов и настройкой сети занимается специальная сетевая служба — networking. Информация о конфигурации сетевых интерфейсов хранится в файле /etc/network/interfaces.
Если вы что-либо измените в этом файле, нужно будет перезапустить сеть, чтобы применить изменения. В этой статье мы рассмотрим как выполнить перезапуск сети Ubuntu 16.04.
Перезагрузка сети в Ubuntu
Можно, конечно, выполнить полную перезагрузку компьютера, но это не совсем удобно если можно просто перезапустить сеть Ubuntu. Для перезапуска сети используйте следующую команду:
sudo service networking restart
В современных дистрибутивах уже давным давно используется система инициализации Systemd, поэтому можно использовать команду systemctl вместо команды service:
sudo systemctl restart networking.service
Кроме того, можно перезапустить NetworkManager, это тоже помогает, если сеть настроена через него:
sudo systemctl restart NetworkManager
Перезапуск сети в NetworkManager
Чаще всего, для управления сетью в современных дистрибутивах используется программа Network Manager. Можно сразу же использовать ещё для наших целей. Просто отключите, а затем включите сеть обратно следующими командами:
sudo nmcli networking off
sudo nmcli networking on
После отключения сети значок NetworkManager пропадёт с панели, а потом снова появится после включения. Аналогично, вы можете использовать NetworkManager в графическом интерфейсе. Кликните по его иконке, выберите нужное сетевое подключение и нажмите Выключить:
Затем включите его обратно.
Команды ifup и ifdown
Эти команды работают на более низком уровне, они управляют непосредственно самими сетевым интерфейсами. Для перезапуска сети мы можем отключить все интерфейсы, а затем включить обратно:
Вы не увидите никаких изменений в графическом интерфейсе, но когда сетевой интерфейс будет отключён, вы не будете иметь доступа к интернету.
Выводы
Как видите, не всегда обязательно перезагружать компьютер после изменений настроек, в большинстве случаев достаточно перезапустить только нужный сервис. Надеюсь, эта информация была вам полезной.
Источник
How To Start / Stop / Restart / Enable / Reload The Network Service In Linux?
systemd is a new system and service manager for Linux system, which was implemented/adapted into all the major Linux distributions over the traditional SysV init systems due to lots of issue/improvement has to be on SysVinit systems.
All the service files are available on /etc/init.d/ directory for SysVinit system.
For systemd system, the service files are available on /usr/lib/systemd/system/ directory.
If you would like to perform any kind of actions like start, stop, restart, enable, reload & status against the specific service then use the following commands.
Make sure that you should have admin privileges to run these commands except status command. It should be root or sudo permission needed to run the below commands.
What Is Network Manager?
NetworkManager is a dynamic network control and configuration system that attempts to keep network devices and connections up and active when they are available.
NetworkManager can be used to configure the following types of connections: Ethernet, wireless, mobile broadband (such as cellular 3G), and DSL and PPPoE (Point-to-Point over Ethernet).
1) How To Start The Network Service In Linux?
Use the below commands to start the networking server in Linux.
For SysVinit Systems – RHEL based systems such as Redhat, CentOS and Fedora.
For systemd Systems – RHEL based systems such as Redhat, CentOS and Fedora.
For systemd Systems – Debian based systems such as Debian and Ubuntu.
2) How To Stop The Network Service In Linux?
Use the below commands to stop the networking server in Linux.
For SysVinit Systems – RHEL based systems such as Redhat, CentOS and Fedora.
For systemd Systems – RHEL based systems such as Redhat, CentOS and Fedora.
For systemd Systems – Debian based systems such as Debian and Ubuntu.
3) How To Restart The Network Service In Linux?
Use the below commands to restart the networking server in Linux.
For SysVinit Systems – RHEL based systems such as Redhat, CentOS and Fedora.
For systemd Systems – RHEL based systems such as Redhat, CentOS and Fedora.
For systemd Systems – Debian based systems such as Debian and Ubuntu.
4) How To Reload The Network Service In Linux?
Use the below commands to reload the networking server in Linux.
For SysVinit Systems – RHEL based systems such as Redhat, CentOS and Fedora.
For systemd Systems – RHEL based systems such as Redhat, CentOS and Fedora.
For systemd Systems – Debian based systems such as Debian and Ubuntu.
5) How To View The Network Service Status In Linux?
Use the below commands to view the networking server status in Linux.
For SysVinit Systems – RHEL based systems such as Redhat, CentOS and Fedora.
For systemd Systems – RHEL based systems such as Redhat, CentOS and Fedora.
For systemd Systems – Debian based systems such as Debian and Ubuntu.
6) How To Enable The Network Service On Boot In Linux?
Use the below commands to enable the networking server on boot in Linux.
For SysVinit Systems – RHEL based systems such as Redhat, CentOS and Fedora.
For systemd Systems – RHEL based systems such as Redhat, CentOS and Fedora.
For systemd Systems – Debian based systems such as Debian and Ubuntu.
Источник
3 ways to configure a network interface in Linux
More Linux resources
Editor’s note: This article was written while James Brigman was a member of the Red Hat Accelerator program.
Almost any useful work that one would want to do with a Linux system requires a network interface. Want to browse the web, watch YouTube, stream video, audio or files? It’s all done over the network interface. RPM-based Linux distributions using Gnome have several fundamental ways to configure the network interface. I’m describing three ways in this article. All of the configuration methods require the entry of sets of numbers that allow the network interface to operate.
You will need three fundamental pieces of numerical information in order to minimally configure a network interface to work over IPv4 and more if you want to define things like IPv6, hostnames, or DNS servers. This article covers the bare minimum for IPv4. Those three fundamental numerical pieces are:
IP Address: The unique number defining the access point to your network interface. It has the form: xxx.xxx.xxx.xxx, where “xxx” are three, or fewer, numbers between 0 and 255. It’s possible for this number to be purely made up, but normally it takes a form that works with the other three numbers. If you are using a home router with DHCP, which is the typical default configuration, the router will “assign” the IP address to your network interface. You won’t have to enter the number at all.
Gateway: The unique number assigned to the network interface at the «other end of the wire» that your computer must communicate through. Again, it has the general xxx.xxx.xxx.xxx format and takes a form that also works with the other two numbers. If you are using a home router, your home router generates this number because it is the gateway through which you communicate with the wider world.
Netmask: The non-unique number that defines the network itself. This number can be automatically generated but is sometimes requested by the method you use to configure the interface. It, too, has the format xxx.xxx.xxx.xxx.
Note that I’m not going into the how of these numbers; I’m just telling you they are needed to configure the network interface. I’ll skip that so you can get on into the point of the article: Three ways to configure network interfaces. In each case, the numbers I use will be real numbers applicable to the system I used to write this article. I used CentOS 8 to generate the images, but everything you see here is the same in Fedora and Red Hat Enterprise Linux.
At installation time
The Anaconda installer prompts for network configuration and you can’t complete the installation without providing these numbers to the installer. Here’s the initial screen, using “Network & Host Name” in the rightmost column, third selection down:
Источник
Настройка сети в 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 и заслужила (на мой взгляд) более пристального внимания 🙂
Источник