How to routing linux

Маршрутизация в Linux

Материал из Xgu.ru

Linux предоставляет большой набор функций для маршрутизации и инструменты для ее настройки. Ядро 2.6.x поддерживает:

  • Простую статическую маршрутизацию.
  • Equal Cost Multi Path маршруты (маршруты до одной сети с одинаковым весом, которые выбираются с равной вероятностью).
  • Blackhole-маршруты.
  • Множественные таблицы маршрутизации.
  • Policy Based Routing

Содержание

[править] Команды

Для управления маршрутизацией применяются следующие команды: route, netstat, ip (последняя из пакета iproute2, возможно его придется установить).

Просмотреть таблицу можно следующими способами:

При этом следует учитывать, что доступ ко всем возможностям дает только ip. Используя route вы не только не сможете настроить «продвинутые» функции вроде политик маршрутизации, но и не увидите их существование в выводе команды просмотра, если они уже настроены в системе. Поэтому следует по возможности использовать ip.

Модификация таблицы маршрутизации:

[править] Использование route

[править] Использование ip

Синтаксис ip по структуре напоминает синтаксис Cisco IOS. Любые опции могут быть сокращены до потери двусмысленности, например «ip ro ad» вместо «ip route add».

Командой вида ip route add blackhole 10.56.50.0/27 можно добавить «зануленный» маршрут (аналог «ip route . null0» в Cisco). Пакеты в сеть с таким маршрутом будут удалены с причиной «No route to host». Может быть полезно для подавление DoS-атаки с хоста или иных подобных случаев.

[править] Действия с маршрутами

Кроме add также поддерживаются и другие действия:

  • del — удалить маршрут.
  • replace — заменить маршрут другим.
  • change — изменить параметры маршрута.

[править] Equal Cost Multi Path

Если добавить два маршрута до одной и той же сети с одинаковой метрикой, ядро начнет распределять нагрузку между ними путем выбора того или другого с равной вероятностью. Работает и для более чем двух маршрутов. Предупреждение: это может вызвать проблемы со входящими соединениями, потому что иногда ответ может пойти по другому маршруту, чем пришел запрос. Будьте осторожны.

[править] IPv6

Настройка маршрутизации IPv6 почти идентична настройке для IPv4.

В некоторых дистрибутивах еще есть нерешенная проблема с маршрутом по умолчанию (например, старые версии RHEL), используйте

[править] Просмотр маршрутов до определенной сети

На маршрутизаторах с длинной таблицей может быть неудобно просматривать вывод «ip route show» в поисках нужного маршрута. В этом случае можно использовать команду вида:

которая выведет маршруты только до указанной сети.

[править] Пересылка пакетов между интерфейсами

Linux позволяет разрешить или запретить пересылку пакетов между интерфейсами (forwarding). На рабочих станциях и серверах приложений ее можно запретить, на маршрутизаторах или межсетевых экранах она, очевидно, должна быть разрешена.

За этот параметр для IPv4 отвечает переменная net.ipv4.ip_forward (1 = «разрешить», 0 = «запретить»).

Для IPv6 используйте net.ipv6.conf.all.forwarding

Чтобы настройки сохранились после перезагрузки, пропишите значения net.ipv4.ip_forward и net.ipv6.conf.all.forwarding в /etc/sysctl.conf.

[править] Конфигурационные файлы

Настройки статической маршрутизации находятся в различных файлах, в зависимости от дистрибутива.

  • Debian GNU/Linux: /etc/network/interfaces
  • RHEL/CentOS/Scientifix: etc/sysconfig/network-scripts/route-
  • Gentoo: /etc/conf.d/net

(добавьте свои дистрибутивы, пожалуйста)

[править] Policy routing

Для хоста 192.168.1.1 используется особенная таблица маршрутизации (table 3), не такая как для всех остальных хостов. В ней указан единственный маршрут — маршрут по умолчанию.

Все будут ходить через шлюз 10.0.1.2, а 192.168.1.1 — через 10.0.3.4.

Источник

ip route add network command for Linux explained

H ow do I use ip route networking command to add a static route on Linux operating systems? Can you explain how to use the ip command?

Introduction: The ip command is used to assign an address to a network interface and/or configure network interface parameters on Linux operating systems. This command replaces old good and now deprecated ifconfig command on modern Linux distributions. A static route is nothing but a way of specifying traffic that must not go through the default gateway. One can use the ip command for adding a static route to a different network that cannot be accessed through your default gateway. For example, VPN gateway or VLNAN might need to use the ip command.

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements ip command on Linux
Est. reading time 3 minutes

ip route add network command examples

The syntax is pretty simple:
ip route add via
ip route add dev
ip route add default dev
ip route add default via

Add a static route on Linux

