Haftalık Ağ Bilgisi Monitörü
Bu Python scripti, haftalık ağ kullanım bilgilerini gerçek zamanlı olarak gösterir. Aktif ağ arayüzünü, yerel ve dış IP adreslerini, toplam upload ve download verilerini, ayrıca anlık veri hızlarını kullanıcı dostu bir şekilde ekranda görüntüler.
📜 Kod:
import psutil
import socket
import requests
import time
import os
import datetime
from rich.console import Console
from rich.table import Table
from rich.progress import BarColumn, Progress, TextColumn
console = Console()
def get_local_ip():
try:
return socket.gethostbyname(socket.gethostname())
except:
return "Yok"
def get_external_ip():
try:
return requests.get("https://ifconfig.me", timeout=5).text.strip()
except:
return "Yok"
def get_active_interface():
for iface, addrs in psutil.net_if_addrs().items():
for addr in addrs:
if addr.family == socket.AF_INET and not addr.address.startswith("127."):
return iface
return "Bilinmiyor"
def bytes_to_mbps(bytes_value):
return round(bytes_value * 8 / 1024 / 1024, 2)
def format_size(bytes_value):
mb = bytes_value / 1024 / 1024
gb = mb / 1024
if gb >= 1:
return f"{round(gb, 2)} GB"
else:
return f"{round(mb, 2)} MB"
def clear_console():
os.system('cls' if os.name == 'nt' else 'clear')
def get_weekly_file():
now = datetime.datetime.now()
year, week_num, _ = now.isocalendar()
filename = f"week_{year}_{week_num}.txt"
return filename
def read_saved_data(filename):
if os.path.exists(filename):
with open(filename, 'r') as f:
lines = f.readlines()
try:
upload = int(lines[0].split('=')[1])
download = int(lines[1].split('=')[1])
return upload, download
except:
return 0, 0
return 0, 0
def write_saved_data(filename, upload, download):
with open(filename, 'w') as f:
f.write(f"upload={upload}\n")
f.write(f"download={download}\n")
def show_network_monitor():
iface = get_active_interface()
if iface not in psutil.net_io_counters(pernic=True):
input(f"'{iface}' adında bir ağ arayüzü bulunamadı. Program kapanıyor. Enter'a bas...")
exit()
local_ip = get_local_ip()
external_ip = get_external_ip()
filename = get_weekly_file()
prev_upload, prev_download = read_saved_data(filename)
old_stats = psutil.net_io_counters(pernic=True)[iface]
while True:
time.sleep(1)
new_stats = psutil.net_io_counters(pernic=True)[iface]
upload_speed = new_stats.bytes_sent - old_stats.bytes_sent
download_speed = new_stats.bytes_recv - old_stats.bytes_recv
old_stats = new_stats
# Haftalık toplamı güncelle
prev_upload += upload_speed
prev_download += download_speed
write_saved_data(filename, prev_upload, prev_download)
clear_console()
table = Table(title="📡 Haftalık Ağ Bilgisi Monitörü", title_style="bold cyan")
table.add_column("Özellik", style="bold yellow")
table.add_column("Değer", style="bold white")
table.add_row("Aktif Arayüz", iface)
table.add_row("Yerel IP", local_ip)
table.add_row("Dış IP", external_ip)
table.add_row("Toplam Upload", format_size(prev_upload))
table.add_row("Toplam Download", format_size(prev_download))
table.add_row("Anlık Upload", f"{bytes_to_mbps(upload_speed)} Mbps")
table.add_row("Anlık Download", f"{bytes_to_mbps(download_speed)} Mbps")
console.print(table)
with Progress(
TextColumn("[progress.description]{task.description}"),
BarColumn(bar_width=40),
TextColumn("{task.percentage:>3.0f}%"),
transient=True,
) as progress:
upload_bar = progress.add_task("[green]Upload", total=10)
download_bar = progress.add_task("[cyan]Download", total=10)
progress.update(upload_bar, completed=min(bytes_to_mbps(upload_speed), 10))
progress.update(download_bar, completed=min(bytes_to_mbps(download_speed), 10))
if __name__ == "__main__":
try:
show_network_monitor()
except Exception as e:
input(f"\nBir hata oluştu: {e}\nDevam etmek için Enter'a bas...")
💾 Kaydetme ve Çalıştırma:
- Bu kodu bir dosyaya
network_monitor.py
adıyla kaydedin. - Gerekli kütüphaneler (
psutil
,requests
,rich
) yüklü değilse şu komutla yükleyebilirsiniz:
pip install psutil requests rich
- Terminal veya komut istemcisinde şu komutla çalıştırın:
python network_monitor.py
🖼️ Örnek Çıktı:
📡 Haftalık Ağ Bilgisi Monitörü
┏━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
┃ Özellik ┃ Değer ┃
┡━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
│ Aktif Arayüz │ Ethernet │
│ Yerel IP │ 192.168.0.24 │
│ Dış IP │ 178.000.168.000 │
│ Toplam Upload │ 1.36 GB │
│ Toplam Download │ 16.75 GB │
│ Anlık Upload │ 10.11 Mbps │
│ Anlık Download │ 0.52 Mbps │
└─────────────────┴─────────────────┘
✅ Özellikler:
- Gerçek zamanlı izleme (1 saniyede bir güncellenir).
- Aktif ağ arayüzünü otomatik algılar.
- Haftalık ağ kullanım verilerini kaydeder.
- Hem upload hem de download hızlarını gösterir.