Пример #1
0
def set_mysql_root(password):
    import db,os
    sql = db.Sql()
    
    root_mysql = '''#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
pwd=$1
service mysqld stop
mysqld_safe --skip-grant-tables&
echo '正在修改密码...';
echo 'The set password...';
sleep 6
m_version=$(cat /www/server/mysql/version.pl|grep -E "(5.1.|5.5.|5.6.)")
if [ "$m_version" != "" ];then
    mysql -uroot -e "insert into mysql.user(Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Reload_priv,Shutdown_priv,Process_priv,File_priv,Grant_priv,References_priv,Index_priv,Alter_priv,Show_db_priv,Super_priv,Create_tmp_table_priv,Lock_tables_priv,Execute_priv,Repl_slave_priv,Repl_client_priv,Create_view_priv,Show_view_priv,Create_routine_priv,Alter_routine_priv,Create_user_priv,Event_priv,Trigger_priv,Create_tablespace_priv,User,Password,host)values('Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','root',password('${pwd}'),'127.0.0.1')"
    mysql -uroot -e "insert into mysql.user(Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Reload_priv,Shutdown_priv,Process_priv,File_priv,Grant_priv,References_priv,Index_priv,Alter_priv,Show_db_priv,Super_priv,Create_tmp_table_priv,Lock_tables_priv,Execute_priv,Repl_slave_priv,Repl_client_priv,Create_view_priv,Show_view_priv,Create_routine_priv,Alter_routine_priv,Create_user_priv,Event_priv,Trigger_priv,Create_tablespace_priv,User,Password,host)values('Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','root',password('${pwd}'),'localhost')"
    mysql -uroot -e "UPDATE mysql.user SET password=PASSWORD('${pwd}') WHERE user='******'";
else
    mysql -uroot -e "UPDATE mysql.user SET authentication_string='' WHERE user='******'";
    mysql -uroot -e "FLUSH PRIVILEGES";
    mysql -uroot -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '${pwd}';";
fi
mysql -uroot -e "FLUSH PRIVILEGES";
pkill -9 mysqld_safe
pkill -9 mysqld
sleep 2
service mysqld start

echo '==========================================='
echo "root密码成功修改为: ${pwd}"
echo "The root password set ${pwd}  successuful"''';
    
    public.writeFile('mysql_root.sh',root_mysql)
    os.system("/bin/bash mysql_root.sh " + password)
    os.system("rm -f mysql_root.sh")
    
    result = sql.table('config').where('id=?',(1,)).setField('mysql_root',password)
    print(result);
Пример #2
0
def install_task():
    if cache.get('install_task'): return True
    if cache.get('install_exists'): return True
    sql = db.Sql()
    sql.table('tasks').where("status=?",('-1',)).setField('status','0')
    taskArr = sql.table('tasks').where("status=?",('0',)).field('id,type,execstr').order("id asc").select();
    cache.set('install_exists',True)
    cache.delete('install_task')
    logPath = '/tmp/panelExec.log'
    for value in taskArr:
        start = int(time.time());
        if not sql.table('tasks').where("id=?",(value['id'],)).count(): continue;
        sql.table('tasks').where("id=?",(value['id'],)).save('status,start',('-1',start))
        if value['type'] == 'download':
            import downloadFile
            argv = value['execstr'].split('|bt|')
            downloadFile.downloadFile().DownloadFile(argv[0],argv[1])
        elif value['type'] == 'execshell':
           os.system(value['execstr'] + " > " + logPath + " 2>&1")
        end = int(time.time())
        sql.table('tasks').where("id=?",(value['id'],)).save('status,end',('1',end))
    cache.delete('install_exists')
Пример #3
0
 def InstallSoft(self,get):
     import db,time
     path = public.GetConfigValue('setup_path') + '/php'
     if not os.path.exists(path): os.system("mkdir -p " + path);
     if session['server_os']['x'] != 'RHEL': get.type = '3'
     apacheVersion='false';
     if public.get_webserver() == 'apache':
         apacheVersion = public.readFile(public.GetConfigValue('setup_path')+'/apache/version.pl');
     public.writeFile('/var/bt_apacheVersion.pl',apacheVersion)
     public.writeFile('/var/bt_setupPath.conf',public.GetConfigValue('root_path'))
     isTask = '/tmp/panelTask.pl'
     execstr = "cd " + public.GetConfigValue('setup_path') + "/panel/install && /bin/bash install_soft.sh " + get.type + " install " + get.name + " "+ get.version;
     sql = db.Sql()
     if hasattr(get,'id'):
         id = get.id;
     else:
         id = None;
     sql.table('tasks').add('id,name,type,status,addtime,execstr',(None,'安装['+get.name+'-'+get.version+']','execshell','0',time.strftime('%Y-%m-%d %H:%M:%S'),execstr))
     public.writeFile(isTask,'True')
     public.WriteLog('TYPE_SETUP','PLUGIN_ADD',(get.name,get.version));
     time.sleep(0.1);
     return public.returnMsg(True,'PLUGIN_ADD');
Пример #4
0
 def SetControl(self,get):
     try:
         if hasattr(get,'day'): 
             get.day = int(get.day);
             get.day = str(get.day);
             if(get.day < 1): return public.returnMsg(False,"CONTROL_ERR");
     except:
         pass
     
     filename = 'data/control.conf';
     if get.type == '1':
         public.writeFile(filename,get.day);
         public.WriteLog("TYPE_PANEL",'CONTROL_OPEN',(get.day,));
     elif get.type == '0':
         public.ExecShell("rm -f " + filename);
         public.WriteLog("TYPE_PANEL", "CONTROL_CLOSE");
     elif get.type == 'del':
         if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK');
         os.remove("data/system.db")
         import db;
         sql = db.Sql()
         result = sql.dbfile('system').create('system');
         public.WriteLog("TYPE_PANEL", "CONTROL_CLOSE");
         return public.returnMsg(True,"CONTROL_CLOSE");
         
     else:
         data = {}
         if os.path.exists(filename):
             try:
                 data['day'] = int(public.readFile(filename));
             except:
                 data['day'] = 30;
             data['status'] = True
         else:
             data['day'] = 30;
             data['status'] = False
         return data
     
     return public.returnMsg(True,"SET_SUCCESS");
Пример #5
0
def startTask():
    global isTask
    import time, public
    try:
        while True:
            try:
                if os.path.exists(isTask):
                    sql = db.Sql()
                    sql.table('tasks').where("status=?",
                                             ('-1', )).setField('status', '0')
                    taskArr = sql.table('tasks').where(
                        "status=?",
                        ('0',
                         )).field('id,type,execstr').order("id asc").select()
                    for value in taskArr:
                        start = int(time.time())
                        if not sql.table('tasks').where(
                                "id=?", (value['id'], )).count():
                            continue
                        sql.table('tasks').where("id=?", (value['id'], )).save(
                            'status,start', ('-1', start))
                        if value['type'] == 'download':
                            argv = value['execstr'].split('|bt|')
                            DownloadFile(argv[0], argv[1])
                        elif value['type'] == 'execshell':
                            ExecShell(value['execstr'])
                        end = int(time.time())
                        sql.table('tasks').where("id=?", (value['id'], )).save(
                            'status,end', ('1', end))
                        if (sql.table('tasks').where("status=?",
                                                     ('0')).count() < 1):
                            public.ExecShell('rm -f ' + isTask)
            except:
                pass
            siteEdate()
            time.sleep(2)
    except:
        time.sleep(60)
        startTask()
Пример #6
0
def set_mysql_root(password):
    import db,os
    sql = db.Sql()
    
    root_mysql = '''#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
pwd=$1
/etc/init.d/mysqld stop
mysqld_safe --skip-grant-tables&
echo 'Changing password...';
sleep 6
m_version=$(cat /www/server/mysql/version.pl|grep -E "(5.1.|5.5.|5.6.|10.0|10.1)")
if [ "$m_version" != "" ];then
    mysql -uroot -e "UPDATE mysql.user SET password=PASSWORD('${pwd}') WHERE user='******'";
else
    m_version=$(cat /www/server/mysql/version.pl|grep -E "(5.7.|8.0.)")
    if [ "$m_version" != "" ];then
        mysql -uroot -e "FLUSH PRIVILEGES;update mysql.user set authentication_string='' where user='******';alter user 'root'@'localhost' identified by '${pwd}';alter user 'root'@'127.0.0.1' identified by '${pwd}';FLUSH PRIVILEGES;";
    else
        mysql -uroot -e "update mysql.user set authentication_string=password('${pwd}') where user='******';"
    fi
fi
mysql -uroot -e "FLUSH PRIVILEGES";
pkill -9 mysqld_safe
pkill -9 mysqld
sleep 2
/etc/init.d/mysqld start

echo '==========================================='
echo "The root password set ${pwd}  successuful"''';
    
    public.writeFile('mysql_root.sh',root_mysql)
    os.system("/bin/bash mysql_root.sh " + password)
    os.system("rm -f mysql_root.sh")
    
    result = sql.table('config').where('id=?',(1,)).setField('mysql_root',password)
    print(result);
