ubuntu 設定開機啟動
技術標籤:ubuntu
備註:在ubuntu20.10中,沒有rc.local.service,只有rc-local.service
1.執行 ls /lib/systemd/system 你可以看到有很多啟動指令碼,其中就有我們需要的 rc-local.service
2.開啟指令碼內容
# This file is part of systemd. # # systemd is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2.1 of the License, or # (at your option) any later version. # This unit gets pulled automatically into multi-user.target by # systemd-rc-local-generator if /etc/rc.local is executable. [Unit] Description=/etc/rc.local Compatibility ConditionFileIsExecutable=/etc/rc.local After=network.target [Service] Type=forking ExecStart=/etc/rc.local start TimeoutSec=0 RemainAfterExit=yes
一般正常的啟動檔案主要分成三部分
[Unit] 段: 啟動順序與依賴關係
[Service] 段: 啟動行為,如何啟動,啟動型別
[Install] 段: 定義如何安裝這個配置檔案,即怎樣做到開機啟動
可以看出,/etc/rc.local 的啟動順序是在網路後面,但是顯然它少了 Install 段,也就沒有定義如何做到開機啟動,所以顯然這樣配置是無效的。 因此我們就需要在後面幫他加上 [Install] 段:
[Install]
WantedBy=multi-user.target
Alias=rc-local.service
這裡需要注意一下,ubuntu-18.04以後 預設是沒有 /etc/rc.local 這個檔案的,需要自己建立
sudo touch /etc/rc.local
然後把你需要啟動指令碼寫入 /etc/rc.local ,我們不妨寫一些測試的指令碼放在裡面,以便驗證指令碼是否生效.
#!/bin/sh
echo "看到這行字,說明新增自啟動指令碼成功。" > /usr/local/test.log
exit 0
注意:#!/bin/sh 這一行一定要加 一定要加 一定要加 !!!!!!!!!
如果不加會報錯,類似下面這種
~$ sudo systemctl status rc-local.service ● rc-local.service - /etc/rc.local Compatibility Loaded: loaded (/etc/systemd/system/rc-local.service; enabled; vendor preset: Drop-In: /lib/systemd/system/rc-local.service.d └─debian.conf Active: inactive (dead) Condition: start condition failed at Wed 2019-08-14 12:21:45 CST; 5min ago └─ ConditionPathExists=/etc/rc.local #指令碼檔案位置 was not met
給rc.local加上許可權
sudo chmod +x /etc/rc.local
做完這一步,還需要最後一步 前面我們說 systemd 預設讀取 /etc/systemd/system 下的配置檔案, 所以還需要在 /etc/systemd/system 目錄下建立軟連結
ln -s /lib/systemd/system/rc-local.service /etc/systemd/system/
cd /home/json/nat123--本地實際安裝目錄
mono nat123linux.sh service & --自動讀取上次成功登入帳號並以後臺服務啟動
開機自動登入啟動(ubuntu參考):
(1)本地必須先手動輸入帳號密碼成功登入一次;
(2)執行“chmod +x/etc/rc.local”命令確保有許可權;
(3)把啟動程式的命令新增到/etc/rc.local檔案中,此檔案內容如下,
#!/bin/sh -e
# rc.local
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
# In order to enable or disable this script just change the execution
# bits.
# By default this script does nothing.
cd /home/json/nat123--本地實際安裝目錄
mono nat123linux.sh service & ---自動讀取上次成功登入帳號並以後臺服務啟動
exit 0