linux下永久添加静态路由

在linux下永久添加静态路由有两种方法:

一、添加路由的命令

1、route add

route add -net 192.56.76.0 netmask 255.255.255.0 dev eth0    #添加一条静态路由
route add default gw 192.168.0.1        #添加默认路由
route del -net 192.168.1.0/24 gw 192.168.0.1        #删除一条路由
route -n                          #查看路由表

2、ip ro add

ip ro add 192.56.76.0/24 dev 192.168.0.1     # 添加一条静态路由
ip ro add default via 192.168.0.1 dev eth0     # 添加默认路由
ip ro del 192.168.1.0/24                             #  删除一条路由
ip route show                                 # 查看路由表

3、常见参数:

add 增加路由
del 删除路由
via 网关出口IP地址
dev 网关出口物理设备名

二、让路由重启服务器后依然生效:

1、在/etc/rc.local里面添加:

添加路由命令为:直接将在命令行操作的命令复制到该文件中,保存退出即可。

2、在/etc/sysconfig/static-routes文件里面写入:

如果该文件不存在,则手动创建,添加内容格式为:
参照/etc/init.d/network文件里面的shell语句:

# Add non interface-specific static-routes.
if [ -f /etc/sysconfig/static-routes ]; then
   grep "^any" /etc/sysconfig/static-routes | while read ignore args ; do
   /sbin/route add -$args
done
fi

则,如果要添加一条静态路由,命令为:
route add -net 192.56.76.0 netmask 255.255.255.0 dev eth0
那么,在/etc/sysconfig/static-routes文件中添加格式为:

any -net 192.56.76.0 netmask 255.255.255.0 dev eth0

3、两种方式添加静态路由对比:

(1)、rc.local:

重启服务器生效;
重启网络服务,则静态路由失效;
rc.local是系统启动后最后运行的一个脚本,因此如果有如NFS需要网络才能挂载的服务需求,则该方式不适合;

(2)、static-routes:

重启服务器生效;
重启网络服务生效:
适合需要网络需求的服务;

脚本添加静态路由的方法和rc.local就差不多了:
这种方法其实也是自己写脚本,放在/etc/rc3.d/ 开头设置为S。
S意思是启动,数字是顺序,K意思是停止。
一般是启动是守护进程在某个模式的启动顺序。
数字越小启动的顺序越靠前;
/etc/rc3.d是文本多用户环境,一般生产环境都是这个环境。

其坏处也是:重启网络后失效。

三、总结:

如果需要添加静态路由,尽量将静态路由添加到/etc/sysconfig/static-routes文件中。避免因重启网络服务导致路由失效,从而避免故障的发生。

猜你喜欢

转载自blog.51cto.com/moerjinrong/2139112