forked from aaPanel/BaoTa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpanelSite.py
5367 lines (4802 loc) · 223 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: hwliang <[email protected]>
#-------------------------------------------------------------------
#------------------------------
# 网站管理类
#------------------------------
import io,re,public,os,sys,shutil,json,hashlib,socket,time
try:
from BTPanel import session
except:
pass
from panelRedirect import panelRedirect
import site_dir_auth
class panelSite(panelRedirect):
siteName = None #网站名称
sitePath = None #根目录
sitePort = None #端口
phpVersion = None #PHP版本
setupPath = None #安装路径
isWriteLogs = None #是否写日志
nginx_conf_bak = '/tmp/backup_nginx.conf'
apache_conf_bak = '/tmp/backup_apache.conf'
is_ipv6 = False
def __init__(self):
self.setupPath = public.get_setup_path()
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'):
public.ExecShell('mkdir -p ' + path)
public.ExecShell('wget -O ' + path + '/index.html '+public.get_url()+'/stop.html &')
self.__proxyfile = '{}/data/proxyfile.json'.format(public.get_panel_path())
self.OldConfigFile()
if os.path.exists(self.nginx_conf_bak): os.remove(self.nginx_conf_bak)
if os.path.exists(self.apache_conf_bak): os.remove(self.apache_conf_bak)
self.is_ipv6 = os.path.exists(self.setupPath + '/panel/data/ipv6.pl')
sys.setrecursionlimit(1000000)
#默认配置文件
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>'''
listen_ipv6 = ''
if self.is_ipv6: listen_ipv6 = "\n listen [::]:80;"
nginx_default = '''server
{
listen 80;%s
server_name _;
index index.html;
root /www/server/nginx/html;
}''' % listen_ipv6
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):
port = str(port)
filename = self.setupPath+'/apache/conf/extra/httpd-ssl.conf'
if os.path.exists(filename):
ssl_conf = public.readFile(filename)
if ssl_conf:
if ssl_conf.find('Listen 443') != -1:
ssl_conf = ssl_conf.replace('Listen 443','')
public.writeFile(filename,ssl_conf)
filename = self.setupPath+'/apache/conf/httpd.conf'
if not os.path.exists(filename): return
allConf = public.readFile(filename)
rep = r"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] + "\n"
listen_ipv6 = ''
#if self.is_ipv6: listen_ipv6 = "\nListen [::]:" + port
allConf = allConf.replace(listen,listen + "Listen " + port + listen_ipv6 + "\n")
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:%s"
</FilesMatch>
''' % (public.get_php_proxy(self.phpVersion,'apache'),)
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):
listen_ipv6 = ''
if self.is_ipv6: listen_ipv6 = "\n listen [::]:%s;" % self.sitePort
conf='''server
{{
listen {listen_port};{listen_ipv6}
server_name {site_name};
index index.php index.html index.htm default.php default.htm default.html;
root {site_path};
#SSL-START {ssl_start_msg}
#error_page 404/404.html;
#SSL-END
#ERROR-PAGE-START {err_page_msg}
#error_page 404 /404.html;
#error_page 502 /502.html;
#ERROR-PAGE-END
#PHP-INFO-START {php_info_start}
include enable-php-{php_version}.conf;
#PHP-INFO-END
#REWRITE-START {rewrite_start_msg}
include {setup_path}/panel/vhost/rewrite/{site_name}.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 /dev/null;
access_log /dev/null;
}}
location ~ .*\\.(js|css)?$
{{
expires 12h;
error_log /dev/null;
access_log /dev/null;
}}
access_log {log_path}/{site_name}.log;
error_log {log_path}/{site_name}.error.log;
}}'''.format(
listen_port=self.sitePort,
listen_ipv6=listen_ipv6,
site_path=self.sitePath,
ssl_start_msg=public.getMsg('NGINX_CONF_MSG1'),
err_page_msg=public.getMsg('NGINX_CONF_MSG2'),
php_info_start=public.getMsg('NGINX_CONF_MSG3'),
php_version=self.phpVersion,
setup_path=self.setupPath,
rewrite_start_msg = public.getMsg('NGINX_CONF_MSG4'),
log_path = public.GetConfigValue('logs_path'),
site_name = 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()
if not os.path.exists(urlrewritePath):
public.writeFile(urlrewritePath,'')
return True
#重新生成nginx配置文件
def rep_site_config(self,get):
self.siteName = get.siteName
siteInfo = public.M('sites').where('name=?',(self.siteName,)).field('id,path,port').find()
siteInfo['domains'] = public.M('domains').where('pid=?',(siteInfo['id'],)).field('name,port').select()
siteInfo['binding'] = public.M('binding').where('pid=?',(siteInfo['id'],)).field('domain,path').select()
# openlitespeed
def openlitespeed_add_site(self,get,init_args=None):
# 写主配置httpd_config.conf
# 操作默认监听配置
if not self.sitePath:
return public.returnMsg(False,"Not specify parameter [sitePath]")
if init_args:
self.siteName = init_args['sitename']
self.phpVersion = init_args['phpv']
self.sitePath = init_args['rundir']
conf_dir = self.setupPath+'/panel/vhost/openlitespeed/'
if not os.path.exists(conf_dir):
os.makedirs(conf_dir)
file = conf_dir+self.siteName+'.conf'
v_h = """
#VHOST_TYPE BT_SITENAME START
virtualhost BT_SITENAME {
vhRoot BT_RUN_PATH
configFile /www/server/panel/vhost/openlitespeed/detail/BT_SITENAME.conf
allowSymbolLink 1
enableScript 1
restrained 1
setUIDMode 0
}
#VHOST_TYPE BT_SITENAME END
"""
self.old_name = self.siteName
if hasattr(get,"dirName"):
self.siteName = self.siteName + "_" + get.dirName
# sub_dir = self.sitePath + "/" + get.dirName
v_h = v_h.replace("VHOST_TYPE","SUBDIR")
v_h = v_h.replace("BT_SITENAME", self.siteName)
v_h = v_h.replace("BT_RUN_PATH", self.sitePath)
# extp_name = self.siteName + "_" + get.dirName
else:
self.openlitespeed_domain(get)
v_h = v_h.replace("VHOST_TYPE", "VHOST")
v_h = v_h.replace("BT_SITENAME", self.siteName)
v_h = v_h.replace("BT_RUN_PATH", self.sitePath)
# extp_name = self.siteName
public.writeFile(file,v_h,"a+")
# 写vhost
conf = '''docRoot $VH_ROOT
vhDomain $VH_NAME
adminEmails [email protected]
enableGzip 1
enableIpGeo 1
index {
useServer 0
indexFiles index.php,index.html
}
errorlog /www/wwwlogs/$VH_NAME_ols.error_log {
useServer 0
logLevel ERROR
rollingSize 10M
}
accesslog /www/wwwlogs/$VH_NAME_ols.access_log {
useServer 0
logFormat '%{X-Forwarded-For}i %h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"'
logHeaders 5
rollingSize 10M
keepDays 10 compressArchive 1
}
scripthandler {
add lsapi:BT_EXTP_NAME php
}
extprocessor BTSITENAME {
type lsapi
address UDS://tmp/lshttpd/BT_EXTP_NAME.sock
maxConns 20
env LSAPI_CHILDREN=20
initTimeout 600
retryTimeout 0
persistConn 1
pcKeepAliveTimeout 1
respBuffer 0
autoStart 1
path /usr/local/lsws/lsphpBTPHPV/bin/lsphp
extUser www
extGroup www
memSoftLimit 2047M
memHardLimit 2047M
procSoftLimit 400
procHardLimit 500
}
phpIniOverride {
php_admin_value open_basedir "/tmp/:BT_RUN_PATH"
}
expires {
enableExpires 1
expiresByType image/*=A43200,text/css=A43200,application/x-javascript=A43200,application/javascript=A43200,font/*=A43200,application/x-font-ttf=A43200
}
rewrite {
enable 1
autoLoadHtaccess 1
include /www/server/panel/vhost/openlitespeed/proxy/BTSITENAME/urlrewrite/*.conf
include /www/server/panel/vhost/apache/redirect/BTSITENAME/*.conf
include /www/server/panel/vhost/openlitespeed/redirect/BTSITENAME/*.conf
}
include /www/server/panel/vhost/openlitespeed/proxy/BTSITENAME/*.conf
'''
open_base_path = self.sitePath
if self.sitePath[-1] != '/':
open_base_path = self.sitePath + '/'
conf = conf.replace('BT_RUN_PATH',open_base_path)
conf = conf.replace('BT_EXTP_NAME',self.siteName)
conf = conf.replace('BTPHPV',self.phpVersion)
conf = conf.replace('BTSITENAME',self.siteName)
# 写配置文件
conf_dir = self.setupPath + '/panel/vhost/openlitespeed/detail/'
if not os.path.exists(conf_dir):
os.makedirs(conf_dir)
file = conf_dir + self.siteName + '.conf'
# if hasattr(get,"dirName"):
# file = conf_dir + self.siteName +'_'+get.dirName+ '.conf'
public.writeFile(file, conf)
# 生成伪静态文件
# urlrewritePath = self.setupPath + '/panel/vhost/rewrite'
# urlrewriteFile = urlrewritePath + '/' + self.old_name + '.conf'
# if not os.path.exists(urlrewritePath): os.makedirs(urlrewritePath)
# open(urlrewriteFile, 'w+').close()
return True
# 上传CSV文件
# def upload_csv(self, get):
# import files
# f = files.files()
# get.f_path = '/tmp/multiple_website.csv'
# result = f.upload(get)
# return result
# 处理CSV内容
def __process_cvs(self, key):
import csv
with open('/tmp/multiple_website.csv')as f:
f_csv = csv.reader(f)
# result = [i for i in f_csv]
return [dict(zip(key, i)) for i in [i for i in f_csv if "FTP" not in i]]
# 批量创建网站
def __create_website_mulitiple(self, websites_info, site_path, get):
create_successfully = {}
create_failed = {}
for data in websites_info:
if not data:
continue
try:
domains = data['website'].split(',')
website_name = domains[0].split(':')[0]
data['port'] = '80' if len(domains[0].split(':')) < 2 else domains[0].split(':')[1]
get.webname = json.dumps({"domain": website_name, "domainlist": domains[1:], "count": 0})
get.path = data['path'] if 'path' in data and data['path'] != '0' and data['path'] != '1' else site_path + '/' + website_name
get.version = data['version'] if 'version' in data and data['version'] !='0' else '00'
get.ftp = 'true' if 'ftp' in data and data['ftp'] == '1' else False
get.sql = 'true' if 'sql' in data and data['sql'] == '1' else False
get.port = data['port'] if 'port' in data else '80'
get.codeing = 'utf8'
get.type = 'PHP'
get.type_id = '0'
get.ps = ''
create_other = {}
create_other['db_status'] = False
create_other['ftp_status'] = False
if get.sql == 'true':
create_other['db_pass'] = get.datapassword = public.gen_password(16)
create_other['db_user'] = get.datauser = website_name.replace('.', '_')
create_other['db_status'] = True
if get.ftp == 'true':
create_other['ftp_pass'] = get.ftp_password = public.gen_password(16)
create_other['ftp_user'] = get.ftp_username = website_name.replace('.', '_')
create_other['ftp_status'] = True
result = self.AddSite(get,multiple=1)
if 'status' in result:
create_failed[domains[0]] = result['msg']
continue
create_successfully[domains[0]] = create_other
except:
create_failed[domains[0]] = '创建出错了,请再试一次'
return {'status': True, 'msg': '创建网站 [ {} ] 成功'.format(','.join(create_successfully)), 'error': create_failed,
'success': create_successfully}
# 批量创建网站
def create_website_multiple(self, get):
'''
@name 批量创建网站
@author zhwen<2020-11-26>
@param create_type txt/csv txt格式为 “网站名|网站路径|是否创建FTP|是否创建数据库|PHP版本” 每个网站一行
"aaa.com:88,bbb.com|/www/wwwserver/aaa.com/或1|1/0|1/0|0/73"
csv格式为 “网站名|网站端口|网站路径|PHP版本|是否创建数据库|是否创建FTP”
@param websites_content "[[aaa.com|80|/www/wwwserver/aaa.com/|1|1|73]...."
'''
key = ['website', 'path', 'ftp', 'sql', 'version']
site_path = public.M('config').getField('sites_path')
if get.create_type == 'txt':
websites_info = [dict(zip(key, i)) for i in [i.strip().split('|') for i in json.loads(get.websites_content)]]
else:
websites_info = self.__process_cvs(key)
res = self.__create_website_mulitiple(websites_info, site_path, get)
public.serviceReload()
return res
#添加站点
def AddSite(self,get,multiple=None):
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)
if not public.check_site_path(get.path):
a,c = public.get_sys_path()
return public.returnMsg(False,'请不要将网站根目录设置到以下关键目录中: <br>{}'.format("<br>".join(a+c)))
try:
siteMenu = json.loads(get.webname)
except:
return public.returnMsg(False,'webname参数格式不正确,应该是可被解析的JSON字符串')
self.siteName = self.ToPunycode(siteMenu['domain'].strip().split(':')[0]).strip().lower()
self.sitePath = self.ToPunycodePath(self.GetPath(get.path.replace(' ',''))).strip()
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')
for domain in siteMenu['domainlist']:
if not len(domain.split(':')) == 2:
continue
if not public.checkPort(domain.split(':')[1]): return public.returnMsg(False, 'SITE_ADD_ERR_PORT')
if hasattr(get,'version'):
self.phpVersion = get.version.replace(' ','')
else:
self.phpVersion = '00'
if not self.phpVersion: self.phpVersion = '00'
php_version = self.GetPHPVersion(get)
is_phpv = False
for php_v in php_version:
if self.phpVersion == php_v['version']:
is_phpv = True
break
if not is_phpv: return public.returnMsg(False,'指定PHP版本不存在!')
domain = None
#if siteMenu['count']:
# domain = get.domain.replace(' ','')
#表单验证
if 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 = r"^([\w\-\*]{1,100}\.){1,24}([\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 self.sitePath[-1] == '.':return public.returnMsg(False, '网站目录结尾不可以是 "."')
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 public.M('binding').where('domain=?',(self.siteName,)).count():
return public.returnMsg(False,'SITE_ADD_ERR_DOMAIN_EXISTS')
#创建根目录
if not os.path.exists(self.sitePath):
try:
os.makedirs(self.sitePath)
except Exception as ex:
return public.returnMsg(False,'创建根目录失败, %s' % ex)
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/')
public.ExecShell('chmod 644 ' + userIni)
public.ExecShell('chown root:root ' + userIni)
public.ExecShell('chattr +i '+userIni)
ngx_open_basedir_path = self.setupPath + '/panel/vhost/open_basedir/nginx'
if not os.path.exists(ngx_open_basedir_path):
os.makedirs(ngx_open_basedir_path,384)
ngx_open_basedir_file = ngx_open_basedir_path + '/{}.conf'.format(self.siteName)
ngx_open_basedir_body = '''set $bt_safe_dir "open_basedir";
set $bt_safe_open "{}/:/tmp/";'''.format(self.sitePath)
public.writeFile(ngx_open_basedir_file,ngx_open_basedir_body)
#创建默认文档
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()
result = self.openlitespeed_add_site(get)
#检查处理结果
if not result: return public.returnMsg(False,'SITE_ADD_ERR_WRITE')
ps = public.xssencode2(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
public.check_domain_cloud(self.siteName)
#写入数据库
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,multiple)
sql.table('domain').add('pid,name,port,addtime',(get.pid,self.siteName,self.sitePort,public.getDate()))
data = {}
data['siteStatus'] = True
data['siteId'] = get.pid
#添加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
if not multiple:
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 delete_website_multiple(self,get):
'''
@name 批量删除网站
@author zhwen<2020-11-17>
@param sites_id "1,2"
@param ftp 0/1
@param database 0/1
@param path 0/1
'''
sites_id = get.sites_id.split(',')
del_successfully = []
del_failed = {}
for site_id in sites_id:
get.id = site_id
get.webname = public.M('sites').where("id=?", (site_id,)).getField('name')
if not get.webname:
continue
try:
self.DeleteSite(get,multiple=1)
del_successfully.append(get.webname)
except:
del_failed[get.webname]='删除时出错了,请再试一次'
pass
public.serviceReload()
return {'status': True, 'msg': '删除网站 [ {} ] 成功'.format(','.join(del_successfully)), 'error': del_failed,
'success': del_successfully}
#删除站点
def DeleteSite(self,get,multiple=None):
proxyconf = self.__read_config(self.__proxyfile)
id = get.id
if public.M('sites').where('id=?',(id,)).count() < 1: return public.returnMsg(False,'指定站点不存在!')
siteName = get.webname
get.siteName = siteName
self.CloseTomcat(get)
# 删除反向代理
for i in range(len(proxyconf)-1,-1,-1):
if proxyconf[i]["sitename"] == siteName:
del proxyconf[i]
self.__write_config(self.__proxyfile,proxyconf)
m_path = self.setupPath+'/panel/vhost/nginx/proxy/'+siteName
if os.path.exists(m_path): public.ExecShell("rm -rf %s" % m_path)
m_path = self.setupPath+'/panel/vhost/apache/proxy/'+siteName
if os.path.exists(m_path): public.ExecShell("rm -rf %s" % m_path)
# 删除目录保护
_dir_aith_file = "%s/panel/data/site_dir_auth.json" % self.setupPath
_dir_aith_conf = public.readFile(_dir_aith_file)
if _dir_aith_conf:
try:
_dir_aith_conf = json.loads(_dir_aith_conf)
if siteName in _dir_aith_conf:
del(_dir_aith_conf[siteName])
except:
pass
self.__write_config(_dir_aith_file,_dir_aith_conf)
dir_aith_path = self.setupPath+'/panel/vhost/nginx/dir_auth/'+siteName
if os.path.exists(dir_aith_path): public.ExecShell("rm -rf %s" % dir_aith_path)
dir_aith_path = self.setupPath+'/panel/vhost/apache/dir_auth/'+siteName
if os.path.exists(dir_aith_path): public.ExecShell("rm -rf %s" % dir_aith_path)
#删除重定向
__redirectfile = "%s/panel/data/redirect.conf" % self.setupPath
redirectconf = self.__read_config(__redirectfile)
for i in range(len(redirectconf)-1,-1,-1):
if redirectconf[i]["sitename"] == siteName:
del redirectconf[i]
self.__write_config(__redirectfile,redirectconf)
m_path = self.setupPath+'/panel/vhost/nginx/redirect/'+siteName
if os.path.exists(m_path): public.ExecShell("rm -rf %s" % m_path)
m_path = self.setupPath+'/panel/vhost/apache/redirect/'+siteName
if os.path.exists(m_path): public.ExecShell("rm -rf %s" % m_path)
#删除配置文件
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)
open_basedir_file = self.setupPath+'/panel/vhost/open_basedir/nginx/'+siteName+'.conf'
if os.path.exists(open_basedir_file): os.remove(open_basedir_file)
# 删除openlitespeed配置
vhost_file = "/www/server/panel/vhost/openlitespeed/{}.conf".format(siteName)
if os.path.exists(vhost_file):
public.ExecShell('rm -f {}*'.format(vhost_file))
vhost_detail_file = "/www/server/panel/vhost/openlitespeed/detail/{}.conf".format(siteName)
if os.path.exists(vhost_detail_file):
public.ExecShell('rm -f {}*'.format(vhost_detail_file))
vhost_ssl_file = "/www/server/panel/vhost/openlitespeed/detail/ssl/{}.conf".format(siteName)
if os.path.exists(vhost_ssl_file):
public.ExecShell('rm -f {}*'.format(vhost_ssl_file))
vhost_sub_file = "/www/server/panel/vhost/openlitespeed/detail/{}_sub.conf".format(siteName)
if os.path.exists(vhost_sub_file):
public.ExecShell('rm -f {}*'.format(vhost_sub_file))
vhost_redirect_file = "/www/server/panel/vhost/openlitespeed/redirect/{}".format(siteName)
if os.path.exists(vhost_redirect_file):
public.ExecShell('rm -rf {}*'.format(vhost_redirect_file))
vhost_proxy_file = "/www/server/panel/vhost/openlitespeed/proxy/{}".format(siteName)
if os.path.exists(vhost_proxy_file):
public.ExecShell('rm -rf {}*'.format(vhost_proxy_file))
# 删除openlitespeed监听配置
self._del_ols_listen_conf(siteName)
#删除伪静态文件
# filename = confPath+'/rewrite/'+siteName+'.conf'
filename = '/www/server/panel/vhost/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 'path' in get:
if get.path == '1':
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)
get.path = '1'
#重载配置
if not multiple:
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'):
if get.database == '1':
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'):
if get.ftp == '1':
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 _del_ols_listen_conf(self,sitename):
conf_dir = '/www/server/panel/vhost/openlitespeed/listen/'
if not os.path.exists(conf_dir):
return False
for i in os.listdir(conf_dir):
file_name = conf_dir + i
if os.path.isdir(file_name):
continue
conf = public.readFile(file_name)
if not conf:
continue
map_rep = 'map\s+{}.*'.format(sitename)
conf = re.sub(map_rep,'',conf)
if "map" not in conf:
public.ExecShell('rm -f {}*'.format(file_name))
continue
public.writeFile(file_name,conf)
#域名编码转换
def ToPunycode(self,domain):
import re
if sys.version_info[0] == 2: domain = domain.encode('utf8')
tmp = domain.split('.')
newdomain = ''
for dkey in tmp:
if dkey == '*': continue
#匹配非ascii字符
match = re.search(u"[\x80-\xff]+",dkey)
if not match: match = re.search(u"[\u4e00-\u9fa5]+",dkey)
if not match:
newdomain += dkey + '.'
else:
if sys.version_info[0] == 2:
newdomain += 'xn--' + dkey.decode('utf-8').encode('punycode') + '.'
else:
newdomain += 'xn--' + dkey.encode('punycode').decode('utf-8') + '.'
if tmp[0] == '*': newdomain = "*." + newdomain
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: match = re.search(u"[\u4e00-\u9fa5]+",path)
if not match: return path
npath = ''
for ph in path.split('/'):
npath += '/' + self.ToPunycode(ph)
return npath.replace('//','/')
def export_domains(self,args):
'''
@name 导出域名列表
@author hwliang<2020-10-27>
@param args<dict_obj>{
siteName: string<网站名称>
}
@return string
'''
pid = public.M('sites').where('name=?',args.siteName).getField('id')
domains = public.M('domain').where('pid=?',pid).field('name,port').select()
text_data = []
for domain in domains:
text_data.append("{}:{}".format(domain['name'], domain['port']))
data = "\n".join(text_data)
return public.send_file(data,'{}_domains'.format(args.siteName))
def import_domains(self,args):
'''
@name 导入域名
@author hwliang<2020-10-27>
@param args<dict_obj>{
siteName: string<网站名称>
domains: string<域名列表> 每行一个 格式: 域名:端口
}
@return string
'''
domains_tmp = args.domains.split("\n")
get = public.dict_obj()
get.webname = args.siteName
get.id = public.M('sites').where('name=?',args.siteName).getField('id')
domains = []
for domain in domains_tmp:
if public.M('domain').where('name=?',domain.split(':')[0]).count():
continue
domains.append(domain)
get.domain = ','.join(domains)
return self.AddDomain(get)
#添加域名
def AddDomain(self,get,multiple = None):
#检查配置文件
isError = public.checkWebConfig()
if isError != True:
return public.returnMsg(False,'ERROR: 检测到配置文件有错误,请先排除后再操作<br><br><a style="color:red;">'+isError.replace("\n",'<br>')+'</a>')
if not 'domain' in get: return public.returnMsg(False,'请填写域名!')
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]).lower()
get.port = '80'
reg = "^([\w\-\*]{1,100}\.){1,24}([\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()
if public.M('binding').where('domain=?',(get.domain,)).count():
return public.returnMsg(False,'SITE_ADD_ERR_DOMAIN_EXISTS')
#写配置文件
self.NginxDomain(get)
try:
self.ApacheDomain(get)
self.openlitespeed_domain(get)
if self._check_ols_ssl(get.webname):
get.port='443'
self.openlitespeed_domain(get)
get.port = '80'
except:
pass
#检查实际端口
if len(domain) == 2: get.port = domain[1]
#添加放行端口
if get.port != '80':
import firewalls
get.ps = get.domain
firewalls.firewalls().AddAcceptPort(get)
if not multiple:
public.serviceReload()
public.check_domain_cloud(get.domain)
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()))