Пример #7
0
def set_mysql_root(password):
    import db, os
    sql = db.Sql()

    root_mysql = '''#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
pwd=$1
/etc/init.d/mysqld stop
mysqld_safe --skip-grant-tables&
echo '正在修改密码...';
echo 'The set password...';
sleep 6
m_version=$(cat /www/server/mysql/version.pl|grep -E "(5.1.|5.5.|5.6.|mariadb|10.)")
if [ "$m_version" != "" ];then
    mysql -uroot -e "UPDATE mysql.user SET password=PASSWORD('${pwd}') WHERE user='******'";
else
    mysql -uroot -e "UPDATE mysql.user SET authentication_string='' WHERE user='******'";
    mysql -uroot -e "FLUSH PRIVILEGES";
    mysql -uroot -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '${pwd}';";
fi
mysql -uroot -e "FLUSH PRIVILEGES";
pkill -9 mysqld_safe
pkill -9 mysqld
sleep 2
/etc/init.d/mysqld start

echo '==========================================='
echo "root密码成功修改为: ${pwd}"
echo "The root password set ${pwd}  successuful"'''

    public.writeFile('mysql_root.sh', root_mysql)
    os.system("/bin/bash mysql_root.sh " + password)
    os.system("rm -f mysql_root.sh")

    result = sql.table('config').where('id=?',
                                       (1, )).setField('mysql_root', password)
    print(result)
Пример #8
0
    def setControl(self, stype, day):

        filename = 'data/control.conf'

        if stype == '0':
            mw.execShell("rm -f " + filename)
        elif stype == '1':
            _day = int(day)
            if _day < 1:
                return mw.returnJson(False, "设置失败!")
            mw.writeFile(filename, day)
        elif stype == 'del':
            if not mw.isRestart():
                return mw.returnJson(False, '请等待所有安装任务完成再执行')
            os.remove("data/system.db")

            sql = db.Sql().dbfile('system')
            csql = mw.readFile('data/sql/system.sql')
            csql_list = csql.split(';')
            for index in range(len(csql_list)):
                sql.execute(csql_list[index], ())
            return mw.returnJson(True, "监控服务已关闭")
        else:
            data = {}
            if os.path.exists(filename):
                try:
                    data['day'] = int(mw.readFile(filename))
                except:
                    data['day'] = 30
                data['status'] = True
            else:
                data['day'] = 30
                data['status'] = False
            return mw.getJson(data)

        return mw.returnJson(True, "设置成功!")
Пример #9
0
 def backupPath(self,path,count):
     sql = db.Sql();
     startTime = time.time();
     if path[-1:] == '/': path = path[:-1]
     name = os.path.basename(path)
     backup_path = sql.table('config').where("id=?",(1,)).getField('backup_path') + '/path';
     if not os.path.exists(backup_path): os.makedirs(backup_path);
     filename= backup_path + "/Path_" + name + "_" + time.strftime('%Y%m%d_%H%M%S',time.localtime()) + '.tar.gz'
     os.system("cd " + os.path.dirname(path) + " && tar zcvf '" + filename + "' '" + os.path.basename(path) + "'" + self.__exclude + " > /dev/null")
             
     endDate = time.strftime('%Y/%m/%d %X',time.localtime())
     if not os.path.exists(filename):
         log = u"目录["+path+"]备份失败"
         print(u"★["+endDate+"] "+log)
         print(u"----------------------------------------------------------------------------")
         return;
     
     outTime = time.time() - startTime
     sql.table('backup').add('type,name,pid,filename,addtime,size',('2',path,'0',filename,endDate,os.path.getsize(filename)))
     log = u"目录["+path+"]备份成功,用时["+str(round(outTime,2))+"]秒";
     public.WriteLog(u'计划任务',log)
     print(u"★["+endDate+"] " + log)
     print(u"|---保留最新的["+count+u"]份备份")
     print(u"|---文件名:"+filename)
     if self.__exclude: print(u"|---排除规则: " + self.__exclude)
     
     #清理多余备份     
     backups = sql.table('backup').where('type=? and pid=? and name=?',('2',0,path)).field('id,filename').select();
     num = len(backups) - int(count)
     if  num > 0:
         for backup in backups:
             public.ExecShell("rm -f " + backup['filename']);
             sql.table('backup').where('id=?',(backup['id'],)).delete();
             num -= 1;
             print(u"|---已清理过期备份文件:" + backup['filename'])
             if num < 1: break;
Пример #10
0
def control_init():
    time.sleep(1)
    sql = db.Sql().dbfile('system')
    if not sql.table('sqlite_master').where('type=? AND name=?',
                                            ('table', 'load_average')).count():
        csql = '''CREATE TABLE IF NOT EXISTS `load_average` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`pro` REAL,
`one` REAL,
`five` REAL,
`fifteen` REAL,
`addtime` INTEGER
)'''
        sql.execute(csql, ())
    if not public.M('sqlite_master').where(
            'type=? AND name=? AND sql LIKE ?',
        ('table', 'sites', '%type_id%')).count():
        public.M('sites').execute(
            "alter TABLE sites add edate integer DEFAULT '0000-00-00'", ())
        public.M('sites').execute(
            "alter TABLE sites add type_id integer DEFAULT 0", ())

    sql = db.Sql()
    if not sql.table('sqlite_master').where('type=? AND name=?',
                                            ('table', 'site_types')).count():
        csql = '''CREATE TABLE IF NOT EXISTS `site_types` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` REAL,
`ps` REAL
)'''

        sql.execute(csql, ())

    if not sql.table('sqlite_master').where(
            'type=? AND name=?', ('table', 'download_token')).count():
        csql = '''CREATE TABLE IF NOT EXISTS `download_token` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`token` REAL,
`filename` REAL,
`total` INTEGER DEFAULT 0,
`expire` INTEGER,
`password` REAL,
`ps` REAL,
`addtime` INTEGER
)'''
        sql.execute(csql, ())

    if not sql.table('sqlite_master').where('type=? AND name=?',
                                            ('table', 'messages')).count():
        csql = '''CREATE TABLE IF NOT EXISTS `messages` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`level` TEXT,
`msg` TEXT,
`state` INTEGER DEFAULT 0,
`expire` INTEGER,
`addtime` INTEGER
)'''
        sql.execute(csql, ())

    if not public.M('sqlite_master').where(
            'type=? AND name=? AND sql LIKE ?',
        ('table', 'logs', '%username%')).count():
        public.M('logs').execute(
            "alter TABLE logs add uid integer DEFAULT '1'", ())
        public.M('logs').execute(
            "alter TABLE logs add username TEXT DEFAULT 'system'", ())

    if not public.M('sqlite_master').where(
            'type=? AND name=? AND sql LIKE ?',
        ('table', 'crontab', '%status%')).count():
        public.M('crontab').execute(
            "ALTER TABLE 'crontab' ADD 'status' INTEGER DEFAULT 1", ())
        public.M('crontab').execute(
            "ALTER TABLE 'crontab' ADD 'save' INTEGER DEFAULT 3", ())
        public.M('crontab').execute(
            "ALTER TABLE 'crontab' ADD 'backupTo' TEXT DEFAULT off", ())
        public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'sName' TEXT",
                                    ())
        public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'sBody' TEXT",
                                    ())
        public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'sType' TEXT",
                                    ())
        public.M('crontab').execute(
            "ALTER TABLE 'crontab' ADD 'urladdress' TEXT", ())

    public.M('users').where(
        'email=? or email=?',
        ('*****@*****.**', '*****@*****.**')).setField(
            'email', '*****@*****.**')

    filename = '/www/server/nginx/off'
    if os.path.exists(filename): os.remove(filename)
    c = public.to_string([
        99, 104, 97, 116, 116, 114, 32, 45, 105, 32, 47, 119, 119, 119, 47,
        115, 101, 114, 118, 101, 114, 47, 112, 97, 110, 101, 108, 47, 99, 108,
        97, 115, 115, 47, 42
    ])
    try:
        init_file = '/etc/init.d/bt'
        src_file = '/www/server/panel/init.sh'
        md51 = public.md5(init_file)
        md52 = public.md5(src_file)
        if md51 != md52:
            import shutil
            shutil.copyfile(src_file, init_file)
            if os.path.getsize(init_file) < 10:
                public.ExecShell("chattr -i " + init_file)
                public.ExecShell("\cp -arf %s %s" % (src_file, init_file))
                public.ExecShell("chmod +x %s" % init_file)
    except:
        pass
    public.writeFile('/var/bt_setupPath.conf', '/www')
    public.ExecShell(c)
    p_file = 'class/plugin2.so'
    if os.path.exists(p_file): public.ExecShell("rm -f class/*.so")
    public.ExecShell(
        "chmod -R  600 /www/server/panel/data;chmod -R  600 /www/server/panel/config;chmod -R  700 /www/server/cron;chmod -R  600 /www/server/cron/*.log;chown -R root:root /www/server/panel/data;chown -R root:root /www/server/panel/config"
    )
    #disable_putenv('putenv')
    clean_session()
    #set_crond()
    clean_max_log('/www/server/panel/plugin/rsync/lsyncd.log')
    clean_max_log('/root/.pm2/pm2.log', 1024 * 1024 * 20)
    remove_tty1()
    clean_hook_log()
    run_new()
    clean_max_log('/www/server/cron', 1024 * 1024 * 5, 20)
    #check_firewall()
    check_dnsapi()
    clean_php_log()
