摘要

弄了个memos,类似网上朋友圈?http://1.94.37.87:8945/explore/
给屋里的nas和win7弄了ups电源保护,nas是通过ping来自动关机的
弄了个jupyter,暂时这些

代码

import socket
import time
from datetime import datetime
import sys
import subprocess

# 定义全局状态变量
global_status = 30

# 定义日志文件名称
log_file = 'logping.txt'

def check_host(host, port=445, timeout=3):
    """尝试连接到指定的主机和端口。"""
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(timeout)
            s.connect((host, port))
            return True
    except (socket.timeout, socket.error):
        return False

def log_and_print(message, end='\n'):
    """同时将消息打印到屏幕和写入日志文件。"""
    # 打印到屏幕
    print(message, end=end)
    # 写入文件
    with open(log_file, 'a') as f:
        f.write(f'{message}{end}')

def monitor_host(host, interval=5):
    """定期检查指定主机的端口状态。"""
    global global_status
    while True and global_status:
        if not check_host(host):
            print("ping不通,准备关机")
            log_and_print(f"{datetime.now()}: {host} 在端口445上不可达。", end='')
            global_status -= 1
            log_and_print(f" 尝试重新连接,第{global_status}次...")
            time.sleep(1)
            if global_status == 1:
                log_and_print(" 执行pyshut.py脚本。")
                subprocess.run(['python', 'pyshut.py'])
                global_status = 0
        else:
            global_status = 30
            log_and_print(f"{datetime.now()}: {host} 在端口445上可达。")
        time.sleep(interval)

if __name__ == "__main__":
    host = '192.168.1.xxx'  # 要检查的主机IP地址
    monitor_host(host)  # 开始监控