CentOS Streamでサービス一覧をコマンドで表示する方法

Linux

CentOS Streamを運用する際、システムで動いているサービスの状態を確認することは非常に重要です。特にサービス一覧の確認は、トラブルシューティングや運用管理でよく使われます。

この記事では、CentOS Streamでサービス一覧を表示するための代表的なコマンドと使い方をわかりやすく解説します。

スポンサーリンク

CentOS Streamのサービス管理の基礎

systemdとは何か?

systemd(システムディー)は、CentOS Streamで採用されているシステム管理ツールです。

従来のSysVinit に代わる新しいサービス管理システムとして導入されました。

systemdの特徴

  • 並列起動:複数のサービスを同時に起動できる
  • 依存関係管理:サービス間の依存関係を自動的に解決
  • ログ管理:journalctlによる統合ログ管理
  • 高速起動:システムの起動時間を短縮

サービス管理の基本概念

  • ユニット(Unit):systemdで管理される最小単位
  • サービス(Service):バックグラウンドで動作するプロセス
  • ターゲット(Target):複数のユニットをまとめたもの
  • systemctl:systemdを操作するメインコマンド

CentOS Streamでのサービス管理

従来からの変更点 CentOS 6以前とCentOS Stream では、サービス管理の方法が大きく変わりました。

従来の方法(CentOS 6以前)

# 古い方法(非推奨)
service httpd start
chkconfig httpd on
service --status-all

現在の方法(CentOS Stream)

# 新しい方法(推奨)
systemctl start httpd
systemctl enable httpd
systemctl list-units --type=service

なぜsystemctlを使うのか?

  • 統一性:すべてのサービス操作が一つのコマンドで完結
  • 詳細情報:より詳しい状態情報を取得できる
  • 安全性:依存関係を考慮した安全な操作
  • 将来性:Red Hat系ディストリビューションの標準

サービス状態の種類と理解

サービスの基本状態

systemdでは、サービスには複数の状態があります。

これらを理解することで、より効果的にサービス管理ができます。

主要な状態一覧

状態意味表示例
active (running)正常に動作中● apache2.service
active (exited)正常終了済み● network.service
inactive (dead)停止中○ postgresql.service
failed起動に失敗✗ broken.service
activating起動処理中⟳ starting.service
deactivating停止処理中⟳ stopping.service

自動起動設定の状態

状態意味説明
enabled自動起動ありシステム起動時に自動で開始
disabled自動起動なし手動でのみ起動
static他のサービスから起動依存関係により起動
masked無効化済み起動禁止状態

サービス表示の色分けと記号

systemctl出力の見方

$ systemctl list-units --type=service
  UNIT                               LOAD   ACTIVE SUB     DESCRIPTION
● sshd.service                       loaded active running OpenSSH server daemon
○ postgresql.service                 loaded inactive dead  PostgreSQL database server
✗ failed-service.service             loaded failed failed  Example failed service

色と記号の意味

  • ●(緑):正常に動作中(active/running)
  • ○(白):停止中(inactive/dead)
  • ✗(赤):エラー状態(failed)
  • ⟳(黄):処理中(activating/deactivating)

サービス一覧表示の基本コマンド

実行中のサービス一覧

基本コマンド

systemctl list-units --type=service --state=running

実行例と出力

$ systemctl list-units --type=service --state=running
  UNIT                               LOAD   ACTIVE SUB     DESCRIPTION
● auditd.service                     loaded active running Security Auditing Service
● chronyd.service                    loaded active running NTP client/server
● crond.service                      loaded active running Command Scheduler
● dbus.service                       loaded active running D-Bus System Message Bus
● firewalld.service                  loaded active running firewalld - dynamic firewall daemon
● NetworkManager.service             loaded active running Network Manager
● rsyslog.service                    loaded active running System Logging Service
● sshd.service                       loaded active running OpenSSH server daemon
● systemd-journald.service           loaded active running Journal Service
● systemd-logind.service             loaded active running Login Service

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

