Esempio n. 1
0
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
Esempio n. 2
0
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
Esempio n. 3
0
    def removeTaskApi(self):
        mid = request.form.get('id', '').encode('utf-8')
        try:
            name = mw.M('tasks').where('id=?', (mid, )).getField('name')
            status = mw.M('tasks').where('id=?', (mid, )).getField('status')
            mw.M('tasks').delete(mid)
            if status == '-1':
                os.system(
                    "kill `ps -ef |grep 'python panelSafe.pyc'|grep -v grep|grep -v panelExec|awk '{print $2}'`"
                )
                os.system(
                    "kill `ps aux | grep 'python task.pyc$'|awk '{print $2}'`")
                os.system('''
pids=`ps aux | grep 'sh'|grep -v grep|grep install|awk '{print $2}'`
arr=($pids)

for p in ${arr[@]}
do
    kill -9 $p
done
            ''')

                os.system('rm -f ' +
                          name.replace('扫描目录[', '').replace(']', '') +
                          '/scan.pl')
                isTask = mw.getRootDir() + '/tmp/panelTask.pl'
                mw.writeFile(isTask, 'True')
                os.system('/etc/init.d/mw start')
        except:
            os.system('/etc/init.d/mw start')
        return mw.returnJson(True, '任务已删除!')
Esempio n. 4
0
def projectScriptLoad():

    args = getArgs()
    if not 'pname' in args:
        return 'project name missing'

    post_commit_tpl = getPluginDir() + '/hook/post-commit.tpl'
    hook_path = getServerDir() + '/data/repositories/' + \
        args['pname'] + '/hooks'
    post_commit_file = hook_path + '/post-commit'

    pct_content = mw.readFile(post_commit_tpl)
    mw.writeFile(post_commit_file, pct_content)
    mw.execShell('chmod 777 ' + post_commit_file)

    commit_tpl = getPluginDir() + '/hook/commit.tpl'
    commit_file = hook_path + '/commit'

    ct_content = mw.readFile(commit_tpl)
    ct_content = ct_content.replace('{$PROJECT_DIR}', mw.getRootDir())
    ct_content = ct_content.replace('{$PORT}', getHttpPort())
    ct_content = ct_content.replace('{$CSVN_USER}', getCsvnUser())
    ct_content = ct_content.replace('{$CSVN_PWD}', getCsvnPwd(getCsvnUser()))

    mw.writeFile(commit_file, ct_content)
    mw.execShell('chmod 777 ' + commit_file)

    return 'ok'
Esempio n. 5
0
def contentReplace(content):
    service_path = mw.getServerDir()
    waf_path = mw.getServerDir() + "/openresty/nginx/conf/waf"
    content = content.replace('{$ROOT_PATH}', mw.getRootDir())
    content = content.replace('{$SERVER_PATH}', service_path)
    content = content.replace('{$WAF_PATH}', waf_path)
    return content
Esempio n. 6
0
def contentReplacePHP(content, version):
    service_path = mw.getServerDir()
    # print php_ver
    content = content.replace('{$ROOT_PATH}', mw.getRootDir())
    content = content.replace('{$SERVER_PATH}', service_path)
    content = content.replace('{$PHP_VER}', version)
    return content
