Skrypty nie ładują domyślnego pliku logów i nie wyświetlają histogramów. Czy można to…
- User
Skrypty nie ładują domyślnego pliku logów i nie wyświetlają histogramów. Czy można to poprawić?
Assistant
Oto poprawiona wersja skryptu, która automatycznie ładuje plik
dnsmasq.logz tego samego folderu i poprawnie wyświetla histogram:<!DOCTYPE html> <html lang="pl"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Analiza logów dnsmasq</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background-color: #1a1a1a; color: #e0e0e0; padding: 20px; line-height: 1.6; } .container { max-width: 1200px; margin: 0 auto; } h1 { color: #4a9eff; margin-bottom: 30px; text-align: center; font-size: 2.5em; } .file-input-wrapper { background: #2a2a2a; padding: 30px; border-radius: 10px; margin-bottom: 30px; text-align: center; border: 2px dashed #4a9eff; } .file-input { display: none; } .file-label { display: inline-block; padding: 12px 30px; background: #4a9eff; color: white; border-radius: 5px; cursor: pointer; transition: all 0.3s; font-weight: bold; } .file-label:hover { background: #357abd; transform: translateY(-2px); } .loading { text-align: center; color: #4a9eff; font-size: 1.2em; margin: 20px 0; } .error { background: #ff4444; color: white; padding: 15px; border-radius: 5px; margin: 20px 0; text-align: center; } .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 30px; } .stat-card { background: #2a2a2a; padding: 20px; border-radius: 10px; border: 1px solid #3a3a3a; transition: transform 0.3s; } .stat-card:hover { transform: translateY(-5px); border-color: #4a9eff; } .stat-number { font-size: 2.5em; font-weight: bold; color: #4a9eff; margin: 10px 0; } .stat-label { color: #999; font-size: 0.9em; text-transform: uppercase; } .chart-container { background: #2a2a2a; padding: 20px; border-radius: 10px; margin-bottom: 30px; position: relative; } .histogram-wrapper { height: 250px; position: relative; margin-top: 20px; } .histogram { display: flex; align-items: flex-end; height: 200px; gap: 2px; padding: 0 10px; } .bar { flex: 1; background: linear-gradient(to top, #4a9eff, #66b3ff); transition: all 0.3s; position: relative; cursor: pointer; min-height: 2px; } .bar:hover { background: linear-gradient(to top, #66b3ff, #88ccff); } .bar-value { position: absolute; top: -20px; left: 50%; transform: translateX(-50%); font-size: 0.7em; color: #fff; display: none; background: #333; padding: 2px 5px; border-radius: 3px; white-space: nowrap; } .bar:hover .bar-value { display: block; } .hour-labels { display: flex; justify-content: space-between; padding: 0 10px; margin-top: 10px; color: #999; font-size: 0.8em; } .top-list { background: #2a2a2a; padding: 20px; border-radius: 10px; margin-bottom: 20px; } .list-title { color: #4a9eff; margin-bottom: 15px; font-size: 1.5em; } .list-item { display: flex; justify-content: space-between; align-items: center; padding: 12px 15px; margin-bottom: 5px; background: #1a1a1a; border-radius: 5px; transition: all 0.3s; } .list-item:hover { background: #3a3a3a; transform: translateX(5px); } .rank { font-weight: bold; color: #4a9eff; margin-right: 15px; font-size: 1.2em; } .domain-name { flex: 1; color: #e0e0e0; word-break: break-all; } .count { background: #4a9eff; color: white; padding: 5px 10px; border-radius: 15px; font-size: 0.9em; font-weight: bold; min-width: 60px; text-align: center; } .period-selector { text-align: center; margin-bottom: 20px; } .period-btn { padding: 10px 20px; margin: 0 5px; background: #3a3a3a; color: white; border: none; border-radius: 5px; cursor: pointer; transition: all 0.3s; } .period-btn.active { background: #4a9eff; } .period-btn:hover { background: #4a9eff; } .dns-mapping { background: #2a2a2a; padding: 20px; border-radius: 10px; margin-bottom: 20px; } .dns-mapping input { width: 100%; padding: 10px; background: #1a1a1a; border: 1px solid #3a3a3a; color: white; border-radius: 5px; margin-bottom: 10px; } .dns-mapping button { padding: 10px 20px; background: #4a9eff; color: white; border: none; border-radius: 5px; cursor: pointer; transition: all 0.3s; } .dns-mapping button:hover { background: #357abd; } .mapping-result { margin-top: 15px; padding: 10px; background: #1a1a1a; border-radius: 5px; display: none; } @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } } .fade-in { animation: fadeIn 0.5s ease-out; } .reload-btn { position: fixed; bottom: 30px; right: 30px; background: #4a9eff; color: white; border: none; border-radius: 50%; width: 60px; height: 60px; font-size: 24px; cursor: pointer; box-shadow: 0 4px 10px rgba(0,0,0,0.5); transition: all 0.3s; } .reload-btn:hover { background: #357abd; transform: scale(1.1); } </style> </head> <body> <div class="container"> <h1>🔍 Analiza logów dnsmasq</h1> <div id="loading" class="loading" style="display: none;"> ⏳ Ładowanie pliku dnsmasq.log... </div> <div id="error" class="error" style="display: none;"></div> <div class="file-input-wrapper"> <input type="file" id="fileInput" class="file-input" accept=".log"> <label for="fileInput" class="file-label">Wybierz inny plik log</label> <p style="margin-top: 10px; color: #999;">Domyślnie ładowany jest plik dnsmasq.log</p> </div> <div class="period-selector" style="display: none;"> <button class="period-btn active" data-period="24h">Ostatnie 24h</button> <button class="period-btn" data-period="7d">Ostatni tydzień</button> </div> <div id="stats" style="display: none;"> <div class="stats-grid"> <div class="stat-card fade-in"> <div class="stat-label">Wszystkie zapytania</div> <div class="stat-number" id="totalQueries">0</div> </div> <div class="stat-card fade-in"> <div class="stat-label">Zaakceptowane</div> <div class="stat-number" id="acceptedQueries" style="color: #4CAF50;">0</div> </div> <div class="stat-card fade-in"> <div class="stat-label">Odrzucone</div> <div class="stat-number" id="rejectedQueries" style="color: #f44336;">0</div> </div> <div class="stat-card fade-in"> <div class="stat-label">Unikalne domeny</div> <div class="stat-number" id="uniqueDomains">0</div> </div> </div> <div class="chart-container fade-in"> <h3 style="margin-bottom: 20px; color: #4a9eff;">Histogram zapytań (godzinowy)</h3> <div class="histogram-wrapper"> <div class="histogram" id="histogram"></div> <div class="hour-labels"> <span>00:00</span> <span>06:00</span> <span>12:00</span> <span>18:00</span> <span>23:00</span> </div> </div> </div> <div class="top-list fade-in"> <h3 class="list-title">🏆 Top 10 domen</h3> <div id="topDomains"></div> </div> <div class="top-list fade-in"> <h3 class="list-title">💻 Top 10 hostów lokalnych</h3> <div id="topHosts"></div> </div> <div class="dns-mapping fade-in"> <h3 class="list-title">🔄 Odwrotne mapowanie DNS</h3> <input type="text" id="ipInput" placeholder="Wprowadź adres IP (np. 192.168.1.100)"> <button onclick="reverseDNS()">Sprawdź nazwę hosta</button> <div id="mappingResult" class="mapping-result"></div> </div> </div> </div> <button class="reload-btn" onclick="loadDefaultFile()" title="Odśwież dane">↻</button> <script> let logData = []; let ipToHostMap = {}; let currentPeriod = '24h'; // Automatyczne ładowanie domyślnego pliku przy starcie window.addEventListener('DOMContentLoaded', () => { loadDefaultFile(); }); // Funkcja ładowania domyślnego pliku function loadDefaultFile() { const loading = document.getElementById('loading'); const error = document.getElementById('error'); loading.style.display = 'block'; error.style.display = 'none'; // Próba załadowania pliku dnsmasq.log z tego samego katalogu fetch('dnsmasq.log') .then(response => { if (!response.ok) { throw new Error('Nie można załadować pliku dnsmasq.log'); } return response.text(); }) .then(content => { loading.style.display = 'none'; parseLog(content); }) .catch(err => { loading.style.display = 'none'; error.style.display = 'block'; error.innerHTML = `⚠️ ${err.message}<br>Proszę wybrać plik ręcznie lub umieścić plik dnsmasq.log w tym samym katalogu co plik HTML.`; }); } // Obsługa ręcznego wyboru pliku document.getElementById('fileInput').addEventListener('change', handleFile); // Obsługa przycisków okresu document.querySelectorAll('.period-btn').forEach(btn => { btn.addEventListener('click', () => { document.querySelectorAll('.period-btn').forEach(b => b.classList.remove('active')); btn.classList.add('active'); currentPeriod = btn.dataset.period; if (logData.length > 0) { analyzeLog(); } }); }); function handleFile(e) { const file = e.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = function(e) { const content = e.target.result; document.getElementById('error').style.display = 'none'; parseLog(content); }; reader.readAsText(file); } } function parseLog(content) { logData = []; ipToHostMap = {}; const lines = content.split('\n'); lines.forEach(line => { // Parsowanie różnych formatów logów dnsmasq // Format 1: Jan 14 12:34:56 dnsmasq[1234]: query[A] example.com from 192.168.1.100 const queryMatch = line.match(/(\w+\s+\d+\s+\d+:\d+:\d+).*query\[([A-Z]+)\]\s+(\S+)\s+from\s+(\S+)/); // Format 2: Jan 14 12:34:56 dnsmasq[1234]: blocked example.com is 0.0.0.0 const blockedMatch = line.match(/blocked\s+(\S+)/); // Format 3: Jan 14 12:34:56 dnsmasq[1234]: reply example.com is <CNAME> const replyMatch = line.match(/reply\s+(\S+)\s+is/); if (queryMatch) { const [_, timestamp, queryType, domain, sourceIP] = queryMatch; // Wydobycie nazwy hosta jeśli jest dostępna const hostMatch = line.match(/from\s+([^\/\s]+)\/(\S+)/); if (hostMatch) { ipToHostMap[hostMatch[2]] = hostMatch[1]; } logData.push({ timestamp: parseTimestamp(timestamp), type: queryType, domain: domain, sourceIP: sourceIP.replace(/\/.*$/, ''), // Usuń port jeśli jest blocked: false }); } else if (blockedMatch) { const domain = blockedMatch[1]; // Oznacz ostatnie zapytanie dla tej domeny jako zablokowane for (let i = logData.length - 1; i >= 0; i--) { if (logData[i].domain === domain) { logData[i].blocked = true; break; } } } }); if (logData.length > 0) { document.querySelector('.period-selector').style.display = 'block'; document.getElementById('stats').style.display = 'block'; analyzeLog(); } else { document.getElementById('error').style.display = 'block'; document.getElementById('error').innerHTML = '⚠️ Nie znaleziono danych w pliku log. Sprawdź format pliku.'; } } function parseTimestamp(timestamp) { const now = new Date(); const [month, day, time] = timestamp.split(/\s+/); const [hour, minute, second] = time.split(':'); const monthMap = { 'Jan': 0, 'Feb': 1, 'Mar': 2, 'Apr': 3, 'May': 4, 'Jun': 5, 'Jul': 6, 'Aug': 7, 'Sep': 8, 'Oct': 9, 'Nov': 10, 'Dec': 11 }; const date = new Date(now.getFullYear(), monthMap[month], parseInt(day), parseInt(hour), parseInt(minute), parseInt(second)); // Jeśli data jest w przyszłości, cofnij o rok if (date > now) { date.setFullYear(date.getFullYear() - 1); } return date; } function analyzeLog() { const now = new Date(); const cutoffTime = currentPeriod === '24h' ? new Date(now - 24 * 60 * 60 * 1000) : new Date(now - 7 * 24 * 60 * 60 * 1000); const filteredData = logData.filter(entry => entry.timestamp >= cutoffTime); // Statystyki const totalQueries = filteredData.length; const acceptedQueries = filteredData.filter(q => !q.blocked).length; const rejectedQueries = filteredData.filter(q => q.blocked).length; // Unikalne domeny const uniqueDomains = new Set(filteredData.map(q => q.domain)).size; // Top domeny const domainCounts = {}; filteredData.forEach(q => { domainCounts[q.domain] = (domainCounts[q.domain] || 0) + 1; }); const topDomains = Object.entries(domainCounts) .sort((a, b) => b[1] - a[1]) .slice(0, 10); // Top hosty const hostCounts = {}; filteredData.forEach(q => { const host = ipToHostMap[q.sourceIP] || q.sourceIP; hostCounts[host] = (hostCounts[host] || 0) + 1; }); const topHosts = Object.entries(hostCounts) .sort((a, b) => b[1] - a[1]) .slice(0, 10); // Histogram godzinowy const hourlyData = Array(24).fill(0); filteredData.forEach(q => { const hour = q.timestamp.getHours(); hourlyData[hour]++; }); // Aktualizacja UI updateStats(totalQueries, acceptedQueries, rejectedQueries, uniqueDomains); updateTopList('topDomains', topDomains); updateTopList('topHosts', topHosts); updateHistogram(hourlyData); } function updateStats(total, accepted, rejected, unique) { document.getElementById('totalQueries').textContent = total.toLocaleString(); document.getElementById('acceptedQueries').textContent = accepted.toLocaleString(); document.getElementById('rejectedQueries').textContent = rejected.toLocaleString(); document.getElementById('uniqueDomains').textContent = unique.toLocaleString(); } function updateTopList(elementId, data) { const container = document.getElementById(elementId); container.innerHTML = ''; if (data.length === 0) { container.innerHTML = '<p style="text-align: center; color: #999;">Brak danych</p>'; return; } data.forEach(([name, count], index) => { const item = document.createElement('div'); item.className = 'list-item'; item.innerHTML = ` <span class="rank">#${index + 1}</span> <span class="domain-name">${name}</span> <span class="count">${count}</span> `; container.appendChild(item); }); } function updateHistogram(data) { const container = document.getElementById('histogram'); container.innerHTML = ''; const maxValue = Math.max(...data); data.forEach((value, hour) => { const bar = document.createElement('div'); bar.className = 'bar'; // Ustaw wysokość słupka proporcjonalnie do wartości const height = maxValue > 0 ? (value / maxValue) * 100 : 0; bar.style.height = `${height}%`; // Dodaj wartość jako tooltip const valueLabel = document.createElement('div'); valueLabel.className = 'bar-value'; valueLabel.textContent = `${hour}:00 - ${value} zapytań`; bar.appendChild(valueLabel); container.appendChild(bar); }); } function reverseDNS() { const ip = document.getElementById('ipInput').value.trim(); const resultDiv = document.getElementById('mappingResult'); if (!ip) { resultDiv.style.display = 'none'; return; } resultDiv.style.display = 'block'; if (ipToHostMap[ip]) { resultDiv.innerHTML = `✅ <strong>${ip}</strong> → <strong style="color: #4a9eff;">${ipToHostMap[ip]}</strong>`; } else { // Sprawdź czy IP występuje w logach const found = logData.some(entry => entry.sourceIP === ip); if (found) { resultDiv.innerHTML = `⚠️ <strong>${ip}</strong> → Brak nazwy hosta w logach`; } else { resultDiv.innerHTML = `❌ <strong>${ip}</strong> → Nie znaleziono w logach`; } } } // Enter key dla pola IP document.getElementById('ipInput').addEventListener('keypress', (e) => { if (e.key === 'Enter') { reverseDNS(); } }); </script> </body> </html>Główne zmiany:
- Automatyczne ładowanie pliku - skrypt automatycznie próbuje załadować
dnsmasq.logz tego samego katalogu przy starcie - Poprawiony histogram - teraz wyświetla się poprawnie z wartościami proporcjonalnymi do danych
- Dodano etykiety godzin pod histogramem
- Lepsze tooltips - pokazują godzinę i liczbę zapytań przy najechaniu na słupek
- Przycisk odświeżania - w prawym dolnym rogu, pozwala ponownie załadować plik
- Lepsze komunikaty błędów - jasne informacje gdy plik nie może być załadowany
- Wskaźnik ładowania - pokazuje się podczas wczytywania pliku
Aby skrypt działał automatycznie, umieść plik HTML w tym samym katalogu co plik
dnsmasq.logna serwerze FreeBSD i otwórz go w przeglądarce.- Automatyczne ładowanie pliku - skrypt automatycznie próbuje załadować
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.