-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurityNetwork.py
More file actions
1790 lines (1628 loc) · 62 KB
/
SecurityNetwork.py
File metadata and controls
1790 lines (1628 loc) · 62 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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1# -*- coding: utf-8 -*-
# Security Network - Application wa7da (one app)
# Chkon m3ak f WiFi | Who is trying to kick you | Bzaaf tools
# Run: py -3 SecurityNetwork.py
import sys
import subprocess
import re
import socket
import platform
import time
import shutil
import concurrent.futures
import urllib.request
import urllib.parse
import ssl
import hashlib
import base64
import random
import string
import os
import json
from collections import defaultdict
if sys.version_info[0] < 3:
print("Security Network needs Python 3. Run: py -3 SecurityNetwork.py")
sys.exit(1)
# --- Rich (optional) ---
try:
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt, IntPrompt
RICH = True
except ImportError:
RICH = False
if RICH:
console = Console()
else:
console = None
# ========== APP IDENTITY (i7tarafiya mn jami3 nawa7i) ==========
APP_NAME = "Security Network"
APP_VERSION = "2.0"
APP_TAGLINE = "i7tarafiya mn jami3 nawa7i"
APP_FULL = "%s v%s - %s" % (APP_NAME, APP_VERSION, APP_TAGLINE)
TOTAL_TOOLS = 62
def show_banner():
"""Show app identity from all sides - recognizable everywhere."""
sep = "=" * 50
if RICH:
console.print(Panel(
"[bold cyan]%s[/bold cyan]\n[bold]v%s[/bold]\n[dim]%s[/dim]" % (APP_NAME, APP_VERSION, APP_TAGLINE),
title="[bold white] Application [/bold white]",
border_style="cyan",
padding=(0, 2),
))
else:
_print(sep)
_print(" %s | v%s" % (APP_NAME, APP_VERSION))
_print(" %s" % APP_TAGLINE)
_print(sep)
def set_window_title():
"""Set console/title so app is recognizable from taskbar."""
try:
if platform.system().lower() == "windows":
os.system("title %s v%s" % (APP_NAME, APP_VERSION))
except Exception:
pass
def show_dashboard():
"""7stat - Dashboard like PC applications, i7rafiya mn jami3 nawa7i."""
my_ip = get_my_ip()
gw = get_gateway_windows()
hostname = get_hostname()
try:
pub_ip = my_public_ip()
if not pub_ip or "error" in str(pub_ip).lower() or "errno" in str(pub_ip).lower():
pub_ip = "—"
except Exception:
pub_ip = "—"
devices = get_connected_devices()
conns = get_connections_windows()
if RICH:
from rich.table import Table as RichTable
from rich.panel import Panel as RichPanel
table = RichTable(show_header=False, title=" Dashboard | 7stat ", border_style="green")
table.add_column("Stat", style="cyan")
table.add_column("Value", style="white")
table.add_row("Application", "%s v%s" % (APP_NAME, APP_VERSION))
table.add_row("Tagline", APP_TAGLINE)
table.add_row("Total tools", str(TOTAL_TOOLS))
table.add_row("—", "—")
table.add_row("My IP (local)", my_ip)
table.add_row("Public IP", pub_ip if pub_ip and len(str(pub_ip)) < 20 else (str(pub_ip)[:30] + "…" if pub_ip else "—"))
table.add_row("Gateway", gw or "—")
table.add_row("Hostname", hostname)
table.add_row("OS", "%s %s" % (platform.system(), platform.release()))
table.add_row("—", "—")
table.add_row("Devices in ARP", str(len(devices)))
table.add_row("Active connections", str(len(conns)))
console.print(RichPanel(table, title="[bold] Application PC | i7rafiya [/bold]", border_style="blue", padding=(0, 1)))
else:
sep = "-" * 40
_print(sep)
_print(" DASHBOARD | 7stat")
_print(sep)
_print(" Application : %s v%s" % (APP_NAME, APP_VERSION))
_print(" %s" % APP_TAGLINE)
_print(" Total tools : %s" % TOTAL_TOOLS)
_print(sep)
_print(" My IP : %s" % my_ip)
_print(" Public IP : %s" % (pub_ip[:25] + "…" if pub_ip and len(str(pub_ip)) > 25 else (pub_ip or "—")))
_print(" Gateway : %s" % (gw or "—"))
_print(" Hostname : %s" % hostname)
_print(" OS : %s %s" % (platform.system(), platform.release()))
_print(sep)
_print(" Devices (ARP): %s" % len(devices))
_print(" Connections : %s" % len(conns))
_print(sep)
# ========== SCANNER (WiFi devices) ==========
def get_my_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
except Exception:
return "127.0.0.1"
def get_arp_table_windows():
try:
out = subprocess.check_output(["arp", "-a"], shell=False, text=True, encoding="utf-8", errors="replace")
return out
except Exception as e:
return str(e)
def parse_arp_table(arp_text):
devices = []
for line in arp_text.splitlines():
match = re.search(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+([0-9a-fA-F\-]{17})", line)
if match:
ip, mac = match.groups()
if not ip.startswith("224.") and not ip.startswith("239."):
devices.append((ip.strip(), mac.strip()))
return devices
def get_connected_devices():
return parse_arp_table(get_arp_table_windows())
def ping_host(ip, timeout=1):
param = "-n" if platform.system().lower() == "windows" else "-c"
try:
subprocess.run(["ping", param, "1", "-w", str(timeout * 1000), ip], capture_output=True, timeout=timeout + 2)
except Exception:
pass
def scan_subnet_arp(my_ip=None):
if my_ip is None:
my_ip = get_my_ip()
parts = my_ip.split(".")
if len(parts) != 4:
return []
base = ".".join(parts[:3])
for i in range(1, 255):
ping_host("%s.%d" % (base, i))
return get_connected_devices()
def get_mac_vendor(mac):
mac_upper = mac.replace("-", ":").upper()[:8]
vendors = {
"00:50:56": "VMware", "00:0C:29": "VMware", "00:1A:2B": "Cisco", "08:00:27": "VirtualBox",
"52:54:00": "QEMU", "DC:A6:32": "Raspberry Pi", "B8:27:EB": "Raspberry Pi", "E4:5F:01": "Raspberry Pi",
"F4:5C:89": "Apple", "00:1E:C2": "Apple", "28:CF:E9": "Apple", "AC:DE:48": "Apple", "D0:03:4B": "Apple",
"00:17:88": "Philips Hue", "94:B9:7E": "TP-Link", "50:C7:BF": "TP-Link", "C0:25:E9": "TP-Link", "F8:1A:67": "TP-Link",
"E4:D3:32": "Xiaomi", "64:CC:2E": "Xiaomi", "34:80:B3": "Intel", "8C:EC:4B": "Intel", "30:65:EC": "Intel",
}
for prefix, name in vendors.items():
if mac_upper.startswith(prefix.replace(":", "")) or mac.replace("-", ":").upper().startswith(prefix):
return name
return "Unknown"
# ========== ARP MONITOR (detect kick / spoofing) ==========
def monitor_arp_changes(duration_seconds=60, check_interval=2, on_change_callback=None):
history = defaultdict(list)
alerts = []
my_ip = get_my_ip()
start = time.time()
while (time.time() - start) < duration_seconds:
devices = get_connected_devices()
now = time.time()
for ip, mac in devices:
if ip == my_ip:
continue
if ip not in history:
history[ip].append((now, mac))
else:
last_mac = history[ip][-1][1]
if last_mac.upper() != mac.upper():
msg = "[!] ARP CHANGE: %s was %s now %s - POSSIBLE SPOOFING / KICK ATTEMPT" % (ip, last_mac, mac)
alerts.append(msg)
history[ip].append((now, mac))
if on_change_callback:
on_change_callback(msg)
time.sleep(check_interval)
return alerts
# ========== PORT SCAN ==========
def scan_port(ip, port, timeout=0.5):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
r = s.connect_ex((ip, port))
s.close()
return (port, r == 0)
except Exception:
return (port, False)
def scan_ports(ip, ports=None, timeout=0.5, max_workers=50):
if ports is None:
ports = list(range(1, 1025))
open_ports = []
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as ex:
futures = {ex.submit(scan_port, ip, p, timeout): p for p in ports}
for f in concurrent.futures.as_completed(futures):
port, is_open = f.result()
if is_open:
open_ports.append(port)
return sorted(open_ports)
COMMON_PORTS = {
21: "FTP", 22: "SSH", 23: "Telnet", 25: "SMTP", 53: "DNS", 80: "HTTP",
110: "POP3", 143: "IMAP", 443: "HTTPS", 445: "SMB", 3306: "MySQL",
3389: "RDP", 5432: "PostgreSQL", 5900: "VNC", 8080: "HTTP-Alt",
}
# ========== DNS ==========
def dns_lookup(hostname):
try:
return list(set(socket.gethostbyname_ex(hostname)[2]))
except socket.gaierror:
try:
return [socket.gethostbyname(hostname)]
except Exception:
return []
except Exception as e:
return [str(e)]
def reverse_dns(ip):
try:
return socket.gethostbyaddr(ip)[0]
except Exception as e:
return str(e)
# ========== PING ==========
def ping_one(ip, timeout=1):
try:
param = "-n" if platform.system().lower() == "windows" else "-c"
r = subprocess.run(["ping", param, "1", "-w", str(timeout * 1000), ip], capture_output=True, text=True, timeout=timeout + 2)
return r.returncode == 0
except Exception:
return False
def ping_sweep(base_ip, start=1, end=255):
parts = base_ip.split(".")
if len(parts) != 4:
return []
base = ".".join(parts[:3])
alive = []
for i in range(start, min(end + 1, 256)):
ip = "%s.%d" % (base, i)
if ping_one(ip):
alive.append(ip)
return alive
def ping_latency(ip, count=4):
param = "-n" if platform.system().lower() == "windows" else "-c"
try:
out = subprocess.run(["ping", param, str(count), ip], capture_output=True, text=True, timeout=count * 3).stdout
ms = re.findall(r"(?:temps?|time)=?\s*(\d+)\s*ms?", out, re.I)
return [int(m) for m in ms]
except Exception:
return []
# ========== NETWORK INFO ==========
def get_hostname():
return socket.gethostname()
def get_gateway_windows():
try:
out = subprocess.check_output(["ipconfig"], shell=False, text=True, encoding="utf-8", errors="replace")
m = re.search(r"Default Gateway[^\d]*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", out, re.I)
if m:
return m.group(1).strip()
except Exception:
pass
return None
def get_dns_servers_windows():
try:
out = subprocess.check_output(["ipconfig", "/all"], shell=False, text=True, encoding="utf-8", errors="replace")
servers = re.findall(r"DNS Servers[^\d]*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", out, re.I)
servers += re.findall(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*\(Preferred\)", out, re.I)
return list(dict.fromkeys(servers))
except Exception:
return []
# ========== TRACEROUTE ==========
def traceroute(host, max_hops=30):
cmd = ["tracert", "-h", str(max_hops), host] if platform.system().lower() == "windows" else ["traceroute", "-m", str(max_hops), host]
try:
out = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
return out.stdout.splitlines() if out.stdout else []
except Exception as e:
return [str(e)]
# ========== WHOIS ==========
def whois_lookup(domain_or_ip):
if shutil.which("whois"):
try:
r = subprocess.run(["whois", domain_or_ip], capture_output=True, text=True, timeout=15)
return r.stdout or r.stderr or "No output"
except Exception as e:
return str(e)
return "whois not installed (optional)."
# ========== HTTP HEADERS ==========
def get_headers(url, timeout=10):
if not url.startswith(("http://", "https://")):
url = "https://" + url
try:
ctx = ssl.create_default_context()
req = urllib.request.Request(url, method="HEAD")
req.add_header("User-Agent", "SecurityNetwork/1.0")
with urllib.request.urlopen(req, timeout=timeout, context=ctx) as r:
return dict(r.headers)
except Exception as e:
return {"Error": str(e)}
def check_security_headers(url):
headers = get_headers(url)
if "Error" in headers:
return [headers["Error"]]
important = ["Strict-Transport-Security", "X-Content-Type-Options", "X-Frame-Options", "Content-Security-Policy", "X-XSS-Protection"]
results = []
for h in important:
for k, v in headers.items():
if k.lower() == h.lower():
results.append("[OK] %s: %s" % (k, v))
break
else:
results.append("[--] Missing: %s" % h)
return results
# ========== SUBNET ==========
def subnet_info(cidr):
try:
import ipaddress
net = ipaddress.ip_network(cidr, strict=False)
return {
"network": str(net.network_address),
"netmask": str(net.netmask),
"broadcast": str(net.broadcast_address),
"hosts_count": net.num_addresses - 2,
"first_host": str(list(net.hosts())[0]) if net.num_addresses > 2 else "N/A",
"last_host": str(list(net.hosts())[-1]) if net.num_addresses > 2 else "N/A",
}
except Exception as e:
return {"error": str(e)}
# ========== CONNECTIONS (netstat) ==========
def get_connections_windows():
try:
out = subprocess.check_output(["netstat", "-an"], shell=False, text=True, encoding="utf-8", errors="replace")
lines = []
for line in out.splitlines():
if "ESTABLISHED" in line or "LISTENING" in line:
parts = line.split()
if len(parts) >= 4:
lines.append((parts[0], parts[1], parts[2], parts[3] if len(parts) > 3 else ""))
return lines
except Exception as e:
return [(str(e), "", "", "")]
# ========== MAC VENDOR API ==========
def mac_vendor_api(mac):
mac_clean = mac.replace(":", "").replace("-", "").upper()[:6]
try:
url = "https://api.macvendors.com/%s" % mac_clean
req = urllib.request.Request(url, headers={"User-Agent": "SecurityNetwork"})
with urllib.request.urlopen(req, timeout=5) as r:
return r.read().decode().strip()
except Exception:
return "Unknown"
# ========== EXTRA TOOLS (bzaaf dyal l7wyj) ==========
def wake_on_lan(mac):
"""Send Wake-on-LAN magic packet."""
mac_clean = mac.replace(":", "").replace("-", "").upper()
if len(mac_clean) != 12:
return "Invalid MAC"
data = bytes.fromhex("FF" * 6 + mac_clean * 16)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(data, ("255.255.255.255", 9))
sock.close()
return "Magic packet sent to %s" % mac
except Exception as e:
return str(e)
def http_status(url):
"""Check if site is up and return status code."""
if not url.startswith(("http://", "https://")):
url = "https://" + url
try:
req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "SecurityNetwork"})
with urllib.request.urlopen(req, timeout=10) as r:
return "UP - Status: %s" % r.status
except urllib.error.HTTPError as e:
return "HTTP %s" % e.code
except Exception as e:
return "DOWN - %s" % e
def ssl_cert_info(host, port=443):
"""SSL certificate expiry."""
try:
hostname = host.replace("https://", "").replace("http://", "").split("/")[0].split(":")[0]
ctx = ssl.create_default_context()
with socket.create_connection((hostname, port), timeout=5) as sock:
with ctx.wrap_socket(sock, server_hostname=hostname) as ssock:
cert = ssock.getpeercert()
from datetime import datetime
not_after = cert["notAfter"]
return "Valid until: %s" % not_after
except Exception as e:
return str(e)
def ip_geolocation(ip):
"""IP geolocation (free API)."""
try:
url = "http://ip-api.com/json/%s?fields=country,regionName,city,isp,org,lat,lon" % ip
req = urllib.request.Request(url, headers={"User-Agent": "SecurityNetwork"})
with urllib.request.urlopen(req, timeout=5) as r:
d = json.loads(r.read().decode())
return " | ".join("%s: %s" % (k, v) for k, v in d.items() if v)
except Exception as e:
return str(e)
def flush_dns():
"""Flush DNS cache (Windows: ipconfig /flushdns)."""
try:
if platform.system().lower() == "windows":
out = subprocess.check_output(["ipconfig", "/flushdns"], shell=False, text=True, encoding="utf-8", errors="replace")
return "DNS cache flushed.\n" + out[:500]
return "Run manually: ipconfig /flushdns (Windows)"
except Exception as e:
return str(e)
def network_interfaces():
"""List network interfaces (ipconfig)."""
try:
out = subprocess.check_output(["ipconfig", "/all"], shell=False, text=True, encoding="utf-8", errors="replace")
return out[:3000]
except Exception as e:
return str(e)
def url_encode(s):
return urllib.parse.quote(s, safe="")
def url_decode(s):
return urllib.parse.unquote(s)
def hash_string(s, algo="sha256"):
h = hashlib.new(algo)
h.update(s.encode("utf-8", errors="replace"))
return h.hexdigest()
def random_password(length=16, with_special=True):
chars = string.ascii_letters + string.digits
if with_special:
chars += "!@#$%&*"
return "".join(random.SystemRandom().choice(chars) for _ in range(length))
def wifi_networks_list():
"""List WiFi networks (netsh wlan show networks)."""
try:
out = subprocess.check_output(["netsh", "wlan", "show", "networks"], shell=False, text=True, encoding="utf-8", errors="replace")
return out
except Exception as e:
return str(e)
# ========== WiFi Analyzer (b7al WiFi Scanner app) ==========
def wifi_analyzer_networks():
"""Access point discovery: SSID, BSSID, Signal %, Channel, Security (netsh mode=bssid)."""
if platform.system().lower() != "windows":
return []
try:
out = subprocess.check_output(
["netsh", "wlan", "show", "networks", "mode=bssid"],
shell=False, text=True, encoding="utf-8", errors="replace"
)
except Exception:
return []
networks = []
current = None
for line in out.splitlines():
line_strip = line.strip()
if line_strip.startswith("SSID ") and ":" in line_strip:
if current and current.get("ssid") is not None:
networks.append(dict(current))
ssid = line_strip.split(":", 1)[-1].strip()
current = {"ssid": ssid, "bssid": "", "signal": 0, "channel": 0, "auth": "", "encryption": ""}
elif current is None:
continue
elif line_strip.startswith("BSSID ") and ":" in line_strip:
if current.get("bssid"):
networks.append(dict(current))
current["bssid"] = line_strip.split(":", 1)[-1].strip()
current["signal"] = 0
current["channel"] = 0
elif "Signal" in line_strip and ":" in line_strip:
try:
val = line_strip.split(":", 1)[-1].strip().replace("%", "").strip()
current["signal"] = int(val)
except ValueError:
pass
elif line_strip.startswith("Channel") and ":" in line_strip:
try:
current["channel"] = int(line_strip.split(":", 1)[-1].strip())
except ValueError:
pass
elif "Authentication" in line_strip and ":" in line_strip:
current["auth"] = line_strip.split(":", 1)[-1].strip()
elif "Encryption" in line_strip and ":" in line_strip:
current["encryption"] = line_strip.split(":", 1)[-1].strip()
if current and current.get("ssid") is not None:
networks.append(current)
return networks
def signal_bars(pct, width=10):
"""Signal strength as bars: |||||||--- 80%"""
if pct is None or pct < 0:
pct = 0
if pct > 100:
pct = 100
filled = int(round(width * pct / 100))
return "|" * filled + "-" * (width - filled) + " %s%%" % pct
def speed_test(download_url=None, size_mb=1):
"""Speed test: download file, return Mbps."""
if download_url is None:
download_url = "https://speed.hetzner.de/1MB.bin"
try:
req = urllib.request.Request(download_url, headers={"User-Agent": "SecurityNetwork"})
start = time.time()
with urllib.request.urlopen(req, timeout=30) as r:
data = r.read()
elapsed = time.time() - start
if elapsed <= 0:
return 0, 0, "Too fast to measure"
size_mb_actual = len(data) / (1024 * 1024)
mbps = (len(data) * 8 / 1_000_000) / elapsed
return round(mbps, 2), round(elapsed, 2), "%.2f MB in %.2f s" % (size_mb_actual, elapsed)
except Exception as e:
return 0, 0, str(e)
def wifi_channel_analysis(networks=None):
"""Channel finding: which channels used, suggest best (least crowded)."""
if networks is None:
networks = wifi_analyzer_networks()
channels = {}
for n in networks:
ch = n.get("channel") or 0
if ch > 0:
channels[ch] = channels.get(ch, 0) + 1
if not channels:
return "No channel data (run WiFi Analyzer first or netsh wlan show networks mode=bssid)"
used = sorted(channels.items(), key=lambda x: -x[1])
best = min(channels.keys(), key=lambda c: channels[c])
lines = ["Channels in use: %s" % dict(channels), "Most crowded: %s" % [c for c, _ in used[:3]], "Suggested (least crowded): Channel %s" % best]
return "\n".join(lines)
def signal_pct_to_dbm(pct):
"""Approximate: 100%% = -50 dBm, 0%% = -100 dBm."""
if pct is None or pct < 0:
pct = 0
if pct > 100:
pct = 100
return -50 - (100 - pct) * 0.5 # -50 to -100 dBm
def channel_to_band(ch):
"""Channel to band: 1-14 = 2.4 GHz, 15-165 = 5 GHz, else 6 GHz."""
if not ch or ch <= 0:
return "—"
if ch <= 14:
return "2.4 GHz"
if ch <= 165:
return "5 GHz"
return "6 GHz"
def get_wifi_adapter_name():
"""Adapter name like 'Intel WiFi 6E' (netsh wlan show interfaces)."""
if platform.system().lower() != "windows":
return "WiFi"
try:
out = subprocess.check_output(
["netsh", "wlan", "show", "interfaces"],
shell=False, text=True, encoding="utf-8", errors="replace"
)
for line in out.splitlines():
if "Description" in line and ":" in line:
return line.split(":", 1)[-1].strip() or "WiFi"
except Exception:
pass
return "WiFi"
def wifi_scanner_full_view():
"""Full view like WIFI Scanner app: top bar, sidebar stats, table, spectrum."""
networks = wifi_analyzer_networks()
adapter = get_wifi_adapter_name()
if not networks:
_print("No networks found. (Windows: netsh wlan show networks mode=bssid)")
return
# Stats (sidebar-like)
bands = set()
ssids = set()
vendors = set()
securities = set()
signal_levels = set()
for n in networks:
ch = n.get("channel") or 0
bands.add(channel_to_band(ch))
ssids.add((n.get("ssid") or "").strip())
bssid = n.get("bssid") or ""
if bssid:
v = get_mac_vendor(bssid)
if v != "Unknown":
vendors.add(v)
sec = (n.get("auth") or "").strip()
if sec:
securities.add(sec)
sig = n.get("signal") or 0
if sig > 0:
signal_levels.add("-%d" % int(signal_pct_to_dbm(sig)))
# Channel usage for spectrum
ch_usage = {}
for n in networks:
ch = n.get("channel") or 0
if ch > 0:
ch_usage[ch] = ch_usage.get(ch, 0) + 1
max_count = max(ch_usage.values()) if ch_usage else 1
if RICH:
from rich.panel import Panel as RichPanel
from rich.layout import Layout
from rich.text import Text
# Top bar
top = Text()
top.append("WIFI Scanner", style="bold cyan")
top.append(" | ", style="dim")
top.append("Showing data from %s" % adapter, style="white")
top.append(" | ", style="dim")
top.append("Scanner", style="green")
console.print(RichPanel(top, border_style="blue", padding=(0, 1)))
# Sidebar stats
stats_text = "[bold]Band:[/bold] %d [bold]SSID:[/bold] %d [bold]BSSID:[/bold] %d [bold]Vendor:[/bold] %d [bold]Security:[/bold] %d [bold]Signal:[/bold] %d" % (
len(bands), len(ssids), len(networks), len(vendors), len(securities), len(signal_levels))
console.print(RichPanel(stats_text, title="[bold] Filters [/bold]", border_style="green", padding=(0, 1)))
# Main table: SSID, BSSID, Vendor, Channel, Band, Signal (dBm), Security
table = Table(title="Showing %d of %d" % (min(50, len(networks)), len(networks)), show_lines=False)
table.add_column("SSID", style="cyan")
table.add_column("BSSID", style="dim")
table.add_column("Vendor", style="yellow")
table.add_column("Channel", style="white")
table.add_column("Band", style="green")
table.add_column("Signal", style="red")
table.add_column("Security", style="white")
for n in networks[:50]:
ssid = (n.get("ssid") or "")[:22]
bssid = (n.get("bssid") or "")[:17]
vendor = (get_mac_vendor(n.get("bssid") or "") or "—")[:18]
ch = n.get("channel") or 0
band = channel_to_band(ch)
sig_pct = n.get("signal") or 0
dbm = int(signal_pct_to_dbm(sig_pct))
sec = (n.get("auth") or "—")[:16]
table.add_row(ssid, bssid, vendor, str(ch) if ch else "—", band, "%d dBm" % dbm, sec)
console.print(table)
# Spectrum (ASCII bar chart)
if ch_usage:
spec_lines = ["[bold]Spectrum - Channel usage[/bold]"]
for ch in sorted(ch_usage.keys()):
cnt = ch_usage[ch]
bar_len = max(1, int(20 * cnt / max_count))
bar = "[" + "#" * bar_len + "]" + " Ch %s (%d)" % (ch, cnt)
spec_lines.append(bar)
console.print(RichPanel("\n".join(spec_lines), title="[bold] Spectrum [/bold]", border_style="blue", padding=(0, 1)))
_print("- %s | i7rafiya" % APP_NAME)
else:
sep = "=" * 70
_print(sep)
_print("WIFI Scanner | Showing data from %s | Scanner" % adapter)
_print(sep)
_print("Band: %d SSID: %d BSSID: %d Vendor: %d Security: %d Signal: %d" % (len(bands), len(ssids), len(networks), len(vendors), len(securities), len(signal_levels)))
_print("-" * 70)
_print("%-22s %-18s %-12s %-6s %-8s %-8s %s" % ("SSID", "BSSID", "Vendor", "Ch", "Band", "Signal", "Security"))
_print("-" * 70)
for n in networks[:50]:
_print("%-22s %-18s %-12s %-6s %-8s %-8s %s" % (
(n.get("ssid") or "")[:22],
(n.get("bssid") or "")[:17],
(get_mac_vendor(n.get("bssid") or "") or "—")[:12],
n.get("channel") or "—",
channel_to_band(n.get("channel")),
"%d dBm" % int(signal_pct_to_dbm(n.get("signal") or 0)),
(n.get("auth") or "—")[:16],
))
_print("-" * 70)
_print("Showing %d of %d" % (min(50, len(networks)), len(networks)))
if ch_usage:
_print("\nSpectrum - Channel usage:")
for ch in sorted(ch_usage.keys()):
cnt = ch_usage[ch]
bar_len = max(1, int(20 * cnt / max_count))
_print(" Ch %3s [%s] %d" % (ch, "#" * bar_len, cnt))
_print(sep)
_print("- %s | i7rafiya" % APP_NAME)
def ip_to_decimal(ip):
"""Convert IP to decimal."""
try:
parts = [int(x) for x in ip.split(".")]
return sum(parts[i] << (24 - 8 * i) for i in range(4))
except Exception:
return "Invalid IP"
def decimal_to_ip(n):
"""Convert decimal to IP."""
try:
n = int(n)
return "%d.%d.%d.%d" % ((n >> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255)
except Exception:
return "Invalid number"
def base64_encode(s):
return base64.b64encode(s.encode("utf-8", errors="replace")).decode("ascii")
def base64_decode(s):
try:
return base64.b64decode(s).decode("utf-8", errors="replace")
except Exception as e:
return str(e)
def get_all_http_headers(url):
"""Fetch all HTTP headers."""
if not url.startswith(("http://", "https://")):
url = "https://" + url
try:
req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "SecurityNetwork"})
with urllib.request.urlopen(req, timeout=10) as r:
return "\n".join("%s: %s" % (k, v) for k, v in r.headers.items())
except Exception as e:
return str(e)
def ping_stats(host, count=10):
"""Ping statistics: min, max, avg, jitter."""
times = ping_latency(host, count=count)
if not times:
return "Host unreachable"
mn, mx = min(times), max(times)
avg = sum(times) / len(times)
jitter = (sum(abs(times[i] - times[i - 1]) for i in range(1, len(times))) / (len(times) - 1)) if len(times) > 1 else 0
return "Min: %d ms | Max: %d ms | Avg: %.1f ms | Jitter: %.1f ms" % (mn, mx, avg, jitter)
def system_info():
"""OS and basic system info."""
info = [
"OS: %s" % platform.system(),
"Release: %s" % platform.release(),
"Machine: %s" % platform.machine(),
"Hostname: %s" % get_hostname(),
"Python: %s" % platform.python_version(),
]
return "\n".join(info)
def hosts_file_content():
"""Read hosts file."""
path = r"C:\Windows\System32\drivers\etc\hosts" if platform.system().lower() == "windows" else "/etc/hosts"
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
return f.read()
except Exception as e:
return str(e)
def port_to_process_windows(port):
"""Which process uses this port (netstat -ano)."""
try:
out = subprocess.check_output(["netstat", "-ano"], shell=False, text=True, encoding="utf-8", errors="replace")
pid = None
for line in out.splitlines():
if ":%s " % port in line or ":%s\t" % port in line:
parts = line.split()
if len(parts) >= 5 and parts[-1].isdigit():
pid = parts[-1]
break
if not pid:
return "No process found on port %s" % port
# tasklist /FI "PID eq X"
out2 = subprocess.check_output(["tasklist", "/FI", "PID eq %s" % pid, "/FO", "CSV"], shell=False, text=True, encoding="utf-8", errors="replace")
return "Port %s -> PID %s\n%s" % (port, pid, out2[:500])
except Exception as e:
return str(e)
def hex_to_bin(hex_s):
try:
n = int(hex_s.replace("0x", ""), 16)
return bin(n)
except Exception:
return "Invalid hex"
def bin_to_hex(bin_s):
try:
n = int(bin_s.replace("0b", ""), 2)
return hex(n)
except Exception:
return "Invalid binary"
def my_public_ip():
"""Get public IP."""
try:
req = urllib.request.Request("https://api.ipify.org", headers={"User-Agent": "SecurityNetwork"})
with urllib.request.urlopen(req, timeout=5) as r:
return r.read().decode().strip()
except Exception as e:
return str(e)
def renew_dhcp():
"""Renew DHCP (ipconfig /renew)."""
try:
if platform.system().lower() == "windows":
out = subprocess.check_output(["ipconfig", "/renew"], shell=False, text=True, encoding="utf-8", errors="replace")
return out[:800]
return "Run: ipconfig /renew (Windows)"
except Exception as e:
return str(e)
def local_listening_ports():
"""Ports in LISTENING state on this machine."""
try:
out = subprocess.check_output(["netstat", "-an"], shell=False, text=True, encoding="utf-8", errors="replace")
lines = []
for line in out.splitlines():
if "LISTENING" in line:
parts = line.split()
if len(parts) >= 2:
lines.append(parts[1])
return "\n".join(sorted(set(lines))[:50])
except Exception as e:
return str(e)
# ========== MORE TOOLS (bzaaaaaaf) ==========
def file_checksum(path, algo="sha256"):
"""MD5 or SHA256 of file."""
try:
h = hashlib.new(algo)
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
h.update(chunk)
return h.hexdigest()
except Exception as e:
return str(e)
def password_strength(pwd):
"""Simple password strength: length, upper, lower, digit, special."""
if not pwd:
return "Empty"
score = 0
if len(pwd) >= 8:
score += 1
if len(pwd) >= 12:
score += 1
if any(c.isupper() for c in pwd):
score += 1
if any(c.islower() for c in pwd):
score += 1
if any(c.isdigit() for c in pwd):
score += 1
if any(c in "!@#$%^&*()_+-=[]{}|;:,.<>?" for c in pwd):
score += 1
labels = ["Very weak", "Weak", "Fair", "Good", "Strong", "Very strong", "Excellent"]
return labels[min(score, 6)]
def uuid_generate():
import uuid
return str(uuid.uuid4())
def timestamp_to_date(ts):
"""Unix timestamp to readable date."""
try:
from datetime import datetime
return datetime.utcfromtimestamp(int(ts)).strftime("%Y-%m-%d %H:%M:%S UTC")
except Exception:
return "Invalid"
def date_to_timestamp(s):
"""Parse date string to unix timestamp (basic)."""
try:
from datetime import datetime
dt = datetime.now()
return int(dt.timestamp())
except Exception:
return "Invalid"
def json_validate(s):
"""Validate JSON string."""
try:
json.loads(s)
return "Valid JSON"
except json.JSONDecodeError as e:
return "Invalid: %s" % e
def url_expand(url):
"""Expand short URL (follow redirect, return final URL)."""
if not url.startswith(("http://", "https://")):
url = "https://" + url
try:
req = urllib.request.Request(url, method="GET", headers={"User-Agent": "SecurityNetwork"})
req.add_header("Accept", "*/*")
with urllib.request.urlopen(req, timeout=10) as r:
return r.geturl()
except Exception as e:
return str(e)
def wifi_saved_profiles():
"""List saved WiFi profiles (netsh wlan show profiles)."""
if platform.system().lower() != "windows":
return "Windows only"
try:
out = subprocess.check_output(
["netsh", "wlan", "show", "profiles"],
shell=False, text=True, encoding="utf-8", errors="replace"
)
return out[:2000]
except Exception as e:
return str(e)
def connection_state_summary():
"""Netstat: count by state (ESTABLISHED, LISTENING, etc.)."""
try:
out = subprocess.check_output(["netstat", "-an"], shell=False, text=True, encoding="utf-8", errors="replace")
counts = {}
for line in out.splitlines():
for state in ["ESTABLISHED", "LISTENING", "TIME_WAIT", "CLOSE_WAIT", "SYN_SENT"]:
if state in line:
counts[state] = counts.get(state, 0) + 1
break
return "\n".join("%s: %d" % (k, v) for k, v in sorted(counts.items(), key=lambda x: -x[1]))
except Exception as e:
return str(e)
def bytes_to_units(n):
"""Convert bytes to KB, MB, GB."""
try:
n = int(n)
if n < 1024:
return "%d B" % n
if n < 1024 * 1024:
return "%.2f KB" % (n / 1024)
if n < 1024 * 1024 * 1024:
return "%.2f MB" % (n / (1024 * 1024))
return "%.2f GB" % (n / (1024 * 1024 * 1024))
except Exception:
return "Invalid"
def hex_encode(s):
return s.encode("utf-8", errors="replace").hex()
def hex_decode(s):
try:
return bytes.fromhex(s.replace(" ", "")).decode("utf-8", errors="replace")
except Exception as e:
return str(e)
def random_ip():
"""Random private IP (10.x, 172.16-31.x, 192.168.x)."""
import random as r
kind = r.choice([1, 2, 3])
if kind == 1:
return "10.%d.%d.%d" % (r.randint(0, 255), r.randint(0, 255), r.randint(0, 255))
if kind == 2:
return "172.%d.%d.%d" % (r.randint(16, 31), r.randint(0, 255), r.randint(0, 255))
return "192.168.%d.%d" % (r.randint(0, 255), r.randint(1, 254))
def user_agent_string():