10 loaded units listed. Pass --all to see loaded but inactive units, too.

よく使用されるオプション

# シンプルな表示(サービス名のみ)
systemctl list-units --type=service --state=running --plain --no-legend

# 実行結果例
auditd.service
chronyd.service
crond.service
dbus.service
firewalld.service

全てのサービス一覧

全サービス表示

systemctl list-units --type=service

より詳細な全サービス表示

systemctl list-units --type=service --all

違いの説明

  • –allなし:現在ロードされているサービスのみ
  • –allあり:ロードされていないサービスも含む全て

実行例

$ systemctl list-units --type=service --all
  UNIT                                   LOAD      ACTIVE   SUB     DESCRIPTION
● auditd.service                         loaded    active   running Security Auditing Service
○ bluetooth.service                      loaded    inactive dead    Bluetooth service
● chronyd.service                        loaded    active   running NTP client/server
✗ example-failed.service                 not-found inactive dead    example-failed.service
○ httpd.service                          loaded    inactive dead    The Apache HTTP Server
● NetworkManager.service                 loaded    active   running Network Manager

サービス状態別の表示

特定の状態のサービスのみ表示

# 停止中のサービス
systemctl list-units --type=service --state=inactive

# 失敗したサービス
systemctl list-units --type=service --state=failed

# 自動起動が有効なサービス
systemctl list-unit-files --type=service --state=enabled

実用例:失敗したサービスの確認

$ systemctl list-units --type=service --state=failed
  UNIT                     LOAD   ACTIVE SUB    DESCRIPTION
✗ example-service.service  loaded failed failed Example Service

1 loaded units listed.

より詳細なサービス情報の取得

個別サービスの詳細確認

基本的な状態確認

systemctl status <サービス名>

実行例:SSHサービスの状態確認

$ systemctl status sshd
● sshd.service - OpenSSH server daemon
     Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2024-01-15 10:30:22 JST; 2h 15min ago
       Docs: man:sshd(8)
             man:sshd_config(5)
   Main PID: 1234 (sshd)
      Tasks: 1 (limit: 11372)
     Memory: 4.2M
        CPU: 15ms
     CGroup: /system.slice/sshd.service
             └─1234 /usr/sbin/sshd -D

Jan 15 10:30:22 localhost systemd[1]: Starting OpenSSH server daemon...
Jan 15 10:30:22 localhost sshd[1234]: Server listening on 0.0.0.0 port 22.
Jan 15 10:30:22 localhost systemd[1]: Started OpenSSH server daemon.

status出力の詳細説明

  • Loaded:サービス定義ファイルの場所と有効/無効状態
  • Active:現在の動作状態と開始時刻
  • Main PID:メインプロセスのID
  • Tasks:関連プロセス数
  • Memory/CPU:リソース使用量
  • CGroup:プロセスグループ
  • ログ:最近のログエントリ

プロセスとの関連確認

サービスに関連するプロセス確認

# サービスのプロセス表示
systemctl status <サービス名> --lines=0

# プロセス一覧との照合
ps aux | grep <サービス名>

# systemdのプロセスツリー表示
systemctl status --no-pager

実用例

$ systemctl status httpd --lines=0
● httpd.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
     Active: active (running) since Mon 2024-01-15 12:00:00 JST; 30min ago
   Main PID: 5678 (httpd)
      Tasks: 82 (limit: 11372)
     Memory: 15.3M
        CPU: 2.1s
     CGroup: /system.slice/httpd.service
             ├─5678 /usr/sbin/httpd -DFOREGROUND
             ├─5679 /usr/sbin/httpd -DFOREGROUND
             └─5680 /usr/sbin/httpd -DFOREGROUND

高度なフィルタリングと表示オプション

grep を使った絞り込み

特定のサービスタイプの検索

# Webサーバー関連
systemctl list-units --type=service | grep -E "(httpd|nginx|apache)"

# データベース関連
systemctl list-units --type=service | grep -E "(mysql|postgresql|mariadb)"

