Теперь более реалистичный пример. Имеется два аплинка до двух провайдеров, необходимо обеспечить доступность сервера с обоих каналов:
В качестве маршрута по умолчанию используется один из провайдеров, не важно какой. При этом веб-сервер будет доступен только через сеть этого провайдера. Запросы через сеть другого провайдера приходить будут, но ответные пакеты будут уходить на шлюз по умолчанию и ничего из этого не выйдет.
Решается это весьма просто:
Определяем таблицы:
# ip route add default via 11.22.33.1 table 101 # ip route add default via 55.66.77.1 table 102
# ip rule add from 11.22.33.44 table 101 # ip rule add from 55.66.77.88 table 102
Думаю теперь уже объяснять смысл этих строк не надо. Аналогичным образом можно сделать доступность сервера по более чем двум аплинкам.
# ip route replace default scope global \ nexthop via 11.22.33.1 dev eth0 weight 1 \ nexthop via 55.66.77.1 dev eth1 weight 1
Эта запись заменит существующий default-роутинг в таблице main. При этом маршрут будет выбираться в зависимости от веса шлюза ( weight ). Например, при указании весов 7 и 3, через первый шлюз будет уходить 70% соединений, а через второй – 30%. Есть один момент, который при этом надо учитывать: ядро кэширует маршруты, и маршрут для какого-либо хоста через определенный шлюз будет висеть в таблице еще некоторое время после последнего обращения к этой записи. А маршрут до часто используемых хостов может не успевать сбрасываться и будет все время обновляться в кэше, оставаясь на одном и том же шлюзе. Если это проблема, то можно иногда очищать кэш вручную командой ip route flush cache .
Допустим нам нужно, чтобы пакеты на 80 порт уходили только через 11.22.33.1. Для этого делаем следующее:
# iptables -t mangle -A OUTPUT -p tcp -m tcp --dport 80 -j MARK --set-mark 0x2 # ip route add default via 11.22.33.1 dev eth0 table 102 # ip rule add fwmark 0x2/0x2 lookup 102
Первой командой маркируем все пакеты, идущие на 80 порт. Второй командой создаем таблицу маршрутизации. Третьей командой заворачиваем все пакеты с указанной маркировкой в нужную таблицу.
Опять же все просто. Рассмотрим также использование модуля iptables CONNMARK. Он позволяет отслеживать и маркировать все пакеты, относящиеся к определенному соединению. Например, можно маркировать пакеты по определенному признаку еще в цепочке INPUT, а затем автоматически маркировать пакеты, относящиеся к этим соединениям и в цепочке OUTPUT. Используется он так:
# iptables -t mangle -A INPUT -i eth0 -j CONNMARK --set-mark 0x2 # iptables -t mangle -A INPUT -i eth1 -j CONNMARK --set-mark 0x4 # iptables -t mangle -A OUTPUT -j CONNMARK --restore-mark
Пакеты, приходящие с eth0 маркируются 2, а с eth1 – 4 (строки 1 и 2). Правило на третьей строке проверяет принадлежность пакета к тому или иному соединению и восстанавливает маркировки (которые были заданы для входящих) для исходящих пакетов.
Надеюсь изложенный материал поможет вам оценить всю гибкость роутинга в Linux. Спасибо за внимание 🙂
Part of the skill set for any Linux user, and particularly a systems administrator, is the ability to perform some network tweaks on a Linux system. This includes adding and deleting routes to enable the system to communicate with other systems o a local network. In this guide, we explore exactly how you can go about adding and deleting routes on a Linux system.
Before we embark on adding or deleting routes, it’s prudent to check the existing default routes on a system. To do so, simply launch your terminal and issue the command:
$ ip route show Or $ ip route list
Similar statistics can be displayed using route command,
Also, you can use the good old netstat command, which is usually used for printing interface statistics as well as the routing table to achieve the same result.
With the default routing statistics in mind, let’s now move a step further and add some routes to our system.
Suppose you want to take a backup of a Linux machine and push the backup file to another backup server in the subnet 10.0.2.0/24 . However, for one reason or the other, you cannot reach the backup server via the default gateway. In this case, you will have to create a new route for backup server subnet via another IP, say 192.168.43.223 via the interface enp0s3 .
The command for this will be
$ sudo ip route add 10.0.2.0/24 via 192.168.43.223 dev enp0s3
You can confirm whether new static route add been in route table using “ip route show” command.
To add the specific IP of the backup server, say 10.0.2.15 run the command:
$ sudo ip route add 10.0.2.15 via 192.168.43.223 dev enp0s3
Once again, you can check the routing changes to see if the changes exist using the ip route show command:
The routes we have just added are temporary and will not survive a reboot. To make the routes persistent, you need to manually add them.
In the /etc/sysconfig/network-scripts/ directory, create an interface file route-interface where the interface attribute is your network interface name. In our case, this will be route-enp0s3 .
$ vim /etc/sysconfig/network-scripts/route-enps03
Next, we will add the routes as shown:
10.0.2.0/32 via 192.168.43.1 10.0.2.15 via 192.168.43.1
Save the file and exit. Then restart NetworkManager Service
$ sudo systemctl restart NetworkManager
For Debian distributions, edit the file /etc/network/interfaces
$ sudo vim /etc/network/interfaces
Append the following line:
up route add -net 10.0.2.0 netmask 255.255.255.0 gw 192.168.43.1 dev enp0s3
Save and exit the file. Finally, for the changes to come into effect, run below commands
$ sudo ifdown enp0s3 && sudo ifup enp0s3
To delete a specific route, use the ip route del command. For example, to remove the route address we just added, run the command:
$ sudo ip route del 10.0.2.0/24 via 192.168.43.223 dev enp0s3
To delete a single IP route in a subnet run the command
$ sudo ip route del 10.0.2.15 via 192.168.43.223 dev enp0s3
To delete default route run:
$ sudo ip route del default
To add a default route run below ‘ip route add’ command,
$ sudo ip route add default via dev interface
$ sudo ip route add default via 192.168.43.1 dev eth0
We hope that this tutorial was informative and provided you with insights into how you can go about adding and deleting static route in Linux.
Also Read : 12 ip Command Examples for Linux Users
Adblock