網路磁碟機常遇到 Windows Event 1014
系統上只記錄問題發生點
需要記錄恢復時間點Windows Event 紀錄 : eventvwr.msc
---
測試方式
- 改 DNS
- netsh interface ip set dns "乙太網路" static 127.0.0.1
- netsh interface ip set dns "乙太網路" dhcp網路先停用
- 改 DNS
---
程式
檢查並記錄 log
import os import socket import datetime import time # === 設定區 === target_host = "IT-NAS" share_path = r"\\IT-NAS\share" log_dir = "C:/Logs" log_file = os.path.join(log_dir, "network_monitor.log") state_file = os.path.join(log_dir, "last_state.txt") time_file = os.path.join(log_dir, "last_state.time") check_interval_sec = 60 os.makedirs(log_dir, exist_ok=True) def get_connection_status(host, share): try: ip = socket.gethostbyname(host) except socket.gaierror: return "DNS_FAIL", None try: socket.create_connection((ip, 80), 3).close() except: return "TCP_FAIL", ip if not os.path.exists(share): return "UNC_FAIL", ip return "OK", ip def write_log(msg): with open(log_file, "a", encoding="utf-8") as f: f.write(msg + "\n") def get_last_state(): if os.path.exists(state_file): with open(state_file, "r") as f: return f.read().strip() return "OK" def set_last_state(state): with open(state_file, "w", encoding="utf-8") as f: f.write(state) def monitor_once(): now = datetime.datetime.now() now_str = now.strftime("%Y-%m-%d %H:%M:%S") status, ip = get_connection_status(target_host, share_path) last_state = get_last_state() if status == "OK" and last_state != "OK": # 剛恢復 if os.path.exists(time_file): with open(time_file, "r") as f: down_start_str = f.read().strip() down_start = datetime.datetime.strptime(down_start_str, "%Y-%m-%d %H:%M:%S") duration = now - down_start mins = int(duration.total_seconds() // 60) secs = int(duration.total_seconds() % 60) else: mins = secs = 0 write_log("===== 網路恢復 =====") write_log(f"時間:{now_str}") write_log(f"IP:{ip}") write_log(f"已恢復連線,離線時長:{mins} 分 {secs} 秒\n") elif status != "OK" and last_state == "OK": # 剛出現異常 write_log("===== 網路異常開始 =====") write_log(f"時間:{now_str}") write_log(f"類型:{status}") write_log(f"IP:{ip if ip else '無法解析'}") write_log(f"詳細:{'DNS 無法解析' if status == 'DNS_FAIL' else '無法連接 TCP 端口' if status == 'TCP_FAIL' else '磁碟路徑無法存取'}\n") with open(time_file, "w", encoding="utf-8") as f: f.write(now_str) # 更新狀態 set_last_state(status) # === 主迴圈 === while True: monitor_once() time.sleep(check_interval_sec)

