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 reboot | OSを再起動 |
| シャットダウン | sudo systemctl poweroff | OSを終了 |
| 登録サービス一覧 | 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)権限で、システムコントロール ストップしろ サービスのサービスって奴だよ。(ばり直訳)