-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.windows.py
516 lines (508 loc) · 19.7 KB
/
main.windows.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
#Main For Windows
'''import argparse
parser = argparse.ArgumentParser(description="")#help msg
parser.add_argument('-gf', '--girlfriend', choices=['jingjing', 'lihuan'])
parser.add_argument('--house', type=int, default=0)
# 3.进行参数解析
args = parser.parse_args()
print('------args---------',args)
'''
import platform
import ctypes
from filetp_cmd import Cmd
from subprocess import *
import sys
import glob
import qrcode
from filetp.filetp import *
from filetp_commands import *
import os
try:#可能是不必要的
nullio=open(os.devnull,"w+")
except:
nullio=open("null.tmp","w+")
if(platform.uname()[0]=="Windows"):
cp=ctypes.windll.kernel32.GetConsoleCP()
path=os.path.join(os.getenv("SystemRoot"),"System32","chcp.com")#%SystemRoot%\System32\chcp.com
p=Popen([path,str(cp),">","NUL"],shell=True,stdout=sys.stdout,stderr=nullio,cwd=os.getcwd())#重新加载codepage
p.wait()
def exit():
#do exit command
print("\n"+strings.app.terminate)
Log.info("----------FileTP App Close:time:"+str(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()))+"----------")
def countdir(path):
file_count = 0
for dirpath, dirnames, filenames in os.walk(path):
for file in filenames:
file_count = file_count + 1
return file_count
def YN():
res=input("(Y/N)").lower()=="y"
return res
def ctrlc(sig, frame):
print("\n")
def _makefilename(name:str):
if(" " in str(name)):
return "\""+str(name)+"\""
else:
return str(name)
def ls(path:str,d:DirTree,color=True):
if(path=="/"):
if(len(d.root.children)==0 and len(d.root.value)==0):
print('\x1b[%sm%s\x1b[0m' % (';'.join([str(colors["lightgray"]),"3","1","2"]), strings.app.nofiles))
return
for i in d.root.children:
if(color):
printcolor(colors["blue"],_makefilename(i.name),bold=True,end=" ")
else:
print(_makefilename(i.name),end=" ")
for i in d.root.value:
print(_makefilename(str(i)),end=" ")
else:
if((len(d.finddir(path.split("/")).children)==0) and (len(d.finddir(path.split("/")).value)==0)):
print('\x1b[%sm%s\x1b[0m' % (';'.join([str(colors["lightgray"]),"3","1","2"]), strings.app.nofiles))
return
path=path.replace("\\","/")
for i in d.finddir(path.split("/")).children:
if(color):
printcolor(colors["blue"],_makefilename(i.name),bold=True,end=" ")
else:
print(_makefilename(i.name),end=" ")
for i in d.finddir(path.split("/")).value:
print(_makefilename(str(i)),end=" ")
print()
def dir_(path:str,d:DirTree,color=True):
if(path=="/"):
if(len(d.root.children)==0 and len(d.root.value)==0):
print('\x1b[%sm%s\x1b[0m' % (';'.join([str(colors["lightgray"]),"3","1","2"]), strings.app.nofiles))
return
for i in d.root.children:
if(color):
printcolor(colors["blue"],i.name,bold=True)
else:
print(i.name)
for i in d.root.value:
print(str(i))
else:
if(len(d.finddir(path.split("/")).children)==0 and len(d.finddir(path.split("/")).value)==0):
print('\x1b[%sm%s\x1b[0m' % (';'.join([str(colors["lightgray"]),"3","1","2"]), strings.app.nofiles))
return
path=path.replace("\\","/")
for i in d.finddir(path.split("/")).children:
if(color):
printcolor(colors["blue"],str(i.name),bold=True)
else:
print(i.name)
for i in d.finddir(path.split("/")).value:
print(str(i))
print()
def parse_addr(addr:str):
args=addr.split(":")
if(len(args)>1):
try:
ip=args[0]
port=int(args[1])
return ip,port
except:
raise AssertionError(strings.app.messages.parseraddrerror)
else:
return addr,PORT
def _connected(c:Client):
try:
return not c.sk.closed
except:
return False
class ClientCmd(Cmd):
def _make_qrcode(self,msg):
qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=1,border=1)
qr.add_data(msg)
qr.make()
im=qr.make_image(fill_color='black', back_color='white')
for i in range(0,im.size[0],2):
for j in range(im.size[1]):
mode=0#0b00,0b01,0b10,0b11
if(im.getpixel((i,j))):
mode+=0b10
if(i<im.size[0]-1):
if(im.getpixel((i+1,j))):
mode+=0b01
match(mode):#please run on Python3.10.x or later
case 0:#00
print(" ",end='')
case 1:#01
print("▄",end='')
case 2:#10
print("▀",end='')
case _:#11
print("█",end='')
print()#\n
im.close()
def do_test(self,arg):
print("do_test() called [ OK ]")
log=getLogger("CMD")
prompt = strings.app.pro
intro = strings.app.intro
cd="/"
d:DirTree=None
@property
def c(self):
return client
timeout=6
def chdirupdate(self):
if(self.d.hasdir(self.cd.split("/"))):
cd='\x1b[%sm%s\x1b[0m' % (';'.join([str(colors["blue"]),"1"]), self.cd)
self.prompt=strings.app.pro % cd
else:
self.do_chdir("/")
def __init__(self):
super().__init__()
self.cd="/"
if(co.has_color()):#Console has color
cd='\x1b[%sm%s\x1b[0m' % (';'.join([str(colors["blue"]),"1"]), self.cd)
else:
cd=self.cd
self.prompt = strings.app.pro % cd
self.intro = strings.app.intro
self.d=DirTree()
self.timeout=6
setattr(self,"help_$",self._help_dollar)
def on_ctrl_c(self):
pass
def do_exit(self, arg):
exit()
return True
def do_quit(self, arg):
self.do_exit(arg)
def do_EOF(self, line):
exit()
return True
def do_ls(self,arg):
try:
path=(os.path.normpath(os.path.join(self.cd,arg))).replace("\\","/").split("/")
if(arg):
if(self.d.hasdir(path)):
ls(arg,self.d)
else:
printcolor(colors["red"],strings.dirtree.notadir)
else:
ls(self.cd,self.d)
except:
printcolor(colors["red"],strings.app.err+":"+getexc())
Log.printerror()
def do_dir(self,arg):
try:
dir_(self.cd,self.d)
except:
printcolor(colors["red"],strings.app.err+":"+getexc())
Log.printerror()
def do_la(self,arg):
try:
la(self.cd,self.d)
except:
printcolor(colors["red"],strings.app.err+":"+getexc())
Log.printerror()
def do_add(self,path):
try:
if(path):
if(os.path.isdir(path)):
self.d.adddir(path)
printcolor(colors["green"],strings.app.messages.addfilessuc % str(countdir(path)))
Log.info("Add dir:"+path)
else:
files=glob.glob(path)
print(files)
if(len(files)):
self.d.addfiles(files)
printcolor(colors["green"],strings.app.messages.addfilessuc % str(len(files)))
else:
printcolor(colors["red"],strings.dirtree.notafile)
Log.fail(strings.dirtree.notafile)
else:
self.help_add()
except AssertionError as e:
printcolor(colors["red"],str(e))
except:
Log.printerror()
printcolor(colors["red"],getexc())
def do_cd(self,path):
Log.info("Chdir:"+path)
if(path):
path=(os.path.normpath(os.path.join(self.cd,path))).replace("\\","/").split("/")
try:
self.d.finddir(path)
self.cd="/".join(path)
self.chdirupdate()
except ValueError:
printcolor(colors["red"],strings.dirtree.notadir)
except:
printcolor(colors["red"],strings.app.err+":"+getexc())
Log.printerror()
else:
print(self.cd)
def do_chdir(self,path):
self.do_cd(path)
def rmdir(self,path:str):
Log.info("Rm dir: "+path)
paths=path.replace("\\","/").split("/")
_d=self.d.root
_f=None
for i in paths:
if(i):
_f=_d
_d=_d.find(i)
_f.children.remove(_d)
if(not self.d.hasdir(self.cd.split("/"))):
self.do_cd("/")
def rmfileinroot(self,name:str):
for i in self.d.root.value:
if(i.relp==name):
self.d.root.value.remove(i)
break
def rmfile(self,path:str):
Log.info("Rm file: "+path)
paths=path.replace("\\","/").split("/")
_d=self.d.root
for i in paths[0:-1]:
if(i):
_d=_d.find(i)
if(len(paths)==2):#file is in root
self.rmfileinroot(paths[-1])
else:
_d.value.remove(paths[-1])
def do_rm(self,path:str):
try:
if(path):
path=(os.path.normpath(os.path.join(self.cd,path))).replace("\\","/").split("/")
if(self.d.hasdir(path) and path!=['','']):#['',''] mean root
if(YN()):
self.rmdir("/".join(path))
else:
printcolor(colors["red"],strings.app.terminate)
return
elif(self.d.hasfile(path)):
if(YN()):
self.rmfile("/".join(path))
else:
printcolor(colors["red"],strings.app.terminate)
else:
raise ValueError(strings.dirtree.notaobj)
else:
pass#help_rm
printcolor(colors["green"],strings.app.messages.rmfilessuc % "/".join(path))
except ValueError as e:
printcolor(colors["red"],strings.app.err+":"+str(e))
except:
Log.printerror()
printcolor(colors["red"],strings.app.err+":"+getexc())
def do_clear(self,arg:str):
console.clear()
def do_cls(self,arg:str):
self.do_clear(arg)
def do_cat(self,path:str):
self.do_type(path)
def do_type(self,path:str):
try:
path=(os.path.normpath(os.path.join(self.cd,path))).replace("\\","/").split("/")
assert self.d.hasfile(path),strings.dirtree.notafile
filep=str(self.d.findfile(path))
assert os.path.isfile(filep),strings.dirtree.notafile+":"+str(filep)
f=open(filep,encoding="utf-8",errors="ignore")
data=f.read(1024*1024*900)
f.close()
ext=os.path.splitext(filep)[1].replace(".","")
printcode(data,ext2lang[ext])
except (AssertionError,ValueError,UnicodeError) as e:
printcolor(colors["red"],str(e))
except:
printcolor(colors["red"],getexc())
def do_help(self,arg):
if(len(arg)):
cmd=arg
if(hasattr(self,"help_"+cmd)):
getattr(self,"help_"+cmd)()
else:
printcolor(colors["red"],strings.app.unkowncmd+arg)
else:
help_msg="add "+strings.app.messages.helps._help_msg.add2+"\n"+ \
"cd/chdir "+strings.app.messages.helps._help_msg.cd_chdir2+"\n"+ \
"clear/cls "+strings.app.messages.helps._help_msg.clear_cls2+"\n"+ \
"$ "+strings.app.messages.helps._help_msg.dollar2+"\n"+ \
"exit/quit "+strings.app.messages.helps._help_msg.exit_quit_EOF2+"\n"+ \
"help "+strings.app.messages.helps._help_msg.help2+"\n"+ \
"ls/dir "+strings.app.messages.helps._help_msg.ls_dir2+"\n"+ \
"rm "+strings.app.messages.helps._help_msg.rm2+"\n"+ \
"cat/type "+strings.app.messages.helps._help_msg.type2+"\n"+ \
"connect "+strings.app.messages.helps._help_msg.connect2+"\n"+ \
"bind "+strings.app.messages.helps._help_msg.bind+"\n"+\
"close "+strings.app.messages.helps._help_msg.close2+"\n"+ \
strings.app.messages.helps._help_msg.end_help
printcolor(colors["white"],help_msg,bold=True)
#network
def do_connect(self,arg):
if(_connected(self.c)):
print(strings.app.messages.connected)
return
if(not arg):
self.help_connect()
return
l=LoadingBar()
try:
#self.c=Client()
addr=parse_addr(arg)
printcolor(colors["yellow"],strings.app.messages.connecting % (str(addr[0])+":"+str(addr[1])))
l.start()
self.c.init(addr[0],addr[1])
printcolor(colors["green"],"\r"+strings.app.messages.after_conn % (str(addr[0])+":"+str(addr[1])))
l.stop()
except (AssertionError,OSError) as e:
l.stop()
self.c.close()
printcolor(colors["red"],str(e))
except:
l.stop()
self.c.close()
printcolor(colors["red"],getexc())
def do_ip(self,arg):
display_format = '\x1b['+str(colors["white"])+';1m%-30s:\x1b['+str(colors["green"])+'m %-20s\x1b[0m'
rg,rnn,rnm,ip,ipm=get_nic_info()
print(display_format % (strings.app.routing_gateway, rg))
print(display_format % (strings.app.routing_NIC, rnn))
print(display_format % (strings.app.routing_MAC, rnm))
print(display_format % (strings.app.routing_IP, ip))
print(display_format % (strings.app.routing_nmask, ipm))
Log.info(display_format % ("Routing Gateway:", rg))
Log.info(display_format % ("Routing NIC Name:", rnn))
Log.info(display_format % ("Routing NIC MAC Address:", rnm))
Log.info(display_format % ("Routing IP Address:", ip))
Log.info(display_format % ("Routing IP Netmask:", ipm))
def do_bind(self,arg:str):
try:
if(not len(arg.strip())):
display_format = '%-30s %-20s'
rg,rnn,rnm,ip,ipm=get_nic_info()
Log.info(display_format % ("Routing Gateway:", rg))
Log.info(display_format % ("Routing NIC Name:", rnn))
Log.info(display_format % ("Routing NIC MAC Address:", rnm))
Log.info(display_format % ("Routing IP Address:", ip))
Log.info(display_format % ("Routing IP Netmask:", ipm))
arg=ip
if(_connected(self.c)):
print(strings.app.messages.connected)
return
addr=parse_addr(arg)
if(not len(arg.strip())):
addr[0]=""
self._make_qrcode(addr)
print(addr[0]+":"+str(addr[1]))
server.init(addr[0],addr[1])
print(strings.app.messages.wait_conn % (addr[0]+":"+str(addr[1])))
server.accept()
print(strings.app.messages.after_conn % (self.c.sk.addr[0]+":"+str(self.c.sk.addr[1])))
server.close()
except:
Log.printerror()
printcolor(colors["red"],getexc())
def do_accept(self,arg):
client._accept_recv.set()
while(client._sending.is_set()):
time.sleep(0.05)
while(client._accept_recv.is_set()):
time.sleep(0.05)
def do_send(self,arg):
if(_connected(client)):
try:
client.setdirtree(self.d)
print(strings.app.messages.wait_accept)
client.sendfiles()
except:
log.printerror()
printcolor(colors["red"],getexc())
else:
print(strings.app.messages.unconnect)
def do_close(self,arg):
try:
if(not _connected(self.c)):
print(strings.app.messages.unconnect)
return
printcolor(colors["yellow"],strings.app.messages.really_want_close_connection,end="")
if(YN()):
self.c.close()
printcolor(colors["green"],strings.app.messages.closed)
else:
printcolor(colors["red"],strings.app.terminate)
except:
printcolor(colors["red"],getexc())
def help_exit(self,*args):
print(strings.app.messages.helps.exit)
def help_quit(self,*args):
print(strings.app.messages.helps.quit)
def help_EOF(self,*args):
print(strings.app.messages.helps.EOF)
def help_ls(self,*args):
print(strings.app.messages.helps.ls)
def help_dir(self,*args):
print(strings.app.messages.helps.dir)
def help_add(self,*args):
print(strings.app.messages.helps.add)
def help_cd(self,*args):
print(strings.app.messages.helps.cd)
def help_chdir(self,*args):
print(strings.app.messages.helps.chdir)
def help_rm(self,*args):
print(strings.app.messages.helps.rm)
def help_clear(self,*args):
print(strings.app.messages.helps.clear)
def help_cls(self,*args):
print(strings.app.messages.helps.cls)
def help_type(self,*args):
print(strings.app.messages.helps.type)
def help_cat(self,*args):
self.help_type(*args)
def help_help(self,*args):
print(strings.app.messages.helps.help)
def _help_dollar(self):
print(strings.app.messages.helps.dollar)
#network commands help
def help_connect(self,*args):
print(strings.app.messages.helps.connect)
def help_close(self,*args):
print(strings.app.messages.helps.close)
def default(self, line):
arg = line.strip()
if(arg.encode("utf-8")[0]==4):#Ctrl+D
exit()
return True
if(line.startswith("$")):
res=os.system(line[1:])
if(res!=0):
print(str(res)+":",end="")
else:
print(strings.app.unkowncmd+arg)
def keyboard_interrupt(self):#Ctrl+C
ctrlc(None,None)
def emptyline(self):
pass
def main(args):
try:
try:
Log.info("----------FileTP "+main_thread().name+" Start: argv="+str(sys.argv)+
",cwd="+str(os.getcwd())+
",mainthread_ident="+str(main_thread().ident)+
",pid:"+str(os.getpid())+
",time="+str(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()))+
"----------"
)
except:
pass
clientcmd=ClientCmd()
clientcmd.chdirupdate()
clientcmd.cmdloop()
except:
print("\n"+strings.app.error.fatalmsg.replace("{msg}",getexc()))
Log.fatal("----------UNHANDLED EXCEPTION!!!!!!!----------")
Log.printerror()
exit()
sys.exit(-1)
if(__name__=="__main__"):
main(sys.argv)
sys.exit(0)