Compare commits

..
107 Commits
Author SHA1 Message Date
Mr Chen c4a844cadb Merge pull request #209 from midoks/dev
0.9.13
2022-10-11 12:47:26 +08:00
midoks a88a281175 0.9.13
0.9.13
2022-10-11 12:46:35 +08:00
midoks f3f3b1c6bd Update init.lua 2022-10-11 12:35:59 +08:00
midoks 4259ac51cb up 2022-10-11 11:41:32 +08:00
midoks 4db1357d3d 更新mysql版本 2022-10-11 09:03:53 +08:00
midoks 15873e0824 Update op_waf.js 2022-10-11 00:40:21 +08:00
midoks dcdb07f76d up 2022-10-11 00:35:13 +08:00
midoks 8b70637479 Update index.py 2022-10-10 23:28:36 +08:00
midoks c77085fea4 Update index.py 2022-10-10 23:27:20 +08:00
midoks a265f3d0d5 Update index.py 2022-10-10 23:24:54 +08:00
midoks 7ea486cd1d Update index.py 2022-10-10 23:22:43 +08:00
midoks 0e31e87e28 Update index.py 2022-10-10 23:22:04 +08:00
midoks 8c621c892e Update index.py 2022-10-10 23:16:59 +08:00
midoks 32bcae603c Update index.py 2022-10-10 23:16:48 +08:00
midoks 98ec21446d Update index.py 2022-10-10 22:41:36 +08:00
midoks 0ee3682502 Update redis.service.tpl 2022-10-10 22:11:51 +08:00
midoks c609d1a012 Update redis.service.tpl 2022-10-10 22:05:55 +08:00
midoks 27b1a78879 up 2022-10-10 22:03:21 +08:00
midoks 773de840a5 Update redis.js 2022-10-10 21:55:00 +08:00
midoks 91d6ff3c54 Update index.py 2022-10-10 21:52:11 +08:00
midoks 03376bd42d Update redis.conf 2022-10-10 21:50:04 +08:00
midoks 036c5114c2 Update index.py 2022-10-10 21:35:51 +08:00
midoks a772e70fde Update index.py 2022-10-10 21:33:20 +08:00
midoks 53055bbdef Update index.py 2022-10-10 21:31:43 +08:00
midoks f81d598fcf Update index.py 2022-10-10 21:13:44 +08:00
midoks 3530e83bb9 up 2022-10-10 21:09:35 +08:00
midoks 1271b2f637 Update index.py 2022-10-10 21:00:30 +08:00
midoks 2dc6bc7753 Update index.py 2022-10-10 20:58:45 +08:00
midoks e52d9e3ea3 Update index.py 2022-10-10 20:55:45 +08:00
midoks d8a570e55e Update index.html 2022-10-10 20:46:07 +08:00
midoks f4ceaf667b php-yum更新 2022-10-10 20:43:48 +08:00
midoks 958ba16b85 Update index.html 2022-10-10 20:28:44 +08:00
midoks 73039777bb Update index.py 2022-10-10 20:06:00 +08:00
midoks 864e4c910c PHP添加会话管理功能 2022-10-10 19:54:23 +08:00
midoks 4da57405af Update init.lua 2022-10-10 13:01:27 +08:00
midoks dff638571a Update init.lua 2022-10-10 12:45:31 +08:00
midoks c7d9ec51cc up 2022-10-10 12:36:42 +08:00
midoks 501c575f73 up 2022-10-10 12:13:45 +08:00
midoks 0fd966ca65 up 2022-10-10 02:14:31 +08:00
midoks 172dde2794 Update mariadb.js 2022-10-09 23:26:50 +08:00
midoks 78fdc80652 优化mysql进入phpmyadmin 2022-10-09 23:24:47 +08:00
midoks 01b8c9b8ff Update init.lua 2022-10-09 22:47:28 +08:00
midoks b840086d4d op防火墙更新1 2022-10-09 21:29:40 +08:00
midoks 4c73f13f2d up 2022-10-09 11:36:57 +08:00
midoks f31c1aae96 up 2022-10-09 10:39:46 +08:00
midoks 5c24a831db Update index.py 2022-10-09 02:04:17 +08:00
midoks 91d07eebad Update install.sh 2022-10-09 01:59:17 +08:00
midoks 3b51ef2434 up 2022-10-09 01:49:17 +08:00
midoks 31c5e42b09 Update index.html 2022-10-09 01:38:15 +08:00
midoks b8b3a237ef up 2022-10-09 01:37:14 +08:00
midoks 5cb2aefbbc up 2022-10-09 01:25:53 +08:00
midoks 19173af3e2 Update logs_backup.py 2022-10-09 00:31:15 +08:00
midoks 3dc493108b Update mw.tpl 2022-10-09 00:30:03 +08:00
midoks 55af62000b Update logs_backup.py 2022-10-09 00:26:28 +08:00
midoks a1c8c48761 Update index.js 2022-10-08 22:45:44 +08:00
midoks 8c3ec0a103 Update index.js 2022-10-08 22:40:23 +08:00
midoks 5cbde31105 Update tool_task.py 2022-10-08 18:15:57 +08:00
midoks 04dd94032e Update tool_task.py 2022-10-08 18:12:45 +08:00
midoks 8a11195b0d Update tool_task.py 2022-10-08 18:08:38 +08:00
midoks 1eb76baae7 改变弹框方式 2022-10-08 16:05:24 +08:00
midoks 2669d6f021 Update init.lua 2022-10-08 15:21:17 +08:00
midoks 6f13a03a2c Update config_api.py 2022-10-08 14:24:58 +08:00
Mr Chen 9c97e1c41c Merge pull request #205 from midoks/dev
0.9.12
2022-10-08 14:21:46 +08:00
midoks 37245ca1e8 0.9.12
* 日志清理插件优化。
* 计划任务显示完整。
* 加入gitea插件。
* 融合mw-cli命令。
* 加快php编译速度。
* swap加上调整功能。
* 其他细节优化。
2022-10-08 14:20:47 +08:00
midoks f706a8a2ea up 2022-10-08 14:03:01 +08:00
midoks e6af6b2062 up 2022-10-07 21:29:00 +08:00
midoks f5b056c965 init 2022-10-07 01:00:02 +08:00
midoks 8c768e8a04 Create tool_task.py 2022-10-07 00:47:26 +08:00
midoks 1d6f4feccb Update soft.js 2022-10-07 00:46:32 +08:00
midoks 49c32dc9c1 Update index.py 2022-10-06 17:52:25 +08:00
midoks 17a865c45d Update install.sh 2022-10-06 17:28:37 +08:00
midoks 0090681ab2 Update index.py 2022-10-06 17:25:15 +08:00
midoks 4d3a6c27f7 up 2022-10-06 17:19:36 +08:00
midoks abf39428fc Update index.py 2022-10-06 17:08:46 +08:00
midoks ec11904959 up 2022-10-06 17:07:26 +08:00
midoks d18f16a2b8 up 2022-10-06 15:32:30 +08:00
midoks 7fbe421b0c 加快php编译速度 2022-10-06 14:16:46 +08:00
midoks 81c7929240 Update install.sh 2022-10-06 14:09:46 +08:00
midoks 76c655872b Update install.sh 2022-10-06 14:09:22 +08:00
midoks 7b09776392 Update install.sh 2022-10-06 14:08:52 +08:00
midoks 0b28077e08 up 2022-10-06 14:07:10 +08:00
midoks ccc00e8b5d 更新版本 2022-10-06 13:40:52 +08:00
midoks 202e04c62d Update install.sh 2022-10-06 13:30:50 +08:00
midoks 01cd35305e Update ubuntu.sh 2022-10-06 13:10:44 +08:00
midoks 2f0d7d1d07 融合mw-cli结束2 2022-10-06 11:22:42 +08:00
midoks 714af23627 融合mw-cli结束 2022-10-06 11:13:09 +08:00
midoks 0a9eb721c6 Delete mw-cli 2022-10-06 11:12:18 +08:00
midoks 5e71c20e2a up 2022-10-06 11:12:01 +08:00
midoks 3c24d9f9a9 Update mw.tpl 2022-10-06 09:32:46 +08:00
midoks 78bdcb79c8 Update index.py 2022-10-05 20:51:38 +08:00
midoks aaf3389460 Update index.py 2022-10-05 20:50:39 +08:00
midoks 9f2cb58812 Update index.py 2022-10-05 20:50:31 +08:00
midoks c6099fb7ce Update gitea.service.tpl 2022-10-05 20:45:01 +08:00
midoks 3fb4d88c4a Update gitea.service.tpl 2022-10-05 20:44:43 +08:00
midoks f90fec182c Update install.sh 2022-10-05 20:39:55 +08:00
midoks ba86217a1a Update mw.py 2022-10-05 20:37:02 +08:00
midoks 9a7bcdc1c4 up 2022-10-05 20:34:43 +08:00
midoks 43b1f5ed86 Update gitea.service.tpl 2022-10-05 20:08:41 +08:00
midoks 68ca194c2d Update gitea.service.tpl 2022-10-05 20:05:27 +08:00
midoks 061eaabe79 Update gitea.service.tpl 2022-10-05 19:50:08 +08:00
midoks 420e830ed9 Update crontab_api.py 2022-10-05 17:52:09 +08:00
midoks 8e9cba6646 Update phplib.conf 2022-10-05 14:06:20 +08:00
midoks e0c183c1ac 加入gitea 2022-10-03 12:27:44 +08:00
midoks 18c59da28d Update crontab.js 2022-10-02 15:33:14 +08:00
midoks 71f2d66966 计划任务 显示完整 2022-10-02 15:23:29 +08:00
midoks abd6cdd738 日志清理 插件优化 2022-10-02 15:05:13 +08:00
midoks dd7b1707c3 Update README.md 2022-10-02 09:33:21 +08:00
91 changed files with 3695 additions and 5971 deletions
+8 -8
View File
@@ -90,15 +90,15 @@ docker run -itd --name mw-server --privileged=true -p 7200:7200 -p 80:80 -p 443:
```
### 版本更新 0.9.11
* 大文件解压优化。
* 防火墙api优化。
* mysql|mariadb安装删除冗余账户。
* imail插件添加。
* 安装面板初始化安装时不再固定端口[7200],优化为随机端口。
* redis添加性能调整功能。
### 版本更新 0.9.13
* 优化弹框。
* 修复计划任务[日志切割]。
* 优化mysql的与phpmyadmin的连接。
* PHP添加`会话管理`功能。
* redis优化。
* 更新mysql[5.7]的安装。
* OP防火墙部分功能优化。
### JSDelivr安装地址
+1 -1
View File
@@ -15,7 +15,7 @@ from flask import request
class config_api:
__version = '0.9.11'
__version = '0.9.13'
def __init__(self):
pass
+4 -4
View File
@@ -414,10 +414,10 @@ class crontab_api:
script_dir = mw.getServerDir() + "/mdserver-web/scripts"
wheres = {
'path': head + "python " + script_dir + "/backup.py path " + param['sname'] + " " + str(param['save']),
'site': head + "python " + script_dir + "/backup.py site " + param['sname'] + " " + str(param['save']),
'database': head + "python " + script_dir + "/backup.py database " + param['sname'] + " " + str(param['save']),
'logs': head + "python " + script_dir + "/logs_backup.py " + param['sname'] + log + " " + str(param['save']),
'path': head + "python3 " + script_dir + "/backup.py path " + param['sname'] + " " + str(param['save']),
'site': head + "python3 " + script_dir + "/backup.py site " + param['sname'] + " " + str(param['save']),
'database': head + "python3 " + script_dir + "/backup.py database " + param['sname'] + " " + str(param['save']),
'logs': head + "python3 " + script_dir + "/logs_backup.py " + param['sname'] + log + " " + str(param['save']),
'rememory': head + "/bin/bash " + script_dir + '/rememory.sh'
}
if param['backup_to'] != 'localhost':
+3 -3
View File
@@ -552,7 +552,7 @@ def getSpeed():
return json.loads(data)
def getLastLine(inputfile, lineNum):
def getLastLineBk(inputfile, lineNum):
# 读文件指定倒数行数
try:
fp = open(inputfile, 'rb')
@@ -585,7 +585,7 @@ def getLastLine(inputfile, lineNum):
# return getMsg('TASK_SLEEP')
def getNumLines(path, num, p=1):
def getLastLine(path, num, p=1):
pyVersion = sys.version_info[0]
try:
import html
@@ -624,7 +624,7 @@ def getNumLines(path, num, p=1):
t_buf = fp.read(to_read)
if pyVersion == 3:
if type(t_buf) == bytes:
t_buf = t_buf.decode('utf-8')
t_buf = t_buf.decode("utf-8", "ignore").strip()
buf = t_buf + buf
fp.seek(-to_read, 1)
if pos - to_read == 0:
-86
View File
@@ -1,86 +0,0 @@
#!/www/server/mdserver-web/bin/python
# description: mdserver-web cli tools
# ln -s /www/server/mdserver-web/mw-cli /usr/bin/mw-cli
import os
import sys
def mw_start():
"""
Start mdserver-web
"""
os.system('systemctl start mw')
print("服务已启动")
def mw_stop():
"""
stop mdserver-web
"""
os.system('systemctl stop mw')
print("服务已停止")
def mw_restart():
"""
restart mdserver-web
"""
os.system('systemctl restart mw')
print("服务已重启")
def mw_reset_username():
"""
reset mdserver-web username
"""
from tools import set_panel_username
user_name = input("请输入新的用户名: ")
set_panel_username(user_name)
def mw_reset_pwd():
"""
reset mdserver-web password
"""
from tools import set_panel_pwd
pwd = input("请输入新的密码: ")
set_panel_pwd(pwd, True)
if __name__ == '__main__':
if os.geteuid() != 0:
print("请使用root账户执行该命令.")
sys.exit(1)
os.chdir("/www/server/mdserver-web")
sys.path.append(os.getcwd() + "/class/core")
try:
str = '''
==== mdserver-web cli tools ====
1. 启动服务 2. 停止服务
3. 重启服务 4. 修改用户名
5. 修改密码
=================================
'''
if len(sys.argv) == 2:
sw = sys.argv[1]
else:
print(str)
sw = input("请输入您要进行的操作: ")
if sw == '1':
mw_start()
elif sw == '2':
mw_stop()
elif sw == '3':
mw_restart()
elif sw == '4':
mw_reset_username()
elif sw == '5':
mw_reset_pwd()
else:
print("操作不存在")
except KeyboardInterrupt:
print("\n操作已终止")
+5 -1
View File
@@ -3,6 +3,7 @@
<div class="bt-w-menu">
<p class="bgw" onclick="pluginService('clean');">服务</p>
<p onclick="pluginConfig('clean');">配置修改</p>
<p onclick="pluginLogs('clean',null,'run_log');">运行日志</p>
<p onclick="pRead()">说明</p>
</div>
<div class="bt-w-con pd15">
@@ -16,7 +17,10 @@ pluginService('clean');
function pRead(){
var readme = '<ul class="help-info-text c7">';
readme += '<li>cd /www/server/mdserver-web && python3 /www/server/mdserver-web/plugins/clean/index.py clean</li>';
readme += '<li>启动后,假如到计划中[2:30]执行。</li>';
readme += '<li>【*】代表要删除。</li>';
readme += '<li>添加/删除清除日志,可在`配置修改`中添加/删除。</li>';
readme += '<li>如果是目录,会寻找【.log】后缀的文件清空。</li>';
readme += '</ul>';
$('.soft-man-con').html(readme);
+96 -70
View File
@@ -53,34 +53,95 @@ def getArgs():
return tmp
def getLockFile():
return getServerDir() + "/installed_lock.pl"
def runLog():
return getServerDir() + "/clean.log"
def status():
if os.path.exists(getConf()):
initConf()
if os.path.exists(getLockFile()):
return "start"
return 'stop'
def initConf():
conf = getConf()
if not os.path.exists(conf):
content = ""
clog = [
"/var/log/cron-*",
"/var/log/maillog-*",
"/var/log/secure-*",
"/var/log/spooler-*",
"/var/log/yum.log-*",
"/var/log/messages-*",
"/var/log/btmp-*",
"/var/log/audit/audit.log.*",
"/var/log/rhsm/rhsm.log-*",
"/var/log/rhsm/rhsmcertd.log-*",
"/tmp/yum_save_*",
"/tmp/tmp.*",
]
for i in clog:
content += i + "\n"
# 常用日志
clogcom = [
"/var/log/messages",
"/var/log/btmp",
"/var/log/wtmp",
"/var/log/secure",
"/var/log/lastlog",
"/var/log/cron",
"/www/server/cron"
]
for i in clogcom:
if os.path.exists(i):
content += i + "\n"
# 清理日志
rootDir = "/var/log"
l = os.listdir(rootDir)
for x in range(len(l)):
abspath = rootDir + "/" + l[x]
content += abspath + "\n"
mw.writeFile(conf, content)
def start():
file = initDreplace()
data = mw.execShell(file + ' start')
if data[1] == '':
initConf()
lock_file = getLockFile()
if not os.path.exists(lock_file):
mw.writeFile(lock_file, "")
import tool_task
tool_task.createBgTask()
return 'ok'
return 'fail'
def stop():
file = initDreplace()
data = mw.execShell(file + ' stop')
if data[1] == '':
initConf()
lock_file = getLockFile()
if os.path.exists(lock_file):
os.remove(lock_file)
import tool_task
tool_task.removeBgTask()
return 'ok'
return 'fail'
def reload():
file = initDreplace()
data = mw.execShell(file + ' reload')
if data[1] == '':
return 'ok'
return 'fail'
return 'ok'
def get_filePath_fileName_fileExt(filename):
@@ -93,15 +154,20 @@ def cleanFileLog(path):
filepath, shotname, extension = get_filePath_fileName_fileExt(path)
if extension == ".log":
cmd = "echo \"\" > " + path
tmp = mw.execShell(cmd)
if tmp[1] != "":
cmd += " | error:" + tmp[1].strip()
print(cmd)
print(mw.execShell(cmd))
def cleanSelfFileLog(path):
filepath, shotname, extension = get_filePath_fileName_fileExt(path)
cmd = "echo \"\" > " + path
print(cmd)
print(mw.execShell(cmd))
if extension == ".log":
cmd = "echo \"\" > " + path
tmp = mw.execShell(cmd)
if tmp[1] != "":
cmd += " | error:" + tmp[1].strip()
print(cmd)
def cleanDirLog(path):
@@ -115,70 +181,28 @@ def cleanDirLog(path):
def cleanLog():
# 清理日志
rootDir = "/var/log"
print("clean start")
clog = [
"rm -rf /var/log/cron-*",
"rm -rf /var/log/maillog-*",
"rm -rf /var/log/secure-*",
"rm -rf /var/log/spooler-*",
"rm -rf /var/log/yum.log-*",
"rm -rf /var/log/messages-*",
"rm -rf /var/log/btmp-*",
"rm -rf /var/log/audit/audit.log.*",
"rm -rf /var/log/rhsm/rhsm.log-*",
"rm -rf /var/log/rhsm/rhsmcertd.log-*",
"rm -rf /tmp/yum_save_*",
"rm -rf /tmp/tmp.*",
]
for i in clog:
print(i)
mw.execShell(i)
# 常用日志
clogcom = [
"/var/log/messages",
"/var/log/btmp",
"/var/log/wtmp",
"/var/log/secure",
"/var/log/lastlog",
"/var/log/cron",
]
for i in clogcom:
if os.path.exists(i):
mw.execShell("echo \"\" > " + i)
l = os.listdir(rootDir)
for x in range(len(l)):
abspath = rootDir + "/" + l[x]
if os.path.isfile(abspath):
cleanFileLog(abspath)
if os.path.isdir(abspath):
cleanDirLog(abspath)
print("conf clean")
confFile = getServerDir()
# mw.readFile()
confFile = confFile + "/clean.conf"
clist = mw.readFile(confFile).strip()
conf = getConf()
clist = mw.readFile(conf).strip()
clist = clist.split("\n")
for x in clist:
abspath = x.strip()
if abspath.find('*') > 1:
cmd = 'rm -rf ' + abspath
print(cmd)
data = mw.execShell(cmd)
# print(data)
continue
if os.path.exists(abspath):
if os.path.isfile(abspath):
cleanSelfFileLog(abspath)
continue
if os.path.isdir(abspath):
cleanDirLog(abspath)
print("conf clean end")
print("clean end")
continue
if __name__ == "__main__":
func = sys.argv[1]
@@ -194,6 +218,8 @@ if __name__ == "__main__":
print(reload())
elif func == 'conf':
print(getConf())
elif func == 'run_log':
print(runLog())
elif func == 'clean':
cleanLog()
else:
+6 -2
View File
@@ -13,20 +13,24 @@ serverPath=$(dirname "$rootPath")
install_tmp=${rootPath}/tmp/mw_install.pl
VERSION=$2
if [ -f ${rootPath}/bin/activate ];then
source ${rootPath}/bin/activate
fi
Install_app()
{
echo '正在安装脚本文件...' > $install_tmp
mkdir -p $serverPath/clean
echo "" > $serverPath/clean/clean.conf
cd ${rootPath} && python3 ${rootPath}/plugins/clean/index.py start
echo "${VERSION}" > $serverPath/clean/version.pl
echo '安装完成' > $install_tmp
}
Uninstall_app()
{
cd ${rootPath} && python3 ${rootPath}/plugins/clean/index.py stop
rm -rf $serverPath/clean
echo "Uninstall_clean" > $install_tmp
}
+156
View File
@@ -0,0 +1,156 @@
# coding:utf-8
import sys
import io
import os
import time
import json
sys.path.append(os.getcwd() + "/class/core")
import mw
app_debug = False
if mw.isAppleSystem():
app_debug = True
def getPluginName():
return 'clean'
def getPluginDir():
return mw.getPluginDir() + '/' + getPluginName()
def getServerDir():
return mw.getServerDir() + '/' + getPluginName()
def getTaskConf():
conf = getServerDir() + "/task_config.json"
return conf
def getConfigData():
try:
return json.loads(mw.readFile(getTaskConf()))
except:
pass
return []
def getConfigTpl():
tpl = {
"name": "",
"task_id": -1,
}
return tpl
def createBgTask():
removeBgTask()
args = {
"period": "day",
"hour": "2",
"minute": "30",
}
createBgTaskByName(getPluginName(), args)
def createBgTaskByName(name, args):
cfg = getConfigTpl()
_name = "[勿删]日志清理[" + name + "]"
res = mw.M("crontab").field("id, name").where("name=?", (_name,)).find()
if res:
return True
if "task_id" in cfg.keys() and cfg["task_id"] > 0:
res = mw.M("crontab").field("id, name").where(
"id=?", (cfg["task_id"],)).find()
if res and res["id"] == cfg["task_id"]:
print("计划任务已经存在!")
return True
import crontab_api
api = crontab_api.crontab_api()
period = args['period']
_hour = ''
_minute = ''
_where1 = ''
_type_day = "day"
if period == 'day':
_type_day = 'day'
_hour = args['hour']
_minute = args['minute']
elif period == 'minute-n':
_type_day = 'minute-n'
_where1 = args['minute-n']
_minute = ''
mw_dir = mw.getRunDir()
cmd = '''
mw_dir=%s
rname=%s
plugin_path=%s
script_path=%s
logs_file=$plugin_path/${rname}.log
''' % (mw_dir, name, getServerDir(), getPluginDir())
cmd += 'echo "★【`date +"%Y-%m-%d %H:%M:%S"`】 STSRT★" >> $logs_file' + "\n"
cmd += 'echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" >> $logs_file' + "\n"
cmd += 'echo "python3 $script_path/index.py clean >> $logs_file 2>&1"' + "\n"
cmd += 'cd $mw_dir && python3 $script_path/index.py clean >> $logs_file 2>&1' + "\n"
cmd += 'echo "【`date +"%Y-%m-%d %H:%M:%S"`】 END★" >> $logs_file' + "\n"
cmd += 'echo "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" >> $logs_file' + "\n"
params = {
'name': _name,
'type': _type_day,
'week': "",
'where1': _where1,
'hour': _hour,
'minute': _minute,
'save': "",
'backup_to': "",
'stype': "toShell",
'sname': '',
'sbody': cmd,
'urladdress': '',
}
task_id = api.add(params)
if task_id > 0:
cfg["task_id"] = task_id
cfg["name"] = name
_dd = getConfigData()
_dd.append(cfg)
mw.writeFile(getTaskConf(), json.dumps(_dd))
def removeBgTask():
cfg_list = getConfigData()
for x in range(len(cfg_list)):
cfg = cfg_list[x]
if "task_id" in cfg.keys() and cfg["task_id"] > 0:
res = mw.M("crontab").field("id, name").where(
"id=?", (cfg["task_id"],)).find()
if res and res["id"] == cfg["task_id"]:
import crontab_api
api = crontab_api.crontab_api()
data = api.delete(cfg["task_id"])
if data[0]:
cfg["task_id"] = -1
cfg_list[x] = cfg
mw.writeFile(getTaskConf(), '[]')
return True
return False
if __name__ == "__main__":
if len(sys.argv) > 1:
action = sys.argv[1]
if action == "remove":
removeBgTask()
elif action == "add":
createBgTask()
+39
View File
@@ -0,0 +1,39 @@
#!/bin/bash
echo `date`
GITADDR="{$GITROOTURL}/{$USERNAME}/{$PROJECT}.git"
GIT_SDIR="{$CODE_DIR}"
GIT_USER_DIR="${GIT_SDIR}/{$USERNAME}"
GIT_PROJECT_DIR="${GIT_USER_DIR}/{$PROJECT}"
git config --global credential.helper store
# echo $GIT_PROJECT_DIR
if [ ! -d $GIT_PROJECT_DIR ];then
mkdir -p $GIT_USER_DIR && cd $GIT_USER_DIR
git clone $GITADDR
fi
unset GIT_DIR
cd $GIT_PROJECT_DIR && git pull
# func 2
# cd $GIT_PROJECT_DIR && env -i git pull origin master
#更新的目的地址
WEB_PATH={$WEB_ROOT}/{$USERNAME}/{$PROJECT}
mkdir -p $WEB_PATH
rsync -vauP --delete --exclude=".*" $GIT_PROJECT_DIR/ $WEB_PATH
sysName=`uname`
if [ $sysName == 'Darwin' ]; then
USER=$(who | sed -n "2,1p" |awk '{print $1}')
chown -R $USER:staff $WEB_PATH
else
chown -R www:www $WEB_PATH
fi
+36
View File
@@ -0,0 +1,36 @@
#!/bin/bash
echo `date`
GITADDR="{$GITROOTURL}/{$USERNAME}/{$PROJECT}"
GIT_SDIR="{$CODE_DIR}"
GIT_USER_DIR="${GIT_SDIR}/{$USERNAME}"
GIT_PROJECT_DIR="${GIT_USER_DIR}/{$PROJECT}"
# echo $GIT_PROJECT_DIR
if [ ! -d $GIT_PROJECT_DIR ];then
mkdir -p $GIT_USER_DIR && cd $GIT_USER_DIR
git clone $GITADDR
fi
unset GIT_DIR
cd $GIT_PROJECT_DIR && git pull
# func 2
# cd $GIT_PROJECT_DIR && env -i git pull origin master
WEB_PATH={$WEB_ROOT}/{$USERNAME}/{$PROJECT}
mkdir -p $WEB_PATH
rsync -vauP --delete --exclude=".*" $GIT_PROJECT_DIR/ $WEB_PATH
sysName=`uname`
if [ $sysName == 'Darwin' ]; then
USER=$(who | sed -n "2,1p" |awk '{print $1}')
chown -R $USER:staff $WEB_PATH
else
chown -R www:www $WEB_PATH
fi
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
sh -x {$PATH}/commit 2>{$PATH}/sh.log
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+24
View File
@@ -0,0 +1,24 @@
<div class="bt-form">
<div class="bt-w-main">
<div class="bt-w-menu">
<p class="bgw" onclick="pluginService('gitea');">服务</p>
<p onclick="pluginInitD('gitea');">自启动</p>
<!-- <p onclick="pluginConfig('gitea',null, 'init_conf');">启动配置</p> -->
<p onclick="gogsEdit();">手动编辑</p>
<p onclick="pluginConfig('gitea',null, 'conf');">配置文件</p>
<p onclick="gogsSetConfig();">配置修改</p>
<p onclick="giteaUserList();">用户列表</p>
<p onclick="pluginLogs('gitea',null,'run_log');">运行日志</p>
<p onclick="pluginLogs('gitea',null,'post_receive_log');" title="提交post-receive日志">提交日志</p>
<p onclick="giteaRead();">使用说明</p>
</div>
<div class="bt-w-con pd15">
<div class="soft-man-con"></div>
</div>
</div>
</div>
<script type="text/javascript">
$.getScript( "/plugins/file?name=gitea&f=js/gitea.js",function(){
pluginService('gitea');
});
</script>
@@ -11,11 +11,10 @@ sys.path.append(os.getcwd() + "/class/core")
import mw
cmd = 'ls /usr/local/lib/ | grep python | cut -d \\ -f 1 | awk \'END {print}\''
info = mw.execShell(cmd)
p = "/usr/local/lib/" + info[0].strip() + "/site-packages"
sys.path.append(p)
import psutil
# cmd = 'ls /usr/local/lib/ | grep python | cut -d \\ -f 1 | awk \'END {print}\''
# info = mw.execShell(cmd)
# p = "/usr/local/lib/" + info[0].strip() + "/site-packages"
# sys.path.append(p)
app_debug = False
@@ -24,15 +23,12 @@ if mw.isAppleSystem():
def getPluginName():
return 'gogs'
return 'gitea'
def getPluginDir():
return mw.getPluginDir() + '/' + getPluginName()
sys.path.append(getPluginDir() + "/class")
import mysqlDb
def getServerDir():
return mw.getServerDir() + '/' + getPluginName()
@@ -61,18 +57,28 @@ def getArgs():
return tmp
def checkArgs(data, ck=[]):
for i in range(len(ck)):
if not ck[i] in data:
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
return (True, mw.returnJson(True, 'ok'))
def getInitdConfTpl():
path = getPluginDir() + "/init.d/gogs.tpl"
path = getPluginDir() + "/init.d/gitea.tpl"
return path
def getInitdConf():
path = getServerDir() + "/init.d/gogs"
path = getServerDir() + "/init.d/gitea"
return path
def getConf():
path = getServerDir() + "/custom/conf/app.ini"
if not os.path.exists(path):
return mw.returnJson(False, "请先安装初始化!<br/>默认地址:http://" + mw.getLocalIp() + ":3000")
return path
@@ -95,7 +101,7 @@ def getHomeDir():
"who | sed -n '2, 1p' |awk '{print $1}'")[0].strip()
return '/Users/' + user
else:
return '/root'
return 'git'
def getRunUser():
@@ -104,7 +110,7 @@ def getRunUser():
"who | sed -n '2, 1p' |awk '{print $1}'")[0].strip()
return user
else:
return 'root'
return 'git'
__SR = '''#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
@@ -140,13 +146,16 @@ def initDreplace():
mw.writeFile(file_bin, content)
mw.execShell('chmod +x ' + file_bin)
conf_bin = getConf()
if not os.path.exists(conf_bin):
mw.execShell('mkdir -p ' + getServerDir() + '/custom/conf')
conf_tpl = getConfTpl()
content = mw.readFile(conf_tpl)
content = contentReplace(content)
mw.writeFile(conf_bin, content)
# systemd
systemDir = mw.systemdCfgDir()
systemService = systemDir + '/gitea.service'
systemServiceTpl = getPluginDir() + '/init.d/gitea.service.tpl'
if os.path.exists(systemDir) and not os.path.exists(systemService):
service_path = mw.getServerDir()
se_content = mw.readFile(systemServiceTpl)
se_content = se_content.replace('{$SERVER_PATH}', service_path)
mw.writeFile(systemService, se_content)
mw.execShell('systemctl daemon-reload')
log_path = getServerDir() + '/log'
if not os.path.exists(log_path):
@@ -159,9 +168,14 @@ def getRootUrl():
content = mw.readFile(getConf())
rep = 'ROOT_URL\s*=\s*(.*)'
tmp = re.search(rep, content)
if not tmp:
return ''
return tmp.groups()[0]
if tmp:
return tmp.groups()[0]
rep = 'EXTERNAL_URL\s*=\s*(.*)'
tmp = re.search(rep, content)
if tmp:
return tmp.groups()[0]
return ''
def getSshPort():
@@ -192,8 +206,11 @@ def getRootPath():
def getDbConfValue():
content = mw.readFile(getConf())
conf = getConf()
if not os.path.exists(conf):
return {}
content = mw.readFile(conf)
rep_scope = "\[database\](.*?)\["
tmp = re.findall(rep_scope, content, re.S)
@@ -207,18 +224,72 @@ def getDbConfValue():
return r
def pMysqlDb():
conf = getDbConfValue()
def pMysqlDb(conf):
host = conf['HOST'].split(':')
conn = mysqlDb.mysqlDb()
# pymysql
db = mw.getMyORM()
# MySQLdb |
# db = mw.getMyORMDb()
conn.setHost(host[0])
conn.setUser(conf['USER'])
conn.setPwd(conf['PASSWD'])
conn.setPort(int(host[1]))
conn.setDb(conf['NAME'])
return conn
db.setPort(int(host[1]))
db.setUser(conf['USER'])
if 'PASSWD' in conf:
db.setPwd(conf['PASSWD'])
else:
db.setPwd(conf['PASSWORD'])
db.setDbName(conf['NAME'])
# db.setSocket(getSocketFile())
db.setCharset("utf8")
return db
def pSqliteDb(conf):
# print(conf)
import db
psDb = db.Sql()
# 默认
gsdir = getServerDir() + '/data'
dbname = 'gitea'
if conf['PATH'][0] == '/':
# 绝对路径
pass
else:
path = conf['PATH'].split('/')
gsdir = getServerDir() + '/' + path[0]
dbname = path[1].split('.')[0]
# print(gsdir, dbname)
psDb.dbPos(gsdir, dbname)
return psDb
def getGiteaDbType(conf):
if 'DB_TYPE' in conf:
return conf['DB_TYPE']
if 'TYPE' in conf:
return conf['TYPE']
return 'NONE'
def pQuery(sql):
conf = getDbConfValue()
gtype = getGiteaDbType(conf)
if gtype == 'sqlite3':
db = pSqliteDb(conf)
data = db.query(sql, []).fetchall()
return data
elif gtype == 'mysql':
db = pMysqlDb(conf)
return db.query(sql)
print("仅支持mysql|sqlite3配置")
exit(0)
def isSqlError(mysqlMsg):
@@ -244,93 +315,66 @@ def isSqlError(mysqlMsg):
return mw.returnData(True, 'OK')
def start():
is_frist = True
conf_bin = getConf()
if os.path.exists(conf_bin):
is_frist = False
def appOp(method):
file = initDreplace()
if is_frist:
return "第一次启动Gogs,默认使用MySQL连接!<br>可以在配置文件中重新设置,再启动!"
if not mw.isAppleSystem():
data = mw.execShell('systemctl ' + method + ' ' + getPluginName())
if data[1] == '':
return 'ok'
return 'fail'
conn = pMysqlDb()
list_table = conn.query('show tables')
data = isSqlError(list_table)
if not data['status']:
return data['msg']
data = mw.execShell(__SR + file + ' start')
data = mw.execShell(__SR + file + ' ' + method)
if data[1] == '':
return 'ok'
return data[0]
def start():
return appOp('start')
def stop():
file = initDreplace()
data = mw.execShell(__SR + file + ' stop')
if data[1] == '':
return 'ok'
return data[1]
return appOp('stop')
def restart():
file = initDreplace()
data = mw.execShell(__SR + file + ' restart')
if data[1] == '':
return 'ok'
return data[1]
return appOp('restart')
def reload():
file = initDreplace()
data = mw.execShell(__SR + file + ' reload')
if data[1] == '':
return 'ok'
return data[1]
return appOp('reload')
def initdStatus():
if not app_debug:
os_name = mw.getOs()
if os_name == 'darwin':
return "Apple Computer does not support"
initd_bin = getInitDFile()
if os.path.exists(initd_bin):
return 'ok'
return 'fail'
if mw.isAppleSystem():
return "Apple Computer does not support"
shell_cmd = 'systemctl status gitea | grep loaded | grep "enabled;"'
data = mw.execShell(shell_cmd)
if data[0] == '':
return 'fail'
return 'ok'
def initdInstall():
import shutil
if not app_debug:
os_name = mw.getOs()
if os_name == 'darwin':
return "Apple Computer does not support"
if mw.isAppleSystem():
return "Apple Computer does not support"
mem_bin = initDreplace()
initd_bin = getInitDFile()
shutil.copyfile(mem_bin, initd_bin)
mw.execShell('chmod +x ' + initd_bin)
mw.execShell('chkconfig --add ' + getPluginName())
mw.execShell('systemctl enable gitea')
return 'ok'
def initdUinstall():
if not app_debug:
os_name = mw.getOs()
if os_name == 'darwin':
return "Apple Computer does not support"
initd_bin = getInitDFile()
os.remove(initd_bin)
mw.execShell('chkconfig --del ' + getPluginName())
if mw.isAppleSystem():
return "Apple Computer does not support"
mw.execShell('systemctl disable gitea')
return 'ok'
def runLog():
log_path = getServerDir() + '/log/gogs.log'
log_path = getServerDir() + '/log/gitea.log'
return log_path
@@ -340,6 +384,10 @@ def postReceiveLog():
def getGogsConf():
conf = getConf()
if not os.path.exists(conf):
return mw.returnJson(False, "请先安装初始化!<br/>默认地址:http://" + mw.getLocalIp() + ":3000")
gets = [
{'name': 'DOMAIN', 'type': -1, 'ps': '服务器域名'},
{'name': 'ROOT_URL', 'type': -1, 'ps': '公开的完整URL路径'},
@@ -360,7 +408,7 @@ def getGogsConf():
{'name': 'SHOW_FOOTER_VERSION', 'type': 2, 'ps': 'Gogs版本信息'},
{'name': 'SHOW_FOOTER_TEMPLATE_LOAD_TIME', 'type': 2, 'ps': 'Gogs模板加载时间'},
]
conf = mw.readFile(getConf())
conf = mw.readFile(conf)
result = []
for g in gets:
@@ -370,7 +418,7 @@ def getGogsConf():
continue
g['value'] = tmp.groups()[0]
result.append(g)
return mw.getJson(result)
return mw.returnJson(True, 'OK', result)
def submitGogsConf():
@@ -402,18 +450,27 @@ def submitGogsConf():
def userList():
conf = getConf()
if not os.path.exists(conf):
return mw.returnJson(False, "请先安装初始化!<br/>默认地址:http://" + mw.getLocalIp() + ":3000")
conf = getDbConfValue()
gtype = getGiteaDbType(conf)
if gtype != 'mysql':
return mw.returnJson(False, "仅支持mysql数据操作!")
import math
args = getArgs()
page = 1
page_size = 10
data = checkArgs(args, ['page', 'page_size'])
if not data[0]:
return data[1]
page = int(args['page'])
page_size = int(args['page_size'])
tojs = args['tojs']
search = ''
if 'page' in args:
page = int(args['page'])
if 'page_size' in args:
page_size = int(args['page_size'])
if 'search' in args:
search = args['search']
@@ -421,17 +478,14 @@ def userList():
data['root_url'] = getRootUrl()
pm = pMysqlDb()
start = (page - 1) * page_size
list_count = pm.query('select count(id) as num from user')
count = list_count[0][0]
list_count = pQuery('select count(id) as num from user')
list_data = pm.query(
count = list_count[0]["num"]
list_data = pQuery(
'select id,name,email from user order by id desc limit ' + str(start) + ',' + str(page_size))
page_info = {'count': count, 'p': page,
'row': page_size, 'tojs': 'gogsUserList'}
data['list'] = mw.getPage(page_info)
data['list'] = mw.getPage(
{'count': count, 'p': page, 'row': page_size, 'tojs': tojs})
data['page'] = page
data['page_size'] = page_size
data['page_count'] = int(math.ceil(count / page_size))
@@ -556,8 +610,8 @@ def projectScriptLoad():
cc_content = mw.readFile(commit_tpl)
sshUrl = 'http://127.0.0.1:' + getHttpPort()
cc_content = cc_content.replace('{$GITROOTURL}', sshUrl)
gitPath = getRootPath()
cc_content = cc_content.replace('{$GITROOTURL}', gitPath)
cc_content = cc_content.replace('{$CODE_DIR}', codeDir)
cc_content = cc_content.replace('{$USERNAME}', user)
cc_content = cc_content.replace('{$PROJECT}', args['name'])
@@ -570,11 +624,9 @@ def projectScriptLoad():
def projectScriptUnload():
args = getArgs()
if not 'user' in args:
return mw.returnJson(True, 'username missing')
if not 'name' in args:
return mw.returnJson(True, 'project name missing')
data = checkArgs(args, ['user', 'name'])
if not data[0]:
return data[1]
user = args['user']
name = args['name'] + '.git'
@@ -591,11 +643,10 @@ def projectScriptUnload():
def projectScriptDebug():
args = getArgs()
if not 'user' in args:
return mw.returnJson(True, 'username missing')
data = checkArgs(args, ['user', 'name'])
if not data[0]:
return data[1]
if not 'name' in args:
return mw.returnJson(True, 'project name missing')
user = args['user']
name = args['name'] + '.git'
commit_log = getRootPath() + '/' + user + '/' + name + \
@@ -634,14 +685,8 @@ def getTotalStatistics():
st = status()
data = {}
if st.strip() == 'start':
pm = pMysqlDb()
list_count = pm.query('select count(id) as num from repository')
if list_count.find("error") > -1:
data['status'] = False
data['count'] = 0
return mw.returnJson(False, 'fail', data)
list_count = pQuery('select count(id) as num from repository')
count = list_count[0]["num"]
data['status'] = True
data['count'] = count
data['ver'] = mw.readFile(getServerDir() + '/version.pl').strip()
+16
View File
@@ -0,0 +1,16 @@
{
"ps": "Gitea 是一个开源社区驱动的轻量级代码托管解决方案。",
"name": "gitea",
"title": "Gitea",
"versions": ["1.17.2"],
"tip": "soft",
"checks": "server/gitea",
"path":"server/gitea",
"author": "gitea",
"date": "2022-10-03",
"home": "https://dl.gitea.io/",
"type": "Git服务器",
"shell": "install.sh",
"pid": "3",
"sort": 7
}
+20
View File
@@ -0,0 +1,20 @@
[Unit]
Description=Gitea (Git with a cup of tea)
After=syslog.target
After=network.target
[Service]
RestartSec=2s
Type=simple
User=git
Group=git
WorkingDirectory={$SERVER_PATH}/gitea
ExecStart={$SERVER_PATH}/gitea/gitea web
Restart=always
Environment=USER=git HOME=/home/git GITEA_WORK_DIR=/var/lib/gitea
RemainAfterExit=yes
#AmbientCapabilities=CAP_NET_BIND_SERVICE
#CapabilityBoundingSet=CAP_NET_BIND_SERVICE
[Install]
WantedBy=multi-user.target
+110
View File
@@ -0,0 +1,110 @@
#!/bin/sh
#
# /etc/rc.d/init.d/Gitea
#
# Runs the Gogs
#
#
# chkconfig: - 85 15
#
### BEGIN INIT INFO
# Provides: Gitea
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Should-Start: mysql postgresql
# Should-Stop: mysql postgresql
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start Gitea at boot time.
# Description: Control Gitea.
### END INIT INFO
# Source function library.
if [ -f /etc/init.d/functions ];then
. /etc/init.d/functions
fi
if [ -f /etc/rc.d/init.d/functions ];then
. /etc/rc.d/init.d/functions
fi
# Default values
export HOME={$HOME_DIR}
export USER={$RUN_USER}
NAME=gitea
GOGS_HOME={$SERVER_PATH}/gitea
GOGS_PATH=${GOGS_HOME}/$NAME
GOGS_USER={$RUN_USER}
SERVICENAME="gitea"
LOCKFILE=/tmp/gitea.lock
LOGPATH=${GOGS_HOME}/log
LOGFILE=${LOGPATH}/gitea.log
RETVAL=0
[ -r /etc/sysconfig/$NAME ] && . /etc/sysconfig/$NAME
DAEMON_OPTS="--check $NAME"
[ ! -z "$GOGS_USER" ] && DAEMON_OPTS="$DAEMON_OPTS --user=${GOGS_USER}"
status(){
isStart=`ps -ef|grep 'gitea web' |grep -v grep|awk '{print $2}'`
if [ "$isStart" == '' ];then
echo -e "${SERVICENAME} not running"
else
echo -e "${SERVICENAME}(pid $(echo $isStart)) already running"
fi
}
start() {
isStart=`ps -ef|grep 'gitea web' |grep -v grep|awk '{print $2}'`
if [ "$isStart" != '' ];then
echo "${SERVICENAME}(pid $(echo $isStart)) already running"
return $RETVAL
fi
cd ${GOGS_HOME}
echo -e "Starting ${SERVICENAME}: \c"
${GOGS_PATH} web > ${LOGFILE} 2>&1 &
RETVAL=$?
[ $RETVAL = 0 ] && touch ${LOCKFILE} && echo -e "\033[32mdone\033[0m"
return $RETVAL
}
stop() {
pids=`ps -ef|grep 'gitea web' |grep -v grep|awk '{print $2}'`
arr=($pids)
echo -e "Stopping gitea... \c"
for p in ${arr[@]}
do
kill -9 $p
done
echo -e "\033[32mdone\033[0m"
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status
;;
restart)
stop
start
;;
reload)
stop
start
;;
*)
echo "Usage: ${NAME} {start|stop|status|restart}"
exit 1
;;
esac
exit $RETVAL
+111
View File
@@ -0,0 +1,111 @@
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
curPath=`pwd`
rootPath=$(dirname "$curPath")
rootPath=$(dirname "$rootPath")
serverPath=$(dirname "$rootPath")
install_tmp=${rootPath}/tmp/mw_install.pl
if [ -f ${rootPath}/bin/activate ];then
source ${rootPath}/bin/activate
fi
URL_DOWNLOAD=https://dl.gitea.io/
getOs(){
os=`uname`
if [ "Darwin" == "$os" ];then
echo 'darwin'
else
echo 'linux'
fi
return 0
}
getBit(){
echo `getconf LONG_BIT`
}
Install_App()
{
mkdir -p $serverPath/source/gitea
if id git &> /dev/null ;then
echo "git UID is `id -u git`"
echo "git Shell is `grep "^git:" /etc/passwd |cut -d':' -f7 `"
else
groupadd git
useradd -g git git
fi
echo '正在安装脚本文件...' > $install_tmp
version=$1
os=`getOs`
git config --global push.default simple
if [ "darwin" == "$os" ];then
file=gitea-${version}-darwin-10.12-amd64
else
file=gitea-${version}-linux-amd64
fi
file_xz="${file}.xz"
echo "wget -O $serverPath/source/gitea/$file_xz ${URL_DOWNLOAD}/gitea/${version}/${file_xz}"
if [ ! -f $serverPath/source/gitea/$file_xz ];then
wget -O $serverPath/source/gitea/$file_xz ${URL_DOWNLOAD}/gitea/${version}/${file_xz}
fi
cd $serverPath/source/gitea && xz -k -d $file_xz
if [ -f $file ];then
mkdir -p $serverPath/gitea
mv $serverPath/source/gitea/$file $serverPath/gitea/gitea
chmod +x $serverPath/gitea/gitea
chown -R git:git $serverPath/gitea
fi
if [ -d $serverPath/gitea ];then
echo $version > $serverPath/gitea/version.pl
cd ${rootPath} && python3 plugins/gitea/index.py start
cd ${rootPath} && python3 plugins/gitea/index.py initd_install
fi
echo 'install success' > $install_tmp
}
Uninstall_App()
{
if [ -f /usr/lib/systemd/system/gitea.service ];then
systemctl stop gitea
systemctl disable gitea
rm -rf /usr/lib/systemd/system/gitea.service
systemctl daemon-reload
fi
if [ -f $serverPath/gitea/initd/gitea ];then
$serverPath/gitea/initd/gitea stop
fi
rm -rf $serverPath/gitea
echo 'uninstall success' > $install_tmp
}
action=$1
version=$2
if [ "${1}" == 'install' ];then
Install_App $version
else
Uninstall_App $version
fi
+353
View File
@@ -0,0 +1,353 @@
function str2Obj(str){
var data = {};
kv = str.split('&');
for(i in kv){
v = kv[i].split('=');
data[v[0]] = v[1];
}
return data;
}
function gogsPost(method,args,callback, title){
var _args = null;
if (typeof(args) == 'string'){
_args = JSON.stringify(str2Obj(args));
} else {
_args = JSON.stringify(args);
}
var _title = '正在获取...';
if (typeof(title) != 'undefined'){
_title = title;
}
var loadT = layer.msg(_title, { icon: 16, time: 0, shade: 0.3 });
$.post('/plugins/run', {name:'gitea', func:method, args:_args}, function(data) {
layer.close(loadT);
if (!data.status){
layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']});
return;
}
if(typeof(callback) == 'function'){
callback(data);
}
},'json');
}
function gogsSetConfig(){
gogsPost('get_gogs_conf', '', function(data){
var rrdata = $.parseJSON(data.data);
if (!rrdata.status){
layer.msg(rrdata.msg,{icon:0,time:2000,shade: [0.3, '#000']});
return;
}
var rdata = rrdata.data;
var mlist = '';
for (var i = 0; i < rdata.length; i++) {
var w = '140';
if (rdata[i].name == 'error_reporting') w = '250';
var ibody = '<input style="width: ' + w + 'px;" class="bt-input-text mr5" name="' + rdata[i].name + '" value="' + rdata[i].value + '" type="text" >';
switch (rdata[i].type) {
case 0:
var selected_1 = (rdata[i].value == 1) ? 'selected' : '';
var selected_0 = (rdata[i].value == 0) ? 'selected' : '';
ibody = '<select class="bt-input-text mr5" name="' + rdata[i].name + '" style="width: ' + w + 'px;">\
<option value="1" ' + selected_1 + '>开启</option>\
<option value="0" ' + selected_0 + '>关闭</option>\
</select>';
break;
case 1:
var selected_1 = (rdata[i].value == 'On') ? 'selected' : '';
var selected_0 = (rdata[i].value == 'Off') ? 'selected' : '';
ibody = '<select class="bt-input-text mr5" name="' + rdata[i].name + '" style="width: ' + w + 'px;">\
<option value="On" ' + selected_1 + '>开启</option>\
<option value="Off" ' + selected_0 + '>关闭</option></select>'
break;
case 2:
var selected_1 = (rdata[i].value == 'true') ? 'selected' : '';
var selected_0 = (rdata[i].value == 'false') ? 'selected' : '';
ibody = '<select class="bt-input-text mr5" name="' + rdata[i].name + '" style="width: ' + w + 'px;">\
<option value="true" ' + selected_1 + '>开启</option>\
<option value="false" ' + selected_0 + '>关闭</option></select>'
break;
}
mlist += '<p><span>' + rdata[i].name + '</span>' + ibody + ', <font>' + rdata[i].ps + '</font></p>'
}
var html = '<style>.conf_p p{margin-bottom: 2px}</style><div class="conf_p" style="margin-bottom:0">\
' + mlist + '\
<div style="margin-top:10px; padding-right:15px" class="text-right">\
<button class="btn btn-success btn-sm mr5" onclick="gogsSetConfig()">刷新</button>\
<button class="btn btn-success btn-sm" onclick="submitGogsConf()">保存</button></div>\
</div>';
$(".soft-man-con").html(html);
});
}
//提交PHP配置
function submitGogsConf() {
var data = {
DOMAIN: $("input[name='DOMAIN']").val(),
ROOT_URL: $("input[name='ROOT_URL']").val(),
HTTP_ADDR: $("select[name='HTTP_ADDR']").val(),
HTTP_PORT: $("input[name='HTTP_PORT']").val(),
START_SSH_SERVER: $("select[name='START_SSH_SERVER']").val() || 'false',
SSH_PORT: $("input[name='SSH_PORT']").val(),
REQUIRE_SIGNIN_VIEW: $("select[name='REQUIRE_SIGNIN_VIEW']").val() || 'false',
ENABLE_CAPTCHA: $("select[name='ENABLE_CAPTCHA']").val() || 'true',
DISABLE_REGISTRATION: $("select[name='DISABLE_REGISTRATION']").val() || 'false',
ENABLE_NOTIFY_MAIL: $("select[name='ENABLE_NOTIFY_MAIL']").val() || 'false',
FORCE_PRIVATE: $("select[name='FORCE_PRIVATE']").val() || 'false',
SHOW_FOOTER_BRANDING: $("select[name='SHOW_FOOTER_BRANDING']").val() || 'false',
SHOW_FOOTER_VERSION: $("select[name='SHOW_FOOTER_VERSION']").val() || 'false',
SHOW_FOOTER_TEMPLATE_LOAD_TIME: $("select[name='SHOW_FOOTER_TEMPLATE_LOAD_TIME']").val() || 'false',
};
gogsPost('submit_gogs_conf', data, function(ret_data){
var rdata = $.parseJSON(ret_data.data);
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
gogsSetConfig();
});
}
function gogsEdit(){
gogsPost('gogs_edit',{} , function(data){
// console.log(data);
var rdata = $.parseJSON(data.data);
var edit = '<p class="status">通用的手动编辑:</p>';
edit +='<div class="sfm-opt">\
<button class="btn btn-default btn-sm" onclick="onlineEditFile(0,\''+rdata['post_receive']+'\');">post-receive.tpl</button>\
<button class="btn btn-default btn-sm" onclick="onlineEditFile(0,\''+rdata['commit']+'\');">commit.tpl</button>\
</div>';
$(".soft-man-con").html(edit);
});
}
function giteaUserList(page, search) {
var _data = {};
if (typeof(page) =='undefined'){
var page = 1;
}
_data['page'] = page;
_data['page_size'] = 10;
if(typeof(search) != 'undefined'){
_data['search'] = search;
}
_data['tojs'] = 'giteaUserList';
gogsPost('user_list', _data, function(data){
var rdata = $.parseJSON(data.data);
if (!rdata.status){
layer.msg(rdata.msg,{icon:0,time:2000,shade: [0.3, '#000']});
return;
}
content = '<div class="finduser"><input class="bt-input-text mr5 outline_no" type="text" placeholder="查找用户名" id="find_user" style="height: 28px; border-radius: 3px;width: 435px;">';
content += '<button class="btn btn-success btn-sm" onclick="userFind();">查找</button></div>';
content += '<div class="divtable" style="margin-top:5px;"><table class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0">';
content += '<thead><tr>';
content += '<th>序号</th>';
content += '<th>用户或组织</th>';
content += '<th>邮件地址</th>';
content += '<th>操作(<a href="'+rdata['data']['root_url']+'" class="btlink" target="_blank">WEB管理</a>)</th>';
content += '</tr></thead>';
content += '<tbody>';
ulist = rdata['data']['data'];
for (i in ulist){
email = ulist[i]["email"] == '' ? '无' : ulist[i]["email"];
content += '<tr><td>'+ulist[i]["id"]+'</td>'+
'<td>'+ulist[i]["name"]+'</td>'+
'<td>'+email+'</td>'+
'<td><a class="btlink" onclick="userProjectList(\''+ulist[i]["name"]+'\')">项目管理</a></td>'+
'</tr>';
}
content += '</tbody>';
content += '</table></div>';
var page = '<div class="dataTables_paginate paging_bootstrap pagination" style="margin-top:0px;"><ul id="softPage" class="page"><div>';
page += rdata['data']['list'];
page += '</div></ul></div>';
content += page;
$(".soft-man-con").html(content);
});
}
function userProjectList(user, search){
var req = {};
if (!isNaN(user)){
req['page'] = user;
req['name'] = user = getCookie('gogsUserSelected');
} else {
req['page'] = 1;
req['name'] = user;
setCookie('gogsUserSelected', user);
}
req['page_size'] = 5;
req['search'] = '';
if(typeof(search) != 'undefined'){
req['search'] = search;
}
$('.layui-layer-close1').click();
gogsPost('user_project_list', req, function(data){
var rdata = [];
try {
rdata = $.parseJSON(data.data);
} catch(e){}
if (!rdata['status']){
layer.msg(rdata['msg'], { icon: 2 });
return;
}
var list = '';
// console.log(rdata);
var project_list = rdata['data']['data'];
for (i in project_list) {
var name = project_list[i]['name'];
list += '<tr><td>'+name+'</td>\
<td>\
<a class="btlink" target="_blank" href="'+rdata['data']['root_url']+user+'/'+name+'">源码</a> | \
<a class="btlink" onclick="projectScript(\''+user+'\',\''+name+'\','+project_list[i]['has_hook']+');">脚本</a>\
</td>\
</tr>';
}
var page = '<div class="dataTables_paginate paging_bootstrap pagination" style="margin-top:0px;"><ul id="softPage" class="page"><div>';
page += rdata['data']['list'];
page += '</div></ul></div>';
var loadOpen = layer.open({
type: 1,
title: '用户('+user+')项目列表',
area: '500px',
content:"<div class='bt-form pd20 c6'>\
<div>\
<div class='divtable' style='margin-top:5px;'>\
<table class='table table-hover'>\
<thead><tr><th>项目</th><th>操作</th></tr></thead>\
<tbody>" + list + "</tbody>\
</table>" +
page +
"</div></div></div>"
});
});
}
function projectScript(user, name,has_hook){
// console.log(user,name,has_hook);
var html = '';
if (has_hook){
html += '<button onclick="projectScriptEdit(\''+user+'\',\''+name+'\')" class="btn btn-default btn-sm">手动编辑</button>';
html += '<button onclick="projectScriptDebug(\''+user+'\',\''+name+'\')" class="btn btn-default btn-sm">调试日志</button>';
html += '<button onclick="projectScriptLoad(\''+user+'\',\''+name+'\')" class="btn btn-default btn-sm">重新加载</button>';
html += '<button onclick="projectScriptUnload(\''+user+'\',\''+name+'\')" class="btn btn-default btn-sm">卸载脚本</button>';
} else {
html += '<button onclick="projectScriptLoad(\''+user+'\',\''+name+'\')" class="btn btn-default btn-sm">加载脚本</button>';
}
var loadOpen = layer.open({
type: 1,
title: '['+user+']['+name+']脚本设置',
area: '240px',
content:'<div class="change-default pd20">'+html+'</div>'
});
}
function projectScriptEdit(user,name){
gogsPost('project_script_edit', {'user':user,'name':name}, function(data){
var rdata = $.parseJSON(data.data);
if (rdata['status']){
onlineEditFile(0, rdata['data']['path']);
} else {
layer.msg(rdata.msg,{icon:1,time:2000,shade: [0.3, '#000']});
}
});
}
function projectScriptLoad(user,name){
gogsPost('project_script_load', {'user':user,'name':name}, function(data){
if (data.data != 'ok'){
layer.msg(data.data,{icon:0,time:2000,shade: [0.3, '#000']});
return;
}
layer.msg('加载成功!',{icon:1,time:2000,shade: [0.3, '#000']});
setTimeout(function(){
userProjectList(1);
}, 2000);
});
}
function projectScriptUnload(user,name){
gogsPost('project_script_unload', {'user':user,'name':name}, function(data){
if (data.data != 'ok'){
layer.msg(data.data,{icon:0,time:2000,shade: [0.3, '#000']});
return;
}
layer.msg('卸载成功!',{icon:1,time:2000,shade: [0.3, '#000']});
setTimeout(function(){
userProjectList(1);
}, 2000);
});
}
function projectScriptDebug(user,name){
gogsPost('project_script_debug', {'user':user,'name':name}, function(data){
var rdata = $.parseJSON(data.data);
if (rdata['status']){
onlineEditFile(0, rdata['path']);
} else {
layer.msg(rdata.msg,{icon:1,time:2000,shade: [0.3, '#000']});
}
});
}
function getRsaPublic(){
gogsPost('get_rsa_public', {}, function(data){
var rdata = $.parseJSON(data.data);
var con = '<div class="tab-con">\
<div class="myKeyCon ptb15">\
<textarea style="margin:0px;width:580px;height:110px;outline:none;" spellcheck="false">'+rdata.mw+'</textarea>\
</div>\
<ul class="help-info-text c7 pull-left"></ul>\
</div>'
layer.open({
type: 1,
area: "600px",
title: '本机公钥',
closeBtn: 2,
shift: 5,
shadeClose: false,
content:con
});
});
}
function giteaRead(){
var readme = '<ul class="help-info-text c7">';
readme += '<li>默认使用MySQL,第一个启动加载各种配置,并修改成正确的数据库配置</li>';
readme += '<li>邮件端口使用456,gogs仅支持使用STARTTLS的SMTP协议</li>';
readme += '<li>如果使用项目中脚本本地同步,<a target="_blank" href="https://github.com/midoks/mdserver-web/wiki/%E6%8F%92%E4%BB%B6%E7%AE%A1%E7%90%86%5Bgogs%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E%5D#%E5%90%AF%E5%8A%A8gogs%E5%90%8E%E5%A6%82%E6%9E%9C%E8%A6%81%E4%BD%BF%E7%94%A8hook%E8%84%9A%E6%9C%AC%E5%90%8C%E6%AD%A5%E4%BB%A3%E7%A0%81%E9%9C%80%E8%A6%81%E5%BC%80%E5%90%AFssh%E7%AB%AF%E5%8F%A3">点击查看</></li>';
readme += '<li><a href="#" onclick="getRsaPublic();">点击查看本机公钥</></li>';
readme += '</ul>';
$('.soft-man-con').html(readme);
}
+5
View File
@@ -462,6 +462,11 @@ def userList():
if not os.path.exists(conf):
return mw.returnJson(False, "请先安装初始化!<br/>默认地址:http://" + mw.getLocalIp() + ":3000")
conf = getDbConfValue()
gtype = getGogsDbType(conf)
if gtype != 'mysql':
return mw.returnJson(False, "仅支持mysql数据操作!")
import math
args = getArgs()
-1
View File
@@ -29,7 +29,6 @@ getBit(){
Install_gogs()
{
pip3 install mysqlclient
mkdir -p $serverPath/source/gogs
+5 -1
View File
@@ -817,6 +817,7 @@ function openPhpmyadmin(name,username,password){
layer.msg('当前为['+rdata.choose+']模式,若要使用请切换模式.',{icon:2,shade: [0.3, '#000']});
return;
}
var phpmyadmin_cfg = rdata;
data = syncPost('/plugins/run',{'name':'phpmyadmin','func':'get_home_page'});
var rdata = $.parseJSON(data.data);
@@ -824,7 +825,10 @@ function openPhpmyadmin(name,username,password){
layer.msg(rdata.msg,{icon:2,shade: [0.3, '#000']});
return;
}
$("#toPHPMyAdmin").attr('action',rdata.data);
var home_page = rdata.data;
home_page = home_page.replace("http://","http://"+phpmyadmin_cfg['username']+":"+phpmyadmin_cfg['password']+"@");
$("#toPHPMyAdmin").attr('action',home_page);
if($("#toPHPMyAdmin").attr('action').indexOf('phpmyadmin') == -1){
layer.msg('请先安装phpMyAdmin',{icon:2,shade: [0.3, '#000']});
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+27 -4
View File
@@ -68,6 +68,26 @@ function myAsyncPost(method,args){
return syncPost('/plugins/run', {name:'mysql', func:method, args:_args});
}
function vaildPhpmyadmin(url,username,password){
console.log("Authorization: Basic " + btoa(username + ":" + password));
$.ajax({
type: "GET",
url: url,
dataType: 'json',
async: false,
username:username,
password:password,
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
data: 'vaild',
success: function (){
alert('Thanks for your comment!');
}
});
}
function runInfo(){
myPost('run_info','',function(data){
@@ -818,16 +838,19 @@ function openPhpmyadmin(name,username,password){
layer.msg('当前为[mariadb]模式,若要使用请切换模式.',{icon:2,shade: [0.3, '#000']});
return;
}
// console.log(data);
var phpmyadmin_cfg = rdata;
data = syncPost('/plugins/run',{'name':'phpmyadmin','func':'get_home_page'});
var rdata = $.parseJSON(data.data);
if (!rdata.status){
layer.msg(rdata.msg,{icon:2,shade: [0.3, '#000']});
return;
}
$("#toPHPMyAdmin").attr('action',rdata.data);
var home_page = rdata.data;
home_page = home_page.replace("http://","http://"+phpmyadmin_cfg['username']+":"+phpmyadmin_cfg['password']+"@")
$("#toPHPMyAdmin").attr('action',home_page);
if($("#toPHPMyAdmin").attr('action').indexOf('phpmyadmin') == -1){
layer.msg('请先安装phpMyAdmin',{icon:2,shade: [0.3, '#000']});
setTimeout(function(){ window.location.href = '/soft'; },3000);
@@ -836,7 +859,7 @@ function openPhpmyadmin(name,username,password){
//检查版本
data = syncPost('/plugins/run',{'name':'phpmyadmin','func':'version'});
bigVer = data.data.split('.')[0]
bigVer = data.data.split('.')[0];
if (bigVer>=4.5){
setTimeout(function(){
+2 -2
View File
@@ -17,7 +17,7 @@ sysName=`uname`
install_tmp=${rootPath}/tmp/mw_install.pl
mysqlDir=${serverPath}/source/mysql
VERSION="5.7.37"
VERSION="5.7.39"
Install_mysql()
@@ -68,7 +68,7 @@ Install_mysql()
fi
#检测文件是否损坏.
md5_mysql_ok=d0489fc3880248a58759c50bfb286dbb
md5_mysql_ok=db1b672fc257bd46356c7af26dd22801
if [ -f ${mysqlDir}/mysql-boost-${VERSION}.tar.gz ];then
md5_mysql=`md5sum ${mysqlDir}/mysql-boost-${VERSION}.tar.gz | awk '{print $1}'`
if [ "${md5_mysql_ok}" == "${md5_mysql}" ]; then
+2 -2
View File
@@ -1,6 +1,6 @@
lua_shared_dict limit 30m;
lua_shared_dict drop_ip 30m;
lua_shared_dict drop_sum 30m;
lua_shared_dict drop_ip 10m;
lua_shared_dict drop_sum 10m;
lua_package_path "{$WAF_PATH}/lua/?.lua;{$ROOT_PATH}/openresty/lualib/?.lua;;";
access_by_lua_file {$WAF_PATH}/lua/init.lua;
+1 -1
View File
@@ -232,7 +232,7 @@
<p onclick="wafGloabl();">全局配置</p>
<p onclick="wafSite();">站点配置</p>
<p onclick="wafHistory();">封锁历史</p>
<!-- <p onclick="wafLogs();">操作日志</p> -->
<p onclick="wafLogs();">操作日志</p>
</div>
<!-- lib-con -->
<div class="bt-w-con pd15">
+39 -5
View File
@@ -111,7 +111,7 @@ def initSiteInfo():
tmp['log'] = True
tmp['get'] = True
tmp['post'] = True
tmp['open'] = False
tmp['open'] = True
tmp['cc'] = config_contents['cc']
tmp['retry'] = config_contents['retry']
@@ -122,7 +122,22 @@ def initSiteInfo():
tmp['scan'] = config_contents['scan']
cdn_header = ['x-forwarded-for',
'x-real-ip', 'HTTP_CF_CONNECTING_IP']
'x-real-ip',
'x-forwarded',
'forwarded-for',
'forwarded',
'true-client-ip',
'client-ip',
'ali-cdn-real-ip',
'cdn-src-ip',
'cdn-real-ip',
'cf-connecting-ip',
'cf-connecting-ip',
'x-cluster-client-ip',
'wl-proxy-client-ip',
'proxy-client-ip',
'true-client-ip',
'HTTP_CF_CONNECTING_IP']
tmp['cdn_header'] = cdn_header
disable_upload_ext = ["php", "jsp"]
@@ -163,6 +178,7 @@ def initTotalInfo():
tmp['get'] = 0
tmp['post'] = 0
tmp['total'] = 0
tmp['url_ext'] = 0
_name = {}
_name[name] = tmp
total_contents['sites'] = _name
@@ -186,10 +202,12 @@ def status():
def contentReplace(content):
service_path = mw.getServerDir()
waf_path = getServerDir() + "/waf"
waf_root = getServerDir()
waf_path = waf_root + "/waf"
content = content.replace('{$ROOT_PATH}', mw.getRootDir())
content = content.replace('{$SERVER_PATH}', service_path)
content = content.replace('{$WAF_PATH}', waf_path)
content = content.replace('{$WAF_ROOT}', waf_root)
return content
@@ -201,6 +219,14 @@ def initDreplace():
cmd = 'cp -rf ' + sdir + ' ' + path
mw.execShell(cmd)
logs_path = path + '/logs'
if not os.path.exists(logs_path):
mw.execShell('mkdir -p ' + logs_path)
debug_log = path + '/debug.log'
if not os.path.exists(debug_log):
mw.execShell('echo "" > ' + debug_log)
config = path + '/waf/config.json'
content = mw.readFile(config)
content = json.loads(content)
@@ -214,6 +240,11 @@ def initDreplace():
content = contentReplace(content)
mw.writeFile(config, content)
config_common = path + "/waf/lua/common.lua"
content = mw.readFile(config_common)
content = contentReplace(content)
mw.writeFile(config_common, content)
waf_conf = mw.getServerDir() + "/openresty/nginx/conf/luawaf.conf"
waf_tpl = getPluginDir() + "/conf/luawaf.conf"
content = mw.readFile(waf_tpl)
@@ -224,6 +255,9 @@ def initDreplace():
initSiteInfo()
initTotalInfo()
if not mw.isAppleSystem():
mw.execShell("chown -R www:www " + path)
def start():
initDreplace()
@@ -800,7 +834,7 @@ def getLogsList():
return data[1]
data = []
path = mw.getLogsDir() + '/waf'
path = getServerDir() + '/logs'
if not os.path.exists(path):
return mw.returnJson(False, '还未生成!', [])
@@ -823,7 +857,7 @@ def getSafeLogs():
if not data[0]:
return data[1]
path = mw.getLogsDir() + '/waf'
path = getServerDir() + '/logs'
file = path + '/' + args['siteName'] + '_' + args['toDate'] + '.log'
if not os.path.exists(file):
return mw.returnJson(False, "文件不存在!")
+2 -2
View File
@@ -19,12 +19,12 @@ Install_of(){
echo '0.1' > $serverPath/op_waf/version.pl
echo 'install ok' > $install_tmp
cd ${rootPath} && python3 plugins/op_waf/index.py start
cd ${rootPath} && python3 ${rootPath}/plugins/op_waf/index.py start
}
Uninstall_of(){
cd ${rootPath} && python3 plugins/op_waf/index.py stop
cd ${rootPath} && python3 ${rootPath}/plugins/op_waf/index.py stop
rm -rf $serverPath/op_waf
}
+17 -17
View File
@@ -28,7 +28,7 @@ function setRequestCode(ruleName, statusCode){
title: "设置响应代码【" + ruleName + "】",
area: '300px',
shift: 5,
closeBtn: 2,
closeBtn: 1,
shadeClose: true,
content: '<div class="bt-form pd20 pb70">\
<div class="line">\
@@ -144,7 +144,7 @@ function setCcRule(cycle, limit, endtime, siteName, increase){
type: 1,
title: "设置CC规则",
area: '540px',
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<form class="bt-form pd20 pb70">\
<div class="line">\
@@ -184,7 +184,7 @@ function setRetry(retry_cycle, retry, retry_time, siteName) {
type: 1,
title: "设置恶意容忍规则",
area: '500px',
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<form class="bt-form pd20 pb70">\
<div class="line">\
@@ -339,7 +339,7 @@ function setObjConf(ruleName, type) {
type: 1,
title: "编辑规则【" + ruleName + "】",
area: ['700px', '530px'],
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<div class="pd15">\
<div style="border-bottom:#ccc 1px solid;margin-bottom:10px;padding-bottom:10px">\
@@ -405,7 +405,7 @@ function scanRule() {
type: 1,
title: "常用扫描器过滤规则",
area: '650px',
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<form class="bt-form pd20 pb70">\
<div class="line">\
@@ -571,7 +571,7 @@ function ipWhite(type) {
type: 1,
title: "管理IP白名单",
area: ['500px', '500px'],
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<div class="pd15 ipv4_list">\
<div style="border-bottom:#ccc 1px solid;margin-bottom:10px;padding-bottom:10px">\
@@ -714,7 +714,7 @@ function ipBlack(type) {
type: 1,
title: "管理IP黑名单",
area: ['500px', '500px'],
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<div class="tab_list"><div class="tab_block active">IPv4黑名单</div><div class="tab_block">IPv6黑名单</div></div>\
<div class="pd15 ipv4_block">\
@@ -824,12 +824,12 @@ function wafScreen(){
<div class="line"><span class="name">CC攻击</span><span class="val">'+rdata.rules.cc+'</span></div>\
<div class="line"><span class="name">恶意User-Agent</span><span class="val">'+rdata.rules.user_agent+'</span></div>\
<div class="line"><span class="name">Cookie渗透</span><span class="val">'+rdata.rules.cookie+'</span></div>\
<div class="line"><span class="name">恶意扫描</span><span class="val">0</span></div>\
<div class="line"><span class="name">恶意扫描</span><span class="val">'+rdata.rules.scan+'</span></div>\
<div class="line"><span class="name">恶意HEAD请求</span><span class="val">0</span></div>\
<div class="line"><span class="name">URI自定义拦截</span><span class="val">0</span></div>\
<div class="line"><span class="name">URI保护</span><span class="val">0</span></div>\
<div class="line"><span class="name">URI自定义拦截</span><span class="val">'+rdata.rules.args+'</span></div>\
<div class="line"><span class="name">URI保护</span><span class="val">'+rdata.rules.args+'</span></div>\
<div class="line"><span class="name">恶意文件上传</span><span class="val">0</span></div>\
<div class="line"><span class="name">禁止的扩展名</span><span class="val">0</span></div>\
<div class="line"><span class="name">禁止的扩展名</span><span class="val">'+rdata.rules.url_ext+'</span></div>\
<div class="line"><span class="name">禁止PHP脚本</span><span class="val">0</span></div>\
</div>';
@@ -975,7 +975,7 @@ function siteWafLog(siteName) {
type: 1,
title: "日志【" + siteName + "】",
area: ['880px', '500px'],
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<div class="lib-box pd15 lib-box-log">\
<div class="lib-con-title" style="height:40px"><select id="selectLogDay" class="bt-input-text" onchange="siteLogCon(\''+ siteName + '\',this.options[this.options.selectedIndex].value,1)">' + selectLogDay + '</select></div>\
@@ -1071,7 +1071,7 @@ function siteLogCon(siteName, day, page) {
type: 1,
title: time + "详情",
area: '600px',
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<div class="pd15 lib-box">\
<table class="table" style="border:#ddd 1px solid; margin-bottom:10px">\
@@ -1190,7 +1190,7 @@ function siteRuleAdmin(siteName, ruleName, type) {
type: 1,
title: "管理网站过滤规则【" + title + "】",
area: ['500px', '500px'],
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<div class="pd15">\
<div style="border-bottom:#ccc 1px solid;margin-bottom:10px;padding-bottom:10px">\
@@ -1237,7 +1237,7 @@ function cdnHeader(siteName, type) {
type: 1,
title: "管理网站【" + siteName + "】CDN-Headers",
area: ['500px', '500px'],
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<div class="pd15">\
<div style="border-bottom:#ccc 1px solid;margin-bottom:10px;padding-bottom:10px">\
@@ -1342,7 +1342,7 @@ function setSiteObjConf(siteName, ruleName, type) {
type: 1,
title: "编辑网站【" + siteName + "】规则【" + ruleName + "】",
area: ['700px', '530px'],
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<div class="pd15">\
<div class="divtable">\
@@ -1394,7 +1394,7 @@ function siteWafConfig(siteName, type) {
type: 1,
title: "网站配置【" + siteName + "】",
area: ['700px', '500px'],
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<div id="s_w_c"></div>'
});
+173
View File
@@ -0,0 +1,173 @@
# coding:utf-8
import sys
import io
import os
import time
import json
import os
import sys
import time
import string
import json
import hashlib
import shlex
import datetime
import subprocess
import re
from random import Random
TEST_URL = "http://t1.cn/"
# TEST_URL = "https://www.zzzvps.com/"
def httpGet(url, timeout=10):
import urllib.request
try:
req = urllib.request.urlopen(url, timeout=timeout)
result = req.read().decode('utf-8')
return result
except Exception as e:
return str(e)
def httpGet__UA(url, ua, timeout=10):
import urllib.request
headers = {'user-agent': ua}
try:
req = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(req)
result = response.read().decode('utf-8')
return result
except Exception as e:
return str(e)
def httpPost(url, data, timeout=10):
"""
发送POST请求
@url 被请求的URL地址(必需)
@data POST参数,可以是字符串或字典(必需)
@timeout 超时时间默认60秒
return string
"""
if sys.version_info[0] == 2:
try:
import urllib
import urllib2
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
data = urllib.urlencode(data)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req, timeout=timeout)
return response.read()
except Exception as ex:
return str(ex)
else:
try:
import urllib.request
import ssl
try:
ssl._create_default_https_context = ssl._create_unverified_context
except:
pass
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req, timeout=timeout)
result = response.read()
if type(result) == bytes:
result = result.decode('utf-8')
return result
except Exception as ex:
return str(ex)
def test_Dir():
'''
目录保存
'''
url = TEST_URL + '?t=../etc/passwd'
print("args test start")
url_val = httpGet(url, 10)
# print(url_val)
print("args test end")
def test_UA():
'''
user-agent 过滤
'''
url = TEST_URL
print("user-agent test start")
url_val = httpGet__UA(url, 'ApacheBench')
print(url_val)
print("user-agent test end")
def test_POST():
'''
user-agent 过滤
'''
url = TEST_URL
print("POST test start")
url_val = httpPost(url, {'data': "substr($mmsss,0,1)"})
# url_val = httpPost(url, {'data': "123123"})
print(url_val)
print("POST test end")
def test_scan():
'''
目录保存
'''
url = TEST_URL + '/acunetix_wvs_security_test?t=1'
print("scan test start")
url_val = httpGet(url, 10)
print(url_val)
print("scan test end")
def test_CC():
'''
目录保存
'''
url = TEST_URL + 'ok.txt'
print("CC test start")
for x in range(122):
url_val = httpGet(url, 10)
print(url_val)
print("CC test end")
def test_url_ext():
'''
目录保存
'''
url = TEST_URL + 't.sql'
print("url_ext start")
url_val = httpGet(url, 10)
print(url_val)
print("url_ext end")
def test_start():
# test_Dir()
# test_UA()
# test_POST()
# test_scan()
# test_CC()
test_url_ext()
if __name__ == "__main__":
os.system('cd /Users/midoks/Desktop/mwdev/server/mdserver-web/plugins/op_waf && sh install.sh uninstall 0.1 && sh install.sh install 0.1')
os.system('cd /Users/midoks/Desktop/mwdev/server/mdserver-web/ && python3 plugins/openresty/index.py stop && python3 plugins/openresty/index.py start')
test_start()
View File
+9
View File
@@ -0,0 +1,9 @@
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
# yum -y install httpd-tools
# ab -c 1000 -n 1000000 http://xx.xx.xx/
python3 index.py
+158
View File
@@ -0,0 +1,158 @@
# coding:utf-8
import sys
import io
import os
import time
import json
sys.path.append(os.getcwd() + "/class/core")
import mw
app_debug = False
if mw.isAppleSystem():
app_debug = True
def getPluginName():
return 'op_waf'
def getPluginDir():
return mw.getPluginDir() + '/' + getPluginName()
def getServerDir():
return mw.getServerDir() + '/' + getPluginName()
def getTaskConf():
conf = getServerDir() + "/task_config.json"
return conf
def getConfigData():
try:
return json.loads(mw.readFile(getTaskConf()))
except:
pass
return []
def getConfigTpl():
tpl = {
"name": "",
"task_id": -1,
}
return tpl
def createBgTask():
removeBgTask()
args = {
"period": "minute-n",
"minute-n": "3",
}
createBgTaskByName(getPluginName(), args)
def createBgTaskByName(name, args):
cfg = getConfigTpl()
_name = "[勿删]OP防火墙后台任务[" + name + "]"
res = mw.M("crontab").field("id, name").where("name=?", (_name,)).find()
if res:
return True
if "task_id" in cfg.keys() and cfg["task_id"] > 0:
res = mw.M("crontab").field("id, name").where(
"id=?", (cfg["task_id"],)).find()
if res and res["id"] == cfg["task_id"]:
print("计划任务已经存在!")
return True
import crontab_api
api = crontab_api.crontab_api()
period = args['period']
_hour = ''
_minute = ''
_where1 = ''
_type_day = "day"
if period == 'day':
_type_day = 'day'
_hour = args['hour']
_minute = args['minute']
elif period == 'minute-n':
_type_day = 'minute-n'
_where1 = args['minute-n']
_minute = ''
cmd = '''
rname=%s
plugin_path=%s
script_path=%s
logs_file=$plugin_path/${rname}.log
''' % (name, getServerDir(), getPluginDir())
cmd += 'echo "★【`date +"%Y-%m-%d %H:%M:%S"`】 STSRT★" >> $logs_file' + "\n"
cmd += 'echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" >> $logs_file' + "\n"
cmd += 'echo "python3 $script_path/tool_task.py run >> $logs_file 2>&1"' + "\n"
cmd += 'python3 $script_path/tool_task.py run >> $logs_file 2>&1' + "\n"
cmd += 'echo "【`date +"%Y-%m-%d %H:%M:%S"`】 END★" >> $logs_file' + "\n"
cmd += 'echo "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" >> $logs_file' + "\n"
params = {
'name': _name,
'type': _type_day,
'week': "",
'where1': _where1,
'hour': _hour,
'minute': _minute,
'save': "",
'backup_to': "",
'stype': "toShell",
'sname': '',
'sbody': cmd,
'urladdress': '',
}
task_id = api.add(params)
if task_id > 0:
cfg["task_id"] = task_id
cfg["name"] = name
_dd = getConfigData()
_dd.append(cfg)
mw.writeFile(getTaskConf(), json.dumps(_dd))
def removeBgTask():
cfg_list = getConfigData()
for x in range(len(cfg_list)):
cfg = cfg_list[x]
if "task_id" in cfg.keys() and cfg["task_id"] > 0:
res = mw.M("crontab").field("id, name").where(
"id=?", (cfg["task_id"],)).find()
if res and res["id"] == cfg["task_id"]:
import crontab_api
api = crontab_api.crontab_api()
data = api.delete(cfg["task_id"])
if data[0]:
cfg["task_id"] = -1
cfg_list[x] = cfg
mw.writeFile(getTaskConf(), '[]')
return True
return False
def run():
print('op lua run ok')
if __name__ == "__main__":
if len(sys.argv) > 1:
action = sys.argv[1]
if action == "remove":
removeBgTask()
elif action == "add":
createBgTask()
elif action == "run":
run()
+1 -1
View File
@@ -1 +1 @@
{"reqfile_path": "{$WAF_PATH}/html", "retry": {"retry_time": 180, "is_open_global": 0, "retry": 6, "retry_cycle": 60}, "log": true, "scan": {"status": 444, "ps": "\u8fc7\u6ee4\u5e38\u89c1\u626b\u63cf\u6d4b\u8bd5\u5de5\u5177\u7684\u6e17\u900f\u6d4b\u8bd5", "open": true, "reqfile": ""}, "cc": {"status": 444, "ps": "\u8fc7\u8651CC\u653b\u51fb", "limit": 120, "endtime": 300, "open": true, "reqfile": "", "cycle": 60}, "get": {"status": 403, "ps": "\u8fc7\u6ee4uri\u3001uri\u53c2\u6570\u4e2d\u5e38\u89c1sql\u6ce8\u5165\u3001xss\u7b49\u653b\u51fb", "open": true, "reqfile": "get.html"}, "log_save": 30, "user-agent": {"status": 403, "ps": "\u901a\u5e38\u7528\u4e8e\u8fc7\u6ee4\u6d4f\u89c8\u5668\u3001\u8718\u86db\u53ca\u4e00\u4e9b\u81ea\u52a8\u626b\u63cf\u5668", "open": true, "reqfile": "user_agent.html"}, "other": {"status": 403, "ps": "\u5176\u5b83\u975e\u901a\u7528\u8fc7\u6ee4", "reqfile": "other.html"}, "cookie": {"status": 403, "ps": "\u8fc7\u6ee4\u5229\u7528Cookie\u53d1\u8d77\u7684\u6e17\u900f\u653b\u51fb", "open": true, "reqfile": "cookie.html"}, "logs_path": "/www/wwwlogs/btwaf", "post": {"status": 403, "ps": "\u8fc7\u6ee4POST\u53c2\u6570\u4e2d\u5e38\u89c1sql\u6ce8\u5165\u3001xss\u7b49\u653b\u51fb", "open": true, "reqfile": "post.html"}, "open": true}
{"reqfile_path": "{$WAF_PATH}/html", "retry": {"retry_time": 180, "is_open_global": 0, "retry": 6, "retry_cycle": 60}, "log": true, "scan": {"status": 444, "ps": "\u8fc7\u6ee4\u5e38\u89c1\u626b\u63cf\u6d4b\u8bd5\u5de5\u5177\u7684\u6e17\u900f\u6d4b\u8bd5", "open": true, "reqfile": ""}, "cc": {"status": 444, "ps": "\u8fc7\u8651CC\u653b\u51fb", "limit": 120, "endtime": 300, "open": true, "reqfile": "", "cycle": 60}, "get": {"status": 403, "ps": "\u8fc7\u6ee4uri\u3001uri\u53c2\u6570\u4e2d\u5e38\u89c1sql\u6ce8\u5165\u3001xss\u7b49\u653b\u51fb", "open": true, "reqfile": "get.html"}, "log_save": 30, "user-agent": {"status": 403, "ps": "\u901a\u5e38\u7528\u4e8e\u8fc7\u6ee4\u6d4f\u89c8\u5668\u3001\u8718\u86db\u53ca\u4e00\u4e9b\u81ea\u52a8\u626b\u63cf\u5668", "open": true, "reqfile": "user_agent.html"}, "other": {"status": 403, "ps": "\u5176\u5b83\u975e\u901a\u7528\u8fc7\u6ee4", "reqfile": "other.html"}, "cookie": {"status": 403, "ps": "\u8fc7\u6ee4\u5229\u7528Cookie\u53d1\u8d77\u7684\u6e17\u900f\u653b\u51fb", "open": true, "reqfile": "cookie.html"}, "logs_path": "/www/wwwlogs/waf", "post": {"status": 403, "ps": "\u8fc7\u6ee4POST\u53c2\u6570\u4e2d\u5e38\u89c1sql\u6ce8\u5165\u3001xss\u7b49\u653b\u51fb", "open": true, "reqfile": "post.html"}, "open": true}
+168 -30
View File
@@ -1,26 +1,89 @@
local setmetatable = setmetatable
local _M = { _VERSION = '0.01' }
local _M = { _VERSION = '0.02' }
local mt = { __index = _M }
local json = require "cjson"
local ngx_match = ngx.re.find
local debug_mode = false
function _M.new(self, cpath, rpath, logdir)
-- ngx.log(ngx.ERR,"read:"..cpath..",rpath:"..rpath)
local opt = {
cpath = cpath,
rpath = rpath,
logdir = logdir,
config = '',
site_config = '',
params = nil
local waf_root = "{$WAF_ROOT}"
local cpath = waf_root.."/waf/"
local logdir = waf_root.."/logs/"
local rpath = cpath.."/rule/"
function _M.new(self)
local self = {
waf_root = waf_root,
cpath = cpath,
rpath = rpath,
logdir = logdir,
config = '',
site_config = '',
server_name = '',
params = nil
}
local p = setmetatable(opt, mt)
return p
return setmetatable(self, mt)
end
function _M.setDebug(self, mode)
debug_mode = mode
end
-- 调试方式
function _M.D(self, msg)
if not debug_mode then return true end
local _msg = ''
if type(msg) == 'table' then
for key, val in pairs(msg) do
_msg = tostring( key)..':'.."\n"
end
elseif type(msg) == 'string' then
_msg = msg
elseif type(msg) == 'nil' then
_msg = 'nil'
else
_msg = msg
end
local fp = io.open(waf_root.."/debug.log", "ab")
if fp == nil then
return nil
end
local localtime = os.date("%Y-%m-%d %H:%M:%S")
if server_name then
fp:write(tostring(_msg) .. "\n")
else
fp:write(localtime..":"..tostring(_msg) .. "\n")
end
fp:flush()
fp:close()
return true
end
local function write_file_clear(filename, body)
fp = io.open(filename,'w')
if fp == nil then
return nil
end
fp:write(body)
fp:flush()
fp:close()
return true
end
function _M.setConfData( self, config, site_config )
self.config = config
self.site_config = site_config
@@ -94,6 +157,10 @@ function _M.compare_ip(self,ips)
end
function _M.to_json(self, msg)
return json.encode(msg)
end
function _M.return_message(self, status, msg)
ngx.header.content_type = "application/json;"
ngx.status = status
@@ -136,20 +203,15 @@ function _M.write_file(self, filename, body)
return true
end
function _M.write_file_clear(self, filename, body)
fp = io.open(filename,'w')
if fp == nil then
return nil
end
fp:write(body)
fp:flush()
fp:close()
return true
return write_file_clear(filename, body)
end
function _M.write_drop_ip(self, is_drop, drop_time)
local filename = self.cpath .. 'drop_ip.log'
local filename = self.logdir .. 'drop_ip.log'
local fp = io.open(filename,'ab')
local server_name = self.params["server_name"]
local ip = self.params["server_name"]
@@ -234,11 +296,21 @@ function _M.read_file(self, name)
end
function _M.read_file_table( self, name )
return self:select_rule(self:read_file('args'))
return self:select_rule(self:read_file(name))
end
local function timer_at_inc_log(premature)
local total_path = cpath .. 'total.json'
local tbody = ngx.shared.limit:get(total_path)
if not tbody then
return false
end
return write_file_clear(total_path,tbody)
end
function _M.inc_log(self, name, rule)
local server_name = self.params['server_name']
local total_path = self.cpath .. 'total.json'
local tbody = ngx.shared.limit:get(total_path)
@@ -246,7 +318,10 @@ function _M.inc_log(self, name, rule)
tbody = self:read_file_body(total_path)
if not tbody then return false end
end
local total = json.decode(tbody)
-- 开始计算
if not total['sites'] then total['sites'] = {} end
if not total['sites'][server_name] then total['sites'][server_name] = {} end
if not total['sites'][server_name][name] then total['sites'][server_name][name] = 0 end
@@ -256,13 +331,15 @@ function _M.inc_log(self, name, rule)
total['total'] = total['total'] + 1
total['sites'][server_name][name] = total['sites'][server_name][name] + 1
total['rules'][name] = total['rules'][name] + 1
local total_log = json.encode(total)
if not total_log then return false end
ngx.shared.limit:set(total_path,total_log)
if not ngx.shared.limit:get('mw_waf_timeout') then
self:write_file_clear(total_path,total_log)
ngx.shared.limit:set('mw_waf_timeout',1,5)
end
-- 异步执行
ngx.timer.at(1, timer_at_inc_log)
end
@@ -289,9 +366,66 @@ function _M.get_server_name(self)
end
-- function _M.get_sn(self)
-- retun string.gsub(self:get_server_name(),'_','.')
-- end
function _M.is_ngx_match_orgin(self,rule,match, sign)
if ngx_match(ngx.unescape_uri(match), rule,"isjo") then
error_rule = rule .. ' >> ' .. sign .. ':' .. match
return true
end
return false
end
function _M.ngx_match_string(self, rule, content,sign)
local t = self:is_ngx_match_orgin(rule, content, sign)
if t then
return true
end
return false
end
function _M.ngx_match_list(self, rules, content)
for i,rule in ipairs(rules)
do
if rule[1] == 1 then
local t = self:is_ngx_match_orgin(rule[2], content, rule[3])
if t then
return true
end
end
end
return false
end
function _M.is_ngx_match_ua(self, rules, content)
-- ngx.header.content_type = "text/html"
for i,rule in ipairs(rules)
do
-- 开启的规则,才匹配。
if rule[1] == 1 then
local t = self:is_ngx_match_orgin(rule[2], content, rule[3])
if t then
return true
end
end
end
return false
end
function _M.is_ngx_match_post(self, rules, content)
for i,rule in ipairs(rules)
do
-- 开启的规则,才匹配。
if rule[1] == 1 then
local t = self:is_ngx_match_orgin(rule[2],content, rule[3])
if t then
return true
end
end
end
return false
end
function _M.is_ngx_match(self, rules, sbody, rule_name)
@@ -341,6 +475,7 @@ end
function _M.write_log(self, name, rule)
local ip = self.params['ip']
local retry = self.config['retry']['retry']
local retry_time = self.config['retry']['retry_time']
@@ -352,6 +487,7 @@ function _M.write_log(self, name, rule)
else
ngx.shared.drop_ip:set(ip,1,retry_cycle)
end
if self.config['log'] ~= true or self:is_site_config('log') ~= true then return false end
local method = ngx.req.get_method()
if error_rule then
@@ -384,10 +520,13 @@ end
function _M.get_client_ip(self)
local client_ip = "unknown"
local server_name = self.params['server_name']
-- self:D("fff..."..client_ip..server_name)
if self.site_config[server_name] then
if self.site_config[server_name]['cdn'] then
for _,v in ipairs(self.site_config[server_name]['cdn_header'])
do
-- C:D("vv:"..v..tostring(request_header[v]))
if request_header[v] ~= nil and request_header[v] ~= "" then
local header_tmp = request_header[v]
if type(header_tmp) == "table" then header_tmp = header_tmp[1] end
@@ -408,7 +547,6 @@ end
function _M.is_site_config(self,cname)
local server_name = self.params["server_name"]
if self.site_config[server_name] ~= nil then
if cname == 'cc' then
return self.site_config[server_name][cname]['open']
+163 -168
View File
@@ -1,65 +1,55 @@
local cpath = "{$WAF_PATH}/"
local rpath = "{$WAF_PATH}/rule/"
local logdir = "{$ROOT_PATH}/wwwlogs/waf/"
local json = require "cjson"
local ngx_match = ngx.re.find
local _C = require "common"
local C = _C:new(cpath, rpath, logdir)
local __C = require "common"
local C = __C:new()
config = C:read_file_body_decode(cpath .. 'config.json')
local site_config = C:read_file_body_decode(cpath .. 'site.json')
local waf_root = "{$WAF_ROOT}"
config = C:read_file_body_decode(waf_root.."/waf/"..'config.json')
local site_config = C:read_file_body_decode(waf_root.."/waf/"..'site.json')
C:setConfData(config, site_config)
-- D func
local function D(msg)
local _msg = ''
if type(msg) == 'table' then
for key, val in pairs(msg) do
_msg = key..':'..val.."\n"
end
elseif type(msg) == 'string' then
_msg = msg
elseif type(msg) == 'nil' then
_msg = 'nil'
else
_msg = msg
end
if not debug_mode then return true end
local fp = io.open(cpath..'debug.log', 'ab')
if fp == nil then
return nil
end
local localtime = os.date("%Y-%m-%d %H:%M:%S")
if server_name then
fp:write(tostring(_msg) .. "\n")
else
fp:write(localtime..":"..tostring(_msg) .. "\n")
end
fp:flush()
fp:close()
return true
end
local get_html = C:read_file_body(config["reqfile_path"] .. '/' .. config["get"]["reqfile"])
local post_html = C:read_file_body(config["reqfile_path"] .. '/' .. config["post"]["reqfile"])
local user_agent_html = C:read_file_body(config["reqfile_path"] .. '/' .. config["user-agent"]["reqfile"])
local args_rules = C:read_file_table('args')
local ip_white_rules = C:read_file('ip_white')
local ip_black_rules = C:read_file('ip_black')
local scan_black_rules = C:read_file('scan_black')
local user_agent_rules = C:read_file('user_agent')
local post_rules = C:read_file('post')
local cookie_rules = C:read_file('cookie')
local server_name = string.gsub(C:get_server_name(),'_','.')
-- C:D("sss:"..C:get_server_name())
function initParams()
local data = {}
data['ip'] = C:get_client_ip()
data['ipn'] = C:arrip(data['ip'])
data['server_name'] = server_name
-- data['ip'] = C:get_client_ip()
-- data['ipn'] = C:arrip(data['ip'])
data['request_header'] = ngx.req.get_headers()
data['uri'] = ngx.unescape_uri(ngx.var.uri)
data['server_name'] = string.gsub(C:get_server_name(),'_','.')
data['uri_request_args'] = ngx.req.get_uri_args()
data['method'] = ngx.req.get_method()
data['request_uri'] = ngx.var.request_uri
data['cookie'] = ngx.var.http_cookie
return data
end
local params = initParams()
C:setParams(params)
C:setDebug(true)
local server_name = params["server_name"]
params['ip'] = C:get_client_ip()
params['ipn'] = C:arrip(params['ip'])
C:D(server_name)
function get_return_state(rstate,rmsg)
result = {}
@@ -102,20 +92,20 @@ function save_ip_on(data)
end
end
function remove_btwaf_drop_ip()
function remove_waf_drop_ip()
if not uri_request_args['ip'] or not C:is_ipaddr(uri_request_args['ip']) then return get_return_state(true,'格式错误') end
if ngx.shared.btwaf:get(cpath2 .. 'stop_ip') then
ret=ngx.shared.btwaf:get(cpath2 .. 'stop_ip')
ip_data=json.decode(ret)
result=is_chekc_table(ip_data,uri_request_args['ip'])
result = is_chekc_table(ip_data,uri_request_args['ip'])
os.execute("sleep " .. 0.6)
ret2=ngx.shared.btwaf:get(cpath2 .. 'stop_ip')
ip_data2=json.decode(ret2)
ip_data2 = json.decode(ret2)
if result == 3 then
for k,v in pairs(ip_data2)
do
if uri_request_args['ip'] == v['ip'] then
v['time']=0
v['time'] = 0
end
end
end
@@ -125,7 +115,7 @@ function remove_btwaf_drop_ip()
return get_return_state(true,uri_request_args['ip'] .. '已解封')
end
function clean_btwaf_drop_ip()
function clean_waf_drop_ip()
if ngx.shared.btwaf:get(cpath2 .. 'stop_ip') then
ret2=ngx.shared.btwaf:get(cpath2 .. 'stop_ip')
ip_data2=json.decode(ret2)
@@ -155,15 +145,7 @@ function min_route()
end
end
local get_html = C:read_file_body(config["reqfile_path"] .. '/' .. config["get"]["reqfile"])
local post_html = C:read_file_body(config["reqfile_path"] .. '/' .. config["post"]["reqfile"])
local user_agent_html = C:read_file_body(config["reqfile_path"] .. '/' .. config["user-agent"]["reqfile"])
local args_rules = C:read_file_table('args')
local ip_white_rules = C:read_file('ip_white')
local ip_black_rules = C:read_file('ip_black')
local scan_black_rules = C:read_file('scan_black')
function waf_args()
function waf_get_args()
if not config['get']['open'] or not C:is_site_config('get') then return false end
if C:is_ngx_match(args_rules, params['uri_request_args'],'args') then
C:write_log('args','regular')
@@ -196,8 +178,20 @@ function waf_ip_black()
end
function waf_user_agent()
-- user_agent 过滤
if not config['user-agent']['open'] or not C:is_site_config('user-agent') then return false end
if C:is_ngx_match_ua(user_agent_rules,params['request_header']['user-agent']) then
C:write_log('user_agent','regular')
C:return_html(config['user-agent']['status'],user_agent_html)
return true
end
return false
end
function waf_drop()
local count,_ = ngx.shared.drop_ip:get(ip)
local count , _ = ngx.shared.drop_ip:get(ip)
if not count then return false end
if count > config['retry'] then
ngx.exit(config['cc']['status'])
@@ -206,28 +200,33 @@ function waf_drop()
return false
end
function waf_user_agent()
if not config['user-agent']['open'] or not C:is_site_config('user-agent') then return false end
if C:is_ngx_match(user_agent_rules,params['request_header']['user-agent'],'user_agent') then
C:write_log('user_agent','regular')
C:return_html(config['user-agent']['status'],user_agent_html)
return true
end
return false
end
function cc()
function waf_cc()
local ip = params['ip']
local ip_lock = ngx.shared.drop_ip:get(ip)
if ip_lock then
if ip_lock > 0 then
ngx.exit(config['cc']['status'])
return true
end
end
if not config['cc']['open'] or not C:is_site_config('cc') then return false end
local request_uri = params['request_uri']
local endtime = config['cc']['endtime']
if not config['cc']['open'] or not site_cc then return false end
local token = ngx.md5(ip .. '_' .. request_uri)
local count,_ = ngx.shared.limit:get(token)
local count = ngx.shared.limit:get(token)
local limit = config['cc']['limit']
local cycle = config['cc']['cycle']
if count then
if count > limit then
local safe_count,_ = ngx.shared.drop_sum:get(ip)
if count > limit then
local safe_count, _ = ngx.shared.drop_sum:get(ip)
if not safe_count then
ngx.shared.drop_sum:set(ip,1,86400)
safe_count = 1
@@ -236,23 +235,22 @@ function cc()
end
local lock_time = (endtime * safe_count)
if lock_time > 86400 then lock_time = 86400 end
ngx.shared.drop_ip:set(ip,retry+1,lock_time)
-- lock_time = 10
ngx.shared.drop_ip:set(ip,1,lock_time)
C:write_log('cc',cycle..'秒内累计超过'..limit..'次请求,封锁' .. lock_time .. '秒')
C:write_drop_ip('cc',lock_time)
if not server_name then
insert_ip_list(ip,lock_time,os.time(),'1111')
else
insert_ip_list(ip,lock_time,os.time(),server_name)
end
ngx.exit(config['cc']['status'])
return true
else
ngx.shared.limit:incr(token,1)
end
else
ngx.shared.limit:set(token,1,cycle)
ngx.shared.drop_sum:set(ip,1,86400)
ngx.shared.limit:set(token, 1, cycle)
end
return false
end
--强制验证是否使用正常浏览器访问网站
@@ -287,20 +285,25 @@ end
function waf_scan_black()
-- 扫描软件禁止
if not config['scan']['open'] or not C:is_site_config('scan') then return false end
if C:is_ngx_match(scan_black_rules['cookie'],params["request_header"]["cookie"],false) then
C:write_log('scan','regular')
ngx.exit(config['scan']['status'])
return true
end
if C:is_ngx_match(scan_black_rules['args'],params["request_uri"],false) then
if not params["cookie"] then
if C:ngx_match_string(scan_black_rules['cookie'], tostring(params["cookie"]),'scan') then
C:write_log('scan','regular')
ngx.exit(config['scan']['status'])
return true
end
end
if C:ngx_match_string(scan_black_rules['args'], params["request_uri"], 'scan') then
C:write_log('scan','regular')
ngx.exit(config['scan']['status'])
return true
end
for key,value in pairs(params["request_header"])
do
if C:is_ngx_match(scan_black_rules['header'], key, false) then
if C:ngx_match_string(scan_black_rules['header'], key, 'scan') then
C:write_log('scan','regular')
ngx.exit(config['scan']['status'])
return true
@@ -309,20 +312,9 @@ function waf_scan_black()
return false
end
function waf_post_referer()
if params['method'] ~= "POST" then return false end
if C:is_ngx_match(referer_local, params['request_header']['Referer'],'post') then
C:write_log('post_referer','regular')
C:return_html(config['post']['status'],post_html)
return true
end
return false
end
function waf_post()
if not config['post']['open'] or not C:is_site_config('post') then return false end
if params['method'] ~= "POST" then return false end
if waf_post_referer() then return true end
content_length = tonumber(params["request_header"]['content-length'])
max_len = 640 * 1020000
if content_length > max_len then return false end
@@ -333,7 +325,19 @@ function waf_post()
return false
end
if C:is_ngx_match(post_rules,request_args,'post') then
for key, val in pairs(request_args) do
if type(val) == "table" then
if type(val[1]) == "boolean" then
return false
end
data = table.concat(val, ", ")
else
data = val
end
end
if C:is_ngx_match_post(post_rules,data) then
C:write_log('post','regular')
C:return_html(config['post']['status'],post_html)
return true
@@ -366,10 +370,11 @@ function post_data_chekc()
end
if not list_list then return false end
aaa=nil
aaa = nil
for k,v in pairs(request_args)
do
aaa=v
aaa = v
end
if not aaa then return false end
@@ -381,7 +386,7 @@ function post_data_chekc()
if not data_len then return false end
if arrlen(data_len) ==0 then return false end
if C:is_ngx_match(post_rules,data_len,'post') then
if C:is_ngx_match_post(post_rules , data_len) then
C:write_log('post','regular')
C:return_html(config['post']['status'],post_html)
return true
@@ -406,7 +411,7 @@ end
function post_X_Forwarded()
if not config['post']['open'] or not C:is_site_config('post') then return false end
if params['method'] ~= "POST" then return false end
if C:is_ngx_match(post_rules,params["request_header"]['X-forwarded-For'],'post') then
if C:is_ngx_match_post(post_rules,params["request_header"]['X-forwarded-For']) then
C:write_log('post','regular')
C:return_html(config['post']['status'],post_html)
return true
@@ -415,39 +420,39 @@ function post_X_Forwarded()
end
function php_path()
if site_config[server_name] == nil then return false end
for _,rule in ipairs(site_config[server_name]['disable_php_path'])
do
if ngx_match(uri,rule .. "/?.*\\.php$","isjo") then
C:write_log('php_path','regular')
C:return_html(config['other']['status'],other_html)
return C:return_message(200,uri)
end
end
return false
end
-- function php_path()
-- if site_config[server_name] == nil then return false end
-- for _,rule in ipairs(site_config[server_name]['disable_php_path'])
-- do
-- if C:ngx_match_string(params['uri'],rule .. "/?.*\\.php$","isjo") then
-- C:write_log('php_path','regular')
-- C:return_html(config['other']['status'],other_html)
-- return C:return_message(200,uri)
-- end
-- end
-- return false
-- end
function url_path()
if site_config[server_name] == nil then return false end
for _,rule in ipairs(site_config[server_name]['disable_path'])
do
if ngx_match(uri,rule,"isjo") then
C:write_log('path','regular')
C:return_html(config['other']['status'],other_html)
return true
end
end
return false
end
-- function url_path()
-- if site_config[server_name] == nil then return false end
-- for _,rule in ipairs(site_config[server_name]['disable_path'])
-- do
-- if ngx_match(uri,rule,"isjo") then
-- C:write_log('path','regular')
-- C:return_html(config['other']['status'],other_html)
-- return true
-- end
-- end
-- return false
-- end
function url_ext()
if site_config[server_name] == nil then return false end
for _,rule in ipairs(site_config[server_name]['disable_ext'])
do
if ngx_match(uri,"\\."..rule.."$","isjo") then
if C:ngx_match_string("\\."..rule.."$", params['uri'],'url_ext') then
C:write_log('url_ext','regular')
C:return_html(config['other']['status'],other_html)
C:return_html(config['other']['status'], other_html)
return true
end
end
@@ -555,7 +560,7 @@ function waf_cookie()
if not params["request_header"]['cookie'] then return false end
if type(params["request_header"]['cookie']) ~= "string" then return false end
request_cookie = string.lower(params["request_header"]['cookie'])
if C:is_ngx_match(cookie_rules,request_cookie,'cookie') then
if C:ngx_match_list(cookie_rules,request_cookie,'cookie') then
C:write_log('cookie','regular')
C:return_html(config['cookie']['status'],cookie_html)
return true
@@ -563,55 +568,45 @@ function waf_cookie()
return false
end
function waf_referer()
if params["method"] ~= "GET" then return false end
if not config['get']['open'] or not C:is_site_config('get') then return false end
if C:is_ngx_match(referer_local,params["request_header"]['Referer'],'args') then
C:write_log('get_referer','regular')
C:return_html(config['get']['status'], get_html)
return true
end
return false
end
function waf()
min_route()
-- white ip
if waf_ip_white() then return true end
waf_ip_black()
-- black ip
if waf_ip_black() then return true end
waf_drop()
waf_user_agent()
-- cc setting
if waf_drop() then return true end
if waf_cc() then return true end
waf_url()
-- ua check
if waf_user_agent() then return true end
if waf_url() then return true end
if params["method"] == "GET" then
waf_referer()
waf_cookie()
end
-- cookie检查
if waf_cookie() then return true end
-- args参数拦截
if waf_get_args() then return true end
if params["method"] == "POST" then
waf_referer()
waf_cookie()
end
-- 扫描软件禁止
if waf_scan_black() then return true end
waf_args()
waf_scan_black()
waf_post()
post_data_chekc()
local server_name = params["server_name"]
if site_config[server_name] then
X_Forwarded()
post_X_Forwarded()
php_path()
url_path()
url_ext()
url_rule_ex()
url_tell()
post_data()
if waf_post() then return true end
if post_data_chekc() then return true end
if site_config[server_name]['open'] then
if X_Forwarded() then return true end
if post_X_Forwarded() then return true end
-- url_path()
if url_ext() then return true end
-- url_rule_ex()
-- url_tell()
-- post_data()
end
end
+1 -1
View File
@@ -1 +1 @@
[[1, "(HTTrack|Apache-HttpClient|harvest|audit|dirbuster|pangolin|nmap|sqln|hydra|Parser|libwww|BBBike|sqlmap|w3af|owasp|Nikto|fimap|havij|zmeu|BabyKrokodil|netsparker|httperf| SF/)", "\u5173\u952e\u8bcd\u8fc7\u6ee41", 0]]
[[1,"(HTTrack|Apache-HttpClient|harvest|audit|dirbuster|pangolin|nmap|sqln|hydra|Parser|libwww|BBBike|sqlmap|w3af|owasp|Nikto|fimap|havij|zmeu|BabyKrokodil|netsparker|httperf| SF/)","关键词过滤1",0],[1,"(ApacheBench)","AB测试",0]]
+1 -1
View File
@@ -1 +1 @@
{"rules":{"user_agent":0,"cookie":0,"post":0,"args":0,"url":0,"cc":0},"sites":{},"total":0}
{"rules":{"url_ext":0,"user_agent":0,"scan":0,"cookie":0,"post":0,"args":0,"url":0,"cc":0},"sites":{},"total":0}
-309
View File
@@ -1,309 +0,0 @@
# coding:utf-8
import sys
import io
import os
import time
import subprocess
sys.path.append(os.getcwd() + "/class/core")
import mw
app_debug = False
if mw.isAppleSystem():
app_debug = True
def getPluginName():
return 'openresty'
def getPluginDir():
return mw.getPluginDir() + '/' + getPluginName()
def getServerDir():
return mw.getServerDir() + '/' + getPluginName()
def getInitDFile():
if app_debug:
return '/tmp/' + getPluginName()
return '/etc/init.d/' + getPluginName()
def getArgs():
args = sys.argv[2:]
tmp = {}
args_len = len(args)
if args_len == 1:
t = args[0].strip('{').strip('}')
t = t.split(':')
tmp[t[0]] = t[1]
elif args_len > 1:
for i in range(len(args)):
t = args[i].split(':')
tmp[t[0]] = t[1]
return tmp
def clearTemp():
path_bin = getServerDir() + "/nginx"
mw.execShell('rm -rf ' + path_bin + '/client_body_temp')
mw.execShell('rm -rf ' + path_bin + '/fastcgi_temp')
mw.execShell('rm -rf ' + path_bin + '/proxy_temp')
mw.execShell('rm -rf ' + path_bin + '/scgi_temp')
mw.execShell('rm -rf ' + path_bin + '/uwsgi_temp')
def getConf():
path = getServerDir() + "/nginx/conf/nginx.conf"
return path
def getConfTpl():
path = getPluginDir() + '/conf/nginx.conf'
return path
def getOs():
data = {}
data['os'] = mw.getOs()
ng_exe_bin = getServerDir() + "/nginx/sbin/nginx"
if checkAuthEq(ng_exe_bin, 'root'):
data['auth'] = True
else:
data['auth'] = False
return mw.getJson(data)
def getInitDTpl():
path = getPluginDir() + "/init.d/nginx.tpl"
return path
def makeConf():
vhost = getServerDir() + '/nginx/conf/vhost'
if not os.path.exists(vhost):
os.mkdir(vhost)
php_status = getServerDir() + '/nginx/conf/php_status'
if not os.path.exists(php_status):
os.mkdir(php_status)
def getFileOwner(filename):
import pwd
stat = os.lstat(filename)
uid = stat.st_uid
pw = pwd.getpwuid(uid)
return pw.pw_name
def checkAuthEq(file, owner='root'):
fowner = getFileOwner(file)
if (fowner == owner):
return True
return False
def confReplace():
service_path = os.path.dirname(os.getcwd())
content = mw.readFile(getConfTpl())
content = content.replace('{$SERVER_PATH}', service_path)
user = 'www'
user_group = 'www'
if mw.getOs() == 'darwin':
# macosx do
user = mw.execShell(
"who | sed -n '2, 1p' |awk '{print $1}'")[0].strip()
# user = 'root'
user_group = 'staff'
content = content.replace('{$EVENT_MODEL}', 'kqueue')
else:
content = content.replace('{$EVENT_MODEL}', 'epoll')
content = content.replace('{$OS_USER}', user)
content = content.replace('{$OS_USER_GROUP}', user_group)
nconf = getServerDir() + '/nginx/conf/nginx.conf'
__content = mw.readFile(nconf)
if __content.find('#user'):
mw.writeFile(getServerDir() + '/nginx/conf/nginx.conf', content)
# give nginx root permission
ng_exe_bin = getServerDir() + "/nginx/sbin/nginx"
if not checkAuthEq(ng_exe_bin, 'root'):
args = getArgs()
sudoPwd = args['pwd']
cmd_own = 'chown -R ' + 'root:' + user_group + ' ' + ng_exe_bin
os.system('echo %s|sudo -S %s' % (sudoPwd, cmd_own))
cmd_mod = 'chmod 755 ' + ng_exe_bin
os.system('echo %s|sudo -S %s' % (sudoPwd, cmd_mod))
cmd_s = 'chmod u+s ' + ng_exe_bin
os.system('echo %s|sudo -S %s' % (sudoPwd, cmd_s))
def initDreplace():
file_tpl = getInitDTpl()
service_path = os.path.dirname(os.getcwd())
initD_path = getServerDir() + '/init.d'
# Openresty is not installed
if not os.path.exists(getServerDir()):
print("ok")
exit(0)
file_bin = initD_path + '/' + getPluginName()
if not os.path.exists(initD_path):
os.mkdir(initD_path)
# initd replace
content = mw.readFile(file_tpl)
content = content.replace('{$SERVER_PATH}', service_path)
mw.writeFile(file_bin, content)
mw.execShell('chmod +x ' + file_bin)
# config replace
confReplace()
# make nginx vhost or other
makeConf()
return file_bin
def status():
data = mw.execShell(
"ps -ef|grep nginx |grep -v grep | grep -v python | awk '{print $2}'")
if data[0] == '':
return 'stop'
return 'start'
def start():
file = initDreplace()
data = mw.execShell(file + ' start')
if data[1] == '':
return 'ok'
return data[1]
def stop():
file = initDreplace()
data = mw.execShell(file + ' stop')
clearTemp()
if data[1] == '':
return 'ok'
return data[1]
def restart():
file = initDreplace()
data = mw.execShell(file + ' restart')
if data[1] == '':
return 'ok'
return data[1]
def reload():
file = initDreplace()
data = mw.execShell(file + ' reload')
if data[1] == '':
return 'ok'
return data[1]
def initdStatus():
if not app_debug:
if mw.isAppleSystem():
return "Apple Computer does not support"
initd_bin = getInitDFile()
if os.path.exists(initd_bin):
return 'ok'
return 'fail'
def initdInstall():
import shutil
if not app_debug:
if mw.isAppleSystem():
return "Apple Computer does not support"
source_bin = initDreplace()
initd_bin = getInitDFile()
shutil.copyfile(source_bin, initd_bin)
mw.execShell('chmod +x ' + initd_bin)
mw.execShell('chkconfig --add ' + getPluginName())
return 'ok'
def initdUinstall():
if not app_debug:
if mw.isAppleSystem():
return "Apple Computer does not support"
mw.execShell('chkconfig --del ' + getPluginName())
initd_bin = getInitDFile()
os.remove(initd_bin)
return 'ok'
def runInfo():
# 取Openresty负载状态
try:
result = mw.httpGet('http://127.0.0.1/nginx_status')
tmp = result.split()
data = {}
data['active'] = tmp[2]
data['accepts'] = tmp[9]
data['handled'] = tmp[7]
data['requests'] = tmp[8]
data['Reading'] = tmp[11]
data['Writing'] = tmp[13]
data['Waiting'] = tmp[15]
return mw.getJson(data)
except Exception as e:
return 'oprenresty not started'
def errorLogPath():
return getServerDir() + '/nginx/logs/error.log'
if __name__ == "__main__":
func = sys.argv[1]
if func == 'status':
print(status())
elif func == 'start':
print(start())
elif func == 'stop':
print(stop())
elif func == 'restart':
print(restart())
elif func == 'reload':
print(reload())
elif func == 'initd_status':
print(initdStatus())
elif func == 'initd_install':
print(initdInstall())
elif func == 'initd_uninstall':
print(initdUinstall())
elif func == 'conf':
print(getConf())
elif func == 'get_os':
print(getOs())
elif func == 'run_info':
print(runInfo())
elif func == 'error_log':
print(errorLogPath())
else:
print('error')
+39
View File
@@ -1,3 +1,41 @@
<style type="text/css">
.bt-w-main{
height: 600px;
}
.session_clear_list {
border:1px solid #ececec;
margin-bottom: 15px;
width: 270px;
}
.session_clear_list .line {
padding: 0;
border-bottom: 1px solid #ececec;
width: 270px;
}
.session_clear_list .line:last-child {
border-bottom: 0px;
}
.session_clear_list .line span{
width: auto;
height: 35px;
line-height: 35px;
text-align: left;
padding: 0 5px;
}
.session_clear_list .line span:first-child {
width: 170px;
border-right: 1px solid #ececec;
background: #f7f7f7;
float: left;
}
</style>
<div class="bt-form">
<div class='plugin_version'></div>
<div class="bt-w-main">
@@ -13,6 +51,7 @@
<p onclick="disableFunc($('.plugin_version').attr('version'));">禁用函数</p>
<p onclick="getFpmConfig($('.plugin_version').attr('version'));">性能调整</p>
<p onclick="getFpmStatus($('.plugin_version').attr('version'));">负载状况</p>
<p onclick="getSessionConfig($('.plugin_version').attr('version'));" title="session管理">会话管理</p>
<p onclick="pluginLogs('php-apt',$('.plugin_version').attr('version'),'fpm_log');">FPM日志</p>
<p onclick="pluginLogs('php-apt',$('.plugin_version').attr('version'),'fpm_slow_log');">慢日志</p>
<p onclick="getPhpinfo($('.plugin_version').attr('version'));">PHPIFNO</p>
+182
View File
@@ -490,6 +490,180 @@ def getFpmStatus(version):
return mw.returnJson(True, "OK", data)
def getSessionConf(version):
filename = getConf(version)
if not os.path.exists(filename):
return mw.returnJson(False, '指定PHP版本不存在!')
phpini = mw.readFile(filename)
rep = r'session.save_handler\s*=\s*([0-9A-Za-z_& ~]+)(\s*;?|\r?\n)'
save_handler = re.search(rep, phpini)
if save_handler:
save_handler = save_handler.group(1)
else:
save_handler = "files"
reppath = r'\nsession.save_path\s*=\s*"tcp\:\/\/([\d\.]+):(\d+).*\r?\n'
passrep = r'\nsession.save_path\s*=\s*"tcp://[\w\.\?\:]+=(.*)"\r?\n'
memcached = r'\nsession.save_path\s*=\s*"([\d\.]+):(\d+)"'
save_path = re.search(reppath, phpini)
if not save_path:
save_path = re.search(memcached, phpini)
passwd = re.search(passrep, phpini)
port = ""
if passwd:
passwd = passwd.group(1)
else:
passwd = ""
if save_path:
port = save_path.group(2)
save_path = save_path.group(1)
else:
save_path = ""
data = {"save_handler": save_handler, "save_path": save_path,
"passwd": passwd, "port": port}
return mw.returnJson(True, 'ok', data)
def setSessionConf(version):
args = getArgs()
ip = args['ip']
port = args['port']
passwd = args['passwd']
save_handler = args['save_handler']
if save_handler != "file":
iprep = r"(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})"
if not re.search(iprep, ip):
return mw.returnJson(False, '请输入正确的IP地址')
try:
port = int(port)
if port >= 65535 or port < 1:
return mw.returnJson(False, '请输入正确的端口号')
except:
return mw.returnJson(False, '请输入正确的端口号')
prep = r"[\~\`\/\=]"
if re.search(prep, passwd):
return mw.returnJson(False, '请不要输入以下特殊字符 " ~ ` / = "')
filename = getConf(version)
if not os.path.exists(filename):
return mw.returnJson(False, '指定PHP版本不存在!')
phpini = mw.readFile(filename)
session_tmp = getServerDir() + "/tmp/session"
rep = r'session.save_handler\s*=\s*(.+)\r?\n'
val = r'session.save_handler = ' + save_handler + '\n'
phpini = re.sub(rep, val, phpini)
content = mw.execShell(
'cat /etc/php/' + version + '/fpm/conf.d/*' + " | grep -v '^;' |tr -s '\n'")
content = content[0]
if save_handler == "memcached":
if not re.search("memcached.so", phpini):
return mw.returnJson(False, '请先安装%s扩展' % save_handler)
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "%s:%s" \n' % (ip, port)
if re.search(rep, phpini):
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "' + "/var/lib/php/sessions" + '"',
'\n;session.save_path = "' + "/var/lib/php/sessions" + '"' + val, phpini)
if save_handler == "memcache":
if not content.find('memcache') > -1:
return mw.returnJson(False, '请先安装%s扩展' % save_handler)
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "%s:%s" \n' % (ip, port)
if re.search(rep, phpini):
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "' + "/var/lib/php/sessions" + '"',
'\n;session.save_path = "' + "/var/lib/php/sessions" + '"' + val, phpini)
if save_handler == "redis":
if not content.find('redis') > -1:
return mw.returnJson(False, '请先安装%s扩展' % save_handler)
if passwd:
passwd = "?auth=" + passwd
else:
passwd = ""
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "tcp://%s:%s%s"\n' % (ip, port, passwd)
res = re.search(rep, phpini)
if res:
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "' + "/var/lib/php/sessions" + '"',
'\n;session.save_path = "' + "/var/lib/php/sessions" + '"' + val, phpini)
if save_handler == "file":
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "' + session_tmp + '"\n'
if re.search(rep, phpini):
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "' + "/var/lib/php/sessions" + '"',
'\n;session.save_path = "' + "/var/lib/php/sessions" + '"' + val, phpini)
mw.writeFile(filename, phpini)
reload(version)
return mw.returnJson(True, '设置成功!')
def getSessionCount_Origin(version):
session_tmp = getServerDir() + "/tmp/session"
d = ["/tmp", "/var/lib/php/sessions", session_tmp]
count = 0
for i in d:
if not os.path.exists(i):
mw.execShell('mkdir -p %s' % i)
list = os.listdir(i)
for l in list:
if os.path.isdir(i + "/" + l):
l1 = os.listdir(i + "/" + l)
for ll in l1:
if "sess_" in ll:
count += 1
continue
if "sess_" in l:
count += 1
s = "find /tmp -mtime +1 |grep 'sess_' | wc -l"
old_file = int(mw.execShell(s)[0].split("\n")[0])
s = "find " + session_tmp + " -mtime +1 |grep 'sess_'|wc -l"
old_file += int(mw.execShell(s)[0].split("\n")[0])
return {"total": count, "oldfile": old_file}
def getSessionCount(version):
data = getSessionCount_Origin(version)
return mw.returnJson(True, 'ok!', data)
def cleanSessionOld(version):
s = "find /tmp -mtime +1 |grep 'sess_'|xargs rm -f"
mw.execShell(s)
session_tmp = getServerDir() + "/tmp/session"
s = "find " + session_tmp + " -mtime +1 |grep 'sess_' |xargs rm -f"
mw.execShell(s)
old_file_conf = getSessionCount_Origin(version)["oldfile"]
if old_file_conf == 0:
return mw.returnJson(True, '清理成功')
else:
return mw.returnJson(True, '清理失败')
def getDisableFunc(version):
filename = getConf(version)
if not os.path.exists(filename):
@@ -688,6 +862,14 @@ if __name__ == "__main__":
print(setFpmConfig(version))
elif func == 'get_fpm_status':
print(getFpmStatus(version))
elif func == 'get_session_conf':
print(getSessionConf(version))
elif func == 'set_session_conf':
print(setSessionConf(version))
elif func == 'get_session_count':
print(getSessionCount(version))
elif func == 'clean_session_old':
print(cleanSessionOld(version))
elif func == 'get_disable_func':
print(getDisableFunc(version))
elif func == 'set_disable_func':
+145
View File
@@ -368,6 +368,151 @@ function disableFunc(version) {
$(".soft-man-con").html(con);
});
}
function getSessionConfig(version){
phpPost('get_session_conf', version, '', function(ret_data){
var rdata = $.parseJSON(ret_data.data);
if(!rdata.status){
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
return;
}
var rdata = rdata.data;
var cacheList = "<option value='file' " + (rdata.save_handler == "file" ? 'selected' : '') + ">file</option>" +
"<option value='redis' " + (rdata.save_handler == "redis" ? 'selected' : '') + ">redis</option>" +
"<option value='memcache' " + (rdata.save_handler == "memcache" ? 'selected' : '') + ">memcache</option>" +
"<option value='memcached' " + (rdata.save_handler == "memcached" ? 'selected' : '') + ">memcached</option>";
var info = rdata.save_path.split(":");
var con = "<div class='conf_p'>" +
"<p class='line'><span class='span_tit'>存储模式:</span><select class='bt-input-text' name='save_handler' style='width:200px;'>" + cacheList + "</select></p>" +
"<p class='line'><span class='span_tit'>IP地址:</span><input class='bt-input-text' type='text' name='ip' style='width:200px;' value='"+ info[0] +"' /></p>" +
"<p class='line'><span class='span_tit'>端口:</span><input class='bt-input-text' type='text' name='port' style='width:200px;' value='"+rdata.port+"' /></p>" +
"<p class='line'><span class='span_tit'>密码:</span><input class='bt-input-text' type='text' name='passwd' style='width:200px;' value='"+rdata.passwd+"' /></p>" +
"<p class='line'><div class='mtb15' style='margin-left:100px;'><button class='btn btn-success btn-sm' onclick='setSessionConfig(\"" + version + "\",1)'>保存</button></div></p>" +
"</div>\
<ul class='help-info-text c7'>\
<li>若你的站点并发比较高,使用Redis,Memcache能有效提升PHP并发能力</li>\
<li>若调整Session模式后,网站访问异常,请切换回原来的模式</li>\
<li>切换Session模式会使在线的用户会话丢失,请在流量小的时候切换</li>\
</ul>\
<div id='session_clear' class='session_clear' style='border-top: #ccc 1px dashed;padding-top: 15px;margin-top: 15px;'>\
</div>\
</div>";
$(".soft-man-con").html(con);
if (rdata.save_handler == 'file'){
$('input[name="ip"]').attr('disabled','disabled');
$('input[name="port"]').attr('disabled','disabled');
$('input[name="passwd"]').attr('placeholder','如果没有密码留空');
$('input[name="passwd"]').attr('disabled','disabled');
}
// change event
$("select[name='save_handler']").change(function() {
var type = $(this).val();
var passwd = $('input[name="passwd"]').val();
if (passwd == ""){
$('input[name="passwd"]').attr('placeholder','如果没有密码留空');
}
var ip = $('input[name="ip"]').val();
if (ip == ""){
$('input[name="ip"]').val('127.0.0.1');
}
switch (type) {
case 'redis':
var port = $('input[name="port"]').val();
if (port == ""){
$('input[name="port"]').val('6379');
}
$('input[name="ip"]').removeAttr('disabled');
$('input[name="port"]').removeAttr('disabled');
$('input[name="passwd"]').removeAttr('disabled');
break;
case 'file':
$('input[name="ip"]').val("").attr('disabled','disabled');
$('input[name="port"]').val("").attr('disabled','disabled');
$('input[name="passwd"]').val("").attr('disabled','disabled');
break;
case 'memcache':
var port = $('input[name="port"]').val();
if (port == ""){
$('input[name="port"]').val('11211');
}
$('input[name="ip"]').removeAttr('disabled');
$('input[name="port"]').removeAttr('disabled');
$('input[name="passwd"]').removeAttr('disabled');
break;
case 'memcached':
var port = $('input[name="port"]').val();
if (port == ""){
$('input[name="port"]').val('11211');
}
$('input[name="ip"]').removeAttr('disabled');
$('input[name="port"]').removeAttr('disabled');
$('input[name="passwd"]').removeAttr('disabled');
break;
}
});
//load session stats
phpPost('get_session_count', version, '', function(ret_data){
var rdata = $.parseJSON(ret_data.data);
if(!rdata.status){
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
return;
}
var rdata = rdata.data;
var html_var = "<div class='clear_title' style='padding-bottom:15px;'>清理Session文件</div>\
<div class='clear_conter'>\
<div class='session_clear_list'>\
<div class='line'><span>总Session文件数量</span><span>"+rdata.total+"</span></div>\
<div class='line'><span>可清理的Session文件数量</span><span>"+rdata.oldfile+"</span></div>\
</div>\
<button id='clean_func' class='btn btn-success btn-sm clear_session_file'>清理session文件</button>";
$("#session_clear").html(html_var);
$('#clean_func').click(function(){
phpPost('clean_session_old', version, '', function(ret_data){
var rdata = $.parseJSON(ret_data.data);
showMsg(rdata.msg,function(){
getSessionConfig(version);
},{ icon: rdata.status ? 1 : 2 });
});
});
});
});
}
function setSessionConfig(version){
var ip = $('input[name="ip"]').val();
var port = $('input[name="port"]').val();
var passwd = $('input[name="passwd"]').val();
var save_handler = $("select[name='save_handler']").val();
var data = {
ip:ip,
port:port,
passwd:passwd,
save_handler:save_handler,
};
phpPost('set_session_conf', version, data, function(ret_data){
var rdata = $.parseJSON(ret_data.data);
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
});
}
//设置禁用函数
function setDisableFunc(version, act, fs) {
var fsArr = fs.split(',');
+38
View File
@@ -1,3 +1,40 @@
<style type="text/css">
.bt-w-main{
height: 600px;
}
.session_clear_list {
border:1px solid #ececec;
margin-bottom: 15px;
width: 270px;
}
.session_clear_list .line {
padding: 0;
border-bottom: 1px solid #ececec;
width: 270px;
}
.session_clear_list .line:last-child {
border-bottom: 0px;
}
.session_clear_list .line span{
width: auto;
height: 35px;
line-height: 35px;
text-align: left;
padding: 0 5px;
}
.session_clear_list .line span:first-child {
width: 170px;
border-right: 1px solid #ececec;
background: #f7f7f7;
float: left;
}
</style>
<div class="bt-form">
<div class='plugin_version'></div>
<div class="bt-w-main">
@@ -13,6 +50,7 @@
<p onclick="disableFunc($('.plugin_version').attr('version'));">禁用函数</p>
<p onclick="getFpmConfig($('.plugin_version').attr('version'));">性能调整</p>
<p onclick="getFpmStatus($('.plugin_version').attr('version'));">负载状况</p>
<p onclick="getSessionConfig($('.plugin_version').attr('version'));" title="session管理">会话管理</p>
<p onclick="pluginLogs('php-yum',$('.plugin_version').attr('version'),'fpm_log');">FPM日志</p>
<p onclick="pluginLogs('php-yum',$('.plugin_version').attr('version'),'fpm_slow_log');">慢日志</p>
<p onclick="getPhpinfo($('.plugin_version').attr('version'));">PHPIFNO</p>
+182
View File
@@ -492,6 +492,180 @@ def getFpmStatus(version):
return mw.returnJson(True, "OK", data)
def getSessionConf(version):
filename = getConf(version)
if not os.path.exists(filename):
return mw.returnJson(False, '指定PHP版本不存在!')
phpini = mw.readFile(filename)
rep = r'session.save_handler\s*=\s*([0-9A-Za-z_& ~]+)(\s*;?|\r?\n)'
save_handler = re.search(rep, phpini)
if save_handler:
save_handler = save_handler.group(1)
else:
save_handler = "files"
reppath = r'\nsession.save_path\s*=\s*"tcp\:\/\/([\d\.]+):(\d+).*\r?\n'
passrep = r'\nsession.save_path\s*=\s*"tcp://[\w\.\?\:]+=(.*)"\r?\n'
memcached = r'\nsession.save_path\s*=\s*"([\d\.]+):(\d+)"'
save_path = re.search(reppath, phpini)
if not save_path:
save_path = re.search(memcached, phpini)
passwd = re.search(passrep, phpini)
port = ""
if passwd:
passwd = passwd.group(1)
else:
passwd = ""
if save_path:
port = save_path.group(2)
save_path = save_path.group(1)
else:
save_path = ""
data = {"save_handler": save_handler, "save_path": save_path,
"passwd": passwd, "port": port}
return mw.returnJson(True, 'ok', data)
def setSessionConf(version):
args = getArgs()
ip = args['ip']
port = args['port']
passwd = args['passwd']
save_handler = args['save_handler']
if save_handler != "file":
iprep = r"(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})"
if not re.search(iprep, ip):
return mw.returnJson(False, '请输入正确的IP地址')
try:
port = int(port)
if port >= 65535 or port < 1:
return mw.returnJson(False, '请输入正确的端口号')
except:
return mw.returnJson(False, '请输入正确的端口号')
prep = r"[\~\`\/\=]"
if re.search(prep, passwd):
return mw.returnJson(False, '请不要输入以下特殊字符 " ~ ` / = "')
filename = getConf(version)
if not os.path.exists(filename):
return mw.returnJson(False, '指定PHP版本不存在!')
phpini = mw.readFile(filename)
session_tmp = getServerDir() + "/tmp/session"
rep = r'session.save_handler\s*=\s*(.+)\r?\n'
val = r'session.save_handler = ' + save_handler + '\n'
phpini = re.sub(rep, val, phpini)
content = mw.execShell('cat /etc/opt/remi/php' +
version + "/php.d/* | grep -v '^;' |tr -s '\n'")
content = content[0]
if save_handler == "memcached":
if not content.find("memcached.so") > -1:
return mw.returnJson(False, '请先安装%s扩展' % save_handler)
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "%s:%s" \n' % (ip, port)
if re.search(rep, phpini):
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "/tmp"',
'\n;session.save_path = "/tmp"' + val, phpini)
if save_handler == "memcache":
if not content.find("memcache.so") > -1:
return mw.returnJson(False, '请先安装%s扩展' % save_handler)
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "%s:%s" \n' % (ip, port)
if re.search(rep, phpini):
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "/tmp"',
'\n;session.save_path = "/tmp"' + val, phpini)
if save_handler == "redis":
if not content.find("redis.so") > -1:
return mw.returnJson(False, '请先安装%s扩展' % save_handler)
if passwd:
passwd = "?auth=" + passwd
else:
passwd = ""
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "tcp://%s:%s%s"\n' % (ip, port, passwd)
res = re.search(rep, phpini)
if res:
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "/tmp"',
'\n;session.save_path = "/tmp"' + val, phpini)
if save_handler == "file":
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "' + session_tmp + '"\n'
if re.search(rep, phpini):
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "/tmp"',
'\n;session.save_path = "/tmp"' + val, phpini)
mw.writeFile(filename, phpini)
restart(version)
return mw.returnJson(True, '设置成功!')
def getSessionCount_Origin(version):
session_tmp = getServerDir() + "/tmp/session"
d = ["/tmp", session_tmp]
count = 0
for i in d:
if not os.path.exists(i):
mw.execShell('mkdir -p %s' % i)
list = os.listdir(i)
for l in list:
if os.path.isdir(i + "/" + l):
l1 = os.listdir(i + "/" + l)
for ll in l1:
if "sess_" in ll:
count += 1
continue
if "sess_" in l:
count += 1
s = "find /tmp -mtime +1 |grep 'sess_' | wc -l"
old_file = int(mw.execShell(s)[0].split("\n")[0])
s = "find " + session_tmp + " -mtime +1 |grep 'sess_'|wc -l"
old_file += int(mw.execShell(s)[0].split("\n")[0])
return {"total": count, "oldfile": old_file}
def getSessionCount(version):
data = getSessionCount_Origin(version)
return mw.returnJson(True, 'ok!', data)
def cleanSessionOld(version):
s = "find /tmp -mtime +1 |grep 'sess_'|xargs rm -f"
mw.execShell(s)
session_tmp = getServerDir() + "/tmp/session"
s = "find " + session_tmp + " -mtime +1 |grep 'sess_' |xargs rm -f"
mw.execShell(s)
old_file_conf = getSessionCount_Origin(version)["oldfile"]
if old_file_conf == 0:
return mw.returnJson(True, '清理成功')
else:
return mw.returnJson(True, '清理失败')
def getDisableFunc(version):
filename = getConf(version)
if not os.path.exists(filename):
@@ -689,6 +863,14 @@ if __name__ == "__main__":
print(setFpmConfig(version))
elif func == 'get_fpm_status':
print(getFpmStatus(version))
elif func == 'get_session_conf':
print(getSessionConf(version))
elif func == 'set_session_conf':
print(setSessionConf(version))
elif func == 'get_session_count':
print(getSessionCount(version))
elif func == 'clean_session_old':
print(cleanSessionOld(version))
elif func == 'get_disable_func':
print(getDisableFunc(version))
elif func == 'set_disable_func':
+141
View File
@@ -340,6 +340,147 @@ function getFpmStatus(version){
});
}
function getSessionConfig(version){
phpPost('get_session_conf', version, '', function(ret_data){
var rdata = $.parseJSON(ret_data.data);
if(!rdata.status){
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
return;
}
var rdata = rdata.data;
var cacheList = "<option value='file' " + (rdata.save_handler == "file" ? 'selected' : '') + ">file</option>" +
"<option value='redis' " + (rdata.save_handler == "redis" ? 'selected' : '') + ">redis</option>" +
"<option value='memcache' " + (rdata.save_handler == "memcache" ? 'selected' : '') + ">memcache</option>" +
"<option value='memcached' " + (rdata.save_handler == "memcached" ? 'selected' : '') + ">memcached</option>";
var info = rdata.save_path.split(":");
var con = "<div class='conf_p'>" +
"<p class='line'><span class='span_tit'>存储模式:</span><select class='bt-input-text' name='save_handler' style='width:200px;'>" + cacheList + "</select></p>" +
"<p class='line'><span class='span_tit'>IP地址:</span><input class='bt-input-text' type='text' name='ip' style='width:200px;' value='"+ info[0] +"' /></p>" +
"<p class='line'><span class='span_tit'>端口:</span><input class='bt-input-text' type='text' name='port' style='width:200px;' value='"+rdata.port+"' /></p>" +
"<p class='line'><span class='span_tit'>密码:</span><input class='bt-input-text' type='text' name='passwd' style='width:200px;' value='"+rdata.passwd+"' /></p>" +
"<p class='line'><div class='mtb15' style='margin-left:100px;'><button class='btn btn-success btn-sm' onclick='setSessionConfig(\"" + version + "\",1)'>保存</button></div></p>" +
"</div>\
<ul class='help-info-text c7'>\
<li>若你的站点并发比较高,使用Redis,Memcache能有效提升PHP并发能力</li>\
<li>若调整Session模式后,网站访问异常,请切换回原来的模式</li>\
<li>切换Session模式会使在线的用户会话丢失,请在流量小的时候切换</li>\
</ul>\
<div id='session_clear' class='session_clear' style='border-top: #ccc 1px dashed;padding-top: 15px;margin-top: 15px;'>\
</div>\
</div>";
$(".soft-man-con").html(con);
if (rdata.save_handler == 'file'){
$('input[name="ip"]').attr('disabled','disabled');
$('input[name="port"]').attr('disabled','disabled');
$('input[name="passwd"]').attr('placeholder','如果没有密码留空');
$('input[name="passwd"]').attr('disabled','disabled');
}
// change event
$("select[name='save_handler']").change(function() {
var type = $(this).val();
var passwd = $('input[name="passwd"]').val();
if (passwd == ""){
$('input[name="passwd"]').attr('placeholder','如果没有密码留空');
}
var ip = $('input[name="ip"]').val();
if (ip == ""){
$('input[name="ip"]').val('127.0.0.1');
}
switch (type) {
case 'redis':
var port = $('input[name="port"]').val();
if (port == ""){
$('input[name="port"]').val('6379');
}
$('input[name="ip"]').removeAttr('disabled');
$('input[name="port"]').removeAttr('disabled');
$('input[name="passwd"]').removeAttr('disabled');
break;
case 'file':
$('input[name="ip"]').val("").attr('disabled','disabled');
$('input[name="port"]').val("").attr('disabled','disabled');
$('input[name="passwd"]').val("").attr('disabled','disabled');
break;
case 'memcache':
var port = $('input[name="port"]').val();
if (port == ""){
$('input[name="port"]').val('11211');
}
$('input[name="ip"]').removeAttr('disabled');
$('input[name="port"]').removeAttr('disabled');
$('input[name="passwd"]').removeAttr('disabled');
break;
case 'memcached':
var port = $('input[name="port"]').val();
if (port == ""){
$('input[name="port"]').val('11211');
}
$('input[name="ip"]').removeAttr('disabled');
$('input[name="port"]').removeAttr('disabled');
$('input[name="passwd"]').removeAttr('disabled');
break;
}
});
//load session stats
phpPost('get_session_count', version, '', function(ret_data){
var rdata = $.parseJSON(ret_data.data);
if(!rdata.status){
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
return;
}
var rdata = rdata.data;
var html_var = "<div class='clear_title' style='padding-bottom:15px;'>清理Session文件</div>\
<div class='clear_conter'>\
<div class='session_clear_list'>\
<div class='line'><span>总Session文件数量</span><span>"+rdata.total+"</span></div>\
<div class='line'><span>可清理的Session文件数量</span><span>"+rdata.oldfile+"</span></div>\
</div>\
<button id='clean_func' class='btn btn-success btn-sm clear_session_file'>清理session文件</button>";
$("#session_clear").html(html_var);
$('#clean_func').click(function(){
phpPost('clean_session_old', version, '', function(ret_data){
var rdata = $.parseJSON(ret_data.data);
showMsg(rdata.msg,function(){
getSessionConfig(version);
},{ icon: rdata.status ? 1 : 2 });
});
});
});
});
}
function setSessionConfig(version){
var ip = $('input[name="ip"]').val();
var port = $('input[name="port"]').val();
var passwd = $('input[name="passwd"]').val();
var save_handler = $("select[name='save_handler']").val();
var data = {
ip:ip,
port:port,
passwd:passwd,
save_handler:save_handler,
};
phpPost('set_session_conf', version, data, function(ret_data){
var rdata = $.parseJSON(ret_data.data);
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
});
}
//禁用函数
function disableFunc(version) {
phpPost('get_disable_func', version,'',function(data){
-725
View File
@@ -1,725 +0,0 @@
# coding:utf-8
import sys
import io
import os
import time
import re
import json
import shutil
# reload(sys)
# sys.setdefaultencoding('utf8')
sys.path.append(os.getcwd() + "/class/core")
# sys.path.append("/usr/local/lib/python3.6/site-packages")
import mw
if mw.isAppleSystem():
cmd = 'ls /usr/local/lib/ | grep python | cut -d \\ -f 1 | awk \'END {print}\''
info = mw.execShell(cmd)
p = "/usr/local/lib/" + info[0].strip() + "/site-packages"
sys.path.append(p)
app_debug = False
if mw.isAppleSystem():
app_debug = True
def getPluginName():
return 'php'
def getPluginDir():
return mw.getPluginDir() + '/' + getPluginName()
def getServerDir():
return mw.getServerDir() + '/' + getPluginName()
def getInitDFile(version):
if app_debug:
return '/tmp/' + getPluginName()
return '/etc/init.d/' + getPluginName() + version
def getArgs():
args = sys.argv[3:]
tmp = {}
args_len = len(args)
if args_len == 1:
t = args[0].strip('{').strip('}')
t = t.split(':')
tmp[t[0]] = t[1]
elif args_len > 1:
for i in range(len(args)):
t = args[i].split(':')
tmp[t[0]] = t[1]
return tmp
def checkArgs(data, ck=[]):
for i in range(len(ck)):
if not ck[i] in data:
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
return (True, mw.returnJson(True, 'ok'))
def getConf(version):
path = getServerDir() + '/' + version + '/etc/php.ini'
return path
def status(version):
cmd = "ps -ef|grep 'php/" + version + \
"' |grep -v grep | grep -v python | awk '{print $2}'"
data = mw.execShell(cmd)
if data[0] == '':
return 'stop'
return 'start'
def contentReplace(content, version):
service_path = mw.getServerDir()
content = content.replace('{$ROOT_PATH}', mw.getRootDir())
content = content.replace('{$SERVER_PATH}', service_path)
content = content.replace('{$PHP_VERSION}', version)
content = content.replace('{$LOCAL_IP}', mw.getLocalIp())
if mw.isAppleSystem():
# user = mw.execShell(
# "who | sed -n '2, 1p' |awk '{print $1}'")[0].strip()
content = content.replace('{$PHP_USER}', 'nobody')
content = content.replace('{$PHP_GROUP}', 'nobody')
rep = 'listen.owner\s*=\s*(.+)\r?\n'
val = ';listen.owner = nobody\n'
content = re.sub(rep, val, content)
rep = 'listen.group\s*=\s*(.+)\r?\n'
val = ';listen.group = nobody\n'
content = re.sub(rep, val, content)
rep = 'user\s*=\s*(.+)\r?\n'
val = ';user = nobody\n'
content = re.sub(rep, val, content)
rep = r'[^\.]group\s*=\s*(.+)\r?\n'
val = ';group = nobody\n'
content = re.sub(rep, val, content)
else:
content = content.replace('{$PHP_USER}', 'www')
content = content.replace('{$PHP_GROUP}', 'www')
return content
def makeOpenrestyConf():
phpversions = ['00', '52', '53', '54', '55', '56',
'70', '71', '72', '73', '74', '80', '81']
if mw.isInstalledWeb():
sdir = mw.getServerDir()
d_pathinfo = sdir + '/openresty/nginx/conf/pathinfo.conf'
if not os.path.exists(d_pathinfo):
s_pathinfo = getPluginDir() + '/conf/pathinfo.conf'
shutil.copyfile(s_pathinfo, d_pathinfo)
info = getPluginDir() + '/info.json'
content = mw.readFile(info)
content = json.loads(content)
versions = content['versions']
tpl = getPluginDir() + '/conf/enable-php.conf'
tpl_content = mw.readFile(tpl)
for x in phpversions:
dfile = sdir + '/openresty/nginx/conf/enable-php-' + x + '.conf'
if not os.path.exists(dfile):
if x == '00':
mw.writeFile(dfile, '')
else:
w_content = contentReplace(tpl_content, x)
mw.writeFile(dfile, w_content)
# php-fpm status
for version in phpversions:
dfile = sdir + '/openresty/nginx/conf/php_status/phpfpm_status_' + version + '.conf'
tpl = getPluginDir() + '/conf/phpfpm_status.conf'
if not os.path.exists(dfile):
content = mw.readFile(tpl)
content = contentReplace(content, version)
mw.writeFile(dfile, content)
mw.restartWeb()
def phpPrependFile(version):
app_start = getServerDir() + '/app_start.php'
if not os.path.exists(app_start):
tpl = getPluginDir() + '/conf/app_start.php'
content = mw.readFile(tpl)
content = contentReplace(content, version)
mw.writeFile(app_start, content)
def phpFpmReplace(version):
desc_php_fpm = getServerDir() + '/' + version + '/etc/php-fpm.conf'
if not os.path.exists(desc_php_fpm):
tpl_php_fpm = getPluginDir() + '/conf/php-fpm.conf'
content = mw.readFile(tpl_php_fpm)
content = contentReplace(content, version)
mw.writeFile(desc_php_fpm, content)
else:
if version == '52':
tpl_php_fpm = tpl_php_fpm = getPluginDir() + '/conf/php-fpm-52.conf'
content = mw.readFile(tpl_php_fpm)
mw.writeFile(desc_php_fpm, content)
def phpFpmWwwReplace(version):
service_php_fpm_dir = getServerDir() + '/' + version + '/etc/php-fpm.d/'
if not os.path.exists(service_php_fpm_dir):
os.mkdir(service_php_fpm_dir)
service_php_fpmwww = service_php_fpm_dir + '/www.conf'
if not os.path.exists(service_php_fpmwww):
tpl_php_fpmwww = getPluginDir() + '/conf/www.conf'
content = mw.readFile(tpl_php_fpmwww)
content = contentReplace(content, version)
mw.writeFile(service_php_fpmwww, content)
def makePhpIni(version):
d_ini = mw.getServerDir() + '/php/' + version + '/etc/php.ini'
if not os.path.exists(d_ini):
s_ini = getPluginDir() + '/conf/php' + version[0:1] + '.ini'
# shutil.copyfile(s_ini, d_ini)
content = mw.readFile(s_ini)
if version == '52':
content = content + "auto_prepend_file=/www/server/php/app_start.php"
mw.writeFile(d_ini, content)
def initReplace(version):
makeOpenrestyConf()
makePhpIni(version)
initD_path = getServerDir() + '/init.d'
if not os.path.exists(initD_path):
os.mkdir(initD_path)
file_bin = initD_path + '/php' + version
if not os.path.exists(file_bin):
file_tpl = getPluginDir() + '/init.d/php.tpl'
if version == '52':
file_tpl = getPluginDir() + '/init.d/php52.tpl'
content = mw.readFile(file_tpl)
content = contentReplace(content, version)
mw.writeFile(file_bin, content)
mw.execShell('chmod +x ' + file_bin)
phpPrependFile(version)
phpFpmWwwReplace(version)
phpFpmReplace(version)
session_path = '/tmp/session'
if not os.path.exists(session_path):
os.mkdir(session_path)
if not mw.isAppleSystem():
mw.execShell('chown -R www:www ' + session_path)
upload_path = '/tmp/upload'
if not os.path.exists(upload_path):
os.mkdir(upload_path)
if not mw.isAppleSystem():
mw.execShell('chown -R www:www ' + upload_path)
return file_bin
def phpOp(version, method):
file = initReplace(version)
data = mw.execShell(file + ' ' + method)
if data[1] == '':
return 'ok'
return data[1]
def start(version):
return phpOp(version, 'start')
def stop(version):
return phpOp(version, 'stop')
def restart(version):
return phpOp(version, 'restart')
def reload(version):
return phpOp(version, 'reload')
def initdStatus(version):
if not app_debug:
if mw.isAppleSystem():
return "Apple Computer does not support"
initd_bin = getInitDFile(version)
if os.path.exists(initd_bin):
return 'ok'
return 'fail'
def initdInstall(version):
import shutil
if not app_debug:
if mw.isAppleSystem():
return "Apple Computer does not support"
source_bin = initReplace(version)
initd_bin = getInitDFile(version)
shutil.copyfile(source_bin, initd_bin)
mw.execShell('chmod +x ' + initd_bin)
mw.execShell('chkconfig --add ' + getPluginName() + version)
return 'ok'
def initdUinstall(version):
if not app_debug:
if mw.isAppleSystem():
return "Apple Computer does not support"
mw.execShell('chkconfig --del ' + getPluginName())
initd_bin = getInitDFile(version)
os.remove(initd_bin)
return 'ok'
def fpmLog(version):
return getServerDir() + '/' + version + '/var/log/php-fpm.log'
def fpmSlowLog(version):
return getServerDir() + '/' + version + '/var/log/www-slow.log'
def getPhpConf(version):
gets = [
{'name': 'short_open_tag', 'type': 1, 'ps': '短标签支持'},
{'name': 'asp_tags', 'type': 1, 'ps': 'ASP标签支持'},
{'name': 'max_execution_time', 'type': 2, 'ps': '最大脚本运行时间'},
{'name': 'max_input_time', 'type': 2, 'ps': '最大输入时间'},
{'name': 'max_input_var', 'type': 2, 'ps': '最大输入数量'},
{'name': 'memory_limit', 'type': 2, 'ps': '脚本内存限制'},
{'name': 'post_max_size', 'type': 2, 'ps': 'POST数据最大尺寸'},
{'name': 'file_uploads', 'type': 1, 'ps': '是否允许上传文件'},
{'name': 'upload_max_filesize', 'type': 2, 'ps': '允许上传文件的最大尺寸'},
{'name': 'max_file_uploads', 'type': 2, 'ps': '允许同时上传文件的最大数量'},
{'name': 'default_socket_timeout', 'type': 2, 'ps': 'Socket超时时间'},
{'name': 'error_reporting', 'type': 3, 'ps': '错误级别'},
{'name': 'display_errors', 'type': 1, 'ps': '是否输出详细错误信息'},
{'name': 'cgi.fix_pathinfo', 'type': 0, 'ps': '是否开启pathinfo'},
{'name': 'date.timezone', 'type': 3, 'ps': '时区'}
]
phpini = mw.readFile(getServerDir() + '/' + version + '/etc/php.ini')
result = []
for g in gets:
rep = g['name'] + '\s*=\s*([0-9A-Za-z_& ~]+)(\s*;?|\r?\n)'
tmp = re.search(rep, phpini)
if not tmp:
continue
g['value'] = tmp.groups()[0]
result.append(g)
return mw.getJson(result)
def submitPhpConf(version):
gets = ['display_errors', 'cgi.fix_pathinfo', 'date.timezone', 'short_open_tag',
'asp_tags', 'max_execution_time', 'max_input_time', 'memory_limit',
'post_max_size', 'file_uploads', 'upload_max_filesize', 'max_file_uploads',
'default_socket_timeout', 'error_reporting']
args = getArgs()
filename = getServerDir() + '/' + version + '/etc/php.ini'
phpini = mw.readFile(filename)
for g in gets:
if g in args:
rep = g + '\s*=\s*(.+)\r?\n'
val = g + ' = ' + args[g] + '\n'
phpini = re.sub(rep, val, phpini)
mw.writeFile(filename, phpini)
mw.execShell(getServerDir() + '/init.d/php' + version + ' reload')
return mw.returnJson(True, '设置成功')
def getLimitConf(version):
fileini = getServerDir() + "/" + version + "/etc/php.ini"
phpini = mw.readFile(fileini)
filefpm = getServerDir() + "/" + version + "/etc/php-fpm.conf"
phpfpm = mw.readFile(filefpm)
# print fileini, filefpm
data = {}
try:
rep = "upload_max_filesize\s*=\s*([0-9]+)M"
tmp = re.search(rep, phpini).groups()
data['max'] = tmp[0]
except:
data['max'] = '50'
try:
rep = "request_terminate_timeout\s*=\s*([0-9]+)\n"
tmp = re.search(rep, phpfpm).groups()
data['maxTime'] = tmp[0]
except:
data['maxTime'] = 0
try:
rep = r"\n;*\s*cgi\.fix_pathinfo\s*=\s*([0-9]+)\s*\n"
tmp = re.search(rep, phpini).groups()
if tmp[0] == '1':
data['pathinfo'] = True
else:
data['pathinfo'] = False
except:
data['pathinfo'] = False
return mw.getJson(data)
def setMaxTime(version):
args = getArgs()
data = checkArgs(args, ['time'])
if not data[0]:
return data[1]
time = args['time']
if int(time) < 30 or int(time) > 86400:
return mw.returnJson(False, '请填写30-86400间的值!')
filefpm = getServerDir() + "/" + version + "/etc/php-fpm.conf"
conf = mw.readFile(filefpm)
rep = "request_terminate_timeout\s*=\s*([0-9]+)\n"
conf = re.sub(rep, "request_terminate_timeout = " + time + "\n", conf)
mw.writeFile(filefpm, conf)
fileini = getServerDir() + "/" + version + "/etc/php.ini"
phpini = mw.readFile(fileini)
rep = "max_execution_time\s*=\s*([0-9]+)\r?\n"
phpini = re.sub(rep, "max_execution_time = " + time + "\n", phpini)
rep = "max_input_time\s*=\s*([0-9]+)\r?\n"
phpini = re.sub(rep, "max_input_time = " + time + "\n", phpini)
mw.writeFile(fileini, phpini)
return mw.returnJson(True, '设置成功!')
def setMaxSize(version):
args = getArgs()
if not 'max' in args:
return 'missing time args!'
max = args['max']
if int(max) < 2:
return mw.returnJson(False, '上传大小限制不能小于2MB!')
path = getServerDir() + '/' + version + '/etc/php.ini'
conf = mw.readFile(path)
rep = u"\nupload_max_filesize\s*=\s*[0-9]+M"
conf = re.sub(rep, u'\nupload_max_filesize = ' + max + 'M', conf)
rep = u"\npost_max_size\s*=\s*[0-9]+M"
conf = re.sub(rep, u'\npost_max_size = ' + max + 'M', conf)
mw.writeFile(path, conf)
msg = mw.getInfo('设置PHP-{1}最大上传大小为[{2}MB]!', (version, max,))
mw.writeLog('插件管理[PHP]', msg)
return mw.returnJson(True, '设置成功!')
def getFpmConfig(version):
filefpm = getServerDir() + '/' + version + '/etc/php-fpm.d/www.conf'
conf = mw.readFile(filefpm)
data = {}
rep = "\s*pm.max_children\s*=\s*([0-9]+)\s*"
tmp = re.search(rep, conf).groups()
data['max_children'] = tmp[0]
rep = "\s*pm.start_servers\s*=\s*([0-9]+)\s*"
tmp = re.search(rep, conf).groups()
data['start_servers'] = tmp[0]
rep = "\s*pm.min_spare_servers\s*=\s*([0-9]+)\s*"
tmp = re.search(rep, conf).groups()
data['min_spare_servers'] = tmp[0]
rep = "\s*pm.max_spare_servers \s*=\s*([0-9]+)\s*"
tmp = re.search(rep, conf).groups()
data['max_spare_servers'] = tmp[0]
rep = "\s*pm\s*=\s*(\w+)\s*"
tmp = re.search(rep, conf).groups()
data['pm'] = tmp[0]
return mw.getJson(data)
def setFpmConfig(version):
args = getArgs()
# if not 'max' in args:
# return 'missing time args!'
version = args['version']
max_children = args['max_children']
start_servers = args['start_servers']
min_spare_servers = args['min_spare_servers']
max_spare_servers = args['max_spare_servers']
pm = args['pm']
file = getServerDir() + '/' + version + '/etc/php-fpm.d/www.conf'
conf = mw.readFile(file)
rep = "\s*pm.max_children\s*=\s*([0-9]+)\s*"
conf = re.sub(rep, "\npm.max_children = " + max_children, conf)
rep = "\s*pm.start_servers\s*=\s*([0-9]+)\s*"
conf = re.sub(rep, "\npm.start_servers = " + start_servers, conf)
rep = "\s*pm.min_spare_servers\s*=\s*([0-9]+)\s*"
conf = re.sub(rep, "\npm.min_spare_servers = " +
min_spare_servers, conf)
rep = "\s*pm.max_spare_servers \s*=\s*([0-9]+)\s*"
conf = re.sub(rep, "\npm.max_spare_servers = " +
max_spare_servers + "\n", conf)
rep = "\s*pm\s*=\s*(\w+)\s*"
conf = re.sub(rep, "\npm = " + pm + "\n", conf)
mw.writeFile(file, conf)
reload(version)
msg = mw.getInfo('设置PHP-{1}并发设置,max_children={2},start_servers={3},min_spare_servers={4},max_spare_servers={5}', (version, max_children,
start_servers, min_spare_servers, max_spare_servers,))
mw.writeLog('插件管理[PHP]', msg)
return mw.returnJson(True, '设置成功!')
def checkFpmStatusFile(version):
if mw.isInstalledWeb():
sdir = mw.getServerDir()
dfile = sdir + '/openresty/nginx/conf/php_status/phpfpm_status_' + version + '.conf'
if not os.path.exists(dfile):
tpl = getPluginDir() + '/conf/phpfpm_status.conf'
content = mw.readFile(tpl)
content = contentReplace(content, version)
mw.writeFile(dfile, content)
mw.restartWeb()
def getFpmStatus(version):
checkFpmStatusFile(version)
result = mw.httpGet(
'http://127.0.0.1/phpfpm_status_' + version + '?json')
tmp = json.loads(result)
fTime = time.localtime(int(tmp['start time']))
tmp['start time'] = time.strftime('%Y-%m-%d %H:%M:%S', fTime)
return mw.getJson(tmp)
def getDisableFunc(version):
filename = mw.getServerDir() + '/php/' + version + '/etc/php.ini'
if not os.path.exists(filename):
return mw.returnJson(False, '指定PHP版本不存在!')
phpini = mw.readFile(filename)
data = {}
rep = "disable_functions\s*=\s{0,1}(.*)\n"
tmp = re.search(rep, phpini).groups()
data['disable_functions'] = tmp[0]
return mw.getJson(data)
def setDisableFunc(version):
filename = mw.getServerDir() + '/php/' + version + '/etc/php.ini'
if not os.path.exists(filename):
return mw.returnJson(False, '指定PHP版本不存在!')
args = getArgs()
disable_functions = args['disable_functions']
phpini = mw.readFile(filename)
rep = "disable_functions\s*=\s*.*\n"
phpini = re.sub(rep, 'disable_functions = ' +
disable_functions + "\n", phpini)
msg = mw.getInfo('修改PHP-{1}的禁用函数为[{2}]', (version, disable_functions,))
mw.writeLog('插件管理[PHP]', msg)
mw.writeFile(filename, phpini)
reload(version)
return mw.returnJson(True, '设置成功!')
def checkPhpinfoFile(v):
if mw.isInstalledWeb():
sdir = mw.getServerDir()
dfile = sdir + '/openresty/nginx/conf/php_status/phpinfo_' + v + '.conf'
if not os.path.exists(dfile):
tpl = getPluginDir() + '/conf/phpinfo.conf'
content = mw.readFile(tpl)
content = contentReplace(content, v)
mw.writeFile(dfile, content)
mw.restartWeb()
def getPhpinfo(v):
checkPhpinfoFile(v)
sPath = mw.getRootDir() + '/phpinfo/' + v
mw.execShell("rm -rf " + mw.getRootDir() + '/phpinfo')
mw.execShell("mkdir -p " + sPath)
mw.writeFile(sPath + '/phpinfo.php', '<?php phpinfo(); ?>')
url = 'http://127.0.0.1/' + v + '/phpinfo.php'
phpinfo = mw.httpGet(url)
os.system("rm -rf " + mw.getRootDir() + '/phpinfo')
return phpinfo
def get_php_info(args):
return getPhpinfo(args['version'])
def getLibConf(version):
fname = mw.getServerDir() + '/php/' + version + '/etc/php.ini'
if not os.path.exists(fname):
return mw.returnJson(False, '指定PHP版本不存在!')
phpini = mw.readFile(fname)
libpath = getPluginDir() + '/versions/phplib.conf'
phplib = json.loads(mw.readFile(libpath))
libs = []
tasks = mw.M('tasks').where(
"status!=?", ('1',)).field('status,name').select()
for lib in phplib:
lib['task'] = '1'
for task in tasks:
tmp = mw.getStrBetween('[', ']', task['name'])
if not tmp:
continue
tmp1 = tmp.split('-')
if tmp1[0].lower() == lib['name'].lower():
lib['task'] = task['status']
lib['phpversions'] = []
lib['phpversions'].append(tmp1[1])
if phpini.find(lib['check']) == -1:
lib['status'] = False
else:
lib['status'] = True
libs.append(lib)
return mw.returnJson(True, 'OK!', libs)
def installLib(version):
args = getArgs()
data = checkArgs(args, ['name'])
if not data[0]:
return data[1]
name = args['name']
execstr = "cd " + getPluginDir() + '/versions/' + version + " && /bin/bash " + \
name + '.sh' + ' install ' + version
rettime = time.strftime('%Y-%m-%d %H:%M:%S')
insert_info = (None, '安装[' + name + '-' + version + ']',
'execshell', '0', rettime, execstr)
mw.M('tasks').add('id,name,type,status,addtime,execstr', insert_info)
return mw.returnJson(True, '已将下载任务添加到队列!')
def uninstallLib(version):
args = getArgs()
data = checkArgs(args, ['name'])
if not data[0]:
return data[1]
name = args['name']
execstr = "cd " + getPluginDir() + '/versions/' + version + " && /bin/bash " + \
name + '.sh' + ' uninstall ' + version
data = mw.execShell(execstr)
if data[0] == '' and data[1] == '':
return mw.returnJson(True, '已经卸载成功!')
else:
return mw.returnJson(False, '卸载信息![通道0]:' + data[0] + "[通道0]:" + data[1])
def getConfAppStart():
pstart = mw.getServerDir() + '/php/app_start.php'
return pstart
if __name__ == "__main__":
if len(sys.argv) < 3:
print('missing parameters')
exit(0)
func = sys.argv[1]
version = sys.argv[2]
if func == 'status':
print(status(version))
elif func == 'start':
print(start(version))
elif func == 'stop':
print(stop(version))
elif func == 'restart':
print(restart(version))
elif func == 'reload':
print(reload(version))
elif func == 'initd_status':
print(initdStatus(version))
elif func == 'initd_install':
print(initdInstall(version))
elif func == 'initd_uninstall':
print(initdUinstall(version))
elif func == 'fpm_log':
print(fpmLog(version))
elif func == 'fpm_slow_log':
print(fpmSlowLog(version))
elif func == 'conf':
print(getConf(version))
elif func == 'app_start':
print(getConfAppStart())
elif func == 'get_php_conf':
print(getPhpConf(version))
elif func == 'submit_php_conf':
print(submitPhpConf(version))
elif func == 'get_limit_conf':
print(getLimitConf(version))
elif func == 'set_max_time':
print(setMaxTime(version))
elif func == 'set_max_size':
print(setMaxSize(version))
elif func == 'get_fpm_conf':
print(getFpmConfig(version))
elif func == 'set_fpm_conf':
print(setFpmConfig(version))
elif func == 'get_fpm_status':
print(getFpmStatus(version))
elif func == 'get_disable_func':
print(getDisableFunc(version))
elif func == 'set_disable_func':
print(setDisableFunc(version))
elif func == 'get_phpinfo':
print(getPhpinfo(version))
elif func == 'get_lib_conf':
print(getLibConf(version))
elif func == 'install_lib':
print(installLib(version))
elif func == 'uninstall_lib':
print(uninstallLib(version))
else:
print("fail")
+40 -1
View File
@@ -1,6 +1,43 @@
<style type="text/css">
.bt-w-main{
height: 642px;
}
.session_clear_list {
border:1px solid #ececec;
margin-bottom: 15px;
width: 270px;
}
.session_clear_list .line {
padding: 0;
border-bottom: 1px solid #ececec;
width: 270px;
}
.session_clear_list .line:last-child {
border-bottom: 0px;
}
.session_clear_list .line span{
width: auto;
height: 35px;
line-height: 35px;
text-align: left;
padding: 0 5px;
}
.session_clear_list .line span:first-child {
width: 170px;
border-right: 1px solid #ececec;
background: #f7f7f7;
float: left;
}
</style>
<div class="bt-form">
<div class='plugin_version'></div>
<div class="bt-w-main">
<div class="bt-w-main" >
<div class="bt-w-menu">
<p class="bgw" onclick="pluginService('php', $('.plugin_version').attr('version'));">服务</p>
<p onclick="pluginInitD('php', $('.plugin_version').attr('version'));">自启动</p>
@@ -13,6 +50,7 @@
<p onclick="disableFunc($('.plugin_version').attr('version'));">禁用函数</p>
<p onclick="getFpmConfig($('.plugin_version').attr('version'));">性能调整</p>
<p onclick="getFpmStatus($('.plugin_version').attr('version'));">负载状况</p>
<p onclick="getSessionConfig($('.plugin_version').attr('version'));" title="session管理">会话管理</p>
<p onclick="pluginLogs('php',$('.plugin_version').attr('version'),'fpm_log');">FPM日志</p>
<p onclick="pluginLogs('php',$('.plugin_version').attr('version'),'fpm_slow_log');">慢日志</p>
<p onclick="getPhpinfo($('.plugin_version').attr('version'));">PHPIFNO</p>
@@ -24,6 +62,7 @@
</div>
</div>
<script type="text/javascript">
$.getScript( "/plugins/file?name=php&f=js/php.js", function(){
pluginService('php', $('.plugin_version').attr('version'));
+179
View File
@@ -632,6 +632,176 @@ def getFpmStatus(version):
return mw.returnJson(True, "OK", data)
def getSessionConf(version):
filename = getConf(version)
if not os.path.exists(filename):
return mw.returnJson(False, '指定PHP版本不存在!')
phpini = mw.readFile(filename)
rep = r'session.save_handler\s*=\s*([0-9A-Za-z_& ~]+)(\s*;?|\r?\n)'
save_handler = re.search(rep, phpini)
if save_handler:
save_handler = save_handler.group(1)
else:
save_handler = "files"
reppath = r'\nsession.save_path\s*=\s*"tcp\:\/\/([\d\.]+):(\d+).*\r?\n'
passrep = r'\nsession.save_path\s*=\s*"tcp://[\w\.\?\:]+=(.*)"\r?\n'
memcached = r'\nsession.save_path\s*=\s*"([\d\.]+):(\d+)"'
save_path = re.search(reppath, phpini)
if not save_path:
save_path = re.search(memcached, phpini)
passwd = re.search(passrep, phpini)
port = ""
if passwd:
passwd = passwd.group(1)
else:
passwd = ""
if save_path:
port = save_path.group(2)
save_path = save_path.group(1)
else:
save_path = ""
data = {"save_handler": save_handler, "save_path": save_path,
"passwd": passwd, "port": port}
return mw.returnJson(True, 'ok', data)
def setSessionConf(version):
args = getArgs()
ip = args['ip']
port = args['port']
passwd = args['passwd']
save_handler = args['save_handler']
if save_handler != "file":
iprep = r"(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})"
if not re.search(iprep, ip):
return mw.returnJson(False, '请输入正确的IP地址')
try:
port = int(port)
if port >= 65535 or port < 1:
return mw.returnJson(False, '请输入正确的端口号')
except:
return mw.returnJson(False, '请输入正确的端口号')
prep = r"[\~\`\/\=]"
if re.search(prep, passwd):
return mw.returnJson(False, '请不要输入以下特殊字符 " ~ ` / = "')
filename = getConf(version)
if not os.path.exists(filename):
return mw.returnJson(False, '指定PHP版本不存在!')
phpini = mw.readFile(filename)
session_tmp = getServerDir() + "/tmp/session"
rep = r'session.save_handler\s*=\s*(.+)\r?\n'
val = r'session.save_handler = ' + save_handler + '\n'
phpini = re.sub(rep, val, phpini)
if save_handler == "memcached":
if not re.search("memcached.so", phpini):
return mw.returnJson(False, '请先安装%s扩展' % save_handler)
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "%s:%s" \n' % (ip, port)
if re.search(rep, phpini):
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "' + session_tmp + '"',
'\n;session.save_path = "' + session_tmp + '"' + val, phpini)
if save_handler == "memcache":
if not re.search("memcache.so", phpini):
return mw.returnJson(False, '请先安装%s扩展' % save_handler)
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "%s:%s" \n' % (ip, port)
if re.search(rep, phpini):
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "' + session_tmp + '"',
'\n;session.save_path = "' + session_tmp + '"' + val, phpini)
if save_handler == "redis":
if not re.search("redis.so", phpini):
return mw.returnJson(False, '请先安装%s扩展' % save_handler)
if passwd:
passwd = "?auth=" + passwd
else:
passwd = ""
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "tcp://%s:%s%s"\n' % (ip, port, passwd)
res = re.search(rep, phpini)
if res:
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "' + session_tmp + '"',
'\n;session.save_path = "' + session_tmp + '"' + val, phpini)
if save_handler == "file":
rep = r'\nsession.save_path\s*=\s*(.+)\r?\n'
val = r'\nsession.save_path = "' + session_tmp + '"\n'
if re.search(rep, phpini):
phpini = re.sub(rep, val, phpini)
else:
phpini = re.sub('\n;session.save_path = "' + session_tmp + '"',
'\n;session.save_path = "' + session_tmp + '"' + val, phpini)
mw.writeFile(filename, phpini)
reload(version)
return mw.returnJson(True, '设置成功!')
def getSessionCount_Origin(version):
session_tmp = getServerDir() + "/tmp/session"
d = [session_tmp]
count = 0
for i in d:
if not os.path.exists(i):
mw.execShell('mkdir -p %s' % i)
list = os.listdir(i)
for l in list:
if os.path.isdir(i + "/" + l):
l1 = os.listdir(i + "/" + l)
for ll in l1:
if "sess_" in ll:
count += 1
continue
if "sess_" in l:
count += 1
s = "find /tmp -mtime +1 |grep 'sess_' | wc -l"
old_file = int(mw.execShell(s)[0].split("\n")[0])
s = "find " + session_tmp + " -mtime +1 |grep 'sess_'|wc -l"
old_file += int(mw.execShell(s)[0].split("\n")[0])
return {"total": count, "oldfile": old_file}
def getSessionCount(version):
data = getSessionCount_Origin(version)
return mw.returnJson(True, 'ok!', data)
def cleanSessionOld(version):
s = "find /tmp -mtime +1 |grep 'sess_'|xargs rm -f"
mw.execShell(s)
session_tmp = getServerDir() + "/tmp/session"
s = "find " + session_tmp + " -mtime +1 |grep 'sess_' |xargs rm -f"
mw.execShell(s)
old_file_conf = getSessionCount_Origin(version)["oldfile"]
if old_file_conf == 0:
return mw.returnJson(True, '清理成功')
else:
return mw.returnJson(True, '清理失败')
def getDisableFunc(version):
filename = getConf(version)
if not os.path.exists(filename):
@@ -794,6 +964,7 @@ def installPreInspection(version):
return 'fedora[{}]不可安装'.format(sysId)
return 'ok'
if __name__ == "__main__":
if len(sys.argv) < 3:
@@ -847,6 +1018,14 @@ if __name__ == "__main__":
print(setFpmConfig(version))
elif func == 'get_fpm_status':
print(getFpmStatus(version))
elif func == 'get_session_conf':
print(getSessionConf(version))
elif func == 'set_session_conf':
print(setSessionConf(version))
elif func == 'get_session_count':
print(getSessionCount(version))
elif func == 'clean_session_old':
print(cleanSessionOld(version))
elif func == 'get_disable_func':
print(getDisableFunc(version))
elif func == 'set_disable_func':
+146 -14
View File
@@ -1,14 +1,3 @@
function str2Obj(str){
var data = {};
kv = str.split('&');
for(i in kv){
v = kv[i].split('=');
data[v[0]] = v[1];
}
return data;
}
function phpPost(method, version, args,callback){
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
@@ -18,7 +7,7 @@ function phpPost(method, version, args,callback){
req_data['version'] = version;
if (typeof(args) == 'string'){
req_data['args'] = JSON.stringify(str2Obj(args));
req_data['args'] = JSON.stringify(toArrayObject(args));
} else {
req_data['args'] = JSON.stringify(args);
}
@@ -46,7 +35,7 @@ function phpPostCallbak(method, version, args,callback){
args['version'] = version;
if (typeof(args) == 'string'){
req_data['args'] = JSON.stringify(str2Obj(args));
req_data['args'] = JSON.stringify(toArrayObject(args));
} else {
req_data['args'] = JSON.stringify(args);
}
@@ -194,7 +183,7 @@ function getFpmConfig(version){
"<option value='3' " + (rdata.max_children == 100 ? 'selected' : '') + ">100并发</option>" +
"<option value='4' " + (rdata.max_children == 200 ? 'selected' : '') + ">200并发</option>" +
"<option value='5' " + (rdata.max_children == 300 ? 'selected' : '') + ">300并发</option>" +
"<option value='6' " + (rdata.max_children == 500 ? 'selected' : '') + ">500并发</option>"
"<option value='6' " + (rdata.max_children == 500 ? 'selected' : '') + ">500并发</option>";
var pms = [{ 'name': 'static', 'title': '静态' }, { 'name': 'dynamic', 'title': '动态' }];
var pmList = '';
for (var i = 0; i < pms.length; i++) {
@@ -340,6 +329,149 @@ function getFpmStatus(version){
});
}
function getSessionConfig(version){
phpPost('get_session_conf', version, '', function(ret_data){
var rdata = $.parseJSON(ret_data.data);
if(!rdata.status){
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
return;
}
var rdata = rdata.data;
var cacheList = "<option value='file' " + (rdata.save_handler == "file" ? 'selected' : '') + ">file</option>" +
"<option value='redis' " + (rdata.save_handler == "redis" ? 'selected' : '') + ">redis</option>" +
"<option value='memcache' " + (rdata.save_handler == "memcache" ? 'selected' : '') + ">memcache</option>" +
"<option value='memcached' " + (rdata.save_handler == "memcached" ? 'selected' : '') + ">memcached</option>";
var info = rdata.save_path.split(":");
var con = "<div class='conf_p'>" +
"<p class='line'><span class='span_tit'>存储模式:</span><select class='bt-input-text' name='save_handler' style='width:200px;'>" + cacheList + "</select></p>" +
"<p class='line'><span class='span_tit'>IP地址:</span><input class='bt-input-text' type='text' name='ip' style='width:200px;' value='"+ info[0] +"' /></p>" +
"<p class='line'><span class='span_tit'>端口:</span><input class='bt-input-text' type='text' name='port' style='width:200px;' value='"+rdata.port+"' /></p>" +
"<p class='line'><span class='span_tit'>密码:</span><input class='bt-input-text' type='text' name='passwd' style='width:200px;' value='"+rdata.passwd+"' /></p>" +
"<p class='line'><div class='mtb15' style='margin-left:100px;'><button class='btn btn-success btn-sm' onclick='setSessionConfig(\"" + version + "\",1)'>保存</button></div></p>" +
"</div>\
<ul class='help-info-text c7'>\
<li>若你的站点并发比较高,使用Redis,Memcache能有效提升PHP并发能力</li>\
<li>若调整Session模式后,网站访问异常,请切换回原来的模式</li>\
<li>切换Session模式会使在线的用户会话丢失,请在流量小的时候切换</li>\
</ul>\
<div id='session_clear' class='session_clear' style='border-top: #ccc 1px dashed;padding-top: 15px;margin-top: 15px;'>\
</div>\
</div>";
$(".soft-man-con").html(con);
if (rdata.save_handler == 'file'){
$('input[name="ip"]').attr('disabled','disabled');
$('input[name="port"]').attr('disabled','disabled');
$('input[name="passwd"]').attr('placeholder','如果没有密码留空');
$('input[name="passwd"]').attr('disabled','disabled');
}
// change event
$("select[name='save_handler']").change(function() {
var type = $(this).val();
var passwd = $('input[name="passwd"]').val();
if (passwd == ""){
$('input[name="passwd"]').attr('placeholder','如果没有密码留空');
}
var ip = $('input[name="ip"]').val();
if (ip == ""){
$('input[name="ip"]').val('127.0.0.1');
}
switch (type) {
case 'redis':
var port = $('input[name="port"]').val();
if (port == ""){
$('input[name="port"]').val('6379');
}
$('input[name="ip"]').removeAttr('disabled');
$('input[name="port"]').removeAttr('disabled');
$('input[name="passwd"]').removeAttr('disabled');
break;
case 'file':
$('input[name="ip"]').val("").attr('disabled','disabled');
$('input[name="port"]').val("").attr('disabled','disabled');
$('input[name="passwd"]').val("").attr('disabled','disabled');
break;
case 'memcache':
var port = $('input[name="port"]').val();
if (port == ""){
$('input[name="port"]').val('11211');
}
$('input[name="ip"]').removeAttr('disabled');
$('input[name="port"]').removeAttr('disabled');
$('input[name="passwd"]').removeAttr('disabled');
break;
case 'memcached':
var port = $('input[name="port"]').val();
if (port == ""){
$('input[name="port"]').val('11211');
}
$('input[name="ip"]').removeAttr('disabled');
$('input[name="port"]').removeAttr('disabled');
$('input[name="passwd"]').removeAttr('disabled');
break;
}
});
//load session stats
phpPost('get_session_count', version, '', function(ret_data){
var rdata = $.parseJSON(ret_data.data);
if(!rdata.status){
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
return;
}
var rdata = rdata.data;
var html_var = "<div class='clear_title' style='padding-bottom:15px;'>清理Session文件</div>\
<div class='clear_conter'>\
<div class='session_clear_list'>\
<div class='line'><span>总Session文件数量</span><span>"+rdata.total+"</span></div>\
<div class='line'><span>可清理的Session文件数量</span><span>"+rdata.oldfile+"</span></div>\
</div>\
<button id='clean_func' class='btn btn-success btn-sm clear_session_file'>清理session文件</button>";
$("#session_clear").html(html_var);
$('#clean_func').click(function(){
phpPost('clean_session_old', version, '', function(ret_data){
var rdata = $.parseJSON(ret_data.data);
showMsg(rdata.msg,function(){
getSessionConfig(version);
},{ icon: rdata.status ? 1 : 2 });
});
});
});
});
}
function setSessionConfig(version){
var ip = $('input[name="ip"]').val();
var port = $('input[name="port"]').val();
var passwd = $('input[name="passwd"]').val();
var save_handler = $("select[name='save_handler']").val();
var data = {
ip:ip,
port:port,
passwd:passwd,
save_handler:save_handler,
};
phpPost('set_session_conf', version, data, function(ret_data){
var rdata = $.parseJSON(ret_data.data);
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
});
}
//禁用函数
function disableFunc(version) {
phpPost('get_disable_func', version,'',function(data){
+23 -1
View File
@@ -56,6 +56,28 @@ if [ "$IS_64BIT" == "64" ];then
OPTIONS="${OPTIONS} --with-libdir=lib64"
fi
# ----- cpu start ------
if [ -z "${cpuCore}" ]; then
cpuCore="1"
fi
if [ -f /proc/cpuinfo ];then
cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l`
fi
MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}')
if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
if [ "${cpuCore}" -gt "${MEM_INFO}" ];then
cpuCore="${MEM_INFO}"
fi
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -d $serverPath/php/53/bin ];then
cd $sourcePath/php/php${PHP_VER} && ./configure \
@@ -88,7 +110,7 @@ if [ ! -d $serverPath/php/53/bin ];then
--disable-fileinfo \
$OPTIONS \
--enable-fpm
make clean && make && make install && make clean
make clean && make -j${cpuCore} && make install && make clean
fi
+24 -1
View File
@@ -48,6 +48,29 @@ if [ "$IS_64BIT" == "64" ];then
OPTIONS="${OPTIONS} --with-libdir=lib64"
fi
# ----- cpu start ------
if [ -z "${cpuCore}" ]; then
cpuCore="1"
fi
if [ -f /proc/cpuinfo ];then
cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l`
fi
MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}')
if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
if [ "${cpuCore}" -gt "${MEM_INFO}" ];then
cpuCore="${MEM_INFO}"
fi
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -d $serverPath/php/${PHP_VER} ];then
cd $sourcePath/php/php${PHP_VER} && ./configure \
@@ -73,7 +96,7 @@ if [ ! -d $serverPath/php/${PHP_VER} ];then
$OPTIONS \
--enable-fpm
make clean && make
make clean && make -j${cpuCore}
#debian11,没有生成php54 man
if [ ! -f sapi/cli/php.1 ];then
+24 -1
View File
@@ -47,6 +47,29 @@ if [ "$IS_64BIT" == "64" ];then
OPTIONS="${OPTIONS} --with-libdir=lib64"
fi
# ----- cpu start ------
if [ -z "${cpuCore}" ]; then
cpuCore="1"
fi
if [ -f /proc/cpuinfo ];then
cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l`
fi
MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}')
if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
if [ "${cpuCore}" -gt "${MEM_INFO}" ];then
cpuCore="${MEM_INFO}"
fi
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -d $serverPath/php/55 ];then
cd $sourcePath/php/php${PHP_VER} && ./configure \
--prefix=$serverPath/php/55 \
@@ -71,7 +94,7 @@ if [ ! -d $serverPath/php/55 ];then
--disable-fileinfo \
$OPTIONS \
--enable-fpm
make clean && make && make install && make clean
make clean && make -j${cpuCore} && make install && make clean
fi
#------------------------ install end ------------------------------------#
+24 -1
View File
@@ -47,6 +47,29 @@ if [ "$IS_64BIT" == "64" ];then
OPTIONS="${OPTIONS} --with-libdir=lib64"
fi
# ----- cpu start ------
if [ -z "${cpuCore}" ]; then
cpuCore="1"
fi
if [ -f /proc/cpuinfo ];then
cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l`
fi
MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}')
if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
if [ "${cpuCore}" -gt "${MEM_INFO}" ];then
cpuCore="${MEM_INFO}"
fi
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -d $serverPath/php/56 ];then
cd $sourcePath/php/php${PHP_VER} && ./configure \
@@ -74,7 +97,7 @@ if [ ! -d $serverPath/php/56 ];then
--disable-fileinfo \
$OPTIONS \
--enable-fpm
make clean && make && make install && make clean
make clean && make -j${cpuCore} && make install && make clean
fi
#------------------------ install end ------------------------------------#
+4
View File
@@ -64,6 +64,10 @@ if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -d $serverPath/php/70 ];then
+24 -1
View File
@@ -44,6 +44,29 @@ if [ "$IS_64BIT" == "64" ];then
OPTIONS="${OPTIONS} --with-libdir=lib64"
fi
# ----- cpu start ------
if [ -z "${cpuCore}" ]; then
cpuCore="1"
fi
if [ -f /proc/cpuinfo ];then
cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l`
fi
MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}')
if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
if [ "${cpuCore}" -gt "${MEM_INFO}" ];then
cpuCore="${MEM_INFO}"
fi
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -d $serverPath/php/71 ];then
cd $sourcePath/php/php${PHP_VER} && ./configure \
--prefix=$serverPath/php/71 \
@@ -67,7 +90,7 @@ if [ ! -d $serverPath/php/71 ];then
--disable-fileinfo \
$OPTIONS \
--enable-fpm
make clean && make && make install && make clean
make clean && make -j${cpuCore} && make install && make clean
fi
#------------------------ install end ------------------------------------#
+24 -1
View File
@@ -46,6 +46,29 @@ if [ "$IS_64BIT" == "64" ];then
OPTIONS="${OPTIONS} --with-libdir=lib64"
fi
# ----- cpu start ------
if [ -z "${cpuCore}" ]; then
cpuCore="1"
fi
if [ -f /proc/cpuinfo ];then
cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l`
fi
MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}')
if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
if [ "${cpuCore}" -gt "${MEM_INFO}" ];then
cpuCore="${MEM_INFO}"
fi
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -d $serverPath/php/72 ];then
cd $sourcePath/php/php${PHP_VER} && ./configure \
--prefix=$serverPath/php/72 \
@@ -69,7 +92,7 @@ if [ ! -d $serverPath/php/72 ];then
--disable-fileinfo \
$OPTIONS \
--enable-fpm
make clean && make && make install && make clean
make clean && make -j${cpuCore} && make install && make clean
fi
#------------------------ install end ------------------------------------#
+24 -1
View File
@@ -60,6 +60,29 @@ if version_lt "$libzip_version" "0.11.0" ;then
ZIP_OPTION="--with-libzip=$serverPath/lib/libzip"
fi
# ----- cpu start ------
if [ -z "${cpuCore}" ]; then
cpuCore="1"
fi
if [ -f /proc/cpuinfo ];then
cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l`
fi
MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}')
if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
if [ "${cpuCore}" -gt "${MEM_INFO}" ];then
cpuCore="${MEM_INFO}"
fi
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -d $serverPath/php/73 ];then
cd $sourcePath/php/php${PHP_VER} && ./configure \
--prefix=$serverPath/php/73 \
@@ -83,7 +106,7 @@ if [ ! -d $serverPath/php/73 ];then
--disable-fileinfo \
$OPTIONS \
--enable-fpm
make clean && make && make install && make clean
make clean && make -j${cpuCore} && make install && make clean
fi
#------------------------ install end ------------------------------------#
+23 -1
View File
@@ -76,6 +76,28 @@ if version_lt "$libzip_version" "0.11.0" ;then
ZIP_OPTION="--with-zip=$serverPath/lib/libzip"
fi
# ----- cpu start ------
if [ -z "${cpuCore}" ]; then
cpuCore="1"
fi
if [ -f /proc/cpuinfo ];then
cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l`
fi
MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}')
if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
if [ "${cpuCore}" -gt "${MEM_INFO}" ];then
cpuCore="${MEM_INFO}"
fi
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
if [ ! -d $serverPath/php/${PHP_VER} ];then
cd $sourcePath/php/php${PHP_VER} && make clean
@@ -102,7 +124,7 @@ if [ ! -d $serverPath/php/${PHP_VER} ];then
--disable-fileinfo \
$OPTIONS \
--enable-fpm
make && make install && make clean
make clean && make -j${cpuCore} && make install && make clean
fi
#------------------------ install end ------------------------------------#
}
+25 -2
View File
@@ -16,7 +16,7 @@ function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)"
function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; }
version=8.0.23
version=8.0.24
PHP_VER=80
Install_php()
{
@@ -67,6 +67,29 @@ if version_lt "$libzip_version" "0.11.0" ;then
ZIP_OPTION="--with-zip=$serverPath/lib/libzip"
fi
# ----- cpu start ------
if [ -z "${cpuCore}" ]; then
cpuCore="1"
fi
if [ -f /proc/cpuinfo ];then
cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l`
fi
MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}')
if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
if [ "${cpuCore}" -gt "${MEM_INFO}" ];then
cpuCore="${MEM_INFO}"
fi
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
echo "$sourcePath/php/php${PHP_VER}"
if [ ! -d $serverPath/php/${PHP_VER} ];then
@@ -94,7 +117,7 @@ if [ ! -d $serverPath/php/${PHP_VER} ];then
--disable-fileinfo \
$OPTIONS \
--enable-fpm
make clean && make && make install && make clean
make clean && make -j${cpuCore} && make install && make clean
fi
#------------------------ install end ------------------------------------#
}
+24 -2
View File
@@ -16,7 +16,7 @@ function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)"
function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; }
version=8.1.10
version=8.1.11
PHP_VER=81
Install_php()
{
@@ -61,6 +61,28 @@ if version_lt "$libzip_version" "0.11.0" ;then
ZIP_OPTION="--with-zip=$serverPath/lib/libzip"
fi
# ----- cpu start ------
if [ -z "${cpuCore}" ]; then
cpuCore="1"
fi
if [ -f /proc/cpuinfo ];then
cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l`
fi
MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}')
if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
if [ "${cpuCore}" -gt "${MEM_INFO}" ];then
cpuCore="${MEM_INFO}"
fi
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
echo "$sourcePath/php/php${PHP_VER}"
@@ -89,7 +111,7 @@ if [ ! -d $serverPath/php/${PHP_VER} ];then
--disable-fileinfo \
$OPTIONS \
--enable-fpm
make clean && make && make install && make clean
make clean && make -j${cpuCore} && make install && make clean
fi
#------------------------ install end ------------------------------------#
}
+26 -3
View File
@@ -16,7 +16,7 @@ function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)"
function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; }
version=8.2.0RC2
version=8.2.0RC3
PHP_VER=82
Install_php()
{
@@ -32,7 +32,7 @@ cd ${rootPath}/plugins/php/lib && /bin/bash zlib.sh
if [ ! -d $sourcePath/php/php${PHP_VER} ];then
if [ ! -f $sourcePath/php/php-${version}.tar.xz ];then
wget --no-check-certificate -O $sourcePath/php/php-${version}.tar.xz https://downloads.php.net/~sergey/php-${version}.tar.xz
wget --no-check-certificate -O $sourcePath/php/php-${version}.tar.xz https://downloads.php.net/~pierrick/php-${version}.tar.xz
fi
cd $sourcePath/php && tar -Jxf $sourcePath/php/php-${version}.tar.xz
@@ -55,6 +55,29 @@ if [ "$IS_64BIT" == "64" ];then
OPTIONS="${OPTIONS} --with-libdir=lib64"
fi
# ----- cpu start ------
if [ -z "${cpuCore}" ]; then
cpuCore="1"
fi
if [ -f /proc/cpuinfo ];then
cpuCore=`cat /proc/cpuinfo | grep "processor" | wc -l`
fi
MEM_INFO=$(free -m|grep Mem|awk '{printf("%.f",($2)/1024)}')
if [ "${cpuCore}" != "1" ] && [ "${MEM_INFO}" != "0" ];then
if [ "${cpuCore}" -gt "${MEM_INFO}" ];then
cpuCore="${MEM_INFO}"
fi
else
cpuCore="1"
fi
if [ "$cpuCore" -gt "1" ];then
cpuCore=`echo "$cpuCore" | awk '{printf("%.f",($1)*0.8)}'`
fi
# ----- cpu end ------
ZIP_OPTION='--with-zip'
libzip_version=`pkg-config libzip --modversion`
if version_lt "$libzip_version" "0.11.0" ;then
@@ -90,7 +113,7 @@ if [ ! -d $serverPath/php/${PHP_VER} ];then
--disable-fileinfo \
$OPTIONS \
--enable-fpm
make clean && make && make install && make clean
make clean && make -j${cpuCore} && make install && make clean
fi
#------------------------ install end ------------------------------------#
}
+5
View File
@@ -46,6 +46,11 @@ Install_lib()
cd ${rootPath}/plugins/php/lib && /bin/bash openssl_10.sh
fi
if [ "$sysName" == "Darwin" ] ;then
LIB_DEPEND_DIR=`brew info openssl@1.1 | grep /usr/local/Cellar/openssl | cut -d \ -f 1 | awk 'END {print}'`
export PKG_CONFIG_PATH=$LIB_DEPEND_DIR/lib/pkgconfig
fi
if [ ! -f "$extFile" ];then
if [ ! -d $sourcePath/php${version}/ext ];then
+26 -1
View File
@@ -584,6 +584,18 @@
{
"name": "zip",
"versions": [
"53",
"54",
"55",
"56",
"70",
"71",
"72",
"73",
"74",
"80",
"81",
"82"
],
"type": "压缩",
"msg": "压缩组件",
@@ -592,7 +604,20 @@
},
{
"name": "zlib",
"versions": [],
"versions": [
"53",
"54",
"55",
"56",
"70",
"71",
"72",
"73",
"74",
"80",
"81",
"82"
],
"type": "压缩",
"msg": "压缩组件",
"shell": "zlib.sh",
+1 -1
View File
@@ -1,7 +1,7 @@
daemonize yes
pidfile {$SERVER_PATH}/redis/redis_6379.pid
bind 127.0.0.1
bind 0.0.0.0
port 6379
requirepass admin
+13 -3
View File
@@ -125,7 +125,7 @@ def redisOp(method):
data = mw.execShell('systemctl ' + method + ' redis')
if data[1] == '':
return 'ok'
return 'fail'
return data[1]
data = mw.execShell(file + ' start')
if data[1] == '':
@@ -154,6 +154,10 @@ def reload():
def runInfo():
s = status()
if s == 'stop':
return mw.returnJson(False, '未启动')
requirepass = ""
conf = getServerDir() + '/redis.conf'
@@ -163,9 +167,15 @@ def runInfo():
if tmp:
requirepass = tmp.groups()[1]
cmd = getServerDir() + "/bin/redis-cli info"
default_ip = '0.0.0.0'
findDebian = mw.execShell('cat /etc/issue |grep Debian')
if findDebian[0] != '':
default_ip = mw.getLocalIp()
cmd = getServerDir() + "/bin/redis-cli -h " + default_ip + " info"
if requirepass != "":
cmd = getServerDir() + '/bin/redis-cli -a "' + requirepass + '" info'
cmd = getServerDir() + '/bin/redis-cli -h ' + default_ip + \
' -a "' + requirepass + '" info'
data = mw.execShell(cmd)[0]
res = [
-1
View File
@@ -5,7 +5,6 @@ After=network.target
[Service]
Type=forking
ExecStart={$SERVER_PATH}/redis/bin/redis-server {$SERVER_PATH}/redis/redis.conf
ExecStop={$SERVER_PATH}/redis/redis-cli shutdown
ExecReload=/bin/kill -USR2 $MAINPID
Restart=on-failure
+5
View File
@@ -69,6 +69,11 @@ function redisStatus(version) {
redisPost('run_info',version, {},function(data){
var rdata = $.parseJSON(data.data);
// if (!rdata.status){
// layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']});
// return;
// }
hit = (parseInt(rdata.keyspace_hits) / (parseInt(rdata.keyspace_hits) + parseInt(rdata.keyspace_misses)) * 100).toFixed(2);
var con = '<div class="divtable">\
<table class="table table-hover table-bordered" style="width: 490px;">\
+5 -11
View File
@@ -3,7 +3,7 @@
<div class="bt-w-menu">
<p class="bgw" onclick="pluginService('swap');">服务</p>
<p onclick="pluginInitD('swap');">自启动</p>
<!-- <p onclick="pluginConfig('swap');">配置修改</p> -->
<p onclick="swapStatus();">配置调整</p>
<p onclick="readme();">说明</p>
</div>
<div class="bt-w-con pd15">
@@ -11,15 +11,9 @@
</div>
</div>
</div>
<script type="text/javascript">
pluginService('swap');
function readme(){
var readme = '<ul class="help-info-text c7">';
readme += '<li>dd if=/dev/zero of=/www/server/swap/swapfile bs=1M count=2048</li>';
readme += '<li>mkswap /www/server/swap/swapfile</li>';
readme += '</ul>';
$('.soft-man-con').html(readme);
}
$.getScript( "/plugins/file?name=swap&f=js/swap.js", function(){
pluginService('swap');
});
</script>
+43 -2
View File
@@ -53,6 +53,13 @@ def getArgs():
return tmp
def checkArgs(data, ck=[]):
for i in range(len(ck)):
if not ck[i] in data:
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
return (True, mw.returnJson(True, 'ok'))
def status():
data = mw.execShell("free -m|grep Swap|awk '{print $2}'")
if data[0].strip() == '0':
@@ -110,7 +117,7 @@ def swapOp(method):
return 'ok'
return 'fail'
data = mw.execShell(file + ' start')
data = mw.execShell(file + ' ' + method)
if data[1] == '':
return 'ok'
return 'fail'
@@ -129,7 +136,7 @@ def restart():
def reload():
return swapOp('reload')
return 'ok'
def initdStatus():
@@ -158,6 +165,36 @@ def initdUinstall():
mw.execShell('systemctl disable swap')
return 'ok'
def swapStatus():
sfile = getServerDir() + '/swapfile'
if os.path.exists(sfile):
size = os.path.getsize(sfile) / 1024 / 1024
else:
size = '218'
data = {'size': size}
return mw.returnJson(True, "ok", data)
def changeSwap():
args = getArgs()
data = checkArgs(args, ['size'])
if not data[0]:
return data[1]
size = args['size']
swapOp('stop')
gsdir = getServerDir()
cmd = 'dd if=/dev/zero of=' + gsdir + '/swapfile bs=1M count=' + size
cmd += ' && mkswap ' + gsdir + '/swapfile && chmod 600 ' + gsdir + '/swapfile'
msg = mw.execShell(cmd)
swapOp('start')
return mw.returnJson(True, "修改成功:\n" + msg[0])
if __name__ == "__main__":
func = sys.argv[1]
if func == 'status':
@@ -178,5 +215,9 @@ if __name__ == "__main__":
print(initdUinstall())
elif func == 'conf':
print(getConf())
elif func == "swap_status":
print(swapStatus())
elif func == "change_swap":
print(changeSwap())
else:
print('error')
+1 -1
View File
@@ -22,7 +22,7 @@ Install_swap()
if [ "$sysName" == "Darwin" ];then
pass
else
dd if=/dev/zero of=$serverPath/swap/swapfile bs=1M count=2048
dd if=/dev/zero of=$serverPath/swap/swapfile bs=1M count=1024
chmod 600 $serverPath/swap/swapfile
mkswap $serverPath/swap/swapfile
swapon $serverPath/swap/swapfile
+81
View File
@@ -0,0 +1,81 @@
function swapPost(method, version, args,callback){
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
var req_data = {};
req_data['name'] = 'swap';
req_data['func'] = method;
req_data['version'] = version;
if (typeof(args) == 'string'){
req_data['args'] = JSON.stringify(toArrayObject(args));
} else {
req_data['args'] = JSON.stringify(args);
}
$.post('/plugins/run', req_data, function(data) {
layer.close(loadT);
if (!data.status){
//错误展示10S
layer.msg(data.msg,{icon:0,time:2000,shade: [10, '#000']});
return;
}
if(typeof(callback) == 'function'){
callback(data);
}
},'json');
}
function swapStatus() {
swapPost('swap_status', '', {}, function(data){
var rdata = $.parseJSON(data.data);
var size = rdata.data['size'];
var spCon = '<div class="conf_p" style="margin-top:30px;margin-bottom:0">\
<div style="border-bottom:#ccc 1px solid;padding-bottom:10px;margin-bottom:10px"><span><b>最大使用交换分区: </b></span>\
<select class="bt-input-text" name="swap_set" style="margin-left:-4px">\
<option value="218MB">218MB</option>\
<option value="512MB">512MB</option>\
<option value="1GB">1GB</option>\
<option value="2GB">2GB</option>\
<option value="4GB">4GB</option>\
</select>\
<span>当前: </span><input style="width:70px;background-color:#eee;" class="bt-input-text mr5" name="cur_size" type="text" value="' + size + '" readonly>MB\
</div>\
<p><span>修改</span><input style="width: 70px;" class="bt-input-text mr5" name="size" value="' + size + '" type="number" >MB</p>\
<div style="margin-top:10px; padding-right:15px" class="text-right"><button class="btn btn-success btn-sm" onclick="submitSwap()">提交</button></div>\
</div>';
$(".soft-man-con").html(spCon);
$(".conf_p select[name='swap_set']").change(function() {
var swap_size = $(this).val();
if (swap_size.indexOf('GB')>-1){
swap_size = parseInt(swap_size)*1024;
} else{
swap_size = parseInt(swap_size);
}
$("input[name='cur_size']").val(swap_size);
$("input[name='size']").val(swap_size);
});
});
}
function submitSwap(){
var size = $("input[name='size']").val();
swapPost('change_swap', '',{"size":size}, function(data){
var rdata = $.parseJSON(data.data);
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 });
});
}
function readme(){
var readme = '<ul class="help-info-text c7">';
readme += '<li>dd if=/dev/zero of=/www/server/swap/swapfile bs=1M count=2048</li>';
readme += '<li>mkswap /www/server/swap/swapfile</li>';
readme += '</ul>';
$('.soft-man-con').html(readme);
}
+5 -5
View File
@@ -54,7 +54,7 @@ function modifyAuthPath() {
type: 1,
area: "500px",
title: "修改安全入口",
closeBtn: 2,
closeBtn: 1,
shift: 5,
shadeClose: false,
content: '<div class="bt-form bt-form pd20 pb70">\
@@ -131,7 +131,7 @@ function setPassword(a) {
type: 1,
area: "290px",
title: '修改密码',
closeBtn: 2,
closeBtn: 1,
shift: 5,
shadeClose: false,
content: "<div class='bt-form pd20 pb70'>\
@@ -187,7 +187,7 @@ function setUserName(a) {
type: 1,
area: "290px",
title: '修改面板用户名',
closeBtn: 2,
closeBtn: 1,
shift: 5,
shadeClose: false,
content: "<div class='bt-form pd20 pb70'>\
@@ -238,7 +238,7 @@ function setPanelSSL(){
<input type="checkbox" id="checkSSL" /><label style="font-weight: 400;margin: 3px 5px 0px;" for="checkSSL">我已了经解详情,并愿意承担风险</label>\
<a target="_blank" class="btlink" href="https://www.bt.cn/bbs/thread-4689-1-1.html" style="float: right;">了解详情</a>\
</p>';
layer.confirm(msg,{title:'设置面板SSL',closeBtn:2,icon:3,area:'550px',cancel:function(){
layer.confirm(msg,{title:'设置面板SSL',closeBtn:1,icon:3,area:'550px',cancel:function(){
if(status == 0){
$("#panelSSL").prop("checked",false);
}
@@ -302,7 +302,7 @@ function getPanelSSL(){
type: 1,
area: "600px",
title: '自定义面板证书',
closeBtn: 2,
closeBtn: 1,
shift: 5,
shadeClose: false,
content:certBody
+1 -1
View File
@@ -180,7 +180,7 @@ function setControl(act, value=false){
//清理记录
function closeControl(){
layer.confirm('您真的清空所有监控记录吗?',{title:'清空记录',icon:3,closeBtn:2}, function() {
layer.confirm('您真的清空所有监控记录吗?',{title:'清空记录',icon:3,closeBtn:1}, function() {
loadT = layer.msg('正在处理,请稍候...',{icon:16,time:0})
$.post('/system/set_control','type=del',function(rdata){
layer.close(loadT);
+19 -5
View File
@@ -24,7 +24,7 @@ function getLogs(id){
title:lan.crontab.task_log_title,
area: ['60%','500px'],
shadeClose:false,
closeBtn:2,
closeBtn:1,
content:'<div class="setchmod bt-form pd20 pb70">'
+'<pre id="crontab-log" style="overflow: auto; border: 0px none; line-height:23px;padding: 15px; margin: 0px; white-space: pre-wrap; height: 405px; background-color: rgb(51,51,51);color:#f1f1f1;border-radius:0px;font-family:"></pre>'
+'<div class="bt-form-submit-btn" style="margin-top: 0px;">'
@@ -54,14 +54,28 @@ function getCronData(page){
'<span class="btOpen" onclick="setTaskStatus(' + rdata.data[i].id + ',0)" style="color:rgb(92, 184, 92);cursor:pointer" title="停用该计划任务">正常<span class="glyphicon glyphicon-play"></span></span>'
:'<span onclick="setTaskStatus('+ rdata.data[i].id +',1)" class="btClose" style="color:red;cursor:pointer" title="启用该计划任务">停用<span style="color:rgb(255, 0, 0);" class="glyphicon glyphicon-pause"></span></span>';
var cron_save = '--';
if (rdata.data[i]['save'] != ''){
cron_save = rdata.data[i]['save']+'份';
}
var cron_backupto = '-';
if (rdata.data[i]['stype'] == 'site' || rdata.data[i]['stype']=='database' ){
cron_backupto = '本地磁盘';
if (rdata.data[i]['backup_to'] != 'localhost'){
cron_backupto = rdata.data[i]['backup_to'];
}
}
cbody += "<tr>\
<td><input type='checkbox' onclick='checkSelect();' title='"+rdata.data[i].name+"' name='id' value='"+rdata.data[i].id+"'></td>\
<td>"+rdata.data[i].name+"</td>\
<td>"+status+"</td>\
<td>"+rdata.data[i].type+"</td>\
<td>"+rdata.data[i].cycle+"</td>\
<td>-</td>\
<td>--</td>\
<td>"+cron_save +"</td>\
<td>"+cron_backupto+"</td>\
<td>"+rdata.data[i].addtime+"</td>\
<td>\
<a href=\"javascript:startTask("+rdata.data[i].id+");\" class='btlink'>执行</a> | \
@@ -79,7 +93,7 @@ function getCronData(page){
// 设置计划任务状态
function setTaskStatus(id,status){
var confirm = layer.confirm(status == '0'?'计划任务暂停后将无法继续运行,您真的要停用这个计划任务吗?':'该计划任务已停用,是否要启用这个计划任务', {title:'提示',icon:3,closeBtn:2},function(index) {
var confirm = layer.confirm(status == '0'?'计划任务暂停后将无法继续运行,您真的要停用这个计划任务吗?':'该计划任务已停用,是否要启用这个计划任务', {title:'提示',icon:3,closeBtn:1},function(index) {
if (index > 0) {
var loadT = layer.msg('正在设置状态,请稍后...',{icon:16,time:0,shade: [0.3, '#000']});
$.post('/crontab/set_cron_status',{id:id},function(rdata){
@@ -596,7 +610,7 @@ function editTaskInfo(id){
area: ['850px','450px'],
skin:'layer-create-content',
shadeClose:false,
closeBtn:2,
closeBtn:1,
content:'<div class="setting-con ptb20">\
<div class="clearfix plan ptb10">\
<span class="typename c4 pull-left f14 text-right mr20">任务类型</span>\
+10 -10
View File
@@ -196,7 +196,7 @@ function recycleBin(type){
layer.open({
type: 1,
shift: 5,
closeBtn: 2,
closeBtn: 1,
area: ['80%','606px'],
title: lan.files.recycle_bin_title,
content: tablehtml
@@ -841,7 +841,7 @@ function createFile(type, path) {
layer.open({
type: 1,
shift: 5,
closeBtn: 2,
closeBtn: 1,
area: '320px',
title: '新建空白文件',
content: '<div class="bt-form pd20 pb70">\
@@ -881,7 +881,7 @@ function createDir(type, path) {
layer.open({
type: 1,
shift: 5,
closeBtn: 2,
closeBtn: 1,
area: '320px',
title: '新建目录',
content: '<div class="bt-form pd20 pb70">\
@@ -981,7 +981,7 @@ function downloadFile(action){
layer.open({
type: 1,
shift: 5,
closeBtn: 2,
closeBtn: 1,
area: '500px',
btn:["确定","关闭"],
title: lan.files.down_title,
@@ -1034,7 +1034,7 @@ function reName(type, fileName) {
layer.open({
type: 1,
shift: 5,
closeBtn: 2,
closeBtn: 1,
area: '320px',
title: '重命名',
btn:["确定","保存"],
@@ -1185,7 +1185,7 @@ function zip(dirName,submits) {
layer.open({
type: 1,
shift: 5,
closeBtn: 2,
closeBtn: 1,
area: '650px',
title: lan.files.zip_title,
content: '<div class="bt-form pd20 pb70">'
@@ -1241,7 +1241,7 @@ function unZip(fileName,type) {
layer.open({
type: 1,
shift: 5,
closeBtn: 2,
closeBtn: 1,
area: '490px',
title: '解压文件',
content: '<div class="bt-form pd20 pb70">'
@@ -1299,7 +1299,7 @@ function getImage(fileName){
var imgUrl = '/files/download?filename='+fileName;
layer.open({
type:1,
closeBtn: 2,
closeBtn: 1,
title:false,
area: '500px',
shadeClose: true,
@@ -1319,7 +1319,7 @@ function uploadFiles(){
var path = $("#DirPathPlace input").val()+"/";
layer.open({
type:1,
closeBtn: 2,
closeBtn: 1,
title:lan.files.up_title,
area: ['500px','300px'],
shadeClose:false,
@@ -1364,7 +1364,7 @@ function setChmod(action,fileName){
// console.log(rdata);
layer.open({
type:1,
closeBtn: 2,
closeBtn: 1,
title: '设置权限['+fileName+']',
area: '400px',
shadeClose:false,
+8 -8
View File
@@ -527,7 +527,7 @@ function checkUpdate() {
}
if (rdata.status === false) {
layer.confirm(rdata.msg, { title: lan.index.update_check, icon: 1, closeBtn: 2, btn: [lan.public.know, lan.public.close] });
layer.confirm(rdata.msg, { title: lan.index.update_check, icon: 1, closeBtn: 1, btn: [lan.public.know, lan.public.close] });
return;
}
layer.msg(rdata.msg, { icon: 1 });
@@ -610,7 +610,7 @@ function reBoot() {
type: 1,
title: '重启服务器或者面板',
area: '330px',
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<div class="rebt-con"><div class="rebt-li"><a data-id="server" href="javascript:;">重启服务器</a></div><div class="rebt-li"><a data-id="panel" href="javascript:;">重启面板</a></div></div>'
});
@@ -620,7 +620,7 @@ function reBoot() {
var type = $(this).attr('data-id');
switch (type) {
case 'panel':
layer.confirm('即将重启面板服务,继续吗?', { title: '重启面板服务', closeBtn: 2, icon: 3 }, function () {
layer.confirm('即将重启面板服务,继续吗?', { title: '重启面板服务', closeBtn: 1, icon: 3 }, function () {
var loadT = layer.load();
$.post('/system/restart','',function (rdata) {
layer.close(loadT);
@@ -634,7 +634,7 @@ function reBoot() {
type: 1,
title: '安全重启服务器',
area: ['500px', '280px'],
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: "<div class='bt-form bt-window-restart'>\
<div class='pd15'>\
@@ -692,7 +692,7 @@ function reBoot() {
//修复面板
function repPanel() {
layer.confirm(lan.index.rep_panel_msg, { title: lan.index.rep_panel_title, closeBtn: 2, icon: 3 }, function() {
layer.confirm(lan.index.rep_panel_msg, { title: lan.index.rep_panel_title, closeBtn: 1, icon: 3 }, function() {
var loadT = layer.msg(lan.index.rep_panel_the, { icon: 16, time: 0, shade: [0.3, '#000'] });
$.get('/system?action=RepPanel', function(rdata) {
layer.close(loadT);
@@ -750,7 +750,7 @@ function showDanger(num, port) {
type: 1,
area: ['720px', '410px'],
title: '安全提醒(如你想放弃任何安全提醒通知,请删除宝塔安全登录插件)',
closeBtn: 2,
closeBtn: 1,
shift: 5,
content: '<div class="pd20">\
<table class="f14 showDanger"><tbody>\
@@ -769,7 +769,7 @@ function showDanger(num, port) {
//加载关键数据总数
loadKeyDataCount();
function loadKeyDataCount(){
var plist = ['mysql', 'csvn', 'gogs'];
var plist = ['mysql', 'gogs','gitea'];
for (var i = 0; i < plist.length; i++) {
pname = plist[i];
function call(pname){
@@ -784,7 +784,7 @@ function loadKeyDataCount(){
}
var html = '<li class="sys-li-box col-xs-3 col-sm-3 col-md-3 col-lg-3">\
<p class="name f15 c9">'+pname+'</p>\
<div class="val"><a class="btlink" onclick="softMain(\''+pname+'\',\''+rdata['data']['ver']+'\')">'+rdata['data']['count']+'</a></div></li>';
<div class="val"><a class="btlink" onclick="softMain(\''+pname+'\',\''+pname+'\',\''+rdata['data']['ver']+'\')">'+rdata['data']['count']+'</a></div></li>';
$('#index_overview').append(html);
},'json');
}
+21 -9
View File
@@ -204,7 +204,7 @@ function changePath(d) {
type: 1,
area: "650px",
title: '选择目录',
closeBtn: 2,
closeBtn: 1,
shift: 5,
shadeClose: false,
content: "<div class='changepath'><div class='path-top'><button type='button' class='btn btn-default btn-sm' onclick='backFile()'><span class='glyphicon glyphicon-share-alt'></span>返回</button>\
@@ -554,7 +554,7 @@ function onlineEditFile(k, f) {
var r = layer.open({
type: 1,
shift: 5,
closeBtn: 2,
closeBtn: 1,
area: ["90%", "90%"],
title: lan.bt.edit_title+"[" + f + "]",
content: '<form class="bt-form pd20 pb70"><div class="line"><p style="color:red;margin-bottom:10px">'+lan.bt.edit_ps+' <select class="bt-input-text" name="encoding" style="width: 74px;position: absolute;top: 31px;right: 19px;height: 22px;z-index: 9999;border-radius: 0;">' + n + '</select></p><textarea class="mCustomScrollbar bt-input-text" id="textBody" style="width:100%;margin:0 auto;line-height: 1.8;position: relative;top: 10px;" value="" /> </div> <div class="bt-form-submit-btn" style="position:absolute; bottom:0; width:100%"> <button type="button" class="btn btn-danger btn-sm btn-editor-close">'+lan.public.close+'</button> <button id="OnlineEditFileBtn" type="button" class="btn btn-success btn-sm">'+lan.public.save+'</button> </div> </form>'
@@ -638,7 +638,7 @@ function safeMessage(j, h, g, f) {
type: 1,
title: j,
area: "350px",
closeBtn: 2,
closeBtn: 1,
shadeClose: true,
content: "<div class='bt-form webDelete pd20 pb70'><p>" + h + "</p>" + f + "<div class='vcode'>"+lan.bt.cal_msg+"<span class='text'>" + sumtext + "</span>=<input type='number' id='vcodeResult' value=''></div><div class='bt-form-submit-btn'><button type='button' class='btn btn-danger btn-sm bt-cancel'>"+lan.public.cancel+"</button> <button type='button' id='toSubmit' class='btn btn-success btn-sm' >"+lan.public.ok+"</button></div></div>"
});
@@ -718,7 +718,7 @@ $(function() {
});
$("#dologin").click(function() {
layer.confirm('您真的要退出面板吗?', {icon:3,closeBtn: 2}, function() {
layer.confirm('您真的要退出面板吗?', {icon:3,closeBtn: 1}, function() {
window.location.href = "/login?dologin=True"
});
return false
@@ -1030,7 +1030,7 @@ function bindPanel(a,type,ip,btid,url,user,pw){
type: 1,
area: "400px",
title: titleName,
closeBtn: 2,
closeBtn: 1,
shift: 5,
shadeClose: false,
content: "<div class='bt-form pd20 pb70'>\
@@ -1106,7 +1106,7 @@ function messageBox() {
type: 1,
title: '消息盒子',
area: "670px",
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<div class="bt-form">\
<div class="bt-w-main">\
@@ -1459,7 +1459,7 @@ function webShell() {
type: 1,
title: "本地终端",
area: ['685px','435px'],
closeBtn: 2,
closeBtn: 1,
shadeClose: false,
content: '<div class="term-box"><div id="term"></div></div>\
<div class="shell-text-input">\
@@ -1598,6 +1598,18 @@ function remove_ssh_menu() {
}
/*** 其中功能,针对插件通过库使用 start ***/
//字符串转数组对象
function toArrayObject(str){
var data = {};
kv = str.split('&');
for(i in kv){
v = kv[i].split('=');
data[v[0]] = v[1];
}
return data;
}
function pluginService(_name, version){
var data = {name:_name, func:'status'}
if ( typeof(version) != 'undefined' ){
@@ -1649,7 +1661,7 @@ function pluginOpService(a, b, v) {
case "restart":d = '重启';break;
case "reload":d = '重载';break;
}
layer.confirm( msgTpl('您真的要{1}{2}{3}服务吗?', [d,a,v]), {icon:3,closeBtn: 2}, function() {
layer.confirm( msgTpl('您真的要{1}{2}{3}服务吗?', [d,a,v]), {icon:3,closeBtn: 1}, function() {
var e = layer.msg(msgTpl('正在{1}{2}{3}服务,请稍候...',[d,a,v]), {icon: 16,time: 0});
$.post("/plugins/run", c, function(g) {
layer.close(e);
@@ -1925,7 +1937,7 @@ function pluginOpInitD(a, _version, b) {
case "initd_install":d = '加载';break;
case "initd_uninstall":d = '卸载';break;
}
layer.confirm( msgTpl('您真的要{1}{2}{3}服务吗?', [d,a,_version]), {icon:3,closeBtn: 2}, function() {
layer.confirm( msgTpl('您真的要{1}{2}{3}服务吗?', [d,a,_version]), {icon:3,closeBtn: 1}, function() {
var e = layer.msg(msgTpl('正在{1}{2}{3}服务,请稍候...',[d,a,_version]), {icon: 16,time: 0});
$.post("/plugins/run", c, function(g) {
layer.close(e);
+14 -14
View File
@@ -233,7 +233,7 @@ function webAddPage(type) {
skin: 'demo-class',
area: '640px',
title: '添加网站',
closeBtn: 2,
closeBtn: 1,
shift: 0,
shadeClose: false,
content: "<form class='bt-form pd20 pb70' id='addweb'>\
@@ -673,7 +673,7 @@ function DomainRoot(id, name,msg) {
skin: 'demo-class',
area: '450px',
title: lan.site.domain_man,
closeBtn: 2,
closeBtn: 1,
shift: 0,
shadeClose: true,
content: "<div class='divtable padding-10'>\
@@ -869,7 +869,7 @@ function getBackup(id,name,page) {
skin: 'demo-class',
area: '700px',
title: '打包备份',
closeBtn: 2,
closeBtn: 1,
shift: 0,
shadeClose: false,
content: "<div class='bt-form ptb15 mlr15' id='webBackup'>\
@@ -918,7 +918,7 @@ function setIndex(id){
type: 1,
area: '500px',
title: lan.site.setindex,
closeBtn: 2,
closeBtn: 1,
shift: 5,
shadeClose: true,
content:"<form class='bt-form' id='SetIndex'><div class='SetIndex'>"
@@ -964,7 +964,7 @@ function getDefaultSite(){
type: 1,
area: '530px',
title: '设置默认站点',
closeBtn: 2,
closeBtn: 1,
shift: 5,
shadeClose: true,
content:'<div class="bt-form ptb15 pb70">\
@@ -1021,7 +1021,7 @@ function webEdit(id,website,endTime,addtime){
type: 1,
area: '640px',
title: '站点修改['+website+'] -- 添加时间['+addtime+']',
closeBtn: 2,
closeBtn: 1,
shift: 0,
content: "<div class='bt-form'>"
+"<div class='bt-w-menu pull-left' style='height: 565px;'>"
@@ -1363,7 +1363,7 @@ function showRewrite(rdata){
type: 1,
area: '500px',
title: '配置伪静态规则',
closeBtn: 2,
closeBtn: 1,
shift: 5,
shadeClose: true,
content:webBakHtml
@@ -1430,7 +1430,7 @@ function to301(siteName, type, obj){
skin: 'demo-class',
area: '650px',
title: type == 1 ? '创建重定向' : '修改重定向[' + obj.redirectname + ']',
closeBtn: 2,
closeBtn: 1,
shift: 5,
shadeClose: false,
content: "<form id='form_redirect' class='divtable pd20' style='padding-bottom: 60px'>" +
@@ -1632,7 +1632,7 @@ function toProxy(siteName, type, obj) {
type: 1,
area: '650px',
title: "创建反向代理",
closeBtn: 2,
closeBtn: 1,
shift: 5,
shadeClose: false,
btn: ['提交','关闭'],
@@ -2381,7 +2381,7 @@ function setRewriteTel(act){
aindex = layer.open({
type: 1,
shift: 5,
closeBtn: 2,
closeBtn: 1,
area: '320px', //宽高
title: '保存为Rewrite模板',
content: '<div class="bt-form pd20 pb70">\
@@ -2408,7 +2408,7 @@ function siteDefaultPage(){
type: 1,
area: '460px',
title: '修改默认页',
closeBtn: 2,
closeBtn: 1,
shift: 0,
content: '<div class="changeDefault pd20">\
<button class="btn btn-default btn-sm mg10" style="width:188px" onclick="changeDefault(1)">默认文档</button>\
@@ -2465,7 +2465,7 @@ function setClassType(){
type: 1,
area: '350px',
title: '网站分类管理',
closeBtn: 2,
closeBtn: 1,
shift: 0,
content: '<div class="bt-form edit_site_type">\
<div class="divtable mtb15" style="overflow:auto">\
@@ -2523,7 +2523,7 @@ function editClassType(id,name){
type: 1,
area: '350px',
title: '修改分类管理【' + name + '】',
closeBtn: 2,
closeBtn: 1,
shift: 0,
content: "<form class='bt-form bt-form pd20 pb70' id='mod_pwd'>\
<div class='line'>\
@@ -2563,7 +2563,7 @@ function moveClassTYpe(){
type: 1,
area: '350px',
title: '设置站点分类',
closeBtn: 2,
closeBtn: 1,
shift: 0,
content: '<div class="bt-form edit_site_type">\
<div class="divtable mtb15" style="overflow:auto;height:80px;">\
+13 -18
View File
@@ -6,15 +6,18 @@ function resetPluginWinWidth(width){
}
//软件管理窗口
function softMain(name, version) {
function softMain(name, title, version) {
var _title = title.replace('-'+version,'')
var loadT = layer.msg("正在处理,请稍后...", { icon: 16, time: 0, shade: [0.3, '#000'] });
$.get('/plugins/setting?name='+name, function(rdata) {
layer.close(loadT);
layer.open({
type: 1,
area: '640px',
title: name + '-' + version + "管理",
closeBtn: 2,
title: _title + '【' + version + "】管理",
closeBtn: 1,
shift: 0,
content: rdata
});
@@ -104,8 +107,8 @@ function getSList(isdisplay) {
var mupdate = '';//(plugin.versions[n] == plugin.updates[n]) '' : '<a class="btlink" onclick="softUpdate(\'' + plugin.name + '\',\'' + plugin.versions[n].version + '\',\'' + plugin.updates[n] + '\')">更新</a> | ';
// if (plugin.versions[n] == '') mupdate = '';
handle = mupdate + '<a class="btlink" onclick="softMain(\'' + plugin.name + '\',\'' + plugin.setup_version + '\')">设置</a> | <a class="btlink" onclick="uninstallVersion(\'' + plugin.name + '\',\'' + plugin.setup_version + '\',' + plugin.uninstall_pre_inspection +')">卸载</a>';
titleClick = 'onclick="softMain(\'' + plugin.name + '\',\'' + plugin.setup_version + '\')" style="cursor:pointer"';
handle = mupdate + '<a class="btlink" onclick="softMain(\'' + plugin.name + '\',\'' + plugin.title + '\',\'' + plugin.setup_version + '\')">设置</a> | <a class="btlink" onclick="uninstallVersion(\'' + plugin.name + '\',\'' + plugin.setup_version + '\',' + plugin.uninstall_pre_inspection +')">卸载</a>';
titleClick = 'onclick="softMain(\'' + plugin.name + '\',\'' + plugin.title + '\',\'' + plugin.setup_version + '\')" style="cursor:pointer"';
softPath = '<span class="glyphicon glyphicon-folder-open" title="' + plugin.path + '" onclick="openPath(\'' + plugin.path + '\')"></span>';
if (plugin.coexist){
@@ -202,7 +205,7 @@ function addVersion(name, ver, type, obj, title, install_pre_inspection) {
type: 1,
title: titlename + "软件安装",
area: '350px',
closeBtn: 2,
closeBtn: 1,
shadeClose: true,
btn: ['提交','关闭'],
content: "<div class='bt-form pd20 c6'>\
@@ -259,7 +262,7 @@ function uninstallPreInspection(name, ver, callback){
function runUninstallVersion(name, version){
layer.confirm(msgTpl('您真的要卸载[{1}-{2}]吗?', [name, version]), { icon: 3, closeBtn: 2 }, function() {
layer.confirm(msgTpl('您真的要卸载[{1}-{2}]吗?', [name, version]), { icon: 3, closeBtn: 1 }, function() {
var data = 'name=' + name + '&version=' + version;
var loadT = layer.msg('正在处理,请稍候...', { icon: 16, time: 0, shade: [0.3, '#000'] });
$.post('/plugins/uninstall', data, function(rdata) {
@@ -335,19 +338,11 @@ function indexListHtml(callback){
name = plugin.title + ' ';
data_id = plugin.name + '-' + plugin.versions;
}
// con += '<div class="col-sm-3 col-md-3 col-lg-3" data-id="' + data_id + '">\
// <span class="spanmove"></span>\
// <div onclick="softMain(\'' + plugin.name + '\',\'' + plugin.setup_version + '\')">\
// <div class="image"><img src="/static/img/loading.gif" data-src="/plugins/file?name=' + plugin.name + '&f=ico.png"></div>\
// <div class="sname">' + name + state + '</div>\
// </div>\
// </div>';
con += '<div class="col-sm-3 col-md-3 col-lg-3" data-id="' + data_id + '">\
<span class="spanmove"></span>\
<div onclick="softMain(\'' + plugin.name + '\',\'' + plugin.setup_version + '\')">\
<div class="image"><img src="/plugins/file?name=' + plugin.name + '&f=ico.png" style="max-width:48px;"></div>\
<div onclick="softMain(\'' + plugin.name + '\',\'' + plugin.title + '\',\'' + plugin.setup_version + '\')">\
<div class="image"><img bk-src="/static/img/loading.gif" src="/plugins/file?name=' + plugin.name + '&f=ico.png" style="max-width:48px;"></div>\
<div class="sname">' + name + state + '</div>\
</div>\
</div>';
@@ -436,7 +431,7 @@ function importPlugin(file){
type: 1,
area: "500px",
title: "安装第三方插件包",
closeBtn: 2,
closeBtn: 1,
shift: 5,
shadeClose: false,
content: '<style>\
+23
View File
@@ -114,6 +114,7 @@ mw_stop_panel()
kill -9 $p &>/dev/null
done
pidfile=${mw_path}/logs/mw.pid
if [ -f $pidfile ];then
rm -f $pidfile
fi
@@ -178,6 +179,22 @@ error_logs()
tail -n 100 $mw_path/logs/error.log
}
mw_update()
{
curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/master/scripts/update.sh | bash
}
mw_update_dev()
{
curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/update_dev.sh | bash
}
mw_install_app()
{
bash $mw_path/scripts/quick/app.sh
}
case "$1" in
'start') mw_start;;
'stop') mw_stop;;
@@ -193,6 +210,9 @@ case "$1" in
mw_start_task;;
'status') mw_status;;
'logs') error_logs;;
'update') mw_update;;
'update_dev') mw_update_dev;;
'install_app') mw_install_app;;
'default')
cd $mw_path
port=7200
@@ -244,4 +264,7 @@ case "$1" in
echo -e "\033[33mrelease the following port (${show_panel_ip}888|80|443|22) in the security group.\033[0m"
echo -e "=================================================================="
;;
*)
cd $mw_path && python3 $mw_path/tools.py cli $1
;;
esac
+6 -3
View File
@@ -83,10 +83,13 @@ fi
echo "use system version: ${OSNAME}"
cd /www/server/mdserver-web && bash scripts/install/${OSNAME}.sh
chmod +x /www/server/mdserver-web/mw-cli
if [ ! -e /usr/bin/mw-cli ]; then
ln -s /www/server/mdserver-web/mw-cli /usr/bin/mw-cli
if [ ! -e /usr/bin/mw ]; then
if [ -f /etc/init.d/mw ];then
ln -s /etc/init.d/mw /usr/bin/mw
fi
fi
endTime=`date +%s`
((outTime=(${endTime}-${startTime})/60))
echo -e "Time consumed:\033[32m $outTime \033[0mMinute!"
+1 -1
View File
@@ -30,7 +30,7 @@ apt install -y expect
apt install -y locate
locale-gen en_US.UTF-8
localedef -v -c -i en_US -f UTF-8 en_US.UTF-8
# sudo localedef -i en_US -f UTF-8 en_US.UTF-8
sudo localedef -i en_US -f UTF-8 en_US.UTF-8
if [ ! -d /root/.acme.sh ];then
curl https://get.acme.sh | sh
+2
View File
@@ -76,6 +76,7 @@ apt install -y patchelf
VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'`
if [ "${VERSION_ID}" == "22.04" ];then
apt install -y python3-cffi
pip3 install -U --force-reinstall --no-binary :all: gevent
fi
@@ -87,6 +88,7 @@ else
fi
if [ "${VERSION_ID}" == "22.04" ];then
apt install -y python3-cffi
pip3 install -U --force-reinstall --no-binary :all: gevent
fi
+4 -7
View File
@@ -71,15 +71,12 @@ if [ $OSNAME != "macos" ];then
fi
echo "use system version: ${OSNAME}"
# cd /www/server/mdserver-web && bash ./scripts/install/debian.sh
cd /www/server/mdserver-web && bash scripts/install/${OSNAME}.sh
# curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/install/${OSNAME}.sh | bash
chmod +x /www/server/mdserver-web/mw-cli
if [ ! -e /usr/bin/mw-cli ]; then
ln -s /www/server/mdserver-web/mw-cli /usr/bin/mw-cli
if [ ! -e /usr/bin/mw ]; then
if [ -f /etc/init.d/mw ];then
ln -s /etc/init.d/mw /usr/bin/mw
fi
fi
endTime=`date +%s`
+3 -2
View File
@@ -15,8 +15,9 @@ if sys.platform != 'darwin':
chdir = os.getcwd()
sys.path.append(chdir + '/class/core')
reload(sys)
sys.setdefaultencoding('utf-8')
# importlib.reload(sys)
# sys.setdefaultencoding('utf-8')
import mw
print('==================================================================')
+6
View File
@@ -67,6 +67,12 @@ rm -rf /tmp/mdserver-web-master
echo "use system version: ${OSNAME}"
cd /www/server/mdserver-web && bash scripts/update/${OSNAME}.sh
if [ ! -e /usr/bin/mw ]; then
if [ ! -f /usr/bin/mw ];then
ln -s /etc/init.d/mw /usr/bin/mw
fi
fi
endTime=`date +%s`
((outTime=($endTime-$startTime)/60))
echo -e "Time consumed:\033[32m $outTime \033[0mMinute!"
+6 -2
View File
@@ -65,9 +65,13 @@ rm -rf /tmp/mdserver-web-dev
#pip uninstall public
echo "use system version: ${OSNAME}"
# cd /www/server/mdserver-web && bash ./scripts/install/debian.sh
cd /www/server/mdserver-web && bash scripts/update/${OSNAME}.sh
# curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/update/${OSNAME}.sh | bash
if [ ! -e /usr/bin/mw ]; then
if [ ! -f /usr/bin/mw ];then
ln -s /etc/init.d/mw /usr/bin/mw
fi
fi
endTime=`date +%s`
((outTime=($endTime-$startTime)/60))
+74 -4
View File
@@ -14,6 +14,68 @@ import db
# p = "/usr/local/lib/" + info[0].strip() + "/site-packages"
# sys.path.append(p)
INIT_DIR = "/etc/init.d"
if mw.isAppleSystem():
INIT_DIR = mw.getRunDir() + "/scripts/init.d"
INIT_CMD = INIT_DIR + "/mw"
def mwcli(mw_input=0):
raw_tip = "======================================================"
if not mw_input:
print("===============mdserver-web cli tools=================")
print("(1) 重启面板服务")
print("(2) 停止面板服务")
print("(3) 启动面板服务")
print("(4) 重载面板服务")
print("(10) 查看面板默认信息")
print("(11) 修改面板密码")
print("(12) 修改面板用户名")
print("(13) 显示面板错误日志")
print("(0) 取消")
print(raw_tip)
try:
mw_input = input("请输入命令编号:")
if sys.version_info[0] == 3:
mw_input = int(mw_input)
except:
mw_input = 0
nums = [1, 2, 3, 4, 10, 11, 12, 13]
if not mw_input in nums:
print(raw_tip)
print("已取消!")
exit()
if mw_input == 1:
os.system(INIT_CMD + " restart")
elif mw_input == 2:
os.system(INIT_CMD + " stop")
elif mw_input == 3:
os.system(INIT_CMD + " start")
elif mw_input == 4:
os.system(INIT_CMD + " reload")
elif mw_input == 10:
os.system(INIT_CMD + " default")
elif mw_input == 11:
if sys.version_info[0] == 2:
input_pwd = raw_input("请输入新的面板密码:")
else:
input_pwd = input("请输入新的面板密码:")
if len(input_pwd.strip()) < 5:
print("|-错误,密码长度不能小于5位")
return
set_panel_pwd(input_pwd.strip(), True)
elif mw_input == 12:
if sys.version_info[0] == 2:
input_user = raw_input("请输入新的面板用户名(>3位):")
else:
input_user = input("请输入新的面板用户名(>3位):")
set_panel_username(input_user.strip())
elif mw_input == 13:
os.system('tail -100 ' + mw.getRunDir() + '/logs/error.log')
def set_panel_pwd(password, ncli=False):
# 设置面板密码
@@ -60,15 +122,23 @@ def getServerIp():
if __name__ == "__main__":
type = sys.argv[1]
if type == 'panel':
method = sys.argv[1]
if method == 'panel':
set_panel_pwd(sys.argv[2])
elif type == 'username':
elif method == 'username':
if len(sys.argv) > 2:
set_panel_username(sys.argv[2])
else:
set_panel_username()
elif type == 'getServerIp':
elif method == 'getServerIp':
getServerIp()
elif method == "cli":
clinum = 0
try:
if len(sys.argv) > 2:
clinum = int(sys.argv[2]) if sys.argv[2][:6] else sys.argv[2]
except:
clinum = sys.argv[2]
mwcli(clinum)
else:
print('ERROR: Parameter error')