1. Linux 设置开机自动运行脚本 1. Linux 设置开机自动运行脚本 1.1. auto_run_script.sh 1.2. auto_run_script.service 1.3. 更新 systemd 配置文件 1.4. 重启系统 1.1. auto_run_script.sh 创建脚本,文件后缀 .sh $ cat /home/luckyboy/auto_run_script.sh #!/bin/bash of=/home/luckyboy/output.txt date >> $of hostname >> $of 1.2. auto_run_script.service 创建 systemd 启动服,文件后缀 .service $ cat /etc/systemd/system/auto_run_script.service [Unit] Description=Run a Custom Script at Startup After=default.target [Service] ExecStart=/home/luckyboy/auto_run_script.sh [Install] WantedBy=default.target 从服务的内容可以看出来,最终还是会调用 /home/luckyboy/auto_run_script.sh 这个脚本。 1.3. 更新 systemd 配置文件 sudo systemctl daemon-reload sudo systemctl enable auto_run_script.service 1.4. 重启系统 sudo reboot ================================================ 方案一:(如果没有/etc/rc.local文件,则推荐方案二) 1、编辑rc.local脚本 rc.local脚本在ubuntu开机后会自动执行。位于/etc/路径下,需要root权限才能修改。 注意: 一定要将命令添加在 exit 0之前 方案二: (方案一缺点:将所有不同的脚本指令写入同一个文件不是一个好的方法。可以写一个run.sh,然后让系统在开机时自动执行) 1、建立自己的脚本 (随便写个内容) 随后将脚本保存为run_server.sh 2、修改脚本权限:7** 3、将脚本放置在启动路径下:将run_server.sh移动到/etc/init.d路径下,可以直接拷贝,也可以链接过去 4、将脚本添加到启动脚本 执行如下指令,在这里90表明一个优先级,越高表示执行的越晚 cd /etc/init.d/ update-rc.d run_server.sh defaluts 90 5、如何移除该脚本 update-rc.d -f run_server.sh remove ================================================ 使用update-rc.d添加开机自启动脚本 ## 进入开机启动目录 cd /etc/init.d ## 创建开机启动脚本 touch xx.sh ## 赋予执行权限 chmod +x /etc/init.d/xx.sh #设置开机自启 update-rc.d xx.sh defaults 可能会报错,缺少必填项 insserv: warning: script 'xx.sh' missing LSB tags insserv: warning: script 'xx.sh' missing LSB tags insserv: Default-Start undefined, assuming empty start runlevel(s) for script `xx.sh' insserv: Default-Stop undefined, assuming empty stop runlevel(s) for script `xx.sh' 在脚本最前面添加必填项,参数说明:LSBInitScripts #!/bin/sh ### BEGIN INIT INFO # Provides: xx # Required-Start: $all # Required-Stop: $all # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: starts xx # Description: starts the xx ### END INIT INFO