forked from aaPanel/BaoTa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpanelPlugin.py
2976 lines (2674 loc) · 122 KB
/
panelPlugin.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
#-------------------------------------------------------------------
# 宝塔Linux面板
#-------------------------------------------------------------------
# Copyright (c) 2015-2099 宝塔软件(http://bt.cn) All rights reserved.
#-------------------------------------------------------------------
# Author: hwliang <[email protected]>
#-------------------------------------------------------------------
import public,os,sys,json,time,psutil,re,shutil,requests
from BTPanel import session,cache,send_file
from pluginAuth import Plugin
if sys.version_info[0] == 3: from importlib import reload
class mget: pass
class panelPlugin:
__isTable = None
__install_path = None
__tasks = None
__list = 'data/list.json'
__type = 'data/type.json'
__index = 'config/index.json'
__link = 'config/link.json'
__product_list = None
__plugin_list = None
__exists_names = {}
__plugin_s_list = []
__panel_path = '/www/server/panel'
__plugin_info = None
__plugin_name = None
__plugin_object = None
__plugin_list = None
__panel_path = '/www/server/panel'
__plugin_path = __panel_path + '/plugin/'
__plugin_save_file = __panel_path + '/data/plugin_bin.pl'
__api_root_url = 'https://api.bt.cn'
__api_url = __api_root_url+ '/panel/get_plugin_list'
__download_url = __api_root_url + '/down/download_plugin'
__download_d_main_url = __api_root_url + '/down/download_plugin_main'
_check_url=__api_root_url+'/panel/get_soft_list_status'
__tmp_path = __panel_path + '/temp/'
_unbinding_url=__api_root_url+'/panel/get_unbinding'
__plugin_timeout = 3600
__is_php = False
__install_opt = 'i'
__pid = 0
__path_error=__panel_path+'/data/error_pl.pl'
__error_html='/www/server/panel/BTPanel/templates/default/block_error.html'
__sub_rules = []
__dict__ = None
__replace_rule = []
pids = None
ROWS = 15
def __init__(self):
self.__install_path = '/www/server/panel/plugin'
self.__replace_rule = public.get_plugin_replace_rules()
def input_package(self,get):
'''
@name 导入插件包到面板
@author hwliang<2021-06-23>
@param filename<string> 解包后的文件路径
@param plugin_name<string> 插件名称
@param install_opt<string> 安装选项 i.安装 r.修复 u.升级 默认: i
@return dict
'''
return self.__input_plugin(get.tmp_path,get.plugin_name,get.install_opt)
def __install_plugin(self,upgrade_plugin_name,upgrade_version = None):
'''
@name 安装指定插件
@author hwliang<2021-06-21>
@param upgrade_plugin_name<string> 插件名称
@param upgrade_version<string> 插件版本 版本号.指定版本号 / tls.最新正式版 / beta.最新测试版
@return dict
'''
self.__plugin_name = upgrade_plugin_name
plugin_info = self.__get_plugin_find(upgrade_plugin_name)
if not plugin_info:
raise public.PanelError('指定插件不存在,无法安装!')
if not plugin_info['versions']:
raise public.PanelError('指定插件当前未发布版本信息,请稍候再安装!')
if not upgrade_version:
upgrade_version = '{}.{}'.format(plugin_info['versions'][0]['m_version'], plugin_info['versions'][0]['version'])
filename = self.__download_plugin(upgrade_plugin_name,upgrade_version)
return self.__unpackup_plugin(filename)
def __repair_plugin(self,upgrade_plugin_name,upgrade_version = None):
'''
@name 修复指定插件
@author hwliang<2021-06-21>
@param upgrade_plugin_name<string> 插件名称
@param upgrade_version<string> 插件版本 版本号.指定版本号 / tls.最新正式版 / beta.最新测试版
@return dict
'''
self.__install_opt = 'r'
return self.__install_plugin(upgrade_plugin_name,upgrade_version)
def __upgrade_plugin(self,upgrade_plugin_name,upgrade_version = None):
'''
@name 升级到指定版本
@author hwliang<2021-06-21>
@param upgrade_plugin_name<string> 插件名称
@param upgrade_version<string> 插件版本 版本号.指定版本号 / tls.最新正式版 / beta.最新测试版
@return dict
'''
self.__install_opt = 'u'
return self.__install_plugin(upgrade_plugin_name,upgrade_version)
def __check_dependnet(self,upgrade_plugin_name):
'''
@name 检查指定插件的依赖安装情况
@author hwliang<2021-06-21>
@param upgrade_plugin_name<string> 插件名称
@return dict
'''
plugin_info = self.__get_plugin_find(upgrade_plugin_name)
if not plugin_info: return {}
if not plugin_info['dependnet']: return {}
deployment_list = {}
for dependnet_plu_name in plugin_info['dependnet'].split(','):
p_info = self.__get_plugin_find(dependnet_plu_name)
if not p_info: continue
deployment_list[dependnet_plu_name] = os.path.exists(p_info['install_checks'])
return deployment_list
def __get_plugin_info(self,upgrade_plugin_name):
'''
@name 获取插件信息
@author hwliang<2021-06-15>
@param upgrade_plugin_name<string> 插件名称
@return dict
'''
plugin_info_file = '{}/{}/info.json'.format(self.__plugin_path,upgrade_plugin_name)
if not os.path.exists(plugin_info_file): return {}
info_body = self.__read_file(plugin_info_file)
if not info_body: return {}
plugin_info = json.loads(info_body)
return plugin_info
def __get_update_msg(self,upgrade_plugin_name,upgrade_version):
'''
@name 检查指定插件版本更新日志
@author hwliang<2021-06-21>
@param upgrade_plugin_name<string> 插件名称
@param upgrade_version<string> 插件版本
@return string
'''
plugin_update_msg = ''
plugin_info = self.__get_plugin_find(upgrade_plugin_name)
if not plugin_info: return plugin_update_msg
for _version_info in plugin_info['versions']:
l_version = '{}.{}'.format(_version_info['m_version'],_version_info['version'])
if l_version == upgrade_version:
plugin_update_msg = _version_info['update_msg']
break
return plugin_update_msg
def __get_plugin_upgrades(self,upgrade_plugin_name):
'''
@name 检查指定插件最近10条更新日志
@author hwliang<2021-06-21>
@param upgrade_plugin_name<string> 插件名称
@return list
'''
plugin_info = self.__get_plugin_find(upgrade_plugin_name)
if not plugin_info: return []
try:
upgrade_list = public.httpPost(self.__api_root_url + '/down/get_update_msg',{'soft_id':plugin_info['id']})
return json.loads(upgrade_list)
except:
return []
def __set_pyenv(self,filename):
'''
@name 设置安全脚本的Python环境变量
@param filename<string> 安装脚本文件名
@return bool
'''
if not os.path.exists(filename): return False
env_py = self.__panel_path + '/pyenv/bin'
if not os.path.exists(env_py): return False
temp_file = public.readFile(filename)
env_path=['PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin']
rep_path=['PATH={}/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin'.format(env_py+":")]
for index_key in range(len(env_path)):
temp_file = temp_file.replace(env_path[index_key],rep_path[index_key])
public.writeFile(filename,temp_file)
return True
def __copy_path(self,src_path,dst_path,input_not_substituted = []):
'''
@name 复制文件夹
@author hwliang<2021-06-24>
@param src_path<string> 源路径
@param dst_path<string> 目标路径
@param input_not_substituted<list> 不复盖规则
@return bool
'''
if not os.path.exists(src_path):
raise public.PanelError('指定源目录不存在:{}'.format(src_path))
if not os.path.exists(dst_path):
os.makedirs(dst_path,384)
for tmp_list_name in os.listdir(src_path):
tmp_src_path = os.path.join(src_path,tmp_list_name)
tmp_dst_path = os.path.join(dst_path,tmp_list_name)
# 目标文件存在,且被不覆盖规则匹配,则跳过此文件
if os.path.exists(tmp_dst_path):
if self.__sub_check(tmp_src_path,input_not_substituted):
continue
# 递归目录
if os.path.isdir(tmp_src_path):
self.__copy_path(tmp_src_path,tmp_dst_path,input_not_substituted)
continue
# 复制文件
shutil.copyfile(tmp_src_path,tmp_dst_path)
self.__replace_check(tmp_dst_path)
return True
def __replace_check(self,filename):
'''
@name 检查文件内容是否需要替换
@author hwliang<2021-06-28>
@param filename<string> 文件全路径
@return void
'''
# 检查前置替换关系
rkey = 'replace_files'
if not rkey in self.__plugin_info: return
if not self.__plugin_info[rkey]: return
if not self.__replace_rule: return
# 指定文件名是否需要替换
p_file_name = os.path.basename(filename)
if not p_file_name in self.__plugin_info[rkey]: return
# 开始替换文件内容
f_body = public.readFile(filename)
is_write = False
for temp_i_rule in self.__replace_rule:
if f_body.find(temp_i_rule['find']) == -1: continue
f_body = f_body.replace(temp_i_rule['find'],temp_i_rule['replace'])
is_write = True
# 是否需要写入数据
if is_write: public.writeFile(filename,f_body)
def __sub_check(self,filename,input_not_substituted):
'''
@name 不覆盖规则检查
@author hwliang<2021-06-24>
@param filename<string> 文件或文件夹名称
@param input_not_substituted<list> 不复盖规则
@return bool
'''
is_file = os.path.isfile(filename)
# 不匹配全路径
f_i_name = os.path.basename(filename)
for temp_i_rule in self.__format_sub_rule(input_not_substituted):
if temp_i_rule['fd'] == 'd' and is_file: continue
if temp_i_rule['fd'] == 'f' and not is_file: continue
# 完全匹配?
if temp_i_rule['type'] == 'find':
if f_i_name == temp_i_rule['rule']:
return True
# 正则表达式?
elif temp_i_rule['type'] == 're':
if temp_i_rule['rule'].search(f_i_name):
return True
return False
def __format_sub_rule(self,input_not_substituted):
'''
@name 解析覆盖规则
@author hwliang<2021-06-24>
@param input_not_substituted<list> 不复盖规则
@return list
'''
if self.__sub_rules:
return self.__sub_rules
self.__sub_rules = []
for item_sub_rule in input_not_substituted:
temp_i_rule = {}
f_sub_2 = item_sub_rule[-2:]
_type_fd = '' if f_sub_2[0] != '|' else f_sub_2[1]
temp_i_rule['fd'] = _type_fd
if item_sub_rule[:3] == 're|':
temp_i_rule['type'] = 're'
if _type_fd:
item_re_string = item_sub_rule[3:-2]
else:
item_re_string = item_sub_rule[3:]
temp_i_rule['rule'] = re.compile(item_re_string)
else:
temp_i_rule['type'] = 'find'
if _type_fd:
temp_i_rule['rule'] = item_sub_rule[:-2]
else:
temp_i_rule['rule'] = item_sub_rule
self.__sub_rules.append(temp_i_rule)
return self.__sub_rules
def __read_file(self,filename,open_mode = 'r'):
'''
@name 读取指定文件
@author hwliang<2021-06-16>
@param filename<string> 文件名
@param mode<string> 打开模式, 默认: r
@return bytes or string
'''
f_object = open(filename,mode=open_mode)
file_body = f_object.read()
f_object.close()
return file_body
def __input_plugin(self,filename,input_plugin_name,input_install_opt = 'i'):
'''
@name 导入插件包到面板
@author hwliang<2021-06-21>
@param filename<string> 解包后的文件路径
@param input_plugin_name<string> 插件名称
@param input_install_opt<string> 安装选项 i.安装 r.修复 u.升级 默认: i
@return dict
'''
if public.is_debug():
mod_key = input_plugin_name + '_main'
if mod_key in sys.modules:
return public.returnMsg(False,'当前插件正在被使用,请重启面板后重试')
opts = {'i':'安装','u':'更新','r':'修复'}
i_opts = {'i':'install.sh install','u':'upgrade.sh','r':'repair.sh'}
if not os.path.exists(filename): return public.returnMsg(False,'临时文件不存在,请重新上传!')
plugin_path_panel = self.__plugin_path + input_plugin_name
if input_install_opt == 'r' and os.path.exists(filename + '/' + i_opts[input_install_opt]):
i_opts[input_install_opt] = 'install.sh install'
if input_install_opt == 'u' and os.path.exists(filename + '/' + i_opts[input_install_opt]):
i_opts[input_install_opt] = 'install.sh install'
if not os.path.exists(plugin_path_panel): os.makedirs(plugin_path_panel)
p_info = public.ReadFile(filename + '/info.json')
if not p_info: raise public.PanelError(filename)
p_info = json.loads(p_info)
if not 'not_substituted' in p_info: p_info['not_substituted'] = []
self.__plugin_info = p_info
self.__copy_path(filename,plugin_path_panel,p_info['not_substituted'])
self.__set_pyenv(plugin_path_panel + '/install.sh')
public.ExecShell('cd ' + plugin_path_panel + ' && bash {} &> /tmp/panelShell.pl'.format(i_opts[input_install_opt]))
# 清理临时文件
if os.path.exists(filename): shutil.rmtree(filename)
if p_info:
# 复制图标
icon_sfile = plugin_path_panel + '/icon.png'
icon_dfile = self.__panel_path + '/BTPanel/static/img/soft_ico/ico-{}.png'.format(input_plugin_name)
if os.path.exists(plugin_path_panel + '/icon.png'):
shutil.copyfile(icon_sfile,icon_dfile)
public.WriteLog('软件管理','{}插件[{}]'.format(opts[input_install_opt],p_info['title']))
# 标记一次重新加载插件
reload_file = os.path.join(self.__panel_path,'data/{}.pl'.format(input_plugin_name))
public.writeFile(reload_file,'')
pluginInfo = self.__get_plugin_find(input_plugin_name)
public.httpPost(public.GetConfigValue('home') + '/api/panel/plugin_total',{"pid":pluginInfo['id'],'p_name':input_plugin_name},3)
return public.returnMsg(True,'{}成功!'.format(opts[input_install_opt]))
# 安装失败清理安装文件?
if os.path.exists(plugin_path_panel): shutil.rmtree(plugin_path_panel)
return public.returnMsg(False,'{}失败!'.format(opts[input_install_opt]))
def __unpackup_plugin(self,tmp_file):
'''
@name 解包插件包
@author hwliang<2021-06-21>
@param tmp_file<string> 下载好的保存路径,从self.download_plugin方法中获取
@return dict
'''
s_tmp_path = self.__tmp_path
if not os.path.exists(s_tmp_path):
os.makedirs(s_tmp_path,mode=384)
if tmp_file:
if not os.path.exists(tmp_file): return public.returnMsg(False,'文件下载失败!')
import panelTask as plu_panelTask
plu_panelTask.bt_task()._unzip(tmp_file,s_tmp_path,'','/dev/null')
os.remove(tmp_file)
s_tmp_path = os.path.join(s_tmp_path,self.__plugin_name)
p_info = os.path.join(s_tmp_path,'info.json')
if not os.path.exists(p_info):
d_path = None
for plugin_df in os.walk(s_tmp_path):
if len(plugin_df[2]) < 3: continue
if not 'info.json' in plugin_df[2]: continue
if not 'install.sh' in plugin_df[2]: continue
if not os.path.exists(plugin_df[0] + '/info.json'): continue
d_path = plugin_df[0]
if d_path:
s_tmp_path = d_path
p_info = s_tmp_path + '/info.json'
try:
try:
plugin_data_info = json.loads(public.ReadFile(p_info))
except:
plugin_data_info = json.loads(self.__read_file(p_info))
plugin_data_info['size'] = public.get_path_size(s_tmp_path)
if not 'author' in plugin_data_info: plugin_data_info['author'] = '宝塔'
if not 'home' in plugin_data_info: plugin_data_info['home'] = 'https://www.bt.cn'
p_info_file = self.__plugin_path + plugin_data_info['name'] + '/info.json'
plugin_data_info['old_version'] = '0'
plugin_data_info['tmp_path'] = s_tmp_path
if os.path.exists(p_info_file):
try:
old_info = json.loads(public.ReadFile(p_info_file))
plugin_data_info['old_version'] = old_info['versions']
except:pass
except:
public.ExecShell("rm -rf " + s_tmp_path + '/*')
return public.get_error_object(plugin_name=self.__plugin_name)
plugin_data_info['install_opt'] = self.__install_opt
plugin_data_info['dependnet'] = self.__check_dependnet(plugin_data_info['name'])
plugin_data_info['update_msg'] = self.__get_update_msg(plugin_data_info['name'],plugin_data_info['versions'])
not_check = self.not_cpu_or_bit(plugin_data_info)
if not_check:
if os.path.exists(s_tmp_path): shutil.rmtree(s_tmp_path)
return not_check
return plugin_data_info
def not_cpu_or_bit(self,plugin_data_info):
'''
@name 检测是否为不支持的平台和系统位数
@author hwliang<2021-07-07>
@param plugin_data_info<dict> 插件信息数据
@return dict or None
'''
if 'not_os_bit' in plugin_data_info:
if public.get_sysbit() == int(plugin_data_info['not_os_bit']):
return public.returnMsg(False,'该应用不支持{}位系统'.format(plugin_data_info['not_os_bit']))
if 'not_cpu_type' in plugin_data_info:
if not plugin_data_info['not_cpu_type']: return None
machine = os.uname().machine
for c_type in plugin_data_info['not_cpu_type']:
c_type = c_type.lower()
result = public.returnMsg(False,'该应用不支持{}平台,{}'.format(c_type,machine))
if c_type in ['arm','aarch64','aarch']:
if machine in ['aarch64','aarch']:
return result
elif c_type in ['mips','mips64','mips64el']:
if machine.find('mips') != -1:
return result
elif c_type in ['x86','x86-64']:
if machine in ['x86','x86-64']:
return result
return None
def __download_plugin(self,upgrade_plugin_name,upgrade_version):
'''
@name 下载插件包
@author hwliang<2021-06-21>
@param upgrade_plugin_name<string> 插件名称
@param upgrade_version<string> 插件版本
@return string 保存路径
'''
pkey = '{}_pre'.format(upgrade_plugin_name)
pdata = public.get_user_info()
pdata['name'] = upgrade_plugin_name
pdata['version'] = upgrade_version
pdata['os'] = 'Linux'
filename = '{}/{}.zip'.format(self.__tmp_path,upgrade_plugin_name)
if not os.path.exists(self.__tmp_path): os.makedirs(self.__tmp_path,384)
if not cache.get(pkey):
try:
download_res = requests.post(self.__download_url,pdata,headers=public.get_requests_headers(),timeout=30,stream=True)
except Exception as ex:
raise public.PanelError(public.error_conn_cloud(str(ex)))
try:
headers_total_size = int(download_res.headers['File-size'])
except:
if download_res.text.find('<html>') != -1:
raise public.PanelError(public.error_conn_cloud(download_res.text))
raise public.PanelError(download_res.text)
res_down_size = 0
res_chunk_size = 8192
last_time = time.time()
with open(filename,'wb+') as with_res_f:
for download_chunk in download_res.iter_content(chunk_size=res_chunk_size):
if download_chunk:
with_res_f.write(download_chunk)
speed_last_size = len(download_chunk)
res_down_size += speed_last_size
res_start_time = time.time()
res_timeout = (res_start_time - last_time)
res_sec_speed = int(res_down_size / res_timeout)
pre_text = '{}/{}/{}'.format(res_down_size,headers_total_size,res_sec_speed)
cache.set(pkey,pre_text,3600)
with_res_f.close()
if cache.get(pkey): cache.delete(pkey)
if public.FileMd5(filename) != download_res.headers['Content-md5']:
raise public.PanelError('软件包下载失败,请重试')
else:
while True:
time.sleep(1)
if not cache.get(pkey): break
return ''
return filename
def __get_plugin_find(self,upgrade_plugin_name = None):
'''
@name 获取指定软件信息
@author hwliang<2021-06-15>
@param upgrade_plugin_name<string> 插件名称
@return dict
'''
if not self.__plugin_object: self.__plugin_object = Plugin(False)
if not self.__plugin_list: self.__plugin_list = self.__plugin_object.get_plugin_list()
for p_data_info in self.__plugin_list['list']:
if p_data_info['name'] == upgrade_plugin_name:
upgrade_plugin_name = p_data_info['name']
return p_data_info
# 如果不在插件列表中
return self.__get_plugin_info(upgrade_plugin_name)
def __download_main(self,upgrade_plugin_name,upgrade_version):
'''
@name 下载插件主程序文件
@author hwliang<2021-06-25>
@param upgrade_plugin_name<string> 插件名称
@param upgrade_version<string> 插件版本
@return void
'''
pdata = public.get_user_info()
pdata['name'] = upgrade_plugin_name
pdata['version'] = upgrade_version
pdata['os'] = 'Linux'
download_res = requests.post(self.__download_d_main_url,pdata,timeout=30)
filename = '{}/{}.py'.format(self.__tmp_path,upgrade_plugin_name)
with open(filename,'wb+') as save_script_f:
save_script_f.write(download_res.content)
save_script_f.close()
if public.md5(download_res.content) != download_res.headers['Content-md5']:
raise public.PanelError('插件安装包HASH校验失败')
dst_file = '{plugin_path}/{plugin_name}/{plugin_name}_main.py'.format(plugin_path=self.__plugin_path,plugin_name = upgrade_plugin_name)
shutil.copyfile(filename,dst_file)
if os.path.exists(filename): os.remove(filename)
public.WriteLog('软件管理',"检测到插件[{}]程序文件异常,已尝试自动修复!".format(self.__get_plugin_info(upgrade_plugin_name)['title']))
def __get_download_speed(self,upgrade_plugin_name):
'''
@name 取插件下载进度
@author hwliang<2021-06-21>
@param upgrade_plugin_name<string> 插件名称
@return dict
'''
pkey = '{}_pre'.format(upgrade_plugin_name)
pre_text = cache.get(pkey)
if not pre_text:
return public.returnMsg(False,'指定进度信息不存在!')
result = { "status": True }
pre_tmp = pre_text.split('/')
result['down_size'],result['total_size'] = (int(pre_tmp[0]),int(pre_tmp[1]))
result['down_pre'] = round(result['down_size'] / result['total_size'] * 100,1)
result['sec_speed'] = int(float(pre_tmp[2]))
result['need_time'] = int((result['total_size'] - result['down_size']) / result['sec_speed'])
return result
def close_install(self,get):
'''
@name 取消指定插件安装过程
@author hwliang<2021-07-07>
@param plugin_name<string> 插件名称
@return void
'''
plugin_name = get.plugin_name.strip()
tmp_path = '{}/{}'.format(self.__tmp_path,plugin_name)
if os.path.exists(tmp_path): shutil.rmtree(tmp_path)
return public.returnMsg(False,'安装过程已取消!')
#检查依赖
def check_deps(self,get):
cacheKey = 'plugin_lib_list'
if not 'force' in get:
libList = cache.get(cacheKey)
if libList: return libList
libList = json.loads(public.readFile('config/lib.json'))
centos = os.path.exists('/bin/yum')
for key in libList.keys():
for i in range(len(libList[key])):
checks = libList[key][i]['check'].split(',')
libList[key][i]['status'] = False
for check in checks:
if os.path.exists(check):
libList[key][i]['status'] = True
break
libList[key][i]['version'] = "-"
if libList[key][i]['status']:
shellTmp = libList[key][i]['getv'].split(':D')
shellEx = shellTmp[0]
if len(shellTmp) > 1 and not centos: shellEx = shellTmp[1]
libList[key][i]['version'] = public.ExecShell(shellEx)[0].strip()
cache.set(cacheKey,libList,86400)
return libList
#检测关键目录是否可以被写入文件
def check_sys_write(self):
test_file = '/etc/init.d/bt_10000100.pl'
public.writeFile(test_file,'True')
if os.path.exists(test_file):
if public.readFile(test_file) == 'True':
os.remove(test_file)
return True
os.remove(test_file)
return False
#检查互斥
def check_mutex(self,mutex):
if mutex == -1: return True
mutexs = mutex.split(',')
for name in mutexs:
pluginInfo = self.get_soft_find(name)
if not pluginInfo: continue
if pluginInfo['setup'] == True:
self.mutex_title = pluginInfo['title']
return False
return True
#检查依赖
def check_dependnet(self,dependnet):
if not dependnet: return True
dependnets = dependnet.split(',')
status = True
for dep in dependnets:
if not dep: continue
if dep.find('|') != -1:
names = dep.split('|')
for name in names:
pluginInfo = self.get_soft_find(name)
if not pluginInfo: return True
if pluginInfo['setup'] == True:
status = True
break
else:
status = False
else:
pluginInfo = self.get_soft_find(dep)
if pluginInfo['setup'] != True:
status = False
break
return status
#检查CPU限制
def check_cpu_limit(self,cpuLimit):
if psutil.cpu_count() < cpuLimit: return False
return True
#检查内存限制
def check_mem_limit(self,memLimit):
if psutil.virtual_memory().total/1024/1024 < memLimit: return False
return True
#检查操作系统限制
def check_os_limit(self,osLimit):
if osLimit == 0: return True
if osLimit == 1:
centos = os.path.exists('/usr/bin/yum')
return centos
elif osLimit == 2:
debian = os.path.exists('/usr/bin/apt-get')
return debian
return True
#安装插件
def install_plugin(self,get):
if not self.check_sys_write(): return public.returnMsg(False,'<a style="color:red;">错误:检测到系统关键目录不可写!</a><br>1、如果安装了[宝塔系统加固],请先关闭<br><br>2、如果安装了云锁,请关闭[系统加固]功能<br>3、如果安装了安全狗,请关闭[系统防护]功能<br>4、如果使用了其它安全软件,请先卸载<br>')
if not 'sName' in get: return public.returnMsg(False,'请指定软件名称!')
pluginInfo = self.get_soft_find(get.sName)
p_node = '/www/server/panel/install/public.sh'
if os.path.exists(p_node):
if len(public.readFile(p_node)) < 100: os.remove(p_node)
if not pluginInfo: return public.returnMsg(False,'指定插件不存在!')
self.mutex_title = pluginInfo['mutex']
if not self.check_mutex(pluginInfo['mutex']): return public.returnMsg(False,'请先卸载[%s]' % self.mutex_title )
if not hasattr(get,'id'):
if not self.check_dependnet(pluginInfo['dependnet']): return public.returnMsg(False,'依赖以下软件,请先安装[%s]' % pluginInfo['dependnet'])
if 'version' in get:
for versionInfo in pluginInfo['versions']:
if versionInfo['m_version'] != get.version: continue
if not 'type' in get: get.type = '0'
if int(get.type) > 4: get.type = '0'
if get.type == '0':
if not self.check_cpu_limit(versionInfo['cpu_limit']): return public.returnMsg(False,'至少需要[%d]个CPU核心才能安装' % versionInfo['cpu_limit'])
if not self.check_mem_limit(versionInfo['mem_limit']): return public.returnMsg(False,'至少需要[%dMB]内存才能安装' % versionInfo['mem_limit'])
if not self.check_os_limit(versionInfo['os_limit']):
m_ps = {0:"所有的",1:"Centos",2:"Ubuntu/Debian"}
return public.returnMsg(False,'仅支持[%s]系统' % m_ps[int(versionInfo['os_limit'])])
if not hasattr(get,'id'):
if not self.check_dependnet(versionInfo['dependnet']): return public.returnMsg(False,'依赖以下软件,请先安装[%s]' % versionInfo['dependnet'])
if pluginInfo['type'] != 5:
result = self.install_sync(pluginInfo,get)
else:
result = self.install_async(pluginInfo,get)
try:
if 'status' in result:
if result['status']:
public.httpPost(public.GetConfigValue('home') + '/api/panel/plugin_total',{"pid":pluginInfo['id'],'p_name':pluginInfo['name']},3)
except:pass
return result
#同步安装
def install_sync(self,pluginInfo,get):
if 'download' in pluginInfo['versions'][0]:
tmp_path = '/www/server/panel/temp'
if not os.path.exists(tmp_path): os.makedirs(tmp_path,mode=384)
public.ExecShell("rm -rf " + tmp_path + '/*')
toFile = tmp_path + '/' + pluginInfo['name'] + '.zip'
public.downloadFile('https://www.bt.cn/api/Pluginother/get_file?fname=' + pluginInfo['versions'][0]['download'],toFile)
if public.FileMd5(toFile) != pluginInfo['versions'][0]['md5']:
try:
return json.loads(public.readFile(toFile))
except :
return public.returnMsg(False,'文件Hash校验失败,停止安装!')
update = False
if os.path.exists(pluginInfo['install_checks']): update =pluginInfo['versions'][0]['version_msg']
return self.update_zip(None,toFile,update)
else:
# download_url = public.get_url() + '/install/plugin/' + pluginInfo['name'] + '/install.sh'
# toFile = '/tmp/%s.sh' % pluginInfo['name']
# public.downloadFile(download_url,toFile)
# self.set_pyenv(toFile)
# public.ExecShell('/bin/bash ' + toFile + ' install &> /tmp/panelShell.pl')
# if os.path.exists(pluginInfo['install_checks']):
# public.WriteLog('TYPE_SETUP','PLUGIN_INSTALL_LIB',(pluginInfo['title'],))
# if os.path.exists(toFile): os.remove(toFile)
# return public.returnMsg(True,'PLUGIN_INSTALL_SUCCESS')
# return public.returnMsg(False,'安装失败!')
if hasattr(get,'min_version'):
get.version += '.' + get.min_version
return self.__install_plugin(pluginInfo['name'], get.version)
# 修复插件
def repair_plugin(self,get):
'''
@name 修复指定插件
@param plugin_name<string> 插件名称
@param version<string> 版本号
@param min_version<string> 子版本号
@return mixed
'''
if hasattr(get,'min_version'):
get.version += '.' + get.min_version
return self.__repair_plugin(get.plugin_name, get.version)
# 更新插件
def upgrade_plugin(self,get):
'''
@name 更新指定插件/切换到指定版本
@param plugin_name<string> 插件名称
@param version<string> 版本号
@param min_version<string> 子版本号
@return mixed
'''
if hasattr(get,'min_version'):
get.version += '.' + get.min_version
return self.__upgrade_plugin(get.plugin_name, get.version)
#设置Python环境变量
def set_pyenv(self,filename):
if not os.path.exists(filename): return False
env_py = '/www/server/panel/pyenv/bin'
if not os.path.exists(env_py): return False
temp_file = public.readFile(filename)
env_path=['PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin']
rep_path=['PATH={}/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin'.format(env_py+":")]
for i in range(len(env_path)):
temp_file = temp_file.replace(env_path[i],rep_path[i])
public.writeFile(filename,temp_file)
return True
def get_download_speed(self,get):
'''
@name 获取插件下载进度
@author hwliang<2021-06-25>
@param plugin_name<string> 插件名称
@return dict
'''
result = self.__get_download_speed(get.plugin_name)
return result
#异步安装
def install_async(self,pluginInfo,get):
mtype = 'install'
mmsg = '安装'
if hasattr(get, 'upgrade'):
mtype = 'update'
mmsg = 'upgrade'
if not 'type' in get: get.type = '0'
if int(get.type) > 4: get.type = '0'
if get.sName == 'nginx':
if get.version == '1.8': return public.returnMsg(False,'Nginx 1.8.1版本过旧,不再提供支持,请选择其它版本!')
if get.sName.find('php-') != -1: get.sName = get.sName.split('-')[0]
ols_execstr = ""
if "php" == get.sName and os.path.exists('/usr/local/lsws/bin/lswsctrl'):
ols_sName = 'php-ols'
ols_version = get.version.replace('.','')
ols_execstr = " &> /tmp/panelExec.log && /bin/bash install_soft.sh {} {} " + ols_sName + " " + ols_version
php_path = '/www/server/php'
if not os.path.exists(php_path): os.makedirs(php_path)
apacheVersion='false'
if public.get_webserver() == 'apache':
apacheVersion = public.readFile('/www/server/apache/version.pl')
public.writeFile('/var/bt_apacheVersion.pl',apacheVersion)
public.writeFile('/var/bt_setupPath.conf','/www')
if os.path.exists('/usr/bin/apt-get'):
if get.type == '0':
get.type = '3'
else:
get.type = '4'
if ols_execstr:
ols_execstr = ols_execstr.format(get.type,mtype)
execstr = "cd /www/server/panel/install && /bin/bash install_soft.sh {} {} {} {} {}".format(get.type,mtype,get.sName,get.version,ols_execstr)
if get.sName == "phpmyadmin":
execstr += "&> /tmp/panelExec.log"
if public.get_webserver() == 'openlitespeed':
execstr += " && sleep 1 && /usr/local/lsws/bin/lswsctrl restart"
# execstr += " && echo '>>命令执行完成!'"
public.M('tasks').add('id,name,type,status,addtime,execstr',(None, mmsg + '['+get.sName+'-'+get.version+']','execshell','0',time.strftime('%Y-%m-%d %H:%M:%S'),execstr))
cache.delete('install_task')
public.writeFile('/tmp/panelTask.pl','True')
public.WriteLog('TYPE_SETUP','PLUGIN_ADD',(get.sName,get.version))
return public.returnMsg(True,'已将安装任务添加到队列!')
#卸载插件
def uninstall_plugin(self,get):
pluginInfo = self.get_soft_find(get.sName)
if not pluginInfo: return public.returnMsg(False,'指定插件不存在!')
if pluginInfo['type'] != 5:
pluginPath = self.__install_path + '/' + pluginInfo['name']
installSh = pluginPath + '/install.sh'
uninstallSh = pluginPath + '/uninstall.sh'
if pluginInfo['type'] != 6 and not os.path.exists(installSh) and not os.path.exists(uninstallSh):
download_url = session['download_url'] + '/install/plugin/' + pluginInfo['name'] + '/install.sh'
toFile = '/tmp/%s.sh' % pluginInfo['name']
public.downloadFile(download_url,toFile)
self.set_pyenv(toFile)
if os.path.exists(toFile):
if os.path.getsize(toFile) > 100:
public.ExecShell('/bin/bash ' + toFile + ' uninstall')
if os.path.exists(uninstallSh):
self.set_pyenv(uninstallSh)
public.ExecShell('/bin/bash {} uninstall'.format(uninstallSh))
elif os.path.exists(installSh):
self.set_pyenv(installSh)
public.ExecShell('/bin/bash {} uninstall'.format(installSh))
if os.path.exists(pluginPath): public.ExecShell('rm -rf ' + pluginPath)
public.WriteLog('TYPE_SETUP','PLUGIN_UNINSTALL_SOFT',(pluginInfo['title'],))
return public.returnMsg(True,'PLUGIN_UNINSTALL')
else:
if pluginInfo['name'] == 'mysql':
if public.M('databases').where('db_type=?',0).count() > 0: return public.returnMsg(False,"本地数据库列表非空,为了您的数据安全,请先<span style='color:red;'>备份所有本地数据库数据</span>后删除现有本地数据库<br>强制卸载命令:rm -rf /www/server/mysql")
get.type = '0'
if session['server_os']['x'] != 'RHEL': get.type = '3'
get.sName = get.sName.lower()
if get.sName.find('php-') != -1:
get.sName = get.sName.split('-')[0]
execstr = "cd /www/server/panel/install && /bin/bash install_soft.sh "+get.type+" uninstall " + get.sName.lower() + " "+ get.version.replace('.','')
public.ExecShell(execstr)
public.WriteLog('TYPE_SETUP','PLUGIN_UNINSTALL',(get.sName,get.version))
return public.returnMsg(True,"PLUGIN_UNINSTALL")
def __is_bind_user(self):
'''
@name 检测是否绑定用户
@author hwliang<2021-06-23>
@return bool
'''
user_info_file = self.__panel_path + '/data/userInfo.json'
if not os.path.exists(user_info_file):
raise public.PanelError('请先绑定宝塔帐号!')
return True
#从云端取列表
def get_cloud_list(self,get=None):
force = False
if hasattr(get,'force'):
if int(get.force) == 1: force = True
self.__is_bind_user()
skey = 'TNaMJdG3mDHKRS6Y'
softList = cache.get(skey)
if not softList or force:
softList = Plugin(False).get_plugin_list(force)
cache.set(skey,softList,3600)
self.clean_panel_log()
if 'ip' in softList:
if public.is_ipv6(softList['ip']):
public.writeFile('data/v4.pl',' -6 ')
else:
public.writeFile('data/v4.pl',' -4 ')
sType = 0
try:
if hasattr(get,'type'): sType = int(get['type'])
if hasattr(get,'query'):
if get.query: sType = 0
except:pass
if type(softList)!=dict:
softList = Plugin(False).get_plugin_list(False)
if type(softList)!=dict:
softList={"list":[]}
return softList
softList['list'] = self.get_local_plugin(softList['list'])
softList['list'] = self.get_types(softList['list'],sType)
if hasattr(get,'query'):
if get.query:
get.query = get.query.lower()
public.total_keyword(get.query)
tmpList = []
for softInfo in softList['list']:
if softInfo['name'].lower().find(get.query) != -1 or \
softInfo['title'].lower().find(get.query) != -1 or \
softInfo['ps'].lower().find(get.query) != -1:
tmpList.append(softInfo)
softList['list'] = tmpList
return softList
#取提醒标记
def get_level_msg(self,level,s_time,endtime):
'''
level 提醒标记
s_time 当前时间戳
endtime 到期时间戳
'''
expire_day = (endtime - s_time) / 86400
if expire_day < 15 and expire_day > 7:
level = level + '15'
elif expire_day < 7 and expire_day > 3:
level = level + '7'
elif expire_day < 3 and expire_day > 0:
level = level + '3'
return level,expire_day
#添加到期提醒
def add_expire_msg(self,title,level,name,expire_day,pid,endtime):
'''
title 软件标题
level 提醒标记
name 软件名称
expire_day 剩余天数
'''
import panelMessage #引用消息提醒模块
pm = panelMessage.panelMessage()
pm.remove_message_level(level) #删除旧的提醒
if expire_day > 15: return False