Пример #11
0
def panel2To3():
    try:
        filename = '/www/server/apache/version.pl'
        if os.path.exists(filename):
            version = public.readFile(filename)
            if version.find('2.2') != -1:
                print('BT-Panel 3.x does not support apache2.2')
                return
    except:
        pass

    import mysql, db, os, shutil, time
    os.system('service mysqld stop')
    os.system('pkill -9 mysqld_safe')
    os.system('pkill -9 mysqld')
    os.system('sleep 2')
    os.system('service mysqld start')
    os.system('service mysqld stop')
    os.system('mysqld_safe --skip-grant-tables&')

    time.sleep(3)
    sql = mysql.mysql()
    sqldb = db.Sql()

    #转移配置
    arr = sql.query('select * from bt_default.bt_config')[0]
    sqldb.table('config').where('id=?', (1, )).save(
        'webserver,backup_path,sites_path,mysql_root',
        (arr[1], arr[2], arr[3], arr[5]))
    webserver = arr[1]
    setupPath = '/www/server'

    if webserver == 'nginx':
        #处理Nginx配置文件
        filename = setupPath + "/nginx/conf/nginx.conf"
        if os.path.exists(filename):
            conf = public.readFile(filename)
            if conf.find('include vhost/*.conf;') != -1:
                conf = conf.replace(
                    'include vhost/*.conf;',
                    'include ' + setupPath + '/panel/vhost/nginx/*.conf;')
                public.writeFile(filename, conf)
        #处理伪静态文件
        dstPath = setupPath + '/panel/vhost/rewrite'
        srcPath = setupPath + '/nginx/conf/rewrite'
        if os.path.exists(srcPath):
            if os.path.exists(dstPath):
                os.system('mv -f ' + dstPath + ' ' + dstPath + '_backup_' +
                          time.strftime('%Y%m%d_%H%M%S', time.localtime()))
            os.system('cp -a -r ' + srcPath + ' ' + dstPath)
            os.system('chmod -R 644 ' + dstPath)
    # else:
    #     #处理Apache配置文件
    #     filename = setupPath + "/apache/conf/httpd.conf"
    #     if os.path.exists(filename):
    #         conf = public.readFile(filename);
    #         if conf.find('IncludeOptional conf/vhost/*.conf') != -1:
    #             conf = conf.replace('IncludeOptional conf/vhost/*.conf','IncludeOptional ' + setupPath + '/panel/vhost/apache/*.conf');
    #             public.writeFile(filename,conf);

    #转移站点
    arr = sql.query('select * from bt_default.bt_sites')
    for siteArr in arr:
        #站点
        pid = sqldb.table('sites').add(
            'name,path,status,ps,addtime',
            (siteArr[1], siteArr[3], siteArr[4], siteArr[6], str(siteArr[7])))

        #域名
        domains = siteArr[2].split(',')
        for domain in domains:
            tmp = domain.split(':')
            if len(tmp) < 2: tmp.append('80')
            sqldb.table('domain').add('pid,name,port,addtime',
                                      (pid, tmp[0], tmp[1], public.getDate()))

        #子目录
        barr = sql.query("select * from bt_default.bt_binding where pid='" +
                         str(siteArr[0]) + "'")
        for binding in barr:
            sqldb.table('binding').add('pid,domain,path,port,addtime',
                                       (pid, binding[2], binding[3],
                                        str(binding[4]), str(binding[5])))

        #迁移配置文件
        letPath = '/etc/letsencrypt/live'
        dstKey = letPath + '/' + siteArr[1] + '/privkey.pem'
        dstCsr = letPath + '/' + siteArr[1] + '/fullchain.pem'
        if webserver == 'nginx':
            confFile = setupPath + '/nginx/conf/vhost/' + siteArr[1] + '.conf'
            if os.path.exists(confFile):
                conf = public.readFile(confFile)
                conf = conf.replace(
                    'rewrite/', setupPath + '/panel/vhost/rewrite/').replace(
                        'key/' + siteArr[1] + '/key.key',
                        dstKey).replace('key/' + siteArr[1] + '/key.csr',
                                        dstCsr)
                filename = setupPath + '/panel/vhost/nginx/' + siteArr[
                    1] + '.conf'
                public.writeFile(filename, conf)
                os.system('chmod 644 ' + filename)
        else:
            confFile = setupPath + '/apache/conf/vhost/' + siteArr[1] + '.conf'
            if os.path.exists(confFile):
                conf = public.readFile(confFile)
                conf = conf.replace('conf/key/' + siteArr[1] + '/key.key',
                                    dstKey).replace(
                                        'conf/key/' + siteArr[1] + '/key.csr',
                                        dstCsr)
                filename = setupPath + '/panel/vhost/apache/' + siteArr[
                    1] + '.conf'
                public.writeFile(filename, conf)
                os.system('chmod 644 ' + filename)

        #转移其它配置文件
        try:
            otherConf = setupPath + '/' + webserver + '/conf/vhost/default.conf'
            if os.path.exists(otherConf):
                dstOther = setupPath + '/panel/vhost/' + webserver + '/default.conf'
                public.ExecShell('\\cp -a -r ' + otherConf + ' ' + dstOther)

            otherConf = setupPath + '/' + webserver + '/conf/vhost/phpfpm_status.conf'
            if os.path.exists(otherConf):
                dstOther = setupPath + '/panel/vhost/' + webserver + '/phpfpm_status.conf'
                public.ExecShell('\\cp -a -r ' + otherConf + ' ' + dstOther)
        except:
            pass

        #迁移证书
        srcKey = setupPath + '/' + webserver + '/conf/key/' + siteArr[
            1] + '/key.key'
        if os.path.exists(srcKey):
            os.system('mkdir -p ' + letPath + '/' + siteArr[1])
            public.ExecShell('\\cp -a -r ' + srcKey + ' ' + dstKey)

        srcCsr = setupPath + '/' + webserver + '/conf/key/' + siteArr[
            1] + '/key.csr'
        if os.path.exists(srcCsr):
            public.ExecShell('\\cp -a -r ' + srcCsr + ' ' + dstCsr)

        print(siteArr[1] + ' -> done.\n')

    #转移数据库
    arr = sql.query('select * from bt_default.bt_databases')
    for databaseArr in arr:
        sqldb.table('databases').add(
            'name,username,password,accept,ps,addtime',
            (databaseArr[1], databaseArr[2], databaseArr[3], databaseArr[4],
             databaseArr[5], str(databaseArr[6])))

    #转移FTP
    arr = sql.query('select * from bt_default.bt_ftps')
    for ftpArr in arr:
        sqldb.table('ftps').add('name,password,path,status,ps,addtime',
                                (ftpArr[1], ftpArr[2], ftpArr[3], ftpArr[4],
                                 ftpArr[5], str(ftpArr[6])))

    #转移用户
    #arr = sql.query('select * from bt_default.bt_user')[0]
    #sqldb.table('users').where('id=?',(1,)).save('username,password,login_ip,login_time',(arr[1],arr[2],arr[3],arr[4]))

    #转移日志
    arr = sql.query('select * from bt_default.bt_logs')
    for log in arr:
        sqldb.table('logs').add('type,log,addtime', (log[1], log[2], log[3]))

    #转移防火墙记录
    arr = sql.query('select * from bt_default.bt_firewall')
    ports = ['80', '22', '21', '20', '888', '8888']
    for fw in arr:
        if str(fw[1]) in ports: continue
        sqldb.table('firewall').add('port,ps,addtime', (fw[1], fw[2], fw[3]))

    #转移计划任务记录
    try:
        arr = sql.query('select * from bt_default.bt_crontab')
        for cron in arr:
            sqldb.table('crontab').add(
                'name,type,where1,where_hour,where_minute,echo,addtime',
                (cron[1], cron[2], cron[3], cron[4], cron[5], cron[6],
                 cron[7]))
    except:
        pass

    os.system('/etc/init.d/yunclient stop')
    os.system('chkconfig --del yunclient')
    os.system('rm -f /etc/init.d/yunclient')
    os.system('pkill -9 mysqld_safe')
    os.system('pkill -9 mysqld')
    os.system('sleep 2 && service mysqld start')
    if os.path.exists('/etc/init.d/nginx'):
        os.system('/etc/init.d/nginx reload')
    if os.path.exists('/etc/init.d/httpd'):
        os.system('/etc/init.d/httpd reload')

    print('=========================')
    print('successful!')
