-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsofilab.py
More file actions
executable file
Β·3165 lines (2869 loc) Β· 121 KB
/
sofilab.py
File metadata and controls
executable file
Β·3165 lines (2869 loc) Β· 121 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
"""
SofiLab - Cross-platform Python CLI
Feature parity with the existing bash tool (sofilab.sh) for:
- login, reset-hostkey, status, run-scripts, run-script, reboot, list-scripts,
logs, clear-logs, install, uninstall, --version, --help
Notes:
- Uses Paramiko for SSH/SFTP to be cross-platform (Windows/macOS/Linux).
- Preserves config format from `sofilab.conf` and global logging options.
- Stores logs in `logs/` with rotation similar to bash version.
"""
from __future__ import annotations
import argparse
import dataclasses
import errno
import getpass
import io
import os
import re
import select
import shlex
import signal
import socket
import sys
import time
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import importlib
import subprocess
import stat
import posixpath
import shutil
# Paramiko is loaded lazily. If missing, we will auto-install from requirements.txt.
PARAMIKO_MOD = None # type: ignore
def ensure_paramiko():
"""Return a working paramiko module or raise with a clear message.
Handles environments where a shadowing module exists or a partial install
returns an invalid object. Attempts auto-install/repair once.
"""
global PARAMIKO_MOD
if PARAMIKO_MOD is not None:
return PARAMIKO_MOD
def _import_paramiko():
mod = importlib.import_module("paramiko")
if mod is None or not hasattr(mod, "SSHClient"):
raise ImportError("paramiko imported but invalid (missing SSHClient)")
return mod
try:
PARAMIKO_MOD = _import_paramiko()
return PARAMIKO_MOD
except Exception:
# Try to install dependencies automatically
req = SCRIPT_DIR / "requirements.txt"
cmd = [sys.executable, "-m", "pip", "install"]
if req.exists():
cmd += ["-r", str(req)]
print("Installing Python dependencies from requirements.txt...", file=sys.stderr)
else:
cmd += ["paramiko>=3.4.0"]
print("Installing Python dependency: paramiko...", file=sys.stderr)
try:
try:
# Remove any preloaded/invalid module
if "paramiko" in sys.modules:
del sys.modules["paramiko"]
except Exception:
pass
subprocess.check_call(cmd)
except Exception as e:
print(f"β Failed to install dependencies automatically: {e}", file=sys.stderr)
print("Please run: python -m pip install paramiko>=3.4.0", file=sys.stderr)
raise
PARAMIKO_MOD = _import_paramiko()
return PARAMIKO_MOD
# --------------------------
# Windows helpers
# --------------------------
def _win_local_appdata() -> Optional[Path]:
"""Return LocalAppData path using Win32 API for robustness on Windows.
Falls back to environment variable or user home if needed.
"""
if os.name != 'nt':
return None
# Try Win32 SHGetKnownFolderPath(FOLDERID_LocalAppData)
try:
import ctypes
from ctypes import wintypes
# FOLDERID_LocalAppData {F1B32785-6FBA-4FCF-9D55-7B8E7F157091}
class GUID(ctypes.Structure):
_fields_ = [
("Data1", ctypes.c_ulong),
("Data2", ctypes.c_ushort),
("Data3", ctypes.c_ushort),
("Data4", ctypes.c_ubyte * 8),
]
FOLDERID_LocalAppData = GUID(0xF1B32785, 0x6FBA, 0x4FCF, (ctypes.c_ubyte * 8)(0x9D, 0x55, 0x7B, 0x8E, 0x7F, 0x15, 0x70, 0x91))
SHGetKnownFolderPath = ctypes.windll.shell32.SHGetKnownFolderPath
SHGetKnownFolderPath.argtypes = [ctypes.POINTER(GUID), wintypes.DWORD, wintypes.HANDLE, ctypes.POINTER(ctypes.c_wchar_p)]
SHGetKnownFolderPath.restype = ctypes.c_long
path_ptr = ctypes.c_wchar_p()
# Flags = 0 (default). Token = None (current user)
hr = SHGetKnownFolderPath(ctypes.byref(FOLDERID_LocalAppData), 0, None, ctypes.byref(path_ptr))
if hr == 0 and path_ptr.value:
try:
return Path(path_ptr.value)
finally:
try:
ctypes.windll.ole32.CoTaskMemFree(path_ptr)
except Exception:
pass
except Exception:
pass
# Fallbacks
try:
env = os.environ.get("LOCALAPPDATA")
if env:
return Path(env)
except Exception:
pass
try:
return Path.home() / "AppData" / "Local"
except Exception:
return None
# --------------------------
# Metadata
# --------------------------
VERSION = "1.0.0-Python"
BUILD_DATE = "2025-09-10"
AUTHOR = "Arafat Ali <arafat@sofibox.com>"
# --------------------------
# Paths and environment
# --------------------------
SCRIPT_PATH = Path(__file__).resolve()
SCRIPT_DIR = SCRIPT_PATH.parent
SCRIPT_NAME = SCRIPT_PATH.name
CONFIG_FILE = SCRIPT_DIR / "sofilab.conf"
# --------------------------
# Logging (Rotating)
# --------------------------
import logging
from logging.handlers import RotatingFileHandler
@dataclasses.dataclass
class GlobalConfig:
log_dir: Path = SCRIPT_DIR / "logs"
log_level: str = "INFO" # DEBUG, INFO, WARN, ERROR
enable_logging: bool = True
max_log_size: str = "10M" # K/M/G
max_log_files: int = 5
script_exit_on_error: bool = True
force_tty: bool = True
def max_bytes(self) -> int:
s = self.max_log_size.strip().upper()
if s.endswith("G"):
return int(s[:-1]) * 1024 * 1024 * 1024
if s.endswith("M"):
return int(s[:-1]) * 1024 * 1024
if s.endswith("K"):
return int(s[:-1]) * 1024
return int(s)
MAIN_LOG: Optional[Path] = None
ERROR_LOG: Optional[Path] = None
REMOTE_LOG: Optional[Path] = None
def init_logging(cfg: GlobalConfig) -> None:
global MAIN_LOG, ERROR_LOG, REMOTE_LOG
if not cfg.enable_logging:
return
cfg.log_dir.mkdir(parents=True, exist_ok=True)
MAIN_LOG = cfg.log_dir / "sofilab.log"
ERROR_LOG = cfg.log_dir / "sofilab-error.log"
REMOTE_LOG = cfg.log_dir / "sofilab-remote.log"
# Root logger setup
root = logging.getLogger("sofilab")
root.setLevel(getattr(logging, cfg.log_level.upper(), logging.INFO))
root.handlers[:] = []
fmt = logging.Formatter("[%(asctime)s] [%(levelname)s] %(message)s")
if MAIN_LOG:
h_main = RotatingFileHandler(MAIN_LOG, maxBytes=cfg.max_bytes(), backupCount=cfg.max_log_files, encoding="utf-8")
h_main.setFormatter(fmt)
h_main.setLevel(getattr(logging, cfg.log_level.upper(), logging.INFO))
root.addHandler(h_main)
# Separate error file
if ERROR_LOG:
h_err = RotatingFileHandler(ERROR_LOG, maxBytes=cfg.max_bytes(), backupCount=cfg.max_log_files, encoding="utf-8")
h_err.setFormatter(fmt)
h_err.setLevel(logging.ERROR)
root.addHandler(h_err)
def log_remote(alias: str, script: str, line: str) -> None:
global REMOTE_LOG
if REMOTE_LOG is None:
return
try:
REMOTE_LOG.parent.mkdir(parents=True, exist_ok=True)
with REMOTE_LOG.open("a", encoding="utf-8", errors="ignore") as f:
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
f.write(f"[{ts}] [{alias}] [{script}] {line}\n")
except Exception:
pass
log = logging.getLogger("sofilab")
def info(msg: str) -> None:
print(f"π‘ {msg}", file=sys.stderr)
log.info(msg)
def warn(msg: str) -> None:
print(f"β οΈ {msg}", file=sys.stderr)
log.warning(msg)
def error(msg: str) -> None:
print(f"β {msg}", file=sys.stderr)
log.error(msg)
def success(msg: str) -> None:
print(f"β
{msg}", file=sys.stderr)
log.info("SUCCESS: %s", msg)
def progress(msg: str) -> None:
print(f"π {msg}", file=sys.stderr)
log.info("PROGRESS: %s", msg)
# --------------------------
# Utilities
# --------------------------
def resolve_host_ip(host: str) -> Optional[str]:
try:
# Prefer IPv4 if possible
for family in (socket.AF_INET, socket.AF_INET6):
try:
infos = socket.getaddrinfo(host, None, family, socket.SOCK_STREAM)
if infos:
return infos[0][4][0]
except socket.gaierror:
continue
except Exception:
pass
return None
def check_port_open(host: str, port: int, timeout: float = 3.0) -> bool:
try:
with socket.create_connection((host, port), timeout=timeout):
return True
except OSError:
return False
def human_size(nbytes: int) -> str:
suffixes = ['B', 'KB', 'MB', 'GB', 'TB']
i = 0
f = float(nbytes)
while f >= 1024 and i < len(suffixes) - 1:
f /= 1024.0
i += 1
if i == 0:
return f"{int(f)}{suffixes[i]}"
return f"{f:.1f}{suffixes[i]}"
# --------------------------
# Config parsing
# --------------------------
@dataclasses.dataclass
class ServerConfig:
aliases: List[str]
host: str
user: str
password: str = ""
port: int = 22
keyfile: str = ""
# Legacy fields no longer used for run-scripts; preserved for compatibility
scripts: List[str] = dataclasses.field(default_factory=list)
script_args_map: Dict[str, List[str]] = dataclasses.field(default_factory=dict)
default_script_args: List[str] = dataclasses.field(default_factory=list)
def parse_conf(path: Path) -> Tuple[GlobalConfig, Dict[str, ServerConfig]]:
if not path.exists():
raise FileNotFoundError(errno.ENOENT, "Configuration file not found", str(path))
gcfg = GlobalConfig()
servers: Dict[str, ServerConfig] = {}
section: Optional[str] = None
section_aliases: List[str] = []
acc: Dict[str, str] = {}
def flush_server() -> None:
nonlocal servers, section_aliases, acc
if not section_aliases:
return
host = acc.get("host", "").strip()
user = acc.get("user", "").strip()
if not host or not user:
# Skip invalid blocks
return
password = acc.get("password", "").strip()
port_s = acc.get("port", "22").strip()
try:
port = int(port_s)
except ValueError:
port = 22
keyfile = acc.get("keyfile", "").strip()
scripts_s = acc.get("scripts", "").strip()
scripts = [s.strip() for s in scripts_s.split(',') if s.strip()] if scripts_s else []
# Support inline args inside scripts entries, e.g.:
# scripts="foo.sh --x 1, bar.sh 'arg with space'"
inline_args_map: Dict[str, List[str]] = {}
normalized_scripts: List[str] = []
for item in scripts:
try:
parts = shlex.split(item)
except Exception:
parts = [p for p in item.split() if p]
if not parts:
continue
name = parts[0]
if len(parts) > 1:
inline_args_map[name] = parts[1:]
normalized_scripts.append(name)
scripts = normalized_scripts
# Parse script args from keys like script_args.<script>="arg1 arg2" and default_script_args
script_args_map: Dict[str, List[str]] = {}
default_script_args: List[str] = []
for k, v in acc.items():
if k.startswith("script_args.") or k.startswith("script-args."):
name = k.split('.', 1)[1].strip()
try:
script_args_map[name] = shlex.split(v)
except Exception:
# Fall back to space split
script_args_map[name] = [p for p in v.split() if p]
elif k in ("default_script_args", "default-script-args"):
try:
default_script_args = shlex.split(v)
except Exception:
default_script_args = [p for p in v.split() if p]
# Merge inline args; explicit keys override inline
for _n, _a in inline_args_map.items():
if _n not in script_args_map:
script_args_map[_n] = _a
sc = ServerConfig(section_aliases, host, user, password, port, keyfile, scripts, script_args_map, default_script_args)
for a in section_aliases:
servers[a] = sc
with path.open("r", encoding="utf-8", errors="ignore") as f:
for raw in f:
line = raw.strip()
if not line or line.startswith('#'):
continue
m = re.match(r"^\[(.+)\]$", line)
if m:
# flush previous
if section == "global":
pass # nothing to flush
else:
flush_server()
section = m.group(1).strip()
if section.lower() == "global":
section = "global"
section_aliases = []
acc = {}
else:
section_aliases = [a.strip() for a in section.split(',') if a.strip()]
acc = {}
continue
# key=value
kv = re.match(r"^([^=]+)=(.*)$", line)
if not kv or section is None:
continue
key = kv.group(1).strip()
val = kv.group(2).strip()
# remove optional quotes
if len(val) >= 2 and ((val[0] == '"' and val[-1] == '"') or (val[0] == "'" and val[-1] == "'")):
val = val[1:-1]
if section == "global":
if key == "log_dir":
p = Path(val)
gcfg.log_dir = p if p.is_absolute() else (SCRIPT_DIR / p)
elif key == "log_level":
if val.upper() in {"DEBUG", "INFO", "WARN", "ERROR"}:
gcfg.log_level = val.upper()
elif key == "enable_logging":
gcfg.enable_logging = val.lower() == "true"
elif key == "max_log_size":
gcfg.max_log_size = val
elif key == "max_log_files":
try:
gcfg.max_log_files = max(1, int(val))
except ValueError:
pass
elif key == "script_exit_on_error":
gcfg.script_exit_on_error = val.lower() == "true"
elif key == "force_tty":
gcfg.force_tty = val.lower() == "true"
else:
warn(f"Unknown global configuration key: {key}")
else:
acc[key] = val
# flush last
if section != "global":
flush_server()
return gcfg, servers
# --------------------------
# SSH/Paramiko helpers
# --------------------------
class SSHClient:
def __init__(self, host: str, port: int, username: str, password: str = "", key_path: Optional[Path] = None):
self.host = host
self.port = port
self.username = username
self.password = password
self.key_path = key_path
self.client: Optional[object] = None
self.transport: Optional[object] = None
def connect(self, timeout: float = 5.0) -> None:
paramiko = ensure_paramiko()
c = paramiko.SSHClient()
# Automatically accept and add new host keys (aligns with bash StrictHostKeyChecking=accept-new)
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
key_filename = None
if self.key_path and self.key_path.exists():
key_filename = str(self.key_path)
# Try agent/keys first without prompting for passphrases
try:
c.connect(
hostname=self.host,
port=self.port,
username=self.username,
password=None,
key_filename=key_filename,
look_for_keys=True,
allow_agent=True,
timeout=timeout,
auth_timeout=timeout,
banner_timeout=timeout,
)
except paramiko.AuthenticationException:
# Fallback to password auth if provided (do not prompt for key passphrase)
if self.password:
c.connect(
hostname=self.host,
port=self.port,
username=self.username,
password=self.password,
look_for_keys=False,
allow_agent=True,
timeout=timeout,
auth_timeout=timeout,
banner_timeout=timeout,
)
else:
raise
self.client = c
self.transport = c.get_transport()
def close(self) -> None:
try:
if self.client:
self.client.close()
finally:
self.client = None
self.transport = None
def run(self, command: str, env: Optional[Dict[str, str]] = None, get_pty: bool = False, timeout: Optional[float] = None) -> Tuple[int, str, str]:
assert self.client is not None, "SSH not connected"
chan = self.client.get_transport().open_session()
if get_pty:
chan.get_pty()
if env:
# Paramiko supports env on exec_command via Channel
for k, v in env.items():
chan.update_environment({k: v})
chan.exec_command(command)
stdout = io.BytesIO()
stderr = io.BytesIO()
start = time.time()
while True:
if chan.recv_ready():
stdout.write(chan.recv(32768))
if chan.recv_stderr_ready():
stderr.write(chan.recv_stderr(32768))
if chan.exit_status_ready():
# flush remaining
while chan.recv_ready():
stdout.write(chan.recv(32768))
while chan.recv_stderr_ready():
stderr.write(chan.recv_stderr(32768))
break
if timeout is not None and (time.time() - start) > timeout:
chan.close()
break
time.sleep(0.01)
code = chan.recv_exit_status()
return code, stdout.getvalue().decode(errors="ignore"), stderr.getvalue().decode(errors="ignore")
def sftp(self):
assert self.client is not None, "SSH not connected"
return self.client.open_sftp()
def interactive_shell(self) -> None:
"""Interactive shell bridging local TTY <-> remote PTY.
On POSIX, switch local TTY to raw mode so line editing keys work
(arrows, backspace, Ctrl-C, etc.), then restore on exit.
"""
assert self.client is not None
# Prefer 256-color term if available; fall back to xterm
term_name = os.environ.get("TERM") or "xterm-256color"
chan = self.client.invoke_shell(term=term_name)
# Try to set window size if we can (POSIX only)
try:
import fcntl, struct, termios
def get_winsize():
s = struct.pack('HHHH', 0, 0, 0, 0)
r = fcntl.ioctl(sys.stdin.fileno(), termios.TIOCGWINSZ, s)
rows, cols, _, _ = struct.unpack('HHHH', r)
return rows, cols
rows, cols = get_winsize()
chan.resize_pty(width=cols, height=rows)
except Exception:
pass
if os.name == 'nt':
# Windows: use msvcrt for keyboard input, and a loop for channel
import threading, msvcrt
stop = False
def reader():
while not stop:
data = chan.recv(32768)
if not data:
break
sys.stdout.write(data.decode(errors="ignore"))
sys.stdout.flush()
t = threading.Thread(target=reader, daemon=True)
t.start()
try:
while True:
if msvcrt.kbhit():
ch = msvcrt.getwch()
if ch == '\r':
chan.send("\r")
else:
chan.send(ch.encode('utf-8'))
if chan.exit_status_ready():
break
time.sleep(0.01)
except KeyboardInterrupt:
pass
finally:
stop = True
try:
chan.close()
except Exception:
pass
else:
# POSIX: put local TTY into raw mode and bridge bytes
import termios, tty, signal
fd = sys.stdin.fileno()
old_attrs = None
# Handle window resize: propagate to remote PTY
def _on_winch(_sig, _frm):
try:
import fcntl, struct, termios as _t
s = struct.pack('HHHH', 0, 0, 0, 0)
r = fcntl.ioctl(fd, _t.TIOCGWINSZ, s)
rows, cols, _, _ = struct.unpack('HHHH', r)
try:
chan.resize_pty(width=cols, height=rows)
except Exception:
pass
except Exception:
pass
try:
if sys.stdin.isatty():
old_attrs = termios.tcgetattr(fd)
tty.setraw(fd)
signal.signal(signal.SIGWINCH, _on_winch)
while True:
rlist, _, _ = select.select([chan, sys.stdin], [], [])
if chan in rlist:
data = chan.recv(32768)
if not data:
break
sys.stdout.write(data.decode(errors="ignore"))
sys.stdout.flush()
if sys.stdin in rlist:
try:
data = os.read(fd, 1024)
except Exception:
data = b""
if not data:
break
try:
chan.send(data)
except Exception:
break
except KeyboardInterrupt:
pass
finally:
if old_attrs is not None:
try:
termios.tcsetattr(fd, termios.TCSADRAIN, old_attrs)
except Exception:
pass
try:
chan.close()
except Exception:
pass
# --------------------------
# Core features
# --------------------------
def determine_ssh_port(configured_port: int, host: str) -> Optional[int]:
display_host = host
rip = resolve_host_ip(host)
if rip and rip != host:
display_host = f"{host} ({rip})"
progress(f"Checking connection to {display_host}:{configured_port}...")
if check_port_open(host, configured_port):
if configured_port == 22:
info("Port 22 is open (default SSH port)")
else:
info(f"Port {configured_port} is open (custom SSH port)")
return configured_port
if configured_port != 22:
progress(f"Port {configured_port} not accessible, trying fallback port 22...")
if check_port_open(host, 22):
info("Port 22 is open (fallback to default SSH port)")
return 22
error(f"Neither port {configured_port} nor port 22 are accessible")
return None
else:
error(f"Port {configured_port} is not accessible")
return None
def get_ssh_keyfile(sc: ServerConfig) -> Optional[Path]:
# Explicit keyfile
if sc.keyfile:
p = Path(sc.keyfile)
if not p.is_absolute():
p = SCRIPT_DIR / p
if p.exists():
info(f"Using SSH key: {p}")
return p
# Auto-detect ssh/<alias>_key
for alias in sc.aliases:
p = SCRIPT_DIR / "ssh" / f"{alias}_key"
if p.exists():
info(f"Using SSH key: {p}")
return p
return None
def server_status(sc: ServerConfig, alias: str, port_override: Optional[int] = None, hook_args: Optional[List[str]] = None) -> int:
port_to_check = port_override if port_override else determine_ssh_port(sc.port, sc.host)
if not port_to_check:
return 1
# Optional local hook override (scripts/hooks/status/* or legacy)
if hook_args and len(hook_args) > 0 and hook_args[0] == "--":
hook_args = hook_args[1:]
hook_rc = _run_local_hook("status", sc, alias, port_to_check, extra_args=hook_args)
if hook_rc is not None:
if hook_rc == 0:
success("Status hook completed successfully")
else:
error(f"Status hook failed with exit code {hook_rc}")
return hook_rc
print("")
print("π©Ί Server Status")
print("ββββββββββββββββββββββββββββββββββββββββββββββββββ")
print(f"π Host: {sc.host}")
print(f"π SSH Port: {port_to_check}")
if check_port_open(sc.host, port_to_check):
success("Port reachable")
else:
error("Port not reachable")
return 1
keyfile = get_ssh_keyfile(sc)
auth_ok = False
# Try key
try:
cli = SSHClient(sc.host, port_to_check, sc.user, key_path=keyfile)
cli.connect(timeout=5)
auth_ok = True
print("π Auth: SSH key works")
# also try a simple command
code, out, _ = cli.run("uname -a && uptime", timeout=5)
if code == 0 and out:
success("Retrieved basic system info")
for ln in out.splitlines():
print(" " + ln)
except Exception:
pass
finally:
try:
cli.close() # type: ignore
except Exception:
pass
if not auth_ok and sc.password:
try:
cli = SSHClient(sc.host, port_to_check, sc.user, password=sc.password)
cli.connect(timeout=5)
auth_ok = True
print("π Auth: Password works")
except Exception:
pass
finally:
try:
cli.close() # type: ignore
except Exception:
pass
if not auth_ok:
print("π Auth: Unknown (may require interactive password or key not found)")
return 0
## test_speed removed (feature deferred)
def router_webui(sc: ServerConfig, action: str) -> int:
"""Enable/disable ASUS Merlin web UI (WAN) on router hosts.
Only runs when the server's alias list includes 'router'.
"""
aliases_lower = {a.lower() for a in sc.aliases}
if "router" not in aliases_lower:
error("This command is restricted to hosts with alias 'router'")
return 1
use_port = determine_ssh_port(sc.port, sc.host)
if not use_port:
return 1
keyfile = get_ssh_keyfile(sc)
try:
cli = SSHClient(sc.host, use_port, sc.user, sc.password, keyfile)
cli.connect(timeout=5)
except Exception as e:
error(f"SSH connection failed: {e}")
return 1
try:
print("")
print("π οΈ ASUS Merlin Web UI Control")
print("ββββββββββββββββββββββββββββββββββββββββββββββββββ")
print(f"π Host: {sc.host}:{use_port}")
print(f"π― Action: {action}")
print("")
if action == "disable":
cmd = (
"sh -lc 'set -e; "
"nvram set misc_http_x=0; "
"nvram commit; "
"service restart_firewall; "
"service restart_httpd'"
)
else: # enable
cmd = (
"sh -lc 'set -e; "
"nvram set misc_http_x=2; "
"nvram commit; "
"service restart_firewall; "
"service restart_httpd'"
)
progress("Applying NVRAM changes on router...")
code, out, err = cli.run(cmd, get_pty=False, timeout=60)
if out.strip():
print(out.strip())
if code != 0:
error(f"Router command failed (exit {code}): {err.strip() or out.strip()}")
return code
success("Web UI setting updated and httpd restarted")
return 0
finally:
try:
cli.close()
except Exception:
pass
def _get_ssh_keyfile_quiet(sc: ServerConfig) -> Optional[Path]:
# Resolve explicit keyfile without logging
if sc.keyfile:
p = Path(sc.keyfile)
if not p.is_absolute():
p = SCRIPT_DIR / p
if p.exists():
return p
# Auto-detect ssh/<alias>_key without logging
for a in sc.aliases:
p = SCRIPT_DIR / "ssh" / f"{a}_key"
if p.exists():
return p
return None
def _run_local_hook(command_name: str, sc: ServerConfig, alias: str, actual_port: int, extra_args: Optional[List[str]] = None, key_path: Optional[Path] = None) -> Optional[int]:
"""Try to execute a local hook script for a command.
Resolution order (new preferred layout first, with legacy fallback):
1) scripts/hooks/<command>/hook.py (cross-platform via current Python)
2) scripts/<command>.py (legacy)
3) Windows: scripts/hooks/<command>/hook.ps1 -> scripts/<command>.ps1
4) POSIX: scripts/hooks/<command>/hook.sh -> scripts/<command>.sh
Returns the exit code if a hook was executed, or None if no hook found.
"""
scripts_dir = SCRIPT_DIR / "scripts"
hooks_dir = scripts_dir / "hooks" / command_name
hooks_scripts_dir = hooks_dir / "scripts"
# Preferred new layout: scripts/hooks/<cmd>/scripts/main.*
main_py = hooks_scripts_dir / "main.py"
main_ps1 = hooks_scripts_dir / "main.ps1"
main_sh = hooks_scripts_dir / "main.sh"
# Fallback new layout: scripts/hooks/<cmd>/hook.*
hook_py_new = hooks_dir / "hook.py"
hook_ps1_new = hooks_dir / "hook.ps1"
hook_sh_new = hooks_dir / "hook.sh"
# Legacy flat layout: scripts/<cmd>.*
hook_py_legacy = scripts_dir / f"{command_name}.py"
hook_ps1_legacy = scripts_dir / f"{command_name}.ps1"
hook_sh_legacy = scripts_dir / f"{command_name}.sh"
# Build environment for hooks
env = os.environ.copy()
env.update({
"SOFILAB_HOST": sc.host,
"SOFILAB_PORT": str(actual_port),
"SOFILAB_USER": sc.user,
"SOFILAB_PASSWORD": sc.password or "",
"SOFILAB_KEYFILE": str((key_path or _get_ssh_keyfile_quiet(sc) or Path()).__str__() if (key_path or _get_ssh_keyfile_quiet(sc)) else ""),
"SOFILAB_ALIAS": alias,
})
try:
# 1) Preferred: scripts/hooks/<cmd>/scripts/main.py
if main_py.exists():
hook_path = str(main_py)
info(f"Using {command_name} hook: {hook_path}")
cmd = [sys.executable, hook_path] + (extra_args or [])
return subprocess.call(cmd, env=env)
# 2) Preferred (Windows/POSIX): main.ps1 / main.sh
if os.name == 'nt' and main_ps1.exists():
pwsh = shutil.which("pwsh") or shutil.which("powershell") or "powershell"
hook_path = str(main_ps1)
info(f"Using {command_name} hook: {hook_path}")
cmd = [pwsh, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", hook_path] + (extra_args or [])
return subprocess.call(cmd, env=env)
if os.name != 'nt' and main_sh.exists():
sh_path = str(main_sh)
info(f"Using {command_name} hook: {sh_path}")
bash = shutil.which("bash")
cmd = [bash, sh_path] + (extra_args or []) if bash else ["/bin/sh", sh_path] + (extra_args or [])
return subprocess.call(cmd, env=env)
# 3) Fallback new layout: hook.py
if hook_py_new.exists():
hook_path = str(hook_py_new)
info(f"Using {command_name} hook: {hook_path}")
cmd = [sys.executable, hook_path] + (extra_args or [])
return subprocess.call(cmd, env=env)
# 4) Fallback new layout: hook.ps1 / hook.sh
if os.name == 'nt' and hook_ps1_new.exists():
pwsh = shutil.which("pwsh") or shutil.which("powershell") or "powershell"
ps1_path = str(hook_ps1_new)
info(f"Using {command_name} hook: {ps1_path}")
cmd = [pwsh, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", ps1_path] + (extra_args or [])
return subprocess.call(cmd, env=env)
if os.name != 'nt' and hook_sh_new.exists():
sh_path = str(hook_sh_new)
info(f"Using {command_name} hook: {sh_path}")
bash = shutil.which("bash")
cmd = [bash, sh_path] + (extra_args or []) if bash else ["/bin/sh", sh_path] + (extra_args or [])
return subprocess.call(cmd, env=env)
# 5) Legacy flat layout: scripts/<cmd>.py|ps1|sh
if hook_py_legacy.exists():
hook_path = str(hook_py_legacy)
info(f"Using {command_name} hook: {hook_path}")
cmd = [sys.executable, hook_path] + (extra_args or [])
return subprocess.call(cmd, env=env)
if os.name == 'nt' and hook_ps1_legacy.exists():
pwsh = shutil.which("pwsh") or shutil.which("powershell") or "powershell"
ps1_path = str(hook_ps1_legacy)
info(f"Using {command_name} hook: {ps1_path}")
cmd = [pwsh, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", ps1_path] + (extra_args or [])
return subprocess.call(cmd, env=env)
if os.name != 'nt' and hook_sh_legacy.exists():
sh_path = str(hook_sh_legacy)
info(f"Using {command_name} hook: {sh_path}")
bash = shutil.which("bash")
cmd = [bash, sh_path] + (extra_args or []) if bash else ["/bin/sh", sh_path] + (extra_args or [])
return subprocess.call(cmd, env=env)
except FileNotFoundError as e:
warn(f"Hook interpreter not found: {e}")
return 127
except Exception as e:
error(f"Hook execution error: {e}")
return 1
return None
def ssh_login(sc: ServerConfig, alias: str) -> int:
port = determine_ssh_port(sc.port, sc.host)
if not port:
return 1
resolved_ip = resolve_host_ip(sc.host) or ""
keyfile = get_ssh_keyfile(sc)
# Optional local hook override (scripts/login.*)
hook_rc = _run_local_hook("login", sc, alias, port, key_path=keyfile)
if hook_rc is not None:
if hook_rc == 0:
success("Login hook completed successfully")
else:
error(f"Login hook failed with exit code {hook_rc}")
return hook_rc
info(f"Attempting SSH connection on port {port}...")
try:
cli = SSHClient(sc.host, port, sc.user, sc.password, keyfile)
cli.connect(timeout=5)
info("Authentication successful")