-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptty.py
More file actions
1602 lines (1237 loc) · 66.8 KB
/
optty.py
File metadata and controls
1602 lines (1237 loc) · 66.8 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/python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2023 "Mr. Lima"
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sub license, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Building Python Dependences
from os import system as local
from socket import gethostname as hostname
from random import randint, choice
from time import sleep as timeout
from sys import exit as close
from sys import stdin, stdout, stderr
#from setuptools import setup, find_packages
import os, sys, json, time, random, platform, subprocess, calendar
import http, http.server, urllib, socket, socketserver, urllib.request
import shutil, getpass, zipfile, datetime, shlex, traceback, code, io
import threading, tarfile, warnings, uuid
import xml.etree.ElementTree as ET
passwd = "" # Default password
library = {
# OpenTTY Release informations
"appname": "OpenTTY",
"version": "1.6.4", "subject": "The Resources Upgrade",
"patch": [
"OpenTTY 98",
],
"developer": "Mr. Lima",
# Development Settings
"debugmode": False, # Enable debug resources
"profile": "Vanilla", # Profile Name
"goto-home": True, # Go to user home at shell start
"do-auth": False, # Ask for password when call a shell session
# Getting informations about machine
"hostname": socket.gethostname(), # Name of current machine
"ipadress": socket.gethostbyname(hostname()), # IP of current machine
"system": platform.system(), # Recognize Operating System name
"root-dir": os.getcwd(), # Installation path
# Terminal settings
"sh": "psh", "sh-prefix": "\033[32m\033[1m$ ", "root-sh-prefix": "\033[31m\033[1m# ",
# Aliases for users (client/ root)
"aliases": {},
"internals": {
"date": "echo &time", "bb": "busybox", "ash": "busybox sh"
},
# Firewall and root settings
"whitelist": [],
# BlockTables
"char-table": [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Ç",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "Y", "z", "ç",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
" ", "'", '"', "!", "@", "#", "$", "%", "¨", "&", "*", "(", ")", "[", "]", "{", "}", "-", "_", "=", "+", "`", "´", "~", "^", "<", ">",
":", ";", "?", "¹", "²", "³", "£", "¢", "¬", "«", "»", "ß", "Æ", "Ð", "©", "®", "Ŧ", "←", "↓", "→", "ĸ", "̉", "Þ", "Ŋ", "“", "”", "µ" ,
".",
],
# Global settings
"head-lines": 10, # Lines of a file that will be show with 'head' and 'tail'
"hash": 32, # Lenght of OpenTTY word warp (hash/ uhash)
"no-kill-services": ['psh'],
"open-disk": "ResidentFlash",
"timeout": 5, # Timeout for Network connections
"hidden-files-prefix": ".", # Prefix for hidden files
"dircolors": {
".py": "\033[32m",
".sh": "\033[32m",
".cmd": "\033[32m",
".bat": "\033[32m",
".exe": "\033[31m",
".com": "\033[31m",
".dll": "\033[31m",
".jar": "\033[31m",
".zip": "\033[36m",
".tar": "\033[36m",
".tar.gz": "\033[36m",
".tar.xz": "\033[36m",
".json": "\033[36m",
".7z": "\033[36m",
".ui": "\033[33m",
".rar": "\033[36m",
".bin": "\033[36m"
},
# Resources Mirrors
"resources": {
"busybox": {"filename": "busybox.exe", "url": "https://github.com/fetuber4095/OpenTTY/raw/main/lib/app.utils.busybox.exe", "py-libs": [], "install-requires": []},
"calendar": {"filename": "calendar.ui", "url": "https://github.com/fetuber4095/OpenTTY/raw/main/xbin/calendar.ui", "py-libs": [], "install-requires": ['qt']},
"cowsay": {"filename": "cowsay.dll", "url": "https://github.com/fetuber4095/OpenTTY/raw/main/usr/games/cowsay.py", "py-libs": [], "install-requires": []},
"enchant": {"filename": "enchant.dll", "url": "https://github.com/fetuber4095/OpenTTY/raw/main/xbin/enchant.py", "py-libs": [], "install-requires": []},
"favicon": {"filename": "favicon.ico", "url": "https://github.com/fetuber4095/OpenTTY/raw/main/root/favicon.ico", "py-libs": [], "install-requires": []},
"figlet": {"filename": "figlet.dll", "url": "https://github.com/fetuber4095/OpenTTY/raw/main/usr/games/figlet.py", "py-libs": ['pyfiglet'], "install-requires": []},
"nano": {"filename": "nano.exe", "url": "https://github.com/fetuber4095/OpenTTY/raw/main/lib/app.utils.nano32.exe", "py-libs": [], "install-requires": []},
"openpad": {"filename": "openpad.py", "url": "https://github.com/fetuber4095/OpenTTY/raw/main/xbin/openpad.py", "py-libs": [], "install-requires": []},
"qt": {"filename": "qt.py", "url": "https://github.com/fetuber4095/OpenTTY/raw/main/lib/qt-sdk/qt.py", "py-libs": ['PyQt5', 'pyqt5-tools'], "install-requires": []},
"qt-tree": {"filename": "qt-tree.py", "url": "https://github.com/fetuber4095/OpenTTY/raw/main/xbin/explorer.py", "py-libs": ['PyQt5'], "install-requires": []},
"ram": {"filename": "ram.py", "url": "https://github.com/fetuber4095/OpenTTY/raw/main/xbin/ram.py", "py-libs": [], "install-requires": []},
"rundll": {"filename": "rundll.py", "url": "https://github.com/fetuber4095/OpenTTY/raw/main/xbin/rundll.py", "py-libs": ['opentty'], "install-requires": []},
#"": {"filename": "", "url": "", "py-libs": [], "install-requires": []}
#"": {"filename": "", "url": "", "py-libs": [], "install-requires": []}
},
"scripts": {
"pypi": {"url": "https://github.com/fetuber4095/OpenTTY/raw/main/root/build.sh"},
"news": {"url": "https://github.com/fetuber4095/ResidentFlash/raw/main/packages/news"},
"psh.test": {"url": "https://github.com/fetuber4095/OpenTTY/raw/main/root/test.sh"},
"rss": {"url": "https://github.com/fetuber4095/OpenTTY/raw/main/usr/libexec/rss.dll"},
"notify-send": {"url": "https://github.com/fetuber4095/OpenTTY/raw/main/usr/libexec/notify-send.dll"},
#"": {"url": ""},
#"": {"url": ""},
},
"setup": {
},
"docs": {
"license": "https://github.com/fetuber4095/OpenTTY/raw/main/LICENSE",
"inbox": "https://github.com/fetuber4095/OpenTTY/raw/main/var/mail/inbox"
},
"github.com": "https://github.com/fetuber4095/OpenTTY",
"opentty.py": "https://github.com/fetuber4095/OpenTTY/raw/main/optty.py",
"venv": "https://github.com/fetuber4095/OpenTTY/raw/main/lib/optty.profiles.template.py"
}
class OpenTTY:
def __init__(self):
# Application data
self.appname = library['appname'] # Saving application name
self.version = library['version'] # Saving application version
self.subject = library['subject'] # Saving release name
self.ttyname = None
self.root, self.puppydir = library['root-dir'], library['root-dir']
self.process = {} # Current running tasks of OpenTTY
self.functions = {} # OpenTTY Functions
# Setup of OpenTTY Runtime
self.globals = {
"app": self, "library": library, "__name__": "__main__", "stdin": stdin, "stdout": stdout, "stderr": stderr,
"nm": socket.socket(socket.AF_INET, socket.SOCK_STREAM), "OpenTTY": OpenTTY, "local": local, "config": self.loadconfig(f"{self.root}/CONFIG.SYS"), "cmd": "",
"os": os, "sys": sys, "json": json, "time": time, "random": random, "platform": platform, "subprocess": subprocess, "calendar": calendar,
"http": http, "urllib": urllib, "socket": socket, "socketserver": socketserver, "shutil": shutil, "getpass": getpass, "zipfile": zipfile,
"datetime": datetime, "shlex": shlex, "traceback": traceback, "code": code, "io": io, "threading": threading, "tarfile": tarfile,
"warnings": warnings
}
self.locals = {}
return
def __enter__(self): return self
def __exit__(self, exc_type, c_value, traceback): return
# OpenTTY Client
def connect(self, host="/dev/localhost", port=8080, admin=False): # Connect into
if library['do-auth'] or admin: self.runas("true"), self.stop("true") # Make user Authentication
if library['goto-home']: os.chdir(self.root if admin else os.path.expanduser("~")) # Warp to user home or to profile directory
if library['sh'] not in self.process:
self.ttyname = host # Set TTY Name
self.process[library['sh']] = (str(port))
print(f"\n\n\033[m{self.appname} v{self.version} ({platform.system()} {platform.release()}) built-in shell ({library['sh']})\nEnter 'help' for more informations.\n")
while library['sh'] in self.process:
try:
self.globals['config'] = self.loadconfig(f"{self.root}/CONFIG.SYS") # Reload for RunDLL environment
for asset in os.listdir(self.root):
if asset.endswith(".sh"): self.insmod(f"{self.root}/{asset}", root=True)
except FileNotFoundError: self.write32u(show=False)
try:
command = input(f"\033[32m\033[1m{getpass.getuser()}@{hostname()}\033[m\033[1m:\033[34m{os.getcwd().replace(os.path.expanduser('~'), '~')}\033[m{library['sh-prefix'] if not admin else library['root-sh-prefix']}\033[m").strip()
for cmd in command.split('|'):
if cmd:
if cmd.split()[0] == "logout": return # Quit from PSH Terminal (End of Code/ End of PSH Environment)
else: self.server(cmd, report=f"{library['sh']}: " if admin else "", root=admin) # Send a command for PSH Execution
except (KeyboardInterrupt): self.clear()
except (IndexError, TypeError): traceback.print_exc()
except (RecursionError, EOFError): break
except UnboundLocalError: continue
def disconnect(self, code=""): # Disconnect from python client
if not code: code = 0
try:
print(f"\n------------------")
print(f"(program exited with code: {code})")
print(f"Press return to continue"), input(), close()
except (KeyboardInterrupt, EOFError): print(), close()
def execfile(self, filename, cmd="", ispkg=False, root=False): # Execute a dll python script
if self.basename(filename).split()[0] not in library['whitelist'] and not ispkg and not root: raise PermissionError("Script not in Whitelist. Are you root?")
if filename.startswith("/"): filename = f"{self.root}{filename}"
if os.name == "nt": filename = filename.replace("/", "\\")
self.globals['cmd'] = cmd
with open(filename, "r") as script:
try: exec(self.recognize(script.read()), self.globals, self.locals)
except Exception as error: traceback.print_exc()
def execonline(self, url, cmd="", root=False): # Execute scripts from internet "without download file"
try: code = urllib.request.urlopen(url).read().decode()
except Exception as error: return traceback.print_exc()
self.globals['cmd'] = cmd
if code.splitlines()[0] == "#!/opentty.py rundll":
try: exec(self.recognize(code), self.globals, self.locals)
except ModuleNotFoundError as module: print(f"rundll: {module}...")
except Exception as error: traceback.print_exc()
elif code.splitlines()[0] == "#!/opentty.py sh":
for cmd in code.splitlines():
if cmd:
if cmd.startswith("#"): run = (True, True)
else: run = self.server(cmd, report=f"{self.basename(url)}: ", root=root)
if not run or not True in run: return
else:
try: exec(self.recognize(code), self.globals, self.locals)
except ModuleNotFoundError as module: traceback.print_exc()
except Exception as error: traceback.print_exc()
def execblock(self, startline=""): # Execute a block (ex: if, try, with, def, for, while)
if len(startline.split()) >= 2 and startline.endswith(":"):
block = []
block.append(startline)
while True:
try:
line = input(f"\033[31m\033[1m[{library['profile']}]\033[m ... ")
if not line: break
block.append(line)
except (KeyboardInterrupt, EOFError): break
try: exec('\n'.join(block), self.globals, self.locals)
except Exception as error: traceback.print_exc()
return block
try: exec(startline, self.globals, self.locals)
except Exception as error: traceback.print_exc()
def server(self, cmd, report="", builtin=False, root=False): # Execute PSH commands
cmd = str(self.recognize(cmd)) # Recognize environment values and color codes
self.start(cmd.split()[0]) # Start service
try:
if cmd.split()[0] in library['aliases'] and not builtin: self.server(f"{library['aliases'][cmd.split()[0]]} {self.replace(cmd)}", report=report, root=root) # Execute aliases
elif cmd.split()[0] == ".": # Call OpenTTY Rundll
if self.replace(cmd): self.execfile(shlex.split(self.replace(cmd))[0], self.replace(self.replace(cmd)), root=root)
elif cmd.split()[0] == ";": # Online Service Deamon for OpenTTY Rundll
if self.replace(cmd): self.execonline(shlex.split(self.replace(cmd))[0], self.replace(self.replace(cmd)))
elif cmd.split()[0] == ":": # Excute a Python Syntax
try: exec(self.replace(cmd), self.globals, self.locals)
except Exception as error: traceback.print_exc()
# Permission Plugin
elif cmd.split()[0] == "chmod": self.chmod(self.replace(cmd), report=report)
elif cmd.split()[0] == "whoami" or cmd.split()[0] == "logname": print("root" if root else getpass.getuser())
elif cmd.split()[0] == "passwd": print(f"{report}passwd: your password is {passwd if root else '*' * passwd}" if passwd else f"{report}passwd: you dont have a password.")
elif cmd.split()[0] == "sudo": self.runas(self.replace(cmd), root=root)
elif cmd.split()[0] == "su": self.login(root=root)
elif cmd.split()[0] == "chroot": self.chroot(self.replace(cmd), root=root)
# Netman
elif cmd.split()[0] == "gaddr": self.gaddr(self.replace(cmd))
elif cmd.split()[0] == "hostname": self.hostname(self.replace(cmd))
elif cmd.split()[0] == "fw": self.fwadress(self.replace(cmd), report=report)
elif cmd.split()[0] == "wget": self.wget(self.replace(cmd), report=report)
elif cmd.split()[0] == "curl": self.curl(self.replace(cmd), show=True)
elif cmd.split()[0] == "server": self.localhost(self.replace(cmd), report=report, root=root)
elif cmd.split()[0] == "genip": print(self.gen_adress())
elif cmd.split()[0] == "connect": self.dialup(self.replace(cmd))
elif cmd.split()[0] == "ping": self.ping(self.replace(cmd), report=report)
elif cmd.split()[0] == "ifconfig": self.ifconfig(self.replace(cmd) if self.replace(cmd) else hostname())
elif cmd.split()[0] == "netstat": print(self.netstat())
elif cmd.split()[0] == "np": self.np(self.replace(cmd))
# The boy of files
#
# "File Utilities"
elif cmd.split()[0] == "mkdir": self.makedir(self.replace(cmd))
elif cmd.split()[0] == "rmdir": self.removedir(self.replace(cmd))
elif cmd.split()[0] == "tree": self.tree(self.replace(cmd))
elif cmd.split()[0] == "rm": self.remove(self.replace(cmd))
elif cmd.split()[0] == "touch": self.touch(self.replace(cmd))
elif cmd.split()[0] == "ls": self.listdir(self.replace(cmd))
elif cmd.split()[0] == "dd": self.txt2bin(self.replace(cmd))
elif cmd.split()[0] == "search": self.search(self.replace(cmd), report=report)
elif cmd.split()[0] == "basename": print(self.basename(self.replace(cmd)) if self.replace(cmd) else f"{report}basename: missing operand [path]...")
elif cmd.split()[0] == "mv" or cmd.split()[0] == "rename": self.move(self.replace(cmd))
elif cmd.split()[0] == "cp": self.copy(self.replace(cmd))
elif cmd.split()[0] == "diff": self.diff(self.replace(cmd))
elif cmd.split()[0] == "read": self.read(self.replace(cmd))
elif cmd.split()[0] == "wc": self.wc(self.replace(cmd))
#
# "Text Utilities"
elif cmd.split()[0] == "cat": self.catfile(self.replace(cmd))
elif cmd.split()[0] == "tac": self.tacfile(self.replace(cmd))
elif cmd.split()[0] == "head": self.headfile(self.replace(cmd))
elif cmd.split()[0] == "tail": self.tail(self.replace(cmd))
elif cmd.split()[0] == "nl": self.nl(self.replace(cmd))
elif cmd.split()[0] == "find": self.find(self.replace(cmd), report=report)
elif cmd.split()[0] == "catbin": print(self.catbin(self.replace(cmd)))
elif cmd.split()[0] == "write": self.write(self.replace(cmd))
elif cmd.split()[0] == "sort": self.sort(self.replace(cmd))
# The PIPES Plugin
elif cmd.split()[0] == "json": self.json(self.replace(cmd))
elif cmd.split()[0] == "xml": self.xml(self.replace(cmd), viewjson=True)
elif cmd.split()[0] == "insmod": self.insmod(self.replace(cmd), root=root)
elif cmd.split()[0] == "public": self.public(self.replace(cmd), report=report)
elif cmd.split()[0] == "static": self.modstatic(self.replace(cmd), report=report)
elif cmd.split()[0] == "flush": self.flush(self.replace(cmd))
elif cmd.split()[0] == "rmmod": self.rmmod(self.replace(cmd))
elif cmd.split()[0] == "lsmod": self.json(jsondict=self.functions)
elif cmd.split()[0] == "function": self.function(self.replace(cmd))
elif cmd.startswith("@"): self.callmethod(cmd.replace("@", ""), root=root)
elif cmd.split()[0] == "set": self.server(f": {self.replace(cmd)}", builtin=True)
elif cmd.startswith("for") or cmd.startswith("while") or cmd.startswith("with") or cmd.startswith("def") or cmd.startswith("class") or cmd.startswith("try") or cmd.startswith("if") or cmd.startswith("case"): self.execblock(f"{cmd.replace('case', 'if')}")
elif cmd.startswith("from") or cmd.startswith("import") or cmd.startswith("print") or cmd.startswith("input") or cmd.startswith("nm") or cmd.startswith("app"): self.server(f": {cmd}")
elif cmd.startswith("lambda") or cmd.startswith("raise") or cmd.startswith("assert") or cmd.startswith("del") or cmd.startswith("global"): self.server(f": {cmd}")
elif cmd.startswith("stdin") or cmd.startswith("stdout") or cmd.startswith("stderr"): self.server(f": {cmd}") if cmd.replace("stdin", "").replace("stdout", "").replace("stderr", "") else self.server(f": print({cmd})")
elif cmd.startswith("(") or cmd.startswith('"') or cmd.startswith('f"') or cmd.startswith("["):
try:
run = eval(cmd, self.globals, self.locals)
if run: print(run)
except Exception as error: traceback.print_exc()
elif cmd.split()[0] == "lsattr": self.server(f": print(dir({self.replace(cmd)}))", builtin=True) if self.replace(cmd) else print(f"{report}lsattr: missing operand [object]...")
elif cmd.split()[0] == "reset.nm": self.globals['nm'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
elif cmd.split()[0] == "reset.cf": self.uninstall("CONFIG.SYS", report="reset: ", root=True)
elif cmd.split()[0] == "reset.locals": self.locals = {}
elif cmd.split()[0] == "remm": self.json(jsondict=self.globals['config'])
# "Hash Security"
elif cmd.split()[0] == "hash": print(self.hash(self.replace(cmd)))
elif cmd.split()[0] == "uhash": print(self.uhash(self.replace(cmd)))
# The Archive Plugin
elif cmd.split()[0] in ["mount", "unmount", "eject", "warp"]: OpenDiskManager(cmd)
elif cmd.split()[0] == "zipinfo": self.zipinfo(self.replace(cmd), report=report)
elif cmd.split()[0] == "unzip": self.unzip(self.replace(cmd))
elif cmd.split()[0] == "gzip": self.gunzip(self.replace(cmd))
# The PSH
elif cmd.split()[0] == "pname": self.pname(self.replace(cmd), report=report)
elif cmd.split()[0] == "uname": self.uname(self.replace(cmd), report=report)
elif cmd.split()[0] == "export": self.export(self.replace(cmd))
elif cmd.split()[0] == "env": self.environ(self.replace(cmd), report=report)
elif cmd.split()[0] == "local": self.explore_list(self.locals, prefix="local ")
elif cmd.split()[0] == "exec": local(self.replace(cmd))
elif cmd.split()[0] == "popon": print(os.popen(self.replace(cmd)).read() if self.replace(cmd) else f"{report}popon: missing operand [command]...\n", end="")
elif cmd.split()[0] == "rem": self.write32u(self.replace(cmd))
elif cmd.split()[0] == "sh" or cmd.split()[0] == library['sh']: self.stop(cmd.split()[0]), self.connect(self.ttyname, 8080, admin=root)
elif cmd.split()[0] == "df": self.diskfree(self.replace(cmd))
elif cmd.split()[0] == "builtin": self.server(self.replace(cmd), report="builtin: ", builtin=True, root=root) if self.replace(cmd) else print(f"{report}builtin: missing operand [command]...")
elif cmd.split()[0] == "eval": print(self.server(self.replace(cmd), report="eval: ", root=root) if self.replace(cmd) else f"{report}eval: missing operand [command]...")
elif cmd.split()[0] == "clear": self.clear()
elif cmd.split()[0] == "echo": print(self.replace(cmd))
elif cmd.split()[0] == "prompt": input(self.replace(cmd))
elif cmd.split()[0] == "stty": self.stty(self.replace(cmd))
elif cmd.split()[0] == "tty": print(self.ttyname if self.ttyname else f"{report}tty: not a tty openned.")
elif cmd.split()[0] == "exit": self.disconnect(self.replace(cmd))
elif cmd.split()[0] == "venv": self.venv(self.replace(cmd), report=report, root=root)
elif cmd.split()[0] == "sleep": self.sleep(self.replace(cmd), report=report)
elif cmd.split()[0] == "setup": self.setup(self.replace(cmd), report=report, root=root)
elif cmd.split()[0] == "gen": self.gen(self.replace(cmd), report=report)
elif cmd.split()[0] == "warn": warnings.warn(self.replace(cmd), UserWarning) if self.replace(cmd) else print(f"{report}warn: missing operand [notify]...")
elif cmd.split()[0] == "cd": self.pushdir(self.replace(cmd))
elif cmd.split()[0] == "popd": self.pushdir(self.puppydir)
elif cmd.split()[0] == "realpath": print(os.getcwd())
elif cmd.split()[0] == "pwd": print(os.getcwd().replace(os.path.expanduser("~"), "~"))
elif cmd.split()[0] == "arch": print(platform.architecture()[0])
elif cmd.split()[0] == "getopt": print(f" {'-' * len(self.replace(cmd).split()[0])} {self.replace(self.replace(cmd))}" if self.replace(cmd) else f"{report}getopt: missing operand [element]...")
#
# "OpenTTY Version Utilities"
elif cmd.split()[0] == "patch": print('\n'.join(f"- {note}" for note in library['patch']))
elif cmd.split()[0] == "version": print(f"{self.appname} v{self.version}")
elif cmd.split()[0] == "sync": local("pip install opentty --upgrade")
#
# "Asset Manager"
elif cmd.split()[0] == "asset": self.asset(report=report)
elif cmd.split()[0] == "mirror": print('\n'.join(f"- {item} \033[1m[{library['resources'][item]['filename']}]\033[m" for item in library['resources']))
elif cmd.split()[0] == "get": self.get_asset(self.replace(cmd), report=report, root=root)
elif cmd.split()[0] == "install": self.install(self.replace(cmd), report=report, root=root)
elif cmd.split()[0] == "uninstall": self.uninstall(self.replace(cmd), report=report, root=root)
elif cmd.split()[0] == "add-repo": self.index_repo(self.replace(cmd), root=root)
elif cmd.split()[0] == "pull": self.pull(self.replace(cmd))
#
# "Alias Manager"
elif cmd.split()[0] == "alias": self.alias(self.replace(cmd))
elif cmd.split()[0] == "unalias": self.unalias(self.replace(cmd), report=report)
#
# "OpenTTY Process Manager"
elif cmd.split()[0] == "ps": self.pslist()
elif cmd.split()[0] == "kill": self.kill(self.replace(cmd), report=report)
elif cmd.split()[0] == "bg": self.bg(self.server, args=(self.replace(cmd), report, builtin, root)) if self.replace(cmd) else print(f"{report}bg: missing operand [command]...")
# The Remote Plugin
elif cmd.split()[0] == "bind": self.bind(int(self.replace(cmd)) if self.replace(cmd) else random.randint(1000, 4095))
# Miscellaneous
elif cmd.split()[0] == "cal": self.calendar()
elif cmd.split()[0] == "inbox": self.curl(library['docs']['inbox'], show=True)
elif cmd.split()[0] == "root": self.pushdir(self.root)
elif cmd.split()[0] == "home": self.pushdir(self.root) if root else self.pushdir(os.path.expanduser("~"))
elif cmd.split()[0] == "genn": self.gen_numner(self.replace(cmd))
elif cmd.split()[0] == "timeout": timeout(library['timeout'])
elif cmd.split()[0] == "seq": self.sequence(self.replace(cmd), report=report)
elif cmd.split()[0] == "help": self.help()
#elif cmd.split()[0] == "":
elif cmd.split()[0] == "no": self.clear(), print(self.replace(cmd) if self.replace(cmd) else "")
elif cmd.split()[0] == "yes":
while True: print(self.replace(cmd))
# Return codes
elif cmd.split()[0] == "true": pass
elif cmd.split()[0] == "false": return self.stop(cmd.split()[0])
else:
if cmd.split()[0] in library['internals']: self.server(f"{library['internals'][cmd.split()[0]]} {self.replace(cmd)}", root=root)
elif cmd.split()[0] in library['scripts']: self.server(f"; {library['scripts'][cmd.split()[0]]['url']} {self.replace(cmd)}", root=root)
elif cmd.split()[0] in ['python', 'python3', 'pip', 'pip3', 'git', 'busybox']: local(cmd)
elif f"{cmd.split()[0]}.py" in os.listdir(self.root) and not builtin: local(f"python {self.root}\\{cmd.split()[0]}.py {self.replace(cmd)}") if os.name == "nt" else local(f"python {self.root}/{cmd.split()[0]}.py {self.replace(cmd)}")
elif f"{cmd.split()[0]}.ui" in os.listdir(self.root) and not builtin: self.server(f"qt {self.root}/{cmd.split()[0]}.ui {self.replace(cmd)}", report=report, builtin=False, root=root)
elif f"{cmd.split()[0]}.exe" in os.listdir(self.root) and not builtin: local(f"{self.root}\\{cmd}" if os.name == "nt" else f"echo {report}{cmd.split()[0]}: asset installed. [POSIX Without Support]")
elif f"{cmd.split()[0]}.dll" in os.listdir(self.root) and not builtin: self.execfile(f"/{cmd.split()[0]}.dll", self.replace(cmd), ispkg=True)
elif f"{cmd.split()[0]}.zip" in os.listdir(self.root) and not builtin: OpenDiskManager(f"mount {self.root}/{cmd.split()[0]}.zip"), True, self.stop(cmd)
elif cmd.split()[0] in library['resources'] and not builtin:
if library['resources'][cmd.split()[0]]['filename'] in os.listdir(self.root): print(f"{report}{cmd.split()[0]}: asset is actived.")
else: return print(f"{report}{cmd.split()[0]}: asset not installed."), self.stop(cmd.split()[0])
elif cmd.split()[0] in os.listdir(self.root): print(f"{report}{cmd.split()[0]}: asset is actived.")
elif os.path.isfile(cmd): print(open(cmd))
else: return print(f"{report}{cmd.split()[0]}: command not found"), self.stop(cmd.split()[0])
except (KeyboardInterrupt, EOFError): return self.stop(cmd.split()[0])
except FileNotFoundError: return print(f"{report}{cmd.split()[0]}: {self.basename(self.replace(cmd)).split()[0]}: no such file.")
except FileExistsError: return print(f"{report}{cmd.split()[0]}: {self.basename(self.replace(cmd)).split()[0]}: oops. this file already exists.")
except IsADirectoryError: return print(f"{report}{cmd.split()[0]}: {self.basename(self.replace(cmd)).split()[0]}: is a directory")
except NotADirectoryError: return print(f"{report}{cmd.split()[0]}: {self.basename(self.replace(cmd).split()[0])}: not a directory")
except UnicodeDecodeError: return print(f"{report}{cmd.split()[0]}: {self.basename(self.replace(cmd).split()[0])}: is a binary-like file.")
except PermissionError: return print(f"{report}{cmd.split()[0]}: permission denied.\n"), traceback.print_exc()
except IndexError as missing: print(f"{report}{cmd.split()[0]}: missing operand [{missing}]..."), self.stop(cmd.split()[0])
except (ValueError, NameError, OSError, RuntimeError, UnboundLocalError, KeyError, OverflowError): return traceback.print_exc()
return True, self.stop(cmd.split()[0]) # Default service end
def start(self, app): self.process[app] = randint(1024, 9999) # Start process
def stop(self, app): # Stop process
try:
if app in library['no-kill-services']: return
del self.process[app]
except KeyError: return
def pslist(self): # List running process at PSH
print(" PID CMD")
print('\n'.join([f" {self.process[process]} {process}" for process in self.process]))
def kill(self, pid, report=""): # Kill a process by virtual PID
for process in self.process:
if self.process[process] == str(pid):
del self.process[process]
return True
print(f"{report}kill: ({pid}) - No such process" if pid else f"{report}kill: missing operand [pid]...")
def bg(self, method, args=()): # Run tasks in background
thread = threading.Thread(target=method, args=args)
thread.start()
return thread
# OpenTTY "Text API"
def basename(self, path): return os.path.basename(path) # Get base name
def replace(self, text): return ' '.join(text.split()[1:]) # Remove first keyword of a text
def recognize(self, text): # Do text codes recognize (Colorama/ Envirronment/ RunDLL Keys)
self.values = {
"&appname": self.appname, "&version": self.version, "&hostname": library['hostname'],
"&ipadress": library['ipadress'], "&subject": library['subject'], "&developer": library['developer'],
"&system": library['system'], "&root": self.root, "&path": os.getcwd(), "&profile": library['profile'],
"&time": time.ctime(), "&username": getpass.getuser(), "&sh": library['sh'], "&random": random.randint(1000, 9999),
# Colorama Utilities
"&black": "\033[30m", "&red": "\033[31m", "&green": "\033[32m", "&yellow": "\033[33m",
"&blue": "\033[34m", "&purple": "\033[35m", "&cian": "\033[36m", "&white": "\033[37m",
"&bold": "\033[1m", "&italic": "\033[3m", "&underline": "\033[4m", "&non-style": "\033[m"
}
for key in self.values: text = text.replace(key, str(self.values[key]))
for key in os.environ: text = text.replace(f"${key}", str(os.environ[key]))
for key in self.locals: text = text.replace(f"${key}", str(self.locals[key]))
return text
def explore_list(self, text, prefix=""): print('\n'.join([f"{prefix}{key}='{text[key]}'" for key in text]))
# OpenTTY "Programs"
#
# Permission Plugin
def chmod(self, filename, report=""): # Add and remove files from whitelist
if filename:
if filename in library['whitelist']: library['whitelist'].remove(self.basename(filename))
else: library['whitelist'].append(self.basename(filename))
else: print('\n'.join([str(i) for i in library['whitelist']]) if library['whitelist'] else f"{report}chmod: whitelist is empty")
def runas(self, cmd, root=False): # Run command as [...]
if cmd:
if root or not passwd: return self.server(cmd, report=f"sudo: ", root=True)
password = getpass.getpass(f"password for '{getpass.getuser()}': ").strip()
if password == passwd: print(), self.server(cmd, report=f"sudo: ", root=True)
else: raise PermissionError("wrong password.")
def login(self, root=False): # Modify current login (to: root)
if not root:
try: self.stop("su"), self.connect(self.ttyname, self.process[library['sh']], admin=True)
except KeyError: print(f"login: no such {library['sh']} session.")
def chroot(self, path, root=False): # Charge root directory
if path:
if not root: raise PermissionError("Unable to charge profile dir. Are you root?")
if os.path.isdir(path):
library['root-dir'] = path
self.root = path
return path
raise FileNotFoundError("no such directory.")
raise IndexError("path")
#
# Netman
def gaddr(self, hostname): # Get IP Address of a machine with it name
if hostname:
try: print(socket.gethostbyname(hostname))
except Exception as error: traceback.print_exc()
else: print(library['ipadress'])
def hostname(self, adress=""): # Get host name by IP Address of a host
if adress:
try:
hostname, _, _ = socket.gethostbyaddr(adress)
print(hostname)
except Exception as error: traceback.print_exc()
else: print(library['hostname'])
def fwadress(self, ipadress, report=""): # Get Informations about IP Address (like host name, time zone, country and others)
def get_ip_info(ip):
try:
with urllib.request.urlopen(f"http://ipinfo.io/{ip}/json") as response: return json.load(response)
except Exception as e: return traceback.print_exc()
if ipadress != "":
try:
socket.inet_aton(ipadress)
ip_info = get_ip_info(ipadress)
if ip_info:
del ip_info["readme"]
for key, value in ip_info.items(): print(f"{key}: {value}")
except socket.error: print(f"{report}fw: {ipadress}: ip adress is invalid.")
else: raise IndexError("ip.adress")
def wget(self, cmd, report=""): # Download files from Internet
if len(cmd.split()) < 2:
if cmd: return self.wget(f"{cmd} {self.basename(cmd)}")
else: raise IndexError("url")
try: urllib.request.urlretrieve(cmd.split()[0], self.replace(cmd)), print(f"{report}wget: {self.basename(self.replace(cmd))}: download complete.")
except Exception as error: traceback.print_exc()
def curl(self, url, show=False): # See a website html
if url:
try: html = urllib.request.urlopen(url).read().decode()
except Exception as error: return traceback.print_exc()
if show: print(self.recognize(html))
return html
else: raise IndexError("url")
def localhost(self, port, report="", root=False): # Open a localhost server in current working directory
if port:
if not root: raise PermissionError("Unable to start server. Are you root?")
try:
with socketserver.TCPServer(("", int(port)), http.server.SimpleHTTPRequestHandler) as httpd:
print(f"Server openned at http://localhost:{port}...\n")
httpd.serve_forever()
except (KeyboardInterrupt, EOFError): return print("\nServer stopped.")
except ValueError: return print(f"{report}server: invalid port '{port}'")
else: self.localhost(randint(2048, 4096), root=root)
def gen_adress(self): return f"1{randint(4, 9)}{randint(2, 5)}.{randint(1, 2)}{randint(2, 9)}{randint(1, 9)}.{choice(['1', '15', '132', '181'])}.{randint(1, 64)}"
def dialup(self, target, timeout=library['timeout']): # Connect into a server
if target:
if len(target.split()) < 2: raise IndexError("port")
try:
host = target.split()[0]
port = int(target.split()[1])
dialobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dialobj.settimeout(timeout)
dialobj.connect((host, port))
while True:
try:
cmd = input(f"\033[32m\033[1m{getpass.getuser()}@{host}\033[m\033[1m:\033[34m{os.getcwd().replace(os.path.expanduser('~'), '~')}\033[m{library['sh-prefix']}\033[m").strip()
if cmd:
if cmd == "/exit": raise KeyboardInterrupt
elif cmd.startswith("/"): self.server(cmd.replace('/', ''))
else: dialobj.send(f"{cmd}\n".encode())
try:
spack = dialobj.recv(9600).decode()
if not spack: raise ConnectionResetError("[Errno 58] Connection reseted by peer.")
print(spack)
except (KeyboardInterrupt, EOFError): print()
except (KeyboardInterrupt, EOFError): return dialobj.close()
except Exception as error: traceback.print_exc()
else: raise IndexError("ip.adress")
def ping(self, host, timeout=library['timeout'], report=""): # Test connection for a host
if host:
try:
dialobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dialobj.settimeout(timeout)
start_time = time.time()
dialobj.connect((host, 80))
end_time = time.time()
ping_time_ms = (end_time - start_time) * 1000
if ping_time_ms < 1000: print(f"{report}{host}: ping is {ping_time_ms:.0f} ms")
else: print(f"{report}{host}: ping is 999+ ms")
except (socket.timeout, ConnectionRefusedError): print(f"{report}{host}: bad. connection failed.")
except socket.gaierror: traceback.print_exc()
finally: dialobj.close()
def ifconfig(self, target): # Get informations about socket objects of a host
if target:
print("Informations for Network Adapters: \n")
for conn in socket.getaddrinfo(target, 80, family=0, type=0, proto=0, flags=0):
_, proto, _, _, info = conn
print(info[0])
print(proto)
print('-' * 22, end="\n\n")
else: self.ifconfig(hostname())
def netstat(self, test_url="https://www.google.com", truecode="Online", falsecode="Offline"): # Verify network status
try: urllib.request.urlopen(test_url)
except Exception as error: return falsecode
return truecode
def np(self, port): # Netcat Python remake
if port:
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.settimeout(4095)
server.bind(('0.0.0.0', int(port)))
server.listen()
def get_msg(size=4096):
while True:
if not connect: return
try: print(client_socket.recv(size).decode())
except OSError: break
while True:
try:
connect = True
client_socket, client_address = server.accept()
thread = self.bg(get_msg)
while True:
try:
text = input()
client_socket.send(text.encode())
except (KeyboardInterrupt, EOFError):
client_socket.close()
connect = False
break
except KeyboardInterrupt: return server.close(), thread.join()
except UnboundLocalError: return
else: raise IndexError("port")
#
# The boy of files
#
# "File Utilities"
def makedir(self, dirname): # Create directories
if dirname: os.makedirs(dirname), self.touch(f"{dirname}/.nomedia")
else: raise IndexError("dirname")
def removedir(self, dirname): # Remove directories
if dirname: shutil.rmtree(dirname)
else: raise IndexError("dirname")
def remove(self, filename): # Remove files
if filename: os.remove(filename)
else: raise IndexError("filename")
def touch(self, filename): # Touch a file resetting it modify date and the content
if filename: open(filename, "wt+").close()
else: raise IndexError("filename")
def tree(self, directory, indent=""): # Show directory tree [Folder, sub-folders and files]
if directory:
print(indent + f"\033[34m\033[1m{os.path.basename(directory)}\033[m" if os.path.isdir(directory) else indent + os.path.basename(directory))
if os.path.isdir(directory):
indent += "│ "
files = os.listdir(directory)
for file in sorted(files):
path = os.path.join(directory, file)
self.tree(path, indent)
else: self.tree(".")
def listdir(self, path=""): # List files at directory
if path:
files = os.listdir(path)
for file in files:
if file.startswith(library['hidden-files-prefix']): continue
elif os.path.isfile(f"{path}/{file}"):
for extensions in library['dircolors']:
if file.endswith(extensions):
print(f"\033[1m{library['dircolors'][extensions]}{file}\033[m")
break
else: print(file)
elif os.path.isdir(f"{path}/{file}"): print(f"\033[34m\033[1m{file}/\033[m")
else: print(file)
else: self.listdir(os.getcwd())
def txt2bin(self, filenames=""): # Convert text files to binary type
def hashbytes(text): return bytes([random.randint(0, 255) for _ in range(len(text))])
def writeBytes(source, output):
with open(source, "r") as source: text = source.read()
with open(output, "wb") as output: output.write(hashbytes(text))
return len(hashbytes(text)), len(text.splitlines())
if len(shlex.split(filenames)) < 2:
if filenames: raise IndexError("output")
text = []
while True:
try: text.append(input())
except (KeyboardInterrupt, EOFError): return print(f"\n0+{len(hashbytes(text))} record in\n0+{len(hashbytes(text))} record out")
lenbytes, lenfile = writeBytes(shlex.split(filenames)[0], shlex.split(filenames)[1])
print(f"0+{lenbytes} record in\n0+{lenfile} lines writed in")
def search(self, target_name, show=True, report=""): # Search files in current directory tree
if target_name:
found_files = []
for root, _, files in os.walk(os.getcwd()):
for filename in files:
if target_name in filename:
found_files.append(os.path.join(root, filename))
if show: print('\n'.join(found_files) if found_files else f"{report}search: {target_name}: no files found.")
return found_files
def move(self, cmdline=""): # Move files and directories
if cmdline:
if len(shlex.split(cmdline)) < 2: raise IndexError("new.path")
shutil.move(shlex.split(cmdline)[0], shlex.split(cmdline)[1])
else: raise IndexError("source >> path")
def copy(self, cmdline=""): # Copy files
if cmdline:
if len(shlex.split(cmdline)) < 2: raise IndexError("copy.path")
shutil.copy(shlex.split(cmdline)[0], shlex.split(cmdline)[1])
else: raise IndexError("source >> copy")
def diff(self, filenames): # Compare files (line-per-line)
if len(shlex.split(filenames)) < 2: raise IndexError("2filename" if filenames else "filename <> filename")
lines1 = open(shlex.split(filenames)[0], "r").readlines()
lines2 = open(shlex.split(filenames)[1], "r").readlines()
for i, (line1, line2) in enumerate(zip(lines1, lines2), start=1):
if line1 != line2:
print(f" {i} - {self.basename(shlex.split(filenames)[0])}: {line1.strip()}")
print(f" {i} - {self.basename(shlex.split(filenames)[1])}: {line2.strip()}")
print()
def read(self, filename): # Open a file and show it content
if filename:
with open(filename, "r") as file:
self.nl(filename)
filesize = os.path.getsize(filename)
print(f"\n==============================")
print(f"File name: \033[1m{filename}\033[m")
print(f"File size: \033[1m{filesize} bytes\033[m")
else: raise IndexError("filename")
def wc(self, filename): # Show file lines and words
if filename:
with open(filename, "r") as file:
file = file.read()
print(f" {len(file.splitlines())} {len(file.split())} {len(file)} {filename}")
else: raise IndexError("filename")
#
# "Text Utilities"
def catfile(self, filename): # Show file content
if filename: print(self.recognize(open(filename, "r").read()))
else: self.txt2bin()
def tacfile(self, filename): # Show file content (Reversed mode)
if filename:
with open(filename, 'r') as file:
lines = file.readlines()
for line in reversed(lines): print(line.rstrip())
else: self.txt2bin()
def headfile(self, filename): # Show first lines of a file
if filename != "":
with open(filename, "r") as text:
text = text.read().splitlines()
try:
for cache in range(library['head-lines']): print(self.recognize(text[cache]))
except IndexError: return text
else: self.txt2bin()
def tail(self, filename): # Show last lines of a file
if filename:
def tailrepliant(filename):
with open(filename, 'r') as file:
lines = file.readlines()
if len(lines) <= library['head-lines']:
return ''.join(lines)
else:
return ''.join(lines[-library['head-lines']:])
print(tailrepliant(filename))
else: self.txt2bin()
def nl(self, filename): # Show file content with line number
if filename:
with open(filename, "r") as file:
line_number = 1
for line in file:
print(f" {line_number}\t{line}", end="")
line_number += 1
else: self.ThreadIn()
def find(self, cmdline, report=""): # Search WORDS in file content
if len(shlex.split(cmdline)) < 2: raise IndexError("words" if cmdline else "filename > words")
filename = shlex.split(cmdline)[0]
search_word = shlex.split(cmdline)[1]
results = []
with open(filename, "r") as text:
text = text.readlines()
line_number = 1
for line in text:
if search_word in line: results.append((line_number, line))
line_number += 1
if not results: return print(f"{report}find: no matches.")
print(f"{len(results)} matches of '{search_word}' in \033[1m{filename}\033[m:\n")
for line_number, line in results:
print(f" {line_number}\t{line}")
def catbin(self, filename): # (Read, Show and return) a byte file content
if filename:
with open(filename, 'rb') as file:
decoded_bytes = file.read()
return decoded_bytes
else: raise IndexError("filename")
def write(self, cmdline): # Append lines in a file (Write trough in the end)
if len(shlex.split(cmdline)) < 2: raise IndexError("words" if shlex.split(cmdline) else "filename << line")
with open(shlex.split(cmdline)[0], 'a') as file:
file.write(' '.join(shlex.split(cmdline)[1:]))