forked from aaPanel/BaoTa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublic.py
4386 lines (3879 loc) · 140 KB
/
public.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 json,os,sys,time,re,socket,importlib,binascii,base64,io,string
from random import choice
_LAN_PUBLIC = None
_LAN_LOG = None
_LAN_TEMPLATE = None
if sys.version_info[0] == 2:
reload(sys)
sys.setdefaultencoding('utf8')
else:
from importlib import reload
def M(table):
"""
@name 访问面板数据库
@author hwliang<[email protected]>
@table 被访问的表名(必需)
@return db.Sql object
ps: 默认访问data/default.db
"""
import db
with db.Sql() as sql:
#sql = db.Sql()
return sql.table(table)
def HttpGet(url,timeout = 6,headers = {}):
"""
@name 发送GET请求
@author hwliang<[email protected]>
@url 被请求的URL地址(必需)
@timeout 超时时间默认60秒
@return string
"""
if url.find('GetAuthToken') == -1:
if is_local(): return False
# rep_home_host()
import http_requests
res = http_requests.get(url,timeout=timeout,headers = headers)
if res.status_code == 0:
if headers: return False
s_body = res.text
return s_body
s_body = res.text
del res
return s_body
def rep_home_host():
hosts_file = "data/home_host.pl"
if os.path.exists(hosts_file):
ExecShell('sed -i "/www.bt.cn/d" /etc/hosts')
os.remove(hosts_file)
def http_get_home(url,timeout,ex):
"""
@name Get方式使用优选节点访问官网
@author hwliang<[email protected]>
@param url 当前官网URL地址
@param timeout 用于测试超时时间
@param ex 上一次错误的响应内容
@return string 响应内容
如果已经是优选节点,将直接返回ex
"""
try:
home = 'www.bt.cn'
if url.find(home) == -1: return ex
hosts_file = "config/hosts.json"
if not os.path.exists(hosts_file): return ex
hosts = json.loads(readFile(hosts_file))
headers = {"host":home}
for host in hosts:
new_url = url.replace(home,host)
res = HttpGet(new_url,timeout,headers)
if res:
writeFile("data/home_host.pl",host)
set_home_host(host)
return res
return ex
except: return ex
def set_home_host(host):
"""
@name 设置官网hosts
@author hwliang<[email protected]>
@param host IP地址
@return void
"""
ExecShell('sed -i "/www.bt.cn/d" /etc/hosts')
ExecShell("echo '' >> /etc/hosts")
ExecShell("echo '%s www.bt.cn' >> /etc/hosts" % host)
ExecShell('sed -i "/^\s*$/d" /etc/hosts')
def httpGet(url,timeout=6):
return HttpGet(url,timeout)
def HttpPost(url,data,timeout = 6,headers = {}):
"""
发送POST请求
@url 被请求的URL地址(必需)
@data POST参数,可以是字符串或字典(必需)
@timeout 超时时间默认60秒
return string
"""
if url.find('GetAuthToken') == -1:
if is_local(): return False
# rep_home_host()
import http_requests
res = http_requests.post(url,data=data,timeout=timeout,headers = headers)
if res.status_code == 0:
if headers: return False
s_body = res.text
return s_body
s_body = res.text
return s_body
def httpPost(url,data,timeout=6):
"""
@name 发送POST请求
@author hwliang<[email protected]>
@param url 被请求的URL地址(必需)
@param data POST参数,可以是字符串或字典(必需)
@param timeout 超时时间默认60秒
@return string
"""
return HttpPost(url,data,timeout)
def check_home():
return True
def Md5(strings):
"""
@name 生成MD5
@author hwliang<[email protected]>
@param strings 要被处理的字符串
@return string(32)
"""
if type(strings) != bytes:
strings = strings.encode()
import hashlib
m = hashlib.md5()
m.update(strings)
return m.hexdigest()
def md5(strings):
return Md5(strings)
def FileMd5(filename):
"""
@name 生成文件的MD5
@author hwliang<[email protected]>
@param filename 文件名
@return string(32) or False
"""
if not os.path.isfile(filename): return False
import hashlib
my_hash = hashlib.md5()
f = open(filename,'rb')
while True:
b = f.read(8096)
if not b :
break
my_hash.update(b)
f.close()
return my_hash.hexdigest()
def GetRandomString(length):
"""
@name 取随机字符串
@author hwliang<[email protected]>
@param length 要获取的长度
@return string(length)
"""
from random import Random
strings = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
chrlen = len(chars) - 1
random = Random()
for i in range(length):
strings += chars[random.randint(0, chrlen)]
return strings
def ReturnJson(status,msg,args=()):
"""
@name 取通用Json返回
@author hwliang<[email protected]>
@param status 返回状态
@param msg 返回消息
@return string(json)
"""
return GetJson(ReturnMsg(status,msg,args))
def returnJson(status,msg,args=()):
"""
@name 取通用Json返回
@author hwliang<[email protected]>
@param status 返回状态
@param msg 返回消息
@return string(json)
"""
return ReturnJson(status,msg,args)
def ReturnMsg(status,msg,args = ()):
"""
@name 取通用dict返回
@author hwliang<[email protected]>
@param status 返回状态
@param msg 返回消息
@return dict {"status":bool,"msg":string}
"""
log_message = json.loads(ReadFile('BTPanel/static/language/' + GetLanguage() + '/public.json'))
keys = log_message.keys()
if type(msg) == str:
if msg in keys:
msg = log_message[msg]
for i in range(len(args)):
rep = '{'+str(i+1)+'}'
msg = msg.replace(rep,args[i])
return {'status':status,'msg':msg}
def returnMsg(status,msg,args = ()):
"""
@name 取通用dict返回
@author hwliang<[email protected]>
@param status 返回状态
@param msg 返回消息
@return dict {"status":bool,"msg":string}
"""
return ReturnMsg(status,msg,args)
def GetFileMode(filename):
"""
@name 取文件权限字符串
@author hwliang<[email protected]>
@param filename 文件全路径
@return string 如:644/777/755
"""
stat = os.stat(filename)
accept = str(oct(stat.st_mode)[-3:])
return accept
def get_mode_and_user(path):
'''取文件或目录权限信息'''
import pwd
data = {}
if not os.path.exists(path): return None
stat = os.stat(path)
data['mode'] = str(oct(stat.st_mode)[-3:])
try:
data['user'] = pwd.getpwuid(stat.st_uid).pw_name
except:
data['user'] = str(stat.st_uid)
return data
def GetJson(data):
"""
将对象转换为JSON
@data 被转换的对象(dict/list/str/int...)
"""
from json import dumps
if data == bytes: data = data.decode('utf-8')
try:
return dumps(data,ensure_ascii=False)
except:
return dumps(returnMsg(False,"错误的响应: %s" % str(data)))
def getJson(data):
return GetJson(data)
def ReadFile(filename,mode = 'r'):
"""
读取文件内容
@filename 文件名
return string(bin) 若文件不存在,则返回None
"""
import os
if not os.path.exists(filename): return False
fp = None
try:
fp = open(filename, mode)
f_body = fp.read()
except Exception as ex:
if sys.version_info[0] != 2:
try:
fp = open(filename, mode,encoding="utf-8")
f_body = fp.read()
except:
fp = open(filename, mode,encoding="GBK")
f_body = fp.read()
else:
return False
finally:
if fp and not fp.closed:
fp.close()
return f_body
def readFile(filename,mode='r'):
'''
@name 读取指定文件数据
@author hwliang<2021-06-09>
@param filename<string> 文件名
@param mode<string> 文件打开模式,默认r
@return string or bytes or False 如果返回False则说明读取失败
'''
return ReadFile(filename,mode)
def WriteFile(filename,s_body,mode='w+'):
"""
写入文件内容
@filename 文件名
@s_body 欲写入的内容
return bool 若文件不存在则尝试自动创建
"""
try:
fp = open(filename, mode)
fp.write(s_body)
fp.close()
return True
except:
try:
fp = open(filename, mode,encoding="utf-8")
fp.write(s_body)
fp.close()
return True
except:
return False
def writeFile(filename,s_body,mode='w+'):
'''
@name 写入到指定文件
@author hwliang<2021-06-09>
@param filename<string> 文件名
@param s_boey<string/bytes> 被写入的内容,字节或字符串
@param mode<string> 文件打开模式,默认w+
@return bool
'''
return WriteFile(filename,s_body,mode)
def WriteLog(type,logMsg,args=(),not_web = False):
#写日志
try:
import time,db,json
username = 'system'
uid = 1
tmp_msg = ''
if not not_web:
try:
from BTPanel import session
if 'username' in session:
username = session['username']
uid = session['uid']
if session.get('debug') == 1: return
except:
pass
global _LAN_LOG
if not _LAN_LOG:
_LAN_LOG = json.loads(ReadFile('BTPanel/static/language/' + GetLanguage() + '/log.json'))
keys = _LAN_LOG.keys()
if logMsg in keys:
logMsg = _LAN_LOG[logMsg]
for i in range(len(args)):
rep = '{'+str(i+1)+'}'
logMsg = logMsg.replace(rep,args[i])
if type in keys: type = _LAN_LOG[type]
sql = db.Sql()
mDate = time.strftime('%Y-%m-%d %X',time.localtime())
data = (uid,username,type,logMsg + tmp_msg,mDate)
result = sql.table('logs').add('uid,username,type,log,addtime',data)
except:
pass
def GetLanguage():
'''
取语言
'''
return GetConfigValue("language")
def get_language():
return GetLanguage()
def GetConfigValue(key):
'''
取配置值
'''
config = GetConfig()
if not key in config.keys():
if key == 'download': return 'https://download.bt.cn'
return None
return config[key]
def SetConfigValue(key,value):
config = GetConfig()
config[key] = value
WriteConfig(config)
def GetConfig():
'''
取所有配置项
'''
path = "config/config.json"
if not os.path.exists(path): return {}
f_body = ReadFile(path)
if not f_body: return {}
return json.loads(f_body)
def WriteConfig(config):
path = "config/config.json"
WriteFile(path,json.dumps(config))
def GetLan(key):
"""
取提示消息
"""
global _LAN_TEMPLATE
if not _LAN_TEMPLATE:
_LAN_TEMPLATE = json.loads(ReadFile('BTPanel/static/language/' + GetLanguage() + '/template.json'))
keys = _LAN_TEMPLATE.keys()
msg = None
if key in keys:
msg = _LAN_TEMPLATE[key]
return msg
def getLan(key):
return GetLan(key)
def GetMsg(key,args = ()):
try:
global _LAN_PUBLIC
if not _LAN_PUBLIC:
_LAN_PUBLIC = json.loads(ReadFile('BTPanel/static/language/' + GetLanguage() + '/public.json'))
keys = _LAN_PUBLIC.keys()
msg = None
if key in keys:
msg = _LAN_PUBLIC[key]
for i in range(len(args)):
rep = '{'+str(i+1)+'}'
msg = msg.replace(rep,args[i])
return msg
except:
return key
def getMsg(key,args = ()):
return GetMsg(key,args)
#获取Web服务器
def GetWebServer():
if os.path.exists('{}/apache/bin/apachectl'.format(get_setup_path())):
webserver = 'apache'
elif os.path.exists('/usr/local/lsws/bin/lswsctrl'):
webserver = 'openlitespeed'
else:
webserver = 'nginx'
return webserver
def get_webserver():
return GetWebServer()
def ServiceReload():
#重载Web服务配置
if os.path.exists('{}/nginx/sbin/nginx'.format(get_setup_path())):
result = ExecShell('/etc/init.d/nginx reload')
if result[1].find('nginx.pid') != -1:
ExecShell('pkill -9 nginx && sleep 1')
ExecShell('/etc/init.d/nginx start')
elif os.path.exists('{}/apache/bin/apachectl'.format(get_setup_path())):
result = ExecShell('/etc/init.d/httpd reload')
else:
result = ExecShell('rm -f /tmp/lshttpd/*.sock* && /usr/local/lsws/bin/lswsctrl restart')
return result
def serviceReload():
return ServiceReload()
def get_preexec_fn(run_user):
'''
@name 获取指定执行用户预处理函数
@author hwliang<2021-08-19>
@param run_user<string> 运行用户
@return 预处理函数
'''
import pwd
pid = pwd.getpwnam(run_user)
uid = pid.pw_uid
gid = pid.pw_gid
def _exec_rn():
os.setgid(gid)
os.setuid(uid)
return _exec_rn
def ExecShell(cmdstring, timeout=None, shell=True,cwd=None,env=None,user = None):
'''
@name 执行命令
@author hwliang<2021-08-19>
@param cmdstring 命令 [必传]
@param timeout 超时时间
@param shell 是否通过shell运行
@param cwd 进入的目录
@param env 环境变量
@param user 执行用户名
@return 命令执行结果
'''
a = ''
e = ''
import subprocess,tempfile
preexec_fn = None
tmp_dir = '/dev/shm'
if user:
preexec_fn = get_preexec_fn(user)
tmp_dir = '/tmp'
try:
rx = md5(cmdstring)
succ_f = tempfile.SpooledTemporaryFile(max_size=4096,mode='wb+',suffix='_succ',prefix='btex_' + rx ,dir=tmp_dir)
err_f = tempfile.SpooledTemporaryFile(max_size=4096,mode='wb+',suffix='_err',prefix='btex_' + rx ,dir=tmp_dir)
sub = subprocess.Popen(cmdstring, close_fds=True, shell=shell,bufsize=128,stdout=succ_f,stderr=err_f,cwd=cwd,env=env,preexec_fn=preexec_fn)
if timeout:
s = 0
d = 0.01
while sub.poll() == None:
time.sleep(d)
s += d
if s >= timeout:
if not err_f.closed: err_f.close()
if not succ_f.closed: succ_f.close()
return 'Timed out'
else:
sub.wait()
err_f.seek(0)
succ_f.seek(0)
a = succ_f.read()
e = err_f.read()
if not err_f.closed: err_f.close()
if not succ_f.closed: succ_f.close()
except:
return '',get_error_info()
try:
#编码修正
if type(a) == bytes: a = a.decode('utf-8')
if type(e) == bytes: e = e.decode('utf-8')
except:
a = str(a)
e = str(e)
return a,e
def GetLocalIp():
#取本地外网IP
try:
filename = 'data/iplist.txt'
ipaddress = readFile(filename)
if not ipaddress:
url = 'http://pv.sohu.com/cityjson?ie=utf-8'
m_str = HttpGet(url)
ipaddress = re.search(r'\d+.\d+.\d+.\d+',m_str).group(0)
WriteFile(filename,ipaddress)
c_ip = check_ip(ipaddress)
if not c_ip: return GetHost()
return ipaddress
except:
try:
url = GetConfigValue('home') + '/Api/getIpAddress'
return HttpGet(url)
except:
return GetHost()
def is_ipv4(ip):
try:
socket.inet_pton(socket.AF_INET, ip)
except AttributeError:
try:
socket.inet_aton(ip)
except socket.error:
return False
return ip.count('.') == 3
except socket.error:
return False
return True
def is_ipv6(ip):
try:
socket.inet_pton(socket.AF_INET6, ip)
except socket.error:
return False
return True
def check_ip(ip):
return is_ipv4(ip) or is_ipv6(ip)
def GetHost(port = False):
from flask import request
host_tmp = request.headers.get('host')
if not host_tmp:
if request.url_root:
tmp = re.findall(r"(https|http)://([\w:\.-]+)",request.url_root)
if tmp: host_tmp = tmp[0][1]
if not host_tmp:
host_tmp = GetLocalIp() + ':' + readFile('data/port.pl').strip()
try:
if host_tmp.find(':') == -1: host_tmp += ':80'
except:
host_tmp = "127.0.0.1:8888"
h = host_tmp.split(':')
if port: return h[-1]
return ':'.join(h[0:-1])
def GetClientIp():
from flask import request
ipaddr = request.remote_addr.replace('::ffff:','')
if not check_ip(ipaddr): return '未知IP地址'
return ipaddr
def get_client_ip():
return GetClientIp()
def phpReload(version):
#重载PHP配置
import os
if os.path.exists(get_setup_path()+'/php/' + version + '/libphp5.so'):
ExecShell('/etc/init.d/httpd reload')
else:
ExecShell('/etc/init.d/php-fpm-'+version+' reload')
ExecShell("/etc/init.d/php-fpm-{} start".format(version))
def get_timeout(url,timeout=3):
try:
start = time.time()
result = int(httpGet(url,timeout))
return result,int((time.time() - start) * 1000 - 500)
except: return 0,False
def get_url(timeout = 0.5):
return 'https://download.bt.cn'
import json
try:
pkey = 'node_url'
node_url = cache_get(pkey)
if node_url: return node_url
nodeFile = 'data/node.json'
node_list = json.loads(readFile(nodeFile))
mnode1 = []
mnode2 = []
mnode3 = []
new_node_list = {}
for node in node_list:
node['net'],node['ping'] = get_timeout(node['protocol'] + node['address'] + ':' + node['port'] + '/net_test',1)
new_node_list[node['address']] = node['ping']
if not node['ping']: continue
if node['ping'] < 100: #当响应时间<100ms且可用带宽大于1500KB时
if node['net'] > 1500:
mnode1.append(node)
elif node['net'] > 1000:
mnode3.append(node)
else:
if node['net'] > 1000: #当响应时间>=100ms且可用带宽大于1000KB时
mnode2.append(node)
if node['ping'] < 100:
if node['net'] > 3000: break #有节点可用带宽大于3000时,不再检查其它节点
if mnode1: #优选低延迟高带宽
mnode = sorted(mnode1,key= lambda x:x['net'],reverse=True)
elif mnode3: #备选低延迟,中等带宽
mnode = sorted(mnode3,key= lambda x:x['net'],reverse=True)
else: #终选中等延迟,中等带宽
mnode = sorted(mnode2,key= lambda x:x['ping'],reverse=False)
if not mnode: return 'http://download.bt.cn'
new_node_keys = new_node_list.keys()
for i in range(len(node_list)):
if node_list[i]['address'] in new_node_keys:
node_list[i]['ping'] = new_node_list[node_list[i]['address']]
else:
node_list[i]['ping'] = 500
new_node_list = sorted(node_list,key=lambda x: x['ping'],reverse=False)
writeFile(nodeFile,json.dumps(new_node_list))
node_url = mnode[0]['protocol'] + mnode[0]['address'] + ':' + mnode[0]['port']
cache_set(pkey,node_url,86400)
return node_url
except:
return 'http://download.bt.cn'
#过滤输入
def checkInput(data):
if not data: return data
if type(data) != str: return data
checkList = [
{'d':'<','r':'<'},
{'d':'>','r':'>'},
{'d':'\'','r':'‘'},
{'d':'"','r':'“'},
{'d':'&','r':'&'},
{'d':'#','r':'#'},
{'d':'<','r':'<'}
]
for v in checkList:
data = data.replace(v['d'],v['r'])
return data
#取文件指定尾行数
def GetNumLines(path,num,p=1):
pyVersion = sys.version_info[0]
max_len = 1024*128
try:
from cgi import html
if not os.path.exists(path): return ""
start_line = (p - 1) * num
count = start_line + num
fp = open(path,'r')
buf = ""
fp.seek(-1, 2)
if fp.read(1) == "\n": fp.seek(-1, 2)
data = []
total_len = 0
b = True
n = 0
for i in range(count):
while True:
newline_pos = str.rfind(str(buf), "\n")
pos = fp.tell()
if newline_pos != -1:
if n >= start_line:
line = buf[newline_pos + 1:]
line_len = len(line)
total_len += line_len
sp_len = total_len - max_len
if sp_len > 0:
line = line[sp_len:]
try:
data.insert(0,html.escape(line))
except: pass
buf = buf[:newline_pos]
n += 1
break
else:
if pos == 0:
b = False
break
to_read = min(4096, pos)
fp.seek(-to_read, 1)
t_buf = fp.read(to_read)
if pyVersion == 3:
try:
if type(t_buf) == bytes: t_buf = t_buf.decode('utf-8')
except:t_buf = str(t_buf)
buf = t_buf + buf
fp.seek(-to_read, 1)
if pos - to_read == 0:
buf = "\n" + buf
if total_len >= max_len: break
if not b: break
fp.close()
result = "\n".join(data)
if not result: raise Exception('null')
except:
result = ExecShell("tail -n {} {}".format(num,path))[0]
if len(result) > max_len:
result = result[-max_len:]
try:
try:
result = json.dumps(result)
return json.loads(result).strip()
except:
if pyVersion == 2:
result = result.decode('utf8',errors='ignore')
else:
result = result.encode('utf-8',errors='ignore').decode("utf-8",errors="ignore")
return result.strip()
except: return ""
#验证证书
def CheckCert(certPath = 'ssl/certificate.pem'):
openssl = '/usr/local/openssl/bin/openssl'
if not os.path.exists(openssl): openssl = 'openssl'
certPem = readFile(certPath)
s = "\n-----BEGIN CERTIFICATE-----"
tmp = certPem.strip().split(s)
for tmp1 in tmp:
if tmp1.find('-----BEGIN CERTIFICATE-----') == -1: tmp1 = s + tmp1
writeFile(certPath,tmp1)
result = ExecShell(openssl + " x509 -in "+certPath+" -noout -subject")
if result[1].find('-bash:') != -1: return True
if len(result[1]) > 2: return False
if result[0].find('error:') != -1: return False
return True
# 获取面板地址
def getPanelAddr():
from flask import request
protocol = 'https://' if os.path.exists("data/ssl.pl") else 'http://'
return protocol + request.headers.get('host')
#字节单位转换
def to_size(size):
if not size: return '0.00 b'
size = float(size)
d = ('b','KB','MB','GB','TB')
s = d[0]
for b in d:
if size < 1024: return ("%.2f" % size) + ' ' + b
size = size / 1024
s = b
return ("%.2f" % size) + ' ' + b
def checkCode(code,outime = 120):
#校验验证码
from BTPanel import session,cache
try:
codeStr = cache.get('codeStr')
cache.delete('codeStr')
if not codeStr:
session['login_error'] = GetMsg('CODE_TIMEOUT')
return False
if md5(code.lower()) != codeStr:
session['login_error'] = GetMsg('CODE_ERR')
return False
return True
except:
session['login_error'] = GetMsg('CODE_NOT_EXISTS')
return False
#写进度
def writeSpeed(title,used,total,speed = 0):
import json
if not title:
data = {'title':None,'progress':0,'total':0,'used':0,'speed':0}
else:
progress = int((100.0 * used / total))
data = {'title':title,'progress':progress,'total':total,'used':used,'speed':speed}
writeFile('/tmp/panelSpeed.pl',json.dumps(data))
return True
#取进度
def getSpeed():
import json;
data = readFile('/tmp/panelSpeed.pl')
if not data:
data = json.dumps({'title':None,'progress':0,'total':0,'used':0,'speed':0})
writeFile('/tmp/panelSpeed.pl',data)
return json.loads(data)
def get_requests_headers():
return {"Content-type":"application/x-www-form-urlencoded","User-Agent":"BT-Panel"}
def downloadFile(url,filename):
try:
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# import requests.packages.urllib3.util.connection as urllib3_conn
# old_family = urllib3_conn.allowed_gai_family
# urllib3_conn.allowed_gai_family = lambda: socket.AF_INET
res = requests.get(url,headers=get_requests_headers(),timeout=30,stream=True)
with open(filename,"wb") as f:
for _chunk in res.iter_content(chunk_size=8192):
f.write(_chunk)
# urllib3_conn.allowed_gai_family = old_family
except:
ExecShell("wget -O {} {} --no-check-certificate".format(filename,url))
def exists_args(args,get):
'''
@name 检查参数是否存在
@author hwliang<2021-06-08>
@param args<list or str> 参数列表 允许是列表或字符串
@param get<dict_obj> 参数对像
@return bool 都存在返回True,否则抛出KeyError异常
'''
if type(args) == str:
args = args.split(',')
for arg in args:
if not arg in get:
raise KeyError('缺少必要参数: {}'.format(arg))
return True
def get_error_info():
import traceback
errorMsg = traceback.format_exc()
return errorMsg
def get_plugin_replace_rules():
'''
@name 获取插件文件内容替换规则
@author hwliang<2021-06-28>
@return list
'''
return [
{
"find":"[PATH]",
"replace": "[PATH]"
}
]
def get_plugin_title(plugin_name):
'''
@name 获取插件标题
@author hwliang<2021-06-24>
@param plugin_name<string> 插件名称
@return string
'''
info_file = '{}/{}/info.json'.format(get_plugin_path(),plugin_name)
try:
return json.loads(readFile(info_file))['title']
except:
return plugin_name
def get_error_object(plugin_title = None,plugin_name = None):
'''
@name 获取格式化错误响应对像
@author hwliang<2021-06-21>
@return Resp
'''
if not plugin_title: plugin_title = get_plugin_title(plugin_name)
try:
from BTPanel import request,Resp
is_cli = False
except:
is_cli = True
if is_cli:
raise get_error_info()
ss = '''404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
During handling of the above exception, another exception occurred:'''
error_info = get_error_info().strip().split(ss)[-1].strip()
request_info = '''REQUEST_DATE: {request_date}
PAN_VERSION: {panel_version}
OS_VERSION: {os_version}
REMOTE_ADDR: {remote_addr}
REQUEST_URI: {method} {full_path}
REQUEST_FORM: {request_form}
USER_AGENT: {user_agent}'''.format(
request_date = getDate(),
remote_addr = GetClientIp(),
method = request.method,
full_path = request.full_path,
request_form = request.form.to_dict(),
user_agent = request.headers.get('User-Agent'),
panel_version = version(),
os_version = get_os_version()
)
result =readFile('{}/BTPanel/templates/default/plugin_error.html'.format(get_panel_path())).format(
plugin_name=plugin_title,
request_info=request_info,
error_title=error_info.split("\n")[-1],
error_msg=error_info
)
return Resp(result,500)
def submit_error(err_msg = None):
try:
if os.path.exists('{}/not_submit_errinfo.pl'.format(get_panel_path())): return False
from BTPanel import request
import system
if not err_msg: err_msg = get_error_info()
pdata = {}
pdata['err_info'] = err_msg
pdata['path_full'] = request.full_path
pdata['version'] = 'Linux-Panel-%s' % version()
pdata['os'] = system.system().GetSystemVersion()
pdata['py_version'] = sys.version
pdata['install_date'] = int(os.stat('{}/common.py'.format(get_class_path())).st_mtime)