Пример #12
0
    def request_post(self,post):
        if not hasattr(post, 'username') or not hasattr(post, 'password'):
            return public.returnJson(False,'LOGIN_USER_EMPTY'),json_header
        
        self.error_num(False)
        if self.limit_address('?') < 1: return public.returnJson(False,'LOGIN_ERR_LIMIT'),json_header
        
        post.username = post.username.strip()
        password = public.md5(post.password.strip())
        sql = db.Sql()
        user_list = sql.table('users').field('id,username,password').select()
        userInfo = None
        for u_info in user_list:
            if u_info['username'] == post.username:
                userInfo = u_info
        if 'code' in session:
            if session['code'] and not 'is_verify_password' in session:
                if not hasattr(post, 'code'): return public.returnMsg(False,'Verification code can not be empty!')
                if not public.checkCode(post.code):
                    public.WriteLog('TYPE_LOGIN','LOGIN_ERR_CODE',('****','****',public.GetClientIp()))
                    return public.returnJson(False,'CODE_ERR'),json_header
        try:
            s_pass = public.md5(public.md5(userInfo['password'] + '_bt.cn'))
            if userInfo['username'] != post.username or s_pass != password:
                public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',('****','******',public.GetClientIp()))
                num = self.limit_address('+')
                return public.returnJson(False,'LOGIN_USER_ERR',(str(num),)),json_header
            _key_file = "/www/server/panel/data/two_step_auth.txt"
            if hasattr(post,'vcode'):
                if self.limit_address('?',v="vcode") < 1: return public.returnJson(False,'您多次验证失败,禁止10分钟'),json_header
                import pyotp
                secret_key = public.readFile(_key_file)
                if not secret_key:
                    return public.returnJson(False, "Did not find the key, please close Google verification on the command line and trun on again"),json_header
                t = pyotp.TOTP(secret_key)
                result = t.verify(post.vcode)
                if not result:
                    if public.sync_date(): result = t.verify(post.vcode)
                    if not result:
                        num = self.limit_address('++',v="vcode")
                        return public.returnJson(False, 'Invalid Verification code. You have [{}] times left to try!'.format(num)), json_header
                now = int(time.time())
                public.writeFile("/www/server/panel/data/dont_vcode_ip.txt",json.dumps({"client_ip":public.GetClientIp(),"add_time":now}))
                self.limit_address('--',v="vcode")
                self.set_cdn_host(post)
                return self._set_login_session(userInfo)

            acc_client_ip = self.check_two_step_auth()

            if not os.path.exists(_key_file) or acc_client_ip:
                self.set_cdn_host(post)
                return self._set_login_session(userInfo)
            self.limit_address('-')
            session['is_verify_password'] = True
            return "1"
        except Exception as ex:
            stringEx = str(ex)
            if stringEx.find('unsupported') != -1 or stringEx.find('-1') != -1: 
                os.system("rm -f /tmp/sess_*")
                os.system("rm -f /www/wwwlogs/*log")
                public.ServiceReload()
                return public.returnJson(False,'USER_INODE_ERR'),json_header
            public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',('****','******',public.GetClientIp()))
            num = self.limit_address('+')
            return public.returnJson(False,'LOGIN_USER_ERR',(str(num),)),json_header
Пример #13
0
def systemTask():
    try:
        import system, psutil, time
        filename = 'data/control.conf'
        sql = db.Sql().dbfile('system')
        cpuIo = cpu = {}
        cpuCount = psutil.cpu_count()
        used = count = 0
        network_up = network_down = diskio_1 = diskio_2 = networkInfo = cpuInfo = diskInfo = None
        while True:
            if not os.path.exists(filename):
                time.sleep(10)
                continue

            day = 30
            try:
                day = int(public.readFile(filename))
                if day < 1:
                    time.sleep(10)
                    continue
            except:
                day = 30

            tmp = {}
            #取当前CPU Io
            tmp['used'] = psutil.cpu_percent(interval=1)

            if not cpuInfo:
                tmp['mem'] = GetMemUsed()
                cpuInfo = tmp

            if cpuInfo['used'] < tmp['used']:
                tmp['mem'] = GetMemUsed()
                cpuInfo = tmp

            #取当前网络Io
            networkIo = psutil.net_io_counters()[:4]
            if not network_up:
                network_up = networkIo[0]
                network_down = networkIo[1]
            tmp = {}
            tmp['upTotal'] = networkIo[0]
            tmp['downTotal'] = networkIo[1]
            tmp['up'] = round(float((networkIo[0] - network_up) / 1024), 2)
            tmp['down'] = round(float((networkIo[1] - network_down) / 1024), 2)
            tmp['downPackets'] = networkIo[3]
            tmp['upPackets'] = networkIo[2]

            network_up = networkIo[0]
            network_down = networkIo[1]

            if not networkInfo: networkInfo = tmp
            if (tmp['up'] + tmp['down']) > (networkInfo['up'] +
                                            networkInfo['down']):
                networkInfo = tmp

            #取磁盘Io
            if os.path.exists('/proc/diskstats'):
                diskio_2 = psutil.disk_io_counters()
                if not diskio_1: diskio_1 = diskio_2
                tmp = {}
                tmp['read_count'] = diskio_2.read_count - diskio_1.read_count
                tmp['write_count'] = diskio_2.write_count - diskio_1.write_count
                tmp['read_bytes'] = diskio_2.read_bytes - diskio_1.read_bytes
                tmp['write_bytes'] = diskio_2.write_bytes - diskio_1.write_bytes
                tmp['read_time'] = diskio_2.read_time - diskio_1.read_time
                tmp['write_time'] = diskio_2.write_time - diskio_1.write_time

                if not diskInfo:
                    diskInfo = tmp
                else:
                    diskInfo['read_count'] += tmp['read_count']
                    diskInfo['write_count'] += tmp['write_count']
                    diskInfo['read_bytes'] += tmp['read_bytes']
                    diskInfo['write_bytes'] += tmp['write_bytes']
                    diskInfo['read_time'] += tmp['read_time']
                    diskInfo['write_time'] += tmp['write_time']

                diskio_1 = diskio_2

            #print diskInfo

            if count >= 12:
                try:
                    addtime = int(time.time())
                    deltime = addtime - (day * 86400)

                    data = (cpuInfo['used'], cpuInfo['mem'], addtime)
                    sql.table('cpuio').add('pro,mem,addtime', data)
                    sql.table('cpuio').where("addtime<?",
                                             (deltime, )).delete()

                    data = (networkInfo['up'] / 5, networkInfo['down'] / 5,
                            networkInfo['upTotal'], networkInfo['downTotal'],
                            networkInfo['downPackets'],
                            networkInfo['upPackets'], addtime)
                    sql.table('network').add(
                        'up,down,total_up,total_down,down_packets,up_packets,addtime',
                        data)
                    sql.table('network').where("addtime<?",
                                               (deltime, )).delete()
                    if os.path.exists('/proc/diskstats'):
                        data = (diskInfo['read_count'],
                                diskInfo['write_count'],
                                diskInfo['read_bytes'],
                                diskInfo['write_bytes'], diskInfo['read_time'],
                                diskInfo['write_time'], addtime)
                        sql.table('diskio').add(
                            'read_count,write_count,read_bytes,write_bytes,read_time,write_time,addtime',
                            data)
                        sql.table('diskio').where("addtime<?",
                                                  (deltime, )).delete()

                    cpuInfo = None
                    networkInfo = None
                    diskInfo = None
                    count = 0
                except:
                    pass
            del (tmp)

            time.sleep(5)
            count += 1
    except:
        time.sleep(30)
        systemTask()
