-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh_man.py
More file actions
935 lines (796 loc) · 30 KB
/
ssh_man.py
File metadata and controls
935 lines (796 loc) · 30 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
'''
SSH Manager
'''
import os
from sys import exit as sys_exit
import base64
import json
from typing import Tuple
from dataclasses import dataclass, field
from subprocess import run
from time import sleep
from uuid import uuid4
from getpass import getpass
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Protocol.KDF import scrypt
from tabulate import tabulate
from src import kb_input as kb_i
from src.classes.terminal_render import (clear_terminal,
terminal_red, terminal_yellow, terminal_purple)
first_run: bool = True
path: str = os.path.abspath(os.path.dirname(__file__))
data_path: str = os.path.join(path,
"data.aes")
DEFAULT_DATA_DICT: dict = {"clients": []}
DEFAULT_PORT: int = 22
SLEEP_TIMER: float = 1
log_dir: str = os.path.join(path,
"log")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
def err_log(content: str) -> None:
'''
Logs error
:param content: :class:`str`
'''
with open(file = os.path.join(log_dir,
"err.log"),
mode = "a",
encoding = "utf-8-sig") as f:
f.write(f"{content}\n")
class SshManException(Exception):
'''
SSH Manager Exception
'''
def __init__(self,
message: str) -> None:
'''
SSH Manager Exception
:param message: :class:`str`
'''
super().__init__(message)
def get_uuid() -> str:
'''
Returns UUID
'''
return str(uuid4())
# TODO: keygen remove
# TODO: enable fingerprint
# TODO: handling too small terminal size (min. width: 96)
# TODO: Settings (ex. sleep timer)
@dataclass()
class SSHClient:
'''
SSH Client dataclass
'''
host: str
user: str
password: str
port: int = field(default = DEFAULT_PORT)
favorite: bool = False
client_id: str = field(default_factory = get_uuid)
def connect(self) -> None:
'''
Connect to SSH client
'''
try:
print(terminal_purple(text = f"Connecting to {self.user}@{self.host}..."))
if self.password:
run(f"sshpass -p {self.password} ssh -p {self.port} {self.user}@{self.host}", # pylint: disable=subprocess-run-check
shell = True)
else:
run(f"ssh {self.user}@{self.host} -p {self.port}", # pylint: disable=subprocess-run-check
shell = True)
sleep(SLEEP_TIMER)
except Exception as e: # pylint: disable=broad-exception-caught
err_log(content = f"Error: {e}")
sleep(SLEEP_TIMER * 2)
clear_terminal()
def ssh_format(self) -> str:
'''
Returns SSH format `<user>@<host>:<port>`
'''
return f"{self.user}@{self.host}:{self.port}"
filtered_clients: list[SSHClient] = []
filter_key: str | None = None
filtered: bool = False
filter_info: str | None = None
def dict_to_json(data: dict,
file_path: str,
encoding: str = "utf-8-sig") -> None:
'''
Converts dictionary to JSON
:param data: :class:`dict`
:param file_path: :class:`str`
:param encoding: :class:`str` defaults to `"utf-8-sig"`
'''
with open(file = file_path,
mode = "w",
encoding = encoding) as file:
json.dump(data,
file,
indent = 4)
def encrypt_data(file_path: str,
password: str,
encoding: str = "utf-8-sig") -> None:
'''
Encrypts file data
:param file_path: :class:`str`
:param passward: :class:`str`
:param encoding: :class:`str`
'''
salt: bytes = os.urandom(16)
key: bytes | Tuple[bytes] = scrypt(password = password.encode(),
salt = salt,
key_len = 32,
N = 2**14,
r = 8,
p = 1)
cipher: AES = AES.new(key,
AES.MODE_CBC)
with open(file = file_path,
mode = "r",
encoding = encoding) as file:
data: str = file.read()
padded_data: bytes = pad(data.encode(),
AES.block_size)
encrypted_data = cipher.encrypt(padded_data)
encrypted_content = salt + cipher.iv + encrypted_data
encrypted_string = base64.b64encode(encrypted_content).decode(encoding)
with open(file_path,
"w",
encoding = encoding) as file:
file.write(encrypted_string)
def decrypt_data(file_path: str,
password: str,
encoding: str = "utf-8-sig") -> str:
'''
Decrypts file data
:param data_path: :class:`str`
:param password: :class:`str`
:param encoding: :class:`str` defaults to `"utf-8-sig"`
'''
with open(file = file_path,
mode = "rb") as file:
encrypted_string: str = file.read()
encrypted_content: bytes = base64.b64decode(encrypted_string)
salt: bytes = encrypted_content[:16]
iv: bytes = encrypted_content[16:32]
encrypted_data: bytes = encrypted_content[32:]
key: bytes | Tuple[bytes] = scrypt(password = password.encode(),
salt = salt,
key_len = 32,
N = 2**14,
r = 8,
p = 1)
cipher = AES.new(key,
AES.MODE_CBC,
iv = iv)
decrypted_data = unpad(cipher.decrypt(encrypted_data),
AES.block_size)
return decrypted_data.decode(encoding)
def json_str_to_dict(data: str) -> dict:
'''
Converts JSON string to dictionary
:param data: :class:`str`
'''
return json.loads(data)
def save_and_encrypt_data(data: dict,
file_path: str,
password: str) -> None:
'''
Saves and encrypts data
:param data: :class:`str`
:param file_path: :class:`str`
:param password: :class:`strű
'''
dict_to_json(data = data,
file_path = file_path)
encrypt_data(file_path = file_path,
password = password)
def create_env(key) -> None:
'''
Creates environment
'''
if key:
if not os.path.exists(data_path):
save_and_encrypt_data(data = DEFAULT_DATA_DICT,
file_path = data_path,
password = key)
else:
print("Decryption key is required.")
sys_exit(1)
def read_encrypted_json(file_path: str,
password: str) -> dict:
'''
Reads encrypted JSON file
:param file_path: :class:`str`
:param password: :class:`str`
'''
return json_str_to_dict(decrypt_data(file_path,
password))
def client_from_data(client_data: dict) -> SSHClient:
'''
Creates SSHClient object from data
:param client_data: :class:`str`
'''
return SSHClient(client_id = client_data["client_id"],
host = client_data["host"],
user = client_data["user"],
password = client_data.get("password", ""),
port = client_data["port"],
favorite = client_data["favorite"] if "favorite" in client_data else False)
def clients_from_data(client_datas: list[dict]) -> list[SSHClient]:
'''
Creates SSHClient objects from data
:param: client_data: :class:`list[dict]`
'''
return [client_from_data(client_data) for client_data in client_datas]
def get_clients(key: str) -> list[SSHClient]:
'''
Gets clients
:param key: :class:`str`
'''
try:
data: dict = read_encrypted_json(file_path = data_path,
password = key)
except ValueError as ve:
raise SshManException(message = "Maybe invalid decryption key.") from ve
return sorted(clients_from_data(data["clients"]),
key = lambda c: f"{0 if c.favorite else 1}{c.host}{c.user}{c.port}")
def current_clients(key: str) -> list[SSHClient]:
'''
Current clients
:param key: :class:`str`
'''
if filtered:
return filtered_clients
return get_clients(key = key)
def get_client_id(clients: list[SSHClient],
input_id: str) -> int:
'''
Gets client ID
:param clients: :class:`list[SSHCLient]`
:param filter: :class:`Union(str, int)`
'''
if input_id.isdigit():
input_id_int: int = int(input_id)
if 0 < input_id_int <= len(clients):
return clients[input_id_int - 1].client_id
print_and_sleep(content = "Invalid client ID.")
return None
for client in clients:
client_ids: list[int] = []
for client in clients:
if input_id in f"{client.host}{client.user}{client.port}":
client_ids.append(client.client_id)
if len(client_ids) == 1:
return client_ids[0]
print_and_sleep(content = "Multiple clients found, be more specific.")
return None
def get_client_by_client_id(clients: list[SSHClient],
client_id: int) -> SSHClient | None:
'''
Gets client by client ID
:param clients: :class:`list[SSHClients]`
:param client_id: :class:`int`
'''
for client in clients:
if client.client_id == client_id:
return client
return None
def get_filter() -> str:
'''
Prints filter info
'''
if filtered and filter_info:
text: str = "FILTERED"
if filter_info:
text += f" - {filter_info}"
return terminal_red(text if text else "")
return ""
def print_and_sleep(content: str = "",
sleep_timer: int = SLEEP_TIMER) -> None:
'''
Prints content and sleeps
:param content: :class:`str`
:param sleep_timer: :class:`int`
'''
print(content)
sleep(sleep_timer)
def find_client_2(search: str,
key: str) -> str | None:
'''
Return specified uuid for client if only one found
:param search: :class:`str`
:param key: :class:`str`
'''
clients: list[SSHClient] = get_clients(key = key)
f_clients: list[SSHClient] = filtered_clients or clients
found_clients: list[SSHClient] = []
if search.isdigit():
try:
index: int = int(search) - 1
if 0 <= index <= len(f_clients):
return f_clients[index].client_id
except ValueError:
print_and_sleep(content = f"Invalid client ID: '{str(search)}'")
for client in f_clients:
if search.lower() in client.ssh_format().lower():
found_clients.append(client)
if len(found_clients) == 1:
return found_clients[0].client_id
if len(found_clients) > 1:
print("Multiple clients found:")
for i, client in enumerate(found_clients):
print(f"{i + 1}. {client.ssh_format()}")
print("Please use client ID or be more specific.")
sleep(2)
return None
def get_client_by_uuid(client_id: str,
key: str) -> SSHClient | None:
'''
Get client by `client_id`
:param client_id: :class:`str`
:param key: :class:`str`
'''
for client in get_clients(key = key):
if client.client_id == client_id:
return client
return None
def get_clients_dict(key: str) -> list[dict]:
'''
Gets clients dictionary
:param key: :class:`str`
'''
clients_dict: dict = [client.__dict__ for client in get_clients(key = key)]
return sorted(clients_dict,
key = lambda c: f"{0 if c['favorite'] else 1}{c['host']}{c['user']}{c['port']}")
def save_clients_dict(clients_dict: list[dict],
key: str) -> None:
'''
Saves clients dictionary
:param clients_dict: :class:`list[dict]`
:param key: :class:`str`
'''
data: dict = read_encrypted_json(file_path = data_path,
password = key)
data["clients"] = clients_dict
save_and_encrypt_data(data = data,
file_path = data_path,
password = key)
def command_connect(command: str,
key: str) -> None:
'''
Connects to client
:param command: :class`str`
:param key: :class:`str`
'''
input_split: list[str] = command.split(" ")
search: str = input("Client ID: ") if len(input_split) == 1 else input_split[1]
client_id: str | None = find_client_2(search = search,
key = key)
client: SSHClient | None = get_client_by_uuid(client_id = client_id,
key = key)
if client:
client.connect()
def filter_clients(clients: list[SSHClient],
filter_text: str) -> list[SSHClient]:
'''
Filters clients
:param clients: :class:`list[SSHClient]`
:param filter: :class:`str`
'''
filtereds: list[SSHClient] = []
for client in clients:
if filter_text.lower() in f"{client.host}{client.user}{client.port}".lower():
filtereds.append(client)
return filtereds
def global_filter(clients: list[SSHClient] | None = None,
filter_str: str | None = None) -> None:
'''
Global filter
:param clients: :class:`list[SSHClient]`
:param filter_str: :class:`str`
'''
global filtered_clients # pylint: disable=global-statement
global filtered # pylint: disable=global-statement
global filter_key # pylint: disable=global-statement
if clients:
filtered_clients = filter_clients(clients = clients,
filter_text = filter_str)
filtered = True
else:
filtered_clients = []
filtered = False
filter_key = filter_str or None
def global_filter_info(text: str | None = None) -> None:
'''
Global filter info
:param text: :class:`str`
'''
global filter_info # pylint: disable=global-statement
filter_info = text
def command_filter(commands: str,
key: str) -> None:
'''
Filters clients
:param commands: :class:`str`
:param key: :class:`str`
'''
input_split: list[str] = commands.split(" ")
filter_text: str = input("Filter: ") if len(input_split) == 1 else input_split[1]
if filtered_clients and not filter_text:
global_filter()
global_filter_info()
return
global_filter(clients = get_clients(key = key),
filter_str = filter_text)
if filter_text and filtered and not filtered_clients:
global_filter_info(text = f"No clients found for '{filter_text}'.")
if filter_text and filtered and filtered_clients:
global_filter_info(text = f"Clients for '{filter_text}'.")
if not filter_text:
global_filter()
global_filter_info()
def command_unfilter() -> None:
'''
Unfilters clients
'''
global_filter()
global_filter_info()
def command_add(key = str) -> None:
'''
Adds client
:param key: :class:`str`
'''
host: str = input("Enter host: ")
user: str = input("Enter user: ")
password: str = getpass("Enter password: ")
port: int = input(f"Enter port (default {DEFAULT_PORT}): ")
if not host or not user or not password:
if not host or not user:
print_and_sleep(content = "Host and user are required.")
return
new_client: SSHClient = SSHClient(host = host,
user = user,
password = password,
port = port or DEFAULT_PORT)
clients_dict: list[dict] = get_clients_dict(key = key)
clients_dict.append(new_client.__dict__)
save_clients_dict(clients_dict = clients_dict,
key = key)
print_and_sleep(f"Client added under '{new_client.client_id}' ID")
if filtered:
global_filter(clients = get_clients(key = key),
filter_str = filter_key)
def update_client(client: SSHClient) -> SSHClient:
'''
Updates client
:param client: :class:`SSHClient`
'''
client.host = input(f"Enter host ({client.host}): ") or client.host
client.user = input(f"Enter user ({client.user}): ") or client.user
client.password = getpass("Enter password: ") or client.password
client.port = input(f"Enter port ({client.port}): ") or client.port
return client
def update_clients(clients: list[SSHClient],
client_id: str) -> list[SSHClient]:
'''
Updates client
:param clients: :class:`list[SSHClient]`
:param client_id: :class:`str`
'''
for client in clients:
if client.client_id == client_id:
client = update_client(client = client)
break
return clients
def command_edit(commands: str,
key: str) -> None:
'''
Edits client
:param commands: :class:`str`
:param key: :class:`str`
'''
input_split: list[str] = commands.split(" ")
client_id: str = input("Client ID: ") if len(input_split) == 1 else input_split[1]
clients: list[SSHClient] = get_clients(key = key)
client_id_int: int | None = get_client_id(clients = clients,
input_id = client_id)
if client_id_int is not None:
clients = update_clients(clients = clients,
client_id = client_id_int)
save_clients_dict(clients_dict = [client.__dict__ for client in clients],
key = key)
if filtered:
global_filter(clients = clients,
filter_str = filter_key)
def client_remove(clients: list[SSHClient],
client_id: str) -> list[SSHClient]:
'''
Removes client
:param clients: :class:`list[SSHClient]`
:param :class:`str`
'''
for i, client in enumerate(clients):
if client.client_id == client_id:
client_rm: SSHClient = client
clients.pop(i)
print_and_sleep(content = f"Client {client_rm.user}@{client_rm.host} removed.")
break
return clients
# TODO: New remove method
def client_remove_2(search: str,
key: str) -> list[SSHClient]:
'''
Removes client by `client_id`
:param client_id: :class:`str`
:param key: :class:`str`
'''
client_id: str | None = find_client_2(search = search,
key = key)
if client_id:
popped: bool = False
clients: list[SSHClient] = get_clients(key = key)
for i, client in enumerate(clients):
if client.client_id == client_id:
client_to_rm: SSHClient = client
if input(f"Are you sure want to remove '{client_to_rm.ssh_format()}'?\n(y/N) ").lower() in ["y", # pylint: disable=line-too-long
"yes"]: # pylint: disable=line-too-long
clients.pop(i)
popped = True
print_and_sleep(content = f"Client '{client_to_rm.ssh_format()}' removed.")
else:
print_and_sleep(content = f"Removing of '{client_to_rm.ssh_format()}' cancelled.") # pylint: disable=line-too-long
break
if popped:
save_clients_dict(clients_dict = [c.__dict__ for c in clients],
key = key)
if filtered:
global_filter(clients = clients,
filter_str = filter_key)
def command_remove_2(commands: str,
key: str) -> None:
'''
Removes client
:param commans: :class:`str`
:param key: :class:`str`
'''
command_split: list[str] = commands.split(" ")
search: str = input("Client to delete: ") if len(command_split) == 1 else command_split[1]
client_remove_2(search = search,
key = key)
def favourite_client(clients: list[SSHClient],
client_id: str) -> list[SSHClient]:
'''
Favorites client
:param clients: :class:`list[SSHClient]`
:param client_id: :class:`str`
'''
for client in clients:
if client.client_id == client_id:
client.favorite = not client.favorite
print_and_sleep(f"Client {client.user}@{client.host} {'favorited' if client.favorite else 'unfavorited'}.") # pylint: disable=line-too-long
break
return clients
def command_favorite(commands: str,
key: str) -> None:
'''
Favorites client
:param commands: :class:`str`
:param key: :class:`str`
'''
input_split: list[str] = commands.split(" ")
shown_clients: list[SSHClient] = filtered_clients or get_clients(key = key)
clients: list[SSHClient] = get_clients(key = key)
client_id: str = input("Client ID: ") if len(input_split) == 1 else input_split[1]
client_id_int: int | None = get_client_id(clients = shown_clients,
input_id = client_id)
if client_id_int is not None:
clients = favourite_client(clients = clients,
client_id = client_id_int)
save_clients_dict(clients_dict = [client.__dict__ for client in clients],
key = key)
if filtered_clients:
global_filter(clients = clients,
filter_str = filter_key)
def command_password(command: str,
key: str) -> None:
'''
Change password on encrypted file
:param command: :class:`str`
:param key: :class:`str`
'''
input_split: list[str] = command.split(" ")
old_pw: str = getpass("Enter old password: ") if len(input_split) < 3 else input_split[1]
new_pw: str = getpass("Enter new password: ") if len(input_split) < 3 else input_split[2]
conf_new_pw: str = getpass("Confirm new password: ") if len(input_split) < 3 else input_split[2]
if old_pw and new_pw and conf_new_pw:
if key == old_pw:
if new_pw == conf_new_pw:
confirm: str = input("Are you sure you want to change the password? (y/N): ")
if confirm.lower() == "y":
data: dict = read_encrypted_json(file_path = data_path,
password = key)
save_and_encrypt_data(data = data,
file_path = data_path,
password = new_pw)
clear_terminal()
print("Password changed successfully, please restart.")
sys_exit(0)
else:
print_and_sleep(content = "Password change cancelled.")
else:
print_and_sleep(content = "New passwords do not match.")
else:
print_and_sleep(content = "Invalid old password.")
def command_export(command: str,
key: str) -> None:
'''
Exports clients
:param command: :class:`str`
:param key: :class:`str`
'''
input_split: list[str] = command.split(" ")
password: str = getpass("Enter password: ") if len(input_split) == 1 else input_split[1]
file_path: str = input("Enter file path: ") if len(input_split) < 3 else input_split[2]
confirm: str = input("Are you sure you want to export clients? (y/N): ")
if not password or not file_path:
print_and_sleep(content = "Password and file path are required.")
elif confirm.lower() != "y":
print_and_sleep(content = "Export cancelled.")
elif password and file_path and password == key:
data: dict = read_encrypted_json(file_path = data_path,
password = key)
dict_to_json(data = data,
file_path = file_path)
print_and_sleep(content = f"Clients exported successfully to '{file_path}'.")
elif password != key:
print_and_sleep(content = "Invalid password.")
else:
if not password or not file_path:
errors: list[str] = []
if not password:
errors.append("Password is required.")
if not file_path:
errors.append("File path is required.")
print_and_sleep(content = "\n".join(errors))
def command_handle(command: str,
key: str) -> None:
'''
Handles commands
:param command: :class:`str`
:param key: :class:`str`
'''
match command.lower():
# connect
case _ if command.lower().startswith("connect") or command.lower().split(" ")[0] == "c":
command_connect(command = command,
key = key)
# filter
case _ if command.lower().startswith("filter") or command.lower().split(" ")[0] == "f":
command_filter(commands = command,
key = key)
# unfilter
case _ if command in ["unfilter", "u"]:
command_unfilter()
# add
case _ if command in ["add", "a"]:
command_add(key = key)
# edit
case _ if command.lower().startswith("edit") or command.lower().split(" ")[0] == "e":
command_edit(commands = command,
key = key)
# remove
case _ if command.lower().startswith("remove") or command.lower().split(" ")[0] == "rm":
command_remove_2(commands = command,
key = key)
# favorite
case _ if command.lower().startswith("favorite") or command.lower().split(" ")[0] == "fav":
command_favorite(commands = command,
key = key)
# password
case _ if command.lower().startswith("password") or command.lower().split(" ")[0] == "p":
command_password(command = command,
key = key)
# export
case _ if command.lower().startswith("export") or command.lower().split(" ")[0] == "exp":
command_export(command = command,
key = key)
# exit
case "exit":
print("Bye!")
sys_exit(0)
# default
case _:
print_and_sleep(content = "Invalid command.")
def print_first_run() -> None:
'''
Prints first run text
'''
if not os.path.exists(data_path):
text: str = "Welcome to SSH Manager!"
text += "\nPlase provide a decryption key (password)."
text += "\nYou can change the password later!"
print(text)
global first_run # pylint: disable=global-statement
first_run = False
def terminal_width() -> int:
'''
Terminal width
'''
return os.get_terminal_size().columns
def small_render() -> bool:
'''
Small render
'''
return terminal_width() < 96
def print_clients(key: str | None) -> None:
'''
Prints clients
:param key: :class:`str`
'''
clients: list[SSHClient] = []
if filtered:
clients = filtered_clients
else:
clients: list[SSHClient] = clients or get_clients(key = key)
table_data: list[list[str]] = [[i + 1,
c.host + (f" {terminal_yellow("*")}" if c.favorite else ""),
c.user,
c.port] for i, c in enumerate(clients)]
clear_terminal()
print("SSH Manager")
ssh_table: str = tabulate(table_data,
headers = ["#",
"Host",
"User",
"Port"],
tablefmt = "simple_grid")
ssh_table += f"\n{get_filter()}"
command_data: list[list[str]] = [["Connect (c)", "Connects to client"],
["Add (a)", "Adds new client"],
["Edit (e)", "Edits client"],
["Remove (rm)", "Removes client"],
["Filter (f)", "Filters clients"],
["Favorite (fav)", f"Favorites client {terminal_yellow('*')}"],
["Password (p)", "Changes password"],
["Export (exp)", "Exports to decrypted .json"],
["Exit (CTRL+C)", "Exits SSH Manager"]]
commands_table: str = tabulate(command_data,
headers = ["Command",
"Description"])
grid: list[list[str]] = [[ssh_table,
commands_table]]
print(tabulate(grid,
headers = ["SSH Clients",
"Commands"],
tablefmt = "simple_grid"))
def print_home(key: str) -> None:
'''
Prints home
:param key: :class:`str`
'''
print_clients(key = key)
def ssh_man() -> None:
'''
SSH Manager
'''
if first_run:
print_first_run()
decrypt_key: str | None = getpass("Enter decryption key: ")
create_env(decrypt_key)
while True:
try:
print_home(key = decrypt_key)
kb_input: str | None = kb_i.get_input()
if kb_input:
command_handle(command = kb_input,
key = decrypt_key)
except KeyboardInterrupt:
print("\nBye!")
sys_exit(0)
if __name__ == "__main__":
ssh_man()