Python腳本實(shí)現(xiàn)定時(shí)監(jiān)控端口
python寫了一個(gè)監(jiān)控端口服務(wù),自動(dòng)重啟的腳本
為了防止以后找不到代碼,特別記錄一下
import os import sys import threading import time import socket import subprocess def check_port_and_run_script(port, script_path): # 創(chuàng)建一個(gè)socket對(duì)象 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 設(shè)置超時(shí)時(shí)間 sock.settimeout(1) # 嘗試連接到指定的端口 result = sock.connect_ex(('localhost', port)) # 如果連接成功,端口正在被使用 if result == 0: print(f"端口 {port} 正在被使用。") else: print(f"端口 {port} 未被使用,正在執(zhí)行 {script_path} 腳本...") # 執(zhí)行a.sh腳本 subprocess.run(['D:/software/Git/bin/bash.exe', script_path]) # subprocess.run(['bash', script_path]) # 關(guān)閉socket sock.close() def read_cof_file(): current_directory = os.getcwd() # 使用glob查找所有.doc文件 if os.path.exists(os.path.join(current_directory, 'shany.txt')): with open(os.path.join(current_directory, 'shany.txt'), 'r', encoding='utf-8') as file: # 逐行讀取文件內(nèi)容 for line in file: if 'shany-end' in line: print('定時(shí)任務(wù)已結(jié)束') sys.exit(0) elif ':=>' in line: parts = line.split(":=>") check_port_and_run_script(int(parts[0]), parts[1]) def timer_task(): print("定時(shí)器任務(wù)執(zhí)行了!") # check_port_and_run_script(8686, 'D:/WorkSpace/shany/simulator/target/start.sh') read_cof_file() set_timer(20) def set_timer(interval): timer = threading.Timer(interval, timer_task) timer.start() if __name__ == '__main__': # 首次設(shè)置定時(shí)器 set_timer(20) # 主線程可以繼續(xù)執(zhí)行其他任務(wù),或者簡(jiǎn)單地等待定時(shí)器執(zhí)行 try: while True: time.sleep(1) # 防止主線程立即退出,可以按需調(diào)整或添加其他邏輯 except KeyboardInterrupt: print("程序被用戶中斷")
用來(lái)監(jiān)控的配置文件,shany.txt 內(nèi)容如下
8686:=>D:/WorkSpace/shany/simulator/target/start.sh
其中8686是端口號(hào), :=> 作為分隔符 ,后面地址對(duì)應(yīng)腳本的所在路徑
方法補(bǔ)充
下面小編為大家整理了一些其他Python進(jìn)行監(jiān)控端口的方法,希望對(duì)大家有所幫助
Python3使用 socket 庫(kù)監(jiān)控端口
import socket def monitor_port(port_number): # 創(chuàng)建一個(gè) socket 對(duì)象 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # 嘗試連接到指定的端口 sock.connect(('localhost', port_number)) print(f"Port {port_number} is active.") except socket.error as e: print(f"Error occurred while monitoring port {port_number} - {str(e)}") finally: # 關(guān)閉 socket sock.close() # 監(jiān)控 8001 端口 monitor_port(8001)
python監(jiān)聽(tīng)網(wǎng)絡(luò)端口號(hào)程序
import tkinter as tk from tkinter import messagebox import socket import time def check_port(host, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(5) # 設(shè)置超時(shí)時(shí)間 result = sock.connect_ex((host, port)) sock.close() # 在檢查后關(guān)閉 socket if result == 0: return f"端口 {port} 是開(kāi)放的。" else: return f"端口 {port} 是關(guān)閉的。" def on_check(): global host, ports, time_interval, port_success_counts, port_failure_counts host = entry_host.get() ports = entry_port.get().split(",") # 以逗號(hào)分隔多個(gè)端口號(hào) try: time_interval = int(entry_timeset.get()) if time_interval <= 0: raise ValueError("時(shí)間間隔必須大于0") for port in ports: port = int(port) if not (0 <= port <= 65535): raise ValueError(f"端口號(hào) {port} 必須在 0 到 65535 之間") # 初始化成功和失敗計(jì)數(shù) port_success_counts = {int(port): 0 for port in ports} port_failure_counts = {int(port): 0 for port in ports} start_monitoring() except ValueError as e: messagebox.showerror("錯(cuò)誤", str(e)) def start_monitoring(): global host, ports, time_interval, port_success_counts, port_failure_counts for port in ports: port = int(port) result = check_port(host, port) timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) text_result.insert(tk.END, f"{timestamp}: {result}\n") # 更新成功和失敗計(jì)數(shù) if "開(kāi)放" in result: port_success_counts[port] += 1 else: port_failure_counts[port] += 1 update_port_counts() root.after(time_interval * 1000, start_monitoring) # 定時(shí)監(jiān)測(cè) def update_port_counts(): text_port_counts.delete(1.0, tk.END) # 清空文本框 for port, success_count in port_success_counts.items(): failure_count = port_failure_counts[port] text_port_counts.insert(tk.END, f"端口 {port} 成功: {success_count}, 失敗: {failure_count}\n") # 創(chuàng)建主窗口 root = tk.Tk() root.title("端口監(jiān)測(cè)工具") root.geometry("500x400") # 設(shè)置窗口大小 # 創(chuàng)建標(biāo)簽 label_host = tk.Label(root, text="主機(jī):") label_host.grid(row=0, column=0) label_port = tk.Label(root, text="端口:") label_port.grid(row=1, column=0) label_port2 = tk.Label(root, text="(0~65535, 用逗號(hào)分隔)") label_port2.grid(row=1, column=2) label_timeset = tk.Label(root, text="時(shí)間 (間隔):") label_timeset.grid(row=2, column=0) label_timeset2 = tk.Label(root, text="(單位:秒)") label_timeset2.grid(row=2, column=2) # 創(chuàng)建輸入框 entry_host = tk.Entry(root) entry_host.grid(row=0, column=1) entry_port = tk.Entry(root) entry_port.grid(row=1, column=1) entry_timeset = tk.Entry(root) entry_timeset.grid(row=2, column=1) # 創(chuàng)建按鈕 button_check = tk.Button(root, text="檢查端口", command=on_check) button_check.grid(row=3, columnspan=3) # 創(chuàng)建文本框顯示端口成功和失敗次數(shù) text_port_counts = tk.Text(root, height=5, width=50) text_port_counts.grid(row=5, column=0, columnspan=3, sticky=tk.NSEW) # 創(chuàng)建滾動(dòng)條 scrollbar = tk.Scrollbar(root) scrollbar.grid(row=4, column=3, sticky=tk.NS) # 創(chuàng)建文本框并關(guān)聯(lián)滾動(dòng)條 text_result = tk.Text(root, height=10, width=50, yscrollcommand=scrollbar.set) text_result.grid(row=4, column=0, columnspan=3, sticky=tk.NSEW) # 配置滾動(dòng)條 scrollbar.config(command=text_result.yview) # 初始化全局計(jì)數(shù)器 port_success_counts = {} port_failure_counts = {} # 啟動(dòng)主循環(huán) root.mainloop()
到此這篇關(guān)于Python腳本實(shí)現(xiàn)定時(shí)監(jiān)控端口的文章就介紹到這了,更多相關(guān)Python監(jiān)控端口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
np.newaxis 實(shí)現(xiàn)為 numpy.ndarray(多維數(shù)組)增加一個(gè)軸
今天小編就為大家分享一篇np.newaxis 實(shí)現(xiàn)為 numpy.ndarray(多維數(shù)組)增加一個(gè)軸,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11python3文件復(fù)制、延遲文件復(fù)制任務(wù)的實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于python3文件復(fù)制、延遲文件復(fù)制任務(wù)的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用python3具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09Python實(shí)現(xiàn)的檢測(cè)網(wǎng)站掛馬程序
這篇文章主要介紹了Python實(shí)現(xiàn)的檢測(cè)網(wǎng)站掛馬程序,需要的朋友可以參考下2014-11-11python實(shí)現(xiàn)0到1之間的隨機(jī)數(shù)方式
這篇文章主要介紹了python實(shí)現(xiàn)0到1之間的隨機(jī)數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07python實(shí)現(xiàn)ID3決策樹(shù)算法
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)ID3決策樹(shù)算法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12PyTorch之怎樣選擇合適的優(yōu)化器和損失函數(shù)
這篇文章主要介紹了PyTorch怎樣選擇合適的優(yōu)化器和損失函數(shù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02Python調(diào)用ffmpeg開(kāi)源視頻處理庫(kù),批量處理視頻
本文主要介紹了如何用Python調(diào)用ffmpeg開(kāi)源視頻處理庫(kù),來(lái)實(shí)現(xiàn)視頻批量的處理:水印、背景音樂(lè)、剪輯、合并、幀率、速率、分辨率等操作2020-11-11Python時(shí)間序列處理之ARIMA模型的使用講解
今天小編就為大家分享一篇關(guān)于Python時(shí)間序列處理之ARIMA模型的使用講解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-04-04