Пример #14
0
def systemTask():
    try:
        filename = 'data/control.conf'
        sql = db.Sql().dbfile('system')
        csql = '''CREATE TABLE IF NOT EXISTS `load_average` (
  `id` INTEGER PRIMARY KEY AUTOINCREMENT,
  `pro` REAL,
  `one` REAL,
  `five` REAL,
  `fifteen` REAL,
  `addtime` INTEGER
)'''
        sql.execute(csql, ())
        count = 0
        reloadNum = 0
        network_up = network_down = diskio_1 = diskio_2 = networkInfo = cpuInfo = diskInfo = None
        while True:
            if not os.path.exists(filename):
                time.sleep(10)
                continue

            day = 30
            try:
                day = int(public.readFile(filename))
                if day < 1:
                    time.sleep(10)
                    continue
            except:
                day = 30

            tmp = {}
            #取当前CPU Io
            tmp['used'] = cpu_percent(interval=1)

            if not cpuInfo:
                tmp['mem'] = GetMemUsed()
                cpuInfo = tmp

            if cpuInfo['used'] < tmp['used']:
                tmp['mem'] = GetMemUsed()
                cpuInfo = tmp

            #取当前网络Io
            networkIo = net_io_counters()[:4]
            if not network_up:
                network_up = networkIo[0]
                network_down = networkIo[1]
            tmp = {}
            tmp['upTotal'] = networkIo[0]
            tmp['downTotal'] = networkIo[1]
            tmp['up'] = round(float((networkIo[0] - network_up) / 1024), 2)
            tmp['down'] = round(float((networkIo[1] - network_down) / 1024), 2)
            tmp['downPackets'] = networkIo[3]
            tmp['upPackets'] = networkIo[2]

            network_up = networkIo[0]
            network_down = networkIo[1]

            if not networkInfo: networkInfo = tmp
            if (tmp['up'] + tmp['down']) > (networkInfo['up'] +
                                            networkInfo['down']):
                networkInfo = tmp

            #取磁盘Io
            disk_ios = True
            try:
                if os.path.exists('/proc/diskstats'):
                    diskio_2 = disk_io_counters()
                    if not diskio_1: diskio_1 = diskio_2
                    tmp = {}
                    tmp['read_count'] = diskio_2.read_count - diskio_1.read_count
                    tmp['write_count'] = diskio_2.write_count - diskio_1.write_count
                    tmp['read_bytes'] = diskio_2.read_bytes - diskio_1.read_bytes
                    tmp['write_bytes'] = diskio_2.write_bytes - diskio_1.write_bytes
                    tmp['read_time'] = diskio_2.read_time - diskio_1.read_time
                    tmp['write_time'] = diskio_2.write_time - diskio_1.write_time

                    if not diskInfo:
                        diskInfo = tmp
                    else:
                        diskInfo['read_count'] += tmp['read_count']
                        diskInfo['write_count'] += tmp['write_count']
                        diskInfo['read_bytes'] += tmp['read_bytes']
                        diskInfo['write_bytes'] += tmp['write_bytes']
                        diskInfo['read_time'] += tmp['read_time']
                        diskInfo['write_time'] += tmp['write_time']

                    diskio_1 = diskio_2
            except:
                disk_ios = False

            #print diskInfo

            if count >= 12:
                try:
                    sql.close()
                    sql = db.Sql().dbfile('system')
                    addtime = int(time.time())
                    deltime = addtime - (day * 86400)

                    data = (cpuInfo['used'], cpuInfo['mem'], addtime)
                    sql.table('cpuio').add('pro,mem,addtime', data)
                    sql.table('cpuio').where("addtime<?", (deltime, )).delete()

                    data = (networkInfo['up'] / 5, networkInfo['down'] / 5,
                            networkInfo['upTotal'], networkInfo['downTotal'],
                            networkInfo['downPackets'],
                            networkInfo['upPackets'], addtime)
                    sql.table('network').add(
                        'up,down,total_up,total_down,down_packets,up_packets,addtime',
                        data)
                    sql.table('network').where("addtime<?",
                                               (deltime, )).delete()
                    if os.path.exists('/proc/diskstats') and disk_ios:
                        data = (diskInfo['read_count'],
                                diskInfo['write_count'],
                                diskInfo['read_bytes'],
                                diskInfo['write_bytes'], diskInfo['read_time'],
                                diskInfo['write_time'], addtime)
                        sql.table('diskio').add(
                            'read_count,write_count,read_bytes,write_bytes,read_time,write_time,addtime',
                            data)
                        sql.table('diskio').where("addtime<?",
                                                  (deltime, )).delete()

                    #LoadAverage
                    load_average = GetLoadAverage()
                    lpro = round(
                        (load_average['one'] / load_average['max']) * 100, 2)
                    if lpro > 100: lpro = 100
                    sql.table('load_average').add(
                        'pro,one,five,fifteen,addtime',
                        (lpro, load_average['one'], load_average['five'],
                         load_average['fifteen'], addtime))

                    lpro = None
                    load_average = None
                    cpuInfo = None
                    networkInfo = None
                    diskInfo = None
                    count = 0
                    reloadNum += 1
                    if reloadNum > 1440:
                        reloadNum = 0
                except Exception as ex:
                    print(str(ex))
            del (tmp)

            time.sleep(5)
            count += 1
    except:
        time.sleep(30)
        systemTask()
Пример #15
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 = public.GetMsg("SITE_NOT_EXIST1", (name, ))
            print(u"★[" + endDate + "] " + log)
            print(
                "----------------------------------------------------------------------------"
            )
            return

        backup_path = sql.table('config').where(
            "id=?", (1, )).getField('backup_path') + '/site'
        if not os.path.exists(backup_path):
            public.ExecShell("mkdir -p " + backup_path)

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

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

        if not os.path.exists(filename):
            log = public.GetMsg("SITE_BACK_FILE", (name, ))
            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 = public.GetMsg("SITE_BACKFTP_SUCCESS",
                            (name, str(round(outTime, 2))))
        public.WriteLog('TYPE_CRON', log)
        print(u"★[" + endDate + "] " + log)
        print(public.GetMsg("KEEP_PART", (count, )))
        print(public.GetMsg("FTP_FILE_NAME") + filename)

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

        num = len(backups) - int(count)
        if num > 0:
            for backup in backups:
                public.ExecShell("rm -f " + backup['filename'])
                sql.table('backup').where('id=?', (backup['id'], )).delete()
                num -= 1
                print(
                    public.GetMsg("FTP_CLEAN_BACK_FILE") + backup['filename'])
                if num < 1: break
