Exemple #1
0
 def __Conn(self):
     try:
         import public
         try:
             import MySQLdb
         except Exception,ex:
             self.__DB_ERR = ex
             return False;
         try:
             myconf = public.readFile('/etc/my.cnf');
             rep = "port\s*=\s*([0-9]+)"
             self.__DB_PORT = int(re.search(rep,myconf).groups()[0]);
         except:
             self.__DB_PORT = 3306;
         self.__DB_PASS = public.M('config').where('id=?',(1,)).getField('mysql_root');
         try:
             if os.path.exists(self.__DB_HOST_CONF): self.__DB_HOST = public.readFile(self.__DB_HOST_CONF);
             self.__DB_CONN = MySQLdb.connect(host = self.__DB_HOST,user = self.__DB_USER,passwd = self.__DB_PASS,port = self.__DB_PORT,charset="utf8",connect_timeout=1)
         except MySQLdb.Error,e:
             if e[0] != 2003: 
                 self.__DB_ERR = e
                 return False
             if self.__DB_HOST == 'localhost':
                 self.__DB_HOST = '127.0.0.1';
             else:
                 self.__DB_HOST = 'localhost';
             public.writeFile(self.__DB_HOST_CONF,self.__DB_HOST);
             self.__DB_CONN = MySQLdb.connect(host = self.__DB_HOST,user = self.__DB_USER,passwd = self.__DB_PASS,port = self.__DB_PORT,charset="utf8",connect_timeout=1)
Exemple #2
0
 def GetLogs(self,get):
     id = get['id']
     echo = public.M('crontab').where("id=?",(id,)).field('echo').find()
     logFile = web.ctx.session.setupPath+'/cron/'+echo['echo']+'.log'
     if not os.path.exists(logFile):return public.returnMsg(False, 'CRONTAB_TASKLOG_EMPTY')
     log = public.GetNumLines(logFile,2000)
     f = open(logFile,'r')
     tmp = f.readline()
     n=0;
     while tmp:
         n += 1;
         tmp = f.readline();
     f.close();
     if n > 2000: public.writeFile(logFile,log)
     
     where = "Warning: Using a password on the command line interface can be insecure.\n"
     if  log.find(where)>-1:
         log = log.replace(where, '')
         public.writeFile('/tmp/read.tmp',log)
     
     import chardet;
     char=chardet.detect(log);
     encodeing = char['encoding'];
     if char['encoding'] == 'GB2312': encodeing = 'GBK';
     if char['encoding'] == 'ascii': encodeing = 'utf-8';
     log = log.decode(encodeing).encode('utf-8');
     return public.returnMsg(True, log);
Exemple #3
0
 def BinLog(self,get):
     myfile = '/etc/my.cnf';
     mycnf = public.readFile(myfile);
     if mycnf.find('#log-bin=mysql-bin') != -1:
         if hasattr(get,'status'): return public.returnMsg(False,'0');
         mycnf = mycnf.replace('#log-bin=mysql-bin','log-bin=mysql-bin')
         mycnf = mycnf.replace('#binlog_format=mixed','binlog_format=mixed')
         os.system('sync')
         os.system('/etc/init.d/mysqld restart');
     else:
         path = self.GetMySQLInfo(get)['datadir'];
         if hasattr(get,'status'): 
             dsize = 0;
             for n in os.listdir(path):
                 if len(n) < 9: continue;
                 if n[0:9] == 'mysql-bin':
                     dsize += os.path.getsize(path + '/' + n);
             return public.returnMsg(True,dsize);
         
         mycnf = mycnf.replace('log-bin=mysql-bin','#log-bin=mysql-bin')
         mycnf = mycnf.replace('binlog_format=mixed','#binlog_format=mixed')
         os.system('sync')
         os.system('/etc/init.d/mysqld restart');
         os.system('rm -f ' + path + '/mysql-bin.*')
     
     public.writeFile(myfile,mycnf);
     return public.returnMsg(True,'SUCCESS');
Exemple #4
0
 def threadto(self,filename):
     print 'scanning ' + filename,
     file= open(filename)
     filestr = file.read()
     char=chardet.detect(filestr)
     try:
         filestr = filestr.decode(char['encoding'])
     except:
         return;
     file.close()
     for rule in self.rulelist:
         tmps = re.compile(rule['code']).findall(filestr)
         if tmps:
             tmp = {}
             tmp['msg'] = rule['msg'];
             tmp['level'] = rule['level'];
             tmp['filename'] = filename;
             tmp['code'] = str(tmps[0][0:200])
             tmp['etime'] = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(os.path.getmtime(filename)))
             self.result['data'].append(tmp);
             self.result['error'] += 1
             break
     print '  done'
     self.result['count'] += 1
     public.writeFile(self.result['path'] + '/scan.pl',json.dumps(self.result));
     del(filestr)
Exemple #5
0
 def DelCrontab(self,get):
     try:
         id = get['id']
         find = public.M('crontab').where("id=?",(id,)).field('name,echo').find()
         x = web.ctx.session.server_os['x'];
         if x == 'RHEL':
             file='/var/spool/cron/root'
         else:
             file='/var/spool/cron/crontabs/root'
         conf=public.readFile(file)
         rep = ".+" + str(find['echo']) + ".+\n"
         conf = re.sub(rep, "", conf)
         cronPath = web.ctx.session.setupPath + '/cron'
         public.writeFile(file,conf)
         
         sfile = cronPath + '/' + find['echo']
         if os.path.exists(sfile): os.remove(sfile)
         sfile = cronPath + '/' + find['echo'] + '.log'
         if os.path.exists(sfile): os.remove(sfile)
         
         self.CrondReload()
         public.M('crontab').where("id=?",(id,)).delete()
         public.WriteLog('TYPE_CRON', 'CRONTAB_DEL',(find['name'],))
         return public.returnMsg(True, 'DEL_SUCCESS')
     except:
         return public.returnMsg(False, 'DEL_ERROR')
Exemple #6
0
 def SetSshPort(self,get):
     #return public.returnMsg(False,'演示服务器,禁止此操作!');
     port = get.port
     if int(port) < 22 or int(port) > 65535: return public.returnMsg(False,'FIREWALL_SSH_PORT_ERR');
     ports = ['21','25','80','443','8080','888','8888'];
     if port in ports: return public.returnMsg(False,'');
     
     file = '/etc/ssh/sshd_config'
     conf = public.readFile(file)
     
     rep = "#*Port\s+([0-9]+)\s*\n"
     conf = re.sub(rep, "Port "+port+"\n", conf)
     public.writeFile(file,conf)
     
     if self.__isFirewalld:
         self.__Obj.AddAcceptPort(port);
         public.ExecShell('setenforce 0');
         public.ExecShell('sed -i "s#SELINUX=enforcing#SELINUX=disabled#" /etc/selinux/config');
         public.ExecShell("systemctl restart sshd.service")
     elif self.__isUfw:
         public.ExecShell('ufw allow ' + port + '/tcp');
         public.ExecShell("service ssh restart")
     else:
         public.ExecShell('iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport '+port+' -j ACCEPT')
         public.ExecShell("/etc/init.d/sshd restart")
     
     self.FirewallReload()
     public.M('firewall').where("ps=?",('SSH远程管理服务',)).setField('port',port)
     public.WriteLog("TYPE_FIREWALL", "FIREWALL_SSH_PORT",(port,))
     return public.returnMsg(True,'EDIT_SUCCESS') 
Exemple #7
0
 def save(self,keys,param):
     #更新数据
     self.__GetConn()
     self.__DB_CONN.text_factory = str
     try:
         opt = ""
         for key in keys.split(','):
             opt += key + "=?,"
         opt = opt[0:len(opt)-1]
         sql = "UPDATE " + self.__DB_TABLE + " SET " + opt+self.__OPT_WHERE
         
         import public
         public.writeFile('/tmp/test.pl',sql)
                     
         #处理拼接WHERE与UPDATE参数
         tmp = list(param)
         for arg in self.__OPT_PARAM:
             tmp.append(arg)
         self.__OPT_PARAM = tuple(tmp)
         result = self.__DB_CONN.execute(sql,self.__OPT_PARAM)
         self.__close()
         self.__DB_CONN.commit()
         return result.rowcount
     except Exception,ex:
         return "error: " + str(ex)
