forked from aaPanel/BaoTa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
panelSite.py
2997 lines (2616 loc) · 121 KB
/
panelSite.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-2017 宝塔软件(http:#bt.cn) All rights reserved.
#-------------------------------------------------------------------
# Author: 黄文良 <[email protected]>
#-------------------------------------------------------------------
#------------------------------
# 网站管理类
#------------------------------
import io,re,public,os,sys,shutil,json
from BTPanel import session
from flask import request
class panelSite:
siteName = None #网站名称
sitePath = None #根目录
sitePort = None #端口
phpVersion = None #PHP版本
setupPath = None #安装路径
isWriteLogs = None #是否写日志
def __init__(self):
self.setupPath = '/www/server';
path = self.setupPath + '/panel/vhost/nginx'
if not os.path.exists(path): public.ExecShell("mkdir -p " + path + " && chmod -R 644 " + path);
path = self.setupPath + '/panel/vhost/apache'
if not os.path.exists(path): public.ExecShell("mkdir -p " + path + " && chmod -R 644 " + path);
path = self.setupPath + '/panel/vhost/rewrite'
if not os.path.exists(path): public.ExecShell("mkdir -p " + path + " && chmod -R 644 " + path);
path = self.setupPath + '/stop';
if not os.path.exists(path + '/index.html'):
os.system('mkdir -p ' + path);
os.system('wget -O ' + path + '/index.html '+public.get_url()+'/stop.html &');
self.OldConfigFile();
#默认配置文件
def check_default(self):
nginx = self.setupPath + '/panel/vhost/nginx'
httpd = self.setupPath + '/panel/vhost/apache'
httpd_default = '''<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/www/server/apache/htdocs"
ServerName bt.default.com
<Directory "/www/server/apache/htdocs">
SetOutputFilter DEFLATE
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
DirectoryIndex index.html
</Directory>
</VirtualHost>'''
nginx_default = '''server
{
listen 80;
server_name _;
index index.html;
root /www/server/nginx/html;
}'''
if not os.path.exists(httpd + '/0.default.conf') and not os.path.exists(httpd + '/default.conf'): public.writeFile(httpd + '/0.default.conf',httpd_default)
if not os.path.exists(nginx + '/0.default.conf') and not os.path.exists(nginx + '/default.conf'): public.writeFile(nginx + '/0.default.conf',nginx_default)
#添加apache端口
def apacheAddPort(self,port):
filename = self.setupPath+'/apache/conf/httpd.conf';
if not os.path.exists(filename): return;
allConf = public.readFile(filename);
rep = "Listen\s+([0-9]+)\n";
tmp = re.findall(rep,allConf);
if not tmp: return False;
for key in tmp:
if key == port: return False
listen = "\nListen "+tmp[0]
allConf = allConf.replace(listen,listen + "\nListen " + port)
public.writeFile(filename, allConf)
return True
#添加到apache
def apacheAdd(self):
import time
listen = '';
if self.sitePort != '80': self.apacheAddPort(self.sitePort);
acc = public.md5(str(time.time()))[0:8];
try:
httpdVersion = public.readFile(self.setupPath+'/apache/version.pl').strip();
except:
httpdVersion = "";
if httpdVersion == '2.2':
vName = '';
if self.sitePort != '80' and self.sitePort != '443':
vName = "NameVirtualHost *:"+self.sitePort+"\n";
phpConfig = "";
apaOpt = "Order allow,deny\n\t\tAllow from all";
else:
vName = "";
phpConfig ='''
#PHP
<FilesMatch \\.php$>
SetHandler "proxy:unix:/tmp/php-cgi-%s.sock|fcgi://localhost"
</FilesMatch>
''' % (self.phpVersion,)
apaOpt = 'Require all granted';
conf='''%s<VirtualHost *:%s>
ServerAdmin [email protected]
DocumentRoot "%s"
ServerName %s.%s
ServerAlias %s
errorDocument 404 /404.html
ErrorLog "%s-error_log"
CustomLog "%s-access_log" combined
#DENY FILES
<Files ~ (\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)$>
Order allow,deny
Deny from all
</Files>
%s
#PATH
<Directory "%s">
SetOutputFilter DEFLATE
Options FollowSymLinks
AllowOverride All
%s
DirectoryIndex index.php index.html index.htm default.php default.html default.htm
</Directory>
</VirtualHost>''' % (vName,self.sitePort,self.sitePath,acc,self.siteName,self.siteName,public.GetConfigValue('logs_path')+'/'+self.siteName,public.GetConfigValue('logs_path')+'/'+self.siteName,phpConfig,self.sitePath,apaOpt)
htaccess = self.sitePath+'/.htaccess'
if not os.path.exists(htaccess): public.writeFile(htaccess, ' ');
public.ExecShell('chmod -R 755 ' + htaccess);
public.ExecShell('chown -R www:www ' + htaccess);
filename = self.setupPath+'/panel/vhost/apache/'+self.siteName+'.conf'
public.writeFile(filename,conf)
return True
#添加到nginx
def nginxAdd(self):
conf='''server
{
listen %s;
server_name %s;
index index.php index.html index.htm default.php default.htm default.html;
root %s;
#SSL-START %s
#error_page 404/404.html;
#SSL-END
#ERROR-PAGE-START %s
error_page 404 /404.html;
error_page 502 /502.html;
#ERROR-PAGE-END
#PHP-INFO-START %s
include enable-php-%s.conf;
#PHP-INFO-END
#REWRITE-START %s
include %s/panel/vhost/rewrite/%s.conf;
#REWRITE-END
#禁止访问的文件或目录
location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)
{
return 404;
}
#一键申请SSL证书验证目录相关设置
location ~ \.well-known{
allow all;
}
location ~ .*\\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
error_log off;
access_log /dev/null;
}
location ~ .*\\.(js|css)?$
{
expires 12h;
error_log off;
access_log /dev/null;
}
access_log %s.log;
error_log %s.error.log;
}''' % (self.sitePort,self.siteName,self.sitePath,public.getMsg('NGINX_CONF_MSG1'),public.getMsg('NGINX_CONF_MSG2'),public.getMsg('NGINX_CONF_MSG3'),self.phpVersion,public.getMsg('NGINX_CONF_MSG4'),self.setupPath,self.siteName,public.GetConfigValue('logs_path')+'/'+self.siteName,public.GetConfigValue('logs_path')+'/'+self.siteName)
#写配置文件
filename = self.setupPath+'/panel/vhost/nginx/'+self.siteName+'.conf'
public.writeFile(filename,conf);
#生成伪静态文件
urlrewritePath = self.setupPath+'/panel/vhost/rewrite';
urlrewriteFile = urlrewritePath+'/'+self.siteName+'.conf';
if not os.path.exists(urlrewritePath): os.makedirs(urlrewritePath);
open(urlrewriteFile,'w+').close();
return True;
#添加站点
def AddSite(self,get):
self.check_default()
isError = public.checkWebConfig()
if isError != True:
return public.returnMsg(False,'ERROR: 检测到配置文件有错误,请先排除后再操作<br><br><a style="color:red;">'+isError.replace("\n",'<br>')+'</a>');
import json,files
get.path = self.__get_site_format_path(get.path)
siteMenu = json.loads(get.webname)
self.siteName = self.ToPunycode(siteMenu['domain'].strip().split(':')[0]).strip();
self.sitePath = self.ToPunycodePath(self.GetPath(get.path.replace(' ','')));
self.sitePort = get.port.strip().replace(' ','');
if self.sitePort == "": get.port = "80";
if not public.checkPort(self.sitePort): return public.returnMsg(False,'SITE_ADD_ERR_PORT');
if hasattr(get,'version'):
self.phpVersion = get.version.replace(' ','');
else:
self.phpVersion = '00';
domain = None
#if siteMenu['count']:
# domain = get.domain.replace(' ','')
#表单验证
if not files.files().CheckDir(self.sitePath) or not self.__check_site_path(self.sitePath): return public.returnMsg(False,'PATH_ERROR');
if len(self.phpVersion) < 2: return public.returnMsg(False,'SITE_ADD_ERR_PHPEMPTY');
reg = "^([\w\-\*]{1,100}\.){1,4}([\w\-]{1,24}|[\w\-]{1,24}\.[\w\-]{1,24})$";
if not re.match(reg, self.siteName): return public.returnMsg(False,'SITE_ADD_ERR_DOMAIN');
if self.siteName.find('*') != -1: return public.returnMsg(False,'SITE_ADD_ERR_DOMAIN_TOW');
if not domain: domain = self.siteName;
#是否重复
sql = public.M('sites');
if sql.where("name=?",(self.siteName,)).count(): return public.returnMsg(False,'SITE_ADD_ERR_EXISTS');
opid = public.M('domain').where("name=?",(self.siteName,)).getField('pid');
if opid:
if public.M('sites').where('id=?',(opid,)).count():
return public.returnMsg(False,'SITE_ADD_ERR_DOMAIN_EXISTS');
public.M('domain').where('pid=?',(opid,)).delete();
#创建根目录
if not os.path.exists(self.sitePath):
os.makedirs(self.sitePath)
public.ExecShell('chmod -R 755 ' + self.sitePath);
public.ExecShell('chown -R www:www ' + self.sitePath);
#创建basedir
self.DelUserInI(self.sitePath);
userIni = self.sitePath+'/.user.ini';
if not os.path.exists(userIni):
public.writeFile(userIni, 'open_basedir='+self.sitePath+'/:/tmp/:/proc/');
public.ExecShell('chmod 644 ' + userIni);
public.ExecShell('chown root:root ' + userIni);
public.ExecShell('chattr +i '+userIni);
#创建默认文档
index = self.sitePath+'/index.html'
if not os.path.exists(index):
public.writeFile(index, public.readFile('data/defaultDoc.html'))
public.ExecShell('chmod -R 755 ' + index);
public.ExecShell('chown -R www:www ' + index);
#创建自定义404页
doc404 = self.sitePath+'/404.html'
if not os.path.exists(doc404):
public.writeFile(doc404, public.readFile('data/404.html'));
public.ExecShell('chmod -R 755 ' + doc404);
public.ExecShell('chown -R www:www ' + doc404);
#写入配置
result = self.nginxAdd()
result = self.apacheAdd()
#检查处理结果
if not result: return public.returnMsg(False,'SITE_ADD_ERR_WRITE');
ps = get.ps
#添加放行端口
if self.sitePort != '80':
import firewalls
get.port = self.sitePort
get.ps = self.siteName;
firewalls.firewalls().AddAcceptPort(get);
if not hasattr(get,'type_id'): get.type_id = 0
#写入数据库
get.pid = sql.table('sites').add('name,path,status,ps,type_id,addtime',(self.siteName,self.sitePath,'1',ps,get.type_id,public.getDate()))
#添加更多域名
for domain in siteMenu['domainlist']:
get.domain = domain
get.webname = self.siteName
get.id = str(get.pid)
self.AddDomain(get)
sql.table('domain').add('pid,name,port,addtime',(get.pid,self.siteName,self.sitePort,public.getDate()))
data = {}
data['siteStatus'] = True
#添加FTP
data['ftpStatus'] = False
if get.ftp == 'true':
import ftp
get.ps = self.siteName
result = ftp.ftp().AddUser(get)
if result['status']:
data['ftpStatus'] = True
data['ftpUser'] = get.ftp_username
data['ftpPass'] = get.ftp_password
#添加数据库
data['databaseStatus'] = False
if get.sql == 'true' or get.sql == 'MySQL':
import database
if len(get.datauser) > 16: get.datauser = get.datauser[:16]
get.name = get.datauser
get.db_user = get.datauser
get.password = get.datapassword
get.address = '127.0.0.1'
get.ps = self.siteName
result = database.database().AddDatabase(get)
if result['status']:
data['databaseStatus'] = True
data['databaseUser'] = get.datauser
data['databasePass'] = get.datapassword
public.serviceReload()
public.WriteLog('TYPE_SITE','SITE_ADD_SUCCESS',(self.siteName,))
return data
def __get_site_format_path(self,path):
path = path.replace('//','/');
if path[-1:] == '/':
path = path[:-1]
return path
def __check_site_path(self,path):
path = self.__get_site_format_path(path)
other_path = public.M('config').where("id=?",('1',)).field('sites_path,backup_path').find();
if path == other_path['sites_path'] or path == other_path['backup_path']: return False
return True
#删除站点
def DeleteSite(self,get):
id = get.id;
siteName = get.webname;
get.siteName = siteName
self.CloseTomcat(get);
#删除配置文件
confPath = self.setupPath+'/panel/vhost/nginx/'+siteName+'.conf'
if os.path.exists(confPath): os.remove(confPath)
confPath = self.setupPath+'/panel/vhost/apache/' + siteName + '.conf';
if os.path.exists(confPath): os.remove(confPath)
#删除伪静态文件
filename = confPath+'/rewrite/'+siteName+'.conf'
if os.path.exists(filename):
os.remove(filename)
public.ExecShell("rm -f " + confPath + '/rewrite/' + siteName + "_*")
#删除日志文件
filename = public.GetConfigValue('logs_path')+'/'+siteName+'*'
public.ExecShell("rm -f " + filename)
#删除证书
#crtPath = '/etc/letsencrypt/live/'+siteName
#if os.path.exists(crtPath):
# import shutil
# shutil.rmtree(crtPath)
#删除日志
public.ExecShell("rm -f " + public.GetConfigValue('logs_path') + '/' + siteName + "-*")
#删除备份
public.ExecShell("rm -f "+session['config']['backup_path']+'/site/'+siteName+'_*')
#删除根目录
if hasattr(get,'path'):
import files
get.path = self.__get_site_format_path(public.M('sites').where("id=?",(id,)).getField('path'));
if self.__check_site_path(get.path): files.files().DeleteDir(get)
#重载配置
public.serviceReload();
#从数据库删除
public.M('sites').where("id=?",(id,)).delete();
public.M('binding').where("pid=?",(id,)).delete();
public.M('domain').where("pid=?",(id,)).delete();
public.WriteLog('TYPE_SITE', "SITE_DEL_SUCCESS",(siteName,));
#是否删除关联数据库
if hasattr(get,'database'):
find = public.M('databases').where("pid=?",(id,)).field('id,name').find()
if find:
import database
get.name = find['name']
get.id = find['id']
database.database().DeleteDatabase(get)
#是否删除关联FTP
if hasattr(get,'ftp'):
find = public.M('ftps').where("pid=?",(id,)).field('id,name').find()
if find:
import ftp
get.username = find['name']
get.id = find['id']
ftp.ftp().DeleteUser(get)
return public.returnMsg(True,'SITE_DEL_SUCCESS')
#域名编码转换
def ToPunycode(self,domain):
import re;
if sys.version_info[0] == 2: domain = domain.encode('utf8');
tmp = domain.split('.');
newdomain = '';
for dkey in tmp:
#匹配非ascii字符
match = re.search(u"[\x80-\xff]+",dkey);
if not match:
newdomain += dkey + '.';
else:
newdomain += 'xn--' + dkey.decode('utf-8').encode('punycode') + '.'
return newdomain[0:-1];
#中文路径处理
def ToPunycodePath(self,path):
if sys.version_info[0] == 2: path = path.encode('utf-8');
if os.path.exists(path): return path;
import re;
match = re.search(u"[\x80-\xff]+",path);
if not match: return path;
npath = '';
for ph in path.split('/'):
npath += '/' + self.ToPunycode(ph);
return npath.replace('//','/')
#添加域名
def AddDomain(self,get):
#检查配置文件
isError = public.checkWebConfig()
if isError != True:
return public.returnMsg(False,'ERROR: 检测到配置文件有错误,请先排除后再操作<br><br><a style="color:red;">'+isError.replace("\n",'<br>')+'</a>');
if len(get.domain) < 3: return public.returnMsg(False,'SITE_ADD_DOMAIN_ERR_EMPTY');
domains = get.domain.replace(' ','').split(',')
for domain in domains:
if domain == "": continue;
domain = domain.strip().split(':')
get.domain = self.ToPunycode(domain[0])
get.port = '80'
reg = "^([\w\-\*]{1,100}\.){1,4}([\w\-]{1,24}|[\w\-]{1,24}\.[\w\-]{1,24})$";
if not re.match(reg, get.domain): return public.returnMsg(False,'SITE_ADD_DOMAIN_ERR_FORMAT');
if len(domain) == 2: get.port = domain[1];
if get.port == "": get.port = "80";
if not public.checkPort(get.port): return public.returnMsg(False,'SITE_ADD_DOMAIN_ERR_POER');
#检查域名是否存在
sql = public.M('domain');
opid = sql.where("name=? AND (port=? OR pid=?)",(get.domain,get.port,get.id)).getField('pid');
if opid:
if public.M('sites').where('id=?',(opid,)).count():
return public.returnMsg(False,'SITE_ADD_DOMAIN_ERR_EXISTS');
sql.where('pid=?',(opid,)).delete();
#写配置文件
self.NginxDomain(get)
try:
self.ApacheDomain(get)
except:
pass;
#添加放行端口
if get.port != '80':
import firewalls
get.ps = get.domain;
firewalls.firewalls().AddAcceptPort(get);
public.serviceReload();
public.WriteLog('TYPE_SITE', 'DOMAIN_ADD_SUCCESS',(get.webname,get.domain));
sql.table('domain').add('pid,name,port,addtime',(get.id,get.domain,get.port,public.getDate()));
return public.returnMsg(True,'SITE_ADD_DOMAIN');
#Nginx写域名配置
def NginxDomain(self,get):
file = self.setupPath + '/panel/vhost/nginx/'+get.webname+'.conf';
conf = public.readFile(file);
if not conf: return;
#添加域名
rep = "server_name\s*(.*);";
tmp = re.search(rep,conf).group()
domains = tmp.split(' ')
if not public.inArray(domains,get.domain):
newServerName = tmp.replace(';',' ' + get.domain + ';')
conf = conf.replace(tmp,newServerName)
#添加端口
rep = "listen\s+([0-9]+)\s*[default_server]*\s*;";
tmp = re.findall(rep,conf);
if not public.inArray(tmp,get.port):
listen = re.search(rep,conf).group()
conf = conf.replace(listen,listen + "\n\tlisten "+get.port+';')
#保存配置文件
public.writeFile(file,conf)
return True
#Apache写域名配置
def ApacheDomain(self,get):
file = self.setupPath + '/panel/vhost/apache/'+get.webname+'.conf';
conf = public.readFile(file);
if not conf: return;
port = get.port;
siteName = get.webname;
newDomain = get.domain
find = public.M('sites').where("id=?",(get.id,)).field('id,name,path').find();
sitePath = find['path'];
siteIndex = 'index.php index.html index.htm default.php default.html default.htm'
#添加域名
if conf.find('<VirtualHost *:'+port+'>') != -1:
repV = "<VirtualHost\s+\*\:"+port+">(.|\n)*</VirtualHost>";
domainV = re.search(repV,conf).group()
rep = "ServerAlias\s*(.*)\n";
tmp = re.search(rep,domainV).group(0)
domains = tmp[1].split(' ')
if not public.inArray(domains,newDomain):
rs = tmp.replace("\n","")
newServerName = rs+' '+newDomain+"\n";
myconf = domainV.replace(tmp,newServerName);
conf = re.sub(repV, myconf, conf);
else:
try:
httpdVersion = public.readFile(self.setupPath+'/apache/version.pl').strip();
except:
httpdVersion = "";
if httpdVersion == '2.2':
vName = '';
if self.sitePort != '80' and self.sitePort != '443':
vName = "NameVirtualHost *:"+port+"\n";
phpConfig = "";
apaOpt = "Order allow,deny\n\t\tAllow from all";
else:
vName = "";
rep = "php-cgi-([0-9]{2,3})\.sock";
version = re.search(rep,conf).groups()[0]
if len(version) < 2: return public.returnMsg(False,'PHP_GET_ERR')
phpConfig ='''
#PHP
<FilesMatch \\.php$>
SetHandler "proxy:unix:/tmp/php-cgi-%s.sock|fcgi://localhost"
</FilesMatch>
''' % (version,);
apaOpt = 'Require all granted';
newconf='''<VirtualHost *:%s>
ServerAdmin [email protected]
DocumentRoot "%s"
ServerName %s.%s
ServerAlias %s
errorDocument 404 /404.html
ErrorLog "%s-error_log"
CustomLog "%s-access_log" combined
%s
#DENY FILES
<Files ~ (\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)$>
Order allow,deny
Deny from all
</Files>
#PATH
<Directory "%s">
SetOutputFilter DEFLATE
Options FollowSymLinks
AllowOverride All
%s
DirectoryIndex %s
</Directory>
</VirtualHost>''' % (port,sitePath,siteName,port,newDomain,public.GetConfigValue('logs_path')+'/'+siteName,public.GetConfigValue('logs_path')+'/'+siteName,phpConfig,sitePath,apaOpt,siteIndex)
conf += "\n\n"+newconf;
#添加端口
if port != '80' and port != '888': self.apacheAddPort(port)
#保存配置文件
public.writeFile(file,conf)
return True
#删除域名
def DelDomain(self,get):
sql = public.M('domain');
id=get['id'];
port = get.port;
find = sql.where("pid=? AND name=?",(get.id,get.domain)).field('id,name').find();
domain_count = sql.table('domain').where("pid=?",(id,)).count();
if domain_count == 1: return public.returnMsg(False,'SITE_DEL_DOMAIN_ERR_ONLY');
#nginx
file = self.setupPath+'/panel/vhost/nginx/'+get['webname']+'.conf';
conf = public.readFile(file);
if conf:
#删除域名
rep = "server_name\s+(.+);";
tmp = re.search(rep,conf).group()
newServerName = tmp.replace(' '+get['domain']+';',';');
newServerName = newServerName.replace(' '+get['domain']+' ',' ');
conf = conf.replace(tmp,newServerName);
#删除端口
rep = "listen\s+([0-9]+);";
tmp = re.findall(rep,conf);
port_count = sql.table('domain').where('pid=? AND port=?',(get.id,get.port)).count()
if public.inArray(tmp,port) == True and port_count < 2:
rep = "\n*\s+listen\s+"+port+";";
conf = re.sub(rep,'',conf);
#保存配置
public.writeFile(file,conf)
#apache
file = self.setupPath+'/panel/vhost/apache/'+get['webname']+'.conf';
conf = public.readFile(file);
if conf:
#删除域名
try:
rep = "\n*<VirtualHost \*\:" + port + ">(.|\n)*</VirtualHost>";
tmp = re.search(rep, conf).group()
rep1 = "ServerAlias\s+(.+)\n";
tmp1 = re.findall(rep1,tmp);
tmp2 = tmp1[0].split(' ')
if len(tmp2) < 2:
conf = re.sub(rep,'',conf);
rep = "NameVirtualHost.+\:" + port + "\n";
conf = re.sub(rep,'',conf);
else:
newServerName = tmp.replace(' '+get['domain']+"\n","\n");
newServerName = newServerName.replace(' '+get['domain']+' ',' ');
conf = conf.replace(tmp,newServerName);
#保存配置
public.writeFile(file,conf)
except:
pass;
sql.table('domain').where("id=?",(find['id'],)).delete();
public.WriteLog('TYPE_SITE', 'DOMAIN_DEL_SUCCESS',(get.webname,get.domain));
public.serviceReload();
return public.returnMsg(True,'DEL_SUCCESS');
#检查域名是否解析
def CheckDomainPing(self,get):
try:
epass = public.GetRandomString(32);
spath = get.path + '/.well-known/pki-validation';
if not os.path.exists(spath): os.system("mkdir -p '" + spath + "'");
public.writeFile(spath + '/fileauth.txt',epass);
result = public.httpGet('http://' + get.domain.replace('*.','') + '/.well-known/pki-validation/fileauth.txt');
if result == epass: return True
return False
except:
return False
#保存第三方证书
def SetSSL(self,get):
#type = get.type;
siteName = get.siteName;
path = '/etc/letsencrypt/live/'+ siteName;
if not os.path.exists(path):
public.ExecShell('mkdir -p ' + path)
csrpath = path+"/fullchain.pem"; #生成证书路径
keypath = path+"/privkey.pem"; #密钥文件路径
if(get.key.find('KEY') == -1): return public.returnMsg(False, 'SITE_SSL_ERR_PRIVATE');
if(get.csr.find('CERTIFICATE') == -1): return public.returnMsg(False, 'SITE_SSL_ERR_CERT');
public.writeFile('/tmp/cert.pl',get.csr);
if not public.CheckCert('/tmp/cert.pl'): return public.returnMsg(False,'证书错误,请粘贴正确的PEM格式证书!');
public.ExecShell('\\cp -a '+keypath+' /tmp/backup1.conf');
public.ExecShell('\\cp -a '+csrpath+' /tmp/backup2.conf');
#清理旧的证书链
if os.path.exists(path+'/README'):
public.ExecShell('rm -rf ' + path);
public.ExecShell('rm -rf ' + path + '-00*');
public.ExecShell('rm -rf /etc/letsencrypt/archive/' + get.siteName);
public.ExecShell('rm -rf /etc/letsencrypt/archive/' + get.siteName + '-00*');
public.ExecShell('rm -f /etc/letsencrypt/renewal/'+ get.siteName + '.conf');
public.ExecShell('rm -f /etc/letsencrypt/renewal/'+ get.siteName + '-00*.conf');
public.ExecShell('rm -f ' + path + '/README');
public.ExecShell('mkdir -p ' + path);
public.writeFile(keypath,get.key);
public.writeFile(csrpath,get.csr);
#写入配置文件
result = self.SetSSLConf(get);
if not result['status']: return result;
isError = public.checkWebConfig();
if(type(isError) == str):
public.ExecShell('\\cp -a /tmp/backup1.conf ' + keypath);
public.ExecShell('\\cp -a /tmp/backup2.conf ' + csrpath);
return public.returnMsg(False,'ERROR: <br><a style="color:red;">'+isError.replace("\n",'<br>')+'</a>');
public.serviceReload();
if os.path.exists(path + '/partnerOrderId'): os.system('rm -f ' + path + '/partnerOrderId');
public.WriteLog('TYPE_SITE','SITE_SSL_SAVE_SUCCESS');
return public.returnMsg(True,'SITE_SSL_SUCCESS');
#获取运行目录
def GetRunPath(self,get):
if hasattr(get,'siteName'):
get.id = public.M('sites').where('name=?',(get.siteName,)).getField('id');
else:
get.id = public.M('sites').where('path=?',(get.path,)).getField('id');
if not get.id: return False;
import panelSite
result = self.GetSiteRunPath(get);
return result['runPath'];
#创建Let's Encrypt免费证书
def CreateLet(self,get):
#检查是否设置301
serverTypes = ['nginx','apache'];
for stype in serverTypes:
file = self.setupPath + '/panel/vhost/'+stype+'/'+get.siteName+'.conf';
if os.path.exists(file):
siteConf = public.readFile(file);
if siteConf.find('301-START') != -1: return public.returnMsg(False,'SITE_SSL_ERR_301');
#定义证书连接目录
path = '/etc/letsencrypt/live/'+ get.siteName.replace('*','\*');
csrpath = path+"/fullchain.pem"; #生成证书路径
keypath = path+"/privkey.pem"; #密钥文件路径
#准备基础信息
actionstr = get.updateOf
siteInfo = public.M('sites').where('name=?',(get.siteName,)).field('id,name,path').find();
runPath = self.GetRunPath(get);
srcPath = siteInfo['path'];
if runPath != False and runPath != '/': siteInfo['path'] += runPath;
get.path = siteInfo['path'];
domains = json.loads(get.domains)
email = public.M('users').getField('email');
if hasattr(get, 'email'):
if get.email.strip() != '':
public.M('users').setField('email',get.email);
email = get.email;
#检测acem是否安装
acem = '/root/.acme.sh/acme.sh';
if not os.path.exists(acem): acem = '/.acme.sh/acme.sh';
if not os.path.exists(acem):
try:
public.ExecShell("curl -sS "+public.get_url()+"/install/acme_install.sh|bash");
except:
public.ExecShell("curl -sS http://download.bt.cn/install/acme_install.sh|bash");
if not os.path.exists(acem):
return public.returnMsg(False,'尝试自动安装ACME失败,请通过以下命令尝试手动安装<p>安装命令: curl http://download.bt.cn/install/acme_install.sh|bash</p>' + acem)
force = False;
dns = False
dns_plu = False
if hasattr(get,'force'): force = True;
if hasattr(get,'renew'):
execStr = acem + " --renew --yes-I-know-dns-manual-mode-enough-go-ahead-please"
else:
execStr = acem + " --issue --force"
if hasattr(get,'dnsapi'):
if get.dnsapi == 'dns':
execStr += ' --dns --yes-I-know-dns-manual-mode-enough-go-ahead-please'
dns = True
else:
execStr += ' --dns ' + get.dnsapi + ' --dnssleep ' + str(get.dnssleep)
if not self.Check_DnsApi(get.dnsapi): return public.returnMsg(False,'请先设置该API');
if get.dnsapi == 'dns_bt':
c_file = '/www/server/panel/plugin/dns/dns_main.py';
if not os.path.exists(c_file): return public.returnMsg(False,'请先安装[云解析]插件');
c_conf = public.readFile(c_file)
if c_conf.find('add_txt') == -1:
os.system('wget -O '+filename+' http://download.bt.cn/install/plugin/dns/dns_main.py -T 5')
sys.path.append('/www/server/panel/plugin/dns')
import dns_main
dns_plu = dns_main.dns_main()
#确定主域名顺序
domainsTmp = []
if get.siteName in domains: domainsTmp.append(get.siteName);
for domainTmp in domains:
if domainTmp == get.siteName: continue;
domainsTmp.append(domainTmp);
domains = domainsTmp;
if not len(domains): return public.returnMsg(False,'请选择域名');
home_path = '/www/server/panel/vhost/cert/'+ domains[0].replace('*','\*')
home_cert = home_path + '/fullchain.cer'
home_key = home_path + '/' + domains[0].replace('*','\*') + '.key'
#构造参数
domainCount = 0
errorDomain = "";
errorDns = "";
done = '';
dns_type = execStr.find('-dns')
for domain in domains:
if public.checkIp(domain): continue;
if dns_type == -1:
if domain.find('*.') != -1: return public.returnMsg(False,'泛域名不能使用【文件验证】的方式申请证书!');
get.domain = domain;
if public.M('domain').where('name=?',(domain,)).count():
p = siteInfo['path'];
else:
p = public.M('binding').where('domain=?',(domain,)).getField('path');
get.path = p;
if force:
if not self.CheckDomainPing(get): errorDomain += '<li>' + domain + '</li>';
if dns_plu:
domainId,key = dns_plu.get_domainid_byfull('test.' + domain)
if not domainId: errorDns += '<li>' + domain + '</li>';
if p != done:
done = p;
execStr += ' -w ' + done;
execStr += ' -d ' + domain
domainCount += 1
if errorDomain: return public.returnMsg(False,'SITE_SSL_ERR_DNS',('<span style="color:red;"><br>'+errorDomain+'</span>',));
#获取域名数据
if domainCount == 0: return public.returnMsg(False,'SITE_SSL_ERR_EMPTY')
#检查是否自定义证书
partnerOrderId = path + '/partnerOrderId';
if os.path.exists(partnerOrderId):
public.ExecShell('rm -rf ' + partnerOrderId);
public.ExecShell('rm -rf ' + path);
public.ExecShell('rm -rf ' + path + '-00*');
public.ExecShell('rm -rf /etc/letsencrypt/archive/' + get.siteName);
public.ExecShell('rm -rf /etc/letsencrypt/archive/' + get.siteName + '-00*');
public.ExecShell('rm -f /etc/letsencrypt/renewal/'+ get.siteName + '.conf');
public.ExecShell('rm -f /etc/letsencrypt/renewal/'+ get.siteName + '-00*.conf');
self.CloseSSLConf(get);
result = public.ExecShell('export ACCOUNT_EMAIL=' + email + ' && ' + execStr);
if not os.path.exists(home_cert):
home_path = '/.acme.sh/'+ domains[0].replace('*','\*')
home_cert = home_path + '/fullchain.cer'
home_key = home_path + '/' + domains[0].replace('*','\*') + '.key'
if not os.path.exists(home_cert):
home_path = '/root/.acme.sh/'+ domains[0]
home_cert = home_path + '/fullchain.cer'
home_key = home_path + '/' + domains[0] + '.key'
if dns and not os.path.exists(home_cert):
try:
data = {}
data['err'] = result;
data['out'] = result[0];
data['status'] = True
data['msg'] = "获取成功,请手动解析域名"
data['fullDomain'] = re.findall("Domain:\s*'(.+)'",result[0])
data['txtValue'] = re.findall("TXT\s+value:\s*'(.+)'",result[0])
return data
except:
data = {};
data['err'] = result;
data['out'] = result[0];
data['msg'] = '获取失败!';
data['result'] = {};
return data
#判断是否获取成功
if not os.path.exists(home_cert):
data = {};
data['err'] = result;
data['out'] = result[0];
data['msg'] = '签发失败,我们无法验证您的域名:<p>1、检查域名是否绑定到对应站点</p><p>2、检查域名是否正确解析到本服务器,或解析还未完全生效</p><p>3、如果您的站点设置了反向代理,或使用了CDN,请先将其关闭</p><p>4、如果您的站点设置了301重定向,请先将其关闭</p><p>5、如果以上检查都确认没有问题,请尝试更换DNS服务商</p>';
data['result'] = {};
if result[1].find('new-authz error:') != -1:
data['result'] = json.loads(re.search("{.+}",result[1]).group());
if data['result']['status'] == 429: data['msg'] = '签发失败,您尝试申请证书的失败次数已达上限!<p>1、检查域名是否绑定到对应站点</p><p>2、检查域名是否正确解析到本服务器,或解析还未完全生效</p><p>3、如果您的站点设置了反向代理,或使用了CDN,请先将其关闭</p><p>4、如果您的站点设置了301重定向,请先将其关闭</p><p>5、如果以上检查都确认没有问题,请尝试更换DNS服务商</p>';
data['status'] = False;
return data
if not os.path.exists(path): public.ExecShell("mkdir -p " + path)
public.ExecShell("ln -sf " + home_cert + " " + csrpath)
public.ExecShell("ln -sf " + home_key + " " + keypath)
public.ExecShell('echo "let" > ' + path + '/README');
if(actionstr == '2'): return public.returnMsg(True,'SITE_SSL_UPDATE_SUCCESS');
#写入配置文件
result = self.SetSSLConf(get);
result['csr'] = public.readFile(csrpath);
result['key'] = public.readFile(keypath);
public.serviceReload();
return result;
#判断DNS-API是否设置
def Check_DnsApi(self,dnsapi):
dnsapis = self.GetDnsApi(None)
for dapi in dnsapis:
if dapi['name'] == dnsapi:
if not dapi['data']: return True
for d in dapi['data']:
if d['key'] == '': return False
return True
#获取DNS-API列表
def GetDnsApi(self,get):
apis = [{
"name":"dns_bt",
"title":"宝塔DNS云解析",
"ps":"使用宝塔DNS云解析插件自动解析申请SSL",
"help":"",
"data":False
},
{
"name":"dns_dp",
"title":"DnsPod",
"ps":"使用DnsPod的API接口自动解析申请SSL",
"help":"DnsPod后台》用户中心》安全设置,开启API Token",
"data":[{"key":"SAVED_DP_Id","name":"ID","value":""},{"key":"SAVED_DP_Key","name":"Token","value":""}]
},
{
"name":"dns_ali",
"title":"阿里云DNS",
"ps":"使用阿里云API接口自动解析申请SSL",
"help":"阿里云控制台》用户头像》accesskeys按指引获取AccessKey/SecretKey",
"data":[{"key":"SAVED_Ali_Key","name":"AccessKey","value":""},{"key":"SAVED_Ali_Secret","name":"SecretKey","value":""}]
},
{
"name":"dns",
"title":"手动解析",
"ps":"返回host和txt值,由用户手动解析",
"data":False
}
]
path = '/root/.acme.sh'
if not os.path.exists(path + '/account.conf'): path = "/.acme.sh"
if not os.path.exists(path + '/account.conf'):
try:
public.ExecShell("curl -sS "+public.get_url()+"/install/acme_install.sh|bash")
except:
public.ExecShell("curl -sS http://download.bt.cn/install/acme_install.sh|bash")
path = '/root/.acme.sh'
if not os.path.exists(path + '/account.conf'): path = "/.acme.sh"
if not os.path.exists(path + '/dnsapi'): os.makedirs(path + '/dnsapi')
account = public.readFile(path + '/account.conf')
for i in range(len(apis)):
filename = path + '/dnsapi/' + apis[i]['name'] + '.sh'
if not os.path.exists(filename) and apis[i]['name'] != 'dns':
public.downloadFile('http://download.bt.cn/install/dnsapi/' + apis[i]['name'] + '.sh',filename)
public.ExecShell("chmod +x " + filename)
if not apis[i]['data']: continue
for j in range(len(apis[i]['data'])):
match = re.search(apis[i]['data'][j]['key'] + "\s*=\s*'(.+)'",account)
if match: apis[i]['data'][j]['value'] = match.groups()[0]
return apis
#设置DNS-API
def SetDnsApi(self,get):
path = '/root/.acme.sh'
if not os.path.exists(path + '/account.conf'): path = "/.acme.sh"
filename = path + '/account.conf'
pdata = json.loads(get.pdata)
for key in pdata.keys():
kvalue = key + "='" + pdata[key] + "'"