簡體   English   中英

在 ubuntu 18.04 上以 root 身份運行 Bash 腳本

[英]Run Bash script as root in startup on ubuntu 18.04

我想在啟動時以 root 身份運行 bash 腳本。 首先,我開始使用 RC.Local 和 Crontab,但沒有任何效果。

按照下面的模板創建服務文件,並將文件添加到位置/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

創建一個 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)中使用腳本的完整路徑。

將腳本放在 /etc/init.d 中

確保它具有擴展名“.sh”

對於 crontab,

如果您設置用戶 crontab 或 root crontab,則會有所不同:

$ crontab -e 

@reboot sudo ...

^^ 這是用戶的 cron 選項卡,不能按原樣工作。

$ sudo crontab -e

@reboot ...

^^ 這是 root 的 cron 選項卡,將以 root 身份運行命令。

@reboot應該可以幫助您在啟動后運行腳本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM