route、ip route修改默认网关和静态路由

Linux系统的route命令用于显示和操作IP路由表。要实现两个不同的子网之间的通信,需要一台连接两个网络的路由器,或者同时位于两个网络的网关来实现.

在Linux系统中,设置路由通常是为了解决以下问题:该Linux系统在一个局域网中,局域网中有一个网关,能够让机器访问Internet,那么就需要将这台机器的IP地址设置为Linux机器的默认路由。

要注意的是,直接在命令行下执行route命令来添加路由,不会永久保存,当网卡重启或者机器重启之后,该路由就失效了;可以在/etc/rc.local中添加route命令来保证该路由设置永久有效。

  • 添加路由
    1
    2
    3
    4
    5
    6
    [root@eve ~]# route add -net 172.16.0.0/24 gw 192.168.10.1 
    #到172.16.0.0网段的数据走网关192.168.10.1
    [root@eve ~]# route add -host 172.16.61.172 dev eth0
    #到172.16.61.172这台主机的数据走设备eth0
    [root@eve ~]# route add -host 172.16.61.172 gw 192.168.10.1
    #到172.16.61.172这台主机的数据走网关 192.168.10.1
  • 删除路由
    1
    [root@eve ~]# route del -host 172.16.61.172 dev eth0

其中,add为增加路由,del为删除路由,-net为设置到某个网段的路由,-host为设置到某台主机的路由,gw为出口网关IP地址,dev为出口网关或物理设备名

  • 增加默认路由
    1
    2
    3
    4
    5
    6
    [root@eve ~]# route -n
    Kernel IP routing table
    Destination Gateway Genmask Flags Metric Ref Use Iface
    0.0.0.0 192.168.10.1 0.0.0.0 UG 100 0 0 eth0
    10.0.0.0 0.0.0.0 255.0.0.0 U 101 0 0 eth1
    192.168.10.0 0.0.0.0 255.255.255.0 U 100 0 0 eth0
    1
    route add default gw 10.0.139.1
    1
    2
    3
    4
    5
    6
    7
    [root@eve ~]# route -n
    Kernel IP routing table
    Destination Gateway Genmask Flags Metric Ref Use Iface
    0.0.0.0 10.0.139.1 0.0.0.0 UG 0 0 0 eth1
    0.0.0.0 192.168.10.1 0.0.0.0 UG 100 0 0 eth0
    10.0.0.0 0.0.0.0 255.0.0.0 U 101 0 0 eth1
    192.168.10.0 0.0.0.0 255.255.255.0 U 100 0 0 eth0

也可以使用ip route命令

  • 添加路由
    1
    2
    [root@eve ~]# ip route add 10.39.0.0/24 via 10.0.139.1
    [root@eve ~]# ip route add 10.39.39.39 dev eth0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    [root@eve ~]# route -n
    Kernel IP routing table
    Destination Gateway Genmask Flags Metric Ref Use Iface
    0.0.0.0 10.0.139.1 0.0.0.0 UG 0 0 0 eth1
    0.0.0.0 192.168.10.1 0.0.0.0 UG 100 0 0 eth0
    10.0.0.0 0.0.0.0 255.0.0.0 U 101 0 0 eth1
    10.39.0.0 10.0.139.1 255.255.255.0 UG 0 0 0 eth1
    10.39.39.39 0.0.0.0 255.255.255.255 UH 0 0 0 eth0
    192.168.10.0 0.0.0.0 255.255.255.0 U 100 0 0 eth0
  • 删除路由
    1
    ip route del 10.39.0.0/24 via 10.0.139.1
    其中,add为增加路由,del为删除路由,via为网关出口ip地址,dev为网关出口或物理设备名。
  • 增加默认路由
    1
    [root@eve ~]# ip route add default via 192.168.10.1 dev eth0

route、ip route修改默认网关和静态路由
http://www.evec.cc/2021/09/14/linux-route/
作者
前夕
发布于
2021年9月15日
许可协议