在 CentOS 环境下,可以通过将脚本添加到系统服务中来实现开机自启动,具体步骤如下:
- 创建一个新的服务文件,比如
/etc/systemd/system/yourscript.service,并在文件中添加以下内容:
[Unit] Description=Your Script After=network.target [Service] Type=simple ExecStart=/path/to/your/script.sh Restart=always User=root [Install] WantedBy=multi-user.target
其中,
Description可以根据你的脚本名称进行修改,After指定该服务在网络服务启动后启动,Type指定该服务为简单的启动类型,ExecStart指定需要执行的脚本路径,Restart指定当服务崩溃时自动重启,User指定执行该服务的用户,WantedBy指定该服务在多用户模式下启动。 - 保存该文件并退出编辑器。
- 启动该服务并设置随系统启动自动启动:
sudo systemctl daemon-reload sudo systemctl start yourscript.service sudo systemctl enable yourscript.service现在,每次系统启动时,该服务都会自动运行你的脚本。如果你需要停止该服务,可以使用以下命令:
sudo systemctl stop yourscript.service
如果你需要禁用该服务自启动,可以使用以下命令:
sudo systemctl disable yourscript.service