systemctl

systemctl は、Linuxのシステムとバックグラウンドサービス(デーモン)を管理するためのコマンドラインツールです。サービスの起動、停止、再起動、自動起動の設定、およびシステム全体のシャットダウンや状態確認を1つのコマンドで行うことができます。

systemctlのコマンド一覧

ほとんどの操作には管理者権限(sudo)が必要です。例 service という名のサービスをどうのこうのしたい場合。

操作 コマンド説明
起動sudo systemctl start service.serviceサービスを開始
停止sudo systemctl stop service.serviceサービスを停止
再起動sudo systemctl restart service.serviceサービスを再起動
状態確認systemctl status service.service動作状況とエラーログを表示
自動起動設定sudo systemctl enable service.service起動時に自動開始する
自動起動解除sudo systemctl disable service.service自動開始を解除
システム再起動sudo systemctl rebootOSを再起動
シャットダウンsudo systemctl poweroffOSを終了
登録サービス一覧systemctl list-unit-files --type=service登録されているサービス一覧を見る
有効化systemctl list-unit-files --type=service --state=enabled有効化されているものだけ見る
動作中systemctl list-units --type=service --state=running現在動作中のサービスだけ見る
自作したサービスsystemctl list-unit-files --type=service | grep dht自作したサービスを探すなら
今回のサービスsystemctl status <サービス名>.service今回のサービスなら

具体例:自動登録したい場合。

例えば/home/pi/scripts/service.pyを自動起動したい場合。

1. service.pyを実行可能にする

chmod +x /home/pi/scripts/service.py

2. systemdサービスを作成

sudo nano /etc/systemd/system/service.service

青文字部分の名称を付ける。基本的にservice.pyならserviceで良いかと。

service.serviceの内容:

[Unit]
Description=My Python Service
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=pi
WorkingDirectory=/home/pi/scripts
ExecStart=/usr/bin/python3 -u /home/pi/scripts/service.py
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

青文字の【パス】部分が重要。よく間違える・・・

3. 登録して起動

sudo systemctl daemon-reload
sudo systemctl enable --now service.service

青文字部分は先ほどの「サービスの名称」です。

4. 確認

systemctl status service.service --no-pager -l

ログを見る:別に見なくてもいいけど・・・

journalctl -u service.service -f

停止したい時:

sudo systemctl stop service.service

自動起動解除:

sudo systemctl disable service.service

自動起動を削除したい時:service.pyのサービス(自動起動)を消す場合。

sudo systemctl stop service.service
sudo systemctl disable service.service
sudo rm /etc/systemd/system/service.service
sudo systemctl daemon-reload
sudo systemctl reset-failed

確認:

systemctl status service.service

次のように出れば削除済みです。

Unit service.service could not be found.

このsystemctlはシステム コントロール(system control)って覚えればいい。

sudo systemctl stop service.service
管理者(root)権限で、システムコントロール ストップしろ サービスのサービスって奴だよ。(ばり直訳)

zero

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です