Linux静态路由配置

  配置了多块网卡后,需要指定数据包由哪块网卡发送,否则可能无法访问内网,这就要用到静态路由了。

  配置静态路由有多种方式:

  1、修改 /etc/rc.local 文件,这样每次重启后就会自动添加,如:

    echo "route add default gw 10.0.2.2 dev eth0" >> /etc/rc.local

    echo "route add -net 192.168.100.0 netmask 255.255.255.0 dev eth1" >> /etc/rc.local

    此方法有个弊端:使用 service network restart 重启网络后,静态路由失效

  2、[推荐]查看网络启动脚本 : /etc/init.d/network 发现有如下命令:    

 # 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    
if [ -f /etc/sysconfig/static-routes ] , -f 意思是存在 /etc/sysconfig/static-routes 且为普通文件,则执行下面的语句
  grep "^any" /etc/sysconfig/static-routes 将 any 开头的行取出
  while read ignore args 执行后 ignore="any" args=其他
  
/sbin/route add -$args 添加路由的命令

  现在可以加入我们自己的静态路由,查看 static-routes 格式如下:

    any net 192.168.100.0 netmask 255.255.255.0 dev eth1
    any net 0.0.0.0 netmask 0.0.0.0 gw 10.0.2.2 dev eth0

  然后重启网络,路由还在:
[root@centos1 ~]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.100.0   0.0.0.0         255.255.255.0   U     0      0        0 eth1
10.0.2.0        0.0.0.0         255.255.255.0   U     0      0        0 eth0
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         10.0.2.2        0.0.0.0         UG    0      0        0 eth0

  

posted @ 2015-06-08 11:55  葡萄不吐皮  阅读(905)  评论(0编辑  收藏  举报