-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathMainUI.py
1662 lines (1505 loc) · 73 KB
/
MainUI.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
# -*- coding: utf-8 -*-
"""
@Time : 2024-06-12 14:20
@Auth : No2Cat
@File :MainUI.py
@IDE :PyCharm
@DESC:
"""
import os
import sys
import time
import threading
import queue
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLineEdit, QTextEdit, QVBoxLayout, QWidget, \
QHBoxLayout, QTabWidget, QMenuBar, QAction, QLabel, QMessageBox, QComboBox, QTreeWidget, QTreeWidgetItem, \
QTableWidget, QSplitter, QTableWidgetItem, QHeaderView, QAbstractItemView, QMenu, QFileDialog, QDialogButtonBox, \
QDialog, QDesktopWidget
from PyQt5.QtGui import QFont, QTextCursor, QIcon
from PyQt5 import QtGui
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import resources_rc
from Common.CommonUtils import *
from Common.GenerateHtml import generate_basic_info_html
from Payloads.CMD import CMD
from Payloads.RealCMDPayloads import RealCMD
from Payloads.FileManagePayloads import FileManage
def setIcon(obj):
# 设置窗口图标
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(':img_res/cat_ico.svg'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
obj.setWindowIcon(icon)
def setFloderIcon(obj):
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap('./GUI/folder.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
obj.setIcon(icon)
def getPayloadFileContent(action_name):
""" 虚拟终端 """
file_path = './Payloads/' + action_name + '.py'
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
escaped_content = content
return escaped_content
except Exception as e:
return f"Error reading or processing file: {e}"
class VirtualTerminal(QTextEdit):
""" 虚拟终端UI和相关事件函数 """
def __init__(self):
super().__init__()
self.stop_threads = False
self.prompt_path = "/>"
self.command_start_pos = 0
self.prompt()
self.queue = queue.Queue()
def setMsfLabel(self, msgLabel):
self.msgLabel = msgLabel
def setBinPath(self, binPath):
self.binPath = binPath
def setTimeDelay(self, timeDelay):
self.timeDelay = timeDelay
def setShellInfo(self, shellInfo):
self.url = shellInfo['url']
self.password = shellInfo['password']
self.os_info = shellInfo['os']
def prompt(self):
self.append(self.prompt_path)
self.setCursorPosition()
def setCursorPosition(self):
""" 设置光标位置 """
cursor = self.textCursor()
cursor.movePosition(QTextCursor.End)
self.setTextCursor(cursor)
self.command_start_pos = cursor.position()
def keyPressEvent(self, event):
""" 键盘事件 检查光标位置 """
cursor = self.textCursor()
if cursor.position() < self.command_start_pos:
cursor.setPosition(self.command_start_pos)
self.setTextCursor(cursor)
if event.key() in (Qt.Key_Return, Qt.Key_Enter):
cursor.setPosition(self.command_start_pos, QTextCursor.KeepAnchor)
command = cursor.selectedText().strip()
self.runCommand(command)
elif event.key() == Qt.Key_Backspace:
if cursor.position() > self.command_start_pos:
super().keyPressEvent(event)
else:
super().keyPressEvent(event)
def runCommand(self, command='', init=False):
""" 命令执行 """
if command.lower() == 'exit shell':
QApplication.instance().quit()
return
try:
if init:
self.runner = CmdContent(self)
self.runner.outputReady.connect(self.appendOutput)
if self.os_info.lower() != 'windows':
self.runner.finished.connect(self.commandFinished)
self.runner.start()
return True
payload = RealCMD['writeCommand']
payload = payload.replace('$command$', command)
json_data = basic_info(payload, self.url, self.password)
if json_data is not None:
if 'status' in json_data and json_data['status'] == 'success':
self.runner = CmdContent(self)
self.runner.outputReady.connect(self.appendOutput)
if self.os_info.lower() != 'windows':
self.runner.finished.connect(self.commandFinished)
self.runner.start()
return True
pass
except Exception as e:
logger.error('[MainUI.VirtualTerminal.runCommand] ' + str(e))
self.msgLabel.setText('[runCommand] ' + str(e))
def appendOutput(self, output):
self.append(output)
self.setCursorPosition()
def commandFinished(self):
self.prompt()
def getCmdContent(self):
flag = True
fail_count = 0
while flag:
output = ''
try:
payload = RealCMD['readTerminal']
json_data = basic_info(payload, self.url, self.password)
if json_data is not None:
if 'status' in json_data and json_data['status'] == 'success':
if json_data['msg'] == '':
if fail_count < 0:
flag = False
self.setCursorPosition()
fail_count -= 1
else:
output = json_data['msg']
except Exception as e:
logger.exception('[MainUI.VirtualTerminal.getCmdContent] ' + str(e))
self.msgLabel.setText('异常' + str(e))
if output != '':
self.append(output)
self.setCursorPosition()
time.sleep(0.5)
class CmdContent(QThread):
""" 防止操作UI控件的时候因为阻塞造成卡顿 """
outputReady = pyqtSignal(str)
def __init__(self, vt):
super().__init__()
self.vt = vt
def run(self):
flag = True
fail_count = -1
line_count = 0
while flag:
output = ''
try:
payload = RealCMD['readTerminal']
json_data = basic_info(payload, self.vt.url, self.vt.password)
if json_data is not None:
if 'status' in json_data and json_data['status'] == 'success':
if json_data['msg'] == '':
if fail_count < 0:
flag = False
fail_count -= 1
else:
output = json_data['msg']
line_count += 1
except Exception as e:
logger.exception('[MainUI.VirtualTerminal.getCmdContent] ' + str(e))
self.vt.msgLabel.setText('异常' + str(e))
if output != '':
# if line_count == 1: # 去掉提示符第一行
# output.replace(self.vt.prompt_path, '这是提示符》')
if output[-2:] == '\r\n':
output = output[:-2]
if output[-1] == '\n':
output = output[:-1]
if output[-1] == '\r':
output = output[:-1]
self.outputReady.emit(output)
# self.vt.setCursorPosition()
time.sleep(0.8)
class CreateFileDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("创建文件")
self.setGeometry(100, 100, 400, 300)
self.file_name_label = QLabel("文件名:")
self.file_name_edit = QLineEdit()
self.file_content_label = QLabel("文件内容:")
self.file_content_edit = QTextEdit()
self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.button_box.accepted.connect(self.accept)
self.button_box.rejected.connect(self.reject)
layout = QVBoxLayout()
layout.addWidget(self.file_name_label)
layout.addWidget(self.file_name_edit)
layout.addWidget(self.file_content_label)
layout.addWidget(self.file_content_edit)
layout.addWidget(self.button_box)
self.setLayout(layout)
self.centerDialog()
def centerDialog(self):
# 获取屏幕的尺寸
screen_rect = QDesktopWidget().availableGeometry()
screen_center = screen_rect.center()
# 获取对话框的尺寸
dialog_rect = self.geometry()
# 计算新的对话框位置
dialog_rect.moveCenter(screen_center)
# 移动对话框到新的位置
self.move(dialog_rect.topLeft())
class CreateFolderDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("创建文件夹")
self.setGeometry(100, 100, 200, 100)
self.folder_name_label = QLabel("文件夹名:")
self.folder_name_edit = QLineEdit()
self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.button_box.accepted.connect(self.accept)
self.button_box.rejected.connect(self.reject)
layout = QVBoxLayout()
layout.addWidget(self.folder_name_label)
layout.addWidget(self.folder_name_edit)
layout.addWidget(self.button_box)
self.setLayout(layout)
self.centerDialog()
def centerDialog(self):
# 获取屏幕的尺寸
screen_rect = QDesktopWidget().availableGeometry()
screen_center = screen_rect.center()
# 获取对话框的尺寸
dialog_rect = self.geometry()
# 计算新的对话框位置
dialog_rect.moveCenter(screen_center)
# 移动对话框到新的位置
self.move(dialog_rect.topLeft())
class FileTableWidget(QTableWidget):
"""主表格窗口"""
def __init__(self, parent=None, data=None, logger=None, tree=None):
super(FileTableWidget, self).__init__(parent)
self.cols = [0, 2, 3, 4, 5, 6] # 数据居中列
self.data_map = {2: 'size', 3: 'created', 4: 'modified', 5: 'permissions'}
self.data = data
self.logger = logger
self.tree = tree
self.initUI()
self.initData()
self.event_func()
self.child_icon = QIcon('./GUI/folder.png')
self.root_icon = QIcon('./GUI/device.png')
self.file_icon = QIcon('./GUI/unknown.png')
def event_func(self):
"""槽函数"""
self.horizontalHeader().sectionClicked.connect(self.table_from_slotHeaderClicked) # 排序
self.customContextMenuRequested.connect(self.showContextMenu) # 右键菜单
def table_from_slotHeaderClicked(self, logicalIndex):
if logicalIndex == 0: # 如果点击的是第一列
return # 不排序
else:
order = self.horizontalHeader().sortIndicatorOrder()
self.sortItems(logicalIndex, order)
def initUI(self):
col_num = 8
col_name = ['编号', '名称', '大小', '创建时间', '修改时间', '权限(读/写/执行)', '属性', '文件路径']
self.setRowCount(0) # 设置初始行数
self.setColumnCount(col_num) # 设置初始列数
# 设置表头
self.setHorizontalHeaderLabels(col_name)
self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
qssTV = '''
# QTableWidget::item:hover{background-color:rgb(92,188,227,200)}"
"QTableWidget::item:selected{background-color:#1B89A1}"
"QHeaderView::section,QTableCornerButton:section{padding:3px; margin:0px; color:#DCDCDC; border:1px solid #242424; border-left-width:0px; border-right-width:1px; border-top-width:0px; border-bottom-width:1px; background:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #646464,stop:1 #525252); }"
"QTableWidget{background-color:white;border:none;}
'''
# 表格铺满
self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
# 禁止编辑
self.setEditTriggers(QAbstractItemView.NoEditTriggers)
# 选中整行
self.setSelectionBehavior(QAbstractItemView.SelectRows)
# 选中颜色
self.setStyleSheet("selection-background-color:darkblue;")
# 设置表头字体加粗
font = self.horizontalHeader().font()
# font.setBold(True)
font.setPointSize(10) # 设置表头字号为10
self.horizontalHeader().setFont(font)
self.setStyleSheet(qssTV)
# 隐藏默认竖向表头
self.verticalHeader().setHidden(True)
# 协调全选按钮与其他按钮事件的状态,避免冲突发生
self.needCheckAll = True
self.needCancelAll = True
# 表头外框线
self.horizontalHeader().setStyleSheet("color: rgb(0, 83, 128);border:1px solid rgb(210, 210, 210);")
# 交替行颜色
self.setAlternatingRowColors(True)
# 不允许拖动选择行
self.setSelectionMode(QTableWidget.SingleSelection)
# 设置表格的上下文菜单策略为自定义
self.setContextMenuPolicy(Qt.CustomContextMenu)
# 隐藏指定列
self.setColumnHidden(0, True)
self.setColumnHidden(7, True)
def showEvent(self, event):
"""显示事件"""
# 数据居中
for row in range(self.rowCount()):
for col in self.cols:
item = self.item(row, col)
if item:
item.setTextAlignment(Qt.AlignCenter)
# 在窗口显示时调整列宽度
self.setColumnWidth(1, 250)
# self.setColumnWidth(2, 80)
# 设置其他列的列宽可手动调节
self.horizontalHeader().setSectionResizeMode(1, QHeaderView.Interactive)
# self.horizontalHeader().setSectionResizeMode(3, QHeaderView.Interactive)
# self.horizontalHeader().setSectionResizeMode(4, QHeaderView.Interactive)
def getPermissions(self, permissions):
per = ''
if permissions['readable']:
per += 'R'
if permissions['writable']:
per += 'W'
if permissions['writable']:
per += 'E'
return per
def initData(self, trees=None):
""" 初始化数据 """
while self.rowCount() > 0:
self.removeRow(0)
if trees is not None:
tree_data = trees['dir']
tree_path = trees['node_path']
# self.treeData = tree_data
for i in range(len(tree_data)):
data = tree_data[i]
self.insertRow(i)
item = QTableWidgetItem(str(data['name']))
if data['is_directory']:
item.setIcon(self.child_icon)
else:
item.setIcon(self.file_icon)
self.setItem(i, 1, item)
self.setItem(i, 2, QTableWidgetItem(str(data['size'])))
self.setItem(i, 3, QTableWidgetItem(data['created']))
self.setItem(i, 4, QTableWidgetItem(data['modified']))
self.setItem(i, 5, QTableWidgetItem(self.getPermissions(data['permissions'])))
self.setItem(i, 6, QTableWidgetItem('文件夹' if data['is_directory'] else '文件'))
if self.tree.main_window.os_shell.lower() == 'windows':
self.setItem(i, 7, QTableWidgetItem(str(tree_path + str(data['name']) + "\\\\")))
else:
self.setItem(i, 7, QTableWidgetItem(str(tree_path + str(data['name']) + "/")))
# 数据居中
for row in range(self.rowCount()):
for col in self.cols:
item = self.item(row, col)
if item:
item.setTextAlignment(Qt.AlignCenter)
def refreshData(self):
""" 刷新数据 """
# 删除数据
while self.rowCount() > 0:
self.removeRow(0)
now_path = self.tree.filePathLineEdit.text()
if self.tree.main_window.os_shell.lower() == 'windows':
now_path = now_path.replace('\\', '\\\\')
if now_path[-1] != '\\':
now_path += '\\\\'
else:
if now_path[-1] != '/':
now_path += '/'
self.tree.on_item_clicked(item=None, column=None, node_path=now_path, flag=True) # 复用函数
# self.initData()
for row in range(self.rowCount()):
for col in self.cols:
item = self.item(row, col)
if item:
item.setTextAlignment(Qt.AlignCenter)
def copyData(self, item):
"""复制数据到粘贴板"""
# 获取点击的行号
row = item.row()
# 获取该行的内容
row_data = []
for column in range(self.columnCount()):
row_data.append(self.item(row, column).text() if self.item(row, column) else "")
# 获取系统剪贴板对象
clipboard = QApplication.clipboard()
# 将文本复制到剪贴板
clipboard.setText(row_data[1])
def delFileAction(self, row_data=None):
reply = QMessageBox.critical(self, "提示", "确认删除吗?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
if reply == QMessageBox.Yes:
try:
payload = FileManage['delete']
if row_data[-2] == '文件':
if self.tree.main_window.os_shell.lower() == 'windows':
row_data[-1] = row_data[-1][:-2]
else:
row_data[-1] = row_data[-1][:-1]
payload = payload.replace('$path$', row_data[-1])
url = self.tree.main_window.url_input.text().strip()
password = self.tree.main_window.password_input.text().strip()
json_data = basic_info(payload=payload, url=url, password=password)
if json_data is not None:
if 'status' in json_data and json_data['status'] == 'success':
self.tree.fileMsgLable.setText('[*] 删除成功')
self.refreshData()
except Exception as e:
logger.exception('[MainUI.FileTableWidget.delFileAction] ' + str(e))
self.tree.fileMsgLable.setText('[*] 异常查看日志')
else:
pass
def openFolder(self, row_data=None):
folder_path = row_data[-1]
self.tree.openDir(event=None, path=folder_path) # 复用函数
def save_file(self, file_name):
# 设置默认文件名
default_file_name = file_name
# 打开文件保存对话框,只选择保存位置
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
# file_path, _ = QFileDialog.getSaveFileName(self, "选择保存位置", default_file_name,
# "所有文件 (*)", options=options)
# if file_path:
# # 提取保存路径,不包含文件名
save_path = QFileDialog.getExistingDirectory(self, "选择保存位置", "")
if save_path:
full_path = f"{save_path}/{default_file_name}"
return full_path
def downloadFile(self, row_data=None):
file_path = row_data[-1]
try:
payload = FileManage['download']
if row_data[-2] == '文件':
if self.tree.main_window.os_shell.lower() == 'windows':
row_data[-1] = row_data[-1][:-2]
else:
row_data[-1] = row_data[-1][:-1]
file_name = row_data[1]
full_file_path = self.save_file(file_name)
if full_file_path:
url = self.tree.main_window.url_input.text().strip()
password = self.tree.main_window.password_input.text().strip()
flag = True
file_id = ''
all_chunks = []
while flag:
rpayload = payload.replace('$path$', row_data[-1]).replace('$file_id$', file_id)
json_data = basic_info(payload=rpayload, url=url, password=password)
if json_data is not None:
if 'status' in json_data:
if json_data['status'] == 'continue':
file_id = json_data['file_id']
all_chunks.append(json_data['msg'])
self.tree.fileMsgLable.setText('[*] 下载中')
elif json_data['status'] == 'success':
flag = False
self.tree.fileMsgLable.setText('[*] 下载完成')
for chunk in all_chunks:
chunk = base64.b64decode(chunk)
with open(full_file_path, 'ab+') as f:
f.write(chunk)
except Exception as e:
logger.exception('[MainUI.FileTableWidget.downloadFile] ' + str(e))
self.tree.fileMsgLable.setText('[*] 异常查看日志')
def read_file_as_binary(self, file_path):
try:
with open(file_path, 'rb') as file:
binary_data = file.read()
return binary_data
except FileNotFoundError as e:
logger.exception('[MainUI.FileTableWidget.read_file_as_binary] ' + str(e))
self.tree.fileMsgLable.setText(f"[*] The file {file_path} was not found.")
except IOError as e:
logger.exception('[MainUI.FileTableWidget.read_file_as_binary] ' + str(e))
self.tree.fileMsgLable.setText(f"[*] An error occurred while reading the file {file_path}.")
def split_and_encode_binary_data(self, binary_data, chunk_size=2 * 1024 * 1024):
# 分割并编码二进制数据
encoded_data_dict = {}
total_size = len(binary_data)
num_chunks = (total_size + chunk_size - 1) // chunk_size # 计算分块数
for i in range(num_chunks):
chunk = binary_data[i * chunk_size: (i + 1) * chunk_size]
encoded_chunk = base64.b64encode(chunk).decode('utf-8')
encoded_data_dict[f'chunk_{i + 1}'] = encoded_chunk
return encoded_data_dict
def showFileDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.ReadOnly
fileName, _ = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "",
"All Files (*)", options=options)
if fileName:
return fileName
def uploadFile(self):
""" 文件上传 """
try:
current_path = self.tree.filePathLineEdit.text().replace('\\', '\\\\')
if self.tree.main_window.os_shell.lower() == 'windows':
now_path = current_path.replace('\\', '\\\\')
if now_path[-1] != '\\':
now_path += '\\\\'
else:
if current_path[-1] != '/':
current_path += '/'
local_file_path = self.showFileDialog()
if local_file_path is None:
pass
else:
(path, filename) = os.path.split(local_file_path)
remote_file_path = current_path + filename
file_id = ''
payload = FileManage['upload']
url = self.tree.main_window.url_input.text().strip()
password = self.tree.main_window.password_input.text().strip()
# 读取文件
binary_data = self.read_file_as_binary(local_file_path)
if binary_data:
# 切割文件
encoded_data_dict = self.split_and_encode_binary_data(binary_data)
for key, value in encoded_data_dict.items():
self.tree.fileMsgLable.setText(f"[*] {key}: {len(value)} characters: ")
# 文件上传包
rpayload = payload.replace('$file_id$', file_id).replace('$content$', value).replace('$path$',
remote_file_path)
json_data = basic_info(payload=rpayload, url=url, password=password)
if json_data is not None:
if 'status' in json_data and 'success' in json_data['status']:
file_id = json_data['file_id']
self.tree.fileMsgLable.setText(
'[*] ' + str(json_data['status']) + ' - ' + str(json_data['msg']))
elif 'status' in json_data and 'error' in json_data['status']:
self.tree.fileMsgLable.setText('[*] 上传失败' + json_data['msg'])
# self.tree.fileMsgLable.setText('[*] 上传完成')
self.refreshData() # 刷新
except Exception as e:
logger.exception('[MainUI.FileTableWidget.uploadFile] ' + str(e))
self.tree.fileMsgLable.setText('[*] 异常查看日志' + str(e))
def createFolder(self):
""" 创建文件夹 """
try:
current_path = self.tree.filePathLineEdit.text().replace('\\', '\\\\')
if self.tree.main_window.os_shell.lower() == 'windows':
now_path = current_path.replace('\\', '\\\\')
if now_path[-1] != '\\':
now_path += '\\\\'
else:
if current_path[-1] != '/':
current_path += '/'
dialog = CreateFolderDialog(self)
if dialog.exec() == QDialog.Accepted:
folder_name = dialog.folder_name_edit.text()
folder_path = current_path + folder_name
url = self.tree.main_window.url_input.text().strip()
password = self.tree.main_window.password_input.text().strip()
payload = FileManage['mkdir']
payload = payload.replace('$path$', folder_path)
json_data = basic_info(payload=payload, url=url, password=password)
if 'status' in json_data and json_data['status'] == 'success':
QMessageBox.information(self, "创建成功", f"{folder_path}")
self.refreshData()
except Exception as e:
logger.exception('[MainUI.FileTableWidget.createFile] ' + str(e))
self.tree.fileMsgLable.setText('[*] 异常查看日志' + str(e))
def createFile(self):
try:
current_path = self.tree.filePathLineEdit.text().replace('\\', '\\\\')
if self.tree.main_window.os_shell.lower() == 'windows':
now_path = current_path.replace('\\', '\\\\')
if now_path[-1] != '\\':
now_path += '\\\\'
else:
if current_path[-1] != '/':
current_path += '/'
dialog = CreateFileDialog(self)
if dialog.exec() == QDialog.Accepted:
file_name = dialog.file_name_edit.text()
file_path = current_path + file_name
file_content = dialog.file_content_edit.toPlainText()
file_content = base64.b64encode(file_content.encode('utf-8')).decode('utf-8')
url = self.tree.main_window.url_input.text().strip()
password = self.tree.main_window.password_input.text().strip()
payload = FileManage['touch']
payload = payload.replace('$path$', file_path).replace('$content$', file_content).replace('$file_id$',
'')
json_data = basic_info(payload=payload, url=url, password=password)
if 'status' in json_data and json_data['status'] == 'success':
QMessageBox.information(self, "创建成功", f"{file_name}")
self.refreshData()
except Exception as e:
logger.exception('[MainUI.FileTableWidget.createFile] ' + str(e))
self.tree.fileMsgLable.setText('[*] 异常查看日志' + str(e))
def showContextMenu(self, position):
"""右键菜单"""
item = self.itemAt(position)
contextMenu = QMenu(self)
# 设置菜单项字体
font = QFont()
font.setPointSize(9) # 设置字体大小
contextMenu.setFont(font)
# 获取该行的内容
row_data = []
if item:
# 获取点击的行号
row = item.row()
for column in range(self.columnCount()):
row_data.append(self.item(row, column).text() if self.item(row, column) else "")
else:
pass
if item:
# 如果点击的是文件夹
if row_data[-2] == '文件夹':
openFolderBtn = contextMenu.addAction("打开目录")
contextMenu.addSeparator()
createFileBtn = contextMenu.addAction("创建文件")
contextMenu.addSeparator()
createFolderBtn = contextMenu.addAction("创建文件夹")
contextMenu.addSeparator()
uploadFileBtn = contextMenu.addAction("上传文件")
contextMenu.addSeparator()
if item:
if row_data[-2] == '文件':
downloadFileBtn = contextMenu.addAction("下载文件")
contextMenu.addSeparator()
if item:
delBtn = contextMenu.addAction("删除")
contextMenu.addSeparator()
cpyBtn = contextMenu.addAction("复制名称")
contextMenu.addSeparator()
refresh = contextMenu.addAction("刷新")
action = contextMenu.exec_(self.mapToGlobal(position))
if item:
if row_data[-2] == '文件夹':
if action == openFolderBtn:
self.openFolder(row_data)
if row_data[-2] == '文件':
if action == downloadFileBtn:
self.downloadFile(row_data)
if action == delBtn:
self.delFileAction(row_data)
elif action == cpyBtn:
self.copyData(item)
if action == createFileBtn:
self.createFile()
elif action == createFolderBtn:
self.createFolder()
elif action == uploadFileBtn:
self.uploadFile()
elif action == refresh:
self.refreshData()
class TreeTableFileManage(QWidget):
def __init__(self, parent=None, main_window=None):
super(TreeTableFileManage, self).__init__(parent)
self.initUI()
self.main_window = main_window
# 保存结构
self.item_info = dict()
def initUI(self):
# 创建一个 QSplitter 用于分割树形控件和表格控件
self.splitter = QSplitter(self)
# 创建树形控件
self.tree = QTreeWidget()
self.tree.setHeaderLabels(["目录"])
self.tree.itemDoubleClicked.connect(self.on_item_clicked) # 连接节点点击信号到槽函数
self.splitter.addWidget(self.tree)
# 展开所有节点
# self.tree.expandAll()
filePathLayout = QHBoxLayout()
self.filePathLabel = QLabel("路径:")
self.filePathLabel.setFont(QFont("Arial", 10))
self.filePathLineEdit = QLineEdit()
self.filePathLineEdit.setPlaceholderText("文件路径")
self.filePathLineEdit.setFixedHeight(30)
self.filePathLineEdit.setFixedHeight(30)
self.filePathLineEdit.setFont(QFont("Arial", 14))
self.filePathLineEdit.setStyleSheet("""
QLineEdit {
border: 1px solid #3E3E3E;
border-radius: 5px;
padding: 5px;
font-size: 18px; padding: 2px;
}
QLineEdit:focus {
border-color: #0078D7;
}
""")
self.filePathButton = QPushButton("打开")
self.filePathButton.setFont(QFont("Arial", 12))
self.filePathButton.setFixedHeight(30)
self.filePathButton.setStyleSheet("""
QPushButton {
background-color: #0078D7;
color: white;
padding: 5px 15px;
border-radius: 5px;
margin-left: 20px;
}
QPushButton:hover {
background-color: #005BB5;
}
QPushButton:pressed {
background-color: #003E8C;
}
""")
self.filePathButton.clicked.connect(self.openDir)
filePathLayout.addWidget(self.filePathLabel)
filePathLayout.addWidget(self.filePathLineEdit)
filePathLayout.addWidget(self.filePathButton)
# 创建表格控件
self.tableWidget = QWidget()
self.tableLayout = QVBoxLayout()
self.tableWidget.setLayout(self.tableLayout)
self.table = FileTableWidget(tree=self)
self.fileMsgLable = QLabel()
self.fileMsgLable.setText('MSG')
self.tableLayout.addLayout(filePathLayout)
self.tableLayout.addWidget(self.table)
self.tableLayout.addWidget(self.fileMsgLable)
self.splitter.addWidget(self.tableWidget)
# 设置 QSplitter 比例
self.splitter.setStretchFactor(0, 1)
self.splitter.setStretchFactor(1, 3)
self.splitter.setSizes([150, 600])
# 创建一个 QVBoxLayout 并将 QSplitter 添加进去
self.layout = QVBoxLayout(self)
self.layout.addWidget(self.splitter)
self.setLayout(self.layout)
def setShell(self, data):
self.url = data['url']
self.password = data['password']
def get_tree_structure(self):
""" 获取目录层次结构 """
def recurse(item):
structure = {item.text(0): {}}
for i in range(item.childCount()):
structure[item.text(0)].update(recurse(item.child(i)))
return structure
tree_structure = {}
root = self.tree.invisibleRootItem()
for i in range(root.childCount()):
tree_structure.update(recurse(root.child(i)))
return tree_structure
def add_tree_child(self, parent, child_name):
child = QTreeWidgetItem(parent)
child_icon = QIcon('./GUI/folder.png')
child.setText(0, str(child_name))
child.setIcon(0, child_icon) # 设置图标
return child
def add_tree_root(self, root_name):
root = QTreeWidgetItem(self.tree)
root_icon = QIcon('./GUI/device.png')
root.setText(0, str(root_name))
root.setIcon(0, root_icon) # 设置图标
return root
def get_node_hierarchy(self, item):
""" 获取节点的层次结构 """
hierarchy = []
while item is not None:
hierarchy.insert(0, item.text(0))
item = item.parent()
return hierarchy
def node_path_to_tree_item(self, node_path):
""" 将路径遍历为tree结构的节点 不存在就添加为节点 """
if self.main_window.os_shell.lower() == 'windows':
node_dict = node_path.split('\\\\')
root = node_dict[0] + '\\\\'
node_dict[0] = root
else:
node_dict = node_path.split('/')
root = '/'
node_dict[0] = root
path = node_dict[0]
for i in range(len(node_dict)):
if i > 0 and node_dict[i] != '':
parent_path = path
if self.main_window.os_shell.lower() == 'windows':
path += node_dict[i] + '\\\\'
else:
path += node_dict[i] + '/'
if path in self.item_info:
pass
else:
child = self.add_tree_child(parent=self.item_info[parent_path]['item'], child_name=node_dict[i])
self.item_info[path] = dict()
self.item_info[path]['item'] = child
def openDir(self, event, path=''):
if path == '':
node_path = self.filePathLineEdit.text()
if self.main_window.os_shell.lower() == 'windows':
node_path = node_path.replace('\\', '\\\\')
if node_path[-1] != '\\':
node_path += '\\\\'
else:
if node_path[-1] != '/':
node_path += '/'
else:
node_path = path
if node_path in self.item_info and 'dir' in self.item_info[node_path]:
item_dir = dict()
item_dir['dir'] = self.item_info[node_path]['dir']
item_dir['node_path'] = str(node_path)
self.table.initData(item_dir)
else:
try:
payload = FileManage['dir']
payload = payload.replace('$path$', str(node_path))
url = self.main_window.url_input.text().strip()
password = self.main_window.password_input.text().strip()
json_data = basic_info(payload=payload, url=url, password=password)
if json_data is not None:
if 'status' in json_data and json_data['status'] == 'success':
directory_details = json_data['msg']
# 添加到item_info 建立表格和树形结构关系
self.node_path_to_tree_item(node_path) # 将打开的文件夹路径添加到tree中
# 遍历当前的路径添加节点到tree中
if node_path not in self.item_info:
self.item_info[node_path] = dict()
self.item_info[node_path]['dir'] = directory_details # 以节点路径作为键
for directory in directory_details:
if directory['is_directory']:
child = self.add_tree_child(parent=self.item_info[node_path]['item'],
child_name=directory['name'])
# 将子节点也添加到item_info中
if self.main_window.os_shell.lower() == 'windows':
self.item_info[str(node_path + directory['name'] + '\\\\')] = dict()
self.item_info[str(node_path + directory['name'] + '\\\\')]['item'] = child
else:
self.item_info[str(node_path + directory['name'] + '/')] = dict()
self.item_info[str(node_path + directory['name'] + '/')]['item'] = child
item_dir = dict()
item_dir['dir'] = self.item_info[node_path]['dir']
item_dir['node_path'] = str(node_path)
self.filePathLineEdit.setText(str(node_path.replace('\\\\', '\\')))
self.table.initData(item_dir)
else:
self.fileMsgLable.setText('[*] 异常查看日志')
except Exception as e:
logger.exception('[MainUI.TreeTableFileManage.openDir] ' + str(e))
self.fileMsgLable.setText('[*] 异常查看日志')
# 定位到树形结构
if 'item' in self.item_info[node_path]:
# 递归收起所有节点
self.collapse_all_nodes(self.tree.invisibleRootItem()) # 收起
self.tree.expandItem(self.item_info[node_path]['item']) # 展开
self.tree.scrollToItem(self.item_info[node_path]['item']) # 滚动
def collapse_all_nodes(self, item):
"""递归收起所有节点"""
for i in range(item.childCount()):
child = item.child(i)
self.tree.collapseItem(child)
self.collapse_all_nodes(child)
def delete_all_children(self, current_item):
"""删除当前节点的所有子节点"""
if current_item:
while current_item.childCount() > 0:
current_item.takeChild(0)
def on_item_clicked(self, item, column, node_path='', flag=False):
""" 双击节点事件: 获取节点下的目录信息 """
if node_path == '':
node_hierarchy = self.get_node_hierarchy(item)
root_path = node_hierarchy[0]
node_path = root_path
if self.main_window.os_shell.lower() == 'windows':
node_path = node_path[:-1] + '\\\\' # 获取盘符
for node in node_hierarchy[1:]:
node_path += node + '\\\\'
else:
for node in node_hierarchy[1:]:
node_path += node + '/'
# 判断该节点下是否存在子节点 并且将该点击事件函数作为了刷新的事件函数
# if item.childCount() > 0:
if node_path in self.item_info and 'dir' in self.item_info[node_path] and not flag:
pass
else:
if not self.injectStaus:
self.fileMsgLable.setText('[*] 函数未注入')
else:
payload = FileManage['dir']
payload = payload.replace('$path$', str(node_path))
url = self.main_window.url_input.text().strip()
password = self.main_window.password_input.text().strip()
json_data = basic_info(payload=payload, url=url, password=password)
if json_data is not None:
if 'status' in json_data and json_data['status'] == 'success':
directory_details = json_data['msg']
if node_path not in self.item_info:
self.item_info[node_path] = dict()
# 这里区分刷新动作和点击动作 刷新的时候是已经有了节点 所以删除更新要覆盖掉item
# 如果是点击事件 这里就是添加节点需要为节点添加记录
if flag:
self.delete_all_children(self.item_info[node_path]['item'])
item = self.item_info[node_path]['item']
else: