Python腳本實現(xiàn)定時監(jiān)控端口
python寫了一個監(jiān)控端口服務(wù),自動重啟的腳本
為了防止以后找不到代碼,特別記錄一下
import os
import sys
import threading
import time
import socket
import subprocess
def check_port_and_run_script(port, script_path):
# 創(chuàng)建一個socket對象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 設(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('定時任務(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("定時器任務(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è)置定時器
set_timer(20)
# 主線程可以繼續(xù)執(zhí)行其他任務(wù),或者簡單地等待定時器執(zhí)行
try:
while True:
time.sleep(1) # 防止主線程立即退出,可以按需調(diào)整或添加其他邏輯
except KeyboardInterrupt:
print("程序被用戶中斷")用來監(jiān)控的配置文件,shany.txt 內(nèi)容如下
8686:=>D:/WorkSpace/shany/simulator/target/start.sh
其中8686是端口號, :=> 作為分隔符 ,后面地址對應(yīng)腳本的所在路徑
方法補充
下面小編為大家整理了一些其他Python進(jìn)行監(jiān)控端口的方法,希望對大家有所幫助
Python3使用 socket 庫監(jiān)控端口
import socket
def monitor_port(port_number):
# 創(chuàng)建一個 socket 對象
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)聽網(wǎng)絡(luò)端口號程序
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è)置超時時間
result = sock.connect_ex((host, port))
sock.close() # 在檢查后關(guān)閉 socket
if result == 0:
return f"端口 {port} 是開放的。"
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(",") # 以逗號分隔多個端口號
try:
time_interval = int(entry_timeset.get())
if time_interval <= 0:
raise ValueError("時間間隔必須大于0")
for port in ports:
port = int(port)
if not (0 <= port <= 65535):
raise ValueError(f"端口號 {port} 必須在 0 到 65535 之間")
# 初始化成功和失敗計數(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("錯誤", 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")
# 更新成功和失敗計數(shù)
if "開放" in result:
port_success_counts[port] += 1
else:
port_failure_counts[port] += 1
update_port_counts()
root.after(time_interval * 1000, start_monitoring) # 定時監(jiān)測
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)測工具")
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, 用逗號分隔)")
label_port2.grid(row=1, column=2)
label_timeset = tk.Label(root, text="時間 (間隔):")
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)建滾動條
scrollbar = tk.Scrollbar(root)
scrollbar.grid(row=4, column=3, sticky=tk.NS)
# 創(chuàng)建文本框并關(guān)聯(lián)滾動條
text_result = tk.Text(root, height=10, width=50, yscrollcommand=scrollbar.set)
text_result.grid(row=4, column=0, columnspan=3, sticky=tk.NSEW)
# 配置滾動條
scrollbar.config(command=text_result.yview)
# 初始化全局計數(shù)器
port_success_counts = {}
port_failure_counts = {}
# 啟動主循環(huán)
root.mainloop()到此這篇關(guān)于Python腳本實現(xiàn)定時監(jiān)控端口的文章就介紹到這了,更多相關(guān)Python監(jiān)控端口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PyQt5內(nèi)嵌瀏覽器注入JavaScript腳本實現(xiàn)自動化操作的代碼實例
今天小編就為大家分享一篇關(guān)于PyQt5內(nèi)嵌瀏覽器注入JavaScript腳本實現(xiàn)自動化操作的代碼實例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-02-02
Python不使用int()函數(shù)把字符串轉(zhuǎn)換為數(shù)字的方法
今天小編就為大家分享一篇Python不使用int()函數(shù)把字符串轉(zhuǎn)換為數(shù)字的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
Python進(jìn)階之使用selenium爬取淘寶商品信息功能示例
這篇文章主要介紹了Python進(jìn)階之使用selenium爬取淘寶商品信息功能,結(jié)合實例形式詳細(xì)分析了Python使用selenium與requests模塊爬取淘寶商品信息的相關(guān)操作技巧,需要的朋友可以參考下2019-09-09
python深度學(xué)習(xí)TensorFlow神經(jīng)網(wǎng)絡(luò)模型的保存和讀取
這篇文章主要為大家介紹了python深度學(xué)習(xí)TensorFlow神經(jīng)網(wǎng)絡(luò)如何將訓(xùn)練得到的模型保存下來方便下次直接使用。為了讓訓(xùn)練結(jié)果可以復(fù)用,需要將訓(xùn)練好的神經(jīng)網(wǎng)絡(luò)模型持久化2021-11-11
python筆記_將循環(huán)內(nèi)容在一行輸出的方法
今天小編就為大家分享一篇python筆記_將循環(huán)內(nèi)容在一行輸出的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Python生命游戲?qū)崿F(xiàn)原理及過程解析(附源代碼)
這篇文章主要介紹了Python生命游戲?qū)崿F(xiàn)原理及過程解析(附源代碼),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08

