-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinal.py
More file actions
122 lines (100 loc) · 4.05 KB
/
final.py
File metadata and controls
122 lines (100 loc) · 4.05 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
import time
import requests
from pysnmp.hlapi import *
import json
import os
# ==============================================================================
# [MERKEZİ AYARLAR / CENTRAL CONFIG]
# ==============================================================================
def load_config():
try:
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
with open(config_path, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
print(f"❌ Config Error: {e}")
return {
"telegram": {"bot_token": "", "chat_id": ""},
"snmp": {"device_ip": "127.0.0.1", "community": "public", "target_oid": "", "check_interval": 5},
"thresholds": {"alarm_limit": 3}
}
CONFIG = load_config()
BOT_TOKEN = CONFIG["telegram"]["bot_token"]
CHAT_ID = CONFIG["telegram"]["chat_id"]
IRD_IP = CONFIG["snmp"]["device_ip"]
COMMUNITY = CONFIG["snmp"]["community"]
HEDEF_OID = CONFIG["snmp"]["target_oid"]
KONTROL_SIKLIGI = CONFIG["snmp"]["check_interval"]
ALARM_LIMITI = CONFIG["thresholds"]["alarm_limit"]
# ==============================================================================
def send_telegram(message):
"""Telegram mesajı atar"""
try:
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
data = {"chat_id": CHAT_ID, "text": message}
requests.post(url, data=data, timeout=10)
print(f"📨 Mesaj Gönderildi: {message}")
except Exception as e:
print(f"❌ Mesaj Hatası: {e}")
def get_snmp_data(oid):
"""IRD Cihazına bağlanıp durumu sorar"""
try:
iterator = getCmd(
SnmpEngine(),
CommunityData(COMMUNITY, mpModel=1),
UdpTransportTarget((IRD_IP, 161), timeout=2.0, retries=1),
ContextData(),
ObjectType(ObjectIdentity(oid))
)
errorIndication, errorStatus, errorIndex, varBinds = next(iterator)
if errorIndication or errorStatus:
return "BAGLANTI_YOK"
else:
for varBind in varBinds:
return str(varBind[1]) # Cihazın cevabını döndür (Örn: 1, Locked)
except:
return "BAGLANTI_YOK"
# --- SİSTEM BAŞLATILIYOR ---
print("------------------------------------------------")
print(f"📡 STREAMGUARD MONITORING SYSTEM ACTIVE (SNMP)")
print(f"Target IP: {IRD_IP}")
print(f"Target OID: {HEDEF_OID}")
print("------------------------------------------------")
send_telegram("✅ STREAMGUARD STARTED: Monitoring Channel Status (24/7).")
last_state_ok = True
fail_counter = 0
while True:
# 1. Cihaza sor (Otomatik veri çekme)
durum = get_snmp_data(HEDEF_OID)
# Ekrana saati ve durumu yaz (Log tutmak gibi düşün)
tarih_saat = time.strftime("%H:%M:%S")
print(f"[{tarih_saat}] Cihaz Durumu: {durum}", end=" ")
# 2. Durumu Analiz Et
# NOT: Cihazın Lock olduğunda '1' mi, 'locked' mı, 'True' mu döndürüyor?
# Ona göre aşağıdaki listeye ekleme yapabilirsin.
KABUL_EDILEN_CEVAPLAR = ["1", "locked", "lock", "sync", "True", "yes"]
is_signal_ok = False
# Veriyi küçük harfe çevirip kontrol edelim
if str(durum).lower() in KABUL_EDILEN_CEVAPLAR:
is_signal_ok = True
print("-> ✅ OK")
elif durum == "BAGLANTI_YOK":
print("-> ⚠️ AĞ HATASI (Cihaza ulaşılamıyor)")
# Ağ hatasında hemen alarm vermesin diye önceki durumu koru
is_signal_ok = last_state_ok
else:
print("-> ❌ SİNYAL YOK!")
is_signal_ok = False
# 3. Alarm Mantığı (Senin test ettiğin mantıkla aynı)
if is_signal_ok:
fail_counter = 0
if not last_state_ok:
send_telegram("✅ DÜZELDİ: Yayın geri geldi.")
last_state_ok = True
else:
fail_counter += 1
if fail_counter == ALARM_LIMITI and last_state_ok:
send_telegram(f"🚨 ALERT: StreamGuard Detected Signal Loss! (Code: {durum})")
last_state_ok = False
# Belirlenen süre kadar bekle ve tekrar başa dön
time.sleep(KONTROL_SIKLIGI)