linux添加和删除路由练习
查看当前路由表
[root@C ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.20.0 192.168.20.100 255.255.255.0 UG 0 0 0 eth0
192.168.20.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
10.0.1.0 192.168.20.100 255.255.255.0 UG 0 0 0 eth0
192.168.30.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1
169.254.0.0 0.0.0.0 255.255.0.0 U 1002 0 0 eth0
169.254.0.0 0.0.0.0 255.255.0.0 U 1003 0 0 eth1
添加默认网关
[root@C ~]# route add default gw 192.168.20.100
[root@C ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.20.0 192.168.20.100 255.255.255.0 UG 0 0 0 eth0
192.168.20.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
10.0.1.0 192.168.20.100 255.255.255.0 UG 0 0 0 eth0
192.168.30.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1
169.254.0.0 0.0.0.0 255.255.0.0 U 1002 0 0 eth0
169.254.0.0 0.0.0.0 255.255.0.0 U 1003 0 0 eth1
0.0.0.0 192.168.20.100 0.0.0.0 UG 0 0 0 eth0
Linux下静态路由修改命令
方法一:
添加路由
route add -net 192.168.0.0/24 gw 192.168.0.1
route add -host 192.168.1.1 dev 192.168.0.1
删除路由
route del -net 192.168.0.0/24 gw 192.168.0.1
add 增加路由
del 删除路由
-net 设置到某个网段的路由
-host 设置到某台主机的路由
gw 出口网关 IP地址
dev 出口网关 物理设备名
增加默认路由
route add default gw 192.168.0.1
默认路由一条就够了
方法二:
添加路由
ip route add 192.168.0.0/24 via 192.168.0.1
ip route add 192.168.1.1 dev 192.168.0.1
删除路由
ip route del 192.168.0.0/24 via 192.168.0.1
也可以使用下面方式,删除到某个子网的路由
route del -net 10.0.1.0/24
add 增加路由
del 删除路由
via 网关出口 IP地址
dev 网关出口 物理设备名
增加默认路由
ip route add default via 192.168.0.1 dev eth0
via 192.168.0.1 是我的默认路由器
查看路由信息
ip route
方法2操作如下
[root@C ~]# ip route add 10.0.2.0/24 via 192.168.20.100
[root@C ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.20.0 192.168.20.100 255.255.255.0 UG 0 0 0 eth0
192.168.20.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
10.0.1.0 192.168.20.100 255.255.255.0 UG 0 0 0 eth0
10.0.2.0 192.168.20.100 255.255.255.0 UG 0 0 0 eth0
192.168.30.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1
169.254.0.0 0.0.0.0 255.255.0.0 U 1002 0 0 eth0
169.254.0.0 0.0.0.0 255.255.0.0 U 1003 0 0 eth1
0.0.0.0 192.168.20.100 0.0.0.0 UG 0 0 0 eth0
[root@C ~]#
上面设置都是临时生效,重启后失效
如果想要永久生效,可以在/etc/rc.local中添加命令,开启添加路由
也可以在配置文件中设置 在network的启动脚本里有下面信息
if [ -f /etc/sysconfig/static-routes ]; then
其中,static-routes就是设置路由的地方,因此可以先创建此文件,然后添加路由
如加入:
route add -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.1
则static-routes的格式为
any net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.1