搜索结果

×

搜索结果将在这里显示。

OpenWrt 部署 OpenVPN 客户端完整教程

# OpenWrt 部署 OpenVPN 客户端完整教程

## 环境说明

| 项目 | 信息 |
|------|------|
| 路由器 | Xiaomi Mi Router 4A Gigabit Edition |
| 架构 | MediaTek MT7621 |
| 固件 | LEDE R25.8.8 / OpenWrt 23.05 |

---

## 一、安装 OpenVPN

```bash
opkg update
opkg install openvpn-openssl
opkg install luci-app-openvpn

二、创建配置文件

2.1 创建客户端配置

cat > /etc/openvpn/client.ovpn << 'EOF'
client
dev-type tun
dev tun0
proto tcp
tun-mtu 1400
cipher AES-256-GCM
comp-lzo
remote 你的服务器地址 端口
resolv-retry infinite
nobind
persist-key
persist-tun
verb 3
auth-user-pass /etc/openvpn/auth.txt
script-security 2

<ca>
-----BEGIN CERTIFICATE-----
你的CA证书内容
-----END CERTIFICATE-----
</ca>
EOF

2.2 创建认证文件

echo "你的用户名" > /etc/openvpn/auth.txt
echo "你的密码" >> /etc/openvpn/auth.txt
chmod 600 /etc/openvpn/auth.txt

三、启动并测试

# 后台启动
openvpn --config /etc/openvpn/client.ovpn --daemon --log /tmp/openvpn.log

# 检查是否成功
sleep 3
ip addr show tun0

看到 inet 10.x.x.x 表示成功。


四、添加路由(按需修改)

# 添加你的目标网段
ip route add 192.168.4.0/24 dev tun0
ip route add 192.168.5.0/24 dev tun0
ip route add 192.168.6.0/24 dev tun0
ip route add 192.168.7.0/24 dev tun0

# 验证
ip route show | grep tun0

五、配置防火墙

# 创建VPN区域
uci add firewall zone
uci set firewall.@zone[-1].name='vpn'
uci set firewall.@zone[-1].input='REJECT'
uci set firewall.@zone[-1].output='ACCEPT'
uci set firewall.@zone[-1].forward='REJECT'
uci set firewall.@zone[-1].masq='1'
uci set firewall.@zone[-1].device='tun0'

# 允许LAN到VPN
uci add firewall forwarding
uci set firewall.@forwarding[-1].src='lan'
uci set firewall.@forwarding[-1].dest='vpn'

uci commit firewall
/etc/init.d/firewall restart

六、设置永久生效

6.1 开机自启

/etc/init.d/openvpn enable

6.2 开机自动添加路由

cat > /etc/rc.local << 'EOF'
#!/bin/sh
sleep 10
ip route add 192.168.4.0/24 dev tun0
ip route add 192.168.5.0/24 dev tun0
ip route add 192.168.6.0/24 dev tun0
ip route add 192.168.7.0/24 dev tun0
exit 0
EOF

chmod +x /etc/rc.local

6.3 添加防火墙规则(持久化)

cat >> /etc/firewall.user << 'EOF'

# VPN forward rules
iptables -I FORWARD -i br-lan -o tun0 -j ACCEPT
iptables -I FORWARD -i tun0 -o br-lan -j ACCEPT
EOF

七、验证

ps | grep openvpn | grep -v grep
ip addr show tun0
ip route show | grep tun0
ping -c 2 10.7.7.1

八、重启测试

reboot

重启后重新登录,执行验证命令确认一切正常。


九、常用命令

用途 命令
查看日志 cat /tmp/openvpn.log
重启VPN /etc/init.d/openvpn restart
停止VPN /etc/init.d/openvpn stop
启动VPN /etc/init.d/openvpn start
添加路由 ip route add 网段 dev tun0
删除路由 ip route del 网段 dev tun0

十、配置文件位置

文件 用途
/etc/openvpn/client.ovpn VPN配置
/etc/openvpn/auth.txt 用户名密码
/etc/rc.local 开机路由
/etc/firewall.user 防火墙规则
/tmp/openvpn.log 运行日志

教程结束