Linux настроить сетевой мост

Bridging Ethernet Connections (as of Ubuntu 16.04)

These instructions work for current Ubuntu versions as of this writing.

  • KVM Networking — Network configuration for the KVM virtual machines server.
  • Network Connection Bridge — This page.
  • Installing bridge utilities — A similar page from a Bridge-Utils point of view.
  • Network Monitoring Bridge — An in-line sniffer page.

Please visit these sites if you need a more in-depth discussion of network bridges and the commands used here.

Why bridge?

It is possible to «bridge» two Ethernet adapters together (for example, eth0 and eth1). When you bridge two Ethernet networks, the two networks become one single (larger) Ethernet network.

One reason you would bridge Ethernet connections is to monitor traffic flowing across an Ethernet cable. For example, an inline sniffer to monitor the traffic flowing between these two devices, such as a router and the switch. (Using tools like ntop, Wireshark, and tcpdump.)

How to bridge? (short version)

The Debian wiki provides a good overview of how to use brctl and the /etc/network/interfaces file to create and set up bridges. Typing man bridge-utils-interfaces at a command prompt provides additional detail.

You can set up a simple Ethernet bridge by installing bridge-utils placing this text into /etc/network/interfaces file:

auto lo iface lo inet loopback auto br0 iface br0 inet dhcp bridge_ports eth0 eth1

Using auto br0 ensures that the bridge starts when the computer reboots, and using iface br0 inet dhcp provides the computer with its own IP address on the single (larger) Ethernet network.

You will note that auto eth0 and iface eth0 inet manual are not in the file. This is because br0 will bring up the components assigned to it.

Once you have edited the /etc/network/interfaces file, it may be easiest to reboot your computer to turn on the bridging. (It is possible to start the bridge without rebooting or logging out, but you may have some problems with the Network Connection Manager interfering with your settings.)

Bridging Ethernet Connections from the GUI

As of Ubuntu 15.04 you can bridge from the desktop using network manager. This is covered in a website at ask.xmodulo.com/configure-linux-bridge-network-manager-ubuntu.html.

Читайте также:  Vipnet client linux документация

