WireGuard是一个现代化的、轻量级的虚拟专用网络(VPN)协议,设计用于提供高速、简洁且安全的连接。它的优点之一是它能够在各种网络环境下穿透 NAT(网络地址转换)和防火墙,从而建立安全的点对点连接。
WireGuard用来做网络穿透、搭建内网访问互通非常好用。
下面是如何在 CentOS 上安装和配置 WireGuard 的步骤,并确保你能在服务器A和服务器B之间通过内网进行安全通信。
1. 安装 WireGuard
sudo yum install -y epel-release
sudo yum install -y wireguard-tools
wg --version
2. 生成 WireGuard 密钥对
在服务器A上生成密钥对:
wg genkey | tee /etc/wireguard/us-server-privatekey | wg pubkey > /etc/wireguard/us-server-publickey
在服务器B上生成密钥对:
wg genkey | tee /etc/wireguard/cn-server-privatekey | wg pubkey > /etc/wireguard/cn-server-publickey
/etc/wireguard/cn-server-privatekey 此为私钥
/etc/wireguard/cn-server-publickey 此为公钥
3. 配置 WireGuard
在A服务器上配置:
vim /etc/wireguard/wg0.conf
[Interface]
PrivateKey = <A服务器的私钥>
Address = 10.8.0.1/24 # A服务器在虚拟私有网络中的内网地址
ListenPort = 51820
[Peer]
PublicKey = <B服务器的公钥>
AllowedIPs = 10.8.0.2/32 # B服务器的内网 IP
Endpoint = <B服务器的公网IP>:51820
PersistentKeepalive = 25
在B服务器上配置:
vim /etc/wireguard/wg0.conf
[Interface]
PrivateKey = <B服务器的私钥>
Address = 10.8.0.2/24 # B服务器在虚拟私有网络中的内网地址
ListenPort = 51820
[Peer]
PublicKey = <A服务器的公钥>
AllowedIPs = 10.8.0.1/32 # A服务器的内网 IP
Endpoint = <A服务器的公网IP>:51820
PersistentKeepalive = 25
两台服务器上启动服务并设置开机自启动:
systemctl start wg-quick@wg0
systemctl enable wg-quick@wg0
netstat -antpul |grep 51820
4. 测试连接
在俩台服务器直接互相ping穿透网络的内外IP地址:
ping 10.8.0.1
ping 10.8.0.2
如果能够成功 ping 通对方的内网IP,说明WireGuard VPN隧道已经成功建立。
通过这些步骤,你可以在CentOS系统上的A服务器和B服务器之间成功建立WireGuard VPN 隧道。