forked from aaPanel/BaoTa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.py
2310 lines (2064 loc) · 94.7 KB
/
config.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面板 x3
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2017 宝塔软件(http://bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author: hwliang <[email protected]>
# +-------------------------------------------------------------------
import base64
import public,re,sys,os,nginx,apache,json,time,ols
try:
import pyotp
except:
public.ExecShell("pip install pyotp &")
try:
from BTPanel import session,admin_path_checks,g,request,cache
import send_mail
except:pass
class config:
_setup_path = "/www/server/panel"
_key_file = _setup_path+"/data/two_step_auth.txt"
_bk_key_file = _setup_path + "/data/bk_two_step_auth.txt"
_username_file = _setup_path + "/data/username.txt"
_core_fle_path = _setup_path + '/data/qrcode'
__mail_config = '/www/server/panel/data/stmp_mail.json'
__mail_list_data = '/www/server/panel/data/mail_list.json'
__dingding_config = '/www/server/panel/data/dingding.json'
__mail_list = []
__weixin_user = []
def __init__(self):
try:
self.mail = send_mail.send_mail()
if not os.path.exists(self.__mail_list_data):
ret = []
public.writeFile(self.__mail_list_data, json.dumps(ret))
else:
try:
mail_data = json.loads(public.ReadFile(self.__mail_list_data))
self.__mail_list = mail_data
except:
ret = []
public.writeFile(self.__mail_list_data, json.dumps(ret))
except:pass
# 返回配置邮件地址
def return_mail_list(self, get):
return public.returnMsg(True, self.__mail_list)
# 删除邮件接口
def del_mail_list(self, get):
emial = get.email.strip()
if emial in self.__mail_list:
self.__mail_list.remove(emial)
public.writeFile(self.__mail_list_data, json.dumps(self.__mail_list))
return public.returnMsg(True, '删除成功')
else:
return public.returnMsg(True, '邮件不存在')
#添加接受邮件地址
def add_mail_address(self, get):
if not hasattr(get, 'email'): return public.returnMsg(False, '请输入邮箱')
emailformat = re.compile(r'[a-zA-Z0-9.-_+%]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+')
if not emailformat.search(get.email): return public.returnMsg(False, '请输入正确的邮箱')
# 测试发送邮件
if get.email.strip() in self.__mail_list: return public.returnMsg(False, '邮箱已经存在')
self.__mail_list.append(get.email.strip())
public.writeFile(self.__mail_list_data, json.dumps(self.__mail_list))
return public.returnMsg(True, '添加成功')
# 添加自定义邮箱地址
def user_mail_send(self, get):
if not (hasattr(get, 'email') or hasattr(get, 'stmp_pwd') or hasattr(get, 'hosts') or hasattr(get, 'port')):
return public.returnMsg(False, '请填写完整信息')
# 自定义邮件
self.mail.qq_stmp_insert(get.email.strip(), get.stmp_pwd.strip(), get.hosts.strip(),get.port.strip())
# 测试发送
if self.mail.qq_smtp_send(get.email.strip(), '宝塔告警测试邮件', '宝塔告警测试邮件'):
if not get.email.strip() in self.__mail_list:
self.__mail_list.append(get.email.strip())
public.writeFile(self.__mail_list_data, json.dumps(self.__mail_list))
return public.returnMsg(True, '添加成功')
else:
ret = []
public.writeFile(self.__mail_config, json.dumps(ret))
return public.returnMsg(False, '邮件发送失败,请检查信息是否正确,或者更换其他端口进行尝试')
# 查看自定义邮箱配置
def get_user_mail(self, get):
qq_mail_info = json.loads(public.ReadFile(self.__mail_config))
if len(qq_mail_info) == 0:
return public.returnMsg(False, '无信息')
if not 'port' in qq_mail_info:qq_mail_info['port']=465
return public.returnMsg(True, qq_mail_info)
#清空数据
def set_empty(self,get):
type=get.type.strip()
if type=='dingding':
ret = []
public.writeFile(self.__dingding_config, json.dumps(ret))
return public.returnMsg(True, '清空成功')
else:
ret = []
public.writeFile(self.__mail_config, json.dumps(ret))
return public.returnMsg(True, '清空成功')
# 用户自定义邮件发送
def user_stmp_mail_send(self, get):
if not (hasattr(get, 'email')): return public.returnMsg(False, '请填写邮件地址')
emailformat = re.compile(r'[a-zA-Z0-9.-_+%]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+')
if not emailformat.search(get.email): return public.returnMsg(False, '请输入正确的邮箱')
# 测试发送邮件
if not get.email.strip() in self.__mail_list: return public.returnMsg(True, '邮箱不存在,请添加到邮箱列表中')
if not (hasattr(get, 'title')): return public.returnMsg(False, '请填写邮件标题')
if not (hasattr(get, 'body')): return public.returnMsg(False, '请输入邮件内容')
# 先判断是否存在stmp信息
qq_mail_info = json.loads(public.ReadFile(self.__mail_config))
if len(qq_mail_info) == 0:
return public.returnMsg(False, '未找到STMP的信息,请在设置中重新添加自定义邮件STMP信息')
if self.mail.qq_smtp_send(get.email.strip(), get.title.strip(), get.body):
# 发送成功
return public.returnMsg(True, '发送成功')
else:
return public.returnMsg(False, '发送失败')
# 查看能使用的告警通道
def get_settings(self, get):
qq_mail_info = json.loads(public.ReadFile(self.__mail_config))
if len(qq_mail_info) == 0:
user_mail = False
else:
user_mail = True
dingding_info = json.loads(public.ReadFile(self.__dingding_config))
if len(dingding_info) == 0:
dingding = False
else:
dingding = True
ret = {}
ret['user_mail'] = {"user_name": user_mail, "mail_list": self.__mail_list,"info":self.get_user_mail(get)}
ret['dingding'] = {"dingding": dingding,"info":self.get_dingding(get)}
return ret
# 设置钉钉报警
def set_dingding(self, get):
if not (hasattr(get, 'url') or hasattr(get, 'atall')):
return public.returnMsg(False, '请填写完整信息')
if get.atall=='True' or get.atall=='1':
get.atall = 'True'
else: get.atall = 'False'
self.mail.dingding_insert(get.url.strip(), get.atall)
if self.mail.dingding_send('宝塔告警测试'):
return public.returnMsg(True, '添加成功')
else:
ret = []
public.writeFile(self.__dingding_config, json.dumps(ret))
return public.returnMsg(False, '添加失败,请查看URL是否正确')
# 查看钉钉
def get_dingding(self, get):
qq_mail_info = json.loads(public.ReadFile(self.__dingding_config))
if len(qq_mail_info) == 0:
return public.returnMsg(False, '无信息')
return public.returnMsg(True, qq_mail_info)
# 使用钉钉发送消息
def user_dingding_send(self, get):
qq_mail_info = json.loads(public.ReadFile(self.__dingding_config))
if len(qq_mail_info) == 0:
return public.returnMsg(False, '未找到您配置的钉钉的配置信息,请在设置中添加')
if not (hasattr(get, 'content')): return public.returnMsg(False, '请输入你需要发送的数据')
if self.mail.dingding_send(get.content):
return public.returnMsg(True, '发送成功')
else:
return public.returnMsg(False, '发送失败')
def getPanelState(self,get):
return os.path.exists('/www/server/panel/data/close.pl')
def reload_session(self):
userInfo = public.M('users').where("id=?",(1,)).field('username,password').find()
token = public.Md5(userInfo['username'] + '/' + userInfo['password'])
public.writeFile('/www/server/panel/data/login_token.pl',token)
skey = 'login_token'
cache.set(skey,token)
sess_path = 'data/sess_files'
if not os.path.exists(sess_path):
os.makedirs(sess_path,384)
self.clean_sess_files(sess_path)
sess_key = public.get_sess_key()
sess_file = os.path.join(sess_path,sess_key)
public.writeFile(sess_file,str(int(time.time()+86400)))
public.set_mode(sess_file,'600')
session['login_token'] = token
def clean_sess_files(self,sess_path):
'''
@name 清理过期的sess_file
@auther hwliang<2020-07-25>
@param sess_path(string) sess_files目录
@return void
'''
s_time = time.time()
for fname in os.listdir(sess_path):
try:
if len(fname) != 32: continue
sess_file = os.path.join(sess_path,fname)
if not os.path.isfile(sess_file): continue
sess_tmp = public.ReadFile(sess_file)
if not sess_tmp:
if os.path.exists(sess_file):
os.remove(sess_file)
if s_time > int(sess_tmp):
os.remove(sess_file)
except:
pass
def get_password_safe_file(self):
'''
@name 获取密码复杂度配置文件
@auther hwliang<2021-10-18>
@return string
'''
return public.get_panel_path() + '/data/check_password_safe.pl'
def check_password_safe(self,password):
'''
@name 密码复杂度验证
@auther hwliang<2021-10-18>
@param password(string) 密码
@return bool
'''
# 是否检测密码复杂度
is_check_file = self.get_password_safe_file()
if not os.path.exists(is_check_file): return True
# 密码长度验证
if len(password) < 8: return False
num = 0
# 密码是否包含数字
if re.search(r'[0-9]+',password): num += 1
# 密码是否包含小写字母
if re.search(r'[a-z]+',password): num += 1
# 密码是否包含大写字母
if re.search(r'[A-Z]+',password): num += 1
# 密码是否包含特殊字符
if re.search(r'[^\w\s]+',password): num += 1
# 密码是否包含以上任意3种组合
if num < 3: return False
return True
def set_password_safe(self,get):
'''
@name 设置密码复杂度
@auther hwliang<2021-10-18>
@param get(string) 参数
@return dict
'''
is_check_file = self.get_password_safe_file()
if os.path.exists(is_check_file):
os.remove(is_check_file)
public.WriteLog('TYPE_PANEL','关闭密码复杂度验证')
return public.returnMsg(True,'已关闭密码复杂度验证')
else:
public.writeFile(is_check_file,'True')
public.WriteLog('TYPE_PANEL','开启密码复杂度验证')
return public.returnMsg(True,'已开启密码复杂度验证')
def get_password_safe(self,get):
'''
@name 获取密码复杂度
@auther hwliang<2021-10-18>
@param get(string) 参数
@return bool
'''
is_check_file = self.get_password_safe_file()
return os.path.exists(is_check_file)
def get_password_expire_file(self):
'''
@name 获取密码过期配置文件
@auther hwliang<2021-10-18>
@return string
'''
return public.get_panel_path() + '/data/password_expire.pl'
def set_password_expire(self,get):
'''
@name 设置密码过期时间
@auther hwliang<2021-10-18>
@param get<dict_obj>{
expire: int<密码过期时间> 单位:天,
}
@return dict
'''
expire = int(get.expire)
expire_file = self.get_password_expire_file()
if expire <= 0:
if os.path.exists(expire_file):
os.remove(expire_file)
public.WriteLog('TYPE_PANEL','关闭密码过期验证')
return public.returnMsg(True,'已关闭密码过期验证')
min_expire = 10
max_expire = 365 * 5
if expire < min_expire: return public.returnMsg(False,'密码过期时间不能小于{}天'.format(min_expire))
if expire > max_expire: return public.returnMsg(False,'密码过期时间不能大于{}天'.format(max_expire))
public.writeFile(self.get_password_expire_file(),str(expire))
if expire > 0:
expire_time_file = public.get_panel_path() + '/data/password_expire_time.pl'
public.writeFile(expire_time_file,str(int(time.time()) + (expire * 86400)))
public.WriteLog('TYPE_PANEL','设置密码过期时间为:[{}]天'.format(expire))
return public.returnMsg(True,'已设置密码过期时间为:[{}]天'.format(expire))
def get_password_config(self,get=None):
'''
@name 获取密码配置
@auther hwliang<2021-10-18>
@param get<dict_obj> 参数
@return dict{expire:int,expire_time:int,password_safe:bool}
'''
expire_file = self.get_password_expire_file()
expire = 0
expire_time=0
if os.path.exists(expire_file):
expire = public.readFile(expire_file)
try:
expire = int(expire)
except:
expire = 0
# 检查密码过期时间文件是否存在
expire_time_file = public.get_panel_path() + '/data/password_expire_time.pl'
if not os.path.exists(expire_time_file) and expire > 0:
public.writeFile(expire_time_file,str(int(time.time()) + (expire * 86400)))
expire_time = public.readFile(expire_time_file)
if expire_time:
expire_time = int(expire_time)
else:
expire_time = 0
data = {}
data['expire'] = expire
data['expire_time'] = expire_time
data['password_safe'] = self.get_password_safe(get)
data['ps'] = '当前未开启密码过期配置,为了您的面板安全,请考虑开启!'
if data['expire_time']:
data['expire_day'] = int((expire_time - time.time()) / 86400)
if data['expire_day'] < 10:
if data['expire_day'] <= 0:
data['ps'] = '您的密码已经过期,为防止下次无法登录,请立即修改密码!'
else:
data['ps'] = "您的面板密码还有 <span style='color:red;'>{}</span> 天就过期了,为了不影响您正常登录,请尽快修改密码!".format(data['expire_day'])
else:
data['ps'] = "您的面板密码离过期时间还有 <span style='color:green;'>{}</span> 天!".format(data['expire_day'])
return data
def setPassword(self,get):
get.password1 = public.url_decode(get.password1)
get.password2 = public.url_decode(get.password2)
if get.password1 != get.password2: return public.returnMsg(False,'USER_PASSWORD_CHECK')
if len(get.password1) < 5: return public.returnMsg(False,'USER_PASSWORD_LEN')
if not self.check_password_safe(get.password1): return public.returnMsg(False,'密码复杂度验证失败,要求:长度大于8位,数字、大写字母、小写字母、特殊字符最少3项组合')
public.M('users').where("username=?",(session['username'],)).setField('password',public.password_salt(public.md5(get.password1.strip()),username=session['username']))
public.WriteLog('TYPE_PANEL','USER_PASSWORD_SUCCESS',(session['username'],))
self.reload_session()
# 密码过期时间
expire_time_file = public.get_panel_path() + '/data/password_expire_time.pl'
if os.path.exists(expire_time_file): os.remove(expire_time_file)
self.get_password_config(None)
if session.get('password_expire',False):
session['password_expire'] = False
return public.returnMsg(True,'USER_PASSWORD_SUCCESS')
def setUsername(self,get):
get.username1 = public.url_decode(get.username1)
get.username2 = public.url_decode(get.username2)
if get.username1 != get.username2: return public.returnMsg(False,'USER_USERNAME_CHECK')
if len(get.username1) < 3: return public.returnMsg(False,'USER_USERNAME_LEN')
public.M('users').where("username=?",(session['username'],)).setField('username',get.username1.strip())
public.WriteLog('TYPE_PANEL','USER_USERNAME_SUCCESS',(session['username'],get.username2))
session['username'] = get.username1
self.reload_session()
return public.returnMsg(True,'USER_USERNAME_SUCCESS')
#取用户列表
def get_users(self,args):
data = public.M('users').field('id,username').select()
return data
# 创建新用户
def create_user(self,args):
args.username = public.url_decode(args.username)
args.password = public.url_decode(args.password)
if session['uid'] != 1: return public.returnMsg(False,'没有权限!')
if len(args.username) < 2: return public.returnMsg(False,'用户名不能少于2位')
if len(args.password) < 8: return public.returnMsg(False,'密码不能少于8位')
pdata = {
"username": args.username.strip(),
"password": public.password_salt(public.md5(args.password.strip()),username=args.username.strip())
}
if(public.M('users').where('username=?',(pdata['username'],)).count()):
return public.returnMsg(False,'指定用户名已存在!')
if(public.M('users').insert(pdata)):
public.WriteLog('用户管理','创建新用户{}'.format(pdata['username']))
return public.returnMsg(True,'创建新用户{}成功!'.format(pdata['username']))
return public.returnMsg(False,'创建新用户失败!')
# 删除用户
def remove_user(self,args):
if session['uid'] != 1: return public.returnMsg(False,'没有权限!')
if int(args.id) == 1: return public.returnMsg(False,'不能删除初始默认用户!')
username = public.M('users').where('id=?',(args.id,)).getField('username')
if not username: return public.returnMsg(False,'指定用户不存在!')
if(public.M('users').where('id=?',(args.id,)).delete()):
public.WriteLog('用户管理','删除用户[{}]'.format(username))
return public.returnMsg(True,'删除用户{}成功!'.format(username))
return public.returnMsg(False,'用户删除失败!')
# 修改用户
def modify_user(self,args):
if session['uid'] != 1: return public.returnMsg(False,'没有权限!')
username = public.M('users').where('id=?',(args.id,)).getField('username')
pdata = {}
if 'username' in args:
args.username = public.url_decode(args.username)
if len(args.username) < 2: return public.returnMsg(False,'用户名不能少于2位')
pdata['username'] = args.username.strip()
if 'password' in args:
if args.password:
args.password = public.url_decode(args.password)
if len(args.password) < 8: return public.returnMsg(False,'密码不能少于8位')
pdata['password'] = public.password_salt(public.md5(args.password.strip()),username=username)
if(public.M('users').where('id=?',(args.id,)).update(pdata)):
public.WriteLog('用户管理',"编辑用户{}".format(username))
return public.returnMsg(True,'修改成功!')
return public.returnMsg(False,'没有提交修改!')
def setPanel(self,get):
if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK')
if 'limitip' in get:
if get.limitip.find('/') != -1:
return public.returnMsg(False,'授权IP格式不正确,不支持子网段写法')
isReWeb = False
sess_out_path = 'data/session_timeout.pl'
if 'session_timeout' in get:
session_timeout = int(get.session_timeout)
s_time_tmp = public.readFile(sess_out_path)
if not s_time_tmp: s_time_tmp = '0'
if int(s_time_tmp) != session_timeout:
if session_timeout < 300: return public.returnMsg(False,'超时时间不能小于300秒')
if session_timeout > 86400: return public.returnMsg(False,'超时时间不能大于86400秒')
public.writeFile(sess_out_path,str(session_timeout))
isReWeb = True
workers_p = 'data/workers.pl'
if 'workers' in get:
workers = int(get.workers)
if int(public.readFile(workers_p)) != workers:
if workers < 1 or workers > 1024: return public.returnMsg(False,'面板线程数范围应该在1-1024之间')
public.writeFile(workers_p,str(workers))
isReWeb = True
if get.domain:
reg = r"^([\w\-\*]{1,100}\.){1,4}(\w{1,10}|\w{1,10}\.\w{1,10})$"
if not re.match(reg, get.domain): return public.returnMsg(False,'SITE_ADD_ERR_DOMAIN')
oldPort = public.GetHost(True)
if not 'port' in get:
get.port = oldPort
newPort = get.port
if oldPort != get.port:
get.port = str(int(get.port))
if self.IsOpen(get.port):
return public.returnMsg(False,'PORT_CHECK_EXISTS',(get.port,))
if int(get.port) >= 65535 or int(get.port) < 100: return public.returnMsg(False,'PORT_CHECK_RANGE')
public.writeFile('data/port.pl',get.port)
import firewalls
get.ps = public.getMsg('PORT_CHECK_PS')
fw = firewalls.firewalls()
fw.AddAcceptPort(get)
get.port = oldPort
get.id = public.M('firewall').where("port=?",(oldPort,)).getField('id')
fw.DelAcceptPort(get)
isReWeb = True
if get.webname != session['title']:
session['title'] = public.xssencode2(get.webname)
public.SetConfigValue('title',public.xssencode2(get.webname))
limitip = public.readFile('data/limitip.conf')
if get.limitip != limitip:
public.writeFile('data/limitip.conf',get.limitip)
cache.set('limit_ip',[])
public.writeFile('data/domain.conf',get.domain.strip())
public.writeFile('data/iplist.txt',get.address)
import files
fs = files.files()
if not fs.CheckDir(get.backup_path): return public.returnMsg(False,'不能使用系统关键目录作为默认备份目录')
if not fs.CheckDir(get.sites_path): return public.returnMsg(False,'不能使用系统关键目录作为默认建站目录')
public.M('config').where("id=?",('1',)).save('backup_path,sites_path',(get.backup_path,get.sites_path))
session['config']['backup_path'] = os.path.join('/',get.backup_path)
session['config']['sites_path'] = os.path.join('/',get.sites_path)
db_backup = get.backup_path + '/database'
if not os.path.exists(db_backup):
try:
os.makedirs(db_backup,384)
except:
public.ExecShell('mkdir -p ' + db_backup)
site_backup = get.backup_path + '/site'
if not os.path.exists(site_backup):
try:
os.makedirs(site_backup,384)
except:
public.ExecShell('mkdir -p ' + site_backup)
mhost = public.GetHost()
if get.domain.strip(): mhost = get.domain
data = {'uri':request.path,'host':mhost+':'+newPort,'status':True,'isReWeb':isReWeb,'msg':public.getMsg('PANEL_SAVE')}
public.WriteLog('TYPE_PANEL','PANEL_SET_SUCCESS',(newPort,get.domain,get.backup_path,get.sites_path,get.address,get.limitip))
if isReWeb: public.restart_panel()
return data
def set_admin_path(self,get):
get.admin_path = get.admin_path.strip()
if len(get.admin_path) < 6: return public.returnMsg(False,'安全入口地址长度不能小于6位!')
if get.admin_path in admin_path_checks: return public.returnMsg(False,'该入口已被面板占用,请使用其它入口!')
if not public.path_safe_check(get.admin_path) or get.admin_path[-1] == '.': return public.returnMsg(False,'入口地址格式不正确,示例: /my_panel')
if get.admin_path[0] != '/': return public.returnMsg(False,'入口地址格式不正确,示例: /my_panel')
admin_path_file = 'data/admin_path.pl'
admin_path = '/'
if os.path.exists(admin_path_file): admin_path = public.readFile(admin_path_file).strip()
if get.admin_path != admin_path:
public.writeFile(admin_path_file,get.admin_path)
public.restart_panel()
return public.returnMsg(True,'修改成功!')
def setPathInfo(self,get):
#设置PATH_INFO
version = get.version
type = get.type
if public.get_webserver() == 'nginx':
path = public.GetConfigValue('setup_path')+'/nginx/conf/enable-php-'+version+'.conf'
conf = public.readFile(path)
rep = r"\s+#*include\s+pathinfo.conf;"
if type == 'on':
conf = re.sub(rep,'\n\t\t\tinclude pathinfo.conf;',conf)
else:
conf = re.sub(rep,'\n\t\t\t#include pathinfo.conf;',conf)
public.writeFile(path,conf)
public.serviceReload()
path = public.GetConfigValue('setup_path')+'/php/'+version+'/etc/php.ini'
conf = public.readFile(path)
rep = r"\n*\s*cgi\.fix_pathinfo\s*=\s*([0-9]+)\s*\n"
status = '0'
if type == 'on':status = '1'
conf = re.sub(rep,"\ncgi.fix_pathinfo = "+status+"\n",conf)
public.writeFile(path,conf)
public.WriteLog("TYPE_PHP", "PHP_PATHINFO_SUCCESS",(version,type))
public.phpReload(version)
return public.returnMsg(True,'SET_SUCCESS')
#设置文件上传大小限制
def setPHPMaxSize(self,get):
version = get.version
max = get.max
if int(max) < 2: return public.returnMsg(False,'PHP_UPLOAD_MAX_ERR')
#设置PHP
path = public.GetConfigValue('setup_path')+'/php/'+version+'/etc/php.ini'
ols_php_path = '/usr/local/lsws/lsphp{}/etc/php/{}.{}/litespeed/php.ini'.format(get.version, get.version[0],get.version[1])
if os.path.exists('/etc/redhat-release'):
ols_php_path = '/usr/local/lsws/lsphp' + get.version + '/etc/php.ini'
for p in [path,ols_php_path]:
if not p:
continue
if not os.path.exists(p):
continue
conf = public.readFile(p)
rep = r"\nupload_max_filesize\s*=\s*[0-9]+M?m?"
conf = re.sub(rep,r'\nupload_max_filesize = '+max+'M',conf)
rep = r"\npost_max_size\s*=\s*[0-9]+M?m?"
conf = re.sub(rep,r'\npost_max_size = '+max+'M',conf)
public.writeFile(p,conf)
if public.get_webserver() == 'nginx':
#设置Nginx
path = public.GetConfigValue('setup_path')+'/nginx/conf/nginx.conf'
conf = public.readFile(path)
rep = r"client_max_body_size\s+([0-9]+)m?M?"
tmp = re.search(rep,conf).groups()
if int(tmp[0]) < int(max):
conf = re.sub(rep,'client_max_body_size '+max+'m',conf)
public.writeFile(path,conf)
public.serviceReload()
public.phpReload(version)
public.WriteLog("TYPE_PHP", "PHP_UPLOAD_MAX",(version,max))
return public.returnMsg(True,'SET_SUCCESS')
#设置禁用函数
def setPHPDisable(self,get):
filename = public.GetConfigValue('setup_path') + '/php/' + get.version + '/etc/php.ini'
ols_php_path = '/usr/local/lsws/lsphp{}/etc/php/{}.{}/litespeed/php.ini'.format(get.version, get.version[0],get.version[1])
if os.path.exists('/etc/redhat-release'):
ols_php_path = '/usr/local/lsws/lsphp' + get.version + '/etc/php.ini'
if not os.path.exists(filename): return public.returnMsg(False,'PHP_NOT_EXISTS')
for file in [filename,ols_php_path]:
if not os.path.exists(file):
continue
phpini = public.readFile(file)
rep = r"disable_functions\s*=\s*.*\n"
phpini = re.sub(rep, 'disable_functions = ' + get.disable_functions + "\n", phpini)
public.WriteLog('TYPE_PHP','PHP_DISABLE_FUNCTION',(get.version,get.disable_functions))
public.writeFile(file,phpini)
public.phpReload(get.version)
public.serviceReload()
return public.returnMsg(True,'SET_SUCCESS')
#设置PHP超时时间
def setPHPMaxTime(self,get):
time = get.time
version = get.version
if int(time) < 30 or int(time) > 86400: return public.returnMsg(False,'PHP_TIMEOUT_ERR')
file = public.GetConfigValue('setup_path')+'/php/'+version+'/etc/php-fpm.conf'
conf = public.readFile(file)
rep = r"request_terminate_timeout\s*=\s*([0-9]+)\n"
conf = re.sub(rep,"request_terminate_timeout = "+time+"\n",conf)
public.writeFile(file,conf)
file = '/www/server/php/'+version+'/etc/php.ini'
phpini = public.readFile(file)
rep = r"max_execution_time\s*=\s*([0-9]+)\r?\n"
phpini = re.sub(rep,"max_execution_time = "+time+"\n",phpini)
rep = r"max_input_time\s*=\s*([0-9]+)\r?\n"
phpini = re.sub(rep,"max_input_time = "+time+"\n",phpini)
public.writeFile(file,phpini)
if public.get_webserver() == 'nginx':
#设置Nginx
path = public.GetConfigValue('setup_path')+'/nginx/conf/nginx.conf'
conf = public.readFile(path)
rep = r"fastcgi_connect_timeout\s+([0-9]+);"
tmp = re.search(rep, conf).groups()
if int(tmp[0]) < int(time):
conf = re.sub(rep,'fastcgi_connect_timeout '+time+';',conf)
rep = r"fastcgi_send_timeout\s+([0-9]+);"
conf = re.sub(rep,'fastcgi_send_timeout '+time+';',conf)
rep = r"fastcgi_read_timeout\s+([0-9]+);"
conf = re.sub(rep,'fastcgi_read_timeout '+time+';',conf)
public.writeFile(path,conf)
public.WriteLog("TYPE_PHP", "PHP_TIMEOUT",(version,time))
public.serviceReload()
public.phpReload(version)
return public.returnMsg(True, 'SET_SUCCESS')
#取FPM设置
def getFpmConfig(self,get):
version = get.version
file = public.GetConfigValue('setup_path')+"/php/"+version+"/etc/php-fpm.conf"
conf = public.readFile(file)
data = {}
rep = r"\s*pm.max_children\s*=\s*([0-9]+)\s*"
tmp = re.search(rep, conf).groups()
data['max_children'] = tmp[0]
rep = r"\s*pm.start_servers\s*=\s*([0-9]+)\s*"
tmp = re.search(rep, conf).groups()
data['start_servers'] = tmp[0]
rep = r"\s*pm.min_spare_servers\s*=\s*([0-9]+)\s*"
tmp = re.search(rep, conf).groups()
data['min_spare_servers'] = tmp[0]
rep = r"\s*pm.max_spare_servers \s*=\s*([0-9]+)\s*"
tmp = re.search(rep, conf).groups()
data['max_spare_servers'] = tmp[0]
rep = r"\s*pm\s*=\s*(\w+)\s*"
tmp = re.search(rep, conf).groups()
data['pm'] = tmp[0]
rep = r"\s*listen.allowed_clients\s*=\s*([\w\.,/]+)\s*"
tmp = re.search(rep, conf).groups()
data['allowed'] = tmp[0]
data['unix'] = 'unix'
data['port'] = ''
data['bind'] = '/tmp/php-cgi-{}.sock'.format(version)
fpm_address = public.get_fpm_address(version,True)
if not isinstance(fpm_address,str):
data['unix'] = 'tcp'
data['port'] = fpm_address[1]
data['bind'] = fpm_address[0]
return data
#设置
def setFpmConfig(self,get):
version = get.version
max_children = get.max_children
start_servers = get.start_servers
min_spare_servers = get.min_spare_servers
max_spare_servers = get.max_spare_servers
pm = get.pm
if not pm in ['static','dynamic','ondemand']:
return public.returnMsg(False,'错误的运行模式!')
file = public.GetConfigValue('setup_path')+"/php/"+version+"/etc/php-fpm.conf"
conf = public.readFile(file)
rep = r"\s*pm.max_children\s*=\s*([0-9]+)\s*"
conf = re.sub(rep, "\npm.max_children = "+max_children, conf)
rep = r"\s*pm.start_servers\s*=\s*([0-9]+)\s*"
conf = re.sub(rep, "\npm.start_servers = "+start_servers, conf)
rep = r"\s*pm.min_spare_servers\s*=\s*([0-9]+)\s*"
conf = re.sub(rep, "\npm.min_spare_servers = "+min_spare_servers, conf)
rep = r"\s*pm.max_spare_servers \s*=\s*([0-9]+)\s*"
conf = re.sub(rep, "\npm.max_spare_servers = "+max_spare_servers+"\n", conf)
rep = r"\s*pm\s*=\s*(\w+)\s*"
conf = re.sub(rep, "\npm = "+pm+"\n", conf)
if pm == 'ondemand':
if conf.find('listen.backlog = -1') != -1:
rep = r"\s*listen\.backlog\s*=\s*([0-9-]+)\s*"
conf = re.sub(rep, "\nlisten.backlog = 8192\n", conf)
if get.listen == 'unix':
listen = '/tmp/php-cgi-{}.sock'.format(version)
else:
default_listen = '127.0.0.1:10{}1'.format(version)
if 'bind_port' in get:
if get.bind_port.find('sock') != -1:
listen = default_listen
else:
listen = get.bind_port
else:
listen = default_listen
rep = r'\s*listen\s*=\s*.+\s*'
conf = re.sub(rep, "\nlisten = "+listen+"\n", conf)
if 'allowed' in get:
if not get.allowed: get.allowed = '127.0.0.1'
rep = r"\s*listen.allowed_clients\s*=\s*([\w\.,/]+)\s*"
conf = re.sub(rep, "\nlisten.allowed_clients = "+get.allowed+"\n", conf)
public.writeFile(file,conf)
public.phpReload(version)
public.sync_php_address(version)
public.WriteLog("TYPE_PHP",'PHP_CHILDREN', (version,max_children,start_servers,min_spare_servers,max_spare_servers))
return public.returnMsg(True, 'SET_SUCCESS')
#同步时间
def syncDate(self,get):
time_str = public.HttpGet(public.GetConfigValue('home') + '/api/index/get_time')
new_time = int(time_str)
time_arr = time.localtime(new_time)
date_str = time.strftime("%Y-%m-%d %H:%M:%S", time_arr)
public.ExecShell('date -s "%s"' % date_str)
public.WriteLog("TYPE_PANEL", "DATE_SUCCESS")
return public.returnMsg(True,"DATE_SUCCESS")
def IsOpen(self,port):
#检查端口是否占用
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect(('127.0.0.1',int(port)))
s.shutdown(2)
return True
except:
return False
#设置是否开启监控
def SetControl(self,get):
try:
if hasattr(get,'day'):
get.day = int(get.day)
get.day = str(get.day)
if(get.day < 1): return public.returnMsg(False,"CONTROL_ERR")
except:
pass
filename = 'data/control.conf'
if get.type == '1':
public.writeFile(filename,get.day)
public.WriteLog("TYPE_PANEL",'CONTROL_OPEN',(get.day,))
elif get.type == '0':
if os.path.exists(filename): os.remove(filename)
public.WriteLog("TYPE_PANEL", "CONTROL_CLOSE")
elif get.type == 'del':
if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK')
os.remove("data/system.db")
import db
sql = db.Sql()
sql.dbfile('system').create('system')
public.WriteLog("TYPE_PANEL", "CONTROL_CLEAR")
return public.returnMsg(True,"CONTROL_CLEAR")
else:
data = {}
if os.path.exists(filename):
try:
data['day'] = int(public.readFile(filename))
except:
data['day'] = 30
data['status'] = True
else:
data['day'] = 30
data['status'] = False
return data
return public.returnMsg(True,"SET_SUCCESS")
#关闭面板
def ClosePanel(self,get):
filename = 'data/close.pl'
if os.path.exists(filename):
os.remove(filename)
return public.returnMsg(True,'开启成功')
public.writeFile(filename,'True')
public.ExecShell("chmod 600 " + filename)
public.ExecShell("chown root.root " + filename)
return public.returnMsg(True,'PANEL_CLOSE')
#设置自动更新
def AutoUpdatePanel(self,get):
#return public.returnMsg(False,'体验服务器,禁止修改!')
filename = 'data/autoUpdate.pl'
if os.path.exists(filename):
os.remove(filename)
else:
public.writeFile(filename,'True')
public.ExecShell("chmod 600 " + filename)
public.ExecShell("chown root.root " + filename)
return public.returnMsg(True,'SET_SUCCESS')
#设置二级密码
def SetPanelLock(self,get):
path = 'data/lock'
if not os.path.exists(path):
public.ExecShell('mkdir ' + path)
public.ExecShell("chmod 600 " + path)
public.ExecShell("chown root.root " + path)
keys = ['files','tasks','config']
for name in keys:
filename = path + '/' + name + '.pl'
if hasattr(get,name):
public.writeFile(filename,'True')
else:
if os.path.exists(filename): os.remove(filename)
#设置PHP守护程序
def Set502(self,get):
filename = 'data/502Task.pl'
if os.path.exists(filename):
public.ExecShell('rm -f ' + filename)
else:
public.writeFile(filename,'True')
return public.returnMsg(True,'SET_SUCCESS')
#设置模板
def SetTemplates(self,get):
public.writeFile('data/templates.pl',get.templates)
return public.returnMsg(True,'SET_SUCCESS')
#设置面板SSL
def SetPanelSSL(self,get):
if hasattr(get,"email"):
rep_mail = r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?"
if not re.search(rep_mail,get.email):
return public.returnMsg(False,'邮箱格式不合法')
import setPanelLets
sp = setPanelLets.setPanelLets()
sps = sp.set_lets(get)
return sps
else:
sslConf = '/www/server/panel/data/ssl.pl'
if os.path.exists(sslConf) and not 'cert_type' in get:
public.ExecShell('rm -f ' + sslConf)
g.rm_ssl = True
return public.returnMsg(True,'PANEL_SSL_CLOSE')
else:
if get.cert_type in [0,'0']:
result = self.SavePanelSSL(get)
if not result['status']: return result
public.writeFile(sslConf,'True')
public.writeFile('data/reload.pl','True')
else:
try:
if not self.CreateSSL(): return public.returnMsg(False,'PANEL_SSL_ERR')
public.writeFile(sslConf,'True')
except:
return public.returnMsg(False,'PANEL_SSL_ERR')
return public.returnMsg(True,'PANEL_SSL_OPEN')
#自签证书
def CreateSSL(self):
userInfo = public.get_user_info()
if userInfo:
domains = []
req_host = public.GetHost()
server_ip = public.get_ip()
domains.append(req_host)
if server_ip != req_host and not server_ip in ['127.0.0.1','::1','localhost']:
domains.append(server_ip)
pdata = {
"action":"get_domain_cert",
"company":"宝塔面板",
"domain":','.join(domains),
"uid":userInfo['uid'],
"access_key":userInfo['access_key'],
"panel":1
}
cert_api = 'https://api.bt.cn/bt_cert'
result = json.loads(public.httpPost(cert_api,{'data': json.dumps(pdata)}))
if 'status' in result:
if result['status']:
public.writeFile('ssl/certificate.pem',result['cert'])
public.writeFile('ssl/privateKey.pem',result['key'])
public.writeFile('ssl/baota_root.pfx',base64.b64decode(result['pfx']),'wb+')
public.writeFile('ssl/root_password.pl',result['password'])
return True
if os.path.exists('ssl/input.pl'): return True
import OpenSSL
key = OpenSSL.crypto.PKey()
key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
cert = OpenSSL.crypto.X509()
cert.set_serial_number(0)
cert.get_subject().CN = public.GetLocalIp()
cert.set_issuer(cert.get_subject())
cert.gmtime_adj_notBefore( 0 )
cert.gmtime_adj_notAfter(86400 * 3650)
cert.set_pubkey( key )
cert.sign( key, 'md5' )
cert_ca = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
private_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key)
if len(cert_ca) > 100 and len(private_key) > 100:
public.writeFile('ssl/certificate.pem',cert_ca,'wb+')
public.writeFile('ssl/privateKey.pem',private_key,'wb+')
return True
return False
#生成Token
def SetToken(self,get):
data = {}
data[''] = public.GetRandomString(24)
#取面板列表
def GetPanelList(self,get):
try:
data = public.M('panel').field('id,title,url,username,password,click,addtime').order('click desc').select()
if type(data) == str: data[111]
return data
except:
sql = '''CREATE TABLE IF NOT EXISTS `panel` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`title` TEXT,
`url` TEXT,
`username` TEXT,
`password` TEXT,
`click` INTEGER,
`addtime` INTEGER
);'''
public.M('sites').execute(sql,())
return []
#添加面板资料