我們有時候會遇到兩個網絡的情況,一個是內部私有的辦公網絡,一個是對外的網絡,為了安全兩個網絡不能互相通訊,而在兩個網絡間要架一台雙網卡的linux服務器,
通過在內網PC上訪問服務器,而服務器將具體數據與公網進行交換,達到內部用戶不用切換網絡,就可以方便、安全的訪問服務器,具體的網絡拓撲如下圖
具體的網卡配置如下
一號網卡,此網卡接外網
[root@MasServer network-scripts]# cat ifcfg-eth0
DEVICE=eth0
BOOTPROTO=static
IPADDR=192.168.0.2
NETMASK=255.255.255.0
GATEWAY=192.168.0.1
ONBOOT=yes
TYPE=Ethernet
二號網卡,此網卡接內網
[root@MasServer network-scripts]# cat ifcfg-eth1
DEVICE=eth1
BOOTPROTO=static
IPADDR=192.168.254.2
NETMASK=255.255.255.0
ONBOOT=yes
TYPE=Ethernet
如此配置后,linux系統的路由表如下
[root@MasServer ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.0.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
192.168.254.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 0 0 0 eth1
0.0.0.0 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
但是如此配置並不能達到我們想要的效果,我們可以通過linux系統ping一下內網網關測試
[root@MasServer root]# ping 192.168.254.1
PING 202.112.14.152 (192.168.251.1) 56(84) bytes of data.
--- 192.168.251.1 ping statistics ---
9 packets transmitted, 0 received, 100% packet loss, time 8016ms
這是因為存在一條默認路由(紅色標記),linux會把所有從私網上傳輸過來的數據,通過eth0傳輸出去,而不會通過eth1返回到私網上。為此
我們要添加一條靜態路由,告訴系統,將私網上的數據強行通過eth1口返回。我們可以用以下命令
[root@MasServer ~]# route add -host 192.168.254.1 dev eth1
添加私網上的網關地址,強行制定內網的數據從eth1口返回。添加以后,查看Linux系統的路由表
[root@MasServer ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.254.1 0.0.0.0 255.255.255.255 UH 0 0 0 eth1
192.168.0.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
192.168.254.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 0 0 0 eth1
0.0.0.0 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
如此就可以ping通內網網關192.168.254.1和192.168.254.3主機了
這樣添加的路由信息,在系統重啟以后將會失效,為此我們需要將此命令添加到/etc/rc.d/rc.local啟動項里.如下
[root@MasServer rc.d]# cat rc.local
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
export LC_ALL="zh_CN.GB18030"
export JAVA_OPTS=-Xmx256M
export JAVA_HOME=/usr/local/jdk
export PATH=$PATH:$JAVA_HOME/bin
/usr/local/tomcat/bin/startup.sh
route add -host 192.168.254.1 dev eth1
注意事項
1、網卡2的配置理由不可以再加GATEWAY網關項,否則有不可預知的問題。可能外網通內網不通,可能內網通外網不通,也可能內外網都不通。因為配置兩個網關,系統就不知道數據到底應該是從eth0口出去,還是從eth1口出去。
2、本來應該是用添加網段的命令
route add -net 192.168.254.0/24 gw 192.168.254.1 dev eth1
但是經過實驗,此命令無法達到效果,具體原因不清楚,所以只好用添加主機的命令直接添加網關地址,如果划分了多個vlan,就需要添加多個網關
3、添加好路由后,ping內網地址,需要用service iptables stop命令將防火牆關閉,否則無法ping通。如果是內網訪問服務器,則不需要關閉防火牆
4、添加到rc.local啟動項時,有可能因為未指定route命令路徑,導致添加不成功,為此可以在route前指定route命令路徑
/sbin/route add -host 192.168.254.1 dev eth1