update 6.5.1

This commit is contained in:
jose
2019-11-22 16:55:21 +08:00
parent 5217c1fc78
commit 382daa375a
91 changed files with 5733 additions and 2661 deletions
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/python
#coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Linux面板
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2099 宝塔软件(http://bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author: 黄文良 <287962566@qq.com>
# +-------------------------------------------------------------------
from gevent import monkey
monkey.patch_all()
import os,ssl
os.chdir('/www/server/panel')
from BTPanel import app,sys
if __name__ == '__main__':
f = open('data/port.pl')
PORT = int(f.read())
HOST = '0.0.0.0'
if os.path.exists('data/ipv6.pl'):
HOST = "0:0:0:0:0:0:0:0"
f.close()
#app.threaded=True
#app.jinja_env.auto_reload = True
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
keyfile = 'ssl/privateKey.pem'
certfile = 'ssl/certificate.pem'
if os.path.exists('data/debug.pl'):
ssl_context = None
if os.path.exists('data/ssl.pl'): ssl_context=(certfile,keyfile)
app.run(host=HOST,port=PORT,threaded=True,debug=True,ssl_context=ssl_context)
else:
if os.path.exists('data/ssl.pl'):
http_server = WSGIServer((HOST, PORT), app,handler_class=WebSocketHandler,keyfile=keyfile,certfile=certfile,log=None,error_log = None)
else:
http_server = WSGIServer((HOST, PORT), app,handler_class=WebSocketHandler)
http_server.serve_forever()
+63 -60
View File
@@ -10,6 +10,7 @@ import sys,json,os,time,logging,re
if sys.version_info[0] != 2:
from imp import reload
sys.path.insert(0,'/www/server/panel/class/')
sys.setrecursionlimit(1000000)
import public
from flask import Flask
app = Flask(__name__,template_folder="templates/" + public.GetConfigValue('template'))
@@ -18,8 +19,10 @@ from flask import Flask,current_app,session,render_template,send_file,request,re
from flask_session import Session
from werkzeug.contrib.cache import SimpleCache
from werkzeug.wrappers import Response
from flask_socketio import SocketIO,emit,send
from threading import Lock
from flask_sockets import Sockets
sockets = Sockets(app)
dns_client = None
app.config['DEBUG'] = os.path.exists('data/debug.pl')
@@ -35,11 +38,12 @@ if os.path.exists(basic_auth_conf):
except: pass
cache = SimpleCache()
socketio = SocketIO()
socketio.init_app(app)
import common,db,jobs,uuid,ssh_terminal
jobs.control_init()
import common,db,jobs,uuid,threading
job = threading.Thread(target=jobs.control_init)
job.setDaemon(True)
job.start()
app.secret_key = uuid.UUID(int=uuid.getnode()).hex[-12:]
local_ip = None
my_terms = {}
@@ -92,23 +96,26 @@ if admin_path in admin_path_checks: admin_path = '/bt'
def service_status():
return 'True'
@socketio.on('connect')
def socket_connect(msg=None):
if not check_login():
emit('server_response',{'data':public.getMsg('111')})
return False
@socketio.on('webssh')
def webssh(msg):
@sockets.route('/webssh')
def webssh(ws):
if not check_login():
session.clear()
emit('server_response',"Panel session is lost, please re-login panel!")
return None
if not 'ssh_obj' in session:
import ssh_terminal
session['ssh_obj'] = ssh_terminal.ssh_terminal()
session['ssh_obj'].send(msg)
if not 'ssh_info' in session:
s_file = '/www/server/panel/config/t_info.json'
if os.path.exists(s_file):
try:
session['ssh_info'] = json.loads(public.en_hexb(public.readFile(s_file)))
except:
session['ssh_info'] = {"host":"127.0.0.1","port":22}
else:
session['ssh_info'] = {"host":"127.0.0.1","port":22}
session['ssh_obj'].run(ws,session['ssh_info'])
@app.route('/term_open',methods=method_all)
@@ -126,10 +133,11 @@ def term_open():
session[key] = session['ssh_info']
s_file = '/www/server/panel/config/t_info.json'
if 'is_save' in session['ssh_info']:
public.writeFile(s_file,public.de_hexb(json.dumps(session['ssh_info'])))
public.writeFile(s_file,public.de_hexb(json.dumps(session['ssh_info'])),'wb+')
public.set_mode(s_file,600)
else:
if os.path.exists(s_file): os.remove(s_file)
if 'ssh_obj' in session: session['ssh_obj']._ssh_info = session['ssh_info']
return public.returnJson(True,'Successful setup!');
@app.route('/reload_mod',methods=method_all)
@@ -146,7 +154,9 @@ def reload_mod():
@app.before_request
def request_check():
if not request.path in ['/safe','/hook','/public']:
if request.path in ['/service_status']: return
if not request.path in ['/safe','/hook','/public','/mail_sys']:
ip_check = public.check_ip_panel()
if ip_check: return ip_check
@@ -162,7 +172,7 @@ def request_check():
return public.returnJson(False,'This feature is not available in offline mode!'),json_header
if app.config['BASIC_AUTH_OPEN']:
if request.path in ['/public','/download']: return;
if request.path in ['/public','/download','/mail_sys','/hook']: return;
auth = request.authorization
if not comm.get_sk(): return;
if not auth: return send_authenticated()
@@ -570,7 +580,7 @@ def code():
try:
import vilidate,time
except:
os.system("pip install Pillow==5.4.1 -I")
public.ExecShell("pip install Pillow==5.4.1 -I")
return "Pillow not install!"
code_time = cache.get('codeOut')
if code_time: return u'Error: Don\'t request validation codes frequently';
@@ -618,7 +628,7 @@ def plugin(pdata = None):
if comReturn: return comReturn
import panelPlugin
pluginObject = panelPlugin.panelPlugin()
defs = ('update_zip','input_zip','export_zip','add_index','remove_index','sort_index','install_plugin','uninstall_plugin','get_soft_find','get_index_list','get_soft_list','get_cloud_list','check_deps','flush_cache','GetCloudWarning','install','unInstall','getPluginList','getPluginInfo','getPluginStatus','setPluginStatus','a','getCloudPlugin','getConfigHtml','savePluginSort')
defs = ('set_score','get_score','update_zip','input_zip','export_zip','add_index','remove_index','sort_index','install_plugin','uninstall_plugin','get_soft_find','get_index_list','get_soft_list','get_cloud_list','check_deps','flush_cache','GetCloudWarning','install','unInstall','getPluginList','getPluginInfo','getPluginStatus','setPluginStatus','a','getCloudPlugin','getConfigHtml','savePluginSort')
return publicObject(pluginObject,defs,None,pdata);
@@ -650,6 +660,7 @@ def panel_public():
data = public.getJson(eval('pluwx.'+get.fun+'(get)'))
return data,json_header
if get.name != 'app': return abort(404)
import panelPlugin
plu = panelPlugin.panelPlugin()
get.s = '_check';
@@ -676,6 +687,19 @@ def send_favicon():
@app.route('/<name>/<fun>',methods=method_all)
@app.route('/<name>/<fun>/<path:stype>',methods=method_all)
def panel_other(name=None,fun = None,stype=None):
is_accept = False
if not fun: fun = 'index.html'
if not stype:
tmp = fun.split('.')
fun = tmp[0]
if len(tmp) == 1: tmp.append('')
stype = tmp[1]
if not name in ['mail_sys'] or not fun in ['send_mail_http']:
comReturn = comm.local()
if comReturn: return comReturn
else:
is_accept = True
if not name: name = 'coll'
if not public.path_safe_check("%s/%s/%s" % (name,fun,stype)): return abort(404)
if name.find('./') != -1 or not re.match("^[\w-]+$",name): return abort(404)
@@ -683,7 +707,6 @@ def panel_other(name=None,fun = None,stype=None):
p_path = '/www/server/panel/plugin/' + name
if not os.path.exists(p_path): return abort(404)
#是否响插件应静态文件
if fun == 'static':
if stype.find('./') != -1 or not os.path.exists(p_path + '/static'): return abort(404)
@@ -697,12 +720,6 @@ def panel_other(name=None,fun = None,stype=None):
#准备参数
args = get_input();
args.client_ip = public.GetClientIp();
if not fun: fun = 'index.html'
if not stype:
tmp = fun.split('.')
fun = tmp[0]
if len(tmp) == 1: tmp.append('')
stype = tmp[1]
args.fun = fun
#初始化插件对象
@@ -721,32 +738,12 @@ def panel_other(name=None,fun = None,stype=None):
plu = eval('plugin_main.' + name + '_main()')
if not hasattr(plu,fun): return public.returnJson(False,'SPECIFY_METHOD'),json_header
#检查访问权限
comReturn = comm.local()
if comReturn:
if not is_php:
if not hasattr(plu,'_check'):
session.clear()
return public.returnJson(False,'SPECIFY_PLUG_ERR'),json_header
checks = plu._check(args)
r_type = type(checks)
if r_type == Response: return checks
if r_type != bool or not checks: return public.getJson(checks),json_header
#初始化面板数据
comm.setSession()
comm.init()
comm.checkWebType()
comm.GetOS()
import panelPlugin
plugins = panelPlugin.panelPlugin()
args.name = name
if not plugins.check_accept(args):
return public.returnMsg(False,public.to_string([24744, 26410, 36141, 20080, 91, 37, 115, 93, 25110, 25480, 26435, 24050, 21040, 26399, 33]) % (plugins.get_title_byname(args),))
#执行插件方法
if not is_php:
if is_accept:
checks = plu._check(args)
if type(checks) != bool or not checks: return public.getJson(checks),json_header
data = eval('plu.'+fun+'(args)')
else:
import panelPHP
@@ -964,15 +961,7 @@ def publicObject(toObject,defs,action=None,get = None):
if hasattr(toObject,'site_path_check'):
if not toObject.site_path_check(get): return public.ReturnJson(False,'Excessive operation!'),json_header
for key in defs:
if key == get.action:
fun = 'toObject.'+key+'(get)'
if hasattr(get,'html') or hasattr(get,'s_module'):
return eval(fun)
else:
return public.GetJson(eval(fun)),json_header
return public.ReturnJson(False,'ARGS_ERR'),json_header
return run_exec().run(toObject,defs,get)
def check_login(http_token=None):
@@ -1077,3 +1066,17 @@ def get_input_data(data):
for key in data.keys():
pdata[key] = str(data[key])
return pdata
class run_exec:
def run(self,toObject,defs,get):
for key in defs:
if key == get.action:
fun = 'toObject.'+key+'(get)'
if hasattr(get,'html') or hasattr(get,'s_module'):
return eval(fun)
else:
return public.GetJson(eval(fun)),json_header
return public.ReturnJson(False,'ARGS_ERR'),json_header
+406 -112
View File
@@ -163,7 +163,7 @@ html {
float:right;
}
.bge6 {
background-color: #F1F2F7;
background-color: #f2f2f2;
}
/* .bge6 {
background-color: #e6e9ee
@@ -368,7 +368,6 @@ html {
color:red;
background-color: #fef3e2;
line-height: 20px;
height: 60px;
margin-bottom: 15px;
padding-left: 10px;
box-shadow: 0 1px 2px 0 rgba(0,0,0,.2);
@@ -574,7 +573,7 @@ html {
}
.main-content {
margin-left: 200px
margin-left: 180px
}
.sidebar-scroll {
@@ -5292,15 +5291,16 @@ select[disabled]{
width: 100%;
display: inline-block;
position: relative;
background: #777;
}
.ace_catalogue {
.ace_catalogue{
display: none;
float: left;
width: 250px;
position: absolute;
z-index: 99;
height: 45px;
background: #333;
height: 100%;
background: #292929;
}
.ace_catalogue_sidebar {
display: none;
@@ -5323,6 +5323,16 @@ select[disabled]{
line-height: 45px;
padding-left: 20px;
color: #fff;
background: #383838;
}
.ace_catalogue_list{
height: auto;
position: absolute;
top: 40px;
left: 0;
right: 0;
bottom: 0;
background: #222;
}
.ace_conter_menu {
height: 40px;
@@ -5351,9 +5361,6 @@ select[disabled]{
background: #565656;
/* transition: all 500ms; */
}
.chrome .ace_header{
background: #dedede;
}
.ace_header span {
float: left;
height: 35px;
@@ -5365,25 +5372,16 @@ select[disabled]{
border-right: 1px solid #4c4c4c;
cursor: pointer;
}
.chrome .ace_header span{
border-right: 1px solid #cccccc;
color: #444;
}
.ace_header span .glyphicon {
.ace_header span i{
margin-right: 5px;
vertical-align: text-top;
vertical-align: text-top;
}
.chrome .ace_header span:hover{
background: #d4d4d4;
.ace_header span .fa {
margin-right: 5px;
}
.ace_header span:hover {
background: #2f2f2f;
}
.chrome .ace_header .pull-down{
color: #555;
background: #dedede;
}
.ace_header .pull-down{
display: inline-block;
position: absolute;
@@ -5397,12 +5395,10 @@ select[disabled]{
background: #292929;
cursor: pointer;
}
.chrome .ace_editor_main{
background: #dedede;
}
.ace_editor_main {
position: relative;
background: #444;
/* margin-left: 250px; */
}
.ace_editor_main_storey {
@@ -5412,18 +5408,8 @@ select[disabled]{
height: 5px;
background: linear-gradient(rgba(0, 0, 0, 0.3), rgba(255, 255, 255, 0));
}
.chrome .ace_conter_menu{
background:rgb(243, 243, 243);
}
.chrome .ace_conter_menu .item{
border-right: 1px solid #ececec;
color: #555;
transition: all 500ms;
}
.ace_conter_menu .item {
display: inline-block;
overflow: hidden;
float: left;
font-size: 15px;
max-width: 350px;
@@ -5435,19 +5421,12 @@ select[disabled]{
cursor: pointer;
border-right: 1px solid #191919;
}
.chrome .ace_conter_menu .item:hover{
background: #fff;
}
.ace_conter_menu .item:hover {
background: #313131;
}
.ace_conter_menu .item:hover .icon-tool {
display: block;
}
.chrome .ace_conter_menu .item.active{
background-color: #fff;
color: #555
}
.ace_conter_menu .item.active {
color: #fff;
background: #404040;
@@ -5457,22 +5436,19 @@ select[disabled]{
display: block;
}
.ace_conter_menu .item span {
max-width:250px;
display: inline-block;
overflow: hidden;
white-space: normal;
text-overflow: ellipsis;
line-height: 40px;
height: 40px;
margin: 0 15px 0 0;
margin: 0 5px;
vertical-align: top;
}
.ace_conter_menu .item span i{
font-style: normal;
}
.ace_conter_menu .item .icon_file {
color: #ff9800;
font-weight: 500;
margin-left: 10px;
}
.ace_conter_menu .item .icon_file i{
width: 14px;
font-style: normal;
min-width: 8px;
}
.ace_conter_menu .item .icon-tool.fa-circle {
display: block;
@@ -5483,7 +5459,6 @@ select[disabled]{
right: 15px;
top: 13px;
transition: all 1000ms;
font-size: 14px;
}
.ace_editor_add {
float: left;
@@ -5539,12 +5514,6 @@ select[disabled]{
border-color: #d43f3a;
}
/* 关闭视图-结束 */
.chrome .ace_conter_toolbar{
background: #e6e6e6;
border-top: 1px solid #e4e4e4;
}
.ace_conter_toolbar {
height: 35px;
line-height: 35px;
@@ -5557,11 +5526,6 @@ select[disabled]{
font-size: 0;
overflow: hidden;
}
.chrome .ace_conter_toolbar .pull-left span ,
.chrome .ace_conter_toolbar .pull-right span{
color: #555;
border-right: 1px solid #d4d0d0
}
.ace_conter_toolbar .pull-left,
.ace_conter_toolbar .pull-right{
@@ -5578,26 +5542,16 @@ select[disabled]{
font-size: 13px;
}
.ace_conter_toolbar .pull-left span{
border-right:0 !important;
border-right:0;
cursor: default;
}
.ace_conter_toolbar .pull-left span i,
.ace_conter_toolbar .pull-right span i {
font-style: normal;
}
.chrome .ace_conter_toolbar .pull-right span:hover {
background:#cacaca;
}
.ace_conter_toolbar .pull-right span:hover {
background: #717171;
}
.chrome .ace_toolbar_menu{
background: #f3f3f3;
box-shadow: 0px 0px 8px 0px #9c9c9c;
}
.ace_toolbar_menu {
position: absolute;
z-index: 9999;
@@ -5609,7 +5563,6 @@ select[disabled]{
padding: 15px 0;
box-shadow: 0px 0px 2px 0px #000;
}
.ace_toolbar_menu .menu-conter {
margin: 0 15px 15px;
position: relative;
@@ -5623,14 +5576,6 @@ select[disabled]{
color: #fff;
cursor: pointer;
}
.chrome .ace_toolbar_menu input{
background: #f3f3f3;
border: 1px solid #7d7d7d;
color: #333;
}
.chrome .ace_toolbar_menu input:focus{
border: 1px solid #7d7d7d;
}
.ace_toolbar_menu input {
width: 100%;
height: 35px;
@@ -5648,9 +5593,6 @@ select[disabled]{
overflow: auto;
max-height: 300px;
}
.chrome .ace_toolbar_menu .menu-item li{
color: #555;
}
.ace_toolbar_menu .menu-item li {
padding: 0 20px;
height: 35px;
@@ -5660,19 +5602,10 @@ select[disabled]{
transition: all 500ms;
position: relative;
}
.chrome .ace_toolbar_menu .menu-item li.active,
.chrome .ace_toolbar_menu .menu-item li.active:hover {
background: #aaa;
color: #fff;
}
.ace_toolbar_menu .menu-item li.active,
.ace_toolbar_menu .menu-item li.active:hover {
background: #666;
}
.chrome .ace_toolbar_menu .menu-item li:hover {
background: #aaa;
color: #fff;
}
.ace_toolbar_menu .menu-item li:hover {
background: #505050;
}
@@ -5684,17 +5617,12 @@ select[disabled]{
position: absolute;
right: 25px;
}
.chrome .ace_toolbar_menu .menu-title{
border-bottom: 1px solid #e4e4e4;
color: #777;
}
.ace_toolbar_menu .menu-title {
padding: 0 0 5px 20px;
border-bottom: 1px solid #666666;
color: #9e9e9e;
}
.make_transist {
-webkit-transition: all .2s ease-in-out;
-moz-transition: all .2s ease-in-out;
@@ -5816,33 +5744,30 @@ select[disabled]{
text-decoration: none;
background-color: #f5f5f5
}
/*.dropdown-menu-li > li > div > a:focus, .dropdown-menu-li > li > div > a:hover {
color: #262626;
text-decoration: none;
background-color: #f5f5f5
}*/
.file-types {
position: relative;
line-height: 30px;
height: 30px;
}
.file-types .ico-folder {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAMpJREFUeNpi/P//P8NAAiaGAQYD7gAWdIFPpxIoMS8ZiOcQqfY5SD0LFT1jAsRTuaU0GZjZuAgq/vPto+S3V3fmUssBokC8llNEjp2ZFWjk/1+Eg56TE0RJsgCD3BPImAvikGs7IzMLAxuvKAMrNz9ZaWAul5iKJAsXPwUBAMzK//9AaDIcIAkODiKCbbQcGHXAqANGHTDqgFEHjDpg1AGjDqCVA57/+f6Z7hZD7XwBahOmfHv1ANQqlqCzG54CcRrjaOd0oB0AEGAAscwsxMSUtNsAAAAASUVORK5CYII=")
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAMpJREFUeNpi/P//P8NAAiaGAQYD7gAWdIFPpxIoMS8ZiOcQqfY5SD0LFT1jAsRTuaU0GZjZuAgq/vPto+S3V3fmUssBokC8llNEjp2ZFWjk/1+Eg56TE0RJsgCD3BPImAvikGs7IzMLAxuvKAMrNz9ZaWAul5iKJAsXPwUBAMzK//9AaDIcIAkODiKCbbQcGHXAqANGHTDqgFEHjDpg1AGjDqCVA57/+f6Z7hZD7XwBahOmfHv1ANQqlqCzG54CcRrjaOd0oB0AEGAAscwsxMSUtNsAAAAASUVORK5CYII=");
}
.file-types .ico-file {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAOVJREFUeNpi/P//P8NAAhZkzrVr1zyB1FwglqSiHSZAfBZZQEtLC7sDQJZLSUlJcnNzU8Xm27dvg6jVQByqqqp6FpsaJjS+JCcnJ8O/f/+ogkFATk5uJ8gRQMcYE+MAqgN2dvYMeXn5g0DmGmyOYKJHQmNjY0tQUFA4gc0RLLS0mI+PD5YOQCACSp8BYka6OEBUVJRBXFwcW8KkTwiAACwx4gJMDAMMRh0w6oBRB4w6YNQBow4YdcCoA0YdMOgc8Pzbt280swxq9gt8reKU58+fgzqnEjRyw1MgTkMWYBzo7jlAgAEAzk5sMbucHicAAAAASUVORK5CYII=")
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAOVJREFUeNpi/P//P8NAAhZkzrVr1zyB1FwglqSiHSZAfBZZQEtLC7sDQJZLSUlJcnNzU8Xm27dvg6jVQByqqqp6FpsaJjS+JCcnJ8O/f/+ogkFATk5uJ8gRQMcYE+MAqgN2dvYMeXn5g0DmGmyOYKJHQmNjY0tQUFA4gc0RLLS0mI+PD5YOQCACSp8BYka6OEBUVJRBXFwcW8KkTwiAACwx4gJMDAMMRh0w6oBRB4w6YNQBow4YdcCoA0YdMOgc8Pzbt280swxq9gt8reKU58+fgzqnEjRyw1MgTkMWYBzo7jlAgAEAzk5sMbucHicAAAAASUVORK5CYII=");
}
.file-types .ico {
background-position: center center;
background-repeat: no-repeat;
background-size: 15px;
display: inline-block;
height: 15px;
margin-right: 10px;
margin-left: 5px;
width: 20px;
margin-top: 3px;
vertical-align: sub;
width: 16px;
vertical-align: text-top;
}
.file-type-li {
@@ -5859,4 +5784,373 @@ background-color: #f5f5f5
top: 7px;
font-size: 11px;
transform: scale(.7);
}
}
/* 评价样式 */
.score_info_view{
display: none;
padding: 25px;
}
.comment_title{
padding: 0 10px;
width: 100%;
height: 100px;
box-sizing: border-box;
border-bottom: 1px solid #efefef;
}
.comment_num{
display: inline-block;
font-size: 60px;
line-height: 100px;
color: #666666;
}
.comment_num_tips{
list-style-type: none;
width: 145px;
height: 100px;
display: inline-block;
vertical-align: top;
padding-left: 10px;
padding: 20px 0 20px 15px;
box-sizing: border-box;
margin: 0;
line-height: 19px;
}
.comment_num_tips li{
color: #888;
display: inline-block;
font-size: 13.5px;
}
.comment_left{
margin-right: 10px;
display: inline-block;
}
.comment_star_group{
height: 12px;
line-height:12px;
}
.comment_right{
width: 230px;
height: 100px;
display: inline-block;
box-sizing: border-box;
float:right;
padding: 20px 0;
}
.comment_right .comment_progress{
width: 150px;
height: 6px;
position: relative;
display: inline-block;
margin-left: 8px;
top: -1.5px;
vertical-align: baseline;
}
.comment_right .comment_progress_bgw{
width: 0;
height: 6px;
background: #CCCCCC;
border-radius: 2px;
position: absolute;
left: 0;
top: 0;
z-index: 999;
}
.comment_right .comment_progress_speed{
width: 150px;
height: 6px;
background: #EFEFEF;
border-radius: 2px;
}
.comment_right .comment_star{
display: inline-block;
height: 12px;
line-height: 12px;
vertical-align: text-top;
}
.comment_star .star_active{
color: #F6BA2A;
}
.comment_star .star_none{
color: #fff;
}
.comment_star{
display: inline-block;
font-size: 0px;
}
.comment_star span{
font-size: 12px;
margin-right: 1px;
}
.comment_tab{
padding:15px 10px 20px 10px;
display: flex;
display: none;
}
.comment_tab span{
display: inline-block;
width: 125px;
margin: 0 10px;
border-radius: 3px;
height: 35px;
line-height: 35px;
text-align: center;
color: #555;
background-color:#F7F7F7;
border: 1px solid #efefef;
flex: 1;
cursor: pointer;
}
.comment_tab span:first-child{
margin-left: 0px;
}
.comment_tab span:last-child{
margin-right: 0px;
}
.comment_tab span.active{
background-color:#20a53a;
border-color: #20a53a;
color: #fff;
}
.comment_tab span i{
font-style: normal;
font-weight: 600;
}
.comment_box{
margin-left: 1%;
margin-right: 0;
padding: 20px;
border-radius: 2px;
background: #F8F8F8;
margin-bottom: 10px;
width: 48%;
float: left;
transition: all 500ms;
}
.comment_box:hover{
box-shadow: 0 0 4px 2px #00000022;
cursor: pointer;
}
.comment_box:nth-child(2n){
margin-left: 2%;
margin-right: 1%;
padding: 20px;
border-radius: 2px;
background: #F8F8F8;
margin-bottom: 10px;
width: 48%;
}
.comment_box_title{
padding-bottom: 10px;
}
.comment_box_title .nice_star{
margin-right: 10px;
}
.comment_box_title .nice_star span{
font-size: 15px;
vertical-align: text-bottom;
color: #aaa;
}
.comment_box_title .nice_star span.star_active {
color: #F6BA2A;
}
.comment_box_title .nice_time{
font-weight: 500;
color: #777;
font-size: 13px;
float: right;
}
.comment_box_title .nice_name{
font-weight: 500;
color: #777;
font-size: 13px;
display: inline-block;
width: 90px;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
vertical-align: middle;
}
.comment_box_content{
color: #777;
font-size: 13px;
height: 36px;
}
.edit_view.active{
cursor: no-drop;
background: #ddd;
border: 1px solid #ccc;
}
.edit_view.active:hover{
background: #ccc;
}
.edit_view .glyphicon{
font-size: 16px;
position: relative;
top: 2px;
}
.edit_view{
width: 200px;
height: 35px;
line-height: 35px;
border-radius: 20px;
text-align: center;
background: #21a53a;
border: 1px solid #21a53a;
color: #fff;
font-size: 15px;
position: relative;
left: 50%;
cursor: pointer;
transition: 500ms all;
margin: 15px 0 8px -100px;
}
.edit_view:hover{
background: #0f9228;
}
.comment_content{
overflow-y: auto;
height: 365px;
border-radius: 2px;
padding: 10px 0;
display: none;
}
.comment_box.get_next_page{
display: block;
width: auto;
padding: 12px;
text-align: center;
font-size: 14px;
color: #888;
line-height: 14px;
box-sizing: border-box;
cursor: pointer;
transition: all 500ms;
margin:1%;
float: none;
clear: both;
}
.comment_box.get_next_page span{
vertical-align: text-top;
}
.comment_box.get_next_page:hover{
background-color: #ececec;
color: #666;
box-shadow: none;
}
.comment_content.box-shadow{
box-shadow: -5px 0 3px 0px #00000022 inset;
}
.add_score_view{
padding: 30px 30px 0 30px;
}
.score_icon_group{
text-align: center;
height: 30px;
line-height: 30px;
font-size: 32px;
margin-bottom: 2px;
color: #cecece;
}
.score_icon_group_tips{
text-align: center;
color: #666;
font-size: 13px;
margin-top: 10px;
}
.score_icon_group span{
margin:0 2px;
cursor: pointer;
color: #bbb;
transition: all 500ms;
}
.score_icon_group span.active{
color: #F6BA2A;
}
.score_input{
width: auto;
display: block;
width: 100%;
height: 130px;
padding: 7px 5px 5px 8px;
margin-top: 10px;
line-height: 20px;
font-size: 13px;
display: none;
}
.score_input_tips{
margin-top: 5px;
color: #888;
display: none;
}
.score_input_tips i{
font-style: normal;
color: #666;
}
.score_details{
padding: 50px 25px;
}
.score_details .nice_star span{
font-size: 17px;
}
.score_details .nice_name{
font-size: 14px;
}
.score_details .nice_time{
font-size: 14px;
}
.score_details .comment_box_content{
height: auto;
font-size: 14px;
line-height: 18px;
}
.score_details .comment_box_title{
padding-bottom: 15px;
}
/* 结束 */
/* 文件侧边栏 */
.cd-accordion-menu{
overflow-y: hidden;
}
.cd-accordion-menu .has-children{
height: 30px;
line-height: 30px;
}
.cd-accordion-menu .has-children ul{
display: none;
}
.cd-accordion-menu .has-children label:hover{
background-color: #313131;
}
.cd-accordion-menu .has-children label{
margin-bottom: 0;
padding: 0 10px;
width: 100%;
cursor: pointer;
color: #cccccc;
}
.cd-accordion-menu .has-children input{
display: none;
}
.cd-accordion-menu .has-children .glyphicon{
margin-right: 10px;
}
.cd-accordion-menu .has-children .folder_icon{
font-style: normal;
font-size: 15px;
margin-right: 2px;
vertical-align: bottom;
}
.cd-accordion-menu .has-children .folder_icon:before{
color: #cccccc;
content: '\f016';
font-family:octicons;
width: 16px;
height: 16px;
display: inline-block;
}
/* 结束 */
+71 -1
View File
@@ -1,3 +1,73 @@
function modify_port_val(port){
layer.open({
type: 1,
area: '400px',
title: 'Change Panel Port',
closeBtn:2,
shadeClose: false,
btn:['Confirm','Cancel'],
content: '<div class="bt-form pd20 pd70" style="padding:20px 35px;">\
<ul style="margin-bottom:10px;color:red;width: 100%;background: #f7f7f7;padding: 10px;border-radius: 5px;font-size: 12px;">\
<li style="color:red;font-size:13px;">1. Have a security group server, please release the new port in the security group in advance.</li>\
<li style="color:red;font-size:13px;">2. If the panel is inaccessible after modifying the port, change the original port to the SSH command line by using the bt command.</li>\
</ul>\
<div class="line">\
<span class="tname" style="width: 70px;">Port</span>\
<div class="info-r" style="margin-left:70px">\
<input name="portss" class="bt-input-text mr5" type="text" style="width:200px" value="'+ port +'">\
</div>\
</div>\
<div class="details" style="margin-top:5px;padding-left: 3px;">\
<input type="checkbox" id="check_port">\
<label style="font-weight: 400;margin: 3px 5px 0px;" for="check_port">I already understand</label>,<a target="_blank" class="btlink" href="https://forum.aapanel.com/d/599-how-to-release-the-aapanel-port">How to release the port?</a>\
</div>\
</div>',
yes:function(index,layero){
var check_port = $('#check_port').prop('checked'),_tips = '';
if(!check_port){
_tips = layer.tips('Please tick the one I already know', '#check_port', {tips:[1,'#ff0000'],time:5000});
return false;
}
layer.close(_tips);
$('#banport').val($('[name="portss"]').val());
var _data = $("#set-Config").serializeObject();
_data['port'] = $('[name="portss"]').val();
var loadT = layer.msg(lan.config.config_save,{icon:16,time:0,shade: [0.3, '#000']});
$.post('/config?action=setPanel',_data,function(rdata){
layer.close(loadT);
layer.msg(rdata.msg,{icon:rdata.status?1:2});
if(rdata.status){
layer.close(index);
setTimeout(function(){
window.location.href = ((window.location.protocol.indexOf('https') != -1)?'https://':'http://') + rdata.host + window.location.pathname;
},4000);
}
});
},
success:function(){
$('#check_port').click(function(){
layer.closeAll('tips');
});
}
});
}
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
//关闭面板
function ClosePanel(){
layer.confirm(lan.config.close_panel_msg,{title:lan.config.close_panel_title,closeBtn:2,icon:13,cancel:function(){
@@ -845,7 +915,7 @@ function modify_basic_auth() {
} else {
m_html = '<div class="risk_form"><i class="layui-layer-ico layui-layer-ico3"></i>'
+ '<h3 class="risk_tilte">Warning! Do not understand this feature, do not open!</h3>'
+ '<ul>'
+ '<ul style="border: 1px solid #ececec;border-radius: 10px; margin: 0px auto;margin-top: 20px;margin-bottom: 20px;background: #f7f7f7; width: 100 %;padding: 33px;list-style-type: inherit;">'
+ '<li style="color:red;">You must use and understand this feature to decide if you want to open it!</li>'
+ '<li>After opening, access the panel in any way, you will be asked to enter the BasicAuth username and password first.</li>'
+ '<li>After being turned on, it can effectively prevent the panel from being scanned and found, but it cannot replace the account password of the panel itself.</li>'
+1258 -1334
View File
File diff suppressed because it is too large Load Diff
+188 -72
View File
@@ -154,7 +154,7 @@ var aceEditor = {
path:_path,
data:editor_item.ace.getValue(),
encoding:editor_item.ace.getValue()
},function(){
},function(res){
layer.msg(res.msg, {icon: 1});
editor_item.fileType = 0;
$('.item_tab_' + editor_item.id + ' .icon-tool').attr('data-file-state', '0').removeClass('glyphicon-exclamation-sign').addClass('glyphicon-remove');
@@ -414,7 +414,7 @@ var aceEditor = {
$('.menu-themes ul').html(_html);
$('.menu-themes ul li').click(function(){
var _theme = $(this).attr('data-value');
$(this).addClass('active').append(_icon).siblings().removeClass('active').find('.icon').remove();
$(this).addClass('active').append(_icon).siblings().removeClass('active').find('.icon').remove();
var _fontSize = JSON.parse(getCookie('aceEditor')).fontSize.match(/([0-9]*)px/)[1],
_data = JSON.stringify({"fontSize": _fontSize +"px","theme":_theme});
for(var item in _this.editor){
@@ -650,7 +650,7 @@ var aceEditor = {
data: editor.getValue(),
encoding: ACE.encoding
}, function (res) {
layer.msg(res.msg, {icon: 1});
layer.msg(res.msg, {icon: res.status?1:2});
ACE.fileType = 0;
$('.item_tab_' + ACE.id + ' .icon-tool').attr('data-file-state', '0').removeClass('glyphicon-exclamation-sign').addClass('glyphicon-remove');
});
@@ -957,22 +957,25 @@ function openEditorView(type,path){
});
}
var my_headers = {};
var request_token_ele = document.getElementById("request_token_head");
if (request_token_ele) {
var request_token = request_token_ele.getAttribute('token');
if (request_token) {
my_headers['x-http-token'] = request_token
function ajaxSetup() {
var my_headers = {};
var request_token_ele = document.getElementById("request_token_head");
if (request_token_ele) {
var request_token = request_token_ele.getAttribute('token');
if (request_token) {
my_headers['x-http-token'] = request_token
}
}
request_token_cookie = getCookie('request_token');
if (request_token_cookie) {
my_headers['x-cookie-token'] = request_token_cookie
}
if (my_headers) {
$.ajaxSetup({ headers: my_headers });
}
}
request_token_cookie = getCookie('request_token');
if (request_token_cookie) {
my_headers['x-cookie-token'] = request_token_cookie
}
if (my_headers) {
$.ajaxSetup({ headers: my_headers });
}
ajaxSetup();
function RandomStrPwd(b) {
b = b || 32;
@@ -2441,8 +2444,9 @@ function remind(a){
function GetReloads() {
var a = 0;
var mm = $(".bt-w-menu .bgw").html()
if(mm == undefined || mm.indexOf(lan.bt.task_list) == -1) {
var mm = $("#taskList").html()
console.log(lan.bt.task_list)
if (mm == undefined || mm.indexOf(lan.bt.task_list) == -1 ) {
clearInterval(speed);
a = 0;
speed = null;
@@ -2450,15 +2454,22 @@ function GetReloads() {
}
if(speed) return;
speed = setInterval(function() {
var mm = $(".bt-w-menu .bgw").html()
if(mm == undefined || mm.indexOf(lan.bt.task_list) == -1) {
var mm = $("#taskList").html()
if (mm == undefined || mm.indexOf(lan.bt.task_list) == -1) {
clearInterval(speed);
speed = null;
a = 0;
return
}
a++;
$.post("/files?action=GetTaskSpeed", "", function(h) {
$.post("/files?action=GetTaskSpeed", "", function (h) {
if (h.status === false) {
clearInterval(speed);
speed = null;
a = 0;
return
}
if(h.task == undefined) {
$(".cmdlist").html(lan.bt.task_not_list);
return
@@ -2580,64 +2591,169 @@ var pdata_socket = {
x_http_token: document.getElementById("request_token_head").getAttribute('token')
}
function web_shell() {
var termCols = 100;
var termRows = 34;
if (!socket) connect_io()
term = new Terminal({ cols: termCols, rows: termRows, screenKeys: true, useStyle: true });
term.setOption('cursorBlink', true);
term_box = layer.open({
type: 1,
title: 'aaPanel terminal',
area: ['920px', '630px'],
closeBtn: 2,
shadeClose: false,
content: '<a class="btlink" onclick="show_ssh_login(1)" style="position: fixed;margin-left: 140px;margin-top: -30px;">[Set]</a><div class="term-box" style="background-color:#000"><div id="term"></div></div>',
cancel: function () {
term.destroy();
},
success: function () {
term.open(document.getElementById('term'));
var Term = {
bws: null, //websocket对象
route: '/webssh', //被访问的方法
term: null,
term_box: null,
ssh_info: null,
//连接websocket
connect: function () {
if (!Term.bws || Term.bws.readyState == 3 || Term.bws.readyState == 2) {
//连接
ws_url = (window.location.protocol === 'http:' ? 'ws://' : 'wss://') + window.location.host + Term.route;
Term.bws = new WebSocket(ws_url);
//绑定事件
Term.bws.addEventListener('message', Term.on_message);
Term.bws.addEventListener('close', Term.on_close);
Term.bws.addEventListener('error', Term.on_error);
if (Term.ssh_info) Term.send(JSON.stringify(Term.ssh_info))
}
});
},
term.on('data', function (data) {
socket.emit('webssh', data);
});
$(".shell_btn_close").click(function(){
layer.close(term_box);
term.destroy();
})
setTimeout(function () {
socket.emit('webssh', "\u0015");
socket.emit('webssh', "new_bt_terminal");
//socket.emit('webssh', "new_bt_terminal");
term.focus();
}, 100)
}
function connect_io() {
socket = io.connect();
socket.on('ssh_data', function (data) {
if (data === "\rServer connection failed!\r" || data === "\rWrong user name or password!\r") {
show_ssh_login(0);
//服务器消息事件
on_message: function (ws_event) {
result = ws_event.data;
if (result === "\rServer connection failed!\r" || result === "\rWrong user name or password!\r") {
show_ssh_login(result);
Term.close();
return;
}
Term.term.write(result);
term.write(data);
if (data == '\r\n登出\r\n' || data == '登出\r\n' || data == '\r\nlogout\r\n' || data == 'logout\r\n') {
if (result == '\r\n登出\r\n' || result == '登出\r\n' || result == '\r\nlogout\r\n' || result == 'logout\r\n') {
setTimeout(function () {
layer.close(term_box);
layer.close(Term.term_box);
}, 500);
Term.close();
Term.bws = null;
}
});
},
//websocket关闭事件
on_close: function (ws_event) {
Term.bws = null;
},
//websocket错误事件
on_error: function (ws_event) {
console.log(ws_event)
},
//关闭连接
close: function () {
Term.bws.close();
},
resize: function () {
var m_width = 100;
var m_height = 34;
Term.term.resize(m_width, m_height);
Term.term.scrollToBottom();
Term.term.focus();
Term.send('new_terminal');
},
//发送数据
//@param event 唯一事件名称
//@param data 发送的数据
//@param collback 服务器返回结果时回调的函数,运行完后将被回收
send: function (data, num) {
//如果没有连接,则尝试连接服务器
if (!Term.bws || Term.bws.readyState == 3 || Term.bws.readyState == 2) {
Term.connect();
}
//判断当前连接状态,如果!=1,则100ms后尝试重新发送
if (Term.bws.readyState === 1) {
Term.bws.send(data);
} else {
if (!num) num = 0;
if (num < 5) {
num++;
setTimeout(function () { Term.send(data, num++); }, 100)
}
}
},
run: function (ssh_info) {
var termCols = 100;
var termRows = 34;
Term.term = new Terminal({ cols: termCols, rows: termRows, screenKeys: true, useStyle: true });
Term.term.setOption('cursorBlink', true);
Term.term_box = layer.open({
type: 1,
title: 'Terminal',
area: ['920px', '630px'],
closeBtn: 2,
shadeClose: false,
content: '<a class="btlink" onclick="show_ssh_login(1)" style="position: fixed;margin-left: 140px;margin-top: -30px;">[Set]</a><div class="term-box" style="background-color:#000"><div id="term"></div></div>',
cancel: function () {
Term.term.destroy();
},
success: function () {
Term.term.open(document.getElementById('term'));
Term.resize();
}
});
Term.term.on('data', function (data) {
try {
Term.bws.send(data)
} catch (e) {
Term.term.write('\r\nThe connection is lost and you are trying to reconnect!\r\n')
Term.connect()
}
});
if (ssh_info) Term.ssh_info = ssh_info
Term.connect();
},
reset_login: function () {
var ssh_info = {
data: JSON.stringify({
host: $("input[name='host']").val(),
port: $("input[name='port']").val(),
username: $("input[name='username']").val(),
password: $("input[name='password']").val()
})
}
$.post('/term_open', ssh_info, function (rdata) {
if (rdata.status === false) {
layer.msg(rdata.msg);
return;
}
layer.closeAll();
Term.connect();
Term.term.scrollToBottom();
Term.term.focus();
});
}
}
function web_shell() {
Term.run();
}
socket = {
emit: function (data,data2) {
if (data === 'webssh') {
data = data2
}
if (typeof(data) === 'object') {
return;
}
Term.send(data);
}
}
function show_ssh_login(is_config) {
if ($("input[name='ssh_user']").attr('autocomplete')) return;
var s_body = '<div class="bt-form bt-form pd20 pb70">\
@@ -2681,7 +2797,7 @@ function show_ssh_login(is_config) {
<div class="line ssh_pkey" style="display:none;"><span class="tname">Key</span><div class="info-r "><textarea name="ssh_pkey" class="bt-input-text mr5" style="width:330px;height:80px;" ></textarea></div></div>\
<div class="line " style="margin-left: -40px;"><span class="tname"></span><div class="info-r "><input style="margin-top: 1px;width: 16px;" name="ssh_is_save" id="ssh_is_save" class="bt-input-text mr5" type="checkbox" ><label style="position: absolute;margin-left: 5px;" for="ssh_is_save">Remember password, the next time you use the aaPanel terminal will automatically log in</label></div></div>\
<p style="color: red;margin-top: 10px;text-align: center;margin-left: -62px;">Only support login to this server</p>\
<div class="bt-form-submit-btn"><button type="button" class="btn btn-sm btn-danger" onclick="'+ (is_config ? 'layer.close(ssh_login)' :'layer.closeAll()')+'">Close</button><button type="button" class="btn btn-sm btn-success ssh-login" onclick="send_ssh_info('+is_config+')">'+(is_config?'Confirm':'Login SSH')+'</button></div></div>';
<div class="bt-form-submit-btn"><button type="button" class="btn btn-sm btn-danger" onclick="'+ (is_config ? 'layer.close(ssh_login)' :'layer.closeAll()')+'">Close</button><button type="button" class="btn btn-sm btn-success ssh-login" onclick="send_ssh_info()">'+(is_config?'Confirm':'Login SSH')+'</button></div></div>';
ssh_login = layer.open({
type: 1,
title: is_config?'Please fill in the SSH connection configuration':'Please enter the SSH login account and password',
@@ -2766,9 +2882,9 @@ function send_ssh_info() {
var loadT = layer.msg('Trying to log in to SSH...', { icon: 16, time: 0, shade: 0.3 });
$.post("/term_open", { data: JSON.stringify(pdata) }, function () {
layer.close(loadT)
socket.emit('webssh', pdata);
Term.send('reset_connect');
layer.close(ssh_login)
term.focus();
Term.term.focus();
})
+8 -4
View File
@@ -1315,7 +1315,7 @@ bt.index = {
var m = "<input id='data_" + l[h].name + "' data-info='" + l[h].name + " " + l[h].versions[0].version + "' type='checkbox' checked>";
for(var b = 0; b < l[h].versions.length; b++) {
var d = "";
if((l[h].name == "PHP" && (l[h].versions[b].version == "5.4" || l[h].versions[b].version == "54")) || (l[h].name == "MySQL" && l[h].versions[b].version == "5.5") || (l[h].name == "phpMyAdmin" && l[h].versions[b].version == "4.4")) {
if((l[h].name == "PHP" && (l[h].versions[b].version == "5.6" || l[h].versions[b].version == "5.6")) || (l[h].name == "MySQL" && l[h].versions[b].version == "5.6") || (l[h].name == "phpMyAdmin" && l[h].versions[b].version == "4.4")) {
d = "selected";
m = "<input id='data_" + l[h].name + "' data-info='" + l[h].name + " " + l[h].versions[b].version + "' type='checkbox' checked>"
}
@@ -1433,7 +1433,11 @@ bt.index = {
case "5.7":
max = 1500;
msg = "2GB";
break;
break;
case "8.0":
max = 5000;
msg = "6GB";
break;
case "5.6":
max = 800;
msg = "1GB";
@@ -3207,9 +3211,9 @@ bt.soft = {
},
php : {
get_config:function(version,callback){ //获取禁用函数,扩展列表
var loading = bt.load();
//var loading = bt.load();
bt.send('GetPHPConfig','ajax/GetPHPConfig',{version:version},function(rdata){
loading.close();
//loading.close();
if(callback) callback(rdata);
})
},
+8
View File
@@ -2550,6 +2550,14 @@ var site = {
bt.msg(ret);
})
}
},
{
text: 'Allow empty HTTP_REFERER requests', name: 'none', value: rdata.none, type: 'checkbox', callback: function (sdata) {
bt.site.set_site_security(web.id, web.name, sdata.sec_fix, sdata.sec_domains, '1', function (ret) {
if (ret.status) site.reload(13)
bt.msg(ret);
})
}
}
]
}
+463 -21
View File
@@ -18,7 +18,7 @@ var soft = {
}
soft.is_install = false;
bt.soft.get_soft_list(page, type, search, function (rdata) {
if (rdata.pro >= 0) {
if (rdata.pro < 0) {
$("#updata_pro_info").html('');
} else if (rdata.pro === -2) {
$("#updata_pro_info").html('<div class="alert alert-success" style="margin-bottom:15px"><strong>' + lan.soft.pro_expire + '</strong><button class="btn btn-success btn-xs va0 updata_pro" onclick="bt.soft.updata_pro()" title="' + lan.soft.renew_pro + '" style="margin-left:8px">' + lan.soft.renew_now + '</button>');
@@ -27,19 +27,20 @@ var soft = {
}
if (type == 10) {
$("#updata_pro_info").html('<div class="alert alert-info" style="margin-bottom:15px"><strong>' + lan.soft.bt_developer + '</strong><a class="btn btn-success btn-xs va0" href="https://www.bt.cn/developer/" title="' + lan.soft.free_to_enter + '" style="margin-left: 8px" target="_blank">' + lan.soft.free_to_enter + '</a><a class="btn btn-success btn-xs va0" href="https://www.bt.cn/bbs/forum-40-1.html" title="' + lan.soft.get_third_party_apps + '" style="margin-left: 8px" target="_blank">' + lan.soft.get_third_party_apps + '</a><input type="file" style="display:none;" accept=".zip,.tar.gz" id="update_zip" multiple="multiple"><button class="btn btn-success btn-xs" onclick="soft.update_zip_open()" style="margin-left:8px">' + lan.soft.import_plug + '</button></div>')
$("#updata_pro_info").html('<div class="alert alert-danger" style="margin-bottom:15px"><strong>' + lan.soft.bt_developer + '</strong><a class="btn btn-success btn-xs va0" href="https://forum.aapanel.com/d/600-third-party-plug-in-for-aapanel-nginx-free-firewall" title="' + lan.soft.get_third_party_apps + '" style="margin-left: 8px" target="_blank">' + lan.soft.get_third_party_apps + '</a><input type="file" style="display:none;" accept=".zip,.tar.gz" id="update_zip" multiple="multiple"><button class="btn btn-success btn-xs" onclick="soft.update_zip_open()" style="margin-left:8px">' + lan.soft.import_plug + '</button></div>')
} else if (type == 11) {
$("#updata_pro_info").html('<div class="alert alert-info" style="margin-bottom:15px"><strong>'+lan.soft.comingsoon+'</strong></div>')
}
var tBody = '';
rdata.type.unshift({ icon: 'icon', id: 0, ps: lan.soft.all, sort: 1, title: lan.soft.all })
rdata.type.unshift({ icon: 'icon', id: 0, ps: lan.soft.all, sort: 1, title: lan.soft.all },{ icon: 'icon', id: -1, ps: 'Installed', sort: 1, title: 'Installed' })
for (var i = 0; i < rdata.type.length; i++) {
var c = '';
if (istype == rdata.type[i].id) {
c = 'class="on"';
}
// 注释软件管理的付费插件,第三方插件,一键部署
if (rdata.type[i].id != "11" && rdata.type[i].id != "10" && rdata.type[i].id != "8") {
// if (rdata.type[i].id != "11" && rdata.type[i].id != "10" && rdata.type[i].id != "8") {
if (rdata.type[i].id != "11" && rdata.type[i].id != "8") {
tBody += '<span typeid="' + rdata.type[i].id + '" ' + c + '>' + rdata.type[i].title + '</span>';
}
}
@@ -121,6 +122,11 @@ var soft = {
return price;
}
},
(type ==10?{
field: 'sort', width: 60, title: 'Score', templet: function (item) {
return item.sort !== undefined?('<a href="javascript:;" onclick="score.open_score_view('+ item.pid +',\''+ item.title +'\','+ item.count +')" class="btlink open_sort_view">' + (item.sort <= 0 || item.sort >5?'无评分':item.sort.toFixed(1)) +'</a>'):'--';
}
}:''),
{
field: 'endtime', width: 120, title: lan.soft.expire_time, templet: function (item) {
var endtime = '--';
@@ -161,7 +167,7 @@ var soft = {
return path;
}
},
{
(type !=10?{
field: 'status', width: 40, title: lan.soft.status1, templet: function (item) {
var status = '';
if (item.setup) {
@@ -174,7 +180,7 @@ var soft = {
}
return status;
}
},
}:''),
{
field: 'index', width: 100, title: lan.soft.display_at_homepage, templet: function (item) {
var to_index = '';
@@ -189,8 +195,8 @@ var soft = {
},
{
field: 'opt', width: 180, title: lan.soft.operate, align: 'right', templet: function (item) {
console.log(item)
var option = '';
var pay_opt = '';
if (item.endtime < 0 && item.pid > 0) {
var re_msg = '';
@@ -236,7 +242,6 @@ var soft = {
var min_version = item.versions[i]
var ret = bt.check_version(item.version, min_version.m_version + '.' + min_version.version);
if (ret > 0) {
if (!min_version.update_msg) min_version.update_msg = '';
if (ret == 2) option += '<a class="btlink" onclick="bt.soft.update_soft(\'' + item.name + '\',\'' + item.title + '\',\'' + min_version.m_version + '\',\'' + min_version.version + '\',\'' + min_version.update_msg.replace(/\n/g,"_bt_") + '\')" >' + lan.soft.update + '</a> | ';
break;
}
@@ -245,7 +250,6 @@ var soft = {
else {
var min_version = item.versions[0];
var cloud_version = min_version.m_version + '.' + min_version.version;
if (!min_version.update_msg) min_version.update_msg = '';
if (item.version != cloud_version) option += '<a class="btlink" onclick="bt.soft.update_soft(\'' + item.name + '\',\'' + item.title + '\',\'' + min_version.m_version + '\',\'' + min_version.version + '\',\'' + min_version.update_msg.replace(/\n/g, "_bt_") + '\')" >' + lan.soft.update + '</a> | ';
}
if (item.admin) {
@@ -318,8 +322,7 @@ var soft = {
$.post('/deployment?action=GetList', pdata, function (rdata) {
layer.close(loadT)
var tBody = '';
rdata.type.unshift({ icon: 'icon', id: 0, ps: 'All', sort: 1, title: 'All' })
rdata.type.unshift({ icon: 'icon', id: 0, ps: 'All', sort: 1, title: 'All' },{ icon: 'icon', id: -1, ps: 'Installed', sort: 1, title: 'Installed' });
for (var i = 0; i < rdata.type.length; i++) {
var c = '';
if ('11' == rdata.type[i].id) {
@@ -373,6 +376,7 @@ var soft = {
<th>Introduction</th>\
<th>Support for PHP version</th>\
<th>Provider</th>\
<th>Score</th>\
<th style="text-align: right;" width="80">Operate</th>\
</tr>\
</thead>';
@@ -391,6 +395,8 @@ var soft = {
+ '<td>' + rdata.list[i].ps + '</td>'
+ '<td>' + rdata.list[i].php + '</td>'
+ '<td><a class="btlink" target="_blank" href="' + rdata.list[i].official + '">' + (rdata.list[i].author == 'aaPanel' ? rdata.list[i].title : rdata.list[i].author) + '</a></td>'
+ '<td>' + (rdata.list[i].sort !== undefined?('<a href="javascript:;" class="btlink open_score_view" onclick="score.open_score_view('+ rdata.list[i].id +',\''+ rdata.list[i].title +'\','+ rdata.list[i].count +')" >' + (rdata.list[i].sort <= 0 || rdata.list[i].sort > 5?'No rating':rdata.list[i].sort.toFixed(1))+'</a>'):'--')
+ '</td>'
+ '<td class="text-right"><a href="javascript:onekeyCodeSite(\'' + rdata.list[i].name + '\',\'' + rdata.list[i].php + '\',\'' + rdata.list[i].title + '\',\'' + rdata.list[i].enable_functions + '\');" class="btlink">One-Click</a>' + remove_opt+'</td>'
+ '</tr>'
}
@@ -1410,7 +1416,11 @@ var soft = {
case 'set_php_config':
bt.soft.php.get_config(version, function (rdata) {
$(".soft-man-con").empty().append('<div class="divtable" id="phpextdiv" style="margin-right:10px;height: 510px; overflow: auto; margin-right: 0px;"><table id="tab_phpext" class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0"></div></div>');
var divObj = document.getElementById('phpextdiv');
var scrollTopNum = 0;
if (divObj) scrollTopNum = divObj.scrollTop;
$(".soft-man-con").empty().append('<div class="divtable" id="phpextdiv" style="margin-right:10px;height: 420px; overflow: auto; margin-right: 0px;"><table id="tab_phpext" class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0"></div></div>');
var list = [];
for (var i = 0; i < rdata.libs.length; i++) {
@@ -1448,9 +1458,7 @@ var soft = {
$(".soft-man-con").append(bt.render_help(helps));
var divObj = document.getElementById('phpextdiv');
var scrollTopNum = 0;
if (divObj) scrollTopNum = divObj.scrollTop;
document.getElementById('phpextdiv').scrollTop = scrollTopNum;
if (divObj) divObj.scrollTop = scrollTopNum;
$('a').click(function () {
var _obj = $(this);
if (_obj.hasClass('lib-uninstall')) {
@@ -1468,6 +1476,12 @@ var soft = {
});
}
})
if ($(".bt-soft-menu .bgw").text() === "Installation extension") {
setTimeout(function () {
soft.get_tab_contents('set_php_config', obj);
}, 3000)
}
})
break;
case 'get_phpinfo':
@@ -1637,7 +1651,6 @@ var soft = {
field: 'opt', title: lan.public.action, width: 50, templet: function (item) {
var new_disable_functions = disable_functions.slice()
new_disable_functions.splice($.inArray(item.name, new_disable_functions), 1)
// console.log(new_disable_functions)
return '<a class="del_functions" style="float:right;" data-val="shell_exec" onclick="set_disable_functions(\'' + version + '\',\'' + new_disable_functions.join(',') + '\')" href="javascript:;">' + lan.soft.del + '</a>';
}
}
@@ -1709,7 +1722,6 @@ var soft = {
{ title: 'max_spare_servers', name: 'max_spare_servers', value: rdata.max_spare_servers, type: 'number', width: '100px', ps: '*' + lan.soft.php_fpm_ps5 },
{
title: ' ', text: lan.public.save, name: 'btn_children_submit', css: 'btn-success', type: 'button', callback: function (ldata) {
// console.log(ldata)
bt.pub.get_menm(function (memInfo) {
var limit_children = parseInt(memInfo['memTotal'] / 8);
if (limit_children < parseInt(ldata.max_children)) {
@@ -1825,7 +1837,6 @@ var soft = {
'</div>');
if(res.save_handler == 'files'){
bt.soft.php.get_session_count(function(res){
// console.log(res);
$('.clear_conter').html('<div class="session_clear_list"><div class="line"><span>' + lan.soft.total_seesion_files + '</span><span>' + res.total + '</span></div><div class="line"><span>' + lan.soft.can_clear_seesion + '</span><span>' + res.oldfile + '</span></div></div><button class="btn btn-success btn-sm clear_session_file">' + lan.soft.clear_seesion_files + '</button>')
$('.clear_session_file').click(function(){
bt.soft.php.clear_session_count({
@@ -2221,7 +2232,8 @@ function onekeyCodeSite(codename, versions,title,enable_functions) {
layer.msg('Missing supported PHP version, please install!', { icon: 5 });
return;
}
var default_path = bt.get_cookie('sites_path');
if (!default_path) default_path = '/www/wwwroot';
var con = '<form class="bt-form pd20 pb70" id="addweb">\
@@ -2234,7 +2246,7 @@ function onekeyCodeSite(codename, versions,title,enable_functions) {
<div class="info-r c4"><input id="Wbeizhu" class="bt-input-text" name="ps" placeholder="Website note" style="width:398px" type="text"> </div>\
</div>\
<div class="line"><span class="tname">Root Directory</span>\
<div class="info-r c4"><input id="inputPath" class="bt-input-text mr5" name="path" value="/www/wwwroot/" placeholder="Website root directory" style="width:398px" type="text"><span class="glyphicon glyphicon-folder-open cursor" onclick="ChangePath(\'inputPath\')"></span> </div>\
<div class="info-r c4"><input id="inputPath" class="bt-input-text mr5" name="path" value="'+ default_path+'" placeholder="Website root directory" style="width:398px" type="text"><span class="glyphicon glyphicon-folder-open cursor" onclick="ChangePath(\'inputPath\')"></span> </div>\
</div>\
<div class="line"><span class="tname">Database</span>\
<div class="info-r c4">\
@@ -2289,7 +2301,8 @@ function onekeyCodeSite(codename, versions,title,enable_functions) {
});
//FTP账号数据绑定域名
$('#mainDomain').on('input', function () {
var defaultPath = '/www/wwwroot';
var default_path = bt.get_cookie('sites_path');
if (!default_path) default_path = '/www/wwwroot';
var array;
var res, ress;
var str = $(this).val();
@@ -2333,4 +2346,433 @@ function _getRandomString(len) {
pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
var score = {
total:1,
type:'',
data:[],
// 获取评论信息
get_score_info:function (obj,callback) {
var loadT = layer.msg('<div class="depSpeed">Getting comment information <img src="/static/img/ing.gif"></div>', { icon: 16, time: 0, shade: [0.3, "#000"] });
bt.send('get_score','plugin/get_score',{
pid:obj.pid,
p:obj.p,
limit_num:obj.limit_num
},function(res){
layer.close(loadT);
if(res.status === false){
layer.msg(res.msg,{icon:2});
return false;
}
if(callback) callback(res);
});
},
render_score_info:function(obj,callback){
var config = {pid:obj.pid},_this = this;
obj.p == undefined?config.p = 1:config.p = parseInt(obj.p)
obj.limit_num == undefined?config.limit_num = '':config.limit_num = obj.limit_num
score.get_score_info(config,function(res){
var _split_score = res.split.reverse(),_average_score = (_split_score[4]*1+_split_score[3]*2+_split_score[2]*3+_split_score[1]*4 +_split_score[0]*5)/res.total,_data = res.data,_html ='';
_this.total = res.total;
$('.comment_user_count').text(obj.count);
$('.comment_num').text((res.total!==0?_average_score:0).toFixed(1));
$('.comment_partake').text(res.total);
$('.comment_rate').text(res.total!==0?((((_split_score[0]+_split_score[1])/res.total).toFixed(2)*100)+'%'):'0%');
for(var i=0;i<5;i++){
$('.comment_star_group:eq('+ i +')').find('.comment_progress .comment_progress_bgw').css('width',((_split_score[i] / res.total).toFixed(2)*100)+'%')
}
$('.comment_tab span:eq(1)').find('i').text(_split_score[0]+_split_score[1]);
$('.comment_tab span:eq(2)').find('i').text(_split_score[2]+_split_score[3]);
$('.comment_tab span:eq(3)').find('i').text(_split_score[4]);
for (var j = 0; j < _data.length; j++){
_html += '<div class="comment_box" data-index="'+ ((config.p == 1?'':config.p-1)+(j+'')) +'">\
<div class="comment_box_title">\
<span class="nice_star">\
<span class="glyphicon '+ (_data[j].num >=1?'star_active':'') +' glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon '+ (_data[j].num >=2?'star_active':'') +' glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon '+ (_data[j].num >=3?'star_active':'') +' glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon '+ (_data[j].num >=4?'star_active':'') +' glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon '+ (_data[j].num >=5?'star_active':'') +' glyphicon-star" aria-hidden="true"></span>\
</span>\
<span class="nice_name" title="'+ _data[j].nickname +'">'+ _data[j].nickname +'</span>\
<span class="nice_time" title="'+ bt.format_data(_data[j].addtime ) +'">'+ timeago(_data[j].addtime * 1000) +'</span>\
</div>\
<div class="comment_box_content">'+ (getLength(_data[j].ps)>65?reBytesStr(_data[j].ps,65)+'...&nbsp;<a href="javascript:;" class="btlink">Details</a>':_data[j].ps) +'</div>\
</div>'
// console.log(getLength(_data[j].ps)>70?reBytesStr(_data[j].ps,70)+'&nbsp;<a href="javascript:;" class="btlink">详情</a>':_data[j].ps);
}
_this.data = _this.data.concat(_data);
if(res.total > 10 && _data.length === 10){
_html += '<div class="comment_box get_next_page"><span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span>Click for more comments</div>'
}
$('.comment_content').find('.get_next_page').remove();
$('.comment_content').append(_html);
if($('.comment_content .comment_box').length > 6){
$('.comment_content').addClass('box-shadow');
}else{
$('.comment_content').removeClass('box-shadow');
}
if(callback) callback(res);
});
},
// 设置评论信息
set_score_info:function (obj,callback){
var loadT = layer.msg('<div class="depSpeed">Submitting comment <img src="/static/img/ing.gif"></div>', { icon: 16, time: 0, shade: [0.3, "#000"] });
bt.send('set_score','plugin/set_score',{
pid:obj.pid,
num:obj.num,
ps:obj.ps
},function(res){
layer.close(loadT);
if(res.status === false){
layer.msg(res.msg,{icon:2});
return false;
}
if(callback) callback(res);
});
},
open_score_view:function(_pid,_name,_count){
layer.open({
type: 1,
title:'[ '+ _name + '] Score',
area:['550px','350px'],
closeBtn: 2,
shadeClose: false,
content:'<div class="pd20 score_info_view"><div class="comment_title">\
<div class="comment_left">\
<div class="comment_num">--</div>\
<ul class="comment_num_tips">\
<li>user count&nbsp;<span class="comment_user_count">--</span></li>\
<li>&nbsp;<span class="comment_partake">--</span>&nbsp;people participated in the score</li>\
<li><span class="comment_rate">--</span>&nbsp;Favorable rate</li>\
</ul>\
</div>\
<div class="comment_right">\
<div class="comment_star_group">\
<div class="comment_star">\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
</div>\
<div class="comment_progress">\
<div class="comment_progress_bgw"></div>\
<div class="comment_progress_speed"></div>\
</div>\
</div>\
<div class="comment_star_group">\
<div class="comment_star">\
<span class="glyphicon star_none glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
</div>\
<div class="comment_progress">\
<div class="comment_progress_bgw"></div>\
<div class="comment_progress_speed"></div>\
</div>\
</div>\
<div class="comment_star_group">\
<div class="comment_star">\
<span class="glyphicon star_none glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_none glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
</div>\
<div class="comment_progress">\
<div class="comment_progress_bgw"></div>\
<div class="comment_progress_speed"></div>\
</div>\
</div>\
<div class="comment_star_group">\
<div class="comment_star">\
<span class="glyphicon star_none glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_none glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_none glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
</div>\
<div class="comment_progress">\
<div class="comment_progress_bgw"></div>\
<div class="comment_progress_speed"></div>\
</div>\
</div>\
<div class="comment_star_group">\
<div class="comment_star">\
<span class="glyphicon star_none glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_none glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_none glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_none glyphicon-star" aria-hidden="true"></span>\
<span class="glyphicon star_active glyphicon-star" aria-hidden="true"></span>\
</div>\
<div class="comment_progress">\
<div class="comment_progress_bgw"></div>\
<div class="comment_progress_speed"></div>\
</div>\
</div>\
</div>\
</div>\
<div class="comment_tab">\
<span class="active" data-num="">All evaluation</span>\
<span data-num="5">Praise&nbsp;<i>--</i>&nbsp;</span>\
<span data-num="3">Average&nbsp;<i>--</i>&nbsp;</span>\
<span data-num="1">Bad review&nbsp;<i>--</i>&nbsp;</span>\
</div>\
<div class="comment_content">\
</div>\
<div class="add_score_view">\
<div class="score_icon_group" data-icon="5">\
<span class="glyphicon glyphicon-star active" aria-hidden="true" title="very bad1 star"></span>\
<span class="glyphicon glyphicon-star active" aria-hidden="true" title="bad2 star"></span>\
<span class="glyphicon glyphicon-star active" aria-hidden="true" title="general3 star"></span>\
<span class="glyphicon glyphicon-star active" aria-hidden="true" title="good4 star"></span>\
<span class="glyphicon glyphicon-star active" aria-hidden="true" title="very good5 star" ></span>\
</div>\
<div class="score_icon_group_tips">Recommended: 5 points</div>\
<textarea class="score_input bt-input-text" placeholder="Please enter the evaluation content, the number of words is less than 60 words, can be empty." name="score_val"></textarea>\
<span class="score_input_tips pull-right">Can also enter&nbsp;<i>60</i>&nbsp;words</span>\
</div>\
<div class="edit_view ">\
<span>Participate in the score</span>\
</div>\
</div>'
,success:function(index,layero){
score.data = [];
score.render_score_info({pid:_pid,count:_count},function(){
$('.score_info_view').show();
});
score.score_icon_time = null;
$('.score_icon_group span').hover(function(){
var _active = $(this).hasClass('active');
// if($(this).prevAll().length == 0 && $(this).nextAll('.active').length == 0 && _active){
// $(this).removeClass('active').nextAll().removeClass('active')
// $('.score_icon_group_tips').html('选择以上图标选择评分等级1-5');
// $('.score_icon_group').attr('data-icon',0)
// }else{
// $(this).addClass('active').nextAll().removeClass('active');
// $(this).prevAll().addClass('active');
// $('.score_icon_group').attr('data-icon',$(this).prevAll().length +1)
// var _title = $(this).attr('title');
// $('.score_icon_group_tips').text(_title);
// }
});
$('.score_icon_group span').click(function(){
var _active = $(this).hasClass('active');
if($(this).prevAll().length == 0 && $(this).nextAll('.active').length == 0 && _active){
$('.edit_view').addClass('active');
$(this).removeClass('active').nextAll().removeClass('active')
$('.score_icon_group_tips').html('Click on the selection icon to rate 1-5 stars');
$('.score_icon_group').attr('data-icon',0)
}else{
$('.edit_view').removeClass('active');
$(this).addClass('active').nextAll().removeClass('active');
$(this).prevAll().addClass('active');
$('.score_icon_group').attr('data-icon',$(this).prevAll().length +1)
var _title = $(this).attr('title');
$('.score_icon_group_tips').text(_title);
}
});
$('.comment_tab span').click(function(e){
var _num = $(this).attr('data-num');
$('.comment_content').removeClass('box-shadow');
$(this).addClass('active').siblings().removeClass('active');
$('.comment_content').html('');
score.data = []
score.type = _num;
score.render_score_info({pid:_pid,limit_num:_num,count:_count});
});
$('.comment_content').on('click','.get_next_page',function () {
var _next_page = ($('.comment_content .comment_box').length / 10)+1;
score.render_score_info({pid:_pid,limit_num:score.type,p:_next_page,count:_count});
});
$('.comment_content').on('click','.comment_box',function(){
if(!$(this).hasClass('get_next_page')){
var _index = $(this).attr('data-index');
layer.open({
type: 1,
title:false,
area:['350px','200px'],
closeBtn: 2,
shadeClose: false,
content: '<div class="score_details" >'+ $(this).html() +'</div>',
success:function(index,layers) {
$('.score_details .comment_box_content').html(score.data[_index]['ps']);
}
});
}
});
$('.edit_view').click(function(){
if($('.edit_view').hasClass('active')){
// layer.msg('请选择评分等级',{icon:2});
$('.score_icon_group_tips').css('color','red');
setTimeout(function(){
$('.score_icon_group_tips').removeAttr('style')
},1000);
return false
}
var _num = parseInt($('.score_icon_group').attr('data-icon')),_ps = $('.score_input').val();
if(_num == 0){
layer.msg('Rating level cannot be empty',{icon:2});
return false;
}
if(120 - getLength(_ps)<0){
layer.msg('Evaluation information cannot exceed 60 words',{icon:2});
return false;
}
score.set_score_info({pid:_pid,num:_num,ps:_ps == ''?'User did not make any evaluation': _ps},function(res){
layer.msg(res.msg,{icon:1});
score.render_score_info({pid:_pid,limit_num:score.type,count:_count});
soft.flush_cache();
layer.close(index);
});
return false
layer.open({
type: 1,
title:'Add review',
area:['400px','350px'],
closeBtn: 2,
shadeClose: false,
btn:['Confirm','Cancel'],
content:'<div class="add_score_view">\
<div class="score_icon_group" data-icon="0">\
<span class="glyphicon glyphicon-star" aria-hidden="true" title="very bad1 star"></span>\
<span class="glyphicon glyphicon-star" aria-hidden="true" title="bad2 star"></span>\
<span class="glyphicon glyphicon-star" aria-hidden="true" title="general3 star"></span>\
<span class="glyphicon glyphicon-star" aria-hidden="true" title="good4 star"></span>\
<span class="glyphicon glyphicon-star" aria-hidden="true" title="very good5 star" ></span>\
</div>\
<div class="score_icon_group_tips">(Click on the icon above to select rating 1-5)</div>\
<textarea class="score_input bt-input-text" placeholder="Please enter the evaluation content, the number of words is less than 60 words, can be empty." name="score_val"></textarea>\
<span class="score_input_tips pull-right">Can also enter&nbsp;<i>60</i>&nbsp;words</span>\
</div>',
success:function(){
$('.score_icon_group span').click(function(){
var _active = $(this).hasClass('active');
if($(this).prevAll().length == 0 && $(this).nextAll('.active').length == 0 && _active){
$(this).removeClass('active').nextAll().removeClass('active')
$('.score_icon_group_tips').html('(Click on the icon above to select rating 1-5)');
$('.score_icon_group').attr('data-icon',0)
}else{
$(this).addClass('active').nextAll().removeClass('active');
$(this).prevAll().addClass('active');
$('.score_icon_group').attr('data-icon',$(this).prevAll().length +1)
var _title = $(this).attr('title');
$('.score_icon_group_tips').text(_title);
}
});
$('.score_input').on('keydown keyup focus click',function(){
var _val = $('.score_input').val(),_size = 120 - getLength(_val);
if(_size > 0){
$('.score_input_tips i').css('color',_size > 20?'#666':'red').text(parseInt(_size/2));
$('.score_input').attr('style','');
}else{
$('.score_input_tips i').text(0)
$('.score_input').css({'outline-color':'red','border':'1px solid red'});
}
});
},
yes:function(index,layero){
var _num = parseInt($('.score_icon_group').attr('data-icon')),_ps = $('.score_input').val();
if(_num == 0){
layer.msg('Rating level cannot be empty',{icon:2});
return false;
}
if(120 - getLength(_ps)<0){
layer.msg('Evaluation information cannot exceed 60 words',{icon:2});
return false;
}
score.set_score_info({pid:_pid,num:_num,ps:_ps == ''?'User did not make any evaluation': _ps},function(res){
layer.msg(res.msg,{icon:1});
score.render_score_info({pid:_pid,limit_num:score.type,count:_count});
soft.flush_cache();
layer.close(index);
});
}
});
});
}
})
}
}
function timeago(dateTimeStamp){ //dateTimeStamp是一个时间毫秒,注意时间戳是秒的形式,在这个毫秒的基础上除以1000,就是十位数的时间戳。13位数的都是时间毫秒。
if(dateTimeStamp.toString().length < 10) dateTimeStamp = dateTimeStamp * 1000
var minute = 1000 * 60,
hour = minute * 60,
day = hour * 24,
week = day * 7,
halfamonth = day * 15,
month = day * 30,
now = new Date().getTime(), //获取当前时间毫秒
diffValue = now - dateTimeStamp;//时间差
if(diffValue <= 0){return 'Just a moment ago';}
var minC = diffValue/minute, //计算时间差的分,时,天,周,月
hourC = diffValue/hour,
dayC = diffValue/day,
weekC = diffValue/week,
monthC = diffValue/month,
result ='Just a moment ago';
if(monthC >= 1 && monthC <= 3){
result = " " + parseInt(monthC) + "month ago"
}else if(weekC >= 1 && weekC <= 3){
result = " " + parseInt(weekC) + "week ago"
}else if(dayC >= 1 && dayC <= 6){
result = " " + parseInt(dayC) + "day ago"
}else if(hourC >= 1 && hourC <= 23){
result = " " + parseInt(hourC) + "hour ago"
}else if(minC >= 1 && minC <= 59){
result =" " + parseInt(minC) + "minute ago"
}else if(diffValue >= 0 && diffValue <= minute){
result = "Just a moment ago"
}else {
var datetime = new Date();
datetime.setTime(dateTimeStamp);
var Nyear = datetime.getFullYear(),
Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1,
Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate(),
Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours(),
Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes(),
Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds(),
result = Nmonth + "-" + Ndate
}
if (!result) result = 'Just a moment ago'
return ((result == undefined || result == 'undefined')?'Just a moment ago':result);
}
// 规则转码
function escapeHTML(val) {
val = "" + val;
return val.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, '&quot;').replace(/'/g, "").replace(/\(/g, "&#40;").replace(/\&#60;/g, "&lt;").replace(/\&#62;/g, "&gt;").replace(/`/g, "&#96;").replace(/=/g, "");
}
function getLength(val) {
var str = new String(val);
var bytesCount = 0;
for (var i = 0 ,n = str.length; i < n; i++) {
var c = str.charCodeAt(i);
if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
bytesCount += 1;
} else {
bytesCount += 2;
}
}
return bytesCount;
}
function reBytesStr(str, len) {
if ((!str && typeof(str) != 'undefined')) {return '';}
var num = 0;
var str1 = str;
var str = '';
for (var i = 0,lens = str1.length; i < lens; i++) {
num += ((str1.charCodeAt(i) > 255) ? 2 : 1);
if (num > len) {
break;
} else {
str = str1.substring(0, i + 1);
}
}
return str;
}
+10 -7
View File
@@ -77,15 +77,18 @@
<span class="set-info c7">{{data['lan']['CY1']}}</span>
</div>
<div class="mtb15">
<span class="set-tit text-right" title="{{data['lan']['CT2']}}">{{data['lan']['CT2']}}</span>
<input id="banport" name="port" class="inputtxt bt-input-text" type="number" value="{{data['panel']['port']}}" maxlength="5">
<div class="btn_tips">
<span class="set-tit text-right" title="{{data['lan']['CT2']}}">{{data['lan']['CT2']}}</span>
<input id="banport" name="port" class="inputtxt bt-input-text disable" type="number" value="{{data['panel']['port']}}" maxlength="5" disabled>
<span class="modify btn btn-xs btn-success" onclick="modify_port_val({{data['panel']['port']}})">{{data['lan']['CY10']}}</span>
</div>
<span class="set-info c7">{{data['lan']['CY2']}}, <a style="color:red;">{{data['lan']['S_PORT_TIPS']}}</a></span>
</div>
<div class="mtb15">
<span class="set-tit text-right" title="{{data['lan']['panel_performance']}}">{{data['lan']['concurrent_thread']}}</span>
<input name="workers" class="inputtxt bt-input-text" type="number" min="1" max="1024" value="{{data['workers']}}">
<span class="set-info c7">{{data['lan']['thread_ps']}}</span>
</div>
<!-- <div class="mtb15">-->
<!-- <span class="set-tit text-right" title="{{data['lan']['panel_performance']}}">{{data['lan']['concurrent_thread']}}</span>-->
<!-- <input name="workers" class="inputtxt bt-input-text" type="number" min="1" max="1024" value="{{data['workers']}}">-->
<!-- <span class="set-info c7">{{data['lan']['thread_ps']}}</span>-->
<!-- </div>-->
<div class="mtb15">
<span class="set-tit text-right" title="{{data['lan']['LOGINTIMEOUT']}}">{{data['lan']['TIMEOUT']}}</span>
<input name="session_timeout" class="inputtxt bt-input-text" type="number" value="{{data['session_timeout']}}">
+1 -1
View File
@@ -8,6 +8,6 @@
<h1>{1}</h1>
<p>{2}</p>
<hr>
<address>{3} 6.x <a href="https://www.bt.cn/bbs" target="_blank">{4}</a></address>
<address>{3} <a href="https://forum.aapanel.com/" target="_blank">{4}</a></address>
</body>
</html>
+1 -1
View File
@@ -10,6 +10,6 @@
<p>{3}</p>
<p>{4}</p>
<hr>
<address>{5} 6.x <a href="http://www.bt.cn/bbs" target="_blank">{6}</a></address>
<address>{5} <a href="https://forum.aapanel.com/" target="_blank">{6}</a></address>
</body>
</html>
+8 -7
View File
@@ -68,6 +68,7 @@
<span class="replaces"><i class="fa fa-random" aria-hidden="true"></i>Replace</span>
<span class="fontSize"><i class="glyphicon glyphicon-text-width" aria-hidden="true"></i>Font</span>
<span class="themes"><i class="glyphicon glyphicon-magnet" aria-hidden="true"></i>Theme</span>
<span class="setUp"><i class="glyphicon glyphicon-cog" aria-hidden="true"></i>Set</span>
<span class="helps"><i class="glyphicon glyphicon-question-sign" aria-hidden="true"></i>Help</span>
<div class="pull-down" title="Hide toolbar"><i class="glyphicon glyphicon-menu-down" aria-hidden="true"></i></div>
</div>
@@ -77,13 +78,14 @@
<div class="ace_catalogue_title">Favorites</div>
<div class="ace_catalogue_list">
<ul class="cd-accordion-menu animated">
<li class="has-children "><span>Back to previous</span></li>
<li class="has-children">
<input type="checkbox" name ="group-1" id="group-1" checked>
<label for="group-1">Group 1</label>
<label for="group-1" class="file_fold"><span class="glyphicon glyphicon-menu-right"></span><span><i class="folder_icon"></i>Document list</span></label>
<ul>
<li class="has-children">
<input type="checkbox" name ="sub-group-1" id="sub-group-1">
<label for="sub-group-1">Sub Group 1</label>
<label for="sub-group-1">Document list</label>
<ul>
<li><a href="#0">Image</a></li>
<li><a href="#0">Image</a></li>
@@ -129,7 +131,6 @@
<span data-type="tab"></span>
<span data-type="encoding"></span>
<span data-type="lang"></span>
<!--<span data-type="history"></span>-->
</div>
</div>
</div>
@@ -182,15 +183,15 @@
</script>
<script src="/static/js/jquery-ui.min.js"></script>
<script src="/static/js/jquery.contextify.min.js"></script>
<script src="/static/js/files.js?date={{g.version}}"></script>
<script src="/static/js/files.js?date22={{g.version}}"></script>
<script src="/static/js/upload.js?date={{g.version}}"></script>
<script type="text/javascript" src="./static/ace/ace.js?date=2"></script>
<script type="text/javascript" src="./static/ace/ext-language_tools.js?date=2"></script>
<script type="text/javascript">
setTimeout(function(){
GetDisk();
},500);
var xPath = getCookie('Path');
GetDisk();
},500);
var xPath = getCookie('Path');
setTimeout(function(){
GetFiles((xPath!=undefined?xPath:'/www/wwwroot'));
},800);
+1 -1
View File
@@ -22,7 +22,7 @@
<span style="margin-right:10px"><a class="btlink" href="javascript:index.re_server();">{{data['lan']['RESTART']}}</a></span>
</span>
</div>
<div class="container-fluid" style="padding-bottom: 66px;padding-left: 0px;">
<div class="container-fluid" style="padding-bottom: 66px;padding-left: 15px;">
<div class="danger-tips">
<div class="important-title" id="messageError" style="display: none; margin-top:15px"></div>
</div>
+2 -2
View File
@@ -8,7 +8,7 @@
<title>{{g.title}}</title>
<link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon" />
<link href="/static/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/css/site.css?f={{g['version']}}" rel="stylesheet">
<link href="/static/css/site.css?f2={{g['version']}}" rel="stylesheet">
<link href="/static/codemirror/lib/codemirror.css" rel="stylesheet">
<!--[if lte IE 9]>
<script src="/static/js/requestAnimationFrame.js"></script>
@@ -78,7 +78,7 @@
<script src="/static/build/addons/search/search.min.js"></script>
<script src="/static/build/addons/winptyCompat/winptyCompat.js"></script>
<script type="text/javascript" src="/static/js/clipboard.min.js"></script>
<script src="/static/js/public.js?v3={{g['version']}}"></script>
<script src="/static/js/public.js?v4={{g['version']}}"></script>
<script src="/static/js/public_backup.js?version={{g['version']}}"></script>
<script src="/static/js/bt_upload.js?version={{g['version']}}"></script>
{% block content %}{% endblock %}
+1 -1
View File
@@ -56,7 +56,7 @@
{% if not data['isSetup'] %}
layer.msg('test', { time: 0, icon: 2 });
layer.msg(lan.site.install_web_server_first+'<a href="/soft" style="color:#20a53a; float: right;">'+lan.site.to_install+'</a>', { icon: 7, shade: [0.3, '#000'], time: 0 });
$(".layui-layer-shade").css("margin-left", "200px");
$(".layui-layer-shade").css("margin-left", "180px");
{% else %}
site.get_list();
site.plugin_firewall();
+5 -4
View File
@@ -30,9 +30,9 @@
</div>
<div class="divtable pd15 relative">
<button class="btn btn-default btn-sm" onclick="soft.flush_cache()" title="{{data['lan']['UPDATE_FROM_CLOUD']}}" style="position:absolute;top:-49px;right:15px">{{data['lan']['UPDATE_APP_LIST']}}</button>
<!--<div id="updata_pro_info">-->
<!--<div class="alert alert-success" style="margin-bottom:15px"><strong>{{data['lan']['PS']}}</strong><button class="btn btn-success btn-xs va0 updata_pro" onclick="bt.soft.updata_pro()" title="{{data['lan']['UPDATE_PRO_NOW']}}" style="margin-left:8px">"{{data['lan']['UPDATE_NOW']}}"</button></div>-->
<!--</div>-->
<div id="updata_pro_info">
<div class="alert alert-success" style="margin-bottom:15px"><strong>{{data['lan']['PS']}}</strong><button class="btn btn-success btn-xs va0 updata_pro" onclick="bt.soft.updata_pro()" title="{{data['lan']['UPDATE_PRO_NOW']}}" style="margin-left:8px">"{{data['lan']['UPDATE_NOW']}}"</button></div>
</div>
<table id="softList" class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0"></table>
<div id='softPage' class="dataTables_paginate paging_bootstrap page">
@@ -49,8 +49,9 @@
<script type="text/javascript" src="/static/js/jquery.dragsort-0.5.2.min.js"></script>
<script type="text/javascript" src="/static/laydate/laydate.js?date=20180301"></script>
<script type="text/javascript" src="/static/js/soft.js?version={{g['version']}}"></script>
<script type="text/javascript" src="/static/js/soft.js?version1={{g['version']}}"></script>
<script type="text/javascript">
bt.set_cookie('sites_path', "{{session['config']['sites_path']}}");
bt.set_cookie('serverType', "{{session['webserver']}}");
$(document).ready(function () {
soft.get_list();
+329
View File
@@ -0,0 +1,329 @@
#coding: utf-8
#-------------------------------------------------------------------
# 宝塔Linux面板
#-------------------------------------------------------------------
# Copyright (c) 2015-2099 宝塔软件(http://bt.cn) All rights reserved.
#-------------------------------------------------------------------
# Author: 黄文良 <287962566@qq.com>
#-------------------------------------------------------------------
#-------------------------------------------------------------------
# ACME v2客户端
#-------------------------------------------------------------------
import os
import time
import copy
import json
import base64
import hashlib
import logging
import binascii
import platform
import sys
import requests
import OpenSSL
import cryptography
os.chdir('/www/server/panel')
sys.path.append('class/')
import public
class acme_v2:
_url = None
_apis = None
debug = True
def __init__(
self,
domain_name = "www.bt.cn",
dns_class = None,
domain_alt_names=None,
contact_email=None,
account_key=None,
certificate_key=None,
bits=2048,
digest="sha256",
ACME_REQUEST_TIMEOUT=7,
ACME_AUTH_STATUS_WAIT_PERIOD=8,
ACME_AUTH_STATUS_MAX_CHECKS=3
):
if self.debug:
self._url = 'https://acme-staging-v02.api.letsencrypt.org/directory'
else:
self._url = 'https://acme-v02.api.letsencrypt.org/directory'
self.domain_name = domain_name
self.dns_class = dns_class
if not domain_alt_names:
domain_alt_names = []
self.domain_alt_names = domain_alt_names
self.domain_alt_names = list(set(self.domain_alt_names))
self.contact_email = contact_email
self.bits = bits
self.digest = digest
self.ACME_REQUEST_TIMEOUT = ACME_REQUEST_TIMEOUT
self.ACME_AUTH_STATUS_WAIT_PERIOD = ACME_AUTH_STATUS_WAIT_PERIOD
self.ACME_AUTH_STATUS_MAX_CHECKS = ACME_AUTH_STATUS_MAX_CHECKS
self.ACME_DIRECTORY_URL = self._url
self.all_domain_names = copy.copy(self.domain_alt_names)
self.all_domain_names.insert(0, self.domain_name)
self.domain_alt_names = list(set(self.domain_alt_names))
self.User_Agent = self.get_user_agent()
acme_endpoints = self.get_apis()
self.ACME_GET_NONCE_URL = acme_endpoints["newNonce"]
self.ACME_TOS_URL = acme_endpoints["meta"]["termsOfService"]
self.ACME_CAA_ID = acme_endpoints["meta"]["caaIdentities"]
self.ACME_KEY_CHANGE_URL = acme_endpoints["keyChange"]
self.ACME_NEW_ACCOUNT_URL = acme_endpoints["newAccount"]
self.ACME_NEW_ORDER_URL = acme_endpoints["newOrder"]
self.ACME_REVOKE_CERT_URL = acme_endpoints["revokeCert"]
self.kid = None
self.certificate_key = certificate_key or self.create_certificate_key()
self.csr = self.create_csr()
if not account_key:
self.account_key = self.create_account_key()
self.PRIOR_REGISTERED = False
else:
self.account_key = account_key
self.PRIOR_REGISTERED = True
#获取API接口清单
def get_apis(self):
if self._apis: return self._apis
result = json.loads(self._http_get(self._url).read())
if result:
self._apis = result
return self._apis
return False
#创建CSR
def create_csr(self):
X509Req = OpenSSL.crypto.X509Req()
X509Req.get_subject().CN = self.domain_name
if self.domain_alt_names:
SAN = "DNS:{0}, ".format(self.domain_name).encode("utf8") + ", ".join(
"DNS:" + i for i in self.domain_alt_names
).encode("utf8")
else:
SAN = "DNS:{0}".format(self.domain_name).encode("utf8")
X509Req.add_extensions(
[
OpenSSL.crypto.X509Extension(
"subjectAltName".encode("utf8"), critical=False, value=SAN
)
]
)
pk = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM, self.certificate_key.encode()
)
X509Req.set_pubkey(pk)
X509Req.set_version(2)
X509Req.sign(pk, self.digest)
return OpenSSL.crypto.dump_certificate_request(OpenSSL.crypto.FILETYPE_ASN1, X509Req)
def get_user_agent(self):
return "BT-Panel/7.0"
def create_certificate_key(self):
return self.create_key().decode()
def create_account_key(self):
return self.create_key().decode()
#创建Key
def create_key(self, key_type=OpenSSL.crypto.TYPE_RSA):
key = OpenSSL.crypto.PKey()
key.generate_key(key_type, self.bits)
private_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key)
return private_key
#注册帐户
def register(self):
if self.PRIOR_REGISTERED:
payload = {"onlyReturnExisting": True}
elif self.contact_email:
payload = {
"termsOfServiceAgreed": True,
"contact": ["mailto:{0}".format(self.contact_email)],
}
else:
payload = {"termsOfServiceAgreed": True}
url = self.ACME_NEW_ACCOUNT_URL
print(url)
acme_register_response = self.make_signed_acme_request(url=url, payload=payload)
print(acme_register_response)
if acme_register_response.code not in [201, 200, 409]:
raise ValueError(
"Error while registering: status_code={status_code} response={response}".format(
status_code=acme_register_response.status_code,
response=self.log_response(acme_register_response),
)
)
kid = acme_register_response.info().getheaders("Location")
setattr(self, "kid", kid)
print(acme_register_response.read())
print(acme_register_response.info().headers)
return acme_register_response
def log_response(self,response):
try:
tmp = response.read()
log_body = json.loads(tmp)
except ValueError:
log_body = tmp[:30]
return log_body
def make_signed_acme_request(self, url, payload):
headers = {"User-Agent": self.User_Agent}
payload = self.stringfy_items(payload)
if payload in ["GET_Z_CHALLENGE", "DOWNLOAD_Z_CERTIFICATE"]:
response = self._http_get(url, headers)
else:
payload64 = self.calculate_safe_base64(json.dumps(payload))
protected = self.get_acme_header(url)
protected64 = self.calculate_safe_base64(json.dumps(protected))
signature = self.sign_message(message="{0}.{1}".format(protected64, payload64))
signature64 = self.calculate_safe_base64(signature) # str
data = {"protected": protected64, "payload": payload64, "signature": signature64}
headers.update({"Content-Type": "application/jose+json"})
response = self._http_post(url, data, headers)
return response
def sign_message(self, message):
pk = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, self.account_key.encode())
return OpenSSL.crypto.sign(pk, message.encode("utf8"), self.digest)
#构造请求头
def get_acme_header(self,url):
header = {"alg": "RS256", "nonce": self.get_nonce(), "url": url}
if url in [self.ACME_NEW_ACCOUNT_URL, self.ACME_REVOKE_CERT_URL, "GET_THUMBPRINT"]:
private_key = cryptography.hazmat.primitives.serialization.load_pem_private_key(
self.account_key.encode(),
password=None,
backend=cryptography.hazmat.backends.default_backend(),
)
public_key_public_numbers = private_key.public_key().public_numbers()
# private key public exponent in hex format
exponent = "{0:x}".format(public_key_public_numbers.e)
exponent = "0{0}".format(exponent) if len(exponent) % 2 else exponent
# private key modulus in hex format
modulus = "{0:x}".format(public_key_public_numbers.n)
jwk = {
"kty": "RSA",
"e": self.calculate_safe_base64(binascii.unhexlify(exponent)),
"n": self.calculate_safe_base64(binascii.unhexlify(modulus)),
}
header["jwk"] = jwk
else:
header["kid"] = self.kid
return header
def get_nonce(self):
headers = {"User-Agent": self.User_Agent}
response = self._http_get(self.ACME_GET_NONCE_URL, headers=headers)
tmp = response.info().getheaders("Replay-Nonce")
if not tmp: return ''
return tmp[0]
#将参数转换为Base64
def calculate_safe_base64(self,un_encoded_data):
if sys.version_info[0] == 3:
if isinstance(un_encoded_data, str):
un_encoded_data = un_encoded_data.encode("utf8")
r = base64.urlsafe_b64encode(un_encoded_data).rstrip(b"=")
return r.decode("utf8")
#参数转换
def stringfy_items(self,payload):
if isinstance(payload, str):
return payload
for k, v in payload.items():
if isinstance(k, bytes):
k = k.decode("utf-8")
if isinstance(v, bytes):
v = v.decode("utf-8")
payload[k] = v
return payload
#GET请求
def _http_get(self,url,headers = {},timeout = 30):
if sys.version_info[0] == 2:
try:
import urllib2,ssl
if sys.version_info[0] == 2:
reload(urllib2)
reload(ssl)
try:
ssl._create_default_https_context = ssl._create_unverified_context
except:pass;
req = urllib2.Request(url, headers = headers)
response = urllib2.urlopen(req,timeout = timeout,)
return response
except Exception as ex:
print(public.get_error_info())
return str(ex);
else:
try:
import urllib.request,ssl
try:
ssl._create_default_https_context = ssl._create_unverified_context
except:pass;
req = urllib.request.Request(url,headers = headers)
response = urllib.request.urlopen(req,timeout = timeout)
return response
except Exception as ex:
print(public.get_error_info())
return str(ex)
#POST请求
def _http_post(self,url,data,headers = {},timeout = 30):
data = json.dumps(data).encode('utf8')
if sys.version_info[0] == 2:
try:
import urllib,urllib2,ssl
try:
ssl._create_default_https_context = ssl._create_unverified_context
except:pass
req = urllib2.Request(url, data,headers = headers)
response = urllib2.urlopen(req,timeout=timeout)
return response
except Exception as ex:
print(public.get_error_info())
return str(ex);
else:
try:
import urllib.request,ssl
try:
ssl._create_default_https_context = ssl._create_unverified_context
except:pass;
req = urllib.request.Request(url, data,headers = headers)
response = urllib.request.urlopen(req,timeout = timeout)
return response
except Exception as ex:
print(public.get_error_info())
return str(ex);
if __name__ == "__main__":
p = acme_v2()
p.register()
+4 -2
View File
@@ -546,6 +546,8 @@ class ajax:
session['version'] = updateInfo['version']
if 'getCloudPlugin' in session: del(session['getCloudPlugin']);
if updateInfo['is_beta'] == 1: self.to_beta()
public.ExecShell("/etc/init.d/bt start")
public.writeFile('data/restart.pl','True')
return public.returnMsg(True,'PANEL_UPDATE',(updateInfo['version'],));
#输出新版本信息
@@ -645,7 +647,7 @@ class ajax:
public.ExecShell("mkdir -p " + sPath);
public.writeFile(sPath + '/phpinfo.php','<?php phpinfo(); ?>');
phpinfo = public.HttpGet('http://127.0.0.2/' + get.version + '/phpinfo.php');
os.system("rm -rf " + sPath);
public.ExecShell("rm -rf " + sPath);
return phpinfo;
#检测PHPINFO配置
@@ -1073,7 +1075,7 @@ ServerName 127.0.0.2
conf = re.sub('MAXCONN=\d+','MAXCONN='+get.maxconn,conf);
conf = re.sub('CACHESIZE=\d+','CACHESIZE='+get.cachesize,conf);
public.writeFile(confFile,conf);
os.system(confFile + ' reload');
public.ExecShell(confFile + ' reload');
return public.returnMsg(True,'SET_SUCCESS');
#取redis状态
+1 -1
View File
@@ -27,7 +27,7 @@ class panelSetup:
if ua:
ua = ua.lower();
if ua.find('spider') != -1 or ua.find('bot') != -1: return redirect('https://www.baidu.com');
g.version = '6.3.3'
g.version = '6.5.1'
g.title = public.GetConfigValue('title')
g.uri = request.path
session['version'] = g.version;
+16 -15
View File
@@ -11,7 +11,7 @@ import public,re,sys,os,nginx,apache,json,time
try:
import pyotp
except:
os.system("pip install pyotp &")
public.ExecShell("pip install pyotp &")
from BTPanel import session,admin_path_checks
from flask import request
@@ -72,8 +72,9 @@ class config:
if get.domain:
reg = "^([\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))
@@ -413,7 +414,7 @@ class config:
def Set502(self,get):
filename = 'data/502Task.pl';
if os.path.exists(filename):
os.system('rm -f ' + filename)
public.ExecShell('rm -f ' + filename)
else:
public.writeFile(filename,'True')
@@ -438,13 +439,13 @@ class config:
else:
sslConf = '/www/server/panel/data/ssl.pl';
if os.path.exists(sslConf):
# os.system('rm -f ' + sslConf);
# public.ExecShell('rm -f ' + sslConf);
os.remove(sslConf)
return public.returnMsg(True,'PANEL_SSL_CLOSE');
else:
os.system('pip install cffi');
os.system('pip install cryptography');
os.system('pip install pyOpenSSL');
public.ExecShell('pip install cffi');
public.ExecShell('pip install cryptography');
public.ExecShell('pip install pyOpenSSL');
try:
if not self.CreateSSL(): return public.returnMsg(False,'PANEL_SSL_ERR');
public.writeFile(sslConf,'True')
@@ -613,7 +614,7 @@ class config:
except: continue
public.writeFile(filename,phpini);
os.system('/etc/init.d/php-fpm-' + get.version + ' reload');
public.ExecShell('/etc/init.d/php-fpm-' + get.version + ' reload');
return public.returnMsg(True,'SET_SUCCESS');
@@ -711,7 +712,7 @@ class config:
else:
phpini = re.sub('\n;session.save_path = "/tmp"', '\n;session.save_path = "/tmp"' + val, phpini)
public.writeFile(filename, phpini)
os.system('/etc/init.d/php-fpm-' + get.version + ' reload')
public.ExecShell('/etc/init.d/php-fpm-' + get.version + ' reload')
return public.returnMsg(True, 'SET_SUCCESS')
# 获取Session文件数量
@@ -719,7 +720,7 @@ class config:
d=["/tmp","/www/php_session"]
count = 0
for i in d:
if not os.path.exists(i): os.system('mkdir -p %s'%i)
if not os.path.exists(i): public.ExecShell('mkdir -p %s'%i)
list = os.listdir(i)
for l in list:
if os.path.isdir(i+"/"+l):
@@ -742,9 +743,9 @@ class config:
# 删除老文件
def DelOldSession(self,get):
s = "find /tmp -mtime +1 |grep 'sess_'|xargs rm -f"
os.system(s)
public.ExecShell(s)
s = "find /www/php_session -mtime +1 |grep 'sess_'|xargs rm -f"
os.system(s)
public.ExecShell(s)
# s = "find /tmp -mtime +1 |grep 'sess_'|wc -l"
# old_file_conf = int(public.ExecShell(s)[0].split("\n")[0])
@@ -1013,7 +1014,7 @@ class config:
# 修改.user.ini文件
def _edit_user_ini(self,file,s_conf,act,session_path):
os.system("chattr -i {}".format(file))
public.ExecShell("chattr -i {}".format(file))
conf = public.readFile(file)
if act == "1":
if "session.save_path" in conf:
@@ -1026,7 +1027,7 @@ class config:
conf = re.sub(rep,"",conf)
conf = re.sub(rep1,"",conf)
public.writeFile(file, conf)
os.system("chattr +i {}".format(file))
public.ExecShell("chattr +i {}".format(file))
# 设置php_session存放到独立文件夹
def set_php_session_path(self,get):
@@ -1047,7 +1048,7 @@ class config:
if get.act == "1":
if not os.path.exists(user_ini_file):
public.writeFile(user_ini_file,conf)
os.system("chattr +i {}".format(user_ini_file))
public.ExecShell("chattr +i {}".format(user_ini_file))
return public.returnMsg(True,"Successful setup")
self._edit_user_ini(user_ini_file,conf,get.act,session_path)
return public.returnMsg(True, "Successful setup")
+2 -2
View File
@@ -419,8 +419,8 @@ echo "--------------------------------------------------------------------------
def StartTask(self,get):
echo = public.M('crontab').where('id=?',(get.id,)).getField('echo');
execstr = public.GetConfigValue('setup_path') + '/cron/' + echo;
os.system('chmod +x ' + execstr)
os.system('nohup ' + execstr + ' >> ' + execstr + '.log 2>&1 &');
public.ExecShell('chmod +x ' + execstr)
public.ExecShell('nohup ' + execstr + ' >> ' + execstr + '.log 2>&1 &');
return public.returnMsg(True,'CRONTAB_TASK_EXEC')
#获取计划任务文件位置
+30 -30
View File
@@ -101,8 +101,8 @@ class database(datatool.datatools):
if "1133" in mysqlMsg: return public.returnMsg(False,'DATABASE_ERR_NOT_EXISTS')
if "libmysqlclient" in mysqlMsg:
result = self.rep_lnk()
os.system("pip uninstall mysql-python -y")
os.system("pip install pymysql")
public.ExecShell("pip uninstall mysql-python -y")
public.ExecShell("pip install pymysql")
public.writeFile('data/restart.pl','True')
return public.returnMsg(False,"MYSQL_FIX_WITH_AUTO_ERR")
return None
@@ -314,7 +314,7 @@ SetLink
result = mysql_obj.query("show databases")
isError=self.IsSqlError(result)
if isError != None:
os.system("cd /www/server/panel && python tools.py root \"" + password + "\"")
public.ExecShell("cd /www/server/panel && python tools.py root \"" + password + "\"")
is_modify = False
if is_modify:
m_version = public.readFile(public.GetConfigValue('setup_path') + '/mysql/version.pl')
@@ -346,8 +346,7 @@ SetLink
name = public.M('databases').where('id=?',(id,)).getField('name');
rep = "^[\w@\.\?\-\_\>\<\~\!\#\$\%\^\&\*\(\)]+$"
if len(re.search(rep, newpassword).groups()) > 0: return public.returnMsg(False, 'DATABASE_NAME_ERR_T')
if not re.match(rep, newpassword): return public.returnMsg(False, 'DATABASE_NAME_ERR_T')
#修改MYSQL
mysql_obj = panelMysql.panelMysql()
m_version = public.readFile(public.GetConfigValue('setup_path') + '/mysql/version.pl')
@@ -388,15 +387,15 @@ SetLink
id = get['id']
name = public.M('databases').where("id=?",(id,)).getField('name')
root = public.M('config').where('id=?',(1,)).getField('mysql_root');
if not os.path.exists(session['config']['backup_path'] + '/database'): os.system('mkdir -p ' + session['config']['backup_path'] + '/database');
if not os.path.exists(session['config']['backup_path'] + '/database'): public.ExecShell('mkdir -p ' + session['config']['backup_path'] + '/database');
if not self.mypass(True, root):return public.returnMsg(False, 'Database configuration file failed to get checked, please check if MySQL configuration file exists')
fileName = name + '_' + time.strftime('%Y%m%d_%H%M%S',time.localtime()) + '.sql.gz'
backupName = session['config']['backup_path'] + '/database/' + fileName
public.ExecShell("/www/server/mysql/bin/mysqldump --default-character-set="+ public.get_database_character(name) +" --force --opt \"" + name + "\" | gzip > " + backupName)
if not os.path.exists(backupName): return public.returnMsg(False,'BACKUP_ERROR');
if not self.mypass(True, root): return public.returnMsg(False, 'Database configuration file failed to get checked, please check if MySQL configuration file exists')
self.mypass(False, root)
sql = public.M('backup')
addTime = time.strftime('%Y-%m-%d %X',time.localtime())
@@ -458,15 +457,15 @@ SetLink
isgzip = True
if not os.path.exists(backupPath + '/' + tmpFile) or tmpFile == '': return public.returnMsg(False, 'FILE_NOT_EXISTS',(tmpFile,))
if not self.mypass(True, root): return public.returnMsg(False, 'Database configuration file failed to get checked, please check if MySQL configuration file exists')
os.system(public.GetConfigValue('setup_path') + "/mysql/bin/mysql -uroot -p" + root + " --force \"" + name + "\" < " +'"'+ backupPath + '/' +tmpFile+'"')
public.ExecShell(public.GetConfigValue('setup_path') + "/mysql/bin/mysql -uroot -p" + root + " --force \"" + name + "\" < " +'"'+ backupPath + '/' +tmpFile+'"')
if not self.mypass(True, root): return public.returnMsg(False, 'Database configuration file failed to get checked, please check if MySQL configuration file exists')
if isgzip:
os.system('cd ' +backupPath+ ' && gzip ' + file.split('/')[-1][:-3]);
public.ExecShell('cd ' +backupPath+ ' && gzip ' + file.split('/')[-1][:-3]);
else:
os.system("rm -f " + backupPath + '/' +tmpFile)
public.ExecShell("rm -f " + backupPath + '/' +tmpFile)
else:
if not self.mypass(True, root): return public.returnMsg(False, 'Database configuration file failed to get checked, please check if MySQL configuration file exists')
os.system(public.GetConfigValue('setup_path') + "/mysql/bin/mysql -uroot -p" + root + " --force \"" + name + "\" < "+'"' + file+'"')
public.ExecShell(public.GetConfigValue('setup_path') + "/mysql/bin/mysql -uroot -p" + root + " --force \"" + name + "\" < "+'"' + file+'"')
if not self.mypass(True, root): return public.returnMsg(False, 'Database configuration file failed to get checked, please check if MySQL configuration file exists')
@@ -501,8 +500,8 @@ SetLink
#配置
def mypass(self,act,root):
os.system("sed -i '/user=root/d' /etc/my.cnf")
os.system("sed -i '/password=/d' /etc/my.cnf")
public.ExecShell("sed -i '/user=root/d' /etc/my.cnf")
public.ExecShell("sed -i '/password=/d' /etc/my.cnf")
if act:
mycnf = public.readFile('/etc/my.cnf');
rep = "\[mysqldump\]\nuser=root"
@@ -512,6 +511,7 @@ SetLink
mycnf = mycnf.replace(sea,subStr)
if len(mycnf) > 100: public.writeFile('/etc/my.cnf',mycnf);
return True
return True
#添加到服务器
def ToDataBase(self,find):
@@ -624,16 +624,16 @@ SetLink
#修改数据库目录
def SetDataDir(self,get):
if get.datadir[-1] == '/': get.datadir = get.datadir[0:-1];
if not os.path.exists(get.datadir): os.system('mkdir -p ' + get.datadir);
if not os.path.exists(get.datadir): public.ExecShell('mkdir -p ' + get.datadir);
mysqlInfo = self.GetMySQLInfo(get);
if mysqlInfo['datadir'] == get.datadir: return public.returnMsg(False,'DATABASE_MOVE_RE');
os.system('/etc/init.d/mysqld stop');
os.system('\cp -a -r ' + mysqlInfo['datadir'] + '/* ' + get.datadir + '/');
os.system('chown -R mysql.mysql ' + get.datadir);
os.system('chmod -R 755 ' + get.datadir);
os.system('rm -f ' + get.datadir + '/*.pid');
os.system('rm -f ' + get.datadir + '/*.err');
public.ExecShell('/etc/init.d/mysqld stop');
public.ExecShell('\cp -a -r ' + mysqlInfo['datadir'] + '/* ' + get.datadir + '/');
public.ExecShell('chown -R mysql.mysql ' + get.datadir);
public.ExecShell('chmod -R 755 ' + get.datadir);
public.ExecShell('rm -f ' + get.datadir + '/*.pid');
public.ExecShell('rm -f ' + get.datadir + '/*.err');
public.CheckMyCnf();
myfile = '/etc/my.cnf';
@@ -641,15 +641,15 @@ SetLink
public.writeFile('/etc/my_backup.cnf',mycnf);
mycnf = mycnf.replace(mysqlInfo['datadir'],get.datadir);
public.writeFile(myfile,mycnf);
os.system('/etc/init.d/mysqld start');
public.ExecShell('/etc/init.d/mysqld start');
result = public.ExecShell('ps aux|grep mysqld|grep -v grep');
if len(result[0]) > 10:
public.writeFile('data/datadir.pl',get.datadir);
return public.returnMsg(True,'DATABASE_MOVE_SUCCESS');
else:
os.system('pkill -9 mysqld');
public.ExecShell('pkill -9 mysqld');
public.writeFile(myfile,public.readFile('/etc/my_backup.cnf'));
os.system('/etc/init.d/mysqld start');
public.ExecShell('/etc/init.d/mysqld start');
return public.returnMsg(False,'DATABASE_MOVE_ERR');
#修改数据库端口
@@ -659,7 +659,7 @@ SetLink
rep = "port\s*=\s*([0-9]+)\s*\n"
mycnf = re.sub(rep,'port = ' + get.port + '\n',mycnf);
public.writeFile(myfile,mycnf);
os.system('/etc/init.d/mysqld restart');
public.ExecShell('/etc/init.d/mysqld restart');
return public.returnMsg(True,'EDIT_SUCCESS');
#获取错误日志
@@ -686,8 +686,8 @@ SetLink
if hasattr(get,'status'): return public.returnMsg(False,'0');
mycnf = mycnf.replace('#log-bin=mysql-bin','log-bin=mysql-bin')
mycnf = mycnf.replace('#binlog_format=mixed','binlog_format=mixed')
os.system('sync')
os.system('/etc/init.d/mysqld restart');
public.ExecShell('sync')
public.ExecShell('/etc/init.d/mysqld restart');
else:
path = self.GetMySQLInfo(get)['datadir'];
if not os.path.exists(path): return public.returnMsg(False,'数据库目录不存在!')
@@ -702,9 +702,9 @@ SetLink
return public.returnMsg(False, "Database directory does not exist")
mycnf = mycnf.replace('log-bin=mysql-bin','#log-bin=mysql-bin')
mycnf = mycnf.replace('binlog_format=mixed','#binlog_format=mixed')
os.system('sync')
os.system('/etc/init.d/mysqld restart');
os.system('rm -f ' + path + '/mysql-bin.*')
public.ExecShell('sync')
public.ExecShell('/etc/init.d/mysqld restart');
public.ExecShell('rm -f ' + path + '/mysql-bin.*')
public.writeFile(myfile,mycnf);
return public.returnMsg(True,'SUCCESS');
+1 -1
View File
@@ -22,7 +22,7 @@ class downloadFile:
try:
ssl._create_default_https_context = ssl._create_unverified_context
except:pass
socket.setdefaulttimeout(10)
socket.setdefaulttimeout(30)
self.pre = 0;
self.oldTime = time.time();
if sys.version_info[0] == 2:
+83 -97
View File
@@ -180,7 +180,7 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
try:
os.remove(new_name)
except:
os.system("rm -f %s" % new_name)
public.ExecShell("rm -f %s" % new_name)
os.renames(save_path, new_name)
if 'dir_mode' in args and 'file_mode' in args:
mode_tmp1 = args.dir_mode.split(',')
@@ -218,6 +218,7 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
if get.path == '': get.path = '/www';
if not os.path.exists(get.path):
return public.ReturnMsg(False,'DIR_NOT_EXISTS')
if get.path == '/www/Recycle_bin': return public.returnMsg(False,'This is the recycle bin directory, please press the [Recycle Bin] button in the upper right corner to open')
if not os.path.isdir(get.path):
get.path = os.path.dirname(get.path)
@@ -479,7 +480,7 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
#删除目录
def DeleteDir(self,get) :
if sys.version_info[0] == 2: get.path = get.path.encode('utf-8');
#if get.path.find('/www/wwwroot') == -1: return public.returnMsg(False,'此为演示服务器,禁止删除此目录!');
if get.path == '/www/Recycle_bin': return public.returnMsg(False,'You cannot directly operate the recycle bin directory, please press the [Recycle Bin] button in the upper right corner to open')
if not os.path.exists(get.path):
return public.returnMsg(False,'DIR_NOT_EXISTS')
@@ -490,8 +491,8 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
try:
#检查是否存在.user.ini
#if os.path.exists(get.path+'/.user.ini'):
# os.system("chattr -i '"+get.path+"/.user.ini'")
os.system("chattr -R -i " + get.path)
# public.ExecShell("chattr -i '"+get.path+"/.user.ini'")
public.ExecShell("chattr -R -i " + get.path)
if hasattr(get,'empty'):
if not self.delete_empty(get.path): return public.returnMsg(False,'DIR_ERR_NOT_EMPTY');
@@ -523,7 +524,7 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
#检查是否为.user.ini
if get.path.find('.user.ini') != -1:
os.system("chattr -i '"+get.path+"'")
public.ExecShell("chattr -i '"+get.path+"'")
try:
if os.path.exists('data/recycle_bin.pl'):
if self.Mv_Recycle_bin(get):
@@ -539,7 +540,7 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
#移动到回收站
def Mv_Recycle_bin(self,get):
rPath = '/www/Recycle_bin/'
if not os.path.exists(rPath): os.system('mkdir -p ' + rPath);
if not os.path.exists(rPath): public.ExecShell('mkdir -p ' + rPath);
rFile = rPath + get.path.replace('/','_bt_') + '_t_' + str(time.time());
try:
import shutil
@@ -571,7 +572,7 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
#获取回收站信息
def Get_Recycle_bin(self,get):
rPath = '/www/Recycle_bin/'
if not os.path.exists(rPath): os.system('mkdir -p ' + rPath);
if not os.path.exists(rPath): public.ExecShell('mkdir -p ' + rPath);
data = {};
data['dirs'] = [];
data['files'] = [];
@@ -619,25 +620,25 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
if not self.CheckDir(filename):
return public.returnMsg(False,'FILE_DANGER');
os.system('chattr -R -i ' + filename)
public.ExecShell('chattr -R -i ' + filename)
if os.path.isdir(filename):
import shutil
try:
shutil.rmtree(filename);
except:
os.system("rm -rf " + filename)
public.ExecShell("rm -rf " + filename)
else:
try:
os.remove(filename);
except:
os.system("rm -f " + filename)
public.ExecShell("rm -f " + filename)
public.WriteLog('TYPE_FILE','FILE_DEL_RECYCLE_BIN',(tfile,));
return public.returnMsg(True,'FILE_DEL_RECYCLE_BIN',(tfile,));
#清空回收站
def Close_Recycle_bin(self,get):
rPath = '/www/Recycle_bin/'
os.system('chattr -R -i ' + rPath)
public.ExecShell('chattr -R -i ' + rPath)
import database,shutil;
rlist = os.listdir(rPath)
i = 0;
@@ -653,12 +654,12 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
try:
shutil.rmtree(path);
except:
os.system('rm -rf ' + path);
public.ExecShell('rm -rf ' + path);
else:
try:
os.remove(path);
except:
os.system('rm -f ' + path);
public.ExecShell('rm -f ' + path);
public.writeSpeed(None,0,0);
public.WriteLog('TYPE_FILE','FILE_CLOSE_RECYCLE_BIN');
@@ -732,6 +733,7 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
get.sfile = get.sfile.encode('utf-8');
get.dfile = get.dfile.encode('utf-8');
if not self.CheckFileName(get.dfile): return public.returnMsg(False,'FILE_NAME_SPECIAL_CHARACTRES');
if get.sfile == '/www/Recycle_bin': return public.returnMsg(False,'You cannot directly operate the recycle bin directory, please press the [Recycle Bin] button in the upper right corner to open')
if not os.path.exists(get.sfile):
return public.returnMsg(False,'FILE_NOT_EXISTS')
@@ -828,12 +830,13 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
#保存文件
def SaveFileBody(self,get):
if not 'path' in get: return public.returnMsg(False,'path parameter cannot be empty!')
if not 'data' in get: return public.returnMsg(False,'data parameter cannot be empty!')
if sys.version_info[0] == 2: get.path = get.path.encode('utf-8');
if not os.path.exists(get.path):
if get.path.find('.htaccess') == -1:
return public.returnMsg(False,'FILE_NOT_EXISTS')
his_path = '/www/backup/file_history/'
if get.path.find(his_path) != -1: return public.returnMsg(False,'不能直接修改历史副本!')
try:
isConf = -1
if os.path.exists('/etc/init.d/nginx') or os.path.exists('/etc/init.d/httpd'):
@@ -841,7 +844,7 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
if isConf == -1: isConf = get.path.find('apache');
if isConf == -1: isConf = get.path.find('rewrite');
if isConf != -1:
os.system('\\cp -a '+get.path+' /tmp/backup.conf');
public.ExecShell('\\cp -a '+get.path+' /tmp/backup.conf');
data = get.data;
userini = False;
@@ -872,7 +875,7 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
if isConf != -1:
isError = public.checkWebConfig();
if isError != True:
os.system('\\cp -a /tmp/backup.conf '+get.path);
public.ExecShell('\\cp -a /tmp/backup.conf '+get.path);
return public.returnMsg(False,'ERROR:<br><font style="color:red;">'+isError.replace("\n",'<br>')+'</font>');
public.serviceReload();
@@ -886,7 +889,9 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
#保存历史副本
def save_history(self,filename):
try:
save_path = ('/www/backup/file_history/' + filename).replace('//','/')
his_path = '/www/backup/file_history/'
if filename.find(his_path) != -1: return
save_path = ( his_path + filename).replace('//','/')
if not os.path.exists(save_path): os.makedirs(save_path,384)
his_list = sorted(os.listdir(save_path),reverse=True)
@@ -969,19 +974,19 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
if not self.CheckDir(get.filename): return public.returnMsg(False,'FILE_DANGER');
if not os.path.exists(get.filename):
return public.returnMsg(False,'FILE_NOT_EXISTS')
os.system('chmod '+all+' '+get.access+" '"+get.filename+"'")
os.system('chown '+all+' '+get.user+':'+get.user+" '"+get.filename+"'")
public.ExecShell('chmod '+all+' '+get.access+" '"+get.filename+"'")
public.ExecShell('chown '+all+' '+get.user+':'+get.user+" '"+get.filename+"'")
public.WriteLog('TYPE_FILE','FILE_ACCESS_SUCCESS',(get.filename,get.access,get.user))
return public.returnMsg(True,'SET_SUCCESS')
except:
return public.returnMsg(False,'SET_ERROR')
def SetFileAccept(self,filename):
os.system('chown -R www:www ' + filename)
public.ExecShell('chown -R www:www ' + filename)
if os.path.isfile(filename):
os.system('chmod -R 644 ' + filename)
public.ExecShell('chmod -R 644 ' + filename)
else:
os.system('chmod -R 755 ' + filename)
public.ExecShell('chmod -R 755 ' + filename)
#取目录大小
def GetDirSize(self,get):
@@ -998,11 +1003,11 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
def CloseLogs(self,get):
get.path = public.GetConfigValue('root_path')
os.system('rm -f '+public.GetConfigValue('logs_path')+'/*')
public.ExecShell('rm -f '+public.GetConfigValue('logs_path')+'/*')
if public.get_webserver() == 'nginx':
os.system('kill -USR1 `cat '+public.GetConfigValue('setup_path')+'/nginx/logs/nginx.pid`');
public.ExecShell('kill -USR1 `cat '+public.GetConfigValue('setup_path')+'/nginx/logs/nginx.pid`');
else:
os.system('/etc/init.d/httpd reload');
public.ExecShell('/etc/init.d/httpd reload');
public.WriteLog('TYPE_FILE','SITE_LOG_CLOSE')
get.path = public.GetConfigValue('logs_path')
@@ -1023,8 +1028,8 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
ret = ' -R '
if 'all' in get:
if get.all == 'False': ret = ''
os.system('chmod '+ret+get.access+" '"+filename+"'")
os.system('chown '+ret+get.user+':'+get.user+" '"+filename+"'")
public.ExecShell('chmod '+ret+get.access+" '"+filename+"'")
public.ExecShell('chown '+ret+get.user+':'+get.user+" '"+filename+"'")
except:
continue;
public.WriteLog('TYPE_FILE','FILE_ALL_ACCESS')
@@ -1045,7 +1050,7 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
public.writeSpeed(key,i,l);
if os.path.isdir(filename):
if not self.CheckDir(filename): return public.returnMsg(False,'FILE_DANGER');
os.system("chattr -R -i " + filename)
public.ExecShell("chattr -R -i " + filename)
if isRecyle:
self.Mv_Recycle_bin(get)
else:
@@ -1053,7 +1058,7 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
else:
if key == '.user.ini':
if l > 1: continue
os.system('chattr -i ' + filename);
public.ExecShell('chattr -i ' + filename);
if isRecyle:
self.Mv_Recycle_bin(get)
@@ -1182,7 +1187,7 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
def InstallSoft(self,get):
import db,time
path = public.GetConfigValue('setup_path') + '/php'
if not os.path.exists(path): os.system("mkdir -p " + path);
if not os.path.exists(path): public.ExecShell("mkdir -p " + path);
if session['server_os']['x'] != 'RHEL': get.type = '3'
apacheVersion='false';
if public.get_webserver() == 'apache':
@@ -1209,10 +1214,10 @@ session.save_handler = files'''.format(path,sess_path,sess_path)
status = public.M('tasks').where('id=?',(get.id,)).getField('status');
public.M('tasks').delete(get.id);
if status == '-1':
os.system("kill `ps -ef |grep 'python panelSafe.pyc'|grep -v grep|grep -v panelExec|awk '{print $2}'`");
os.system("kill `ps -ef |grep 'install_soft.sh'|grep -v grep|grep -v panelExec|awk '{print $2}'`");
os.system("kill `ps aux | grep 'python task.pyc$'|awk '{print $2}'`");
os.system('''
public.ExecShell("kill `ps -ef |grep 'python panelSafe.pyc'|grep -v grep|grep -v panelExec|awk '{print $2}'`");
public.ExecShell("kill `ps -ef |grep 'install_soft.sh'|grep -v grep|grep -v panelExec|awk '{print $2}'`");
public.ExecShell("kill `ps aux | grep 'python task.pyc$'|awk '{print $2}'`");
public.ExecShell('''
pids=`ps aux | grep 'sh'|grep -v grep|grep install|awk '{print $2}'`
arr=($pids)
@@ -1222,12 +1227,12 @@ do
done
''');
os.system('rm -f ' + name.replace('扫描目录[','').replace(']','') + '/scan.pl');
public.ExecShell('rm -f ' + name.replace('扫描目录[','').replace(']','') + '/scan.pl');
isTask = '/tmp/panelTask.pl';
public.writeFile(isTask,'True');
os.system('/etc/init.d/bt start');
public.ExecShell('/etc/init.d/bt start');
except:
os.system('/etc/init.d/bt start');
public.ExecShell('/etc/init.d/bt start');
return public.returnMsg(True,'PLUGIN_DEL');
#重新激活任务
@@ -1243,7 +1248,7 @@ done
get.type = '0'
if session['server_os']['x'] != 'RHEL': get.type = '3'
execstr = "cd " + public.GetConfigValue('setup_path') + "/panel/install && /bin/bash install_soft.sh "+get.type+" uninstall " + get.name.lower() + " "+ get.version.replace('.','');
os.system(execstr);
public.ExecShell(execstr);
public.WriteLog('TYPE_SETUP','PLUGIN_UNINSTALL',(get.name,get.version));
return public.returnMsg(True,"PLUGIN_UNINSTALL");
@@ -1303,7 +1308,7 @@ cd %s
%s
''' % (get.path,get.shell)
public.writeFile('/tmp/panelShell.sh',shellStr);
os.system('nohup bash /tmp/panelShell.sh > /tmp/panelShell.pl 2>&1 &');
public.ExecShell('nohup bash /tmp/panelShell.sh > /tmp/panelShell.pl 2>&1 &');
return public.returnMsg(True,'FILE_SHELL_EXEC');
#取SHELL执行结果
@@ -1371,7 +1376,7 @@ cd %s
try:
import rarfile
except:
os.system("pip install rarfile")
public.ExecShell("pip install rarfile")
return True
import platform
@@ -1380,101 +1385,82 @@ cd %s
download_url = public.get_url() + '/src/rarlinux'+os_bit+'-5.6.1.tar.gz';
tmp_file = '/tmp/bt_rar.tar.gz'
os.system('wget -O ' + tmp_file + ' ' + download_url)
if os.path.exists(unrar_file): os.system("rm -rf /www/server/rar")
os.system("tar xvf " + tmp_file + ' -C /www/server/')
public.ExecShell('wget -O ' + tmp_file + ' ' + download_url)
if os.path.exists(unrar_file): public.ExecShell("rm -rf /www/server/rar")
public.ExecShell("tar xvf " + tmp_file + ' -C /www/server/')
if os.path.exists(tmp_file): os.remove(tmp_file)
if not os.path.exists(unrar_file): return False
if os.path.exists(bin_unrar): os.remove(bin_unrar)
if os.path.exists(bin_rar): os.remove(bin_rar)
os.system('ln -sf ' + unrar_file + ' ' + bin_unrar)
os.system('ln -sf ' + rar_file + ' ' + bin_rar)
os.system("pip install rarfile")
public.ExecShell('ln -sf ' + unrar_file + ' ' + bin_unrar)
public.ExecShell('ln -sf ' + rar_file + ' ' + bin_rar)
public.ExecShell("pip install rarfile")
#public.writeFile('data/restart.pl','True')
return True
def get_store_data(self):
data = {}
data = []
path = 'data/file_store.json'
try:
if os.path.exists(path):
data = json.loads(public.readFile(path))
except :
data = {}
if not data:
data['Default category'] = []
data = []
if type(data) == dict:
result = []
for key in data:
for path in data[key]:
result.append(path)
self.set_store_data(result)
return result
return data
def set_store_data(self,data):
public.writeFile('data/file_store.json',json.dumps(data))
return True
#添加收藏夹分类
def add_files_store_types(self,get):
file_type = get.file_type
if sys.version_info[0] == 2: file_type = file_type.decode('utf-8')
data = self.get_store_data()
if file_type in data: return public.returnMsg(False,'Do not add categories repeatedly!')
data[file_type] = []
self.set_store_data(data)
return public.returnMsg(True,'Add favorites to classify successfully!')
#删除收藏夹分类
def del_files_store_types(self,get):
file_type = get.file_type
if sys.version_info[0] == 2: file_type = file_type.decode('utf-8')
if file_type == 'Default category': return public.returnMsg(False,'Default category cannot be deleted!')
data = self.get_store_data()
if file_type in data:
del data[file_type]
self.set_store_data(data)
return public.returnMsg(True,'Delete [' + file_type + '] successfully!')
return public.returnMsg(False,'Delete [' + file_type + '] successfully!')
#获取收藏夹
def get_files_store(self,get):
data = self.get_store_data()
result = []
for key in data:
rlist = []
for path in data[key]:
info = { 'path': path,'name':os.path.basename(path)}
if os.path.isdir(path) :
info['type'] = 'dir'
else:
info['type'] = 'file'
rlist.append(info)
result.append({'name':key,'data':rlist})
for path in data:
if type(path) == dict:
path = path['path']
info = { 'path': path,'name':os.path.basename(path)}
if os.path.isdir(path) :
info['type'] = 'dir'
else:
info['type'] = 'file'
result.append(info)
return result
#添加收藏夹
def add_files_store(self,get):
file_type = get.file_type
if sys.version_info[0] == 2: file_type = file_type.decode('utf-8')
path = get.path
if not os.path.exists(path): return public.returnMsg(False,'File or directory does not exist!')
data = self.get_store_data()
if path in data[file_type]: return public.returnMsg(False,'Do not add it repeatedly!')
data[file_type].append(path)
if path in data: return public.returnMsg(False,'Do not add it repeatedly!')
data.append(path)
self.set_store_data(data)
return public.returnMsg(True,'Added successfully!')
#删除收藏夹
def del_files_store(self,get):
file_type = get.file_type
if sys.version_info[0] == 2: file_type = file_type.decode('utf-8')
path = get.path
data = self.get_store_data()
if not file_type in data: return public.returnMsg(False,'Cannot find this favorite category!')
data[file_type].remove(path)
if len(data[file_type]) <= 0: data[file_type] = []
if not path in data:
is_go = False
for info in data:
if type(info) == dict:
if info['path'] == path:
path = info
is_go = True
break
if not is_go:
return public.returnMsg(False,'This favorite object could not be found!')
data.remove(path)
if len(data) <= 0: data = []
self.set_store_data(data)
return public.returnMsg(True,'Successfully deleted!')
+2 -2
View File
@@ -320,14 +320,14 @@ class firewalld:
# 服务控制
def FirewalldService(self, type):
os.system('systemctl ' + type + ' firewalld.service')
public.ExecShell('systemctl ' + type + ' firewalld.service')
return public.returnMsg(True, 'SUCCESS')
# 保存配置
def Save(self):
self.format(self.__ROOT)
self.__TREE.write(self.__CONF_FILE, 'utf-8')
os.system('firewall-cmd --reload')
public.ExecShell('firewall-cmd --reload')
# 整理配置文件格式
def format(self, em, level=0):
+113
View File
@@ -0,0 +1,113 @@
# -*- coding: utf-8 -*-
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import NotFound
from werkzeug.http import parse_cookie
from flask import request
# Monkeys are made for freedom.
try:
from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker
from geventwebsocket.handler import WebSocketHandler
from gunicorn.workers.ggevent import PyWSGIHandler
import gevent
except ImportError:
pass
class SocketMiddleware(object):
def __init__(self, wsgi_app, app, socket):
self.ws = socket
self.app = app
self.wsgi_app = wsgi_app
def __call__(self, environ, start_response):
adapter = self.ws.url_map.bind_to_environ(environ)
try:
handler, values = adapter.match()
environment = environ['wsgi.websocket']
cookie = None
if 'HTTP_COOKIE' in environ:
cookie = parse_cookie(environ['HTTP_COOKIE'])
with self.app.app_context():
with self.app.request_context(environ):
# add cookie to the request to have correct session handling
request.cookie = cookie
handler(environment, **values)
return []
except (NotFound, KeyError):
return self.wsgi_app(environ, start_response)
class Sockets(object):
def __init__(self, app=None):
#: Compatibility with 'Flask' application.
#: The :class:`~werkzeug.routing.Map` for this instance. You can use
#: this to change the routing converters after the class was created
#: but before any routes are connected.
self.url_map = Map()
#: Compatibility with 'Flask' application.
#: All the attached blueprints in a dictionary by name. Blueprints
#: can be attached multiple times so this dictionary does not tell
#: you how often they got attached.
self.blueprints = {}
self._blueprint_order = []
if app:
self.init_app(app)
def init_app(self, app):
app.wsgi_app = SocketMiddleware(app.wsgi_app, app, self)
def route(self, rule, **options):
def decorator(f):
endpoint = options.pop('endpoint', None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
def add_url_rule(self, rule, _, f, **options):
self.url_map.add(Rule(rule, endpoint=f))
def register_blueprint(self, blueprint, **options):
"""
Registers a blueprint for web sockets like for 'Flask' application.
Decorator :meth:`~flask.app.setupmethod` is not applied, because it
requires ``debug`` and ``_got_first_request`` attributes to be defined.
"""
first_registration = False
if blueprint.name in self.blueprints:
assert self.blueprints[blueprint.name] is blueprint, (
'A blueprint\'s name collision occurred between %r and '
'%r. Both share the same name "%s". Blueprints that '
'are created on the fly need unique names.'
% (blueprint, self.blueprints[blueprint.name], blueprint.name))
else:
self.blueprints[blueprint.name] = blueprint
self._blueprint_order.append(blueprint)
first_registration = True
blueprint.register(self, options, first_registration)
# CLI sugar.
if ('Worker' in locals() and 'PyWSGIHandler' in locals() and
'gevent' in locals()):
class GunicornWebSocketHandler(PyWSGIHandler, WebSocketHandler):
def log_request(self):
if '101' not in self.status:
super(GunicornWebSocketHandler, self).log_request()
Worker.wsgi_handler = GunicornWebSocketHandler
worker = Worker
+1 -1
View File
@@ -30,7 +30,7 @@ class ftp:
get.path = get['path'].replace(' ','')
get.path = get.path.replace("\\", "/")
fileObj.CreateDir(get)
os.system('chown www.www ' + get.path)
public.ExecShell('chown www.www ' + get.path)
public.ExecShell(self.__runPath + '/pure-pw useradd ' + username + ' -u www -d ' + get.path + '<<EOF \n' + password + '\n' + password + '\nEOF')
self.FtpReload()
ps=get['ps']
+22 -3
View File
@@ -51,9 +51,9 @@ def control_init():
import shutil
shutil.copyfile(src_file,init_file)
if os.path.getsize(init_file) < 10:
os.system("chattr -i " + init_file)
os.system("\cp -arf %s %s" % (src_file,init_file))
os.system("chmod +x %s" % init_file)
public.ExecShell("chattr -i " + init_file)
public.ExecShell("\cp -arf %s %s" % (src_file,init_file))
public.ExecShell("chmod +x %s" % init_file)
except:pass
public.writeFile('/var/bt_setupPath.conf','/www')
public.ExecShell(c)
@@ -66,6 +66,25 @@ def control_init():
clean_max_log('/www/server/panel/plugin/rsync/lsyncd.log')
remove_tty1()
clean_hook_log()
run_new()
#尝试启动新架构
def run_new():
try:
new_file = '/www/server/panel/data/new.pl'
port_file = '/www/server/panel/data/port.pl'
if os.path.exists(new_file): return False
if not os.path.exists(port_file): return False
port = public.readFile(port_file)
if not port: return False
cmd_line = public.ExecShell('lsof -P -i:{}|grep LISTEN|grep -v grep'.format(int(port)))[0]
if len(cmd_line) < 20: return False
if cmd_line.find('BT-Panel') != -1: return False
public.writeFile('/www/server/panel/data/restart.pl','True')
public.writeFile(new_file,'True')
return True
except:
return False
#清理webhook日志
def clean_hook_log():
+4 -2
View File
@@ -32,12 +32,12 @@ import hmac
try:
import requests
except:
os.system('pip install requests')
public.ExecShell('pip install requests')
import requests
try:
import OpenSSL
except:
os.system('pip install pyopenssl')
public.ExecShell('pip install pyopenssl')
import OpenSSL
import random
import datetime
@@ -119,6 +119,8 @@ class AliyunDns(object):
"Type": "TXT",
"Value": domain_dns_value,
}
print(paramsdata)
Signature = self.sign(self.secret, paramsdata)
paramsdata['Signature'] = Signature
req = requests.get(url=self.url, params=paramsdata)
+1 -1
View File
@@ -20,7 +20,7 @@ if __name__ != '__main__':
try:
import dns.resolver
except:
os.system("pip install dnspython")
public.ExecShell("pip install dnspython")
try:
import dns.resolver
except:
+77 -23
View File
@@ -169,7 +169,7 @@ class panelPlugin:
download_url = public.get_url() + '/install/plugin/' + pluginInfo['name'] + '/install.sh';
toFile = '/tmp/%s.sh' % pluginInfo['name']
public.downloadFile(download_url,toFile);
os.system('/bin/bash ' + toFile + ' install > /tmp/panelShell.pl');
public.ExecShell('/bin/bash ' + toFile + ' install > /tmp/panelShell.pl');
if os.path.exists(pluginInfo['install_checks']):
public.WriteLog('TYPE_SETUP','PLUGIN_INSTALL_LIB',(pluginInfo['title'],));
if os.path.exists(toFile): os.remove(toFile)
@@ -195,7 +195,11 @@ class panelPlugin:
apacheVersion = public.readFile('/www/server/apache/version.pl');
public.writeFile('/var/bt_apacheVersion.pl',apacheVersion)
public.writeFile('/var/bt_setupPath.conf','/www')
if os.path.exists('/usr/bin/apt-get'): get.type = '3'
if os.path.exists('/usr/bin/apt-get'):
if get.type == '0':
get.type = '3'
else:
get.type = '4'
execstr = "cd /www/server/panel/install && /bin/bash install_soft.sh " + get.type + " "+mtype+" " + get.sName + " "+ get.version;
public.M('tasks').add('id,name,type,status,addtime,execstr',(None, mmsg + '['+get.sName+'-'+get.version+']','execshell','0',time.strftime('%Y-%m-%d %H:%M:%S'),execstr))
cache.delete('install_task')
@@ -215,12 +219,12 @@ class panelPlugin:
public.downloadFile(download_url,toFile)
if os.path.exists(toFile):
if os.path.getsize(toFile) > 100:
os.system('/bin/bash ' + toFile + ' uninstall')
public.ExecShell('/bin/bash ' + toFile + ' uninstall')
if os.path.exists(pluginPath + '/install.sh'):
os.system('/bin/bash ' + pluginPath + '/install.sh uninstall');
public.ExecShell('/bin/bash ' + pluginPath + '/install.sh uninstall');
if os.path.exists(pluginPath): os.system('rm -rf ' + pluginPath)
if os.path.exists(pluginPath): public.ExecShell('rm -rf ' + pluginPath)
public.WriteLog('TYPE_SETUP','PLUGIN_UNINSTALL_SOFT',(pluginInfo['title'],));
return public.returnMsg(True,'PLUGIN_UNINSTALL');
else:
@@ -234,7 +238,7 @@ class panelPlugin:
if get.sName.find('php-') != -1:
get.sName = get.sName.split('-')[0]
execstr = "cd /www/server/panel/install && /bin/bash install_soft.sh "+get.type+" uninstall " + get.sName.lower() + " "+ get.version.replace('.','');
os.system(execstr);
public.ExecShell(execstr);
public.WriteLog('TYPE_SETUP','PLUGIN_UNINSTALL',(get.sName,get.version));
return public.returnMsg(True,"PLUGIN_UNINSTALL");
@@ -286,6 +290,7 @@ class panelPlugin:
softList['list'] = self.get_types(softList['list'],sType)
if hasattr(get,'query'):
if get.query:
get.query = get.query.lower()
tmpList = []
for softInfo in softList['list']:
if softInfo['name'].lower().find(get.query) != -1 or \
@@ -295,6 +300,46 @@ class panelPlugin:
softList['list'] = tmpList
return softList
#提交用户评分
def set_score(self,args):
try:
import panelAuth
pdata = panelAuth.panelAuth().create_serverid(None)
pdata['ps'] = args.ps
pdata['num'] = int(args.num)
pdata['pid'] = int(args.pid)
if 1< pdata['num'] >5: return public.returnMsg(False,'Scoring range [1-5]')
if not pdata['pid']: return public.returnMsg(False,'The specified plugin does not exist!')
result = public.httpPost(public.GetConfigValue('home') + '/api/panel/plugin_score',pdata,10)
result = json.loads(result);
return result
except:
return public.returnMsg(False,'Connection failure!')
#获取指定插件评分
def get_score(self,args):
try:
import panelAuth
pdata = panelAuth.panelAuth().create_serverid(None)
pdata['pid'] = int(args.pid)
if not pdata['pid']: return []
u_args = ""
sp_tip = '?'
if 'p' in args:
u_args += sp_tip + 'p=' + args.p
sp_tip = '&'
if 'tojs' in args:
u_args += sp_tip + 'tojs='+ args.tojs
sp_tip = '&'
if 'limit_num' in args:
pdata['limit_num'] = int(args.limit_num)
result = public.httpPost(public.GetConfigValue('home') + '/api/panel/get_plugin_socre' + u_args,pdata,10)
result = json.loads(result);
return result
except:
return public.returnMsg(False,'Connection failure!')
#清除多余面板日志
def clean_panel_log(self):
try:
@@ -413,7 +458,7 @@ class panelPlugin:
#处理分类
def get_types(self,sList,sType):
if sType == 0: return sList
if sType <= 0: return sList
newList = []
for sInfo in sList:
if sInfo['type'] == sType: newList.append(sInfo)
@@ -447,8 +492,17 @@ class panelPlugin:
softList = self.get_cloud_list(get)
if not softList: return public.returnMsg(False,'GET_SOFTLIST_FAIL',"401")
softList['list'] = self.set_coexist(softList['list'])
softList['list'] = self.get_page(softList['list'],get)
softList['list']['data'] = self.check_isinstall(softList['list']['data'])
if not 'type' in get: get.type = '0'
if get.type == '-1':
soft_list_tmp = []
softList['list'] = self.check_isinstall(softList['list'])
for val in softList['list']:
if val['setup']: soft_list_tmp.append(val);
softList['list'] = soft_list_tmp;
softList['list'] = self.get_page(softList['list'],get)
else:
softList['list'] = self.get_page(softList['list'],get)
softList['list']['data'] = self.check_isinstall(softList['list']['data'])
softList['apache22'] = False
softList['apache24'] = False
check_version_path = '/www/server/apache/version_check.pl'
@@ -962,21 +1016,21 @@ class panelPlugin:
pluginInfo = json.loads(public.readFile(self.__install_path + '/' + get.name + '/info.json'));
if pluginInfo['tip'] == 'lib':
if not os.path.exists(self.__install_path + '/' + pluginInfo['name']): os.system('mkdir -p ' + self.__install_path + '/' + pluginInfo['name']);
if not os.path.exists(self.__install_path + '/' + pluginInfo['name']): public.ExecShell('mkdir -p ' + self.__install_path + '/' + pluginInfo['name']);
if not 'download_url' in session: session['download_url'] = 'http://download.bt.cn';
download_url = session['download_url'] + '/install/plugin/' + pluginInfo['name'] + '/install.sh';
toFile = self.__install_path + '/' + pluginInfo['name'] + '/install.sh';
public.downloadFile(download_url,toFile);
os.system('/bin/bash ' + toFile + ' install');
public.ExecShell('/bin/bash ' + toFile + ' install');
if self.checksSetup(pluginInfo['name'],pluginInfo['checks'],pluginInfo['versions'])[0]['status'] or os.path.exists(self.__install_path + '/' + get.name):
public.WriteLog('TYPE_SETUP','PLUGIN_INSTALL_LIB',(pluginInfo['title'],));
#os.system('rm -f ' + toFile);
#public.ExecShell('rm -f ' + toFile);
return public.returnMsg(True,'PLUGIN_INSTALL_SUCCESS');
return public.returnMsg(False,'PLUGIN_INSTALL_ERR');
else:
import db,time
path = '/www/server/php'
if not os.path.exists(path): os.system("mkdir -p " + path);
if not os.path.exists(path): public.ExecShell("mkdir -p " + path);
issue = public.readFile('/etc/issue')
if session['server_os']['x'] != 'RHEL': get.type = '3'
@@ -1013,16 +1067,16 @@ class panelPlugin:
pluginInfo = json.loads(public.readFile(self.__install_path + '/' + get.name + '/info.json'));
if pluginInfo['tip'] == 'lib':
if not os.path.exists(self.__install_path+ '/' + pluginInfo['name']): os.system('mkdir -p ' + self.__install_path + '/' + pluginInfo['name']);
if not os.path.exists(self.__install_path+ '/' + pluginInfo['name']): public.ExecShell('mkdir -p ' + self.__install_path + '/' + pluginInfo['name']);
download_url = session['download_url'] + '/install/plugin/' + pluginInfo['name'] + '/install.sh';
toFile = self.__install_path + '/' + pluginInfo['name'] + '/uninstall.sh';
public.downloadFile(download_url,toFile)
os.system('/bin/bash ' + toFile + ' uninstall')
os.system('rm -rf ' + session['download_url'] + '/install/plugin/' + pluginInfo['name'])
public.ExecShell('/bin/bash ' + toFile + ' uninstall')
public.ExecShell('rm -rf ' + session['download_url'] + '/install/plugin/' + pluginInfo['name'])
pluginPath = self.__install_path + '/' + pluginInfo['name']
if os.path.exists(pluginPath + '/install.sh'):
os.system('/bin/bash ' + pluginPath + '/install.sh uninstall');
public.ExecShell('/bin/bash ' + pluginPath + '/install.sh uninstall');
if os.path.exists(pluginPath):
public.ExecShell('rm -rf ' + pluginPath);
@@ -1035,7 +1089,7 @@ class panelPlugin:
if session['server_os']['x'] != 'RHEL': get.type = '3'
public.writeFile('/var/bt_setupPath.conf',public.GetConfigValue('root_path'))
execstr = "cd /www/server/panel/install && /bin/bash install_soft.sh "+get.type+" uninstall " + get.name.lower() + " "+ get.version.replace('.','');
os.system(execstr);
public.ExecShell(execstr);
public.WriteLog('TYPE_SETUP','PLUGIN_UNINSTALL',(get.name,get.version));
return public.returnMsg(True,"PLUGIN_UNINSTALL");
@@ -1170,7 +1224,7 @@ class panelPlugin:
public.ExecShell("echo `"+path+"/bin/php 2>/dev/null -v|grep cli|awk '{print $2}'` > " + path + '/version.pl')
try:
v1 = public.readFile(path+'/version.pl').strip();
if not v1: os.system('rm -f ' + path + '/version.pl');
if not v1: public.ExecShell('rm -f ' + path + '/version.pl');
except:
v1 = "";
if os.path.exists(tm.replace('VERSION',v2)): status = True;
@@ -1288,7 +1342,7 @@ class panelPlugin:
if os.path.exists(pidf):
pid = public.readFile(pidf)
versions[i]['run'] = self.checkProcess(pid)
if not versions[i]['run']: os.system('rm -f ' + pidf)
if not versions[i]['run']: public.ExecShell('rm -f ' + pidf)
elif name == 'phpmyadmin':
for i in range(len(versions)):
if versions[i]['status']: versions[i] = self.getPHPMyAdminStatus();
@@ -1298,14 +1352,14 @@ class panelPlugin:
if os.path.exists(pidf):
pid = public.readFile(pidf)
versions[i]['run'] = self.checkProcess(pid)
if not versions[i]['run']: os.system('rm -f ' + pidf)
if not versions[i]['run']: public.ExecShell('rm -f ' + pidf)
elif name == 'memcached':
for i in range(len(versions)):
pidf = '/var/run/memcached.pid'
if os.path.exists(pidf):
pid = public.readFile(pidf)
versions[i]['run'] = self.checkProcess(pid)
if not versions[i]['run']: os.system('rm -f ' + pidf)
if not versions[i]['run']: public.ExecShell('rm -f ' + pidf)
else:
for i in range(len(versions)):
if versions[i]['status']: versions[i]['run'] = True;
@@ -1480,7 +1534,7 @@ class panelPlugin:
path = '/www/server/php';
if get.status == '0':
versions = self.GetFind(get.name)['versions']
os.system('rm -f ' + path + '/' + get.version.replace('.','') + '/display.pl');
public.ExecShell('rm -f ' + path + '/' + get.version.replace('.','') + '/display.pl');
for version in versions.split(','):
if os.path.exists(path + '/' + version.replace('.','') + '/display.pl'):
isRemove = False;
+4 -4
View File
@@ -319,7 +319,7 @@ class panelRedirect:
redirectdir = "%s/panel/vhost/%s/redirect/%s" % (self.setupPath,w,get.sitename)
if not os.path.exists(redirectdir):
os.system("mkdir -p %s" % redirectdir)
public.ExecShell("mkdir -p %s" % redirectdir)
if w == "nginx":
public.writeFile(redirectfile,nginxrconf)
else:
@@ -372,8 +372,8 @@ class panelRedirect:
for i in range(len(redirectconf)):
if redirectconf[i]["sitename"] == sitename and redirectconf[i]["redirectname"] == redirectname:
proxyname_md5 = self.__calc_md5(redirectconf[i]["redirectname"])
os.system("rm -f %s/panel/vhost/nginx/redirect/%s/%s_%s.conf" % (self.setupPath,redirectconf[i]["sitename"],proxyname_md5,redirectconf[i]["sitename"]))
os.system("rm -f %s/panel/vhost/apache/redirect/%s/%s_%s.conf" % (self.setupPath,redirectconf[i]["sitename"],proxyname_md5, redirectconf[i]["sitename"]))
public.ExecShell("rm -f %s/panel/vhost/nginx/redirect/%s/%s_%s.conf" % (self.setupPath,redirectconf[i]["sitename"],proxyname_md5,redirectconf[i]["sitename"]))
public.ExecShell("rm -f %s/panel/vhost/apache/redirect/%s/%s_%s.conf" % (self.setupPath,redirectconf[i]["sitename"],proxyname_md5, redirectconf[i]["sitename"]))
del redirectconf[i]
self.__write_config(self.__redirectfile,redirectconf)
self.SetRedirectNginx(get)
@@ -414,7 +414,7 @@ class panelRedirect:
# 备份并替换老虚拟主机配置文件
# if not os.path.exists(conf_path + "_bak"):
# os.system("cp %s %s_bak" % (conf_path, conf_path))
# public.ExecShell("cp %s %s_bak" % (conf_path, conf_path))
# conf = re.sub(rep, "", old_conf)
# public.writeFile(conf_path, conf)
#self.CreateRedirect(get)
+6 -6
View File
@@ -66,7 +66,7 @@ class panelSSL:
#删除Token
def DelToken(self,get):
os.system("rm -f " + self.__UPATH);
public.ExecShell("rm -f " + self.__UPATH);
session['focre_cloud'] = True
return public.returnMsg(True,"SSL_BTUSER_UN");
@@ -172,7 +172,7 @@ class panelSSL:
try:
epass = public.GetRandomString(32);
spath = get.path + '/.well-known/pki-validation';
if not os.path.exists(spath): os.system("mkdir -p '" + spath + "'");
if not os.path.exists(spath): public.ExecShell("mkdir -p '" + spath + "'");
public.writeFile(spath + '/fileauth.txt',epass);
result = public.httpGet('http://' + get.domain + '/.well-known/pki-validation/fileauth.txt');
if result == epass: return True
@@ -197,7 +197,7 @@ class panelSSL:
sslInfo['data'] = self.En_Code(sslInfo['data']);
try:
spath = get.path + '/.well-known/pki-validation';
if not os.path.exists(spath): os.system("mkdir -p '" + spath + "'");
if not os.path.exists(spath): public.ExecShell("mkdir -p '" + spath + "'");
public.writeFile(spath + '/fileauth.txt',sslInfo['data']['authValue']);
except:
return public.returnMsg(False,'SSL_CHECK_WRITE_ERR');
@@ -305,7 +305,7 @@ class panelSSL:
def GetCertList(self,get):
try:
vpath = '/www/server/panel/vhost/ssl'
if not os.path.exists(vpath): os.system("mkdir -p " + vpath);
if not os.path.exists(vpath): public.ExecShell("mkdir -p " + vpath);
data = []
for d in os.listdir(vpath):
mpath = vpath + '/' + d + '/info.json';
@@ -323,7 +323,7 @@ class panelSSL:
try:
vpath = '/www/server/panel/vhost/ssl/' + get.certName.replace("*.",'')
if not os.path.exists(vpath): return public.returnMsg(False,'CRET_NOT_EXIST');
os.system("rm -rf " + vpath)
public.ExecShell("rm -rf " + vpath)
return public.returnMsg(True,'CRET_DEL')
except:
return public.returnMsg(False,'CRET_DEL_FAIL')
@@ -336,7 +336,7 @@ class panelSSL:
vpath = '/www/server/panel/vhost/ssl/' + certInfo['subject'];
vpath=vpath.replace("*.",'')
if not os.path.exists(vpath):
os.system("mkdir -p " + vpath);
public.ExecShell("mkdir -p " + vpath);
public.writeFile(vpath + '/privkey.pem',public.readFile(get.keyPath));
public.writeFile(vpath + '/fullchain.pem',public.readFile(get.certPath));
public.writeFile(vpath + '/info.json',json.dumps(certInfo));
+107 -73
View File
@@ -35,13 +35,14 @@ class panelSite(panelRedirect):
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_en.html &');
public.ExecShell('mkdir -p ' + path);
public.ExecShell('wget -O ' + path + '/index.html '+public.get_url()+'/stop.html &');
self.__proxyfile = '/www/server/panel/data/proxyfile.json'
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):
@@ -790,7 +791,7 @@ class panelSite(panelRedirect):
try:
epass = public.GetRandomString(32);
spath = get.path + '/.well-known/pki-validation';
if not os.path.exists(spath): os.system("mkdir -p '" + spath + "'");
if not os.path.exists(spath): public.ExecShell("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
@@ -918,11 +919,13 @@ class panelSite(panelRedirect):
self.check_ssl_pack()
try:
import panelLets
public.mod_reload(panelLets)
except Exception as ex:
if str(ex).find('No module named requests') != -1:
os.system("pip install requests &")
public.ExecShell("pip install requests &")
return public.returnMsg(False,'Missing requests component, please try to repair the panel!')
public.mod_reload(panelLets)
return public.returnMsg(False,str(ex))
lets = panelLets.panelLets()
result = lets.apple_lest_cert(get)
if result['status'] and not 'code' in result:
@@ -940,11 +943,11 @@ class panelSite(panelRedirect):
try:
import requests
except:
os.system('pip install requests')
public.ExecShell('pip install requests')
try:
import OpenSSL
except:
os.system('pip install pyopenssl')
public.ExecShell('pip install pyopenssl')
#判断DNS-API是否设置
@@ -1076,7 +1079,7 @@ class panelSite(panelRedirect):
sslStr = """#error_page 404/404.html;
ssl_certificate /www/server/panel/vhost/cert/%s/fullchain.pem;
ssl_certificate_key /www/server/panel/vhost/cert/%s/privkey.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2%s;
ssl_protocols TLSv1.1 TLSv1.2%s;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
@@ -1154,7 +1157,7 @@ class panelSite(panelRedirect):
SSLCertificateFile /www/server/panel/vhost/cert/%s/fullchain.pem
SSLCertificateKeyFile /www/server/panel/vhost/cert/%s/privkey.pem
SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
SSLProtocol All -SSLv2 -SSLv3
SSLProtocol All -SSLv2 -SSLv3 -TLSv1
SSLHonorCipherOrder On
%s
@@ -1332,7 +1335,7 @@ class panelSite(panelRedirect):
partnerOrderId = '/www/server/panel/vhost/cert/' + siteName + '/partnerOrderId';
if os.path.exists(partnerOrderId): public.ExecShell('rm -f ' + partnerOrderId);
p_file = '/etc/letsencrypt/live/' + siteName + '/partnerOrderId'
if os.path.exists(p_file): os.system('rm -f ' + p_file);
if os.path.exists(p_file): public.ExecShell('rm -f ' + p_file);
public.WriteLog('TYPE_SITE', 'SITE_SSL_CLOSE_SUCCESS', (siteName,));
public.serviceReload();
@@ -1353,6 +1356,7 @@ class panelSite(panelRedirect):
csr = public.readFile(csrpath);
file = self.setupPath + '/panel/vhost/' + public.get_webserver() + '/' + siteName + '.conf';
conf = public.readFile(file);
if not conf: return public.returnMsg(False,'The specified website profile does not exist!')
keyText = 'SSLCertificateFile'
if public.get_webserver() == 'nginx': keyText = 'ssl_certificate';
status = True
@@ -1662,9 +1666,9 @@ class panelSite(panelRedirect):
data['dirs'] = []
data['binding'] = []
return data;
os.system('mkdir -p ' + path);
os.system('chmod 755 ' + path);
os.system('chown www:www ' + path);
public.ExecShell('mkdir -p ' + path);
public.ExecShell('chmod 755 ' + path);
public.ExecShell('chown www:www ' + path);
get.path = path
self.SetDirUserINI(get)
siteName = public.M('sites').where('id=?',(get.id,)).getField('name')
@@ -1851,7 +1855,7 @@ server
public.M('binding').where("id=?",(id,)).delete();
filename = self.setupPath + '/panel/vhost/rewrite/' + siteName + '_' + binding['path'] + '.conf';
if os.path.exists(filename): os.system('rm -rf %s'%filename)
if os.path.exists(filename): public.ExecShell('rm -rf %s'%filename)
public.serviceReload();
public.WriteLog('TYPE_SITE', 'SITE_BINDING_DEL_SUCCESS',(siteName,binding['path']));
return public.returnMsg(True,'DEL_SUCCESS')
@@ -2184,7 +2188,7 @@ server
#proxyname_md5 = self.__calc_md5(get.proxyname)
# 备份并替换老虚拟主机配置文件
os.system("cp %s %s_bak" % (conf_path, conf_path))
public.ExecShell("cp %s %s_bak" % (conf_path, conf_path))
conf = re.sub(rep, "", old_conf)
public.writeFile(conf_path, conf)
if n == 0:
@@ -2214,8 +2218,8 @@ server
for i in range(len(proxyUrl)):
if proxyUrl[i]["sitename"] == sitename and proxyUrl[i]["proxyname"] == proxyname:
proxyname_md5 = self.__calc_md5(proxyUrl[i]["proxyname"])
os.system("rm -f %s/panel/vhost/nginx/proxy/%s/%s_%s.conf" % (self.setupPath,proxyUrl[i]["sitename"],proxyname_md5,proxyUrl[i]["sitename"]))
os.system("rm -f %s/panel/vhost/apache/proxy/%s/%s_%s.conf" % (self.setupPath,proxyUrl[i]["sitename"],proxyname_md5, proxyUrl[i]["sitename"]))
public.ExecShell("rm -f %s/panel/vhost/nginx/proxy/%s/%s_%s.conf" % (self.setupPath,proxyUrl[i]["sitename"],proxyname_md5,proxyUrl[i]["sitename"]))
public.ExecShell("rm -f %s/panel/vhost/apache/proxy/%s/%s_%s.conf" % (self.setupPath,proxyUrl[i]["sitename"],proxyname_md5, proxyUrl[i]["sitename"]))
del proxyUrl[i]
self.__write_config(self.__proxyfile,proxyUrl)
self.SetNginx(get)
@@ -2307,7 +2311,7 @@ server
return public.returnMsg(False, "INPUT_NUM")
rep = "http(s)?\:\/\/"
repd = "http(s)?\:\/\/([a-zA-Z0-9][-a-zA-Z0-9]{0,62}\.)+([a-zA-Z0-9][a-zA-Z0-9]{0,62})+.?"
#repd = "http(s)?\:\/\/([a-zA-Z0-9][-a-zA-Z0-9]{0,62}\.)+([a-zA-Z0-9][a-zA-Z0-9]{0,62})+.?"
tod = "[a-zA-Z]+$"
repte = "[\?\=\[\]\)\(\*\&\^\%\$\#\@\!\~\`{\}\>\<\,\',\"]+"
# 检测代理目录格式
@@ -2385,7 +2389,7 @@ server
rep = "location.+\(gif[\w\|\$\(\)\n\{\}\s\;\/\~\.\*\\\\\?]+access_log\s+/"
ng_conf = re.sub(rep, 'access_log /', ng_conf)
ng_conf = ng_conf.replace("include enable-php-","%s\n" % public.GetMsg("CLEAR_CACHE") +cureCache +"\n\t%s\n\t" % public.GetMsg("NGINX_PROXY_REP") + "include " + ng_proxyfile + ";\n\n\tinclude enable-php-")
#public.writeFile(ng_file,ng_conf)
public.writeFile(ng_file,ng_conf)
else:
rep = "%s[\w\s\~\/\(\)\.\*\{\}\;\$\n\#]+.{66,66}\n+[\s\w\/\*\.\;]+include enable-php-" % public.GetMsg("CLEAR_CACHE")
@@ -2403,7 +2407,7 @@ server
access_log /dev/null;
}'''
ng_conf = ng_conf.replace('access_log', oldconf + "\n\taccess_log")
public.writeFile(ng_file, ng_conf)
public.writeFile(ng_file, ng_conf)
# 设置apache配置
def SetApache(self,sitename):
@@ -2478,8 +2482,9 @@ server
self.__write_config(self.__proxyfile, proxyUrl)
self.SetNginx(get)
self.SetApache(get.sitename)
self.SetProxy(get)
# return public.returnMsg(False, '配置冲突')
status = self.SetProxy(get)
if not status["status"]:
return status
get.version = '00'
get.siteName = get.sitename
self.SetPHPVersion(get)
@@ -2526,27 +2531,30 @@ server
for i in range(len(proxyUrl)):
if proxyUrl[i]["proxyname"] == get.proxyname and proxyUrl[i]["sitename"] == get.sitename:
if int(get.type) != 1:
os.system("mv %s %s_bak" % (ap_conf_file, ap_conf_file))
os.system("mv %s %s_bak" % (ng_conf_file, ng_conf_file))
public.ExecShell("mv %s %s_bak" % (ap_conf_file, ap_conf_file))
public.ExecShell("mv %s %s_bak" % (ng_conf_file, ng_conf_file))
proxyUrl[i]["type"] = int(get.type)
self.__write_config(self.__proxyfile, proxyUrl)
public.serviceReload()
return public.returnMsg(True, 'Successfully modified')
else:
if os.path.exists(ap_conf_file+"_bak"):
os.system("mv %s_bak %s" % (ap_conf_file, ap_conf_file))
os.system("mv %s_bak %s" % (ng_conf_file, ng_conf_file))
public.ExecShell("mv %s_bak %s" % (ap_conf_file, ap_conf_file))
public.ExecShell("mv %s_bak %s" % (ng_conf_file, ng_conf_file))
ng_conf = public.readFile(ng_conf_file)
# 修改nginx配置
ng_conf = re.sub("location\s+%s" % proxyUrl[i]["proxydir"],"location "+get.proxydir,ng_conf)
ng_conf = re.sub("proxy_pass\s+%s" % proxyUrl[i]["proxysite"],"proxy_pass "+get.proxysite,ng_conf)
ng_conf = re.sub("\sHost\s+%s" % proxyUrl[i]["todomain"]," Host "+get.todomain,ng_conf)
cache_rep = "proxy_cache_valid\s+200\s+304\s+301\s+302\s+"
cache_rep = "proxy_cache_valid\s+200\s+304\s+301\s+302\s+\d+m;((\n|.)+expires\s+\d+m;)*"
if int(get.cache) == 1:
if re.search(cache_rep,ng_conf):
ng_conf = re.sub(cache_rep+"%sm;" % proxyUrl[i]["cachetime"], "proxy_cache_valid 200 304 301 302 %sm;" % get.cachetime, ng_conf)
expires_rep = "\{\n\s+expires\s+12h;"
ng_conf = re.sub(expires_rep, "{",ng_conf)
ng_conf = re.sub(cache_rep, "proxy_cache_valid 200 304 301 302 {0}m;".format(get.cachetime), ng_conf)
else:
ng_cache = """
proxy_ignore_headers Set-Cookie Cache-Control expires;
proxy_cache cache_one;
proxy_cache_key $host$uri$is_args$args;
proxy_cache_valid 200 304 301 302 %sm;""" % (get.cachetime)
@@ -2554,16 +2562,17 @@ server
cache_rep = '\n\s*#Set\s*Nginx\s*Cache(.|\n)*no-cache;'
ng_conf = re.sub(cache_rep,'\n\t#Set Nginx Cache\n'+ng_cache,ng_conf)
else:
cache_rep = '#proxy_set_header\s+Connection\s+"upgrade";'
ng_conf = re.sub(cache_rep, '\n\t#proxy_set_header Connection "upgrade";\n\t#Set Nginx Cache' + ng_cache,
# cache_rep = '#proxy_set_header\s+Connection\s+"upgrade";'
cache_rep = 'proxy_set_header\s+REMOTE-HOST\s+\$remote_addr;'
ng_conf = re.sub(cache_rep, '\n\tproxy_set_header\s+REMOTE-HOST\s+\$remote_addr;\n\t#Set Nginx Cache' + ng_cache,
ng_conf)
else:
if self.check_annotate(ng_conf):
rep = '\n\s*#Set\s*Nginx\s*Cache(.|\n)*1m;'
ng_conf = re.sub(rep, "\n\t#Set Nginx Cache\n\tadd_header Cache-Control no-cache;", ng_conf)
rep = '\n\s*#Set\s*Nginx\s*Cache(.|\n)*\d+m;'
ng_conf = re.sub(rep, "\n\t#Set Nginx Cache\n\tproxy_ignore_headers Set-Cookie Cache-Control expires;\n\tadd_header Cache-Control no-cache;", ng_conf)
else:
rep = '\s+proxy_cache\s+cache_one.*[\n\s\w\_\";\$]+m;'
ng_conf = re.sub(rep, '\n\t#Set Nginx Cache\n\tadd_header Cache-Control no-cache;', ng_conf)
ng_conf = re.sub(rep, '\n\t#Set Nginx Cache\n\tproxy_ignore_headers Set-Cookie Cache-Control expires;\n\tadd_header Cache-Control no-cache;', ng_conf)
sub_rep = "sub_filter"
subfilter = json.loads(get.subfilter)
@@ -2637,20 +2646,24 @@ server
# 构造缓存配置
ng_cache = """
proxy_ignore_headers Set-Cookie Cache-Control expires;
proxy_cache cache_one;
proxy_cache_key $host$uri$is_args$args;
proxy_cache_valid 200 304 301 302 %sm;""" % (cachetime)
rep = "(https?://[\w\.]+)"
# rep = "(https?://[\w\.]+)"
# proxysite1 = re.search(rep,get.proxysite).group(1)
ng_proxy = '''
#PROXY-START%s
location ~* \.(php|jsp|cgi|asp|aspx)$
{
proxy_pass %s;
proxy_set_header Host %s;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header REMOTE-HOST $remote_addr;
}
location %s
{
expires 12h;
if ($request_uri ~* "(php|jsp|cgi|asp|aspx)")
{
expires 0;
}
proxy_pass %s;
proxy_set_header Host %s;
proxy_set_header X-Real-IP $remote_addr;
@@ -2658,17 +2671,13 @@ location %s
proxy_set_header REMOTE-HOST $remote_addr;
%s
#proxy_connect_timeout 30s;
#proxy_read_timeout 86400s;
#proxy_send_timeout 30s;
#proxy_http_version 1.1;
#proxy_set_header Upgrade $http_upgrade;
#proxy_set_header Connection "upgrade";
add_header X-Cache $upstream_cache_status;
#Set Nginx Cache
%s
%s
expires 12h;
}
#PROXY-END%s'''
@@ -2677,7 +2686,7 @@ location %s
ng_proxyfile = "%s/panel/vhost/nginx/proxy/%s/%s_%s.conf" % (self.setupPath,sitename,proxyname_md5, sitename)
ng_proxydir = "%s/panel/vhost/nginx/proxy/%s" % (self.setupPath, sitename)
if not os.path.exists(ng_proxydir):
os.system("mkdir -p %s" % ng_proxydir)
public.ExecShell("mkdir -p %s" % ng_proxydir)
# 构造替换字符串
@@ -2697,17 +2706,17 @@ location %s
if advanced == 1:
if type == 1 and cache == 1:
ng_proxy_cache += ng_proxy % (
get.proxydir, get.proxydir,get.proxysite, get.todomain, public.GetMsg("NGINX_PERSISTENCE") ,ng_sub_filter, ng_cache ,get.proxydir)
get.proxydir, get.proxysite ,get.todomain,get.proxydir,get.proxysite,get.todomain, public.GetMsg("NGINX_PERSISTENCE") ,ng_sub_filter, ng_cache ,get.proxydir)
if type == 1 and cache == 0:
ng_proxy_cache += ng_proxy % (
get.proxydir, get.proxydir, get.proxysite, get.todomain, public.GetMsg("NGINX_PERSISTENCE") ,ng_sub_filter,'\tadd_header Cache-Control no-cache;' ,get.proxydir)
get.proxydir,get.proxysite ,get.todomain, get.proxydir,get.proxysite,get.todomain, public.GetMsg("NGINX_PERSISTENCE") ,ng_sub_filter,'\tadd_header Cache-Control no-cache;' ,get.proxydir)
else:
if type == 1 and cache == 1:
ng_proxy_cache += ng_proxy % (
get.proxydir, get.proxydir, get.proxysite, get.todomain, public.GetMsg("NGINX_PERSISTENCE") ,ng_sub_filter, ng_cache, get.proxydir)
get.proxydir, get.proxysite ,get.todomain, get.proxydir,get.proxysite,get.todomain, public.GetMsg("NGINX_PERSISTENCE") ,ng_sub_filter, ng_cache, get.proxydir)
if type == 1 and cache == 0:
ng_proxy_cache += ng_proxy % (
get.proxydir, get.proxydir, get.proxysite, get.todomain, public.GetMsg("NGINX_PERSISTENCE") ,ng_sub_filter, '\tadd_header Cache-Control no-cache;', get.proxydir)
get.proxydir, get.proxysite ,get.todomain,get.proxydir,get.proxysite,get.todomain, public.GetMsg("NGINX_PERSISTENCE") ,ng_sub_filter, '\tadd_header Cache-Control no-cache;', get.proxydir)
public.writeFile(ng_proxyfile, ng_proxy_cache)
@@ -2716,7 +2725,7 @@ location %s
ap_proxyfile = "%s/panel/vhost/apache/proxy/%s/%s_%s.conf" % (self.setupPath,get.sitename,proxyname_md5,get.sitename)
ap_proxydir = "%s/panel/vhost/apache/proxy/%s" % (self.setupPath,get.sitename)
if not os.path.exists(ap_proxydir):
os.system("mkdir -p %s" % ap_proxydir)
public.ExecShell("mkdir -p %s" % ap_proxydir)
ap_proxy = ''
if type == 1:
ap_proxy += '''#PROXY-START%s
@@ -2738,6 +2747,7 @@ location %s
for i in range(len(p_conf)-1,-1,-1):
if get.sitename == p_conf[i]["sitename"] and p_conf[i]["proxyname"]:
del p_conf[i]
self.RemoveProxy(get)
return public.returnMsg(False, 'ERROR: %s<br><a style="color:red;">' % public.GetMsg("CONFIG_ERROR") + isError.replace("\n",
'<br>') + '</a>')
return public.returnMsg(True, 'SUCCESS')
@@ -3296,9 +3306,9 @@ location %s
s_path = sitePath+old_run_path+"/.user.ini"
d_path = sitePath + get.runPath+"/.user.ini"
if s_path != d_path:
os.system("chattr -i {}".format(s_path))
os.system("mv {} {}".format(s_path,d_path))
os.system("chattr +i {}".format(d_path))
public.ExecShell("chattr -i {}".format(s_path))
public.ExecShell("mv {} {}".format(s_path,d_path))
public.ExecShell("chattr +i {}".format(d_path))
public.serviceReload();
return public.returnMsg(True,'SET_SUCCESS');
@@ -3431,8 +3441,12 @@ location %s
rep = "#SECURITY-START(\n|.){1,500}#SECURITY-END";
tmp = re.search(rep,conf).group()
data['fix'] = re.search("\(.+\)\$",tmp).group().replace('(','').replace(')$','').replace('|',',');
data['domains'] = ','.join(re.search("valid_referers\s+none\s+blocked\s+(.+);\n",tmp).groups()[0].split());
try:
data['domains'] = ','.join(re.search("valid_referers\s+none\s+blocked\s+(.+);\n",tmp).groups()[0].split());
except:
data['domains'] = ','.join(re.search("valid_referers\s+(.+);\n",tmp).groups()[0].split());
data['status'] = True;
data['none'] = tmp.find('none blocked') != -1
else:
data['fix'] = 'jpg,jpeg,gif,png,js,css';
domains = public.M('domain').where('pid=?',(get.id,)).field('name').select();
@@ -3441,6 +3455,7 @@ location %s
tmp.append(domain['name']);
data['domains'] = ','.join(tmp);
data['status'] = False
data['none'] = False
return data;
#设置防盗链
@@ -3450,13 +3465,22 @@ location %s
file = '/www/server/panel/vhost/nginx/' + get.name + '.conf';
if os.path.exists(file):
conf = public.readFile(file);
if conf.find('SECURITY-START') != -1:
rep = "\s{0,4}#SECURITY-START(\n|.){1,500}#SECURITY-END\n?";
conf = re.sub(rep,'',conf);
public.WriteLog('TYPE_SITE',"SITE_STOP_ANTI_STEALING_LINK",(get.name,))
if get.status == '1':
r_key = 'valid_referers none blocked'
d_key = 'valid_referers'
if conf.find(r_key) == -1:
conf = conf.replace(d_key,r_key)
else:
if conf.find('SECURITY-START') == -1: return public.returnMsg(False,'请先开启防盗链!')
conf = conf.replace(r_key,d_key)
else:
rconf = '''
%s
if conf.find('SECURITY-START') != -1:
rep = "\s{0,4}#SECURITY-START(\n|.){1,500}#SECURITY-END\n?";
conf = re.sub(rep,'',conf);
public.WriteLog('TYPE_SITE',"SITE_STOP_ANTI_STEALING_LINK",(get.name,))
else:
rconf = '''%s
location ~ .*\.(%s)$
{
expires 30d;
@@ -3468,23 +3492,33 @@ location %s
}
#SECURITY-END
include enable-php-''' % (public.GetMsg("SECURITY_START"),get.fix.strip().replace(',','|'),get.domains.strip().replace(',',' '))
conf = re.sub("include\s+enable-php-",rconf,conf);
public.WriteLog('TYPE_SITE',"SITE_START_ANTI_STEALING_LINK",(get.name,))
conf = re.sub("include\s+enable-php-",rconf,conf);
public.WriteLog('TYPE_SITE',"SITE_START_ANTI_STEALING_LINK",(get.name,))
public.writeFile(file,conf);
file = '/www/server/panel/vhost/apache/' + get.name + '.conf';
if os.path.exists(file):
conf = public.readFile(file);
if conf.find('SECURITY-START') != -1:
rep = "#SECURITY-START(\n|.){1,500}#SECURITY-END\n";
conf = re.sub(rep,'',conf);
if get.status == '1':
r_key = '#SECURITY-START.*\n RewriteEngine on\n RewriteCond %{HTTP_REFERER} !^$ [NC]\n'
d_key = '#SECURITY-START.*\n RewriteEngine on\n'
if conf.find(r_key) == -1:
conf = conf.replace(d_key,r_key)
else:
if conf.find('SECURITY-START') == -1: return public.returnMsg(False,'请先开启防盗链!')
conf = conf.replace(r_key,d_key)
else:
tmp = " RewriteCond %{HTTP_REFERER} !{DOMAIN} [NC]";
tmps = [];
for d in get.domains.split(','):
tmps.append(tmp.replace('{DOMAIN}',d));
domains = "\n".join(tmps);
rconf = "combined\n "+ public.GetMsg("SECURITY_START") +"\n RewriteEngine on\n RewriteCond %{HTTP_REFERER} !^$ [NC]\n" + domains + "\n RewriteRule .("+get.fix.strip().replace(',','|')+") /404.html [R=404,NC,L]\n #SECURITY-END"
conf = conf.replace('combined',rconf)
if conf.find('SECURITY-START') != -1:
rep = "#SECURITY-START(\n|.){1,500}#SECURITY-END\n";
conf = re.sub(rep,'',conf);
else:
tmp = " RewriteCond %{HTTP_REFERER} !{DOMAIN} [NC]";
tmps = [];
for d in get.domains.split(','):
tmps.append(tmp.replace('{DOMAIN}',d));
domains = "\n".join(tmps);
rconf = "combined\n "+ public.GetMsg("SECURITY_START") +"\n RewriteEngine on\n RewriteCond %{HTTP_REFERER} !^$ [NC]\n" + domains + "\n RewriteRule .("+get.fix.strip().replace(',','|')+") /404.html [R=404,NC,L]\n #SECURITY-END"
conf = conf.replace('combined',rconf)
public.writeFile(file,conf);
public.serviceReload();
return public.returnMsg(True,'SET_SUCCESS');
+43 -43
View File
@@ -76,7 +76,7 @@ class bt_task:
self.clean_log()
public.M(self.__table).add('name,type,shell,other,addtime,status',(task_name,task_type,task_shell,other,int(time.time()),0))
public.WriteFile(self.__task_tips,'True')
os.system("/etc/init.d/bt start")
public.ExecShell("/etc/init.d/bt start")
return True
@@ -90,28 +90,28 @@ class bt_task:
task_info = self.get_task_find(get.id)
public.M(self.__table).where('id=?',(get.id,)).delete();
if str(task_info['status']) == '-1':
os.system("kill -9 $(ps aux|grep 'task.py'|grep -v grep|awk '{print $2}')")
public.ExecShell("kill -9 $(ps aux|grep 'task.py'|grep -v grep|awk '{print $2}')")
if task_info['type'] == '1':
if os.path.exists(task_info['other']): os.remove(task_info['other'])
elif task_info['type'] == '3':
z_info = json.loads(task_info['other'])
if z_info['z_type'] == 'tar.gz':
os.system("kill -9 $(ps aux|grep 'tar -zcvf'|grep -v grep|awk '{print $2}')")
public.ExecShell("kill -9 $(ps aux|grep 'tar -zcvf'|grep -v grep|awk '{print $2}')")
elif z_info['z_type'] == 'rar':
os.system("kill -9 $(ps aux|grep /www/server/rar/rar|grep -v grep|awk '{print $2}')")
public.ExecShell("kill -9 $(ps aux|grep /www/server/rar/rar|grep -v grep|awk '{print $2}')")
elif z_info['z_type'] == 'zip':
os.system("kill -9 $(ps aux|grep '.zip -r'|grep -v grep|awk '{print $2}')")
os.system("kill -9 $(ps aux|grep '.zip\' -r'|grep -v grep|awk '{print $2}')")
public.ExecShell("kill -9 $(ps aux|grep '.zip -r'|grep -v grep|awk '{print $2}')")
public.ExecShell("kill -9 $(ps aux|grep '.zip\' -r'|grep -v grep|awk '{print $2}')")
if os.path.exists(z_info['dfile']): os.remove(z_info['dfile'])
elif task_info['type'] == '2':
os.system("kill -9 $(ps aux|grep 'tar -zxvf'|grep -v grep|awk '{print $2}')")
os.system("kill -9 $(ps aux|grep '/www/server/rar/unrar'|grep -v grep|awk '{print $2}')")
os.system("kill -9 $(ps aux|grep 'unzip -P'|grep -v grep|awk '{print $2}')")
os.system("kill -9 $(ps aux|grep 'gunzip -c'|grep -v grep|awk '{print $2}')")
public.ExecShell("kill -9 $(ps aux|grep 'tar -zxvf'|grep -v grep|awk '{print $2}')")
public.ExecShell("kill -9 $(ps aux|grep '/www/server/rar/unrar'|grep -v grep|awk '{print $2}')")
public.ExecShell("kill -9 $(ps aux|grep 'unzip -P'|grep -v grep|awk '{print $2}')")
public.ExecShell("kill -9 $(ps aux|grep 'gunzip -c'|grep -v grep|awk '{print $2}')")
elif task_info['type'] == '0':
os.system("kill -9 $(ps aux|grep '"+task_info['shell']+"'|grep -v grep|awk '{print $2}')")
public.ExecShell("kill -9 $(ps aux|grep '"+task_info['shell']+"'|grep -v grep|awk '{print $2}')")
os.system("/etc/init.d/bt start")
public.ExecShell("/etc/init.d/bt start")
return public.returnMsg(True,'TASK_CANCEL')
#取一条任务
@@ -131,7 +131,7 @@ class bt_task:
task_type = int(task_type)
#开始执行
if task_type == 0: #执行命令
os.system(task_shell + ' &> ' + log_file)
public.ExecShell(task_shell + ' &> ' + log_file)
elif task_type == 1: #下载文件
down_file = downloadFile.downloadFile()
down_file.logPath = log_file
@@ -234,13 +234,13 @@ class bt_task:
#判断压缩格式
if z_type == 'zip':
os.system("cd '"+path+"' && zip '"+dfile+"' -r "+sfiles+" &> "+log_file)
public.ExecShell("cd '"+path+"' && zip '"+dfile+"' -r "+sfiles+" &> "+log_file)
elif z_type == 'tar.gz':
os.system("cd '" + path + "' && tar -zcvf '" + dfile + "' " + sfiles + " &> " + log_file);
public.ExecShell("cd '" + path + "' && tar -zcvf '" + dfile + "' " + sfiles + " &> " + log_file);
elif z_type == 'rar':
rar_file = '/www/server/rar/rar'
if not os.path.exists(rar_file): self.install_rar()
os.system("cd '" + path + "' && "+rar_file+" a -r '" + dfile + "' " + sfiles + " &> " + log_file)
public.ExecShell("cd '" + path + "' && "+rar_file+" a -r '" + dfile + "' " + sfiles + " &> " + log_file)
else:
return public.returnMsg(False,'NOT_SUP_COMP_FORMAT')
@@ -259,19 +259,19 @@ class bt_task:
#判断压缩包格式
if sfile[-4:] == '.zip':
os.system("unzip -P '"+password+"' -o '" + sfile + "' -d '" + dfile + "' &> " + log_file)
public.ExecShell("unzip -P '"+password+"' -o '" + sfile + "' -d '" + dfile + "' &> " + log_file)
elif sfile[-7:] == '.tar.gz' or sfile[-4:] == '.tgz':
os.system("tar zxvf '" + sfile + "' -C '" + dfile + "' &> " + log_file)
public.ExecShell("tar zxvf '" + sfile + "' -C '" + dfile + "' &> " + log_file)
elif sfile[-4:] == '.rar':
rar_file = '/www/server/rar/unrar'
if not os.path.exists(rar_file): self.install_rar()
os.system('echo "'+password+'"|' + rar_file + ' x -u -y "' + sfile + '" "' + dfile + '" &> ' + log_file)
public.ExecShell('echo "'+password+'"|' + rar_file + ' x -u -y "' + sfile + '" "' + dfile + '" &> ' + log_file)
elif sfile[-4:] == '.war':
os.system("unzip -P '"+password+"' -o '" + sfile + "' -d '" + dfile + "' &> " + log_file)
public.ExecShell("unzip -P '"+password+"' -o '" + sfile + "' -d '" + dfile + "' &> " + log_file)
elif sfile[-4:] == '.bz2':
os.system("tar jxvf '" + sfile + "' -C '" + dfile + "' &> " + log_file)
public.ExecShell("tar jxvf '" + sfile + "' -C '" + dfile + "' &> " + log_file)
else:
os.system("gunzip -c " + sfile + " > " + sfile[:-3])
public.ExecShell("gunzip -c " + sfile + " > " + sfile[:-3])
#检查是否设置权限
if self.check_dir(dfile):
@@ -281,7 +281,7 @@ class bt_task:
else:
import pwd
user = pwd.getpwuid(os.stat(dfile).st_uid).pw_name
os.system("chown %s:%s %s" % (user,user,dfile))
public.ExecShell("chown %s:%s %s" % (user,user,dfile))
public.WriteLog("TYPE_FILE", 'UNZIP_SUCCESS',(sfile,dfile));
return public.returnMsg(True,'UNZIP_SUCCESS');
@@ -296,7 +296,7 @@ class bt_task:
if not (os.path.exists(backupPath)): os.makedirs(backupPath)
execStr = "cd '" + find['path'] + "' && zip '" + zipName + "' -x .user.ini -r ./ &> " + log_file
os.system(execStr)
public.ExecShell(execStr)
sql = public.M('backup').add('type,name,pid,filename,size,addtime',(0,fileName,find['id'],zipName,0,public.getDate()));
public.WriteLog('TYPE_SITE', 'SITE_BACKUP_SUCCESS',(find['name'],));
@@ -307,12 +307,12 @@ class bt_task:
name = public.M('databases').where("id=?",(id,)).getField('name')
find = public.M('config').where('id=?',(1,)).field('mysql_root,backup_path').find()
if not os.path.exists(find['backup_path'] + '/database'): os.system('mkdir -p ' + find['backup_path'] + '/database')
if not os.path.exists(find['backup_path'] + '/database'): public.ExecShell('mkdir -p ' + find['backup_path'] + '/database')
self.mypass(True, find['mysql_root'])
fileName = name + '_' + time.strftime('%Y%m%d_%H%M%S',time.localtime()) + '.sql.gz'
backupName = find['backup_path'] + '/database/' + fileName
os.system("/www/server/mysql/bin/mysqldump --force --opt \"" + name + "\" | gzip > " + backupName)
public.ExecShell("/www/server/mysql/bin/mysqldump --force --opt \"" + name + "\" | gzip > " + backupName)
if not os.path.exists(backupName): return public.returnMsg(False,'BACKUP_ERROR')
self.mypass(False, find['mysql_root'])
@@ -352,15 +352,15 @@ class bt_task:
if not os.path.exists(backupPath + '/' + tmpFile) or tmpFile == '': return public.returnMsg(False, 'FILE_NOT_EXISTS',(tmpFile,))
self.mypass(True, root);
os.system(public.GetConfigValue('setup_path') + "/mysql/bin/mysql -uroot -p" + root + " --force \"" + name + "\" < " + backupPath + '/' +tmpFile)
public.ExecShell(public.GetConfigValue('setup_path') + "/mysql/bin/mysql -uroot -p" + root + " --force \"" + name + "\" < " + backupPath + '/' +tmpFile)
self.mypass(False, root);
if isgizp:
os.system('cd ' +backupPath+ ' && gzip ' + file.split('/')[-1][:-3]);
public.ExecShell('cd ' +backupPath+ ' && gzip ' + file.split('/')[-1][:-3]);
else:
os.system("rm -f " + backupPath + '/' +tmpFile)
public.ExecShell("rm -f " + backupPath + '/' +tmpFile)
else:
self.mypass(True, root);
os.system(public.GetConfigValue('setup_path') + "/mysql/bin/mysql -uroot -p" + root + " --force \"" + name + "\" < " + file)
public.ExecShell(public.GetConfigValue('setup_path') + "/mysql/bin/mysql -uroot -p" + root + " --force \"" + name + "\" < " + file)
self.mypass(False, root);
@@ -372,8 +372,8 @@ class bt_task:
#配置
def mypass(self,act,root):
my_cnf = '/etc/my.cnf'
os.system("sed -i '/user=root/d' " + my_cnf)
os.system("sed -i '/password=/d' " + my_cnf)
public.ExecShell("sed -i '/user=root/d' " + my_cnf)
public.ExecShell("sed -i '/password=/d' " + my_cnf)
if act:
mycnf = public.readFile(my_cnf);
rep = "\[mysqldump\]\nuser=root"
@@ -384,11 +384,11 @@ class bt_task:
#设置权限
def set_file_accept(self,filename):
os.system('chown -R www:www ' + filename)
# os.system('chmod -R 755 ' + filename)
public.ExecShell('chown -R www:www ' + filename)
# public.ExecShell('chmod -R 755 ' + filename)
a = 'find {filename} -type d |xargs chmod 0755'.format(filename=filename)
os.system(a)
os.system('find {filename} -type f |xargs chmod 0644'.format(filename=filename))
public.ExecShell(a)
public.ExecShell('find {filename} -type f |xargs chmod 0644'.format(filename=filename))
#检查敏感目录
@@ -436,7 +436,7 @@ class bt_task:
try:
import rarfile
except:
os.system("pip install rarfile")
public.ExecShell("pip install rarfile")
return True
import platform
@@ -445,18 +445,18 @@ class bt_task:
download_url = public.get_url() + '/src/rarlinux'+os_bit+'-5.6.1.tar.gz';
tmp_file = '/tmp/bt_rar.tar.gz'
os.system('wget -O ' + tmp_file + ' ' + download_url)
if os.path.exists(unrar_file): os.system("rm -rf /www/server/rar")
os.system("tar xvf " + tmp_file + ' -C /www/server/')
public.ExecShell('wget -O ' + tmp_file + ' ' + download_url)
if os.path.exists(unrar_file): public.ExecShell("rm -rf /www/server/rar")
public.ExecShell("tar xvf " + tmp_file + ' -C /www/server/')
if os.path.exists(tmp_file): os.remove(tmp_file)
if not os.path.exists(unrar_file): return False
if os.path.exists(bin_unrar): os.remove(bin_unrar)
if os.path.exists(bin_rar): os.remove(bin_rar)
os.system('ln -sf ' + unrar_file + ' ' + bin_unrar)
os.system('ln -sf ' + rar_file + ' ' + bin_rar)
#os.system("pip install rarfile")
public.ExecShell('ln -sf ' + unrar_file + ' ' + bin_unrar)
public.ExecShell('ln -sf ' + rar_file + ' ' + bin_rar)
#public.ExecShell("pip install rarfile")
return True
+217
View File
@@ -0,0 +1,217 @@
# coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Linux面板
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2099 宝塔软件(http://bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author: 梁凯强 <1249648969@qq.com>
# +-------------------------------------------------------------------
# +--------------------------------------------------------------------
# | 密码管理
# +--------------------------------------------------------------------
import sys, os
if sys.version_info[0] == 2:
reload(sys)
sys.setdefaultencoding('utf-8')
os.chdir('/www/server/panel')
sys.path.append("class/")
import re
import public,data,database,config
class password:
def __init__(self):
self.__data=data.data()
self.__database=database.database()
self.__config=config.config()
#设置面板密码
def set_panel_password(self,get):
get.password1=get.password
get.password2 = get.password
data=self.__config.setPassword(get)
return data
#查看面板用户名
def get_panel_username(self,get):
data=public.M('users').where("id=?", (1,)).getField('username')
if data:
return data
else:
return False
# 设置root 密码
def set_root_password(self,get):
public.ExecShell("echo"+get.user+":"+get.password+"|chpasswd")
return True
#查看mysql_root密码
def get_mysql_root(self,get):
password = public.M('config').where("id=?",(1,)).getField('mysql_root')
return public.returnMsg(True, password)
#设置mysql_root 密码
def set_mysql_password(self,get):
if 'password' in get:
resutl=self.__database.SetupPassword(get)
return resutl
else:
return public.returnMsg(False, 'password参数不能为空')
# MySQL 的其他账户设置
#获取其他mysql的信息
def get_databses(self,get):
data=public.M('databases').select()
return public.returnMsg(True, data)
# 修改MySQL 其他账户的密码
def rem_mysql_pass(self,get):
'''
参数 三个
id 数据库ID name:数据库名称, password:数据库密码
'''
data=self.__database.ResDatabasePassword(get)
return data
# 修改其他Mysql 账户的权限
def set_mysql_access(self,get):
'''
参数 三个
name:数据库名称, dataAccess: 权限 access 权限
'''
data=self.__database.SetDatabaseAccess(get)
return data
#################### SSH 的基础设置####################
# 开启密码登陆
def SetPassword(self, get):
ssh_password = '\n#?PasswordAuthentication\s\w+'
file = public.readFile('/etc/ssh/sshd_config')
if len(re.findall(ssh_password, file)) == 0:
file_result = file + '\nPasswordAuthentication yes'
else:
file_result = re.sub(ssh_password, '\nPasswordAuthentication yes', file)
self.Wirte('/etc/ssh/sshd_config', file_result)
self.RestartSsh()
return public.returnMsg(True, '开启成功')
# 设置ssh_key
def SetSshKey(self, get):
''''''
type_list = ['rsa', 'dsa']
ssh_type = ['yes', 'no']
ssh = get.ssh
if not ssh in ssh_type: return public.returnMsg(False, 'ssh选项失败')
type = get.type
if not type in type_list: return public.returnMsg(False, '加密方式错误')
file = ['/root/.ssh/id_rsa.pub', '/root/.ssh/id_rsa', '/root/.ssh/authorized_keys']
for i in file:
if os.path.exists(i):
os.remove(i)
public.ExecShell("ssh-keygen -t %s -P '' -f ~/.ssh/id_rsa |echo y" % type)
if os.path.exists(file[0]):
public.ExecShell('cat %s >%s && chmod 600 %s' % (file[0], file[-1], file[-1]))
rec = '\n#?RSAAuthentication\s\w+'
rec2 = '\n#?PubkeyAuthentication\s\w+'
file = public.readFile('/etc/ssh/sshd_config')
if len(re.findall(rec, file)) == 0: file = file + '\nRSAAuthentication yes'
if len(re.findall(rec2, file)) == 0: file = file + '\nPubkeyAuthentication yes'
file_ssh = re.sub(rec, '\nRSAAuthentication yes', file)
file_result = re.sub(rec2, '\nPubkeyAuthentication yes', file_ssh)
if ssh == 'no':
ssh_password = '\n#?PasswordAuthentication\s\w+'
if len(re.findall(ssh_password, file_result)) == 0:
file_result = file_result + '\nPasswordAuthentication no'
else:
file_result = re.sub(ssh_password, '\nPasswordAuthentication no', file_result)
self.Wirte('/etc/ssh/sshd_config', file_result)
self.RestartSsh()
return public.returnMsg(True, '开启成功')
else:
return public.returnMsg(False, '开启失败')
# 关闭sshkey
def StopKey(self, get):
file = ['/root/.ssh/id_rsa.pub', '/root/.ssh/id_rsa', '/root/.ssh/authorized_keys']
rec = '\n#?RSAAuthentication\s\w+'
rec2 = '\n#?PubkeyAuthentication\s\w+'
file = public.readFile('/etc/ssh/sshd_config')
file_ssh = re.sub(rec, '\n#RSAAuthentication no', file)
file_result = re.sub(rec2, '\n#PubkeyAuthentication no', file_ssh)
self.Wirte('/etc/ssh/sshd_config', file_result)
self.SetPassword(get)
self.RestartSsh()
return public.returnMsg(True, '关闭成功')
# 读取配置文件 获取当前状态
def GetConfig(self, get):
result = {}
file = public.readFile('/etc/ssh/sshd_config')
rec = '\n#?RSAAuthentication\s\w+'
pubkey = '\n#?PubkeyAuthentication\s\w+'
ssh_password = '\nPasswordAuthentication\s\w+'
ret = re.findall(ssh_password, file)
if not ret:
result['password'] = 'no'
else:
if ret[-1].split()[-1] == 'yes':
result['password'] = 'yes'
else:
result['password'] = 'no'
pubkey = re.findall(pubkey, file)
if not pubkey:
result['pubkey'] = 'no'
else:
if pubkey[-1].split()[-1] == 'no':
result['pubkey'] = 'no'
else:
result['pubkey'] = 'yes'
rsa_auth = re.findall(rec, file)
if not rsa_auth:
result['rsa_auth'] = 'no'
else:
if rsa_auth[-1].split()[-1] == 'no':
result['rsa_auth'] = 'no'
else:
result['rsa_auth'] = 'yes'
return result
# 关闭密码方式
def StopPassword(self, get):
file = public.readFile('/etc/ssh/sshd_config')
ssh_password = '\n#?PasswordAuthentication\s\w+'
file_result = re.sub(ssh_password, '\nPasswordAuthentication no', file)
self.Wirte('/etc/ssh/sshd_config', file_result)
self.RestartSsh()
return public.returnMsg(True, '关闭成功')
#显示key文件
def GetKey(self, get):
file = '/root/.ssh/id_rsa'
if not os.path.exists(file): return public.returnMsg(True, '')
ret = public.readFile(file)
return public.returnMsg(True, ret)
# 下载
def Download(self, get):
if os.path.exists('/root/.ssh/id_rsa'):
ret = '/download?filename=/root/.ssh/id_rsa'
return public.returnMsg(True, ret)
# 写入配置文件
def Wirte(self, file, ret):
result = public.writeFile(file, ret)
return result
def RestartSsh(self):
version = public.readFile('/etc/redhat-release')
act = 'restart'
if not os.path.exists('/etc/redhat-release'):
public.ExecShell('service ssh ' + act)
elif version.find(' 7.') != -1:
public.ExecShell("systemctl " + act + " sshd.service")
else:
public.ExecShell("/etc/init.d/sshd " + act)
+41 -33
View File
@@ -11,7 +11,7 @@
# 宝塔公共库
# --------------------------------
import json,os,sys,time,re,socket,importlib,binascii,base64
import json,os,sys,time,re,socket,importlib,binascii,base64,io
if sys.version_info[0] == 2:
reload(sys)
@@ -478,33 +478,27 @@ def serviceReload():
def ExecShell(cmdstring, cwd=None, timeout=None, shell=True):
a = ''
e = ''
try:
#通过管道执行SHELL
import shlex
import datetime
import subprocess
import time
import subprocess,tempfile
if shell:
cmdstring_list = cmdstring
else:
cmdstring_list = shlex.split(cmdstring)
if timeout:
end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
sub = subprocess.Popen(cmdstring_list, cwd=cwd, stdin=subprocess.PIPE,shell=shell,bufsize=4096,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
while sub.poll() is None:
time.sleep(0.1)
if timeout:
if end_time <= datetime.datetime.now():
raise Exception("Timeout%s"%cmdstring)
a,e = sub.communicate()
try:
if type(a) == bytes: a = a.decode('utf-8')
if type(e) == bytes: e = e.decode('utf-8')
except:pass
try:
rx = md5(cmdstring)
succ_f = tempfile.SpooledTemporaryFile(max_size=4096,mode='wb+',suffix='_succ',prefix='btex_' + rx ,dir='/dev/shm')
err_f = tempfile.SpooledTemporaryFile(max_size=4096,mode='wb+',suffix='_err',prefix='btex_' + rx ,dir='/dev/shm')
sub = subprocess.Popen(cmdstring, close_fds=True, shell=shell,bufsize=128,stdout=succ_f,stderr=err_f)
sub.wait()
err_f.seek(0)
succ_f.seek(0)
a = succ_f.read()
e = err_f.read()
if not err_f.closed: err_f.close()
if not succ_f.closed: succ_f.close()
except:
if not a:
a = os.popen(cmdstring).read()
print(get_error_info())
try:
#编码修正
if type(a) == bytes: a = a.decode('utf-8')
if type(e) == bytes: e = e.decode('utf-8')
except:pass
return a,e
@@ -1022,7 +1016,7 @@ MySQL_Opt
mycnf = mycnf.replace('/www/server/data', newPath);
writeFile('/etc/my.cnf', mycnf);
os.system(shellStr);
ExecShell(shellStr);
WriteLog('TYPE_SOFE', 'MYSQL_CHECK_ERR');
return True;
@@ -1289,7 +1283,6 @@ def get_page(count, p=1, rows=12, callback='', result='1,2,3,4,5,8'):
# 取面板版本
def version():
from BTPanel import g
try:
from BTPanel import g
return g.version
@@ -1356,11 +1349,9 @@ def set_own(filename, user, group=None):
from pwd import getpwnam
try:
user_info = getpwnam(user)
# user_info = getpwnam('www')
user = user_info.pw_uid
if group:
user_info = getpwnam(group)
# user_info = getpwnam('www')
group = user_info.pw_gid
except:
# 如果指定用户或组不存在,则使用www
@@ -1438,7 +1429,7 @@ def en_crypt(key,strings):
result = f.encrypt(strings)
return result.decode('utf-8')
except:
print(get_error_info())
#print(get_error_info())
return strings
#解密字符串
@@ -1478,7 +1469,7 @@ def check_domain_panel():
errorStr = ReadFile('./BTPanel/templates/' + GetConfigValue('template') + '/error2.html')
try:
errorStr = errorStr.format(getMsg('PAGE_ERR_TITLE'),getMsg('PAGE_ERR_DOMAIN_H1'),getMsg('PAGE_ERR_DOMAIN_P1'),getMsg('PAGE_ERR_DOMAIN_P2'),getMsg('PAGE_ERR_DOMAIN_P3'),getMsg('NAME'),getMsg('PAGE_ERR_HELP'))
except IndexError:pass
except:pass
return errorStr
return False
@@ -1542,7 +1533,7 @@ def sync_date():
new_time = int(time_str)
time_arr = time.localtime(new_time)
date_str = time.strftime("%Y-%m-%d %H:%M:%S", time_arr)
os.system('date -s "%s"' % date_str)
ExecShell('date -s "%s"' % date_str)
writeFile(tip_file,str(s_time))
return True
except:
@@ -1605,6 +1596,23 @@ def en_hexb(data):
if type(result) != str: result = result.decode('utf-8')
return result;
def upload_file_url(filename):
try:
if os.path.exists(filename):
data = ExecShell('/usr/bin/curl https://scanner.baidu.com/enqueue -F archive=@%s' % filename)
data = json.loads(data[0])
time.sleep(1)
import requests
default_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
data_list = requests.get(url=data['url'], headers=default_headers, verify=False)
return (data_list.json())
else:
return False
except:
return False
#取通用对象
class dict_obj:
def __contains__(self, key):
File diff suppressed because it is too large Load Diff
+3
View File
@@ -0,0 +1,3 @@
import os
a='/www/backup/database/fdsa_20190808_034550.sql.gz'
print(os.path.exists(a))
+55 -49
View File
@@ -6,18 +6,20 @@
# +-------------------------------------------------------------------
# | Author: 黄文良 <287962566@qq.com>
# +-------------------------------------------------------------------
import paramiko
try:
import paramiko
except: pass
import json
import time
import os
import sys
import socket
import threading
sys.path.insert(0, '/www/server/panel/class/')
import public
from io import BytesIO, StringIO
from BTPanel import session,socketio
from BTPanel import session
class ssh_terminal:
__log_type = 'aaPanel terminal'
@@ -31,6 +33,8 @@ class ssh_terminal:
_my_terms = {}
_room = "ssh_data"
_send_last = False
_send_last_time = 0
_connect_time = 0
def __init__(self):
pass
@@ -48,7 +52,7 @@ class ssh_terminal:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 262144)
sock.connect((self._ssh_info['host'], int(self._ssh_info['port'])))
except Exception as e:
socketio.emit(self._room,"\rServer connection failed!\r")
self._web_socket.send("\rServer connection failed!\r")
return False
# 使用Transport连接
p1 = paramiko.Transport(sock)
@@ -67,7 +71,7 @@ class ssh_terminal:
# print('-----------使用密码登陆-----------')
p1.auth_password(username=self._ssh_info['username'].strip(), password=self._ssh_info['password'])
except Exception as e:
socketio.emit(self._room,"\rWrong user name or password!\r")
self._web_socket.send("\rWrong user name or password!\r")
p1.close()
return False
@@ -84,6 +88,7 @@ class ssh_terminal:
#print("登录成功")
self._my_terms[self._host].last_send = []
self._send_last = True
self._connect_time = time.time()
return True
def resize(self, data):
@@ -95,64 +100,54 @@ class ssh_terminal:
print(public.get_error_info())
return False
def send(self,c_data):
def send(self):
try:
if not c_data: return
if not self._thread:
s_file = '/www/server/panel/config/t_info.json'
ssh_info = None
if os.path.exists(s_file):
ssh_info = json.loads(public.en_hexb(public.readFile(s_file)))
if not 'host' in c_data:
host = "127.0.0.1"
if ssh_info:
c_data = ssh_info
host = c_data['host']
else:
host = c_data['host']
if not host:
if not ssh_info: return socketio.emit(self._room,"\rWrong user name or password!\r")
c_data = ssh_info
key = 'ssh_' + host
if 'password' in c_data:
session[key] = c_data
if not key in session: return socketio.emit(self._room,"\rWrong user name or password!\r")
result = self.run(session[key])
else:
while not self._web_socket.closed:
c_data = self._web_socket.receive()
if not c_data: continue
if len(c_data) > 10:
if c_data == 'new_bt_terminal':
if not self._send_last: self.last_send()
self._send_last = False
return
if c_data.find('resize_pty') != -1:
if self.resize(c_data): return
if type(c_data) == dict: return
if c_data.find('new_terminal') != -1:
if not self._host in self._my_terms:
self.connect()
else:
if time.time() - self._connect_time > 3:
self.last_send()
continue
if c_data.find("reset_connect") != -1:
if not self._host in self._my_terms: self.connect()
continue
if self._host in self._my_terms:
self._my_terms[self._host].last_time = time.time()
self._my_terms[self._host].tty.send(c_data)
else:
return
except:
self.close()
socketio.emit(self._room,'\rConnection failure!\r')
print(public.get_error_info())
def recv(self):
try:
while True:
n = 0
while not self._web_socket.closed:
self.not_send()
#if n == 0: self.last_send()
data = self._my_terms[self._host].tty.recv(1024)
self.not_send()
if not data:
self.close()
socketio.emit(self._room,"\rThe connection has been disconnected and pressing Enter will attempt to reconnect!\r")
self._web_socket.send('The connection has been disconnected and pressing Enter will attempt to reconnect!')
return
try:
result = data.decode()
except:
result = str(data)
if not result: continue
if self._web_socket.closed:
self._my_terms[self._host].not_send = result
return
self.set_last_send(result)
socketio.emit(self._room,result)
if not n: n = 1
self._web_socket.send(result)
except:
print(public.get_error_info())
@@ -169,14 +164,17 @@ class ssh_terminal:
def not_send(self):
if 'not_send' in self._my_terms[self._host]:
if self._my_terms[self._host].not_send:
socketio.emit(self._room,self._my_terms[self._host].not_send)
self._web_socket.send(self._my_terms[self._host].not_send)
self._my_terms[self._host].not_send = ""
def last_send(self):
if time.time()- self._send_last_time < 3: return False
self._send_last_time = time.time()
time.sleep(0.3)
if not self._host in self._my_terms: return False
if 'last_send' in self._my_terms[self._host]:
for d in self._my_terms[self._host].last_send:
socketio.emit(self._room,d)
self._web_socket.send(d)
def close(self):
try:
@@ -186,14 +184,22 @@ class ssh_terminal:
del self._my_terms[self._host]
self._thread = None
def run(self, ssh_info=None):
if not ssh_info:
return
def run(self,web_socket, ssh_info=None):
self._web_socket = web_socket
if 'id' in ssh_info:
self._ssh_info = self.get_server_ssh_info(ssh_info)
else:
self._ssh_info = ssh_info
if not self._ssh_info:
return
result = self.connect()
if result and not self._thread:
self._thread = socketio.start_background_task(target=self.recv)
return result
time.sleep(0.1)
if result:
sendt = threading.Thread(target=self.send)
recvt = threading.Thread(target=self.recv)
sendt.start()
recvt.start()
sendt.join()
recvt.join()
if time.time() - self._my_terms[self._host].last_time > 86400: self.close()
self._web_socket = None
+10 -9
View File
@@ -280,7 +280,7 @@ class system:
c_tmp = public.readFile('/proc/cpuinfo')
d_tmp = re.findall("physical id.+",c_tmp)
cpuW = len(set(d_tmp))
used = self.get_cpu_percent()
used = psutil.cpu_percent(1)
used_all = psutil.cpu_percent(percpu=True)
cpu_name = public.getCpuType() + " * {}".format(cpuW)
return used,cpuCount,used_all,cpu_name,cpuNum,cpuW
@@ -362,8 +362,9 @@ class system:
if len(disk) < 5: continue;
if disk[1].find('M') != -1: continue;
if disk[1].find('K') != -1: continue;
if len(disk[5].split('/')) > 4: continue;
if len(disk[5].split('/')) > 10: continue;
if disk[5] in cuts: continue;
if disk[5].find('docker') != -1: continue
arr = {}
arr['path'] = disk[5];
tmp1 = [disk[1],disk[2],disk[3],disk[4]];
@@ -433,7 +434,7 @@ class system:
public.serviceReload();
filename = '/www/server/nginx/off'
if os.path.exists(filename): os.remove(filename)
os.system('echo > /tmp/panelBoot.pl');
public.ExecShell('echo > /tmp/panelBoot.pl');
return total,count
def GetNetWork(self,get=None):
@@ -671,14 +672,14 @@ class system:
#执行
execStr = "/etc/init.d/"+get.name+" "+get.type
if execStr == '/etc/init.d/pure-ftpd reload': execStr = self.setupPath+'/pure-ftpd/bin/pure-pw mkdb '+self.setupPath+'/pure-ftpd/etc/pureftpd.pdb'
if execStr == '/etc/init.d/pure-ftpd start': os.system('pkill -9 pure-ftpd');
if execStr == '/etc/init.d/pure-ftpd start': public.ExecShell('pkill -9 pure-ftpd');
if execStr == '/etc/init.d/tomcat reload': execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start';
if execStr == '/etc/init.d/tomcat restart': execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start';
if get.name != 'mysqld':
result = public.ExecShell(execStr);
else:
os.system(execStr);
public.ExecShell(execStr);
result = [];
result.append('');
result.append('');
@@ -705,7 +706,7 @@ class system:
#释放内存
def ReMemory(self,get):
os.system('sync');
public.ExecShell('sync');
scriptFile = 'script/rememory.sh'
if not os.path.exists(scriptFile):
public.downloadFile(public.GetConfigValue('home') + '/script/rememory.sh',scriptFile);
@@ -717,7 +718,7 @@ class system:
#s = time.time()
#if not self.shell: self.connect_ssh()
#self.shell.send("nohup /etc/init.d/bt restart && sleep 1 && /etc/init.d/bt start > /dev/null &\n")
#os.system("nohup sleep 2 && /etc/init.d/bt restart 2>&1 >/dev/null &")
#public.ExecShell("nohup sleep 2 && /etc/init.d/bt restart 2>&1 >/dev/null &")
public.ExecShell("/etc/init.d/bt start")
public.writeFile('data/restart.pl','True')
@@ -749,13 +750,13 @@ class system:
#修复面板
def RepPanel(self,get):
os.system("wget -O update.sh " + public.get_url() + "/install/update6_en.sh && bash update.sh");
public.ExecShell("wget -O update.sh " + public.get_url() + "/install/update6_en.sh && bash update.sh");
self.ReWeb(None)
return True;
#升级到专业版
def UpdatePro(self,get):
os.system("wget -O update.sh " + public.get_url() + "/install/update6_en.sh && bash update.sh");
public.ExecShell("wget -O update.sh " + public.get_url() + "/install/update6_en.sh && bash update.sh");
self.ReWeb(None)
return True;
+23 -1
View File
@@ -104,6 +104,7 @@ class userlogin:
def login_token(self):
import config
config.config().reload_session()
self.clear_session()
def request_get(self,get):
#if os.path.exists('/www/server/panel/install.pl'): raise redirect('/install');
@@ -231,4 +232,25 @@ class userlogin:
v_time = now - int(dont_vcode_ip_info["add_time"])
if ip and v_time < 86400:
acc_client_ip = True
return acc_client_ip
return acc_client_ip
# 清理多余SESSION数据
def clear_session(self):
session_file = '/dev/shm/session.db'
if not os.path.exists(session_file): return False
s_size = os.path.getsize(session_file)
if s_size < 1024 * 512: return False
try:
sid = 'BT_:' + session.sid
import db
sql = db.Sql()
sql._Sql__DB_FILE = session_file
if s_size > 1024 * 1024 * 10:
sql.table('session').where('session_id!=?',(sid,)).delete()
sql.table('session').execute('VACUUM',())
else:
sql.table('session').where('session_id!=? AND expiry<?',(sid,public.format_date())).delete()
sql.close()
return True
except:
return False
+287 -611
View File
@@ -1,636 +1,312 @@
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
LANG=en_US.UTF-8
is64bit=`getconf LONG_BIT`
if [ -f "/usr/bin/apt-get" ];then
isDebian=`cat /etc/issue|grep Debian`
if [ "$isDebian" != "" ];then
wget -O install.sh http://www.aapanel.com/script/install-ubuntu_6.0_en.sh && bash install.sh
exit;
else
wget -O install.sh http://www.aapanel.com/script/install-ubuntu_6.0_en.sh && sudo bash install.sh
exit;
fi
fi
if [ "$is64bit" != '64' ];then
echo "====================================="
echo "Sorry, 6.0 Does not support 32-bit systems, Use 64-bit system Please!";
exit 0;
fi
# chkconfig: 2345 55 25
# description: bt Cloud Service
### BEGIN INIT INFO
# Provides: bt
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts bt
# Description: starts the bt
### END INIT INFO
panel_path=/www/server/panel
pidfile=$panel_path/logs/panel.pid
cd $panel_path
py26=$(python -V 2>&1|grep '2.6.')
if [ "$py26" != "" ];then
echo "====================================="
echo "Sorry, 6.0 Does not support Centos6.x, Please install Centos7";
exit 0;
pythonV=python3
fi
env_path=$panel_path/env/bin/activate
if [ -f $env_path ];then
source $env_path
fi
chmod 700 $panel_path/BT-Panel
log_file=/www/server/panel/logs/error.log
if [ -f $panel_path/data/ssl.pl ];then
log_file=/dev/null
fi
CN='http://125.88.182.172:5880'
port=$(cat /www/server/panel/data/port.pl)
Install_Check(){
while [ "$yes" != 'yes' ] && [ "$yes" != 'n' ]
do
echo -e "----------------------------------------------------"
echo -e "Web service is alreday installed,installing aaPanel may affect existing sites."
echo -e "----------------------------------------------------"
read -p "Enter yes to force installation (yes/n): " yes;
done
if [ "$yes" == 'n' ];then
exit;
panel_start()
{
isStart=`ps aux|grep 'runserver:app'|grep -v grep|awk '{print $2}'`
if [ "$isStart" != '' ];then
kill -9 $isStart
fi
isStart=`ps aux|grep 'BT-Panel'|grep -v grep|awk '{print $2}'`
if [ "$isStart" == '' ];then
rm -f $pidfile
panel_port_check
echo -e "Starting Bt-Panel.\c"
nohup $panel_path/BT-Panel >> $log_file 2>&1 &
isStart=""
n=0
while [[ "$isStart" == "" ]];
do
echo -e ".\c"
sleep 0.5
isStart=$(lsof -n -P -i:$port|grep LISTEN|grep -v grep|awk '{print $2}'|xargs)
let n+=1
if [ $n -gt 8 ];then
break;
fi
done
if [ "$isStart" == '' ];then
echo -e "\033[31mfailed\033[0m"
echo '------------------------------------------------------'
tail -n 20 $log_file
echo '------------------------------------------------------'
echo -e "\033[31mError: BT-Panel service startup failed.\033[0m"
fi
echo -e " \033[32mdone\033[0m"
else
echo "Starting Bt-Panel... Bt-Panel (pid $(echo $isStart)) already running"
fi
isStart=$(ps aux |grep 'task.py'|grep -v grep|awk '{print $2}')
if [ "$isStart" == '' ];then
echo -e "Starting Bt-Tasks... \c"
nohup python task.py >> /www/server/panel/logs/task.log 2>&1 &
sleep 0.2
isStart=$(ps aux |grep 'task.py'|grep -v grep|awk '{print $2}')
if [ "$isStart" == '' ];then
echo -e "\033[31mfailed\033[0m"
echo '------------------------------------------------------'
tail -n 20 /www/server/panel/logs/task.log
echo '------------------------------------------------------'
echo -e "\033[31mError: BT-Task service startup failed.\033[0m"
return;
fi
echo -e " \033[32mdone\033[0m"
else
echo "Starting Bt-Tasks... Bt-Tasks (pid $isStart) already running"
fi
}
panel_port_check()
{
is_process=$(lsof -n -P -i:$port|grep LISTEN|grep -v grep|awk '{print $1}'|sort|uniq|xargs)
for pn in ${is_process[@]}
do
if [ "$pn" = "nginx" ];then
/etc/init.d/nginx restart
fi
if [ "$pn" = "httpd" ];then
/etc/init.d/httpd restart
fi
if [ "$pn" = "mysqld" ];then
/etc/init.d/mysqld restart
fi
if [ "$pn" = "superviso" ];then
pkill -9 superviso
sleep 0.2
supervisord -c /etc/supervisor/supervisord.conf
fi
if [ "$pn" = "pure-ftpd" ];then
/etc/init.d/pure-ftpd restart
fi
if [ "$pn" = "memcached" ];then
/etc/init.d/memcached restart
fi
if [ "$pn" = "sudo" ];then
if [ -f /etc/init.d/redis ];then
/etc/init.d/redis restart
fi
fi
if [ "$pn" = "php-fpm" ];then
php_v=(52 53 54 55 56 70 71 72 73 74);
for pv in ${php_v[@]};
do
if [ -f /etc/init.d/php-fpm-${pv} ];then
if [ -f /www/server/php/%{pv}/sbin/php-fpm ];then
if [ -f /tmp/php-cgi-${pv}.sock ];then
/etc/init.d/php-fpm-${pv} start
fi
/etc/init.d/php-fpm-${pv} restart
fi
fi
done
fi
done
is_ports=$(lsof -n -P -i:$port|grep LISTEN|grep -v grep|awk '{print $2}'|xargs)
if [ "$is_ports" != '' ];then
kill -9 $is_ports
sleep 1
fi
}
Web_Service_Check(){
if [ -f "/etc/init.d/nginx" ]; then
nginxV=$(cat /etc/init.d/nginx|grep /www/server/nginx)
if [ "${nginxV}" = "" ];then
Install_Check
fi
fi
panel_stop()
{
echo -e "Stopping Bt-Tasks...\c";
pids=$(ps aux | grep 'task.py'|grep -v grep|awk '{print $2}')
arr=($pids)
if [ -f "/etc/init.d/httpd" ]; then
httpdV=$(cat /etc/init.d/httpd|grep /www/server/apache)
if [ "${httpdV}" = "" ];then
Install_Check
fi
fi
for p in ${arr[@]}
do
kill -9 $p
done
echo -e " \033[32mdone\033[0m"
if [ -f "/etc/init.d/mysqld" ]; then
mysqlV=$(cat /etc/init.d/mysqld|grep /www/server/mysql)
if [ "${mysqlV}" = "" ];then
Install_Check
echo -e "Stopping Bt-Panel...\c";
arr=`ps aux|grep -E '(runserver|BT-Panel)'|grep -v grep|awk '{print $2}'`
for p in ${arr[@]}
do
kill -9 $p &>/dev/null
done
if [ -f $pidfile ];then
rm -f $pidfile
fi
echo -e " \033[32mdone\033[0m"
}
panel_status()
{
port=$(cat /www/server/panel/data/port.pl)
isStart=$(lsof -i:$port|grep LISTEN|grep -v grep|awk '{print $2}'|xargs)
if [ "$isStart" != '' ];then
echo -e "\033[32mBt-Panel (pid $(echo $isStart)) already running\033[0m"
else
echo -e "\033[31mBt-Panel not running\033[0m"
fi
isStart=$(ps aux |grep 'task.py'|grep -v grep|awk '{print $2}')
if [ "$isStart" != '' ];then
echo -e "\033[32mBt-Task (pid $isStart) already running\033[0m"
else
echo -e "\033[31mBt-Task not running\033[0m"
fi
}
panel_reload()
{
isStart=$(ps aux|grep 'runserver:app'|grep -v grep|awk '{print $2}')
if [ "$isStart" != '' ];then
kill -9 $isStart
sleep 0.5
fi
isStart=$(ps aux|grep 'BT-Panel'|grep -v grep|awk '{print $2}')
if [ "$isStart" != '' ];then
arr=`ps aux|grep 'BT-Panel'|grep -v grep|awk '{print $2}'`
for p in ${arr[@]}
do
kill -9 $p
done
rm -f $pidfile
panel_port_check
echo -e "Reload Bt-Panel.\c";
nohup $panel_path/BT-Panel >> $log_file 2>&1 &
isStart=""
n=0
while [[ "$isStart" == "" ]];
do
echo -e ".\c"
sleep 0.5
isStart=$(lsof -n -P -i:$port|grep LISTEN|grep -v grep|awk '{print $2}'|xargs)
let n+=1
if [ $n -gt 8 ];then
break;
fi
done
if [ "$isStart" == '' ];then
echo -e "\033[31mfailed\033[0m"
echo '------------------------------------------------------'
tail -n 20 $log_file
echo '------------------------------------------------------'
echo -e "\033[31mError: BT-Panel service startup failed.\033[0m"
return;
fi
echo -e " \033[32mdone\033[0m"
else
echo -e "\033[31mBt-Panel not running\033[0m"
panel_start
fi
}
Web_Service_Check
echo "
+----------------------------------------------------------------------
| aaPanel 6.0 FOR CentOS
+----------------------------------------------------------------------
| Copyright © 2015-2099 aaPanel(http://www.aapanel.com) All rights reserved.
+----------------------------------------------------------------------
| The WebPanel URL will be http://SERVER_IP:8888 when installed.
+----------------------------------------------------------------------
"
get_node_url(){
nodes=(http://183.235.223.101:3389 http://119.188.210.21:5880 http://125.88.182.172:5880 http://103.224.251.67 http://45.32.116.160 http://download.bt.cn);
i=1;
if [ ! -f /bin/curl ];then
if [ -f /usr/local/curl/bin/curl ];then
ln -sf /usr/local/curl/bin/curl /bin/curl
else
yum install curl -y
fi
fi
for node in ${nodes[@]};
do
start=`date +%s.%N`
result=`curl -sS --connect-timeout 3 -m 60 $node/check.txt`
if [ $result = 'True' ];then
end=`date +%s.%N`
start_s=`echo $start | cut -d '.' -f 1`
start_ns=`echo $start | cut -d '.' -f 2`
end_s=`echo $end | cut -d '.' -f 1`
end_ns=`echo $end | cut -d '.' -f 2`
time_micro=$(( (10#$end_s-10#$start_s)*1000000 + (10#$end_ns/1000 - 10#$start_ns/1000) ))
time_ms=$(($time_micro/1000))
values[$i]=$time_ms;
urls[$time_ms]=$node
i=$(($i+1))
fi
done
j=5000
for n in ${values[@]};
do
if [ $j -gt $n ];then
j=$n
fi
done
if [ $j = 5000 ];then
NODE_URL='http://download.bt.cn';
else
NODE_URL=${urls[$j]}
fi
}
echo '---------------------------------------------';
echo "Selected download node...";
get_node_url
download_Url=$NODE_URL
echo "Download node: $download_Url";
echo '---------------------------------------------';
setup_path=/www
port='8888'
if [ -f $setup_path/server/panel/data/port.pl ];then
port=`cat $setup_path/server/panel/data/port.pl`
fi
while [ "$go" != 'y' ] && [ "$go" != 'n' ]
do
read -p "Do you want to install aaPanel to the $setup_path directory now?(y/n): " go;
done
if [ "$go" == 'n' ];then
exit;
fi
path=/etc/yum.conf
isExc=`cat $path|grep httpd`
if [ "$isExc" = "" ];then
echo "exclude=httpd nginx php mysql mairadb python-psutil python2-psutil" >> $path
fi
#自动挂载Swap
autoSwap()
install_used()
{
swap=`free |grep Swap|awk '{print $2}'`
if [ $swap -gt 1 ];then
echo "Swap total sizse: $swap";
return;
fi
if [ ! -d /www ];then
mkdir /www
fi
swapFile='/www/swap'
dd if=/dev/zero of=$swapFile bs=1M count=1025
mkswap -f $swapFile
swapon $swapFile
echo "$swapFile swap swap defaults 0 0" >> /etc/fstab
swap=`free |grep Swap|awk '{print $2}'`
if [ $swap -gt 1 ];then
echo "Swap total sizse: $swap";
return;
fi
sed -i "/\/www\/swap/d" /etc/fstab
rm -f $swapFile
if [ ! -f $panel_path/aliyun.pl ];then
return;
fi
password=$(cat /dev/urandom | head -n 16 | md5sum | head -c 12)
username=$($pythonV $panel_path/tools.py panel $password)
echo "$password" > $panel_path/default.pl
rm -f $panel_path/aliyun.pl
}
autoSwap
#判断kernel-headers组件是否安装
rpm -qa | grep kernel-headers > kernel-headers.pl
kernelStatus=`cat kernel-headers.pl`
#判断华为云
huaweiLogin=`cat /etc/motd |grep 4000-955-988`
huaweiSys=`cat /etc/redhat-release | grep ' 7.'`
if [ "$kernelStatus" = "" ]; then
if [ "$huaweiLogin" != "" ] && [ "$huaweiSys" != "" ]; then
wget $download_Url/src/kernel-headers-3.10.0-514.el7.x86_64.rpm
rpm -ivh kernel-headers-3.10.0-514.el7.x86_64.rpm
rm -f kernel-headers-3.10.0-514.el7.x86_64.rpm
else
yum install kernel-headers -y
fi
fi
rm -f kernel-headers.pl
#try sync time from bt.cn
echo 'Synchronizing system time...'
v1=$(curl http://www.bt.cn/api/index/get_time)
date -s "$(date -d @$v1 +"%Y-%m-%d %H:%M:%S")"
yum install ntp chrony -y
systemctl restart chrony
timedatectl set-ntp 1
#rm -rf /etc/localtime
#ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
#echo 'Synchronizing system time...'
ntpdate 0.asia.pool.ntp.org
startTime=`date +%s`
setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
for pace in python-devel python-imaging zip unzip openssl openssl-devel gcc libxml2 libxml2-devel libxslt* zlib zlib-devel libjpeg-devel libpng-devel libwebp libwebp-devel freetype freetype-devel lsof pcre pcre-devel vixie-cron crontabs icu libicu-devel c-ares;
do
yum -y install ${pace};
done
if [ -f "/usr/bin/dnf" ]; then
dnf install -y redhat-rpm-config
fi
yum install python-devel -y
py26=$(python -V 2>&1|grep '2.6.')
if [ "$py26" != "" ];then
if [ ! -f /etc/yum.repos.d/epel.repo ];then
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
fi
if [ ! -f /usr/bin/python3 ];then
yum install python34 python34-devel -y
if [ ! -f /usr/bin/python3 ];then
echo "python3.4 install error!"
exit 0;
fi
isSed=$(cat /usr/bin/yum|grep /usr/bin/python2.6)
if [ "$isSed" == "" ];then
sed -i "s#/usr/bin/python#/usr/bin/python2.6#" /usr/bin/yum
fi
#rm -f /usr/bin/python2
mv -f /usr/bin/python /usr/bin/python2_backup
ln -sf /usr/bin/python3 /usr/bin/python
fi
if [ ! -f /usr/bin/pip3 ];then
wget --no-check-certificate https://bootstrap.pypa.io/get-pip.py
python3 get-pip.py
mv -f /usr/bin/pip /usr/bin/pip_backup
ln -sf /usr/bin/pip3.4 /usr/bin/pip
fi
fi
tmp=`python -V 2>&1|awk '{print $2}'`
pVersion=${tmp:0:3}
Install_setuptools()
error_logs()
{
if [ ! -f "/usr/bin/easy_install" ];then
wget -O setuptools-33.1.1.zip $download_Url/install/src/setuptools-33.1.1.zip -T 10
unzip setuptools-33.1.1.zip
rm -f setuptools-33.1.1.zip
cd setuptools-33.1.1
python setup.py install
cd ..
rm -rf setuptools-33.1.1
fi
if [ ! -f "/usr/bin/easy_install" ];then
echo '=================================================';
echo -e "\033[31msetuptools installation failed. \033[0m";
exit;
fi
}
Install_pip()
{
ispip=`pip -V |grep from`
if [ "$ispip" == "" ];then
if [ ! -f "/usr/bin/easy_install" ];then
Install_setuptools
fi
wget -O pip-9.0.1.tar.gz $download_Url/install/src/pip-9.0.1.tar.gz -T 10
tar xvf pip-9.0.1.tar.gz
rm -f pip-9.0.1.tar.gz
cd pip-9.0.1
python setup.py install
cd ..
rm -rf pip-9.0.1
fi
ispip=`pip -V |grep from`
if [ "$ispip" = "" ];then
echo '=================================================';
echo -e "\033[31m Python-pip installation failed. \033[0m";
exit;
fi
pip install -U pip
}
Install_Pillow()
{
isSetup=`python -m PIL 2>&1|grep package`
if [ "$isSetup" = "" ];then
isFedora = `cat /etc/redhat-release |grep Fedora`
if [ "$isFedora" != "" ];then
pip install Pillow
return;
fi
wget -O Pillow-3.2.0.zip $download_Url/install/src/Pillow-3.2.0.zip -T 10
unzip Pillow-3.2.0.zip
rm -f Pillow-3.2.0.zip
cd Pillow-3.2.0
python setup.py install
cd ..
rm -rf Pillow-3.2.0
fi
isSetup=`python -m PIL 2>&1|grep package`
if [ "$isSetup" = "" ];then
echo '=================================================';
echo -e "\033[31mPillow installation failed. \033[0m";
exit;
fi
}
Install_psutil()
{
isSetup=`python -m psutil 2>&1|grep package`
if [ "$isSetup" = "" ];then
wget -O psutil-5.2.2.tar.gz $download_Url/install/src/psutil-5.2.2.tar.gz -T 10
tar xvf psutil-5.2.2.tar.gz
rm -f psutil-5.2.2.tar.gz
cd psutil-5.2.2
python setup.py install
cd ..
rm -rf psutil-5.2.2
fi
isSetup=`python -m psutil 2>&1|grep package`
if [ "$isSetup" = "" ];then
echo '=================================================';
echo -e "\033[31mpsutil installation failed. \033[0m";
exit;
fi
}
Install_mysqldb()
{
isSetup=`python -m MySQLdb 2>&1|grep package`
if [ "$isSetup" = "" ];then
wget -O MySQL-python-1.2.5.zip $download_Url/install/src/MySQL-python-1.2.5.zip -T 10
unzip MySQL-python-1.2.5.zip
rm -f MySQL-python-1.2.5.zip
cd MySQL-python-1.2.5
python setup.py install
cd ..
rm -rf MySQL-python-1.2.5
fi
}
Install_chardet()
{
isSetup=`python -m chardet 2>&1|grep package`
if [ "$isSetup" = "" ];then
wget -O chardet-2.3.0.tar.gz $download_Url/install/src/chardet-2.3.0.tar.gz -T 10
tar xvf chardet-2.3.0.tar.gz
rm -f chardet-2.3.0.tar.gz
cd chardet-2.3.0
python setup.py install
cd ..
rm -rf chardet-2.3.0
fi
isSetup=`python -m chardet 2>&1|grep package`
if [ "$isSetup" = "" ];then
echo '=================================================';
echo -e "\033[31mchardet installation failed. \033[0m";
exit;
fi
tail -n 100 $log_file
}
Install_setuptools
Install_pip
curl -Ss --connect-timeout 3 -m 60 http://download.bt.cn/install/pip_select.sh|bash
isPsutil=`python -m psutil 2>&1|grep package`
if [ "$isPsutil" != "" ];then
psutil_version=`python -c 'import psutil;print psutil.__version__;' |grep '5.'`
if [ "$psutil_version" = '' ];then
pip uninstall psutil -y
fi
fi
yum install libffi-devel -y
pip install --upgrade setuptools
pip install -U pip
pip install six --upgrade --ignore-installed six
pip install itsdangerous==0.24
pip install paramiko==2.0.2
pip install flask-socketio==3.0.2
pip install python-socketio==2.1.2
pip install Werkzeug==0.15.1
pip install Pillow==5.4.1
pip install -I requests==2.20
for p_name in psutil chardet virtualenv Flask Flask-Session Flask-SocketIO flask-sqlalchemy Pillow gunicorn gevent-websocket pyopenssl cryptography;
do
pip install ${p_name}
done
is_gevent=$(pip list|grep gevent)
if [ "$is_gevent" = "" ];then
if [ -f /usr/bin/yum ];then
yum install python-gevent -y
else
apt install python-gevent -y
fi
fi
pip install psutil chardet virtualenv Flask Flask-Session Flask-SocketIO flask-sqlalchemy Pillow gunicorn gevent-websocket paramiko requests pyopenssl cryptography
Install_Pillow
Install_psutil
pip install gunicorn
if [ -f /www/server/mysql/bin/mysql ]; then
pip install mysql-python
Install_mysqldb
fi
Install_chardet
mkdir -p $setup_path/server/panel/logs
mkdir -p $setup_path/server/panel/vhost/apache
mkdir -p $setup_path/server/panel/vhost/nginx
mkdir -p $setup_path/server/panel/vhost/rewrite
case "$1" in
'start')
install_used
panel_start
;;
'stop')
panel_stop
;;
'restart')
panel_stop
sleep 1
panel_start
;;
'reload')
panel_reload
;;
'status')
panel_status
;;
'logs')
error_logs
;;
'panel')
python $panel_path/tools.py cli $2
;;
'default')
port=$(cat $panel_path/data/port.pl)
password=$(cat $panel_path/default.pl)
if [ -f $panel_path/data/domain.conf ];then
address=$(cat $panel_path/data/domain.conf)
fi
if [ -f $panel_path/data/admin_path.pl ];then
auth_path=$(cat $panel_path/data/admin_path.pl)
fi
if [ "$address" = "" ];then
address=$(curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/getIpAddress)
fi
pool=http
if [ -f $panel_path/data/ssl.pl ];then
pool=https
fi
echo -e "=================================================================="
echo -e "\033[32maaPanel default info!\033[0m"
echo -e "=================================================================="
echo "Bt-Panel-URL: $pool://$address:$port$auth_path"
echo -e `python $panel_path/tools.py username`
echo -e "password: $password"
echo -e "\033[33mWarning:\033[0m"
echo -e "\033[33mIf you cannot access the panel, \033[0m"
echo -e "\033[33mrelease the following port (8888|888|80|443|20|21) in the security group\033[0m"
echo -e "=================================================================="
;;
*)
python $panel_path/tools.py cli $1
;;
esac
if [ -f '/etc/init.d/bt' ];then
/etc/init.d/bt stop
fi
mkdir -p /www/server
mkdir -p /www/wwwroot
mkdir -p /www/wwwlogs
mkdir -p /www/backup/database
mkdir -p /www/backup/site
if [ ! -f "/usr/bin/unzip" ];then
#rm -f /etc/yum.repos.d/epel.repo
yum install unzip -y
fi
wget -O panel.zip $download_Url/install/src/panel6_en.zip -T 10
wget -O /etc/init.d/bt $download_Url/install/src/bt6_en.init -T 10
if [ -f "$setup_path/server/panel/data/default.db" ];then
if [ -d "/$setup_path/server/panel/old_data" ];then
rm -rf $setup_path/server/panel/old_data
fi
mkdir -p $setup_path/server/panel/old_data
mv -f $setup_path/server/panel/data/default.db $setup_path/server/panel/old_data/default.db
mv -f $setup_path/server/panel/data/system.db $setup_path/server/panel/old_data/system.db
mv -f $setup_path/server/panel/data/port.pl $setup_path/server/panel/old_data/port.pl
mv -f $setup_path/server/panel/data/admin_path.pl $setup_path/server/panel/old_data/admin_path.pl
fi
unzip -o panel.zip -d $setup_path/server/ > /dev/null
if [ -d "$setup_path/server/panel/old_data" ];then
mv -f $setup_path/server/panel/old_data/default.db $setup_path/server/panel/data/default.db
mv -f $setup_path/server/panel/old_data/system.db $setup_path/server/panel/data/system.db
mv -f $setup_path/server/panel/old_data/port.pl $setup_path/server/panel/data/port.pl
mv -f $setup_path/server/panel/old_data/admin_path.pl $setup_path/server/panel/data/admin_path.pl
if [ -d "/$setup_path/server/panel/old_data" ];then
rm -rf $setup_path/server/panel/old_data
fi
fi
rm -f panel.zip
if [ ! -f $setup_path/server/panel/tools.py ];then
echo -e "\033[31mERROR: Failed to download, please try again!\033[0m";
echo '============================================'
exit;
fi
rm -f $setup_path/server/panel/class/*.pyc
rm -f $setup_path/server/panel/*.pyc
chmod +x /etc/init.d/bt
chkconfig --add bt
chkconfig --level 2345 bt on
chmod -R 600 $setup_path/server/panel
chmod -R +x $setup_path/server/panel/script
chmod 655 $setup_path/server/panel
chmod 655 $setup_path/server/panel/data
chmod 655 $setup_path/server/panel/data/empty.html
ln -sf /etc/init.d/bt /usr/bin/bt
echo "$port" > $setup_path/server/panel/data/port.pl
/etc/init.d/bt start
password=`cat /dev/urandom | head -n 16 | md5sum | head -c 8`
sleep 1
admin_auth='/www/server/panel/data/admin_path.pl'
if [ ! -f $admin_auth ];then
auth_path=`cat /dev/urandom | head -n 16 | md5sum | head -c 8`
echo "/$auth_path" > $admin_auth
fi
auth_path=`cat $admin_auth`
cd $setup_path/server/panel/
python -m py_compile tools.py
python tools.py username
username=`python tools.py panel $password`
cd ~
echo "$password" > $setup_path/server/panel/default.pl
chmod 600 $setup_path/server/panel/default.pl
/etc/init.d/bt restart
sleep 3
isStart=`ps aux |grep 'gunicorn'|grep -v grep|awk '{print $2}'`
if [ "$isStart" == '' ];then
echo -e "\033[31mERROR: The aaPanel service startup failed.\033[0m";
echo '============================================'
exit;
fi
if [ -f "/etc/init.d/iptables" ];then
sshPort=`cat /etc/ssh/sshd_config | grep 'Port ' | grep -oE [0-9] | tr -d '\n'`
if [ "${sshPort}" != "22" ]; then
iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport $sshPort -j ACCEPT
fi
iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 20 -j ACCEPT
iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 21 -j ACCEPT
iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport $port -j ACCEPT
iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 39000:40000 -j ACCEPT
#iptables -I INPUT -p tcp -m state --state NEW -m udp --dport 39000:40000 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type any -j ACCEPT
iptables -A INPUT -s localhost -d localhost -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -P INPUT DROP
service iptables save
sed -i "s#IPTABLES_MODULES=\"\"#IPTABLES_MODULES=\"ip_conntrack_netbios_ns ip_conntrack_ftp ip_nat_ftp\"#" /etc/sysconfig/iptables-config
iptables_status=`service iptables status | grep 'not running'`
if [ "${iptables_status}" == '' ];then
service iptables restart
fi
fi
if [ "${isVersion}" == '' ];then
if [ ! -f "/etc/init.d/iptables" ];then
sshPort=`cat /etc/ssh/sshd_config | grep 'Port ' | grep -oE [0-9] | tr -d '\n'`
yum install firewalld -y
systemctl enable firewalld
systemctl start firewalld
firewall-cmd --set-default-zone=public > /dev/null 2>&1
if [ "${sshPort}" != "22" ]; then
firewall-cmd --permanent --zone=public --add-port=$sshPort/tcp > /dev/null 2>&1
fi
firewall-cmd --permanent --zone=public --add-port=20/tcp > /dev/null 2>&1
firewall-cmd --permanent --zone=public --add-port=21/tcp > /dev/null 2>&1
firewall-cmd --permanent --zone=public --add-port=22/tcp > /dev/null 2>&1
firewall-cmd --permanent --zone=public --add-port=80/tcp > /dev/null 2>&1
firewall-cmd --permanent --zone=public --add-port=$port/tcp > /dev/null 2>&1
firewall-cmd --permanent --zone=public --add-port=39000-40000/tcp > /dev/null 2>&1
#firewall-cmd --permanent --zone=public --add-port=39000-40000/udp > /dev/null 2>&1
firewall-cmd --reload
fi
fi
pip install psutil chardet psutil virtualenv cryptography==2.1 > /dev/null 2>&1
if [ ! -d '/etc/letsencrypt' ];then
yum install epel-release -y
if [ "${country}" = "CN" ]; then
isC7=`cat /etc/redhat-release |grep ' 7.'`
if [ "${isC7}" == "" ];then
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo
else
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
fi
fi
mkdir -p /var/spool/cron
if [ ! -f '/var/spool/cron/root' ];then
echo '' > /var/spool/cron/root
chmod 600 /var/spool/cron/root
fi
fi
wget -O acme_install.sh $download_Url/install/acme_install.sh
nohup bash acme_install.sh &> /dev/null &
sleep 1
rm -f acme_install.sh
address=""
address=`curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/getIpAddress`
if [ "$address" == '0.0.0.0' ] || [ "$address" == '' ];then
isHosts=`cat /etc/hosts|grep 'www.bt.cn'`
if [ "$isHosts" == '' ];then
echo "" >> /etc/hosts
echo "125.88.182.170 www.bt.cn" >> /etc/hosts
address=`curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/getIpAddress`
if [ "$address" == '' ];then
sed -i "/bt.cn/d" /etc/hosts
fi
fi
fi
ipCheck=`python -c "import re; print(re.match('^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$','$address'))"`
if [ "$ipCheck" == "None" ];then
address="SERVER_IP"
fi
if [ "$address" != "SERVER_IP" ];then
echo "$address" > $setup_path/server/panel/data/iplist.txt
fi
curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/SetupCount?type=Linux\&o=EN > /dev/null 2>&1
curl -sS --connect-timeout 10 -m 60 https://www.aapanel.com/Api/SetupCount?type=Linux > /dev/null 2>&1
if [ "$1" != "" ];then
echo $1 > /www/server/panel/data/o.pl
cd /www/server/panel
python tools.py o
fi
echo /www > /var/bt_setupPath.conf
/etc/init.d/bt start
echo -e "=================================================================="
echo -e "\033[32mCongratulations! Installed successfully!\033[0m"
echo -e "=================================================================="
echo "aaPanel: http://$address:$port$auth_path"
echo -e "username: $username"
echo -e "password: $password"
echo -e "\033[33mWarning:\033[0m"
echo -e "\033[33mIf you cannot access the panel, \033[0m"
echo -e "\033[33mrelease the following port (8888|888|80|443|20|21) in the security group\033[0m"
echo -e "=================================================================="
endTime=`date +%s`
((outTime=($endTime-$startTime)/60))
echo -e "Time consumed:\033[32m $outTime \033[0mMinute!"
rm -f install.sh
+2 -1
View File
@@ -2,6 +2,7 @@ Flask>=1.0.2
paramiko>=2.6.0
flask-socketio>=4.1.0
python-socketio>=4.2.0
flask_sockets>=0.2.1
Werkzeug>=0.15.1
Pillow==5.4.1
requests>=2.20
@@ -14,4 +15,4 @@ gunicorn>=18.0
gevent-websocket>=0.10.1
pyopenssl>=19.0
cryptography>=2.7
six>=1.12.0
six>=1.12.0
+10
View File
@@ -0,0 +1,10 @@
RewriteEngine On
RewriteBase /
RewriteRule ^([0-9]+).([0-9]+)/$ e/action/ShowInfo.php?classid=$1&id=$2 [L]
RewriteRule ^([0-9]+).([0-9]+)$ $1.$2/ [L,R=301]
RewriteRule ^([0-9]+)/$ e/action/ListInfo/?classid=$1 [L]
RewriteRule ^([0-9]+)$ $1/ [L,R=301]
RewriteRule ^list([0-9]+).([0-9]+)/$ e/action/ListInfo/index.php?page=$1&classid=$2 [L]
RewriteRule ^list([0-9]+).([0-9]+)$ list$1.$2/ [L,R=301]
RewriteRule^archive([0-9]+).([0-9]+)-([0-9]+)-([0-9]+)/$e/action/ListInfo.php?classid=$1&mid=1&tempid=9&starttime=$2-$3-$4&endtime=$2-$3-$4 [L]
RewriteRule^archive([0-9]+).([0-9]+)-([0-9]+)-([0-9]+)$^archive([0-9]+).([0-9]+)-([0-9]+)-([0-9]+)/ [L,R=301]
+13
View File
@@ -0,0 +1,13 @@
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)/question-id-([0-9]+)\.html$ $1/question\.php\?id=$2
RewriteRule ^(.*)/browser-tid-([0-9]+)\.html$ $1/browser\.php\?tid=$2
RewriteRule ^(.*)/browser-tid2-([0-9]+)\.html$ $1/browser\.php\?tid2=$2
RewriteRule ^(.*)/browser-lm-([0-9]+)\.html$ $1/browser\.php\?lm=$2
RewriteRule ^(.*)/browser-tid-([0-9]+)-lm-([0-9]+)\.html$ $1/browser\.php\?tid=$2&lm=$3
RewriteRule ^(.*)/browser-tid2-([0-9]+)-lm-([0-9]+)\.html$ $1/browser\.php\?tid2=$2&lm=$3
RewriteRule ^(.*)index\.html$ $1/index.php
RewriteRule ^(.*)list-([0-9]+)\.html$ $1/plus/list.php?tid=$2
RewriteRule ^(.*)list-([0-9]+)-([0-9]+)\.html$ $1/plus/list.php?typeid=$2&PageNo=$3
RewriteRule ^(.*)view-([0-9]+).html$ $1/plus/view.php?aid=$2
RewriteRule ^(.*)view-([0-9]+)-([0-9]+).html$ $1/plus/view.php?aid=$2&pageno=$3
+1
View File
@@ -0,0 +1 @@
+16
View File
@@ -0,0 +1,16 @@
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^topic-(.+)\.html$ portal.php?mod=topic&topic=$1&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^article-([0-9]+)-([0-9]+)\.html$ portal.php?mod=view&aid=$1&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^forum-(\w+)-([0-9]+)\.html$ forum.php?mod=forumdisplay&fid=$1&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ forum.php?mod=viewthread&tid=$1&extra=page\%3D$3&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^group-([0-9]+)-([0-9]+)\.html$ forum.php?mod=group&fid=$1&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^space-(username|uid)-(.+)\.html$ home.php?mod=space&$1=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^([a-z]+)-(.+)\.html$ $1.php?rewrite=$2&%1
+20
View File
@@ -0,0 +1,20 @@
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^topic-(.+)\.html$ portal.php?mod=topic&topic=$1&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^article-([0-9]+)-([0-9]+)\.html$ portal.php?mod=view&aid=$1&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^forum-(\w+)-([0-9]+)\.html$ forum.php?mod=forumdisplay&fid=$1&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ forum.php?mod=viewthread&tid=$1&extra=page\%3D$3&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^group-([0-9]+)-([0-9]+)\.html$ forum.php?mod=group&fid=$1&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^space-(username|uid)-(.+)\.html$ home.php?mod=space&$1=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^blog-([0-9]+)-([0-9]+)\.html$ home.php?mod=space&uid=$1&do=blog&id=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^archiver/(fid|tid)-([0-9]+)\.html$ archiver/index.php?action=$1&value=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^([a-z]+[a-z0-9_]*)-([a-z0-9_\-]+)\.html$ plugin.php?id=$1:$2&%1
+20
View File
@@ -0,0 +1,20 @@
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^topic-(.+)\.html$ portal.php?mod=topic&topic=$1&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^article-([0-9]+)-([0-9]+)\.html$ portal.php?mod=view&aid=$1&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^forum-(\w+)-([0-9]+)\.html$ forum.php?mod=forumdisplay&fid=$1&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ forum.php?mod=viewthread&tid=$1&extra=page\%3D$3&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^group-([0-9]+)-([0-9]+)\.html$ forum.php?mod=group&fid=$1&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^space-(username|uid)-(.+)\.html$ home.php?mod=space&$1=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^blog-([0-9]+)-([0-9]+)\.html$ home.php?mod=space&uid=$1&do=blog&id=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^archiver/(fid|tid)-([0-9]+)\.html$ archiver/index.php?action=$1&value=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^([a-z]+[a-z0-9_]*)-([a-z0-9_\-]+)\.html$ plugin.php?id=$1:$2&%1
+28
View File
@@ -0,0 +1,28 @@
RewriteEngine On
RewriteBase /
# direct one-word access
RewriteRule ^index\.html$ index\.php [L]
RewriteRule ^category$ index\.php [L]
# access any object by its numeric identifier
RewriteRule ^feed-c([0-9]+)\.xml$ feed\.php\?cat=$1 [L]
RewriteRule ^feed-b([0-9]+)\.xml$ feed\.php\?brand=$1 [L]
RewriteRule ^feed\.xml$ feed\.php [L]
RewriteRule ^category-([0-9]+)-b([0-9]+)-min([0-9]+)-max([0-9]+)-attr([^-]*)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$ category\.php\?id=$1&brand=$2&price_min=$3&price_max=$4&filter_attr=$5&page=$6&sort=$7&order=$8 [QSA,L]
RewriteRule ^category-([0-9]+)-b([0-9]+)-min([0-9]+)-max([0-9]+)-attr([^-]*)(.*)\.html$ category\.php\?id=$1&brand=$2&price_min=$3&price_max=$4&filter_attr=$5 [QSA,L]
RewriteRule ^category-([0-9]+)-b([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$ category\.php\?id=$1&brand=$2&page=$3&sort=$4&order=$5 [QSA,L]
RewriteRule ^category-([0-9]+)-b([0-9]+)-([0-9]+)(.*)\.html$ category\.php\?id=$1&brand=$2&page=$3 [QSA,L]
RewriteRule ^category-([0-9]+)-b([0-9]+)(.*)\.html$ category\.php\?id=$1&brand=$2 [QSA,L]
RewriteRule ^category-([0-9]+)(.*)\.html$ category\.php\?id=$1 [QSA,L]
RewriteRule ^goods-([0-9]+)(.*)\.html$ goods\.php\?id=$1 [QSA,L]
RewriteRule ^article_cat-([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$ article_cat\.php\?id=$1&page=$2&sort=$3&order=$4 [QSA,L]
RewriteRule ^article_cat-([0-9]+)-([0-9]+)(.*)\.html$ article_cat\.php\?id=$1&page=$2 [QSA,L]
RewriteRule ^article_cat-([0-9]+)(.*)\.html$ article_cat\.php\?id=$1 [QSA,L]
RewriteRule ^article-([0-9]+)(.*)\.html$ article\.php\?id=$1 [QSA,L]
RewriteRule ^brand-([0-9]+)-c([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)\.html brand\.php\?id=$1&cat=$2&page=$3&sort=$4&order=$5 [QSA,L]
RewriteRule ^brand-([0-9]+)-c([0-9]+)-([0-9]+)(.*)\.html brand\.php\?id=$1&cat=$2&page=$3 [QSA,L]
RewriteRule ^brand-([0-9]+)-c([0-9]+)(.*)\.html brand\.php\?id=$1&cat=$2 [QSA,L]
RewriteRule ^brand-([0-9]+)(.*)\.html brand\.php\?id=$1 [QSA,L]
RewriteRule ^tag-(.*)\.html search\.php\?keywords=$1 [QSA,L]
RewriteRule ^snatch-([0-9]+)\.html$ snatch\.php\?id=$1 [QSA,L]
RewriteRule ^group_buy-([0-9]+)\.html$ group_buy\.php\?act=view&id=$1 [QSA,L]
RewriteRule ^auction-([0-9]+)\.html$ auction\.php\?act=view&id=$1 [QSA,L]
+1
View File
@@ -0,0 +1 @@
default,discuzx,discuzx2,discuzx3,dedecms,ecshop,phpcms,thinkphp,wordpress,phpwind,mvc,EmpireCMS
+7
View File
@@ -0,0 +1,7 @@
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>
+5
View File
@@ -0,0 +1,5 @@
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)content-([0-9]+)-([0-9]+)-([0-9]+)\.html$ $1/index\.php\?m=content&c=index&a=show&catid=$2&id=$3&page=$4
RewriteRule ^(.*)show-([0-9]+)-([0-9]+)-([0-9]+).html$ $1/index\.php\?m=content&c=index&a=show&catid=$2&id=$3&page=$4
RewriteRule ^(.*)list-([0-9]+)-([0-9]+).html$ $1/index\.php\?m=content&c=index&a=lists&catid=$2&page=$3
+7
View File
@@ -0,0 +1,7 @@
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule !.(js|ico|gif|jpe?g|bmp|png|css)$ /index.php [NC,L]
+7
View File
@@ -0,0 +1,7 @@
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?s=/$1 [QSA,PT,L]
</IfModule>
+8
View File
@@ -0,0 +1,8 @@
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
+7
View File
@@ -0,0 +1,7 @@
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
View File
+8
View File
@@ -0,0 +1,8 @@
rewrite ^([^\.]*)/listinfo-(.+?)-(.+?)\.html$ $1/e/action/ListInfo/index.php?classid=$2&page=$3 last;
rewrite ^([^\.]*)/showinfo-(.+?)-(.+?)-(.+?)\.html$ $1/e/action/ShowInfo.php?classid=$2&id=$3&page=$4 last;
rewrite ^([^\.]*)/infotype-(.+?)-(.+?)\.html$ $1/e/action/InfoType/index.php?ttid=$2&page=$3 last;
rewrite ^([^\.]*)/tags-(.+?)-(.+?)\.html$ $1/e/tags/index.php?tagname=$2&page=$3 last;
rewrite ^([^\.]*)/comment-(.+?)-(.+?)-(.+?)-(.+?)-(.+?)-(.+?)\.html$ $1/e/pl/index\.php\?doaction=$2&classid=$3&id=$4&page=$5&myorder=$6&tempid=$7 last;
if (!-e $request_filename) {
return 404;
}
+5
View File
@@ -0,0 +1,5 @@
location / {
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php?q=$1 last;
}
}
+7
View File
@@ -0,0 +1,7 @@
location /{
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.htaccess{
deny all;
}
+10
View File
@@ -0,0 +1,10 @@
rewrite "^/list-([0-9]+)\.html$" /plus/list.php?tid=$1 last;
rewrite "^/list-([0-9]+)-([0-9]+)-([0-9]+)\.html$" /plus/list.php?tid=$1&totalresult=$2&PageNo=$3 last;
rewrite "^/view-([0-9]+)-1\.html$" /plus/view.php?arcID=$1 last;
rewrite "^/view-([0-9]+)-([0-9]+)\.html$" /plus/view.php?aid=$1&pageno=$2 last;
rewrite "^/plus/list-([0-9]+)\.html$" /plus/list.php?tid=$1 last;
rewrite "^/plus/list-([0-9]+)-([0-9]+)-([0-9]+)\.html$" /plus/list.php?tid=$1&totalresult=$2&PageNo=$3 last;
rewrite "^/plus/view-([0-9]+)-1\.html$" /plus/view.php?arcID=$1 last;
rewrite "^/plus/view-([0-9]+)-([0-9]+)\.html$" /plus/view.php?aid=$1&pageno=$2 last;
rewrite "^/tags.html$" /tags.php last;
rewrite "^/tag-([0-9]+)-([0-9]+)\.html$" /tags.php?/$1/$2/ last;
+1
View File
@@ -0,0 +1 @@
+7
View File
@@ -0,0 +1,7 @@
location / {
rewrite ^/archiver/((fid|tid)-[\w\-]+\.html)$ /archiver/index.php?$1 last;
rewrite ^/forum-([0-9]+)-([0-9]+)\.html$ /forumdisplay.php?fid=$1&page=$2 last;
rewrite ^/thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /viewthread.php?tid=$1&extra=page%3D$3&page=$2 last;
rewrite ^/space-(username|uid)-(.+)\.html$ /space.php?$1=$2 last;
rewrite ^/tag-(.+)\.html$ /tag.php?name=$1 last;
}
+12
View File
@@ -0,0 +1,12 @@
rewrite ^([^\.]*)/topic-(.+)\.html$ $1/portal.php?mod=topic&topic=$2 last;
rewrite ^([^\.]*)/article-([0-9]+)-([0-9]+)\.html$ $1/portal.php?mod=view&aid=$2&page=$3 last;
rewrite ^([^\.]*)/forum-(\w+)-([0-9]+)\.html$ $1/forum.php?mod=forumdisplay&fid=$2&page=$3 last;
rewrite ^([^\.]*)/thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ $1/forum.php?mod=viewthread&tid=$2&extra=page%3D$4&page=$3 last;
rewrite ^([^\.]*)/group-([0-9]+)-([0-9]+)\.html$ $1/forum.php?mod=group&fid=$2&page=$3 last;
rewrite ^([^\.]*)/space-(username|uid)-(.+)\.html$ $1/home.php?mod=space&$2=$3 last;
rewrite ^([^\.]*)/blog-([0-9]+)-([0-9]+)\.html$ $1/home.php?mod=space&uid=$2&do=blog&id=$3 last;
rewrite ^([^\.]*)/(fid|tid)-([0-9]+)\.html$ $1/index.php?action=$2&value=$3 last;
rewrite ^([^\.]*)/([a-z]+[a-z0-9_]*)-([a-z0-9_\-]+)\.html$ $1/plugin.php?id=$2:$3 last;
if (!-e $request_filename) {
return 404;
}
+14
View File
@@ -0,0 +1,14 @@
location /bbs/ {
rewrite ^([^\.]*)/topic-(.+)\.html$ $1/portal.php?mod=topic&topic=$2 last;
rewrite ^([^\.]*)/article-([0-9]+)-([0-9]+)\.html$ $1/portal.php?mod=view&aid=$2&page=$3 last;
rewrite ^([^\.]*)/forum-(\w+)-([0-9]+)\.html$ $1/forum.php?mod=forumdisplay&fid=$2&page=$3 last;
rewrite ^([^\.]*)/thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ $1/forum.php?mod=viewthread&tid=$2&extra=page%3D$4&page=$3 last;
rewrite ^([^\.]*)/group-([0-9]+)-([0-9]+)\.html$ $1/forum.php?mod=group&fid=$2&page=$3 last;
rewrite ^([^\.]*)/space-(username|uid)-(.+)\.html$ $1/home.php?mod=space&$2=$3 last;
rewrite ^([^\.]*)/blog-([0-9]+)-([0-9]+)\.html$ $1/home.php?mod=space&uid=$2&do=blog&id=$3 last;
rewrite ^([^\.]*)/(fid|tid)-([0-9]+)\.html$ $1/index.php?action=$2&value=$3 last;
rewrite ^([^\.]*)/([a-z]+[a-z0-9_]*)-([a-z0-9_\-]+)\.html$ $1/plugin.php?id=$2:$3 last;
if (!-e $request_filename) {
return 404;
}
}
+15
View File
@@ -0,0 +1,15 @@
location / {
rewrite ^([^\.]*)/topic-(.+)\.html$ $1/portal.php?mod=topic&topic=$2 last;
rewrite ^([^\.]*)/article-([0-9]+)-([0-9]+)\.html$ $1/portal.php?mod=view&aid=$2&page=$3 last;
rewrite ^([^\.]*)/forum-(\w+)-([0-9]+)\.html$ $1/forum.php?mod=forumdisplay&fid=$2&page=$3 last;
rewrite ^([^\.]*)/thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ $1/forum.php?mod=viewthread&tid=$2&extra=page%3D$4&page=$3 last;
rewrite ^([^\.]*)/group-([0-9]+)-([0-9]+)\.html$ $1/forum.php?mod=group&fid=$2&page=$3 last;
rewrite ^([^\.]*)/space-(username|uid)-(.+)\.html$ $1/home.php?mod=space&$2=$3 last;
rewrite ^([^\.]*)/blog-([0-9]+)-([0-9]+)\.html$ $1/home.php?mod=space&uid=$2&do=blog&id=$3 last;
rewrite ^([^\.]*)/(fid|tid)-([0-9]+)\.html$ $1/index.php?action=$2&value=$3 last;
rewrite ^([^\.]*)/([a-z]+[a-z0-9_]*)-([a-z0-9_\-]+)\.html$ $1/plugin.php?id=$2:$3 last;
if (!-e $request_filename) {
return 404;
}
}
+3
View File
@@ -0,0 +1,3 @@
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php?q=$1 last;
}
+32
View File
@@ -0,0 +1,32 @@
if (!-e $request_filename)
{
rewrite "^/index\.html" /index.php last;
rewrite "^/category$" /index.php last;
rewrite "^/feed-c([0-9]+)\.xml$" /feed.php?cat=$1 last;
rewrite "^/feed-b([0-9]+)\.xml$" /feed.php?brand=$1 last;
rewrite "^/feed\.xml$" /feed.php last;
rewrite "^/category-([0-9]+)-b([0-9]+)-min([0-9]+)-max([0-9]+)-attr([^-]*)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$" /category.php?id=$1&brand=$2&price_min=$3&price_max=$4&filter_attr=$5&page=$6&sort=$7&order=$8 last;
rewrite "^/category-([0-9]+)-b([0-9]+)-min([0-9]+)-max([0-9]+)-attr([^-]*)(.*)\.html$" /category.php?id=$1&brand=$2&price_min=$3&price_max=$4&filter_attr=$5 last;
rewrite "^/category-([0-9]+)-b([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$" /category.php?id=$1&brand=$2&page=$3&sort=$4&order=$5 last;
rewrite "^/category-([0-9]+)-b([0-9]+)-([0-9]+)(.*)\.html$" /category.php?id=$1&brand=$2&page=$3 last;
rewrite "^/category-([0-9]+)-b([0-9]+)(.*)\.html$" /category.php?id=$1&brand=$2 last;
rewrite "^/category-([0-9]+)(.*)\.html$" /category.php?id=$1 last;
rewrite "^/goods-([0-9]+)(.*)\.html" /goods.php?id=$1 last;
rewrite "^/article_cat-([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$" /article_cat.php?id=$1&page=$2&sort=$3&order=$4 last;
rewrite "^/article_cat-([0-9]+)-([0-9]+)(.*)\.html$" /article_cat.php?id=$1&page=$2 last;
rewrite "^/article_cat-([0-9]+)(.*)\.html$" /article_cat.php?id=$1 last;
rewrite "^/article-([0-9]+)(.*)\.html$" /article.php?id=$1 last;
rewrite "^/brand-([0-9]+)-c([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)\.html" /brand.php?id=$1&cat=$2&page=$3&sort=$4&order=$5 last;
rewrite "^/brand-([0-9]+)-c([0-9]+)-([0-9]+)(.*)\.html" /brand.php?id=$1&cat=$2&page=$3 last;
rewrite "^/brand-([0-9]+)-c([0-9]+)(.*)\.html" /brand.php?id=$1&cat=$2 last;
rewrite "^/brand-([0-9]+)(.*)\.html" /brand.php?id=$1 last;
rewrite "^/tag-(.*)\.html" /search.php?keywords=$1 last;
rewrite "^/snatch-([0-9]+)\.html$" /snatch.php?id=$1 last;
rewrite "^/group_buy-([0-9]+)\.html$" /group_buy.php?act=view&id=$1 last;
rewrite "^/auction-([0-9]+)\.html$" /auction.php?act=view&id=$1 last;
rewrite "^/exchange-id([0-9]+)(.*)\.html$" /exchange.php?id=$1&act=view last;
rewrite "^/exchange-([0-9]+)-min([0-9]+)-max([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$" /exchange.php?cat_id=$1&integral_min=$2&integral_max=$3&page=$4&sort=$5&order=$6 last;
rewrite ^/exchange-([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$" /exchange.php?cat_id=$1&page=$2&sort=$3&order=$4 last;
rewrite "^/exchange-([0-9]+)-([0-9]+)(.*)\.html$" /exchange.php?cat_id=$1&page=$2 last;
rewrite "^/exchange-([0-9]+)(.*)\.html$" /exchange.php?cat_id=$1 last;
}
+7
View File
@@ -0,0 +1,7 @@
location / {
index index.php index.html;
if (!-e $request_filename)
{
rewrite ^/(.*)$ /index.php last;
}
}
+3
View File
@@ -0,0 +1,3 @@
location / {
try_files $uri $uri/ /index.php$is_args$query_string;
}
+5
View File
@@ -0,0 +1,5 @@
rewrite ^/vod-(.*)$ /index.php?m=vod-$1 break;
rewrite ^/art-(.*)$ /index.php?m=art-$1 break;
rewrite ^/gbook-(.*)$ /index.php?m=gbook-$1 break;
rewrite ^/label-(.*)$ /index.php?m=label-$1 break;
rewrite ^/map-(.*)$ /index.php?m=map-$1 break;
+6
View File
@@ -0,0 +1,6 @@
location /{
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php/$1 last;
break;
}
}
+6
View File
@@ -0,0 +1,6 @@
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=$1 last;
break;
}
}
+9
View File
@@ -0,0 +1,9 @@
location / {
###以下为PHPCMS 伪静态化rewrite法则
rewrite ^(.*)show-([0-9]+)-([0-9]+)\.html$ $1/show.php?itemid=$2&page=$3;
rewrite ^(.*)list-([0-9]+)-([0-9]+)\.html$ $1/list.php?catid=$2&page=$3;
rewrite ^(.*)show-([0-9]+)\.html$ $1/show.php?specialid=$2;
####以下为PHPWind 伪静态化rewrite法则
rewrite ^(.*)-htm-(.*)$ $1.php?$2 last;
rewrite ^(.*)/simple/([a-z0-9\_]+\.html)$ $1/simple/index.php?$2 last;
}
+4
View File
@@ -0,0 +1,4 @@
location / {
rewrite ^(.*)-htm-(.*)$ $1.php?$2 last;
rewrite ^(.*)/simple/([a-z0-9\_]+\.html)$ $1/simple/index.php?$2 last;
}
+16
View File
@@ -0,0 +1,16 @@
location / {
rewrite "^/date/([0-9]{6})/?([0-9]+)?/?$" /index.php?action=article&setdate=$1&page=$2 last;
rewrite ^/page/([0-9]+)?/?$ /index.php?action=article&page=$1 last;
rewrite ^/category/([0-9]+)/?([0-9]+)?/?$ /index.php?action=article&cid=$1&page=$2 last;
rewrite ^/category/([^/]+)/?([0-9]+)?/?$ /index.php?action=article&curl=$1&page=$2 last;
rewrite ^/(archives|search|article|links)/?$ /index.php?action=$1 last;
rewrite ^/(comments|tagslist|trackbacks|article)/?([0-9]+)?/?$ /index.php?action=$1&page=$2 last;
rewrite ^/tag/([^/]+)/?([0-9]+)?/?$ /index.php?action=article&item=$1&page=$2 last;
rewrite ^/archives/([0-9]+)/?([0-9]+)?/?$ /index.php?action=show&id=$1&page=$2 last;
rewrite ^/rss/([0-9]+)?/?$ /rss.php?cid=$1 last;
rewrite ^/rss/([^/]+)/?$ /rss.php?url=$1 last;
rewrite ^/uid/([0-9]+)/?([0-9]+)?/?$ /index.php?action=article&uid=$1&page=$2 last;
rewrite ^/user/([^/]+)/?([0-9]+)?/?$ /index.php?action=article&user=$1&page=$2 last;
rewrite sitemap.xml sitemap.php last;
rewrite ^(.*)/([0-9a-zA-Z\-\_]+)/?([0-9]+)?/?$ $1/index.php?action=show&alias=$2&page=$3 last;
}
+11
View File
@@ -0,0 +1,11 @@
location / {
rewrite ^/frim/index(.+?)\.html$ /list/index.php?$1 last;
rewrite ^/movie/index(.+?)\.html$ /detail/index.php?$1 last;
rewrite ^/play/([0-9]+)-([0-9]+)-([0-9]+)\.html$ /video/index.php?$1-$2-$3 last;
rewrite ^/topic/index(.+?)\.html$ /topic/index.php?$1 last;
rewrite ^/topiclist/index(.+?).html$ /topiclist/index.php?$1 last;
rewrite ^/index\.html$ index.php permanent;
rewrite ^/news\.html$ news/ permanent;
rewrite ^/part/index(.+?)\.html$ /articlelist/index.php?$1 last;
rewrite ^/article/index(.+?)\.html$ /article/index.php?$1 last;
}
+5
View File
@@ -0,0 +1,5 @@
location / {
if (!-e $request_filename) {
rewrite ^/(.+\.(html|xml|json|htm|php|jsp|asp|shtml))$ /index.php?$1 last;
}
}
+5
View File
@@ -0,0 +1,5 @@
location / {
if (!-e $request_filename){
rewrite ^(.*)$ /index.php?s=$1 last; break;
}
}
+3
View File
@@ -0,0 +1,3 @@
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php$1 last;
}
+5
View File
@@ -0,0 +1,5 @@
location /typecho/ {
if (!-e $request_filename) {
rewrite ^(.*)$ /typecho/index.php$1 last;
}
}
+6
View File
@@ -0,0 +1,6 @@
location /
{
try_files $uri $uri/ /index.php?$args;
}
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
+6
View File
@@ -0,0 +1,6 @@
rewrite ^.*/files/(.*)$ /wp-includes/ms-files.php?file=$1 last;
if (!-e $request_filename){
rewrite ^.+?(/wp-.*) $1 last;
rewrite ^.+?(/.*\.php)$ $1 last;
rewrite ^ /index.php last;
}
+9
View File
@@ -0,0 +1,9 @@
if (-f $request_filename/index.html){
rewrite (.*) $1/index.html break;
}
if (-f $request_filename/index.php){
rewrite (.*) $1/index.php;
}
if (!-f $request_filename){
rewrite (.*) /index.php;
}
+2 -2
View File
@@ -7,11 +7,11 @@
# | Author: 黄文良 <287962566@qq.com>
# +-------------------------------------------------------------------
from os import environ
from BTPanel import app,socketio,sys
from BTPanel import app,sys
if __name__ == '__main__':
f = open('data/port.pl')
PORT = int(f.read())
HOST = '0.0.0.0'
f.close()
socketio.run(app,host=HOST,port=PORT)
app.run(host=HOST,port=PORT)
+2 -2
View File
@@ -92,7 +92,7 @@ class backupTools:
if len(mycnf) > 100:
public.writeFile('/etc/my.cnf',mycnf);
public.ExecShell("/www/server/mysql/bin/mysqldump --force --opt " + name + " | gzip > " + filename)
public.ExecShell("/www/server/mysql/bin/mysqldump --default-character-set="+ public.get_database_character(name) +" --force --opt " + name + " | gzip > " + filename)
if not os.path.exists(filename):
endDate = time.strftime('%Y/%m/%d %X',time.localtime())
@@ -138,7 +138,7 @@ class backupTools:
backup_path = sql.table('config').where("id=?",(1,)).getField('backup_path') + '/path';
if not os.path.exists(backup_path): os.makedirs(backup_path);
filename= backup_path + "/Path_" + name + "_" + time.strftime('%Y%m%d_%H%M%S',time.localtime()) + '.tar.gz'
os.system("cd " + os.path.dirname(path) + " && tar zcvf '" + filename + "' '" + os.path.basename(path) + "' > /dev/null")
os.system("cd " + os.path.dirname(path) + " && tar zcvf '" + filename + "' '" + os.path.basename(path) + "'" + self.__exclude + " > /dev/null")
endDate = time.strftime('%Y/%m/%d %X',time.localtime())
if not os.path.exists(filename):
+20 -18
View File
@@ -55,7 +55,7 @@ def DownloadFile(url,filename):
import urllib,socket
socket.setdefaulttimeout(10)
urllib.urlretrieve(url,filename=filename ,reporthook= DownloadHook)
os.system('chown www.www ' + filename);
public.ExecShell('chown www.www ' + filename);
WriteLogs('done')
except:
WriteLogs('done')
@@ -105,7 +105,7 @@ def startTask():
ExecShell(value['execstr'])
end = int(time.time())
sql.table('tasks').where("id=?",(value['id'],)).save('status,end',('1',end))
if(sql.table('tasks').where("status=?",('0')).count() < 1): os.system('rm -f ' + isTask);
if(sql.table('tasks').where("status=?",('0')).count() < 1): public.ExecShell('rm -f ' + isTask);
except:
pass
siteEdate();
@@ -323,17 +323,17 @@ def startPHPVersion(version):
return False;
#尝试重载服务
os.system(fpm + ' reload');
public.ExecShell(fpm + ' reload');
if checkPHPVersion(version): return True;
#尝试重启服务
cgi = '/tmp/php-cgi-'+version + '.sock'
pid = '/www/server/php/'+version+'/var/run/php-fpm.pid';
os.system('pkill -9 php-fpm-'+version)
public.ExecShell('pkill -9 php-fpm-'+version)
time.sleep(0.5);
if not os.path.exists(cgi): os.system('rm -f ' + cgi);
if not os.path.exists(pid): os.system('rm -f ' + pid);
os.system(fpm + ' start');
if not os.path.exists(cgi): public.ExecShell('rm -f ' + cgi);
if not os.path.exists(pid): public.ExecShell('rm -f ' + pid);
public.ExecShell(fpm + ' start');
if checkPHPVersion(version): return True;
#检查是否正确启动
@@ -360,9 +360,9 @@ def checkPHPVersion(version):
isStatus = public.readFile(isTask);
if isStatus == 'True': return True;
filename = '/etc/init.d/nginx';
if os.path.exists(filename): os.system(filename + ' start');
if os.path.exists(filename): public.ExecShell(filename + ' start');
filename = '/etc/init.d/httpd';
if os.path.exists(filename): os.system(filename + ' start');
if os.path.exists(filename): public.ExecShell(filename + ' start');
return True;
except:
@@ -460,11 +460,12 @@ def panel_status():
s = 0
v = 0
while True:
time.sleep(1)
time.sleep(5)
if not panel_pid: panel_pid = get_panel_pid()
if not panel_pid: run_panel()
try:
if psutil.Process(panel_pid).cmdline()[-1] != 'runserver:app':
f = psutil.Process(panel_pid).cmdline()[-1]
if f.find('runserver') == -1 and f.find('BT-Panel') == -1:
run_panel()
time.sleep(3)
panel_pid = get_panel_pid()
@@ -490,7 +491,7 @@ def panel_status():
if e_body.find('table session') != -1:
sess_file = '/dev/shm/session.db'
if os.path.exists(sess_file): os.remove(sess_file)
os.system("/etc/init.d/bt reload &")
public.ExecShell("/etc/init.d/bt reload &")
time.sleep(10)
result = public.httpGet(panel_url)
if result == 'True':
@@ -502,7 +503,7 @@ def panel_status():
if result == 'True':
time.sleep(10)
continue
os.system("/etc/init.d/bt reload &")
public.ExecShell("/etc/init.d/bt reload &")
result = public.httpGet(panel_url)
if result == 'True':
public.WriteLog('TYPE_SOFE','Checked to panel service exception, has been automatically restored!')
@@ -511,7 +512,7 @@ def panel_status():
def run_panel():
os.system("/etc/init.d/bt start &")
public.ExecShell("/etc/init.d/bt start &")
#重启面板服务
def restart_panel_service():
@@ -520,10 +521,10 @@ def restart_panel_service():
while True:
if os.path.exists(rtips):
os.remove(rtips)
os.system("/etc/init.d/bt restart &")
public.ExecShell("/etc/init.d/bt restart &")
if os.path.exists(reload_tips):
os.remove(reload_tips)
os.system("/etc/init.d/bt reload &")
public.ExecShell("/etc/init.d/bt reload &")
time.sleep(1)
#取面板pid
@@ -531,7 +532,8 @@ def get_panel_pid():
for pid in psutil.pids():
try:
p = psutil.Process(pid)
if p.cmdline()[-1] == 'runserver:app': return pid
n = p.cmdline()[-1]
if n.find('runserver') != -1 or n.find('BT-Panel') != -1: return pid
except: pass
return None
@@ -551,7 +553,7 @@ def btkill():
b.start();
if __name__ == "__main__":
os.system('rm -rf /www/server/phpinfo/*');
public.ExecShell('rm -rf /www/server/phpinfo/*');
if os.path.exists('/www/server/nginx/sbin/nginx'):
pfile = '/www/server/nginx/conf/enable-php-72.conf';
if not os.path.exists(pfile):
+6 -1
View File
@@ -34,7 +34,12 @@ m_version=$(cat /www/server/mysql/version.pl|grep -E "(5.1.|5.5.|5.6.|10.0|10.1)
if [ "$m_version" != "" ];then
mysql -uroot -e "UPDATE mysql.user SET password=PASSWORD('${pwd}') WHERE user='root'";
else
mysql -uroot -e "update mysql.user set authentication_string=password('${pwd}') where user='root';"
m_version=$(cat /www/server/mysql/version.pl|grep -E "(5.7.|8.0.)")
if [ "$m_version" != "" ];then
mysql -uroot -e "FLUSH PRIVILEGES;update mysql.user set authentication_string='' where user='root';alter user 'root'@'localhost' identified by '${pwd}';alter user 'root'@'127.0.0.1' identified by '${pwd}';FLUSH PRIVILEGES;";
else
mysql -uroot -e "update mysql.user set authentication_string=password('${pwd}') where user='root';"
fi
fi
mysql -uroot -e "FLUSH PRIVILEGES";
pkill -9 mysqld_safe