如何透過Crontab執行Python腳本監控伺服器狀態並建立新實例?
透過Crontab 執行Python 腳本
問題:使用者在嘗試使用Linux crontab 執行Python 腳本時可能會遇到困難,特別是當旨在每10 分鐘運行一次。各種解決方案(例如修改 anacron 檔案或使用 crontab -e)可能無效,讓使用者質疑是否需要重新啟動特定服務或應編輯設定檔。
答案:
要解決此問題,請參閱以下指南:
- 編輯crontab> 在 在 在>終端機中輸入crontab -e 以存取crontab .
- 新增腳本: 將所需的命令追加到crontab 檔案中,如下所示,每10 分鐘執行一次腳本:
*/10 * * * * /usr/bin/python /home/souza/Documents/Listener/listener.py
- 儲存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中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python在開發效率上優於C ,但C 在執行性能上更高。 1.Python的簡潔語法和豐富庫提高開發效率。 2.C 的編譯型特性和硬件控制提升執行性能。選擇時需根據項目需求權衡開發速度與執行效率。

每天學習Python兩個小時是否足夠?這取決於你的目標和學習方法。 1)制定清晰的學習計劃,2)選擇合適的學習資源和方法,3)動手實踐和復習鞏固,可以在這段時間內逐步掌握Python的基本知識和高級功能。

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

Python在科學計算中的應用包括數據分析、機器學習、數值模擬和可視化。 1.Numpy提供高效的多維數組和數學函數。 2.SciPy擴展Numpy功能,提供優化和線性代數工具。 3.Pandas用於數據處理和分析。 4.Matplotlib用於生成各種圖表和可視化結果。
