GNU/Linux >> Linux の 問題 >  >> Cent OS

CentOS / RHEL 7 :起動時に自動的に実行されるカスタム スクリプトを作成する方法

RHEL 5 および 6 では、/etc/rc.d/init.d を介して RHEL の自動起動機能を使用し、システムの起動時に任意のスクリプトを実行していました。 RHEL 7 以降、init は systemd に置き換えられ、以前の方法は非推奨になりました。 RHEL 7 には、同じことを行う別の方法があります。

カスタム スクリプトの作成

1. まず、システムの起動時に自動的に実行されるカスタム スクリプトのサンプルを作成しましょう。

# vi /var/tmp/test_script.sh
#!/bin/bash
echo "This is a sample script to test auto run during boot" > /var/tmp/script.out
echo "The time the script run was -->  `date`" >> /var/tmp/script.out

2. ファイルのパーミッションを確認して確認してください。

# ls -lrt /usr/local/sbin/myscript.sh

3. 実行権限を追加します (まだ設定されていない場合)。

# chmod +x /var/tmp/test_script.sh

新しい systemd サービス ユニットの作成

/etc/systemd/system/sample.service に新しいサービス ユニット ファイルを作成します。 以下の内容で。サービス ユニットの名前はユーザーが定義し、任意の名前にすることができます。

# vi /etc/systemd/system/sample.service
[Unit]
Description=Description for sample script goes here
After=network.target

[Service]
Type=simple
ExecStart=/var/tmp/test_script.sh
TimeoutStartSec=0

[Install]
WantedBy=default.target

ここで、

After= : If the script needs any other system facilities (networking, etc), modify the [Unit] section to include appropriate After=, Wants=, or Requires= directives.
Type= : Switch Type=simple for Type=idle in the [Service] section to delay execution of the script until all other jobs are dispatched
WantedBy= : target to run the sample script in

systemd サービス ユニットを有効にする

1. systemd プロセスをリロードして、新しく作成された sample.service を考慮するか、sample.service が変更されるたびに。

# systemctl daemon-reload

2. 再起動後にこのサービスが自動的に開始されるようにします。

# systemctl enable sample.service

3. サービスを開始します。

# systemctl start sample.service

4. ホストを再起動して、システムの起動中にスクリプトが期待どおりに開始されるかどうかを確認します。

# systemctl reboot


Cent OS
  1. CentOS/RHEL で avahi-daemon サービスを無効にする方法

  2. CentOS/RHEL で yum リポジトリを作成する方法

  3. CentOS/RHEL 7 で systemd にカスタム スクリプトを追加する方法

  1. CentOS 7 /RHEL7でネットワークブリッジを作成する方法

  2. CentOS/RHEL 5 で NTPD を起動するときに ntpdate を自動的に実行する方法

  3. Centos 7 で起動時にスクリプトを自動的に実行するにはどうすればよいですか?

  1. CentOS8またはRHEL8でネットワークサービスを再起動する方法

  2. CentOS / RHEL で新しい /boot パーティションを作成する方法

  3. CentOS/RHEL 7 で systemd にカスタム スクリプトを追加する方法