You must login as root user with the help of su command or sudo command:
$ su —
OR
$ sudo -i
Once become a root user, setup a temporary route using the ip command:
# ip route add 172.10.1.0/24 via 10.0.0.100 dev eth0
Verify it:
# ip r
Here is another example where I am setting up route for my VPN gateway:
# ip link set dev tun0 up mtu 1500
# ip addr add dev tun0 10.8.0.2/24 broadcast 10.8.0.255
# ip route add 139.59.2.125/32 via 192.168.2.254
# ip route add 0.0.0.0/1 via 10.8.0.1
# ip route add 128.0.0.0/1 via 10.8.0.1
Again view route with the ip command:
# ip r

Warning : Do not stop networking service over ssh session.

How to add a permanent static route using ip command on Linux

Edit config file such as /etc/sysconfig/network-scripts/route-eth0 on a CentOS/RHEL/Fedora Linux for interface eth0 using a text editor such as nano command or vim command:
# vim /etc/sysconfig/network-scripts/route-eth0
Append the following text:
172.10.1.0/24 via 10.0.0.100 dev eth0
Save and exit (close) the file in a vim text editor. Finally, restart your network service on a CentOS/RHEL/Fedora Linux so they take effect:
# systemctl restart network.service

Restarting network service on a CentOS/RHEL/Fedora Linux

A note about ip command and persistence static routing on a Debian/Ubuntu

Edit your /etc/network/interfaces file for say eth0:
# vi /etc/network/interfaces
Update it as follows:

Источник

Linux route Add Command Examples

I am a new Linux user. How do I add a new or default gateway using route command on Linux operating systems? How can I use route command to show or set a new route on Linux based server or desktop system?

In Linux and Unix-like system, a gateway is nothing but device that connects two networks. Often it is called a router or gateway. In most cases your ISP’s modem act as a default router or gateway. You can use any one of the following tool to add, display, delete Linux kernel routing table:

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements Linux with ip or route command
Est. reading time 3 mintues
  1. route command : show / manipulate the IP routing table on Linux.
  2. ip command : show / manipulate routing, devices, policy routing and tunnels on Linux.

Display your current routing table

Open the Terminal or login to server using ssh/console. Type the following command to display routing table:
# route
OR
# route -n
Sample outputs:

Fig.01: Display routing table using route command

Fig.02: ip command in action

Linux route Add Command Examples

I am going to show you both ip and route command. Most modern Linux distro recommend and use the ip command for setting or displaying default gateway IP address on Linux. Let us see some examples.

Linux add a default route using route command

Route all traffic via 192.168.1.254 gateway connected via eth0 network interface:
# route add default gw 192.168.1.254 eth0

Linux add a default gateway (route) using ip command

Route all traffic via 192.168.1.254 gateway connected via eth0 network interface:
# ip route add 192.168.1.0/24 dev eth0

Verify newly added route ip in the Linux kernel routing table

To verify new routing table, enter:
# ip route list
OR
# route -n

Verify new route

Use the ping command to verify connectivity to your router or external network:
# ping your-router-ip-here
# ping your-ISPs-Gateway-ip-here
# ping 192.168.1.254
# ping www.cyberciti.biz
You should able to ping public IP address too:
ping 1.1.1.1
ping 8.8.8.8
And use the dig command or host command to resolve domain names provided that /etc/resolv.conf configured with correct DNS server names:
host www.cyberciti.biz
host google.com
dig www.cyberciti.biz

How do I make routing changes persistent across reboots?

To make route entry persistent in the Linux kernel routing table, you need to modify config file as per your Linux distributions.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

RHEL/CentOS/Fedora/Scientific Linux persistent routing configuration

Edit /etc/sysconfig/network and set default gateway IP address:
# vi /etc/sysconfig/network
Sample outputs:

You can add additional static route for eth0 by editing /etc/sysconfig/network-scripts/route-eth0 file as follows:

The above config sets static routing for network 10.0.0.0/8 via 10.9.38.65 router.

Debian / Ubuntu Linux persistence static routing configuration

Edit /etc/network/interfaces file, enter:
# vi /etc/network/interfaces
Append the following in eth0 section:

Save and close the file.

Generic method to add persistent static routing on Linux

The following method works with almost all Linux distributions. However, on systemd based Linux distro, see how to enable /etc/rc.local with systemd tutorial for more info.

Edit /etc/rc.d/rc.local or /etc/rc.local , enter
# vi /etc/rc.local
Append the following line:

Summing up

You learned how to add routing on Linux. See

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Changes to survive a reboot can be set in
/etc/sysconfig/networking/devices/route-ethX

Other profiles for switching between different configurations can be found in
/etc/sysconfig/networking/profiles/default/route-ethX

