我想在启动时以root身份运行bash脚本。首先,我开始使用RC.Local和Crontab,但是没有任何效果。
答案 0 :(得分:1)
将脚本放入/etc/init.d
确保其扩展名为“ .sh”
答案 1 :(得分:1)
创建一个systemd单位文件并在其中执行脚本:
[Unit]
Description=Hello world
After=sysinit.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=no
RemainAfterExit=yes
User=root
ExecStart=/bin/echo hello world
ExecStop=/bin/echo goodby world
[Install]
WantedBy=multi-user.target
将其另存为/etc/systemd/system/hello-world.service:
$ systemctl enable hello-world
$ systemctl start hello-world
$ systemctl stop hello-world
$ systemctl status hello-world
● hello-world.service - Hello world
Loaded: loaded (/etc/systemd/system/hello-world.service; enabled; vendor preset: enabled)
Active: inactive (dead) since Wed 2019-10-09 13:54:58 CEST; 1min 47s ago
Process: 11864 ExecStop=/bin/echo goodby world (code=exited, status=0/SUCCESS)
Main PID: 11842 (code=exited, status=0/SUCCESS)
Oct 09 13:54:38 lnxclnt1705 systemd[1]: Started Hello world.
Oct 09 13:54:38 lnxclnt1705 echo[11842]: hello world
Oct 09 13:54:57 lnxclnt1705 systemd[1]: Stopping Hello world...
Oct 09 13:54:57 lnxclnt1705 echo[11864]: goodby world
Oct 09 13:54:58 lnxclnt1705 systemd[1]: Stopped Hello world.
确保在单位文件(即/ bin / echo)中使用脚本的完整路径。
答案 2 :(得分:1)
按照下面的模板创建服务文件,并将文件添加到位置/etc/systemd/system/
模板为
[Unit]
Description = ~Name of the service~
[Service]
WorkingDirectory= ~directory of working file~
ExecStart= ~directory~/filename.sh
[Install]
WantedBy=multi-user.target
使用以下名称启动服务文件
systemctl start servicefile.service
要在启动时启用
systemctl enable servicefile.service
要检查状态
systemctl status servicefile.service
停止
systemctl stop servicefile.service
答案 3 :(得分:0)
对于 crontab,
设置用户 crontab 或 root crontab 是有区别的:
$ crontab -e
@reboot sudo ...
^^ 这是用户的 cron 选项卡,无法正常工作。
$ sudo crontab -e
@reboot ...
^^ 这是 root 的 cron 选项卡,将以 root 身份运行命令。
@reboot
应该可以帮助您在启动后运行脚本。