例:在rc.local中加入 nohup openvpn --config /root/client.ovpn %& 命令
在 Ubuntu 16.04 中,当您尝试在 rc.local
脚本中加入开机自启动的命令时,出现网络无法通的问题,可能有几个原因:
1. 执行时机:rc.local
中的命令是在系统启动的最后阶段执行的,但它可能在网络服务完全启动并初始化之前就运行了。OpenVPN 需要网络接口和相关服务已经准备好才能正常工作。
2. 环境变量:
使用 nohup
和后台运行符号 &
通常会创建新的子 shell 来执行命令,这个过程中可能某些环境变量未被正确设置或传递。
3. 权限问题:
并且当系统执行 rc.local
时,运行的命令是否有足够的权限去启动 OpenVPN
4. 路径问题:
在 rc.local
脚本中,最好使用绝对路径指定所有执行文件和配置。
5. 服务依赖:
maybe rc.local
is executed before all necessary services are up and running. OpenVPN can depend on other services like network-manager or networking service to fully initialise the network stack.
为了解决这个问题,您可以:
使用 systemd 服务:
建议在使用 newer versions 的系统时,通过 systemd 创建一个服务单元来管理 OpenVPN 这样的守护程序。这不仅可以让您控制服务在启动过程中的时机,也能确保依赖关系正确处理。例如:
[Unit]
Description=OpenVPN connection to client
Wants=network-online.target
After=network-online.target
[Service]
ExecStart=/usr/sbin/openvpn --config /root/client.ovpn
# or
# ExecStart=/bin/sh -c '/usr/sbin/openvpn --config /root/client.ovpn &'
[Install]
WantedBy=multi-user.target
将以上文件保存为 /etc/systemd/system/openvpn-client.service
并通过以下命令启用服务:
sudo systemctl enable openvpn-client
sudo systemctl start openvpn-client
使用 systemd 服务也让您能够通过 systemctl status 等命令监控服务状态,更容易诊断问题。