Files
UPC-Resent/crond/upcrond-dev3.py
2026-03-22 17:17:44 +08:00

86 lines
3.3 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Auto-generated from template. DO NOT EDIT DIRECTLY!
# Device: 设备UDP示例 (dev3) - UDP Protocol
import time
import logging
import os
import socket
import sys
import subprocess
# ====== 配置参数(从配置文件读取)======
TARGET_IP = '192.168.8.9'
TARGET_PORT = 10080
LOG_FILE = '/home/smart/pythonPJ/upc_resent/log/crond-dev3.log'
RESTART_COMMAND = "/usr/bin/python3 /home/smart/pythonPJ/upc_resent/bin/dev3.py &"
DEVICE_ID = 'dev3'
# =========================
ISOTIMEFORMAT = '%Y-%m-%d %X'
logging.basicConfig(filename=LOG_FILE, filemode="a", level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s', datefmt=ISOTIMEFORMAT)
def is_udp_port_open(ip, port):
"""
检查UDP端口是否可用。
UDP是无连接的这里通过检查端口是否被占用或发送测试数据来判断。
"""
try:
# 尝试绑定到该端口,如果成功说明端口未被占用(服务未启动)
# 如果失败说明端口已被占用(服务正在运行)
test_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
test_sock.settimeout(1)
test_sock.bind((ip, int(port)))
test_sock.close()
# 如果绑定成功,说明服务未启动
print(f"[{DEVICE_ID}] UDP端口 {port} 未被占用,服务可能未运行")
logging.warning(f"UDP端口 {port} 未被占用,服务可能未运行,尝试重启程序")
logging.info(f"执行重启命令: {RESTART_COMMAND}")
os.system(RESTART_COMMAND)
return False
except OSError as e:
# 绑定失败,说明端口已被占用,服务正在运行
if "Address already in use" in str(e) or "98" in str(e):
print(f"[{DEVICE_ID}] UDP端口 {port} is open (已被占用,服务运行中)")
logging.info(f"UDP端口 {port} is open (服务运行中)")
return True
else:
print(f"[{DEVICE_ID}] 检查UDP端口 {port} 时发生错误: {e}")
logging.error(f"检查UDP端口 {port} 时发生错误: {e}")
return False
def check_process_running():
"""通过进程名检查服务是否正在运行"""
try:
# 检查是否有对应设备的Python进程在运行
cmd = f"ps aux | grep '{DEVICE_ID}.py' | grep -v grep"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode == 0 and result.stdout.strip():
print(f"[{DEVICE_ID}] 进程检查: 服务正在运行")
logging.info(f"进程检查: 服务正在运行")
return True
else:
print(f"[{DEVICE_ID}] 进程检查: 服务未运行")
logging.warning(f"进程检查: 服务未运行,尝试重启")
logging.info(f"执行重启命令: {RESTART_COMMAND}")
os.system(RESTART_COMMAND)
return False
except Exception as e:
print(f"[{DEVICE_ID}] 进程检查失败: {e}")
logging.error(f"进程检查失败: {e}")
return False
if __name__ == '__main__':
logging.info(f"[{DEVICE_ID}] 启动UDP端口检查程序检查 {TARGET_IP}:{TARGET_PORT}")
print(f"[{DEVICE_ID}] 启动UDP端口检查程序检查 {TARGET_IP}:{TARGET_PORT}")
# 对于UDP优先使用进程检查方式
check_process_running()