Crontab 経由で Python スクリプトを実行してサーバーのステータスを監視し、新しいインスタンスを作成する方法

Linda Hamilton
リリース: 2024-10-22 07:30:31
オリジナル
463 人が閲覧しました

How to Execute Python Scripts Via Crontab to Monitor Server Status and Create New Instances?

Crontab を介した Python スクリプトの実行

問題: ユーザーが Linux crontab を使用して Python スクリプトを実行しようとすると、特に次のことを目的とした場合に問題が発生することがあります。 10分ごとに実行してください。 anacron ファイルの変更や crontab -e の利用などのさまざまな解決策は効果がないと判明する可能性があり、ユーザーは特定のサービスの再起動の必要性や、構成のために編集する必要があるファイルについて疑問を抱くことになります。

回答:

この問題を解決するには、次のガイドを参照してください:

  1. crontab ファイルを編集します: crontab にアクセスするには、端末に crontab -e と入力します。 .
  2. スクリプトを追加します: 以下に示すように、必要なコマンドを crontab ファイルに追加して、スクリプトを 10 分ごとに実行します:
*/10 * * * * /usr/bin/python /home/souza/Documents/Listener/listener.py
ログイン後にコピー
  1. crontab ファイルを保存します: Ctrl X を押して終了し、Y を押して変更を保存します。

ファイル構成:

編集が必要なファイルは crontab ファイルで、crontab -e コマンドを使用してアクセスして変更できます。

スクリプト:

Python スクリプトが正しく設定されている必要があります必要なアクションを実行します。参考までに、10 分ごとに実行されるように調整された提供されたスクリプトを次に示します。

<code class="python">#!/usr/bin/python
# -*- coding: iso-8859-15 -*-

import json
import os
import pycurl
import sys
import cStringIO

if __name__ == "__main__":

    name_server_standart = "Server created by script %d"
    json_file_standart = """{ "server" : {  "name" : "%s", "imageRef" : "%s", "flavorRef" : "%s" } }"""

    curl_auth_token = pycurl.Curl()

    gettoken = cStringIO.StringIO()

    curl_auth_token.setopt(pycurl.URL, "http://192.168.100.241:8774/v1.1")
    curl_auth_token.setopt(pycurl.POST, 1)
    curl_auth_token.setopt(
        pycurl.HTTPHEADER,
        ["X-Auth-User: cpca", "X-Auth-Key: 438ac2d9-689f-4c50-9d00-c2883cfd38d0"],
    )

    curl_auth_token.setopt(pycurl.HEADERFUNCTION, gettoken.write)
    curl_auth_token.perform()
    chg = gettoken.getvalue()

    auth_token = chg[
        chg.find("X-Auth-Token: ") + len("X-Auth-Token: ") : chg.find("X-Server-Management-Url:") - 1
    ]

    token = "X-Auth-Token: {0}".format(auth_token)
    curl_auth_token.close()

    # ----------------------------

    getter = cStringIO.StringIO()
    curl_hab_image = pycurl.Curl()
    curl_hab_image.setopt(pycurl.URL, "http://192.168.100.241:8774/v1.1/nuvemcpca/images/7")
    curl_hab_image.setopt(pycurl.HTTPGET, 1)  # Removing this line allows the script to run.
    curl_hab_image.setopt(pycurl.HTTPHEADER, [token])

    curl_hab_image.setopt(pycurl.WRITEFUNCTION, getter.write)
    # curl_list.setopt(pycurl.VERBOSE, 1)
    curl_hab_image.perform()
    curl_hab_image.close()

    getter = cStringIO.StringIO()

    curl_list = pycurl.Curl()
    curl_list.setopt(pycurl.URL, "http://192.168.100.241:8774/v1.1/nuvemcpca/servers/detail")
    curl_list.setopt(pycurl.HTTPGET, 1)  # Removing this line allows the script to run.
    curl_list.setopt(pycurl.HTTPHEADER, [token])

    curl_list.setopt(pycurl.WRITEFUNCTION, getter.write)
    # curl_list.setopt(pycurl.VERBOSE, 1)
    curl_list.perform()
    curl_list.close()

    # ----------------------------

    resp = getter.getvalue()

    con = int(resp.count("status"))

    s = json.loads(resp)

    lst = []

    for i in range(con):
        lst.append(s["servers"][i]["status"])

    for j in range(len(lst)):
        actual = lst.pop()
        print actual

        if actual != "ACTIVE" and actual != "BUILD" and actual != "REBOOT" and actual != "RESIZE":

            print "Enters the if block."

            f = file("counter", "r+w")

            num = 0
            for line in f:
                num = line

            content = int(num) + 1

            ins = str(content)

            f.seek(0)
            f.write(ins)
            f.truncate()
            f.close()

            print "Increments the counter."

            json_file = file("json_file_create_server.json", "r+w")

            name_server_final = name_server_standart % content
            path_to_image = "http://192.168.100.241:8774/v1.1/nuvemcpca/images/7"
            path_to_flavor = "http://192.168.100.241:8774/v1.1/nuvemcpca/flavors/1"

            new_json_file_content = json_file_standart % (
                name_server_final,
                path_to_image,
                path_to_flavor,
            )

            json_file.seek(0)
            json_file.write(new_json_file_content)
            json_file.truncate()
            json_file.close()

            print "Updates the JSON file."

            fil = file("json_file_create_server.json")
            siz = os.path.getsize("json_file_create_server.json")

            cont_size = "Content-Length: %d" % siz
            cont_type = "Content-Type: application/json"
            accept = "Accept: application/json"

            c_create_servers = pycurl.Curl()

            logger = cStringIO.StringIO()

            c_create_servers.setopt(pycurl.URL, "http://192.168.100.241:8774/v1.1/nuvemcpca/servers")

            c_create_servers.setopt(pycurl.HTTPHEADER, [token, cont_type, accept, cont_size])

            c_create_servers.setopt(pycurl.POST, 1)

            c_create_servers.setopt(pycurl.INFILE, fil)

            c_create_servers.setopt(pycurl.INFILESIZE, siz)

            c_create_servers.setopt(pycurl.WRITEFUNCTION, logger.write)

            print "Executes the curl command."

            c_create_servers.perform()

            print logger.getvalue()

            c_create_servers.close()</code>
ログイン後にコピー

以上がCrontab 経由で Python スクリプトを実行してサーバーのステータスを監視し、新しいインスタンスを作成する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!