需求
A机器可以访问外网,B机器和A机器处于同一个内网,现在要让B机器通过A机器访问外网。
步骤
1.为虚拟机添加一块网卡。
如果没有区段名称的话,点击‘LAN区段(S)...’按钮,新建一个。
2.ifconfig -a命令可以看到刚添加进来的尚未启用的网卡:
[root@bogon ~]# ifconfig -a
eth1 Link encap:Ethernet HWaddr 00:0C:29:AC:CC:56
inet addr:192.168.182.130 Bcast:192.168.182.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:feac:cc56/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1546 errors:0 dropped:0 overruns:0 frame:0
TX packets:1187 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:157665 (153.9 KiB) TX bytes:168997 (165.0 KiB)
eth2 Link encap:Ethernet HWaddr 00:0C:29:AC:CC:60
BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:18 errors:0 dropped:0 overruns:0 frame:0
TX packets:18 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:1512 (1.4 KiB) TX bytes:1512 (1.4 KiB)
3.配置网卡eth2:
TYPE=Ethernet
DEVICE=eth2
ONBOOT=yes
BOOTPROTO=static
IPADDR=192.168.100.1
NETMASK=255.255.255.0
HWADDR=00:0C:29:AC:CC:60
4.在机器A上运行:
echo "1" > /proc/sys/net/ipv4/ip_forward
打开ip转发。
5.在A机器上添加规则:
iptables -t nat -A POSTROUTING -s 192.168.100.0/24 -o eth2 -j MASQUERADE
6.配置B机器到相同的“lan区段”,设置ip为192.168.100.2,网关为192.168.100.1。
需求
用xshell登陆B机器
步骤一:A机器打开路由转发
[root@localhost ~]# echo "1" > /proc/sys/net/ipv4/ip_forward
说明:该命令是更改内核设置,打开路由转发功能,默认值是0.
步骤二:在A机器的nat表中增加2条规则(执行该步骤前先清除nat表原有规则)
规则1:
[root@localhost ~]# iptables -t nat -A PREROUTING -d 192.168.8.125 -p tcp --dport 1122 -j DNAT --to 192.168.100.100:22
规则2:
[root@localhost ~]# iptables -t nat -A POSTROUTING -s 192.168.100.100 -j SNAT --to 192.168.8.125
这个实验失败了。。。以后再看吧,尽力了。。。
备份
# service iptables save
/etc/sysconfig/iptables //默认保存的位置
指定备份位置
[root@localhost ~]# iptables-save > /tmp/ipt.txt
[root@localhost ~]# cat /tmp/ipt.txt
# Generated by iptables-save v1.4.21 on Fri Dec 1 21:16:41 2017
*filter
:INPUT DROP [9:702]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [262:26184]
-A INPUT -p icmp -m icmp --icmp-type 8 -j DROP
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -s 192.168.8.0/24 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 21 -j ACCEPT
COMMIT
# Completed on Fri Dec 1 21:16:41 2017
恢复备份的规则
[root@localhost ~]# iptables-restore < /tmp/ipt.txt