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 -e 명령을 사용하여 액세스하고 수정할 수 있는 crontab 파일입니다.

스크립트:

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!