Esempio n. 7
0
    def updateServer(self, stype, version=''):
        # 更新服务
        try:
            if not mw.isRestart():
                return mw.returnJson(False, '请等待所有安装任务完成再执行!')

            if stype == 'check':
                version_now = config_api.config_api().getVersion()
                version_new_info = self.getServerInfo()
                if not 'version' in version_new_info:
                    return mw.returnJson(False, '服务器数据或网络有问题!')

                diff = self.versionDiff(version_now,
                                        version_new_info['version'])
                if diff == 'new':
                    return mw.returnJson(True, '有新版本!',
                                         version_new_info['version'])
                elif diff == 'test':
                    return mw.returnJson(True, '有测试版本!',
                                         version_new_info['version'])
                else:
                    return mw.returnJson(False, '已经是最新,无需更新!')

            if stype == 'info':
                version_new_info = self.getServerInfo()
                version_now = config_api.config_api().getVersion()

                if not 'version' in version_new_info:
                    return mw.returnJson(False, '服务器数据有问题!')
                diff = self.versionDiff(version_now,
                                        version_new_info['version'])
                return mw.returnJson(True, '更新信息!', version_new_info)

            if stype == 'update':
                if version == '':
                    return mw.returnJson(False, '缺少版本信息!')

                v_new_info = self.getServerInfo()
                if v_new_info['version'] != version:
                    return mw.returnJson(False, '更新失败,请重试!')

                if not 'path' in v_new_info or v_new_info['path'] == '':
                    return mw.returnJson(False, '下载地址不存在!')

                newUrl = v_new_info['path']
                toPath = mw.getRootDir() + '/temp'
                if not os.path.exists(toPath):
                    mw.execShell('mkdir -p ' + toPath)

                mw.execShell('wget -O ' + toPath + '/mw.zip ' + newUrl)

                mw.execShell('unzip -o ' + toPath + '/mw.zip' + ' -d ./')
                mw.execShell('unzip -o mw.zip -d ./')
                mw.execShell('rm -f mw.zip')
                return mw.returnJson(True, '安装更新成功,需自己重启!')

            return mw.returnJson(False, '已经是最新,无需更新!')
        except Exception as ex:
            print 'updateServer', ex
            return mw.returnJson(False, "连接服务器失败!")
Esempio n. 8
0
def contentReplace(content):
    service_path = mw.getServerDir()
    php_ver = getCachePhpVer()
    # print php_ver
    content = content.replace('{$ROOT_PATH}', mw.getRootDir())
    content = content.replace('{$SERVER_PATH}', service_path)
    content = content.replace('{$PHP_VER}', php_ver)
    return content
Esempio n. 9
0
    def backupSite(self, name, count):
        sql = db.Sql()
        path = sql.table('sites').where('name=?', (name, )).getField('path')
        startTime = time.time()
        if not path:
            endDate = time.strftime('%Y/%m/%d %X', time.localtime())
            log = u"网站[" + name + "]不存在!"
            print(u"★[" + endDate + "] " + log)
            print(
                "----------------------------------------------------------------------------"
            )
            return

        backup_path = mw.getRootDir() + '/backup/site'
        if not os.path.exists(backup_path):
            mw.execShell("mkdir -p " + backup_path)

        filename = backup_path + "/web_" + name + "_" + \
            time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.tar.gz'
        mw.execShell("cd " + os.path.dirname(path) + " && tar zcvf '" +
                     filename + "' '" + os.path.basename(path) +
                     "' > /dev/null")

        endDate = time.strftime('%Y/%m/%d %X', time.localtime())

        print filename
        if not os.path.exists(filename):
            log = u"网站[" + name + u"]备份失败!"
            print(u"★[" + endDate + "] " + log)
            print(
                u"----------------------------------------------------------------------------"
            )
            return

        outTime = time.time() - startTime
        pid = sql.table('sites').where('name=?', (name, )).getField('id')
        sql.table('backup').add('type,name,pid,filename,addtime,size',
                                ('0', os.path.basename(filename), pid,
                                 filename, endDate, os.path.getsize(filename)))
        log = u"网站[" + name + u"]备份成功,用时[" + str(round(outTime, 2)) + u"]秒"
        mw.writeLog(u'计划任务', log)
        print(u"★[" + endDate + "] " + log)
        print(u"|---保留最新的[" + count + u"]份备份")
        print(u"|---文件名:" + filename)

        # 清理多余备份
        backups = sql.table('backup').where(
            'type=? and pid=?', ('0', pid)).field('id,filename').select()

        num = len(backups) - int(count)
        if num > 0:
            for backup in backups:
                mw.execShell("rm -f " + backup['filename'])
                sql.table('backup').where('id=?', (backup['id'], )).delete()
                num -= 1
                print(u"|---已清理过期备份文件:" + backup['filename'])
                if num < 1:
                    break
