Think before you speak, read before you think.

查看路由与添加删除静态路由

by

in

静态路由可以细化,定制网络运行方式。很多时候网络走不通,也要加静态路由,指定包的转发。

显示当前的路由表

root@agent-test:~# ip route show
default via 192.168.198.2 dev eth0 
192.168.198.0/24 dev eth0  proto kernel  scope link  src 192.168.198.137

内核的路由表

root@agent-test:~# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         localhost       0.0.0.0         UG    0      0        0 eth0
192.168.198.0   *               255.255.255.0   U     0      0        0 eth0

内核的路由表,全部使用数字方式显示

root@agent-test:~# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.198.2   0.0.0.0         UG    0      0        0 eth0
192.168.198.0   0.0.0.0         255.255.255.0   U     0      0        0 eth0

添加路由,格式为 ip route add {目标网络} via {ip地址} dev {设备},如192.168.3.0/24的网络从192.168.1.254走

ip route add 192.168.3.0/24 via 192.168.1.254 dev eth0

旧命令格式为

route add -net 192.168.3.0 netmask 255.255.255.0 gw 192.168.1.254 dev eth1

以上命令立即生效,重启失效。永久静态路由

如CentOS下

#vi /etc/sysconfig/network-scripts/route-eth0

既可以如下添加一行

10.0.0.0/8 via 10.9.38.65

也可以按这种格式

ADDRESS0=192.168.0.62
NETMASK0=255.255.255.255
GATEWAY0=192.168.8.51
ADDRESS1=192.168.0.71
NETMASK1=255.255.255.255
GATEWAY1=192.168.8.51
ADDRESS2=192.168.1.0
NETMASK2=255.255.255.0
GATEWAY2=192.168.8.28

重启网络后生效

在Debian下,找到对应的interface,编辑/etc/network/interface

auto eth0
iface eth0 inet static
address 10.9.38.76
netmask 255.255.255.240
network 10.9.38.64
broadcast 10.9.38.79
### static routing ###
post-up route add -net 10.0.0.0 netmask 255.0.0.0 gw 10.9.38.65
pre-down route del -net 10.0.0.0 netmask 255.0.0.0 gw 10.9.38.65

在启动eth0时,添加一条路由,关闭时删掉对应路由即可。

除了路由的添加删除,可以使用ip route replace改变已有路由的属性。如

ip route replace default via 192.168.8.33 dev eth0

关于默认路由,在CentOS中,既可以在/etc/sysconfig/networ-scripts/ifcfg-eth0中指定gateway,也可以在/etc/sysconfig/network中指定gateway,也可以在上面的ip route add default via 192.168.8.1 dev eth0。


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *