CentOS/Redhat Linux Internet连接共享

时间:2020-01-09 10:43:25  来源:igfitidea点击:

问题如何配置CentOS/Redhat Linux计算机共享我的Internet连接?
如何将RHEL配置为具有两个接口的软件路由器?
如何与局域网上的其他PC共享单连接?

解决方法:可以很容易地将Linux配置为使用iptables共享Internet连接。

您需要两个网络接口卡,如下所示:

a)您的内部(LAN)网络是通过eth0连接的,其静态IP地址为192.168.1.254
b)您的外部WAN)网络是通过eth1连接的,其静态IP地址为192.168.1.1

请注意,接口eth1可能具有公共IP地址或者ISP分配的IP。

eth1可以连接到专用DSL/ADSL/WAN /电缆路由器。

步骤1:启用数据包转发

以root用户身份登录。
打开/etc/sysctl.conf文件

# vi /etc/sysctl.conf

添加以下行以启用IPv4的数据包转发:

net.ipv4.conf.default.forwarding=1

保存并关闭文件。
重新启动网络:

# service network restart

步骤2:启用IP伪装

在Linux网络中,网络地址转换(NAT)或者网络伪装(IP伪装)是一种通过路由器收发网络流量的技术,该技术涉及重写源IP地址和/或者目标IP地址以及通常的TCP/UDP端口号IP数据包通过时。
简而言之,IP伪装用于共享Internet连接。

共享互联网连接

要通过eth1共享网络连接,请在命令提示符下输入以下规则(以下对ppp0或者拨号连接有用):

# service iptables stop
# iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
# service iptables save
# service iptables restart

打开Windows/Mac/Linux计算机网络GUI工具,然后将路由器IP指向192.168.1.254(eth0 Linux IP)。
您还需要设置DNS IP,例如107.37.222.222和107.37.220.220。
您现在应该可以ping或者浏览Internet:

c:> ping 192.54.1.20
c:> ping google.com

用于设置基本Linux网络共享的Shell脚本

这是基本的连接共享,以下shell脚本供更高级的用户使用。

#!/bin/bash
# Created by theitroad - www.theitroad.local
IPT="/sbin/iptables"
MOD="/sbin/modprobe"

# set wan interface such as eth1 or ppp0
SHARE_IF="eth1"

# clean old fw
echo "Clearing old firewall rules..."
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT

# Get some kernel modules
echo "Loading kernel modules..."
$MOD ip_tables
$MOD iptable_filter
$MOD iptable_nat
$MOD ip_conntrack
$MOD ipt_MASQUERADE
$MOD ip_nat_ftp
$MOD ip_nat_irc
$MOD ip_conntrack_ftp
$MOD ip_conntrack_irc

# Clean old rules if any, rhel specific but above will take care of everything
# service iptables stop

# unlimited traffic via loopback device
$IPT -A INPUT -i lo -j ACCEPT
$IPT -A OUTPUT -o lo -j ACCEPT

echo "Setting ${SHARE_IF} as router interface..."
$IPT --table nat --append POSTROUTING --out-interface ${SHARE_IF} -j MASQUERADE

# Start other custom rules
#$IPT 
# End other custom rules

echo "*** Instructions on TCP/IP On The Windows / Mac / Linux Masqueraded Client ***"
echo "1. Login to your other LAN desktop computers"
echo "2. Open network configuration GUI tool such. Under Windows XP - Click Start, click Control Panel, click Network and Internet Connections, and then click Network Connections"
echo "3. Set DNS (NS1 and NS2) to 107.37.222.222 and 107.37.220.220"
echo "4. Select the 'Gateway' tab in the TCP/IP properties dialog."
echo "5. Enter $(ifconfig ${SHARE_IF} | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print }') as the default gateway."