云服务器Centos7添加静态路由

  • 来源:网络
  • 更新日期:2020-05-06

摘要:  一、ip route显示和设定路由   1、显示路由表  [root@centos7~]# ip route show  default via 192.168.150.254 dev enp0s3 proto static metric 1024  192.168.

一、ip route显示和设定路由
  1、显示路由表
  [root@centos7 ~]# ip route show
  default via 192.168.150.254 dev enp0s3  proto static  metric 1024
  192.168.150.0/24 dev enp0s3  proto kernel  scope link  src 192.168.150.110
  太难看了,格式化一下(显示的是默认网关和局域网路由,两行的内容没有共通性):
  [root@centos7 tmp]# ip route show|column -t
  default           via  192.168.150.254  dev    enp0s3  proto  static  metric  1024
  192.168.150.0/24  dev  enp0s3           proto  kernel  scope  link    src     192.168.150.110
  2、添加静态路由
  复制代码
  [root@centos7 ~]# ip route add 10.15.150.0/24 via 192.168.150.253 dev enp0s3
  [root@centos7 ~]#
  [root@centos7 ~]# ip route show|column -t
  default           via  192.168.150.254  dev    enp0s3  proto  static  metric  1024
  10.15.150.0/24    via  192.168.150.253  dev    enp0s3  proto  static  metric  1
  192.168.150.0/24  dev  enp0s3           proto  kernel  scope  link    src     192.168.150.110
  [root@centos7 ~]#
  [root@centos7 ~]# ping 10.15.150.1
  PING 10.15.150.1 (10.15.150.1) 56(84) bytes of data.
  64 bytes from 10.15.150.1: icmp_seq=1 ttl=63 time=1.77 ms
  64 bytes from 10.15.150.1: icmp_seq=1 ttl=63 time=1.08 ms
  64 bytes from 10.15.150.1: icmp_seq=1 ttl=63 time=1.57 ms
  ^C
  复制代码
  3、删除静态路由
  只需要把 add 替换成 del,或者更简单的只写目标网络
  [root@centos7 ~]# ip route del 10.15.150.0/24
  二、设置永久的静态路由
  1、添加永久静态路由
  ip route 指令对路由的修改不能保存,重启就没了。把 ip route 指令写到 /etc/rc.local 也是徒劳的。
  RHEL7官网文档没有提到 /etc/sysconfig/static-routes,经测试此文件已经无效;
  /etc/sysconfig/network 配置文件仅仅可以提供全局默认网关,语法同 Centos6 一样: GATEWAY=<ip address> ;
  永久静态路由需要写到 /etc/sysconfig/network-scripts/route-interface 文件中,比如添加两条静态路由:
  [root@centos7 ~]# vi /etc/sysconfig/network-scripts/route-enp0s3
  10.15.150.0/24 via 192.168.150.253 dev enp0s3
  10.25.250.0/24 via 192.168.150.253 dev enp0s3
  重启计算机,或者重新启用设备enp0s3才能生效。
  [root@centos7 ~]# nmcli dev connect enp0s3
  一般直接连接一次设备即可,如果不成功就先断开设备再连接设备,注意必须两个指令一起运行,否则,,,,,,你晓得。
  [root@centos7 ~]# nmcli dev disconnect enp0s3 && nmcli dev connect enp0s3
  2、清除永久静态路由
  可以删除 ifcfg-enp0s3文件或者注释掉文件里的相应静态路由条目,重启计算机。
  想要让修改后的静态路由立即生效,只能用 ip route del 手工删除静态路由条目。
  实验的过程中出现两个奇怪的现象:
  1)有时候路由生效了但是在 ip route show 却没有显示,重启计算机后是肯定显示的,原因暂时不明。
  2)存在多个网卡时,默认路由似乎是随机经由某个网卡设备。检查了所有连接配置文件后发现,第一网卡的默认连接配置文件 ifcfg-eth0 设置了GATEWAY0(此设置会覆盖/etc/sysconfig/network 定义的全局默认网关),第二网卡的连接配置文件 ifcfg-eth1 使用的是dhcp,会在启动时也分配默认网关,两个默认网关让计算机糊涂了。这是在测试系统里经常发生的现象,生产系统一般不会让网卡用dhcp,或者即使是用了也会仔细分配默认网关防止冲突。
  其他需要注意的:
  1)连接配置文件 ifcfg-* 里可以设置多个GATEWAY,一般第一个是 GATEWAY0,然后GATEWAY1, GATEWAY2... ,尾号最大的有效;
  2)如果必须在/etc/sysconfig/network 文件定义全局网关,连接配置文件 ifcfg-* 就不要设置GATEWAY了,dhcp的连接要注意dhcp服务器不要定义默认网关。
  3)ifcfg-enp0s3 文件改名为 ifcfg-eth0 后,route-enp0s3 文件也要改名为 route-eth0。