I have a problem , my default route will go away when i reboot my system, regarding to this matter that all info was issued under interface network-script.

Please advice,
Momo.

add configuration file

Can you please let me know how to add the route command in Linux.

Hi
add the route command in linux

# route add -net 10.10.1.1/24 ethx
Alternate is by ip command
# ip route add 10.10.2.2/24 ethx
after that configure gateway,netmask and ip in route-ethx file located in /etc/sysconfig/network-scripts dir.

it worked ..thanks

Adding the route command in Linux

Route traffic via 192.168.0.5 gateway destined to 192.168.1.16 :

route add -net 192.168.1.16 netmask 255.255.255.240 gw 192.168.0.5

This will handle all the traffice from your client systems destined to the 192.168.1.16 subnet.
The resources that will be accessed are in the range 192.168.1.16 – 192.168.1.30

I have tried it on Suse Linux, and i belive other flavors are similar or close to this .

Thank you very much this works

To add default route for a host:
#route add 192.168.0.1 gw 10.0.0.1
“where 192.168.0.1 is destination host, gw commad to specify gateway and 10.0.0.1 is the gateway to destination host. (Test on Feroda 11)”

Another way to add route at startup (testing on CentOS)

edit file /etc/rc.d/rc.local (add to end of file your route):
/sbin/route add -net 192.168.11.0 netmask 255.255.255.0 gw 10.0.0.1

After reboot check your route table:
/sbin/route

Thanks Alex. You saved my day. On CentOS this was needed

i want to add below command in Linux server.but here it is showing error

[root@plnotxsmsc01 rc.d]# route add -net 10.202.11.0 gw 10.102.13.241
bash: route: command not found
[root@plnotxsmsc01 rc.d]#

[root@plnotxsmsc01 rc.d]# uname -a
Linux plnotxsmsc01 2.6.18-128.el5xen #1 SMP Wed Dec 17 12:01:40 EST 2008 x86_64 x86_64 x86_64 GNU/Linux
[root@plnotxsmsc01 rc.d]#

please try /sbin/route or locate where the route is

route add -net 192.168.0.0 netmask 255.255.0.0 gw 192.168.1.1

The routing information above is not persistent across reboots. After a reboot, the routing information will be lost and you need to add them in again.

To make the routing information persistent, add the “route add” line as seen above into the /etc/rc.local file.

Sample /etc/rc.local file.

#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don’t
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
route add -net 192.168.0.0 netmask 255.255.0.0 gw 192.168.1.1

Yes Alex, your comment was also what I needed.

Thank you so much for that!

how to find remote systems gateway with out login

i want to add below command in Linux server.but here it is showing error

[root@zmocmp1 sbin]# route add -net 10.26.66.0 netmask 255.255.255.192 gw 0.0.0.0
SIOCADDRT: Invalid argument
[root@zmocmp1 sbin]#

and how to make routing information persistent,

please assign valid gateway it will work….

Hi,
I want to do ping6 to another linux machine..I added inet6 address in both the linux machine in the main LAN interface..bt ping6 is not wrking. “Destination Unreachable is coming”. So,For that when i tried to add route to ipv6 thorough a gateway,using the command ” /sbin/route -A inet6 add 2000::/64 gw 2000:db8:0:bbbb::1 ” is is telling invalid command..pls help me with this and how can i rectify it.

Muchas gracias me ayudo bastante, saludos desde México…

awsome explanation!! love it

check the routes #route

route add -net netmask gw

after add permanent route entry
create a file vi /etc/sysconfig/network-scripts/route-eth0

after add route entry this format

ADDRESS0=
NETMASK0=
GATEWAY0=

ADDRESS1=
NETMASK1=
GATEWAY1=

ADDRESS2=
NETMASK2=
GATEWAY2=

En los sistemas RHEL/CentOS/Fedora/Scientific Linux la configuración de la ruta por defecto (default gateway) se guarda en /etc/sysconfig/network y las rutas estáticas en /etc/sysconfig/network-scripts/route-ethX (siendo X el número de la placa de red, verbigracia eth0 para la primer placa red).

En los sistemas Debian / Ubuntu Linux la configuración de la ruta por defecto (default gateway) se guarda en /etc/network/interfaces y las rutas estáticas se pueden agregar bajo a sección eth0 o bien en el archivo /etc/rc.local junto con las definiciones de ejecuciones de archivos locales al inicio del sistema.

Lic. Matias Colli
Perito Judicial en Informática
RHCSA

how to add the route in lubuntu
route add 172.18.0.0 mask 255.255.0.0 192.168.1.100 -p also how to check the route table. the application needs IE siebel framework. need solution

Источник

Читайте также:  Share windows folder with linux virtualbox
Оцените статью