55 lines
1.8 KiB
Python
Executable File
55 lines
1.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# -*- coding: UTF-8 -*-
|
|
# Auto-generated from template. DO NOT EDIT DIRECTLY!
|
|
# Device: 设备73-TCP (dev1)
|
|
|
|
import time
|
|
import logging
|
|
import os
|
|
import socket
|
|
import sys
|
|
|
|
# ====== 配置参数(从配置文件读取)======
|
|
TARGET_IP = '192.168.8.9'
|
|
TARGET_PORT = 10079
|
|
LOG_FILE = '/home/smart/pythonPJ/upc_resent/log/crond-dev1.log'
|
|
RESTART_COMMAND = "/usr/bin/python3 /home/smart/pythonPJ/upc_resent/bin/dev1.py &"
|
|
DEVICE_ID = 'dev1'
|
|
# =========================
|
|
|
|
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)
|