70 lines
2.7 KiB
Python
70 lines
2.7 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: UTF-8 -*-
|
||
|
||
import time
|
||
import logging
|
||
import os
|
||
import socket
|
||
import sys # sys 模块用于 sys.exit(),虽然这里没有直接使用,但通常在脚本中需要
|
||
|
||
# --- 配置日志 ---
|
||
# 确保日志文件路径正确
|
||
LOG_FILE = '/opt/upc_resent/log/upc-192.168.8.125.log'
|
||
# 定义时间格式,将被 logging.basicConfig 的 datefmt 使用
|
||
ISOTIMEFORMAT = '%Y-%m-%d %X'
|
||
|
||
# 配置日志,确保只执行一次
|
||
# format 中包含了时间戳 %(asctime)s,所以不需要手动在日志字符串中添加 datetime
|
||
logging.basicConfig(filename=LOG_FILE, filemode="a", level=logging.DEBUG,
|
||
format='%(asctime)s - %(levelname)s - %(message)s', datefmt=ISOTIMEFORMAT)
|
||
# --- 日志配置结束 ---
|
||
|
||
|
||
def IsOpen(ip, port):
|
||
"""
|
||
检查指定IP和端口是否可达。
|
||
如果端口不可达,则记录警告并尝试重启另一个Python脚本。
|
||
"""
|
||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
s.settimeout(1) # 设置连接超时为1秒,避免无限期阻塞
|
||
try:
|
||
logging.debug(f"尝试连接到 {ip}:{port}...")
|
||
s.connect((ip, int(port)))
|
||
s.shutdown(socket.SHUT_RDWR) # 使用 SHUT_RDWR 代替数字 2,更具可读性
|
||
|
||
print(f"端口 {port} is open") # Python 3 print 函数
|
||
logging.info(f"端口 {port} is open")
|
||
return True
|
||
except (OSError, socket.timeout) as e: # 捕获具体的网络错误和超时
|
||
print(f"端口 {port} is down") # Python 3 print 函数
|
||
logging.warning(f"端口 {port} 检查失败: {e},尝试重启程序")
|
||
|
||
# --- 重启命令 ---
|
||
# 确保这里的 python3 路径和脚本路径正确
|
||
# 这里的脚本名 "192.168.8.125.py" 看起来是硬编码的,请确认是否正确
|
||
restart_command = "/usr/bin/python3 /opt/upc_resent/bin/192.168.8.125.py &"
|
||
logging.info(f"执行重启命令: {restart_command}")
|
||
os.system(restart_command)
|
||
# --- 重启命令结束 ---
|
||
|
||
return False
|
||
except ValueError: # 捕获 int(port) 转换失败的情况
|
||
print(f"错误: 端口 '{port}' 不是有效的数字。")
|
||
logging.error(f"端口 '{port}' 不是有效的数字。")
|
||
return False
|
||
finally:
|
||
s.close() # 确保无论成功或失败,socket 都会被关闭
|
||
|
||
|
||
if __name__ == '__main__':
|
||
# --- 目标设备IP和端口 ---
|
||
# 这些值在原脚本中是硬编码的,如果需要从命令行参数获取,请修改
|
||
target_ip = '192.168.8.9'
|
||
target_port = 10129
|
||
# --- 目标设备IP和端口结束 ---
|
||
|
||
logging.info(f"启动端口检查程序,检查 {target_ip}:{target_port}")
|
||
IsOpen(target_ip, target_port)
|
||
|
||
|