1
This commit is contained in:
54
templates/crond_tcp.py.tpl
Normal file
54
templates/crond_tcp.py.tpl
Normal 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)
|
||||
Reference in New Issue
Block a user