Пример #16
0
    def GetSql(self, get, result='1,2,3,4,5,8'):
        #判断前端是否传入参数
        order = "id desc"
        if hasattr(get, 'order'):
            order = get.order

        limit = 20
        if hasattr(get, 'limit'):
            limit = int(get.limit)

        if hasattr(get, 'result'):
            result = get.result

        SQL = db.Sql()
        data = {}
        #取查询条件
        where = ''
        if hasattr(get, 'search'):
            if sys.version_info[0] == 2:
                get.search = get.search.encode('utf-8')
            where = self.GetWhere(get.table, get.search)
            if get.table == 'backup':
                where += " and type='" + get.type + "'"

            if get.table == 'sites' and get.search:
                pid = SQL.table('domain').where(
                    "name LIKE '%" + get.search + "%'", ()).getField('pid')
                if pid:
                    if where:
                        where += " or id=" + str(pid)
                    else:
                        where += "id=" + str(pid)

        if get.table == 'sites' and hasattr(get, 'type'):
            if get.type != '-1':
                type_where = "type_id=%s" % get.type
                if where == '':
                    where = type_where
                else:
                    where += " and " + type_where

        field = self.GetField(get.table)
        #实例化数据库对象

        #是否直接返回所有列表
        if hasattr(get, 'list'):
            data = SQL.table(get.table).where(
                where, ()).field(field).order(order).select()
            return data

        #取总行数
        count = SQL.table(get.table).where(where, ()).count()
        #get.uri = get
        #包含分页类
        import page
        #实例化分页类
        page = page.Page()

        info = {}
        info['count'] = count
        info['row'] = limit

        info['p'] = 1
        if hasattr(get, 'p'):
            info['p'] = int(get['p'])
        info['uri'] = get
        info['return_js'] = ''
        if hasattr(get, 'tojs'):
            info['return_js'] = get.tojs

        data['where'] = where

        #获取分页数据
        data['page'] = page.GetPage(info, result)
        #取出数据
        data['data'] = SQL.table(get.table).where(
            where, ()).order(order).field(field).limit(
                str(page.SHIFT) + ',' + str(page.ROW)).select()
        return data
Пример #17
0
def check_system():
    sql = db.Sql()
    sql.execute("alter TABLE sites add edate integer DEFAULT '0000-00-00'", ())
Пример #18
0
        'panelDownloadApi', '/safe', 'panelSafe')

app = web.application(urls, globals(), autoreload=False)

#初始化SESSION
web.config.session_parameters['cookie_name'] = 'BT_PANEL'
web.config.session_parameters['cookie_domain'] = None
web.config.session_parameters['timeout'] = 3600
web.config.session_parameters['ignore_expiry'] = True
web.config.session_parameters['ignore_change_ip'] = True
web.config.session_parameters['secret_key'] = 'www.bt.cn'
web.config.session_parameters['expired_message'] = 'Session expired'
dbfile = '/dev/shm/session.db'
src_sessiondb = 'data/session.db'
if not os.path.exists(src_sessiondb):
    print db.Sql().dbfile('session').create('session')
if not os.path.exists(dbfile):
    os.system("\\cp -a -r " + src_sessiondb + " " + dbfile)
sessionDB = web.database(dbn='sqlite', db=dbfile)
session = web.session.Session(app,
                              web.session.DBStore(sessionDB, 'sessions'),
                              initializer={'login': False})


def session_hook():
    session.panelPath = os.path.dirname(__file__)
    web.ctx.session = session


app.add_processor(web.loadhook(session_hook))
Пример #19
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 = "网站[" + name + "]不存在!"
            print "★[" + endDate + "] " + log
            print "----------------------------------------------------------------------------"
            return

        backup_path = sql.table('config').where(
            "id=?", (1, )).getField('backup_path') + '/site'
        if not os.path.exists(backup_path):
            public.ExecShell("mkdir -p " + backup_path)

        filename = backup_path + "/Web_" + name + "_" + time.strftime(
            '%Y%m%d_%H%M%S', time.localtime()) + '.tar.gz'
        public.ExecShell("cd " + os.path.dirname(path) + " && tar zcvf '" +
                         filename + "' '" + os.path.basename(path) +
                         "' > /dev/null")
        endDate = time.strftime('%Y/%m/%d %X', time.localtime())

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

        #上传文件
        self.upload_file(filename)

        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,
                                 'alioss', endDate, os.path.getsize(filename)))
        log = "网站[" + name + "]已成功备份到阿里云OSS,用时[" + str(round(outTime,
                                                             2)) + "]秒"
        public.WriteLog('计划任务', log)
        print "★[" + endDate + "] " + log
        print "|---保留最新的[" + count + "]份备份"
        print "|---文件名:" + os.path.basename(filename)

        #清理本地文件
        public.ExecShell("rm -f " + filename)

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

        num = len(backups) - int(count)
        if num > 0:
            for backup in backups:
                if os.path.exists(backup['filename']):
                    public.ExecShell("rm -f " + backup['filename'])
                self.delete_file(backup['name'])
                sql.table('backup').where('id=?', (backup['id'], )).delete()
                num -= 1
                print "|---已清理过期备份文件:" + backup['name']
                if num < 1: break
        return None
Пример #20
0
    def GetSql(self, get, result='1,2,3,4,5,8'):
        #判断前端是否传入参数
        order = "id desc"
        if hasattr(get, 'order'):
            order = get.order

        limit = 20
        if hasattr(get, 'limit'):
            limit = int(get.limit)

        if hasattr(get, 'result'):
            result = get.result

        data = {}
        #取查询条件
        where = ''
        if hasattr(get, 'search'):
            where = self.GetWhere(get.table, get.search)
            if get.table == 'backup':
                where += " and type='" + get.type + "'"

        field = self.GetField(get.table)
        #实例化数据库对象
        SQL = db.Sql()

        #是否直接返回所有列表
        if hasattr(get, 'list'):
            data = SQL.table(get.table).where(
                where, ()).field(field).order(order).select()
            return data

        #取总行数
        count = SQL.table(get.table).where(where, ()).count()
        #get.uri = get
        #包含分页类
        import page
        #实例化分页类
        page = page.Page()

        del (get.data)
        del (get.zunfile)
        info = {}
        info['count'] = count
        info['row'] = limit

        info['p'] = 1
        if hasattr(get, 'p'):
            info['p'] = int(get['p'])
        info['uri'] = get
        info['return_js'] = ''
        if hasattr(get, 'tojs'):
            info['return_js'] = get.tojs

        data['where'] = where

        #获取分页数据
        data['page'] = page.GetPage(info, result)
        #取出数据
        data['data'] = SQL.table(get.table).where(
            where, ()).order(order).field(field).limit(
                bytes(page.SHIFT) + ',' + bytes(page.ROW)).select()
        return data
Пример #21
0
    def GET(self):
        if os.path.exists('/www/server/panel/install.pl'):
            raise web.seeother('/install')
        web.ctx.session.lan = public.get_language()
        if not hasattr(session, 'webname'):
            session.webname = public.getMsg('NAME')
        tmp = web.ctx.host.split(':')
        domain = public.readFile('data/domain.conf')
        if domain:
            if (tmp[0].strip() != domain.strip()):
                errorStr = '''
<meta charset="utf-8">
<title>%s</title>
</head><body>
<h1>%s</h1>
    <p>%s</p>
    <p>%s</p>
    <p>%s</p>
<hr>
<address>%s 5.x <a href="http://www.bt.cn/bbs" target="_blank">%s</a></address>
</body></html>
    ''' % (public.getMsg('PAGE_ERR_TITLE'),
                public.getMsg('PAGE_ERR_DOMAIN_H1'),
                public.getMsg('PAGE_ERR_DOMAIN_P1'),
                public.getMsg('PAGE_ERR_DOMAIN_P2'),
                public.getMsg('PAGE_ERR_DOMAIN_P3'), public.getMsg('NAME'),
                public.getMsg('PAGE_ERR_HELP'))
                web.header('Content-Type',
                           'text/html; charset=utf-8',
                           unique=True)
                return errorStr
        if os.path.exists('data/limitip.conf'):
            iplist = public.readFile('data/limitip.conf')
            if iplist:
                iplist = iplist.strip()
                if not web.ctx.ip in iplist.split(','):
                    errorStr = '''
<meta charset="utf-8">
<title>%s</title>
</head><body>
<h1>%s</h1>
    <p>%s</p>
    <p>%s</p>
    <p>%s</p>
<hr>
<address>%s 5.x <a href="http://www.bt.cn/bbs" target="_blank">%s</a></address>
</body></html>
''' % (public.getMsg('PAGE_ERR_TITLE'), public.getMsg('PAGE_ERR_IP_H1'),
                    public.getMsg('PAGE_ERR_IP_P1', (web.ctx.ip, )),
                    public.getMsg('PAGE_ERR_IP_P2'), public.getMsg('PAGE_ERR_IP_P3'),
                    public.getMsg('NAME'), public.getMsg('PAGE_ERR_HELP'))
                    web.header('Content-Type',
                               'text/html; charset=utf-8',
                               unique=True)
                    return errorStr

        get = web.input()
        sql = db.Sql()
        if hasattr(get, 'dologin'):
            if web.ctx.session.login != False:
                web.ctx.session.login = False
                web.ctx.session.kill()
            import time
            time.sleep(0.2)
            raise web.seeother('/login')

        if hasattr(web.ctx.session, 'login'):
            if web.ctx.session.login == True:
                raise web.seeother('/')

        if not hasattr(web.ctx.session, 'code'):
            web.ctx.session.code = False
        data = {}
        data['lan'] = public.getLan('login')
        render = web.template.render('templates/' + templateName + '/',
                                     globals={
                                         'session': session,
                                         'web': web
                                     })
        return render.login(data)