# セキュリティ関連
systemctl list-units --type=service | grep -E "(firewall|audit|selinux)"

実行例

$ systemctl list-units --type=service | grep -E "(httpd|nginx)"
● httpd.service              loaded active running The Apache HTTP Server
○ nginx.service              loaded inactive dead  The nginx HTTP and reverse proxy server

awk を使った高度な表示

サービス名のみ抽出

# 実行中のサービス名のみ表示
systemctl list-units --type=service --state=running --no-legend | awk '{print $1}'

# 実行結果例
auditd.service
chronyd.service
crond.service
dbus.service

カスタム形式での表示

# サービス名と状態を整理して表示
systemctl list-units --type=service --no-legend | awk '{printf "%-30s %s\n", $1, $3}'

# 実行結果例
auditd.service                 running
bluetooth.service              dead
chronyd.service                running

出力形式のカスタマイズ

JSONフォーマットでの出力

systemctl list-units --type=service --output=json

表形式での整理表示

systemctl list-units --type=service --no-legend | \
column -t -s' ' | \
head -10

サービス一覧の活用場面

システム監視での活用

定期的なヘルスチェック

#!/bin/bash
# システムヘルスチェックスクリプト例

echo "=== 実行中のサービス数 ==="
systemctl list-units --type=service --state=running --no-legend | wc -l

echo "=== 失敗したサービス ==="
systemctl list-units --type=service --state=failed --no-legend

echo "=== 重要サービスの状態 ==="
for service in sshd httpd mysql firewalld; do
    status=$(systemctl is-active $service 2>/dev/null)
    enabled=$(systemctl is-enabled $service 2>/dev/null)
    printf "%-15s: %s (自動起動: %s)\n" $service $status $enabled
done

ログファイル出力

# 日次レポート生成
{
    echo "=== サービス状態レポート ($(date)) ==="
    echo ""
    echo "実行中のサービス:"
    systemctl list-units --type=service --state=running --no-legend | awk '{print $1}'
    echo ""
    echo "停止中の自動起動サービス:"
    systemctl list-unit-files --type=service --state=enabled --no-legend | \
    while read service; do
        if ! systemctl is-active $service >/dev/null 2>&1; then
            echo $service
        fi
    done
} >> /var/log/service-report.log

トラブルシューティングでの活用

問題のあるサービスの特定

# 失敗したサービスの詳細確認
systemctl list-units --type=service --state=failed --no-legend | \
while read unit rest; do
    echo "=== $unit ==="
    systemctl status "$unit" --lines=5
    echo ""
done

依存関係の確認

# サービスの依存関係表示
systemctl list-dependencies <サービス名>

# 実行例
$ systemctl list-dependencies httpd
httpd.service
● ├─-.mount
● ├─httpd-init.service
● ├─system.slice
● └─sysinit.target
  ● ├─dev-hugepages.mount
  ● ├─dev-mqueue.mount

自動化とスクリプト活用

サービス監視スクリプト

#!/bin/bash
# 重要サービス監視スクリプト

CRITICAL_SERVICES="sshd network firewalld"
ALERT_EMAIL="admin@example.com"

for service in $CRITICAL_SERVICES; do
    if ! systemctl is-active $service >/dev/null 2>&1; then
        echo "警告: $service が停止しています" | \
        mail -s "サービス停止アラート" $ALERT_EMAIL
        
        # サービス再起動を試行
        systemctl start $service
        
        # ログ記録
        echo "$(date): $service を再起動しました" >> /var/log/service-auto-restart.log
    fi
done

定期レポート作成

#!/bin/bash
# 週次サービスレポート

REPORT_FILE="/tmp/weekly-service-report.txt"