Bridging Ethernet Connections (Step by step)

  • Your interface name. This used to be eth0 or eth1, but now we have Predictable Network Interface Names which means they could be eth0, p3p1, p2p1, enp9s0, wlp9s0, or eno16777728. (Yes, those are all real examples. Do an ifconfig from the cli to find out what Ubuntu is actually calling your nics.
  • Your IP address, subnet mask, gateway and DNS. (If not using dhcp)
  • Information about your network. (Specifically if a loop could ever be formed.)

Installing bridge-utils

sudo apt-get update sudo apt-get install bridge-utils

If you use sudo -i and enter your password, then you will not have to use sudo before each command. It may also save you some typing in the future.

Automatically Create the Bridge at Start-up

The above setup demonstrated how to create a bridge using the command line, however when you restart your computer you will lose it. To prevent this from happening, we need to edit the /etc/network/interfaces file. This file shows an example of a bridge configure via dhcp.

Sample /etc/network/interfaces file

# This file describes the network interfaces available on your system # and how to activate them. For more information, see interfaces(5). # The loopback network interface auto lo iface lo inet loopback # Bridge between eth0 and eth1 auto br0 iface br0 inet dhcp # For static configuration delete or comment out the above line and uncomment the following: # iface br0 inet static # address 192.168.1.10 # netmask 255.255.255.0 # gateway 192.168.1.1 # dns-nameservers 192.168.1.5 # dns-search example.com bridge_ports eth0 eth1 bridge_stp off bridge_fd 0 bridge_maxwait 0
sudo /etc/init.d/networking restart
  • bridge_stp off is a setting for spanning tree. If you have a possibility for network looks, you may want to turn this on.
  • bridge_fd 0 turns off all forwarding delay. If you do not know what this is, you probably do not need it.
  • bridge_maxwait 0 is how long the system will wait for the Ethernet ports to come up. Zero is no wait.

Manually Setting up the Bridge

If you do not want to use your bridge all the time (or if you do not want to break Network Manager for the times when you are not bridging) you can build a bridge by hand. Or you can script it to bring up your bridge on demand.

Ensure that both (or all) of your interfaces are installed and enabled. If they are then you may proceed at this point. For a few moments, if your computer is connected to the Internet then it will be disconnected temporarily.

Читайте также:  Vmware windows on linux or linux on windows

Open a terminal and use the following commands. Note that when interfaces are referenced, they refer to device names assigned by Linux such as «eth0» and «eth1». A bridge can be anything, but a simple name like bridge0 or br0 is suggested.

ip addr flush dev ip addr flush dev brctl addbr brctl addif   ip link set dev up

In lines 1-2 we simply prepared the devices to be bridged. In line 3, we added a new bridge named myBridge (whatever you named your bridge). In lines 4-5, we added interface1 and interface2 to myBridge. In line 6, we made the bridge operational. For more information on commands: use the Konsole command brctl

Manually creating the routing

If you manually created the bridge above, you will also need to manually give it IP address information. If you are using DHCP, running sudo dhclient br0 will get your interface up and running. If not, it is all manual.

At this point you may also want to see http://linux-net.osdl.org/index.php/Bridge at this point for a more in depth explanation of bridges and other commands within brctl.

Contributors

Websites

Editors can add any website they find that are related to this article or that they used to add to this article.

Users

Editors post their name/username and some form of contact.

Jonte Craighead, JonTec on #(K)ubuntu IRC Channel

[JonTec’s reference]: sethk on #ubuntu IRC Channel

Additions

13.Aug.06: JonTec: There was an error inside my bridge setup commands that would prevent you from adding interfaces to the bridge. I have fixed this error.

2.Nov.06 JackWasey: Is this possible between ethernet and Firewire connections? If not, what is the appropriate method?

4.Sep.12 griffin2: Added section on Ubuntu 12.04.

14.Apr.16 Lee Sharp: A lot of cleanup and realignment with other pages.

NetworkConnectionBridge (последним исправлял пользователь c-73-136-18-217 2016-04-15 03:40:47)

The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details

Источник

🐧 Как настроить сетевой мост на Ubuntu

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

Мост действует почти как сетевой коммутатор и в программном смысле используется для реализации концепции «виртуального сетевого коммутатора».

Типичный пример использования программных сетевых мостов – в среде виртуализации для непосредственного подключения виртуальных машин (ВМ) к сети хост-сервера.

Таким образом, виртуальные машины развертываются в той же подсети, что и хост, и могут получать доступ к таким службам, как DHCP и многое другое.

Читайте также:  Installing alfresco on linux

В этой статье вы узнаете, как настроить сетевой мост в Ubuntu и использовать его в среде виртуализации для создания виртуальных сетей в мостовом режиме в VirtualBox и KVM, чтобы подключить виртуальные машины к той же сети, что и хост.

Установка утилит сетевого моста в Ubuntu

Начните с установки пакета bridge-utils, который содержит утилиты для настройки моста Ubuntu Ethernet с помощью менеджера пакетов apt, как показано ниже:

$ apt-get install bridge-utils

Создание сетевого моста с использованием NetPlan на Ubuntu

Netplan – это простая и простая в использовании утилита для настройки сети на Linux с использованием формата YAML.

Внастоящее время он поддерживает NetworkManager и systemd-netword в качестве внутренних инструментов.

Чтобы настроить сеть для интерфейса, такого как мост, отредактируйте файл конфигурации netplan, находящийся в каталоге /etc/netplan/.

Ниже приведен пример файла конфигурации, где по умолчанию используется средство визуализации systemd-netword (замените enp1s0 на имя вашего интерфейса Ethernet).

network: version: 2 renderer: networkd ethernets: enp1s0: dhcp4: no bridges: br0: dhcp4: yes interfaces: - enp1s0

Сохраните файл конфигурации и примените ее, чтобы включить сеть типа мост, выполнив следующую команду.

Если вы хотите отключить или деактивировать созданный сетевой мост, удалите его с помощью следующих команд.

$ sudo ip link set enp1s0 up $ sudo ip link set br0 down $ sudo brctl delbr br0 или $ sudo nmcli conn up Wired\ connection\ 1 $ sudo nmcli conn down br0 $ sudo nmcli conn del br0 $ sudo nmcli conn del bridge-br0

Создание сетевого моста с помощью Nmcli в Ubuntu

nmcli – широко используемый инструмент командной строки для администрирования NetworkManager (создания, отображения, редактирования, удаления, активации и деактивации сетевых подключений) и отображения состояния сетевого устройства.

Чтобы создать сетевой мост с помощью nmcli, выполните следующую команду.

$ sudo nmcli conn add type bridge con-name br0 ifname br0

Затем добавьте интерфейс Ethernet в качестве порта в мост, как показано (не забудьте заменить enp1s0 на имя вашего устройства).

$ sudo nmcli conn add type ethernet slave-type bridge con-name bridge-br0 ifname enp1s0 master br0

Затем подтвердите, что мост был создан, показав все сетевые подключения.

$ sudo nmcli conn show --active

Затем активируйте соединение следующим образом (вы можете использовать либо имя соединения / интерфейса, либо UUID).

$ sudo nmcli conn up br0 или $ sudo nmcli conn up e7385b2d-0e93-4a8e-b9a0-5793e5a1fda3

Затем отключите интерфейс или соединение Ethernet.

$ sudo nmcli conn down Ethernet\ connection\ 1 или $ sudo nmcli conn down 525284a9-60d9-4396-a1c1-a37914d43eff

Теперь попробуйте просмотреть активные соединения еще раз, интерфейс Ethernet теперь должен быть нужном нам соединении bridge.

$ sudo nmcli conn show --active

Источник

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