86 lines
3.4 KiB
Smarty
86 lines
3.4 KiB
Smarty
#!/usr/bin/env python3
|
||
# -*- coding: UTF-8 -*-
|
||
# Auto-generated from template. DO NOT EDIT DIRECTLY!
|
||
# Device: {device_name} ({device_id}) - UDP Protocol
|
||
|
||
import time
|
||
import logging
|
||
import os
|
||
import socket
|
||
import sys
|
||
import subprocess
|
||
|
||
# ====== 配置参数(从配置文件读取)======
|
||
TARGET_IP = '{tms_server_ip}'
|
||
TARGET_PORT = {listen_port}
|
||
LOG_FILE = '{base_dir}/log/crond-{device_id}.log'
|
||
RESTART_COMMAND = "{python_path} {base_dir}/bin/{device_id}.py &"
|
||
DEVICE_ID = '{device_id}'
|
||
# =========================
|
||
|
||
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()
|