""" 워치독 태스크를 XML로 직접 등록 관리자 권한 없이 현재 사용자 세션으로 등록 """ import subprocess, sys, os, tempfile PROJECT = r'C:\Users\whdwo\OneDrive\바탕 화면\stockbot_v3' SCRIPT = fr'{PROJECT}\scripts\run_watchdog.ps1' xml = f''' \\StockBot\\StockBot_Watchdog InteractiveToken LeastPrivilege false false PT3M IgnoreNew true PT10M PT1H true false 2026-05-27T09:00:00+09:00 PT5M PT6H10M true 1 powershell.exe -NonInteractive -ExecutionPolicy Bypass -File "{SCRIPT}" {PROJECT} ''' # UTF-16 LE BOM으로 임시 파일 저장 (Task Scheduler XML 요구사항) with tempfile.NamedTemporaryFile(suffix='.xml', delete=False, mode='wb') as f: f.write(b'\xff\xfe') # UTF-16 LE BOM f.write(xml.encode('utf-16-le')) tmp = f.name try: # 1단계: XML로 등록 ps_cmd = f'Register-ScheduledTask -TaskName "StockBot_Watchdog" -TaskPath "\\\\StockBot\\\\" -Xml (Get-Content -Path \'{tmp}\' -Raw -Encoding Unicode) -Force | Out-Null; Write-Host "1단계 완료"' r = subprocess.run( ['powershell', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', ps_cmd], capture_output=True, text=True, encoding='utf-8', errors='replace' ) print(r.stdout.strip()) # 2단계: 한글 경로 깨짐 교정 (setup_scheduler.ps1과 동일 방식) # 등록된 태스크의 Arguments에서 garbled 문자열 추출 → 정상 한글로 치환 후 재등록 fix_cmd = r''' $task = Get-ScheduledTask -TaskName "StockBot_Watchdog" -TaskPath "\StockBot\" $stored = $task.Actions[0].Arguments if ($stored -match [regex]::Escape("바탕 화면")) { Write-Host "경로 정상" } else { $xml = Export-ScheduledTask -TaskName "StockBot_Watchdog" -TaskPath "\StockBot\" if ($stored -match 'OneDrive\\(.+?)\\stockbot') { $garbled = $Matches[1] $fixedXml = $xml.Replace($garbled, "바탕 화면") Register-ScheduledTask -TaskName "StockBot_Watchdog" -TaskPath "\StockBot\" -Xml $fixedXml -Force | Out-Null Write-Host "한글 경로 교정 완료" } else { Write-Host "교정 패턴 미일치 — 수동 확인 필요" } } ''' r2 = subprocess.run( ['powershell', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', fix_cmd], capture_output=True, text=True, encoding='utf-8', errors='replace' ) print(r2.stdout.strip()) if r2.returncode != 0: print('STDERR:', r2.stderr.strip()) # 최종 확인 check = subprocess.run( ['powershell', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', 'Get-ScheduledTask -TaskPath "\\StockBot\\" | Format-Table TaskName, State -AutoSize'], capture_output=True, text=True, encoding='utf-8', errors='replace' ) print(check.stdout) finally: os.unlink(tmp)