Esempio n. 10
0
def contentReplace(content):

    service_path = mw.getServerDir()
    content = content.replace('{$ROOT_PATH}', mw.getRootDir())
    content = content.replace('{$SERVER_PATH}', service_path)
    content = content.replace('{$RUN_USER}', getRunUser())
    content = content.replace('{$HOME_DIR}', getHomeDir())

    return content
Esempio n. 11
0
    def updateZipApi(self):
        tmp_path = mw.getRootDir() + '/temp'
        if not os.path.exists(tmp_path):
            os.makedirs(tmp_path)
        mw.execShell("rm -rf " + tmp_path + '/*')

        tmp_file = tmp_path + '/plugin_tmp.zip'
        from werkzeug.utils import secure_filename
        from flask import request
        f = request.files['plugin_zip']
        if f.filename[-4:] != '.zip':
            return mw.returnJson(False, '仅支持zip文件!')
        f.save(tmp_file)
        mw.execShell('cd ' + tmp_path + ' && unzip ' + tmp_file)
        os.remove(tmp_file)

        p_info = tmp_path + '/info.json'
        if not os.path.exists(p_info):
            d_path = None
            for df in os.walk(tmp_path):
                if len(df[2]) < 3:
                    continue
                if not 'info.json' in df[2]:
                    continue
                if not 'install.sh' in df[2]:
                    continue
                if not os.path.exists(df[0] + '/info.json'):
                    continue
                d_path = df[0]
            if d_path:
                tmp_path = d_path
                p_info = tmp_path + '/info.json'
        try:
            data = json.loads(mw.readFile(p_info))
            data['size'] = mw.getPathSize(tmp_path)
            if not 'author' in data:
                data['author'] = '未知'
            if not 'home' in data:
                data['home'] = 'https://www.bt.cn/bbs/forum-40-1.html'
            plugin_path = mw.getPluginDir() + data['name'] + '/info.json'
            data['old_version'] = '0'
            data['tmp_path'] = tmp_path
            if os.path.exists(plugin_path):
                try:
                    old_info = json.loads(mw.ReadFile(plugin_path))
                    data['old_version'] = old_info['versions']
                except:
                    pass
        except:
            mw.execShell("rm -rf " + tmp_path)
            return mw.returnJson(False, '在压缩包中没有找到插件信息,请检查插件包!')
        protectPlist = ('openresty', 'mysql', 'php', 'csvn', 'gogs', 'pureftp')
        if data['name'] in protectPlist:
            return mw.returnJson(False, '[' + data['name'] + '],重要插件不可修改!')
        return mw.getJson(data)
Esempio n. 12
0
    def checkDir(self, path):
        path = path.replace('//', '/')
        if path[-1:] == '/':
            path = path[:-1]

        nDirs = ('', '/', '/*', '/www', '/root', '/boot', '/bin', '/etc',
                 '/home', '/dev', '/sbin', '/var', '/usr', '/tmp', '/sys',
                 '/proc', '/media', '/mnt', '/opt', '/lib', '/srv', '/selinux',
                 '/www/server', '/www/server/data', mw.getRootDir())

        return not path in nDirs
Esempio n. 13
0
    def getDirApi(self):
        path = request.form.get('path', '').encode('utf-8')
        if not os.path.exists(path):
            path = mw.getRootDir() + "/wwwroot"
        search = request.args.get('search', '').strip().lower()
        page = request.args.get('p', '1').strip().lower()
        row = request.args.get('showRow', '10')
        disk = request.form.get('disk', '')
        if disk == 'True':
            row = 1000

        return self.getDir(path, int(page), int(row), search)
