Как поменять шлюз в linux

How can I change the default gateway?

Currently I’m running a FreeBSD 9.1 and the default gateway is already configured in the rc.conf . rc.conf :

7 Answers 7

route del default route add default 1.2.3.4 

Where 1.2.3.4 is the new gateway. You can even concatenate them onto the same line with a ;

Edit: This is FreeBSD, not Linux. The command is different. Please do not edit this Answer if you haven’t read the Question carefully enough to determine the operating system being used.

Note: do this in console, not over ssh. If you must do this via ssh (or other network method), issue both commands at once, with ; or with &&

Or, use the generic safe method: 1) Log into a shell, shutdown/reboot in 15 minutes unless cancelled 2) Do unsafe things. 3) Cancel shutdown/reboot.

On Linux the commands ip route del default and ip route add default via 1.2.3.4 work. So the command is still relevant for Linux users too as it has quite a bit of resemblance.

You can add a new default route and remove the old one using either the ip or route command. The commands below will replace the gateway with 192.0.2.1. Both command pairs do the same thing. FreeBSD and other OSs should have one or both programs, possibly with slightly different formats. (FreeBSD has the route command and excludes the gw keyword used in other implementations.) The commands man ip and/or man route should provide you with documentation on your specific implementation.

route add default 192.0.2.1 route del default 10.0.0.1 ip route add default via 192.0.2.1 ip route del default via 10.0.0.1 

There are multiple implementations of these commands, so the above may not match your implementation. Your implementation should have a man page with examples for common use cases such as adding and removing default gateways. Try man route and man ip to see how your implementation works.

Change 192.0.2.1 to your desired default gateway. The default gateway needs to be on one of networks you have a direct connection to. You can change your IP address in a similar manner. ip is a newer tool which will do most everything you need to do to view and manage IP addresses and routing on IPv4 and IPv6 networks. ifconfig is an an older tool for configuring IP addresses on an IPv4 network.

Читайте также:  What is escape character in linux

To make the change permanent, update your network configuration files in /etc . The file(s) vary depending on the distribution you are using.

At least one of these commands should be available on any Unix derived O/S. Different versions may work slightly differently. Check the man page for details on your O/S.

Источник

[РЕШЕНО] Как в ubuntu поменять шлюз по умолчанию

И немного о том как вообще понять какой дефолтный шлюз установлен в вашей убунте:
1. ip route
пример:
default via 10.112.11.1 dev eth0
10.112.11.0/24 dev eth0 proto kernel scope link src 10.112.11.4 metric 100
169.254.0.0/16 dev eth0 scope link metric 1000

пример:
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.0.254 0.0.0.0 UG 0 0 0 enp4s0
192.168.0.0 0.0.0.0 255.255.255.0 U 0 0 0 enp4s0

И немного о том что значит flag UG на против шлюза по умолчанию:

U : UP— indicates that the route is up and valid
H : Host— target is to a host
G : Gateway—means that the route is to a gateway
R : Reject— It is set by ARP when an entry is expired
D : Dynamic— Route added by a routing redirect
M : Modified— Route modified by a routing redirect

если команда роут не найден то установите:
sudo apt install net-tools

Основной шлюз (установленный по умолчанию, default gateway) — является главным, он обрабатывает все пакеты данных, которые отправляются узлом за пределы его локальной сети в интернет или просто в другую подсеть. Т.е. если ПК не знает куда отправлять пакеты данных, то он обращается к основному сетевому шлюзу. (не знает, это значит нет подключенного маршрута или более точного)

И маршрут к шлюзу прописывается как наименее точный 0.0.0.0 через Основной шлюз
При этом других маршрутов может быть сколько угодно много и если не найден более точный то запрос идет на 0.0.0.0 который будет указывать на дефолтный GW

Источник

How to Set the Default Gateway on Ubuntu

All the devices on your network rely on the default gateway for communication. Data packets pass through the router to and from your network before being routed to the particular device that owns the packet.

Читайте также:  Mounting filesystem in linux

