pull/632/head
Mr Chen 6 months ago
parent d4cfd90ccd
commit b1dd7ea609
  1. 7
      data/sql/default.sql
  2. 26
      web/admin/__init__.py
  3. 82
      web/admin/crontab/__init__.py
  4. 26
      web/admin/firewall/__init__.py
  5. 3
      web/config.py
  6. 7
      web/core/mw.py
  7. 1
      web/static/app/crontab.js
  8. 52
      web/static/app/public.js
  9. 1
      web/thisdb/__init__.py
  10. 11
      web/thisdb/crontab.py
  11. 55
      web/thisdb/firewall.py
  12. 214
      web/utils/crontab.py
  13. 13
      web/utils/firewall.py

@ -43,14 +43,15 @@ CREATE TABLE IF NOT EXISTS `firewall` (
`port` TEXT, `port` TEXT,
`protocol` TEXT DEFAULT 'tcp', `protocol` TEXT DEFAULT 'tcp',
`ps` TEXT, `ps` TEXT,
`add_time` TEXT `add_time` TEXT,
`update_time` TEXT
); );
ALTER TABLE `firewall` ADD COLUMN `protocol` TEXT DEFAULT 'tcp'; ALTER TABLE `firewall` ADD COLUMN `protocol` TEXT DEFAULT 'tcp';
INSERT INTO `firewall` (`id`, `port`, `protocol`, `ps`, `add_time`) VALUES INSERT INTO `firewall` (`id`, `port`, `protocol`, `ps`, `add_time`) VALUES
(1, '80', 'tcp','网站默认端口', '0000-00-00 00:00:00'), (1, '80', 'tcp','网站默认端口', '0000-00-00 00:00:00','0000-00-00 00:00:00'),
(2, '443', 'tcp/udp', 'HTTPS', '0000-00-00 00:00:00'); (2, '443', 'tcp/udp', 'HTTPS', '0000-00-00 00:00:00','0000-00-00 00:00:00');

@ -100,13 +100,12 @@ setup.init_db_system()
app.config['BASIC_AUTH_OPEN'] = False app.config['BASIC_AUTH_OPEN'] = False
with app.app_context(): try:
try: basic_auth = model.getOptionByJson('basic_auth', default={'open':False})
basic_auth = model.getOptionByJson('basic_auth', default={'open':False}) if basic_auth['open']:
if basic_auth['open']: app.config['BASIC_AUTH_OPEN'] = True
app.config['BASIC_AUTH_OPEN'] = True except Exception as e:
except Exception as e: pass
pass
@ -127,6 +126,7 @@ def sendAuthenticated():
@app.before_request @app.before_request
def requestCheck(): def requestCheck():
config.APP_START_TIME=time.time()
# 自定义basic auth认证 # 自定义basic auth认证
if app.config['BASIC_AUTH_OPEN']: if app.config['BASIC_AUTH_OPEN']:
basic_auth = model.getOptionByJson('basic_auth', default={'open':False}) basic_auth = model.getOptionByJson('basic_auth', default={'open':False})
@ -152,6 +152,8 @@ def requestCheck():
def requestAfter(response): def requestAfter(response):
response.headers['soft'] = config.APP_NAME response.headers['soft'] = config.APP_NAME
response.headers['mw-version'] = config.APP_VERSION response.headers['mw-version'] = config.APP_VERSION
if mw.isDebugMode():
response.headers['mw-debug-cos'] = time.time() - config.APP_START_TIME
return response return response
@ -163,20 +165,16 @@ def page_unauthorized(error):
# 设置模板全局变量 # 设置模板全局变量
@app.context_processor @app.context_processor
def inject_global_variables(): def inject_global_variables():
start_t = time.time() app_ver = config.APP_VERSION
ver = config.APP_VERSION;
if mw.isDebugMode(): if mw.isDebugMode():
ver = ver + str(time.time()) app_ver = app_ver + str(time.time())
data = utils_config.getGlobalVar() data = utils_config.getGlobalVar()
g_config = { g_config = {
'version': ver, 'version': app_ver,
'title' : 'MW面板', 'title' : 'MW面板',
'ip' : '127.0.0.1' 'ip' : '127.0.0.1'
} }
end_t = time.time()
print("cos:"+str(end_t-start_t))
return dict(config=g_config, data=data) return dict(config=g_config, data=data)