Exemple #8
0
 def setFpmConfig(self,get):
     version = get.version
     max_children = get.max_children
     start_servers = get.start_servers
     min_spare_servers = get.min_spare_servers
     max_spare_servers = get.max_spare_servers
     pm = get.pm
     
     file = web.ctx.session.setupPath+"/php/"+version+"/etc/php-fpm.conf";
     conf = public.readFile(file);
     
     rep = "\s*pm.max_children\s*=\s*([0-9]+)\s*";
     conf = re.sub(rep, "\npm.max_children = "+max_children, conf);
     
     rep = "\s*pm.start_servers\s*=\s*([0-9]+)\s*";
     conf = re.sub(rep, "\npm.start_servers = "+start_servers, conf);
     
     rep = "\s*pm.min_spare_servers\s*=\s*([0-9]+)\s*";
     conf = re.sub(rep, "\npm.min_spare_servers = "+min_spare_servers, conf);
     
     rep = "\s*pm.max_spare_servers \s*=\s*([0-9]+)\s*";
     conf = re.sub(rep, "\npm.max_spare_servers = "+max_spare_servers+"\n", conf);
     
     rep = "\s*pm\s*=\s*(\w+)\s*";
     conf = re.sub(rep, "\npm = "+pm+"\n", conf);
     
     public.writeFile(file,conf)
     public.phpReload(version);
     public.WriteLog("TYPE_PHP",'PHP_CHILDREN', (version,max_children,start_servers,min_spare_servers,max_spare_servers));
     return public.returnMsg(True, 'SET_SUCCESS');
Exemple #9
0
 def setPHPMaxSize(self,get):
     version = get.version
     max = get.max
     
     if int(max) < 2: return public.returnMsg(False,'PHP_UPLOAD_MAX_ERR')
     
     #设置PHP
     path = web.ctx.session.setupPath+'/php/'+version+'/etc/php.ini'
     conf = public.readFile(path)
     rep = u"\nupload_max_filesize\s*=\s*[0-9]+M"
     conf = re.sub(rep,u'\nupload_max_filesize = '+max+'M',conf)
     rep = u"\npost_max_size\s*=\s*[0-9]+M"
     conf = re.sub(rep,u'\npost_max_size = '+max+'M',conf)
     public.writeFile(path,conf)
     
     if public.get_webserver() == 'nginx':
         #设置Nginx
         path = web.ctx.session.setupPath+'/nginx/conf/nginx.conf'
         conf = public.readFile(path)
         rep = "client_max_body_size\s+([0-9]+)m"
         tmp = re.search(rep,conf).groups()
         if int(tmp[0]) < int(max):
             conf = re.sub(rep,'client_max_body_size '+max+'m',conf)
             public.writeFile(path,conf)
         
     public.serviceReload()
     public.phpReload(version);
     public.WriteLog("TYPE_PHP", "PHP_UPLOAD_MAX",(version,max))
     return public.returnMsg(True,'SET_SUCCESS')
Exemple #10
0
 def setPathInfo(self,get):
     #设置PATH_INFO
     version = get.version
     type = get.type
     if public.get_webserver() == 'nginx':
         path = web.ctx.session.setupPath+'/nginx/conf/enable-php-'+version+'.conf';
         conf = public.readFile(path);
         rep = "\s+#*include\s+pathinfo.conf;";
         if type == 'on':
             conf = re.sub(rep,'\n\t\t\tinclude pathinfo.conf;',conf)
         else:
             conf = re.sub(rep,'\n\t\t\t#include pathinfo.conf;',conf)
         public.writeFile(path,conf)
         public.serviceReload();
     
     path = web.ctx.session.setupPath+'/php/'+version+'/etc/php.ini';
     conf = public.readFile(path);
     rep = "\n*\s*cgi\.fix_pathinfo\s*=\s*([0-9]+)\s*\n";
     status = '0'
     if type == 'on':status = '1'
     conf = re.sub(rep,"\ncgi.fix_pathinfo = "+status+"\n",conf)
     public.writeFile(path,conf)
     public.WriteLog("TYPE_PHP", "PHP_PATHINFO_SUCCESS",(version,type));
     public.phpReload(version);
     return public.returnMsg(True,'SET_SUCCESS');
Exemple #11
0
 def ClosePanel(self,get):
     #return public.returnMsg(False,'体验服务器,禁止修改!')
     filename = 'data/close.pl'
     public.writeFile(filename,'True');
     public.ExecShell("chmod 600 " + filename);
     public.ExecShell("chown root.root " + filename);
     return public.returnMsg(True,'PANEL_CLOSE');
Exemple #12
0
 def GetTaskSpeed(self,get):
     tempFile = '/tmp/panelExec.log'
     freshFile = '/tmp/panelFresh'
     import db
     find = db.Sql().table('tasks').where('status=? OR status=?',('-1','0')).field('id,type,name,execstr').find()
     if not len(find): return public.returnMsg(False,'当前没有任务队列在执行-2!')
     isTask = '/tmp/panelTask.pl'
     public.writeFile(isTask,'True');
     echoMsg = {}
     echoMsg['name'] = find['name']
     echoMsg['execstr'] = find['execstr']
     if find['type'] == 'download':
         import json
         try:
             tmp = public.readFile(tempFile)
             if len(tmp) < 10:
                 return public.returnMsg(False,'当前没有任务队列在执行-3!')
             echoMsg['msg'] = json.loads(tmp)
             echoMsg['isDownload'] = True
         except:
             db.Sql().table('tasks').where("id=?",(find['id'],)).save('status',('0',))
             return public.returnMsg(False,'当前没有任务队列在执行-4!')
     else:
         echoMsg['msg'] = self.GetLastLine(tempFile,20)
         echoMsg['isDownload'] = False
     
     echoMsg['task'] = public.M('tasks').where("status!=?",('1',)).field('id,status,name,type').order("id asc").select()
     return echoMsg