Each operating system comes with a default gateway. However, you can temporarily or permanently change the default gateway to add another route for your network devices. You can use the IP command on Ubuntu to modify your default gateway.

Checking the Default Gateway

Changing the default gateway is common when you have different sub-networks or when you must point a specific machine to a particular gateway. Before changing the default gateway, let’s list the available routes.

Use the list option with the IP command or its shorthand r to stand for the route.

The default gateway has the default keyword in it. If you configured multiple routes on your network, you can use the grep command to filter the router and get the default gateway.

Use the following command:

The current default gateway is 192.168.88.1 on enp0s3 interface. Let’s proceed to set a new default gateway.

How to Set a New Default Gateway

The ip command uses the route option to set the new default gateway. You must specify the type of route that you want to add. In our case, it’s “default”.

For instance, let’s set the default gateway as 192.168.88.10.

Suppose we want to set the default gateway for a particular network interface. In that case, specify the network interface after the gateway. In our case, the interface is enp0s3.

Note that we must add sudo to use the administrator privileges since we are editing the routing table for Ubuntu which is an administrative task.

We can use the list or route options to verify the newly added default gateway.

Note how the currently added default gateway is the one that we specified earlier. In the previous output, we now have two default gateways. The keynote is that the changes we made are temporary until you add them to the network manager configuration files.

In the previous case, we can delete the added gateway such that we remain with only one.

Use the delete keyword to remove the added gateway.

If we check the available default gateway after running the delete command, we confirm that we only have one default gateway remaining which is 192.168.88.1.

Читайте также:  Dpkg команда в линуксе

Suppose we want to make the permanent network changes to implement the new gateway. We must edit the configuration file. Open the network manager file using a file editor of your choice. In this case, let’s use gedit with the following command:

Add the new gateway using the following presented format. Make sure that the spacing is set to two whitespaces with the correct indention. Once edited, save the file and exit the editor.

Before applying the changes using the netplan command, run a dry test.

If you are sure with the new network configuration, press the enter key. Otherwise, the changes will revert to the previous settings after the specified seconds.

Conclusion

Ubuntu comes with a default gateway, but that doesn’t mean that you can’t set a new gateway. This guide covered everything about adding a new gateway using the ip command and how to save the changes permanently to the configuration file.

About the author

Denis Kariuki

Denis is a Computer Scientist with a passion for Networking and Cyber Security. I love the terminal, and using Linux is a hobby. I am passionate about sharing tips and ideas about Linux and computing.

Источник

Как добавить или сменить шлюз по умолчанию в Linux

wikiHow работает по принципу вики, а это значит, что многие наши статьи написаны несколькими авторами. При создании этой статьи над ее редактированием и улучшением работали, в том числе анонимно, 10 человек(а).

Количество просмотров этой статьи: 66 154.

Основной шлюз (шлюз по умолчанию) — это IP-адрес вашего маршрутизатора. Обычно он автоматически определяется операционной системой во время установки, но, возможно, вам нужно изменить его. Это особенно актуально, если в сети есть несколько сетевых адаптеров или маршрутизаторов.

С помощью терминала

Изображение с названием Add or Change the Default Gateway in Linux Step 1

Изображение с названием Add or Change the Default Gateway in Linux Step 2

Найдите адрес активного основного шлюза. Для этого введите route и нажмите ↵ Enter . В строке «default» (по умолчанию) отобразится адрес основного шлюза, а назначенный ему интерфейс можно найти в правой части таблицы.

Изображение с названием Add or Change the Default Gateway in Linux Step 3

  • Введите sudo route delete default gw IP-адрес Адаптер . Например, чтобы удалить основной шлюз 10.0.2.2 адаптера eth0 , введите sudo route delete default gw 10.0.2.2 eth0 .

Изображение с названием Add or Change the Default Gateway in Linux Step 4

Введите sudo route add default gw IP-адрес Адаптер . Например, чтобы изменить основной шлюз адаптера eth0 на 192.168.1.254, введите sudo route add default gw 192.168.1.254 eth0 . Вам будет предложено ввести пароль пользователя, чтобы выполнить команду.

Источник

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