@ -23,40 +23,82 @@ blueprint = Blueprint('crontab', __name__, url_prefix='/crontab', template_folde
def index(): def index():
return render_template('crontab.html') return render_template('crontab.html')
# 插件列表 # 计划任务列表
@blueprint.route('/list', endpoint='list', methods=['GET','POST']) @blueprint.route('/list', endpoint='list', methods=['POST'])
@panel_login_required @panel_login_required
def list(): def list():
page = request.args.get('p', '1').strip() page = request.args.get('p', '1').strip()
limit = request.args.get('limit', '10').strip() limit = request.args.get('limit', '10').strip()
return MwCrontab.instance().getCrontabList(page=int(page),size=int(limit)) return MwCrontab.instance().getCrontabList(page=int(page),size=int(limit))
# 插件列表 # 计划任务日志
@blueprint.route('/logs', endpoint='logs', methods=['GET','POST']) @blueprint.route('/logs', endpoint='logs', methods=['POST'])
def logs(self): def logs():
sid = request.form.get('id', '') cron_id = request.form.get('id', '')
echo = mw.M('crontab').where("id=?", (sid,)).field('echo').find() return MwCrontab.instance().cronLog(cron_id)
logFile = mw.getServerDir() + '/cron/' + echo['echo'] + '.log'
if not os.path.exists(logFile):
return mw.returnData(False, '当前日志为空!')
log = mw.getLastLine(logFile, 500)
return mw.returnData(True, log)
# 获取计划任务 # 删除计划任务
@blueprint.route('/del', endpoint='del', methods=['GET','POST']) @blueprint.route('/del', endpoint='del', methods=['POST'])
def crontab_del(): def crontab_del():
task_id = request.form.get('id', '') cron_id = request.form.get('id', '')
return MwCrontab.instance().delete(task_id) return MwCrontab.instance().delete(cron_id)
# 删除计划任务日志
@blueprint.route('/del_logs', endpoint='del_logs', methods=['POST'])
def del_logs():
cron_id = request.form.get('id', '')
return MwCrontab.instance().delLogs(cron_id)
# 设置计划任务状态
@blueprint.route('/set_cron_status', endpoint='set_cron_status', methods=['POST'])
def set_cron_status():
cron_id = request.form.get('id', '')
return MwCrontab.instance().setCronStatus(cron_id)
# 设置计划任务状态
@blueprint.route('/get_data_list', endpoint='get_data_list', methods=['POST'])
def get_data_list():
stype = request.form.get('type', '')
return MwCrontab.instance().getDataList(stype)
# 获取计划任务 # 获取计划任务
@blueprint.route('/get_crond_find', endpoint='get_crond_find', methods=['GET','POST']) @blueprint.route('/get_crond_find', endpoint='get_crond_find', methods=['POST'])
def get_crond_find(): def get_crond_find():
sid = request.form.get('id', '') cron_id = request.form.get('id', '')
data = MwCrontab.instance().getCrondFind(sid) data = MwCrontab.instance().getCrondFind(cron_id)
return data return data
# 修改计划任务
@blueprint.route('/modify_crond', endpoint='modify_crond', methods=['POST'])
def modify_crond():
request_data = {}
request_data['name'] = request.form.get('name', '')
request_data['type'] = request.form.get('type', '')
request_data['week'] = request.form.get('week', '')
request_data['where1'] = request.form.get('where1', '')
request_data['hour'] = request.form.get('hour', '')
request_data['minute'] = request.form.get('minute', '')
request_data['save'] = request.form.get('save', '')
request_data['backup_to'] = request.form.get('backupTo', '')
request_data['stype'] = request.form.get('stype', '')
request_data['sname'] = request.form.get('sname', '')
request_data['sbody'] = request.form.get('sbody', '')
request_data['url_address'] = request.form.get('urladdress', '')
cron_id = request.form.get('id', '')
data = MwCrontab.instance().modifyCrond(cron_id,request_data)
return data
# 执行计划任务
@blueprint.route('/start_task', endpoint='start_task', methods=['POST'])
def start_task():
cron_id = request.form.get('id', '')
return MwCrontab.instance().startTask(cron_id)
# 添加计划任务 # 添加计划任务
@blueprint.route('/add', endpoint='add', methods=['GET','POST']) @blueprint.route('/add', endpoint='add', methods=['POST'])
@panel_login_required @panel_login_required
def add(): def add():
request_data = {} request_data = {}

@ -33,25 +33,7 @@ def index():
def get_list(): def get_list():
p = request.form.get('p', '1').strip() p = request.form.get('p', '1').strip()
limit = request.form.get('limit', '10').strip() limit = request.form.get('limit', '10').strip()
return MwFirewall.instance().getList(p,limit)
count = Firewall.query.filter_by().count()
pagination = Firewall.query.filter_by().paginate(page=int(p), per_page=int(limit))
rows = []
for item in pagination.items:
t = {}
t['id'] = item.id
t['port'] = item.port
t['protocol'] = item.protocol
t['ps'] = item.ps
t['add_time'] = item.add_time
t['update_time'] = item.update_time
rows.append(t)
data = {}
data['data'] = rows
data['page'] = mw.getPage({'count':count,'tojs':'getLogs','p':p,'row':limit})
return data
# 获取站点日志目录 # 获取站点日志目录
@blueprint.route('/get_www_path', endpoint='get_www_path', methods=['POST']) @blueprint.route('/get_www_path', endpoint='get_www_path', methods=['POST'])
@ -64,8 +46,7 @@ def get_www_path():
@blueprint.route('/get_ssh_info', endpoint='get_ssh_info', methods=['POST']) @blueprint.route('/get_ssh_info', endpoint='get_ssh_info', methods=['POST'])
@panel_login_required @panel_login_required
def get_ssh_info(): def get_ssh_info():
mf = MwFirewall.instance() return MwFirewall.instance().getSshInfo()
return mf.getSshInfo()
# 切换ping开关 # 切换ping开关
@ -88,8 +69,7 @@ def add_accept_port():
protocol = request.form.get('protocol', '').strip() protocol = request.form.get('protocol', '').strip()
stype = request.form.get('type', '').strip() stype = request.form.get('type', '').strip()
data = mf.addAcceptPort(port, ps, stype, protocol=protocol) return mf.addAcceptPort(port, ps, stype, protocol=protocol)
return mw.getJson(data)

@ -60,3 +60,6 @@ SQLITE_PATH = os.path.join(DATA_DIR, APP_SQLITE_NAME + '.db')
DEFAULT_SERVER = '127.0.0.1' DEFAULT_SERVER = '127.0.0.1'
DEFAULT_SERVER_PORT = 7201 DEFAULT_SERVER_PORT = 7201
# APP启动时间
APP_START_TIME=0

@ -97,6 +97,13 @@ def getServerDir():
def getLogsDir(): def getLogsDir():
return getFatherDir() + '/wwwlogs' return getFatherDir() + '/wwwlogs'
def getWwwDir():
file = getPanelDir() + '/data/site.pl'
if os.path.exists(file):
return readFile(file).strip()
return getFatherDir() + '/wwwroot'
def getRecycleBinDir(): def getRecycleBinDir():
rb_dir = getFatherDir() + '/recycle_bin' rb_dir = getFatherDir() + '/recycle_bin'
if not os.path.exists(rb_dir): if not os.path.exists(rb_dir):

@ -83,7 +83,6 @@ function getBackupName(hook_data, name){
function getCronData(page){ function getCronData(page){
var load = layer.msg(lan.public.the,{icon:16,time:0,shade: [0.3, '#000']}); var load = layer.msg(lan.public.the,{icon:16,time:0,shade: [0.3, '#000']});
$.post("/crontab/list?p="+page,'', function(rdata){ $.post("/crontab/list?p="+page,'', function(rdata){
console.log(rdata);
layer.close(load); layer.close(load);
var cbody = ""; var cbody = "";
if(rdata == ""){ if(rdata == ""){

@ -259,7 +259,6 @@ function getFormatTime(tm, format) {
function changePathCallback(default_dir, callback) { function changePathCallback(default_dir, callback) {
var c = layer.open({ var c = layer.open({
type: 1, type: 1,
area: "650px", area: "650px",
@ -276,7 +275,7 @@ function changePathCallback(default_dir, callback) {
</div>\ </div>\
<div class='path-con'>\ <div class='path-con'>\
<div class='path-con-left'>\ <div class='path-con-left'>\
<dl><dt id='changecomlist' onclick='backMyComputer()'>计算机</dt></dl>\ <dl><dt id='changecomlist' onclick='backMyComputer()'>计算机</dt></dl>\
</div>\ </div>\
<div class='path-con-right'>\ <div class='path-con-right'>\
<ul class='default' id='computerDefautl'></ul>\ <ul class='default' id='computerDefautl'></ul>\
@ -387,14 +386,15 @@ function getDiskList(b) {
var a = ""; var a = "";
var c = "path=" + b + "&disk=True"; var c = "path=" + b + "&disk=True";
$.post("/files/get_dir", c, function(h) { $.post("/files/get_dir", c, function(h) {
if(h.DISK != undefined) { // console.log(h);
for(var f = 0; f < h.DISK.length; f++) { // if(h.dir != undefined) {
a += "<dd onclick=\"getDiskList('" + h.DISK[f].path + "')\"><span class='glyphicon glyphicon-hdd'></span>&nbsp;" + h.DISK[f].path + "</dd>" // for(var f = 0; f < h.dir.length; f++) {
} // a += "<dd onclick=\"getDiskList('" + h.dir[f].path + "')\"><span class='glyphicon glyphicon-hdd'></span>&nbsp;" + h.dir[f].path + "</dd>";
$("#changecomlist").html(a) // }
} // $("#changecomlist").html(a);
for(var f = 0; f < h.DIR.length; f++) { // }
var g = h.DIR[f].split(";"); for(var f = 0; f < h.dir.length; f++) {
var g = h.dir[f].split(";");
var e = g[0]; var e = g[0];
if(isChineseChar(e)) { if(isChineseChar(e)) {
@ -408,16 +408,16 @@ function getDiskList(b) {
} }
d += "<tr>\ d += "<tr>\
<td onclick=\"getDiskList('" + h.PATH + "/" + g[0] + "')\" title='" + g[0] + "'>\ <td onclick=\"getDiskList('" + h.path + "/" + g[0] + "')\" title='" + g[0] + "'>\
<span class='glyphicon glyphicon-folder-open'></span>" + e + "</td><td>" + getLocalTime(g[2]) + "</td>\ <span class='glyphicon glyphicon-folder-open'></span>" + e + "</td><td>" + getLocalTime(g[2]) + "</td>\
<td>" + g[3] + "</td>\ <td>" + g[3] + "</td>\
<td>" + g[4] + "</td>\ <td>" + g[4] + "</td>\
<td><span class='delfile-btn' onclick=\"NewDelFile('" + h.PATH + "/" + g[0] + "')\">X</span></td>\ <td><span class='delfile-btn' onclick=\"NewDelFile('" + h.path + "/" + g[0] + "')\">X</span></td>\
</tr>"; </tr>";
} }
if(h.FILES != null && h.FILES != "") { if(h.files != null && h.files != "") {
for(var f = 0; f < h.FILES.length; f++) { for(var f = 0; f < h.files.length; f++) {
var g = h.FILES[f].split(";"); var g = h.files[f].split(";");
var e = g[0]; var e = g[0];
if(isChineseChar(e)) { if(isChineseChar(e)) {
if(e.length > 10) { if(e.length > 10) {
@ -441,10 +441,10 @@ function getDiskList(b) {
$(".default").hide(); $(".default").hide();
$(".file-list").show(); $(".file-list").show();
$("#tbody").html(d); $("#tbody").html(d);
if(h.PATH.substr(h.PATH.length - 1, 1) != "/") { if(h.path.substr(h.path.length - 1, 1) != "/") {
h.PATH += "/"; h.path += "/";
} }
$("#PathPlace").find("span").html(h.PATH); $("#PathPlace").find("span").html(h.path);
activeDisk(); activeDisk();
return; return;
},'json'); },'json');
@ -530,10 +530,11 @@ function activeDisk() {
} }
function backMyComputer() { function backMyComputer() {
$(".default").show(); // $(".default").show();
$(".file-list").hide(); // $(".file-list").hide();
$("#PathPlace").find("span").html(""); // $("#PathPlace").find("span").html("");
activeDisk(); // activeDisk();
return;
} }
function backFile() { function backFile() {
@ -1601,13 +1602,6 @@ function activeDisk() {
} }
function backMyComputer() {
$(".default").show();
$(".file-list").hide();
$("#PathPlace").find("span").html("");
activeDisk();
}
//检查登陆状态 //检查登陆状态
function check_login(){ function check_login(){
$.post('/check_login',{},function(rdata){ $.post('/check_login',{},function(rdata){

@ -15,3 +15,4 @@ from .sites import *
from .tasks import * from .tasks import *
from .logs import * from .logs import *
from .crontab import * from .crontab import *
from .firewall import *

@ -20,6 +20,14 @@ def addCrontab(data):
data['update_time'] = now_time data['update_time'] = now_time
return mw.M('crontab').insert(data) return mw.M('crontab').insert(data)
def setCrontabData(cron_id, data):
mw.M('crontab').where('id=?', (cron_id,)).update(data)
return True
def setCrontabStatus(cron_id, status):
mw.M('crontab').where('id=?', (cron_id,)).update({'status':status})
return True
def getCrond(id): def getCrond(id):
return mw.M('crontab').where('id=?', (id,)).field(__field).find() return mw.M('crontab').where('id=?', (id,)).field(__field).find()
@ -40,4 +48,5 @@ def getCrontabList(
data = {} data = {}
data['count'] = count data['count'] = count
data['list'] = cron_list data['list'] = cron_list
return data return data

@ -0,0 +1,55 @@
# coding:utf-8
# ---------------------------------------------------------------------------------
# MW-Linux面板
# ---------------------------------------------------------------------------------
# copyright (c) 2018-∞(https://github.com/midoks/mdserver-web) All rights reserved.
# ---------------------------------------------------------------------------------
# Author: midoks <midoks@163.com>
# ---------------------------------------------------------------------------------
import core.mw as mw
__FIELD = 'id,port,protocol,ps,add_time,update_time'
def getFirewallList(
page:int | None = 1,
size:int | None = 10,
):
start = (int(page) - 1) * (int(size))
limit = str(start) + ',' +str(size)
firewall_list = mw.M('firewall').field(__FIELD).limit(limit).order('id desc').select()
count = mw.M('firewall').count()
data = {}
data['count'] = count
data['list'] = firewall_list
return data
def addFirewall(port,
protocol: str | None = 'tcp',
ps: str | None = '备注'
) -> bool:
'''
设置配置的值
:port -> str 端口 (必填)
:protocol -> str 协议 (可选|tcp,udp,tcp/udp)
:ps -> str 备注 (可选)
'''
now_time = mw.formatDate()
insert_data = {
'port':port,
'protocol':protocol,
'ps':ps,
'add_time':now_time,
'update_time':now_time,
}
mw.M('firewall').insert(insert_data)
return True
def getFirewallCountByPort(port):
return mw.M('firewall').where('port=?',(port,)).count()

@ -10,6 +10,7 @@
import os import os
import sys import sys
import re
import time import time
import json import json
import threading import threading
@ -20,6 +21,7 @@ from admin import model
import core.mw as mw import core.mw as mw
import thisdb import thisdb
class crontab(object): class crontab(object):
# lock # lock
_instance_lock = threading.Lock() _instance_lock = threading.Lock()
@ -32,6 +34,119 @@ class crontab(object):
crontab._instance = crontab(*args, **kwargs) crontab._instance = crontab(*args, **kwargs)
return crontab._instance return crontab._instance
def modifyCrond(self,cron_id,data):
if len(data['name']) < 1:
return mw.returnData(False, '任务名称不能为空!')
is_check_pass, msg = self.cronCheck(data)
if not is_check_pass:
return mw.returnData(is_check_pass, msg)
info = thisdb.getCrond(cron_id)
dbdata = {}
dbdata['name'] = data['name']
dbdata['type'] = data['type']
dbdata['where1'] = data['where1']
dbdata['where_hour'] = data['hour']
dbdata['where_minute'] = data['minute']
dbdata['save'] = data['save']
dbdata['backup_to'] = data['backup_to']
dbdata['sname'] = data['sname']
dbdata['sbody'] = data['sbody']
dbdata['stype'] = data['stype']
dbdata['url_address'] = data['url_address']
if not self.removeForCrond(info['echo']):
return mw.returnData(False, '无法写入文件,是否开启了系统加固功能!')
thisdb.setCrontabData(cron_id, dbdata)
self.syncToCrond(cron_id)
msg = '修改计划任务[' + data['name'] + ']成功'
mw.writeLog('计划任务', msg)
return mw.returnData(True, msg)
# 取数据列表
def getDataList(self,stype=''):
bak_data = []
if stype == 'site' or stype == 'sites' or stype == 'database' or stype.find('database_') > -1 or stype == 'path':
hookPath = mw.getPanelDataDir() + "/hook_backup.json"
if os.path.exists(hookPath):
t = mw.readFile(hookPath)
bak_data = json.loads(t)
if stype == 'database' or stype.find('database_') > -1:
sqlite3_name = 'mysql'
path = mw.getServerDir() + '/mysql'
if stype != 'database':
soft_name = stype.replace('database_', '')
path = mw.getServerDir() + '/' + soft_name
if soft_name == 'postgresql':
sqlite3_name = 'pgsql'
if soft_name == 'mongodb':
sqlite3_name = 'mongodb'
db_list = {}
db_list['orderOpt'] = bak_data
if not os.path.exists(path + '/' + sqlite3_name + '.db'):
db_list['data'] = []
else:
db_list['data'] = mw.M('databases').dbPos(path, sqlite3_name).field('name,ps').select()
return mw.getJson(db_list)
if stype == 'path':
db_list = {}
db_list['data'] = [{"name": mw.getWwwDir(), "ps": "www"}]
db_list['orderOpt'] = bak_data
return mw.getJson(db_list)
data = {}
data['orderOpt'] = bak_data
default_db = 'sites'
data['data'] = mw.M(default_db).field('name,ps').select()
return mw.getJson(data)
def setCronStatus(self,cron_id):
data = thisdb.getCrond(cron_id)
status = 1
status_msg = '开启'
if data['status'] == status:
status = 0
status_msg = '关闭'
self.removeForCrond(data['echo'])
else:
data['status'] = 1
self.syncToCrond(cron_id)
thisdb.setCrontabStatus(cron_id, status)
msg = '修改计划任务[' + data['name'] + ']状态为[' + str(status_msg) + ']'
mw.writeLog('计划任务', msg)
return mw.returnJson(True, msg)
def cronLog(self, cron_id):
data = thisdb.getCrond(cron_id)
log_file = mw.getServerDir() + '/cron/' + data['echo'] + '.log'
if not os.path.exists(log_file):
return mw.returnData(False, '当前日志为空!')
content = mw.getLastLine(log_file, 500)
return mw.returnData(True, content)
def startTask(self, cron_id):
data = thisdb.getCrond(cron_id)
cmd_file = mw.getServerDir() + '/cron/' + data['echo']
os.system('chmod +x ' + cmd_file)
os.system('nohup ' + cmd_file + ' >> ' + cmd_file + '.log 2>&1 &')
return mw.returnData(True, '计划任务【%s】已执行!' % data['name'])
# 获取指定任务数据 # 获取指定任务数据
def getCrondFind(self, cron_id): def getCrondFind(self, cron_id):
return thisdb.getCrond(cron_id) return thisdb.getCrond(cron_id)
@ -78,7 +193,7 @@ class crontab(object):
def delete(self, tid): def delete(self, tid):
data = thisdb.getCrond(tid) data = thisdb.getCrond(tid)
if not self.removeForCrond(data['echo']): if not self.removeForCrond(data['echo']):
return mw.returnData(False, '无法写入文件,请检查是否开启了系统加固功能!') return mw.returnData(False, '无法写入文件,是否开启了系统加固功能!')
cron_path = mw.getServerDir() + '/cron' cron_path = mw.getServerDir() + '/cron'
cron_file = cron_path + '/' + data['echo'] cron_file = cron_path + '/' + data['echo']
@ -94,6 +209,17 @@ class crontab(object):
mw.writeLog('计划任务', msg) mw.writeLog('计划任务', msg)
return mw.returnData(True, msg) return mw.returnData(True, msg)
def delLogs(self,cron_id):
try:
data = thisdb.getCrond(cron_id)
log_file = mw.getServerDir() + '/cron/' + data['echo'] + '.log'
if os.path.exists(log_file):
os.remove(log_file)
return mw.returnData(True, '任务日志已清空!')
except:
return mw.returnData(False, '任务日志清空失败!')
def getCrontabHuman(self, data): def getCrontabHuman(self, data):
rdata = [] rdata = []
for i in range(len(data)): for i in range(len(data)):
@ -129,18 +255,23 @@ class crontab(object):
if mw.isAppleSystem(): if mw.isAppleSystem():
return True return True
u_file = '/var/spool/cron/crontabs/root' cron_file = [
if not os.path.exists(u_file): '/var/spool/cron/crontabs/root',
file = '/var/spool/cron/root' '/var/spool/cron/root',
if not os.path.exists(file): ]
return False
else:
file = u_file
conf = mw.readFile(file) file = ''
for i in cron_file:
if os.path.exists(file):
file = i
if file == '':
return False
content = mw.readFile(file)
rep = ".+" + str(echo) + ".+\n" rep = ".+" + str(echo) + ".+\n"
conf = re.sub(rep, "", conf) content = re.sub(rep, "", content)
if not mw.writeFile(file, conf): if not mw.writeFile(file, content):
return False return False
self.crondReload() self.crondReload()
return True return True
@ -288,7 +419,6 @@ class crontab(object):
shell = param.sFile shell = param.sFile
else: else:
head = "#!/bin/bash\nPATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin\nexport PATH\n" head = "#!/bin/bash\nPATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin\nexport PATH\n"
start_head = ''' start_head = '''
SCRIPT_RUN_TIME="0s" SCRIPT_RUN_TIME="0s"
MW_ToSeconds() MW_ToSeconds()
@ -336,22 +466,16 @@ fi''' % (mw.getPanelDir(),)
'rememory': head + "/bin/bash " + script_dir + '/rememory.sh' 'rememory': head + "/bin/bash " + script_dir + '/rememory.sh'
} }
if param['backup_to'] != 'localhost': if param['backup_to'] != 'localhost':
cfile = mw.getPluginDir() + "/" + \ cfile = mw.getPluginDir() + "/" + param['backup_to'] + "/index.py"
param['backup_to'] + "/index.py"
wheres['path'] = head + "python3 " + cfile + " path " + param['sname'] + " " + str(param['save'])
wheres['path'] = head + "python3 " + cfile + \ wheres['site'] = head + "python3 " + cfile + " site " + param['sname'] + " " + str(param['save'])
" path " + param['sname'] + " " + str(param['save']) wheres['database'] = head + "python3 " + cfile + " " + source_stype + " " + param['sname'] + " " + str(param['save'])
wheres['site'] = head + "python3 " + cfile + \
" site " + param['sname'] + " " + str(param['save'])
wheres['database'] = head + "python3 " + cfile + " " + \
source_stype + " " + \
param['sname'] + " " + str(param['save'])
try: try:
shell = wheres[stype] shell = wheres[stype]
except: except:
if stype == 'toUrl': if stype == 'toUrl':
shell = head + "curl -sS --connect-timeout 10 -m 60 '" + \ shell = head + "curl -sS --connect-timeout 10 -m 60 '" + param['urladdress'] + "'"
param['urladdress'] + "'"
else: else:
shell = head + param['sbody'].replace("\r\n", "\n") shell = head + param['sbody'].replace("\r\n", "\n")
@ -381,19 +505,19 @@ echo "--------------------------------------------------------------------------
def checkScript(self, shell): def checkScript(self, shell):
keys = ['shutdown', 'init 0', 'mkfs', 'passwd', keys = ['shutdown', 'init 0', 'mkfs', 'passwd',
'chpasswd', '--stdin', 'mkfs.ext', 'mke2fs'] 'chpasswd', '--stdin', 'mkfs.ext', 'mke2fs']
for key in keys: for k in keys:
shell = shell.replace(key, '[***]') shell = shell.replace(k, '[***]')
return shell return shell
# 将Shell脚本写到文件 # 将Shell脚本写到文件
def writeShell(self, config): def writeShell(self, bash_script):
if mw.isAppleSystem():
return mw.returnData(True, 'ok')
file = '/var/spool/cron/crontabs/root' file = '/var/spool/cron/crontabs/root'
current_os = mw.getOs() sys_os = mw.getOs()
if current_os == 'darwin': if sys_os == 'darwin':
file = '/etc/crontab' file = '/etc/crontab'
elif current_os.startswith("freebsd"): elif sys_os.startswith("freebsd"):
file = '/var/cron/tabs/root' file = '/var/cron/tabs/root'
if not os.path.exists(file): if not os.path.exists(file):
@ -401,15 +525,16 @@ echo "--------------------------------------------------------------------------
if not os.path.exists(file): if not os.path.exists(file):
mw.writeFile(file, '') mw.writeFile(file, '')
conf = mw.readFile(file)
conf += str(config) + "\n" content = mw.readFile(file)
if mw.writeFile(file, conf): content += str(bash_script) + "\n"
if mw.writeFile(file, content):
if not os.path.exists(file): if not os.path.exists(file):
mw.execShell("chmod 600 '" + file +"' && chown root.root " + file) mw.execShell("chmod 600 '" + file +"' && chown root.root " + file)
else: else:
mw.execShell("chmod 600 '" + file +"' && chown root.crontab " + file) mw.execShell("chmod 600 '" + file +"' && chown root.crontab " + file)
return mw.returnData(True, 'ok') return mw.returnData(True, 'ok')
return mw.returnData(False, '文件写入失败,请检查是否开启系统加固功能!') return mw.returnData(False, '文件写入失败,是否开启系统加固功能!')
# 重载配置 # 重载配置
def crondReload(self): def crondReload(self):
@ -424,7 +549,22 @@ echo "--------------------------------------------------------------------------
else: else:
mw.execShell("systemctl reload crond") mw.execShell("systemctl reload crond")
def syncToCrond(self, cron_id):
info = thisdb.getCrond(cron_id)
if 'status' in info:
if info['status'] == 0:
return False
if 'where_hour' in info:
info['hour'] = info['where_hour']
info['minute'] = info['where_minute']
info['week'] = info['where1']
cmd, _ = self.getCrondCycle(info)
cron_path = mw.getServerDir() + '/cron'
cron_name = self.getShell(info)
cmd += ' ' + cron_path + '/' + cron_name + ' >> ' + cron_path + '/' + cron_name + '.log 2>&1'
self.writeShell(cmd)
self.crondReload()
return True

@ -14,9 +14,9 @@ import threading
import re import re
import time import time
from admin import model
import core.mw as mw import core.mw as mw
import thisdb
class Firewall(object): class Firewall(object):
@ -47,6 +47,14 @@ class Firewall(object):
elif mw.isAppleSystem(): elif mw.isAppleSystem():
self.__isMac = True self.__isMac = True
def getList(self, page=1,size=10):
info = thisdb.getFirewallList(page=page, size=size)
rdata = {}
rdata['data'] = info['list']
rdata['page'] = mw.getPage({'count':info['count'],'tojs':'showAccept','p':page,'row':size})
return rdata
def reload(self): def reload(self):
if self.__isUfw: if self.__isUfw:
mw.execShell('/usr/sbin/ufw reload') mw.execShell('/usr/sbin/ufw reload')
@ -236,8 +244,7 @@ class Firewall(object):
msg = mw.getInfo('放行端口[{1}][{2}]成功', (port, protocol,)) msg = mw.getInfo('放行端口[{1}][{2}]成功', (port, protocol,))
mw.writeLog("防火墙管理", msg) mw.writeLog("防火墙管理", msg)
return mw.returnData(True, msg)
return mw.returnData(True, '添加放行(' + port + ')端口成功!')

Loading…
Cancel
Save