Пример #22
0
    def request_post(self, post):
        if not hasattr(post, 'username') or not hasattr(post, 'password'):
            return public.returnJson(False, 'LOGIN_USER_EMPTY'), json_header

        self.error_num(False)
        if self.limit_address('?') < 1:
            return public.returnJson(False, 'LOGIN_ERR_LIMIT'), json_header

        post.username = post.username.strip()
        password = public.md5(post.password.strip())
        sql = db.Sql()
        userInfo = sql.table('users').where(
            "id=?", (1, )).field('id,username,password').find()
        m_code = cache.get('codeStr')
        if 'code' in session:
            if session['code'] and not 'is_verify_password' in session:
                if not hasattr(post, 'code'):
                    return public.returnJson(False, '验证码不能为空!'), json_header
                if not public.checkCode(post.code):
                    public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_CODE',
                                    ('****', '****', public.GetClientIp()))
                    return public.returnJson(False, 'CODE_ERR'), json_header
        try:
            s_pass = public.md5(public.md5(userInfo['password'] + '_bt.cn'))
            if userInfo['username'] != post.username or s_pass != password:
                public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_PASS',
                                ('****', '******', public.GetClientIp()))
                num = self.limit_address('+')
                return public.returnJson(False, 'LOGIN_USER_ERR',
                                         (str(num), )), json_header
            _key_file = "/www/server/panel/data/two_step_auth.txt"
            if hasattr(post, 'vcode'):
                if self.limit_address('?', v="vcode") < 1:
                    return public.returnJson(False,
                                             '您多次验证失败,禁止10分钟'), json_header
                import pyotp
                secret_key = public.readFile(_key_file)
                if not secret_key:
                    return public.returnJson(
                        False, "没有找到key,请尝试在命令行关闭谷歌验证后在开启"), json_header
                t = pyotp.TOTP(secret_key)
                result = t.verify(post.vcode)
                if not result:
                    if public.sync_date(): result = t.verify(post.vcode)
                    if not result:
                        num = self.limit_address('++', v="vcode")
                        return public.returnJson(
                            False,
                            '验证失败,您还可以尝试[{}]次!'.format(num)), json_header
                now = int(time.time())
                public.writeFile(
                    "/www/server/panel/data/dont_vcode_ip.txt",
                    json.dumps({
                        "client_ip": public.GetClientIp(),
                        "add_time": now
                    }))
                self.limit_address('--', v="vcode")
                return self._set_login_session(userInfo)

            acc_client_ip = self.check_two_step_auth()

            if not os.path.exists(_key_file) or acc_client_ip:
                return self._set_login_session(userInfo)
            self.limit_address('-')
            session['is_verify_password'] = True
            return "1"
        except Exception as ex:
            stringEx = str(ex)
            if stringEx.find('unsupported') != -1 or stringEx.find('-1') != -1:
                os.system("rm -f /tmp/sess_*")
                os.system("rm -f /www/wwwlogs/*log")
                public.ServiceReload()
                return public.returnJson(False, 'USER_INODE_ERR'), json_header
            public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_PASS',
                            ('****', '******', public.GetClientIp()))
            num = self.limit_address('+')
            return public.returnJson(False, 'LOGIN_USER_ERR',
                                     (str(num), )), json_header
Пример #23
0
 def __check_host_name(self, domain):
     sql = db.Sql()
     path = sql.table('sites').where('name=?', (domain, )).getField('path')
     return path
Пример #24
0
import sys, os
panelPath = '/www/server/panel/'
os.chdir(panelPath)
sys.path.append(panelPath + "class/")
import public, time, json
import db

username = '******'
password = '******'

sql = db.Sql()
sql.table('users').where('id=?', (1, )).setField('password',
                                                 public.md5(password))
sql.table('users').where('id=?', (1, )).setField('username', username)

admin_path_file = 'data/admin_path.pl'
public.writeFile(admin_path_file, '/')

password_path_file = 'default.pl'
public.writeFile(password_path_file, password)
Пример #25
0
def control_init():
    global exec_tips
    if exec_tips: return
    exec_tips = True
    sql_tips = '/dev/shm/bt_sql_tips.pl'

    if not os.path.exists(sql_tips):
        sql = db.Sql().dbfile('system')
        csql = '''CREATE TABLE IF NOT EXISTS `load_average` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`pro` REAL,
`one` REAL,
`five` REAL,
`fifteen` REAL,
`addtime` INTEGER
)'''
        sql.execute(csql, ())
        public.M('sites').execute(
            "alter TABLE sites add edate integer DEFAULT '0000-00-00'", ())
        public.M('sites').execute(
            "alter TABLE sites add type_id integer DEFAULT 0", ())

        sql = db.Sql()
        csql = '''CREATE TABLE IF NOT EXISTS `site_types` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` REAL,
`ps` REAL
)'''
        sql.execute(csql, ())
        public.writeFile(sql_tips, 'True')

    filename = '/www/server/nginx/off'
    if os.path.exists(filename): os.remove(filename)
    c = public.to_string([
        99, 104, 97, 116, 116, 114, 32, 45, 105, 32, 47, 119, 119, 119, 47,
        115, 101, 114, 118, 101, 114, 47, 112, 97, 110, 101, 108, 47, 99, 108,
        97, 115, 115, 47, 42
    ])
    try:
        init_file = '/etc/init.d/bt'
        src_file = '/www/server/panel/init.sh'
        md51 = public.md5(init_file)
        md52 = public.md5(src_file)
        if md51 != md52:
            import shutil
            shutil.copyfile(src_file, init_file)
            if os.path.getsize(init_file) < 10:
                os.system("chattr -i " + init_file)
                os.system("\cp -arf %s %s" % (src_file, init_file))
                os.system("chmod +x %s" % init_file)
    except:
        pass
    public.writeFile('/var/bt_setupPath.conf', '/www')
    public.ExecShell(c)
    p_file = 'class/plugin2.so'
    if os.path.exists(p_file): public.ExecShell("rm -f class/*.so")
    public.ExecShell(
        "chmod -R  600 /www/server/panel/data;chmod -R  600 /www/server/panel/config;chmod -R  700 /www/server/cron;chmod -R  600 /www/server/cron/*.log;chown -R root:root /www/server/panel/data;chown -R root:root /www/server/panel/config"
    )
    #disable_putenv('putenv')
    clean_session()
    #set_crond()
    clean_max_log('/www/server/panel/plugin/rsync/lsyncd.log')
    remove_tty1()
    clean_hook_log()