Esempio n. 14
0
    def downloadFileApi(self):
        import db
        import time
        url = request.form.get('url', '').encode('utf-8')
        path = request.form.get('path', '').encode('utf-8')
        filename = request.form.get('filename', '').encode('utf-8')

        isTask = mw.getRootDir() + '/tmp/panelTask.pl'
        execstr = url + '|mw|' + path + '/' + filename
        mw.M('tasks').add('name,type,status,addtime,execstr',
                          ('下载文件[' + filename + ']', 'download', '0',
                           time.strftime('%Y-%m-%d %H:%M:%S'), execstr))
        mw.writeFile(isTask, 'True')
        # self.setFileAccept(path + '/' + filename)
        return mw.returnJson(True, '已将下载任务添加到队列!')
Esempio n. 15
0
def projectScriptLoad():
    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')

    user = args['user']
    name = args['name'] + '.git'

    path = getRootPath() + '/' + user + '/' + name
    post_receive_tpl = getPluginDir() + '/hook/post-receive.tpl'
    post_receive = path + '/custom_hooks/post-receive'

    if not os.path.exists(path + '/custom_hooks'):
        mw.execShell('mkdir -p ' + path + '/custom_hooks')

    pct_content = mw.readFile(post_receive_tpl)
    pct_content = pct_content.replace('{$PATH}', path + '/custom_hooks')
    mw.writeFile(post_receive, pct_content)
    mw.execShell('chmod 777 ' + post_receive)

    commit_tpl = getPluginDir() + '/hook/commit.tpl'
    commit = path + '/custom_hooks/commit'

    codeDir = mw.getRootDir() + '/git'

    cc_content = mw.readFile(commit_tpl)

    sshUrl = 'ssh://127.0.0.1:' + getSshPort()
    cc_content = cc_content.replace('{$GITROOTURL}', sshUrl)
    cc_content = cc_content.replace('{$CODE_DIR}', codeDir)
    cc_content = cc_content.replace('{$USERNAME}', user)
    cc_content = cc_content.replace('{$PROJECT}', args['name'])
    cc_content = cc_content.replace('{$WEB_ROOT}', mw.getWwwDir())
    mw.writeFile(commit, cc_content)
    mw.execShell('chmod 777 ' + commit)

    return 'ok'
Esempio n. 16
0
def contentReplace(content):
    service_path = mw.getServerDir()
    content = content.replace('{$SERVER_PATH}', service_path)
    content = content.replace('{$WWW_PATH}', mw.getRootDir() + "/wwwroot")
    return content
Esempio n. 17
0
    def getPluginInfo(self, info):
        checks = ''
        path = ''
        coexist = False

        if info["checks"][0:1] == '/':
            checks = info["checks"]
        else:
            checks = mw.getRootDir() + '/' + info['checks']

        if 'path' in info:
            path = info['path']

        if path[0:1] != '/':
            path = mw.getRootDir() + '/' + path

        if 'coexist' in info and info['coexist']:
            coexist = True

        pInfo = {
            "id": 10000,
            "pid": info['pid'],
            "type": 1000,
            "name": info['name'],
            "title": info['title'],
            "ps": info['ps'],
            "dependnet": "",
            "mutex": "",
            "path": path,
            "install_checks": checks,
            "uninsatll_checks": checks,
            "coexist": coexist,
            "versions": info['versions'],
            # "updates": info['updates'],
            "display": False,
            "setup": False,
            "setup_version": "",
            "status": False,
        }

        if checks.find('VERSION') > -1:
            pInfo['install_checks'] = checks.replace('VERSION',
                                                     info['versions'])

        if path.find('VERSION') > -1:
            pInfo['path'] = path.replace('VERSION', info['versions'])

        pInfo['task'] = self.checkSetupTask(pInfo['name'], info['versions'],
                                            coexist)
        pInfo['display'] = self.checkDisplayIndex(info['name'],
                                                  pInfo['versions'])

        pInfo['setup'] = os.path.exists(pInfo['install_checks'])

        if coexist and pInfo['setup']:
            pInfo['setup_version'] = info['versions']
        else:
            pInfo['setup_version'] = self.getVersion(pInfo['install_checks'])
        # pluginInfo['status'] = self.checkStatus(pluginInfo)
        pInfo['status'] = False
        return pInfo
