-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.py
More file actions
4612 lines (3948 loc) · 212 KB
/
Copy pathmanager.py
File metadata and controls
4612 lines (3948 loc) · 212 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
#!/usr/bin/env python3
import webbrowser
import warnings
import re
import sys
import sqlite3
import threading
import os
import socket
import struct
import ipaddress
import subprocess
import paramiko
import time
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import font as tkfont
from tkinter import filedialog
from cryptography.fernet import Fernet
from datetime import datetime
# --- Cross-Platform Button Logic ---
if sys.platform == "darwin": # "darwin" is the internal name for macOS
try:
from tkmacosx import Button as AdaptiveButton
print("Using tkmacosx for color support")
except ImportError:
# Fallback if the user hasn't installed tkmacosx yet
AdaptiveButton = tk.Button
print("tkmacosx not found, falling back to standard buttons")
else:
# Windows and Linux use standard buttons (which already support colors)
AdaptiveButton = tk.Button
# --- Redesigned Styling Configuration ---
# Main surfaces
BG_PRIMARY = '#161718' # Near-black main background
BG_SECONDARY = '#1f2022' # Sidebar / topbar surface
BG_TERTIARY = '#28292b' # Card / panel surface
BG_LOG = '#111213' # Console background
# Text
FG_PRIMARY = '#e2e3e5' # Primary text
FG_SECONDARY = '#8a8d91' # Muted / label text
FG_TERTIARY = '#555860' # Very muted (timestamps)
# Accents
ACCENT_BLUE = '#4a9eff' # Selection / info blue
ACCENT_GREEN = '#3ecf8e' # Success / online green
ACCENT_RED = '#f56565' # Danger / offline red
ACCENT_AMBER = '#f6ad55' # Warning / amber
BORDER_COLOR = '#2e3033' # Subtle border
# Sidebar
SB_BG = '#111213'
SB_ICON_ACTIVE_BG = '#1e3a5a'
SB_ICON_ACTIVE_FG = '#4a9eff'
SB_ICON_FG = '#555860'
# Toolbar button palette (text-button style — no big coloured fills)
BTN_PRIMARY = '#1a3a5c'
BTN_PRIMARY_HOVER = '#214972'
BTN_PRIMARY_FG = '#4a9eff'
BTN_SUCCESS = '#1a3a2a'
BTN_SUCCESS_HOVER = '#1f4a34'
BTN_SUCCESS_FG = '#3ecf8e'
BTN_DANGER = '#3a1a1a'
BTN_DANGER_HOVER = '#4a2020'
BTN_DANGER_FG = '#f56565'
BTN_WARNING = '#3a2e1a'
BTN_WARNING_HOVER = '#4a3b20'
BTN_WARNING_FG = '#f6ad55'
BTN_INFO = '#2a1f3a'
BTN_INFO_HOVER = '#352745'
BTN_INFO_FG = '#a78bfa'
# Legacy aliases kept so dialogs/SSH code compile unchanged
BTN_PRIMARY_HOVER = BTN_PRIMARY_HOVER # noqa: already set
BTN_SUCCESS_HOVER = BTN_SUCCESS_HOVER # noqa
# PC Log Color Palette (High contrast, professional neon accents)
PC_COLOR_PALETTE = [
'#00d4ff', # Cyan
'#00ff88', # Mint green
'#ff9d00', # Amber
'#00ffc8', # Aqua
'#a770ff', # Purple
'#ffb800', # Gold
'#ff4d94', # Hot pink
'#4da6ff', # Sky blue
'#80ff80', # Light green
'#ffa64d', # Orange
'#cc99ff', # Lavender
'#00e5ff', # Bright cyan
'#ffff66', # Yellow
'#66ffcc', # Teal
'#ff8080', # Coral
'#8cd1ff', # Baby blue
'#ffcc80', # Peach
'#b3ff99', # Lime
'#ff99cc', # Rose
'#ff6b9d', # Pink
]
# --- Warning Suppression ---
warnings.filterwarnings("ignore", category=DeprecationWarning)
# --- Global Config ---
APP_NAME = "Remote Linux Manager - V2"
APP_URL = "https://hackaday.io/project/204282-remote-linux-manager" # ← update to your actual Hackaday URL
DB_NAME = "pc_manager.db"
KEY_FILE = ".secret.key"
SSH_CONNECT_TIMEOUT = 10
MONITOR_POLL_INTERVAL_SECONDS = 10
# --- Wake-on-LAN-before-connect tuning ---
# When a PC doesn't answer on the SSH port but has a MAC address on file,
# we treat it as "asleep, not offline": send a magic packet and give it a
# window to boot before falling back to the normal Offline result.
WOL_PORT_CHECK_TIMEOUT = 1.5 # quick probe to see if the PC is already up
WOL_BOOT_WAIT_SECONDS = 35 # how long to wait for a woken PC to answer SSH
WOL_POLL_INTERVAL_SECONDS = 3 # how often to re-check the port while waiting
WOL_RETRY_COOLDOWN_SECONDS = 60 # don't re-send a magic packet more than once per this window per PC
# --- Encryption Utility ---
class EncryptionUtility:
def __init__(self, key_file=KEY_FILE):
self.key_file = key_file
self._ensure_key()
self.fernet = Fernet(self.key)
def _ensure_key(self):
if os.path.exists(self.key_file):
with open(self.key_file, "rb") as f:
self.key = f.read()
print("[INFO] Encryption key loaded.")
else:
self.key = Fernet.generate_key()
with open(self.key_file, "wb") as f:
f.write(self.key)
print("[INFO] New encryption key generated and saved.")
def encrypt(self, data):
return self.fernet.encrypt(data.encode())
def decrypt(self, token):
try:
return self.fernet.decrypt(token).decode()
except Exception as e:
print(f"[ERROR] Decryption failed: {e}", file=sys.stderr)
return None
# --- Wake-on-LAN Utility ---
def is_tcp_port_open(host, port=22, timeout=1.5):
"""Quick, lightweight reachability probe — plain TCP connect, no SSH
handshake/auth. Used to decide 'asleep vs genuinely offline' without the
cost of a full paramiko connection attempt."""
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
return s.connect_ex((host, port)) == 0
except Exception:
return False
def send_magic_packet(mac_address, broadcast_ip='255.255.255.255', port=9):
"""
Builds and broadcasts a Wake-on-LAN magic packet for the given MAC address.
Returns (success: bool, message: str). Requires the target machine to have
WoL enabled in BIOS/UEFI and at the OS/NIC level (and to be on Ethernet —
WoL over Wi-Fi is unreliable/unsupported on most hardware).
"""
try:
clean_mac = re.sub(r'[^0-9a-fA-F]', '', mac_address)
if len(clean_mac) != 12:
return False, f"Invalid MAC address: '{mac_address}'"
mac_bytes = bytes.fromhex(clean_mac)
magic_packet = b'\xff' * 6 + mac_bytes * 16
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(magic_packet, (broadcast_ip, port))
sock.close()
return True, "Magic packet sent"
except Exception as e:
return False, str(e)
# --- Network Discovery Utility ---
def get_local_subnet_hosts():
"""
Best-effort discovery of the local /24 subnet's usable host addresses,
based on the IP the OS would use to reach the internet (no packets are
actually sent for this part — it's just how the OS picks a local route).
Returns a list of ipaddress.IPv4Address objects, or [] if it can't tell.
"""
try:
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
probe.settimeout(0)
probe.connect(('10.255.255.255', 1))
local_ip = probe.getsockname()[0]
probe.close()
network = ipaddress.ip_network(f"{local_ip}/24", strict=False)
return list(network.hosts())
except Exception:
return []
def scan_for_ssh_hosts(hosts, port=22, timeout=0.4, max_workers=60, progress_callback=None):
"""
Threaded TCP-connect scan across the given list of IPv4Address objects,
checking whether `port` (default 22/SSH) is open. Also attempts a reverse
DNS / mDNS lookup for a friendly hostname where possible.
Returns a list of dicts: [{'ip': '192.168.1.42', 'hostname': 'pi4' or None}, ...]
sorted by IP. Intended to be called from a background thread — this
function blocks until the scan completes.
"""
found = []
found_lock = threading.Lock()
sem = threading.Semaphore(max_workers)
def _probe(ip_obj):
ip_str = str(ip_obj)
with sem:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
if s.connect_ex((ip_str, port)) == 0:
hostname = None
try:
hostname = socket.gethostbyaddr(ip_str)[0].split('.')[0]
except Exception:
pass
with found_lock:
found.append({'ip': ip_str, 'hostname': hostname})
except Exception:
pass
finally:
if progress_callback:
try:
progress_callback()
except Exception:
pass
threads = [threading.Thread(target=_probe, args=(h,), daemon=True) for h in hosts]
for t in threads:
t.start()
for t in threads:
t.join()
found.sort(key=lambda d: tuple(int(p) for p in d['ip'].split('.')))
return found
def get_arp_table():
"""
Best-effort read of the local ARP cache as {ip: mac}. A TCP-connect scan
of the subnet (scan_for_ssh_hosts) populates this cache as a side effect
for local hosts, so calling this right after a scan will generally have
entries for whatever was just found — letting us grab a MAC address for
Wake-on-LAN without ever needing to SSH into the machine.
Cross-platform: reads /proc/net/arp on Linux, shells out to `arp -a`
elsewhere (Windows/macOS).
"""
table = {}
mac_re = re.compile(r'([0-9a-fA-F]{2}(?::[0-9a-fA-F]{2}){5})')
ip_re = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
try:
if os.path.exists('/proc/net/arp'):
with open('/proc/net/arp', 'r') as f:
lines = f.readlines()[1:]
for line in lines:
parts = line.split()
if len(parts) >= 4:
ip, mac = parts[0], parts[3]
if mac_re.fullmatch(mac) and mac.lower() != '00:00:00:00:00:00':
table[ip] = mac.lower()
else:
output = subprocess.run(['arp', '-a'], capture_output=True, text=True, timeout=5).stdout
for line in output.splitlines():
ip_m, mac_m = ip_re.search(line), mac_re.search(line)
if ip_m and mac_m:
table[ip_m.group(1)] = mac_m.group(1).replace('-', ':').lower()
except Exception:
pass
return table
# --- Database Manager ---
class DBManager:
def __init__(self, db_name=DB_NAME):
self.conn = sqlite3.connect(db_name, check_same_thread=False)
self.cursor = self.conn.cursor()
self._create_table()
self._upgrade_db() # Run an upgrade on the DB if number of fields is different
def _create_table(self):
"""Creates the basic table structure if it doesn't exist."""
# Create the main PC table with all 10 columns
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS pcs (
id INTEGER PRIMARY KEY,
hostname TEXT NOT NULL,
username TEXT NOT NULL,
password_encrypted BLOB NOT NULL,
alias TEXT,
status TEXT,
last_update TEXT,
pending_updates INTEGER DEFAULT 0,
uptime TEXT DEFAULT 'N/A',
disk_free TEXT DEFAULT 'N/A',
mac_address TEXT DEFAULT ''
)
""")
# Create the snapshots table
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS software_snapshots (
id INTEGER PRIMARY KEY,
pc_id INTEGER NOT NULL,
timestamp TEXT NOT NULL,
package_list TEXT NOT NULL,
FOREIGN KEY (pc_id) REFERENCES pcs(id)
)
""")
self.conn.commit()
print("[INFO] Database structure verified.")
def _upgrade_db(self):
"""Adds missing columns to old databases automatically."""
cursor = self.conn.cursor()
# ── pcs table migrations ──────────────────────────────────────────────
cursor.execute("PRAGMA table_info(pcs)")
existing_pcs_columns = [column[1] for column in cursor.fetchall()]
pcs_migrations = [
("pending_updates", "INTEGER DEFAULT 0"),
("uptime", "TEXT DEFAULT 'N/A'"),
("disk_free", "TEXT DEFAULT 'N/A'"),
("mac_address", "TEXT DEFAULT ''")
]
for col_name, col_type in pcs_migrations:
if col_name not in existing_pcs_columns:
try:
cursor.execute(f"ALTER TABLE pcs ADD COLUMN {col_name} {col_type}")
print(f"[DB] Added missing column to pcs: {col_name}")
except sqlite3.OperationalError:
pass
# ── software_snapshots table migrations ───────────────────────────────
cursor.execute("PRAGMA table_info(software_snapshots)")
existing_snap_columns = [column[1] for column in cursor.fetchall()]
snap_migrations = [
("user_list", "TEXT DEFAULT ''"), # passwd-style lines: user:uid:gid:home:shell
("group_list", "TEXT DEFAULT ''"), # group-style lines: group:gid:members
]
for col_name, col_type in snap_migrations:
if col_name not in existing_snap_columns:
try:
cursor.execute(f"ALTER TABLE software_snapshots ADD COLUMN {col_name} {col_type}")
print(f"[DB] Added missing column to software_snapshots: {col_name}")
except sqlite3.OperationalError:
pass
self.conn.commit()
def get_all_pcs(self):
# Using SELECT * for robust searches
self.cursor.execute("SELECT * FROM pcs ORDER BY alias")
return self.cursor.fetchall()
def add_pc(self, hostname, username, encrypted_password, alias, mac_address=''):
self.cursor.execute(
"INSERT INTO pcs (hostname, username, password_encrypted, alias, status, last_update, pending_updates, uptime, disk_free, mac_address) VALUES (?, ?, ?, ?, 'Unknown', 'N/A', 0, 'N/A', 'N/A', ?)",
(hostname, username, encrypted_password, alias, mac_address or ''),
)
self.conn.commit()
return self.cursor.lastrowid
def update_mac(self, pc_id, mac_address):
"""Stores/refreshes the MAC address for a PC (used for Wake-on-LAN)."""
if not mac_address:
return
try:
self.cursor.execute(
"UPDATE pcs SET mac_address=? WHERE id=?",
(mac_address, pc_id),
)
self.conn.commit()
except sqlite3.Error as e:
print(f"[DB ERROR] Failed to update MAC for PC {pc_id}: {e}")
def delete_pc(self, pc_id):
self.cursor.execute("DELETE FROM pcs WHERE id=?", (pc_id,))
self.conn.commit()
def update_status(self, pc_id, status, last_update, pending_updates=0, uptime='N/A', disk_free='N/A'):
"""Updates the database record for a PC."""
try:
self.cursor.execute(
"UPDATE pcs SET status=?, last_update=?, pending_updates=?, uptime=?, disk_free=? WHERE id=?",
(status, last_update, pending_updates, uptime, disk_free, pc_id),
)
self.conn.commit()
except sqlite3.Error as e:
print(f"[DB ERROR] Failed to update status for PC {pc_id}: {e}")
def update_pc(self, pc_id, hostname, username, encrypted_password, alias):
self.cursor.execute(
"UPDATE pcs SET hostname=?, username=?, password_encrypted=?, alias=? WHERE id=?",
(hostname, username, encrypted_password, alias, pc_id),
)
self.conn.commit()
def delete_all_snapshots_for_pc(self, pc_id):
self.cursor.execute("DELETE FROM software_snapshots WHERE pc_id=?", (pc_id,))
self.conn.commit()
def save_snapshot(self, pc_id, package_list_data, user_list_data="", group_list_data=""):
self.delete_all_snapshots_for_pc(pc_id)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.cursor.execute(
"INSERT INTO software_snapshots (pc_id, timestamp, package_list, user_list, group_list) "
"VALUES (?, ?, ?, ?, ?)",
(pc_id, timestamp, package_list_data, user_list_data or "", group_list_data or ""),
)
self.conn.commit()
def get_latest_snapshot(self, pc_id):
"""Returns package_list string only (backwards-compatible)."""
self.cursor.execute(
"SELECT package_list FROM software_snapshots WHERE pc_id=? ORDER BY timestamp DESC LIMIT 1",
(pc_id,),
)
result = self.cursor.fetchone()
return result[0] if result else None
def get_latest_snapshot_full(self, pc_id):
"""Returns (package_list, user_list, group_list) tuple, or None."""
self.cursor.execute(
"SELECT package_list, user_list, group_list "
"FROM software_snapshots WHERE pc_id=? ORDER BY timestamp DESC LIMIT 1",
(pc_id,),
)
result = self.cursor.fetchone()
if result:
return result[0], result[1] or "", result[2] or ""
return None
def get_latest_snapshot_timestamp(self, pc_id):
self.cursor.execute(
"SELECT timestamp FROM software_snapshots WHERE pc_id=? ORDER BY timestamp DESC LIMIT 1",
(pc_id,),
)
result = self.cursor.fetchone()
return result[0] if result else "N/A"
# --- Tooltip Class ---
class Tooltip:
"""
A polished dark tooltip that appears after a short hover delay.
Attach with: Tooltip(widget, "Your text here")
"""
DELAY_MS = 500 # ms before tooltip appears
BG = '#2a2b2d'
FG = '#e2e3e5'
BORDER = '#4a9eff'
FONT = ('Segoe UI', 9)
def __init__(self, widget, text):
self.widget = widget
self.text = text
self._win = None
self._job = None
widget.bind('<Enter>', self._schedule, add='+')
widget.bind('<Leave>', self._cancel, add='+')
widget.bind('<Button-1>', self._cancel, add='+')
def _schedule(self, event=None):
self._cancel()
self._job = self.widget.after(self.DELAY_MS, self._show)
def _cancel(self, event=None):
if self._job:
self.widget.after_cancel(self._job)
self._job = None
if self._win:
self._win.destroy()
self._win = None
def _show(self):
if self._win:
return
# Position just below-right of the widget
x = self.widget.winfo_rootx() + 20
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 4
self._win = tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(True) # no window chrome
tw.wm_geometry(f'+{x}+{y}')
tw.wm_attributes('-topmost', True)
# Outer border frame
border = tk.Frame(tw, bg=self.BORDER, padx=1, pady=1)
border.pack()
inner = tk.Frame(border, bg=self.BG, padx=8, pady=5)
inner.pack()
tk.Label(inner, text=self.text,
bg=self.BG, fg=self.FG,
font=self.FONT,
justify='left',
wraplength=260).pack()
# --- Autocomplete Entry Widget ---
class AutocompleteEntry(tk.Entry):
"""
A plain tk.Entry that shows a filtering dropdown of suggestions as the
user types. Free-text entry is always preserved — nothing here validates
or restricts what can be typed; the dropdown is purely a shortcut for
values that match a discovered/known list. Clicking a suggestion fills
the field and closes the dropdown; typing something that matches nothing
just leaves the dropdown empty.
Usage:
entry = AutocompleteEntry(parent, ...)
entry.set_suggestions([{'value': '192.168.1.42', 'label': '192.168.1.42 (pi4)'}, ...])
"""
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self._suggestions = [] # list of {'value': ..., 'label': ...}
self._popup = None
self._listbox = None
self.bind('<KeyRelease>', self._on_keyrelease)
self.bind('<FocusOut>', lambda e: self.after(150, self._hide_popup))
self.bind('<Escape>', lambda e: self._hide_popup())
def set_suggestions(self, suggestions):
"""suggestions: list of {'value': str, 'label': str}"""
self._suggestions = suggestions or []
def _on_keyrelease(self, event):
if event.keysym in ('Up', 'Down', 'Return', 'Escape'):
return
typed = self.get().strip().lower()
if not typed or not self._suggestions:
self._hide_popup()
return
matches = [s for s in self._suggestions
if typed in s['value'].lower() or typed in s['label'].lower()]
if not matches:
self._hide_popup()
return
self._show_popup(matches[:12])
def _show_popup(self, matches):
if self._popup is None:
self._popup = tk.Toplevel(self)
self._popup.wm_overrideredirect(True)
self._popup.wm_attributes('-topmost', True)
self._listbox = tk.Listbox(self._popup,
bg=BG_TERTIARY, fg=FG_PRIMARY,
selectbackground=ACCENT_BLUE,
relief='flat', bd=1,
highlightthickness=1,
highlightbackground=BORDER_COLOR,
font=('Consolas', 10),
activestyle='none')
self._listbox.pack(fill='both', expand=True)
self._listbox.bind('<<ListboxSelect>>', self._on_select)
self._listbox.bind('<Button-1>', self._on_select, add='+')
self._listbox.delete(0, 'end')
self._match_values = []
for m in matches:
self._listbox.insert('end', m['label'])
self._match_values.append(m['value'])
x = self.winfo_rootx()
y = self.winfo_rooty() + self.winfo_height()
width = max(self.winfo_width(), 220)
height = min(22 * len(matches) + 4, 200)
self._popup.wm_geometry(f'{width}x{height}+{x}+{y}')
self._popup.deiconify()
def _on_select(self, event=None):
if not self._listbox:
return
sel = self._listbox.curselection()
if not sel:
return
value = self._match_values[sel[0]]
self.delete(0, 'end')
self.insert(0, value)
self._hide_popup()
self.icursor('end')
def _hide_popup(self):
if self._popup is not None:
self._popup.destroy()
self._popup = None
self._listbox = None
# --- Add PC Dialog Class ---
class AddPCDialog(tk.Toplevel):
def __init__(self, parent, is_edit=False):
super().__init__(parent)
self.title("Edit PC Details" if is_edit else "Add New PC")
self.transient(parent)
self.parent = parent
self.result = None
self.data = {}
self._idle_check_timer_id = None
self._watchdog_timer_id = None
# ip -> {'hostname': str|None, 'mac': str|None}, populated by the
# background subnet scan. Used to auto-suggest in the hostname field
# and to silently carry a discovered MAC address through to on_ok()
# for Wake-on-LAN, without ever forcing the user to type one in.
self._discovered = {}
self.config(bg=BG_PRIMARY)
self.minsize(600, 280)
main_frame = tk.Frame(self, bg=BG_PRIMARY)
main_frame.pack(fill='both', expand=True, padx=20, pady=20)
# Title
title_label = tk.Label(main_frame,
text="Edit PC Details" if is_edit else "Add New PC",
bg=BG_PRIMARY, fg=FG_PRIMARY,
font=('Segoe UI', 14, 'bold'))
title_label.pack(pady=(0, 20))
# Fields frame
fields_frame = tk.Frame(main_frame, bg=BG_PRIMARY)
fields_frame.pack(fill='both', expand=True, pady=10)
fields = [
("Alias:", "alias_entry"),
("Hostname or IP:", "hostname_entry"),
("Username:", "username_entry"),
("Password:", "password_entry"),
]
self.entries = {}
for i, (label_text, entry_key) in enumerate(fields):
label = tk.Label(fields_frame, text=label_text,
bg=BG_PRIMARY, fg=FG_SECONDARY,
font=('Segoe UI', 10), anchor='w')
label.grid(row=i, column=0, sticky='w', padx=(0, 15), pady=8)
entry_cls = AutocompleteEntry if entry_key == "hostname_entry" else tk.Entry
entry = entry_cls(fields_frame, width=40,
bg=BG_TERTIARY, fg=FG_PRIMARY,
insertbackground=FG_PRIMARY,
relief='flat', bd=0,
font=('Segoe UI', 10))
entry.config(highlightthickness=1, highlightcolor=ACCENT_BLUE,
highlightbackground=BORDER_COLOR)
if entry_key == "password_entry":
entry.config(show='●')
if is_edit:
entry.insert(0, "(Leave blank to keep existing password)")
if entry_key == "hostname_entry":
self.hostname_entry = entry
self.entries[entry_key] = entry
entry.grid(row=i, column=1, sticky='we', padx=0, pady=8)
fields_frame.columnconfigure(1, weight=1)
# Scan status line — shows progress of the background subnet scan
# that powers the hostname autocomplete suggestions.
self.scan_status_var = tk.StringVar(value="")
scan_status_label = tk.Label(main_frame, textvariable=self.scan_status_var,
bg=BG_PRIMARY, fg=FG_TERTIARY,
font=('Segoe UI', 8), anchor='w')
scan_status_label.pack(fill='x', pady=(0, 4))
# Kick off a background network scan so suggestions are ready (or
# filling in) by the time the user starts typing. Never blocks the UI.
if not is_edit:
self._start_network_scan()
# Button frame
button_frame = tk.Frame(main_frame, bg=BG_PRIMARY)
button_frame.pack(fill='x', pady=(20, 0))
cancel_btn = AdaptiveButton(button_frame, text="Cancel",
command=self.destroy,
bg=BG_TERTIARY, fg=FG_PRIMARY,
font=('Segoe UI', 10),
relief='flat', bd=0,
padx=20, pady=8,
cursor='hand2')
cancel_btn.pack(side='right', padx=(10, 0))
ok_btn = AdaptiveButton(button_frame, text="OK",
command=self.on_ok,
bg=BTN_PRIMARY, fg='white',
font=('Segoe UI', 10, 'bold'),
relief='flat', bd=0,
padx=20, pady=8,
cursor='hand2')
ok_btn.pack(side='right')
# Hover effects
def on_enter(e, btn, color):
btn['bg'] = color
def on_leave(e, btn, color):
btn['bg'] = color
ok_btn.bind('<Enter>', lambda e: on_enter(e, ok_btn, BTN_PRIMARY_HOVER))
ok_btn.bind('<Leave>', lambda e: on_leave(e, ok_btn, BTN_PRIMARY))
cancel_btn.bind('<Enter>', lambda e: on_enter(e, cancel_btn, BG_SECONDARY))
cancel_btn.bind('<Leave>', lambda e: on_leave(e, cancel_btn, BG_TERTIARY))
self.protocol("WM_DELETE_WINDOW", self.destroy)
self.update_idletasks()
self.grab_set()
width = self.winfo_width()
height = self.winfo_height()
x = parent.winfo_x() + parent.winfo_width() // 2 - width // 2
y = parent.winfo_y() + parent.winfo_height() // 2 - height // 2
self.geometry(f'+{x}+{y}')
def _start_network_scan(self):
self.scan_status_var.set("Scanning local network for SSH-reachable hosts...")
def worker():
hosts = get_local_subnet_hosts()
if not hosts:
self.after(0, lambda: self.scan_status_var.set(
"Could not determine local subnet — enter hostname/IP manually."))
return
found = scan_for_ssh_hosts(hosts)
arp = get_arp_table()
for entry in found:
entry['mac'] = arp.get(entry['ip'])
self.after(0, lambda: self._apply_scan_results(found))
threading.Thread(target=worker, daemon=True).start()
def _apply_scan_results(self, found):
if not self.winfo_exists():
return # dialog was closed before the scan finished
self._discovered = {f['ip']: {'hostname': f['hostname'], 'mac': f['mac']} for f in found}
suggestions = []
for f in found:
label = f['ip'] if not f['hostname'] else f"{f['ip']} ({f['hostname']})"
suggestions.append({'value': f['ip'], 'label': label})
if f['hostname']:
# Also suggest by hostname, so typing a name works too
suggestions.append({'value': f['ip'], 'label': f"{f['hostname']} ({f['ip']})"})
self.hostname_entry.set_suggestions(suggestions)
if found:
self.scan_status_var.set(
f"Found {len(found)} SSH-reachable device(s) on the network — start typing to see suggestions.")
else:
self.scan_status_var.set("No SSH-reachable devices found on the local network.")
def on_ok(self):
self.data = {key.replace('_entry', ''): entry.get().strip()
for key, entry in self.entries.items()}
# If what was entered/selected matches a discovered host, carry its
# MAC address through silently for Wake-on-LAN — no extra field,
# no extra step for the user.
entered = self.data.get('hostname', '')
match = self._discovered.get(entered)
self.data['mac_address'] = (match or {}).get('mac') or ''
self.result = "ok"
self.destroy()
def show(self):
self.wait_window(self)
return self.result, self.data
# --- Deploy Software Dialog Class ---
class DeploySoftwareDialog(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.title("Deploy Software to Selected PCs")
self.transient(parent)
self.parent = parent
self.result = None
self.packages = []
self.placeholder_text = "e.g., htop git vim curl"
self.placeholder_color = '#666666'
self.default_color = FG_PRIMARY
self.config(bg=BG_PRIMARY)
self.minsize(500, 220)
main_frame = tk.Frame(self, bg=BG_PRIMARY)
main_frame.pack(fill='both', expand=True, padx=20, pady=20)
# Title
title_label = tk.Label(main_frame,
text="Deploy Software",
bg=BG_PRIMARY, fg=FG_PRIMARY,
font=('Segoe UI', 14, 'bold'))
title_label.pack(pady=(0, 10))
info_label = tk.Label(main_frame,
text="Enter package names separated by space or comma:",
bg=BG_PRIMARY, fg=FG_SECONDARY,
font=('Segoe UI', 9))
info_label.pack(anchor='w', pady=(0, 10))
self.software_entry = tk.Entry(main_frame, width=50,
bg=BG_TERTIARY, fg=self.placeholder_color,
insertbackground=FG_PRIMARY,
relief='flat', bd=0,
font=('Segoe UI', 11))
self.software_entry.config(highlightthickness=1, highlightcolor=ACCENT_BLUE,
highlightbackground=BORDER_COLOR)
self.software_entry.insert(0, self.placeholder_text)
self.software_entry.pack(fill='x', pady=10, ipady=8)
self.software_entry.bind('<FocusIn>', self.on_entry_focus)
# Button frame
button_frame = tk.Frame(main_frame, bg=BG_PRIMARY)
button_frame.pack(fill='x', pady=(20, 0))
cancel_btn = AdaptiveButton(button_frame, text="Cancel",
command=self.destroy,
bg=BG_TERTIARY, fg=FG_PRIMARY,
font=('Segoe UI', 10),
relief='flat', bd=0,
padx=20, pady=8,
cursor='hand2')
cancel_btn.pack(side='right', padx=(10, 0))
deploy_btn = AdaptiveButton(button_frame, text="Deploy",
command=self.on_deploy,
bg=BTN_SUCCESS, fg='white',
font=('Segoe UI', 10, 'bold'),
relief='flat', bd=0,
padx=20, pady=8,
cursor='hand2')
deploy_btn.pack(side='right')
# Hover effects
deploy_btn.bind('<Enter>', lambda e: deploy_btn.config(bg=BTN_SUCCESS_HOVER))
deploy_btn.bind('<Leave>', lambda e: deploy_btn.config(bg=BTN_SUCCESS))
cancel_btn.bind('<Enter>', lambda e: cancel_btn.config(bg=BG_SECONDARY))
cancel_btn.bind('<Leave>', lambda e: cancel_btn.config(bg=BG_TERTIARY))
self.protocol("WM_DELETE_WINDOW", self.destroy)
self.update_idletasks()
self.grab_set()
width = self.winfo_width()
height = self.winfo_height()
x = parent.winfo_x() + parent.winfo_width() // 2 - width // 2
y = parent.winfo_y() + parent.winfo_height() // 2 - height // 2
self.geometry(f'+{x}+{y}')
def on_entry_focus(self, event):
if self.software_entry.get() == self.placeholder_text:
self.software_entry.delete(0, 'end')
self.software_entry.config(fg=self.default_color)
def on_deploy(self):
text = self.software_entry.get().strip()
if not text or text == self.placeholder_text:
messagebox.showerror("Error", "Package list cannot be empty.")
return
self.packages = text.replace(',', ' ').split()
self.result = "deploy"
self.destroy()
def show(self):
self.wait_window(self)
return self.result, self.packages
# --- Run Command Dialog Class ---
class RunCommandDialog(tk.Toplevel):
# Dictionary of popular commands for quick selection
# You can add / alter your own here
POPULAR_COMMANDS = {
"Show Disk Usage": "df -h",
"View System Uptime": "uptime",
"Check Free Memory (RAM)": "free -h",
"Top 5 Memory Hogs": "ps aux --sort=-%mem | head -n 6",
"CPU Temperature (Universal)": "cat /sys/class/thermal/thermal_zone*/temp | cut -c1-2 | sed s/$/°C/",
"Quick Port Scan (Ports 1-1024) - Run without Sudo": "for port in $(seq 1 1024); do (echo > /dev/tcp/127.0.0.1/$port) >/dev/null 2>&1 && echo Port $port is OPEN; done",
"Check Kernel Information": "uname -a",
"View System Logs (tail -n 50)": "tail -n 50 /var/log/syslog || journalctl -n 50",
"Check Failed Systemd Services": "systemctl --failed",
"Network Card Info (ifconfig fallback)": "ip a || ifconfig -a",
"Test Internet Connection (Ping Google DNS)": "ping -c 4 8.8.8.8",
"Check IP Address (All Non-Loopback)": "ip a | grep 'inet ' | grep -v '127.0.0.1'",
"Remove Package": "apt remove --purge -y <TYPE PACKAGE NAME HERE>",
"Cleanup (Autoremove & Purge Cache)": "sudo apt update && sudo apt autoremove --purge -y && sudo apt clean",
}
def __init__(self, parent):
super().__init__(parent)
self.title("Run Remote Command")
self.transient(parent)
self.parent = parent
self.result = None
self.command = ""
self.use_sudo = tk.BooleanVar(value=True)
self.config(bg=BG_PRIMARY)
# Increased minsize to accommodate the side-by-side elements
self.minsize(700, 400)
main_frame = tk.Frame(self, bg=BG_PRIMARY)
main_frame.pack(fill='both', expand=True, padx=20, pady=20)
# Title
title_label = tk.Label(main_frame,
text="Run Remote Command",
bg=BG_PRIMARY, fg=FG_PRIMARY,
font=('Segoe UI', 14, 'bold'))
title_label.pack(pady=(0, 10))
# --- Command Section Container (Grid for Listbox + Textbox) ---
command_section = tk.Frame(main_frame, bg=BG_PRIMARY)
command_section.pack(fill='both', expand=True, pady=(0, 15))
# Configure columns: Listbox (weight 2) and Textbox (weight 1)
command_section.columnconfigure(0, weight=2)
command_section.columnconfigure(1, weight=1)
# --- Popular Commands Listbox ---
list_label = tk.Label(command_section,
text="Popular Commands (Click to select):",
bg=BG_PRIMARY, fg=FG_SECONDARY,
font=('Segoe UI', 9))
list_label.grid(row=0, column=0, sticky='w', pady=(0, 5))
list_frame = tk.Frame(command_section, bg=BORDER_COLOR)
list_frame.grid(row=1, column=0, sticky='nsew', padx=(0, 10))
self.command_listbox = tk.Listbox(list_frame, height=10,
width=40, # <-- WIDTH FIX APPLIED HERE
bg=BG_TERTIARY, fg=FG_PRIMARY,
selectbackground=ACCENT_BLUE,
selectforeground='white',
relief='flat', bd=0,
exportselection=False,
font=('Consolas', 10))
# Populate listbox with command display names
for display_name in self.POPULAR_COMMANDS.keys():
self.command_listbox.insert(tk.END, display_name)
# Use ttk.Scrollbar here
list_vsb = ttk.Scrollbar(list_frame, orient="vertical", command=self.command_listbox.yview)
self.command_listbox.configure(yscrollcommand=list_vsb.set)
list_vsb.pack(side='right', fill='y')
self.command_listbox.pack(side='left', fill='both', expand=True, padx=1, pady=1)
# Bind the selection event to the handler method
self.command_listbox.bind('<<ListboxSelect>>', self._on_command_select)
# --- Manual Command Text Widget ---
text_label = tk.Label(command_section,
text="Manual Command / Selected Command:",
bg=BG_PRIMARY, fg=FG_SECONDARY,
font=('Segoe UI', 9))
text_label.grid(row=0, column=1, sticky='w', pady=(0, 5))
text_frame = tk.Frame(command_section, bg=BORDER_COLOR)
text_frame.grid(row=1, column=1, sticky='nsew')