This commit is contained in:
zj
2026-03-22 17:17:44 +08:00
commit b64c39ecbd
29 changed files with 2720 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Auto-generated from template. DO NOT EDIT DIRECTLY!
# Device: {device_name} ({device_id})
import time
import logging
import os
import socket
import sys
# ====== 配置参数(从配置文件读取)======
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_port_open(ip, port):
"""检查指定IP和端口是否可达"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
try:
logging.debug(f"尝试连接到 {{ip}}:{{port}}...")
s.connect((ip, int(port)))
s.shutdown(socket.SHUT_RDWR)
print(f"[{{DEVICE_ID}}] 端口 {{port}} is open")
logging.info(f"端口 {{port}} is open")
return True
except (OSError, socket.timeout) as e:
print(f"[{{DEVICE_ID}}] 端口 {{port}} is down")
logging.warning(f"端口 {{port}} 检查失败: {{e}},尝试重启程序")
logging.info(f"执行重启命令: {{RESTART_COMMAND}}")
os.system(RESTART_COMMAND)
return False
except ValueError:
print(f"错误: 端口 '{{port}}' 不是有效的数字。")
logging.error(f"端口 '{{port}}' 不是有效的数字。")
return False
finally:
s.close()
if __name__ == '__main__':
logging.info(f"[{{DEVICE_ID}}] 启动端口检查程序,检查 {{TARGET_IP}}:{{TARGET_PORT}}")
print(f"[{{DEVICE_ID}}] 启动端口检查程序,检查 {{TARGET_IP}}:{{TARGET_PORT}}")
is_port_open(TARGET_IP, TARGET_PORT)