-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
578 lines (491 loc) · 22.9 KB
/
app.py
File metadata and controls
578 lines (491 loc) · 22.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
import threading
import time
import re
from datetime import datetime
from flask import Flask, render_template_string, request, jsonify
from ping3 import ping
app = Flask(__name__)
ping_results = {}
check_interval = 30
last_scan_time = None
def perform_ping_check():
"""모든 IP에 ping을 수행하고 결과를 업데이트"""
global last_scan_time
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
for ip in list(ping_results.keys()):
try:
delay = ping(ip, timeout=1)
if delay is not None:
status = "UP"
rtt_ms = round(delay * 1000, 2)
else:
status = "DOWN"
rtt_ms = None
except Exception:
status = "ERROR"
rtt_ms = None
prev = ping_results.get(ip, {})
ping_results[ip] = {
"equipment": prev.get("equipment", "Unknown"),
"site": prev.get("site", "Unknown"),
"status": status,
"rtt_ms": rtt_ms,
"checked_at": now,
"memo": prev.get("memo", ""),
}
last_scan_time = now
def ping_loop():
"""IP들을 주기적으로 ping하는 백그라운드 스레드"""
while True:
perform_ping_check()
time.sleep(check_interval)
HTML_TEMPLATE = """
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>IP Ping Monitor</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
.container { max-width: 1400px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
textarea { width: 100%; height: 250px; font-family: monospace; padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 12px; }
table { border-collapse: collapse; width: 100%; margin-top: 20px; }
th, td { border: 1px solid #ddd; padding: 10px; text-align: left; font-size: 13px; }
th { background-color: #4CAF50; color: white; font-weight: bold; }
tr:nth-child(even) { background-color: #f9f9f9; }
.up { color: green; font-weight: bold; }
.down { color: red; font-weight: bold; }
.error { color: orange; font-weight: bold; }
button { padding: 10px 20px; background: #4CAF50; color: white; border: none; cursor: pointer; border-radius: 4px; margin: 5px 5px 5px 0; font-size: 14px; }
button:hover { background: #45a049; }
button:active { background: #3d8b40; }
button:disabled { background: #999; cursor: not-allowed; }
.info { background: #e7f3fe; padding: 12px; margin: 10px 0; border-left: 4px solid #2196F3; border-radius: 4px; }
code { background: #f4f4f4; padding: 2px 6px; border-radius: 3px; font-family: monospace; }
input[type="text"] { font-size: 12px; }
input[type="checkbox"] { cursor: pointer; width: 18px; height: 18px; }
.auto-refresh-badge { background: #4CAF50; color: white; padding: 4px 8px; border-radius: 3px; font-size: 12px; }
#dataContainer { display: none; }
.timer-badge { background: #2196F3; color: white; padding: 4px 8px; border-radius: 3px; font-size: 12px; margin-left: 10px; }
.memo-saved { color: #4CAF50; font-weight: bold; }
</style>
</head>
<body>
<div class="container">
<h1>🌐 IP Ping 모니터</h1>
<h3>1단계: 텍스트 붙여넣기</h3>
<div class="info">
<strong>MOSS 내용을 아래에 붙여넣으세요.</strong>
<br/>자동 추출: <code>장비명:</code> | <code>사업장명:</code> | <code>장비IP:</code>
</div>
<textarea id="inputText" placeholder="text.txt 전체 내용을 붙여넣으세요..."></textarea>
<br><br>
<button id="parseBtn">✓ 추출 시작</button>
<div id="dataContainer" style="display: none;">
<h3>2단계: 모니터링 상태 (<span id="itemCount">0</span>개 항목)</h3>
<div class="info">
마지막 체크: <strong id="lastScan">대기중</strong> | 주기: <strong>{{ interval }}초</strong>
<br/>
<span class="auto-refresh-badge">🔄 자동 갱신 중</span>
<span class="timer-badge">⏱️ 다음 갱신: <span id="nextRefresh">{{ interval }}</span>초</span>
</div>
<button id="refreshBtn" onclick="manualRefresh()">🔄 수동 갱신 (즉시 Ping)</button>
<table>
<thead>
<tr>
<th style="width: 6%;">알림여부</th>
<th style="width: 21%;">장비명</th>
<th style="width: 21%;">사업장명</th>
<th style="width: 10%;">IP 주소</th>
<th style="width: 9%;">상태</th>
<th style="width: 19%;">비고 (메모)</th>
<th style="width: 7%;">체크시간</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</div>
</div>
<script>
const REFRESH_INTERVAL = {{ interval }} * 1000; // 밀리초 단위
let autoRefreshInterval = null; // 자동 갱신 타이머 ID
let countdownInterval = null; // 카운트다운 타이머 ID
let remainingTime = {{ interval }}; // 남은 시간
let memoMap = {}; // 메모 저장소 (IP → 메모)
let checkedIPs = {}; // 체크 상태 저장소 (IP → true/false)
let prevStatus = {}; // 이전 상태 저장 (IP → status)
// 상태 우선순위 (UP가 최상단)
const statusPriority = {
'UP': 0,
'DOWN': 1,
'ERROR': 2
};
// localStorage에서 메모 로드
function loadMemos() {
const saved = localStorage.getItem('pingMemos');
if (saved) {
memoMap = JSON.parse(saved);
console.log('✓ 저장된 메모 로드 완료:', Object.keys(memoMap).length + '개');
}
}
// localStorage에서 체크 상태 로드
function loadCheckedIPs() {
const saved = localStorage.getItem('checkedIPs');
if (saved) {
checkedIPs = JSON.parse(saved);
console.log('✓ 저장된 체크 상태 로드 완료:', Object.keys(checkedIPs).length + '개');
}
}
// localStorage에 메모 저장
function saveMemos() {
localStorage.setItem('pingMemos', JSON.stringify(memoMap));
console.log('✓ 메모 저장 완료');
}
// localStorage에 체크 상태 저장
function saveCheckedIPs() {
localStorage.setItem('checkedIPs', JSON.stringify(checkedIPs));
}
// 메모 업데이트 함수
function updateMemo(ip, memo) {
memoMap[ip] = memo;
saveMemos();
}
// 체크박스 상태 업데이트
function updateCheckbox(ip, checked) {
checkedIPs[ip] = checked;
saveCheckedIPs();
}
// UP 상태 변화 감지 및 알림
function checkStatusChanges(results) {
const recoveredIPs = [];
for (const [ip, result] of Object.entries(results)) {
const currentStatus = result.status;
const previousStatus = prevStatus[ip] || 'INIT';
// DOWN/ERROR → UP 변화 감지 (그리고 체크되어 있는 항목만)
if ((previousStatus === 'DOWN' || previousStatus === 'ERROR' || previousStatus === 'INIT')
&& currentStatus === 'UP'
&& checkedIPs[ip]) {
recoveredIPs.push(ip);
console.log('🔔 UP 감지:', ip);
}
// 현재 상태를 이전 상태로 업데이트
prevStatus[ip] = currentStatus;
}
// 복구된 IP가 있으면 알림 표시
if (recoveredIPs.length > 0) {
showNotification(recoveredIPs);
}
}
// 알림 팝업 함수
function showNotification(ips) {
const ipList = ips.join(', ');
const message = `✅ 다음 장비가 정상(UP)되었습니다:\n\n${ipList}`;
alert(message);
console.log('🔔 알림 표시:', message);
}
// 테이블 갱신 함수 (메모 보존 + 상태 정렬 + 체크박스)
function updateTable() {
console.log('테이블 갱신 중...');
fetch('/status')
.then(r => r.json())
.then(data => {
const results = data.results;
const lastScan = data.last_scan_time;
if (Object.keys(results).length > 0) {
document.getElementById('dataContainer').style.display = 'block';
document.getElementById('itemCount').textContent = Object.keys(results).length;
document.getElementById('lastScan').textContent = lastScan || '대기중';
// 상태 변화 감지 (알림 필요)
checkStatusChanges(results);
// 1. 데이터를 배열로 변환
const rows = [];
for (const [ip, result] of Object.entries(results)) {
rows.push({
ip: ip,
equipment: result.equipment,
site: result.site,
status: result.status,
checked_at: result.checked_at,
memo: memoMap[ip] || ''
});
}
// 2. 상태 기준으로 정렬 (UP → DOWN → ERROR)
rows.sort((a, b) => {
return statusPriority[a.status] - statusPriority[b.status];
});
console.log('✓ 상태 정렬 완료 (UP 맨 위)');
// 3. 정렬된 순서로 테이블에 추가
const tableBody = document.getElementById('tableBody');
tableBody.innerHTML = '';
rows.forEach(row => {
const statusClass = row.status === 'UP' ? 'up' : (row.status === 'DOWN' ? 'down' : 'error');
const isChecked = checkedIPs[row.ip] ? 'checked' : '';
const tr = document.createElement('tr');
tr.innerHTML = `
<td style="text-align: center;">
<input type="checkbox"
class="row-checkbox"
data-ip="${row.ip}"
${isChecked}
/>
</td>
<td>${row.equipment}</td>
<td>${row.site}</td>
<td><code>${row.ip}</code></td>
<td><span class="${statusClass}">● ${row.status}</span></td>
<td>
<input type="text"
value="${row.memo}"
placeholder="메모 입력..."
data-ip="${row.ip}"
class="memo-input"
style="width: 95%; padding: 4px;"
/>
</td>
<td style="font-size: 11px; color: #666; text-align: center;">${row.checked_at || '-'}</td>
`;
tableBody.appendChild(tr);
});
// 4. 체크박스 이벤트 리스너 추가
document.querySelectorAll('.row-checkbox').forEach(checkbox => {
checkbox.addEventListener('change', function() {
updateCheckbox(this.getAttribute('data-ip'), this.checked);
});
});
// 5. 메모 입력 필드에 이벤트 리스너 추가
document.querySelectorAll('.memo-input').forEach(input => {
input.addEventListener('input', function() {
updateMemo(this.getAttribute('data-ip'), this.value);
});
});
console.log('✓ 테이블 갱신 완료 (체크박스 + 메모 + 정렬)');
} else {
document.getElementById('dataContainer').style.display = 'none';
}
})
.catch(err => {
console.error('❌ 갱신 실패:', err);
});
}
// 카운트다운 타이머 시작
function startCountdown() {
remainingTime = {{ interval }};
document.getElementById('nextRefresh').textContent = remainingTime;
if (countdownInterval) clearInterval(countdownInterval);
countdownInterval = setInterval(function() {
remainingTime--;
document.getElementById('nextRefresh').textContent = remainingTime;
if (remainingTime <= 0) {
clearInterval(countdownInterval);
}
}, 1000);
}
// 자동 갱신 시작
function startAutoRefresh() {
console.log('✓ 자동 갱신 시작: ' + (REFRESH_INTERVAL / 1000) + '초 주기');
startCountdown();
if (autoRefreshInterval) clearInterval(autoRefreshInterval);
autoRefreshInterval = setInterval(function() {
console.log('🔄 자동 갱신 실행');
updateTable();
startCountdown();
}, REFRESH_INTERVAL);
}
// 수동 갱신 함수 (즉시 ping 실행 + 타이머 리셋)
function manualRefresh() {
console.log('🔄 수동 갱신 시작 (즉시 Ping 수행)...');
const btn = document.getElementById('refreshBtn');
btn.disabled = true;
btn.textContent = '🔄 Ping 중...';
// 기존 자동 갱신 타이머 제거
if (autoRefreshInterval) {
clearInterval(autoRefreshInterval);
console.log('기존 자동 갱신 타이머 제거');
}
if (countdownInterval) {
clearInterval(countdownInterval);
}
fetch('/manual-refresh', {
method: 'POST'
})
.then(r => r.json())
.then(data => {
console.log('✓ Ping 완료:', data.checked_count + '개 항목');
updateTable();
// 수동 갱신 후 자동 갱신 타이머 재설정 (리셋)
console.log('⏱️ 자동 갱신 타이머 리셋 ({{ interval }}초)');
startAutoRefresh();
btn.disabled = false;
btn.textContent = '🔄 수동 갱신 (즉시 Ping)';
})
.catch(err => {
console.error('❌ Ping 실패:', err);
alert('Ping 실패: ' + err.message);
btn.disabled = false;
btn.textContent = '🔄 수동 갱신 (즉시 Ping)';
// 실패 시에도 자동 갱신 재시작
startAutoRefresh();
});
}
// 페이지 로드 후 초기화
window.addEventListener('load', function() {
console.log('✓ 페이지 로드 완료');
// 저장된 데이터 로드
loadMemos();
loadCheckedIPs();
// 초기 갱신
updateTable();
// 자동 갱신 시작
startAutoRefresh();
// 추출 버튼 이벤트
document.getElementById('parseBtn').addEventListener('click', function() {
const text = document.getElementById('inputText').value;
if (!text.trim()) {
alert('텍스트를 붙여넣어 주세요.');
return;
}
const btn = document.getElementById('parseBtn');
btn.disabled = true;
btn.textContent = '✓ 추출 중...';
fetch('/parse', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({text: text})
}).then(r => r.json())
.then(data => {
if (data.count > 0) {
alert(data.count + '개 항목 추출 완료!');
console.log('✓ 텍스트 추출 완료, 즉시 Ping 테스트 시작');
// 기존 타이머 제거
if (autoRefreshInterval) clearInterval(autoRefreshInterval);
if (countdownInterval) clearInterval(countdownInterval);
// 즉시 Ping 수행
performInitialPing();
} else {
alert('추출된 항목이 없습니다. 텍스트 형식을 확인하세요.');
btn.disabled = false;
btn.textContent = '✓ 추출 시작';
}
})
.catch(err => {
console.error(err);
alert('파싱 중 오류 발생');
btn.disabled = false;
btn.textContent = '✓ 추출 시작';
});
});
});
// 초기 Ping 테스트 함수 (텍스트 추출 후)
function performInitialPing() {
console.log('🔄 초기 Ping 테스트 시작...');
const btn = document.getElementById('parseBtn');
fetch('/manual-refresh', {
method: 'POST'
})
.then(r => r.json())
.then(data => {
console.log('✓ 초기 Ping 완료:', data.checked_count + '개 항목');
updateTable();
// Ping 완료 후 자동 갱신 시작
console.log('⏱️ 자동 갱신 시작');
startAutoRefresh();
btn.disabled = false;
btn.textContent = '✓ 추출 시작';
})
.catch(err => {
console.error('❌ 초기 Ping 실패:', err);
alert('초기 Ping 실패: ' + err.message);
btn.disabled = false;
btn.textContent = '✓ 추출 시작';
// 실패 시에도 자동 갱신 시작
startAutoRefresh();
});
}
</script>
</body>
</html>
"""
@app.route("/")
def index():
return render_template_string(
HTML_TEMPLATE,
results=ping_results,
last_scan_time=last_scan_time,
interval=check_interval,
)
@app.route("/status")
def get_status():
"""현재 상태를 JSON으로 반환"""
return jsonify({
"results": ping_results,
"last_scan_time": last_scan_time,
"interval": check_interval,
})
@app.route("/manual-refresh", methods=["POST"])
def manual_refresh():
"""수동 갱신: 즉시 모든 IP에 ping을 수행"""
print("🔄 수동 Ping 테스트 시작...")
perform_ping_check()
print("✓ 수동 Ping 테스트 완료")
return jsonify({
"status": "ok",
"checked_count": len(ping_results),
"last_scan_time": last_scan_time
})
@app.route("/parse", methods=["POST"])
def parse_text():
"""
텍스트에서 정확하게 추출:
- 장비명: "장비명:" 키워드를 찾아서 다음 "숫자. " 앞까지
- 사업장명: "사업장명:" 키워드를 찾아서 다음 "숫자. " 앞까지
- 장비IP: "장비IP:" 뒤의 IPv4 주소
"""
data = request.get_json()
text = data.get("text", "")
# 섹션 분리: "1. 발생" 으로 시작하는 부분별로
sections = re.split(r'(?=1\.\s*발생)', text)
count = 0
processed_ips = set()
for section in sections:
# 필수: 장비IP 추출
ip_match = re.search(
r'장비IP\s*:\s*([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})',
section
)
if not ip_match:
continue
ip = ip_match.group(1).strip()
# 중복 방지
if ip in processed_ips:
continue
processed_ips.add(ip)
# 장비명 추출: "장비명:" 키워드를 찾아서 다음 "숫자. " 앞까지
equipment_match = re.search(
r'장비명:\s*(.+?)\s+\d+\.',
section
)
equipment = equipment_match.group(1).strip() if equipment_match else "Unknown"
# 사업장명 추출: "사업장명:" 키워드를 찾아서 다음 "숫자. " 앞까지
site_match = re.search(
r'사업장명:\s*(.+?)\s+\d+\.',
section
)
site = site_match.group(1).strip() if site_match else "Unknown"
# 기존 데이터 유지 (메모 등)
prev = ping_results.get(ip, {})
ping_results[ip] = {
"equipment": equipment,
"site": site,
"status": prev.get("status", "대기"),
"rtt_ms": prev.get("rtt_ms"),
"checked_at": prev.get("checked_at", "추출됨"),
"memo": prev.get("memo", ""),
}
count += 1
return {"status": "ok", "count": count}
if __name__ == "__main__":
t = threading.Thread(target=ping_loop, daemon=True)
t.start()
print("\n✓ 서버 시작: http://localhost:5000\n")
app.run(host="0.0.0.0", port=5000, debug=True)