Пример #26
0
    def backupDatabase(self, name, count):
        sql = db.Sql()
        path = sql.table('databases').where('name=?',
                                            (name, )).getField('path')
        startTime = time.time()
        if not path:
            endDate = time.strftime('%Y/%m/%d %X', time.localtime())
            log = "数据库[" + name + "]不存在!"
            print "★[" + endDate + "] " + log
            print "----------------------------------------------------------------------------"
            return

        backup_path = sql.table('config').where(
            "id=?", (1, )).getField('backup_path') + '/database'
        if not os.path.exists(backup_path):
            public.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 = sql.table('config').where("id=?",
                                               (1, )).getField('mysql_root')
        mycnf = public.readFile('/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:
            public.writeFile('/etc/my.cnf', mycnf)

        public.ExecShell(
            "/www/server/mysql/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 = "数据库[" + name + "]备份失败!"
            print "★[" + endDate + "] " + log
            print "----------------------------------------------------------------------------"
            return

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

        endDate = time.strftime('%Y/%m/%d %X', time.localtime())
        outTime = time.time() - startTime
        pid = sql.table('databases').where('name=?', (name, )).getField('id')

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

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

        num = len(backups) - int(count)
        if num > 0:
            for backup in backups:
                public.ExecShell("rm -f " + backup['filename'])
                sql.table('backup').where('id=?', (backup['id'], )).delete()
                num -= 1
                print "|---已清理过期备份文件:" + backup['filename']
                if num < 1: break
Пример #27
0
    def backupDatabase(self, name, count):
        sql = db.Sql()
        path = sql.table('databases').where('name=?', (name, )).getField('id')
        startTime = time.time()
        if not path:
            endDate = time.strftime('%Y/%m/%d %X', time.localtime())
            log = public.GetMsg("FTP_DB_NOT_EXIST", (name, ))
            print(u"★[" + endDate + "] " + log)
            print(
                u"----------------------------------------------------------------------------"
            )
            return

        backup_path = sql.table('config').where(
            "id=?", (1, )).getField('backup_path') + '/database'
        if not os.path.exists(backup_path):
            public.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 = sql.table('config').where("id=?",
                                               (1, )).getField('mysql_root')

        mycnf = public.readFile('/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:
            public.writeFile('/etc/my.cnf', mycnf)

        public.ExecShell("/www/server/mysql/bin/mysqldump --force --opt " +
                         name + " | gzip > " + filename)

        if not os.path.exists(filename):
            endDate = time.strftime('%Y/%m/%d %X', time.localtime())
            log = public.GetMsg("FTP_DB_BACK", (name, ))
            print(u"★[" + endDate + "] " + log)
            print(
                u"----------------------------------------------------------------------------"
            )
            return

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

        endDate = time.strftime('%Y/%m/%d %X', time.localtime())
        outTime = time.time() - startTime
        pid = sql.table('databases').where('name=?', (name, )).getField('id')

        sql.table('backup').add('type,name,pid,filename,addtime,size',
                                (1, os.path.basename(filename), pid, filename,
                                 endDate, os.path.getsize(filename)))
        log = public.GetMsg("FTP_DB_BACK_SUCCESS",
                            (name, str(round(outTime, 2))))
        public.WriteLog('TYPE_CRON', log)
        print("★[" + endDate + "] " + log)
        print(public.GetMsg("KEEP_PART", (count, )))
        print(public.GetMsg("FTP_FILE_NAME") + filename)

        #清理多余备份
        backups = sql.table('backup').where(
            'type=? and pid=? and filename!=? and filename!=? and filename!=? and filename!=? and filename!=?',
            ('1', pid, 'alioss', 'txcos', 'upyun', 'qiniu',
             'ftp')).field('id,filename').select()

        num = len(backups) - int(count)
        if num > 0:
            for backup in backups:
                public.ExecShell("rm -f " + backup['filename'])
                sql.table('backup').where('id=?', (backup['id'], )).delete()
                num -= 1
                print(
                    public.GetMsg("FTP_CLEAN_BACK_FILE") + backup['filename'])
                if num < 1: break
Пример #28
0
def systemTask():
    # 系统监控任务
    try:
        import system_api
        import psutil
        import time
        sm = system_api.system_api()
        filename = 'data/control.conf'

        sql = db.Sql().dbfile('system')
        csql = mw.readFile('data/sql/system.sql')
        csql_list = csql.split(';')
        for index in range(len(csql_list)):
            sql.execute(csql_list[index], ())

        cpuIo = cpu = {}
        cpuCount = psutil.cpu_count()
        used = count = 0
        reloadNum = 0
        network_up = network_down = diskio_1 = diskio_2 = networkInfo = cpuInfo = diskInfo = None
        while True:
            if not os.path.exists(filename):
                time.sleep(10)
                continue

            day = 30
            try:
                day = int(mw.readFile(filename))
                if day < 1:
                    time.sleep(10)
                    continue
            except:
                day = 30

            tmp = {}
            # 取当前CPU Io
            tmp['used'] = psutil.cpu_percent(interval=1)

            if not cpuInfo:
                tmp['mem'] = sm.getMemUsed()
                cpuInfo = tmp

            if cpuInfo['used'] < tmp['used']:
                tmp['mem'] = sm.getMemUsed()
                cpuInfo = tmp

            # 取当前网络Io
            networkIo = psutil.net_io_counters()[:4]
            if not network_up:
                network_up = networkIo[0]
                network_down = networkIo[1]
            tmp = {}
            tmp['upTotal'] = networkIo[0]
            tmp['downTotal'] = networkIo[1]
            tmp['up'] = round(float((networkIo[0] - network_up) / 1024), 2)
            tmp['down'] = round(float((networkIo[1] - network_down) / 1024), 2)
            tmp['downPackets'] = networkIo[3]
            tmp['upPackets'] = networkIo[2]

            network_up = networkIo[0]
            network_down = networkIo[1]

            if not networkInfo:
                networkInfo = tmp
            if (tmp['up'] + tmp['down']) > (networkInfo['up'] + networkInfo['down']):
                networkInfo = tmp
            # 取磁盘Io
            # if os.path.exists('/proc/diskstats'):
            diskio_2 = psutil.disk_io_counters()
            if not diskio_1:
                diskio_1 = diskio_2
            tmp = {}
            tmp['read_count'] = diskio_2.read_count - diskio_1.read_count
            tmp['write_count'] = diskio_2.write_count - diskio_1.write_count
            tmp['read_bytes'] = diskio_2.read_bytes - diskio_1.read_bytes
            tmp['write_bytes'] = diskio_2.write_bytes - diskio_1.write_bytes
            tmp['read_time'] = diskio_2.read_time - diskio_1.read_time
            tmp['write_time'] = diskio_2.write_time - diskio_1.write_time

            if not diskInfo:
                diskInfo = tmp
            else:
                diskInfo['read_count'] += tmp['read_count']
                diskInfo['write_count'] += tmp['write_count']
                diskInfo['read_bytes'] += tmp['read_bytes']
                diskInfo['write_bytes'] += tmp['write_bytes']
                diskInfo['read_time'] += tmp['read_time']
                diskInfo['write_time'] += tmp['write_time']
            diskio_1 = diskio_2

            # print diskInfo
            if count >= 12:
                try:
                    addtime = int(time.time())
                    deltime = addtime - (day * 86400)

                    data = (cpuInfo['used'], cpuInfo['mem'], addtime)
                    sql.table('cpuio').add('pro,mem,addtime', data)
                    sql.table('cpuio').where("addtime<?", (deltime,)).delete()

                    data = (networkInfo['up'] / 5, networkInfo['down'] / 5, networkInfo['upTotal'], networkInfo[
                            'downTotal'], networkInfo['downPackets'], networkInfo['upPackets'], addtime)
                    sql.table('network').add(
                        'up,down,total_up,total_down,down_packets,up_packets,addtime', data)
                    sql.table('network').where(
                        "addtime<?", (deltime,)).delete()
                    # if os.path.exists('/proc/diskstats'):
                    data = (diskInfo['read_count'], diskInfo['write_count'], diskInfo['read_bytes'], diskInfo[
                            'write_bytes'], diskInfo['read_time'], diskInfo['write_time'], addtime)
                    sql.table('diskio').add(
                        'read_count,write_count,read_bytes,write_bytes,read_time,write_time,addtime', data)
                    sql.table('diskio').where(
                        "addtime<?", (deltime,)).delete()

                    # LoadAverage
                    load_average = sm.getLoadAverage()
                    lpro = round(
                        (load_average['one'] / load_average['max']) * 100, 2)
                    if lpro > 100:
                        lpro = 100
                    sql.table('load_average').add('pro,one,five,fifteen,addtime', (lpro, load_average[
                        'one'], load_average['five'], load_average['fifteen'], addtime))

                    lpro = None
                    load_average = None
                    cpuInfo = None
                    networkInfo = None
                    diskInfo = None
                    count = 0
                    reloadNum += 1
                    if reloadNum > 1440:
                        reloadNum = 0
                        restartMw()
                except Exception, ex:
                    print str(ex)

            del(tmp)
            time.sleep(5)
            count += 1
    except Exception, ex:
        print str(ex)
        import time
        time.sleep(30)
        systemTask()
Пример #29
0
def M(table):
    import db
    sql = db.Sql()
    return sql.table(table);
Пример #30
0
def M(table):
    sql = db.Sql()
    return sql.table(table)