Exemple #13
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
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='******'";
mysql -uroot -e "UPDATE mysql.user SET authentication_string=PASSWORD('${pwd}') WHERE user='******'";
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;
Exemple #14
0
    def RemoveTask(self,get):
        try:
            name = public.M('tasks').where('id=?',(get.id,)).getField('name');
            status = public.M('tasks').where('id=?',(get.id,)).getField('status');
            public.M('tasks').delete(get.id);
            if status == '-1':
                os.system("kill `ps -ef |grep 'python panelSafe.pyc'|grep -v grep|grep -v panelExec|awk '{print $2}'`");
                os.system("kill `ps -ef |grep 'install_soft.sh'|grep -v grep|grep -v panelExec|awk '{print $2}'`");
                os.system("kill `ps aux | grep 'python task.pyc$'|awk '{print $2}'`");
                os.system('''
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 = '/tmp/panelTask.pl';
                public.writeFile(isTask,'True');
                os.system('/etc/init.d/bt start');
        except:
            os.system('/etc/init.d/bt start');
        return public.returnMsg(True,'PLUGIN_DEL');
Exemple #15
0
 def AddPackage(self,get):
     jsonFile = self.__setupPath + '/list.json';
     if not os.path.exists(jsonFile): return public.returnMsg(False,'配置文件不存在!');
     
     data = {}
     data = json.loads(public.readFile(jsonFile));
     for d in data:
         if d['name'] == get.dname: return public.returnMsg(False,'您要添加的程序标识已存在!');
         if d['title'] == get.title: return public.returnMsg(False,'您要添加的程序名称已存在!');
     
     if hasattr(get,'rewrite'): get.rewrite = True;
     
     pinfo = {}
     pinfo['name'] = get.dname;
     pinfo['title'] = get.title;
     pinfo['version'] = get.version;
     pinfo['md5'] = get.md5;
     pinfo['rewrite'] = get.rewrite;
     pinfo['php'] = get.php;
     pinfo['ps'] = get.ps;
     pinfo['shell'] = get.shell;
     pinfo['download'] = get.download;
     data.append(pinfo);
     public.writeFile(jsonFile,json.dumps(data));
     return public.returnMsg(True,'添加成功!');
Exemple #16
0
 def limitAddress(self,type):
     import time
     logFile = 'data/'+web.ctx.ip+'.login';
     timeFile = 'data/'+web.ctx.ip+'_time.login';
     limit = 6;
     outtime = 600;
     try:
         #初始化
         if not os.path.exists(timeFile): public.writeFile(timeFile,str(time.time()));
         if not os.path.exists(logFile): public.writeFile(logFile,'0');
         
         #判断是否解除登陆限制
         time1 = float(public.readFile(timeFile));
         if (time.time() - time1) > outtime: 
             public.writeFile(logFile,'0');
             public.writeFile(timeFile,str(time.time()));
         
         #计数
         num1 = int(public.readFile(logFile));
         if type == '+':
             num1 += 1;
             public.writeFile(logFile,str(num1));
             self.errorNum();
             web.ctx.session.code = True;
             return limit - num1;
         
         #清空
         if type == '-':
             public.ExecShell('rm -f data/*.login');
             web.ctx.session.code = False;
             return 1;
         return limit - num1;
     except:
         return limit;
Exemple #17
0
 def GetFileBody(self,get) :
     get.path = get.path.encode('utf-8');
     if not os.path.exists(get.path):
         if get.path.find('rewrite') == -1:
             return public.returnMsg(False,'FILE_NOT_EXISTS')
         public.writeFile(get.path,'');
     try:
         if os.path.getsize(get.path) > 2097152: return public.returnMsg(False,'不能在线编辑大于2MB的文件!');
         srcBody = public.readFile(get.path)
         
         data = {}
         if srcBody:
             import chardet
             char=chardet.detect(srcBody)
             data['encoding'] = char['encoding']
             if char['encoding'] == 'GB2312': data['encoding'] = 'GBK';
             if char['encoding'] == 'ascii': data['encoding'] = 'utf-8'
             data['data'] = srcBody.decode(data['encoding']).encode('utf-8')
         else:
             data['data'] = srcBody
             data['encoding'] = 'utf-8'
         
         data['status'] = True
         return data
     except Exception,ex:
         return public.returnMsg(False,'FILE_GET_ERR' + str(ex))
Exemple #18
0
def set_mysql_dir(path):
    mysql_dir = '''#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
oldDir=`cat /etc/my.cnf |grep 'datadir'|awk '{print $3}'`
newDir=$1
mkdir $newDir
if [ ! -d "${newDir}" ];then
    echo 'The specified storage path does not exist!'
    exit
fi
echo "Stopping MySQL service..."
service mysqld stop

echo "Copying files, please wait..."
\cp -r -a $oldDir/* $newDir
chown -R mysql.mysql $newDir
sed -i "s#$oldDir#$newDir#" /etc/my.cnf

echo "Starting MySQL service..."
service mysqld start
echo ''
echo 'Successful'
echo '---------------------------------------------------------------------'
echo "Has changed the MySQL storage directory to: $newDir"
echo '---------------------------------------------------------------------'
''';


    public.writeFile('mysql_dir.sh',mysql_dir)
    os.system("/bin/bash mysql_dir.sh " + path)
    os.system("rm -f mysql_dir.sh")
Exemple #19
0
 def SetField(self,name,key,value):
     data = self.GetList(None);
     for i in range(len(data)):
         if data[i]['name'] != name: continue;
         data[i][key] = value;
     
     public.writeFile(self.__list,json.dumps(data));
     return True;
Exemple #20
0
 def remove_ssh_limit(self,get):
     ip = get.ip;
     if not ip in self.get_ssh_limit(): return public.returnMsg(True,'指定白名单不存在!');
     allowConf = public.readFile(self.__ALLOW).strip();
     while allowConf[-1:] == "\n" or allowConf[-1:] == " ": allowConf = allowConf[:-1];
     allowConf = re.sub("\nsshd:"+ip+":allow\n?","\n",allowConf);
     public.writeFile(self.__ALLOW,allowConf+"\n");
     return public.returnMsg(True,'删除成功!');
Exemple #21
0
 def SetMySQLPort(self,get):
     myfile = '/etc/my.cnf';
     mycnf = public.readFile(myfile);
     rep = "port\s*=\s*([0-9]+)\s*\n"
     mycnf = re.sub(rep,'port = ' + get.port + '\n',mycnf);
     public.writeFile(myfile,mycnf);
     os.system('/etc/init.d/mysqld restart');
     return public.returnMsg(True,'EDIT_SUCCESS');
Exemple #22
0
 def checkSSH(self):
     if self.md5sum('/etc/issue') == '3e3c7c4194b12af573ab11c16990c477':
         if self.md5sum('/usr/sbin/sshd') != 'abf7a90c36705ef679298a44af80b10b':  self.result['sshd'] = False
             
     if self.md5sum('/etc/issue') == '6c9222ee501323045d85545853ebea55':
         if self.md5sum('/usr/sbin/sshd') != '4bbf2b12d6b7f234fa01b23dc9822838': self.result['sshd'] = False
     self.result['sshd'] = True
     public.writeFile(self.result['path'] + '/scan.pl',json.dumps(self.result));
Exemple #23
0
 def Set502(self,get):
     filename = 'data/502Task.pl';
     if os.path.exists(filename):
         os.system('rm -f ' + filename)
     else:
         public.writeFile(filename,'True')
     
     return public.returnMsg(True,'SET_SUCCESS');
Exemple #24
0
    def SetupPassword(self,get):
        password = get['password'].strip()
        try:
            rep = "^[\w#@%\.]+$"
            if not re.match(rep, password): return public.returnMsg(False, 'DATABASE_NAME_ERR_T')
            mysql_root = public.M('config').where("id=?",(1,)).getField('mysql_root')
            #修改MYSQL
            result = panelMysql.panelMysql().query("show databases")
            isError=self.IsSqlError(result)
            if  isError != None: 
                #尝试使用新密码
                public.M('config').where("id=?",(1,)).setField('mysql_root',password)
                result = panelMysql.panelMysql().query("show databases")
                isError=self.IsSqlError(result)
                if  isError != None: 
                    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
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='******'";
mysql -uroot -e "UPDATE mysql.user SET authentication_string=PASSWORD('${pwd}') WHERE user='******'";
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("bash mysql_root.sh " + password)
                os.system("rm -f mysql_root.sh")
                
                
            else:
                if '5.7' in public.readFile(web.ctx.session.setupPath + '/mysql/version.pl'):
                    result = panelMysql.panelMysql().execute("update mysql.user set authentication_string=password('" + password + "') where User='******'")
                else:
                    result = panelMysql.panelMysql().execute("update mysql.user set Password=password('" + password + "') where User='******'")
                panelMysql.panelMysql().execute("flush privileges")

            msg = public.getMsg('DATABASE_ROOT_SUCCESS');
            #修改SQLITE
            public.M('config').where("id=?",(1,)).setField('mysql_root',password)  
            public.WriteLog("TYPE_DATABASE", "DATABASE_ROOT_SUCCESS")
            web.ctx.session.config['mysql_root']=password
            return public.returnMsg(True,msg)
        except Exception,ex:
            return public.returnMsg(False,'EDIT_ERROR');
Exemple #25
0
 def UninstallSoft(self,get):
     import web
     public.writeFile('/var/bt_setupPath.conf',web.ctx.session.rootPath)
     get.type = '0'
     if web.ctx.session.server_os['x'] != 'RHEL': get.type = '3'
     execstr = "cd " + web.ctx.session.setupPath + "/panel/install && /bin/bash install_soft.sh "+get.type+" uninstall " + get.name.lower() + " "+ get.version.replace('.','');
     os.system(execstr);
     public.WriteLog('TYPE_SETUP','PLUGIN_UNINSTALL',(get.name,get.version));
     return public.returnMsg(True,"PLUGIN_UNINSTALL");
Exemple #26
0
 def GetQiniuAS(self,get):
     filename = web.ctx.session.setupPath + '/panel/data/'+get.name+'As.conf';
     if not os.path.exists(filename): public.writeFile(filename,'');
     data = {}
     data['AS'] = public.readFile(filename).split('|');
     data['info'] = self.GetLibInfo(get.name);
     if len(data['AS']) < 3:
         data['AS'] = ['','','',''];
     return data;
Exemple #27
0
 def GetIndex(self,get):
     try:
         if hasattr(web.ctx.session,'btyw'): return False;
         result = public.httpGet('https://www.bt.cn/lib/btyw.html');
         public.writeFile('/www/server/panel/plugin/btyw/index.html',result);
         web.ctx.session.btyw = True;
         return True;
     except:
         return False;
Exemple #28
0
 def GetPHPInfo(self,get):
     self.CheckPHPINFO();
     sPath = web.ctx.session.setupPath + '/phpinfo/' + get.version;
     public.ExecShell("rm -rf /www/server/phpinfo/*");
     public.ExecShell("mkdir -p " + sPath);
     public.writeFile(sPath + '/phpinfo.php','<?php phpinfo(); ?>');
     phpinfo = public.httpGet('http://127.0.0.2/' + get.version + '/phpinfo.php');
     os.system("rm -rf " + sPath);
     return phpinfo;
Exemple #29
0
    def CheckStatusConf(self):
        if public.get_webserver() != 'nginx': return;
        filename = web.ctx.session.setupPath + '/panel/vhost/nginx/phpfpm_status.conf';
        if os.path.exists(filename): return;
        
        conf = '''server {
    listen 80;
    server_name 127.0.0.1;
    allow 127.0.0.1;
    location /nginx_status {
        stub_status on;
        access_log off;
    }
    location /phpfpm_52_status {
        fastcgi_pass unix:/tmp/php-cgi-52.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$fastcgi_script_name;
    }
    location /phpfpm_53_status {
        fastcgi_pass unix:/tmp/php-cgi-53.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$fastcgi_script_name;
    }
    location /phpfpm_54_status {
        fastcgi_pass unix:/tmp/php-cgi-54.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$fastcgi_script_name;
    }
    location /phpfpm_55_status {
        fastcgi_pass unix:/tmp/php-cgi-55.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$fastcgi_script_name;
    }
    location /phpfpm_56_status {
        fastcgi_pass unix:/tmp/php-cgi-56.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$fastcgi_script_name;
    }
    location /phpfpm_70_status {
        fastcgi_pass unix:/tmp/php-cgi-70.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$fastcgi_script_name;
    }
    location /phpfpm_71_status {
        fastcgi_pass unix:/tmp/php-cgi-71.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$fastcgi_script_name;
    }
    location /phpfpm_72_status {
        fastcgi_pass unix:/tmp/php-cgi-72.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$fastcgi_script_name;
    }
}'''
        public.writeFile(filename,conf);
        public.serviceReload();
Exemple #30
0
 def AutoUpdatePanel(self,get):
     #return public.returnMsg(False,'体验服务器,禁止修改!')
     filename = 'data/autoUpdate.pl'
     if os.path.exists(filename):
         os.remove(filename);
     else:
         public.writeFile(filename,'True');
         public.ExecShell("chmod 600 " + filename);
         public.ExecShell("chown root.root " + filename);
     return public.returnMsg(True,'SET_SUCCESS');
Exemple #31
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 = "Basis data ["+name+"] tidak ada!"
            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 = "Backup basis data ["+name+"] gagal!"
            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 = "Sukses membackup basis data ["+name+"], dengan waktu ["+str(round(outTime,2))+"] detik";
        public.WriteLog('Crontab',log)
        print "★["+endDate+"] " + log
        print "|---Simpan backup yang terbaru ["+count+"]"
        print "|---Nama file: "+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 "|---File cadangan yang kedaluwarsa telah dibersihkan:" + backup['filename']
                if num < 1: break;
Exemple #32
0
    def ServiceAdmin(self, get=None):
        #服务管理
        if get.name == 'mysqld':
            public.CheckMyCnf()
            self.__check_mysql_path()

        if get.name == 'phpmyadmin':
            import ajax
            get.status = 'True'
            ajax.ajax().setPHPMyAdmin(get)
            return public.returnMsg(True, 'SYS_EXEC_SUCCESS')

        #检查httpd配置文件
        if get.name == 'apache' or get.name == 'httpd':
            get.name = 'httpd'
            if not os.path.exists(self.setupPath + '/apache/bin/apachectl'):
                return public.returnMsg(True, 'SYS_NOT_INSTALL_APACHE')
            vhostPath = self.setupPath + '/panel/vhost/apache'
            if not os.path.exists(vhostPath):
                public.ExecShell('mkdir ' + vhostPath)
                public.ExecShell('/etc/init.d/httpd start')

            if get.type == 'start':
                public.ExecShell('/etc/init.d/httpd stop')
                self.kill_port()

            result = public.ExecShell('ulimit -n 8192 ; ' + self.setupPath +
                                      '/apache/bin/apachectl -t')
            if result[1].find('Syntax OK') == -1:
                public.WriteLog("TYPE_SOFT", 'SYS_EXEC_ERR', (str(result), ))
                return public.returnMsg(False, 'SYS_CONF_APACHE_ERR',
                                        (result[1].replace("\n", '<br>'), ))

            if get.type == 'restart':
                public.ExecShell('pkill -9 httpd')
                public.ExecShell('/etc/init.d/httpd start')
                time.sleep(0.5)

        #检查nginx配置文件
        elif get.name == 'nginx':
            vhostPath = self.setupPath + '/panel/vhost/rewrite'
            if not os.path.exists(vhostPath):
                public.ExecShell('mkdir ' + vhostPath)
            vhostPath = self.setupPath + '/panel/vhost/nginx'
            if not os.path.exists(vhostPath):
                public.ExecShell('mkdir ' + vhostPath)
                public.ExecShell('/etc/init.d/nginx start')

            result = public.ExecShell('ulimit -n 8192 ; nginx -t -c ' +
                                      self.setupPath +
                                      '/nginx/conf/nginx.conf')
            if result[1].find('perserver') != -1:
                limit = self.setupPath + '/nginx/conf/nginx.conf'
                nginxConf = public.readFile(limit)
                limitConf = "limit_conn_zone $binary_remote_addr zone=perip:10m;\n\t\tlimit_conn_zone $server_name zone=perserver:10m;"
                nginxConf = nginxConf.replace(
                    "#limit_conn_zone $binary_remote_addr zone=perip:10m;",
                    limitConf)
                public.writeFile(limit, nginxConf)
                public.ExecShell('/etc/init.d/nginx start')
                return public.returnMsg(True, 'SYS_CONF_NGINX_REP')

            if result[1].find('proxy') != -1:
                import panelSite
                panelSite.panelSite().CheckProxy(get)
                public.ExecShell('/etc/init.d/nginx start')
                return public.returnMsg(True, 'SYS_CONF_NGINX_REP')

            #return result
            if result[1].find('successful') == -1:
                public.WriteLog("TYPE_SOFT", 'SYS_EXEC_ERR', (str(result), ))
                return public.returnMsg(False, 'SYS_CONF_NGINX_ERR',
                                        (result[1].replace("\n", '<br>'), ))

            if get.type == 'start':
                self.kill_port()
                time.sleep(0.5)
        if get.name == 'redis':
            redis_init = '/etc/init.d/redis'
            if os.path.exists(redis_init):
                init_body = public.ReadFile(redis_init)
                if init_body.find('pkill -9 redis') == -1:
                    public.ExecShell("wget -O " + redis_init + " " +
                                     public.get_url() + '/init/redis.init')
                    public.ExecShell("chmod +x " + redis_init)

        #执行
        execStr = "/etc/init.d/" + get.name + " " + get.type
        if execStr == '/etc/init.d/pure-ftpd reload':
            execStr = self.setupPath + '/pure-ftpd/bin/pure-pw mkdb ' + self.setupPath + '/pure-ftpd/etc/pureftpd.pdb'
        if execStr == '/etc/init.d/pure-ftpd start':
            os.system('pkill -9 pure-ftpd')
        if execStr == '/etc/init.d/tomcat reload':
            execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start'
        if execStr == '/etc/init.d/tomcat restart':
            execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start'

        if get.name != 'mysqld':
            result = public.ExecShell(execStr)
        else:
            os.system(execStr)
            result = []
            result.append('')
            result.append('')

        if result[1].find('nginx.pid') != -1:
            public.ExecShell('pkill -9 nginx && sleep 1')
            public.ExecShell('/etc/init.d/nginx start')
        if get.type != 'test':
            public.WriteLog("TYPE_SOFT", 'SYS_EXEC_SUCCESS', (execStr, ))

        if len(result[1]
               ) > 1 and get.name != 'pure-ftpd' and get.name != 'redis':
            return public.returnMsg(
                False, '<p>警告消息: <p>' + result[1].replace('\n', '<br>'))
        return public.returnMsg(True, 'SYS_EXEC_SUCCESS')
Exemple #33
0
    def set_ssl_check(self, siteName):
        rewriteConf = '''#一键申请SSL证书验证目录相关设置
location ~ \.well-known{
    allow all;
}'''
        public.writeFile('vhost/rewrite/' + siteName + '.conf', rewriteConf)
Exemple #34
0
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))

#获取当前模板
templatesConf = 'data/templates.pl';
if os.path.exists('templates/index.html'): os.system('rm -f templates/*.html');
if not os.path.exists(templatesConf): public.writeFile(templatesConf,'default');
templateName = public.readFile(templatesConf);

#初始化模板引擎
render = web.template.render('templates/' + templateName + '/',base='template',globals={'session': session,'web':web})

class panelIndex(common.panelAdmin):
    def GET(self):
        import system
        data = system.system().GetConcifInfo()
        data['siteCount'] = public.M('sites').count()
        data['ftpCount'] = public.M('ftps').count()
        data['databaseCount'] = public.M('databases').count()
        data['lan'] = public.getLan('index')
        return render.index(data)
    
Exemple #35
0
 def clean_panel_error_logs(self,get):
     filename = 'logs/error.log'
     public.writeFile(filename,'')
     public.WriteLog('面板配置','清空面板运行日志')
     return public.returnMsg(True,'已清空!')
Exemple #36
0
                              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))

#获取当前模板
templatesConf = 'data/templates.pl'
if os.path.exists('templates/index.html'): os.system('rm -f templates/*.html')
if not os.path.exists(templatesConf):
    public.writeFile(templatesConf, 'default')
templateName = public.readFile(templatesConf)

#初始化模板引擎
render = web.template.render('templates/' + templateName + '/',
                             base='template',
                             globals={
                                 'session': session,
                                 'web': web
                             })


# 打开面板首页
class panelIndex(common.panelAdmin):
    def GET(self):
        import system
Exemple #37
0
 def POST(self):
     get = web.input(backup={},data=[]);
     public.writeFile('test.pl',get['backup'].file.read());
     return public.returnJson(True,'OK!')
Exemple #38
0
    def __init__(self):
        # QQ邮箱基础实例化
        if not os.path.exists(self.__mail_list_data):
            ret = []
            public.writeFile(self.__mail_list_data, json.dumps(ret))
        else:
            try:
                mail_data = json.loads(public.ReadFile(self.__mail_list_data))
                self.__mail_list = mail_data
            except:
                ret = []
                public.writeFile(self.__mail_list_data, json.dumps(ret))

        if not os.path.exists(self.__mail_config):
            ret = []
            public.writeFile(self.__mail_config, json.dumps(ret))
        else:
            try:
                qq_mail_info = json.loads(public.ReadFile(self.__mail_config))
                if 'qq_mail' in qq_mail_info and 'qq_stmp_pwd' in qq_mail_info and 'hosts' in qq_mail_info:
                    self.__qq_mail_user = qq_mail_info
            except:
                ret = []
                public.writeFile(self.__mail_config, json.dumps(ret))

        # 初始化钉钉
        if not os.path.exists(self.__dingding_config):
            ret = []
            public.writeFile(self.__dingding_config, json.dumps(ret))
        else:
            try:
                dingding_info = json.loads(
                    public.ReadFile(self.__dingding_config))
                if 'dingding_url' in dingding_info and 'isAtAll' in dingding_info and 'user' in dingding_info:
                    self.__dingding_info = dingding_info
            except:
                ret = []
                public.writeFile(self.__dingding_config, json.dumps(ret))

        # 初始化微信
        if not os.path.exists(self.__weixin_config):
            ret = []
            public.writeFile(self.__weixin_config, json.dumps(ret))
        else:
            try:
                weixin_info = json.loads(public.ReadFile(self.__weixin_config))
                if 'corpid' in weixin_info and 'corpsecret' in weixin_info and 'user_id' in weixin_info and 'agentid' in weixin_info:
                    self.__weixin_info = weixin_info
            except:
                ret = []
                public.writeFile(self.__weixin_config, json.dumps(ret))
Exemple #39
0
    def apple_lest_cert(self, get):

        data = {}
        data['siteName'] = get.siteName
        data['domains'] = json.loads(get.domains)
        data['email'] = get.email
        data['dnssleep'] = get.dnssleep

        if len(data['domains']) <= 0:
            return public.returnMsg(False, '申请域名列表不能为空.')

        data['first_domain'] = data['domains'][0]

        path = self.setupPath + '/panel/vhost/cert/' + data['siteName']
        if not os.path.exists(path): os.makedirs(path)

        # 检查是否自定义证书
        partnerOrderId = path + '/partnerOrderId'
        if os.path.exists(partnerOrderId): os.remove(partnerOrderId)
        #清理续签key
        re_key = path + '/account_key.key'
        if os.path.exists(re_key): os.remove(re_key)

        re_password = path + '/password'
        if os.path.exists(re_password): os.remove(re_password)

        data['account_key'] = None
        if hasattr(get, 'dnsapi'):
            if not 'app_root' in get: get.app_root = '0'
            data['app_root'] = get.app_root
            domain_list = data['domains']
            if data['app_root'] == '1':
                domain_list = []
                data['first_domain'] = self.get_root_domain(
                    data['first_domain'])
                for domain in data['domains']:
                    rootDoamin = self.get_root_domain(domain)
                    if not rootDoamin in domain_list:
                        domain_list.append(rootDoamin)
                    if not "*." + rootDoamin in domain_list:
                        domain_list.append("*." + rootDoamin)
                data['domains'] = domain_list
            if get.dnsapi == 'dns':
                domain_path = path + '/domain_txt_dns_value.json'
                if hasattr(get, 'renew'):  #验证
                    data['renew'] = True
                    dns = json.loads(public.readFile(domain_path))
                    data['dns'] = dns
                    certificate = self.crate_let_by_oper(data)
                else:
                    #手动解析提前返回
                    result = self.crate_let_by_oper(data)
                    if 'status' in result and not result['status']:
                        return result
                    result['status'] = True
                    public.writeFile(domain_path, json.dumps(result))
                    result['msg'] = '获取成功,请手动解析域名'
                    result['code'] = 2
                    return result
            elif get.dnsapi == 'dns_bt':
                data['dnsapi'] = get.dnsapi
                certificate = self.crate_let_by_dns(data)
            else:
                data['dnsapi'] = get.dnsapi
                data['dns_param'] = get.dns_param.split('|')
                certificate = self.crate_let_by_dns(data)
        else:
            #文件验证
            data['site_dir'] = get.site_dir
            certificate = self.crate_let_by_file(data)

        if not certificate['status']:
            return public.returnMsg(False, certificate['msg'])

        #保存续签
        cpath = self.setupPath + '/panel/vhost/cert/crontab.json'
        config = {}
        if os.path.exists(cpath):
            config = json.loads(public.readFile(cpath))
        config[data['siteName']] = data
        public.writeFile(cpath, json.dumps(config))
        public.set_mode(cpath, 600)

        #存储证书
        public.writeFile(path + "/privkey.pem", certificate['key'])
        public.writeFile(path + "/fullchain.pem",
                         certificate['cert'] + certificate['ca_data'])
        public.writeFile(path + "/account_key.key",
                         certificate['account_key'])  #续签KEY

        #转为IIS证书
        p12 = self.dump_pkcs12(certificate['key'],
                               certificate['cert'] + certificate['ca_data'],
                               certificate['ca_data'], data['first_domain'])
        pfx_buffer = p12.export()
        public.writeFile(path + "/fullchain.pfx", pfx_buffer, 'wb+')
        public.writeFile(path + "/README", "let")

        #计划任务续签
        self.set_crond()
        return public.returnMsg(True, '申请成功.')
Exemple #40
0
 def __write_site_config(self, site_config):
     public.writeFile(self.__path + 'site.json', json.dumps(site_config))
     public.serviceReload()
Exemple #41
0
 def __write_total(self, total):
     return public.writeFile(self.__path + 'total.json', json.dumps(total))
Exemple #42
0
 def __write_rule(self, ruleName, rule):
     path = self.__path + 'rule/' + ruleName + '.json'
     public.writeFile(path, json.dumps(rule))
     public.serviceReload()
Exemple #43
0
    def __init__(self):
        if not os.path.exists(self._check_all_site):
            ret = []
            public.writeFile(self._check_all_site, json.dumps(ret))
        else:
            ret = public.ReadFile(self._check_all_site)
            self._check_site_all_data = json.loads(ret)

        if not os.path.exists(self._check_all_date):
            ret = []
            public.writeFile(self._check_all_date, json.dumps(ret))
        else:
            ret = public.ReadFile(self._check_all_date)
            self._check_date_all_data = json.loads(ret)
        if not os.path.exists('/www/backup/site_backup'):
            os.system('mkdir /www/backup/site_backup -p')
        if not os.path.exists('/www/backup/database_backup'):
            os.system('mkdir /www/backup/database_backup')
        if not os.path.exists(self._check_database):
            ret = []
            public.writeFile(self._check_database, json.dumps(ret))
        else:
            ret = public.ReadFile(self._check_database)
            self._check_database_data = json.loads(ret)
        if not os.path.exists(self._check_site):
            ret = []
            public.writeFile(self._check_site, json.dumps(ret))
        else:
            ret = public.ReadFile(self._check_site)
            self._check_site_data = json.loads(ret)
        if not os.path.exists(self._chekc_path):
            ret = []
            public.writeFile(self._chekc_path, json.dumps(ret))
        else:
            ret = public.ReadFile(self._chekc_path)
            self._check_path_data = json.loads(ret)

        #下载所需要的
        if not os.path.exists(self._down_path):
            ret = []
            public.writeFile(self._down_path, json.dumps(ret))
        else:
            ret = public.ReadFile(self._down_path)
            self._down_path_data = json.loads(ret)
Exemple #44
0
    def get_task_log(self, id, task_type, num=5):
        log_file = self.__task_path + str(id) + '.log'
        if not os.path.exists(log_file):
            data = ''
            if (task_type == '1'):
                data = {
                    'name': '下载文件',
                    'total': 0,
                    'used': 0,
                    'pre': 0,
                    'speed': 0,
                    'time': 0
                }
            return data

        if (task_type == '1'):
            total = 0
            if not os.path.exists(self.down_log_total_file):
                f = open(log_file, 'r')
                head = f.read(4096)
                content_length = re.findall("Length:\s+(\d+)", head)
                if content_length:
                    total = int(content_length[0])
                    public.writeFile(self.down_log_total_file,
                                     content_length[0])
            else:
                total = public.readFile(self.down_log_total_file)
                if not total:
                    total = 0
                total = int(total)

            filename = public.M(self.__table).where('id=?',
                                                    (id, )).getField('shell')

            speed_tmp = public.ExecShell("tail -n 2 {}".format(log_file))[0]
            speed_total = re.findall(
                "([\d\.]+[BbKkMmGg]).+\s+(\d+)%\s+([\d\.]+[KMBGkmbg])\s+(\w+[sS])",
                speed_tmp)
            if not speed_total:
                data = {
                    'name': '下载文件{}'.format(filename),
                    'total': 0,
                    'used': 0,
                    'pre': 0,
                    'speed': 0,
                    'time': 0
                }
            else:
                speed_total = speed_total[0]
                used = speed_total[0]
                if speed_total[0].lower().find('k') != -1:
                    used = public.to_size(
                        float(speed_total[0].lower().replace('k', '')) * 1024)
                    u_time = speed_total[3].replace('h', '小时').replace(
                        'm', '分').replace('s', '秒')
                data = {
                    'name': '下载文件{}'.format(filename),
                    'total': total,
                    'used': used,
                    'pre': speed_total[1],
                    'speed': speed_total[2],
                    'time': u_time
                }
        else:
            data = public.ExecShell("tail -n {} {}".format(num, log_file))[0]
            n = 0
            if type(data) == list: return ''
            data = data.replace('\x08', '').replace('\n', '<br>')
        return data
Exemple #45
0
 def write_sites(self,data):
     public.writeFile(self.__plugin_path + '/sites.json',json.dumps(data))
     os.system('/etc/init.d/bt_tamper_proof restart')
Exemple #46
0
 def __read_config(self):
     if not os.path.exists(self.__confPath):
         public.writeFile(self.__confPath, '[]')
     upBody = public.readFile(self.__confPath)
     return json.loads(upBody)
Exemple #47
0
def write_run_script_log(_log,rn='\n'):
    _log_file = '/www/server/panel/logs/run_script.log'
    public.writeFile(_log_file,_log + rn,'a+')
Exemple #48
0
 def write_lock(self):
     self.is_lock()
     public.writeFile(self.__LOCK, "True")
Exemple #49
0
 def scan_login(self, get):
     # 用于小程序
     data = public.GetRandomString(48) + ':' + str(time.time())
     public.writeFile(self.app_path + "login.pl", data)
     return public.returnMsg(True, '扫码成功, 正在登录')
Exemple #50
0
    def SetRedirect(self, get):
        ng_file = self.setupPath + "/panel/vhost/nginx/" + get.sitename + ".conf"
        ap_file = self.setupPath + "/panel/vhost/apache/" + get.sitename + ".conf"
        p_conf = self.__read_config(self.__redirectfile)
        # nginx
        # 构建重定向配置
        if int(get.type) == 1:
            domainstr = """
        if ($host ~ '^%s'){
            return %s %s%s;
        }
"""
            pathstr = """
        rewrite ^%s(.*) %s%s %s;
"""
            rconf = "#REWRITE-START"
            tourl = get.tourl
            # if tourl[-1] == "/":
            #     tourl = tourl[:-1]
            if get.domainorpath == "domain":
                domains = json.loads(get.redirectdomain)
                holdpath = int(get.holdpath)
                if holdpath == 1:
                    for sd in domains:
                        rconf += domainstr % (sd, get.redirecttype, tourl,
                                              "$request_uri")
                else:
                    for sd in domains:
                        rconf += domainstr % (sd, get.redirecttype, tourl, "")
            if get.domainorpath == "path":
                redirectpath = get.redirectpath
                if get.redirecttype == "301":
                    redirecttype = "permanent"
                else:
                    redirecttype = "redirect"
                if int(get.holdpath) == 1 and redirecttype == "permanent":
                    rconf += pathstr % (redirectpath, tourl, "$1",
                                        redirecttype)
                elif int(get.holdpath) == 0 and redirecttype == "permanent":
                    rconf += pathstr % (redirectpath, tourl, "", redirecttype)
                elif int(get.holdpath) == 1 and redirecttype == "redirect":
                    rconf += pathstr % (redirectpath, tourl, "$1",
                                        redirecttype)
                elif int(get.holdpath) == 0 and redirecttype == "redirect":
                    rconf += pathstr % (redirectpath, tourl, "", redirecttype)
            rconf += "#REWRITE-END"
            nginxrconf = rconf

            # 设置apache重定向

            domainstr = """
	<IfModule mod_rewrite.c>
		RewriteEngine on
		RewriteCond %s{HTTP_HOST} ^%s [NC]
		RewriteRule ^(.*) %s%s [L,R=%s]
	</IfModule>
"""
            pathstr = """
	<IfModule mod_rewrite.c>
		RewriteEngine on
		RewriteRule ^%s(.*) %s%s [L,R=%s]
	</IfModule>
"""
            rconf = "#REWRITE-START"
            if get.domainorpath == "domain":
                domains = json.loads(get.redirectdomain)
                holdpath = int(get.holdpath)
                if holdpath == 1:
                    for sd in domains:
                        rconf += domainstr % ("%", sd, tourl, "$1",
                                              get.redirecttype)
                else:
                    for sd in domains:
                        rconf += domainstr % ("%", sd, tourl, "",
                                              get.redirecttype)

            if get.domainorpath == "path":
                holdpath = int(get.holdpath)
                if holdpath == 1:
                    rconf += pathstr % (get.redirectpath, tourl, "$1",
                                        get.redirecttype)
                else:
                    rconf += pathstr % (get.redirectpath, tourl, "",
                                        get.redirecttype)
            rconf += "#REWRITE-END"
            apacherconf = rconf

            redirectname_md5 = self.__calc_md5(get.redirectname)
            for w in ["nginx", "apache"]:
                redirectfile = "%s/panel/vhost/%s/redirect/%s/%s_%s.conf" % (
                    self.setupPath, w, get.sitename, redirectname_md5,
                    get.sitename)
                redirectdir = "%s/panel/vhost/%s/redirect/%s" % (
                    self.setupPath, w, get.sitename)

                if not os.path.exists(redirectdir):
                    public.ExecShell("mkdir -p %s" % redirectdir)
                if w == "nginx":
                    public.writeFile(redirectfile, nginxrconf)
                else:
                    public.writeFile(redirectfile, apacherconf)
            isError = public.checkWebConfig()
            if (isError != True):
                if public.get_webserver() == "nginx":
                    shutil.copyfile('/tmp/ng_file_bk.conf', ng_file)
                else:
                    shutil.copyfile('/tmp/ap_file_bk.conf', ap_file)
                for i in range(len(p_conf) - 1, -1, -1):
                    if get.sitename == p_conf[i]["sitename"] and p_conf[i][
                            "redirectname"]:
                        del (p_conf[i])
                return public.returnMsg(
                    False,
                    '%s<br><a style="color:red;">' % public.GetMsg("HAVE_ERR")
                    + isError.replace("\n", '<br>') + '</a>')

        else:
            redirectname_md5 = self.__calc_md5(get.redirectname)
            redirectfile = "%s/panel/vhost/%s/redirect/%s/%s_%s.conf"
            for w in ["apache", "nginx"]:
                rf = redirectfile % (self.setupPath, w, get.sitename,
                                     redirectname_md5, get.sitename)
                if os.path.exists(rf):
                    os.remove(rf)
Exemple #51
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
Exemple #52
0
 def __read_config(self, path):
     if not os.path.exists(path):
         public.writeFile(path, '[]')
     upBody = public.readFile(path)
     if not upBody: upBody = '[]'
     return json.loads(upBody)
Exemple #53
0
 def SetSessionConf(self, get):
     g = get.save_handler
     ip = get.ip
     port = get.port
     passwd = get.passwd
     if g != "files":
         iprep = "(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})"
         if not re.search(iprep, ip):
             return public.returnMsg(False, '请输入正确的IP地址')
         try:
             port = int(port)
             if port >= 65535 or port < 1:
                 return public.returnMsg(False, '请输入正确的端口号')
         except:
             return public.returnMsg(False, '请输入正确的端口号')
         prep = "[\~\`\/\=]"
         if re.search(prep,passwd):
             return public.returnMsg(False, '请不要输入以下特殊字符 " ~ ` / = "')
     filename = '/www/server/php/' + get.version + '/etc/php.ini'
     phpini = public.readFile(filename)
     rep = 'session.save_handler\s*=\s*(.+)\r?\n'
     val = 'session.save_handler = ' + g + '\n'
     phpini = re.sub(rep, val, phpini)
     if g == "memcached":
         if not re.search("memcached.so", phpini):
             return public.returnMsg(False, '请先安装%s扩展' % g)
         rep = '\nsession.save_path\s*=\s*(.+)\r?\n'
         val = '\nsession.save_path = "%s:%s" \n' % (ip,port)
         if re.search(rep, phpini):
             phpini = re.sub(rep, val, phpini)
         else:
             phpini = re.sub('\n;session.save_path = "/tmp"', '\n;session.save_path = "/tmp"' + val, phpini)
     if g == "memcache":
         if not re.search("memcache.so",phpini):
             return public.returnMsg(False, '请先安装%s扩展' % g)
         rep = '\nsession.save_path\s*=\s*(.+)\r?\n'
         val = '\nsession.save_path = "tcp://%s:%s"\n' % (ip, port)
         if re.search(rep, phpini):
             phpini = re.sub(rep, val, phpini)
         else:
             phpini = re.sub('\n;session.save_path = "/tmp"', '\n;session.save_path = "/tmp"' + val, phpini)
     if g == "redis":
         if not re.search("redis.so",phpini):
             return public.returnMsg(False, '请先安装%s扩展' % g)
         if passwd:
             passwd = "?auth=" + passwd
         else:
             passwd = ""
         rep = '\nsession.save_path\s*=\s*(.+)\r?\n'
         val = '\nsession.save_path = "tcp://%s:%s%s"\n' % (ip, port, passwd)
         res = re.search(rep, phpini)
         if res:
             phpini = re.sub(rep, val, phpini)
         else:
             phpini = re.sub('\n;session.save_path = "/tmp"', '\n;session.save_path = "/tmp"' + val, phpini)
     if g == "files":
         rep = '\nsession.save_path\s*=\s*(.+)\r?\n'
         val = '\nsession.save_path = "/tmp"\n'
         if re.search(rep, phpini):
             phpini = re.sub(rep, val, phpini)
         else:
             phpini = re.sub('\n;session.save_path = "/tmp"', '\n;session.save_path = "/tmp"' + val, phpini)
     public.writeFile(filename, phpini)
     public.ExecShell('/etc/init.d/php-fpm-' + get.version + ' reload')
     return public.returnMsg(True, 'SET_SUCCESS')
Exemple #54
0
 def scan_login(self, get):
     # 用于小程序
     data = public.GetRandomString(48) + ':' + str(time.time())
     public.writeFile(self.app_path + "login.pl", data)
     return public.returnMsg(True, 'SCAN_QRCORE_SUCCESS_LOGGING_IN')
Exemple #55
0
 def __write_mail_conf(self, data):
     return public.writeFile(self.__emailPath, json.dumps(data))
Exemple #56
0
def bt_cli():
    raw_tip = "==============================================="
    print("===============%s==================" % public.GetMsg("PANEL_SHELL"))
    print("(01) %s           (08) %s" %
          (public.GetMsg("RESTART_PANEL"), public.GetMsg("CHANGE_PANEL_PORT")))
    print("(02) %s           (09) %s" %
          (public.GetMsg("STOP_PANEL"), public.GetMsg("CLEAR_PANEL_CACHE")))
    print("(03) %s           (10) %s" %
          (public.GetMsg("START_PANEL"), public.GetMsg("CLEAR_PANEL_LIMIT")))
    print("(04) %s           (11) %s" %
          (public.GetMsg("RELOAD_PANEL"), public.GetMsg("CANCEL_ENTRY")))
    print("(05) %s           (12) %s" % (public.GetMsg("CHANGE_PANEL_PASS"),
                                         public.GetMsg("CANCEL_DOMAIN_BIND")))
    print(
        "(06) %s         (13) %s" %
        (public.GetMsg("CHANGE_PANEL_USER"), public.GetMsg("CANCEL_IP_LIMIT")))
    print("(07) %s      (14) %s" % (public.GetMsg("CHANGE_MYSQL_PASS_FORCE"),
                                    public.GetMsg("GET_PANEL_DEFAULT_MSG")))
    print("(00) %s                   (15) %s" %
          (public.GetMsg("CANCEL"), public.GetMsg("CLEAR_SYS_RUBBISH")))
    print(raw_tip)
    try:
        u_input = input(public.GetMsg("INPUT_CMD_NUM"))
        if sys.version_info[0] == 3: u_input = int(u_input)
    except:
        u_input = 0
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    if not u_input in nums:
        print(raw_tip)
        print(public.GetMsg("CANCELLED"))
        exit()

    print(raw_tip)
    print(public.GetMsg("EXECUTING", (u_input, )))
    print(raw_tip)

    if u_input == 1:
        os.system("/etc/init.d/bt restart")
    elif u_input == 2:
        os.system("/etc/init.d/bt stop")
    elif u_input == 3:
        os.system("/etc/init.d/bt start")
    elif u_input == 4:
        os.system("/etc/init.d/bt reload")
    elif u_input == 5:
        if sys.version_info[0] == 2:
            input_pwd = raw_input(public.GetMsg("INPUT_NEW_PASS"))
        else:
            input_pwd = input(public.GetMsg("INPUT_NEW_PASS"))
        set_panel_pwd(input_pwd.strip(), True)
    elif u_input == 6:
        if sys.version_info[0] == 2:
            input_user = raw_input(public.GetMsg("INPUT_NEW_USER"))
        else:
            input_user = input(public.GetMsg("INPUT_NEW_USER"))
        set_panel_username(input_user.strip())
    elif u_input == 7:
        if sys.version_info[0] == 2:
            input_mysql = raw_input(public.GetMsg("INPUT_NEW_MYSQL_PASS"))
        else:
            input_mysql = input(public.GetMsg("INPUT_NEW_MYSQL_PASS"))
        if not input_mysql:
            print(public.GetMsg("PASS_NOT_EMPTY"))
            return

        if len(input_mysql) < 8:
            print(public.GetMsg("PASS_LEN_ERR"))
            return

        import re
        rep = "^[\w@\._]+$"
        if not re.match(rep, input_mysql):
            print(public.GetMsg("PASS_SPECIAL_CHARACTRES_ERR"))
            return

        print(input_mysql)
        set_mysql_root(input_mysql.strip())
    elif u_input == 8:
        input_port = input(public.GetMsg("INPUT_NEW_PANEL_PORT"))
        if sys.version_info[0] == 3: input_port = int(input_port)
        if not input_port:
            print(public.GetMsg("INPUT_PANEL_PORT_ERR"))
            return
        if input_port in [80, 443, 21, 20, 22]:
            print(public.GetMsg("CANT_USE_USUALLY_PORT_ERR"))
            return
        old_port = int(public.readFile('data/port.pl'))
        if old_port == input_port:
            print(public.GetMsg("NEW_PORT_SAMEAS_OLD"))
            return

        is_exists = public.ExecShell("lsof -i:%s" % input_port)
        if len(is_exists[0]) > 5:
            print(public.GetMsg("PORT_ALREADY_IN_USE"))
            return

        public.writeFile('data/port.pl', str(input_port))
        if os.path.exists("/usr/bin/firewall-cmd"):
            os.system(
                "firewall-cmd --permanent --zone=public --add-port=%s/tcp" %
                input_port)
            os.system("firewall-cmd --reload")
        elif os.path.exists("/etc/sysconfig/iptables"):
            os.system(
                "iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport %s -j ACCEPT"
                % input_port)
            os.system("service iptables save")
        else:
            os.system("ufw allow %s" % input_port)
            os.system("ufw reload")
        print("CHANGE_PORT_SUCCESS", (input_port, ))
        print("CLOUD_RELEASE_PORT", (input_port, ))
    elif u_input == 9:
        sess_file = '/dev/shm/session.db'
        if os.path.exists(sess_file): os.remove(sess_file)
        os.system("/etc/init.d/bt reload")
    elif u_input == 10:
        os.system("/etc/init.d/bt reload")
    elif u_input == 11:
        auth_file = 'data/admin_path.pl'
        if os.path.exists(auth_file): os.remove(auth_file)
        os.system("/etc/init.d/bt reload")
        print(public.GetMsg("CHANGE_LIMITED_CANCEL"))
    elif u_input == 12:
        auth_file = 'data/domain.conf'
        if os.path.exists(auth_file): os.remove(auth_file)
        os.system("/etc/init.d/bt reload")
        print(public.GetMsg("CHANGE_DOMAIN_CANCEL"))
    elif u_input == 13:
        auth_file = 'data/limitip.conf'
        if os.path.exists(auth_file): os.remove(auth_file)
        os.system("/etc/init.d/bt reload")
        print(public.GetMsg("CHANGE_IP_CANCEL"))
    elif u_input == 14:
        os.system("/etc/init.d/bt default")
    elif u_input == 15:
        ClearSystem()
Exemple #57
0
    def GetShell(self, param):
        #try:
        type = param['sType']
        if type == 'toFile':
            shell = param.sFile
        else:
            head = "#!/bin/bash\nPATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin\nexport PATH\n"
            log = '-access_log'
            if public.get_webserver() == 'nginx':
                log = '.log'
            if type in [
                    'site', 'path'
            ] and param['sBody'] != 'undefined' and len(param['sBody']) > 1:
                exports = param['sBody'].replace("\r\n",
                                                 "\n").replace("\n", ",")
                head += "BT_EXCLUDE=\"" + exports.strip(
                ) + "\"\nexport BT_EXCLUDE\n"
            wheres = {
                'path':
                head + "python " + public.GetConfigValue('setup_path') +
                "/panel/script/backup.py path " + param['sName'] + " " +
                str(param['save']),
                'site':
                head + "python " + public.GetConfigValue('setup_path') +
                "/panel/script/backup.py site " + param['sName'] + " " +
                str(param['save']),
                'database':
                head + "python " + public.GetConfigValue('setup_path') +
                "/panel/script/backup.py database " + param['sName'] + " " +
                str(param['save']),
                'logs':
                head + "python " + public.GetConfigValue('setup_path') +
                "/panel/script/logsBackup " + param['sName'] + log + " " +
                str(param['save']),
                'rememory':
                head + "/bin/bash " + public.GetConfigValue('setup_path') +
                '/panel/script/rememory.sh',
                'webshell':
                head + "python " + public.GetConfigValue('setup_path') +
                '/panel/class/webshell_check.py site ' + param['sName'] + ' ' +
                param['urladdress']
            }
            if param['backupTo'] != 'localhost':
                cfile = public.GetConfigValue(
                    'setup_path') + "/panel/plugin/" + param[
                        'backupTo'] + "/" + param['backupTo'] + "_main.py"
                if not os.path.exists(cfile):
                    cfile = public.GetConfigValue(
                        'setup_path'
                    ) + "/panel/script/backup_" + param['backupTo'] + ".py"
                wheres = {
                    'path':
                    head + "python " + cfile + " path " + param['sName'] +
                    " " + str(param['save']),
                    'site':
                    head + "python " + cfile + " site " + param['sName'] +
                    " " + str(param['save']),
                    'database':
                    head + "python " + cfile + " database " + param['sName'] +
                    " " + str(param['save']),
                    'logs':
                    head + "python " + public.GetConfigValue('setup_path') +
                    "/panel/script/logsBackup " + param['sName'] + log + " " +
                    str(param['save']),
                    'rememory':
                    head + "/bin/bash " + public.GetConfigValue('setup_path') +
                    '/panel/script/rememory.sh',
                    'webshell':
                    head + "python " + public.GetConfigValue('setup_path') +
                    '/panel/class/webshell_check.py site ' + param['sName'] +
                    ' ' + param['urladdress']
                }

            try:
                shell = wheres[type]
            except:
                if type == 'toUrl':
                    shell = head + "curl -sS --connect-timeout 10 -m 3600 '" + param[
                        'urladdress'] + "'"
                else:
                    shell = head + param['sBody'].replace("\r\n", "\n")

                shell += '''
echo "----------------------------------------------------------------------------"
endDate=`date +"%Y-%m-%d %H:%M:%S"`
echo "★[$endDate] Successful"
echo "----------------------------------------------------------------------------"
'''
        cronPath = public.GetConfigValue('setup_path') + '/cron'
        if not os.path.exists(cronPath):
            public.ExecShell('mkdir -p ' + cronPath)
        if not 'echo' in param:
            cronName = public.md5(public.md5(str(time.time()) + '_bt'))
        else:
            cronName = param['echo']
        file = cronPath + '/' + cronName
        public.writeFile(file, self.CheckScript(shell))
        public.ExecShell('chmod 750 ' + file)
        return cronName
Exemple #58
0
def control_init():
    dirPath = '/www/server/phpmyadmin/pma'
    if os.path.exists(dirPath):
        public.ExecShell("rm -rf {}".format(dirPath))

    dirPath = '/www/server/adminer'
    if os.path.exists(dirPath):
        public.ExecShell("rm -rf {}".format(dirPath))

    dirPath = '/www/server/panel/adminer'
    if os.path.exists(dirPath):
        public.ExecShell("rm -rf {}".format(dirPath))

    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', '*****@*****.**')

    if not public.M('sqlite_master').where(
            'type=? AND name=? AND sql LIKE ?',
        ('table', 'users', '%salt%')).count():
        public.M('users').execute("ALTER TABLE 'users' ADD 'salt' TEXT", ())

    public.chdck_salt()

    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;chown -R root:root /www/server/phpmyadmin;chmod -R 755 /www/server/phpmyadmin"
    )
    if os.path.exists("/www/server/mysql"):
        public.ExecShell("chown mysql:mysql /etc/my.cnf;chmod 600 /etc/my.cnf")
    stop_path = '/www/server/stop'
    if not os.path.exists(stop_path):
        os.makedirs(stop_path)
    public.ExecShell(
        "chown -R root:root {path};chmod -R 755 {path}".format(path=stop_path))
    public.ExecShell('chmod 755 /www;chmod 755 /www/server')
    if os.path.exists('/www/server/phpmyadmin/pma'):
        public.ExecShell("rm -rf /www/server/phpmyadmin/pma")
    if os.path.exists("/www/server/adminer"):
        public.ExecShell("rm -rf /www/server/adminer")
    if os.path.exists("/www/server/panel/adminer"):
        public.ExecShell("rm -rf /www/server/panel/adminer")
    if os.path.exists('/dev/shm/session.db'):
        os.remove('/dev/shm/session.db')
    #disable_putenv('putenv')
    clean_session()
    #set_crond()
    clean_max_log('/www/server/panel/plugin/rsync/lsyncd.log')
    clean_max_log('/var/log/rsyncd.log', 1024 * 1024 * 10)
    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()
    #update_py37()
    files_set_mode()
Exemple #59
0
 def __write_config(self, path, data):
     return public.writeFile(path, json.dumps(data))
Exemple #60
0
def control_init():
    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, ())
    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")
    public.ExecShell("chmod -R  600 /www/server/panel/config")
    public.ExecShell("chmod -R  700 /www/server/cron")
    public.ExecShell("chmod -R  600 /www/server/cron/*.log")
    public.ExecShell("chown -R root:root /www/server/panel/data")
    public.ExecShell("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()