{
    echo "週次サービスレポート - $(date)"
    echo "================================"
    echo ""
    
    echo "【総サービス数】"
    echo "全サービス: $(systemctl list-unit-files --type=service --no-legend | wc -l)"
    echo "実行中: $(systemctl list-units --type=service --state=running --no-legend | wc -l)"
    echo "自動起動有効: $(systemctl list-unit-files --type=service --state=enabled --no-legend | wc -l)"
    echo ""
    
    echo "【失敗したサービス】"
    if systemctl list-units --type=service --state=failed --no-legend | grep -q .; then
        systemctl list-units --type=service --state=failed --no-legend
    else
        echo "なし"
    fi
    echo ""
    
    echo "【新規追加されたサービス】"
    # 前回のレポートと比較(実装例)
    echo "(比較機能は要実装)"
    
} > $REPORT_FILE

# メール送信
mail -s "週次サービスレポート" admin@example.com < $REPORT_FILE

レガシーコマンドとの比較

従来のservice コマンド

service コマンドの使用

# 従来の方法(CentOS 6以前)
service --status-all
service httpd status

CentOS Streamでの対応

# 現在推奨される方法
systemctl list-units --type=service
systemctl status httpd

併用時の注意点

  • 互換性:一部のserviceコマンドは動作するが推奨されない
  • 情報の違い:systemctlの方が詳細な情報を提供
  • 将来性:serviceコマンドは将来的に廃止される可能性

chkconfig コマンドとの比較

自動起動設定の確認

# 従来の方法
chkconfig --list

# 現在の方法
systemctl list-unit-files --type=service

機能比較表

操作従来コマンド現在のコマンド
サービス一覧service --status-allsystemctl list-units --type=service
サービス状態service httpd statussystemctl status httpd
自動起動一覧chkconfig --listsystemctl list-unit-files --type=service
サービス起動service httpd startsystemctl start httpd
自動起動有効chkconfig httpd onsystemctl enable httpd

トラブルシューティング

よくある問題と解決法

問題1:サービスが表示されない

原因と対処法

# 原因1: サービスがインストールされていない
rpm -qa | grep <パッケージ名>

# 原因2: サービス名が間違っている
systemctl list-unit-files --type=service | grep <部分的名前>

# 原因3: ユニットファイルが破損している
systemctl daemon-reload

問題2:権限エラーが発生する

対処法

# sudo権限で実行
sudo systemctl list-units --type=service

# 一般ユーザーでも実行可能なコマンド
systemctl --user list-units --type=service

問題3:出力が文字化けする

対処法

# ロケール設定の確認
locale

# 環境変数の設定
export LANG=ja_JP.UTF-8
export LC_ALL=ja_JP.UTF-8

# またはC言語に設定
export LANG=C

パフォーマンスへの影響

大量のサービスがある場合

# 高速化のためのオプション
systemctl list-units --type=service --no-pager --no-legend

# 必要な情報のみ取得
systemctl is-active <サービス名>
systemctl is-enabled <サービス名>

スクリプトでの効率的な処理

# 複数サービスの状態を効率的に確認
systemctl is-active sshd httpd mysql 2>/dev/null

# 結果をまとめて処理
services="sshd httpd mysql firewalld"
systemctl is-active $services | \
paste <(echo "$services" | tr ' ' '\n') -

まとめ

CentOS Streamでサービス一覧を確認する際は、systemctl list-unitsコマンドが基本となります。状況に応じて適切なオプションを使い分けることで、効率的なシステム管理が可能になります。

重要なポイント

基本コマンド

  • 実行中のサービス: systemctl list-units --type=service --state=running
  • 全サービス一覧: systemctl list-units --type=service
  • 個別サービス詳細: systemctl status <サービス名>
  • 自動起動設定確認: systemctl list-unit-files --type=service

運用のベストプラクティス

  • 定期監視: 重要サービスの状態を定期的にチェック
  • ログ管理: サービス状態の変化をログに記録
  • 自動化: スクリプトによる監視と対応の自動化
  • 文書化: サービス構成と依存関係の文書化

トラブルシューティング

  • 失敗サービス: systemctl list-units --type=service --state=failed
  • 依存関係確認: systemctl list-dependencies <サービス名>
  • 詳細ログ: journalctl -u <サービス名>
  • 設定再読込: systemctl daemon-reload

コメント

タイトルとURLをコピーしました