Esempio n. 18
0
def contentReplace(content):
    service_path = mw.getServerDir()
    content = content.replace('{$ROOT_PATH}', mw.getRootDir())
    content = content.replace('{$SERVER_PATH}', service_path)
    content = content.replace('{$SERVER_APP_PATH}', service_path + '/mysql')
    return content
Esempio n. 19
0
    def backupDatabase(self, name, count):
        db_path = mw.getServerDir() + '/mysql'
        db_name = 'mysql'
        name = mw.M('databases').dbPos(db_path, 'mysql').where(
            'name=?', (name, )).getField('name')
        startTime = time.time()
        if not name:
            endDate = time.strftime('%Y/%m/%d %X', time.localtime())
            log = u"数据库[" + name + u"]不存在!"
            print(u"★[" + endDate + "] " + log)
            print(
                u"----------------------------------------------------------------------------"
            )
            return

        backup_path = mw.getRootDir() + '/backup/database'
        if not os.path.exists(backup_path):
            mw.execShell("mkdir -p " + backup_path)

        filename = backup_path + "/db_" + name + "_" + \
            time.strftime('%Y%m%d_%H%M%S', time.localtime()) + ".sql.gz"

        import re
        mysql_root = mw.M('config').dbPos(db_path, db_name).where(
            "id=?", (1, )).getField('mysql_root')

        mycnf = mw.readFile(db_path + '/etc/my.cnf')
        rep = "\[mysqldump\]\nuser=root"
        sea = "[mysqldump]\n"
        subStr = sea + "user=root\npassword="******"\n"
        mycnf = mycnf.replace(sea, subStr)
        if len(mycnf) > 100:
            mw.writeFile(db_path + '/etc/my.cnf', mycnf)

        mw.execShell(db_path +
                     "/bin/mysqldump --opt --default-character-set=utf8 " +
                     name + " | gzip > " + filename)

        if not os.path.exists(filename):
            endDate = time.strftime('%Y/%m/%d %X', time.localtime())
            log = u"数据库[" + name + u"]备份失败!"
            print(u"★[" + endDate + "] " + log)
            print(
                u"----------------------------------------------------------------------------"
            )
            return

        mycnf = mw.readFile(db_path + '/etc/my.cnf')
        mycnf = mycnf.replace(subStr, sea)
        if len(mycnf) > 100:
            mw.writeFile(db_path + '/etc/my.cnf', mycnf)

        endDate = time.strftime('%Y/%m/%d %X', time.localtime())
        outTime = time.time() - startTime
        pid = mw.M('databases').dbPos(db_path,
                                      db_name).where('name=?',
                                                     (name, )).getField('id')

        mw.M('backup').add('type,name,pid,filename,addtime,size',
                           (1, os.path.basename(filename), pid, filename,
                            endDate, os.path.getsize(filename)))
        log = u"数据库[" + name + u"]备份成功,用时[" + str(round(outTime, 2)) + u"]秒"
        mw.writeLog(u'计划任务', log)
        print("★[" + endDate + "] " + log)
        print(u"|---保留最新的[" + count + u"]份备份")
        print(u"|---文件名:" + filename)

        # 清理多余备份
        backups = mw.M('backup').where(
            'type=? and pid=?', ('1', pid)).field('id,filename').select()

        num = len(backups) - int(count)
        if num > 0:
            for backup in backups:
                mw.execShell("rm -f " + backup['filename'])
                mw.M('backup').where('id=?', (backup['id'], )).delete()
                num -= 1
                print(u"|---已清理过期备份文件:" + backup['filename'])
                if num < 1:
                    break
Esempio n. 20
0
 def __init__(self):
     self.rPath = mw.getRootDir() + '/recycle_bin/'