forked from EdwardLab/binpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinpython.py
1255 lines (1217 loc) · 53.2 KB
/
binpython.py
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
#BINPython By:XINGYUJIE AGPL-V3.0 LICENSE Release
#Please follow the LICENSE AGPL-V3
#full version
####################################
#build configure
ver = "0.44"
libs_warning = "1"
#1 is ture 0 is false.
#Changing the value to 0 will close the prompt that the library does not exist
releases_ver = "offical"
importlibs = "os"
cloudrunver = "1.04"
cmdver = "0.08"
#Imported library name, please use "importlibs="<library name>" instead of "import <library name>"
#Please note: The "importlibs" function does not support loading functions (such as from xxxx import xxxx, if necessary, please write it in the following location. However, please note that this operation may have the risk of error reporting, please report issues or solve it yourself
#xxxxxxxxxxxxxx
#from xxxx import xxxx
#xxxxxxxxxxxxxx
####################################
#BINPython function and variable START
class binpythoninfo:
def ver():
print(ver)
def libs_warning():
print(libs_warning)
def releases_ver():
print(releases_ver)
def build_importlibs():
print(importlibs)
from os import makedirs
import time
#get system info(windows or linux ...)
import platform
sys = platform.system()
#if system is windows, then enable setwindowtitle() function
if sys == "Windows":
class binpythonwin:
def setwindowtitle(titlename):
import ctypes
ctypes.windll.kernel32.SetConsoleTitleW(titlename)
#print binpython all configure function
def binpythonallconf():
print("ver: " + ver + " buildversion: " + " libs_warning settings:" + libs_warning + " releases full version: " + releases_ver + " custom library that has been build: " + importlibs)
#if system is windows, show default window title
if sys == "Windows":
import ctypes
ctypes.windll.kernel32.SetConsoleTitleW("BINPython " + ver)
#binpython self import function
def self_import(name):
__import__(name)
try:
self_import(importlibs)
#get libswarning
except ImportError:
if libs_warning == "1":
print("Warning: Custom import library %s does not exist, please check the source code library configuration and rebuild" % importlibs)
print("")
#run python files option(-f)
def optreadfile():
import sys
getfile = sys.argv[1]
getfilecode = open(getfile,encoding = "utf-8")
exec(getfilecode.read())
input("Run finished. Enter to Shell.")
sys.exit(0)
try:
#base import
import getopt
import sys
import platform
import os
import timeit
import pdb
import random
import webbrowser
import urllib.request
import base64
import cmd
import zipfile
import requests
import urllib
import wget
import shutil
import json
#fix for exit()
from sys import exit
#import for http_server
import http.server
import socketserver
import flask
#except ImportError:
except(Exception, BaseException) as error:
print("Unable to use any library, the program does not work properly, please rebuild")
f = open("binpython_importerror.log", "a")
f.write('Import Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
#gui import
try:
import tkinter
import tkinter as tk
from tkinter import *
import turtle
def importpygame():
import pygame
import pygame.locals
import pyglet
null = importpygame
#warning for gui
except ImportError:
if libs_warning == "1":
print("Warning: Some GUI (graphical) libraries for BINPython do not exist, such as tkinter and turtle. Because they are not built when they are built. If you need to fix this warning, please complete the support libraries imported in the source code at build time (use pip or build it yourself), if your system does not support these libraries, you can remove or change this hint in the source code and rebuild")
print("")
#import math
try:
import fractions
import cmath
except ImportError:
if libs_warning == "1":
print("Warning: Some math or computation libraries for BINPython do not exist, such as fractions and cmath. Because they weren't built when they were built. If you need to fix this warning, please complete the support libraries imported in the source code when building (use pip or build it yourself), if your system does not support these libraries, you can remove or change this prompt in the source code and rebuild")
print("")
#import for normal
try:
#str
import rlcompleter
import array
import xlrd
except ImportError:
if libs_warning == "1":
print("Warning: Some libraries for functions, data types, etc. for BINPython do not exist, such as rlcomplter and array. Because they weren't built when they were built. If you need to fix this warning, please complete the support libraries imported in the source code when building (use pip or build it yourself), if your system does not support these libraries, you can remove or change this prompt in the source code and rebuild")
print("")
try:
import filecmp
import tempfile
except ImportError:
if libs_warning == "1":
print("Warning: Some file manipulation libraries for BINPython do not exist, such as filecmp and tempfile. Because they weren't built when they were built. If you need to fix this warning, please complete the support libraries imported in the source code when building (use pip or build it yourself), if your system does not support these libraries, you can remove or change this prompt in the source code and rebuild")
print("")
#main BINPython
def binpython_welcome_text():
print("BINPython " + ver + "-" + releases_ver + " (Python Version:" + platform.python_version() + ") By: Edward Hsing(Xing Yu Jie) https://github.com/xingyujie/binpython[Running on " + platform.platform() + " " + platform.version() + "]")
print('Type "about", "help", "copyright", "credits" or "license" for more information. Type "binpython_cmd" to enter BINPython CMD')
def binpython_shell():
while True:
try:
pycmd=input(">>> ")
if pycmd in globals().keys():
print(globals()[pycmd])
continue
elif pycmd == 'about':
print("BINPython By: Edward Hsing(Xing Yu Jie)[https://github.com/xingyujie] AGPL-3.0 LICENSE Release")
elif pycmd == 'help':
print("Type help() for interactive help, or help(object) for help about object.")
elif pycmd == 'copyright':
print("""
Copyright (c) 2001-2022 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
""")
elif pycmd == 'credits':
print("""
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
for supporting Python development. See www.python.org for more information.
""")
elif pycmd == 'license':
print("Type license() to see the full license text")
elif pycmd == 'binpython_cmd':
binpython_cmd()
else:
exec(pycmd)
except KeyboardInterrupt:
print("KeyboardInterrupt")
sys.exit()
except Exception as err:
print(err)
try:
optreadfile()
except:
pass
def cloudruncli():
print("Welcome to CloudRun CLI. Let your script run in the cloud with BINPython")
print('Type "help" for more information')
while True:
cloudruncli = input("cloudrun~ ")
if cloudruncli == 'help':
print("""
CloudRun Help:
get -- Enter application/script name to get run from software repository
load -- Run scripts from custom URL
editsource -- Set up custom sources and save via configuration files
shell -- Go to BINPython Shell
version -- CloudRun Version
help -- show this help
exit -- quit cloudrun
""")
if cloudruncli == 'get':
print("Get apps/scripts in software repository")
print("Under normal circumstances, we review the code of the software repositories and generally do not have any malware. But we will not take any legal responsibility")
print()
pkgname = input("packagename: ")
if pkgname == '':
pass
else:
cloudrun.get(pkgname)
if cloudruncli == 'load':
print("Let CloudRun run scripts through a custom server")
print("The format should be like this: http://domain.com/filename.py")
url = input("Python script URL: ")
if url == '':
pass
else:
cloudrun.load(url)
if cloudruncli == 'editsource':
print('caution! The set software source must be in a standard format, otherwise it may not work, like http://127.0.0.1/, if you set http://127.0.0.1, it will not work properly, even if there is one less "/"!')
entersource = input("Please input sources server address: ")
cloudrun.editsource(entersource)
print("success!")
if cloudruncli == 'shell':
binpython_shell()
if cloudruncli == 'version':
print(f"CloudRun-{cloudrunver} BINPython version By:Edward Hsing(Xing Yu Jie) AGPL-3.0 LICENSE")
if cloudruncli == 'exit':
exit()
if cloudruncli == '':
pass
else:
pass
#cloudrun functions start
from pywebio.output import *
import pywebio.input
class cloudrun:
def get(pkgname):
try:
sources = open("cloudrun_config/sources.config", "r")
sources = str(sources.read()) + pkgname + ".py"
except:
sources = f"https://raw.githubusercontent.com/xingyujie/cloudrun-repository/main/{pkgname}.py"
try:
cloudrunenv = True
getcoderes = urllib.request.urlopen(sources)
except(Exception, BaseException) as error:
print("There is no network connection or the repository does not exist for this script")
print("Error details are in cloudrun_error.log in the run directory")
f = open("cloudrun_error.log", "a")
f.write('Get Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
try:
exec(str(getcoderes.read().decode('utf-8')))
getcoderes.close()
except(Exception, BaseException) as error:
print("run failed")
print("Error details are in cloudrun_error.log in the run directory")
f = open("cloudrun_error.log", "a")
f.write('Run Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
def load(url):
try:
cloudrunenv = True
getcoderes = urllib.request.urlopen(url)
except(Exception, BaseException) as error:
print("There is no network connection or the repository does not exist for this script")
print("Error details are in cloudrun_error.log in the run directory")
f = open("cloudrun_error.log", "a")
f.write('Get Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
try:
exec(getcoderes.read().decode('utf-8'))
getcoderes.close()
except(Exception, BaseException) as error:
print("run failed")
print("Error details are in cloudrun_error.log in the run directory")
f = open("cloudrun_error.log", "a")
f.write('Run Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
def editsource(url):
try:
os.mkdir("cloudrun_config")
except:
pass
sources = open("cloudrun_config/sources.config", "w")
sources.write(url)
#cloudrun functions end
#cmd start
def get_resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
def listfiles():
import os
dirs = os.listdir("./")
for file in dirs:
print (file)
def listfilesfunc(path):
import os
dirs = os.listdir(path)
for file in dirs:
print (file)
def download(url,path):
if not os.path.exists(path):
os.mkdir(path)
start = time.time()
response = requests.get(url, stream=True)
size = 0
chunk_size = 1024
content_size = int(response.headers['content-length'])
try:
if response.status_code == 200:
print('Start download,[App size]:{size:.2f} MB'.format(size = content_size / chunk_size /1024))
filepath = path+'\name.extension name'
with open(filepath,'wb') as file:
for data in response.iter_content(chunk_size = chunk_size):
file.write(data)
size +=len(data)
print('\r'+'[Downloading]:%s%.2f%%' % ('>'*int(size*50/ content_size), float(size / content_size * 100)) ,end=' ')
end = time.time()
print('Download completed!,times: %.2f second' % (end - start))
except:
print("Download package failed!")
def unzip(path, folder_abs):
zip_file = zipfile.ZipFile(path)
zip_list = zip_file.namelist()
for f in zip_list:
zip_file.extract(f, folder_abs)
zip_file.close()
def mkbpfs():
print("Welcome to bpfs[BINPython File System] making tool (mkfs.bpfs). Type help to list commands and help.")
while True:
cmd = input("(BPFS CLI) ")
if cmd == 'mkfs':
print("Make a new bpfs filesystem")
fspath = input("Enter the bpfs save path of the file system: ")
try:
os.mkdir(fspath)
except:
pass
try:
os.chdir(fspath)
print("[*] Done.")
except:
print("[E] path does not exist!")
print("[*] Make base file system")
try:
os.makedirs("binpython_files/apps")
os.makedirs("binpython_files/cmd")
os.makedirs("binpython_files/hostname")
os.makedirs("binpython_files/userdata")
open("binpython_files/cmd/cmd.py", "w")
except(Exception, BaseException) as error:
print("make dirs and files Error." + error)
try:
hostnameyn = input("do you want to create hostname(y/n): ")
if hostnameyn == 'y':
hostnamecontent = input("enter hostname: ")
with open("binpython_files/hostname/hostname", "w") as sethostname:
sethostname.write(hostnamecontent)
print("[*] Done.")
else:
pass
except(Exception, BaseException) as error:
print("makehostname Error." + error)
try:
usernameyn = input("do you want to set default login user(y/n): ")
if usernameyn == 'y':
usernamecontent = input("enter default login username: ")
with open("binpython_files/userdata/defaultloginuser", "w") as setusername:
setusername.write(usernamecontent)
os.makedirs(f"binpython_files/userdata/home/{usernamecontent}")
print("[*] Done.")
else:
pass
except(Exception, BaseException) as error:
print("Set default username Error. " + error)
if cmd == 'help':
print("""
List commands:
mkfs -- Make a new bpfs filesystem
help -- This help
exit -- exit mkbpfs
""")
if cmd == 'exit':
binpython_cmd()
def getfsfile(path):
try:
os.mkdir("binpython_files")
except:
pass
print("[*] Unzip File System BPFS(BINPython File System) from file")
unzip(path, runpath + "/binpython_files")
print("\n")
print("[*] Done!")
binpython_cmd()
def downfs(bpfsurl):
try:
os.mkdir("binpython_files")
except:
pass
print("[*] Download File System BPFS(BINPython File System)")
wget.download(bpfsurl, runpath + "/binpython_files")
unzip(runpath + "/binpython_files/officialbpfs.bpfs", runpath + "/binpython_files")
print("\n")
print("[*] Done!")
binpython_cmd()
def binpython_cmd():
global runpath
runpath = os.path.dirname(os.path.realpath(sys.argv[0]))
try:
os.chdir(runpath + f"/binpython_files/userdata/")
os.chdir(runpath + f"/binpython_files/cmd")
except:
whichmethod = input("""
Welcome to BINPython CMD! Choose a method to install BINPython CMD:
1. WEB graphical interactive installation (recommended)
2. Interactive text interface (also for non-graphical devices)
Please enter a number (1/2):
""")
if whichmethod == '1':
getwebui = open(get_resource_path('webui.py'))
webui = getwebui.read()
exec(webui)
if whichmethod == '2':
print('''
The file system cannot be found or there is an incomplete file system.
type "getfs" to download a file system;
type "getfsurl" to download a filesystem via a custom url;
Type "getfsfile" to unzip the filesystem via file;
type "mkbpfs" to make a new file system;
type "exit" to exit;
type "shell" to force entry into the shell.
* After forcing into the shell, you can create bpfs via "mkbpfs" command or use "adduser", "setdefaultuser" and other commands to build the filesystem step by step. But we don't recommend it, it may be more problematic and more complex
''')
while True:
initcmd = input("(InstallationENV) ")
if initcmd == 'exit':
exit()
if initcmd == 'shell':
break
if initcmd == 'mkbpfs':
mkbpfs()
if initcmd == 'getfs':
downfs('https://raw.githubusercontent.com/xingyujie/binpython-repository/main/officialbpfsbase.bpfs')
if initcmd == 'getfsurl':
fsurl = input("Please enter a download link (like: http://url.com/bpfs/bpfsbase.bpfs)")
downfs(fsurl)
if initcmd == 'getfsfile':
filepath = input("Please enter a (*.bpfs) file path: ")
getfsfile(filepath)
try:
global cmd_username
defaultprofile = open(runpath + "/binpython_files/userdata/defaultloginuser", "r")
cmd_username = defaultprofile.read()
os.chdir(runpath + f"/binpython_files/userdata/home/{cmd_username}")
except:
cmd_username = 'user'
print('Unable to switch to BINPython userprofile: Default user not found. To use a temporary directory user, use "adduser" and "setdefaultuser <username>" to create a user and set default user')
try:
gethostname = open(runpath + "/binpython_files/hostname/hostname", "r")
cmd_hostname = gethostname.read()
except:
cmd_hostname = "binpython"
try:
shutil.rmtree(runpath + f"/binpython_files/userdata/home/tempuser")
shutil.rmtree(runpath + f"/binpython_files/apps/tempuser")
except:
pass
class cmdshell(cmd.Cmd):
intro = 'Welcome to BINPython Shell. Type help or ? to list commands and help.\n'
prompt = cmd_username + '@' + cmd_hostname + ':~# '
file = None
try:
os.makedirs(runpath + f"/binpython_files/cmd/")
except:
pass
try:
f = open(runpath + f"/binpython_files/cmd/cmd.py", "r")
exec(f.read())
except(Exception, BaseException) as error:
f = open(runpath + f"/binpython_files/cmd/cmd_ignore.txt", "a")
f.write('Custom CMD ignore: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
def do_cloudrunget(self, arg):
'Get CloudRun Script from repository use:cloudrunget <scriptname>'
cloudrun.get(arg)
def do_cloudrunload(self, arg):
'Get CloudRun Script from repository use:cloudrunload <URL> URL can be http://domain.com/filename.py'
cloudrun.load(arg)
def do_cloudruneditsource(self, arg):
'Change the source of CloudRun'
cloudrun.editsource(arg)
def do_ls(self, arg):
'List files'
listfiles()
def do_pwd(self, arg):
'show current path'
print(os.path.dirname(os.path.realpath('__file__')))
def do_cd(self, arg):
'change path'
os.chdir(arg)
def do_adduser(self, arg):
'Create a new user profile for BINPython'
print("Create a new user profile for BINPython")
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0]))
username = input("Username: ")
print("create user...")
try:
os.makedirs(runpath + f"/binpython_files/userdata/home/{username}")
except(Exception, BaseException) as error:
print("User already exits or system error")
print(error)
print("Done")
def do_setdefaultuser(self, arg):
'Set a default user'
defaultprofile = open(runpath + "/binpython_files/userdata/defaultloginuser", "w")
defaultprofile.write(arg)
print("Done")
def do_shell(self, arg):
'Go to Python interpreter'
binpython_shell()
def do_python(self, arg):
'Run a Python script file (*.py) Usage: python <filename>.py'
if arg == '':
binpython_shell()
f = open(arg, "r")
exec(f.read())
def do_seteditor(self, arg):
'Set a default Python or Text file code editor usage: seteditor <editorname>. like: "seteditor code" (Open code via Visual Studio Code when using the "edit <filename>" command). "seteditor notepad" (Open the code through Notepad that comes with Windows)'
defaulteditor = open(runpath + f"/binpython_files/userdata/home/{cmd_username}/defaulteditor.config", "w")
defaulteditor.write(arg)
def do_edit(self, arg):
'Before using this command, you must use "seteditor <editorname>" to set the editor (see the usage of this parameter for details), otherwise it cannot be called up. edit usage: edit <filename>'
defaulteditor = open(runpath + f"/binpython_files/userdata/home/{cmd_username}/defaulteditor.config", "r")
try:
os.system(defaulteditor.read() + ' ' + arg)
except KeyboardInterrupt:
pass
def do_exit(self, arg):
'exit shell'
print("logout")
sys.exit()
def do_sethostname(self, arg):
'set up hostname. Usage sethostname <hostname>'
try:
os.makedirs(runpath + "/binpython_files/hostname/")
except:
pass
hostnamefile = open(runpath + "/binpython_files/hostname/hostname", "w")
hostnamefile.write(arg)
def do_rm(self, arg):
'remove files Usage: rm <filename>'
os.remove(arg)
def do_system(self, arg):
'call system command. Usage: system <command> like: system ls (Invoke system command to list directory)'
os.system(arg)
def do_mkdir(self, arg):
'make a directory. Usage: mkdir <dirname>'
os.mkdir(arg)
def do_touch(self, arg):
'make a empty file Usage: touch <filename>'
open(arg, "w")
def do_write(self, arg):
'write text to file. Usage: write <filename>'
writetext = open(arg, "w")
arg1 = input(f"What you want to write to the target file {arg}: ")
writetext.write(arg1)
def do_ukraine(self, arg):
'stand with ukraine'
print("We stand with Ukraine")
webbrowser.open("https://war.ukraine.ua/")
def do_uname(self, arg):
'version of CMD'
print(f"BINPython CMD By: Edward Hsing VER:{cmdver} ")
def do_user(self, arg):
'Switch User Usage: user <username>'
os.chdir(runpath + f"/binpython_files/userdata/home/{arg}")
try:
f = open(runpath + "/binpython_files/userdata/defaultloginuser", "w")
f.write(arg)
except(Exception, BaseException) as error:
print('Switch User Error, please see the log "binpython_user_error.log" for details')
f = open("binpython_user_error.log", "a")
f.write('Switch User Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
def do_install(self, arg):
'Install package'
try:
os.makedirs(runpath + f"/binpython_files/apps/{cmd_username}")
except:
pass
try:
os.makedirs(runpath + f"/binpython_files/apps/{cmd_username}/installtemp")
except:
pass
try:
global appsource
f = open(runpath + f"/binpython_files/apps/source.config", "r")
appsource = f.read()
except:
f = open(runpath + f"/binpython_files/apps/source.config", "w")
f.write("https://raw.githubusercontent.com/xingyujie/binpython-repository/main/")
appsource = "https://raw.githubusercontent.com/xingyujie/binpython-repository/main/"
if arg == '':
print("Please use install <package name> missing options <package name>")
exit()
try:
print("[*] download package")
wget.download(f"{appsource}{arg}.bpkg", runpath + f"/binpython_files/apps/{cmd_username}/installtemp/{arg}.bpkg")
print("\n")
except(Exception, BaseException) as error:
print('The package does not exist or system error, please see the log "install_error.log" for details')
f = open("install_error.log", "a")
f.write('Install Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + f" {appsource}{arg}.bpkg " + str(error) +'\n')
exit()
try:
print("[*] Unzip the package")
unzip(runpath + f"/binpython_files/apps/{cmd_username}/installtemp/{arg}.bpkg", runpath + f"/binpython_files/apps/{cmd_username}/{arg}")
except(Exception, BaseException) as error:
print('Unzip the package failed, please see the log "install_error.log" for details')
f = open("install_error.log", "a")
f.write('Unzip package Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
try:
f = open(runpath + f"/binpython_files/apps/{cmd_username}/{arg}/package.json")
pkginfo = json.loads(f.read())
print(f"""
Package information:
Name: {pkginfo['name']}
Version: {pkginfo['version']}
Summary: {pkginfo['summary']}
Homepage: {pkginfo['homepage']}
Author: {pkginfo['author']}
Email: {pkginfo['email']}
License: {pkginfo['license']}
""")
f.close()
yn = input("Do you want to continue?(y/n): ")
if yn == 'y':
pass
else:
sys.exit(0)
except(Exception, BaseException) as error:
print('[W] Warning: Could not find package configuration information file, please see the log "install_warning.log" for details')
f = open("install_warning.log", "a")
f.write('Run package information Warning: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
try:
print("[*] configure package")
f = open(runpath + f"/binpython_files/apps/{cmd_username}/{arg}/config.py")
exec(f.read())
except(Exception, BaseException) as error:
print('[W] Warning: config file no configuration or configuration error, please see the log "install_warning.log" for details')
f = open("install_warning.log", "a")
f.write('Run package configuration file Warning: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
try:
print("[*] Clean up temporary files")
os.remove(runpath + f"/binpython_files/apps/{cmd_username}/installtemp/{arg}.bpkg")
except(Exception, BaseException) as error:
print('Failed to clean up temporary files, please see the log "install_error.log" for details')
f = open("install_error.log", "a")
f.write('clean up temporary files Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
print("[OK]Finished!")
def do_installfile(self, arg):
'Install package from local bpkg file'
if arg == '':
print("Please use install <package file name> missing options <package file name>")
exit()
nobpkgarg = arg.replace('.bpkg', '')
try:
os.makedirs(runpath + f"/binpython_files/apps/{cmd_username}")
except:
pass
try:
os.makedirs(runpath + f"/binpython_files/apps/{cmd_username}/installtemp")
except:
pass
try:
print("[*] Unzip the package")
unzip(arg, runpath + f"/binpython_files/apps/{cmd_username}/{nobpkgarg}")
except(Exception, BaseException) as error:
print('Unzip the package failed, please see the log "install_error.log" for details')
f = open("install_error.log", "a")
f.write('Unzip package Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
try:
f = open(runpath + f"/binpython_files/apps/{cmd_username}/{nobpkgarg}/package.json")
pkginfo = json.loads(f.read())
print(f"""
Package information:
Name: {pkginfo['name']}
Version: {pkginfo['version']}
Summary: {pkginfo['summary']}
Homepage: {pkginfo['homepage']}
Author: {pkginfo['author']}
Email: {pkginfo['email']}
License: {pkginfo['license']}
""")
yn = input("Do you want to continue?(y/n): ")
if yn == 'y':
pass
else:
binpython_cmd()
except(Exception, BaseException) as error:
print('[W] Warning: Could not find package configuration information file, please see the log "install_warning.log" for details')
f = open("install_warning.log", "a")
f.write('Run package information Warning: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
try:
print("[*] configure package")
f = open(runpath + f"/binpython_files/apps/{cmd_username}/{nobpkgarg}/config.py")
exec(f.read())
except(Exception, BaseException) as error:
print('[W]config file no configuration or configuration error, please see the log "install_warning.log" for details')
f = open("install_warning.log", "a")
f.write('Run package configuration file Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
print("[OK]Finished!")
def do_switchappdir(self, arg):
'Switch to App directory. Usage: switchappdir <appname>'
try:
os.chdir(runpath + f"/binpython_files/apps/{cmd_username}/{arg}")
except(Exception, BaseException) as error:
print('Can not switch app directory, please see the log "binpython_pkg_error.log" for details')
f = open("binpython_pkg_error.log", "a")
f.write('Switch package directory Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
def do_runapp(self, arg):
'To run a BINPython bpkg program, first pass install <app name> or installfile <app package path> Usage: runapp <appname>. '
try:
execpyfile(runpath + f"/binpython_files/apps/{cmd_username}/{arg}/main.py")
except(Exception, BaseException) as error:
print('App not exits or failed, please see the log "binpython_pkg_error.log" for details')
f = open("binpython_pkg_error.log", "a")
f.write('Run package Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
def do_removeapp(self, arg):
'To delete a BINPython application, usage: removeapp <appname>'
try:
shutil.rmtree(runpath + f"/binpython_files/apps/{cmd_username}/{arg}")
except(Exception, BaseException) as error:
print('App not exits or failed, please see the log "binpython_pkg_error.log" for details')
f = open("binpython_pkg_error.log", "a")
f.write('Remove package Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
def do_listapps(self, arg):
'List installed BINPython applications'
try:
listfilesfunc(runpath + f"/binpython_files/apps/{cmd_username}")
except(Exception, BaseException) as error:
print('Can not list apps, please see the log "binpython_pkg_error.log" for details')
f = open("binpython_pkg_error.log", "a")
f.write('List package Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
def do_editsource(self, arg):
'To change the software source, usage: editsouce <souceurl>. Please pay attention to the software source specification, otherwise you will get an error. <souceurl> like this: http://xxx.com/'
f = open(runpath + f"/binpython_files/apps/source.config", "w")
f.write('http://' + arg + '/')
def do_tempuser(self, arg):
'Create a temporary user, logging out will destroy the user space'
print("You are trying to create a temporary user, this user space is only used for demonstration, testing and learning. When this user is logged out, all user data will also be deleted")
print("..........")
time.sleep(0.3)
print('Please note: the username of the temporary user is "tempuser" and the "tempuser" user is being created')
try:
os.makedirs(runpath + f"/binpython_files/apps/tempuser")
os.makedirs(runpath + f"/binpython_files/userdata/home/tempuser")
except(Exception, BaseException) as error:
print('Can not create tempuser, please see the log "binpython_user_error.log" for details')
f = open("binpython_user_error.log", "a")
f.write('Switch tempuser Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
os.chdir(runpath + f"/binpython_files/userdata/home/tempuser")
print("Created successfully, has switched to the tempuser directory")
def do_repolist(self, arg):
'Change the BINPython source from the official list'
cloudrun.load("https://raw.githubusercontent.com/xingyujie/binpython-repository/main/source.py")
def do_cloudrunshell(self, arg):
'Go to CloudRun Shell'
cloudruncli()
def do_whoami(self, arg):
'Print Username'
print(cmd_username)
def do_hostname(self, arg):
'Print Hostname'
print(cmd_hostname)
def do_rootpath(self, arg):
'Print rootpath(runpath)'
print(runpath)
def do_initcmd(self, arg):
'Initialize the custom CMD command file. After opening, you can use the "def do_cloudrunget(self, arg):" code to write your own commands through the "/binpython_files/cmd/cmd.py" file.'
try:
os.makedirs(runpath + f"/binpython_files/cmd")
except:
pass
try:
f = open(runpath + f"/binpython_files/cmd/{arg}.py", "w")
f.write('#Initialize the custom CMD command file, you can write your own command through the "def do_cloudrunget(self, arg):" code, please refer to "https://docs.python.org/3/library/cmd.html" for details')
except(Exception, BaseException) as error:
print('Can not initcmd, please see the log "binpython_cmd_error.log" for details')
f = open("binpython_cmd_error.log", "a")
f.write('Init CMD Error: ' + time.strftime('%m-%d-%Y %H:%M:%S',time.localtime(time.time())) + ' ' + str(error) + '\n')
def do_mkbpfs(self, arg):
'Make BINPython File System'
mkbpfs()
if __name__ == '__main__':
cmdshell().cmdloop()
#cmd end
#def
#print all helpinfo
helpinfo = """
Usage: binpython [OPTIONS]
Options:
<filename> Enter Python Filename and run (*.py)
-f --file Enter Python Filename and run (*.py), But this options is no Run finished prompt
-h --help View this help
-s <port> --server=<port> Start a simple web server that supports html and file transfer (http.server)
-g --gui View GUI About and build info
-i --idle Open BINPython IDLE Code Editor
-p <port> --plus=<port> Open BINPython IDE Plus Code Editor(beta) with http web server
-e --example Run various code examples through BINPython
-c --cmd Operations on BINPython (including Package Manager, CloudRun, etc.)
-v --version View BINPython Version
"""
#base + plus, print full help
def outputfullhelp():
try:
f = open("binpython_config/help.txt",encoding = "utf-8")
print(f.read())
except:
print(helpinfo)
#set about info
about = "BINPython " + ver + "-" + releases_ver + " By: Edward Hsing(Xing Yu Jie)[https://github.com/xingyujie/binpython] AGPL-3.0 LICENSE Release"
#getopt
try:
#set options
opts,args = getopt.getopt(sys.argv[1:],'-h-f:-s:-g-i-p:-e-c-v',['help','file=','server=','gui','idle','plus','example','cmd','version'])
#set getopt error prompt
except getopt.GetoptError as err:
print("Please check help:")
print("The parameters you use do not exist or are not entered completely, please check help!!!!")
#then show full help(outputfullhelp())
outputfullhelp()
sys.exit()
#get every option and run
for opt_name,opt_value in opts:
def execpyfile(filename):
f = open(filename)
exec(f.read())
if opt_name in ('-h','--help'):
#-h show full help function
outputfullhelp()
sys.exit()
if opt_name in ('-v','--version'):
#-v show version(read custom config)
try:
f = open("binpython_config/version.py",encoding = "utf-8")
exec(f.read())
print("Powered by: BINPython[https://github.com/xingyujie/binpython] AGPL 3.0")
except:
print("BINPython " + ver + "-" + releases_ver + " By: Edward Hsing(Xing Yu Jie)[https://github.com/xingyujie/binpython] AGPL-3.0 LICENSE Release")
print("Python " + platform.python_version())
sys.exit()
if opt_name in ('-f','--file'):
#-f runfile(or no option)
file = opt_value
f = open(file,encoding = "utf-8")
exec(f.read())
sys.exit()
if opt_name in ('-s','--server'):
#-s set simple http server(support html or files transfer)
server_port = opt_value
webbrowser.open(f"http://127.0.0.1:{server_port}")
exec("""
PORT = """ + server_port + """
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
""")
if opt_name in ('-g','--gui'):
#-g gui show gui about info(based on tkinter)
from tkinter import *
root = Tk()
root.title("Welcome to BINPython")
root.geometry('600x300')
text =Text(root, width=35, heigh=15)
text.pack()
text.insert("insert", "BINPython" + about)
print(text.get("1.3", "1.end"))
####
text=Label(root,text="Welcome to BINPython" + ver,bg="yellow",fg="red",font=('Times', 20, 'bold italic'))
text.pack()
button=Button(root,text="EXIT",command=root.quit)
button.pack(side="bottom")
root.mainloop()
sys.exit()
def show():
os.system('cls' if os.name == 'nt' else 'clear')
print("<<<<<<<<<<START>>>>>>>>>>")
exec(e1.get(1.0, END))
#tkinter ide Simulation environment
if opt_name in ('-i','--idle'):
import tkinter as tk
from tkinter import *
master = tk.Tk()
master.title("BINPython IDLE")
tk.Label(master, text="Type Code", height=5).grid(row=0)
e1 = Text(master,
width=150,
height=40,)
e1.grid(row=0, column=1, padx=10, pady=5)
tk.Button(master, text="Run", width=10, command=show).grid(row=3, column=0, sticky="w", padx=10, pady=5)
tk.Button(master, text="EXIT", width=10, command=master.quit).grid(row=3, column=1, sticky="e", padx=10, pady=5)
master.mainloop()
sys.exit()
#-p binpython ideplus
if opt_name in ('-p','--plus'):
ideplusport = opt_value
import pywebio.input
from pywebio.input import *
from pywebio.output import *
from pywebio import *
from pywebio.session import *
import sys
import subprocess
import os
import webbrowser
print("______________________________________")
print("BINPython WEB IDE STARTED")
print(f"""
Welcome to BINPython IDEPlus!
HTTP Port: {ideplusport}
""")
#open browser
webbrowser.open(f"http://127.0.0.1:{ideplusport}")
#IDE Plus main
def line():
put_text('_______________________',
sep=' '
)
#set bootstrap ui(bar)
def head():
set_env(title="BINPython IDE Plus", auto_scroll_bottom=True)
put_html(f"""
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="http://localhost:{ideplusport}"></a>
<img src="https://github.com/xingyujie/binpython/blob/main/py.ico?raw=true" width="30" height="30" class="d-inline-block align-top" alt="">
BINPython IDEPlus
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="http://localhost:{ideplusport}/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://localhost:{ideplusport}/?app=ideplus">IDEPlus</a>
</li>
</a>
</ul>
</div>
</nav>
""")
def plushead():
set_env(title="BINPython IDE Plus", auto_scroll_bottom=True)
put_html(f"""
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="http://localhost:{ideplusport}"></a>
<img src="https://github.com/xingyujie/binpython/blob/main/py.ico?raw=true" width="30" height="30" class="d-inline-block align-top" alt="">
BINPython IDEPlus
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="http://localhost:{ideplusport}/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="http://localhost:{ideplusport}/?app=ideplus">IDEPlus</a>
</li>
</a>
</ul>
</div>